diff --git a/src/Common/Game/GameLanguage.h b/src/Common/Game/GameLanguage.h index 9740ac0e7..b169e34ca 100644 --- a/src/Common/Game/GameLanguage.h +++ b/src/Common/Game/GameLanguage.h @@ -2,40 +2,34 @@ #include -enum class GameLanguage -{ - LANGUAGE_NONE, - LANGUAGE_ENGLISH, - LANGUAGE_FRENCH, - LANGUAGE_GERMAN, - LANGUAGE_ITALIAN, - LANGUAGE_SPANISH, - LANGUAGE_BRITISH, - LANGUAGE_RUSSIAN, - LANGUAGE_POLISH, - LANGUAGE_KOREAN, - LANGUAGE_TAIWANESE, - LANGUAGE_JAPANESE, - LANGUAGE_CHINESE, - LANGUAGE_THAI, - LANGUAGE_LEET, - LANGUAGE_CZECH, - LANGUAGE_FRENCH_CAN, - LANGUAGE_AUSTRIAN, - LANGUAGE_PORTUGUESE, - LANGUAGE_MEXICAN_SPANISH, - LANGUAGE_FULL_JAPANESE +enum class GameLanguage { + LANGUAGE_NONE, + LANGUAGE_ENGLISH, + LANGUAGE_FRENCH, + LANGUAGE_GERMAN, + LANGUAGE_ITALIAN, + LANGUAGE_SPANISH, + LANGUAGE_BRITISH, + LANGUAGE_RUSSIAN, + LANGUAGE_POLISH, + LANGUAGE_KOREAN, + LANGUAGE_TAIWANESE, + LANGUAGE_JAPANESE, + LANGUAGE_CHINESE, + LANGUAGE_THAI, + LANGUAGE_LEET, + LANGUAGE_CZECH, + LANGUAGE_FRENCH_CAN, + LANGUAGE_AUSTRIAN, + LANGUAGE_PORTUGUESE, + LANGUAGE_MEXICAN_SPANISH, + LANGUAGE_FULL_JAPANESE }; -class GameLanguagePrefix -{ +class GameLanguagePrefix { public: - GameLanguage m_language; - const std::string m_prefix; + GameLanguage m_language; + const std::string m_prefix; - GameLanguagePrefix(const GameLanguage language, std::string prefix) - : m_language(language), - m_prefix(std::move(prefix)) - { - } + GameLanguagePrefix(const GameLanguage language, std::string prefix) : m_language(language), m_prefix(std::move(prefix)) {} }; diff --git a/src/Common/Game/IGame.h b/src/Common/Game/IGame.h index eae862f7b..a35bb61ab 100644 --- a/src/Common/Game/IGame.h +++ b/src/Common/Game/IGame.h @@ -1,23 +1,22 @@ #pragma once -#include #include "GameLanguage.h" +#include class Zone; -class IGame -{ +class IGame { public: - IGame() = default; - virtual ~IGame() = default; - IGame(const IGame& other) = default; - IGame(IGame&& other) noexcept = default; - IGame& operator=(const IGame& other) = default; - IGame& operator=(IGame&& other) noexcept = default; + IGame() = default; + virtual ~IGame() = default; + IGame(const IGame &other) = default; + IGame(IGame &&other) noexcept = default; + IGame &operator=(const IGame &other) = default; + IGame &operator=(IGame &&other) noexcept = default; - virtual std::string GetFullName() = 0; - virtual std::string GetShortName() = 0; - virtual void AddZone(Zone* zone) = 0; - virtual void RemoveZone(Zone* zone) = 0; - virtual std::vector GetZones() = 0; - virtual std::vector GetLanguagePrefixes() = 0; + virtual std::string GetFullName() = 0; + virtual std::string GetShortName() = 0; + virtual void AddZone(Zone *zone) = 0; + virtual void RemoveZone(Zone *zone) = 0; + virtual std::vector GetZones() = 0; + virtual std::vector GetLanguagePrefixes() = 0; }; \ No newline at end of file diff --git a/src/Common/Game/IW3/CommonIW3.cpp b/src/Common/Game/IW3/CommonIW3.cpp index cea4d6161..216447eb7 100644 --- a/src/Common/Game/IW3/CommonIW3.cpp +++ b/src/Common/Game/IW3/CommonIW3.cpp @@ -4,32 +4,14 @@ using namespace IW3; -PackedTexCoords Common::Vec2PackTexCoords(const vec2_t* in) -{ - return PackedTexCoords{Pack32::Vec2PackTexCoords(reinterpret_cast(in))}; -} - -PackedUnitVec Common::Vec3PackUnitVec(const vec3_t* in) -{ - return PackedUnitVec{Pack32::Vec3PackUnitVec(reinterpret_cast(in))}; -} - -GfxColor Common::Vec4PackGfxColor(const vec4_t* in) -{ - return GfxColor{Pack32::Vec4PackGfxColor(reinterpret_cast(in))}; -} - -void Common::Vec2UnpackTexCoords(const PackedTexCoords& in, vec2_t* out) -{ - Pack32::Vec2UnpackTexCoordsVU(in.packed, reinterpret_cast(out)); -} - -void Common::Vec3UnpackUnitVec(const PackedUnitVec& in, vec3_t* out) -{ - Pack32::Vec3UnpackUnitVecScaleBased(in.packed, reinterpret_cast(out)); -} - -void Common::Vec4UnpackGfxColor(const GfxColor& in, vec4_t* out) -{ - Pack32::Vec4UnpackGfxColor(in.packed, reinterpret_cast(out)); -} +PackedTexCoords Common::Vec2PackTexCoords(const vec2_t *in) { return PackedTexCoords{Pack32::Vec2PackTexCoords(reinterpret_cast(in))}; } + +PackedUnitVec Common::Vec3PackUnitVec(const vec3_t *in) { return PackedUnitVec{Pack32::Vec3PackUnitVec(reinterpret_cast(in))}; } + +GfxColor Common::Vec4PackGfxColor(const vec4_t *in) { return GfxColor{Pack32::Vec4PackGfxColor(reinterpret_cast(in))}; } + +void Common::Vec2UnpackTexCoords(const PackedTexCoords &in, vec2_t *out) { Pack32::Vec2UnpackTexCoordsVU(in.packed, reinterpret_cast(out)); } + +void Common::Vec3UnpackUnitVec(const PackedUnitVec &in, vec3_t *out) { Pack32::Vec3UnpackUnitVecScaleBased(in.packed, reinterpret_cast(out)); } + +void Common::Vec4UnpackGfxColor(const GfxColor &in, vec4_t *out) { Pack32::Vec4UnpackGfxColor(in.packed, reinterpret_cast(out)); } diff --git a/src/Common/Game/IW3/CommonIW3.h b/src/Common/Game/IW3/CommonIW3.h index 26e019f5b..948013907 100644 --- a/src/Common/Game/IW3/CommonIW3.h +++ b/src/Common/Game/IW3/CommonIW3.h @@ -2,30 +2,26 @@ #include "IW3.h" -namespace IW3 -{ - class Common - { - public: - static constexpr uint32_t R_HashString(const char* string, const uint32_t hash) - { - const char* v2 = string; // edx@1 - char v3 = *string; // cl@1 - uint32_t result = hash; +namespace IW3 { +class Common { +public: + static constexpr uint32_t R_HashString(const char *string, const uint32_t hash) { + const char *v2 = string; // edx@1 + char v3 = *string; // cl@1 + uint32_t result = hash; - for (; *v2; v3 = *v2) - { - ++v2; - result = 33 * result ^ (v3 | 0x20); - } - return result; - } + for (; *v2; v3 = *v2) { + ++v2; + result = 33 * result ^ (v3 | 0x20); + } + return result; + } - static PackedTexCoords Vec2PackTexCoords(const vec2_t* in); - static PackedUnitVec Vec3PackUnitVec(const vec3_t* in); - static GfxColor Vec4PackGfxColor(const vec4_t* in); - static void Vec2UnpackTexCoords(const PackedTexCoords& in, vec2_t* out); - static void Vec3UnpackUnitVec(const PackedUnitVec& in, vec3_t* out); - static void Vec4UnpackGfxColor(const GfxColor& in, vec4_t* out); - }; -} \ No newline at end of file + static PackedTexCoords Vec2PackTexCoords(const vec2_t *in); + static PackedUnitVec Vec3PackUnitVec(const vec3_t *in); + static GfxColor Vec4PackGfxColor(const vec4_t *in); + static void Vec2UnpackTexCoords(const PackedTexCoords &in, vec2_t *out); + static void Vec3UnpackUnitVec(const PackedUnitVec &in, vec3_t *out); + static void Vec4UnpackGfxColor(const GfxColor &in, vec4_t *out); +}; +} // namespace IW3 \ No newline at end of file diff --git a/src/Common/Game/IW3/GameIW3.cpp b/src/Common/Game/IW3/GameIW3.cpp index c9b69fe5f..f5ce385ac 100644 --- a/src/Common/Game/IW3/GameIW3.cpp +++ b/src/Common/Game/IW3/GameIW3.cpp @@ -8,36 +8,22 @@ using namespace IW3; GameIW3 g_GameIW3; -std::string GameIW3::GetFullName() -{ - return "Call Of Duty 4: Modern Warfare"; -} +std::string GameIW3::GetFullName() { return "Call Of Duty 4: Modern Warfare"; } -std::string GameIW3::GetShortName() -{ - return "IW3"; -} +std::string GameIW3::GetShortName() { return "IW3"; } -void GameIW3::AddZone(Zone* zone) -{ - m_zones.push_back(zone); -} +void GameIW3::AddZone(Zone *zone) { m_zones.push_back(zone); } -void GameIW3::RemoveZone(Zone* zone) -{ - const auto foundEntry = std::find(m_zones.begin(), m_zones.end(), zone); +void GameIW3::RemoveZone(Zone *zone) { + const auto foundEntry = std::find(m_zones.begin(), m_zones.end(), zone); - if (foundEntry != m_zones.end()) - m_zones.erase(foundEntry); + if (foundEntry != m_zones.end()) + m_zones.erase(foundEntry); } -std::vector GameIW3::GetZones() -{ - return m_zones; -} +std::vector GameIW3::GetZones() { return m_zones; } -std::vector GameIW3::GetLanguagePrefixes() -{ - std::vector prefixes; - return prefixes; +std::vector GameIW3::GetLanguagePrefixes() { + std::vector prefixes; + return prefixes; } diff --git a/src/Common/Game/IW3/GameIW3.h b/src/Common/Game/IW3/GameIW3.h index ec06f8c73..84c18af1e 100644 --- a/src/Common/Game/IW3/GameIW3.h +++ b/src/Common/Game/IW3/GameIW3.h @@ -1,17 +1,16 @@ #pragma once #include "Game/IGame.h" -class GameIW3 : public IGame -{ - std::vector m_zones; +class GameIW3 : public IGame { + std::vector m_zones; public: - std::string GetFullName() override; - std::string GetShortName() override; - void AddZone(Zone* zone) override; - void RemoveZone(Zone* zone) override; - std::vector GetZones() override; - std::vector GetLanguagePrefixes() override; + std::string GetFullName() override; + std::string GetShortName() override; + void AddZone(Zone *zone) override; + void RemoveZone(Zone *zone) override; + std::vector GetZones() override; + std::vector GetLanguagePrefixes() override; }; extern GameIW3 g_GameIW3; \ No newline at end of file diff --git a/src/Common/Game/IW3/IW3.h b/src/Common/Game/IW3/IW3.h index 25ca8d08a..b0b0685a4 100644 --- a/src/Common/Game/IW3/IW3.h +++ b/src/Common/Game/IW3/IW3.h @@ -1,82 +1,75 @@ #pragma once -//#include +// #include #include "Image/Texture.h" #include "IW3_Assets.h" -namespace IW3 -{ - struct ScriptStringList - { - int count; - const char** strings; - }; +namespace IW3 { +struct ScriptStringList { + int count; + const char **strings; +}; - struct XAsset - { - XAssetType type; - XAssetHeader header; - }; +struct XAsset { + XAssetType type; + XAssetHeader header; +}; - struct XAssetList - { - ScriptStringList stringList; - int assetCount; - XAsset* assets; - }; +struct XAssetList { + ScriptStringList stringList; + int assetCount; + XAsset *assets; +}; - struct cspField_t - { - const char* szName; - int iOffset; - int iFieldType; - }; +struct cspField_t { + const char *szName; + int iOffset; + int iFieldType; +}; - enum csParseFieldType_t - { - CSPFT_STRING = 0, - CSPFT_STRING_MAX_STRING_CHARS, - CSPFT_STRING_MAX_QPATH, - CSPFT_STRING_MAX_OSPATH, - CSPFT_INT, - CSPFT_QBOOLEAN, - CSPFT_FLOAT, - CSPFT_MILLISECONDS, - CSPFT_FX, - CSPFT_XMODEL, - CSPFT_MATERIAL, - CSPFT_SOUND, +enum csParseFieldType_t { + CSPFT_STRING = 0, + CSPFT_STRING_MAX_STRING_CHARS, + CSPFT_STRING_MAX_QPATH, + CSPFT_STRING_MAX_OSPATH, + CSPFT_INT, + CSPFT_QBOOLEAN, + CSPFT_FLOAT, + CSPFT_MILLISECONDS, + CSPFT_FX, + CSPFT_XMODEL, + CSPFT_MATERIAL, + CSPFT_SOUND, - CSPFT_NUM_BASE_FIELD_TYPES - }; + CSPFT_NUM_BASE_FIELD_TYPES +}; - enum weapFieldType_t - { - WFT_WEAPONTYPE = CSPFT_NUM_BASE_FIELD_TYPES, - WFT_WEAPONCLASS, - WFT_OVERLAYRETICLE, - WFT_PENETRATE_TYPE, - WFT_IMPACT_TYPE, - WFT_STANCE, - WFT_PROJ_EXPLOSION, - WFT_OFFHAND_CLASS, - WFT_ANIMTYPE, - WFT_ACTIVE_RETICLE_TYPE, - WFT_GUIDED_MISSILE_TYPE, - WFT_BOUNCE_SOUND, - WFT_STICKINESS, - WFT_OVERLAYINTERFACE, - WFT_INVENTORYTYPE, - WFT_FIRETYPE, - WFT_AMMOCOUNTER_CLIPTYPE, - WFT_ICONRATIO_HUD, - WFT_ICONRATIO_AMMOCOUNTER, - WFT_ICONRATIO_KILL, - WFT_ICONRATIO_DPAD, - WFT_HIDETAGS, - WFT_NOTETRACKSOUNDMAP, +enum weapFieldType_t { + WFT_WEAPONTYPE = CSPFT_NUM_BASE_FIELD_TYPES, + WFT_WEAPONCLASS, + WFT_OVERLAYRETICLE, + WFT_PENETRATE_TYPE, + WFT_IMPACT_TYPE, + WFT_STANCE, + WFT_PROJ_EXPLOSION, + WFT_OFFHAND_CLASS, + WFT_ANIMTYPE, + WFT_ACTIVE_RETICLE_TYPE, + WFT_GUIDED_MISSILE_TYPE, + WFT_BOUNCE_SOUND, + WFT_STICKINESS, + WFT_OVERLAYINTERFACE, + WFT_INVENTORYTYPE, + WFT_FIRETYPE, + WFT_AMMOCOUNTER_CLIPTYPE, + WFT_ICONRATIO_HUD, + WFT_ICONRATIO_AMMOCOUNTER, + WFT_ICONRATIO_KILL, + WFT_ICONRATIO_DPAD, + WFT_HIDETAGS, + WFT_NOTETRACKSOUNDMAP, - WFT_NUM_FIELD_TYPES - }; -} \ No newline at end of file + WFT_NUM_FIELD_TYPES +}; +} // namespace IW3 \ No newline at end of file diff --git a/src/Common/Game/IW3/IW3_Assets.h b/src/Common/Game/IW3/IW3_Assets.h index a77230008..f7130c7f7 100644 --- a/src/Common/Game/IW3/IW3_Assets.h +++ b/src/Common/Game/IW3/IW3_Assets.h @@ -6,3344 +6,3093 @@ #include "../../Utils/TypeAlignment.h" #ifndef __zonecodegenerator -namespace IW3 -{ +namespace IW3 { #endif - enum XAssetType - { - ASSET_TYPE_XMODELPIECES = 0x0, - ASSET_TYPE_PHYSPRESET = 0x1, - ASSET_TYPE_XANIMPARTS = 0x2, - ASSET_TYPE_XMODEL = 0x3, - ASSET_TYPE_MATERIAL = 0x4, - ASSET_TYPE_TECHNIQUE_SET = 0x5, - ASSET_TYPE_IMAGE = 0x6, - ASSET_TYPE_SOUND = 0x7, - ASSET_TYPE_SOUND_CURVE = 0x8, - ASSET_TYPE_LOADED_SOUND = 0x9, - ASSET_TYPE_CLIPMAP = 0xA, - ASSET_TYPE_CLIPMAP_PVS = 0xB, - ASSET_TYPE_COMWORLD = 0xC, - ASSET_TYPE_GAMEWORLD_SP = 0xD, - ASSET_TYPE_GAMEWORLD_MP = 0xE, - ASSET_TYPE_MAP_ENTS = 0xF, - ASSET_TYPE_GFXWORLD = 0x10, - ASSET_TYPE_LIGHT_DEF = 0x11, - ASSET_TYPE_UI_MAP = 0x12, - ASSET_TYPE_FONT = 0x13, - ASSET_TYPE_MENULIST = 0x14, - ASSET_TYPE_MENU = 0x15, - ASSET_TYPE_LOCALIZE_ENTRY = 0x16, - ASSET_TYPE_WEAPON = 0x17, - ASSET_TYPE_SNDDRIVER_GLOBALS = 0x18, - ASSET_TYPE_FX = 0x19, - ASSET_TYPE_IMPACT_FX = 0x1A, - ASSET_TYPE_AITYPE = 0x1B, - ASSET_TYPE_MPTYPE = 0x1C, - ASSET_TYPE_CHARACTER = 0x1D, - ASSET_TYPE_XMODELALIAS = 0x1E, - ASSET_TYPE_RAWFILE = 0x1F, - ASSET_TYPE_STRINGTABLE = 0x20, - ASSET_TYPE_COUNT, - - ASSET_TYPE_STRING = ASSET_TYPE_COUNT, - ASSET_TYPE_ASSETLIST, - - ASSET_TYPE_FULLCOUNT - }; - - enum XFileBlock - { - XFILE_BLOCK_TEMP, - XFILE_BLOCK_RUNTIME, - XFILE_BLOCK_LARGE_RUNTIME, - XFILE_BLOCK_PHYSICAL_RUNTIME, - XFILE_BLOCK_VIRTUAL, - XFILE_BLOCK_LARGE, - XFILE_BLOCK_PHYSICAL, - XFILE_BLOCK_VERTEX, - XFILE_BLOCK_INDEX, - - MAX_XFILE_COUNT - }; - - struct XModelPieces; - struct PhysPreset; - struct XAnimParts; - struct XModel; - struct Material; - struct MaterialPixelShader; - struct MaterialVertexShader; - struct MaterialTechniqueSet; - struct GfxImage; - struct snd_alias_list_t; - struct SndCurve; - struct LoadedSound; - struct clipMap_t; - struct ComWorld; - struct GameWorldSp; - struct GameWorldMp; - struct MapEnts; - struct GfxWorld; - struct GfxLightDef; - struct Font_s; - struct MenuList; - struct menuDef_t; - struct LocalizeEntry; - struct WeaponDef; - struct SndDriverGlobals; - struct FxEffectDef; - struct FxImpactTable; - struct RawFile; - struct StringTable; - - union XAssetHeader - { - // XModelPieces *xmodelPieces; // NOT AN ASSET - PhysPreset *physPreset; - XAnimParts *parts; - XModel *model; - Material *material; - MaterialPixelShader *pixelShader; - MaterialVertexShader *vertexShader; - MaterialTechniqueSet *techniqueSet; - GfxImage *image; - snd_alias_list_t *sound; - SndCurve *sndCurve; - LoadedSound *loadSnd; - clipMap_t *clipMap; - ComWorld *comWorld; - GameWorldSp *gameWorldSp; - GameWorldMp *gameWorldMp; - MapEnts *mapEnts; - GfxWorld *gfxWorld; - GfxLightDef *lightDef; - Font_s *font; - MenuList *menuList; - menuDef_t *menu; - LocalizeEntry *localize; - WeaponDef *weapon; - SndDriverGlobals *sndDriverGlobals; - FxEffectDef *fx; - FxImpactTable *impactFx; - RawFile *rawfile; - StringTable *stringTable; - void *data; - }; - - typedef char cbrushedge_t; - typedef float vec2_t[2]; - typedef float vec3_t[3]; - typedef float vec4_t[4]; - typedef tdef_align(128) unsigned int raw_uint128; - - struct XModelPiece - { - XModel* model; - float offset[3]; - }; - - struct XModelPieces - { - const char* name; - int numpieces; - XModelPiece* pieces; - }; - - struct PhysPreset - { - const char *name; - int type; - float mass; - float bounce; - float friction; - float bulletForceScale; - float explosiveForceScale; - const char *sndAliasPrefix; - float piecesSpreadFraction; - float piecesUpwardVelocity; - bool tempDefaultToCylinder; - }; - - union XAnimIndices - { - char* _1; - uint16_t* _2; - void* data; - }; - - struct XAnimNotifyInfo - { - uint16_t name; - float time; - }; - - typedef unsigned char ByteVec[3]; - typedef tdef_align(4) unsigned short UShortVec[3]; - - union XAnimDynamicIndicesTrans - { - char _1[1]; - uint16_t _2[1]; - }; - - union XAnimDynamicFrames - { - ByteVec* _1; - UShortVec* _2; - }; - - struct XAnimPartTransFrames - { - float mins[3]; - float size[3]; - XAnimDynamicFrames frames; - XAnimDynamicIndicesTrans indices; - }; - - union XAnimPartTransData - { - XAnimPartTransFrames frames; - vec3_t frame0; - }; - - struct XAnimPartTrans - { - uint16_t size; - char smallTrans; - XAnimPartTransData u; - }; - - typedef tdef_align(4) short XQuat[2]; - - union XAnimDynamicIndicesQuat - { - char _1[1]; - uint16_t _2[1]; - }; - - struct XAnimDeltaPartQuatDataFrames - { - XQuat *frames; - XAnimDynamicIndicesQuat indices; - }; - - union XAnimDeltaPartQuatData - { - XAnimDeltaPartQuatDataFrames frames; - int16_t frame0[2]; - }; - - struct XAnimDeltaPartQuat - { - uint16_t size; - XAnimDeltaPartQuatData u; - }; - - struct XAnimDeltaPart - { - XAnimPartTrans* trans; - XAnimDeltaPartQuat* quat; - }; - - struct XAnimParts - { - const char* name; - uint16_t dataByteCount; - uint16_t dataShortCount; - uint16_t dataIntCount; - uint16_t randomDataByteCount; - uint16_t randomDataIntCount; - uint16_t numframes; - bool bLoop; - bool bDelta; - unsigned char boneCount[10]; - char notifyCount; - char assetType; - bool isDefault; - unsigned int randomDataShortCount; - unsigned int indexCount; - float framerate; - float frequency; - uint16_t* names; - char* dataByte; - int16_t* dataShort; - int* dataInt; - int16_t* randomDataShort; - char* randomDataByte; - int* randomDataInt; - XAnimIndices indices; - XAnimNotifyInfo* notify; - XAnimDeltaPart* deltaPart; - }; - - struct DObjSkelMat - { - float axis[3][4]; - float origin[4]; - }; - - struct DObjAnimMat - { - float quat[4]; - float trans[3]; - float transWeight; - }; - - struct XSurfaceCollisionAabb - { - uint16_t mins[3]; - uint16_t maxs[3]; - }; - - struct type_align(16) XSurfaceCollisionNode - { - XSurfaceCollisionAabb aabb; - uint16_t childBeginIndex; - uint16_t childCount; - }; - - struct XSurfaceCollisionLeaf - { - uint16_t triangleBeginIndex; - }; - - struct XSurfaceCollisionTree - { - float trans[3]; - float scale[3]; - unsigned int nodeCount; - XSurfaceCollisionNode* nodes; - unsigned int leafCount; - XSurfaceCollisionLeaf* leafs; - }; - - struct XRigidVertList - { - uint16_t boneOffset; - uint16_t vertCount; - uint16_t triOffset; - uint16_t triCount; - XSurfaceCollisionTree* collisionTree; - }; - - union GfxColor - { - unsigned int packed; - char array[4]; - }; - - union PackedTexCoords - { - unsigned int packed; - }; - - union PackedUnitVec - { - unsigned int packed; - char array[4]; - }; - - struct type_align(16) GfxPackedVertex - { - float xyz[3]; - float binormalSign; - GfxColor color; - PackedTexCoords texCoord; - PackedUnitVec normal; - PackedUnitVec tangent; - }; - - struct XSurfaceVertexInfo - { - int16_t vertCount[4]; - uint16_t* vertsBlend; - }; - - typedef tdef_align(16) uint16_t r_index16_t; - - struct XSurface - { - char tileMode; - bool deformed; - uint16_t vertCount; - uint16_t triCount; - char zoneHandle; - uint16_t baseTriIndex; - uint16_t baseVertIndex; - r_index16_t(*triIndices)[3]; - XSurfaceVertexInfo vertInfo; - GfxPackedVertex* verts0; - unsigned int vertListCount; - XRigidVertList* vertList; - int partBits[4]; - }; - - struct XModelLodInfo - { - float dist; - uint16_t numsurfs; - uint16_t surfIndex; - int partBits[4]; - char lod; - char smcIndexPlusOne; - char smcAllocBits; - char unused; - }; - - struct XModelCollTri_s - { - float plane[4]; - float svec[4]; - float tvec[4]; - }; - - struct XModelCollSurf_s - { - XModelCollTri_s* collTris; - int numCollTris; - float mins[3]; - float maxs[3]; - int boneIdx; - int contents; - int surfFlags; - }; - - struct XBoneInfo - { - float bounds[2][3]; - float offset[3]; - float radiusSquared; - }; - - struct cplane_s - { - float normal[3]; - float dist; - char type; - char signbits; - char pad[2]; - }; - - struct cbrushside_t - { - cplane_s* plane; - unsigned int materialNum; - int16_t firstAdjacentSideOffset; - char edgeCount; - }; - - struct BrushWrapper - { - float mins[3]; - int contents; - float maxs[3]; - unsigned int numsides; - cbrushside_t* sides; - int16_t axialMaterialNum[2][3]; - char* baseAdjacentSide; - int16_t firstAdjacentSideOffsets[2][3]; - char edgeCount[2][3]; - int totalEdgeCount; - cplane_s* planes; - }; - - struct PhysGeomInfo - { - BrushWrapper* brush; - int type; - float orientation[3][3]; - float offset[3]; - float halfLengths[3]; - }; - - struct PhysMass - { - float centerOfMass[3]; - float momentsOfInertia[3]; - float productsOfInertia[3]; - }; - - struct PhysGeomList - { - unsigned int count; - PhysGeomInfo* geoms; - PhysMass mass; - }; - - struct XModelStreamInfo - { - char pad; - }; - - struct XModel - { - const char* name; - unsigned char numBones; - unsigned char numRootBones; - unsigned char numsurfs; - char lodRampType; - uint16_t* boneNames; - char* parentList; - int16_t(*quats)[4]; - float(*trans)[4]; - char* partClassification; - DObjAnimMat* baseMat; - XSurface* surfs; - Material** materialHandles; - XModelLodInfo lodInfo[4]; - XModelCollSurf_s* collSurfs; - int numCollSurfs; - int contents; - XBoneInfo* boneInfo; - float radius; - float mins[3]; - float maxs[3]; - uint16_t numLods; - uint16_t collLod; - XModelStreamInfo streamInfo; - int memUsage; - char flags; - bool bad; - PhysPreset* physPreset; - PhysGeomList* physGeoms; - }; - - enum GfxBlend - { - GFXS_BLEND_DISABLED = 0x0, - GFXS_BLEND_ZERO = 0x1, - GFXS_BLEND_ONE = 0x2, - GFXS_BLEND_SRCCOLOR = 0x3, - GFXS_BLEND_INVSRCCOLOR = 0x4, - GFXS_BLEND_SRCALPHA = 0x5, - GFXS_BLEND_INVSRCALPHA = 0x6, - GFXS_BLEND_DESTALPHA = 0x7, - GFXS_BLEND_INVDESTALPHA = 0x8, - GFXS_BLEND_DESTCOLOR = 0x9, - GFXS_BLEND_INVDESTCOLOR = 0xA, - GFXS_BLEND_MASK = 0xF, - }; - - enum GfxBlendOp - { - GFXS_BLENDOP_DISABLED = 0x0, - GFXS_BLENDOP_ADD = 0x1, - GFXS_BLENDOP_SUBTRACT = 0x2, - GFXS_BLENDOP_REVSUBTRACT = 0x3, - GFXS_BLENDOP_MIN = 0x4, - GFXS_BLENDOP_MAX = 0x5, - GFXS_BLENDOP_MASK = 0x7, - }; - - enum GfxStencilOp - { - GFXS_STENCILOP_KEEP = 0x0, - GFXS_STENCILOP_ZERO = 0x1, - GFXS_STENCILOP_REPLACE = 0x2, - GFXS_STENCILOP_INCRSAT = 0x3, - GFXS_STENCILOP_DECRSAT = 0x4, - GFXS_STENCILOP_INVERT = 0x5, - GFXS_STENCILOP_INCR = 0x6, - GFXS_STENCILOP_DECR = 0x7, - - GFXS_STENCILOP_COUNT, - GFXS_STENCILOP_MASK = 0x7 - }; - - enum GfxStateBitsEnum : unsigned int - { - GFXS0_SRCBLEND_RGB_SHIFT = 0x0, - GFXS0_SRCBLEND_RGB_MASK = 0xF, - - GFXS0_DSTBLEND_RGB_SHIFT = 0x4, - GFXS0_DSTBLEND_RGB_MASK = 0xF0, - - GFXS0_BLENDOP_RGB_SHIFT = 0x8, - GFXS0_BLENDOP_RGB_MASK = 0x700, - GFXS0_BLEND_RGB_MASK = 0x7FF, - - GFXS0_ATEST_DISABLE = 0x800, - GFXS0_ATEST_GT_0 = 0x1000, - GFXS0_ATEST_LT_128 = 0x2000, - GFXS0_ATEST_GE_128 = 0x3000, - GFXS0_ATEST_MASK = 0x3000, - - GFXS0_CULL_SHIFT = 0xE, - GFXS0_CULL_NONE = 0x4000, - GFXS0_CULL_BACK = 0x8000, - GFXS0_CULL_FRONT = 0xC000, - GFXS0_CULL_MASK = 0xC000, - - GFXS0_SRCBLEND_ALPHA_SHIFT = 0x10, - GFXS0_SRCBLEND_ALPHA_MASK = 0xF0000, - - GFXS0_DSTBLEND_ALPHA_SHIFT = 0x14, - GFXS0_DSTBLEND_ALPHA_MASK = 0xF00000, - - GFXS0_BLENDOP_ALPHA_SHIFT = 0x18, - GFXS0_BLENDOP_ALPHA_MASK = 0x7000000, - GFXS0_BLEND_ALPHA_MASK = 0x7FF0000, - - GFXS0_COLORWRITE_RGB = 0x8000000, - GFXS0_COLORWRITE_ALPHA = 0x10000000, - GFXS0_COLORWRITE_MASK = 0x18000000, - - GFXS0_POLYMODE_LINE = 0x80000000, - - GFXS1_DEPTHWRITE = 0x1, - - GFXS1_DEPTHTEST_DISABLE = 0x2, - GFXS1_DEPTHTEST_SHIFT = 0x2, - GFXS1_DEPTHTEST_ALWAYS = 0x0, - GFXS1_DEPTHTEST_LESS = 0x4, - GFXS1_DEPTHTEST_EQUAL = 0x8, - GFXS1_DEPTHTEST_LESSEQUAL = 0xC, - GFXS1_DEPTHTEST_MASK = 0xC, - - GFXS1_POLYGON_OFFSET_SHIFT = 0x4, - GFXS1_POLYGON_OFFSET_0 = 0x0, - GFXS1_POLYGON_OFFSET_1 = 0x10, - GFXS1_POLYGON_OFFSET_2 = 0x20, - GFXS1_POLYGON_OFFSET_SHADOWMAP = 0x30, - GFXS1_POLYGON_OFFSET_MASK = 0x30, - - GFXS1_STENCIL_FRONT_ENABLE = 0x40, - GFXS1_STENCIL_BACK_ENABLE = 0x80, - GFXS1_STENCIL_MASK = 0xC0, - - GFXS1_STENCIL_FRONT_PASS_SHIFT = 0x8, - GFXS1_STENCIL_FRONT_FAIL_SHIFT = 0xB, - GFXS1_STENCIL_FRONT_ZFAIL_SHIFT = 0xE, - GFXS1_STENCIL_FRONT_FUNC_SHIFT = 0x11, - GFXS1_STENCIL_FRONT_MASK = 0xFFF00, - - GFXS1_STENCIL_BACK_PASS_SHIFT = 0x14, - GFXS1_STENCIL_BACK_FAIL_SHIFT = 0x17, - GFXS1_STENCIL_BACK_ZFAIL_SHIFT = 0x1A, - GFXS1_STENCIL_BACK_FUNC_SHIFT = 0x1D, - GFXS1_STENCIL_BACK_MASK = 0xFFF00000, - - GFXS1_STENCILFUNC_FRONTBACK_MASK = 0xE00E0000, - GFXS1_STENCILOP_FRONTBACK_MASK = 0x1FF1FF00, - }; - - struct GfxStateBits - { - unsigned int loadBits[2]; - }; - - struct type_align(16) MaterialConstantDef - { - unsigned int nameHash; - char name[12]; - float literal[4]; - }; - - struct complex_s - { - float real; - float imag; - }; - - struct WaterWritable - { - float floatTime; - }; - - struct water_t - { - WaterWritable writable; - complex_s* H0; - float* wTerm; - int M; - int N; - float Lx; - float Lz; - float gravity; - float windvel; - float winddir[2]; - float amplitude; - float codeConstant[4]; - GfxImage* image; - }; - - union MaterialTextureDefInfo - { - GfxImage* image; - water_t* water; - }; - - enum SamplerStateBits_e - { - SAMPLER_FILTER_SHIFT = 0x0, - SAMPLER_FILTER_NEAREST = 0x1, - SAMPLER_FILTER_LINEAR = 0x2, - SAMPLER_FILTER_ANISO2X = 0x3, - SAMPLER_FILTER_ANISO4X = 0x4, - SAMPLER_FILTER_MASK = 0x7, - - SAMPLER_MIPMAP_SHIFT = 0x3, - SAMPLER_MIPMAP_DISABLED = 0x0, - SAMPLER_MIPMAP_NEAREST = 0x8, - SAMPLER_MIPMAP_LINEAR = 0x10, - SAMPLER_MIPMAP_COUNT = 0x3, - SAMPLER_MIPMAP_MASK = 0x18, - - SAMPLER_CLAMP_U_SHIFT = 0x5, - SAMPLER_CLAMP_V_SHIFT = 0x6, - SAMPLER_CLAMP_W_SHIFT = 0x7, - SAMPLER_CLAMP_U = 0x20, - SAMPLER_CLAMP_V = 0x40, - SAMPLER_CLAMP_W = 0x80, - SAMPLER_CLAMP_MASK = 0xE0, - }; - - struct MaterialTextureDef - { - unsigned int nameHash; - char nameStart; - char nameEnd; - unsigned char samplerState; // SamplerStateBits_e - unsigned char semantic; // TextureSemantic - MaterialTextureDefInfo u; - }; - - struct gcc_align(8) GfxDrawSurfFields - { - uint64_t objectId : 16; - uint64_t reflectionProbeIndex : 8; - uint64_t customIndex : 5; - uint64_t materialSortedIndex : 11; - uint64_t prepass : 2; - uint64_t primaryLightIndex : 8; - uint64_t surfType : 4; - uint64_t primarySortKey : 6; - uint64_t unused : 4; - }; - - union GfxDrawSurf - { - gcc_align(8) GfxDrawSurfFields fields; - gcc_align(8) uint64_t packed; - }; - - enum materialSurfType_t - { - SURF_TYPE_DEFAULT, - SURF_TYPE_BARK, - SURF_TYPE_BRICK, - SURF_TYPE_CARPET, - SURF_TYPE_CLOTH, - SURF_TYPE_CONCRETE, - SURF_TYPE_DIRT, - SURF_TYPE_FLESH, - SURF_TYPE_FOLIAGE, - SURF_TYPE_GLASS, - SURF_TYPE_GRASS, - SURF_TYPE_GRAVEL, - SURF_TYPE_ICE, - SURF_TYPE_METAL, - SURF_TYPE_MUD, - SURF_TYPE_PAPER, - SURF_TYPE_PLASTER, - SURF_TYPE_ROCK, - SURF_TYPE_SAND, - SURF_TYPE_SNOW, - SURF_TYPE_WATER, - SURF_TYPE_WOOD, - SURF_TYPE_ASPHALT, - SURF_TYPE_CERAMIC, - SURF_TYPE_PLASTIC, - SURF_TYPE_RUBBER, - SURF_TYPE_CUSHION, - SURF_TYPE_FRUIT, - SURF_TYPE_PAINTED_METAL, - - SURF_TYPE_NUM - }; - - struct MaterialInfo - { - const char* name; - unsigned char gameFlags; - unsigned char sortKey; - unsigned char textureAtlasRowCount; - unsigned char textureAtlasColumnCount; - GfxDrawSurf drawSurf; - unsigned int surfaceTypeBits; - uint16_t hashIndex; - }; - - enum GfxCameraRegionType - { - CAMERA_REGION_LIT = 0x0, - CAMERA_REGION_DECAL = 0x1, - CAMERA_REGION_EMISSIVE = 0x2, - CAMERA_REGION_COUNT = 0x3, - CAMERA_REGION_NONE = 0x3, - }; - - enum MaterialStateFlags - { - STATE_FLAG_CULL_BACK = 0x1, - STATE_FLAG_CULL_FRONT = 0x2, - STATE_FLAG_DECAL = 0x4, - STATE_FLAG_WRITES_DEPTH = 0x8, - STATE_FLAG_USES_DEPTH_BUFFER = 0x10, - STATE_FLAG_USES_STENCIL_BUFFER = 0x20, - STATE_FLAG_CULL_BACK_SHADOW = 0x40, - STATE_FLAG_CULL_FRONT_SHADOW = 0x80, - }; - - struct Material - { - MaterialInfo info; - char stateBitsEntry[34]; - unsigned char textureCount; - unsigned char constantCount; - unsigned char stateBitsCount; - unsigned char stateFlags; - unsigned char cameraRegion; - MaterialTechniqueSet* techniqueSet; - MaterialTextureDef* textureTable; - MaterialConstantDef* constantTable; - GfxStateBits* stateBitsTable; - }; - - struct MaterialArgumentCodeConst - { - uint16_t index; - char firstRow; - char rowCount; - }; - - union MaterialArgumentDef - { - const float(*literalConst)[4]; - MaterialArgumentCodeConst codeConst; - unsigned int codeSampler; - unsigned int nameHash; - }; - - enum MaterialShaderArgumentType - { - MTL_ARG_MATERIAL_VERTEX_CONST = 0x0, - MTL_ARG_LITERAL_VERTEX_CONST = 0x1, - MTL_ARG_MATERIAL_PIXEL_SAMPLER = 0x2, - - MTL_ARG_CODE_PRIM_BEGIN = 0x3, - - MTL_ARG_CODE_VERTEX_CONST = 0x3, - MTL_ARG_CODE_PIXEL_SAMPLER = 0x4, - MTL_ARG_CODE_PIXEL_CONST = 0x5, - - MTL_ARG_CODE_PRIM_END = 0x6, - - MTL_ARG_MATERIAL_PIXEL_CONST = 0x6, - MTL_ARG_LITERAL_PIXEL_CONST = 0x7, - - MLT_ARG_COUNT - }; - - enum MaterialConstantSource - { - CONST_SRC_CODE_MAYBE_DIRTY_PS_BEGIN = 0x0, - CONST_SRC_CODE_LIGHT_POSITION = 0x0, - CONST_SRC_CODE_LIGHT_DIFFUSE = 0x1, - CONST_SRC_CODE_LIGHT_SPOTDIR = 0x2, - CONST_SRC_CODE_LIGHT_SPOTFACTORS = 0x3, - CONST_SRC_CODE_LIGHT_ATTENUATION = 0x4, - CONST_SRC_CODE_LIGHT_FALLOFF_A = 0x5, - CONST_SRC_CODE_LIGHT_FALLOFF_B = 0x6, - CONST_SRC_CODE_LIGHT_SPOT_MATRIX0 = 0x7, - CONST_SRC_CODE_LIGHT_SPOT_MATRIX1 = 0x8, - CONST_SRC_CODE_LIGHT_SPOT_MATRIX2 = 0x9, - CONST_SRC_CODE_LIGHT_SPOT_MATRIX3 = 0xA, - CONST_SRC_CODE_LIGHT_SPOT_AABB = 0xB, - CONST_SRC_CODE_LIGHT_CONE_CONTROL1 = 0xC, - CONST_SRC_CODE_LIGHT_CONE_CONTROL2 = 0xD, - CONST_SRC_CODE_LIGHT_SPOT_COOKIE_SLIDE_CONTROL = 0xE, - CONST_SRC_CODE_SHADOW_PARMS = 0xF, - CONST_SRC_CODE_SHADOWMAP_POLYGON_OFFSET = 0x10, - CONST_SRC_CODE_RENDER_TARGET_SIZE = 0x11, - CONST_SRC_CODE_UPSCALED_TARGET_SIZE = 0x12, - CONST_SRC_CODE_DOF_EQUATION_VIEWMODEL_AND_FAR_BLUR = 0x13, - CONST_SRC_CODE_DOF_EQUATION_SCENE = 0x14, - CONST_SRC_CODE_DOF_LERP_SCALE = 0x15, - CONST_SRC_CODE_DOF_LERP_BIAS = 0x16, - CONST_SRC_CODE_DOF_ROW_DELTA = 0x17, - CONST_SRC_CODE_PARTICLE_CLOUD_COLOR = 0x18, - CONST_SRC_CODE_GAMETIME = 0x19, - CONST_SRC_CODE_MAYBE_DIRTY_PS_END = 0x1A, - CONST_SRC_CODE_ALWAYS_DIRTY_PS_BEGIN = 0x1A, - CONST_SRC_CODE_FILTER_TAP_0 = 0x1A, - CONST_SRC_CODE_FILTER_TAP_1 = 0x1B, - CONST_SRC_CODE_FILTER_TAP_2 = 0x1C, - CONST_SRC_CODE_FILTER_TAP_3 = 0x1D, - CONST_SRC_CODE_FILTER_TAP_4 = 0x1E, - CONST_SRC_CODE_FILTER_TAP_5 = 0x1F, - CONST_SRC_CODE_FILTER_TAP_6 = 0x20, - CONST_SRC_CODE_FILTER_TAP_7 = 0x21, - CONST_SRC_CODE_COLOR_MATRIX_R = 0x22, - CONST_SRC_CODE_COLOR_MATRIX_G = 0x23, - CONST_SRC_CODE_COLOR_MATRIX_B = 0x24, - CONST_SRC_CODE_ALWAYS_DIRTY_PS_END = 0x25, - CONST_SRC_CODE_NEVER_DIRTY_PS_BEGIN = 0x25, - CONST_SRC_CODE_SHADOWMAP_SWITCH_PARTITION = 0x25, - CONST_SRC_CODE_SUNSHADOWMAP_PIXEL_SIZE = 0x26, - CONST_SRC_CODE_SHADOWMAP_SCALE = 0x27, - CONST_SRC_CODE_ZNEAR = 0x28, - CONST_SRC_CODE_SUN_POSITION = 0x29, - CONST_SRC_CODE_SUN_DIFFUSE = 0x2A, - CONST_SRC_CODE_LIGHTING_LOOKUP_SCALE = 0x2B, - CONST_SRC_CODE_DEBUG_BUMPMAP = 0x2C, - CONST_SRC_CODE_DEBUG_PERFORMANCE = 0x2D, - CONST_SRC_CODE_MATERIAL_COLOR = 0x2E, - CONST_SRC_CODE_FOG = 0x2F, - CONST_SRC_CODE_FOG2 = 0x30, - CONST_SRC_CODE_FOG_COLOR = 0x31, - CONST_SRC_CODE_SUN_FOG = 0x32, - CONST_SRC_CODE_SUN_FOG_DIR = 0x33, - CONST_SRC_CODE_SUN_FOG_COLOR = 0x34, - CONST_SRC_CODE_GLOW_SETUP = 0x35, - CONST_SRC_CODE_GLOW_APPLY = 0x36, - CONST_SRC_CODE_COLOR_BIAS = 0x37, - CONST_SRC_CODE_COLOR_TINT_BASE = 0x38, - CONST_SRC_CODE_COLOR_TINT_DELTA = 0x39, - CONST_SRC_CODE_OUTDOOR_FEATHER_PARMS = 0x3A, - CONST_SRC_CODE_SKY_TRANSITION = 0x3B, - CONST_SRC_CODE_SPOT_SHADOWMAP_PIXEL_ADJUST = 0x3C, - CONST_SRC_CODE_DLIGHT_SPOT_SHADOWMAP_PIXEL_ADJUST = 0x3D, - CONST_SRC_CODE_CLIP_SPACE_LOOKUP_SCALE = 0x3E, - CONST_SRC_CODE_CLIP_SPACE_LOOKUP_OFFSET = 0x3F, - CONST_SRC_CODE_PARTICLE_CLOUD_MATRIX = 0x40, - CONST_SRC_CODE_PARTICLE_CLOUD_VEL_WORLD = 0x41, - CONST_SRC_CODE_DEPTH_FROM_CLIP = 0x42, - CONST_SRC_CODE_CODE_MESH_ARG_0 = 0x43, - CONST_SRC_CODE_CODE_MESH_ARG_1 = 0x44, - CONST_SRC_CODE_CODE_MESH_ARG_LAST = 0x44, - CONST_SRC_CODE_GRID_LIGHTING_COORDS_AND_VIS = 0x45, - CONST_SRC_CODE_GRID_LIGHTING_SH_0 = 0x46, - CONST_SRC_CODE_GRID_LIGHTING_SH_1 = 0x47, - CONST_SRC_CODE_GRID_LIGHTING_SH_2 = 0x48, - CONST_SRC_CODE_REFLECTION_LIGHTING_SH_0 = 0x49, - CONST_SRC_CODE_REFLECTION_LIGHTING_SH_1 = 0x4A, - CONST_SRC_CODE_REFLECTION_LIGHTING_SH_2 = 0x4B, - CONST_SRC_CODE_WIND_DIRECTION = 0x4C, - CONST_SRC_CODE_MOTIONBLUR_DIRECTION_AND_MAGNITUDE = 0x4D, - CONST_SRC_CODE_COMPOSITE_FX_DISTORTION = 0x4E, - CONST_SRC_CODE_GLOW_BLOOM_SCALE = 0x4F, - CONST_SRC_CODE_COMPOSITE_FX_OVERLAY_TEXCOORD = 0x50, - CONST_SRC_CODE_COLOR_BIAS1 = 0x51, - CONST_SRC_CODE_COLOR_TINT_BASE1 = 0x52, - CONST_SRC_CODE_COLOR_TINT_DELTA1 = 0x53, - CONST_SRC_CODE_POSTFX_FADE_EFFECT = 0x54, - CONST_SRC_CODE_VIEWPORT_DIMENSIONS = 0x55, - CONST_SRC_CODE_FRAMEBUFFER_READ = 0x56, - CONST_SRC_CODE_RESIZE_PARAMS1 = 0x57, - CONST_SRC_CODE_RESIZE_PARAMS2 = 0x58, - CONST_SRC_CODE_RESIZE_PARAMS3 = 0x59, - CONST_SRC_CODE_VARIANT_WIND_SPRING_0 = 0x5A, - CONST_SRC_CODE_VARIANT_WIND_SPRING_1 = 0x5B, - CONST_SRC_CODE_VARIANT_WIND_SPRING_2 = 0x5C, - CONST_SRC_CODE_VARIANT_WIND_SPRING_3 = 0x5D, - CONST_SRC_CODE_VARIANT_WIND_SPRING_4 = 0x5E, - CONST_SRC_CODE_VARIANT_WIND_SPRING_5 = 0x5F, - CONST_SRC_CODE_VARIANT_WIND_SPRING_6 = 0x60, - CONST_SRC_CODE_VARIANT_WIND_SPRING_7 = 0x61, - CONST_SRC_CODE_VARIANT_WIND_SPRING_8 = 0x62, - CONST_SRC_CODE_VARIANT_WIND_SPRING_9 = 0x63, - CONST_SRC_CODE_VARIANT_WIND_SPRING_10 = 0x64, - CONST_SRC_CODE_VARIANT_WIND_SPRING_11 = 0x65, - CONST_SRC_CODE_VARIANT_WIND_SPRING_12 = 0x66, - CONST_SRC_CODE_VARIANT_WIND_SPRING_13 = 0x67, - CONST_SRC_CODE_VARIANT_WIND_SPRING_14 = 0x68, - CONST_SRC_CODE_VARIANT_WIND_SPRING_15 = 0x69, - CONST_SRC_CODE_CHARACTER_CHARRED_AMOUNT = 0x6A, - CONST_SRC_CODE_POSTFX_CONTROL0 = 0x6B, - CONST_SRC_CODE_POSTFX_CONTROL1 = 0x6C, - CONST_SRC_CODE_POSTFX_CONTROL2 = 0x6D, - CONST_SRC_CODE_POSTFX_CONTROL3 = 0x6E, - CONST_SRC_CODE_POSTFX_CONTROL4 = 0x6F, - CONST_SRC_CODE_POSTFX_CONTROL5 = 0x70, - CONST_SRC_CODE_POSTFX_CONTROL6 = 0x71, - CONST_SRC_CODE_POSTFX_CONTROL7 = 0x72, - CONST_SRC_CODE_POSTFX_CONTROL8 = 0x73, - CONST_SRC_CODE_POSTFX_CONTROL9 = 0x74, - CONST_SRC_CODE_POSTFX_CONTROLA = 0x75, - CONST_SRC_CODE_POSTFX_CONTROLB = 0x76, - CONST_SRC_CODE_POSTFX_CONTROLC = 0x77, - CONST_SRC_CODE_POSTFX_CONTROLD = 0x78, - CONST_SRC_CODE_POSTFX_CONTROLE = 0x79, - CONST_SRC_CODE_POSTFX_CONTROLF = 0x7A, - CONST_SRC_CODE_HDRCONTROL_0 = 0x7B, - CONST_SRC_CODE_HDRCONTROL_1 = 0x7C, - CONST_SRC_CODE_GLIGHT_POSXS = 0x7D, - CONST_SRC_CODE_GLIGHT_POSYS = 0x7E, - CONST_SRC_CODE_GLIGHT_POSZS = 0x7F, - CONST_SRC_CODE_GLIGHT_FALLOFFS = 0x80, - CONST_SRC_CODE_GLIGHT_REDS = 0x81, - CONST_SRC_CODE_GLIGHT_GREENS = 0x82, - CONST_SRC_CODE_GLIGHT_BLUES = 0x83, - CONST_SRC_CODE_DLIGHT_POSITION = 0x84, - CONST_SRC_CODE_DLIGHT_DIFFUSE = 0x85, - CONST_SRC_CODE_DLIGHT_ATTENUATION = 0x86, - CONST_SRC_CODE_DLIGHT_FALLOFF = 0x87, - CONST_SRC_CODE_DLIGHT_SPOT_MATRIX_0 = 0x88, - CONST_SRC_CODE_DLIGHT_SPOT_MATRIX_1 = 0x89, - CONST_SRC_CODE_DLIGHT_SPOT_MATRIX_2 = 0x8A, - CONST_SRC_CODE_DLIGHT_SPOT_MATRIX_3 = 0x8B, - CONST_SRC_CODE_DLIGHT_SPOT_DIR = 0x8C, - CONST_SRC_CODE_DLIGHT_SPOT_FACTORS = 0x8D, - CONST_SRC_CODE_DLIGHT_SHADOW_LOOKUP_MATRIX_0 = 0x8E, - CONST_SRC_CODE_DLIGHT_SHADOW_LOOKUP_MATRIX_1 = 0x8F, - CONST_SRC_CODE_DLIGHT_SHADOW_LOOKUP_MATRIX_2 = 0x90, - CONST_SRC_CODE_DLIGHT_SHADOW_LOOKUP_MATRIX_3 = 0x91, - CONST_SRC_CODE_CLOUD_LAYER_CONTROL0 = 0x92, - CONST_SRC_CODE_CLOUD_LAYER_CONTROL1 = 0x93, - CONST_SRC_CODE_CLOUD_LAYER_CONTROL2 = 0x94, - CONST_SRC_CODE_CLOUD_LAYER_CONTROL3 = 0x95, - CONST_SRC_CODE_CLOUD_LAYER_CONTROL4 = 0x96, - CONST_SRC_CODE_HERO_LIGHTING_R = 0x97, - CONST_SRC_CODE_HERO_LIGHTING_G = 0x98, - CONST_SRC_CODE_HERO_LIGHTING_B = 0x99, - CONST_SRC_CODE_LIGHT_HERO_SCALE = 0x9A, - CONST_SRC_CODE_CINEMATIC_BLUR_BOX = 0x9B, - CONST_SRC_CODE_CINEMATIC_BLUR_BOX2 = 0x9C, - CONST_SRC_CODE_ADSZSCALE = 0x9D, - CONST_SRC_CODE_UI3D_UV_SETUP_0 = 0x9E, - CONST_SRC_CODE_UI3D_UV_SETUP_1 = 0x9F, - CONST_SRC_CODE_UI3D_UV_SETUP_2 = 0xA0, - CONST_SRC_CODE_UI3D_UV_SETUP_3 = 0xA1, - CONST_SRC_CODE_UI3D_UV_SETUP_4 = 0xA2, - CONST_SRC_CODE_UI3D_UV_SETUP_5 = 0xA3, - CONST_SRC_CODE_CHARACTER_DISSOLVE_COLOR = 0xA4, - CONST_SRC_CODE_CAMERA_LOOK = 0xA5, - CONST_SRC_CODE_CAMERA_UP = 0xA6, - CONST_SRC_CODE_CAMERA_SIDE = 0xA7, - CONST_SRC_CODE_RIMINTENSITY = 0xA8, - CONST_SRC_CODE_GENERIC_PARAM0 = 0xA9, - CONST_SRC_CODE_GENERIC_PARAM1 = 0xAA, - CONST_SRC_CODE_GENERIC_PARAM2 = 0xAB, - CONST_SRC_CODE_GENERIC_PARAM3 = 0xAC, - CONST_SRC_CODE_GENERIC_PARAM4 = 0xAD, - CONST_SRC_CODE_GENERIC_PARAM5 = 0xAE, - CONST_SRC_CODE_GENERIC_PARAM6 = 0xAF, - CONST_SRC_CODE_GENERIC_PARAM7 = 0xB0, - CONST_SRC_CODE_GENERIC_EYEOFFSET = 0xB1, - CONST_SRC_CODE_GENERIC_QUADINTENSITY = 0xB2, - CONST_SRC_CODE_WEAPON_PARAM0 = 0xB3, - CONST_SRC_CODE_WEAPON_PARAM1 = 0xB4, - CONST_SRC_CODE_WEAPON_PARAM2 = 0xB5, - CONST_SRC_CODE_WEAPON_PARAM3 = 0xB6, - CONST_SRC_CODE_WEAPON_PARAM4 = 0xB7, - CONST_SRC_CODE_WEAPON_PARAM5 = 0xB8, - CONST_SRC_CODE_WEAPON_PARAM6 = 0xB9, - CONST_SRC_CODE_WEAPON_PARAM7 = 0xBA, - CONST_SRC_CODE_WEAPON_PARAM8 = 0xBB, - CONST_SRC_CODE_WEAPON_PARAM9 = 0xBC, - CONST_SRC_CODE_QRCODE_0 = 0xBD, - CONST_SRC_CODE_QRCODE_1 = 0xBE, - CONST_SRC_CODE_QRCODE_2 = 0xBF, - CONST_SRC_CODE_QRCODE_3 = 0xC0, - CONST_SRC_CODE_QRCODE_4 = 0xC1, - CONST_SRC_CODE_QRCODE_5 = 0xC2, - CONST_SRC_CODE_QRCODE_6 = 0xC3, - CONST_SRC_CODE_QRCODE_7 = 0xC4, - CONST_SRC_CODE_QRCODE_8 = 0xC5, - CONST_SRC_CODE_QRCODE_9 = 0xC6, - CONST_SRC_CODE_QRCODE_10 = 0xC7, - CONST_SRC_CODE_QRCODE_11 = 0xC8, - CONST_SRC_CODE_EYEOFFSET = 0xC9, - CONST_SRC_CODE_SKY_COLOR_MULTIPLIER = 0xCA, - CONST_SRC_CODE_EXTRA_CAM_PARAM = 0xCB, - CONST_SRC_CODE_EMBLEM_LUT_SELECTOR = 0xCC, - CONST_SRC_CODE_DEBUG_COLOR_OVERRIDE = 0xCD, - CONST_SRC_CODE_DEBUG_ALPHA_OVERRIDE = 0xCE, - CONST_SRC_CODE_DEBUG_NORMAL_OVERRIDE = 0xCF, - CONST_SRC_CODE_DEBUG_SPECULAR_OVERRIDE = 0xD0, - CONST_SRC_CODE_DEBUG_GLOSS_OVERRIDE = 0xD1, - CONST_SRC_CODE_DEBUG_OCCLUSION_OVERRIDE = 0xD2, - CONST_SRC_CODE_NEVER_DIRTY_PS_END = 0xD3, - CONST_SRC_CODE_COUNT_FLOAT4 = 0xD3, - CONST_SRC_FIRST_CODE_MATRIX = 0xD3, - CONST_SRC_CODE_WORLD_MATRIX = 0xD3, - CONST_SRC_CODE_INVERSE_WORLD_MATRIX = 0xD4, - CONST_SRC_CODE_TRANSPOSE_WORLD_MATRIX = 0xD5, - CONST_SRC_CODE_INVERSE_TRANSPOSE_WORLD_MATRIX = 0xD6, - CONST_SRC_CODE_VIEW_MATRIX = 0xD7, - CONST_SRC_CODE_INVERSE_VIEW_MATRIX = 0xD8, - CONST_SRC_CODE_TRANSPOSE_VIEW_MATRIX = 0xD9, - CONST_SRC_CODE_INVERSE_TRANSPOSE_VIEW_MATRIX = 0xDA, - CONST_SRC_CODE_PROJECTION_MATRIX = 0xDB, - CONST_SRC_CODE_INVERSE_PROJECTION_MATRIX = 0xDC, - CONST_SRC_CODE_TRANSPOSE_PROJECTION_MATRIX = 0xDD, - CONST_SRC_CODE_INVERSE_TRANSPOSE_PROJECTION_MATRIX = 0xDE, - CONST_SRC_CODE_WORLD_VIEW_MATRIX = 0xDF, - CONST_SRC_CODE_INVERSE_WORLD_VIEW_MATRIX = 0xE0, - CONST_SRC_CODE_TRANSPOSE_WORLD_VIEW_MATRIX = 0xE1, - CONST_SRC_CODE_INVERSE_TRANSPOSE_WORLD_VIEW_MATRIX = 0xE2, - CONST_SRC_CODE_VIEW_PROJECTION_MATRIX = 0xE3, - CONST_SRC_CODE_INVERSE_VIEW_PROJECTION_MATRIX = 0xE4, - CONST_SRC_CODE_TRANSPOSE_VIEW_PROJECTION_MATRIX = 0xE5, - CONST_SRC_CODE_INVERSE_TRANSPOSE_VIEW_PROJECTION_MATRIX = 0xE6, - CONST_SRC_CODE_WORLD_VIEW_PROJECTION_MATRIX = 0xE7, - CONST_SRC_CODE_INVERSE_WORLD_VIEW_PROJECTION_MATRIX = 0xE8, - CONST_SRC_CODE_TRANSPOSE_WORLD_VIEW_PROJECTION_MATRIX = 0xE9, - CONST_SRC_CODE_INVERSE_TRANSPOSE_WORLD_VIEW_PROJECTION_MATRIX = 0xEA, - CONST_SRC_CODE_SHADOW_LOOKUP_MATRIX = 0xEB, - CONST_SRC_CODE_INVERSE_SHADOW_LOOKUP_MATRIX = 0xEC, - CONST_SRC_CODE_TRANSPOSE_SHADOW_LOOKUP_MATRIX = 0xED, - CONST_SRC_CODE_INVERSE_TRANSPOSE_SHADOW_LOOKUP_MATRIX = 0xEE, - CONST_SRC_CODE_WORLD_OUTDOOR_LOOKUP_MATRIX = 0xEF, - CONST_SRC_CODE_INVERSE_WORLD_OUTDOOR_LOOKUP_MATRIX = 0xF0, - CONST_SRC_CODE_TRANSPOSE_WORLD_OUTDOOR_LOOKUP_MATRIX = 0xF1, - CONST_SRC_CODE_INVERSE_TRANSPOSE_WORLD_OUTDOOR_LOOKUP_MATRIX = 0xF2, - CONST_SRC_TOTAL_COUNT = 0xF3, - CONST_SRC_NONE = 0xF4, - }; - - struct MaterialShaderArgument - { - uint16_t type; - uint16_t dest; - MaterialArgumentDef u; - }; - - enum MaterialStreamStreamSource_e - { - STREAM_SRC_POSITION = 0x0, - STREAM_SRC_COLOR = 0x1, - STREAM_SRC_TEXCOORD_0 = 0x2, - STREAM_SRC_NORMAL = 0x3, - STREAM_SRC_TANGENT = 0x4, - - STREAM_SRC_OPTIONAL_BEGIN = 0x5, - STREAM_SRC_PRE_OPTIONAL_BEGIN = 0x4, - - STREAM_SRC_TEXCOORD_1 = 0x5, - STREAM_SRC_TEXCOORD_2 = 0x6, - STREAM_SRC_NORMAL_TRANSFORM_0 = 0x7, - STREAM_SRC_NORMAL_TRANSFORM_1 = 0x8, - - STREAM_SRC_COUNT - }; - - enum MaterialStreamDestination_e - { - STREAM_DST_POSITION = 0x0, - STREAM_DST_NORMAL = 0x1, - STREAM_DST_COLOR_0 = 0x2, - STREAM_DST_COLOR_1 = 0x3, - STREAM_DST_TEXCOORD_0 = 0x4, - STREAM_DST_TEXCOORD_1 = 0x5, - STREAM_DST_TEXCOORD_2 = 0x6, - STREAM_DST_TEXCOORD_3 = 0x7, - STREAM_DST_TEXCOORD_4 = 0x8, - STREAM_DST_TEXCOORD_5 = 0x9, - STREAM_DST_TEXCOORD_6 = 0xA, - STREAM_DST_TEXCOORD_7 = 0xB, - STREAM_DST_COUNT - }; - - struct MaterialStreamRouting - { - unsigned char source; - unsigned char dest; - }; - - struct MaterialVertexStreamRouting - { - MaterialStreamRouting data[16]; - void/*IDirect3DVertexDeclaration9*/* decl[16]; - }; - - struct MaterialVertexDeclaration - { - char streamCount; - bool hasOptionalSource; - bool isLoaded; - MaterialVertexStreamRouting routing; - }; - - struct GfxVertexShaderLoadDef - { - unsigned int* program; - uint16_t programSize; - uint16_t loadForRenderer; - }; - - struct MaterialVertexShaderProgram - { - void/*IDirect3DVertexShader9*/* vs; - GfxVertexShaderLoadDef loadDef; - }; - - struct MaterialVertexShader - { - const char* name; - MaterialVertexShaderProgram prog; - }; - - struct GfxPixelShaderLoadDef - { - unsigned int* program; - uint16_t programSize; - uint16_t loadForRenderer; - }; - - struct MaterialPixelShaderProgram - { - void/*IDirect3DPixelShader9*/* ps; - GfxPixelShaderLoadDef loadDef; - }; - - struct MaterialPixelShader - { - const char* name; - MaterialPixelShaderProgram prog; - }; - - struct MaterialPass - { - MaterialVertexDeclaration* vertexDecl; - MaterialVertexShader* vertexShader; - MaterialPixelShader* pixelShader; - char perPrimArgCount; - char perObjArgCount; - char stableArgCount; - char customSamplerFlags; - MaterialShaderArgument* args; - }; - - struct MaterialTechnique - { - const char* name; - uint16_t flags; - uint16_t passCount; - MaterialPass passArray[1]; - }; - - enum MaterialTechniqueType - { - TECHNIQUE_DEPTH_PREPASS = 0x0, - TECHNIQUE_BUILD_FLOAT_Z = 0x1, - TECHNIQUE_BUILD_SHADOWMAP_DEPTH = 0x2, - TECHNIQUE_BUILD_SHADOWMAP_COLOR = 0x3, - TECHNIQUE_UNLIT = 0x4, - TECHNIQUE_EMISSIVE = 0x5, - TECHNIQUE_EMISSIVE_SHADOW = 0x6, - - TECHNIQUE_LIT_BEGIN = 0x7, - - TECHNIQUE_LIT = 0x7, - TECHNIQUE_LIT_SUN = 0x8, - TECHNIQUE_LIT_SUN_SHADOW = 0x9, - TECHNIQUE_LIT_SPOT = 0xA, - TECHNIQUE_LIT_SPOT_SHADOW = 0xB, - TECHNIQUE_LIT_OMNI = 0xC, - TECHNIQUE_LIT_OMNI_SHADOW = 0xD, - TECHNIQUE_LIT_INSTANCED = 0xE, - TECHNIQUE_LIT_INSTANCED_SUN = 0xF, - TECHNIQUE_LIT_INSTANCED_SUN_SHADOW = 0x10, - TECHNIQUE_LIT_INSTANCED_SPOT = 0x11, - TECHNIQUE_LIT_INSTANCED_SPOT_SHADOW = 0x12, - TECHNIQUE_LIT_INSTANCED_OMNI = 0x13, - TECHNIQUE_LIT_INSTANCED_OMNI_SHADOW = 0x14, - - TECHNIQUE_LIT_END = 0x15, - - TECHNIQUE_LIGHT_SPOT = 0x15, - TECHNIQUE_LIGHT_OMNI = 0x16, - TECHNIQUE_LIGHT_SPOT_SHADOW = 0x17, - TECHNIQUE_FAKELIGHT_NORMAL = 0x18, - TECHNIQUE_FAKELIGHT_VIEW = 0x19, - TECHNIQUE_SUNLIGHT_PREVIEW = 0x1A, - TECHNIQUE_CASE_TEXTURE = 0x1B, - TECHNIQUE_WIREFRAME_SOLID = 0x1C, - TECHNIQUE_WIREFRAME_SHADED = 0x1D, - TECHNIQUE_SHADOWCOOKIE_CASTER = 0x1E, - TECHNIQUE_SHADOWCOOKIE_RECEIVER = 0x1F, - TECHNIQUE_DEBUG_BUMPMAP = 0x20, - TECHNIQUE_DEBUG_BUMPMAP_INSTANCED = 0x21, - TECHNIQUE_COUNT = 0x22, - TECHNIQUE_TOTAL_COUNT = 0x23, - TECHNIQUE_NONE = 0x24, - }; - - struct MaterialTechniqueSet - { - const char* name; - char worldVertFormat; - bool hasBeenUploaded; - char unused[1]; - MaterialTechniqueSet* remappedTechniqueSet; - MaterialTechnique* techniques[34]; - }; - - struct CardMemory - { - int platform[2]; - }; - - struct Picmip - { - char platform[2]; - }; - - struct GfxImageLoadDef - { - char levelCount; - char flags; - int16_t dimensions[3]; - int format; - int resourceSize; - char data[1]; - }; - - union GfxTexture - { - //void/*IDirect3DBaseTexture9*/* basemap; - //void/*IDirect3DTexture9*/* map; - //void/*IDirect3DVolumeTexture9*/* volmap; - //void/*IDirect3DCubeTexture9*/* cubemap; - Texture* texture; - GfxImageLoadDef* loadDef; - }; - - enum MapType - { - MAPTYPE_NONE = 0x0, - MAPTYPE_INVALID1 = 0x1, - MAPTYPE_INVALID2 = 0x2, - MAPTYPE_2D = 0x3, - MAPTYPE_3D = 0x4, - MAPTYPE_CUBE = 0x5, - MAPTYPE_COUNT = 0x6, - }; - - enum TextureSemantic - { - TS_2D = 0x0, - TS_FUNCTION = 0x1, - TS_COLOR_MAP = 0x2, - TS_UNUSED_1 = 0x3, - TS_UNUSED_2 = 0x4, - TS_NORMAL_MAP = 0x5, - TS_UNUSED_3 = 0x6, - TS_UNUSED_4 = 0x7, - TS_SPECULAR_MAP = 0x8, - TS_UNUSED_5 = 0x9, - TS_UNUSED_6 = 0xA, - TS_WATER_MAP = 0xB, - }; - - enum ImageCategory - { - IMG_CATEGORY_UNKNOWN = 0x0, - IMG_CATEGORY_AUTO_GENERATED = 0x1, - IMG_CATEGORY_LIGHTMAP = 0x2, - IMG_CATEGORY_LOAD_FROM_FILE = 0x3, - IMG_CATEGORY_RAW = 0x4, - IMG_CATEGORY_FIRST_UNMANAGED = 0x5, - IMG_CATEGORY_WATER = 0x5, - IMG_CATEGORY_RENDERTARGET = 0x6, - IMG_CATEGORY_TEMP = 0x7, - }; - - struct GfxImage - { - MapType mapType; - GfxTexture texture; - Picmip picmip; - bool noPicmip; - char semantic; - char track; - CardMemory cardMemory; - uint16_t width; - uint16_t height; - uint16_t depth; - char category; - bool delayLoadPixels; - const char* name; - }; - - struct SndCurve - { - const char* filename; - int knotCount; - float knots[8][2]; - }; - - struct MSSSpeakerLevels - { - int speaker; - int numLevels; - float levels[2]; - }; - - struct MSSChannelMap - { - int speakerCount; - MSSSpeakerLevels speakers[6]; - }; - - struct SpeakerMap - { - bool isDefault; - const char* name; - MSSChannelMap channelMaps[2][2]; - }; - - struct StreamedSound - { - const char* dir; - const char* name; - }; - - union SoundFileRef - { - LoadedSound* loadSnd; - StreamedSound streamSnd; - }; - - enum snd_alias_type_t - { - SAT_UNKNOWN = 0x0, - SAT_LOADED = 0x1, - SAT_STREAMED = 0x2, - SAT_COUNT = 0x3, - }; - - struct SoundFile - { - char type; - char exists; - SoundFileRef u; - }; - - struct snd_alias_t - { - const char* aliasName; - const char* subtitle; - const char* secondaryAliasName; - const char* chainAliasName; - SoundFile* soundFile; - int sequence; - float volMin; - float volMax; - float pitchMin; - float pitchMax; - float distMin; - float distMax; - int flags; - float slavePercentage; - float probability; - float lfePercentage; - float centerPercentage; - int startDelay; - SndCurve* volumeFalloffCurve; - float envelopMin; - float envelopMax; - float envelopPercentage; - SpeakerMap* speakerMap; - }; - - struct snd_alias_list_t - { - const char* aliasName; - snd_alias_t* head; - int count; - }; - - struct AILSOUNDINFO - { - int format; - const void* data_ptr; - unsigned int data_len; - unsigned int rate; - int bits; - int channels; - unsigned int samples; - unsigned int block_size; - const void* initial_ptr; - }; - - struct MssSound - { - AILSOUNDINFO info; - char* data; - }; - - struct LoadedSound - { - const char* name; - MssSound sound; - }; - - struct cStaticModelWritable - { - uint16_t nextModelInWorldSector; - }; - - struct cStaticModel_s - { - cStaticModelWritable writable; - XModel* xmodel; - float origin[3]; - float invScaledAxis[3][3]; - float absmin[3]; - float absmax[3]; - }; - - struct dmaterial_t - { - char material[64]; - int surfaceFlags; - int contentFlags; - }; - - struct cNode_t - { - cplane_s* plane; - int16_t children[2]; - }; - - struct cLeaf_t - { - uint16_t firstCollAabbIndex; - uint16_t collAabbCount; - int brushContents; - int terrainContents; - float mins[3]; - float maxs[3]; - int leafBrushNode; - int16_t cluster; - }; - - struct cLeafBrushNodeChildren_t - { - float dist; - float range; - uint16_t childOffset[2]; - }; - - struct cLeafBrushNodeLeaf_t - { - uint16_t* brushes; - }; - - union cLeafBrushNodeData_t - { - cLeafBrushNodeLeaf_t leaf; - cLeafBrushNodeChildren_t children; - }; - - struct cLeafBrushNode_s - { - char axis; - int16_t leafBrushCount; - int contents; - cLeafBrushNodeData_t data; - }; - - struct CollisionBorder - { - float distEq[3]; - float zBase; - float zSlope; - float start; - float length; - }; - - struct CollisionPartition - { - unsigned char triCount; - unsigned char borderCount; - int firstTri; - CollisionBorder* borders; - }; - - union CollisionAabbTreeIndex - { - int firstChildIndex; - int partitionIndex; - }; - - struct CollisionAabbTree - { - float origin[3]; - float halfSize[3]; - uint16_t materialIndex; - uint16_t childCount; - CollisionAabbTreeIndex u; - }; - - struct cmodel_t - { - float mins[3]; - float maxs[3]; - float radius; - cLeaf_t leaf; - }; - - struct type_align(16) cbrush_t - { - float mins[3]; - int contents; - float maxs[3]; - unsigned int numsides; - cbrushside_t* sides; - int16_t axialMaterialNum[2][3]; - char* baseAdjacentSide; - int16_t firstAdjacentSideOffsets[2][3]; - char edgeCount[2][3]; - }; - - struct GfxPlacement - { - float quat[4]; - float origin[3]; - }; - - enum DynEntityType - { - DYNENT_TYPE_INVALID = 0x0, - DYNENT_TYPE_CLUTTER = 0x1, - DYNENT_TYPE_DESTRUCT = 0x2, - DYNENT_TYPE_COUNT = 0x3, - }; - - struct DynEntityDef - { - DynEntityType type; - GfxPlacement pose; - XModel* xModel; - uint16_t brushModel; - uint16_t physicsBrushModel; - FxEffectDef* destroyFx; - XModelPieces* destroyPieces; - PhysPreset* physPreset; - int health; - PhysMass mass; - int contents; - }; - - struct DynEntityPose - { - GfxPlacement pose; - float radius; - }; - - struct DynEntityClient - { - int physObjId; - uint16_t flags; - uint16_t lightingHandle; - int health; - }; - - struct DynEntityColl - { - uint16_t sector; - uint16_t nextEntInSector; - float linkMins[2]; - float linkMaxs[2]; - }; - - typedef unsigned short LeafBrush; - - typedef tdef_align(16) cbrush_t cbrush_array_t; - - struct clipMap_t - { - const char* name; - int isInUse; - int planeCount; - cplane_s* planes; - unsigned int numStaticModels; - cStaticModel_s* staticModelList; - unsigned int numMaterials; - dmaterial_t* materials; - unsigned int numBrushSides; - cbrushside_t* brushsides; - unsigned int numBrushEdges; - cbrushedge_t* brushEdges; - unsigned int numNodes; - cNode_t* nodes; - unsigned int numLeafs; - cLeaf_t* leafs; - unsigned int leafbrushNodesCount; - cLeafBrushNode_s* leafbrushNodes; - unsigned int numLeafBrushes; - LeafBrush* leafbrushes; - unsigned int numLeafSurfaces; - unsigned int* leafsurfaces; - unsigned int vertCount; - vec3_t *verts; - int triCount; - uint16_t* triIndices; - char* triEdgeIsWalkable; - int borderCount; - CollisionBorder* borders; - int partitionCount; - CollisionPartition* partitions; - int aabbTreeCount; - CollisionAabbTree* aabbTrees; - unsigned int numSubModels; - cmodel_t* cmodels; - uint16_t numBrushes; - cbrush_t* brushes; - int numClusters; - int clusterBytes; - char* visibility; - int vised; - MapEnts* mapEnts; - cbrush_t* box_brush; - cmodel_t box_model; - uint16_t dynEntCount[2]; - DynEntityDef* dynEntDefList[2]; - DynEntityPose* dynEntPoseList[2]; - DynEntityClient* dynEntClientList[2]; - DynEntityColl* dynEntCollList[2]; - unsigned int checksum; - }; - - struct ComPrimaryLight - { - char type; - char canUseShadowMap; - char exponent; - char unused; - float color[3]; - float dir[3]; - float origin[3]; - float radius; - float cosHalfFovOuter; - float cosHalfFovInner; - float cosHalfFovExpanded; - float rotationLimit; - float translationLimit; - const char* defName; - }; - - struct ComWorld - { - const char* name; - int isInUse; - unsigned int primaryLightCount; - ComPrimaryLight* primaryLights; - }; - - struct pathnode_tree_nodes_t - { - int nodeCount; - uint16_t* nodes; - }; - - struct pathnode_t; - struct pathnode_tree_t; - - union pathnode_tree_info_t - { - pathnode_tree_t* child[2]; - pathnode_tree_nodes_t s; - }; - - struct pathnode_tree_t - { - int axis; - float dist; - pathnode_tree_info_t u; - }; - - struct type_align(16) pathbasenode_t - { - float vOrigin[3]; - unsigned int type; - }; - - struct pathnode_transient_t - { - int iSearchFrame; - pathnode_t* pNextOpen; - pathnode_t* pPrevOpen; - pathnode_t* pParent; - float fCost; - float fHeuristic; - float costFactor; - }; - - struct pathnode_dynamic_t - { - void* pOwner; - int iFreeTime; - int iValidTime[3]; - int inPlayerLOSTime; - int16_t wLinkCount; - int16_t wOverlapCount; - int16_t turretEntNumber; - int16_t userCount; - }; - - struct pathlink_s - { - float fDist; - uint16_t nodeNum; - char disconnectCount; - char negotiationLink; - char ubBadPlaceCount[4]; - }; - - enum nodeType - { - NODE_BADNODE = 0x0, - NODE_PATHNODE = 0x1, - NODE_COVER_STAND = 0x2, - NODE_COVER_CROUCH = 0x3, - NODE_COVER_CROUCH_WINDOW = 0x4, - NODE_COVER_PRONE = 0x5, - NODE_COVER_RIGHT = 0x6, - NODE_COVER_LEFT = 0x7, - NODE_COVER_WIDE_RIGHT = 0x8, - NODE_COVER_WIDE_LEFT = 0x9, - NODE_CONCEALMENT_STAND = 0xA, - NODE_CONCEALMENT_CROUCH = 0xB, - NODE_CONCEALMENT_PRONE = 0xC, - NODE_REACQUIRE = 0xD, - NODE_BALCONY = 0xE, - NODE_SCRIPTED = 0xF, - NODE_NEGOTIATION_BEGIN = 0x10, - NODE_NEGOTIATION_END = 0x11, - NODE_TURRET = 0x12, - NODE_GUARD = 0x13, - NODE_NUMTYPES = 0x14, - NODE_DONTLINK = 0x14, - }; - - struct pathnode_constant_t - { - nodeType type; - uint16_t spawnflags; - uint16_t targetname; - uint16_t script_linkName; - uint16_t script_noteworthy; - uint16_t target; - uint16_t animscript; - int animscriptfunc; - float vOrigin[3]; - float fAngle; - float forward[2]; - float fRadius; - float minUseDistSq; - int16_t wOverlapNode[2]; - int16_t wChainId; - int16_t wChainDepth; - int16_t wChainParent; - uint16_t totalLinkCount; - pathlink_s* Links; - }; - - struct pathnode_t - { - pathnode_constant_t constant; - pathnode_dynamic_t dynamic; - pathnode_transient_t transient; - }; - - struct PathData - { - unsigned int nodeCount; - pathnode_t* nodes; - pathbasenode_t* basenodes; - unsigned int chainNodeCount; - uint16_t* chainNodeForNode; - uint16_t* nodeForChainNode; - int visBytes; - char* pathVis; - int nodeTreeCount; - pathnode_tree_t* nodeTree; - }; - - struct GameWorldSp - { - const char* name; - PathData path; - }; - - struct GameWorldMp - { - const char* name; - }; - - struct MapEnts - { - const char* name; - char* entityString; - int numEntityChars; - }; - - struct GfxWorldVertex - { - float xyz[3]; - float binormalSign; - GfxColor color; - float texCoord[2]; - float lmapCoord[2]; - PackedUnitVec normal; - PackedUnitVec tangent; - }; - - struct GfxWorldVertexData - { - GfxWorldVertex* vertices; - void/*IDirect3DVertexBuffer9*/* worldVb; - }; - - struct GfxWorldVertexLayerData - { - char* data; - void/*IDirect3DVertexBuffer9*/* layerVb; - }; - - struct SunLightParseParams - { - char name[64]; - float ambientScale; - float ambientColor[3]; - float diffuseFraction; - float sunLight; - float sunColor[3]; - float diffuseColor[3]; - bool diffuseColorHasBeenSet; - float angles[3]; - }; - - struct GfxLightImage - { - GfxImage* image; - char samplerState; - }; - - struct GfxLightDef - { - const char* name; - GfxLightImage attenuation; - int lmapLookupStart; - }; - - struct GfxLight - { - char type; - char canUseShadowMap; - char unused[2]; - float color[3]; - float dir[3]; - float origin[3]; - float radius; - float cosHalfFovOuter; - float cosHalfFovInner; - int exponent; - unsigned int spotShadowIndex; - GfxLightDef* def; - }; - - struct GfxReflectionProbe - { - float origin[3]; - GfxImage* reflectionImage; - }; - - struct GfxWorldDpvsPlanes - { - int cellCount; - cplane_s* planes; - uint16_t* nodes; - unsigned int* sceneEntCellBits; - }; - - struct DpvsPlane - { - float coeffs[4]; - char side[3]; - char pad; - }; - - struct GfxCell; - struct GfxPortal; - - struct GfxPortalWritable - { - bool isQueued; - bool isAncestor; - char recursionDepth; - char hullPointCount; - float(*hullPoints)[2]; - GfxPortal* queuedParent; - }; - - struct GfxPortal - { - GfxPortalWritable writable; - DpvsPlane plane; - GfxCell* cell; - vec3_t* vertices; - char vertexCount; - float hullAxis[2][3]; - }; - - struct GfxAabbTree - { - float mins[3]; - float maxs[3]; - uint16_t childCount; - uint16_t surfaceCount; - uint16_t startSurfIndex; - uint16_t surfaceCountNoDecal; - uint16_t startSurfIndexNoDecal; - uint16_t smodelIndexCount; - uint16_t* smodelIndexes; - int childrenOffset; - }; - - struct GfxCell - { - float mins[3]; - float maxs[3]; - int aabbTreeCount; - GfxAabbTree* aabbTree; - int portalCount; - GfxPortal* portals; - int cullGroupCount; - int* cullGroups; - char reflectionProbeCount; - char* reflectionProbes; - }; - - struct GfxLightmapArray - { - GfxImage* primary; - GfxImage* secondary; - }; - - struct type_align(4) GfxLightGridEntry - { - uint16_t colorsIndex; - char primaryLightIndex; - char needsTrace; - }; - - struct type_align(4) GfxLightGridColors - { - char rgb[56][3]; - }; - - struct GfxLightGrid - { - bool hasLightRegions; - unsigned int sunPrimaryLightIndex; - uint16_t mins[3]; - uint16_t maxs[3]; - unsigned int rowAxis; - unsigned int colAxis; - uint16_t* rowDataStart; - unsigned int rawRowDataSize; - char* rawRowData; - unsigned int entryCount; - GfxLightGridEntry* entries; - unsigned int colorCount; - GfxLightGridColors* colors; - }; - - struct GfxBrushModelWritable - { - float mins[3]; - float maxs[3]; - }; - - struct GfxBrushModel - { - GfxBrushModelWritable writable; - float bounds[2][3]; - uint16_t surfaceCount; - uint16_t startSurfIndex; - uint16_t surfaceCountNoDecal; - }; - - struct MaterialMemory - { - Material* material; - int memory; - }; - - struct sunflare_t - { - bool hasValidData; - Material* spriteMaterial; - Material* flareMaterial; - float spriteSize; - float flareMinSize; - float flareMinDot; - float flareMaxSize; - float flareMaxDot; - float flareMaxAlpha; - int flareFadeInTime; - int flareFadeOutTime; - float blindMinDot; - float blindMaxDot; - float blindMaxDarken; - int blindFadeInTime; - int blindFadeOutTime; - float glareMinDot; - float glareMaxDot; - float glareMaxLighten; - int glareFadeInTime; - int glareFadeOutTime; - float sunFxPosition[3]; - }; - - struct XModelDrawInfo - { - uint16_t lod; - uint16_t surfId; - }; - - struct GfxSceneDynModel - { - XModelDrawInfo info; - uint16_t dynEntId; - }; - - struct BModelDrawInfo - { - uint16_t surfId; - }; - - struct type_align(4) GfxSceneDynBrush - { - BModelDrawInfo info; - uint16_t dynEntId; - }; - - struct GfxShadowGeometry - { - uint16_t surfaceCount; - uint16_t smodelCount; - uint16_t* sortedSurfIndex; - uint16_t* smodelIndex; - }; - - struct GfxLightRegionAxis - { - float dir[3]; - float midPoint; - float halfSize; - }; - - struct GfxLightRegionHull - { - float kdopMidPoint[9]; - float kdopHalfSize[9]; - unsigned int axisCount; - GfxLightRegionAxis* axis; - }; - - struct GfxLightRegion - { - unsigned int hullCount; - GfxLightRegionHull* hulls; - }; - - struct GfxPackedPlacement - { - float origin[3]; - float axis[3][3]; - float scale; - }; - - struct GfxStaticModelDrawInst - { - float cullDist; - GfxPackedPlacement placement; - XModel* model; - uint16_t smodelCacheIndex[4]; - char reflectionProbeIndex; - char primaryLightIndex; - uint16_t lightingHandle; - char flags; - }; - - struct GfxStaticModelInst - { - float mins[3]; - float maxs[3]; - GfxColor groundLighting; - }; - - struct srfTriangles_t - { - int vertexLayerData; - int firstVertex; - uint16_t vertexCount; - uint16_t triCount; - int baseIndex; - }; - - struct GfxSurface - { - srfTriangles_t tris; - Material* material; - char lightmapIndex; - char reflectionProbeIndex; - char primaryLightIndex; - char flags; - float bounds[2][3]; - }; - - struct GfxCullGroup - { - float mins[3]; - float maxs[3]; - int surfaceCount; - int startSurfIndex; - }; - - struct GfxWorldDpvsStatic - { - unsigned int smodelCount; - unsigned int staticSurfaceCount; - unsigned int staticSurfaceCountNoDecal; - unsigned int litSurfsBegin; - unsigned int litSurfsEnd; - unsigned int decalSurfsBegin; - unsigned int decalSurfsEnd; - unsigned int emissiveSurfsBegin; - unsigned int emissiveSurfsEnd; - unsigned int smodelVisDataCount; - unsigned int surfaceVisDataCount; - char* smodelVisData[3]; - char* surfaceVisData[3]; - raw_uint128* lodData; - uint16_t* sortedSurfIndex; - GfxStaticModelInst* smodelInsts; - GfxSurface* surfaces; - GfxCullGroup* cullGroups; - GfxStaticModelDrawInst* smodelDrawInsts; - GfxDrawSurf* surfaceMaterials; - raw_uint128* surfaceCastsSunShadow; - volatile int usageCount; - }; - - struct GfxWorldDpvsDynamic - { - unsigned int dynEntClientWordCount[2]; - unsigned int dynEntClientCount[2]; - unsigned int* dynEntCellBits[2]; - char* dynEntVisData[2][3]; - }; - - struct GfxWorldStreamInfo - { - char pad; - }; - - typedef tdef_align(4) GfxSceneDynModel GfxSceneDynModel4; - - struct GfxWorld - { - const char* name; - const char* baseName; - int planeCount; - int nodeCount; - int indexCount; - uint16_t* indices; - int surfaceCount; - GfxWorldStreamInfo streamInfo; - int skySurfCount; - int* skyStartSurfs; - GfxImage* skyImage; - char skySamplerState; - unsigned int vertexCount; - GfxWorldVertexData vd; - unsigned int vertexLayerDataSize; - GfxWorldVertexLayerData vld; - SunLightParseParams sunParse; - GfxLight* sunLight; - float sunColorFromBsp[3]; - unsigned int sunPrimaryLightIndex; - unsigned int primaryLightCount; - int cullGroupCount; - unsigned int reflectionProbeCount; - GfxReflectionProbe* reflectionProbes; - GfxTexture* reflectionProbeTextures; - GfxWorldDpvsPlanes dpvsPlanes; - int cellBitsCount; - GfxCell* cells; - int lightmapCount; - GfxLightmapArray* lightmaps; - GfxLightGrid lightGrid; - GfxTexture* lightmapPrimaryTextures; - GfxTexture* lightmapSecondaryTextures; - int modelCount; - GfxBrushModel* models; - float mins[3]; - float maxs[3]; - unsigned int checksum; - int materialMemoryCount; - MaterialMemory* materialMemory; - sunflare_t sun; - float outdoorLookupMatrix[4][4]; - GfxImage* outdoorImage; - unsigned int* cellCasterBits; - GfxSceneDynModel4* sceneDynModel; - GfxSceneDynBrush* sceneDynBrush; - unsigned int* primaryLightEntityShadowVis; - unsigned int* primaryLightDynEntShadowVis[2]; - char* nonSunPrimaryLightForModelDynEnt; - GfxShadowGeometry* shadowGeom; - GfxLightRegion* lightRegion; - GfxWorldDpvsStatic dpvs; - GfxWorldDpvsDynamic dpvsDyn; - }; - - struct Glyph - { - uint16_t letter; - char x0; - char y0; - char dx; - char pixelWidth; - char pixelHeight; - float s0; - float t0; - float s1; - float t1; - }; - - struct Font_s - { - const char* fontName; - int pixelHeight; - int glyphCount; - Material* material; - Material* glowMaterial; - Glyph* glyphs; - }; - - struct MenuList - { - const char* name; - int menuCount; - menuDef_t** menus; - }; - - struct rectDef_s - { - float x; - float y; - float w; - float h; - int horzAlign; - int vertAlign; - }; - - struct windowDef_t - { - const char* name; - rectDef_s rect; - rectDef_s rectClient; - const char* group; - int style; - int border; - int ownerDraw; - int ownerDrawFlags; - float borderSize; - int staticFlags; - int dynamicFlags[1]; - int nextTime; - float foreColor[4]; - float backColor[4]; - float borderColor[4]; - float outlineColor[4]; - Material* background; - }; - - struct ItemKeyHandler - { - int key; - const char* action; - ItemKeyHandler* next; - }; - - union operandInternalDataUnion - { - int intVal; - float floatVal; - const char* stringVal; - }; - - enum expDataType - { - VAL_INT = 0x0, - VAL_FLOAT = 0x1, - VAL_STRING = 0x2, - }; - - struct Operand - { - expDataType dataType; - operandInternalDataUnion internals; - }; - - union entryInternalData - { - int op; - Operand operand; - }; - - enum expressionEntryType : int - { - EET_OPERATOR = 0x0, - EET_OPERAND = 0x1, - }; - - struct expressionEntry - { - int type; - entryInternalData data; - }; - - struct statement_s - { - int numEntries; - expressionEntry** entries; - }; - - struct columnInfo_s - { - int pos; - int width; - int maxChars; - int alignment; - }; - - struct listBoxDef_s - { - int mousePos; - int startPos[1]; - int endPos[1]; - int drawPadding; - float elementWidth; - float elementHeight; - int elementStyle; - int numColumns; - columnInfo_s columnInfo[16]; - const char* doubleClick; - int notselectable; - int noScrollBars; - int usePaging; - float selectBorder[4]; - float disableColor[4]; - Material* selectIcon; - }; - - struct editFieldDef_s - { - float minVal; - float maxVal; - float defVal; - float range; - int maxChars; - int maxCharsGotoNext; - int maxPaintChars; - int paintOffset; - }; - - struct multiDef_s - { - const char* dvarList[32]; - const char* dvarStr[32]; - float dvarValue[32]; - int count; - int strDef; - }; - - union itemDefData_t - { - listBoxDef_s* listBox; - editFieldDef_s* editField; - multiDef_s* multi; - const char* enumDvarName; - void* data; - }; - - enum ItemDefType - { - ITEM_TYPE_TEXT = 0x0, - ITEM_TYPE_BUTTON = 0x1, - ITEM_TYPE_RADIOBUTTON = 0x2, - ITEM_TYPE_CHECKBOX = 0x3, - ITEM_TYPE_EDITFIELD = 0x4, - ITEM_TYPE_COMBO = 0x5, - ITEM_TYPE_LISTBOX = 0x6, - ITEM_TYPE_MODEL = 0x7, - ITEM_TYPE_OWNERDRAW = 0x8, - ITEM_TYPE_NUMERICFIELD = 0x9, - ITEM_TYPE_SLIDER = 0xA, - ITEM_TYPE_YESNO = 0xB, - ITEM_TYPE_MULTI = 0xC, - ITEM_TYPE_DVARENUM = 0xD, - ITEM_TYPE_BIND = 0xE, - ITEM_TYPE_MENUMODEL = 0xF, - ITEM_TYPE_VALIDFILEFIELD = 0x10, - ITEM_TYPE_DECIMALFIELD = 0x11, - ITEM_TYPE_UPREDITFIELD = 0x12, - ITEM_TYPE_GAME_MESSAGE_WINDOW = 0x13 - }; - - struct itemDef_s - { - windowDef_t window; - rectDef_s textRect[1]; - int type; - int dataType; - int alignment; - int fontEnum; - int textAlignMode; - float textalignx; - float textaligny; - float textscale; - int textStyle; - int gameMsgWindowIndex; - int gameMsgWindowMode; - const char* text; - int itemFlags; - menuDef_t* parent; - const char* mouseEnterText; - const char* mouseExitText; - const char* mouseEnter; - const char* mouseExit; - const char* action; - const char* onAccept; - const char* onFocus; - const char* leaveFocus; - const char* dvar; - const char* dvarTest; - ItemKeyHandler* onKey; - const char* enableDvar; - int dvarFlags; - snd_alias_list_t* focusSound; - float special; - int cursorPos[1]; - itemDefData_t typeData; - int imageTrack; - statement_s visibleExp; - statement_s textExp; - statement_s materialExp; - statement_s rectXExp; - statement_s rectYExp; - statement_s rectWExp; - statement_s rectHExp; - statement_s forecolorAExp; - }; - - struct menuDef_t - { - windowDef_t window; - const char* font; - int fullScreen; - int itemCount; - int fontIndex; - int cursorItem[1]; - int fadeCycle; - float fadeClamp; - float fadeAmount; - float fadeInAmount; - float blurRadius; - const char* onOpen; - const char* onClose; - const char* onESC; - ItemKeyHandler* onKey; - statement_s visibleExp; - const char* allowedBinding; - const char* soundName; - int imageTrack; - float focusColor[4]; - float disableColor[4]; - statement_s rectXExp; - statement_s rectYExp; - itemDef_s** items; - }; - - struct LocalizeEntry - { - const char* value; - const char* name; - }; - - enum weapType_t - { - WEAPTYPE_BULLET = 0x0, - WEAPTYPE_GRENADE = 0x1, - WEAPTYPE_PROJECTILE = 0x2, - WEAPTYPE_BINOCULARS = 0x3, - WEAPTYPE_NUM = 0x4, - }; - - enum weapClass_t - { - WEAPCLASS_RIFLE = 0x0, - WEAPCLASS_MG = 0x1, - WEAPCLASS_SMG = 0x2, - WEAPCLASS_SPREAD = 0x3, - WEAPCLASS_PISTOL = 0x4, - WEAPCLASS_GRENADE = 0x5, - WEAPCLASS_ROCKETLAUNCHER = 0x6, - WEAPCLASS_TURRET = 0x7, - WEAPCLASS_NON_PLAYER = 0x8, - WEAPCLASS_ITEM = 0x9, - WEAPCLASS_NUM = 0xA, - }; - - enum PenetrateType - { - PENETRATE_TYPE_NONE = 0x0, - PENETRATE_TYPE_SMALL = 0x1, - PENETRATE_TYPE_MEDIUM = 0x2, - PENETRATE_TYPE_LARGE = 0x3, - PENETRATE_TYPE_COUNT = 0x4, - }; - - enum ImpactType - { - IMPACT_TYPE_NONE = 0x0, - IMPACT_TYPE_BULLET_SMALL = 0x1, - IMPACT_TYPE_BULLET_LARGE = 0x2, - IMPACT_TYPE_BULLET_AP = 0x3, - IMPACT_TYPE_SHOTGUN = 0x4, - IMPACT_TYPE_GRENADE_BOUNCE = 0x5, - IMPACT_TYPE_GRENADE_EXPLODE = 0x6, - IMPACT_TYPE_ROCKET_EXPLODE = 0x7, - IMPACT_TYPE_PROJECTILE_DUD = 0x8, - IMPACT_TYPE_COUNT = 0x9, - }; - - enum weapInventoryType_t - { - WEAPINVENTORY_PRIMARY = 0x0, - WEAPINVENTORY_OFFHAND = 0x1, - WEAPINVENTORY_ITEM = 0x2, - WEAPINVENTORY_ALTMODE = 0x3, - WEAPINVENTORYCOUNT = 0x4, - }; - - enum weapFireType_t - { - WEAPON_FIRETYPE_FULLAUTO = 0x0, - WEAPON_FIRETYPE_SINGLESHOT = 0x1, - WEAPON_FIRETYPE_BURSTFIRE2 = 0x2, - WEAPON_FIRETYPE_BURSTFIRE3 = 0x3, - WEAPON_FIRETYPE_BURSTFIRE4 = 0x4, - WEAPON_FIRETYPECOUNT = 0x5, - }; - - enum OffhandClass - { - OFFHAND_CLASS_NONE = 0x0, - OFFHAND_CLASS_FRAG_GRENADE = 0x1, - OFFHAND_CLASS_SMOKE_GRENADE = 0x2, - OFFHAND_CLASS_FLASH_GRENADE = 0x3, - OFFHAND_CLASS_COUNT = 0x4, - }; - - enum weapStance_t - { - WEAPSTANCE_STAND = 0x0, - WEAPSTANCE_DUCK = 0x1, - WEAPSTANCE_PRONE = 0x2, - WEAPSTANCE_NUM = 0x3, - }; - - enum activeReticleType_t - { - VEH_ACTIVE_RETICLE_NONE = 0x0, - VEH_ACTIVE_RETICLE_PIP_ON_A_STICK = 0x1, - VEH_ACTIVE_RETICLE_BOUNCING_DIAMOND = 0x2, - VEH_ACTIVE_RETICLE_COUNT = 0x3, - }; - - enum weaponIconRatioType_t - { - WEAPON_ICON_RATIO_1TO1 = 0x0, - WEAPON_ICON_RATIO_2TO1 = 0x1, - WEAPON_ICON_RATIO_4TO1 = 0x2, - WEAPON_ICON_RATIO_COUNT = 0x3, - }; - - enum ammoCounterClipType_t - { - AMMO_COUNTER_CLIP_NONE = 0x0, - AMMO_COUNTER_CLIP_MAGAZINE = 0x1, - AMMO_COUNTER_CLIP_SHORTMAGAZINE = 0x2, - AMMO_COUNTER_CLIP_SHOTGUN = 0x3, - AMMO_COUNTER_CLIP_ROCKET = 0x4, - AMMO_COUNTER_CLIP_BELTFED = 0x5, - AMMO_COUNTER_CLIP_ALTWEAPON = 0x6, - AMMO_COUNTER_CLIP_COUNT = 0x7, - }; - - enum weapOverlayReticle_t - { - WEAPOVERLAYRETICLE_NONE = 0x0, - WEAPOVERLAYRETICLE_CROSSHAIR = 0x1, - WEAPOVERLAYRETICLE_NUM = 0x2, - }; - - enum WeapOverlayInteface_t - { - WEAPOVERLAYINTERFACE_NONE = 0x0, - WEAPOVERLAYINTERFACE_JAVELIN = 0x1, - WEAPOVERLAYINTERFACE_TURRETSCOPE = 0x2, - WEAPOVERLAYINTERFACECOUNT = 0x3, - }; - - enum weapProjExposion_t - { - WEAPPROJEXP_GRENADE = 0x0, - WEAPPROJEXP_ROCKET = 0x1, - WEAPPROJEXP_FLASHBANG = 0x2, - WEAPPROJEXP_NONE = 0x3, - WEAPPROJEXP_DUD = 0x4, - WEAPPROJEXP_SMOKE = 0x5, - WEAPPROJEXP_HEAVY = 0x6, - WEAPPROJEXP_NUM = 0x7, - }; - - enum WeapStickinessType - { - WEAPSTICKINESS_NONE = 0x0, - WEAPSTICKINESS_ALL = 0x1, - WEAPSTICKINESS_GROUND = 0x2, - WEAPSTICKINESS_GROUND_WITH_YAW = 0x3, - WEAPSTICKINESS_COUNT = 0x4, - }; - - enum guidedMissileType_t - { - MISSILE_GUIDANCE_NONE = 0x0, - MISSILE_GUIDANCE_SIDEWINDER = 0x1, - MISSILE_GUIDANCE_HELLFIRE = 0x2, - MISSILE_GUIDANCE_JAVELIN = 0x3, - MISSILE_GUIDANCE_COUNT = 0x4, - }; - - struct snd_alias_list_name - { - const char* soundName; - }; - - union SndAliasCustom - { - snd_alias_list_name* name; - snd_alias_list_t* sound; - }; - - struct WeaponDef - { - const char* szInternalName; - const char* szDisplayName; - const char* szOverlayName; - XModel* gunXModel[16]; - XModel* handXModel; - const char* szXAnims[33]; - const char* szModeName; - uint16_t hideTags[8]; - uint16_t notetrackSoundMapKeys[16]; - uint16_t notetrackSoundMapValues[16]; - int playerAnimType; - weapType_t weapType; - weapClass_t weapClass; - PenetrateType penetrateType; - ImpactType impactType; - weapInventoryType_t inventoryType; - weapFireType_t fireType; - OffhandClass offhandClass; - weapStance_t stance; - FxEffectDef* viewFlashEffect; - FxEffectDef* worldFlashEffect; - SndAliasCustom pickupSound; - SndAliasCustom pickupSoundPlayer; - SndAliasCustom ammoPickupSound; - SndAliasCustom ammoPickupSoundPlayer; - SndAliasCustom projectileSound; - SndAliasCustom pullbackSound; - SndAliasCustom pullbackSoundPlayer; - SndAliasCustom fireSound; - SndAliasCustom fireSoundPlayer; - SndAliasCustom fireLoopSound; - SndAliasCustom fireLoopSoundPlayer; - SndAliasCustom fireStopSound; - SndAliasCustom fireStopSoundPlayer; - SndAliasCustom fireLastSound; - SndAliasCustom fireLastSoundPlayer; - SndAliasCustom emptyFireSound; - SndAliasCustom emptyFireSoundPlayer; - SndAliasCustom meleeSwipeSound; - SndAliasCustom meleeSwipeSoundPlayer; - SndAliasCustom meleeHitSound; - SndAliasCustom meleeMissSound; - SndAliasCustom rechamberSound; - SndAliasCustom rechamberSoundPlayer; - SndAliasCustom reloadSound; - SndAliasCustom reloadSoundPlayer; - SndAliasCustom reloadEmptySound; - SndAliasCustom reloadEmptySoundPlayer; - SndAliasCustom reloadStartSound; - SndAliasCustom reloadStartSoundPlayer; - SndAliasCustom reloadEndSound; - SndAliasCustom reloadEndSoundPlayer; - SndAliasCustom detonateSound; - SndAliasCustom detonateSoundPlayer; - SndAliasCustom nightVisionWearSound; - SndAliasCustom nightVisionWearSoundPlayer; - SndAliasCustom nightVisionRemoveSound; - SndAliasCustom nightVisionRemoveSoundPlayer; - SndAliasCustom altSwitchSound; - SndAliasCustom altSwitchSoundPlayer; - SndAliasCustom raiseSound; - SndAliasCustom raiseSoundPlayer; - SndAliasCustom firstRaiseSound; - SndAliasCustom firstRaiseSoundPlayer; - SndAliasCustom putawaySound; - SndAliasCustom putawaySoundPlayer; - SndAliasCustom* bounceSound; - FxEffectDef* viewShellEjectEffect; - FxEffectDef* worldShellEjectEffect; - FxEffectDef* viewLastShotEjectEffect; - FxEffectDef* worldLastShotEjectEffect; - Material* reticleCenter; - Material* reticleSide; - int iReticleCenterSize; - int iReticleSideSize; - int iReticleMinOfs; - activeReticleType_t activeReticleType; - float vStandMove[3]; - float vStandRot[3]; - float vDuckedOfs[3]; - float vDuckedMove[3]; - float vDuckedRot[3]; - float vProneOfs[3]; - float vProneMove[3]; - float vProneRot[3]; - float fPosMoveRate; - float fPosProneMoveRate; - float fStandMoveMinSpeed; - float fDuckedMoveMinSpeed; - float fProneMoveMinSpeed; - float fPosRotRate; - float fPosProneRotRate; - float fStandRotMinSpeed; - float fDuckedRotMinSpeed; - float fProneRotMinSpeed; - XModel* worldModel[16]; - XModel* worldClipModel; - XModel* rocketModel; - XModel* knifeModel; - XModel* worldKnifeModel; - Material* hudIcon; - weaponIconRatioType_t hudIconRatio; - Material* ammoCounterIcon; - weaponIconRatioType_t ammoCounterIconRatio; - ammoCounterClipType_t ammoCounterClip; - int iStartAmmo; - const char* szAmmoName; - int iAmmoIndex; - const char* szClipName; - int iClipIndex; - int iMaxAmmo; - int iClipSize; - int shotCount; - const char* szSharedAmmoCapName; - int iSharedAmmoCapIndex; - int iSharedAmmoCap; - int damage; - int playerDamage; - int iMeleeDamage; - int iDamageType; - int iFireDelay; - int iMeleeDelay; - int meleeChargeDelay; - int iDetonateDelay; - int iFireTime; - int iRechamberTime; - int iRechamberBoltTime; - int iHoldFireTime; - int iDetonateTime; - int iMeleeTime; - int meleeChargeTime; - int iReloadTime; - int reloadShowRocketTime; - int iReloadEmptyTime; - int iReloadAddTime; - int iReloadStartTime; - int iReloadStartAddTime; - int iReloadEndTime; - int iDropTime; - int iRaiseTime; - int iAltDropTime; - int iAltRaiseTime; - int quickDropTime; - int quickRaiseTime; - int iFirstRaiseTime; - int iEmptyRaiseTime; - int iEmptyDropTime; - int sprintInTime; - int sprintLoopTime; - int sprintOutTime; - int nightVisionWearTime; - int nightVisionWearTimeFadeOutEnd; - int nightVisionWearTimePowerUp; - int nightVisionRemoveTime; - int nightVisionRemoveTimePowerDown; - int nightVisionRemoveTimeFadeInStart; - int fuseTime; - int aiFuseTime; - int requireLockonToFire; - int noAdsWhenMagEmpty; - int avoidDropCleanup; - float autoAimRange; - float aimAssistRange; - float aimAssistRangeAds; - float aimPadding; - float enemyCrosshairRange; - int crosshairColorChange; - float moveSpeedScale; - float adsMoveSpeedScale; - float sprintDurationScale; - float fAdsZoomFov; - float fAdsZoomInFrac; - float fAdsZoomOutFrac; - Material* overlayMaterial; - Material* overlayMaterialLowRes; - weapOverlayReticle_t overlayReticle; - WeapOverlayInteface_t overlayInterface; - float overlayWidth; - float overlayHeight; - float fAdsBobFactor; - float fAdsViewBobMult; - float fHipSpreadStandMin; - float fHipSpreadDuckedMin; - float fHipSpreadProneMin; - float hipSpreadStandMax; - float hipSpreadDuckedMax; - float hipSpreadProneMax; - float fHipSpreadDecayRate; - float fHipSpreadFireAdd; - float fHipSpreadTurnAdd; - float fHipSpreadMoveAdd; - float fHipSpreadDuckedDecay; - float fHipSpreadProneDecay; - float fHipReticleSidePos; - int iAdsTransInTime; - int iAdsTransOutTime; - float fAdsIdleAmount; - float fHipIdleAmount; - float adsIdleSpeed; - float hipIdleSpeed; - float fIdleCrouchFactor; - float fIdleProneFactor; - float fGunMaxPitch; - float fGunMaxYaw; - float swayMaxAngle; - float swayLerpSpeed; - float swayPitchScale; - float swayYawScale; - float swayHorizScale; - float swayVertScale; - float swayShellShockScale; - float adsSwayMaxAngle; - float adsSwayLerpSpeed; - float adsSwayPitchScale; - float adsSwayYawScale; - float adsSwayHorizScale; - float adsSwayVertScale; - int bRifleBullet; - int armorPiercing; - int bBoltAction; - int aimDownSight; - int bRechamberWhileAds; - float adsViewErrorMin; - float adsViewErrorMax; - int bCookOffHold; - int bClipOnly; - int adsFireOnly; - int cancelAutoHolsterWhenEmpty; - int suppressAmmoReserveDisplay; - int enhanced; - int laserSightDuringNightvision; - Material* killIcon; - weaponIconRatioType_t killIconRatio; - int flipKillIcon; - Material* dpadIcon; - weaponIconRatioType_t dpadIconRatio; - int bNoPartialReload; - int bSegmentedReload; - int iReloadAmmoAdd; - int iReloadStartAdd; - const char* szAltWeaponName; - unsigned int altWeaponIndex; - int iDropAmmoMin; - int iDropAmmoMax; - int blocksProne; - int silenced; - int iExplosionRadius; - int iExplosionRadiusMin; - int iExplosionInnerDamage; - int iExplosionOuterDamage; - float damageConeAngle; - int iProjectileSpeed; - int iProjectileSpeedUp; - int iProjectileSpeedForward; - int iProjectileActivateDist; - float projLifetime; - float timeToAccelerate; - float projectileCurvature; - XModel* projectileModel; - weapProjExposion_t projExplosion; - FxEffectDef* projExplosionEffect; - int projExplosionEffectForceNormalUp; - FxEffectDef* projDudEffect; - SndAliasCustom projExplosionSound; - SndAliasCustom projDudSound; - int bProjImpactExplode; - WeapStickinessType stickiness; - int hasDetonator; - int timedDetonation; - int rotate; - int holdButtonToThrow; - int freezeMovementWhenFiring; - float lowAmmoWarningThreshold; - float parallelBounce[29]; - float perpendicularBounce[29]; - FxEffectDef* projTrailEffect; - float vProjectileColor[3]; - guidedMissileType_t guidedMissileType; - float maxSteeringAccel; - int projIgnitionDelay; - FxEffectDef* projIgnitionEffect; - SndAliasCustom projIgnitionSound; - float fAdsAimPitch; - float fAdsCrosshairInFrac; - float fAdsCrosshairOutFrac; - int adsGunKickReducedKickBullets; - float adsGunKickReducedKickPercent; - float fAdsGunKickPitchMin; - float fAdsGunKickPitchMax; - float fAdsGunKickYawMin; - float fAdsGunKickYawMax; - float fAdsGunKickAccel; - float fAdsGunKickSpeedMax; - float fAdsGunKickSpeedDecay; - float fAdsGunKickStaticDecay; - float fAdsViewKickPitchMin; - float fAdsViewKickPitchMax; - float fAdsViewKickYawMin; - float fAdsViewKickYawMax; - float fAdsViewKickCenterSpeed; - float fAdsViewScatterMin; - float fAdsViewScatterMax; - float fAdsSpread; - int hipGunKickReducedKickBullets; - float hipGunKickReducedKickPercent; - float fHipGunKickPitchMin; - float fHipGunKickPitchMax; - float fHipGunKickYawMin; - float fHipGunKickYawMax; - float fHipGunKickAccel; - float fHipGunKickSpeedMax; - float fHipGunKickSpeedDecay; - float fHipGunKickStaticDecay; - float fHipViewKickPitchMin; - float fHipViewKickPitchMax; - float fHipViewKickYawMin; - float fHipViewKickYawMax; - float fHipViewKickCenterSpeed; - float fHipViewScatterMin; - float fHipViewScatterMax; - float fightDist; - float maxDist; - // TODO: Order is accuracyGraphName[0] -> originalAccuracyGraphKnots[0] -> accuracyGraphName[1] -> ... - // Which is currently not possible to do in code generation. Afaik this is the only place where this is the case. - // So might be something to fix but on the other hand it might be too much work for this little inconvenience. - //const char* accuracyGraphName[2]; - const char* accuracyGraphName0; - const char* accuracyGraphName1; - //float(*accuracyGraphKnots[2])[2]; - vec2_t* accuracyGraphKnots0; - vec2_t* accuracyGraphKnots1; - //float(*originalAccuracyGraphKnots[2])[2]; - vec2_t* originalAccuracyGraphKnots0; - vec2_t* originalAccuracyGraphKnots1; - int accuracyGraphKnotCount[2]; - int originalAccuracyGraphKnotCount[2]; - int iPositionReloadTransTime; - float leftArc; - float rightArc; - float topArc; - float bottomArc; - float accuracy; - float aiSpread; - float playerSpread; - float minTurnSpeed[2]; - float maxTurnSpeed[2]; - float pitchConvergenceTime; - float yawConvergenceTime; - float suppressTime; - float maxRange; - float fAnimHorRotateInc; - float fPlayerPositionDist; - const char* szUseHintString; - const char* dropHintString; - int iUseHintStringIndex; - int dropHintStringIndex; - float horizViewJitter; - float vertViewJitter; - const char* szScript; - float fOOPosAnimLength[2]; - int minDamage; - int minPlayerDamage; - float fMaxDamageRange; - float fMinDamageRange; - float destabilizationRateTime; - float destabilizationCurvatureMax; - int destabilizeDistance; - float locationDamageMultipliers[19]; - const char* fireRumble; - const char* meleeImpactRumble; - float adsDofStart; - float adsDofEnd; - }; - - struct SndDriverGlobals - { - const char* name; - }; - - struct FxIntRange - { - int base; - int amplitude; - }; - - struct FxFloatRange - { - float base; - float amplitude; - }; - - struct FxSpawnDefOneShot - { - FxIntRange count; - }; - - struct FxSpawnDefLooping - { - int intervalMsec; - int count; - }; - - union FxSpawnDef - { - FxSpawnDefLooping looping; - FxSpawnDefOneShot oneShot; - }; - - struct FxElemAtlas - { - char behavior; - char index; - char fps; - char loopCount; - char colIndexBits; - char rowIndexBits; - int16_t entryCount; - }; - - struct FxElemVec3Range - { - float base[3]; - float amplitude[3]; - }; - - struct FxElemVelStateInFrame - { - FxElemVec3Range velocity; - FxElemVec3Range totalDelta; - }; - - struct FxElemVelStateSample - { - FxElemVelStateInFrame local; - FxElemVelStateInFrame world; - }; - - struct FxElemVisualState - { - char color[4]; - float rotationDelta; - float rotationTotal; - float size[2]; - float scale; - }; - - struct FxElemVisStateSample - { - FxElemVisualState base; - FxElemVisualState amplitude; - }; - - union FxEffectDefRef - { - FxEffectDef* handle; - const char* name; - }; - - enum FxElemType - { - FX_ELEM_TYPE_SPRITE_BILLBOARD = 0x0, - FX_ELEM_TYPE_SPRITE_ORIENTED = 0x1, - FX_ELEM_TYPE_TAIL = 0x2, - FX_ELEM_TYPE_TRAIL = 0x3, - FX_ELEM_TYPE_CLOUD = 0x4, - FX_ELEM_TYPE_MODEL = 0x5, - FX_ELEM_TYPE_OMNI_LIGHT = 0x6, - FX_ELEM_TYPE_SPOT_LIGHT = 0x7, - FX_ELEM_TYPE_SOUND = 0x8, - FX_ELEM_TYPE_DECAL = 0x9, - FX_ELEM_TYPE_RUNNER = 0xA, - FX_ELEM_TYPE_COUNT = 0xB, - FX_ELEM_TYPE_LAST_SPRITE = 0x3, - FX_ELEM_TYPE_LAST_DRAWN = 0x7, - }; - - union FxElemVisuals - { - const void* anonymous; - Material* material; - XModel* model; - FxEffectDefRef effectDef; - const char* soundName; - }; - - struct FxElemMarkVisuals - { - Material* materials[2]; - }; - - union FxElemDefVisuals - { - FxElemMarkVisuals* markArray; - FxElemVisuals* array; - FxElemVisuals instance; - }; - - struct FxTrailVertex - { - float pos[2]; - float normal[2]; - float texCoord; - }; - - struct FxTrailDef - { - int scrollTimeMsec; - int repeatDist; - int splitDist; - int vertCount; - FxTrailVertex* verts; - int indCount; - uint16_t* inds; - }; - - struct FxElemDef - { - int flags; - FxSpawnDef spawn; - FxFloatRange spawnRange; - FxFloatRange fadeInRange; - FxFloatRange fadeOutRange; - float spawnFrustumCullRadius; - FxIntRange spawnDelayMsec; - FxIntRange lifeSpanMsec; - FxFloatRange spawnOrigin[3]; - FxFloatRange spawnOffsetRadius; - FxFloatRange spawnOffsetHeight; - FxFloatRange spawnAngles[3]; - FxFloatRange angularVelocity[3]; - FxFloatRange initialRotation; - FxFloatRange gravity; - FxFloatRange reflectionFactor; - FxElemAtlas atlas; - char elemType; - char visualCount; - char velIntervalCount; - char visStateIntervalCount; - FxElemVelStateSample* velSamples; - FxElemVisStateSample* visSamples; - FxElemDefVisuals visuals; - float collMins[3]; - float collMaxs[3]; - FxEffectDefRef effectOnImpact; - FxEffectDefRef effectOnDeath; - FxEffectDefRef effectEmitted; - FxFloatRange emitDist; - FxFloatRange emitDistVariance; - FxTrailDef* trailDef; - char sortOrder; - char lightingFrac; - char useItemClip; - char unused[1]; - }; - - struct FxEffectDef - { - const char* name; - int flags; - int totalSize; - int msecLoopingLife; - int elemDefCountLooping; - int elemDefCountOneShot; - int elemDefCountEmission; - FxElemDef* elemDefs; - }; - - struct FxImpactEntry - { - FxEffectDef* nonflesh[29]; - FxEffectDef* flesh[4]; - }; - - struct FxImpactTable - { - const char* name; - FxImpactEntry* table; - }; - - struct RawFile - { - const char* name; - int len; - const char* buffer; - }; - - struct StringTable - { - const char* name; - int columnCount; - int rowCount; - const char** values; - }; +enum XAssetType { + ASSET_TYPE_XMODELPIECES = 0x0, + ASSET_TYPE_PHYSPRESET = 0x1, + ASSET_TYPE_XANIMPARTS = 0x2, + ASSET_TYPE_XMODEL = 0x3, + ASSET_TYPE_MATERIAL = 0x4, + ASSET_TYPE_TECHNIQUE_SET = 0x5, + ASSET_TYPE_IMAGE = 0x6, + ASSET_TYPE_SOUND = 0x7, + ASSET_TYPE_SOUND_CURVE = 0x8, + ASSET_TYPE_LOADED_SOUND = 0x9, + ASSET_TYPE_CLIPMAP = 0xA, + ASSET_TYPE_CLIPMAP_PVS = 0xB, + ASSET_TYPE_COMWORLD = 0xC, + ASSET_TYPE_GAMEWORLD_SP = 0xD, + ASSET_TYPE_GAMEWORLD_MP = 0xE, + ASSET_TYPE_MAP_ENTS = 0xF, + ASSET_TYPE_GFXWORLD = 0x10, + ASSET_TYPE_LIGHT_DEF = 0x11, + ASSET_TYPE_UI_MAP = 0x12, + ASSET_TYPE_FONT = 0x13, + ASSET_TYPE_MENULIST = 0x14, + ASSET_TYPE_MENU = 0x15, + ASSET_TYPE_LOCALIZE_ENTRY = 0x16, + ASSET_TYPE_WEAPON = 0x17, + ASSET_TYPE_SNDDRIVER_GLOBALS = 0x18, + ASSET_TYPE_FX = 0x19, + ASSET_TYPE_IMPACT_FX = 0x1A, + ASSET_TYPE_AITYPE = 0x1B, + ASSET_TYPE_MPTYPE = 0x1C, + ASSET_TYPE_CHARACTER = 0x1D, + ASSET_TYPE_XMODELALIAS = 0x1E, + ASSET_TYPE_RAWFILE = 0x1F, + ASSET_TYPE_STRINGTABLE = 0x20, + ASSET_TYPE_COUNT, + + ASSET_TYPE_STRING = ASSET_TYPE_COUNT, + ASSET_TYPE_ASSETLIST, + + ASSET_TYPE_FULLCOUNT +}; + +enum XFileBlock { + XFILE_BLOCK_TEMP, + XFILE_BLOCK_RUNTIME, + XFILE_BLOCK_LARGE_RUNTIME, + XFILE_BLOCK_PHYSICAL_RUNTIME, + XFILE_BLOCK_VIRTUAL, + XFILE_BLOCK_LARGE, + XFILE_BLOCK_PHYSICAL, + XFILE_BLOCK_VERTEX, + XFILE_BLOCK_INDEX, + + MAX_XFILE_COUNT +}; + +struct XModelPieces; +struct PhysPreset; +struct XAnimParts; +struct XModel; +struct Material; +struct MaterialPixelShader; +struct MaterialVertexShader; +struct MaterialTechniqueSet; +struct GfxImage; +struct snd_alias_list_t; +struct SndCurve; +struct LoadedSound; +struct clipMap_t; +struct ComWorld; +struct GameWorldSp; +struct GameWorldMp; +struct MapEnts; +struct GfxWorld; +struct GfxLightDef; +struct Font_s; +struct MenuList; +struct menuDef_t; +struct LocalizeEntry; +struct WeaponDef; +struct SndDriverGlobals; +struct FxEffectDef; +struct FxImpactTable; +struct RawFile; +struct StringTable; + +union XAssetHeader { + // XModelPieces *xmodelPieces; // NOT AN ASSET + PhysPreset *physPreset; + XAnimParts *parts; + XModel *model; + Material *material; + MaterialPixelShader *pixelShader; + MaterialVertexShader *vertexShader; + MaterialTechniqueSet *techniqueSet; + GfxImage *image; + snd_alias_list_t *sound; + SndCurve *sndCurve; + LoadedSound *loadSnd; + clipMap_t *clipMap; + ComWorld *comWorld; + GameWorldSp *gameWorldSp; + GameWorldMp *gameWorldMp; + MapEnts *mapEnts; + GfxWorld *gfxWorld; + GfxLightDef *lightDef; + Font_s *font; + MenuList *menuList; + menuDef_t *menu; + LocalizeEntry *localize; + WeaponDef *weapon; + SndDriverGlobals *sndDriverGlobals; + FxEffectDef *fx; + FxImpactTable *impactFx; + RawFile *rawfile; + StringTable *stringTable; + void *data; +}; + +typedef char cbrushedge_t; +typedef float vec2_t[2]; +typedef float vec3_t[3]; +typedef float vec4_t[4]; +typedef tdef_align(128) unsigned int raw_uint128; + +struct XModelPiece { + XModel *model; + float offset[3]; +}; + +struct XModelPieces { + const char *name; + int numpieces; + XModelPiece *pieces; +}; + +struct PhysPreset { + const char *name; + int type; + float mass; + float bounce; + float friction; + float bulletForceScale; + float explosiveForceScale; + const char *sndAliasPrefix; + float piecesSpreadFraction; + float piecesUpwardVelocity; + bool tempDefaultToCylinder; +}; + +union XAnimIndices { + char *_1; + uint16_t *_2; + void *data; +}; + +struct XAnimNotifyInfo { + uint16_t name; + float time; +}; + +typedef unsigned char ByteVec[3]; +typedef tdef_align(4) unsigned short UShortVec[3]; + +union XAnimDynamicIndicesTrans { + char _1[1]; + uint16_t _2[1]; +}; + +union XAnimDynamicFrames { + ByteVec *_1; + UShortVec *_2; +}; + +struct XAnimPartTransFrames { + float mins[3]; + float size[3]; + XAnimDynamicFrames frames; + XAnimDynamicIndicesTrans indices; +}; + +union XAnimPartTransData { + XAnimPartTransFrames frames; + vec3_t frame0; +}; + +struct XAnimPartTrans { + uint16_t size; + char smallTrans; + XAnimPartTransData u; +}; + +typedef tdef_align(4) short XQuat[2]; + +union XAnimDynamicIndicesQuat { + char _1[1]; + uint16_t _2[1]; +}; + +struct XAnimDeltaPartQuatDataFrames { + XQuat *frames; + XAnimDynamicIndicesQuat indices; +}; + +union XAnimDeltaPartQuatData { + XAnimDeltaPartQuatDataFrames frames; + int16_t frame0[2]; +}; + +struct XAnimDeltaPartQuat { + uint16_t size; + XAnimDeltaPartQuatData u; +}; + +struct XAnimDeltaPart { + XAnimPartTrans *trans; + XAnimDeltaPartQuat *quat; +}; + +struct XAnimParts { + const char *name; + uint16_t dataByteCount; + uint16_t dataShortCount; + uint16_t dataIntCount; + uint16_t randomDataByteCount; + uint16_t randomDataIntCount; + uint16_t numframes; + bool bLoop; + bool bDelta; + unsigned char boneCount[10]; + char notifyCount; + char assetType; + bool isDefault; + unsigned int randomDataShortCount; + unsigned int indexCount; + float framerate; + float frequency; + uint16_t *names; + char *dataByte; + int16_t *dataShort; + int *dataInt; + int16_t *randomDataShort; + char *randomDataByte; + int *randomDataInt; + XAnimIndices indices; + XAnimNotifyInfo *notify; + XAnimDeltaPart *deltaPart; +}; + +struct DObjSkelMat { + float axis[3][4]; + float origin[4]; +}; + +struct DObjAnimMat { + float quat[4]; + float trans[3]; + float transWeight; +}; + +struct XSurfaceCollisionAabb { + uint16_t mins[3]; + uint16_t maxs[3]; +}; + +struct type_align(16) XSurfaceCollisionNode { + XSurfaceCollisionAabb aabb; + uint16_t childBeginIndex; + uint16_t childCount; +}; + +struct XSurfaceCollisionLeaf { + uint16_t triangleBeginIndex; +}; + +struct XSurfaceCollisionTree { + float trans[3]; + float scale[3]; + unsigned int nodeCount; + XSurfaceCollisionNode *nodes; + unsigned int leafCount; + XSurfaceCollisionLeaf *leafs; +}; + +struct XRigidVertList { + uint16_t boneOffset; + uint16_t vertCount; + uint16_t triOffset; + uint16_t triCount; + XSurfaceCollisionTree *collisionTree; +}; + +union GfxColor { + unsigned int packed; + char array[4]; +}; + +union PackedTexCoords { + unsigned int packed; +}; + +union PackedUnitVec { + unsigned int packed; + char array[4]; +}; + +struct type_align(16) GfxPackedVertex { + float xyz[3]; + float binormalSign; + GfxColor color; + PackedTexCoords texCoord; + PackedUnitVec normal; + PackedUnitVec tangent; +}; + +struct XSurfaceVertexInfo { + int16_t vertCount[4]; + uint16_t *vertsBlend; +}; + +typedef tdef_align(16) uint16_t r_index16_t; + +struct XSurface { + char tileMode; + bool deformed; + uint16_t vertCount; + uint16_t triCount; + char zoneHandle; + uint16_t baseTriIndex; + uint16_t baseVertIndex; + r_index16_t (*triIndices)[3]; + XSurfaceVertexInfo vertInfo; + GfxPackedVertex *verts0; + unsigned int vertListCount; + XRigidVertList *vertList; + int partBits[4]; +}; + +struct XModelLodInfo { + float dist; + uint16_t numsurfs; + uint16_t surfIndex; + int partBits[4]; + char lod; + char smcIndexPlusOne; + char smcAllocBits; + char unused; +}; + +struct XModelCollTri_s { + float plane[4]; + float svec[4]; + float tvec[4]; +}; + +struct XModelCollSurf_s { + XModelCollTri_s *collTris; + int numCollTris; + float mins[3]; + float maxs[3]; + int boneIdx; + int contents; + int surfFlags; +}; + +struct XBoneInfo { + float bounds[2][3]; + float offset[3]; + float radiusSquared; +}; + +struct cplane_s { + float normal[3]; + float dist; + char type; + char signbits; + char pad[2]; +}; + +struct cbrushside_t { + cplane_s *plane; + unsigned int materialNum; + int16_t firstAdjacentSideOffset; + char edgeCount; +}; + +struct BrushWrapper { + float mins[3]; + int contents; + float maxs[3]; + unsigned int numsides; + cbrushside_t *sides; + int16_t axialMaterialNum[2][3]; + char *baseAdjacentSide; + int16_t firstAdjacentSideOffsets[2][3]; + char edgeCount[2][3]; + int totalEdgeCount; + cplane_s *planes; +}; + +struct PhysGeomInfo { + BrushWrapper *brush; + int type; + float orientation[3][3]; + float offset[3]; + float halfLengths[3]; +}; + +struct PhysMass { + float centerOfMass[3]; + float momentsOfInertia[3]; + float productsOfInertia[3]; +}; + +struct PhysGeomList { + unsigned int count; + PhysGeomInfo *geoms; + PhysMass mass; +}; + +struct XModelStreamInfo { + char pad; +}; + +struct XModel { + const char *name; + unsigned char numBones; + unsigned char numRootBones; + unsigned char numsurfs; + char lodRampType; + uint16_t *boneNames; + char *parentList; + int16_t (*quats)[4]; + float (*trans)[4]; + char *partClassification; + DObjAnimMat *baseMat; + XSurface *surfs; + Material **materialHandles; + XModelLodInfo lodInfo[4]; + XModelCollSurf_s *collSurfs; + int numCollSurfs; + int contents; + XBoneInfo *boneInfo; + float radius; + float mins[3]; + float maxs[3]; + uint16_t numLods; + uint16_t collLod; + XModelStreamInfo streamInfo; + int memUsage; + char flags; + bool bad; + PhysPreset *physPreset; + PhysGeomList *physGeoms; +}; + +enum GfxBlend { + GFXS_BLEND_DISABLED = 0x0, + GFXS_BLEND_ZERO = 0x1, + GFXS_BLEND_ONE = 0x2, + GFXS_BLEND_SRCCOLOR = 0x3, + GFXS_BLEND_INVSRCCOLOR = 0x4, + GFXS_BLEND_SRCALPHA = 0x5, + GFXS_BLEND_INVSRCALPHA = 0x6, + GFXS_BLEND_DESTALPHA = 0x7, + GFXS_BLEND_INVDESTALPHA = 0x8, + GFXS_BLEND_DESTCOLOR = 0x9, + GFXS_BLEND_INVDESTCOLOR = 0xA, + GFXS_BLEND_MASK = 0xF, +}; + +enum GfxBlendOp { + GFXS_BLENDOP_DISABLED = 0x0, + GFXS_BLENDOP_ADD = 0x1, + GFXS_BLENDOP_SUBTRACT = 0x2, + GFXS_BLENDOP_REVSUBTRACT = 0x3, + GFXS_BLENDOP_MIN = 0x4, + GFXS_BLENDOP_MAX = 0x5, + GFXS_BLENDOP_MASK = 0x7, +}; + +enum GfxStencilOp { + GFXS_STENCILOP_KEEP = 0x0, + GFXS_STENCILOP_ZERO = 0x1, + GFXS_STENCILOP_REPLACE = 0x2, + GFXS_STENCILOP_INCRSAT = 0x3, + GFXS_STENCILOP_DECRSAT = 0x4, + GFXS_STENCILOP_INVERT = 0x5, + GFXS_STENCILOP_INCR = 0x6, + GFXS_STENCILOP_DECR = 0x7, + + GFXS_STENCILOP_COUNT, + GFXS_STENCILOP_MASK = 0x7 +}; + +enum GfxStateBitsEnum : unsigned int { + GFXS0_SRCBLEND_RGB_SHIFT = 0x0, + GFXS0_SRCBLEND_RGB_MASK = 0xF, + + GFXS0_DSTBLEND_RGB_SHIFT = 0x4, + GFXS0_DSTBLEND_RGB_MASK = 0xF0, + + GFXS0_BLENDOP_RGB_SHIFT = 0x8, + GFXS0_BLENDOP_RGB_MASK = 0x700, + GFXS0_BLEND_RGB_MASK = 0x7FF, + + GFXS0_ATEST_DISABLE = 0x800, + GFXS0_ATEST_GT_0 = 0x1000, + GFXS0_ATEST_LT_128 = 0x2000, + GFXS0_ATEST_GE_128 = 0x3000, + GFXS0_ATEST_MASK = 0x3000, + + GFXS0_CULL_SHIFT = 0xE, + GFXS0_CULL_NONE = 0x4000, + GFXS0_CULL_BACK = 0x8000, + GFXS0_CULL_FRONT = 0xC000, + GFXS0_CULL_MASK = 0xC000, + + GFXS0_SRCBLEND_ALPHA_SHIFT = 0x10, + GFXS0_SRCBLEND_ALPHA_MASK = 0xF0000, + + GFXS0_DSTBLEND_ALPHA_SHIFT = 0x14, + GFXS0_DSTBLEND_ALPHA_MASK = 0xF00000, + + GFXS0_BLENDOP_ALPHA_SHIFT = 0x18, + GFXS0_BLENDOP_ALPHA_MASK = 0x7000000, + GFXS0_BLEND_ALPHA_MASK = 0x7FF0000, + + GFXS0_COLORWRITE_RGB = 0x8000000, + GFXS0_COLORWRITE_ALPHA = 0x10000000, + GFXS0_COLORWRITE_MASK = 0x18000000, + + GFXS0_POLYMODE_LINE = 0x80000000, + + GFXS1_DEPTHWRITE = 0x1, + + GFXS1_DEPTHTEST_DISABLE = 0x2, + GFXS1_DEPTHTEST_SHIFT = 0x2, + GFXS1_DEPTHTEST_ALWAYS = 0x0, + GFXS1_DEPTHTEST_LESS = 0x4, + GFXS1_DEPTHTEST_EQUAL = 0x8, + GFXS1_DEPTHTEST_LESSEQUAL = 0xC, + GFXS1_DEPTHTEST_MASK = 0xC, + + GFXS1_POLYGON_OFFSET_SHIFT = 0x4, + GFXS1_POLYGON_OFFSET_0 = 0x0, + GFXS1_POLYGON_OFFSET_1 = 0x10, + GFXS1_POLYGON_OFFSET_2 = 0x20, + GFXS1_POLYGON_OFFSET_SHADOWMAP = 0x30, + GFXS1_POLYGON_OFFSET_MASK = 0x30, + + GFXS1_STENCIL_FRONT_ENABLE = 0x40, + GFXS1_STENCIL_BACK_ENABLE = 0x80, + GFXS1_STENCIL_MASK = 0xC0, + + GFXS1_STENCIL_FRONT_PASS_SHIFT = 0x8, + GFXS1_STENCIL_FRONT_FAIL_SHIFT = 0xB, + GFXS1_STENCIL_FRONT_ZFAIL_SHIFT = 0xE, + GFXS1_STENCIL_FRONT_FUNC_SHIFT = 0x11, + GFXS1_STENCIL_FRONT_MASK = 0xFFF00, + + GFXS1_STENCIL_BACK_PASS_SHIFT = 0x14, + GFXS1_STENCIL_BACK_FAIL_SHIFT = 0x17, + GFXS1_STENCIL_BACK_ZFAIL_SHIFT = 0x1A, + GFXS1_STENCIL_BACK_FUNC_SHIFT = 0x1D, + GFXS1_STENCIL_BACK_MASK = 0xFFF00000, + + GFXS1_STENCILFUNC_FRONTBACK_MASK = 0xE00E0000, + GFXS1_STENCILOP_FRONTBACK_MASK = 0x1FF1FF00, +}; + +struct GfxStateBits { + unsigned int loadBits[2]; +}; + +struct type_align(16) MaterialConstantDef { + unsigned int nameHash; + char name[12]; + float literal[4]; +}; + +struct complex_s { + float real; + float imag; +}; + +struct WaterWritable { + float floatTime; +}; + +struct water_t { + WaterWritable writable; + complex_s *H0; + float *wTerm; + int M; + int N; + float Lx; + float Lz; + float gravity; + float windvel; + float winddir[2]; + float amplitude; + float codeConstant[4]; + GfxImage *image; +}; + +union MaterialTextureDefInfo { + GfxImage *image; + water_t *water; +}; + +enum SamplerStateBits_e { + SAMPLER_FILTER_SHIFT = 0x0, + SAMPLER_FILTER_NEAREST = 0x1, + SAMPLER_FILTER_LINEAR = 0x2, + SAMPLER_FILTER_ANISO2X = 0x3, + SAMPLER_FILTER_ANISO4X = 0x4, + SAMPLER_FILTER_MASK = 0x7, + + SAMPLER_MIPMAP_SHIFT = 0x3, + SAMPLER_MIPMAP_DISABLED = 0x0, + SAMPLER_MIPMAP_NEAREST = 0x8, + SAMPLER_MIPMAP_LINEAR = 0x10, + SAMPLER_MIPMAP_COUNT = 0x3, + SAMPLER_MIPMAP_MASK = 0x18, + + SAMPLER_CLAMP_U_SHIFT = 0x5, + SAMPLER_CLAMP_V_SHIFT = 0x6, + SAMPLER_CLAMP_W_SHIFT = 0x7, + SAMPLER_CLAMP_U = 0x20, + SAMPLER_CLAMP_V = 0x40, + SAMPLER_CLAMP_W = 0x80, + SAMPLER_CLAMP_MASK = 0xE0, +}; + +struct MaterialTextureDef { + unsigned int nameHash; + char nameStart; + char nameEnd; + unsigned char samplerState; // SamplerStateBits_e + unsigned char semantic; // TextureSemantic + MaterialTextureDefInfo u; +}; + +struct gcc_align(8) GfxDrawSurfFields { + uint64_t objectId : 16; + uint64_t reflectionProbeIndex : 8; + uint64_t customIndex : 5; + uint64_t materialSortedIndex : 11; + uint64_t prepass : 2; + uint64_t primaryLightIndex : 8; + uint64_t surfType : 4; + uint64_t primarySortKey : 6; + uint64_t unused : 4; +}; + +union GfxDrawSurf { + gcc_align(8) GfxDrawSurfFields fields; + gcc_align(8) uint64_t packed; +}; + +enum materialSurfType_t { + SURF_TYPE_DEFAULT, + SURF_TYPE_BARK, + SURF_TYPE_BRICK, + SURF_TYPE_CARPET, + SURF_TYPE_CLOTH, + SURF_TYPE_CONCRETE, + SURF_TYPE_DIRT, + SURF_TYPE_FLESH, + SURF_TYPE_FOLIAGE, + SURF_TYPE_GLASS, + SURF_TYPE_GRASS, + SURF_TYPE_GRAVEL, + SURF_TYPE_ICE, + SURF_TYPE_METAL, + SURF_TYPE_MUD, + SURF_TYPE_PAPER, + SURF_TYPE_PLASTER, + SURF_TYPE_ROCK, + SURF_TYPE_SAND, + SURF_TYPE_SNOW, + SURF_TYPE_WATER, + SURF_TYPE_WOOD, + SURF_TYPE_ASPHALT, + SURF_TYPE_CERAMIC, + SURF_TYPE_PLASTIC, + SURF_TYPE_RUBBER, + SURF_TYPE_CUSHION, + SURF_TYPE_FRUIT, + SURF_TYPE_PAINTED_METAL, + + SURF_TYPE_NUM +}; + +struct MaterialInfo { + const char *name; + unsigned char gameFlags; + unsigned char sortKey; + unsigned char textureAtlasRowCount; + unsigned char textureAtlasColumnCount; + GfxDrawSurf drawSurf; + unsigned int surfaceTypeBits; + uint16_t hashIndex; +}; + +enum GfxCameraRegionType { + CAMERA_REGION_LIT = 0x0, + CAMERA_REGION_DECAL = 0x1, + CAMERA_REGION_EMISSIVE = 0x2, + CAMERA_REGION_COUNT = 0x3, + CAMERA_REGION_NONE = 0x3, +}; + +enum MaterialStateFlags { + STATE_FLAG_CULL_BACK = 0x1, + STATE_FLAG_CULL_FRONT = 0x2, + STATE_FLAG_DECAL = 0x4, + STATE_FLAG_WRITES_DEPTH = 0x8, + STATE_FLAG_USES_DEPTH_BUFFER = 0x10, + STATE_FLAG_USES_STENCIL_BUFFER = 0x20, + STATE_FLAG_CULL_BACK_SHADOW = 0x40, + STATE_FLAG_CULL_FRONT_SHADOW = 0x80, +}; + +struct Material { + MaterialInfo info; + char stateBitsEntry[34]; + unsigned char textureCount; + unsigned char constantCount; + unsigned char stateBitsCount; + unsigned char stateFlags; + unsigned char cameraRegion; + MaterialTechniqueSet *techniqueSet; + MaterialTextureDef *textureTable; + MaterialConstantDef *constantTable; + GfxStateBits *stateBitsTable; +}; + +struct MaterialArgumentCodeConst { + uint16_t index; + char firstRow; + char rowCount; +}; + +union MaterialArgumentDef { + const float (*literalConst)[4]; + MaterialArgumentCodeConst codeConst; + unsigned int codeSampler; + unsigned int nameHash; +}; + +enum MaterialShaderArgumentType { + MTL_ARG_MATERIAL_VERTEX_CONST = 0x0, + MTL_ARG_LITERAL_VERTEX_CONST = 0x1, + MTL_ARG_MATERIAL_PIXEL_SAMPLER = 0x2, + + MTL_ARG_CODE_PRIM_BEGIN = 0x3, + + MTL_ARG_CODE_VERTEX_CONST = 0x3, + MTL_ARG_CODE_PIXEL_SAMPLER = 0x4, + MTL_ARG_CODE_PIXEL_CONST = 0x5, + + MTL_ARG_CODE_PRIM_END = 0x6, + + MTL_ARG_MATERIAL_PIXEL_CONST = 0x6, + MTL_ARG_LITERAL_PIXEL_CONST = 0x7, + + MLT_ARG_COUNT +}; + +enum MaterialConstantSource { + CONST_SRC_CODE_MAYBE_DIRTY_PS_BEGIN = 0x0, + CONST_SRC_CODE_LIGHT_POSITION = 0x0, + CONST_SRC_CODE_LIGHT_DIFFUSE = 0x1, + CONST_SRC_CODE_LIGHT_SPOTDIR = 0x2, + CONST_SRC_CODE_LIGHT_SPOTFACTORS = 0x3, + CONST_SRC_CODE_LIGHT_ATTENUATION = 0x4, + CONST_SRC_CODE_LIGHT_FALLOFF_A = 0x5, + CONST_SRC_CODE_LIGHT_FALLOFF_B = 0x6, + CONST_SRC_CODE_LIGHT_SPOT_MATRIX0 = 0x7, + CONST_SRC_CODE_LIGHT_SPOT_MATRIX1 = 0x8, + CONST_SRC_CODE_LIGHT_SPOT_MATRIX2 = 0x9, + CONST_SRC_CODE_LIGHT_SPOT_MATRIX3 = 0xA, + CONST_SRC_CODE_LIGHT_SPOT_AABB = 0xB, + CONST_SRC_CODE_LIGHT_CONE_CONTROL1 = 0xC, + CONST_SRC_CODE_LIGHT_CONE_CONTROL2 = 0xD, + CONST_SRC_CODE_LIGHT_SPOT_COOKIE_SLIDE_CONTROL = 0xE, + CONST_SRC_CODE_SHADOW_PARMS = 0xF, + CONST_SRC_CODE_SHADOWMAP_POLYGON_OFFSET = 0x10, + CONST_SRC_CODE_RENDER_TARGET_SIZE = 0x11, + CONST_SRC_CODE_UPSCALED_TARGET_SIZE = 0x12, + CONST_SRC_CODE_DOF_EQUATION_VIEWMODEL_AND_FAR_BLUR = 0x13, + CONST_SRC_CODE_DOF_EQUATION_SCENE = 0x14, + CONST_SRC_CODE_DOF_LERP_SCALE = 0x15, + CONST_SRC_CODE_DOF_LERP_BIAS = 0x16, + CONST_SRC_CODE_DOF_ROW_DELTA = 0x17, + CONST_SRC_CODE_PARTICLE_CLOUD_COLOR = 0x18, + CONST_SRC_CODE_GAMETIME = 0x19, + CONST_SRC_CODE_MAYBE_DIRTY_PS_END = 0x1A, + CONST_SRC_CODE_ALWAYS_DIRTY_PS_BEGIN = 0x1A, + CONST_SRC_CODE_FILTER_TAP_0 = 0x1A, + CONST_SRC_CODE_FILTER_TAP_1 = 0x1B, + CONST_SRC_CODE_FILTER_TAP_2 = 0x1C, + CONST_SRC_CODE_FILTER_TAP_3 = 0x1D, + CONST_SRC_CODE_FILTER_TAP_4 = 0x1E, + CONST_SRC_CODE_FILTER_TAP_5 = 0x1F, + CONST_SRC_CODE_FILTER_TAP_6 = 0x20, + CONST_SRC_CODE_FILTER_TAP_7 = 0x21, + CONST_SRC_CODE_COLOR_MATRIX_R = 0x22, + CONST_SRC_CODE_COLOR_MATRIX_G = 0x23, + CONST_SRC_CODE_COLOR_MATRIX_B = 0x24, + CONST_SRC_CODE_ALWAYS_DIRTY_PS_END = 0x25, + CONST_SRC_CODE_NEVER_DIRTY_PS_BEGIN = 0x25, + CONST_SRC_CODE_SHADOWMAP_SWITCH_PARTITION = 0x25, + CONST_SRC_CODE_SUNSHADOWMAP_PIXEL_SIZE = 0x26, + CONST_SRC_CODE_SHADOWMAP_SCALE = 0x27, + CONST_SRC_CODE_ZNEAR = 0x28, + CONST_SRC_CODE_SUN_POSITION = 0x29, + CONST_SRC_CODE_SUN_DIFFUSE = 0x2A, + CONST_SRC_CODE_LIGHTING_LOOKUP_SCALE = 0x2B, + CONST_SRC_CODE_DEBUG_BUMPMAP = 0x2C, + CONST_SRC_CODE_DEBUG_PERFORMANCE = 0x2D, + CONST_SRC_CODE_MATERIAL_COLOR = 0x2E, + CONST_SRC_CODE_FOG = 0x2F, + CONST_SRC_CODE_FOG2 = 0x30, + CONST_SRC_CODE_FOG_COLOR = 0x31, + CONST_SRC_CODE_SUN_FOG = 0x32, + CONST_SRC_CODE_SUN_FOG_DIR = 0x33, + CONST_SRC_CODE_SUN_FOG_COLOR = 0x34, + CONST_SRC_CODE_GLOW_SETUP = 0x35, + CONST_SRC_CODE_GLOW_APPLY = 0x36, + CONST_SRC_CODE_COLOR_BIAS = 0x37, + CONST_SRC_CODE_COLOR_TINT_BASE = 0x38, + CONST_SRC_CODE_COLOR_TINT_DELTA = 0x39, + CONST_SRC_CODE_OUTDOOR_FEATHER_PARMS = 0x3A, + CONST_SRC_CODE_SKY_TRANSITION = 0x3B, + CONST_SRC_CODE_SPOT_SHADOWMAP_PIXEL_ADJUST = 0x3C, + CONST_SRC_CODE_DLIGHT_SPOT_SHADOWMAP_PIXEL_ADJUST = 0x3D, + CONST_SRC_CODE_CLIP_SPACE_LOOKUP_SCALE = 0x3E, + CONST_SRC_CODE_CLIP_SPACE_LOOKUP_OFFSET = 0x3F, + CONST_SRC_CODE_PARTICLE_CLOUD_MATRIX = 0x40, + CONST_SRC_CODE_PARTICLE_CLOUD_VEL_WORLD = 0x41, + CONST_SRC_CODE_DEPTH_FROM_CLIP = 0x42, + CONST_SRC_CODE_CODE_MESH_ARG_0 = 0x43, + CONST_SRC_CODE_CODE_MESH_ARG_1 = 0x44, + CONST_SRC_CODE_CODE_MESH_ARG_LAST = 0x44, + CONST_SRC_CODE_GRID_LIGHTING_COORDS_AND_VIS = 0x45, + CONST_SRC_CODE_GRID_LIGHTING_SH_0 = 0x46, + CONST_SRC_CODE_GRID_LIGHTING_SH_1 = 0x47, + CONST_SRC_CODE_GRID_LIGHTING_SH_2 = 0x48, + CONST_SRC_CODE_REFLECTION_LIGHTING_SH_0 = 0x49, + CONST_SRC_CODE_REFLECTION_LIGHTING_SH_1 = 0x4A, + CONST_SRC_CODE_REFLECTION_LIGHTING_SH_2 = 0x4B, + CONST_SRC_CODE_WIND_DIRECTION = 0x4C, + CONST_SRC_CODE_MOTIONBLUR_DIRECTION_AND_MAGNITUDE = 0x4D, + CONST_SRC_CODE_COMPOSITE_FX_DISTORTION = 0x4E, + CONST_SRC_CODE_GLOW_BLOOM_SCALE = 0x4F, + CONST_SRC_CODE_COMPOSITE_FX_OVERLAY_TEXCOORD = 0x50, + CONST_SRC_CODE_COLOR_BIAS1 = 0x51, + CONST_SRC_CODE_COLOR_TINT_BASE1 = 0x52, + CONST_SRC_CODE_COLOR_TINT_DELTA1 = 0x53, + CONST_SRC_CODE_POSTFX_FADE_EFFECT = 0x54, + CONST_SRC_CODE_VIEWPORT_DIMENSIONS = 0x55, + CONST_SRC_CODE_FRAMEBUFFER_READ = 0x56, + CONST_SRC_CODE_RESIZE_PARAMS1 = 0x57, + CONST_SRC_CODE_RESIZE_PARAMS2 = 0x58, + CONST_SRC_CODE_RESIZE_PARAMS3 = 0x59, + CONST_SRC_CODE_VARIANT_WIND_SPRING_0 = 0x5A, + CONST_SRC_CODE_VARIANT_WIND_SPRING_1 = 0x5B, + CONST_SRC_CODE_VARIANT_WIND_SPRING_2 = 0x5C, + CONST_SRC_CODE_VARIANT_WIND_SPRING_3 = 0x5D, + CONST_SRC_CODE_VARIANT_WIND_SPRING_4 = 0x5E, + CONST_SRC_CODE_VARIANT_WIND_SPRING_5 = 0x5F, + CONST_SRC_CODE_VARIANT_WIND_SPRING_6 = 0x60, + CONST_SRC_CODE_VARIANT_WIND_SPRING_7 = 0x61, + CONST_SRC_CODE_VARIANT_WIND_SPRING_8 = 0x62, + CONST_SRC_CODE_VARIANT_WIND_SPRING_9 = 0x63, + CONST_SRC_CODE_VARIANT_WIND_SPRING_10 = 0x64, + CONST_SRC_CODE_VARIANT_WIND_SPRING_11 = 0x65, + CONST_SRC_CODE_VARIANT_WIND_SPRING_12 = 0x66, + CONST_SRC_CODE_VARIANT_WIND_SPRING_13 = 0x67, + CONST_SRC_CODE_VARIANT_WIND_SPRING_14 = 0x68, + CONST_SRC_CODE_VARIANT_WIND_SPRING_15 = 0x69, + CONST_SRC_CODE_CHARACTER_CHARRED_AMOUNT = 0x6A, + CONST_SRC_CODE_POSTFX_CONTROL0 = 0x6B, + CONST_SRC_CODE_POSTFX_CONTROL1 = 0x6C, + CONST_SRC_CODE_POSTFX_CONTROL2 = 0x6D, + CONST_SRC_CODE_POSTFX_CONTROL3 = 0x6E, + CONST_SRC_CODE_POSTFX_CONTROL4 = 0x6F, + CONST_SRC_CODE_POSTFX_CONTROL5 = 0x70, + CONST_SRC_CODE_POSTFX_CONTROL6 = 0x71, + CONST_SRC_CODE_POSTFX_CONTROL7 = 0x72, + CONST_SRC_CODE_POSTFX_CONTROL8 = 0x73, + CONST_SRC_CODE_POSTFX_CONTROL9 = 0x74, + CONST_SRC_CODE_POSTFX_CONTROLA = 0x75, + CONST_SRC_CODE_POSTFX_CONTROLB = 0x76, + CONST_SRC_CODE_POSTFX_CONTROLC = 0x77, + CONST_SRC_CODE_POSTFX_CONTROLD = 0x78, + CONST_SRC_CODE_POSTFX_CONTROLE = 0x79, + CONST_SRC_CODE_POSTFX_CONTROLF = 0x7A, + CONST_SRC_CODE_HDRCONTROL_0 = 0x7B, + CONST_SRC_CODE_HDRCONTROL_1 = 0x7C, + CONST_SRC_CODE_GLIGHT_POSXS = 0x7D, + CONST_SRC_CODE_GLIGHT_POSYS = 0x7E, + CONST_SRC_CODE_GLIGHT_POSZS = 0x7F, + CONST_SRC_CODE_GLIGHT_FALLOFFS = 0x80, + CONST_SRC_CODE_GLIGHT_REDS = 0x81, + CONST_SRC_CODE_GLIGHT_GREENS = 0x82, + CONST_SRC_CODE_GLIGHT_BLUES = 0x83, + CONST_SRC_CODE_DLIGHT_POSITION = 0x84, + CONST_SRC_CODE_DLIGHT_DIFFUSE = 0x85, + CONST_SRC_CODE_DLIGHT_ATTENUATION = 0x86, + CONST_SRC_CODE_DLIGHT_FALLOFF = 0x87, + CONST_SRC_CODE_DLIGHT_SPOT_MATRIX_0 = 0x88, + CONST_SRC_CODE_DLIGHT_SPOT_MATRIX_1 = 0x89, + CONST_SRC_CODE_DLIGHT_SPOT_MATRIX_2 = 0x8A, + CONST_SRC_CODE_DLIGHT_SPOT_MATRIX_3 = 0x8B, + CONST_SRC_CODE_DLIGHT_SPOT_DIR = 0x8C, + CONST_SRC_CODE_DLIGHT_SPOT_FACTORS = 0x8D, + CONST_SRC_CODE_DLIGHT_SHADOW_LOOKUP_MATRIX_0 = 0x8E, + CONST_SRC_CODE_DLIGHT_SHADOW_LOOKUP_MATRIX_1 = 0x8F, + CONST_SRC_CODE_DLIGHT_SHADOW_LOOKUP_MATRIX_2 = 0x90, + CONST_SRC_CODE_DLIGHT_SHADOW_LOOKUP_MATRIX_3 = 0x91, + CONST_SRC_CODE_CLOUD_LAYER_CONTROL0 = 0x92, + CONST_SRC_CODE_CLOUD_LAYER_CONTROL1 = 0x93, + CONST_SRC_CODE_CLOUD_LAYER_CONTROL2 = 0x94, + CONST_SRC_CODE_CLOUD_LAYER_CONTROL3 = 0x95, + CONST_SRC_CODE_CLOUD_LAYER_CONTROL4 = 0x96, + CONST_SRC_CODE_HERO_LIGHTING_R = 0x97, + CONST_SRC_CODE_HERO_LIGHTING_G = 0x98, + CONST_SRC_CODE_HERO_LIGHTING_B = 0x99, + CONST_SRC_CODE_LIGHT_HERO_SCALE = 0x9A, + CONST_SRC_CODE_CINEMATIC_BLUR_BOX = 0x9B, + CONST_SRC_CODE_CINEMATIC_BLUR_BOX2 = 0x9C, + CONST_SRC_CODE_ADSZSCALE = 0x9D, + CONST_SRC_CODE_UI3D_UV_SETUP_0 = 0x9E, + CONST_SRC_CODE_UI3D_UV_SETUP_1 = 0x9F, + CONST_SRC_CODE_UI3D_UV_SETUP_2 = 0xA0, + CONST_SRC_CODE_UI3D_UV_SETUP_3 = 0xA1, + CONST_SRC_CODE_UI3D_UV_SETUP_4 = 0xA2, + CONST_SRC_CODE_UI3D_UV_SETUP_5 = 0xA3, + CONST_SRC_CODE_CHARACTER_DISSOLVE_COLOR = 0xA4, + CONST_SRC_CODE_CAMERA_LOOK = 0xA5, + CONST_SRC_CODE_CAMERA_UP = 0xA6, + CONST_SRC_CODE_CAMERA_SIDE = 0xA7, + CONST_SRC_CODE_RIMINTENSITY = 0xA8, + CONST_SRC_CODE_GENERIC_PARAM0 = 0xA9, + CONST_SRC_CODE_GENERIC_PARAM1 = 0xAA, + CONST_SRC_CODE_GENERIC_PARAM2 = 0xAB, + CONST_SRC_CODE_GENERIC_PARAM3 = 0xAC, + CONST_SRC_CODE_GENERIC_PARAM4 = 0xAD, + CONST_SRC_CODE_GENERIC_PARAM5 = 0xAE, + CONST_SRC_CODE_GENERIC_PARAM6 = 0xAF, + CONST_SRC_CODE_GENERIC_PARAM7 = 0xB0, + CONST_SRC_CODE_GENERIC_EYEOFFSET = 0xB1, + CONST_SRC_CODE_GENERIC_QUADINTENSITY = 0xB2, + CONST_SRC_CODE_WEAPON_PARAM0 = 0xB3, + CONST_SRC_CODE_WEAPON_PARAM1 = 0xB4, + CONST_SRC_CODE_WEAPON_PARAM2 = 0xB5, + CONST_SRC_CODE_WEAPON_PARAM3 = 0xB6, + CONST_SRC_CODE_WEAPON_PARAM4 = 0xB7, + CONST_SRC_CODE_WEAPON_PARAM5 = 0xB8, + CONST_SRC_CODE_WEAPON_PARAM6 = 0xB9, + CONST_SRC_CODE_WEAPON_PARAM7 = 0xBA, + CONST_SRC_CODE_WEAPON_PARAM8 = 0xBB, + CONST_SRC_CODE_WEAPON_PARAM9 = 0xBC, + CONST_SRC_CODE_QRCODE_0 = 0xBD, + CONST_SRC_CODE_QRCODE_1 = 0xBE, + CONST_SRC_CODE_QRCODE_2 = 0xBF, + CONST_SRC_CODE_QRCODE_3 = 0xC0, + CONST_SRC_CODE_QRCODE_4 = 0xC1, + CONST_SRC_CODE_QRCODE_5 = 0xC2, + CONST_SRC_CODE_QRCODE_6 = 0xC3, + CONST_SRC_CODE_QRCODE_7 = 0xC4, + CONST_SRC_CODE_QRCODE_8 = 0xC5, + CONST_SRC_CODE_QRCODE_9 = 0xC6, + CONST_SRC_CODE_QRCODE_10 = 0xC7, + CONST_SRC_CODE_QRCODE_11 = 0xC8, + CONST_SRC_CODE_EYEOFFSET = 0xC9, + CONST_SRC_CODE_SKY_COLOR_MULTIPLIER = 0xCA, + CONST_SRC_CODE_EXTRA_CAM_PARAM = 0xCB, + CONST_SRC_CODE_EMBLEM_LUT_SELECTOR = 0xCC, + CONST_SRC_CODE_DEBUG_COLOR_OVERRIDE = 0xCD, + CONST_SRC_CODE_DEBUG_ALPHA_OVERRIDE = 0xCE, + CONST_SRC_CODE_DEBUG_NORMAL_OVERRIDE = 0xCF, + CONST_SRC_CODE_DEBUG_SPECULAR_OVERRIDE = 0xD0, + CONST_SRC_CODE_DEBUG_GLOSS_OVERRIDE = 0xD1, + CONST_SRC_CODE_DEBUG_OCCLUSION_OVERRIDE = 0xD2, + CONST_SRC_CODE_NEVER_DIRTY_PS_END = 0xD3, + CONST_SRC_CODE_COUNT_FLOAT4 = 0xD3, + CONST_SRC_FIRST_CODE_MATRIX = 0xD3, + CONST_SRC_CODE_WORLD_MATRIX = 0xD3, + CONST_SRC_CODE_INVERSE_WORLD_MATRIX = 0xD4, + CONST_SRC_CODE_TRANSPOSE_WORLD_MATRIX = 0xD5, + CONST_SRC_CODE_INVERSE_TRANSPOSE_WORLD_MATRIX = 0xD6, + CONST_SRC_CODE_VIEW_MATRIX = 0xD7, + CONST_SRC_CODE_INVERSE_VIEW_MATRIX = 0xD8, + CONST_SRC_CODE_TRANSPOSE_VIEW_MATRIX = 0xD9, + CONST_SRC_CODE_INVERSE_TRANSPOSE_VIEW_MATRIX = 0xDA, + CONST_SRC_CODE_PROJECTION_MATRIX = 0xDB, + CONST_SRC_CODE_INVERSE_PROJECTION_MATRIX = 0xDC, + CONST_SRC_CODE_TRANSPOSE_PROJECTION_MATRIX = 0xDD, + CONST_SRC_CODE_INVERSE_TRANSPOSE_PROJECTION_MATRIX = 0xDE, + CONST_SRC_CODE_WORLD_VIEW_MATRIX = 0xDF, + CONST_SRC_CODE_INVERSE_WORLD_VIEW_MATRIX = 0xE0, + CONST_SRC_CODE_TRANSPOSE_WORLD_VIEW_MATRIX = 0xE1, + CONST_SRC_CODE_INVERSE_TRANSPOSE_WORLD_VIEW_MATRIX = 0xE2, + CONST_SRC_CODE_VIEW_PROJECTION_MATRIX = 0xE3, + CONST_SRC_CODE_INVERSE_VIEW_PROJECTION_MATRIX = 0xE4, + CONST_SRC_CODE_TRANSPOSE_VIEW_PROJECTION_MATRIX = 0xE5, + CONST_SRC_CODE_INVERSE_TRANSPOSE_VIEW_PROJECTION_MATRIX = 0xE6, + CONST_SRC_CODE_WORLD_VIEW_PROJECTION_MATRIX = 0xE7, + CONST_SRC_CODE_INVERSE_WORLD_VIEW_PROJECTION_MATRIX = 0xE8, + CONST_SRC_CODE_TRANSPOSE_WORLD_VIEW_PROJECTION_MATRIX = 0xE9, + CONST_SRC_CODE_INVERSE_TRANSPOSE_WORLD_VIEW_PROJECTION_MATRIX = 0xEA, + CONST_SRC_CODE_SHADOW_LOOKUP_MATRIX = 0xEB, + CONST_SRC_CODE_INVERSE_SHADOW_LOOKUP_MATRIX = 0xEC, + CONST_SRC_CODE_TRANSPOSE_SHADOW_LOOKUP_MATRIX = 0xED, + CONST_SRC_CODE_INVERSE_TRANSPOSE_SHADOW_LOOKUP_MATRIX = 0xEE, + CONST_SRC_CODE_WORLD_OUTDOOR_LOOKUP_MATRIX = 0xEF, + CONST_SRC_CODE_INVERSE_WORLD_OUTDOOR_LOOKUP_MATRIX = 0xF0, + CONST_SRC_CODE_TRANSPOSE_WORLD_OUTDOOR_LOOKUP_MATRIX = 0xF1, + CONST_SRC_CODE_INVERSE_TRANSPOSE_WORLD_OUTDOOR_LOOKUP_MATRIX = 0xF2, + CONST_SRC_TOTAL_COUNT = 0xF3, + CONST_SRC_NONE = 0xF4, +}; + +struct MaterialShaderArgument { + uint16_t type; + uint16_t dest; + MaterialArgumentDef u; +}; + +enum MaterialStreamStreamSource_e { + STREAM_SRC_POSITION = 0x0, + STREAM_SRC_COLOR = 0x1, + STREAM_SRC_TEXCOORD_0 = 0x2, + STREAM_SRC_NORMAL = 0x3, + STREAM_SRC_TANGENT = 0x4, + + STREAM_SRC_OPTIONAL_BEGIN = 0x5, + STREAM_SRC_PRE_OPTIONAL_BEGIN = 0x4, + + STREAM_SRC_TEXCOORD_1 = 0x5, + STREAM_SRC_TEXCOORD_2 = 0x6, + STREAM_SRC_NORMAL_TRANSFORM_0 = 0x7, + STREAM_SRC_NORMAL_TRANSFORM_1 = 0x8, + + STREAM_SRC_COUNT +}; + +enum MaterialStreamDestination_e { + STREAM_DST_POSITION = 0x0, + STREAM_DST_NORMAL = 0x1, + STREAM_DST_COLOR_0 = 0x2, + STREAM_DST_COLOR_1 = 0x3, + STREAM_DST_TEXCOORD_0 = 0x4, + STREAM_DST_TEXCOORD_1 = 0x5, + STREAM_DST_TEXCOORD_2 = 0x6, + STREAM_DST_TEXCOORD_3 = 0x7, + STREAM_DST_TEXCOORD_4 = 0x8, + STREAM_DST_TEXCOORD_5 = 0x9, + STREAM_DST_TEXCOORD_6 = 0xA, + STREAM_DST_TEXCOORD_7 = 0xB, + STREAM_DST_COUNT +}; + +struct MaterialStreamRouting { + unsigned char source; + unsigned char dest; +}; + +struct MaterialVertexStreamRouting { + MaterialStreamRouting data[16]; + void /*IDirect3DVertexDeclaration9*/ *decl[16]; +}; + +struct MaterialVertexDeclaration { + char streamCount; + bool hasOptionalSource; + bool isLoaded; + MaterialVertexStreamRouting routing; +}; + +struct GfxVertexShaderLoadDef { + unsigned int *program; + uint16_t programSize; + uint16_t loadForRenderer; +}; + +struct MaterialVertexShaderProgram { + void /*IDirect3DVertexShader9*/ *vs; + GfxVertexShaderLoadDef loadDef; +}; + +struct MaterialVertexShader { + const char *name; + MaterialVertexShaderProgram prog; +}; + +struct GfxPixelShaderLoadDef { + unsigned int *program; + uint16_t programSize; + uint16_t loadForRenderer; +}; + +struct MaterialPixelShaderProgram { + void /*IDirect3DPixelShader9*/ *ps; + GfxPixelShaderLoadDef loadDef; +}; + +struct MaterialPixelShader { + const char *name; + MaterialPixelShaderProgram prog; +}; + +struct MaterialPass { + MaterialVertexDeclaration *vertexDecl; + MaterialVertexShader *vertexShader; + MaterialPixelShader *pixelShader; + char perPrimArgCount; + char perObjArgCount; + char stableArgCount; + char customSamplerFlags; + MaterialShaderArgument *args; +}; + +struct MaterialTechnique { + const char *name; + uint16_t flags; + uint16_t passCount; + MaterialPass passArray[1]; +}; + +enum MaterialTechniqueType { + TECHNIQUE_DEPTH_PREPASS = 0x0, + TECHNIQUE_BUILD_FLOAT_Z = 0x1, + TECHNIQUE_BUILD_SHADOWMAP_DEPTH = 0x2, + TECHNIQUE_BUILD_SHADOWMAP_COLOR = 0x3, + TECHNIQUE_UNLIT = 0x4, + TECHNIQUE_EMISSIVE = 0x5, + TECHNIQUE_EMISSIVE_SHADOW = 0x6, + + TECHNIQUE_LIT_BEGIN = 0x7, + + TECHNIQUE_LIT = 0x7, + TECHNIQUE_LIT_SUN = 0x8, + TECHNIQUE_LIT_SUN_SHADOW = 0x9, + TECHNIQUE_LIT_SPOT = 0xA, + TECHNIQUE_LIT_SPOT_SHADOW = 0xB, + TECHNIQUE_LIT_OMNI = 0xC, + TECHNIQUE_LIT_OMNI_SHADOW = 0xD, + TECHNIQUE_LIT_INSTANCED = 0xE, + TECHNIQUE_LIT_INSTANCED_SUN = 0xF, + TECHNIQUE_LIT_INSTANCED_SUN_SHADOW = 0x10, + TECHNIQUE_LIT_INSTANCED_SPOT = 0x11, + TECHNIQUE_LIT_INSTANCED_SPOT_SHADOW = 0x12, + TECHNIQUE_LIT_INSTANCED_OMNI = 0x13, + TECHNIQUE_LIT_INSTANCED_OMNI_SHADOW = 0x14, + + TECHNIQUE_LIT_END = 0x15, + + TECHNIQUE_LIGHT_SPOT = 0x15, + TECHNIQUE_LIGHT_OMNI = 0x16, + TECHNIQUE_LIGHT_SPOT_SHADOW = 0x17, + TECHNIQUE_FAKELIGHT_NORMAL = 0x18, + TECHNIQUE_FAKELIGHT_VIEW = 0x19, + TECHNIQUE_SUNLIGHT_PREVIEW = 0x1A, + TECHNIQUE_CASE_TEXTURE = 0x1B, + TECHNIQUE_WIREFRAME_SOLID = 0x1C, + TECHNIQUE_WIREFRAME_SHADED = 0x1D, + TECHNIQUE_SHADOWCOOKIE_CASTER = 0x1E, + TECHNIQUE_SHADOWCOOKIE_RECEIVER = 0x1F, + TECHNIQUE_DEBUG_BUMPMAP = 0x20, + TECHNIQUE_DEBUG_BUMPMAP_INSTANCED = 0x21, + TECHNIQUE_COUNT = 0x22, + TECHNIQUE_TOTAL_COUNT = 0x23, + TECHNIQUE_NONE = 0x24, +}; + +struct MaterialTechniqueSet { + const char *name; + char worldVertFormat; + bool hasBeenUploaded; + char unused[1]; + MaterialTechniqueSet *remappedTechniqueSet; + MaterialTechnique *techniques[34]; +}; + +struct CardMemory { + int platform[2]; +}; + +struct Picmip { + char platform[2]; +}; + +struct GfxImageLoadDef { + char levelCount; + char flags; + int16_t dimensions[3]; + int format; + int resourceSize; + char data[1]; +}; + +union GfxTexture { + // void/*IDirect3DBaseTexture9*/* basemap; + // void/*IDirect3DTexture9*/* map; + // void/*IDirect3DVolumeTexture9*/* volmap; + // void/*IDirect3DCubeTexture9*/* cubemap; + Texture *texture; + GfxImageLoadDef *loadDef; +}; + +enum MapType { + MAPTYPE_NONE = 0x0, + MAPTYPE_INVALID1 = 0x1, + MAPTYPE_INVALID2 = 0x2, + MAPTYPE_2D = 0x3, + MAPTYPE_3D = 0x4, + MAPTYPE_CUBE = 0x5, + MAPTYPE_COUNT = 0x6, +}; + +enum TextureSemantic { + TS_2D = 0x0, + TS_FUNCTION = 0x1, + TS_COLOR_MAP = 0x2, + TS_UNUSED_1 = 0x3, + TS_UNUSED_2 = 0x4, + TS_NORMAL_MAP = 0x5, + TS_UNUSED_3 = 0x6, + TS_UNUSED_4 = 0x7, + TS_SPECULAR_MAP = 0x8, + TS_UNUSED_5 = 0x9, + TS_UNUSED_6 = 0xA, + TS_WATER_MAP = 0xB, +}; + +enum ImageCategory { + IMG_CATEGORY_UNKNOWN = 0x0, + IMG_CATEGORY_AUTO_GENERATED = 0x1, + IMG_CATEGORY_LIGHTMAP = 0x2, + IMG_CATEGORY_LOAD_FROM_FILE = 0x3, + IMG_CATEGORY_RAW = 0x4, + IMG_CATEGORY_FIRST_UNMANAGED = 0x5, + IMG_CATEGORY_WATER = 0x5, + IMG_CATEGORY_RENDERTARGET = 0x6, + IMG_CATEGORY_TEMP = 0x7, +}; + +struct GfxImage { + MapType mapType; + GfxTexture texture; + Picmip picmip; + bool noPicmip; + char semantic; + char track; + CardMemory cardMemory; + uint16_t width; + uint16_t height; + uint16_t depth; + char category; + bool delayLoadPixels; + const char *name; +}; + +struct SndCurve { + const char *filename; + int knotCount; + float knots[8][2]; +}; + +struct MSSSpeakerLevels { + int speaker; + int numLevels; + float levels[2]; +}; + +struct MSSChannelMap { + int speakerCount; + MSSSpeakerLevels speakers[6]; +}; + +struct SpeakerMap { + bool isDefault; + const char *name; + MSSChannelMap channelMaps[2][2]; +}; + +struct StreamedSound { + const char *dir; + const char *name; +}; + +union SoundFileRef { + LoadedSound *loadSnd; + StreamedSound streamSnd; +}; + +enum snd_alias_type_t { + SAT_UNKNOWN = 0x0, + SAT_LOADED = 0x1, + SAT_STREAMED = 0x2, + SAT_COUNT = 0x3, +}; + +struct SoundFile { + char type; + char exists; + SoundFileRef u; +}; + +struct snd_alias_t { + const char *aliasName; + const char *subtitle; + const char *secondaryAliasName; + const char *chainAliasName; + SoundFile *soundFile; + int sequence; + float volMin; + float volMax; + float pitchMin; + float pitchMax; + float distMin; + float distMax; + int flags; + float slavePercentage; + float probability; + float lfePercentage; + float centerPercentage; + int startDelay; + SndCurve *volumeFalloffCurve; + float envelopMin; + float envelopMax; + float envelopPercentage; + SpeakerMap *speakerMap; +}; + +struct snd_alias_list_t { + const char *aliasName; + snd_alias_t *head; + int count; +}; + +struct AILSOUNDINFO { + int format; + const void *data_ptr; + unsigned int data_len; + unsigned int rate; + int bits; + int channels; + unsigned int samples; + unsigned int block_size; + const void *initial_ptr; +}; + +struct MssSound { + AILSOUNDINFO info; + char *data; +}; + +struct LoadedSound { + const char *name; + MssSound sound; +}; + +struct cStaticModelWritable { + uint16_t nextModelInWorldSector; +}; + +struct cStaticModel_s { + cStaticModelWritable writable; + XModel *xmodel; + float origin[3]; + float invScaledAxis[3][3]; + float absmin[3]; + float absmax[3]; +}; + +struct dmaterial_t { + char material[64]; + int surfaceFlags; + int contentFlags; +}; + +struct cNode_t { + cplane_s *plane; + int16_t children[2]; +}; + +struct cLeaf_t { + uint16_t firstCollAabbIndex; + uint16_t collAabbCount; + int brushContents; + int terrainContents; + float mins[3]; + float maxs[3]; + int leafBrushNode; + int16_t cluster; +}; + +struct cLeafBrushNodeChildren_t { + float dist; + float range; + uint16_t childOffset[2]; +}; + +struct cLeafBrushNodeLeaf_t { + uint16_t *brushes; +}; + +union cLeafBrushNodeData_t { + cLeafBrushNodeLeaf_t leaf; + cLeafBrushNodeChildren_t children; +}; + +struct cLeafBrushNode_s { + char axis; + int16_t leafBrushCount; + int contents; + cLeafBrushNodeData_t data; +}; + +struct CollisionBorder { + float distEq[3]; + float zBase; + float zSlope; + float start; + float length; +}; + +struct CollisionPartition { + unsigned char triCount; + unsigned char borderCount; + int firstTri; + CollisionBorder *borders; +}; + +union CollisionAabbTreeIndex { + int firstChildIndex; + int partitionIndex; +}; + +struct CollisionAabbTree { + float origin[3]; + float halfSize[3]; + uint16_t materialIndex; + uint16_t childCount; + CollisionAabbTreeIndex u; +}; + +struct cmodel_t { + float mins[3]; + float maxs[3]; + float radius; + cLeaf_t leaf; +}; + +struct type_align(16) cbrush_t { + float mins[3]; + int contents; + float maxs[3]; + unsigned int numsides; + cbrushside_t *sides; + int16_t axialMaterialNum[2][3]; + char *baseAdjacentSide; + int16_t firstAdjacentSideOffsets[2][3]; + char edgeCount[2][3]; +}; + +struct GfxPlacement { + float quat[4]; + float origin[3]; +}; + +enum DynEntityType { + DYNENT_TYPE_INVALID = 0x0, + DYNENT_TYPE_CLUTTER = 0x1, + DYNENT_TYPE_DESTRUCT = 0x2, + DYNENT_TYPE_COUNT = 0x3, +}; + +struct DynEntityDef { + DynEntityType type; + GfxPlacement pose; + XModel *xModel; + uint16_t brushModel; + uint16_t physicsBrushModel; + FxEffectDef *destroyFx; + XModelPieces *destroyPieces; + PhysPreset *physPreset; + int health; + PhysMass mass; + int contents; +}; + +struct DynEntityPose { + GfxPlacement pose; + float radius; +}; + +struct DynEntityClient { + int physObjId; + uint16_t flags; + uint16_t lightingHandle; + int health; +}; + +struct DynEntityColl { + uint16_t sector; + uint16_t nextEntInSector; + float linkMins[2]; + float linkMaxs[2]; +}; + +typedef unsigned short LeafBrush; + +typedef tdef_align(16) cbrush_t cbrush_array_t; + +struct clipMap_t { + const char *name; + int isInUse; + int planeCount; + cplane_s *planes; + unsigned int numStaticModels; + cStaticModel_s *staticModelList; + unsigned int numMaterials; + dmaterial_t *materials; + unsigned int numBrushSides; + cbrushside_t *brushsides; + unsigned int numBrushEdges; + cbrushedge_t *brushEdges; + unsigned int numNodes; + cNode_t *nodes; + unsigned int numLeafs; + cLeaf_t *leafs; + unsigned int leafbrushNodesCount; + cLeafBrushNode_s *leafbrushNodes; + unsigned int numLeafBrushes; + LeafBrush *leafbrushes; + unsigned int numLeafSurfaces; + unsigned int *leafsurfaces; + unsigned int vertCount; + vec3_t *verts; + int triCount; + uint16_t *triIndices; + char *triEdgeIsWalkable; + int borderCount; + CollisionBorder *borders; + int partitionCount; + CollisionPartition *partitions; + int aabbTreeCount; + CollisionAabbTree *aabbTrees; + unsigned int numSubModels; + cmodel_t *cmodels; + uint16_t numBrushes; + cbrush_t *brushes; + int numClusters; + int clusterBytes; + char *visibility; + int vised; + MapEnts *mapEnts; + cbrush_t *box_brush; + cmodel_t box_model; + uint16_t dynEntCount[2]; + DynEntityDef *dynEntDefList[2]; + DynEntityPose *dynEntPoseList[2]; + DynEntityClient *dynEntClientList[2]; + DynEntityColl *dynEntCollList[2]; + unsigned int checksum; +}; + +struct ComPrimaryLight { + char type; + char canUseShadowMap; + char exponent; + char unused; + float color[3]; + float dir[3]; + float origin[3]; + float radius; + float cosHalfFovOuter; + float cosHalfFovInner; + float cosHalfFovExpanded; + float rotationLimit; + float translationLimit; + const char *defName; +}; + +struct ComWorld { + const char *name; + int isInUse; + unsigned int primaryLightCount; + ComPrimaryLight *primaryLights; +}; + +struct pathnode_tree_nodes_t { + int nodeCount; + uint16_t *nodes; +}; + +struct pathnode_t; +struct pathnode_tree_t; + +union pathnode_tree_info_t { + pathnode_tree_t *child[2]; + pathnode_tree_nodes_t s; +}; + +struct pathnode_tree_t { + int axis; + float dist; + pathnode_tree_info_t u; +}; + +struct type_align(16) pathbasenode_t { + float vOrigin[3]; + unsigned int type; +}; + +struct pathnode_transient_t { + int iSearchFrame; + pathnode_t *pNextOpen; + pathnode_t *pPrevOpen; + pathnode_t *pParent; + float fCost; + float fHeuristic; + float costFactor; +}; + +struct pathnode_dynamic_t { + void *pOwner; + int iFreeTime; + int iValidTime[3]; + int inPlayerLOSTime; + int16_t wLinkCount; + int16_t wOverlapCount; + int16_t turretEntNumber; + int16_t userCount; +}; + +struct pathlink_s { + float fDist; + uint16_t nodeNum; + char disconnectCount; + char negotiationLink; + char ubBadPlaceCount[4]; +}; + +enum nodeType { + NODE_BADNODE = 0x0, + NODE_PATHNODE = 0x1, + NODE_COVER_STAND = 0x2, + NODE_COVER_CROUCH = 0x3, + NODE_COVER_CROUCH_WINDOW = 0x4, + NODE_COVER_PRONE = 0x5, + NODE_COVER_RIGHT = 0x6, + NODE_COVER_LEFT = 0x7, + NODE_COVER_WIDE_RIGHT = 0x8, + NODE_COVER_WIDE_LEFT = 0x9, + NODE_CONCEALMENT_STAND = 0xA, + NODE_CONCEALMENT_CROUCH = 0xB, + NODE_CONCEALMENT_PRONE = 0xC, + NODE_REACQUIRE = 0xD, + NODE_BALCONY = 0xE, + NODE_SCRIPTED = 0xF, + NODE_NEGOTIATION_BEGIN = 0x10, + NODE_NEGOTIATION_END = 0x11, + NODE_TURRET = 0x12, + NODE_GUARD = 0x13, + NODE_NUMTYPES = 0x14, + NODE_DONTLINK = 0x14, +}; + +struct pathnode_constant_t { + nodeType type; + uint16_t spawnflags; + uint16_t targetname; + uint16_t script_linkName; + uint16_t script_noteworthy; + uint16_t target; + uint16_t animscript; + int animscriptfunc; + float vOrigin[3]; + float fAngle; + float forward[2]; + float fRadius; + float minUseDistSq; + int16_t wOverlapNode[2]; + int16_t wChainId; + int16_t wChainDepth; + int16_t wChainParent; + uint16_t totalLinkCount; + pathlink_s *Links; +}; + +struct pathnode_t { + pathnode_constant_t constant; + pathnode_dynamic_t dynamic; + pathnode_transient_t transient; +}; + +struct PathData { + unsigned int nodeCount; + pathnode_t *nodes; + pathbasenode_t *basenodes; + unsigned int chainNodeCount; + uint16_t *chainNodeForNode; + uint16_t *nodeForChainNode; + int visBytes; + char *pathVis; + int nodeTreeCount; + pathnode_tree_t *nodeTree; +}; + +struct GameWorldSp { + const char *name; + PathData path; +}; + +struct GameWorldMp { + const char *name; +}; + +struct MapEnts { + const char *name; + char *entityString; + int numEntityChars; +}; + +struct GfxWorldVertex { + float xyz[3]; + float binormalSign; + GfxColor color; + float texCoord[2]; + float lmapCoord[2]; + PackedUnitVec normal; + PackedUnitVec tangent; +}; + +struct GfxWorldVertexData { + GfxWorldVertex *vertices; + void /*IDirect3DVertexBuffer9*/ *worldVb; +}; + +struct GfxWorldVertexLayerData { + char *data; + void /*IDirect3DVertexBuffer9*/ *layerVb; +}; + +struct SunLightParseParams { + char name[64]; + float ambientScale; + float ambientColor[3]; + float diffuseFraction; + float sunLight; + float sunColor[3]; + float diffuseColor[3]; + bool diffuseColorHasBeenSet; + float angles[3]; +}; + +struct GfxLightImage { + GfxImage *image; + char samplerState; +}; + +struct GfxLightDef { + const char *name; + GfxLightImage attenuation; + int lmapLookupStart; +}; + +struct GfxLight { + char type; + char canUseShadowMap; + char unused[2]; + float color[3]; + float dir[3]; + float origin[3]; + float radius; + float cosHalfFovOuter; + float cosHalfFovInner; + int exponent; + unsigned int spotShadowIndex; + GfxLightDef *def; +}; + +struct GfxReflectionProbe { + float origin[3]; + GfxImage *reflectionImage; +}; + +struct GfxWorldDpvsPlanes { + int cellCount; + cplane_s *planes; + uint16_t *nodes; + unsigned int *sceneEntCellBits; +}; + +struct DpvsPlane { + float coeffs[4]; + char side[3]; + char pad; +}; + +struct GfxCell; +struct GfxPortal; + +struct GfxPortalWritable { + bool isQueued; + bool isAncestor; + char recursionDepth; + char hullPointCount; + float (*hullPoints)[2]; + GfxPortal *queuedParent; +}; + +struct GfxPortal { + GfxPortalWritable writable; + DpvsPlane plane; + GfxCell *cell; + vec3_t *vertices; + char vertexCount; + float hullAxis[2][3]; +}; + +struct GfxAabbTree { + float mins[3]; + float maxs[3]; + uint16_t childCount; + uint16_t surfaceCount; + uint16_t startSurfIndex; + uint16_t surfaceCountNoDecal; + uint16_t startSurfIndexNoDecal; + uint16_t smodelIndexCount; + uint16_t *smodelIndexes; + int childrenOffset; +}; + +struct GfxCell { + float mins[3]; + float maxs[3]; + int aabbTreeCount; + GfxAabbTree *aabbTree; + int portalCount; + GfxPortal *portals; + int cullGroupCount; + int *cullGroups; + char reflectionProbeCount; + char *reflectionProbes; +}; + +struct GfxLightmapArray { + GfxImage *primary; + GfxImage *secondary; +}; + +struct type_align(4) GfxLightGridEntry { + uint16_t colorsIndex; + char primaryLightIndex; + char needsTrace; +}; + +struct type_align(4) GfxLightGridColors { char rgb[56][3]; }; + +struct GfxLightGrid { + bool hasLightRegions; + unsigned int sunPrimaryLightIndex; + uint16_t mins[3]; + uint16_t maxs[3]; + unsigned int rowAxis; + unsigned int colAxis; + uint16_t *rowDataStart; + unsigned int rawRowDataSize; + char *rawRowData; + unsigned int entryCount; + GfxLightGridEntry *entries; + unsigned int colorCount; + GfxLightGridColors *colors; +}; + +struct GfxBrushModelWritable { + float mins[3]; + float maxs[3]; +}; + +struct GfxBrushModel { + GfxBrushModelWritable writable; + float bounds[2][3]; + uint16_t surfaceCount; + uint16_t startSurfIndex; + uint16_t surfaceCountNoDecal; +}; + +struct MaterialMemory { + Material *material; + int memory; +}; + +struct sunflare_t { + bool hasValidData; + Material *spriteMaterial; + Material *flareMaterial; + float spriteSize; + float flareMinSize; + float flareMinDot; + float flareMaxSize; + float flareMaxDot; + float flareMaxAlpha; + int flareFadeInTime; + int flareFadeOutTime; + float blindMinDot; + float blindMaxDot; + float blindMaxDarken; + int blindFadeInTime; + int blindFadeOutTime; + float glareMinDot; + float glareMaxDot; + float glareMaxLighten; + int glareFadeInTime; + int glareFadeOutTime; + float sunFxPosition[3]; +}; + +struct XModelDrawInfo { + uint16_t lod; + uint16_t surfId; +}; + +struct GfxSceneDynModel { + XModelDrawInfo info; + uint16_t dynEntId; +}; + +struct BModelDrawInfo { + uint16_t surfId; +}; + +struct type_align(4) GfxSceneDynBrush { + BModelDrawInfo info; + uint16_t dynEntId; +}; + +struct GfxShadowGeometry { + uint16_t surfaceCount; + uint16_t smodelCount; + uint16_t *sortedSurfIndex; + uint16_t *smodelIndex; +}; + +struct GfxLightRegionAxis { + float dir[3]; + float midPoint; + float halfSize; +}; + +struct GfxLightRegionHull { + float kdopMidPoint[9]; + float kdopHalfSize[9]; + unsigned int axisCount; + GfxLightRegionAxis *axis; +}; + +struct GfxLightRegion { + unsigned int hullCount; + GfxLightRegionHull *hulls; +}; + +struct GfxPackedPlacement { + float origin[3]; + float axis[3][3]; + float scale; +}; + +struct GfxStaticModelDrawInst { + float cullDist; + GfxPackedPlacement placement; + XModel *model; + uint16_t smodelCacheIndex[4]; + char reflectionProbeIndex; + char primaryLightIndex; + uint16_t lightingHandle; + char flags; +}; + +struct GfxStaticModelInst { + float mins[3]; + float maxs[3]; + GfxColor groundLighting; +}; + +struct srfTriangles_t { + int vertexLayerData; + int firstVertex; + uint16_t vertexCount; + uint16_t triCount; + int baseIndex; +}; + +struct GfxSurface { + srfTriangles_t tris; + Material *material; + char lightmapIndex; + char reflectionProbeIndex; + char primaryLightIndex; + char flags; + float bounds[2][3]; +}; + +struct GfxCullGroup { + float mins[3]; + float maxs[3]; + int surfaceCount; + int startSurfIndex; +}; + +struct GfxWorldDpvsStatic { + unsigned int smodelCount; + unsigned int staticSurfaceCount; + unsigned int staticSurfaceCountNoDecal; + unsigned int litSurfsBegin; + unsigned int litSurfsEnd; + unsigned int decalSurfsBegin; + unsigned int decalSurfsEnd; + unsigned int emissiveSurfsBegin; + unsigned int emissiveSurfsEnd; + unsigned int smodelVisDataCount; + unsigned int surfaceVisDataCount; + char *smodelVisData[3]; + char *surfaceVisData[3]; + raw_uint128 *lodData; + uint16_t *sortedSurfIndex; + GfxStaticModelInst *smodelInsts; + GfxSurface *surfaces; + GfxCullGroup *cullGroups; + GfxStaticModelDrawInst *smodelDrawInsts; + GfxDrawSurf *surfaceMaterials; + raw_uint128 *surfaceCastsSunShadow; + volatile int usageCount; +}; + +struct GfxWorldDpvsDynamic { + unsigned int dynEntClientWordCount[2]; + unsigned int dynEntClientCount[2]; + unsigned int *dynEntCellBits[2]; + char *dynEntVisData[2][3]; +}; + +struct GfxWorldStreamInfo { + char pad; +}; + +typedef tdef_align(4) GfxSceneDynModel GfxSceneDynModel4; + +struct GfxWorld { + const char *name; + const char *baseName; + int planeCount; + int nodeCount; + int indexCount; + uint16_t *indices; + int surfaceCount; + GfxWorldStreamInfo streamInfo; + int skySurfCount; + int *skyStartSurfs; + GfxImage *skyImage; + char skySamplerState; + unsigned int vertexCount; + GfxWorldVertexData vd; + unsigned int vertexLayerDataSize; + GfxWorldVertexLayerData vld; + SunLightParseParams sunParse; + GfxLight *sunLight; + float sunColorFromBsp[3]; + unsigned int sunPrimaryLightIndex; + unsigned int primaryLightCount; + int cullGroupCount; + unsigned int reflectionProbeCount; + GfxReflectionProbe *reflectionProbes; + GfxTexture *reflectionProbeTextures; + GfxWorldDpvsPlanes dpvsPlanes; + int cellBitsCount; + GfxCell *cells; + int lightmapCount; + GfxLightmapArray *lightmaps; + GfxLightGrid lightGrid; + GfxTexture *lightmapPrimaryTextures; + GfxTexture *lightmapSecondaryTextures; + int modelCount; + GfxBrushModel *models; + float mins[3]; + float maxs[3]; + unsigned int checksum; + int materialMemoryCount; + MaterialMemory *materialMemory; + sunflare_t sun; + float outdoorLookupMatrix[4][4]; + GfxImage *outdoorImage; + unsigned int *cellCasterBits; + GfxSceneDynModel4 *sceneDynModel; + GfxSceneDynBrush *sceneDynBrush; + unsigned int *primaryLightEntityShadowVis; + unsigned int *primaryLightDynEntShadowVis[2]; + char *nonSunPrimaryLightForModelDynEnt; + GfxShadowGeometry *shadowGeom; + GfxLightRegion *lightRegion; + GfxWorldDpvsStatic dpvs; + GfxWorldDpvsDynamic dpvsDyn; +}; + +struct Glyph { + uint16_t letter; + char x0; + char y0; + char dx; + char pixelWidth; + char pixelHeight; + float s0; + float t0; + float s1; + float t1; +}; + +struct Font_s { + const char *fontName; + int pixelHeight; + int glyphCount; + Material *material; + Material *glowMaterial; + Glyph *glyphs; +}; + +struct MenuList { + const char *name; + int menuCount; + menuDef_t **menus; +}; + +struct rectDef_s { + float x; + float y; + float w; + float h; + int horzAlign; + int vertAlign; +}; + +struct windowDef_t { + const char *name; + rectDef_s rect; + rectDef_s rectClient; + const char *group; + int style; + int border; + int ownerDraw; + int ownerDrawFlags; + float borderSize; + int staticFlags; + int dynamicFlags[1]; + int nextTime; + float foreColor[4]; + float backColor[4]; + float borderColor[4]; + float outlineColor[4]; + Material *background; +}; + +struct ItemKeyHandler { + int key; + const char *action; + ItemKeyHandler *next; +}; + +union operandInternalDataUnion { + int intVal; + float floatVal; + const char *stringVal; +}; + +enum expDataType { + VAL_INT = 0x0, + VAL_FLOAT = 0x1, + VAL_STRING = 0x2, +}; + +struct Operand { + expDataType dataType; + operandInternalDataUnion internals; +}; + +union entryInternalData { + int op; + Operand operand; +}; + +enum expressionEntryType : int { + EET_OPERATOR = 0x0, + EET_OPERAND = 0x1, +}; + +struct expressionEntry { + int type; + entryInternalData data; +}; + +struct statement_s { + int numEntries; + expressionEntry **entries; +}; + +struct columnInfo_s { + int pos; + int width; + int maxChars; + int alignment; +}; + +struct listBoxDef_s { + int mousePos; + int startPos[1]; + int endPos[1]; + int drawPadding; + float elementWidth; + float elementHeight; + int elementStyle; + int numColumns; + columnInfo_s columnInfo[16]; + const char *doubleClick; + int notselectable; + int noScrollBars; + int usePaging; + float selectBorder[4]; + float disableColor[4]; + Material *selectIcon; +}; + +struct editFieldDef_s { + float minVal; + float maxVal; + float defVal; + float range; + int maxChars; + int maxCharsGotoNext; + int maxPaintChars; + int paintOffset; +}; + +struct multiDef_s { + const char *dvarList[32]; + const char *dvarStr[32]; + float dvarValue[32]; + int count; + int strDef; +}; + +union itemDefData_t { + listBoxDef_s *listBox; + editFieldDef_s *editField; + multiDef_s *multi; + const char *enumDvarName; + void *data; +}; + +enum ItemDefType { + ITEM_TYPE_TEXT = 0x0, + ITEM_TYPE_BUTTON = 0x1, + ITEM_TYPE_RADIOBUTTON = 0x2, + ITEM_TYPE_CHECKBOX = 0x3, + ITEM_TYPE_EDITFIELD = 0x4, + ITEM_TYPE_COMBO = 0x5, + ITEM_TYPE_LISTBOX = 0x6, + ITEM_TYPE_MODEL = 0x7, + ITEM_TYPE_OWNERDRAW = 0x8, + ITEM_TYPE_NUMERICFIELD = 0x9, + ITEM_TYPE_SLIDER = 0xA, + ITEM_TYPE_YESNO = 0xB, + ITEM_TYPE_MULTI = 0xC, + ITEM_TYPE_DVARENUM = 0xD, + ITEM_TYPE_BIND = 0xE, + ITEM_TYPE_MENUMODEL = 0xF, + ITEM_TYPE_VALIDFILEFIELD = 0x10, + ITEM_TYPE_DECIMALFIELD = 0x11, + ITEM_TYPE_UPREDITFIELD = 0x12, + ITEM_TYPE_GAME_MESSAGE_WINDOW = 0x13 +}; + +struct itemDef_s { + windowDef_t window; + rectDef_s textRect[1]; + int type; + int dataType; + int alignment; + int fontEnum; + int textAlignMode; + float textalignx; + float textaligny; + float textscale; + int textStyle; + int gameMsgWindowIndex; + int gameMsgWindowMode; + const char *text; + int itemFlags; + menuDef_t *parent; + const char *mouseEnterText; + const char *mouseExitText; + const char *mouseEnter; + const char *mouseExit; + const char *action; + const char *onAccept; + const char *onFocus; + const char *leaveFocus; + const char *dvar; + const char *dvarTest; + ItemKeyHandler *onKey; + const char *enableDvar; + int dvarFlags; + snd_alias_list_t *focusSound; + float special; + int cursorPos[1]; + itemDefData_t typeData; + int imageTrack; + statement_s visibleExp; + statement_s textExp; + statement_s materialExp; + statement_s rectXExp; + statement_s rectYExp; + statement_s rectWExp; + statement_s rectHExp; + statement_s forecolorAExp; +}; + +struct menuDef_t { + windowDef_t window; + const char *font; + int fullScreen; + int itemCount; + int fontIndex; + int cursorItem[1]; + int fadeCycle; + float fadeClamp; + float fadeAmount; + float fadeInAmount; + float blurRadius; + const char *onOpen; + const char *onClose; + const char *onESC; + ItemKeyHandler *onKey; + statement_s visibleExp; + const char *allowedBinding; + const char *soundName; + int imageTrack; + float focusColor[4]; + float disableColor[4]; + statement_s rectXExp; + statement_s rectYExp; + itemDef_s **items; +}; + +struct LocalizeEntry { + const char *value; + const char *name; +}; + +enum weapType_t { + WEAPTYPE_BULLET = 0x0, + WEAPTYPE_GRENADE = 0x1, + WEAPTYPE_PROJECTILE = 0x2, + WEAPTYPE_BINOCULARS = 0x3, + WEAPTYPE_NUM = 0x4, +}; + +enum weapClass_t { + WEAPCLASS_RIFLE = 0x0, + WEAPCLASS_MG = 0x1, + WEAPCLASS_SMG = 0x2, + WEAPCLASS_SPREAD = 0x3, + WEAPCLASS_PISTOL = 0x4, + WEAPCLASS_GRENADE = 0x5, + WEAPCLASS_ROCKETLAUNCHER = 0x6, + WEAPCLASS_TURRET = 0x7, + WEAPCLASS_NON_PLAYER = 0x8, + WEAPCLASS_ITEM = 0x9, + WEAPCLASS_NUM = 0xA, +}; + +enum PenetrateType { + PENETRATE_TYPE_NONE = 0x0, + PENETRATE_TYPE_SMALL = 0x1, + PENETRATE_TYPE_MEDIUM = 0x2, + PENETRATE_TYPE_LARGE = 0x3, + PENETRATE_TYPE_COUNT = 0x4, +}; + +enum ImpactType { + IMPACT_TYPE_NONE = 0x0, + IMPACT_TYPE_BULLET_SMALL = 0x1, + IMPACT_TYPE_BULLET_LARGE = 0x2, + IMPACT_TYPE_BULLET_AP = 0x3, + IMPACT_TYPE_SHOTGUN = 0x4, + IMPACT_TYPE_GRENADE_BOUNCE = 0x5, + IMPACT_TYPE_GRENADE_EXPLODE = 0x6, + IMPACT_TYPE_ROCKET_EXPLODE = 0x7, + IMPACT_TYPE_PROJECTILE_DUD = 0x8, + IMPACT_TYPE_COUNT = 0x9, +}; + +enum weapInventoryType_t { + WEAPINVENTORY_PRIMARY = 0x0, + WEAPINVENTORY_OFFHAND = 0x1, + WEAPINVENTORY_ITEM = 0x2, + WEAPINVENTORY_ALTMODE = 0x3, + WEAPINVENTORYCOUNT = 0x4, +}; + +enum weapFireType_t { + WEAPON_FIRETYPE_FULLAUTO = 0x0, + WEAPON_FIRETYPE_SINGLESHOT = 0x1, + WEAPON_FIRETYPE_BURSTFIRE2 = 0x2, + WEAPON_FIRETYPE_BURSTFIRE3 = 0x3, + WEAPON_FIRETYPE_BURSTFIRE4 = 0x4, + WEAPON_FIRETYPECOUNT = 0x5, +}; + +enum OffhandClass { + OFFHAND_CLASS_NONE = 0x0, + OFFHAND_CLASS_FRAG_GRENADE = 0x1, + OFFHAND_CLASS_SMOKE_GRENADE = 0x2, + OFFHAND_CLASS_FLASH_GRENADE = 0x3, + OFFHAND_CLASS_COUNT = 0x4, +}; + +enum weapStance_t { + WEAPSTANCE_STAND = 0x0, + WEAPSTANCE_DUCK = 0x1, + WEAPSTANCE_PRONE = 0x2, + WEAPSTANCE_NUM = 0x3, +}; + +enum activeReticleType_t { + VEH_ACTIVE_RETICLE_NONE = 0x0, + VEH_ACTIVE_RETICLE_PIP_ON_A_STICK = 0x1, + VEH_ACTIVE_RETICLE_BOUNCING_DIAMOND = 0x2, + VEH_ACTIVE_RETICLE_COUNT = 0x3, +}; + +enum weaponIconRatioType_t { + WEAPON_ICON_RATIO_1TO1 = 0x0, + WEAPON_ICON_RATIO_2TO1 = 0x1, + WEAPON_ICON_RATIO_4TO1 = 0x2, + WEAPON_ICON_RATIO_COUNT = 0x3, +}; + +enum ammoCounterClipType_t { + AMMO_COUNTER_CLIP_NONE = 0x0, + AMMO_COUNTER_CLIP_MAGAZINE = 0x1, + AMMO_COUNTER_CLIP_SHORTMAGAZINE = 0x2, + AMMO_COUNTER_CLIP_SHOTGUN = 0x3, + AMMO_COUNTER_CLIP_ROCKET = 0x4, + AMMO_COUNTER_CLIP_BELTFED = 0x5, + AMMO_COUNTER_CLIP_ALTWEAPON = 0x6, + AMMO_COUNTER_CLIP_COUNT = 0x7, +}; + +enum weapOverlayReticle_t { + WEAPOVERLAYRETICLE_NONE = 0x0, + WEAPOVERLAYRETICLE_CROSSHAIR = 0x1, + WEAPOVERLAYRETICLE_NUM = 0x2, +}; + +enum WeapOverlayInteface_t { + WEAPOVERLAYINTERFACE_NONE = 0x0, + WEAPOVERLAYINTERFACE_JAVELIN = 0x1, + WEAPOVERLAYINTERFACE_TURRETSCOPE = 0x2, + WEAPOVERLAYINTERFACECOUNT = 0x3, +}; + +enum weapProjExposion_t { + WEAPPROJEXP_GRENADE = 0x0, + WEAPPROJEXP_ROCKET = 0x1, + WEAPPROJEXP_FLASHBANG = 0x2, + WEAPPROJEXP_NONE = 0x3, + WEAPPROJEXP_DUD = 0x4, + WEAPPROJEXP_SMOKE = 0x5, + WEAPPROJEXP_HEAVY = 0x6, + WEAPPROJEXP_NUM = 0x7, +}; + +enum WeapStickinessType { + WEAPSTICKINESS_NONE = 0x0, + WEAPSTICKINESS_ALL = 0x1, + WEAPSTICKINESS_GROUND = 0x2, + WEAPSTICKINESS_GROUND_WITH_YAW = 0x3, + WEAPSTICKINESS_COUNT = 0x4, +}; + +enum guidedMissileType_t { + MISSILE_GUIDANCE_NONE = 0x0, + MISSILE_GUIDANCE_SIDEWINDER = 0x1, + MISSILE_GUIDANCE_HELLFIRE = 0x2, + MISSILE_GUIDANCE_JAVELIN = 0x3, + MISSILE_GUIDANCE_COUNT = 0x4, +}; + +struct snd_alias_list_name { + const char *soundName; +}; + +union SndAliasCustom { + snd_alias_list_name *name; + snd_alias_list_t *sound; +}; + +struct WeaponDef { + const char *szInternalName; + const char *szDisplayName; + const char *szOverlayName; + XModel *gunXModel[16]; + XModel *handXModel; + const char *szXAnims[33]; + const char *szModeName; + uint16_t hideTags[8]; + uint16_t notetrackSoundMapKeys[16]; + uint16_t notetrackSoundMapValues[16]; + int playerAnimType; + weapType_t weapType; + weapClass_t weapClass; + PenetrateType penetrateType; + ImpactType impactType; + weapInventoryType_t inventoryType; + weapFireType_t fireType; + OffhandClass offhandClass; + weapStance_t stance; + FxEffectDef *viewFlashEffect; + FxEffectDef *worldFlashEffect; + SndAliasCustom pickupSound; + SndAliasCustom pickupSoundPlayer; + SndAliasCustom ammoPickupSound; + SndAliasCustom ammoPickupSoundPlayer; + SndAliasCustom projectileSound; + SndAliasCustom pullbackSound; + SndAliasCustom pullbackSoundPlayer; + SndAliasCustom fireSound; + SndAliasCustom fireSoundPlayer; + SndAliasCustom fireLoopSound; + SndAliasCustom fireLoopSoundPlayer; + SndAliasCustom fireStopSound; + SndAliasCustom fireStopSoundPlayer; + SndAliasCustom fireLastSound; + SndAliasCustom fireLastSoundPlayer; + SndAliasCustom emptyFireSound; + SndAliasCustom emptyFireSoundPlayer; + SndAliasCustom meleeSwipeSound; + SndAliasCustom meleeSwipeSoundPlayer; + SndAliasCustom meleeHitSound; + SndAliasCustom meleeMissSound; + SndAliasCustom rechamberSound; + SndAliasCustom rechamberSoundPlayer; + SndAliasCustom reloadSound; + SndAliasCustom reloadSoundPlayer; + SndAliasCustom reloadEmptySound; + SndAliasCustom reloadEmptySoundPlayer; + SndAliasCustom reloadStartSound; + SndAliasCustom reloadStartSoundPlayer; + SndAliasCustom reloadEndSound; + SndAliasCustom reloadEndSoundPlayer; + SndAliasCustom detonateSound; + SndAliasCustom detonateSoundPlayer; + SndAliasCustom nightVisionWearSound; + SndAliasCustom nightVisionWearSoundPlayer; + SndAliasCustom nightVisionRemoveSound; + SndAliasCustom nightVisionRemoveSoundPlayer; + SndAliasCustom altSwitchSound; + SndAliasCustom altSwitchSoundPlayer; + SndAliasCustom raiseSound; + SndAliasCustom raiseSoundPlayer; + SndAliasCustom firstRaiseSound; + SndAliasCustom firstRaiseSoundPlayer; + SndAliasCustom putawaySound; + SndAliasCustom putawaySoundPlayer; + SndAliasCustom *bounceSound; + FxEffectDef *viewShellEjectEffect; + FxEffectDef *worldShellEjectEffect; + FxEffectDef *viewLastShotEjectEffect; + FxEffectDef *worldLastShotEjectEffect; + Material *reticleCenter; + Material *reticleSide; + int iReticleCenterSize; + int iReticleSideSize; + int iReticleMinOfs; + activeReticleType_t activeReticleType; + float vStandMove[3]; + float vStandRot[3]; + float vDuckedOfs[3]; + float vDuckedMove[3]; + float vDuckedRot[3]; + float vProneOfs[3]; + float vProneMove[3]; + float vProneRot[3]; + float fPosMoveRate; + float fPosProneMoveRate; + float fStandMoveMinSpeed; + float fDuckedMoveMinSpeed; + float fProneMoveMinSpeed; + float fPosRotRate; + float fPosProneRotRate; + float fStandRotMinSpeed; + float fDuckedRotMinSpeed; + float fProneRotMinSpeed; + XModel *worldModel[16]; + XModel *worldClipModel; + XModel *rocketModel; + XModel *knifeModel; + XModel *worldKnifeModel; + Material *hudIcon; + weaponIconRatioType_t hudIconRatio; + Material *ammoCounterIcon; + weaponIconRatioType_t ammoCounterIconRatio; + ammoCounterClipType_t ammoCounterClip; + int iStartAmmo; + const char *szAmmoName; + int iAmmoIndex; + const char *szClipName; + int iClipIndex; + int iMaxAmmo; + int iClipSize; + int shotCount; + const char *szSharedAmmoCapName; + int iSharedAmmoCapIndex; + int iSharedAmmoCap; + int damage; + int playerDamage; + int iMeleeDamage; + int iDamageType; + int iFireDelay; + int iMeleeDelay; + int meleeChargeDelay; + int iDetonateDelay; + int iFireTime; + int iRechamberTime; + int iRechamberBoltTime; + int iHoldFireTime; + int iDetonateTime; + int iMeleeTime; + int meleeChargeTime; + int iReloadTime; + int reloadShowRocketTime; + int iReloadEmptyTime; + int iReloadAddTime; + int iReloadStartTime; + int iReloadStartAddTime; + int iReloadEndTime; + int iDropTime; + int iRaiseTime; + int iAltDropTime; + int iAltRaiseTime; + int quickDropTime; + int quickRaiseTime; + int iFirstRaiseTime; + int iEmptyRaiseTime; + int iEmptyDropTime; + int sprintInTime; + int sprintLoopTime; + int sprintOutTime; + int nightVisionWearTime; + int nightVisionWearTimeFadeOutEnd; + int nightVisionWearTimePowerUp; + int nightVisionRemoveTime; + int nightVisionRemoveTimePowerDown; + int nightVisionRemoveTimeFadeInStart; + int fuseTime; + int aiFuseTime; + int requireLockonToFire; + int noAdsWhenMagEmpty; + int avoidDropCleanup; + float autoAimRange; + float aimAssistRange; + float aimAssistRangeAds; + float aimPadding; + float enemyCrosshairRange; + int crosshairColorChange; + float moveSpeedScale; + float adsMoveSpeedScale; + float sprintDurationScale; + float fAdsZoomFov; + float fAdsZoomInFrac; + float fAdsZoomOutFrac; + Material *overlayMaterial; + Material *overlayMaterialLowRes; + weapOverlayReticle_t overlayReticle; + WeapOverlayInteface_t overlayInterface; + float overlayWidth; + float overlayHeight; + float fAdsBobFactor; + float fAdsViewBobMult; + float fHipSpreadStandMin; + float fHipSpreadDuckedMin; + float fHipSpreadProneMin; + float hipSpreadStandMax; + float hipSpreadDuckedMax; + float hipSpreadProneMax; + float fHipSpreadDecayRate; + float fHipSpreadFireAdd; + float fHipSpreadTurnAdd; + float fHipSpreadMoveAdd; + float fHipSpreadDuckedDecay; + float fHipSpreadProneDecay; + float fHipReticleSidePos; + int iAdsTransInTime; + int iAdsTransOutTime; + float fAdsIdleAmount; + float fHipIdleAmount; + float adsIdleSpeed; + float hipIdleSpeed; + float fIdleCrouchFactor; + float fIdleProneFactor; + float fGunMaxPitch; + float fGunMaxYaw; + float swayMaxAngle; + float swayLerpSpeed; + float swayPitchScale; + float swayYawScale; + float swayHorizScale; + float swayVertScale; + float swayShellShockScale; + float adsSwayMaxAngle; + float adsSwayLerpSpeed; + float adsSwayPitchScale; + float adsSwayYawScale; + float adsSwayHorizScale; + float adsSwayVertScale; + int bRifleBullet; + int armorPiercing; + int bBoltAction; + int aimDownSight; + int bRechamberWhileAds; + float adsViewErrorMin; + float adsViewErrorMax; + int bCookOffHold; + int bClipOnly; + int adsFireOnly; + int cancelAutoHolsterWhenEmpty; + int suppressAmmoReserveDisplay; + int enhanced; + int laserSightDuringNightvision; + Material *killIcon; + weaponIconRatioType_t killIconRatio; + int flipKillIcon; + Material *dpadIcon; + weaponIconRatioType_t dpadIconRatio; + int bNoPartialReload; + int bSegmentedReload; + int iReloadAmmoAdd; + int iReloadStartAdd; + const char *szAltWeaponName; + unsigned int altWeaponIndex; + int iDropAmmoMin; + int iDropAmmoMax; + int blocksProne; + int silenced; + int iExplosionRadius; + int iExplosionRadiusMin; + int iExplosionInnerDamage; + int iExplosionOuterDamage; + float damageConeAngle; + int iProjectileSpeed; + int iProjectileSpeedUp; + int iProjectileSpeedForward; + int iProjectileActivateDist; + float projLifetime; + float timeToAccelerate; + float projectileCurvature; + XModel *projectileModel; + weapProjExposion_t projExplosion; + FxEffectDef *projExplosionEffect; + int projExplosionEffectForceNormalUp; + FxEffectDef *projDudEffect; + SndAliasCustom projExplosionSound; + SndAliasCustom projDudSound; + int bProjImpactExplode; + WeapStickinessType stickiness; + int hasDetonator; + int timedDetonation; + int rotate; + int holdButtonToThrow; + int freezeMovementWhenFiring; + float lowAmmoWarningThreshold; + float parallelBounce[29]; + float perpendicularBounce[29]; + FxEffectDef *projTrailEffect; + float vProjectileColor[3]; + guidedMissileType_t guidedMissileType; + float maxSteeringAccel; + int projIgnitionDelay; + FxEffectDef *projIgnitionEffect; + SndAliasCustom projIgnitionSound; + float fAdsAimPitch; + float fAdsCrosshairInFrac; + float fAdsCrosshairOutFrac; + int adsGunKickReducedKickBullets; + float adsGunKickReducedKickPercent; + float fAdsGunKickPitchMin; + float fAdsGunKickPitchMax; + float fAdsGunKickYawMin; + float fAdsGunKickYawMax; + float fAdsGunKickAccel; + float fAdsGunKickSpeedMax; + float fAdsGunKickSpeedDecay; + float fAdsGunKickStaticDecay; + float fAdsViewKickPitchMin; + float fAdsViewKickPitchMax; + float fAdsViewKickYawMin; + float fAdsViewKickYawMax; + float fAdsViewKickCenterSpeed; + float fAdsViewScatterMin; + float fAdsViewScatterMax; + float fAdsSpread; + int hipGunKickReducedKickBullets; + float hipGunKickReducedKickPercent; + float fHipGunKickPitchMin; + float fHipGunKickPitchMax; + float fHipGunKickYawMin; + float fHipGunKickYawMax; + float fHipGunKickAccel; + float fHipGunKickSpeedMax; + float fHipGunKickSpeedDecay; + float fHipGunKickStaticDecay; + float fHipViewKickPitchMin; + float fHipViewKickPitchMax; + float fHipViewKickYawMin; + float fHipViewKickYawMax; + float fHipViewKickCenterSpeed; + float fHipViewScatterMin; + float fHipViewScatterMax; + float fightDist; + float maxDist; + // TODO: Order is accuracyGraphName[0] -> originalAccuracyGraphKnots[0] -> accuracyGraphName[1] -> ... + // Which is currently not possible to do in code generation. Afaik this is the only place where this is the case. + // So might be something to fix but on the other hand it might be too much work for this little inconvenience. + // const char* accuracyGraphName[2]; + const char *accuracyGraphName0; + const char *accuracyGraphName1; + // float(*accuracyGraphKnots[2])[2]; + vec2_t *accuracyGraphKnots0; + vec2_t *accuracyGraphKnots1; + // float(*originalAccuracyGraphKnots[2])[2]; + vec2_t *originalAccuracyGraphKnots0; + vec2_t *originalAccuracyGraphKnots1; + int accuracyGraphKnotCount[2]; + int originalAccuracyGraphKnotCount[2]; + int iPositionReloadTransTime; + float leftArc; + float rightArc; + float topArc; + float bottomArc; + float accuracy; + float aiSpread; + float playerSpread; + float minTurnSpeed[2]; + float maxTurnSpeed[2]; + float pitchConvergenceTime; + float yawConvergenceTime; + float suppressTime; + float maxRange; + float fAnimHorRotateInc; + float fPlayerPositionDist; + const char *szUseHintString; + const char *dropHintString; + int iUseHintStringIndex; + int dropHintStringIndex; + float horizViewJitter; + float vertViewJitter; + const char *szScript; + float fOOPosAnimLength[2]; + int minDamage; + int minPlayerDamage; + float fMaxDamageRange; + float fMinDamageRange; + float destabilizationRateTime; + float destabilizationCurvatureMax; + int destabilizeDistance; + float locationDamageMultipliers[19]; + const char *fireRumble; + const char *meleeImpactRumble; + float adsDofStart; + float adsDofEnd; +}; + +struct SndDriverGlobals { + const char *name; +}; + +struct FxIntRange { + int base; + int amplitude; +}; + +struct FxFloatRange { + float base; + float amplitude; +}; + +struct FxSpawnDefOneShot { + FxIntRange count; +}; + +struct FxSpawnDefLooping { + int intervalMsec; + int count; +}; + +union FxSpawnDef { + FxSpawnDefLooping looping; + FxSpawnDefOneShot oneShot; +}; + +struct FxElemAtlas { + char behavior; + char index; + char fps; + char loopCount; + char colIndexBits; + char rowIndexBits; + int16_t entryCount; +}; + +struct FxElemVec3Range { + float base[3]; + float amplitude[3]; +}; + +struct FxElemVelStateInFrame { + FxElemVec3Range velocity; + FxElemVec3Range totalDelta; +}; + +struct FxElemVelStateSample { + FxElemVelStateInFrame local; + FxElemVelStateInFrame world; +}; + +struct FxElemVisualState { + char color[4]; + float rotationDelta; + float rotationTotal; + float size[2]; + float scale; +}; + +struct FxElemVisStateSample { + FxElemVisualState base; + FxElemVisualState amplitude; +}; + +union FxEffectDefRef { + FxEffectDef *handle; + const char *name; +}; + +enum FxElemType { + FX_ELEM_TYPE_SPRITE_BILLBOARD = 0x0, + FX_ELEM_TYPE_SPRITE_ORIENTED = 0x1, + FX_ELEM_TYPE_TAIL = 0x2, + FX_ELEM_TYPE_TRAIL = 0x3, + FX_ELEM_TYPE_CLOUD = 0x4, + FX_ELEM_TYPE_MODEL = 0x5, + FX_ELEM_TYPE_OMNI_LIGHT = 0x6, + FX_ELEM_TYPE_SPOT_LIGHT = 0x7, + FX_ELEM_TYPE_SOUND = 0x8, + FX_ELEM_TYPE_DECAL = 0x9, + FX_ELEM_TYPE_RUNNER = 0xA, + FX_ELEM_TYPE_COUNT = 0xB, + FX_ELEM_TYPE_LAST_SPRITE = 0x3, + FX_ELEM_TYPE_LAST_DRAWN = 0x7, +}; + +union FxElemVisuals { + const void *anonymous; + Material *material; + XModel *model; + FxEffectDefRef effectDef; + const char *soundName; +}; + +struct FxElemMarkVisuals { + Material *materials[2]; +}; + +union FxElemDefVisuals { + FxElemMarkVisuals *markArray; + FxElemVisuals *array; + FxElemVisuals instance; +}; + +struct FxTrailVertex { + float pos[2]; + float normal[2]; + float texCoord; +}; + +struct FxTrailDef { + int scrollTimeMsec; + int repeatDist; + int splitDist; + int vertCount; + FxTrailVertex *verts; + int indCount; + uint16_t *inds; +}; + +struct FxElemDef { + int flags; + FxSpawnDef spawn; + FxFloatRange spawnRange; + FxFloatRange fadeInRange; + FxFloatRange fadeOutRange; + float spawnFrustumCullRadius; + FxIntRange spawnDelayMsec; + FxIntRange lifeSpanMsec; + FxFloatRange spawnOrigin[3]; + FxFloatRange spawnOffsetRadius; + FxFloatRange spawnOffsetHeight; + FxFloatRange spawnAngles[3]; + FxFloatRange angularVelocity[3]; + FxFloatRange initialRotation; + FxFloatRange gravity; + FxFloatRange reflectionFactor; + FxElemAtlas atlas; + char elemType; + char visualCount; + char velIntervalCount; + char visStateIntervalCount; + FxElemVelStateSample *velSamples; + FxElemVisStateSample *visSamples; + FxElemDefVisuals visuals; + float collMins[3]; + float collMaxs[3]; + FxEffectDefRef effectOnImpact; + FxEffectDefRef effectOnDeath; + FxEffectDefRef effectEmitted; + FxFloatRange emitDist; + FxFloatRange emitDistVariance; + FxTrailDef *trailDef; + char sortOrder; + char lightingFrac; + char useItemClip; + char unused[1]; +}; + +struct FxEffectDef { + const char *name; + int flags; + int totalSize; + int msecLoopingLife; + int elemDefCountLooping; + int elemDefCountOneShot; + int elemDefCountEmission; + FxElemDef *elemDefs; +}; + +struct FxImpactEntry { + FxEffectDef *nonflesh[29]; + FxEffectDef *flesh[4]; +}; + +struct FxImpactTable { + const char *name; + FxImpactEntry *table; +}; + +struct RawFile { + const char *name; + int len; + const char *buffer; +}; + +struct StringTable { + const char *name; + int columnCount; + int rowCount; + const char **values; +}; #ifndef __zonecodegenerator } diff --git a/src/Common/Game/IW4/CommonIW4.cpp b/src/Common/Game/IW4/CommonIW4.cpp index 6a5128365..f065137be 100644 --- a/src/Common/Game/IW4/CommonIW4.cpp +++ b/src/Common/Game/IW4/CommonIW4.cpp @@ -4,48 +4,28 @@ using namespace IW4; -int Common::StringTable_HashString(const char* str) -{ - if (!str) - return 0; - - auto result = 0; - auto offset = 0; - while (str[offset]) - { - const auto c = tolower(str[offset++]); - result = c + 31 * result; - } - - return result; +int Common::StringTable_HashString(const char *str) { + if (!str) + return 0; + + auto result = 0; + auto offset = 0; + while (str[offset]) { + const auto c = tolower(str[offset++]); + result = c + 31 * result; + } + + return result; } -PackedTexCoords Common::Vec2PackTexCoords(const vec2_t* in) -{ - return PackedTexCoords{Pack32::Vec2PackTexCoords(reinterpret_cast(in))}; -} +PackedTexCoords Common::Vec2PackTexCoords(const vec2_t *in) { return PackedTexCoords{Pack32::Vec2PackTexCoords(reinterpret_cast(in))}; } -PackedUnitVec Common::Vec3PackUnitVec(const vec3_t* in) -{ - return PackedUnitVec{Pack32::Vec3PackUnitVec(reinterpret_cast(in))}; -} +PackedUnitVec Common::Vec3PackUnitVec(const vec3_t *in) { return PackedUnitVec{Pack32::Vec3PackUnitVec(reinterpret_cast(in))}; } -GfxColor Common::Vec4PackGfxColor(const vec4_t* in) -{ - return GfxColor{Pack32::Vec4PackGfxColor(reinterpret_cast(in))}; -} +GfxColor Common::Vec4PackGfxColor(const vec4_t *in) { return GfxColor{Pack32::Vec4PackGfxColor(reinterpret_cast(in))}; } -void Common::Vec2UnpackTexCoords(const PackedTexCoords& in, vec2_t* out) -{ - Pack32::Vec2UnpackTexCoordsVU(in.packed, reinterpret_cast(out)); -} +void Common::Vec2UnpackTexCoords(const PackedTexCoords &in, vec2_t *out) { Pack32::Vec2UnpackTexCoordsVU(in.packed, reinterpret_cast(out)); } -void Common::Vec3UnpackUnitVec(const PackedUnitVec& in, vec3_t* out) -{ - Pack32::Vec3UnpackUnitVecScaleBased(in.packed, reinterpret_cast(out)); -} +void Common::Vec3UnpackUnitVec(const PackedUnitVec &in, vec3_t *out) { Pack32::Vec3UnpackUnitVecScaleBased(in.packed, reinterpret_cast(out)); } -void Common::Vec4UnpackGfxColor(const GfxColor& in, vec4_t* out) -{ - Pack32::Vec4UnpackGfxColor(in.packed, reinterpret_cast(out)); -} +void Common::Vec4UnpackGfxColor(const GfxColor &in, vec4_t *out) { Pack32::Vec4UnpackGfxColor(in.packed, reinterpret_cast(out)); } diff --git a/src/Common/Game/IW4/CommonIW4.h b/src/Common/Game/IW4/CommonIW4.h index 9e8ceabaf..3b24cb578 100644 --- a/src/Common/Game/IW4/CommonIW4.h +++ b/src/Common/Game/IW4/CommonIW4.h @@ -2,37 +2,30 @@ #include "IW4.h" -namespace IW4 -{ - class Common - { - public: - static constexpr uint32_t R_HashString(const char* string, const uint32_t hash) - { - const char* v2 = string; // edx@1 - char v3 = *string; // cl@1 - uint32_t result = hash; +namespace IW4 { +class Common { +public: + static constexpr uint32_t R_HashString(const char *string, const uint32_t hash) { + const char *v2 = string; // edx@1 + char v3 = *string; // cl@1 + uint32_t result = hash; - for (; *v2; v3 = *v2) - { - ++v2; - result = 33 * result ^ (v3 | 0x20); - } - return result; - } + for (; *v2; v3 = *v2) { + ++v2; + result = 33 * result ^ (v3 | 0x20); + } + return result; + } - static constexpr uint32_t R_HashString(const char* string) - { - return R_HashString(string, 0u); - } + static constexpr uint32_t R_HashString(const char *string) { return R_HashString(string, 0u); } - static int StringTable_HashString(const char* str); + static int StringTable_HashString(const char *str); - static PackedTexCoords Vec2PackTexCoords(const vec2_t* in); - static PackedUnitVec Vec3PackUnitVec(const vec3_t* in); - static GfxColor Vec4PackGfxColor(const vec4_t* in); - static void Vec2UnpackTexCoords(const PackedTexCoords& in, vec2_t* out); - static void Vec3UnpackUnitVec(const PackedUnitVec& in, vec3_t* out); - static void Vec4UnpackGfxColor(const GfxColor& in, vec4_t* out); - }; -} + static PackedTexCoords Vec2PackTexCoords(const vec2_t *in); + static PackedUnitVec Vec3PackUnitVec(const vec3_t *in); + static GfxColor Vec4PackGfxColor(const vec4_t *in); + static void Vec2UnpackTexCoords(const PackedTexCoords &in, vec2_t *out); + static void Vec3UnpackUnitVec(const PackedUnitVec &in, vec3_t *out); + static void Vec4UnpackGfxColor(const GfxColor &in, vec4_t *out); +}; +} // namespace IW4 diff --git a/src/Common/Game/IW4/GameIW4.cpp b/src/Common/Game/IW4/GameIW4.cpp index 76d225217..1f960d540 100644 --- a/src/Common/Game/IW4/GameIW4.cpp +++ b/src/Common/Game/IW4/GameIW4.cpp @@ -8,36 +8,22 @@ using namespace IW4; GameIW4 g_GameIW4; -std::string GameIW4::GetFullName() -{ - return "Call Of Duty: Modern Warfare 2"; -} +std::string GameIW4::GetFullName() { return "Call Of Duty: Modern Warfare 2"; } -std::string GameIW4::GetShortName() -{ - return "IW4"; -} +std::string GameIW4::GetShortName() { return "IW4"; } -void GameIW4::AddZone(Zone* zone) -{ - m_zones.push_back(zone); -} +void GameIW4::AddZone(Zone *zone) { m_zones.push_back(zone); } -void GameIW4::RemoveZone(Zone* zone) -{ - const auto foundEntry = std::find(m_zones.begin(), m_zones.end(), zone); +void GameIW4::RemoveZone(Zone *zone) { + const auto foundEntry = std::find(m_zones.begin(), m_zones.end(), zone); - if (foundEntry != m_zones.end()) - m_zones.erase(foundEntry); + if (foundEntry != m_zones.end()) + m_zones.erase(foundEntry); } -std::vector GameIW4::GetZones() -{ - return m_zones; -} +std::vector GameIW4::GetZones() { return m_zones; } -std::vector GameIW4::GetLanguagePrefixes() -{ - std::vector prefixes; - return prefixes; +std::vector GameIW4::GetLanguagePrefixes() { + std::vector prefixes; + return prefixes; } diff --git a/src/Common/Game/IW4/GameIW4.h b/src/Common/Game/IW4/GameIW4.h index 26a9b79e2..7e0eb56ce 100644 --- a/src/Common/Game/IW4/GameIW4.h +++ b/src/Common/Game/IW4/GameIW4.h @@ -1,17 +1,16 @@ #pragma once #include "Game/IGame.h" -class GameIW4 : public IGame -{ - std::vector m_zones; +class GameIW4 : public IGame { + std::vector m_zones; public: - std::string GetFullName() override; - std::string GetShortName() override; - void AddZone(Zone* zone) override; - void RemoveZone(Zone* zone) override; - std::vector GetZones() override; - std::vector GetLanguagePrefixes() override; + std::string GetFullName() override; + std::string GetShortName() override; + void AddZone(Zone *zone) override; + void RemoveZone(Zone *zone) override; + std::vector GetZones() override; + std::vector GetLanguagePrefixes() override; }; extern GameIW4 g_GameIW4; \ No newline at end of file diff --git a/src/Common/Game/IW4/IW4.h b/src/Common/Game/IW4/IW4.h index eaf14151f..44788cfc0 100644 --- a/src/Common/Game/IW4/IW4.h +++ b/src/Common/Game/IW4/IW4.h @@ -1,125 +1,113 @@ #pragma once -//#include +// #include #include "Image/Texture.h" #include "IW4_Assets.h" -namespace IW4 -{ - struct DB_AuthHash - { - char bytes[32]; - }; - - struct DB_AuthSignature - { - char bytes[256]; - }; - - struct DB_AuthSubHeader - { - char fastfileName[32]; - unsigned int reserved; - DB_AuthHash masterBlockHashes[244]; - }; - - struct DB_AuthHeader - { - char magic[8]; // + 0 - unsigned int reserved; // + 8 - DB_AuthHash subheaderHash; // + 12 - DB_AuthSignature signedSubheaderHash; // + 44 - DB_AuthSubHeader subheader; // + 300 - }; - - struct ScriptStringList - { - int count; - const char** strings; - }; - - struct XAsset - { - XAssetType type; - XAssetHeader header; - }; - - struct XAssetList - { - ScriptStringList stringList; - int assetCount; - XAsset* assets; - }; - - struct cspField_t - { - const char* szName; - int iOffset; - int iFieldType; - }; - - enum csParseFieldType_t - { - CSPFT_STRING = 0, - CSPFT_STRING_MAX_STRING_CHARS, - CSPFT_STRING_MAX_QPATH, - CSPFT_STRING_MAX_OSPATH, - CSPFT_INT, - CSPFT_QBOOLEAN, - CSPFT_BOOL, - CSPFT_FLOAT, - CSPFT_MPH_TO_INCHES_PER_SEC, - CSPFT_MILLISECONDS, - CSPFT_FX, - CSPFT_XMODEL, - CSPFT_MATERIAL, - CSPFT_PHYS_COLLMAP, - CSPFT_SOUND, - CSPFT_TRACER, - - CSPFT_NUM_BASE_FIELD_TYPES, - }; - - enum weapFieldType_t - { - WFT_WEAPONTYPE = CSPFT_NUM_BASE_FIELD_TYPES, - WFT_WEAPONCLASS, - WFT_OVERLAYRETICLE, - WFT_PENETRATE_TYPE, - WFT_IMPACT_TYPE, - WFT_STANCE, - WFT_PROJ_EXPLOSION, - WFT_OFFHAND_CLASS, - WFT_ANIMTYPE, - WFT_ACTIVE_RETICLE_TYPE, - WFT_GUIDED_MISSILE_TYPE, - WFT_BOUNCE_SOUND, - WFT_STICKINESS, - WFT_OVERLAYINTERFACE, - WFT_INVENTORYTYPE, - WFT_FIRETYPE, - WFT_AMMOCOUNTER_CLIPTYPE, - WFT_ICONRATIO_HUD, - WFT_ICONRATIO_PICKUP, - WFT_ICONRATIO_AMMOCOUNTER, - WFT_ICONRATIO_KILL, - WFT_ICONRATIO_DPAD, - WFT_HIDETAGS, - WFT_NOTETRACKSOUNDMAP, - WFT_NOTETRACKRUMBLEMAP, - - WFT_NUM_FIELD_TYPES, - }; - - enum VehicleFieldType - { - VFT_TYPE = CSPFT_NUM_BASE_FIELD_TYPES, - VFT_AXLE_STEERING, - VFT_AXLE_POWER, - VFT_AXLE_BRAKING, - VFT_TROPHY_TAGS, - - VFT_NUM, - }; -} \ No newline at end of file +namespace IW4 { +struct DB_AuthHash { + char bytes[32]; +}; + +struct DB_AuthSignature { + char bytes[256]; +}; + +struct DB_AuthSubHeader { + char fastfileName[32]; + unsigned int reserved; + DB_AuthHash masterBlockHashes[244]; +}; + +struct DB_AuthHeader { + char magic[8]; // + 0 + unsigned int reserved; // + 8 + DB_AuthHash subheaderHash; // + 12 + DB_AuthSignature signedSubheaderHash; // + 44 + DB_AuthSubHeader subheader; // + 300 +}; + +struct ScriptStringList { + int count; + const char **strings; +}; + +struct XAsset { + XAssetType type; + XAssetHeader header; +}; + +struct XAssetList { + ScriptStringList stringList; + int assetCount; + XAsset *assets; +}; + +struct cspField_t { + const char *szName; + int iOffset; + int iFieldType; +}; + +enum csParseFieldType_t { + CSPFT_STRING = 0, + CSPFT_STRING_MAX_STRING_CHARS, + CSPFT_STRING_MAX_QPATH, + CSPFT_STRING_MAX_OSPATH, + CSPFT_INT, + CSPFT_QBOOLEAN, + CSPFT_BOOL, + CSPFT_FLOAT, + CSPFT_MPH_TO_INCHES_PER_SEC, + CSPFT_MILLISECONDS, + CSPFT_FX, + CSPFT_XMODEL, + CSPFT_MATERIAL, + CSPFT_PHYS_COLLMAP, + CSPFT_SOUND, + CSPFT_TRACER, + + CSPFT_NUM_BASE_FIELD_TYPES, +}; + +enum weapFieldType_t { + WFT_WEAPONTYPE = CSPFT_NUM_BASE_FIELD_TYPES, + WFT_WEAPONCLASS, + WFT_OVERLAYRETICLE, + WFT_PENETRATE_TYPE, + WFT_IMPACT_TYPE, + WFT_STANCE, + WFT_PROJ_EXPLOSION, + WFT_OFFHAND_CLASS, + WFT_ANIMTYPE, + WFT_ACTIVE_RETICLE_TYPE, + WFT_GUIDED_MISSILE_TYPE, + WFT_BOUNCE_SOUND, + WFT_STICKINESS, + WFT_OVERLAYINTERFACE, + WFT_INVENTORYTYPE, + WFT_FIRETYPE, + WFT_AMMOCOUNTER_CLIPTYPE, + WFT_ICONRATIO_HUD, + WFT_ICONRATIO_PICKUP, + WFT_ICONRATIO_AMMOCOUNTER, + WFT_ICONRATIO_KILL, + WFT_ICONRATIO_DPAD, + WFT_HIDETAGS, + WFT_NOTETRACKSOUNDMAP, + WFT_NOTETRACKRUMBLEMAP, + + WFT_NUM_FIELD_TYPES, +}; + +enum VehicleFieldType { + VFT_TYPE = CSPFT_NUM_BASE_FIELD_TYPES, + VFT_AXLE_STEERING, + VFT_AXLE_POWER, + VFT_AXLE_BRAKING, + VFT_TROPHY_TAGS, + + VFT_NUM, +}; +} // namespace IW4 \ No newline at end of file diff --git a/src/Common/Game/IW4/IW4_Assets.h b/src/Common/Game/IW4/IW4_Assets.h index aa8243c28..8061a21e5 100644 --- a/src/Common/Game/IW4/IW4_Assets.h +++ b/src/Common/Game/IW4/IW4_Assets.h @@ -6,4746 +6,4386 @@ #include "../../Utils/TypeAlignment.h" #ifndef __zonecodegenerator -namespace IW4 -{ +namespace IW4 { #endif - enum XAssetType - { - ASSET_TYPE_PHYSPRESET = 0x0, - ASSET_TYPE_PHYSCOLLMAP = 0x1, - ASSET_TYPE_XANIMPARTS = 0x2, - ASSET_TYPE_XMODEL_SURFS = 0x3, - ASSET_TYPE_XMODEL = 0x4, - ASSET_TYPE_MATERIAL = 0x5, - ASSET_TYPE_PIXELSHADER = 0x6, - ASSET_TYPE_VERTEXSHADER = 0x7, - ASSET_TYPE_VERTEXDECL = 0x8, - ASSET_TYPE_TECHNIQUE_SET = 0x9, - ASSET_TYPE_IMAGE = 0xA, - ASSET_TYPE_SOUND = 0xB, - ASSET_TYPE_SOUND_CURVE = 0xC, - ASSET_TYPE_LOADED_SOUND = 0xD, - ASSET_TYPE_CLIPMAP_SP = 0xE, - ASSET_TYPE_CLIPMAP_MP = 0xF, - ASSET_TYPE_COMWORLD = 0x10, - ASSET_TYPE_GAMEWORLD_SP = 0x11, - ASSET_TYPE_GAMEWORLD_MP = 0x12, - ASSET_TYPE_MAP_ENTS = 0x13, - ASSET_TYPE_FXWORLD = 0x14, - ASSET_TYPE_GFXWORLD = 0x15, - ASSET_TYPE_LIGHT_DEF = 0x16, - ASSET_TYPE_UI_MAP = 0x17, - ASSET_TYPE_FONT = 0x18, - ASSET_TYPE_MENULIST = 0x19, - ASSET_TYPE_MENU = 0x1A, - ASSET_TYPE_LOCALIZE_ENTRY = 0x1B, - ASSET_TYPE_WEAPON = 0x1C, - ASSET_TYPE_SNDDRIVER_GLOBALS = 0x1D, - ASSET_TYPE_FX = 0x1E, - ASSET_TYPE_IMPACT_FX = 0x1F, - ASSET_TYPE_AITYPE = 0x20, - ASSET_TYPE_MPTYPE = 0x21, - ASSET_TYPE_CHARACTER = 0x22, - ASSET_TYPE_XMODELALIAS = 0x23, - ASSET_TYPE_RAWFILE = 0x24, - ASSET_TYPE_STRINGTABLE = 0x25, - ASSET_TYPE_LEADERBOARD = 0x26, - ASSET_TYPE_STRUCTURED_DATA_DEF = 0x27, - ASSET_TYPE_TRACER = 0x28, - ASSET_TYPE_VEHICLE = 0x29, - ASSET_TYPE_ADDON_MAP_ENTS = 0x2A, - - ASSET_TYPE_COUNT, - ASSET_TYPE_STRING = ASSET_TYPE_COUNT, - ASSET_TYPE_ASSETLIST = 0x2C, - - ASSET_TYPE_FULLCOUNT - }; - - enum XFileBlock - { - XFILE_BLOCK_TEMP, - XFILE_BLOCK_PHYSICAL, - XFILE_BLOCK_RUNTIME, - XFILE_BLOCK_VIRTUAL, - XFILE_BLOCK_LARGE, - XFILE_BLOCK_CALLBACK, - XFILE_BLOCK_VERTEX, - XFILE_BLOCK_INDEX, - - MAX_XFILE_COUNT, - }; - - struct PhysPreset; - struct PhysCollmap; - struct XAnimParts; - struct XModel; - struct Material; - struct MaterialPixelShader; - struct MaterialVertexShader; - struct MaterialVertexDeclaration; - struct MaterialTechniqueSet; - struct GfxImage; - struct snd_alias_list_t; - struct SndCurve; - struct LoadedSound; - struct clipMap_t; - struct ComWorld; - struct GameWorldSp; - struct GameWorldMp; - struct MapEnts; - struct FxWorld; - struct GfxWorld; - struct GfxLightDef; - struct Font_s; - struct MenuList; - struct menuDef_t; - struct LocalizeEntry; - struct WeaponCompleteDef; - // struct SndDriverGlobals; - struct FxEffectDef; - struct FxImpactTable; - struct RawFile; - struct StringTable; - struct LeaderboardDef; - struct StructuredDataDefSet; - struct TracerDef; - struct VehicleDef; - struct AddonMapEnts; - - union XAssetHeader - { - PhysPreset* physPreset; - PhysCollmap* physCollmap; - XAnimParts* parts; - // XModelSurfs* modelSurfs; // NOT AN ASSET - XModel* model; - Material* material; - MaterialPixelShader* pixelShader; - MaterialVertexShader* vertexShader; - MaterialVertexDeclaration* vertexDecl; - MaterialTechniqueSet* techniqueSet; - GfxImage* image; - snd_alias_list_t* sound; - SndCurve* sndCurve; - LoadedSound* loadSnd; - clipMap_t* clipMap; - ComWorld* comWorld; - GameWorldSp* gameWorldSp; - GameWorldMp* gameWorldMp; - MapEnts* mapEnts; - FxWorld* fxWorld; - GfxWorld* gfxWorld; - GfxLightDef* lightDef; - Font_s* font; - MenuList* menuList; - menuDef_t* menu; - LocalizeEntry* localize; - WeaponCompleteDef* weapon; - // SndDriverGlobals* sndDriverGlobals; // UNUSED ON PC - FxEffectDef* fx; - FxImpactTable* impactFx; - RawFile* rawfile; - StringTable* stringTable; - LeaderboardDef* leaderboardDef; - StructuredDataDefSet* structuredDataDefSet; - TracerDef* tracerDef; - VehicleDef* vehDef; - AddonMapEnts* addonMapEnts; - void* data; - }; - - typedef tdef_align(16) char raw_byte16; - typedef tdef_align(16) float raw_float16; - typedef unsigned int raw_uint; - typedef tdef_align(128) unsigned int raw_uint128; - typedef unsigned char cbrushedge_t; - typedef unsigned short r_index_t; - typedef float vec2_t[2]; - typedef float vec3_t[3]; - typedef float vec4_t[4]; - - struct PhysPreset - { - const char* name; - int type; - float mass; - float bounce; - float friction; - float bulletForceScale; - float explosiveForceScale; - const char* sndAliasPrefix; - float piecesSpreadFraction; - float piecesUpwardVelocity; - bool tempDefaultToCylinder; - bool perSurfaceSndAlias; - }; - - struct PhysPresetInfo - { - float mass; - float bounce; - float friction; - int isFrictionInfinity; - float bulletForceScale; - float explosiveForceScale; - const char* sndAliasPrefix; - float piecesSpreadFraction; - float piecesUpwardVelocity; - int tempDefaultToCylinder; - int perSurfaceSndAlias; - }; - - struct Bounds - { - float midPoint[3]; - float halfSize[3]; - }; - - struct cplane_s - { - float normal[3]; - float dist; - char type; - char pad[3]; - }; - - struct cbrushside_t - { - cplane_s* plane; - uint16_t materialNum; - char firstAdjacentSideOffset; - char edgeCount; - }; - - struct cbrushWrapper_t - { - uint16_t numsides; - uint16_t glassPieceIndex; - cbrushside_t* sides; - cbrushedge_t* baseAdjacentSide; - int16_t axialMaterialNum[2][3]; - unsigned char firstAdjacentSideOffsets[2][3]; - unsigned char edgeCount[2][3]; - }; - - struct BrushWrapper - { - Bounds bounds; - cbrushWrapper_t brush; - int totalEdgeCount; - cplane_s* planes; - }; - - enum PhysicsGeomType - { - PHYS_GEOM_NONE = 0x0, - PHYS_GEOM_BOX = 0x1, - PHYS_GEOM_BRUSHMODEL = 0x2, - PHYS_GEOM_BRUSH = 0x3, - PHYS_GEOM_COLLMAP = 0x4, - PHYS_GEOM_CYLINDER = 0x5, - PHYS_GEOM_CAPSULE = 0x6, - PHYS_GEOM_GLASS = 0x7, - - PHYS_GEOM_COUNT, - }; - - struct PhysGeomInfo - { - BrushWrapper* brushWrapper; - int type; - float orientation[3][3]; - Bounds bounds; - }; - - struct PhysMass - { - float centerOfMass[3]; - float momentsOfInertia[3]; - float productsOfInertia[3]; - }; - - struct PhysCollmap - { - const char* name; - unsigned int count; - PhysGeomInfo* geoms; - PhysMass mass; - Bounds bounds; - }; - - union XAnimIndices - { - char* _1; - uint16_t* _2; - void* data; - }; - - struct XAnimNotifyInfo - { - uint16_t name; - float time; - }; - - typedef unsigned char ByteVec[3]; - typedef tdef_align(4) unsigned short UShortVec[3]; - - union XAnimDynamicFrames - { - ByteVec* _1; - UShortVec* _2; - }; - - union XAnimDynamicIndicesTrans - { - char _1[1]; - uint16_t _2[1]; - }; - - struct type_align(4) XAnimPartTransFrames - { - float mins[3]; - float size[3]; - XAnimDynamicFrames frames; - XAnimDynamicIndicesTrans indices; - }; - - union XAnimPartTransData - { - XAnimPartTransFrames frames; - vec3_t frame0; - }; - - struct XAnimPartTrans - { - uint16_t size; - char smallTrans; - XAnimPartTransData u; - }; - - union XAnimDynamicIndicesQuat2 - { - char _1[1]; - uint16_t _2[1]; - }; - - typedef tdef_align(4) short XQuat2[2]; - - struct type_align(4) XAnimDeltaPartQuatDataFrames2 - { - XQuat2* frames; - XAnimDynamicIndicesQuat2 indices; - }; - - union XAnimDeltaPartQuatData2 - { - XAnimDeltaPartQuatDataFrames2 frames; - int16_t frame0[2]; - }; - - struct XAnimDeltaPartQuat2 - { - uint16_t size; - XAnimDeltaPartQuatData2 u; - }; - - union XAnimDynamicIndicesQuat - { - char _1[1]; - uint16_t _2[1]; - }; - - typedef tdef_align(4) short XQuat[4]; - - struct XAnimDeltaPartQuatDataFrames - { - XQuat* frames; - XAnimDynamicIndicesQuat indices; - }; - - union XAnimDeltaPartQuatData - { - XAnimDeltaPartQuatDataFrames frames; - int16_t frame0[4]; - }; - - struct XAnimDeltaPartQuat - { - uint16_t size; - XAnimDeltaPartQuatData u; - }; - - struct XAnimDeltaPart - { - XAnimPartTrans* trans; - XAnimDeltaPartQuat2* quat2; - XAnimDeltaPartQuat* quat; - }; - - struct XAnimParts - { - const char* name; - uint16_t dataByteCount; - uint16_t dataShortCount; - uint16_t dataIntCount; - uint16_t randomDataByteCount; - uint16_t randomDataIntCount; - uint16_t numframes; - char flags; - unsigned char boneCount[10]; - char notifyCount; - char assetType; - bool isDefault; - unsigned int randomDataShortCount; - unsigned int indexCount; - float framerate; - float frequency; - uint16_t* names; - char* dataByte; - int16_t* dataShort; - int* dataInt; - int16_t* randomDataShort; - char* randomDataByte; - int* randomDataInt; - XAnimIndices indices; - XAnimNotifyInfo* notify; - XAnimDeltaPart* deltaPart; - }; - - struct DObjSkelMat - { - float axis[3][4]; - float origin[4]; - }; - - struct XSurfaceVertexInfo - { - int16_t vertCount[4]; - uint16_t* vertsBlend; - }; - - union GfxColor - { - unsigned int packed; - char array[4]; - }; - - union PackedTexCoords - { - unsigned int packed; - }; - - union PackedUnitVec - { - unsigned int packed; - char array[4]; - }; - - struct type_align(16) GfxPackedVertex - { - float xyz[3]; - float binormalSign; - GfxColor color; - PackedTexCoords texCoord; - PackedUnitVec normal; - PackedUnitVec tangent; - }; - - struct XSurfaceCollisionAabb - { - uint16_t mins[3]; - uint16_t maxs[3]; - }; - - struct type_align(16) XSurfaceCollisionNode - { - XSurfaceCollisionAabb aabb; - uint16_t childBeginIndex; - uint16_t childCount; - }; - - struct XSurfaceCollisionLeaf - { - uint16_t triangleBeginIndex; - }; - - struct XSurfaceCollisionTree - { - float trans[3]; - float scale[3]; - unsigned int nodeCount; - XSurfaceCollisionNode* nodes; - unsigned int leafCount; - XSurfaceCollisionLeaf* leafs; - }; - - struct XRigidVertList - { - uint16_t boneOffset; - uint16_t vertCount; - uint16_t triOffset; - uint16_t triCount; - XSurfaceCollisionTree* collisionTree; - }; - - typedef tdef_align(16) uint16_t r_index16_t; - - struct XSurface - { - char tileMode; - bool deformed; - uint16_t vertCount; - uint16_t triCount; - char zoneHandle; - uint16_t baseTriIndex; - uint16_t baseVertIndex; - r_index16_t (*triIndices)[3]; - XSurfaceVertexInfo vertInfo; - GfxPackedVertex* verts0; - unsigned int vertListCount; - XRigidVertList* vertList; - int partBits[6]; - }; - - struct XModelSurfs - { - const char* name; - XSurface* surfs; - uint16_t numsurfs; - int partBits[6]; - }; - - struct XModelLodInfo - { - float dist; - uint16_t numsurfs; - uint16_t surfIndex; - XModelSurfs* modelSurfs; - int partBits[6]; - XSurface* surfs; - char lod; - char smcBaseIndexPlusOne; - char smcSubIndexMask; - char smcBucket; - }; - - struct XModelCollTri_s - { - float plane[4]; - float svec[4]; - float tvec[4]; - }; - - struct XModelCollSurf_s - { - XModelCollTri_s* collTris; - int numCollTris; - Bounds bounds; - int boneIdx; - int contents; - int surfFlags; - }; - - struct XBoneInfo - { - Bounds bounds; - float radiusSquared; - }; - - struct DObjAnimMat - { - float quat[4]; - float trans[3]; - float transWeight; - }; - - struct XModel - { - const char* name; - unsigned char numBones; - unsigned char numRootBones; - unsigned char numsurfs; - char lodRampType; - float scale; - unsigned int noScalePartBits[6]; - uint16_t* boneNames; - unsigned char* parentList; - int16_t(*quats)[4]; - float(*trans)[3]; - unsigned char* partClassification; - DObjAnimMat* baseMat; - Material** materialHandles; - XModelLodInfo lodInfo[4]; - char maxLoadedLod; - unsigned char numLods; - unsigned char collLod; - char flags; - XModelCollSurf_s* collSurfs; - int numCollSurfs; - int contents; - XBoneInfo* boneInfo; - float radius; - Bounds bounds; - int memUsage; - bool bad; - PhysPreset* physPreset; - PhysCollmap* physCollmap; - }; - - struct WaterWritable - { - float floatTime; - }; - - struct complex_s - { - float real; - float imag; - }; - - struct water_t - { - WaterWritable writable; - complex_s* H0; - float* wTerm; - int M; - int N; - float Lx; - float Lz; - float gravity; - float windvel; - float winddir[2]; - float amplitude; - float codeConstant[4]; - GfxImage* image; - }; - - union MaterialTextureDefInfo - { - GfxImage* image; - water_t* water; - }; - - enum MaterialTextureFilter - { - TEXTURE_FILTER_DISABLED = 0x0, - TEXTURE_FILTER_NEAREST = 0x1, - TEXTURE_FILTER_LINEAR = 0x2, - TEXTURE_FILTER_ANISO2X = 0x3, - TEXTURE_FILTER_ANISO4X = 0x4, - - TEXTURE_FILTER_COUNT - }; - - enum SamplerStateBits_e - { - SAMPLER_FILTER_SHIFT = 0x0, - SAMPLER_FILTER_NEAREST = 0x1, - SAMPLER_FILTER_LINEAR = 0x2, - SAMPLER_FILTER_ANISO2X = 0x3, - SAMPLER_FILTER_ANISO4X = 0x4, - SAMPLER_FILTER_MASK = 0x7, - - SAMPLER_MIPMAP_SHIFT = 0x3, - SAMPLER_MIPMAP_DISABLED = 0x0, - SAMPLER_MIPMAP_NEAREST = 0x8, - SAMPLER_MIPMAP_LINEAR = 0x10, - SAMPLER_MIPMAP_COUNT = 0x3, - SAMPLER_MIPMAP_MASK = 0x18, - - SAMPLER_CLAMP_U_SHIFT = 0x5, - SAMPLER_CLAMP_V_SHIFT = 0x6, - SAMPLER_CLAMP_W_SHIFT = 0x7, - SAMPLER_CLAMP_U = 0x20, - SAMPLER_CLAMP_V = 0x40, - SAMPLER_CLAMP_W = 0x80, - SAMPLER_CLAMP_MASK = 0xE0, - }; - - struct MaterialTextureDef - { - unsigned int nameHash; - char nameStart; - char nameEnd; - unsigned char samplerState; // SamplerStateBits_e - unsigned char semantic; // TextureSemantic - MaterialTextureDefInfo u; - }; - - struct type_align(16) MaterialConstantDef - { - unsigned int nameHash; - char name[12]; - float literal[4]; - }; - - enum GfxBlend : unsigned int - { - GFXS_BLEND_DISABLED = 0x0, - GFXS_BLEND_ZERO = 0x1, - GFXS_BLEND_ONE = 0x2, - GFXS_BLEND_SRCCOLOR = 0x3, - GFXS_BLEND_INVSRCCOLOR = 0x4, - GFXS_BLEND_SRCALPHA = 0x5, - GFXS_BLEND_INVSRCALPHA = 0x6, - GFXS_BLEND_DESTALPHA = 0x7, - GFXS_BLEND_INVDESTALPHA = 0x8, - GFXS_BLEND_DESTCOLOR = 0x9, - GFXS_BLEND_INVDESTCOLOR = 0xA, - GFXS_BLEND_MASK = 0xF, - }; - - enum GfxBlendOp : unsigned int - { - GFXS_BLENDOP_DISABLED = 0x0, - GFXS_BLENDOP_ADD = 0x1, - GFXS_BLENDOP_SUBTRACT = 0x2, - GFXS_BLENDOP_REVSUBTRACT = 0x3, - GFXS_BLENDOP_MIN = 0x4, - GFXS_BLENDOP_MAX = 0x5, - GFXS_BLENDOP_MASK = 0x7, - }; - - enum GfxStencilFunc : unsigned int - { - GFXS_STENCILFUNC_NEVER = 0x0, - GFXS_STENCILFUNC_LESS = 0x1, - GFXS_STENCILFUNC_EQUAL = 0x2, - GFXS_STENCILFUNC_LESSEQUAL = 0x3, - GFXS_STENCILFUNC_GREATER = 0x4, - GFXS_STENCILFUNC_NOTEQUAL = 0x5, - GFXS_STENCILFUNC_GREATEREQUAL = 0x6, - GFXS_STENCILFUNC_ALWAYS = 0x7, - - GFXS_STENCILFUNC_COUNT, - GFXS_STENCILFUNC_MASK = 0x7 - }; - - enum GfxStencilOp : unsigned int - { - GFXS_STENCILOP_KEEP = 0x0, - GFXS_STENCILOP_ZERO = 0x1, - GFXS_STENCILOP_REPLACE = 0x2, - GFXS_STENCILOP_INCRSAT = 0x3, - GFXS_STENCILOP_DECRSAT = 0x4, - GFXS_STENCILOP_INVERT = 0x5, - GFXS_STENCILOP_INCR = 0x6, - GFXS_STENCILOP_DECR = 0x7, - - GFXS_STENCILOP_COUNT, - GFXS_STENCILOP_MASK = 0x7 - }; - - enum GfxStateBitsEnum : unsigned int - { - GFXS0_SRCBLEND_RGB_SHIFT = 0x0, - GFXS0_SRCBLEND_RGB_MASK = 0xF, - - GFXS0_DSTBLEND_RGB_SHIFT = 0x4, - GFXS0_DSTBLEND_RGB_MASK = 0xF0, - - GFXS0_BLENDOP_RGB_SHIFT = 0x8, - GFXS0_BLENDOP_RGB_MASK = 0x700, - GFXS0_BLEND_RGB_MASK = 0x7FF, - - GFXS0_ATEST_DISABLE = 0x800, - GFXS0_ATEST_GT_0 = 0x1000, - GFXS0_ATEST_LT_128 = 0x2000, - GFXS0_ATEST_GE_128 = 0x3000, - GFXS0_ATEST_MASK = 0x3000, - - GFXS0_CULL_NONE = 0x4000, - GFXS0_CULL_BACK = 0x8000, - GFXS0_CULL_FRONT = 0xC000, - GFXS0_CULL_SHIFT = 0xE, - GFXS0_CULL_MASK = 0xC000, - - GFXS0_SRCBLEND_ALPHA_SHIFT = 0x10, - GFXS0_SRCBLEND_ALPHA_MASK = 0xF0000, - - GFXS0_DSTBLEND_ALPHA_SHIFT = 0x14, - GFXS0_DSTBLEND_ALPHA_MASK = 0xF00000, - - GFXS0_BLENDOP_ALPHA_SHIFT = 0x18, - GFXS0_BLENDOP_ALPHA_MASK = 0x7000000, - GFXS0_BLEND_ALPHA_MASK = 0x7FF0000, - - GFXS0_COLORWRITE_RGB = 0x8000000, - GFXS0_COLORWRITE_ALPHA = 0x10000000, - GFXS0_COLORWRITE_MASK = 0x18000000, - - GFXS0_GAMMAWRITE = 0x40000000, - GFXS0_POLYMODE_LINE = 0x80000000, - - GFXS1_DEPTHWRITE = 0x1, - - GFXS1_DEPTHTEST_DISABLE = 0x2, - GFXS1_DEPTHTEST_ALWAYS = 0x0, - GFXS1_DEPTHTEST_LESS = 0x4, - GFXS1_DEPTHTEST_EQUAL = 0x8, - GFXS1_DEPTHTEST_LESSEQUAL = 0xC, - GFXS1_DEPTHTEST_SHIFT = 0x2, - GFXS1_DEPTHTEST_MASK = 0xC, - - GFXS1_POLYGON_OFFSET_0 = 0x0, - GFXS1_POLYGON_OFFSET_1 = 0x10, - GFXS1_POLYGON_OFFSET_2 = 0x20, - GFXS1_POLYGON_OFFSET_SHADOWMAP = 0x30, - GFXS1_POLYGON_OFFSET_SHIFT = 0x4, - GFXS1_POLYGON_OFFSET_MASK = 0x30, - - GFXS1_STENCIL_FRONT_ENABLE = 0x40, - GFXS1_STENCIL_BACK_ENABLE = 0x80, - GFXS1_STENCIL_MASK = 0xC0, - - GFXS1_STENCIL_FRONT_PASS_SHIFT = 0x8, - GFXS1_STENCIL_FRONT_PASS_MASK = 0x700, - - GFXS1_STENCIL_FRONT_FAIL_SHIFT = 0xB, - GFXS1_STENCIL_FRONT_FAIL_MASK = 0x3800, - - GFXS1_STENCIL_FRONT_ZFAIL_SHIFT = 0xE, - GFXS1_STENCIL_FRONT_ZFAIL_MASK = 0x1C000, - - GFXS1_STENCIL_FRONT_FUNC_SHIFT = 0x11, - GFXS1_STENCIL_FRONT_FUNC_MASK = 0xE0000, - GFXS1_STENCIL_FRONT_MASK = 0xFFF00, - - GFXS1_STENCIL_BACK_PASS_SHIFT = 0x14, - GFXS1_STENCIL_BACK_PASS_MASK = 0x700000, - - GFXS1_STENCIL_BACK_FAIL_SHIFT = 0x17, - GFXS1_STENCIL_BACK_FAIL_MASK = 0x3800000, - - GFXS1_STENCIL_BACK_ZFAIL_SHIFT = 0x1A, - GFXS1_STENCIL_BACK_ZFAIL_MASK = 0x1C000000, - - GFXS1_STENCIL_BACK_FUNC_SHIFT = 0x1D, - GFXS1_STENCIL_BACK_FUNC_MASK = 0xE0000000, - GFXS1_STENCIL_BACK_MASK = 0xFFF00000, - - GFXS1_STENCILFUNC_FRONTBACK_MASK = 0xE00E0000, - GFXS1_STENCILOP_FRONTBACK_MASK = 0x1FF1FF00, - }; - - struct GfxStateBits - { - unsigned int loadBits[2]; - }; - - struct infoParm_t - { - const char* name; - unsigned int clearSolid; - unsigned int surfaceFlags; - unsigned int contents; - unsigned int toolFlags; - }; - - struct gcc_align(8) GfxDrawSurfFields - { - uint64_t objectId : 16; - uint64_t reflectionProbeIndex : 8; - uint64_t hasGfxEntIndex : 1; - uint64_t customIndex : 5; - uint64_t materialSortedIndex : 12; - uint64_t prepass : 2; - uint64_t useHeroLighting : 1; - uint64_t sceneLightIndex : 8; - uint64_t surfType : 4; - uint64_t primarySortKey : 6; - uint64_t unused : 1; - }; - - union GfxDrawSurf - { - gcc_align(8) GfxDrawSurfFields fields; - gcc_align(8) uint64_t packed; - }; - - // The sort key is translated to a numeric value inside the material templates - // when converting the material. - // TODO: Try to find out which value is which sort key by investigating on materials - enum SortKey_e - { - SORTKEY_OPAQUE_AMBIENT = 0, - SORTKEY_OPAQUE = 1, - SORTKEY_SKY = 2, - SORTKEY_SKYBOX = 3, - // ? = 4, // some kind of dynamic decal? - // ? = 5, // another kind of dynamic decal? - - SORTKEY_TRANS_START = 6, - - SORTKEY_DECAL_BOTTOM_1 = 6, // prob decal - bottom 1 - SORTKEY_DECAL_BOTTOM_2 = 7, // prob decal - bottom 2 - SORTKEY_DECAL_BOTTOM_3 = 8, // prob decal - bottom 3 - SORTKEY_DECAL_STATIC_DECAL = 9, // prob decal - static decal - SORTKEY_DECAL_MIDDLE_1 = 10, // prob decal - middle 1 - SORTKEY_DECAL_MIDDLE_2 = 11, // prob decal - middle 2 - SORTKEY_DECAL_MIDDLE_3 = 12, // prob decal - middle 3 - SORTKEY_DECAL_WEAPON_IMPACT = 13, // prob decal - weapon impact - // ? = 14, // prob decal - top 1 - // some decal = 15, // prob decal - top 2 or decal - top 3 - // some decal = 16, - // prob decal = 17, - // ? = 18, - // water related = 19, // maybe underwater - // water related = 20, // maybe transparent water - // ? = 21, - // - = 22, - // - = 23, - SORTKEY_WINDOW_INSIDE = 24, // prob window inside - SORTKEY_WINDOW_OUTSIDE = 25, // prob window outside - // ? = 26, // includes motiontracker3d, impact fx, atmos - // ? = 27, - // ? = 28, - // ? = 29, - // ? = 30, - // ? = 31, - // - = 32, - // ? = 33, - // some ui/2d/fullscreen sort = 34, - // - = 35, - // - = 36, - // - = 37, - // - = 38, - // - = 39, - // - = 40, - // framecolordebug = 41, // multiplicative? - // - = 42, - SORTKEY_DISTORTION = 43, - // ? = 44, - // ? = 45, - // - = 46, - SORTKEY_BLEND_ADDITIVE = 47, // most likely blend / additive - SORTKEY_EFFECT_AUTO_SORT = 48, // most likely effect - auto sort - SORTKEY_AFTER_EFFECTS_BOTTOM = 49, - SORTKEY_AFTER_EFFECTS_MIDDLE = 50, // prob after effects - middle - SORTKEY_AFTER_EFFECTS_TOP = 51, // prob after effects - top - // - = 52, - SORTKEY_VIEWMODEL_EFFECT = 53, // maybe viewmodel effect - - SORTKEY_MAX - }; - - // Names unknown - // There's probably: MTL_GAMEFLAG_CASTS_SHADOW (part of iw3; 0x40 there) - enum MaterialGameFlags - { - MTL_GAMEFLAG_1 = 0x1, - MTL_GAMEFLAG_2 = 0x2, - MTL_GAMEFLAG_4 = 0x4, - MTL_GAMEFLAG_8 = 0x8, - MTL_GAMEFLAG_10 = 0x10, - MTL_GAMEFLAG_20 = 0x20, - MTL_GAMEFLAG_40 = 0x40, - MTL_GAMEFLAG_80 = 0x80, - }; - - struct MaterialInfo - { - const char* name; - unsigned char gameFlags; - unsigned char sortKey; // SortKey_e - unsigned char textureAtlasRowCount; - unsigned char textureAtlasColumnCount; - GfxDrawSurf drawSurf; // seems to be zeroed when loading - unsigned int surfaceTypeBits; - uint16_t hashIndex; - }; - - enum GfxCameraRegionType - { - CAMERA_REGION_LIT_OPAQUE = 0x0, - CAMERA_REGION_LIT_TRANS = 0x1, - CAMERA_REGION_EMISSIVE = 0x2, - CAMERA_REGION_DEPTH_HACK = 0x3, - - CAMERA_REGION_COUNT, - CAMERA_REGION_NONE = CAMERA_REGION_COUNT, - }; - - enum MaterialStateFlags - { - STATE_FLAG_CULL_BACK = 0x1, - STATE_FLAG_AMBIENT = 0x2, - STATE_FLAG_DECAL = 0x4, - STATE_FLAG_WRITES_DEPTH = 0x8, - STATE_FLAG_USES_DEPTH_BUFFER = 0x10, - STATE_FLAG_USES_STENCIL_BUFFER = 0x20, - STATE_FLAG_CULL_BACK_SHADOW = 0x40, - }; - - struct Material - { - MaterialInfo info; - unsigned char stateBitsEntry[48]; - unsigned char textureCount; - unsigned char constantCount; - unsigned char stateBitsCount; - unsigned char stateFlags; - unsigned char cameraRegion; // GfxCameraRegionType - MaterialTechniqueSet* techniqueSet; - MaterialTextureDef* textureTable; - MaterialConstantDef* constantTable; - GfxStateBits* stateBitsTable; - }; - - struct type_align(4) GfxImageLoadDef - { - char levelCount; - char pad[3]; - int flags; - int format; - int resourceSize; - char data[1]; - }; - - union GfxTexture - { - // IDirect3DBaseTexture9* basemap; - // IDirect3DTexture9* map; - // IDirect3DVolumeTexture9* volmap; - // IDirect3DCubeTexture9* cubemap; - Texture* texture; - GfxImageLoadDef* loadDef; - }; - - struct Picmip - { - char platform[2]; - }; - - struct CardMemory - { - int platform[2]; - }; - - enum TextureSemantic - { - TS_2D = 0x0, - TS_FUNCTION = 0x1, - TS_COLOR_MAP = 0x2, - TS_DETAIL_MAP = 0x3, - TS_UNUSED_2 = 0x4, - TS_NORMAL_MAP = 0x5, - TS_UNUSED_3 = 0x6, - TS_UNUSED_4 = 0x7, - TS_SPECULAR_MAP = 0x8, - TS_UNUSED_5 = 0x9, - TS_UNUSED_6 = 0xA, - TS_WATER_MAP = 0xB, - }; - - struct GfxImage - { - GfxTexture texture; - unsigned char mapType; - unsigned char semantic; - unsigned char category; - bool useSrgbReads; - Picmip picmip; - bool noPicmip; - char track; - CardMemory cardMemory; - uint16_t width; - uint16_t height; - uint16_t depth; - bool delayLoadPixels; - const char* name; - }; - - struct GfxPixelShaderLoadDef - { - unsigned int* program; - uint16_t programSize; - uint16_t loadForRenderer; - }; - - struct GfxVertexShaderLoadDef - { - unsigned int* program; - uint16_t programSize; - uint16_t loadForRenderer; - }; - - enum MaterialStreamStreamSource_e - { - STREAM_SRC_POSITION = 0x0, - STREAM_SRC_COLOR = 0x1, - STREAM_SRC_TEXCOORD_0 = 0x2, - STREAM_SRC_NORMAL = 0x3, - STREAM_SRC_TANGENT = 0x4, - STREAM_SRC_OPTIONAL_BEGIN = 0x5, - STREAM_SRC_PRE_OPTIONAL_BEGIN = 0x4, - STREAM_SRC_TEXCOORD_1 = 0x5, - STREAM_SRC_TEXCOORD_2 = 0x6, - STREAM_SRC_NORMAL_TRANSFORM_0 = 0x7, - STREAM_SRC_NORMAL_TRANSFORM_1 = 0x8, - - STREAM_SRC_COUNT - }; - - enum MaterialStreamDestination_e - { - STREAM_DST_POSITION = 0x0, - STREAM_DST_NORMAL = 0x1, - STREAM_DST_COLOR_0 = 0x2, - STREAM_DST_COLOR_1 = 0x3, - STREAM_DST_DEPTH = 0x4, - STREAM_DST_TEXCOORD_0 = 0x5, - STREAM_DST_TEXCOORD_1 = 0x6, - STREAM_DST_TEXCOORD_2 = 0x7, - STREAM_DST_TEXCOORD_3 = 0x8, - STREAM_DST_TEXCOORD_4 = 0x9, - STREAM_DST_TEXCOORD_5 = 0xA, - STREAM_DST_TEXCOORD_6 = 0xB, - STREAM_DST_TEXCOORD_7 = 0xC, - - STREAM_DST_COUNT - }; - - struct MaterialStreamRouting - { - unsigned char source; - unsigned char dest; - }; - - struct MaterialVertexStreamRouting - { - MaterialStreamRouting data[13]; - void/*IDirect3DVertexDeclaration9*/* decl[16]; - }; - - struct MaterialVertexDeclaration - { - const char* name; - unsigned char streamCount; - bool hasOptionalSource; - MaterialVertexStreamRouting routing; - }; - - struct MaterialVertexShaderProgram - { - void/*IDirect3DVertexShader9*/* vs; - GfxVertexShaderLoadDef loadDef; - }; - - struct MaterialVertexShader - { - const char* name; - MaterialVertexShaderProgram prog; - }; - - struct MaterialPixelShaderProgram - { - void/*IDirect3DPixelShader9*/* ps; - GfxPixelShaderLoadDef loadDef; - }; - - struct MaterialPixelShader - { - const char* name; - MaterialPixelShaderProgram prog; - }; - - enum MaterialTextureSource - { - TEXTURE_SRC_CODE_BLACK = 0x0, - TEXTURE_SRC_CODE_WHITE = 0x1, - TEXTURE_SRC_CODE_IDENTITY_NORMAL_MAP = 0x2, - TEXTURE_SRC_CODE_MODEL_LIGHTING = 0x3, - TEXTURE_SRC_CODE_LIGHTMAP_PRIMARY = 0x4, - TEXTURE_SRC_CODE_LIGHTMAP_SECONDARY = 0x5, - TEXTURE_SRC_CODE_SHADOWMAP_SUN = 0x6, - TEXTURE_SRC_CODE_SHADOWMAP_SPOT = 0x7, - TEXTURE_SRC_CODE_FEEDBACK = 0x8, - TEXTURE_SRC_CODE_RESOLVED_POST_SUN = 0x9, - TEXTURE_SRC_CODE_RESOLVED_SCENE = 0xA, - TEXTURE_SRC_CODE_POST_EFFECT_0 = 0xB, - TEXTURE_SRC_CODE_POST_EFFECT_1 = 0xC, - TEXTURE_SRC_CODE_LIGHT_ATTENUATION = 0xD, - TEXTURE_SRC_CODE_OUTDOOR = 0xE, - TEXTURE_SRC_CODE_FLOATZ = 0xF, - TEXTURE_SRC_CODE_PROCESSED_FLOATZ = 0x10, - TEXTURE_SRC_CODE_RAW_FLOATZ = 0x11, - TEXTURE_SRC_CODE_HALF_PARTICLES = 0x12, - TEXTURE_SRC_CODE_HALF_PARTICLES_Z = 0x13, - TEXTURE_SRC_CODE_CASE_TEXTURE = 0x14, - TEXTURE_SRC_CODE_CINEMATIC_Y = 0x15, - TEXTURE_SRC_CODE_CINEMATIC_CR = 0x16, - TEXTURE_SRC_CODE_CINEMATIC_CB = 0x17, - TEXTURE_SRC_CODE_CINEMATIC_A = 0x18, - TEXTURE_SRC_CODE_REFLECTION_PROBE = 0x19, - TEXTURE_SRC_CODE_ALTERNATE_SCENE = 0x1A, - - TEXTURE_SRC_CODE_COUNT - }; - - enum CustomSamplers - { - CUSTOM_SAMPLER_REFLECTION_PROBE = 0x0, - CUSTOM_SAMPLER_LIGHTMAP_PRIMARY = 0x1, - CUSTOM_SAMPLER_LIGHTMAP_SECONDARY = 0x2, - - CUSTOM_SAMPLER_COUNT - }; - - struct CodeSamplerSource - { - const char* name; - MaterialTextureSource source; - CodeSamplerSource* subtable; - int arrayCount; - int arrayStride; - }; - - enum MaterialType - { - MTL_TYPE_DEFAULT = 0x0, - MTL_TYPE_MODEL = 0x1, // m_ - MTL_TYPE_MODEL_VERTCOL = 0x2, // mc_ - MTL_TYPE_MODEL_VERTCOL_GREY = 0x3, // mg_ - MTL_TYPE_WORLD = 0x4, // w_ - MTL_TYPE_WORLD_VERTCOL = 0x5, // wc_ - - MTL_TYPE_COUNT, - }; - - struct MaterialTypeInfo - { - const char* materialPrefix; - const char* techniqueSetPrefix; - }; - - enum MaterialConstantSource - { - CONST_SRC_CODE_MAYBE_DIRTY_PS_BEGIN = 0x0, - - CONST_SRC_CODE_LIGHT_POSITION = 0x0, - CONST_SRC_CODE_LIGHT_DIFFUSE = 0x1, - CONST_SRC_CODE_LIGHT_SPECULAR = 0x2, - CONST_SRC_CODE_LIGHT_SPOTDIR = 0x3, - CONST_SRC_CODE_LIGHT_SPOTFACTORS = 0x4, - CONST_SRC_CODE_LIGHT_FALLOFF_PLACEMENT = 0x5, - CONST_SRC_CODE_PARTICLE_CLOUD_COLOR = 0x6, - CONST_SRC_CODE_GAMETIME = 0x7, - - CONST_SRC_CODE_MAYBE_DIRTY_PS_END = 0x8, - - CONST_SRC_CODE_ALWAYS_DIRTY_PS_BEGIN = 0x8, - - CONST_SRC_CODE_PIXEL_COST_FRACS = 0x8, - CONST_SRC_CODE_PIXEL_COST_DECODE = 0x9, - CONST_SRC_CODE_FILTER_TAP_0 = 0xA, - CONST_SRC_CODE_FILTER_TAP_1 = 0xB, - CONST_SRC_CODE_FILTER_TAP_2 = 0xC, - CONST_SRC_CODE_FILTER_TAP_3 = 0xD, - CONST_SRC_CODE_FILTER_TAP_4 = 0xE, - CONST_SRC_CODE_FILTER_TAP_5 = 0xF, - CONST_SRC_CODE_FILTER_TAP_6 = 0x10, - CONST_SRC_CODE_FILTER_TAP_7 = 0x11, - CONST_SRC_CODE_COLOR_MATRIX_R = 0x12, - CONST_SRC_CODE_COLOR_MATRIX_G = 0x13, - CONST_SRC_CODE_COLOR_MATRIX_B = 0x14, - CONST_SRC_CODE_SHADOWMAP_POLYGON_OFFSET = 0x15, - CONST_SRC_CODE_RENDER_TARGET_SIZE = 0x16, - - CONST_SRC_CODE_ALWAYS_DIRTY_PS_END = 0x17, - - CONST_SRC_CODE_FIXED_PS_BEGIN = 0x17, - - CONST_SRC_CODE_DOF_EQUATION_VIEWMODEL_AND_FAR_BLUR = 0x17, - CONST_SRC_CODE_DOF_EQUATION_SCENE = 0x18, - CONST_SRC_CODE_DOF_LERP_SCALE = 0x19, - CONST_SRC_CODE_DOF_LERP_BIAS = 0x1A, - CONST_SRC_CODE_DOF_ROW_DELTA = 0x1B, - CONST_SRC_CODE_MOTION_MATRIX_X = 0x1C, - CONST_SRC_CODE_MOTION_MATRIX_Y = 0x1D, - CONST_SRC_CODE_MOTION_MATRIX_W = 0x1E, - CONST_SRC_CODE_SHADOWMAP_SWITCH_PARTITION = 0x1F, - CONST_SRC_CODE_SHADOWMAP_SCALE = 0x20, - CONST_SRC_CODE_ZNEAR = 0x21, - CONST_SRC_CODE_LIGHTING_LOOKUP_SCALE = 0x22, - CONST_SRC_CODE_DEBUG_BUMPMAP = 0x23, - CONST_SRC_CODE_MATERIAL_COLOR = 0x24, - CONST_SRC_CODE_FOG = 0x25, - CONST_SRC_CODE_FOG_COLOR_LINEAR = 0x26, - CONST_SRC_CODE_FOG_COLOR_GAMMA = 0x27, - CONST_SRC_CODE_FOG_SUN_CONSTS = 0x28, - CONST_SRC_CODE_FOG_SUN_COLOR_LINEAR = 0x29, - CONST_SRC_CODE_FOG_SUN_COLOR_GAMMA = 0x2A, - CONST_SRC_CODE_FOG_SUN_DIR = 0x2B, - CONST_SRC_CODE_GLOW_SETUP = 0x2C, - CONST_SRC_CODE_GLOW_APPLY = 0x2D, - CONST_SRC_CODE_COLOR_BIAS = 0x2E, - CONST_SRC_CODE_COLOR_TINT_BASE = 0x2F, - CONST_SRC_CODE_COLOR_TINT_DELTA = 0x30, - CONST_SRC_CODE_COLOR_TINT_QUADRATIC_DELTA = 0x31, - CONST_SRC_CODE_OUTDOOR_FEATHER_PARMS = 0x32, - CONST_SRC_CODE_ENVMAP_PARMS = 0x33, - CONST_SRC_CODE_SUN_SHADOWMAP_PIXEL_ADJUST = 0x34, - CONST_SRC_CODE_SPOT_SHADOWMAP_PIXEL_ADJUST = 0x35, - CONST_SRC_CODE_COMPOSITE_FX_DISTORTION = 0x36, - CONST_SRC_CODE_POSTFX_FADE_EFFECT = 0x37, - CONST_SRC_CODE_VIEWPORT_DIMENSIONS = 0x38, - CONST_SRC_CODE_FRAMEBUFFER_READ = 0x39, - - CONST_SRC_CODE_FIXED_PS_END = 0x3A, - - CONST_SRC_CODE_NON_PS_BEGIN = 0x3A, - - CONST_SRC_CODE_BASE_LIGHTING_COORDS = 0x3A, - CONST_SRC_CODE_LIGHT_PROBE_AMBIENT = 0x3B, - CONST_SRC_CODE_NEARPLANE_ORG = 0x3C, - CONST_SRC_CODE_NEARPLANE_DX = 0x3D, - CONST_SRC_CODE_NEARPLANE_DY = 0x3E, - CONST_SRC_CODE_CLIP_SPACE_LOOKUP_SCALE = 0x3F, - CONST_SRC_CODE_CLIP_SPACE_LOOKUP_OFFSET = 0x40, - CONST_SRC_CODE_PARTICLE_CLOUD_MATRIX0 = 0x41, - CONST_SRC_CODE_PARTICLE_CLOUD_MATRIX1 = 0x42, - CONST_SRC_CODE_PARTICLE_CLOUD_MATRIX2 = 0x43, - CONST_SRC_CODE_PARTICLE_CLOUD_SPARK_COLOR0 = 0x44, - CONST_SRC_CODE_PARTICLE_CLOUD_SPARK_COLOR1 = 0x45, - CONST_SRC_CODE_PARTICLE_CLOUD_SPARK_COLOR2 = 0x46, - CONST_SRC_CODE_PARTICLE_FOUNTAIN_PARM0 = 0x47, - CONST_SRC_CODE_PARTICLE_FOUNTAIN_PARM1 = 0x48, - CONST_SRC_CODE_DEPTH_FROM_CLIP = 0x49, - CONST_SRC_CODE_CODE_MESH_ARG_0 = 0x4A, - CONST_SRC_CODE_CODE_MESH_ARG_1 = 0x4B, - - CONST_SRC_CODE_CODE_MESH_ARG_LAST = 0x4B, - CONST_SRC_CODE_NON_PS_END = 0x4C, - CONST_SRC_CODE_COUNT_FLOAT4 = 0x4C, - - CONST_SRC_FIRST_CODE_MATRIX = 0x4C, - - CONST_SRC_CODE_VIEW_MATRIX = 0x4C, - CONST_SRC_CODE_INVERSE_VIEW_MATRIX = 0x4D, - CONST_SRC_CODE_TRANSPOSE_VIEW_MATRIX = 0x4E, - CONST_SRC_CODE_INVERSE_TRANSPOSE_VIEW_MATRIX = 0x4F, - CONST_SRC_CODE_PROJECTION_MATRIX = 0x50, - CONST_SRC_CODE_INVERSE_PROJECTION_MATRIX = 0x51, - CONST_SRC_CODE_TRANSPOSE_PROJECTION_MATRIX = 0x52, - CONST_SRC_CODE_INVERSE_TRANSPOSE_PROJECTION_MATRIX = 0x53, - CONST_SRC_CODE_VIEW_PROJECTION_MATRIX = 0x54, - CONST_SRC_CODE_INVERSE_VIEW_PROJECTION_MATRIX = 0x55, - CONST_SRC_CODE_TRANSPOSE_VIEW_PROJECTION_MATRIX = 0x56, - CONST_SRC_CODE_INVERSE_TRANSPOSE_VIEW_PROJECTION_MATRIX = 0x57, - CONST_SRC_CODE_SHADOW_LOOKUP_MATRIX = 0x58, - CONST_SRC_CODE_INVERSE_SHADOW_LOOKUP_MATRIX = 0x59, - CONST_SRC_CODE_TRANSPOSE_SHADOW_LOOKUP_MATRIX = 0x5A, - CONST_SRC_CODE_INVERSE_TRANSPOSE_SHADOW_LOOKUP_MATRIX = 0x5B, - CONST_SRC_CODE_WORLD_OUTDOOR_LOOKUP_MATRIX = 0x5C, - CONST_SRC_CODE_INVERSE_WORLD_OUTDOOR_LOOKUP_MATRIX = 0x5D, - CONST_SRC_CODE_TRANSPOSE_WORLD_OUTDOOR_LOOKUP_MATRIX = 0x5E, - CONST_SRC_CODE_INVERSE_TRANSPOSE_WORLD_OUTDOOR_LOOKUP_MATRIX = 0x5F, - CONST_SRC_CODE_WORLD_MATRIX0 = 0x60, - CONST_SRC_CODE_INVERSE_WORLD_MATRIX0 = 0x61, - CONST_SRC_CODE_TRANSPOSE_WORLD_MATRIX0 = 0x62, - CONST_SRC_CODE_INVERSE_TRANSPOSE_WORLD_MATRIX0 = 0x63, - CONST_SRC_CODE_WORLD_VIEW_MATRIX0 = 0x64, - CONST_SRC_CODE_INVERSE_WORLD_VIEW_MATRIX0 = 0x65, - CONST_SRC_CODE_TRANSPOSE_WORLD_VIEW_MATRIX0 = 0x66, - CONST_SRC_CODE_INVERSE_TRANSPOSE_WORLD_VIEW_MATRIX0 = 0x67, - CONST_SRC_CODE_WORLD_VIEW_PROJECTION_MATRIX0 = 0x68, - CONST_SRC_CODE_INVERSE_WORLD_VIEW_PROJECTION_MATRIX0 = 0x69, - CONST_SRC_CODE_TRANSPOSE_WORLD_VIEW_PROJECTION_MATRIX0 = 0x6A, - CONST_SRC_CODE_INVERSE_TRANSPOSE_WORLD_VIEW_PROJECTION_MATRIX0 = 0x6B, - CONST_SRC_CODE_WORLD_MATRIX1 = 0x6C, - CONST_SRC_CODE_INVERSE_WORLD_MATRIX1 = 0x6D, - CONST_SRC_CODE_TRANSPOSE_WORLD_MATRIX1 = 0x6E, - CONST_SRC_CODE_INVERSE_TRANSPOSE_WORLD_MATRIX1 = 0x6F, - CONST_SRC_CODE_WORLD_VIEW_MATRIX1 = 0x70, - CONST_SRC_CODE_INVERSE_WORLD_VIEW_MATRIX1 = 0x71, - CONST_SRC_CODE_TRANSPOSE_WORLD_VIEW_MATRIX1 = 0x72, - CONST_SRC_CODE_INVERSE_TRANSPOSE_WORLD_VIEW_MATRIX1 = 0x73, - CONST_SRC_CODE_WORLD_VIEW_PROJECTION_MATRIX1 = 0x74, - CONST_SRC_CODE_INVERSE_WORLD_VIEW_PROJECTION_MATRIX1 = 0x75, - CONST_SRC_CODE_TRANSPOSE_WORLD_VIEW_PROJECTION_MATRIX1 = 0x76, - CONST_SRC_CODE_INVERSE_TRANSPOSE_WORLD_VIEW_PROJECTION_MATRIX1 = 0x77, - CONST_SRC_CODE_WORLD_MATRIX2 = 0x78, - CONST_SRC_CODE_INVERSE_WORLD_MATRIX2 = 0x79, - CONST_SRC_CODE_TRANSPOSE_WORLD_MATRIX2 = 0x7A, - CONST_SRC_CODE_INVERSE_TRANSPOSE_WORLD_MATRIX2 = 0x7B, - CONST_SRC_CODE_WORLD_VIEW_MATRIX2 = 0x7C, - CONST_SRC_CODE_INVERSE_WORLD_VIEW_MATRIX2 = 0x7D, - CONST_SRC_CODE_TRANSPOSE_WORLD_VIEW_MATRIX2 = 0x7E, - CONST_SRC_CODE_INVERSE_TRANSPOSE_WORLD_VIEW_MATRIX2 = 0x7F, - CONST_SRC_CODE_WORLD_VIEW_PROJECTION_MATRIX2 = 0x80, - CONST_SRC_CODE_INVERSE_WORLD_VIEW_PROJECTION_MATRIX2 = 0x81, - CONST_SRC_CODE_TRANSPOSE_WORLD_VIEW_PROJECTION_MATRIX2 = 0x82, - CONST_SRC_CODE_INVERSE_TRANSPOSE_WORLD_VIEW_PROJECTION_MATRIX2 = 0x83, - - CONST_SRC_TOTAL_COUNT, - CONST_SRC_NONE - }; - - struct CodeConstantSource - { - const char* name; - MaterialConstantSource source; - CodeConstantSource* subtable; - int arrayCount; - int arrayStride; - }; - - struct MaterialArgumentCodeConst - { - uint16_t index; - unsigned char firstRow; - unsigned char rowCount; - }; - - union MaterialArgumentDef - { - const float (*literalConst)[4]; - MaterialArgumentCodeConst codeConst; - unsigned int codeSampler; - unsigned int nameHash; - }; - - enum MaterialShaderArgumentType - { - MTL_ARG_MATERIAL_VERTEX_CONST = 0x0, // stable - MTL_ARG_LITERAL_VERTEX_CONST = 0x1, // stable - MTL_ARG_MATERIAL_PIXEL_SAMPLER = 0x2, // stable - - MTL_ARG_CODE_PRIM_BEGIN = 0x3, - - MTL_ARG_CODE_VERTEX_CONST = 0x3, // stable object prim - MTL_ARG_CODE_PIXEL_SAMPLER = 0x4, // stable object - MTL_ARG_CODE_PIXEL_CONST = 0x5, // stable - - MTL_ARG_CODE_PRIM_END = 0x6, - - MTL_ARG_MATERIAL_PIXEL_CONST = 0x6, // stable - MTL_ARG_LITERAL_PIXEL_CONST = 0x7, // stable - - MTL_ARG_COUNT - }; - - enum MaterialUpdateFrequency - { - MTL_UPDATE_PER_PRIM = 0x0, - MTL_UPDATE_PER_OBJECT = 0x1, - MTL_UPDATE_RARELY = 0x2, - MTL_UPDATE_CUSTOM = 0x3, - }; - - struct MaterialShaderArgument - { - uint16_t type; - uint16_t dest; - MaterialArgumentDef u; - }; - - struct MaterialPass - { - MaterialVertexDeclaration* vertexDecl; - MaterialVertexShader* vertexShader; - MaterialPixelShader* pixelShader; - unsigned char perPrimArgCount; - unsigned char perObjArgCount; - unsigned char stableArgCount; - unsigned char customSamplerFlags; - MaterialShaderArgument* args; - }; - - enum TechniqueFlags - { - // Guesses purely based on data analysis: - TECHNIQUE_FLAG_1 = 0x1, // uses resolvedPostSun code sampler // MTL_TECHFLAG_NEEDS_RESOLVED_POST_SUN - TECHNIQUE_FLAG_2 = 0x2, // uses resolvedScene code sampler MTL_TECHFLAG_NEEDS_RESOLVED_SCENE - TECHNIQUE_FLAG_4 = 0x4, // zprepass only - TECHNIQUE_FLAG_8 = 0x8, // build_floatz only - TECHNIQUE_FLAG_10 = 0x10, // build_shadowmap_depth + build_shadowmap_model only - TECHNIQUE_FLAG_20 = 0x20, // techniques with _i_ in its name (all use texcoord[1] in decl -> other optional stream sources are not used at all so might be any optional) - TECHNIQUE_FLAG_40 = 0x40, // uses code constant light.spotDir or light.spotFactors - TECHNIQUE_FLAG_80 = 0x80, // uses floatZ sampler and does not have 0x100 flag - TECHNIQUE_FLAG_100 = 0x100, // distortion_scale_zfeather_dtex + distortion_scale_ua_zfeather + distortion_scale_zfeather - TECHNIQUE_FLAG_200 = 0x200, // ? - }; - - struct MaterialTechnique - { - const char* name; - uint16_t flags; - uint16_t passCount; - MaterialPass passArray[1]; - }; - - enum MaterialTechniqueType - { - TECHNIQUE_DEPTH_PREPASS = 0x0, - TECHNIQUE_BUILD_FLOAT_Z = 0x1, - TECHNIQUE_BUILD_SHADOWMAP_DEPTH = 0x2, - TECHNIQUE_BUILD_SHADOWMAP_COLOR = 0x3, - TECHNIQUE_UNLIT = 0x4, - TECHNIQUE_EMISSIVE = 0x5, - TECHNIQUE_EMISSIVE_DFOG = 0x6, - TECHNIQUE_EMISSIVE_SHADOW = 0x7, - TECHNIQUE_EMISSIVE_SHADOW_DFOG = 0x8, - - TECHNIQUE_LIT_BEGIN = 0x9, - - TECHNIQUE_LIT = 0x9, - TECHNIQUE_LIT_DFOG = 0xA, - TECHNIQUE_LIT_SUN = 0xB, - TECHNIQUE_LIT_SUN_DFOG = 0xC, - TECHNIQUE_LIT_SUN_SHADOW = 0xD, - TECHNIQUE_LIT_SUN_SHADOW_DFOG = 0xE, - TECHNIQUE_LIT_SPOT = 0xF, - TECHNIQUE_LIT_SPOT_DFOG = 0x10, - TECHNIQUE_LIT_SPOT_SHADOW = 0x11, - TECHNIQUE_LIT_SPOT_SHADOW_DFOG = 0x12, - TECHNIQUE_LIT_OMNI = 0x13, - TECHNIQUE_LIT_OMNI_DFOG = 0x14, - TECHNIQUE_LIT_OMNI_SHADOW = 0x15, - TECHNIQUE_LIT_OMNI_SHADOW_DFOG = 0x16, - TECHNIQUE_LIT_INSTANCED = 0x17, - TECHNIQUE_LIT_INSTANCED_DFOG = 0x18, - TECHNIQUE_LIT_INSTANCED_SUN = 0x19, - TECHNIQUE_LIT_INSTANCED_SUN_DFOG = 0x1A, - TECHNIQUE_LIT_INSTANCED_SUN_SHADOW = 0x1B, - TECHNIQUE_LIT_INSTANCED_SUN_SHADOW_DFOG = 0x1C, - TECHNIQUE_LIT_INSTANCED_SPOT = 0x1D, - TECHNIQUE_LIT_INSTANCED_SPOT_DFOG = 0x1E, - TECHNIQUE_LIT_INSTANCED_SPOT_SHADOW = 0x1F, - TECHNIQUE_LIT_INSTANCED_SPOT_SHADOW_DFOG = 0x20, - TECHNIQUE_LIT_INSTANCED_OMNI = 0x21, - TECHNIQUE_LIT_INSTANCED_OMNI_DFOG = 0x22, - TECHNIQUE_LIT_INSTANCED_OMNI_SHADOW = 0x23, - TECHNIQUE_LIT_INSTANCED_OMNI_SHADOW_DFOG = 0x24, - - TECHNIQUE_LIT_END = 0x25, - - TECHNIQUE_LIGHT_SPOT = 0x25, - TECHNIQUE_LIGHT_OMNI = 0x26, - TECHNIQUE_LIGHT_SPOT_SHADOW = 0x27, - TECHNIQUE_FAKELIGHT_NORMAL = 0x28, - TECHNIQUE_FAKELIGHT_VIEW = 0x29, - TECHNIQUE_SUNLIGHT_PREVIEW = 0x2A, - TECHNIQUE_CASE_TEXTURE = 0x2B, - TECHNIQUE_WIREFRAME_SOLID = 0x2C, - TECHNIQUE_WIREFRAME_SHADED = 0x2D, - TECHNIQUE_DEBUG_BUMPMAP = 0x2E, - TECHNIQUE_DEBUG_BUMPMAP_INSTANCED = 0x2F, - - TECHNIQUE_COUNT - }; - - struct MaterialTechniqueSet - { - const char* name; - unsigned char worldVertFormat; - bool hasBeenUploaded; - unsigned char unused[1]; - MaterialTechniqueSet* remappedTechniqueSet; - MaterialTechnique* techniques[48]; - }; - - union RawFileBuffer - { - const char* compressedBuffer; - const char* buffer; - }; - - struct RawFile - { - const char* name; - int compressedLen; - int len; - RawFileBuffer data; - }; - - struct StringTableCell - { - const char* string; - int hash; - }; - - struct StringTable - { - const char* name; - int columnCount; - int rowCount; - StringTableCell* values; - }; - - struct AILSOUNDINFO - { - int format; - const void* data_ptr; - unsigned int data_len; - unsigned int rate; - int bits; - int channels; - unsigned int samples; - unsigned int block_size; - const void* initial_ptr; - }; - - struct MssSound - { - AILSOUNDINFO info; - char* data; - }; - - struct LoadedSound - { - const char* name; - MssSound sound; - }; - - struct StreamedSound - { - const char* dir; - const char* name; - }; - - union SoundFileRef - { - LoadedSound* loadSnd; - StreamedSound streamSnd; - }; - - enum snd_alias_type_t : char - { - SAT_UNKNOWN = 0x0, - SAT_LOADED = 0x1, - SAT_STREAMED = 0x2, - SAT_VOICED = 0x3, - SAT_COUNT, - }; - - struct SoundFile - { - snd_alias_type_t type; - char exists; - SoundFileRef u; - }; - - struct MSSSpeakerLevels - { - int speaker; - int numLevels; - float levels[2]; - }; - - struct MSSChannelMap - { - int speakerCount; - MSSSpeakerLevels speakers[6]; - }; - - struct SpeakerMap - { - bool isDefault; - const char* name; - MSSChannelMap channelMaps[2][2]; - }; - - struct snd_alias_t - { - const char* aliasName; - const char* subtitle; - const char* secondaryAliasName; - const char* chainAliasName; - const char* mixerGroup; - SoundFile* soundFile; - int sequence; - float volMin; - float volMax; - float pitchMin; - float pitchMax; - float distMin; - float distMax; - float velocityMin; - int flags; - - union - { - float slavePercentage; - float masterPercentage; - }; - - float probability; - float lfePercentage; - float centerPercentage; - int startDelay; - SndCurve* volumeFalloffCurve; - float envelopMin; - float envelopMax; - float envelopPercentage; - SpeakerMap* speakerMap; - }; - - struct snd_alias_list_t - { - const char* aliasName; - snd_alias_t* head; - int count; - }; - - struct SndCurve - { - const char* filename; - uint16_t knotCount; - float knots[16][2]; - }; - - struct LocalizeEntry - { - const char* value; - const char* name; - }; - - struct StringList - { - int totalStrings; - const char** strings; - }; - - union DvarLimits - { - struct - { - int stringCount; - const char** strings; - } enumeration; - - struct - { - int min; - int max; - } integer; - - struct - { - float min; - float max; - } value; - - struct - { - float min; - float max; - } vector; - }; - - union DvarValue - { - bool enabled; - int integer; - unsigned int unsignedInt; - float value; - float vector[4]; - const char* string; - char color[4]; - }; - - struct dvar_t - { - const char* name; - const char* description; - unsigned int flags; - char type; - bool modified; - DvarValue current; - DvarValue latched; - DvarValue reset; - DvarLimits domain; - //bool (__cdecl* domainFunc)(dvar_t*, DvarValue); - void* domainFunc; - dvar_t* hashNext; - }; - - struct StaticDvar - { - dvar_t* dvar; - char* dvarName; - }; - - struct StaticDvarList - { - int numStaticDvars; - StaticDvar** staticDvars; - }; - - struct ExpressionString - { - const char* string; - }; - - struct Statement_s; - - union operandInternalDataUnion - { - int intVal; - float floatVal; - ExpressionString stringVal; - Statement_s* function; - }; - - enum expDataType - { - VAL_INT = 0x0, - VAL_FLOAT = 0x1, - VAL_STRING = 0x2, - VAL_FUNCTION = 0x3, - - NUM_DATATYPES, - }; - - struct Operand - { - expDataType dataType; - operandInternalDataUnion internals; - }; - - enum expressionOperatorType_e - { - OP_NOOP = 0x0, - OP_RIGHTPAREN = 0x1, - OP_MULTIPLY = 0x2, - OP_DIVIDE = 0x3, - OP_MODULUS = 0x4, - OP_ADD = 0x5, - OP_SUBTRACT = 0x6, - OP_NOT = 0x7, - OP_LESSTHAN = 0x8, - OP_LESSTHANEQUALTO = 0x9, - OP_GREATERTHAN = 0xA, - OP_GREATERTHANEQUALTO = 0xB, - OP_EQUALS = 0xC, - OP_NOTEQUAL = 0xD, - OP_AND = 0xE, - OP_OR = 0xF, - OP_LEFTPAREN = 0x10, - OP_COMMA = 0x11, - OP_BITWISEAND = 0x12, - OP_BITWISEOR = 0x13, - OP_BITWISENOT = 0x14, - OP_BITSHIFTLEFT = 0x15, - OP_BITSHIFTRIGHT = 0x16, - - OP_COUNT - }; - - enum expressionFunction_e - { - EXP_FUNC_STATIC_DVAR_INT = OP_COUNT, - EXP_FUNC_STATIC_DVAR_BOOL, - EXP_FUNC_STATIC_DVAR_FLOAT, - EXP_FUNC_STATIC_DVAR_STRING, - - EXP_FUNC_DYN_START, - - EXP_FUNC_INT = EXP_FUNC_DYN_START, - EXP_FUNC_STRING, - EXP_FUNC_FLOAT, - EXP_FUNC_SIN, - EXP_FUNC_COS, - EXP_FUNC_MIN, - EXP_FUNC_MAX, - EXP_FUNC_MILLISECONDS, - EXP_FUNC_DVAR_INT, - EXP_FUNC_DVAR_BOOL, - EXP_FUNC_DVAR_FLOAT, - EXP_FUNC_DVAR_STRING - }; - - union entryInternalData - { - int op; - Operand operand; - }; - - enum expressionEntryType : int - { - EET_OPERATOR = 0x0, - EET_OPERAND = 0x1, - }; - - struct expressionEntry - { - expressionEntryType type; - entryInternalData data; - }; - - struct ExpressionSupportingData; - - struct Statement_s - { - int numEntries; - expressionEntry* entries; - ExpressionSupportingData* supportingData; - int lastExecuteTime; - Operand lastResult; - }; - - struct UIFunctionList - { - int totalFunctions; - Statement_s** functions; - }; - - struct ExpressionSupportingData - { - UIFunctionList uifunctions; - StaticDvarList staticDvarList; - StringList uiStrings; - }; - - struct menuTransition - { - int transitionType; - int targetField; - int startTime; - float startVal; - float endVal; - float time; - int endTriggerType; - }; - - enum ItemFloatExpressionTarget - { - ITEM_FLOATEXP_TGT_RECT_X = 0x0, - ITEM_FLOATEXP_TGT_RECT_Y = 0x1, - ITEM_FLOATEXP_TGT_RECT_W = 0x2, - ITEM_FLOATEXP_TGT_RECT_H = 0x3, - ITEM_FLOATEXP_TGT_FORECOLOR_R = 0x4, - ITEM_FLOATEXP_TGT_FORECOLOR_G = 0x5, - ITEM_FLOATEXP_TGT_FORECOLOR_B = 0x6, - ITEM_FLOATEXP_TGT_FORECOLOR_RGB = 0x7, - ITEM_FLOATEXP_TGT_FORECOLOR_A = 0x8, - ITEM_FLOATEXP_TGT_GLOWCOLOR_R = 0x9, - ITEM_FLOATEXP_TGT_GLOWCOLOR_G = 0xA, - ITEM_FLOATEXP_TGT_GLOWCOLOR_B = 0xB, - ITEM_FLOATEXP_TGT_GLOWCOLOR_RGB = 0xC, - ITEM_FLOATEXP_TGT_GLOWCOLOR_A = 0xD, - ITEM_FLOATEXP_TGT_BACKCOLOR_R = 0xE, - ITEM_FLOATEXP_TGT_BACKCOLOR_G = 0xF, - ITEM_FLOATEXP_TGT_BACKCOLOR_B = 0x10, - ITEM_FLOATEXP_TGT_BACKCOLOR_RGB = 0x11, - ITEM_FLOATEXP_TGT_BACKCOLOR_A = 0x12, - - ITEM_FLOATEXP_TGT_COUNT - }; - - struct ItemExpressionTargetBinding - { - int target; - const char* name; - const char* componentName; - }; - - struct ItemFloatExpression - { - int target; - Statement_s* expression; - }; - - struct columnInfo_s - { - int pos; - int width; - int maxChars; - int alignment; - }; - - struct MenuEventHandlerSet; - - struct ConditionalScript - { - MenuEventHandlerSet* eventHandlerSet; - Statement_s* eventExpression; - }; - - struct SetLocalVarData - { - const char* localVarName; - Statement_s* expression; - }; - - union EventData - { - const char* unconditionalScript; - ConditionalScript* conditionalScript; - MenuEventHandlerSet* elseScript; - SetLocalVarData* setLocalVarData; - }; - - enum EventType : unsigned char - { - EVENT_UNCONDITIONAL = 0x0, - EVENT_IF = 0x1, - EVENT_ELSE = 0x2, - EVENT_SET_LOCAL_VAR_BOOL = 0x3, - EVENT_SET_LOCAL_VAR_INT = 0x4, - EVENT_SET_LOCAL_VAR_FLOAT = 0x5, - EVENT_SET_LOCAL_VAR_STRING = 0x6, - - EVENT_COUNT, - }; - - struct MenuEventHandler - { - EventData eventData; - EventType eventType; - }; - - struct MenuEventHandlerSet - { - int eventHandlerCount; - MenuEventHandler** eventHandlers; - }; - - struct listBoxDef_s - { - int mousePos; - int startPos[1]; - int endPos[1]; - int drawPadding; - float elementWidth; - float elementHeight; - int elementStyle; - int numColumns; - columnInfo_s columnInfo[16]; - MenuEventHandlerSet* onDoubleClick; - int notselectable; - int noScrollBars; - int usePaging; - float selectBorder[4]; - Material* selectIcon; - }; - - struct editFieldDef_s - { - float minVal; - float maxVal; - float defVal; - float range; - int maxChars; - int maxCharsGotoNext; - int maxPaintChars; - int paintOffset; - }; - - struct multiDef_s - { - const char* dvarList[32]; - const char* dvarStr[32]; - float dvarValue[32]; - int count; - int strDef; - }; - - struct newsTickerDef_s - { - int feedId; - int speed; - int spacing; - int lastTime; - int start; - int end; - float x; - }; - - struct textScrollDef_s - { - int startTime; - }; - - union itemDefData_t - { - listBoxDef_s* listBox; - editFieldDef_s* editField; - multiDef_s* multi; - const char* enumDvarName; - newsTickerDef_s* ticker; - textScrollDef_s* scroll; - void* data; - }; - - struct ItemKeyHandler - { - int key; - MenuEventHandlerSet* action; - ItemKeyHandler* next; - }; - - struct rectDef_s - { - float x; - float y; - float w; - float h; - unsigned char horzAlign; - unsigned char vertAlign; - }; - - enum WindowDefStaticFlag : unsigned int - { - WINDOW_FLAG_DECORATION = 0x100000, - WINDOW_FLAG_HORIZONTAL_SCROLL = 0x200000, - WINDOW_FLAG_OUT_OF_BOUNDS_CLICK = 0x2000000, - WINDOW_FLAG_SCREEN_SPACE = 0x400000, - WINDOW_FLAG_AUTO_WRAPPED = 0x800000, - WINDOW_FLAG_POPUP = 0x1000000, - WINDOW_FLAG_LEGACY_SPLIT_SCREEN_SCALE = 0x4000000, - WINDOW_FLAG_HIDDEN_DURING_FLASH_BANG = 0x10000000, - WINDOW_FLAG_HIDDEN_DURING_SCOPE = 0x20000000, - WINDOW_FLAG_HIDDEN_DURING_UI = 0x40000000, - WINDOW_FLAG_TEXT_ONLY_FOCUS = 0x80000000, - }; - - enum WindowDefDynamicFlag : unsigned int - { - WINDOW_FLAG_HOVERED = 0x1, // guessed - WINDOW_FLAG_FOCUSED = 0x2, - WINDOW_FLAG_VISIBLE = 0x4, - WINDOW_FLAG_FADING_OUT = 0x10, - WINDOW_FLAG_FADING_IN = 0x20, - WINDOW_FLAG_80 = 0x80, - WINDOW_FLAG_NON_DEFAULT_BACKCOLOR = 0x8000, - WINDOW_FLAG_NON_DEFAULT_FORECOLOR = 0x10000 - }; - - struct windowDef_t - { - const char* name; - rectDef_s rect; - rectDef_s rectClient; - const char* group; - int style; - int border; - int ownerDraw; - int ownerDrawFlags; - float borderSize; - int staticFlags; - unsigned int dynamicFlags[1]; - int nextTime; - float foreColor[4]; - float backColor[4]; - float borderColor[4]; - float outlineColor[4]; - float disableColor[4]; - Material* background; - }; - - enum ItemDefFlag : unsigned int - { - ITEM_FLAG_SAVE_GAME_INFO = 0x1, - ITEM_FLAG_CINEMATIC_SUBTITLE = 0x2, - }; - - enum ItemDefDvarFlag - { - ITEM_DVAR_FLAG_ENABLE = 0x1, - ITEM_DVAR_FLAG_DISABLE = 0x2, - ITEM_DVAR_FLAG_SHOW = 0x4, - ITEM_DVAR_FLAG_HIDE = 0x8, - ITEM_DVAR_FLAG_FOCUS = 0x10, - }; - - enum ItemDefType - { - ITEM_TYPE_TEXT = 0x0, - ITEM_TYPE_BUTTON = 0x1, - ITEM_TYPE_RADIOBUTTON = 0x2, - ITEM_TYPE_CHECKBOX = 0x3, - ITEM_TYPE_EDITFIELD = 0x4, - ITEM_TYPE_COMBO = 0x5, - ITEM_TYPE_LISTBOX = 0x6, - ITEM_TYPE_MODEL = 0x7, - ITEM_TYPE_OWNERDRAW = 0x8, - ITEM_TYPE_NUMERICFIELD = 0x9, - ITEM_TYPE_SLIDER = 0xA, - ITEM_TYPE_YESNO = 0xB, - ITEM_TYPE_MULTI = 0xC, - ITEM_TYPE_DVARENUM = 0xD, - ITEM_TYPE_BIND = 0xE, - ITEM_TYPE_MENUMODEL = 0xF, - ITEM_TYPE_VALIDFILEFIELD = 0x10, - ITEM_TYPE_DECIMALFIELD = 0x11, - ITEM_TYPE_UPREDITFIELD = 0x12, - ITEM_TYPE_GAME_MESSAGE_WINDOW = 0x13, - ITEM_TYPE_NEWS_TICKER = 0x14, - ITEM_TYPE_TEXT_SCROLL = 0x15, - ITEM_TYPE_EMAILFIELD = 0x16, - ITEM_TYPE_PASSWORDFIELD = 0x17 - }; - - struct itemDef_s - { - windowDef_t window; - rectDef_s textRect[1]; - int type; - int dataType; - int alignment; - int fontEnum; - int textAlignMode; - float textalignx; - float textaligny; - float textscale; - int textStyle; - int gameMsgWindowIndex; - int gameMsgWindowMode; - const char* text; - int itemFlags; - menuDef_t* parent; - MenuEventHandlerSet* mouseEnterText; - MenuEventHandlerSet* mouseExitText; - MenuEventHandlerSet* mouseEnter; - MenuEventHandlerSet* mouseExit; - MenuEventHandlerSet* action; - MenuEventHandlerSet* accept; - MenuEventHandlerSet* onFocus; - MenuEventHandlerSet* leaveFocus; - const char* dvar; - const char* dvarTest; - ItemKeyHandler* onKey; - const char* enableDvar; - const char* localVar; - int dvarFlags; - snd_alias_list_t* focusSound; - float special; - int cursorPos[1]; - itemDefData_t typeData; - int imageTrack; - int floatExpressionCount; - ItemFloatExpression* floatExpressions; - Statement_s* visibleExp; - Statement_s* disabledExp; - Statement_s* textExp; - Statement_s* materialExp; - float glowColor[4]; - bool decayActive; - int fxBirthTime; - int fxLetterTime; - int fxDecayStartTime; - int fxDecayDuration; - int lastSoundPlayedTime; - }; - - struct menuDef_t - { - windowDef_t window; - const char* font; - int fullScreen; - int itemCount; - int fontIndex; - int cursorItem[1]; - int fadeCycle; - float fadeClamp; - float fadeAmount; - float fadeInAmount; - float blurRadius; - MenuEventHandlerSet* onOpen; - MenuEventHandlerSet* onCloseRequest; - MenuEventHandlerSet* onClose; - MenuEventHandlerSet* onESC; - ItemKeyHandler* onKey; - Statement_s* visibleExp; - const char* allowedBinding; - const char* soundName; - int imageTrack; - float focusColor[4]; - Statement_s* rectXExp; - Statement_s* rectYExp; - Statement_s* rectWExp; - Statement_s* rectHExp; - Statement_s* openSoundExp; - Statement_s* closeSoundExp; - itemDef_s** items; - menuTransition scaleTransition[1]; - menuTransition alphaTransition[1]; - menuTransition xTransition[1]; - menuTransition yTransition[1]; - ExpressionSupportingData* expressionData; - }; - - struct MenuList - { - const char* name; - int menuCount; - menuDef_t** menus; - }; - - enum FxElemType - { - FX_ELEM_TYPE_SPRITE_BILLBOARD = 0x0, - FX_ELEM_TYPE_SPRITE_ORIENTED = 0x1, - FX_ELEM_TYPE_TAIL = 0x2, - FX_ELEM_TYPE_TRAIL = 0x3, - FX_ELEM_TYPE_CLOUD = 0x4, - FX_ELEM_TYPE_SPARK_CLOUD = 0x5, - FX_ELEM_TYPE_SPARK_FOUNTAIN = 0x6, - FX_ELEM_TYPE_MODEL = 0x7, - FX_ELEM_TYPE_OMNI_LIGHT = 0x8, - FX_ELEM_TYPE_SPOT_LIGHT = 0x9, - FX_ELEM_TYPE_SOUND = 0xA, - FX_ELEM_TYPE_DECAL = 0xB, - FX_ELEM_TYPE_RUNNER = 0xC, - FX_ELEM_TYPE_COUNT = 0xD, - FX_ELEM_TYPE_LAST_SPRITE = 0x3, - FX_ELEM_TYPE_LAST_DRAWN = 0x9, - }; - - struct FxIntRange - { - int base; - int amplitude; - }; - - struct FxSpawnDefOneShot - { - FxIntRange count; - }; - - struct FxSpawnDefLooping - { - int intervalMsec; - int count; - }; - - union FxSpawnDef - { - FxSpawnDefLooping looping; - FxSpawnDefOneShot oneShot; - }; - - struct FxFloatRange - { - float base; - float amplitude; - }; - - struct FxElemAtlas - { - char behavior; - char index; - char fps; - char loopCount; - char colIndexBits; - char rowIndexBits; - int16_t entryCount; - }; - - struct FxElemVec3Range - { - float base[3]; - float amplitude[3]; - }; - - struct FxElemVelStateInFrame - { - FxElemVec3Range velocity; - FxElemVec3Range totalDelta; - }; - - struct FxElemVelStateSample - { - FxElemVelStateInFrame local; - FxElemVelStateInFrame world; - }; - - struct FxElemVisualState - { - char color[4]; - float rotationDelta; - float rotationTotal; - float size[2]; - float scale; - }; - - struct FxElemVisStateSample - { - FxElemVisualState base; - FxElemVisualState amplitude; - }; - - union FxEffectDefRef - { - FxEffectDef* handle; - const char* name; - }; - - union FxElemVisuals - { - const void* anonymous; - Material* material; - XModel* model; - FxEffectDefRef effectDef; - const char* soundName; - }; - - struct FxElemMarkVisuals - { - Material* materials[2]; - }; - - union FxElemDefVisuals - { - FxElemMarkVisuals* markArray; - FxElemVisuals* array; - FxElemVisuals instance; - }; - - struct FxTrailVertex - { - float pos[2]; - float normal[2]; - float texCoord; - }; - - struct FxTrailDef - { - int scrollTimeMsec; - int repeatDist; - float invSplitDist; - float invSplitArcDist; - float invSplitTime; - int vertCount; - FxTrailVertex* verts; - int indCount; - uint16_t* inds; - }; - - struct FxSparkFountainDef - { - float gravity; - float bounceFrac; - float bounceRand; - float sparkSpacing; - float sparkLength; - int sparkCount; - float loopTime; - float velMin; - float velMax; - float velConeFrac; - float restSpeed; - float boostTime; - float boostFactor; - }; - - union FxElemExtendedDefPtr - { - FxTrailDef* trailDef; - FxSparkFountainDef* sparkFountainDef; - char* unknownDef; - }; - - struct FxElemDef - { - int flags; - FxSpawnDef spawn; - FxFloatRange spawnRange; - FxFloatRange fadeInRange; - FxFloatRange fadeOutRange; - float spawnFrustumCullRadius; - FxIntRange spawnDelayMsec; - FxIntRange lifeSpanMsec; - FxFloatRange spawnOrigin[3]; - FxFloatRange spawnOffsetRadius; - FxFloatRange spawnOffsetHeight; - FxFloatRange spawnAngles[3]; - FxFloatRange angularVelocity[3]; - FxFloatRange initialRotation; - FxFloatRange gravity; - FxFloatRange reflectionFactor; - FxElemAtlas atlas; - char elemType; - char visualCount; - char velIntervalCount; - char visStateIntervalCount; - FxElemVelStateSample* velSamples; - FxElemVisStateSample* visSamples; - FxElemDefVisuals visuals; - Bounds collBounds; - FxEffectDefRef effectOnImpact; - FxEffectDefRef effectOnDeath; - FxEffectDefRef effectEmitted; - FxFloatRange emitDist; - FxFloatRange emitDistVariance; - FxElemExtendedDefPtr extended; - char sortOrder; - char lightingFrac; - char useItemClip; - char fadeInfo; - }; - - struct FxEffectDef - { - const char* name; - int flags; - int totalSize; - int msecLoopingLife; - int elemDefCountLooping; - int elemDefCountOneShot; - int elemDefCountEmission; - FxElemDef* elemDefs; - }; - - struct GfxLightImage - { - GfxImage* image; - char samplerState; - }; - - struct GfxLightDef - { - const char* name; - GfxLightImage attenuation; - int lmapLookupStart; - }; - - struct Glyph - { - uint16_t letter; - char x0; - char y0; - char dx; - char pixelWidth; - char pixelHeight; - float s0; - float t0; - float s1; - float t1; - }; - - struct Font_s - { - const char* fontName; - int pixelHeight; - int glyphCount; - Material* material; - Material* glowMaterial; - Glyph* glyphs; - }; - - struct FxImpactEntry - { - FxEffectDef* nonflesh[31]; - FxEffectDef* flesh[4]; - }; - - struct FxImpactTable - { - const char* name; - FxImpactEntry* table; - }; - - enum LbColType - { - LBCOL_TYPE_NUMBER = 0x0, - LBCOL_TYPE_TIME = 0x1, - LBCOL_TYPE_LEVELXP = 0x2, - LBCOL_TYPE_PRESTIGE = 0x3, - LBCOL_TYPE_BIGNUMBER = 0x4, - LBCOL_TYPE_PERCENT = 0x5, - LBCOL_TYPE_COUNT = 0x6, - }; - - enum LbAggType - { - LBAGG_TYPE_MIN = 0x0, - LBAGG_TYPE_MAX = 0x1, - LBAGG_TYPE_SUM = 0x2, - LBAGG_TYPE_LAST = 0x3, - LBAGG_TYPE_COUNT = 0x4, - }; - - struct LbColumnDef - { - const char* name; - int id; - int propertyId; - bool hidden; - const char* statName; - LbColType type; - int precision; - LbAggType agg; - }; - - struct LeaderboardDef - { - const char* name; - int id; - int columnCount; - int xpColId; - int prestigeColId; - LbColumnDef* columns; - }; - - struct TracerDef - { - const char* name; - Material* material; - unsigned int drawInterval; - float speed; - float beamLength; - float beamWidth; - float screwRadius; - float screwDist; - float colors[5][4]; - }; - - enum StructuredDataTypeCategory - { - DATA_INT = 0x0, - DATA_BYTE = 0x1, - DATA_BOOL = 0x2, - DATA_STRING = 0x3, - DATA_ENUM = 0x4, - DATA_STRUCT = 0x5, - DATA_INDEXED_ARRAY = 0x6, - DATA_ENUM_ARRAY = 0x7, - DATA_FLOAT = 0x8, - DATA_SHORT = 0x9, - - DATA_COUNT - }; - - struct StructuredDataEnumEntry - { - const char* string; - uint16_t index; - }; - - struct StructuredDataEnum - { - int entryCount; - int reservedEntryCount; - StructuredDataEnumEntry* entries; - }; - - union StructuredDataTypeUnion - { - unsigned int stringDataLength; - int enumIndex; - int structIndex; - int indexedArrayIndex; - int enumedArrayIndex; - }; - - struct StructuredDataType - { - StructuredDataTypeCategory type; - StructuredDataTypeUnion u; - }; - - struct StructuredDataStructProperty - { - const char* name; - StructuredDataType type; - unsigned int offset; - }; - - struct StructuredDataStruct - { - int propertyCount; - StructuredDataStructProperty* properties; - int size; - unsigned int bitOffset; - }; - - struct StructuredDataIndexedArray - { - int arraySize; - StructuredDataType elementType; - unsigned int elementSize; - }; - - struct StructuredDataEnumedArray - { - int enumIndex; - StructuredDataType elementType; - unsigned int elementSize; - }; - - struct StructuredDataDef - { - int version; - unsigned int formatChecksum; - int enumCount; - StructuredDataEnum* enums; - int structCount; - StructuredDataStruct* structs; - int indexedArrayCount; - StructuredDataIndexedArray* indexedArrays; - int enumedArrayCount; - StructuredDataEnumedArray* enumedArrays; - StructuredDataType rootType; - unsigned int size; - }; - - struct StructuredDataDefSet - { - const char* name; - unsigned int defCount; - StructuredDataDef* defs; - }; - - struct TriggerModel - { - int contents; - uint16_t hullCount; - uint16_t firstHull; - }; - - struct TriggerHull - { - Bounds bounds; - int contents; - uint16_t slabCount; - uint16_t firstSlab; - }; - - struct TriggerSlab - { - float dir[3]; - float midPoint; - float halfSize; - }; - - struct MapTriggers - { - unsigned int count; - TriggerModel* models; - unsigned int hullCount; - TriggerHull* hulls; - unsigned int slabCount; - TriggerSlab* slabs; - }; - - struct Stage - { - const char* name; - float origin[3]; - uint16_t triggerIndex; - char sunPrimaryLightIndex; - }; - - struct MapEnts - { - const char* name; - char* entityString; - int numEntityChars; - MapTriggers trigger; - Stage* stages; - char stageCount; - }; - - struct AddonMapEnts - { - const char* name; - char* entityString; - int numEntityChars; - MapTriggers trigger; - }; - - typedef unsigned short LeafBrush; - - struct cStaticModel_s - { - XModel* xmodel; - float origin[3]; - float invScaledAxis[3][3]; - Bounds absBounds; - }; - - struct ClipMaterial - { - const char* name; - int surfaceFlags; - int contents; - }; - - struct cNode_t - { - cplane_s* plane; - int16_t children[2]; - }; - - struct cLeafBrushNodeLeaf_t - { - LeafBrush* brushes; - }; - - struct cLeafBrushNodeChildren_t - { - float dist; - float range; - uint16_t childOffset[2]; - }; - - union cLeafBrushNodeData_t - { - cLeafBrushNodeLeaf_t leaf; - cLeafBrushNodeChildren_t children; - }; - - struct cLeafBrushNode_s - { - char axis; - int16_t leafBrushCount; - int contents; - cLeafBrushNodeData_t data; - }; - - struct CollisionBorder - { - float distEq[3]; - float zBase; - float zSlope; - float start; - float length; - }; - - struct CollisionPartition - { - char triCount; - char borderCount; - char firstVertSegment; - int firstTri; - CollisionBorder* borders; - }; - - union CollisionAabbTreeIndex - { - int firstChildIndex; - int partitionIndex; - }; - - struct type_align(16) CollisionAabbTree - { - float midPoint[3]; - uint16_t materialIndex; - uint16_t childCount; - float halfSize[3]; - CollisionAabbTreeIndex u; - }; - - struct cLeaf_t - { - uint16_t firstCollAabbIndex; - uint16_t collAabbCount; - int brushContents; - int terrainContents; - Bounds bounds; - int leafBrushNode; - }; - - struct cmodel_t - { - Bounds bounds; - float radius; - cLeaf_t leaf; - }; - - struct cbrush_t - { - uint16_t numsides; - uint16_t glassPieceIndex; - cbrushside_t* sides; - char* baseAdjacentSide; - int16_t axialMaterialNum[2][3]; - char firstAdjacentSideOffsets[2][3]; - char edgeCount[2][3]; - }; - - struct SModelAabbNode - { - Bounds bounds; - uint16_t firstChild; - uint16_t childCount; - }; - - struct GfxPlacement - { - float quat[4]; - float origin[3]; - }; - - enum DynEntityType - { - DYNENT_TYPE_INVALID = 0x0, - DYNENT_TYPE_CLUTTER = 0x1, - DYNENT_TYPE_DESTRUCT = 0x2, - DYNENT_TYPE_COUNT = 0x3, - }; - - struct DynEntityDef - { - DynEntityType type; - GfxPlacement pose; - XModel* xModel; - uint16_t brushModel; - uint16_t physicsBrushModel; - FxEffectDef* destroyFx; - PhysPreset* physPreset; - int health; - PhysMass mass; - int contents; - }; - - struct DynEntityPose - { - GfxPlacement pose; - float radius; - }; - - struct DynEntityClient - { - int physObjId; - uint16_t flags; - uint16_t lightingHandle; - int health; - }; - - struct DynEntityColl - { - uint16_t sector; - uint16_t nextEntInSector; - float linkMins[2]; - float linkMaxs[2]; - }; - - typedef tdef_align(128) cbrush_t cbrush_array_t; - typedef tdef_align(128) Bounds BoundsArray; - - struct clipMap_t - { - const char* name; - int isInUse; - int planeCount; - cplane_s* planes; - unsigned int numStaticModels; - cStaticModel_s* staticModelList; - unsigned int numMaterials; - ClipMaterial* materials; - unsigned int numBrushSides; - cbrushside_t* brushsides; - unsigned int numBrushEdges; - cbrushedge_t* brushEdges; - unsigned int numNodes; - cNode_t* nodes; - unsigned int numLeafs; - cLeaf_t* leafs; - unsigned int leafbrushNodesCount; - cLeafBrushNode_s* leafbrushNodes; - unsigned int numLeafBrushes; - LeafBrush* leafbrushes; - unsigned int numLeafSurfaces; - unsigned int* leafsurfaces; - unsigned int vertCount; - vec3_t* verts; - int triCount; - uint16_t* triIndices; - char* triEdgeIsWalkable; - int borderCount; - CollisionBorder* borders; - int partitionCount; - CollisionPartition* partitions; - int aabbTreeCount; - CollisionAabbTree* aabbTrees; - unsigned int numSubModels; - cmodel_t* cmodels; - uint16_t numBrushes; - cbrush_array_t* brushes; - BoundsArray* brushBounds; - int* brushContents; - MapEnts* mapEnts; - uint16_t smodelNodeCount; - SModelAabbNode* smodelNodes; - uint16_t dynEntCount[2]; - DynEntityDef* dynEntDefList[2]; - DynEntityPose* dynEntPoseList[2]; - DynEntityClient* dynEntClientList[2]; - DynEntityColl* dynEntCollList[2]; - unsigned int checksum; - char padding[48]; - }; - - struct ComPrimaryLight - { - char type; - char canUseShadowMap; - char exponent; - char unused; - float color[3]; - float dir[3]; - float origin[3]; - float radius; - float cosHalfFovOuter; - float cosHalfFovInner; - float cosHalfFovExpanded; - float rotationLimit; - float translationLimit; - const char* defName; - }; - - struct ComWorld - { - const char* name; - int isInUse; - unsigned int primaryLightCount; - ComPrimaryLight* primaryLights; - }; - - struct pathnode_t; - - enum nodeType - { - NODE_ERROR = 0x0, - NODE_PATHNODE = 0x1, - NODE_COVER_STAND = 0x2, - NODE_COVER_CROUCH = 0x3, - NODE_COVER_CROUCH_WINDOW = 0x4, - NODE_COVER_PRONE = 0x5, - NODE_COVER_RIGHT = 0x6, - NODE_COVER_LEFT = 0x7, - NODE_AMBUSH = 0x8, - NODE_EXPOSED = 0x9, - NODE_CONCEALMENT_STAND = 0xA, - NODE_CONCEALMENT_CROUCH = 0xB, - NODE_CONCEALMENT_PRONE = 0xC, - NODE_DOOR = 0xD, - NODE_DOOR_INTERIOR = 0xE, - NODE_SCRIPTED = 0xF, - NODE_NEGOTIATION_BEGIN = 0x10, - NODE_NEGOTIATION_END = 0x11, - NODE_TURRET = 0x12, - NODE_GUARD = 0x13, - NODE_NUMTYPES = 0x14, - NODE_DONTLINK = 0x14, - }; - - struct pathlink_s - { - float fDist; - uint16_t nodeNum; - char disconnectCount; - char negotiationLink; - char flags; - char ubBadPlaceCount[3]; - }; - - enum PathNodeErrorCode - { - PNERR_NONE = 0x0, - PNERR_INSOLID = 0x1, - PNERR_FLOATING = 0x2, - PNERR_NOLINK = 0x3, - PNERR_DUPLICATE = 0x4, - PNERR_NOSTANCE = 0x5, - PNERR_INVALIDDOOR = 0x6, - PNERR_NOANGLES = 0x7, - PNERR_BADPLACEMENT = 0x8, - - NUM_PATH_NODE_ERRORS - }; - - struct pathnode_constant_t - { - nodeType type; - uint16_t spawnflags; - uint16_t targetname; - uint16_t script_linkName; - uint16_t script_noteworthy; - uint16_t target; - uint16_t animscript; - int animscriptfunc; - float vOrigin[3]; - float fAngle; - float forward[2]; - float fRadius; - union - { - float minUseDistSq; - PathNodeErrorCode error; - }; - int16_t wOverlapNode[2]; - uint16_t totalLinkCount; - pathlink_s* Links; - }; - - struct pathnode_dynamic_t - { - void* pOwner; - int iFreeTime; - int iValidTime[3]; - int dangerousNodeTime[3]; - int inPlayerLOSTime; - int16_t wLinkCount; - int16_t wOverlapCount; - int16_t turretEntNumber; - char userCount; - bool hasBadPlaceLink; - }; - - struct pathnode_transient_t - { - int iSearchFrame; - pathnode_t* pNextOpen; - pathnode_t* pPrevOpen; - pathnode_t* pParent; - float fCost; - float fHeuristic; - union - { - float nodeCost; - int linkIndex; - }; - }; - - struct pathnode_t - { - pathnode_constant_t constant; - pathnode_dynamic_t dynamic; - pathnode_transient_t transient; - }; - - struct type_align(16) pathbasenode_t - { - float vOrigin[3]; - unsigned int type; - }; - - struct pathnode_tree_nodes_t - { - int nodeCount; - uint16_t* nodes; - }; - - struct pathnode_tree_t; - - union pathnode_tree_info_t - { - pathnode_tree_t* child[2]; - pathnode_tree_nodes_t s; - }; - - struct pathnode_tree_t - { - int axis; - float dist; - pathnode_tree_info_t u; - }; - - struct PathData - { - unsigned int nodeCount; - pathnode_t* nodes; - pathbasenode_t* basenodes; - unsigned int chainNodeCount; - uint16_t* chainNodeForNode; - uint16_t* nodeForChainNode; - int visBytes; - char* pathVis; - int nodeTreeCount; - pathnode_tree_t* nodeTree; - }; - - struct VehicleTrackObstacle - { - float origin[2]; - float radius; - }; - - struct VehicleTrackSector - { - float startEdgeDir[2]; - float startEdgeDist; - float leftEdgeDir[2]; - float leftEdgeDist; - float rightEdgeDir[2]; - float rightEdgeDist; - float sectorLength; - float sectorWidth; - float totalPriorLength; - float totalFollowingLength; - VehicleTrackObstacle* obstacles; - unsigned int obstacleCount; - }; - - struct VehicleTrackSegment - { - const char* targetName; - VehicleTrackSector* sectors; - unsigned int sectorCount; - VehicleTrackSegment** nextBranches; - unsigned int nextBranchesCount; - VehicleTrackSegment** prevBranches; - unsigned int prevBranchesCount; - float endEdgeDir[2]; - float endEdgeDist; - float totalLength; - }; - - struct VehicleTrack - { - VehicleTrackSegment* segments; - unsigned int segmentCount; - }; - - struct G_GlassPiece - { - uint16_t damageTaken; - uint16_t collapseTime; - int lastStateChangeTime; - char impactDir; - char impactPos[2]; - }; - - struct G_GlassName - { - char* nameStr; - uint16_t name; - uint16_t pieceCount; - uint16_t* pieceIndices; - }; - - struct G_GlassData - { - G_GlassPiece* glassPieces; - unsigned int pieceCount; - uint16_t damageToWeaken; - uint16_t damageToDestroy; - unsigned int glassNameCount; - G_GlassName* glassNames; - char pad[108]; - }; - - struct GameWorldSp - { - const char* name; - PathData path; - VehicleTrack vehicleTrack; - G_GlassData* g_glassData; - }; - - struct GameWorldMp - { - const char* name; - G_GlassData* g_glassData; - }; - - struct FxGlassDef - { - float halfThickness; - float texVecs[2][2]; - GfxColor color; - Material* material; - Material* materialShattered; - PhysPreset* physPreset; - }; - - struct FxSpatialFrame - { - float quat[4]; - float origin[3]; - }; - - union FxGlassPiecePlace - { - struct - { - FxSpatialFrame frame; - float radius; - }; - unsigned int nextFree; - }; - - struct FxGlassPieceState - { - float texCoordOrigin[2]; - unsigned int supportMask; - uint16_t initIndex; - uint16_t geoDataStart; - char defIndex; - char pad[5]; - char vertCount; - char holeDataCount; - char crackDataCount; - char fanDataCount; - uint16_t flags; - float areaX2; - }; - - struct FxGlassPieceDynamics - { - int fallTime; - int physObjId; - int physJointId; - float vel[3]; - float avel[3]; - }; - - struct FxGlassVertex - { - int16_t x; - int16_t y; - }; - - struct FxGlassHoleHeader - { - uint16_t uniqueVertCount; - char touchVert; - char pad[1]; - }; - - struct FxGlassCrackHeader - { - uint16_t uniqueVertCount; - char beginVertIndex; - char endVertIndex; - }; - - union type_align(4) FxGlassGeometryData - { - FxGlassVertex vert; - FxGlassHoleHeader hole; - FxGlassCrackHeader crack; - char asBytes[4]; - int16_t anonymous[2]; - }; - - struct FxGlassInitPieceState - { - FxSpatialFrame frame; - float radius; - float texCoordOrigin[2]; - unsigned int supportMask; - float areaX2; - char defIndex; - char vertCount; - char fanDataCount; - char pad[1]; - }; - - struct FxGlassSystem - { - int time; - int prevTime; - unsigned int defCount; - unsigned int pieceLimit; - unsigned int pieceWordCount; - unsigned int initPieceCount; - unsigned int cellCount; - unsigned int activePieceCount; - unsigned int firstFreePiece; - unsigned int geoDataLimit; - unsigned int geoDataCount; - unsigned int initGeoDataCount; - FxGlassDef* defs; - FxGlassPiecePlace* piecePlaces; - FxGlassPieceState* pieceStates; - FxGlassPieceDynamics* pieceDynamics; - FxGlassGeometryData* geoData; - raw_uint* isInUse; - raw_uint* cellBits; - raw_byte16* visData; - vec3_t* linkOrg; - raw_float16* halfThickness; - uint16_t* lightingHandles; - FxGlassInitPieceState* initPieceStates; - FxGlassGeometryData* initGeoData; - bool needToCompactData; - char initCount; - float effectChanceAccum; - int lastPieceDeletionTime; - }; - - struct FxWorld - { - const char* name; - FxGlassSystem glassSys; - }; - - struct GfxSky - { - int skySurfCount; - int* skyStartSurfs; - GfxImage* skyImage; - char skySamplerState; - }; - - struct GfxWorldDpvsPlanes - { - int cellCount; - cplane_s* planes; - uint16_t* nodes; - raw_uint* sceneEntCellBits; - }; - - struct GfxCellTreeCount - { - int aabbTreeCount; - }; - - typedef unsigned short StaticModelIndex; - - struct GfxAabbTree - { - Bounds bounds; - uint16_t childCount; - uint16_t surfaceCount; - uint16_t startSurfIndex; - uint16_t surfaceCountNoDecal; - uint16_t startSurfIndexNoDecal; - uint16_t smodelIndexCount; - StaticModelIndex* smodelIndexes; - int childrenOffset; - }; - - struct GfxCellTree - { - GfxAabbTree* aabbTree; - }; - - struct GfxPortal; - - struct GfxPortalWritable - { - bool isQueued; - bool isAncestor; - char recursionDepth; - char hullPointCount; - float(*hullPoints)[2]; - GfxPortal* queuedParent; - }; - - struct DpvsPlane - { - float coeffs[4]; - }; - - struct GfxPortal - { - GfxPortalWritable writable; - DpvsPlane plane; - vec3_t* vertices; - uint16_t cellIndex; - char vertexCount; - float hullAxis[2][3]; - }; - - struct GfxCell - { - Bounds bounds; - int portalCount; - GfxPortal* portals; - char reflectionProbeCount; - char* reflectionProbes; - }; - - struct GfxReflectionProbe - { - float origin[3]; - }; - - struct GfxLightmapArray - { - GfxImage* primary; - GfxImage* secondary; - }; - - struct GfxWorldVertex - { - float xyz[3]; - float binormalSign; - GfxColor color; - float texCoord[2]; - float lmapCoord[2]; - PackedUnitVec normal; - PackedUnitVec tangent; - }; - - struct GfxWorldVertexData - { - GfxWorldVertex* vertices; - void/*IDirect3DVertexBuffer9*/* worldVb; - }; - - struct GfxWorldVertexLayerData - { - char* data; - void/*IDirect3DVertexBuffer9*/* layerVb; - }; - - struct GfxWorldDraw - { - unsigned int reflectionProbeCount; - GfxImage** reflectionProbes; - GfxReflectionProbe* reflectionProbeOrigins; - GfxTexture* reflectionProbeTextures; - int lightmapCount; - GfxLightmapArray* lightmaps; - GfxTexture* lightmapPrimaryTextures; - GfxTexture* lightmapSecondaryTextures; - GfxImage* lightmapOverridePrimary; - GfxImage* lightmapOverrideSecondary; - unsigned int vertexCount; - GfxWorldVertexData vd; - unsigned int vertexLayerDataSize; - GfxWorldVertexLayerData vld; - unsigned int indexCount; - r_index_t* indices; - }; - - struct type_align(4) GfxLightGridEntry - { - uint16_t colorsIndex; - char primaryLightIndex; - char needsTrace; - }; - - struct type_align(4) GfxLightGridColors - { - char rgb[56][3]; - }; - - struct GfxLightGrid - { - bool hasLightRegions; - unsigned int lastSunPrimaryLightIndex; - uint16_t mins[3]; - uint16_t maxs[3]; - unsigned int rowAxis; - unsigned int colAxis; - uint16_t* rowDataStart; - unsigned int rawRowDataSize; - char* rawRowData; - unsigned int entryCount; - GfxLightGridEntry* entries; - unsigned int colorCount; - GfxLightGridColors* colors; - }; - - struct GfxBrushModelWritable - { - Bounds bounds; - }; - - struct type_align(4) GfxBrushModel - { - GfxBrushModelWritable writable; - Bounds bounds; - float radius; - uint16_t surfaceCount; - uint16_t startSurfIndex; - uint16_t surfaceCountNoDecal; - }; - - struct MaterialMemory - { - Material* material; - int memory; - }; - - struct sunflare_t - { - bool hasValidData; - Material* spriteMaterial; - Material* flareMaterial; - float spriteSize; - float flareMinSize; - float flareMinDot; - float flareMaxSize; - float flareMaxDot; - float flareMaxAlpha; - int flareFadeInTime; - int flareFadeOutTime; - float blindMinDot; - float blindMaxDot; - float blindMaxDarken; - int blindFadeInTime; - int blindFadeOutTime; - float glareMinDot; - float glareMaxDot; - float glareMaxLighten; - int glareFadeInTime; - int glareFadeOutTime; - float sunFxPosition[3]; - }; - - struct XModelDrawInfo - { - char hasGfxEntIndex; - char lod; - uint16_t surfId; - }; - - struct GfxSceneDynModel - { - XModelDrawInfo info; - uint16_t dynEntId; - }; - - struct BModelDrawInfo - { - uint16_t surfId; - }; - - struct type_align(4) GfxSceneDynBrush - { - BModelDrawInfo info; - uint16_t dynEntId; - }; - - struct GfxShadowGeometry - { - uint16_t surfaceCount; - uint16_t smodelCount; - uint16_t* sortedSurfIndex; - uint16_t* smodelIndex; - }; - - struct GfxLightRegionAxis - { - float dir[3]; - float midPoint; - float halfSize; - }; - - struct GfxLightRegionHull - { - float kdopMidPoint[9]; - float kdopHalfSize[9]; - unsigned int axisCount; - GfxLightRegionAxis* axis; - }; - - struct GfxLightRegion - { - unsigned int hullCount; - GfxLightRegionHull* hulls; - }; - - struct GfxPackedPlacement - { - float origin[3]; - float axis[3][3]; - float scale; - }; - - struct GfxStaticModelDrawInst - { - GfxPackedPlacement placement; - XModel* model; - uint16_t cullDist; - uint16_t lightingHandle; - char reflectionProbeIndex; - char primaryLightIndex; - char flags; - char firstMtlSkinIndex; - GfxColor groundLighting; - uint16_t cacheId[4]; - }; - - struct GfxStaticModelInst - { - Bounds bounds; - float lightingOrigin[3]; - }; - - struct srfTriangles_t - { - unsigned int vertexLayerData; - unsigned int firstVertex; - uint16_t vertexCount; - uint16_t triCount; - unsigned int baseIndex; - }; - - struct GfxSurfaceLightingAndFlagsFields - { - char lightmapIndex; - char reflectionProbeIndex; - char primaryLightIndex; - char flags; - }; - - union GfxSurfaceLightingAndFlags - { - GfxSurfaceLightingAndFlagsFields fields; - unsigned int packed; - }; - - struct GfxSurface - { - srfTriangles_t tris; - Material* material; - GfxSurfaceLightingAndFlags laf; - }; - - struct GfxSurfaceBounds - { - Bounds bounds; - }; - - struct GfxWorldDpvsStatic - { - unsigned int smodelCount; - unsigned int staticSurfaceCount; - unsigned int staticSurfaceCountNoDecal; - unsigned int litOpaqueSurfsBegin; - unsigned int litOpaqueSurfsEnd; - unsigned int litTransSurfsBegin; - unsigned int litTransSurfsEnd; - unsigned int shadowCasterSurfsBegin; - unsigned int shadowCasterSurfsEnd; - unsigned int emissiveSurfsBegin; - unsigned int emissiveSurfsEnd; - unsigned int smodelVisDataCount; - unsigned int surfaceVisDataCount; - char* smodelVisData[3]; - char* surfaceVisData[3]; - uint16_t* sortedSurfIndex; - GfxStaticModelInst* smodelInsts; - GfxSurface* surfaces; - GfxSurfaceBounds* surfacesBounds; - GfxStaticModelDrawInst* smodelDrawInsts; - GfxDrawSurf* surfaceMaterials; - raw_uint128* surfaceCastsSunShadow; - volatile int usageCount; - }; - - struct GfxWorldDpvsDynamic - { - unsigned int dynEntClientWordCount[2]; - unsigned int dynEntClientCount[2]; - raw_uint* dynEntCellBits[2]; - raw_byte16* dynEntVisData[2][3]; - }; - - struct GfxHeroOnlyLight - { - char type; - char unused[3]; - float color[3]; - float dir[3]; - float origin[3]; - float radius; - float cosHalfFovOuter; - float cosHalfFovInner; - int exponent; - }; - - typedef tdef_align(128) GfxCellTree GfxCellTree128; - typedef tdef_align(4) GfxSceneDynModel GfxSceneDynModel4; - - struct GfxWorld - { - const char* name; - const char* baseName; - int planeCount; - int nodeCount; - unsigned int surfaceCount; - int skyCount; - GfxSky* skies; - unsigned int lastSunPrimaryLightIndex; - unsigned int primaryLightCount; - unsigned int sortKeyLitDecal; - unsigned int sortKeyEffectDecal; - unsigned int sortKeyEffectAuto; - unsigned int sortKeyDistortion; - GfxWorldDpvsPlanes dpvsPlanes; - int/*GfxCellTreeCount*/* aabbTreeCounts; - GfxCellTree128* aabbTrees; - GfxCell* cells; - GfxWorldDraw draw; - GfxLightGrid lightGrid; - int modelCount; - GfxBrushModel* models; - Bounds bounds; - unsigned int checksum; - int materialMemoryCount; - MaterialMemory* materialMemory; - sunflare_t sun; - float outdoorLookupMatrix[4][4]; - GfxImage* outdoorImage; - raw_uint* cellCasterBits; - raw_uint* cellHasSunLitSurfsBits; - GfxSceneDynModel4* sceneDynModel; - GfxSceneDynBrush* sceneDynBrush; - raw_uint* primaryLightEntityShadowVis; - raw_uint* primaryLightDynEntShadowVis[2]; - char* nonSunPrimaryLightForModelDynEnt; - GfxShadowGeometry* shadowGeom; - GfxLightRegion* lightRegion; - GfxWorldDpvsStatic dpvs; - GfxWorldDpvsDynamic dpvsDyn; - unsigned int mapVtxChecksum; - unsigned int heroOnlyLightCount; - GfxHeroOnlyLight* heroOnlyLights; - char fogTypesAllowed; - }; - - enum ImpactType - { - IMPACT_TYPE_NONE = 0x0, - IMPACT_TYPE_BULLET_SMALL = 0x1, - IMPACT_TYPE_BULLET_LARGE = 0x2, - IMPACT_TYPE_BULLET_AP = 0x3, - IMPACT_TYPE_BULLET_EXPLODE = 0x4, - IMPACT_TYPE_SHOTGUN = 0x5, - IMPACT_TYPE_SHOTGUN_EXPLODE = 0x6, - IMPACT_TYPE_GRENADE_BOUNCE = 0x7, - IMPACT_TYPE_GRENADE_EXPLODE = 0x8, - IMPACT_TYPE_ROCKET_EXPLODE = 0x9, - IMPACT_TYPE_PROJECTILE_DUD = 0xA, - - IMPACT_TYPE_COUNT - }; - - enum weaponIconRatioType_t - { - WEAPON_ICON_RATIO_1TO1 = 0x0, - WEAPON_ICON_RATIO_2TO1 = 0x1, - WEAPON_ICON_RATIO_4TO1 = 0x2, - - WEAPON_ICON_RATIO_COUNT - }; - - enum weapType_t - { - WEAPTYPE_BULLET = 0x0, - WEAPTYPE_GRENADE = 0x1, - WEAPTYPE_PROJECTILE = 0x2, - WEAPTYPE_RIOTSHIELD = 0x3, - - WEAPTYPE_NUM - }; - - enum weapClass_t - { - WEAPCLASS_RIFLE = 0x0, - WEAPCLASS_SNIPER = 0x1, - WEAPCLASS_MG = 0x2, - WEAPCLASS_SMG = 0x3, - WEAPCLASS_SPREAD = 0x4, - WEAPCLASS_PISTOL = 0x5, - WEAPCLASS_GRENADE = 0x6, - WEAPCLASS_ROCKETLAUNCHER = 0x7, - WEAPCLASS_TURRET = 0x8, - WEAPCLASS_THROWINGKNIFE = 0x9, - WEAPCLASS_NON_PLAYER = 0xA, - WEAPCLASS_ITEM = 0xB, - - WEAPCLASS_NUM - }; - - enum PenetrateType - { - PENETRATE_TYPE_NONE = 0x0, - PENETRATE_TYPE_SMALL = 0x1, - PENETRATE_TYPE_MEDIUM = 0x2, - PENETRATE_TYPE_LARGE = 0x3, - - PENETRATE_TYPE_COUNT - }; - - enum weapInventoryType_t - { - WEAPINVENTORY_PRIMARY = 0x0, - WEAPINVENTORY_OFFHAND = 0x1, - WEAPINVENTORY_ITEM = 0x2, - WEAPINVENTORY_ALTMODE = 0x3, - WEAPINVENTORY_EXCLUSIVE = 0x4, - WEAPINVENTORY_SCAVENGER = 0x5, - - WEAPINVENTORYCOUNT - }; - - enum weapFireType_t - { - WEAPON_FIRETYPE_FULLAUTO = 0x0, - WEAPON_FIRETYPE_SINGLESHOT = 0x1, - WEAPON_FIRETYPE_BURSTFIRE2 = 0x2, - WEAPON_FIRETYPE_BURSTFIRE3 = 0x3, - WEAPON_FIRETYPE_BURSTFIRE4 = 0x4, - WEAPON_FIRETYPE_DOUBLEBARREL = 0x5, - WEAPON_FIRETYPECOUNT = 0x6, - WEAPON_FIRETYPE_BURSTFIRE_FIRST = 0x2, - WEAPON_FIRETYPE_BURSTFIRE_LAST = 0x4, - }; - - enum OffhandClass - { - OFFHAND_CLASS_NONE = 0x0, - OFFHAND_CLASS_FRAG_GRENADE = 0x1, - OFFHAND_CLASS_SMOKE_GRENADE = 0x2, - OFFHAND_CLASS_FLASH_GRENADE = 0x3, - OFFHAND_CLASS_THROWINGKNIFE = 0x4, - OFFHAND_CLASS_OTHER = 0x5, - - OFFHAND_CLASS_COUNT - }; - - enum weapStance_t - { - WEAPSTANCE_STAND = 0x0, - WEAPSTANCE_DUCK = 0x1, - WEAPSTANCE_PRONE = 0x2, - - WEAPSTANCE_NUM - }; - - enum activeReticleType_t - { - VEH_ACTIVE_RETICLE_NONE = 0x0, - VEH_ACTIVE_RETICLE_PIP_ON_A_STICK = 0x1, - VEH_ACTIVE_RETICLE_BOUNCING_DIAMOND = 0x2, - - VEH_ACTIVE_RETICLE_COUNT - }; - - enum ammoCounterClipType_t - { - AMMO_COUNTER_CLIP_NONE = 0x0, - AMMO_COUNTER_CLIP_MAGAZINE = 0x1, - AMMO_COUNTER_CLIP_SHORTMAGAZINE = 0x2, - AMMO_COUNTER_CLIP_SHOTGUN = 0x3, - AMMO_COUNTER_CLIP_ROCKET = 0x4, - AMMO_COUNTER_CLIP_BELTFED = 0x5, - AMMO_COUNTER_CLIP_ALTWEAPON = 0x6, - - AMMO_COUNTER_CLIP_COUNT - }; - - enum weapOverlayReticle_t - { - WEAPOVERLAYRETICLE_NONE = 0x0, - WEAPOVERLAYRETICLE_CROSSHAIR = 0x1, - - WEAPOVERLAYRETICLE_NUM - }; - - enum WeapOverlayInteface_t - { - WEAPOVERLAYINTERFACE_NONE = 0x0, - WEAPOVERLAYINTERFACE_JAVELIN = 0x1, - WEAPOVERLAYINTERFACE_TURRETSCOPE = 0x2, - - WEAPOVERLAYINTERFACECOUNT - }; - - enum weapProjExposion_t - { - WEAPPROJEXP_GRENADE = 0x0, - WEAPPROJEXP_ROCKET = 0x1, - WEAPPROJEXP_FLASHBANG = 0x2, - WEAPPROJEXP_NONE = 0x3, - WEAPPROJEXP_DUD = 0x4, - WEAPPROJEXP_SMOKE = 0x5, - WEAPPROJEXP_HEAVY = 0x6, - - WEAPPROJEXP_NUM - }; - - enum WeapStickinessType - { - WEAPSTICKINESS_NONE = 0x0, - WEAPSTICKINESS_ALL = 0x1, - WEAPSTICKINESS_ALL_ORIENT = 0x2, - WEAPSTICKINESS_GROUND = 0x3, - WEAPSTICKINESS_GROUND_WITH_YAW = 0x4, - WEAPSTICKINESS_KNIFE = 0x5, - - WEAPSTICKINESS_COUNT - }; - - enum guidedMissileType_t - { - MISSILE_GUIDANCE_NONE = 0x0, - MISSILE_GUIDANCE_SIDEWINDER = 0x1, - MISSILE_GUIDANCE_HELLFIRE = 0x2, - MISSILE_GUIDANCE_JAVELIN = 0x3, - - MISSILE_GUIDANCE_COUNT - }; - - enum weapAnimFiles_t - { - WEAP_ANIM_ROOT = 0x0, - WEAP_ANIM_IDLE = 0x1, - WEAP_ANIM_EMPTY_IDLE = 0x2, - WEAP_ANIM_FIRE = 0x3, - WEAP_ANIM_HOLD_FIRE = 0x4, - WEAP_ANIM_LASTSHOT = 0x5, - WEAP_ANIM_RECHAMBER = 0x6, - WEAP_ANIM_MELEE = 0x7, - WEAP_ANIM_MELEE_CHARGE = 0x8, - WEAP_ANIM_RELOAD = 0x9, - WEAP_ANIM_RELOAD_EMPTY = 0xA, - WEAP_ANIM_RELOAD_START = 0xB, - WEAP_ANIM_RELOAD_END = 0xC, - WEAP_ANIM_RAISE = 0xD, - WEAP_ANIM_FIRST_RAISE = 0xE, - WEAP_ANIM_BREACH_RAISE = 0xF, - WEAP_ANIM_DROP = 0x10, - WEAP_ANIM_ALT_RAISE = 0x11, - WEAP_ANIM_ALT_DROP = 0x12, - WEAP_ANIM_QUICK_RAISE = 0x13, - WEAP_ANIM_QUICK_DROP = 0x14, - WEAP_ANIM_EMPTY_RAISE = 0x15, - WEAP_ANIM_EMPTY_DROP = 0x16, - WEAP_ANIM_SPRINT_IN = 0x17, - WEAP_ANIM_SPRINT_LOOP = 0x18, - WEAP_ANIM_SPRINT_OUT = 0x19, - WEAP_ANIM_STUNNED_START = 0x1A, - WEAP_ANIM_STUNNED_LOOP = 0x1B, - WEAP_ANIM_STUNNED_END = 0x1C, - WEAP_ANIM_DETONATE = 0x1D, - WEAP_ANIM_NIGHTVISION_WEAR = 0x1E, - WEAP_ANIM_NIGHTVISION_REMOVE = 0x1F, - WEAP_ANIM_ADS_FIRE = 0x20, - WEAP_ANIM_ADS_LASTSHOT = 0x21, - WEAP_ANIM_ADS_RECHAMBER = 0x22, - WEAP_ANIM_ADS_UP = 0x23, - WEAP_ANIM_ADS_DOWN = 0x24, - - NUM_WEAP_ANIMS, - }; - - enum materialSurfType_t - { - SURF_TYPE_DEFAULT, - SURF_TYPE_BARK, - SURF_TYPE_BRICK, - SURF_TYPE_CARPET, - SURF_TYPE_CLOTH, - SURF_TYPE_CONCRETE, - SURF_TYPE_DIRT, - SURF_TYPE_FLESH, - SURF_TYPE_FOLIAGE, - SURF_TYPE_GLASS, - SURF_TYPE_GRASS, - SURF_TYPE_GRAVEL, - SURF_TYPE_ICE, - SURF_TYPE_METAL, - SURF_TYPE_MUD, - SURF_TYPE_PAPER, - SURF_TYPE_PLASTER, - SURF_TYPE_ROCK, - SURF_TYPE_SAND, - SURF_TYPE_SNOW, - SURF_TYPE_WATER, - SURF_TYPE_WOOD, - SURF_TYPE_ASPHALT, - SURF_TYPE_CERAMIC, - SURF_TYPE_PLASTIC, - SURF_TYPE_RUBBER, - SURF_TYPE_CUSHION, - SURF_TYPE_FRUIT, - SURF_TYPE_PAINTED_METAL, - SURF_TYPE_RIOT_SHIELD, - SURF_TYPE_SLUSH, - - SURF_TYPE_NUM - }; - - enum hitLocation_t - { - HITLOC_NONE = 0x0, - HITLOC_HELMET = 0x1, - HITLOC_HEAD = 0x2, - HITLOC_NECK = 0x3, - HITLOC_TORSO_UPR = 0x4, - HITLOC_TORSO_LWR = 0x5, - HITLOC_R_ARM_UPR = 0x6, - HITLOC_L_ARM_UPR = 0x7, - HITLOC_R_ARM_LWR = 0x8, - HITLOC_L_ARM_LWR = 0x9, - HITLOC_R_HAND = 0xA, - HITLOC_L_HAND = 0xB, - HITLOC_R_LEG_UPR = 0xC, - HITLOC_L_LEG_UPR = 0xD, - HITLOC_R_LEG_LWR = 0xE, - HITLOC_L_LEG_LWR = 0xF, - HITLOC_R_FOOT = 0x10, - HITLOC_L_FOOT = 0x11, - HITLOC_GUN = 0x12, - HITLOC_SHIELD = 0x13, - - HITLOC_NUM, - }; - - struct snd_alias_list_name - { - const char* soundName; - }; - - union SndAliasCustom - { - snd_alias_list_name* name; - snd_alias_list_t* sound; - }; - - struct WeaponDef - { - const char* szOverlayName; - XModel** gunXModel; - XModel* handXModel; - const char** szXAnimsRightHanded; - const char** szXAnimsLeftHanded; - const char* szModeName; - uint16_t* notetrackSoundMapKeys; - uint16_t* notetrackSoundMapValues; - uint16_t* notetrackRumbleMapKeys; - uint16_t* notetrackRumbleMapValues; - int playerAnimType; - weapType_t weapType; - weapClass_t weapClass; - PenetrateType penetrateType; - weapInventoryType_t inventoryType; - weapFireType_t fireType; - OffhandClass offhandClass; - weapStance_t stance; - FxEffectDef* viewFlashEffect; - FxEffectDef* worldFlashEffect; - SndAliasCustom pickupSound; - SndAliasCustom pickupSoundPlayer; - SndAliasCustom ammoPickupSound; - SndAliasCustom ammoPickupSoundPlayer; - SndAliasCustom projectileSound; - SndAliasCustom pullbackSound; - SndAliasCustom pullbackSoundPlayer; - SndAliasCustom fireSound; - SndAliasCustom fireSoundPlayer; - SndAliasCustom fireSoundPlayerAkimbo; - SndAliasCustom fireLoopSound; - SndAliasCustom fireLoopSoundPlayer; - SndAliasCustom fireStopSound; - SndAliasCustom fireStopSoundPlayer; - SndAliasCustom fireLastSound; - SndAliasCustom fireLastSoundPlayer; - SndAliasCustom emptyFireSound; - SndAliasCustom emptyFireSoundPlayer; - SndAliasCustom meleeSwipeSound; - SndAliasCustom meleeSwipeSoundPlayer; - SndAliasCustom meleeHitSound; - SndAliasCustom meleeMissSound; - SndAliasCustom rechamberSound; - SndAliasCustom rechamberSoundPlayer; - SndAliasCustom reloadSound; - SndAliasCustom reloadSoundPlayer; - SndAliasCustom reloadEmptySound; - SndAliasCustom reloadEmptySoundPlayer; - SndAliasCustom reloadStartSound; - SndAliasCustom reloadStartSoundPlayer; - SndAliasCustom reloadEndSound; - SndAliasCustom reloadEndSoundPlayer; - SndAliasCustom detonateSound; - SndAliasCustom detonateSoundPlayer; - SndAliasCustom nightVisionWearSound; - SndAliasCustom nightVisionWearSoundPlayer; - SndAliasCustom nightVisionRemoveSound; - SndAliasCustom nightVisionRemoveSoundPlayer; - SndAliasCustom altSwitchSound; - SndAliasCustom altSwitchSoundPlayer; - SndAliasCustom raiseSound; - SndAliasCustom raiseSoundPlayer; - SndAliasCustom firstRaiseSound; - SndAliasCustom firstRaiseSoundPlayer; - SndAliasCustom putawaySound; - SndAliasCustom putawaySoundPlayer; - SndAliasCustom scanSound; - SndAliasCustom* bounceSound; - FxEffectDef* viewShellEjectEffect; - FxEffectDef* worldShellEjectEffect; - FxEffectDef* viewLastShotEjectEffect; - FxEffectDef* worldLastShotEjectEffect; - Material* reticleCenter; - Material* reticleSide; - int iReticleCenterSize; - int iReticleSideSize; - int iReticleMinOfs; - activeReticleType_t activeReticleType; - float vStandMove[3]; - float vStandRot[3]; - float strafeMove[3]; - float strafeRot[3]; - float vDuckedOfs[3]; - float vDuckedMove[3]; - float vDuckedRot[3]; - float vProneOfs[3]; - float vProneMove[3]; - float vProneRot[3]; - float fPosMoveRate; - float fPosProneMoveRate; - float fStandMoveMinSpeed; - float fDuckedMoveMinSpeed; - float fProneMoveMinSpeed; - float fPosRotRate; - float fPosProneRotRate; - float fStandRotMinSpeed; - float fDuckedRotMinSpeed; - float fProneRotMinSpeed; - XModel** worldModel; - XModel* worldClipModel; - XModel* rocketModel; - XModel* knifeModel; - XModel* worldKnifeModel; - Material* hudIcon; - weaponIconRatioType_t hudIconRatio; - Material* pickupIcon; - weaponIconRatioType_t pickupIconRatio; - Material* ammoCounterIcon; - weaponIconRatioType_t ammoCounterIconRatio; - ammoCounterClipType_t ammoCounterClip; - int iStartAmmo; - const char* szAmmoName; - int iAmmoIndex; - const char* szClipName; - int iClipIndex; - int iMaxAmmo; - int shotCount; - const char* szSharedAmmoCapName; - int iSharedAmmoCapIndex; - int iSharedAmmoCap; - int damage; - int playerDamage; - int iMeleeDamage; - int iDamageType; - int iFireDelay; - int iMeleeDelay; - int meleeChargeDelay; - int iDetonateDelay; - int iRechamberTime; - int rechamberTimeOneHanded; - int iRechamberBoltTime; - int iHoldFireTime; - int iDetonateTime; - int iMeleeTime; - int meleeChargeTime; - int iReloadTime; - int reloadShowRocketTime; - int iReloadEmptyTime; - int iReloadAddTime; - int iReloadStartTime; - int iReloadStartAddTime; - int iReloadEndTime; - int iDropTime; - int iRaiseTime; - int iAltDropTime; - int quickDropTime; - int quickRaiseTime; - int iBreachRaiseTime; - int iEmptyRaiseTime; - int iEmptyDropTime; - int sprintInTime; - int sprintLoopTime; - int sprintOutTime; - int stunnedTimeBegin; - int stunnedTimeLoop; - int stunnedTimeEnd; - int nightVisionWearTime; - int nightVisionWearTimeFadeOutEnd; - int nightVisionWearTimePowerUp; - int nightVisionRemoveTime; - int nightVisionRemoveTimePowerDown; - int nightVisionRemoveTimeFadeInStart; - int fuseTime; - int aiFuseTime; - float autoAimRange; - float aimAssistRange; - float aimAssistRangeAds; - float aimPadding; - float enemyCrosshairRange; - float moveSpeedScale; - float adsMoveSpeedScale; - float sprintDurationScale; - float fAdsZoomInFrac; - float fAdsZoomOutFrac; - Material* overlayMaterial; - Material* overlayMaterialLowRes; - Material* overlayMaterialEMP; - Material* overlayMaterialEMPLowRes; - weapOverlayReticle_t overlayReticle; - WeapOverlayInteface_t overlayInterface; - float overlayWidth; - float overlayHeight; - float overlayWidthSplitscreen; - float overlayHeightSplitscreen; - float fAdsBobFactor; - float fAdsViewBobMult; - float fHipSpreadStandMin; - float fHipSpreadDuckedMin; - float fHipSpreadProneMin; - float hipSpreadStandMax; - float hipSpreadDuckedMax; - float hipSpreadProneMax; - float fHipSpreadDecayRate; - float fHipSpreadFireAdd; - float fHipSpreadTurnAdd; - float fHipSpreadMoveAdd; - float fHipSpreadDuckedDecay; - float fHipSpreadProneDecay; - float fHipReticleSidePos; - float fAdsIdleAmount; - float fHipIdleAmount; - float adsIdleSpeed; - float hipIdleSpeed; - float fIdleCrouchFactor; - float fIdleProneFactor; - float fGunMaxPitch; - float fGunMaxYaw; - float swayMaxAngle; - float swayLerpSpeed; - float swayPitchScale; - float swayYawScale; - float swayHorizScale; - float swayVertScale; - float swayShellShockScale; - float adsSwayMaxAngle; - float adsSwayLerpSpeed; - float adsSwayPitchScale; - float adsSwayYawScale; - float adsSwayHorizScale; - float adsSwayVertScale; - float adsViewErrorMin; - float adsViewErrorMax; - PhysCollmap* physCollmap; - float dualWieldViewModelOffset; - weaponIconRatioType_t killIconRatio; - int iReloadAmmoAdd; - int iReloadStartAdd; - int ammoDropStockMin; - int ammoDropClipPercentMin; - int ammoDropClipPercentMax; - int iExplosionRadius; - int iExplosionRadiusMin; - int iExplosionInnerDamage; - int iExplosionOuterDamage; - float damageConeAngle; - float bulletExplDmgMult; - float bulletExplRadiusMult; - int iProjectileSpeed; - int iProjectileSpeedUp; - int iProjectileSpeedForward; - int iProjectileActivateDist; - float projLifetime; - float timeToAccelerate; - float projectileCurvature; - XModel* projectileModel; - weapProjExposion_t projExplosion; - FxEffectDef* projExplosionEffect; - FxEffectDef* projDudEffect; - SndAliasCustom projExplosionSound; - SndAliasCustom projDudSound; - WeapStickinessType stickiness; - float lowAmmoWarningThreshold; - float ricochetChance; - float* parallelBounce; - float* perpendicularBounce; - FxEffectDef* projTrailEffect; - FxEffectDef* projBeaconEffect; - float vProjectileColor[3]; - guidedMissileType_t guidedMissileType; - float maxSteeringAccel; - int projIgnitionDelay; - FxEffectDef* projIgnitionEffect; - SndAliasCustom projIgnitionSound; - float fAdsAimPitch; - float fAdsCrosshairInFrac; - float fAdsCrosshairOutFrac; - int adsGunKickReducedKickBullets; - float adsGunKickReducedKickPercent; - float fAdsGunKickPitchMin; - float fAdsGunKickPitchMax; - float fAdsGunKickYawMin; - float fAdsGunKickYawMax; - float fAdsGunKickAccel; - float fAdsGunKickSpeedMax; - float fAdsGunKickSpeedDecay; - float fAdsGunKickStaticDecay; - float fAdsViewKickPitchMin; - float fAdsViewKickPitchMax; - float fAdsViewKickYawMin; - float fAdsViewKickYawMax; - float fAdsViewScatterMin; - float fAdsViewScatterMax; - float fAdsSpread; - int hipGunKickReducedKickBullets; - float hipGunKickReducedKickPercent; - float fHipGunKickPitchMin; - float fHipGunKickPitchMax; - float fHipGunKickYawMin; - float fHipGunKickYawMax; - float fHipGunKickAccel; - float fHipGunKickSpeedMax; - float fHipGunKickSpeedDecay; - float fHipGunKickStaticDecay; - float fHipViewKickPitchMin; - float fHipViewKickPitchMax; - float fHipViewKickYawMin; - float fHipViewKickYawMax; - float fHipViewScatterMin; - float fHipViewScatterMax; - float fightDist; - float maxDist; - // const char* accuracyGraphName[2];// TODO: Order is accuracyGraphName[0] -> originalAccuracyGraphKnots[0] -> accuracyGraphName[1] -> ... - // Which is currently not possible to do in code generation. Afaik this is the only place where this is the case. - // So might be something to fix but on the other hand it might be too much work for this little inconvenience. - // vec2_t* originalAccuracyGraphKnots[2]; - const char* accuracyGraphName0; - const char* accuracyGraphName1; - vec2_t* originalAccuracyGraphKnots0; - vec2_t* originalAccuracyGraphKnots1; - uint16_t originalAccuracyGraphKnotCount[2]; - int iPositionReloadTransTime; - float leftArc; - float rightArc; - float topArc; - float bottomArc; - float accuracy; - float aiSpread; - float playerSpread; - float minTurnSpeed[2]; - float maxTurnSpeed[2]; - float pitchConvergenceTime; - float yawConvergenceTime; - float suppressTime; - float maxRange; - float fAnimHorRotateInc; - float fPlayerPositionDist; - const char* szUseHintString; - const char* dropHintString; - int iUseHintStringIndex; - int dropHintStringIndex; - float horizViewJitter; - float vertViewJitter; - float scanSpeed; - float scanAccel; - int scanPauseTime; - const char* szScript; - float fOOPosAnimLength[2]; - int minDamage; - int minPlayerDamage; - float fMaxDamageRange; - float fMinDamageRange; - float destabilizationRateTime; - float destabilizationCurvatureMax; - int destabilizeDistance; - float* locationDamageMultipliers; - const char* fireRumble; - const char* meleeImpactRumble; - TracerDef* tracerType; - float turretScopeZoomRate; - float turretScopeZoomMin; - float turretScopeZoomMax; - float turretOverheatUpRate; - float turretOverheatDownRate; - float turretOverheatPenalty; - SndAliasCustom turretOverheatSound; - FxEffectDef* turretOverheatEffect; - const char* turretBarrelSpinRumble; - float turretBarrelSpinSpeed; - float turretBarrelSpinUpTime; - float turretBarrelSpinDownTime; - SndAliasCustom turretBarrelSpinMaxSnd; - SndAliasCustom turretBarrelSpinUpSnd[4]; - SndAliasCustom turretBarrelSpinDownSnd[4]; - SndAliasCustom missileConeSoundAlias; - SndAliasCustom missileConeSoundAliasAtBase; - float missileConeSoundRadiusAtTop; - float missileConeSoundRadiusAtBase; - float missileConeSoundHeight; - float missileConeSoundOriginOffset; - float missileConeSoundVolumescaleAtCore; - float missileConeSoundVolumescaleAtEdge; - float missileConeSoundVolumescaleCoreSize; - float missileConeSoundPitchAtTop; - float missileConeSoundPitchAtBottom; - float missileConeSoundPitchTopSize; - float missileConeSoundPitchBottomSize; - float missileConeSoundCrossfadeTopSize; - float missileConeSoundCrossfadeBottomSize; - bool sharedAmmo; - bool lockonSupported; - bool requireLockonToFire; - bool bigExplosion; - bool noAdsWhenMagEmpty; - bool avoidDropCleanup; - bool inheritsPerks; - bool crosshairColorChange; - bool bRifleBullet; - bool armorPiercing; - bool bBoltAction; - bool aimDownSight; - bool bRechamberWhileAds; - bool bBulletExplosiveDamage; - bool bCookOffHold; - bool bClipOnly; - bool noAmmoPickup; - bool adsFireOnly; - bool cancelAutoHolsterWhenEmpty; - bool disableSwitchToWhenEmpty; - bool suppressAmmoReserveDisplay; - bool laserSightDuringNightvision; - bool markableViewmodel; - bool noDualWield; - bool flipKillIcon; - bool bNoPartialReload; - bool bSegmentedReload; - bool blocksProne; - bool silenced; - bool isRollingGrenade; - bool projExplosionEffectForceNormalUp; - bool bProjImpactExplode; - bool stickToPlayers; - bool hasDetonator; - bool disableFiring; - bool timedDetonation; - bool rotate; - bool holdButtonToThrow; - bool freezeMovementWhenFiring; - bool thermalScope; - bool altModeSameWeapon; - bool turretBarrelSpinEnabled; - bool missileConeSoundEnabled; - bool missileConeSoundPitchshiftEnabled; - bool missileConeSoundCrossfadeEnabled; - bool offhandHoldIsCancelable; - }; - - struct WeaponCompleteDef - { - const char* szInternalName; - WeaponDef* weapDef; - const char* szDisplayName; - uint16_t* hideTags; - const char** szXAnims; - float fAdsZoomFov; - int iAdsTransInTime; - int iAdsTransOutTime; - int iClipSize; - ImpactType impactType; - int iFireTime; - weaponIconRatioType_t dpadIconRatio; - float penetrateMultiplier; - float fAdsViewKickCenterSpeed; - float fHipViewKickCenterSpeed; - const char* szAltWeaponName; - unsigned int altWeaponIndex; - int iAltRaiseTime; - Material* killIcon; - Material* dpadIcon; - int fireAnimLength; - int iFirstRaiseTime; - int ammoDropStockMax; - float adsDofStart; - float adsDofEnd; - uint16_t accuracyGraphKnotCount[2]; - vec2_t* accuracyGraphKnots[2]; - bool motionTracker; - bool enhanced; - bool dpadIconShowsAmmo; - }; - - struct WeaponFullDef - { - WeaponCompleteDef weapCompleteDef; - WeaponDef weapDef; - uint16_t hideTags[32]; - const char* szXAnims[37]; - XModel* gunXModel[16]; - const char* szXAnimsRightHanded[37]; - const char* szXAnimsLeftHanded[37]; - uint16_t notetrackSoundMapKeys[16]; - uint16_t notetrackSoundMapValues[16]; - uint16_t notetrackRumbleMapKeys[16]; - uint16_t notetrackRumbleMapValues[16]; - XModel* worldModel[16]; - float parallelBounce[31]; - float perpendicularBounce[31]; - float locationDamageMultipliers[20]; - }; - - enum VehicleAxleType - { - VEH_AXLE_FRONT = 0x0, - VEH_AXLE_REAR = 0x1, - VEH_AXLE_ALL = 0x2, - VEH_AXLE_COUNT = 0x3, - }; - - struct VehiclePhysDef - { - int physicsEnabled; - const char* physPresetName; - PhysPreset* physPreset; - const char* accelGraphName; - VehicleAxleType steeringAxle; - VehicleAxleType powerAxle; - VehicleAxleType brakingAxle; - float topSpeed; - float reverseSpeed; - float maxVelocity; - float maxPitch; - float maxRoll; - float suspensionTravelFront; - float suspensionTravelRear; - float suspensionStrengthFront; - float suspensionDampingFront; - float suspensionStrengthRear; - float suspensionDampingRear; - float frictionBraking; - float frictionCoasting; - float frictionTopSpeed; - float frictionSide; - float frictionSideRear; - float velocityDependentSlip; - float rollStability; - float rollResistance; - float pitchResistance; - float yawResistance; - float uprightStrengthPitch; - float uprightStrengthRoll; - float targetAirPitch; - float airYawTorque; - float airPitchTorque; - float minimumMomentumForCollision; - float collisionLaunchForceScale; - float wreckedMassScale; - float wreckedBodyFriction; - float minimumJoltForNotify; - float slipThresholdFront; - float slipThresholdRear; - float slipFricScaleFront; - float slipFricScaleRear; - float slipFricRateFront; - float slipFricRateRear; - float slipYawTorque; - }; - - enum VehicleType - { - VEH_WHEELS_4 = 0x0, - VEH_TANK = 0x1, - VEH_PLANE = 0x2, - VEH_BOAT = 0x3, - VEH_ARTILLERY = 0x4, - VEH_HELICOPTER = 0x5, - VEH_SNOWMOBILE = 0x6, - VEH_TYPE_COUNT = 0x7, - }; - - - struct VehicleDef - { - const char* name; - VehicleType type; - const char* useHintString; - int health; - int quadBarrel; - float texScrollScale; - float topSpeed; - float accel; - float rotRate; - float rotAccel; - float maxBodyPitch; - float maxBodyRoll; - float fakeBodyAccelPitch; - float fakeBodyAccelRoll; - float fakeBodyVelPitch; - float fakeBodyVelRoll; - float fakeBodySideVelPitch; - float fakeBodyPitchStrength; - float fakeBodyRollStrength; - float fakeBodyPitchDampening; - float fakeBodyRollDampening; - float fakeBodyBoatRockingAmplitude; - float fakeBodyBoatRockingPeriod; - float fakeBodyBoatRockingRotationPeriod; - float fakeBodyBoatRockingFadeoutSpeed; - float boatBouncingMinForce; - float boatBouncingMaxForce; - float boatBouncingRate; - float boatBouncingFadeinSpeed; - float boatBouncingFadeoutSteeringAngle; - float collisionDamage; - float collisionSpeed; - float killcamOffset[3]; - int playerProtected; - int bulletDamage; - int armorPiercingDamage; - int grenadeDamage; - int projectileDamage; - int projectileSplashDamage; - int heavyExplosiveDamage; - VehiclePhysDef vehPhysDef; - float boostDuration; - float boostRechargeTime; - float boostAcceleration; - float suspensionTravel; - float maxSteeringAngle; - float steeringLerp; - float minSteeringScale; - float minSteeringSpeed; - int camLookEnabled; - float camLerp; - float camPitchInfluence; - float camRollInfluence; - float camFovIncrease; - float camFovOffset; - float camFovSpeed; - const char* turretWeaponName; - WeaponCompleteDef* turretWeapon; - float turretHorizSpanLeft; - float turretHorizSpanRight; - float turretVertSpanUp; - float turretVertSpanDown; - float turretRotRate; - SndAliasCustom turretSpinSnd; - SndAliasCustom turretStopSnd; - int trophyEnabled; - float trophyRadius; - float trophyInactiveRadius; - int trophyAmmoCount; - float trophyReloadTime; - uint16_t trophyTags[4]; - Material* compassFriendlyIcon; - Material* compassEnemyIcon; - int compassIconWidth; - int compassIconHeight; - SndAliasCustom idleLowSnd; - SndAliasCustom idleHighSnd; - SndAliasCustom engineLowSnd; - SndAliasCustom engineHighSnd; - float engineSndSpeed; - SndAliasCustom engineStartUpSnd; - int engineStartUpLength; - SndAliasCustom engineShutdownSnd; - SndAliasCustom engineIdleSnd; - SndAliasCustom engineSustainSnd; - SndAliasCustom engineRampUpSnd; - int engineRampUpLength; - SndAliasCustom engineRampDownSnd; - int engineRampDownLength; - SndAliasCustom suspensionSoftSnd; - float suspensionSoftCompression; - SndAliasCustom suspensionHardSnd; - float suspensionHardCompression; - SndAliasCustom collisionSnd; - float collisionBlendSpeed; - SndAliasCustom speedSnd; - float speedSndBlendSpeed; - const char* surfaceSndPrefix; - SndAliasCustom surfaceSnds[31]; - float surfaceSndBlendSpeed; - float slideVolume; - float slideBlendSpeed; - float inAirPitch; - }; +enum XAssetType { + ASSET_TYPE_PHYSPRESET = 0x0, + ASSET_TYPE_PHYSCOLLMAP = 0x1, + ASSET_TYPE_XANIMPARTS = 0x2, + ASSET_TYPE_XMODEL_SURFS = 0x3, + ASSET_TYPE_XMODEL = 0x4, + ASSET_TYPE_MATERIAL = 0x5, + ASSET_TYPE_PIXELSHADER = 0x6, + ASSET_TYPE_VERTEXSHADER = 0x7, + ASSET_TYPE_VERTEXDECL = 0x8, + ASSET_TYPE_TECHNIQUE_SET = 0x9, + ASSET_TYPE_IMAGE = 0xA, + ASSET_TYPE_SOUND = 0xB, + ASSET_TYPE_SOUND_CURVE = 0xC, + ASSET_TYPE_LOADED_SOUND = 0xD, + ASSET_TYPE_CLIPMAP_SP = 0xE, + ASSET_TYPE_CLIPMAP_MP = 0xF, + ASSET_TYPE_COMWORLD = 0x10, + ASSET_TYPE_GAMEWORLD_SP = 0x11, + ASSET_TYPE_GAMEWORLD_MP = 0x12, + ASSET_TYPE_MAP_ENTS = 0x13, + ASSET_TYPE_FXWORLD = 0x14, + ASSET_TYPE_GFXWORLD = 0x15, + ASSET_TYPE_LIGHT_DEF = 0x16, + ASSET_TYPE_UI_MAP = 0x17, + ASSET_TYPE_FONT = 0x18, + ASSET_TYPE_MENULIST = 0x19, + ASSET_TYPE_MENU = 0x1A, + ASSET_TYPE_LOCALIZE_ENTRY = 0x1B, + ASSET_TYPE_WEAPON = 0x1C, + ASSET_TYPE_SNDDRIVER_GLOBALS = 0x1D, + ASSET_TYPE_FX = 0x1E, + ASSET_TYPE_IMPACT_FX = 0x1F, + ASSET_TYPE_AITYPE = 0x20, + ASSET_TYPE_MPTYPE = 0x21, + ASSET_TYPE_CHARACTER = 0x22, + ASSET_TYPE_XMODELALIAS = 0x23, + ASSET_TYPE_RAWFILE = 0x24, + ASSET_TYPE_STRINGTABLE = 0x25, + ASSET_TYPE_LEADERBOARD = 0x26, + ASSET_TYPE_STRUCTURED_DATA_DEF = 0x27, + ASSET_TYPE_TRACER = 0x28, + ASSET_TYPE_VEHICLE = 0x29, + ASSET_TYPE_ADDON_MAP_ENTS = 0x2A, + + ASSET_TYPE_COUNT, + ASSET_TYPE_STRING = ASSET_TYPE_COUNT, + ASSET_TYPE_ASSETLIST = 0x2C, + + ASSET_TYPE_FULLCOUNT +}; + +enum XFileBlock { + XFILE_BLOCK_TEMP, + XFILE_BLOCK_PHYSICAL, + XFILE_BLOCK_RUNTIME, + XFILE_BLOCK_VIRTUAL, + XFILE_BLOCK_LARGE, + XFILE_BLOCK_CALLBACK, + XFILE_BLOCK_VERTEX, + XFILE_BLOCK_INDEX, + + MAX_XFILE_COUNT, +}; + +struct PhysPreset; +struct PhysCollmap; +struct XAnimParts; +struct XModel; +struct Material; +struct MaterialPixelShader; +struct MaterialVertexShader; +struct MaterialVertexDeclaration; +struct MaterialTechniqueSet; +struct GfxImage; +struct snd_alias_list_t; +struct SndCurve; +struct LoadedSound; +struct clipMap_t; +struct ComWorld; +struct GameWorldSp; +struct GameWorldMp; +struct MapEnts; +struct FxWorld; +struct GfxWorld; +struct GfxLightDef; +struct Font_s; +struct MenuList; +struct menuDef_t; +struct LocalizeEntry; +struct WeaponCompleteDef; +// struct SndDriverGlobals; +struct FxEffectDef; +struct FxImpactTable; +struct RawFile; +struct StringTable; +struct LeaderboardDef; +struct StructuredDataDefSet; +struct TracerDef; +struct VehicleDef; +struct AddonMapEnts; + +union XAssetHeader { + PhysPreset *physPreset; + PhysCollmap *physCollmap; + XAnimParts *parts; + // XModelSurfs* modelSurfs; // NOT AN ASSET + XModel *model; + Material *material; + MaterialPixelShader *pixelShader; + MaterialVertexShader *vertexShader; + MaterialVertexDeclaration *vertexDecl; + MaterialTechniqueSet *techniqueSet; + GfxImage *image; + snd_alias_list_t *sound; + SndCurve *sndCurve; + LoadedSound *loadSnd; + clipMap_t *clipMap; + ComWorld *comWorld; + GameWorldSp *gameWorldSp; + GameWorldMp *gameWorldMp; + MapEnts *mapEnts; + FxWorld *fxWorld; + GfxWorld *gfxWorld; + GfxLightDef *lightDef; + Font_s *font; + MenuList *menuList; + menuDef_t *menu; + LocalizeEntry *localize; + WeaponCompleteDef *weapon; + // SndDriverGlobals* sndDriverGlobals; // UNUSED ON PC + FxEffectDef *fx; + FxImpactTable *impactFx; + RawFile *rawfile; + StringTable *stringTable; + LeaderboardDef *leaderboardDef; + StructuredDataDefSet *structuredDataDefSet; + TracerDef *tracerDef; + VehicleDef *vehDef; + AddonMapEnts *addonMapEnts; + void *data; +}; + +typedef tdef_align(16) char raw_byte16; +typedef tdef_align(16) float raw_float16; +typedef unsigned int raw_uint; +typedef tdef_align(128) unsigned int raw_uint128; +typedef unsigned char cbrushedge_t; +typedef unsigned short r_index_t; +typedef float vec2_t[2]; +typedef float vec3_t[3]; +typedef float vec4_t[4]; + +struct PhysPreset { + const char *name; + int type; + float mass; + float bounce; + float friction; + float bulletForceScale; + float explosiveForceScale; + const char *sndAliasPrefix; + float piecesSpreadFraction; + float piecesUpwardVelocity; + bool tempDefaultToCylinder; + bool perSurfaceSndAlias; +}; + +struct PhysPresetInfo { + float mass; + float bounce; + float friction; + int isFrictionInfinity; + float bulletForceScale; + float explosiveForceScale; + const char *sndAliasPrefix; + float piecesSpreadFraction; + float piecesUpwardVelocity; + int tempDefaultToCylinder; + int perSurfaceSndAlias; +}; + +struct Bounds { + float midPoint[3]; + float halfSize[3]; +}; + +struct cplane_s { + float normal[3]; + float dist; + char type; + char pad[3]; +}; + +struct cbrushside_t { + cplane_s *plane; + uint16_t materialNum; + char firstAdjacentSideOffset; + char edgeCount; +}; + +struct cbrushWrapper_t { + uint16_t numsides; + uint16_t glassPieceIndex; + cbrushside_t *sides; + cbrushedge_t *baseAdjacentSide; + int16_t axialMaterialNum[2][3]; + unsigned char firstAdjacentSideOffsets[2][3]; + unsigned char edgeCount[2][3]; +}; + +struct BrushWrapper { + Bounds bounds; + cbrushWrapper_t brush; + int totalEdgeCount; + cplane_s *planes; +}; + +enum PhysicsGeomType { + PHYS_GEOM_NONE = 0x0, + PHYS_GEOM_BOX = 0x1, + PHYS_GEOM_BRUSHMODEL = 0x2, + PHYS_GEOM_BRUSH = 0x3, + PHYS_GEOM_COLLMAP = 0x4, + PHYS_GEOM_CYLINDER = 0x5, + PHYS_GEOM_CAPSULE = 0x6, + PHYS_GEOM_GLASS = 0x7, + + PHYS_GEOM_COUNT, +}; + +struct PhysGeomInfo { + BrushWrapper *brushWrapper; + int type; + float orientation[3][3]; + Bounds bounds; +}; + +struct PhysMass { + float centerOfMass[3]; + float momentsOfInertia[3]; + float productsOfInertia[3]; +}; + +struct PhysCollmap { + const char *name; + unsigned int count; + PhysGeomInfo *geoms; + PhysMass mass; + Bounds bounds; +}; + +union XAnimIndices { + char *_1; + uint16_t *_2; + void *data; +}; + +struct XAnimNotifyInfo { + uint16_t name; + float time; +}; + +typedef unsigned char ByteVec[3]; +typedef tdef_align(4) unsigned short UShortVec[3]; + +union XAnimDynamicFrames { + ByteVec *_1; + UShortVec *_2; +}; + +union XAnimDynamicIndicesTrans { + char _1[1]; + uint16_t _2[1]; +}; + +struct type_align(4) XAnimPartTransFrames { + float mins[3]; + float size[3]; + XAnimDynamicFrames frames; + XAnimDynamicIndicesTrans indices; +}; + +union XAnimPartTransData { + XAnimPartTransFrames frames; + vec3_t frame0; +}; + +struct XAnimPartTrans { + uint16_t size; + char smallTrans; + XAnimPartTransData u; +}; + +union XAnimDynamicIndicesQuat2 { + char _1[1]; + uint16_t _2[1]; +}; + +typedef tdef_align(4) short XQuat2[2]; + +struct type_align(4) XAnimDeltaPartQuatDataFrames2 { + XQuat2 *frames; + XAnimDynamicIndicesQuat2 indices; +}; + +union XAnimDeltaPartQuatData2 { + XAnimDeltaPartQuatDataFrames2 frames; + int16_t frame0[2]; +}; + +struct XAnimDeltaPartQuat2 { + uint16_t size; + XAnimDeltaPartQuatData2 u; +}; + +union XAnimDynamicIndicesQuat { + char _1[1]; + uint16_t _2[1]; +}; + +typedef tdef_align(4) short XQuat[4]; + +struct XAnimDeltaPartQuatDataFrames { + XQuat *frames; + XAnimDynamicIndicesQuat indices; +}; + +union XAnimDeltaPartQuatData { + XAnimDeltaPartQuatDataFrames frames; + int16_t frame0[4]; +}; + +struct XAnimDeltaPartQuat { + uint16_t size; + XAnimDeltaPartQuatData u; +}; + +struct XAnimDeltaPart { + XAnimPartTrans *trans; + XAnimDeltaPartQuat2 *quat2; + XAnimDeltaPartQuat *quat; +}; + +struct XAnimParts { + const char *name; + uint16_t dataByteCount; + uint16_t dataShortCount; + uint16_t dataIntCount; + uint16_t randomDataByteCount; + uint16_t randomDataIntCount; + uint16_t numframes; + char flags; + unsigned char boneCount[10]; + char notifyCount; + char assetType; + bool isDefault; + unsigned int randomDataShortCount; + unsigned int indexCount; + float framerate; + float frequency; + uint16_t *names; + char *dataByte; + int16_t *dataShort; + int *dataInt; + int16_t *randomDataShort; + char *randomDataByte; + int *randomDataInt; + XAnimIndices indices; + XAnimNotifyInfo *notify; + XAnimDeltaPart *deltaPart; +}; + +struct DObjSkelMat { + float axis[3][4]; + float origin[4]; +}; + +struct XSurfaceVertexInfo { + int16_t vertCount[4]; + uint16_t *vertsBlend; +}; + +union GfxColor { + unsigned int packed; + char array[4]; +}; + +union PackedTexCoords { + unsigned int packed; +}; + +union PackedUnitVec { + unsigned int packed; + char array[4]; +}; + +struct type_align(16) GfxPackedVertex { + float xyz[3]; + float binormalSign; + GfxColor color; + PackedTexCoords texCoord; + PackedUnitVec normal; + PackedUnitVec tangent; +}; + +struct XSurfaceCollisionAabb { + uint16_t mins[3]; + uint16_t maxs[3]; +}; + +struct type_align(16) XSurfaceCollisionNode { + XSurfaceCollisionAabb aabb; + uint16_t childBeginIndex; + uint16_t childCount; +}; + +struct XSurfaceCollisionLeaf { + uint16_t triangleBeginIndex; +}; + +struct XSurfaceCollisionTree { + float trans[3]; + float scale[3]; + unsigned int nodeCount; + XSurfaceCollisionNode *nodes; + unsigned int leafCount; + XSurfaceCollisionLeaf *leafs; +}; + +struct XRigidVertList { + uint16_t boneOffset; + uint16_t vertCount; + uint16_t triOffset; + uint16_t triCount; + XSurfaceCollisionTree *collisionTree; +}; + +typedef tdef_align(16) uint16_t r_index16_t; + +struct XSurface { + char tileMode; + bool deformed; + uint16_t vertCount; + uint16_t triCount; + char zoneHandle; + uint16_t baseTriIndex; + uint16_t baseVertIndex; + r_index16_t (*triIndices)[3]; + XSurfaceVertexInfo vertInfo; + GfxPackedVertex *verts0; + unsigned int vertListCount; + XRigidVertList *vertList; + int partBits[6]; +}; + +struct XModelSurfs { + const char *name; + XSurface *surfs; + uint16_t numsurfs; + int partBits[6]; +}; + +struct XModelLodInfo { + float dist; + uint16_t numsurfs; + uint16_t surfIndex; + XModelSurfs *modelSurfs; + int partBits[6]; + XSurface *surfs; + char lod; + char smcBaseIndexPlusOne; + char smcSubIndexMask; + char smcBucket; +}; + +struct XModelCollTri_s { + float plane[4]; + float svec[4]; + float tvec[4]; +}; + +struct XModelCollSurf_s { + XModelCollTri_s *collTris; + int numCollTris; + Bounds bounds; + int boneIdx; + int contents; + int surfFlags; +}; + +struct XBoneInfo { + Bounds bounds; + float radiusSquared; +}; + +struct DObjAnimMat { + float quat[4]; + float trans[3]; + float transWeight; +}; + +struct XModel { + const char *name; + unsigned char numBones; + unsigned char numRootBones; + unsigned char numsurfs; + char lodRampType; + float scale; + unsigned int noScalePartBits[6]; + uint16_t *boneNames; + unsigned char *parentList; + int16_t (*quats)[4]; + float (*trans)[3]; + unsigned char *partClassification; + DObjAnimMat *baseMat; + Material **materialHandles; + XModelLodInfo lodInfo[4]; + char maxLoadedLod; + unsigned char numLods; + unsigned char collLod; + char flags; + XModelCollSurf_s *collSurfs; + int numCollSurfs; + int contents; + XBoneInfo *boneInfo; + float radius; + Bounds bounds; + int memUsage; + bool bad; + PhysPreset *physPreset; + PhysCollmap *physCollmap; +}; + +struct WaterWritable { + float floatTime; +}; + +struct complex_s { + float real; + float imag; +}; + +struct water_t { + WaterWritable writable; + complex_s *H0; + float *wTerm; + int M; + int N; + float Lx; + float Lz; + float gravity; + float windvel; + float winddir[2]; + float amplitude; + float codeConstant[4]; + GfxImage *image; +}; + +union MaterialTextureDefInfo { + GfxImage *image; + water_t *water; +}; + +enum MaterialTextureFilter { + TEXTURE_FILTER_DISABLED = 0x0, + TEXTURE_FILTER_NEAREST = 0x1, + TEXTURE_FILTER_LINEAR = 0x2, + TEXTURE_FILTER_ANISO2X = 0x3, + TEXTURE_FILTER_ANISO4X = 0x4, + + TEXTURE_FILTER_COUNT +}; + +enum SamplerStateBits_e { + SAMPLER_FILTER_SHIFT = 0x0, + SAMPLER_FILTER_NEAREST = 0x1, + SAMPLER_FILTER_LINEAR = 0x2, + SAMPLER_FILTER_ANISO2X = 0x3, + SAMPLER_FILTER_ANISO4X = 0x4, + SAMPLER_FILTER_MASK = 0x7, + + SAMPLER_MIPMAP_SHIFT = 0x3, + SAMPLER_MIPMAP_DISABLED = 0x0, + SAMPLER_MIPMAP_NEAREST = 0x8, + SAMPLER_MIPMAP_LINEAR = 0x10, + SAMPLER_MIPMAP_COUNT = 0x3, + SAMPLER_MIPMAP_MASK = 0x18, + + SAMPLER_CLAMP_U_SHIFT = 0x5, + SAMPLER_CLAMP_V_SHIFT = 0x6, + SAMPLER_CLAMP_W_SHIFT = 0x7, + SAMPLER_CLAMP_U = 0x20, + SAMPLER_CLAMP_V = 0x40, + SAMPLER_CLAMP_W = 0x80, + SAMPLER_CLAMP_MASK = 0xE0, +}; + +struct MaterialTextureDef { + unsigned int nameHash; + char nameStart; + char nameEnd; + unsigned char samplerState; // SamplerStateBits_e + unsigned char semantic; // TextureSemantic + MaterialTextureDefInfo u; +}; + +struct type_align(16) MaterialConstantDef { + unsigned int nameHash; + char name[12]; + float literal[4]; +}; + +enum GfxBlend : unsigned int { + GFXS_BLEND_DISABLED = 0x0, + GFXS_BLEND_ZERO = 0x1, + GFXS_BLEND_ONE = 0x2, + GFXS_BLEND_SRCCOLOR = 0x3, + GFXS_BLEND_INVSRCCOLOR = 0x4, + GFXS_BLEND_SRCALPHA = 0x5, + GFXS_BLEND_INVSRCALPHA = 0x6, + GFXS_BLEND_DESTALPHA = 0x7, + GFXS_BLEND_INVDESTALPHA = 0x8, + GFXS_BLEND_DESTCOLOR = 0x9, + GFXS_BLEND_INVDESTCOLOR = 0xA, + GFXS_BLEND_MASK = 0xF, +}; + +enum GfxBlendOp : unsigned int { + GFXS_BLENDOP_DISABLED = 0x0, + GFXS_BLENDOP_ADD = 0x1, + GFXS_BLENDOP_SUBTRACT = 0x2, + GFXS_BLENDOP_REVSUBTRACT = 0x3, + GFXS_BLENDOP_MIN = 0x4, + GFXS_BLENDOP_MAX = 0x5, + GFXS_BLENDOP_MASK = 0x7, +}; + +enum GfxStencilFunc : unsigned int { + GFXS_STENCILFUNC_NEVER = 0x0, + GFXS_STENCILFUNC_LESS = 0x1, + GFXS_STENCILFUNC_EQUAL = 0x2, + GFXS_STENCILFUNC_LESSEQUAL = 0x3, + GFXS_STENCILFUNC_GREATER = 0x4, + GFXS_STENCILFUNC_NOTEQUAL = 0x5, + GFXS_STENCILFUNC_GREATEREQUAL = 0x6, + GFXS_STENCILFUNC_ALWAYS = 0x7, + + GFXS_STENCILFUNC_COUNT, + GFXS_STENCILFUNC_MASK = 0x7 +}; + +enum GfxStencilOp : unsigned int { + GFXS_STENCILOP_KEEP = 0x0, + GFXS_STENCILOP_ZERO = 0x1, + GFXS_STENCILOP_REPLACE = 0x2, + GFXS_STENCILOP_INCRSAT = 0x3, + GFXS_STENCILOP_DECRSAT = 0x4, + GFXS_STENCILOP_INVERT = 0x5, + GFXS_STENCILOP_INCR = 0x6, + GFXS_STENCILOP_DECR = 0x7, + + GFXS_STENCILOP_COUNT, + GFXS_STENCILOP_MASK = 0x7 +}; + +enum GfxStateBitsEnum : unsigned int { + GFXS0_SRCBLEND_RGB_SHIFT = 0x0, + GFXS0_SRCBLEND_RGB_MASK = 0xF, + + GFXS0_DSTBLEND_RGB_SHIFT = 0x4, + GFXS0_DSTBLEND_RGB_MASK = 0xF0, + + GFXS0_BLENDOP_RGB_SHIFT = 0x8, + GFXS0_BLENDOP_RGB_MASK = 0x700, + GFXS0_BLEND_RGB_MASK = 0x7FF, + + GFXS0_ATEST_DISABLE = 0x800, + GFXS0_ATEST_GT_0 = 0x1000, + GFXS0_ATEST_LT_128 = 0x2000, + GFXS0_ATEST_GE_128 = 0x3000, + GFXS0_ATEST_MASK = 0x3000, + + GFXS0_CULL_NONE = 0x4000, + GFXS0_CULL_BACK = 0x8000, + GFXS0_CULL_FRONT = 0xC000, + GFXS0_CULL_SHIFT = 0xE, + GFXS0_CULL_MASK = 0xC000, + + GFXS0_SRCBLEND_ALPHA_SHIFT = 0x10, + GFXS0_SRCBLEND_ALPHA_MASK = 0xF0000, + + GFXS0_DSTBLEND_ALPHA_SHIFT = 0x14, + GFXS0_DSTBLEND_ALPHA_MASK = 0xF00000, + + GFXS0_BLENDOP_ALPHA_SHIFT = 0x18, + GFXS0_BLENDOP_ALPHA_MASK = 0x7000000, + GFXS0_BLEND_ALPHA_MASK = 0x7FF0000, + + GFXS0_COLORWRITE_RGB = 0x8000000, + GFXS0_COLORWRITE_ALPHA = 0x10000000, + GFXS0_COLORWRITE_MASK = 0x18000000, + + GFXS0_GAMMAWRITE = 0x40000000, + GFXS0_POLYMODE_LINE = 0x80000000, + + GFXS1_DEPTHWRITE = 0x1, + + GFXS1_DEPTHTEST_DISABLE = 0x2, + GFXS1_DEPTHTEST_ALWAYS = 0x0, + GFXS1_DEPTHTEST_LESS = 0x4, + GFXS1_DEPTHTEST_EQUAL = 0x8, + GFXS1_DEPTHTEST_LESSEQUAL = 0xC, + GFXS1_DEPTHTEST_SHIFT = 0x2, + GFXS1_DEPTHTEST_MASK = 0xC, + + GFXS1_POLYGON_OFFSET_0 = 0x0, + GFXS1_POLYGON_OFFSET_1 = 0x10, + GFXS1_POLYGON_OFFSET_2 = 0x20, + GFXS1_POLYGON_OFFSET_SHADOWMAP = 0x30, + GFXS1_POLYGON_OFFSET_SHIFT = 0x4, + GFXS1_POLYGON_OFFSET_MASK = 0x30, + + GFXS1_STENCIL_FRONT_ENABLE = 0x40, + GFXS1_STENCIL_BACK_ENABLE = 0x80, + GFXS1_STENCIL_MASK = 0xC0, + + GFXS1_STENCIL_FRONT_PASS_SHIFT = 0x8, + GFXS1_STENCIL_FRONT_PASS_MASK = 0x700, + + GFXS1_STENCIL_FRONT_FAIL_SHIFT = 0xB, + GFXS1_STENCIL_FRONT_FAIL_MASK = 0x3800, + + GFXS1_STENCIL_FRONT_ZFAIL_SHIFT = 0xE, + GFXS1_STENCIL_FRONT_ZFAIL_MASK = 0x1C000, + + GFXS1_STENCIL_FRONT_FUNC_SHIFT = 0x11, + GFXS1_STENCIL_FRONT_FUNC_MASK = 0xE0000, + GFXS1_STENCIL_FRONT_MASK = 0xFFF00, + + GFXS1_STENCIL_BACK_PASS_SHIFT = 0x14, + GFXS1_STENCIL_BACK_PASS_MASK = 0x700000, + + GFXS1_STENCIL_BACK_FAIL_SHIFT = 0x17, + GFXS1_STENCIL_BACK_FAIL_MASK = 0x3800000, + + GFXS1_STENCIL_BACK_ZFAIL_SHIFT = 0x1A, + GFXS1_STENCIL_BACK_ZFAIL_MASK = 0x1C000000, + + GFXS1_STENCIL_BACK_FUNC_SHIFT = 0x1D, + GFXS1_STENCIL_BACK_FUNC_MASK = 0xE0000000, + GFXS1_STENCIL_BACK_MASK = 0xFFF00000, + + GFXS1_STENCILFUNC_FRONTBACK_MASK = 0xE00E0000, + GFXS1_STENCILOP_FRONTBACK_MASK = 0x1FF1FF00, +}; + +struct GfxStateBits { + unsigned int loadBits[2]; +}; + +struct infoParm_t { + const char *name; + unsigned int clearSolid; + unsigned int surfaceFlags; + unsigned int contents; + unsigned int toolFlags; +}; + +struct gcc_align(8) GfxDrawSurfFields { + uint64_t objectId : 16; + uint64_t reflectionProbeIndex : 8; + uint64_t hasGfxEntIndex : 1; + uint64_t customIndex : 5; + uint64_t materialSortedIndex : 12; + uint64_t prepass : 2; + uint64_t useHeroLighting : 1; + uint64_t sceneLightIndex : 8; + uint64_t surfType : 4; + uint64_t primarySortKey : 6; + uint64_t unused : 1; +}; + +union GfxDrawSurf { + gcc_align(8) GfxDrawSurfFields fields; + gcc_align(8) uint64_t packed; +}; + +// The sort key is translated to a numeric value inside the material templates +// when converting the material. +// TODO: Try to find out which value is which sort key by investigating on materials +enum SortKey_e { + SORTKEY_OPAQUE_AMBIENT = 0, + SORTKEY_OPAQUE = 1, + SORTKEY_SKY = 2, + SORTKEY_SKYBOX = 3, + // ? = 4, // some kind of dynamic decal? + // ? = 5, // another kind of dynamic decal? + + SORTKEY_TRANS_START = 6, + + SORTKEY_DECAL_BOTTOM_1 = 6, // prob decal - bottom 1 + SORTKEY_DECAL_BOTTOM_2 = 7, // prob decal - bottom 2 + SORTKEY_DECAL_BOTTOM_3 = 8, // prob decal - bottom 3 + SORTKEY_DECAL_STATIC_DECAL = 9, // prob decal - static decal + SORTKEY_DECAL_MIDDLE_1 = 10, // prob decal - middle 1 + SORTKEY_DECAL_MIDDLE_2 = 11, // prob decal - middle 2 + SORTKEY_DECAL_MIDDLE_3 = 12, // prob decal - middle 3 + SORTKEY_DECAL_WEAPON_IMPACT = 13, // prob decal - weapon impact + // ? = 14, // prob decal - top 1 + // some decal = 15, // prob decal - top 2 or decal - top 3 + // some decal = 16, + // prob decal = 17, + // ? = 18, + // water related = 19, // maybe underwater + // water related = 20, // maybe transparent water + // ? = 21, + // - = 22, + // - = 23, + SORTKEY_WINDOW_INSIDE = 24, // prob window inside + SORTKEY_WINDOW_OUTSIDE = 25, // prob window outside + // ? = 26, // includes motiontracker3d, impact fx, atmos + // ? = 27, + // ? = 28, + // ? = 29, + // ? = 30, + // ? = 31, + // - = 32, + // ? = 33, + // some ui/2d/fullscreen sort = 34, + // - = 35, + // - = 36, + // - = 37, + // - = 38, + // - = 39, + // - = 40, + // framecolordebug = 41, // multiplicative? + // - = 42, + SORTKEY_DISTORTION = 43, + // ? = 44, + // ? = 45, + // - = 46, + SORTKEY_BLEND_ADDITIVE = 47, // most likely blend / additive + SORTKEY_EFFECT_AUTO_SORT = 48, // most likely effect - auto sort + SORTKEY_AFTER_EFFECTS_BOTTOM = 49, + SORTKEY_AFTER_EFFECTS_MIDDLE = 50, // prob after effects - middle + SORTKEY_AFTER_EFFECTS_TOP = 51, // prob after effects - top + // - = 52, + SORTKEY_VIEWMODEL_EFFECT = 53, // maybe viewmodel effect + + SORTKEY_MAX +}; + +// Names unknown +// There's probably: MTL_GAMEFLAG_CASTS_SHADOW (part of iw3; 0x40 there) +enum MaterialGameFlags { + MTL_GAMEFLAG_1 = 0x1, + MTL_GAMEFLAG_2 = 0x2, + MTL_GAMEFLAG_4 = 0x4, + MTL_GAMEFLAG_8 = 0x8, + MTL_GAMEFLAG_10 = 0x10, + MTL_GAMEFLAG_20 = 0x20, + MTL_GAMEFLAG_40 = 0x40, + MTL_GAMEFLAG_80 = 0x80, +}; + +struct MaterialInfo { + const char *name; + unsigned char gameFlags; + unsigned char sortKey; // SortKey_e + unsigned char textureAtlasRowCount; + unsigned char textureAtlasColumnCount; + GfxDrawSurf drawSurf; // seems to be zeroed when loading + unsigned int surfaceTypeBits; + uint16_t hashIndex; +}; + +enum GfxCameraRegionType { + CAMERA_REGION_LIT_OPAQUE = 0x0, + CAMERA_REGION_LIT_TRANS = 0x1, + CAMERA_REGION_EMISSIVE = 0x2, + CAMERA_REGION_DEPTH_HACK = 0x3, + + CAMERA_REGION_COUNT, + CAMERA_REGION_NONE = CAMERA_REGION_COUNT, +}; + +enum MaterialStateFlags { + STATE_FLAG_CULL_BACK = 0x1, + STATE_FLAG_AMBIENT = 0x2, + STATE_FLAG_DECAL = 0x4, + STATE_FLAG_WRITES_DEPTH = 0x8, + STATE_FLAG_USES_DEPTH_BUFFER = 0x10, + STATE_FLAG_USES_STENCIL_BUFFER = 0x20, + STATE_FLAG_CULL_BACK_SHADOW = 0x40, +}; + +struct Material { + MaterialInfo info; + unsigned char stateBitsEntry[48]; + unsigned char textureCount; + unsigned char constantCount; + unsigned char stateBitsCount; + unsigned char stateFlags; + unsigned char cameraRegion; // GfxCameraRegionType + MaterialTechniqueSet *techniqueSet; + MaterialTextureDef *textureTable; + MaterialConstantDef *constantTable; + GfxStateBits *stateBitsTable; +}; + +struct type_align(4) GfxImageLoadDef { + char levelCount; + char pad[3]; + int flags; + int format; + int resourceSize; + char data[1]; +}; + +union GfxTexture { + // IDirect3DBaseTexture9* basemap; + // IDirect3DTexture9* map; + // IDirect3DVolumeTexture9* volmap; + // IDirect3DCubeTexture9* cubemap; + Texture *texture; + GfxImageLoadDef *loadDef; +}; + +struct Picmip { + char platform[2]; +}; + +struct CardMemory { + int platform[2]; +}; + +enum TextureSemantic { + TS_2D = 0x0, + TS_FUNCTION = 0x1, + TS_COLOR_MAP = 0x2, + TS_DETAIL_MAP = 0x3, + TS_UNUSED_2 = 0x4, + TS_NORMAL_MAP = 0x5, + TS_UNUSED_3 = 0x6, + TS_UNUSED_4 = 0x7, + TS_SPECULAR_MAP = 0x8, + TS_UNUSED_5 = 0x9, + TS_UNUSED_6 = 0xA, + TS_WATER_MAP = 0xB, +}; + +struct GfxImage { + GfxTexture texture; + unsigned char mapType; + unsigned char semantic; + unsigned char category; + bool useSrgbReads; + Picmip picmip; + bool noPicmip; + char track; + CardMemory cardMemory; + uint16_t width; + uint16_t height; + uint16_t depth; + bool delayLoadPixels; + const char *name; +}; + +struct GfxPixelShaderLoadDef { + unsigned int *program; + uint16_t programSize; + uint16_t loadForRenderer; +}; + +struct GfxVertexShaderLoadDef { + unsigned int *program; + uint16_t programSize; + uint16_t loadForRenderer; +}; + +enum MaterialStreamStreamSource_e { + STREAM_SRC_POSITION = 0x0, + STREAM_SRC_COLOR = 0x1, + STREAM_SRC_TEXCOORD_0 = 0x2, + STREAM_SRC_NORMAL = 0x3, + STREAM_SRC_TANGENT = 0x4, + STREAM_SRC_OPTIONAL_BEGIN = 0x5, + STREAM_SRC_PRE_OPTIONAL_BEGIN = 0x4, + STREAM_SRC_TEXCOORD_1 = 0x5, + STREAM_SRC_TEXCOORD_2 = 0x6, + STREAM_SRC_NORMAL_TRANSFORM_0 = 0x7, + STREAM_SRC_NORMAL_TRANSFORM_1 = 0x8, + + STREAM_SRC_COUNT +}; + +enum MaterialStreamDestination_e { + STREAM_DST_POSITION = 0x0, + STREAM_DST_NORMAL = 0x1, + STREAM_DST_COLOR_0 = 0x2, + STREAM_DST_COLOR_1 = 0x3, + STREAM_DST_DEPTH = 0x4, + STREAM_DST_TEXCOORD_0 = 0x5, + STREAM_DST_TEXCOORD_1 = 0x6, + STREAM_DST_TEXCOORD_2 = 0x7, + STREAM_DST_TEXCOORD_3 = 0x8, + STREAM_DST_TEXCOORD_4 = 0x9, + STREAM_DST_TEXCOORD_5 = 0xA, + STREAM_DST_TEXCOORD_6 = 0xB, + STREAM_DST_TEXCOORD_7 = 0xC, + + STREAM_DST_COUNT +}; + +struct MaterialStreamRouting { + unsigned char source; + unsigned char dest; +}; + +struct MaterialVertexStreamRouting { + MaterialStreamRouting data[13]; + void /*IDirect3DVertexDeclaration9*/ *decl[16]; +}; + +struct MaterialVertexDeclaration { + const char *name; + unsigned char streamCount; + bool hasOptionalSource; + MaterialVertexStreamRouting routing; +}; + +struct MaterialVertexShaderProgram { + void /*IDirect3DVertexShader9*/ *vs; + GfxVertexShaderLoadDef loadDef; +}; + +struct MaterialVertexShader { + const char *name; + MaterialVertexShaderProgram prog; +}; + +struct MaterialPixelShaderProgram { + void /*IDirect3DPixelShader9*/ *ps; + GfxPixelShaderLoadDef loadDef; +}; + +struct MaterialPixelShader { + const char *name; + MaterialPixelShaderProgram prog; +}; + +enum MaterialTextureSource { + TEXTURE_SRC_CODE_BLACK = 0x0, + TEXTURE_SRC_CODE_WHITE = 0x1, + TEXTURE_SRC_CODE_IDENTITY_NORMAL_MAP = 0x2, + TEXTURE_SRC_CODE_MODEL_LIGHTING = 0x3, + TEXTURE_SRC_CODE_LIGHTMAP_PRIMARY = 0x4, + TEXTURE_SRC_CODE_LIGHTMAP_SECONDARY = 0x5, + TEXTURE_SRC_CODE_SHADOWMAP_SUN = 0x6, + TEXTURE_SRC_CODE_SHADOWMAP_SPOT = 0x7, + TEXTURE_SRC_CODE_FEEDBACK = 0x8, + TEXTURE_SRC_CODE_RESOLVED_POST_SUN = 0x9, + TEXTURE_SRC_CODE_RESOLVED_SCENE = 0xA, + TEXTURE_SRC_CODE_POST_EFFECT_0 = 0xB, + TEXTURE_SRC_CODE_POST_EFFECT_1 = 0xC, + TEXTURE_SRC_CODE_LIGHT_ATTENUATION = 0xD, + TEXTURE_SRC_CODE_OUTDOOR = 0xE, + TEXTURE_SRC_CODE_FLOATZ = 0xF, + TEXTURE_SRC_CODE_PROCESSED_FLOATZ = 0x10, + TEXTURE_SRC_CODE_RAW_FLOATZ = 0x11, + TEXTURE_SRC_CODE_HALF_PARTICLES = 0x12, + TEXTURE_SRC_CODE_HALF_PARTICLES_Z = 0x13, + TEXTURE_SRC_CODE_CASE_TEXTURE = 0x14, + TEXTURE_SRC_CODE_CINEMATIC_Y = 0x15, + TEXTURE_SRC_CODE_CINEMATIC_CR = 0x16, + TEXTURE_SRC_CODE_CINEMATIC_CB = 0x17, + TEXTURE_SRC_CODE_CINEMATIC_A = 0x18, + TEXTURE_SRC_CODE_REFLECTION_PROBE = 0x19, + TEXTURE_SRC_CODE_ALTERNATE_SCENE = 0x1A, + + TEXTURE_SRC_CODE_COUNT +}; + +enum CustomSamplers { + CUSTOM_SAMPLER_REFLECTION_PROBE = 0x0, + CUSTOM_SAMPLER_LIGHTMAP_PRIMARY = 0x1, + CUSTOM_SAMPLER_LIGHTMAP_SECONDARY = 0x2, + + CUSTOM_SAMPLER_COUNT +}; + +struct CodeSamplerSource { + const char *name; + MaterialTextureSource source; + CodeSamplerSource *subtable; + int arrayCount; + int arrayStride; +}; + +enum MaterialType { + MTL_TYPE_DEFAULT = 0x0, + MTL_TYPE_MODEL = 0x1, // m_ + MTL_TYPE_MODEL_VERTCOL = 0x2, // mc_ + MTL_TYPE_MODEL_VERTCOL_GREY = 0x3, // mg_ + MTL_TYPE_WORLD = 0x4, // w_ + MTL_TYPE_WORLD_VERTCOL = 0x5, // wc_ + + MTL_TYPE_COUNT, +}; + +struct MaterialTypeInfo { + const char *materialPrefix; + const char *techniqueSetPrefix; +}; + +enum MaterialConstantSource { + CONST_SRC_CODE_MAYBE_DIRTY_PS_BEGIN = 0x0, + + CONST_SRC_CODE_LIGHT_POSITION = 0x0, + CONST_SRC_CODE_LIGHT_DIFFUSE = 0x1, + CONST_SRC_CODE_LIGHT_SPECULAR = 0x2, + CONST_SRC_CODE_LIGHT_SPOTDIR = 0x3, + CONST_SRC_CODE_LIGHT_SPOTFACTORS = 0x4, + CONST_SRC_CODE_LIGHT_FALLOFF_PLACEMENT = 0x5, + CONST_SRC_CODE_PARTICLE_CLOUD_COLOR = 0x6, + CONST_SRC_CODE_GAMETIME = 0x7, + + CONST_SRC_CODE_MAYBE_DIRTY_PS_END = 0x8, + + CONST_SRC_CODE_ALWAYS_DIRTY_PS_BEGIN = 0x8, + + CONST_SRC_CODE_PIXEL_COST_FRACS = 0x8, + CONST_SRC_CODE_PIXEL_COST_DECODE = 0x9, + CONST_SRC_CODE_FILTER_TAP_0 = 0xA, + CONST_SRC_CODE_FILTER_TAP_1 = 0xB, + CONST_SRC_CODE_FILTER_TAP_2 = 0xC, + CONST_SRC_CODE_FILTER_TAP_3 = 0xD, + CONST_SRC_CODE_FILTER_TAP_4 = 0xE, + CONST_SRC_CODE_FILTER_TAP_5 = 0xF, + CONST_SRC_CODE_FILTER_TAP_6 = 0x10, + CONST_SRC_CODE_FILTER_TAP_7 = 0x11, + CONST_SRC_CODE_COLOR_MATRIX_R = 0x12, + CONST_SRC_CODE_COLOR_MATRIX_G = 0x13, + CONST_SRC_CODE_COLOR_MATRIX_B = 0x14, + CONST_SRC_CODE_SHADOWMAP_POLYGON_OFFSET = 0x15, + CONST_SRC_CODE_RENDER_TARGET_SIZE = 0x16, + + CONST_SRC_CODE_ALWAYS_DIRTY_PS_END = 0x17, + + CONST_SRC_CODE_FIXED_PS_BEGIN = 0x17, + + CONST_SRC_CODE_DOF_EQUATION_VIEWMODEL_AND_FAR_BLUR = 0x17, + CONST_SRC_CODE_DOF_EQUATION_SCENE = 0x18, + CONST_SRC_CODE_DOF_LERP_SCALE = 0x19, + CONST_SRC_CODE_DOF_LERP_BIAS = 0x1A, + CONST_SRC_CODE_DOF_ROW_DELTA = 0x1B, + CONST_SRC_CODE_MOTION_MATRIX_X = 0x1C, + CONST_SRC_CODE_MOTION_MATRIX_Y = 0x1D, + CONST_SRC_CODE_MOTION_MATRIX_W = 0x1E, + CONST_SRC_CODE_SHADOWMAP_SWITCH_PARTITION = 0x1F, + CONST_SRC_CODE_SHADOWMAP_SCALE = 0x20, + CONST_SRC_CODE_ZNEAR = 0x21, + CONST_SRC_CODE_LIGHTING_LOOKUP_SCALE = 0x22, + CONST_SRC_CODE_DEBUG_BUMPMAP = 0x23, + CONST_SRC_CODE_MATERIAL_COLOR = 0x24, + CONST_SRC_CODE_FOG = 0x25, + CONST_SRC_CODE_FOG_COLOR_LINEAR = 0x26, + CONST_SRC_CODE_FOG_COLOR_GAMMA = 0x27, + CONST_SRC_CODE_FOG_SUN_CONSTS = 0x28, + CONST_SRC_CODE_FOG_SUN_COLOR_LINEAR = 0x29, + CONST_SRC_CODE_FOG_SUN_COLOR_GAMMA = 0x2A, + CONST_SRC_CODE_FOG_SUN_DIR = 0x2B, + CONST_SRC_CODE_GLOW_SETUP = 0x2C, + CONST_SRC_CODE_GLOW_APPLY = 0x2D, + CONST_SRC_CODE_COLOR_BIAS = 0x2E, + CONST_SRC_CODE_COLOR_TINT_BASE = 0x2F, + CONST_SRC_CODE_COLOR_TINT_DELTA = 0x30, + CONST_SRC_CODE_COLOR_TINT_QUADRATIC_DELTA = 0x31, + CONST_SRC_CODE_OUTDOOR_FEATHER_PARMS = 0x32, + CONST_SRC_CODE_ENVMAP_PARMS = 0x33, + CONST_SRC_CODE_SUN_SHADOWMAP_PIXEL_ADJUST = 0x34, + CONST_SRC_CODE_SPOT_SHADOWMAP_PIXEL_ADJUST = 0x35, + CONST_SRC_CODE_COMPOSITE_FX_DISTORTION = 0x36, + CONST_SRC_CODE_POSTFX_FADE_EFFECT = 0x37, + CONST_SRC_CODE_VIEWPORT_DIMENSIONS = 0x38, + CONST_SRC_CODE_FRAMEBUFFER_READ = 0x39, + + CONST_SRC_CODE_FIXED_PS_END = 0x3A, + + CONST_SRC_CODE_NON_PS_BEGIN = 0x3A, + + CONST_SRC_CODE_BASE_LIGHTING_COORDS = 0x3A, + CONST_SRC_CODE_LIGHT_PROBE_AMBIENT = 0x3B, + CONST_SRC_CODE_NEARPLANE_ORG = 0x3C, + CONST_SRC_CODE_NEARPLANE_DX = 0x3D, + CONST_SRC_CODE_NEARPLANE_DY = 0x3E, + CONST_SRC_CODE_CLIP_SPACE_LOOKUP_SCALE = 0x3F, + CONST_SRC_CODE_CLIP_SPACE_LOOKUP_OFFSET = 0x40, + CONST_SRC_CODE_PARTICLE_CLOUD_MATRIX0 = 0x41, + CONST_SRC_CODE_PARTICLE_CLOUD_MATRIX1 = 0x42, + CONST_SRC_CODE_PARTICLE_CLOUD_MATRIX2 = 0x43, + CONST_SRC_CODE_PARTICLE_CLOUD_SPARK_COLOR0 = 0x44, + CONST_SRC_CODE_PARTICLE_CLOUD_SPARK_COLOR1 = 0x45, + CONST_SRC_CODE_PARTICLE_CLOUD_SPARK_COLOR2 = 0x46, + CONST_SRC_CODE_PARTICLE_FOUNTAIN_PARM0 = 0x47, + CONST_SRC_CODE_PARTICLE_FOUNTAIN_PARM1 = 0x48, + CONST_SRC_CODE_DEPTH_FROM_CLIP = 0x49, + CONST_SRC_CODE_CODE_MESH_ARG_0 = 0x4A, + CONST_SRC_CODE_CODE_MESH_ARG_1 = 0x4B, + + CONST_SRC_CODE_CODE_MESH_ARG_LAST = 0x4B, + CONST_SRC_CODE_NON_PS_END = 0x4C, + CONST_SRC_CODE_COUNT_FLOAT4 = 0x4C, + + CONST_SRC_FIRST_CODE_MATRIX = 0x4C, + + CONST_SRC_CODE_VIEW_MATRIX = 0x4C, + CONST_SRC_CODE_INVERSE_VIEW_MATRIX = 0x4D, + CONST_SRC_CODE_TRANSPOSE_VIEW_MATRIX = 0x4E, + CONST_SRC_CODE_INVERSE_TRANSPOSE_VIEW_MATRIX = 0x4F, + CONST_SRC_CODE_PROJECTION_MATRIX = 0x50, + CONST_SRC_CODE_INVERSE_PROJECTION_MATRIX = 0x51, + CONST_SRC_CODE_TRANSPOSE_PROJECTION_MATRIX = 0x52, + CONST_SRC_CODE_INVERSE_TRANSPOSE_PROJECTION_MATRIX = 0x53, + CONST_SRC_CODE_VIEW_PROJECTION_MATRIX = 0x54, + CONST_SRC_CODE_INVERSE_VIEW_PROJECTION_MATRIX = 0x55, + CONST_SRC_CODE_TRANSPOSE_VIEW_PROJECTION_MATRIX = 0x56, + CONST_SRC_CODE_INVERSE_TRANSPOSE_VIEW_PROJECTION_MATRIX = 0x57, + CONST_SRC_CODE_SHADOW_LOOKUP_MATRIX = 0x58, + CONST_SRC_CODE_INVERSE_SHADOW_LOOKUP_MATRIX = 0x59, + CONST_SRC_CODE_TRANSPOSE_SHADOW_LOOKUP_MATRIX = 0x5A, + CONST_SRC_CODE_INVERSE_TRANSPOSE_SHADOW_LOOKUP_MATRIX = 0x5B, + CONST_SRC_CODE_WORLD_OUTDOOR_LOOKUP_MATRIX = 0x5C, + CONST_SRC_CODE_INVERSE_WORLD_OUTDOOR_LOOKUP_MATRIX = 0x5D, + CONST_SRC_CODE_TRANSPOSE_WORLD_OUTDOOR_LOOKUP_MATRIX = 0x5E, + CONST_SRC_CODE_INVERSE_TRANSPOSE_WORLD_OUTDOOR_LOOKUP_MATRIX = 0x5F, + CONST_SRC_CODE_WORLD_MATRIX0 = 0x60, + CONST_SRC_CODE_INVERSE_WORLD_MATRIX0 = 0x61, + CONST_SRC_CODE_TRANSPOSE_WORLD_MATRIX0 = 0x62, + CONST_SRC_CODE_INVERSE_TRANSPOSE_WORLD_MATRIX0 = 0x63, + CONST_SRC_CODE_WORLD_VIEW_MATRIX0 = 0x64, + CONST_SRC_CODE_INVERSE_WORLD_VIEW_MATRIX0 = 0x65, + CONST_SRC_CODE_TRANSPOSE_WORLD_VIEW_MATRIX0 = 0x66, + CONST_SRC_CODE_INVERSE_TRANSPOSE_WORLD_VIEW_MATRIX0 = 0x67, + CONST_SRC_CODE_WORLD_VIEW_PROJECTION_MATRIX0 = 0x68, + CONST_SRC_CODE_INVERSE_WORLD_VIEW_PROJECTION_MATRIX0 = 0x69, + CONST_SRC_CODE_TRANSPOSE_WORLD_VIEW_PROJECTION_MATRIX0 = 0x6A, + CONST_SRC_CODE_INVERSE_TRANSPOSE_WORLD_VIEW_PROJECTION_MATRIX0 = 0x6B, + CONST_SRC_CODE_WORLD_MATRIX1 = 0x6C, + CONST_SRC_CODE_INVERSE_WORLD_MATRIX1 = 0x6D, + CONST_SRC_CODE_TRANSPOSE_WORLD_MATRIX1 = 0x6E, + CONST_SRC_CODE_INVERSE_TRANSPOSE_WORLD_MATRIX1 = 0x6F, + CONST_SRC_CODE_WORLD_VIEW_MATRIX1 = 0x70, + CONST_SRC_CODE_INVERSE_WORLD_VIEW_MATRIX1 = 0x71, + CONST_SRC_CODE_TRANSPOSE_WORLD_VIEW_MATRIX1 = 0x72, + CONST_SRC_CODE_INVERSE_TRANSPOSE_WORLD_VIEW_MATRIX1 = 0x73, + CONST_SRC_CODE_WORLD_VIEW_PROJECTION_MATRIX1 = 0x74, + CONST_SRC_CODE_INVERSE_WORLD_VIEW_PROJECTION_MATRIX1 = 0x75, + CONST_SRC_CODE_TRANSPOSE_WORLD_VIEW_PROJECTION_MATRIX1 = 0x76, + CONST_SRC_CODE_INVERSE_TRANSPOSE_WORLD_VIEW_PROJECTION_MATRIX1 = 0x77, + CONST_SRC_CODE_WORLD_MATRIX2 = 0x78, + CONST_SRC_CODE_INVERSE_WORLD_MATRIX2 = 0x79, + CONST_SRC_CODE_TRANSPOSE_WORLD_MATRIX2 = 0x7A, + CONST_SRC_CODE_INVERSE_TRANSPOSE_WORLD_MATRIX2 = 0x7B, + CONST_SRC_CODE_WORLD_VIEW_MATRIX2 = 0x7C, + CONST_SRC_CODE_INVERSE_WORLD_VIEW_MATRIX2 = 0x7D, + CONST_SRC_CODE_TRANSPOSE_WORLD_VIEW_MATRIX2 = 0x7E, + CONST_SRC_CODE_INVERSE_TRANSPOSE_WORLD_VIEW_MATRIX2 = 0x7F, + CONST_SRC_CODE_WORLD_VIEW_PROJECTION_MATRIX2 = 0x80, + CONST_SRC_CODE_INVERSE_WORLD_VIEW_PROJECTION_MATRIX2 = 0x81, + CONST_SRC_CODE_TRANSPOSE_WORLD_VIEW_PROJECTION_MATRIX2 = 0x82, + CONST_SRC_CODE_INVERSE_TRANSPOSE_WORLD_VIEW_PROJECTION_MATRIX2 = 0x83, + + CONST_SRC_TOTAL_COUNT, + CONST_SRC_NONE +}; + +struct CodeConstantSource { + const char *name; + MaterialConstantSource source; + CodeConstantSource *subtable; + int arrayCount; + int arrayStride; +}; + +struct MaterialArgumentCodeConst { + uint16_t index; + unsigned char firstRow; + unsigned char rowCount; +}; + +union MaterialArgumentDef { + const float (*literalConst)[4]; + MaterialArgumentCodeConst codeConst; + unsigned int codeSampler; + unsigned int nameHash; +}; + +enum MaterialShaderArgumentType { + MTL_ARG_MATERIAL_VERTEX_CONST = 0x0, // stable + MTL_ARG_LITERAL_VERTEX_CONST = 0x1, // stable + MTL_ARG_MATERIAL_PIXEL_SAMPLER = 0x2, // stable + + MTL_ARG_CODE_PRIM_BEGIN = 0x3, + + MTL_ARG_CODE_VERTEX_CONST = 0x3, // stable object prim + MTL_ARG_CODE_PIXEL_SAMPLER = 0x4, // stable object + MTL_ARG_CODE_PIXEL_CONST = 0x5, // stable + + MTL_ARG_CODE_PRIM_END = 0x6, + + MTL_ARG_MATERIAL_PIXEL_CONST = 0x6, // stable + MTL_ARG_LITERAL_PIXEL_CONST = 0x7, // stable + + MTL_ARG_COUNT +}; + +enum MaterialUpdateFrequency { + MTL_UPDATE_PER_PRIM = 0x0, + MTL_UPDATE_PER_OBJECT = 0x1, + MTL_UPDATE_RARELY = 0x2, + MTL_UPDATE_CUSTOM = 0x3, +}; + +struct MaterialShaderArgument { + uint16_t type; + uint16_t dest; + MaterialArgumentDef u; +}; + +struct MaterialPass { + MaterialVertexDeclaration *vertexDecl; + MaterialVertexShader *vertexShader; + MaterialPixelShader *pixelShader; + unsigned char perPrimArgCount; + unsigned char perObjArgCount; + unsigned char stableArgCount; + unsigned char customSamplerFlags; + MaterialShaderArgument *args; +}; + +enum TechniqueFlags { + // Guesses purely based on data analysis: + TECHNIQUE_FLAG_1 = 0x1, // uses resolvedPostSun code sampler // MTL_TECHFLAG_NEEDS_RESOLVED_POST_SUN + TECHNIQUE_FLAG_2 = 0x2, // uses resolvedScene code sampler MTL_TECHFLAG_NEEDS_RESOLVED_SCENE + TECHNIQUE_FLAG_4 = 0x4, // zprepass only + TECHNIQUE_FLAG_8 = 0x8, // build_floatz only + TECHNIQUE_FLAG_10 = 0x10, // build_shadowmap_depth + build_shadowmap_model only + TECHNIQUE_FLAG_20 = + 0x20, // techniques with _i_ in its name (all use texcoord[1] in decl -> other optional stream sources are not used at all so might be any optional) + TECHNIQUE_FLAG_40 = 0x40, // uses code constant light.spotDir or light.spotFactors + TECHNIQUE_FLAG_80 = 0x80, // uses floatZ sampler and does not have 0x100 flag + TECHNIQUE_FLAG_100 = 0x100, // distortion_scale_zfeather_dtex + distortion_scale_ua_zfeather + distortion_scale_zfeather + TECHNIQUE_FLAG_200 = 0x200, // ? +}; + +struct MaterialTechnique { + const char *name; + uint16_t flags; + uint16_t passCount; + MaterialPass passArray[1]; +}; + +enum MaterialTechniqueType { + TECHNIQUE_DEPTH_PREPASS = 0x0, + TECHNIQUE_BUILD_FLOAT_Z = 0x1, + TECHNIQUE_BUILD_SHADOWMAP_DEPTH = 0x2, + TECHNIQUE_BUILD_SHADOWMAP_COLOR = 0x3, + TECHNIQUE_UNLIT = 0x4, + TECHNIQUE_EMISSIVE = 0x5, + TECHNIQUE_EMISSIVE_DFOG = 0x6, + TECHNIQUE_EMISSIVE_SHADOW = 0x7, + TECHNIQUE_EMISSIVE_SHADOW_DFOG = 0x8, + + TECHNIQUE_LIT_BEGIN = 0x9, + + TECHNIQUE_LIT = 0x9, + TECHNIQUE_LIT_DFOG = 0xA, + TECHNIQUE_LIT_SUN = 0xB, + TECHNIQUE_LIT_SUN_DFOG = 0xC, + TECHNIQUE_LIT_SUN_SHADOW = 0xD, + TECHNIQUE_LIT_SUN_SHADOW_DFOG = 0xE, + TECHNIQUE_LIT_SPOT = 0xF, + TECHNIQUE_LIT_SPOT_DFOG = 0x10, + TECHNIQUE_LIT_SPOT_SHADOW = 0x11, + TECHNIQUE_LIT_SPOT_SHADOW_DFOG = 0x12, + TECHNIQUE_LIT_OMNI = 0x13, + TECHNIQUE_LIT_OMNI_DFOG = 0x14, + TECHNIQUE_LIT_OMNI_SHADOW = 0x15, + TECHNIQUE_LIT_OMNI_SHADOW_DFOG = 0x16, + TECHNIQUE_LIT_INSTANCED = 0x17, + TECHNIQUE_LIT_INSTANCED_DFOG = 0x18, + TECHNIQUE_LIT_INSTANCED_SUN = 0x19, + TECHNIQUE_LIT_INSTANCED_SUN_DFOG = 0x1A, + TECHNIQUE_LIT_INSTANCED_SUN_SHADOW = 0x1B, + TECHNIQUE_LIT_INSTANCED_SUN_SHADOW_DFOG = 0x1C, + TECHNIQUE_LIT_INSTANCED_SPOT = 0x1D, + TECHNIQUE_LIT_INSTANCED_SPOT_DFOG = 0x1E, + TECHNIQUE_LIT_INSTANCED_SPOT_SHADOW = 0x1F, + TECHNIQUE_LIT_INSTANCED_SPOT_SHADOW_DFOG = 0x20, + TECHNIQUE_LIT_INSTANCED_OMNI = 0x21, + TECHNIQUE_LIT_INSTANCED_OMNI_DFOG = 0x22, + TECHNIQUE_LIT_INSTANCED_OMNI_SHADOW = 0x23, + TECHNIQUE_LIT_INSTANCED_OMNI_SHADOW_DFOG = 0x24, + + TECHNIQUE_LIT_END = 0x25, + + TECHNIQUE_LIGHT_SPOT = 0x25, + TECHNIQUE_LIGHT_OMNI = 0x26, + TECHNIQUE_LIGHT_SPOT_SHADOW = 0x27, + TECHNIQUE_FAKELIGHT_NORMAL = 0x28, + TECHNIQUE_FAKELIGHT_VIEW = 0x29, + TECHNIQUE_SUNLIGHT_PREVIEW = 0x2A, + TECHNIQUE_CASE_TEXTURE = 0x2B, + TECHNIQUE_WIREFRAME_SOLID = 0x2C, + TECHNIQUE_WIREFRAME_SHADED = 0x2D, + TECHNIQUE_DEBUG_BUMPMAP = 0x2E, + TECHNIQUE_DEBUG_BUMPMAP_INSTANCED = 0x2F, + + TECHNIQUE_COUNT +}; + +struct MaterialTechniqueSet { + const char *name; + unsigned char worldVertFormat; + bool hasBeenUploaded; + unsigned char unused[1]; + MaterialTechniqueSet *remappedTechniqueSet; + MaterialTechnique *techniques[48]; +}; + +union RawFileBuffer { + const char *compressedBuffer; + const char *buffer; +}; + +struct RawFile { + const char *name; + int compressedLen; + int len; + RawFileBuffer data; +}; + +struct StringTableCell { + const char *string; + int hash; +}; + +struct StringTable { + const char *name; + int columnCount; + int rowCount; + StringTableCell *values; +}; + +struct AILSOUNDINFO { + int format; + const void *data_ptr; + unsigned int data_len; + unsigned int rate; + int bits; + int channels; + unsigned int samples; + unsigned int block_size; + const void *initial_ptr; +}; + +struct MssSound { + AILSOUNDINFO info; + char *data; +}; + +struct LoadedSound { + const char *name; + MssSound sound; +}; + +struct StreamedSound { + const char *dir; + const char *name; +}; + +union SoundFileRef { + LoadedSound *loadSnd; + StreamedSound streamSnd; +}; + +enum snd_alias_type_t : char { + SAT_UNKNOWN = 0x0, + SAT_LOADED = 0x1, + SAT_STREAMED = 0x2, + SAT_VOICED = 0x3, + SAT_COUNT, +}; + +struct SoundFile { + snd_alias_type_t type; + char exists; + SoundFileRef u; +}; + +struct MSSSpeakerLevels { + int speaker; + int numLevels; + float levels[2]; +}; + +struct MSSChannelMap { + int speakerCount; + MSSSpeakerLevels speakers[6]; +}; + +struct SpeakerMap { + bool isDefault; + const char *name; + MSSChannelMap channelMaps[2][2]; +}; + +struct snd_alias_t { + const char *aliasName; + const char *subtitle; + const char *secondaryAliasName; + const char *chainAliasName; + const char *mixerGroup; + SoundFile *soundFile; + int sequence; + float volMin; + float volMax; + float pitchMin; + float pitchMax; + float distMin; + float distMax; + float velocityMin; + int flags; + + union { + float slavePercentage; + float masterPercentage; + }; + + float probability; + float lfePercentage; + float centerPercentage; + int startDelay; + SndCurve *volumeFalloffCurve; + float envelopMin; + float envelopMax; + float envelopPercentage; + SpeakerMap *speakerMap; +}; + +struct snd_alias_list_t { + const char *aliasName; + snd_alias_t *head; + int count; +}; + +struct SndCurve { + const char *filename; + uint16_t knotCount; + float knots[16][2]; +}; + +struct LocalizeEntry { + const char *value; + const char *name; +}; + +struct StringList { + int totalStrings; + const char **strings; +}; + +union DvarLimits { + struct { + int stringCount; + const char **strings; + } enumeration; + + struct { + int min; + int max; + } integer; + + struct { + float min; + float max; + } value; + + struct { + float min; + float max; + } vector; +}; + +union DvarValue { + bool enabled; + int integer; + unsigned int unsignedInt; + float value; + float vector[4]; + const char *string; + char color[4]; +}; + +struct dvar_t { + const char *name; + const char *description; + unsigned int flags; + char type; + bool modified; + DvarValue current; + DvarValue latched; + DvarValue reset; + DvarLimits domain; + // bool (__cdecl* domainFunc)(dvar_t*, DvarValue); + void *domainFunc; + dvar_t *hashNext; +}; + +struct StaticDvar { + dvar_t *dvar; + char *dvarName; +}; + +struct StaticDvarList { + int numStaticDvars; + StaticDvar **staticDvars; +}; + +struct ExpressionString { + const char *string; +}; + +struct Statement_s; + +union operandInternalDataUnion { + int intVal; + float floatVal; + ExpressionString stringVal; + Statement_s *function; +}; + +enum expDataType { + VAL_INT = 0x0, + VAL_FLOAT = 0x1, + VAL_STRING = 0x2, + VAL_FUNCTION = 0x3, + + NUM_DATATYPES, +}; + +struct Operand { + expDataType dataType; + operandInternalDataUnion internals; +}; + +enum expressionOperatorType_e { + OP_NOOP = 0x0, + OP_RIGHTPAREN = 0x1, + OP_MULTIPLY = 0x2, + OP_DIVIDE = 0x3, + OP_MODULUS = 0x4, + OP_ADD = 0x5, + OP_SUBTRACT = 0x6, + OP_NOT = 0x7, + OP_LESSTHAN = 0x8, + OP_LESSTHANEQUALTO = 0x9, + OP_GREATERTHAN = 0xA, + OP_GREATERTHANEQUALTO = 0xB, + OP_EQUALS = 0xC, + OP_NOTEQUAL = 0xD, + OP_AND = 0xE, + OP_OR = 0xF, + OP_LEFTPAREN = 0x10, + OP_COMMA = 0x11, + OP_BITWISEAND = 0x12, + OP_BITWISEOR = 0x13, + OP_BITWISENOT = 0x14, + OP_BITSHIFTLEFT = 0x15, + OP_BITSHIFTRIGHT = 0x16, + + OP_COUNT +}; + +enum expressionFunction_e { + EXP_FUNC_STATIC_DVAR_INT = OP_COUNT, + EXP_FUNC_STATIC_DVAR_BOOL, + EXP_FUNC_STATIC_DVAR_FLOAT, + EXP_FUNC_STATIC_DVAR_STRING, + + EXP_FUNC_DYN_START, + + EXP_FUNC_INT = EXP_FUNC_DYN_START, + EXP_FUNC_STRING, + EXP_FUNC_FLOAT, + EXP_FUNC_SIN, + EXP_FUNC_COS, + EXP_FUNC_MIN, + EXP_FUNC_MAX, + EXP_FUNC_MILLISECONDS, + EXP_FUNC_DVAR_INT, + EXP_FUNC_DVAR_BOOL, + EXP_FUNC_DVAR_FLOAT, + EXP_FUNC_DVAR_STRING +}; + +union entryInternalData { + int op; + Operand operand; +}; + +enum expressionEntryType : int { + EET_OPERATOR = 0x0, + EET_OPERAND = 0x1, +}; + +struct expressionEntry { + expressionEntryType type; + entryInternalData data; +}; + +struct ExpressionSupportingData; + +struct Statement_s { + int numEntries; + expressionEntry *entries; + ExpressionSupportingData *supportingData; + int lastExecuteTime; + Operand lastResult; +}; + +struct UIFunctionList { + int totalFunctions; + Statement_s **functions; +}; + +struct ExpressionSupportingData { + UIFunctionList uifunctions; + StaticDvarList staticDvarList; + StringList uiStrings; +}; + +struct menuTransition { + int transitionType; + int targetField; + int startTime; + float startVal; + float endVal; + float time; + int endTriggerType; +}; + +enum ItemFloatExpressionTarget { + ITEM_FLOATEXP_TGT_RECT_X = 0x0, + ITEM_FLOATEXP_TGT_RECT_Y = 0x1, + ITEM_FLOATEXP_TGT_RECT_W = 0x2, + ITEM_FLOATEXP_TGT_RECT_H = 0x3, + ITEM_FLOATEXP_TGT_FORECOLOR_R = 0x4, + ITEM_FLOATEXP_TGT_FORECOLOR_G = 0x5, + ITEM_FLOATEXP_TGT_FORECOLOR_B = 0x6, + ITEM_FLOATEXP_TGT_FORECOLOR_RGB = 0x7, + ITEM_FLOATEXP_TGT_FORECOLOR_A = 0x8, + ITEM_FLOATEXP_TGT_GLOWCOLOR_R = 0x9, + ITEM_FLOATEXP_TGT_GLOWCOLOR_G = 0xA, + ITEM_FLOATEXP_TGT_GLOWCOLOR_B = 0xB, + ITEM_FLOATEXP_TGT_GLOWCOLOR_RGB = 0xC, + ITEM_FLOATEXP_TGT_GLOWCOLOR_A = 0xD, + ITEM_FLOATEXP_TGT_BACKCOLOR_R = 0xE, + ITEM_FLOATEXP_TGT_BACKCOLOR_G = 0xF, + ITEM_FLOATEXP_TGT_BACKCOLOR_B = 0x10, + ITEM_FLOATEXP_TGT_BACKCOLOR_RGB = 0x11, + ITEM_FLOATEXP_TGT_BACKCOLOR_A = 0x12, + + ITEM_FLOATEXP_TGT_COUNT +}; + +struct ItemExpressionTargetBinding { + int target; + const char *name; + const char *componentName; +}; + +struct ItemFloatExpression { + int target; + Statement_s *expression; +}; + +struct columnInfo_s { + int pos; + int width; + int maxChars; + int alignment; +}; + +struct MenuEventHandlerSet; + +struct ConditionalScript { + MenuEventHandlerSet *eventHandlerSet; + Statement_s *eventExpression; +}; + +struct SetLocalVarData { + const char *localVarName; + Statement_s *expression; +}; + +union EventData { + const char *unconditionalScript; + ConditionalScript *conditionalScript; + MenuEventHandlerSet *elseScript; + SetLocalVarData *setLocalVarData; +}; + +enum EventType : unsigned char { + EVENT_UNCONDITIONAL = 0x0, + EVENT_IF = 0x1, + EVENT_ELSE = 0x2, + EVENT_SET_LOCAL_VAR_BOOL = 0x3, + EVENT_SET_LOCAL_VAR_INT = 0x4, + EVENT_SET_LOCAL_VAR_FLOAT = 0x5, + EVENT_SET_LOCAL_VAR_STRING = 0x6, + + EVENT_COUNT, +}; + +struct MenuEventHandler { + EventData eventData; + EventType eventType; +}; + +struct MenuEventHandlerSet { + int eventHandlerCount; + MenuEventHandler **eventHandlers; +}; + +struct listBoxDef_s { + int mousePos; + int startPos[1]; + int endPos[1]; + int drawPadding; + float elementWidth; + float elementHeight; + int elementStyle; + int numColumns; + columnInfo_s columnInfo[16]; + MenuEventHandlerSet *onDoubleClick; + int notselectable; + int noScrollBars; + int usePaging; + float selectBorder[4]; + Material *selectIcon; +}; + +struct editFieldDef_s { + float minVal; + float maxVal; + float defVal; + float range; + int maxChars; + int maxCharsGotoNext; + int maxPaintChars; + int paintOffset; +}; + +struct multiDef_s { + const char *dvarList[32]; + const char *dvarStr[32]; + float dvarValue[32]; + int count; + int strDef; +}; + +struct newsTickerDef_s { + int feedId; + int speed; + int spacing; + int lastTime; + int start; + int end; + float x; +}; + +struct textScrollDef_s { + int startTime; +}; + +union itemDefData_t { + listBoxDef_s *listBox; + editFieldDef_s *editField; + multiDef_s *multi; + const char *enumDvarName; + newsTickerDef_s *ticker; + textScrollDef_s *scroll; + void *data; +}; + +struct ItemKeyHandler { + int key; + MenuEventHandlerSet *action; + ItemKeyHandler *next; +}; + +struct rectDef_s { + float x; + float y; + float w; + float h; + unsigned char horzAlign; + unsigned char vertAlign; +}; + +enum WindowDefStaticFlag : unsigned int { + WINDOW_FLAG_DECORATION = 0x100000, + WINDOW_FLAG_HORIZONTAL_SCROLL = 0x200000, + WINDOW_FLAG_OUT_OF_BOUNDS_CLICK = 0x2000000, + WINDOW_FLAG_SCREEN_SPACE = 0x400000, + WINDOW_FLAG_AUTO_WRAPPED = 0x800000, + WINDOW_FLAG_POPUP = 0x1000000, + WINDOW_FLAG_LEGACY_SPLIT_SCREEN_SCALE = 0x4000000, + WINDOW_FLAG_HIDDEN_DURING_FLASH_BANG = 0x10000000, + WINDOW_FLAG_HIDDEN_DURING_SCOPE = 0x20000000, + WINDOW_FLAG_HIDDEN_DURING_UI = 0x40000000, + WINDOW_FLAG_TEXT_ONLY_FOCUS = 0x80000000, +}; + +enum WindowDefDynamicFlag : unsigned int { + WINDOW_FLAG_HOVERED = 0x1, // guessed + WINDOW_FLAG_FOCUSED = 0x2, + WINDOW_FLAG_VISIBLE = 0x4, + WINDOW_FLAG_FADING_OUT = 0x10, + WINDOW_FLAG_FADING_IN = 0x20, + WINDOW_FLAG_80 = 0x80, + WINDOW_FLAG_NON_DEFAULT_BACKCOLOR = 0x8000, + WINDOW_FLAG_NON_DEFAULT_FORECOLOR = 0x10000 +}; + +struct windowDef_t { + const char *name; + rectDef_s rect; + rectDef_s rectClient; + const char *group; + int style; + int border; + int ownerDraw; + int ownerDrawFlags; + float borderSize; + int staticFlags; + unsigned int dynamicFlags[1]; + int nextTime; + float foreColor[4]; + float backColor[4]; + float borderColor[4]; + float outlineColor[4]; + float disableColor[4]; + Material *background; +}; + +enum ItemDefFlag : unsigned int { + ITEM_FLAG_SAVE_GAME_INFO = 0x1, + ITEM_FLAG_CINEMATIC_SUBTITLE = 0x2, +}; + +enum ItemDefDvarFlag { + ITEM_DVAR_FLAG_ENABLE = 0x1, + ITEM_DVAR_FLAG_DISABLE = 0x2, + ITEM_DVAR_FLAG_SHOW = 0x4, + ITEM_DVAR_FLAG_HIDE = 0x8, + ITEM_DVAR_FLAG_FOCUS = 0x10, +}; + +enum ItemDefType { + ITEM_TYPE_TEXT = 0x0, + ITEM_TYPE_BUTTON = 0x1, + ITEM_TYPE_RADIOBUTTON = 0x2, + ITEM_TYPE_CHECKBOX = 0x3, + ITEM_TYPE_EDITFIELD = 0x4, + ITEM_TYPE_COMBO = 0x5, + ITEM_TYPE_LISTBOX = 0x6, + ITEM_TYPE_MODEL = 0x7, + ITEM_TYPE_OWNERDRAW = 0x8, + ITEM_TYPE_NUMERICFIELD = 0x9, + ITEM_TYPE_SLIDER = 0xA, + ITEM_TYPE_YESNO = 0xB, + ITEM_TYPE_MULTI = 0xC, + ITEM_TYPE_DVARENUM = 0xD, + ITEM_TYPE_BIND = 0xE, + ITEM_TYPE_MENUMODEL = 0xF, + ITEM_TYPE_VALIDFILEFIELD = 0x10, + ITEM_TYPE_DECIMALFIELD = 0x11, + ITEM_TYPE_UPREDITFIELD = 0x12, + ITEM_TYPE_GAME_MESSAGE_WINDOW = 0x13, + ITEM_TYPE_NEWS_TICKER = 0x14, + ITEM_TYPE_TEXT_SCROLL = 0x15, + ITEM_TYPE_EMAILFIELD = 0x16, + ITEM_TYPE_PASSWORDFIELD = 0x17 +}; + +struct itemDef_s { + windowDef_t window; + rectDef_s textRect[1]; + int type; + int dataType; + int alignment; + int fontEnum; + int textAlignMode; + float textalignx; + float textaligny; + float textscale; + int textStyle; + int gameMsgWindowIndex; + int gameMsgWindowMode; + const char *text; + int itemFlags; + menuDef_t *parent; + MenuEventHandlerSet *mouseEnterText; + MenuEventHandlerSet *mouseExitText; + MenuEventHandlerSet *mouseEnter; + MenuEventHandlerSet *mouseExit; + MenuEventHandlerSet *action; + MenuEventHandlerSet *accept; + MenuEventHandlerSet *onFocus; + MenuEventHandlerSet *leaveFocus; + const char *dvar; + const char *dvarTest; + ItemKeyHandler *onKey; + const char *enableDvar; + const char *localVar; + int dvarFlags; + snd_alias_list_t *focusSound; + float special; + int cursorPos[1]; + itemDefData_t typeData; + int imageTrack; + int floatExpressionCount; + ItemFloatExpression *floatExpressions; + Statement_s *visibleExp; + Statement_s *disabledExp; + Statement_s *textExp; + Statement_s *materialExp; + float glowColor[4]; + bool decayActive; + int fxBirthTime; + int fxLetterTime; + int fxDecayStartTime; + int fxDecayDuration; + int lastSoundPlayedTime; +}; + +struct menuDef_t { + windowDef_t window; + const char *font; + int fullScreen; + int itemCount; + int fontIndex; + int cursorItem[1]; + int fadeCycle; + float fadeClamp; + float fadeAmount; + float fadeInAmount; + float blurRadius; + MenuEventHandlerSet *onOpen; + MenuEventHandlerSet *onCloseRequest; + MenuEventHandlerSet *onClose; + MenuEventHandlerSet *onESC; + ItemKeyHandler *onKey; + Statement_s *visibleExp; + const char *allowedBinding; + const char *soundName; + int imageTrack; + float focusColor[4]; + Statement_s *rectXExp; + Statement_s *rectYExp; + Statement_s *rectWExp; + Statement_s *rectHExp; + Statement_s *openSoundExp; + Statement_s *closeSoundExp; + itemDef_s **items; + menuTransition scaleTransition[1]; + menuTransition alphaTransition[1]; + menuTransition xTransition[1]; + menuTransition yTransition[1]; + ExpressionSupportingData *expressionData; +}; + +struct MenuList { + const char *name; + int menuCount; + menuDef_t **menus; +}; + +enum FxElemType { + FX_ELEM_TYPE_SPRITE_BILLBOARD = 0x0, + FX_ELEM_TYPE_SPRITE_ORIENTED = 0x1, + FX_ELEM_TYPE_TAIL = 0x2, + FX_ELEM_TYPE_TRAIL = 0x3, + FX_ELEM_TYPE_CLOUD = 0x4, + FX_ELEM_TYPE_SPARK_CLOUD = 0x5, + FX_ELEM_TYPE_SPARK_FOUNTAIN = 0x6, + FX_ELEM_TYPE_MODEL = 0x7, + FX_ELEM_TYPE_OMNI_LIGHT = 0x8, + FX_ELEM_TYPE_SPOT_LIGHT = 0x9, + FX_ELEM_TYPE_SOUND = 0xA, + FX_ELEM_TYPE_DECAL = 0xB, + FX_ELEM_TYPE_RUNNER = 0xC, + FX_ELEM_TYPE_COUNT = 0xD, + FX_ELEM_TYPE_LAST_SPRITE = 0x3, + FX_ELEM_TYPE_LAST_DRAWN = 0x9, +}; + +struct FxIntRange { + int base; + int amplitude; +}; + +struct FxSpawnDefOneShot { + FxIntRange count; +}; + +struct FxSpawnDefLooping { + int intervalMsec; + int count; +}; + +union FxSpawnDef { + FxSpawnDefLooping looping; + FxSpawnDefOneShot oneShot; +}; + +struct FxFloatRange { + float base; + float amplitude; +}; + +struct FxElemAtlas { + char behavior; + char index; + char fps; + char loopCount; + char colIndexBits; + char rowIndexBits; + int16_t entryCount; +}; + +struct FxElemVec3Range { + float base[3]; + float amplitude[3]; +}; + +struct FxElemVelStateInFrame { + FxElemVec3Range velocity; + FxElemVec3Range totalDelta; +}; + +struct FxElemVelStateSample { + FxElemVelStateInFrame local; + FxElemVelStateInFrame world; +}; + +struct FxElemVisualState { + char color[4]; + float rotationDelta; + float rotationTotal; + float size[2]; + float scale; +}; + +struct FxElemVisStateSample { + FxElemVisualState base; + FxElemVisualState amplitude; +}; + +union FxEffectDefRef { + FxEffectDef *handle; + const char *name; +}; + +union FxElemVisuals { + const void *anonymous; + Material *material; + XModel *model; + FxEffectDefRef effectDef; + const char *soundName; +}; + +struct FxElemMarkVisuals { + Material *materials[2]; +}; + +union FxElemDefVisuals { + FxElemMarkVisuals *markArray; + FxElemVisuals *array; + FxElemVisuals instance; +}; + +struct FxTrailVertex { + float pos[2]; + float normal[2]; + float texCoord; +}; + +struct FxTrailDef { + int scrollTimeMsec; + int repeatDist; + float invSplitDist; + float invSplitArcDist; + float invSplitTime; + int vertCount; + FxTrailVertex *verts; + int indCount; + uint16_t *inds; +}; + +struct FxSparkFountainDef { + float gravity; + float bounceFrac; + float bounceRand; + float sparkSpacing; + float sparkLength; + int sparkCount; + float loopTime; + float velMin; + float velMax; + float velConeFrac; + float restSpeed; + float boostTime; + float boostFactor; +}; + +union FxElemExtendedDefPtr { + FxTrailDef *trailDef; + FxSparkFountainDef *sparkFountainDef; + char *unknownDef; +}; + +struct FxElemDef { + int flags; + FxSpawnDef spawn; + FxFloatRange spawnRange; + FxFloatRange fadeInRange; + FxFloatRange fadeOutRange; + float spawnFrustumCullRadius; + FxIntRange spawnDelayMsec; + FxIntRange lifeSpanMsec; + FxFloatRange spawnOrigin[3]; + FxFloatRange spawnOffsetRadius; + FxFloatRange spawnOffsetHeight; + FxFloatRange spawnAngles[3]; + FxFloatRange angularVelocity[3]; + FxFloatRange initialRotation; + FxFloatRange gravity; + FxFloatRange reflectionFactor; + FxElemAtlas atlas; + char elemType; + char visualCount; + char velIntervalCount; + char visStateIntervalCount; + FxElemVelStateSample *velSamples; + FxElemVisStateSample *visSamples; + FxElemDefVisuals visuals; + Bounds collBounds; + FxEffectDefRef effectOnImpact; + FxEffectDefRef effectOnDeath; + FxEffectDefRef effectEmitted; + FxFloatRange emitDist; + FxFloatRange emitDistVariance; + FxElemExtendedDefPtr extended; + char sortOrder; + char lightingFrac; + char useItemClip; + char fadeInfo; +}; + +struct FxEffectDef { + const char *name; + int flags; + int totalSize; + int msecLoopingLife; + int elemDefCountLooping; + int elemDefCountOneShot; + int elemDefCountEmission; + FxElemDef *elemDefs; +}; + +struct GfxLightImage { + GfxImage *image; + char samplerState; +}; + +struct GfxLightDef { + const char *name; + GfxLightImage attenuation; + int lmapLookupStart; +}; + +struct Glyph { + uint16_t letter; + char x0; + char y0; + char dx; + char pixelWidth; + char pixelHeight; + float s0; + float t0; + float s1; + float t1; +}; + +struct Font_s { + const char *fontName; + int pixelHeight; + int glyphCount; + Material *material; + Material *glowMaterial; + Glyph *glyphs; +}; + +struct FxImpactEntry { + FxEffectDef *nonflesh[31]; + FxEffectDef *flesh[4]; +}; + +struct FxImpactTable { + const char *name; + FxImpactEntry *table; +}; + +enum LbColType { + LBCOL_TYPE_NUMBER = 0x0, + LBCOL_TYPE_TIME = 0x1, + LBCOL_TYPE_LEVELXP = 0x2, + LBCOL_TYPE_PRESTIGE = 0x3, + LBCOL_TYPE_BIGNUMBER = 0x4, + LBCOL_TYPE_PERCENT = 0x5, + LBCOL_TYPE_COUNT = 0x6, +}; + +enum LbAggType { + LBAGG_TYPE_MIN = 0x0, + LBAGG_TYPE_MAX = 0x1, + LBAGG_TYPE_SUM = 0x2, + LBAGG_TYPE_LAST = 0x3, + LBAGG_TYPE_COUNT = 0x4, +}; + +struct LbColumnDef { + const char *name; + int id; + int propertyId; + bool hidden; + const char *statName; + LbColType type; + int precision; + LbAggType agg; +}; + +struct LeaderboardDef { + const char *name; + int id; + int columnCount; + int xpColId; + int prestigeColId; + LbColumnDef *columns; +}; + +struct TracerDef { + const char *name; + Material *material; + unsigned int drawInterval; + float speed; + float beamLength; + float beamWidth; + float screwRadius; + float screwDist; + float colors[5][4]; +}; + +enum StructuredDataTypeCategory { + DATA_INT = 0x0, + DATA_BYTE = 0x1, + DATA_BOOL = 0x2, + DATA_STRING = 0x3, + DATA_ENUM = 0x4, + DATA_STRUCT = 0x5, + DATA_INDEXED_ARRAY = 0x6, + DATA_ENUM_ARRAY = 0x7, + DATA_FLOAT = 0x8, + DATA_SHORT = 0x9, + + DATA_COUNT +}; + +struct StructuredDataEnumEntry { + const char *string; + uint16_t index; +}; + +struct StructuredDataEnum { + int entryCount; + int reservedEntryCount; + StructuredDataEnumEntry *entries; +}; + +union StructuredDataTypeUnion { + unsigned int stringDataLength; + int enumIndex; + int structIndex; + int indexedArrayIndex; + int enumedArrayIndex; +}; + +struct StructuredDataType { + StructuredDataTypeCategory type; + StructuredDataTypeUnion u; +}; + +struct StructuredDataStructProperty { + const char *name; + StructuredDataType type; + unsigned int offset; +}; + +struct StructuredDataStruct { + int propertyCount; + StructuredDataStructProperty *properties; + int size; + unsigned int bitOffset; +}; + +struct StructuredDataIndexedArray { + int arraySize; + StructuredDataType elementType; + unsigned int elementSize; +}; + +struct StructuredDataEnumedArray { + int enumIndex; + StructuredDataType elementType; + unsigned int elementSize; +}; + +struct StructuredDataDef { + int version; + unsigned int formatChecksum; + int enumCount; + StructuredDataEnum *enums; + int structCount; + StructuredDataStruct *structs; + int indexedArrayCount; + StructuredDataIndexedArray *indexedArrays; + int enumedArrayCount; + StructuredDataEnumedArray *enumedArrays; + StructuredDataType rootType; + unsigned int size; +}; + +struct StructuredDataDefSet { + const char *name; + unsigned int defCount; + StructuredDataDef *defs; +}; + +struct TriggerModel { + int contents; + uint16_t hullCount; + uint16_t firstHull; +}; + +struct TriggerHull { + Bounds bounds; + int contents; + uint16_t slabCount; + uint16_t firstSlab; +}; + +struct TriggerSlab { + float dir[3]; + float midPoint; + float halfSize; +}; + +struct MapTriggers { + unsigned int count; + TriggerModel *models; + unsigned int hullCount; + TriggerHull *hulls; + unsigned int slabCount; + TriggerSlab *slabs; +}; + +struct Stage { + const char *name; + float origin[3]; + uint16_t triggerIndex; + char sunPrimaryLightIndex; +}; + +struct MapEnts { + const char *name; + char *entityString; + int numEntityChars; + MapTriggers trigger; + Stage *stages; + char stageCount; +}; + +struct AddonMapEnts { + const char *name; + char *entityString; + int numEntityChars; + MapTriggers trigger; +}; + +typedef unsigned short LeafBrush; + +struct cStaticModel_s { + XModel *xmodel; + float origin[3]; + float invScaledAxis[3][3]; + Bounds absBounds; +}; + +struct ClipMaterial { + const char *name; + int surfaceFlags; + int contents; +}; + +struct cNode_t { + cplane_s *plane; + int16_t children[2]; +}; + +struct cLeafBrushNodeLeaf_t { + LeafBrush *brushes; +}; + +struct cLeafBrushNodeChildren_t { + float dist; + float range; + uint16_t childOffset[2]; +}; + +union cLeafBrushNodeData_t { + cLeafBrushNodeLeaf_t leaf; + cLeafBrushNodeChildren_t children; +}; + +struct cLeafBrushNode_s { + char axis; + int16_t leafBrushCount; + int contents; + cLeafBrushNodeData_t data; +}; + +struct CollisionBorder { + float distEq[3]; + float zBase; + float zSlope; + float start; + float length; +}; + +struct CollisionPartition { + char triCount; + char borderCount; + char firstVertSegment; + int firstTri; + CollisionBorder *borders; +}; + +union CollisionAabbTreeIndex { + int firstChildIndex; + int partitionIndex; +}; + +struct type_align(16) CollisionAabbTree { + float midPoint[3]; + uint16_t materialIndex; + uint16_t childCount; + float halfSize[3]; + CollisionAabbTreeIndex u; +}; + +struct cLeaf_t { + uint16_t firstCollAabbIndex; + uint16_t collAabbCount; + int brushContents; + int terrainContents; + Bounds bounds; + int leafBrushNode; +}; + +struct cmodel_t { + Bounds bounds; + float radius; + cLeaf_t leaf; +}; + +struct cbrush_t { + uint16_t numsides; + uint16_t glassPieceIndex; + cbrushside_t *sides; + char *baseAdjacentSide; + int16_t axialMaterialNum[2][3]; + char firstAdjacentSideOffsets[2][3]; + char edgeCount[2][3]; +}; + +struct SModelAabbNode { + Bounds bounds; + uint16_t firstChild; + uint16_t childCount; +}; + +struct GfxPlacement { + float quat[4]; + float origin[3]; +}; + +enum DynEntityType { + DYNENT_TYPE_INVALID = 0x0, + DYNENT_TYPE_CLUTTER = 0x1, + DYNENT_TYPE_DESTRUCT = 0x2, + DYNENT_TYPE_COUNT = 0x3, +}; + +struct DynEntityDef { + DynEntityType type; + GfxPlacement pose; + XModel *xModel; + uint16_t brushModel; + uint16_t physicsBrushModel; + FxEffectDef *destroyFx; + PhysPreset *physPreset; + int health; + PhysMass mass; + int contents; +}; + +struct DynEntityPose { + GfxPlacement pose; + float radius; +}; + +struct DynEntityClient { + int physObjId; + uint16_t flags; + uint16_t lightingHandle; + int health; +}; + +struct DynEntityColl { + uint16_t sector; + uint16_t nextEntInSector; + float linkMins[2]; + float linkMaxs[2]; +}; + +typedef tdef_align(128) cbrush_t cbrush_array_t; +typedef tdef_align(128) Bounds BoundsArray; + +struct clipMap_t { + const char *name; + int isInUse; + int planeCount; + cplane_s *planes; + unsigned int numStaticModels; + cStaticModel_s *staticModelList; + unsigned int numMaterials; + ClipMaterial *materials; + unsigned int numBrushSides; + cbrushside_t *brushsides; + unsigned int numBrushEdges; + cbrushedge_t *brushEdges; + unsigned int numNodes; + cNode_t *nodes; + unsigned int numLeafs; + cLeaf_t *leafs; + unsigned int leafbrushNodesCount; + cLeafBrushNode_s *leafbrushNodes; + unsigned int numLeafBrushes; + LeafBrush *leafbrushes; + unsigned int numLeafSurfaces; + unsigned int *leafsurfaces; + unsigned int vertCount; + vec3_t *verts; + int triCount; + uint16_t *triIndices; + char *triEdgeIsWalkable; + int borderCount; + CollisionBorder *borders; + int partitionCount; + CollisionPartition *partitions; + int aabbTreeCount; + CollisionAabbTree *aabbTrees; + unsigned int numSubModels; + cmodel_t *cmodels; + uint16_t numBrushes; + cbrush_array_t *brushes; + BoundsArray *brushBounds; + int *brushContents; + MapEnts *mapEnts; + uint16_t smodelNodeCount; + SModelAabbNode *smodelNodes; + uint16_t dynEntCount[2]; + DynEntityDef *dynEntDefList[2]; + DynEntityPose *dynEntPoseList[2]; + DynEntityClient *dynEntClientList[2]; + DynEntityColl *dynEntCollList[2]; + unsigned int checksum; + char padding[48]; +}; + +struct ComPrimaryLight { + char type; + char canUseShadowMap; + char exponent; + char unused; + float color[3]; + float dir[3]; + float origin[3]; + float radius; + float cosHalfFovOuter; + float cosHalfFovInner; + float cosHalfFovExpanded; + float rotationLimit; + float translationLimit; + const char *defName; +}; + +struct ComWorld { + const char *name; + int isInUse; + unsigned int primaryLightCount; + ComPrimaryLight *primaryLights; +}; + +struct pathnode_t; + +enum nodeType { + NODE_ERROR = 0x0, + NODE_PATHNODE = 0x1, + NODE_COVER_STAND = 0x2, + NODE_COVER_CROUCH = 0x3, + NODE_COVER_CROUCH_WINDOW = 0x4, + NODE_COVER_PRONE = 0x5, + NODE_COVER_RIGHT = 0x6, + NODE_COVER_LEFT = 0x7, + NODE_AMBUSH = 0x8, + NODE_EXPOSED = 0x9, + NODE_CONCEALMENT_STAND = 0xA, + NODE_CONCEALMENT_CROUCH = 0xB, + NODE_CONCEALMENT_PRONE = 0xC, + NODE_DOOR = 0xD, + NODE_DOOR_INTERIOR = 0xE, + NODE_SCRIPTED = 0xF, + NODE_NEGOTIATION_BEGIN = 0x10, + NODE_NEGOTIATION_END = 0x11, + NODE_TURRET = 0x12, + NODE_GUARD = 0x13, + NODE_NUMTYPES = 0x14, + NODE_DONTLINK = 0x14, +}; + +struct pathlink_s { + float fDist; + uint16_t nodeNum; + char disconnectCount; + char negotiationLink; + char flags; + char ubBadPlaceCount[3]; +}; + +enum PathNodeErrorCode { + PNERR_NONE = 0x0, + PNERR_INSOLID = 0x1, + PNERR_FLOATING = 0x2, + PNERR_NOLINK = 0x3, + PNERR_DUPLICATE = 0x4, + PNERR_NOSTANCE = 0x5, + PNERR_INVALIDDOOR = 0x6, + PNERR_NOANGLES = 0x7, + PNERR_BADPLACEMENT = 0x8, + + NUM_PATH_NODE_ERRORS +}; + +struct pathnode_constant_t { + nodeType type; + uint16_t spawnflags; + uint16_t targetname; + uint16_t script_linkName; + uint16_t script_noteworthy; + uint16_t target; + uint16_t animscript; + int animscriptfunc; + float vOrigin[3]; + float fAngle; + float forward[2]; + float fRadius; + union { + float minUseDistSq; + PathNodeErrorCode error; + }; + int16_t wOverlapNode[2]; + uint16_t totalLinkCount; + pathlink_s *Links; +}; + +struct pathnode_dynamic_t { + void *pOwner; + int iFreeTime; + int iValidTime[3]; + int dangerousNodeTime[3]; + int inPlayerLOSTime; + int16_t wLinkCount; + int16_t wOverlapCount; + int16_t turretEntNumber; + char userCount; + bool hasBadPlaceLink; +}; + +struct pathnode_transient_t { + int iSearchFrame; + pathnode_t *pNextOpen; + pathnode_t *pPrevOpen; + pathnode_t *pParent; + float fCost; + float fHeuristic; + union { + float nodeCost; + int linkIndex; + }; +}; + +struct pathnode_t { + pathnode_constant_t constant; + pathnode_dynamic_t dynamic; + pathnode_transient_t transient; +}; + +struct type_align(16) pathbasenode_t { + float vOrigin[3]; + unsigned int type; +}; + +struct pathnode_tree_nodes_t { + int nodeCount; + uint16_t *nodes; +}; + +struct pathnode_tree_t; + +union pathnode_tree_info_t { + pathnode_tree_t *child[2]; + pathnode_tree_nodes_t s; +}; + +struct pathnode_tree_t { + int axis; + float dist; + pathnode_tree_info_t u; +}; + +struct PathData { + unsigned int nodeCount; + pathnode_t *nodes; + pathbasenode_t *basenodes; + unsigned int chainNodeCount; + uint16_t *chainNodeForNode; + uint16_t *nodeForChainNode; + int visBytes; + char *pathVis; + int nodeTreeCount; + pathnode_tree_t *nodeTree; +}; + +struct VehicleTrackObstacle { + float origin[2]; + float radius; +}; + +struct VehicleTrackSector { + float startEdgeDir[2]; + float startEdgeDist; + float leftEdgeDir[2]; + float leftEdgeDist; + float rightEdgeDir[2]; + float rightEdgeDist; + float sectorLength; + float sectorWidth; + float totalPriorLength; + float totalFollowingLength; + VehicleTrackObstacle *obstacles; + unsigned int obstacleCount; +}; + +struct VehicleTrackSegment { + const char *targetName; + VehicleTrackSector *sectors; + unsigned int sectorCount; + VehicleTrackSegment **nextBranches; + unsigned int nextBranchesCount; + VehicleTrackSegment **prevBranches; + unsigned int prevBranchesCount; + float endEdgeDir[2]; + float endEdgeDist; + float totalLength; +}; + +struct VehicleTrack { + VehicleTrackSegment *segments; + unsigned int segmentCount; +}; + +struct G_GlassPiece { + uint16_t damageTaken; + uint16_t collapseTime; + int lastStateChangeTime; + char impactDir; + char impactPos[2]; +}; + +struct G_GlassName { + char *nameStr; + uint16_t name; + uint16_t pieceCount; + uint16_t *pieceIndices; +}; + +struct G_GlassData { + G_GlassPiece *glassPieces; + unsigned int pieceCount; + uint16_t damageToWeaken; + uint16_t damageToDestroy; + unsigned int glassNameCount; + G_GlassName *glassNames; + char pad[108]; +}; + +struct GameWorldSp { + const char *name; + PathData path; + VehicleTrack vehicleTrack; + G_GlassData *g_glassData; +}; + +struct GameWorldMp { + const char *name; + G_GlassData *g_glassData; +}; + +struct FxGlassDef { + float halfThickness; + float texVecs[2][2]; + GfxColor color; + Material *material; + Material *materialShattered; + PhysPreset *physPreset; +}; + +struct FxSpatialFrame { + float quat[4]; + float origin[3]; +}; + +union FxGlassPiecePlace { + struct { + FxSpatialFrame frame; + float radius; + }; + unsigned int nextFree; +}; + +struct FxGlassPieceState { + float texCoordOrigin[2]; + unsigned int supportMask; + uint16_t initIndex; + uint16_t geoDataStart; + char defIndex; + char pad[5]; + char vertCount; + char holeDataCount; + char crackDataCount; + char fanDataCount; + uint16_t flags; + float areaX2; +}; + +struct FxGlassPieceDynamics { + int fallTime; + int physObjId; + int physJointId; + float vel[3]; + float avel[3]; +}; + +struct FxGlassVertex { + int16_t x; + int16_t y; +}; + +struct FxGlassHoleHeader { + uint16_t uniqueVertCount; + char touchVert; + char pad[1]; +}; + +struct FxGlassCrackHeader { + uint16_t uniqueVertCount; + char beginVertIndex; + char endVertIndex; +}; + +union type_align(4) FxGlassGeometryData { + FxGlassVertex vert; + FxGlassHoleHeader hole; + FxGlassCrackHeader crack; + char asBytes[4]; + int16_t anonymous[2]; +}; + +struct FxGlassInitPieceState { + FxSpatialFrame frame; + float radius; + float texCoordOrigin[2]; + unsigned int supportMask; + float areaX2; + char defIndex; + char vertCount; + char fanDataCount; + char pad[1]; +}; + +struct FxGlassSystem { + int time; + int prevTime; + unsigned int defCount; + unsigned int pieceLimit; + unsigned int pieceWordCount; + unsigned int initPieceCount; + unsigned int cellCount; + unsigned int activePieceCount; + unsigned int firstFreePiece; + unsigned int geoDataLimit; + unsigned int geoDataCount; + unsigned int initGeoDataCount; + FxGlassDef *defs; + FxGlassPiecePlace *piecePlaces; + FxGlassPieceState *pieceStates; + FxGlassPieceDynamics *pieceDynamics; + FxGlassGeometryData *geoData; + raw_uint *isInUse; + raw_uint *cellBits; + raw_byte16 *visData; + vec3_t *linkOrg; + raw_float16 *halfThickness; + uint16_t *lightingHandles; + FxGlassInitPieceState *initPieceStates; + FxGlassGeometryData *initGeoData; + bool needToCompactData; + char initCount; + float effectChanceAccum; + int lastPieceDeletionTime; +}; + +struct FxWorld { + const char *name; + FxGlassSystem glassSys; +}; + +struct GfxSky { + int skySurfCount; + int *skyStartSurfs; + GfxImage *skyImage; + char skySamplerState; +}; + +struct GfxWorldDpvsPlanes { + int cellCount; + cplane_s *planes; + uint16_t *nodes; + raw_uint *sceneEntCellBits; +}; + +struct GfxCellTreeCount { + int aabbTreeCount; +}; + +typedef unsigned short StaticModelIndex; + +struct GfxAabbTree { + Bounds bounds; + uint16_t childCount; + uint16_t surfaceCount; + uint16_t startSurfIndex; + uint16_t surfaceCountNoDecal; + uint16_t startSurfIndexNoDecal; + uint16_t smodelIndexCount; + StaticModelIndex *smodelIndexes; + int childrenOffset; +}; + +struct GfxCellTree { + GfxAabbTree *aabbTree; +}; + +struct GfxPortal; + +struct GfxPortalWritable { + bool isQueued; + bool isAncestor; + char recursionDepth; + char hullPointCount; + float (*hullPoints)[2]; + GfxPortal *queuedParent; +}; + +struct DpvsPlane { + float coeffs[4]; +}; + +struct GfxPortal { + GfxPortalWritable writable; + DpvsPlane plane; + vec3_t *vertices; + uint16_t cellIndex; + char vertexCount; + float hullAxis[2][3]; +}; + +struct GfxCell { + Bounds bounds; + int portalCount; + GfxPortal *portals; + char reflectionProbeCount; + char *reflectionProbes; +}; + +struct GfxReflectionProbe { + float origin[3]; +}; + +struct GfxLightmapArray { + GfxImage *primary; + GfxImage *secondary; +}; + +struct GfxWorldVertex { + float xyz[3]; + float binormalSign; + GfxColor color; + float texCoord[2]; + float lmapCoord[2]; + PackedUnitVec normal; + PackedUnitVec tangent; +}; + +struct GfxWorldVertexData { + GfxWorldVertex *vertices; + void /*IDirect3DVertexBuffer9*/ *worldVb; +}; + +struct GfxWorldVertexLayerData { + char *data; + void /*IDirect3DVertexBuffer9*/ *layerVb; +}; + +struct GfxWorldDraw { + unsigned int reflectionProbeCount; + GfxImage **reflectionProbes; + GfxReflectionProbe *reflectionProbeOrigins; + GfxTexture *reflectionProbeTextures; + int lightmapCount; + GfxLightmapArray *lightmaps; + GfxTexture *lightmapPrimaryTextures; + GfxTexture *lightmapSecondaryTextures; + GfxImage *lightmapOverridePrimary; + GfxImage *lightmapOverrideSecondary; + unsigned int vertexCount; + GfxWorldVertexData vd; + unsigned int vertexLayerDataSize; + GfxWorldVertexLayerData vld; + unsigned int indexCount; + r_index_t *indices; +}; + +struct type_align(4) GfxLightGridEntry { + uint16_t colorsIndex; + char primaryLightIndex; + char needsTrace; +}; + +struct type_align(4) GfxLightGridColors { char rgb[56][3]; }; + +struct GfxLightGrid { + bool hasLightRegions; + unsigned int lastSunPrimaryLightIndex; + uint16_t mins[3]; + uint16_t maxs[3]; + unsigned int rowAxis; + unsigned int colAxis; + uint16_t *rowDataStart; + unsigned int rawRowDataSize; + char *rawRowData; + unsigned int entryCount; + GfxLightGridEntry *entries; + unsigned int colorCount; + GfxLightGridColors *colors; +}; + +struct GfxBrushModelWritable { + Bounds bounds; +}; + +struct type_align(4) GfxBrushModel { + GfxBrushModelWritable writable; + Bounds bounds; + float radius; + uint16_t surfaceCount; + uint16_t startSurfIndex; + uint16_t surfaceCountNoDecal; +}; + +struct MaterialMemory { + Material *material; + int memory; +}; + +struct sunflare_t { + bool hasValidData; + Material *spriteMaterial; + Material *flareMaterial; + float spriteSize; + float flareMinSize; + float flareMinDot; + float flareMaxSize; + float flareMaxDot; + float flareMaxAlpha; + int flareFadeInTime; + int flareFadeOutTime; + float blindMinDot; + float blindMaxDot; + float blindMaxDarken; + int blindFadeInTime; + int blindFadeOutTime; + float glareMinDot; + float glareMaxDot; + float glareMaxLighten; + int glareFadeInTime; + int glareFadeOutTime; + float sunFxPosition[3]; +}; + +struct XModelDrawInfo { + char hasGfxEntIndex; + char lod; + uint16_t surfId; +}; + +struct GfxSceneDynModel { + XModelDrawInfo info; + uint16_t dynEntId; +}; + +struct BModelDrawInfo { + uint16_t surfId; +}; + +struct type_align(4) GfxSceneDynBrush { + BModelDrawInfo info; + uint16_t dynEntId; +}; + +struct GfxShadowGeometry { + uint16_t surfaceCount; + uint16_t smodelCount; + uint16_t *sortedSurfIndex; + uint16_t *smodelIndex; +}; + +struct GfxLightRegionAxis { + float dir[3]; + float midPoint; + float halfSize; +}; + +struct GfxLightRegionHull { + float kdopMidPoint[9]; + float kdopHalfSize[9]; + unsigned int axisCount; + GfxLightRegionAxis *axis; +}; + +struct GfxLightRegion { + unsigned int hullCount; + GfxLightRegionHull *hulls; +}; + +struct GfxPackedPlacement { + float origin[3]; + float axis[3][3]; + float scale; +}; + +struct GfxStaticModelDrawInst { + GfxPackedPlacement placement; + XModel *model; + uint16_t cullDist; + uint16_t lightingHandle; + char reflectionProbeIndex; + char primaryLightIndex; + char flags; + char firstMtlSkinIndex; + GfxColor groundLighting; + uint16_t cacheId[4]; +}; + +struct GfxStaticModelInst { + Bounds bounds; + float lightingOrigin[3]; +}; + +struct srfTriangles_t { + unsigned int vertexLayerData; + unsigned int firstVertex; + uint16_t vertexCount; + uint16_t triCount; + unsigned int baseIndex; +}; + +struct GfxSurfaceLightingAndFlagsFields { + char lightmapIndex; + char reflectionProbeIndex; + char primaryLightIndex; + char flags; +}; + +union GfxSurfaceLightingAndFlags { + GfxSurfaceLightingAndFlagsFields fields; + unsigned int packed; +}; + +struct GfxSurface { + srfTriangles_t tris; + Material *material; + GfxSurfaceLightingAndFlags laf; +}; + +struct GfxSurfaceBounds { + Bounds bounds; +}; + +struct GfxWorldDpvsStatic { + unsigned int smodelCount; + unsigned int staticSurfaceCount; + unsigned int staticSurfaceCountNoDecal; + unsigned int litOpaqueSurfsBegin; + unsigned int litOpaqueSurfsEnd; + unsigned int litTransSurfsBegin; + unsigned int litTransSurfsEnd; + unsigned int shadowCasterSurfsBegin; + unsigned int shadowCasterSurfsEnd; + unsigned int emissiveSurfsBegin; + unsigned int emissiveSurfsEnd; + unsigned int smodelVisDataCount; + unsigned int surfaceVisDataCount; + char *smodelVisData[3]; + char *surfaceVisData[3]; + uint16_t *sortedSurfIndex; + GfxStaticModelInst *smodelInsts; + GfxSurface *surfaces; + GfxSurfaceBounds *surfacesBounds; + GfxStaticModelDrawInst *smodelDrawInsts; + GfxDrawSurf *surfaceMaterials; + raw_uint128 *surfaceCastsSunShadow; + volatile int usageCount; +}; + +struct GfxWorldDpvsDynamic { + unsigned int dynEntClientWordCount[2]; + unsigned int dynEntClientCount[2]; + raw_uint *dynEntCellBits[2]; + raw_byte16 *dynEntVisData[2][3]; +}; + +struct GfxHeroOnlyLight { + char type; + char unused[3]; + float color[3]; + float dir[3]; + float origin[3]; + float radius; + float cosHalfFovOuter; + float cosHalfFovInner; + int exponent; +}; + +typedef tdef_align(128) GfxCellTree GfxCellTree128; +typedef tdef_align(4) GfxSceneDynModel GfxSceneDynModel4; + +struct GfxWorld { + const char *name; + const char *baseName; + int planeCount; + int nodeCount; + unsigned int surfaceCount; + int skyCount; + GfxSky *skies; + unsigned int lastSunPrimaryLightIndex; + unsigned int primaryLightCount; + unsigned int sortKeyLitDecal; + unsigned int sortKeyEffectDecal; + unsigned int sortKeyEffectAuto; + unsigned int sortKeyDistortion; + GfxWorldDpvsPlanes dpvsPlanes; + int /*GfxCellTreeCount*/ *aabbTreeCounts; + GfxCellTree128 *aabbTrees; + GfxCell *cells; + GfxWorldDraw draw; + GfxLightGrid lightGrid; + int modelCount; + GfxBrushModel *models; + Bounds bounds; + unsigned int checksum; + int materialMemoryCount; + MaterialMemory *materialMemory; + sunflare_t sun; + float outdoorLookupMatrix[4][4]; + GfxImage *outdoorImage; + raw_uint *cellCasterBits; + raw_uint *cellHasSunLitSurfsBits; + GfxSceneDynModel4 *sceneDynModel; + GfxSceneDynBrush *sceneDynBrush; + raw_uint *primaryLightEntityShadowVis; + raw_uint *primaryLightDynEntShadowVis[2]; + char *nonSunPrimaryLightForModelDynEnt; + GfxShadowGeometry *shadowGeom; + GfxLightRegion *lightRegion; + GfxWorldDpvsStatic dpvs; + GfxWorldDpvsDynamic dpvsDyn; + unsigned int mapVtxChecksum; + unsigned int heroOnlyLightCount; + GfxHeroOnlyLight *heroOnlyLights; + char fogTypesAllowed; +}; + +enum ImpactType { + IMPACT_TYPE_NONE = 0x0, + IMPACT_TYPE_BULLET_SMALL = 0x1, + IMPACT_TYPE_BULLET_LARGE = 0x2, + IMPACT_TYPE_BULLET_AP = 0x3, + IMPACT_TYPE_BULLET_EXPLODE = 0x4, + IMPACT_TYPE_SHOTGUN = 0x5, + IMPACT_TYPE_SHOTGUN_EXPLODE = 0x6, + IMPACT_TYPE_GRENADE_BOUNCE = 0x7, + IMPACT_TYPE_GRENADE_EXPLODE = 0x8, + IMPACT_TYPE_ROCKET_EXPLODE = 0x9, + IMPACT_TYPE_PROJECTILE_DUD = 0xA, + + IMPACT_TYPE_COUNT +}; + +enum weaponIconRatioType_t { + WEAPON_ICON_RATIO_1TO1 = 0x0, + WEAPON_ICON_RATIO_2TO1 = 0x1, + WEAPON_ICON_RATIO_4TO1 = 0x2, + + WEAPON_ICON_RATIO_COUNT +}; + +enum weapType_t { + WEAPTYPE_BULLET = 0x0, + WEAPTYPE_GRENADE = 0x1, + WEAPTYPE_PROJECTILE = 0x2, + WEAPTYPE_RIOTSHIELD = 0x3, + + WEAPTYPE_NUM +}; + +enum weapClass_t { + WEAPCLASS_RIFLE = 0x0, + WEAPCLASS_SNIPER = 0x1, + WEAPCLASS_MG = 0x2, + WEAPCLASS_SMG = 0x3, + WEAPCLASS_SPREAD = 0x4, + WEAPCLASS_PISTOL = 0x5, + WEAPCLASS_GRENADE = 0x6, + WEAPCLASS_ROCKETLAUNCHER = 0x7, + WEAPCLASS_TURRET = 0x8, + WEAPCLASS_THROWINGKNIFE = 0x9, + WEAPCLASS_NON_PLAYER = 0xA, + WEAPCLASS_ITEM = 0xB, + + WEAPCLASS_NUM +}; + +enum PenetrateType { + PENETRATE_TYPE_NONE = 0x0, + PENETRATE_TYPE_SMALL = 0x1, + PENETRATE_TYPE_MEDIUM = 0x2, + PENETRATE_TYPE_LARGE = 0x3, + + PENETRATE_TYPE_COUNT +}; + +enum weapInventoryType_t { + WEAPINVENTORY_PRIMARY = 0x0, + WEAPINVENTORY_OFFHAND = 0x1, + WEAPINVENTORY_ITEM = 0x2, + WEAPINVENTORY_ALTMODE = 0x3, + WEAPINVENTORY_EXCLUSIVE = 0x4, + WEAPINVENTORY_SCAVENGER = 0x5, + + WEAPINVENTORYCOUNT +}; + +enum weapFireType_t { + WEAPON_FIRETYPE_FULLAUTO = 0x0, + WEAPON_FIRETYPE_SINGLESHOT = 0x1, + WEAPON_FIRETYPE_BURSTFIRE2 = 0x2, + WEAPON_FIRETYPE_BURSTFIRE3 = 0x3, + WEAPON_FIRETYPE_BURSTFIRE4 = 0x4, + WEAPON_FIRETYPE_DOUBLEBARREL = 0x5, + WEAPON_FIRETYPECOUNT = 0x6, + WEAPON_FIRETYPE_BURSTFIRE_FIRST = 0x2, + WEAPON_FIRETYPE_BURSTFIRE_LAST = 0x4, +}; + +enum OffhandClass { + OFFHAND_CLASS_NONE = 0x0, + OFFHAND_CLASS_FRAG_GRENADE = 0x1, + OFFHAND_CLASS_SMOKE_GRENADE = 0x2, + OFFHAND_CLASS_FLASH_GRENADE = 0x3, + OFFHAND_CLASS_THROWINGKNIFE = 0x4, + OFFHAND_CLASS_OTHER = 0x5, + + OFFHAND_CLASS_COUNT +}; + +enum weapStance_t { + WEAPSTANCE_STAND = 0x0, + WEAPSTANCE_DUCK = 0x1, + WEAPSTANCE_PRONE = 0x2, + + WEAPSTANCE_NUM +}; + +enum activeReticleType_t { + VEH_ACTIVE_RETICLE_NONE = 0x0, + VEH_ACTIVE_RETICLE_PIP_ON_A_STICK = 0x1, + VEH_ACTIVE_RETICLE_BOUNCING_DIAMOND = 0x2, + + VEH_ACTIVE_RETICLE_COUNT +}; + +enum ammoCounterClipType_t { + AMMO_COUNTER_CLIP_NONE = 0x0, + AMMO_COUNTER_CLIP_MAGAZINE = 0x1, + AMMO_COUNTER_CLIP_SHORTMAGAZINE = 0x2, + AMMO_COUNTER_CLIP_SHOTGUN = 0x3, + AMMO_COUNTER_CLIP_ROCKET = 0x4, + AMMO_COUNTER_CLIP_BELTFED = 0x5, + AMMO_COUNTER_CLIP_ALTWEAPON = 0x6, + + AMMO_COUNTER_CLIP_COUNT +}; + +enum weapOverlayReticle_t { + WEAPOVERLAYRETICLE_NONE = 0x0, + WEAPOVERLAYRETICLE_CROSSHAIR = 0x1, + + WEAPOVERLAYRETICLE_NUM +}; + +enum WeapOverlayInteface_t { + WEAPOVERLAYINTERFACE_NONE = 0x0, + WEAPOVERLAYINTERFACE_JAVELIN = 0x1, + WEAPOVERLAYINTERFACE_TURRETSCOPE = 0x2, + + WEAPOVERLAYINTERFACECOUNT +}; + +enum weapProjExposion_t { + WEAPPROJEXP_GRENADE = 0x0, + WEAPPROJEXP_ROCKET = 0x1, + WEAPPROJEXP_FLASHBANG = 0x2, + WEAPPROJEXP_NONE = 0x3, + WEAPPROJEXP_DUD = 0x4, + WEAPPROJEXP_SMOKE = 0x5, + WEAPPROJEXP_HEAVY = 0x6, + + WEAPPROJEXP_NUM +}; + +enum WeapStickinessType { + WEAPSTICKINESS_NONE = 0x0, + WEAPSTICKINESS_ALL = 0x1, + WEAPSTICKINESS_ALL_ORIENT = 0x2, + WEAPSTICKINESS_GROUND = 0x3, + WEAPSTICKINESS_GROUND_WITH_YAW = 0x4, + WEAPSTICKINESS_KNIFE = 0x5, + + WEAPSTICKINESS_COUNT +}; + +enum guidedMissileType_t { + MISSILE_GUIDANCE_NONE = 0x0, + MISSILE_GUIDANCE_SIDEWINDER = 0x1, + MISSILE_GUIDANCE_HELLFIRE = 0x2, + MISSILE_GUIDANCE_JAVELIN = 0x3, + + MISSILE_GUIDANCE_COUNT +}; + +enum weapAnimFiles_t { + WEAP_ANIM_ROOT = 0x0, + WEAP_ANIM_IDLE = 0x1, + WEAP_ANIM_EMPTY_IDLE = 0x2, + WEAP_ANIM_FIRE = 0x3, + WEAP_ANIM_HOLD_FIRE = 0x4, + WEAP_ANIM_LASTSHOT = 0x5, + WEAP_ANIM_RECHAMBER = 0x6, + WEAP_ANIM_MELEE = 0x7, + WEAP_ANIM_MELEE_CHARGE = 0x8, + WEAP_ANIM_RELOAD = 0x9, + WEAP_ANIM_RELOAD_EMPTY = 0xA, + WEAP_ANIM_RELOAD_START = 0xB, + WEAP_ANIM_RELOAD_END = 0xC, + WEAP_ANIM_RAISE = 0xD, + WEAP_ANIM_FIRST_RAISE = 0xE, + WEAP_ANIM_BREACH_RAISE = 0xF, + WEAP_ANIM_DROP = 0x10, + WEAP_ANIM_ALT_RAISE = 0x11, + WEAP_ANIM_ALT_DROP = 0x12, + WEAP_ANIM_QUICK_RAISE = 0x13, + WEAP_ANIM_QUICK_DROP = 0x14, + WEAP_ANIM_EMPTY_RAISE = 0x15, + WEAP_ANIM_EMPTY_DROP = 0x16, + WEAP_ANIM_SPRINT_IN = 0x17, + WEAP_ANIM_SPRINT_LOOP = 0x18, + WEAP_ANIM_SPRINT_OUT = 0x19, + WEAP_ANIM_STUNNED_START = 0x1A, + WEAP_ANIM_STUNNED_LOOP = 0x1B, + WEAP_ANIM_STUNNED_END = 0x1C, + WEAP_ANIM_DETONATE = 0x1D, + WEAP_ANIM_NIGHTVISION_WEAR = 0x1E, + WEAP_ANIM_NIGHTVISION_REMOVE = 0x1F, + WEAP_ANIM_ADS_FIRE = 0x20, + WEAP_ANIM_ADS_LASTSHOT = 0x21, + WEAP_ANIM_ADS_RECHAMBER = 0x22, + WEAP_ANIM_ADS_UP = 0x23, + WEAP_ANIM_ADS_DOWN = 0x24, + + NUM_WEAP_ANIMS, +}; + +enum materialSurfType_t { + SURF_TYPE_DEFAULT, + SURF_TYPE_BARK, + SURF_TYPE_BRICK, + SURF_TYPE_CARPET, + SURF_TYPE_CLOTH, + SURF_TYPE_CONCRETE, + SURF_TYPE_DIRT, + SURF_TYPE_FLESH, + SURF_TYPE_FOLIAGE, + SURF_TYPE_GLASS, + SURF_TYPE_GRASS, + SURF_TYPE_GRAVEL, + SURF_TYPE_ICE, + SURF_TYPE_METAL, + SURF_TYPE_MUD, + SURF_TYPE_PAPER, + SURF_TYPE_PLASTER, + SURF_TYPE_ROCK, + SURF_TYPE_SAND, + SURF_TYPE_SNOW, + SURF_TYPE_WATER, + SURF_TYPE_WOOD, + SURF_TYPE_ASPHALT, + SURF_TYPE_CERAMIC, + SURF_TYPE_PLASTIC, + SURF_TYPE_RUBBER, + SURF_TYPE_CUSHION, + SURF_TYPE_FRUIT, + SURF_TYPE_PAINTED_METAL, + SURF_TYPE_RIOT_SHIELD, + SURF_TYPE_SLUSH, + + SURF_TYPE_NUM +}; + +enum hitLocation_t { + HITLOC_NONE = 0x0, + HITLOC_HELMET = 0x1, + HITLOC_HEAD = 0x2, + HITLOC_NECK = 0x3, + HITLOC_TORSO_UPR = 0x4, + HITLOC_TORSO_LWR = 0x5, + HITLOC_R_ARM_UPR = 0x6, + HITLOC_L_ARM_UPR = 0x7, + HITLOC_R_ARM_LWR = 0x8, + HITLOC_L_ARM_LWR = 0x9, + HITLOC_R_HAND = 0xA, + HITLOC_L_HAND = 0xB, + HITLOC_R_LEG_UPR = 0xC, + HITLOC_L_LEG_UPR = 0xD, + HITLOC_R_LEG_LWR = 0xE, + HITLOC_L_LEG_LWR = 0xF, + HITLOC_R_FOOT = 0x10, + HITLOC_L_FOOT = 0x11, + HITLOC_GUN = 0x12, + HITLOC_SHIELD = 0x13, + + HITLOC_NUM, +}; + +struct snd_alias_list_name { + const char *soundName; +}; + +union SndAliasCustom { + snd_alias_list_name *name; + snd_alias_list_t *sound; +}; + +struct WeaponDef { + const char *szOverlayName; + XModel **gunXModel; + XModel *handXModel; + const char **szXAnimsRightHanded; + const char **szXAnimsLeftHanded; + const char *szModeName; + uint16_t *notetrackSoundMapKeys; + uint16_t *notetrackSoundMapValues; + uint16_t *notetrackRumbleMapKeys; + uint16_t *notetrackRumbleMapValues; + int playerAnimType; + weapType_t weapType; + weapClass_t weapClass; + PenetrateType penetrateType; + weapInventoryType_t inventoryType; + weapFireType_t fireType; + OffhandClass offhandClass; + weapStance_t stance; + FxEffectDef *viewFlashEffect; + FxEffectDef *worldFlashEffect; + SndAliasCustom pickupSound; + SndAliasCustom pickupSoundPlayer; + SndAliasCustom ammoPickupSound; + SndAliasCustom ammoPickupSoundPlayer; + SndAliasCustom projectileSound; + SndAliasCustom pullbackSound; + SndAliasCustom pullbackSoundPlayer; + SndAliasCustom fireSound; + SndAliasCustom fireSoundPlayer; + SndAliasCustom fireSoundPlayerAkimbo; + SndAliasCustom fireLoopSound; + SndAliasCustom fireLoopSoundPlayer; + SndAliasCustom fireStopSound; + SndAliasCustom fireStopSoundPlayer; + SndAliasCustom fireLastSound; + SndAliasCustom fireLastSoundPlayer; + SndAliasCustom emptyFireSound; + SndAliasCustom emptyFireSoundPlayer; + SndAliasCustom meleeSwipeSound; + SndAliasCustom meleeSwipeSoundPlayer; + SndAliasCustom meleeHitSound; + SndAliasCustom meleeMissSound; + SndAliasCustom rechamberSound; + SndAliasCustom rechamberSoundPlayer; + SndAliasCustom reloadSound; + SndAliasCustom reloadSoundPlayer; + SndAliasCustom reloadEmptySound; + SndAliasCustom reloadEmptySoundPlayer; + SndAliasCustom reloadStartSound; + SndAliasCustom reloadStartSoundPlayer; + SndAliasCustom reloadEndSound; + SndAliasCustom reloadEndSoundPlayer; + SndAliasCustom detonateSound; + SndAliasCustom detonateSoundPlayer; + SndAliasCustom nightVisionWearSound; + SndAliasCustom nightVisionWearSoundPlayer; + SndAliasCustom nightVisionRemoveSound; + SndAliasCustom nightVisionRemoveSoundPlayer; + SndAliasCustom altSwitchSound; + SndAliasCustom altSwitchSoundPlayer; + SndAliasCustom raiseSound; + SndAliasCustom raiseSoundPlayer; + SndAliasCustom firstRaiseSound; + SndAliasCustom firstRaiseSoundPlayer; + SndAliasCustom putawaySound; + SndAliasCustom putawaySoundPlayer; + SndAliasCustom scanSound; + SndAliasCustom *bounceSound; + FxEffectDef *viewShellEjectEffect; + FxEffectDef *worldShellEjectEffect; + FxEffectDef *viewLastShotEjectEffect; + FxEffectDef *worldLastShotEjectEffect; + Material *reticleCenter; + Material *reticleSide; + int iReticleCenterSize; + int iReticleSideSize; + int iReticleMinOfs; + activeReticleType_t activeReticleType; + float vStandMove[3]; + float vStandRot[3]; + float strafeMove[3]; + float strafeRot[3]; + float vDuckedOfs[3]; + float vDuckedMove[3]; + float vDuckedRot[3]; + float vProneOfs[3]; + float vProneMove[3]; + float vProneRot[3]; + float fPosMoveRate; + float fPosProneMoveRate; + float fStandMoveMinSpeed; + float fDuckedMoveMinSpeed; + float fProneMoveMinSpeed; + float fPosRotRate; + float fPosProneRotRate; + float fStandRotMinSpeed; + float fDuckedRotMinSpeed; + float fProneRotMinSpeed; + XModel **worldModel; + XModel *worldClipModel; + XModel *rocketModel; + XModel *knifeModel; + XModel *worldKnifeModel; + Material *hudIcon; + weaponIconRatioType_t hudIconRatio; + Material *pickupIcon; + weaponIconRatioType_t pickupIconRatio; + Material *ammoCounterIcon; + weaponIconRatioType_t ammoCounterIconRatio; + ammoCounterClipType_t ammoCounterClip; + int iStartAmmo; + const char *szAmmoName; + int iAmmoIndex; + const char *szClipName; + int iClipIndex; + int iMaxAmmo; + int shotCount; + const char *szSharedAmmoCapName; + int iSharedAmmoCapIndex; + int iSharedAmmoCap; + int damage; + int playerDamage; + int iMeleeDamage; + int iDamageType; + int iFireDelay; + int iMeleeDelay; + int meleeChargeDelay; + int iDetonateDelay; + int iRechamberTime; + int rechamberTimeOneHanded; + int iRechamberBoltTime; + int iHoldFireTime; + int iDetonateTime; + int iMeleeTime; + int meleeChargeTime; + int iReloadTime; + int reloadShowRocketTime; + int iReloadEmptyTime; + int iReloadAddTime; + int iReloadStartTime; + int iReloadStartAddTime; + int iReloadEndTime; + int iDropTime; + int iRaiseTime; + int iAltDropTime; + int quickDropTime; + int quickRaiseTime; + int iBreachRaiseTime; + int iEmptyRaiseTime; + int iEmptyDropTime; + int sprintInTime; + int sprintLoopTime; + int sprintOutTime; + int stunnedTimeBegin; + int stunnedTimeLoop; + int stunnedTimeEnd; + int nightVisionWearTime; + int nightVisionWearTimeFadeOutEnd; + int nightVisionWearTimePowerUp; + int nightVisionRemoveTime; + int nightVisionRemoveTimePowerDown; + int nightVisionRemoveTimeFadeInStart; + int fuseTime; + int aiFuseTime; + float autoAimRange; + float aimAssistRange; + float aimAssistRangeAds; + float aimPadding; + float enemyCrosshairRange; + float moveSpeedScale; + float adsMoveSpeedScale; + float sprintDurationScale; + float fAdsZoomInFrac; + float fAdsZoomOutFrac; + Material *overlayMaterial; + Material *overlayMaterialLowRes; + Material *overlayMaterialEMP; + Material *overlayMaterialEMPLowRes; + weapOverlayReticle_t overlayReticle; + WeapOverlayInteface_t overlayInterface; + float overlayWidth; + float overlayHeight; + float overlayWidthSplitscreen; + float overlayHeightSplitscreen; + float fAdsBobFactor; + float fAdsViewBobMult; + float fHipSpreadStandMin; + float fHipSpreadDuckedMin; + float fHipSpreadProneMin; + float hipSpreadStandMax; + float hipSpreadDuckedMax; + float hipSpreadProneMax; + float fHipSpreadDecayRate; + float fHipSpreadFireAdd; + float fHipSpreadTurnAdd; + float fHipSpreadMoveAdd; + float fHipSpreadDuckedDecay; + float fHipSpreadProneDecay; + float fHipReticleSidePos; + float fAdsIdleAmount; + float fHipIdleAmount; + float adsIdleSpeed; + float hipIdleSpeed; + float fIdleCrouchFactor; + float fIdleProneFactor; + float fGunMaxPitch; + float fGunMaxYaw; + float swayMaxAngle; + float swayLerpSpeed; + float swayPitchScale; + float swayYawScale; + float swayHorizScale; + float swayVertScale; + float swayShellShockScale; + float adsSwayMaxAngle; + float adsSwayLerpSpeed; + float adsSwayPitchScale; + float adsSwayYawScale; + float adsSwayHorizScale; + float adsSwayVertScale; + float adsViewErrorMin; + float adsViewErrorMax; + PhysCollmap *physCollmap; + float dualWieldViewModelOffset; + weaponIconRatioType_t killIconRatio; + int iReloadAmmoAdd; + int iReloadStartAdd; + int ammoDropStockMin; + int ammoDropClipPercentMin; + int ammoDropClipPercentMax; + int iExplosionRadius; + int iExplosionRadiusMin; + int iExplosionInnerDamage; + int iExplosionOuterDamage; + float damageConeAngle; + float bulletExplDmgMult; + float bulletExplRadiusMult; + int iProjectileSpeed; + int iProjectileSpeedUp; + int iProjectileSpeedForward; + int iProjectileActivateDist; + float projLifetime; + float timeToAccelerate; + float projectileCurvature; + XModel *projectileModel; + weapProjExposion_t projExplosion; + FxEffectDef *projExplosionEffect; + FxEffectDef *projDudEffect; + SndAliasCustom projExplosionSound; + SndAliasCustom projDudSound; + WeapStickinessType stickiness; + float lowAmmoWarningThreshold; + float ricochetChance; + float *parallelBounce; + float *perpendicularBounce; + FxEffectDef *projTrailEffect; + FxEffectDef *projBeaconEffect; + float vProjectileColor[3]; + guidedMissileType_t guidedMissileType; + float maxSteeringAccel; + int projIgnitionDelay; + FxEffectDef *projIgnitionEffect; + SndAliasCustom projIgnitionSound; + float fAdsAimPitch; + float fAdsCrosshairInFrac; + float fAdsCrosshairOutFrac; + int adsGunKickReducedKickBullets; + float adsGunKickReducedKickPercent; + float fAdsGunKickPitchMin; + float fAdsGunKickPitchMax; + float fAdsGunKickYawMin; + float fAdsGunKickYawMax; + float fAdsGunKickAccel; + float fAdsGunKickSpeedMax; + float fAdsGunKickSpeedDecay; + float fAdsGunKickStaticDecay; + float fAdsViewKickPitchMin; + float fAdsViewKickPitchMax; + float fAdsViewKickYawMin; + float fAdsViewKickYawMax; + float fAdsViewScatterMin; + float fAdsViewScatterMax; + float fAdsSpread; + int hipGunKickReducedKickBullets; + float hipGunKickReducedKickPercent; + float fHipGunKickPitchMin; + float fHipGunKickPitchMax; + float fHipGunKickYawMin; + float fHipGunKickYawMax; + float fHipGunKickAccel; + float fHipGunKickSpeedMax; + float fHipGunKickSpeedDecay; + float fHipGunKickStaticDecay; + float fHipViewKickPitchMin; + float fHipViewKickPitchMax; + float fHipViewKickYawMin; + float fHipViewKickYawMax; + float fHipViewScatterMin; + float fHipViewScatterMax; + float fightDist; + float maxDist; + // const char* accuracyGraphName[2];// TODO: Order is accuracyGraphName[0] -> originalAccuracyGraphKnots[0] -> accuracyGraphName[1] -> ... + // Which is currently not possible to do in code generation. Afaik this is the only place where this is the case. + // So might be something to fix but on the other hand it might be too much work for this little inconvenience. + // vec2_t* originalAccuracyGraphKnots[2]; + const char *accuracyGraphName0; + const char *accuracyGraphName1; + vec2_t *originalAccuracyGraphKnots0; + vec2_t *originalAccuracyGraphKnots1; + uint16_t originalAccuracyGraphKnotCount[2]; + int iPositionReloadTransTime; + float leftArc; + float rightArc; + float topArc; + float bottomArc; + float accuracy; + float aiSpread; + float playerSpread; + float minTurnSpeed[2]; + float maxTurnSpeed[2]; + float pitchConvergenceTime; + float yawConvergenceTime; + float suppressTime; + float maxRange; + float fAnimHorRotateInc; + float fPlayerPositionDist; + const char *szUseHintString; + const char *dropHintString; + int iUseHintStringIndex; + int dropHintStringIndex; + float horizViewJitter; + float vertViewJitter; + float scanSpeed; + float scanAccel; + int scanPauseTime; + const char *szScript; + float fOOPosAnimLength[2]; + int minDamage; + int minPlayerDamage; + float fMaxDamageRange; + float fMinDamageRange; + float destabilizationRateTime; + float destabilizationCurvatureMax; + int destabilizeDistance; + float *locationDamageMultipliers; + const char *fireRumble; + const char *meleeImpactRumble; + TracerDef *tracerType; + float turretScopeZoomRate; + float turretScopeZoomMin; + float turretScopeZoomMax; + float turretOverheatUpRate; + float turretOverheatDownRate; + float turretOverheatPenalty; + SndAliasCustom turretOverheatSound; + FxEffectDef *turretOverheatEffect; + const char *turretBarrelSpinRumble; + float turretBarrelSpinSpeed; + float turretBarrelSpinUpTime; + float turretBarrelSpinDownTime; + SndAliasCustom turretBarrelSpinMaxSnd; + SndAliasCustom turretBarrelSpinUpSnd[4]; + SndAliasCustom turretBarrelSpinDownSnd[4]; + SndAliasCustom missileConeSoundAlias; + SndAliasCustom missileConeSoundAliasAtBase; + float missileConeSoundRadiusAtTop; + float missileConeSoundRadiusAtBase; + float missileConeSoundHeight; + float missileConeSoundOriginOffset; + float missileConeSoundVolumescaleAtCore; + float missileConeSoundVolumescaleAtEdge; + float missileConeSoundVolumescaleCoreSize; + float missileConeSoundPitchAtTop; + float missileConeSoundPitchAtBottom; + float missileConeSoundPitchTopSize; + float missileConeSoundPitchBottomSize; + float missileConeSoundCrossfadeTopSize; + float missileConeSoundCrossfadeBottomSize; + bool sharedAmmo; + bool lockonSupported; + bool requireLockonToFire; + bool bigExplosion; + bool noAdsWhenMagEmpty; + bool avoidDropCleanup; + bool inheritsPerks; + bool crosshairColorChange; + bool bRifleBullet; + bool armorPiercing; + bool bBoltAction; + bool aimDownSight; + bool bRechamberWhileAds; + bool bBulletExplosiveDamage; + bool bCookOffHold; + bool bClipOnly; + bool noAmmoPickup; + bool adsFireOnly; + bool cancelAutoHolsterWhenEmpty; + bool disableSwitchToWhenEmpty; + bool suppressAmmoReserveDisplay; + bool laserSightDuringNightvision; + bool markableViewmodel; + bool noDualWield; + bool flipKillIcon; + bool bNoPartialReload; + bool bSegmentedReload; + bool blocksProne; + bool silenced; + bool isRollingGrenade; + bool projExplosionEffectForceNormalUp; + bool bProjImpactExplode; + bool stickToPlayers; + bool hasDetonator; + bool disableFiring; + bool timedDetonation; + bool rotate; + bool holdButtonToThrow; + bool freezeMovementWhenFiring; + bool thermalScope; + bool altModeSameWeapon; + bool turretBarrelSpinEnabled; + bool missileConeSoundEnabled; + bool missileConeSoundPitchshiftEnabled; + bool missileConeSoundCrossfadeEnabled; + bool offhandHoldIsCancelable; +}; + +struct WeaponCompleteDef { + const char *szInternalName; + WeaponDef *weapDef; + const char *szDisplayName; + uint16_t *hideTags; + const char **szXAnims; + float fAdsZoomFov; + int iAdsTransInTime; + int iAdsTransOutTime; + int iClipSize; + ImpactType impactType; + int iFireTime; + weaponIconRatioType_t dpadIconRatio; + float penetrateMultiplier; + float fAdsViewKickCenterSpeed; + float fHipViewKickCenterSpeed; + const char *szAltWeaponName; + unsigned int altWeaponIndex; + int iAltRaiseTime; + Material *killIcon; + Material *dpadIcon; + int fireAnimLength; + int iFirstRaiseTime; + int ammoDropStockMax; + float adsDofStart; + float adsDofEnd; + uint16_t accuracyGraphKnotCount[2]; + vec2_t *accuracyGraphKnots[2]; + bool motionTracker; + bool enhanced; + bool dpadIconShowsAmmo; +}; + +struct WeaponFullDef { + WeaponCompleteDef weapCompleteDef; + WeaponDef weapDef; + uint16_t hideTags[32]; + const char *szXAnims[37]; + XModel *gunXModel[16]; + const char *szXAnimsRightHanded[37]; + const char *szXAnimsLeftHanded[37]; + uint16_t notetrackSoundMapKeys[16]; + uint16_t notetrackSoundMapValues[16]; + uint16_t notetrackRumbleMapKeys[16]; + uint16_t notetrackRumbleMapValues[16]; + XModel *worldModel[16]; + float parallelBounce[31]; + float perpendicularBounce[31]; + float locationDamageMultipliers[20]; +}; + +enum VehicleAxleType { + VEH_AXLE_FRONT = 0x0, + VEH_AXLE_REAR = 0x1, + VEH_AXLE_ALL = 0x2, + VEH_AXLE_COUNT = 0x3, +}; + +struct VehiclePhysDef { + int physicsEnabled; + const char *physPresetName; + PhysPreset *physPreset; + const char *accelGraphName; + VehicleAxleType steeringAxle; + VehicleAxleType powerAxle; + VehicleAxleType brakingAxle; + float topSpeed; + float reverseSpeed; + float maxVelocity; + float maxPitch; + float maxRoll; + float suspensionTravelFront; + float suspensionTravelRear; + float suspensionStrengthFront; + float suspensionDampingFront; + float suspensionStrengthRear; + float suspensionDampingRear; + float frictionBraking; + float frictionCoasting; + float frictionTopSpeed; + float frictionSide; + float frictionSideRear; + float velocityDependentSlip; + float rollStability; + float rollResistance; + float pitchResistance; + float yawResistance; + float uprightStrengthPitch; + float uprightStrengthRoll; + float targetAirPitch; + float airYawTorque; + float airPitchTorque; + float minimumMomentumForCollision; + float collisionLaunchForceScale; + float wreckedMassScale; + float wreckedBodyFriction; + float minimumJoltForNotify; + float slipThresholdFront; + float slipThresholdRear; + float slipFricScaleFront; + float slipFricScaleRear; + float slipFricRateFront; + float slipFricRateRear; + float slipYawTorque; +}; + +enum VehicleType { + VEH_WHEELS_4 = 0x0, + VEH_TANK = 0x1, + VEH_PLANE = 0x2, + VEH_BOAT = 0x3, + VEH_ARTILLERY = 0x4, + VEH_HELICOPTER = 0x5, + VEH_SNOWMOBILE = 0x6, + VEH_TYPE_COUNT = 0x7, +}; + +struct VehicleDef { + const char *name; + VehicleType type; + const char *useHintString; + int health; + int quadBarrel; + float texScrollScale; + float topSpeed; + float accel; + float rotRate; + float rotAccel; + float maxBodyPitch; + float maxBodyRoll; + float fakeBodyAccelPitch; + float fakeBodyAccelRoll; + float fakeBodyVelPitch; + float fakeBodyVelRoll; + float fakeBodySideVelPitch; + float fakeBodyPitchStrength; + float fakeBodyRollStrength; + float fakeBodyPitchDampening; + float fakeBodyRollDampening; + float fakeBodyBoatRockingAmplitude; + float fakeBodyBoatRockingPeriod; + float fakeBodyBoatRockingRotationPeriod; + float fakeBodyBoatRockingFadeoutSpeed; + float boatBouncingMinForce; + float boatBouncingMaxForce; + float boatBouncingRate; + float boatBouncingFadeinSpeed; + float boatBouncingFadeoutSteeringAngle; + float collisionDamage; + float collisionSpeed; + float killcamOffset[3]; + int playerProtected; + int bulletDamage; + int armorPiercingDamage; + int grenadeDamage; + int projectileDamage; + int projectileSplashDamage; + int heavyExplosiveDamage; + VehiclePhysDef vehPhysDef; + float boostDuration; + float boostRechargeTime; + float boostAcceleration; + float suspensionTravel; + float maxSteeringAngle; + float steeringLerp; + float minSteeringScale; + float minSteeringSpeed; + int camLookEnabled; + float camLerp; + float camPitchInfluence; + float camRollInfluence; + float camFovIncrease; + float camFovOffset; + float camFovSpeed; + const char *turretWeaponName; + WeaponCompleteDef *turretWeapon; + float turretHorizSpanLeft; + float turretHorizSpanRight; + float turretVertSpanUp; + float turretVertSpanDown; + float turretRotRate; + SndAliasCustom turretSpinSnd; + SndAliasCustom turretStopSnd; + int trophyEnabled; + float trophyRadius; + float trophyInactiveRadius; + int trophyAmmoCount; + float trophyReloadTime; + uint16_t trophyTags[4]; + Material *compassFriendlyIcon; + Material *compassEnemyIcon; + int compassIconWidth; + int compassIconHeight; + SndAliasCustom idleLowSnd; + SndAliasCustom idleHighSnd; + SndAliasCustom engineLowSnd; + SndAliasCustom engineHighSnd; + float engineSndSpeed; + SndAliasCustom engineStartUpSnd; + int engineStartUpLength; + SndAliasCustom engineShutdownSnd; + SndAliasCustom engineIdleSnd; + SndAliasCustom engineSustainSnd; + SndAliasCustom engineRampUpSnd; + int engineRampUpLength; + SndAliasCustom engineRampDownSnd; + int engineRampDownLength; + SndAliasCustom suspensionSoftSnd; + float suspensionSoftCompression; + SndAliasCustom suspensionHardSnd; + float suspensionHardCompression; + SndAliasCustom collisionSnd; + float collisionBlendSpeed; + SndAliasCustom speedSnd; + float speedSndBlendSpeed; + const char *surfaceSndPrefix; + SndAliasCustom surfaceSnds[31]; + float surfaceSndBlendSpeed; + float slideVolume; + float slideBlendSpeed; + float inAirPitch; +}; #ifndef __zonecodegenerator } diff --git a/src/Common/Game/IW5/CommonIW5.cpp b/src/Common/Game/IW5/CommonIW5.cpp index de2fc41e6..96bc4da76 100644 --- a/src/Common/Game/IW5/CommonIW5.cpp +++ b/src/Common/Game/IW5/CommonIW5.cpp @@ -4,48 +4,28 @@ using namespace IW5; -int Common::StringTable_HashString(const char* str) -{ - if (!str) - return 0; - - auto result = 0; - auto offset = 0; - while (str[offset]) - { - const auto c = tolower(str[offset++]); - result = c + 31 * result; - } - - return result; +int Common::StringTable_HashString(const char *str) { + if (!str) + return 0; + + auto result = 0; + auto offset = 0; + while (str[offset]) { + const auto c = tolower(str[offset++]); + result = c + 31 * result; + } + + return result; } -PackedTexCoords Common::Vec2PackTexCoords(const vec2_t* in) -{ - return PackedTexCoords{ Pack32::Vec2PackTexCoords(reinterpret_cast(in)) }; -} +PackedTexCoords Common::Vec2PackTexCoords(const vec2_t *in) { return PackedTexCoords{Pack32::Vec2PackTexCoords(reinterpret_cast(in))}; } -PackedUnitVec Common::Vec3PackUnitVec(const vec3_t* in) -{ - return PackedUnitVec{ Pack32::Vec3PackUnitVec(reinterpret_cast(in)) }; -} +PackedUnitVec Common::Vec3PackUnitVec(const vec3_t *in) { return PackedUnitVec{Pack32::Vec3PackUnitVec(reinterpret_cast(in))}; } -GfxColor Common::Vec4PackGfxColor(const vec4_t* in) -{ - return GfxColor{ Pack32::Vec4PackGfxColor(reinterpret_cast(in)) }; -} +GfxColor Common::Vec4PackGfxColor(const vec4_t *in) { return GfxColor{Pack32::Vec4PackGfxColor(reinterpret_cast(in))}; } -void Common::Vec2UnpackTexCoords(const PackedTexCoords& in, vec2_t* out) -{ - Pack32::Vec2UnpackTexCoordsVU(in.packed, reinterpret_cast(out)); -} +void Common::Vec2UnpackTexCoords(const PackedTexCoords &in, vec2_t *out) { Pack32::Vec2UnpackTexCoordsVU(in.packed, reinterpret_cast(out)); } -void Common::Vec3UnpackUnitVec(const PackedUnitVec& in, vec3_t* out) -{ - Pack32::Vec3UnpackUnitVecScaleBased(in.packed, reinterpret_cast(out)); -} +void Common::Vec3UnpackUnitVec(const PackedUnitVec &in, vec3_t *out) { Pack32::Vec3UnpackUnitVecScaleBased(in.packed, reinterpret_cast(out)); } -void Common::Vec4UnpackGfxColor(const GfxColor& in, vec4_t* out) -{ - Pack32::Vec4UnpackGfxColor(in.packed, reinterpret_cast(out)); -} +void Common::Vec4UnpackGfxColor(const GfxColor &in, vec4_t *out) { Pack32::Vec4UnpackGfxColor(in.packed, reinterpret_cast(out)); } diff --git a/src/Common/Game/IW5/CommonIW5.h b/src/Common/Game/IW5/CommonIW5.h index 818c50662..344e50afe 100644 --- a/src/Common/Game/IW5/CommonIW5.h +++ b/src/Common/Game/IW5/CommonIW5.h @@ -2,18 +2,16 @@ #include "IW5.h" -namespace IW5 -{ - class Common - { - public: - static int StringTable_HashString(const char* str); +namespace IW5 { +class Common { +public: + static int StringTable_HashString(const char *str); - static PackedTexCoords Vec2PackTexCoords(const vec2_t* in); - static PackedUnitVec Vec3PackUnitVec(const vec3_t* in); - static GfxColor Vec4PackGfxColor(const vec4_t* in); - static void Vec2UnpackTexCoords(const PackedTexCoords& in, vec2_t* out); - static void Vec3UnpackUnitVec(const PackedUnitVec& in, vec3_t* out); - static void Vec4UnpackGfxColor(const GfxColor& in, vec4_t* out); - }; -} + static PackedTexCoords Vec2PackTexCoords(const vec2_t *in); + static PackedUnitVec Vec3PackUnitVec(const vec3_t *in); + static GfxColor Vec4PackGfxColor(const vec4_t *in); + static void Vec2UnpackTexCoords(const PackedTexCoords &in, vec2_t *out); + static void Vec3UnpackUnitVec(const PackedUnitVec &in, vec3_t *out); + static void Vec4UnpackGfxColor(const GfxColor &in, vec4_t *out); +}; +} // namespace IW5 diff --git a/src/Common/Game/IW5/GameIW5.cpp b/src/Common/Game/IW5/GameIW5.cpp index 5ff784906..cecceef79 100644 --- a/src/Common/Game/IW5/GameIW5.cpp +++ b/src/Common/Game/IW5/GameIW5.cpp @@ -8,36 +8,22 @@ using namespace IW5; GameIW5 g_GameIW5; -std::string GameIW5::GetFullName() -{ - return "Call Of Duty: Modern Warfare 3"; -} +std::string GameIW5::GetFullName() { return "Call Of Duty: Modern Warfare 3"; } -std::string GameIW5::GetShortName() -{ - return "IW5"; -} +std::string GameIW5::GetShortName() { return "IW5"; } -void GameIW5::AddZone(Zone* zone) -{ - m_zones.push_back(zone); -} +void GameIW5::AddZone(Zone *zone) { m_zones.push_back(zone); } -void GameIW5::RemoveZone(Zone* zone) -{ - const auto foundEntry = std::find(m_zones.begin(), m_zones.end(), zone); +void GameIW5::RemoveZone(Zone *zone) { + const auto foundEntry = std::find(m_zones.begin(), m_zones.end(), zone); - if (foundEntry != m_zones.end()) - m_zones.erase(foundEntry); + if (foundEntry != m_zones.end()) + m_zones.erase(foundEntry); } -std::vector GameIW5::GetZones() -{ - return m_zones; -} +std::vector GameIW5::GetZones() { return m_zones; } -std::vector GameIW5::GetLanguagePrefixes() -{ - std::vector prefixes; - return prefixes; +std::vector GameIW5::GetLanguagePrefixes() { + std::vector prefixes; + return prefixes; } diff --git a/src/Common/Game/IW5/GameIW5.h b/src/Common/Game/IW5/GameIW5.h index 57b942fa0..78b97e410 100644 --- a/src/Common/Game/IW5/GameIW5.h +++ b/src/Common/Game/IW5/GameIW5.h @@ -1,17 +1,16 @@ #pragma once #include "Game/IGame.h" -class GameIW5 : public IGame -{ - std::vector m_zones; +class GameIW5 : public IGame { + std::vector m_zones; public: - std::string GetFullName() override; - std::string GetShortName() override; - void AddZone(Zone* zone) override; - void RemoveZone(Zone* zone) override; - std::vector GetZones() override; - std::vector GetLanguagePrefixes() override; + std::string GetFullName() override; + std::string GetShortName() override; + void AddZone(Zone *zone) override; + void RemoveZone(Zone *zone) override; + std::vector GetZones() override; + std::vector GetLanguagePrefixes() override; }; extern GameIW5 g_GameIW5; \ No newline at end of file diff --git a/src/Common/Game/IW5/IW5.h b/src/Common/Game/IW5/IW5.h index 727ea2a04..f869cf466 100644 --- a/src/Common/Game/IW5/IW5.h +++ b/src/Common/Game/IW5/IW5.h @@ -1,82 +1,72 @@ #pragma once -//#include +// #include #include "Image/Texture.h" #include "IW5_Assets.h" -namespace IW5 -{ - struct DB_AuthHash - { - char bytes[32]; - }; +namespace IW5 { +struct DB_AuthHash { + char bytes[32]; +}; - struct DB_AuthSignature - { - char bytes[256]; - }; +struct DB_AuthSignature { + char bytes[256]; +}; - struct DB_AuthSubHeader - { - char fastfileName[32]; - unsigned int reserved; - DB_AuthHash masterBlockHashes[244]; - }; +struct DB_AuthSubHeader { + char fastfileName[32]; + unsigned int reserved; + DB_AuthHash masterBlockHashes[244]; +}; - struct DB_AuthHeader - { - char magic[8]; // + 0 - unsigned int reserved; // + 8 - DB_AuthHash subheaderHash; // + 12 - DB_AuthSignature signedSubheaderHash; // + 44 - DB_AuthSubHeader subheader; // + 300 - }; +struct DB_AuthHeader { + char magic[8]; // + 0 + unsigned int reserved; // + 8 + DB_AuthHash subheaderHash; // + 12 + DB_AuthSignature signedSubheaderHash; // + 44 + DB_AuthSubHeader subheader; // + 300 +}; - struct ScriptStringList - { - int count; - const char** strings; - }; +struct ScriptStringList { + int count; + const char **strings; +}; - struct XAsset - { - XAssetType type; - XAssetHeader header; - }; +struct XAsset { + XAssetType type; + XAssetHeader header; +}; - struct XAssetList - { - ScriptStringList stringList; - int assetCount; - XAsset* assets; - }; +struct XAssetList { + ScriptStringList stringList; + int assetCount; + XAsset *assets; +}; - struct cspField_t - { - const char* szName; - int iOffset; - int iFieldType; - }; +struct cspField_t { + const char *szName; + int iOffset; + int iFieldType; +}; - enum csParseFieldType_t - { - CSPFT_STRING = 0, - CSPFT_STRING_MAX_STRING_CHARS, - CSPFT_STRING_MAX_QPATH, - CSPFT_STRING_MAX_OSPATH, - CSPFT_INT, - CSPFT_QBOOLEAN, - CSPFT_BOOL, - CSPFT_FLOAT, - CSPFT_MPH_TO_INCHES_PER_SEC, - CSPFT_MILLISECONDS, - CSPFT_FX, - CSPFT_XMODEL, - CSPFT_MATERIAL, - CSPFT_SOUND, - CSPFT_TRACER, +enum csParseFieldType_t { + CSPFT_STRING = 0, + CSPFT_STRING_MAX_STRING_CHARS, + CSPFT_STRING_MAX_QPATH, + CSPFT_STRING_MAX_OSPATH, + CSPFT_INT, + CSPFT_QBOOLEAN, + CSPFT_BOOL, + CSPFT_FLOAT, + CSPFT_MPH_TO_INCHES_PER_SEC, + CSPFT_MILLISECONDS, + CSPFT_FX, + CSPFT_XMODEL, + CSPFT_MATERIAL, + CSPFT_SOUND, + CSPFT_TRACER, - CSPFT_NUM_BASE_FIELD_TYPES, - }; -} \ No newline at end of file + CSPFT_NUM_BASE_FIELD_TYPES, +}; +} // namespace IW5 \ No newline at end of file diff --git a/src/Common/Game/IW5/IW5_Assets.h b/src/Common/Game/IW5/IW5_Assets.h index 9b073b0d2..4a2938fcd 100644 --- a/src/Common/Game/IW5/IW5_Assets.h +++ b/src/Common/Game/IW5/IW5_Assets.h @@ -13,4686 +13,4272 @@ #ifndef __zonecodegenerator #ifndef __ida -namespace IW5 -{ +namespace IW5 { #endif #endif - enum XAssetType - { - ASSET_TYPE_PHYSPRESET = 0x0, - ASSET_TYPE_PHYSCOLLMAP = 0x1, - ASSET_TYPE_XANIMPARTS = 0x2, - ASSET_TYPE_XMODEL_SURFS = 0x3, - ASSET_TYPE_XMODEL = 0x4, - ASSET_TYPE_MATERIAL = 0x5, - ASSET_TYPE_PIXELSHADER = 0x6, - ASSET_TYPE_VERTEXSHADER = 0x7, - ASSET_TYPE_VERTEXDECL = 0x8, - ASSET_TYPE_TECHNIQUE_SET = 0x9, - ASSET_TYPE_IMAGE = 0xA, - ASSET_TYPE_SOUND = 0xB, - ASSET_TYPE_SOUND_CURVE = 0xC, - ASSET_TYPE_LOADED_SOUND = 0xD, - ASSET_TYPE_CLIPMAP = 0xE, - ASSET_TYPE_COMWORLD = 0xF, - ASSET_TYPE_GLASSWORLD = 0x10, - ASSET_TYPE_PATHDATA = 0x11, - ASSET_TYPE_VEHICLE_TRACK = 0x12, - ASSET_TYPE_MAP_ENTS = 0x13, - ASSET_TYPE_FXWORLD = 0x14, - ASSET_TYPE_GFXWORLD = 0x15, - ASSET_TYPE_LIGHT_DEF = 0x16, - ASSET_TYPE_UI_MAP = 0x17, - ASSET_TYPE_FONT = 0x18, - ASSET_TYPE_MENULIST = 0x19, - ASSET_TYPE_MENU = 0x1A, - ASSET_TYPE_LOCALIZE_ENTRY = 0x1B, - ASSET_TYPE_ATTACHMENT = 0x1C, - ASSET_TYPE_WEAPON = 0x1D, - ASSET_TYPE_SNDDRIVER_GLOBALS = 0x1E, - ASSET_TYPE_FX = 0x1F, - ASSET_TYPE_IMPACT_FX = 0x20, - ASSET_TYPE_SURFACE_FX = 0x21, - ASSET_TYPE_AITYPE = 0x22, - ASSET_TYPE_MPTYPE = 0x23, - ASSET_TYPE_CHARACTER = 0x24, - ASSET_TYPE_XMODELALIAS = 0x25, - ASSET_TYPE_RAWFILE = 0x26, - ASSET_TYPE_SCRIPTFILE = 0x27, - ASSET_TYPE_STRINGTABLE = 0x28, - ASSET_TYPE_LEADERBOARD = 0x29, - ASSET_TYPE_STRUCTURED_DATA_DEF = 0x2A, - ASSET_TYPE_TRACER = 0x2B, - ASSET_TYPE_VEHICLE = 0x2C, - ASSET_TYPE_ADDON_MAP_ENTS = 0x2D, - ASSET_TYPE_COUNT, - - ASSET_TYPE_STRING = ASSET_TYPE_COUNT, - ASSET_TYPE_ASSETLIST = 0x2F, - - ASSET_TYPE_FULLCOUNT - }; - - enum XFileBlock - { - XFILE_BLOCK_TEMP, - XFILE_BLOCK_PHYSICAL, - XFILE_BLOCK_RUNTIME, - XFILE_BLOCK_VIRTUAL, - XFILE_BLOCK_LARGE, - XFILE_BLOCK_CALLBACK, - XFILE_BLOCK_VERTEX, - XFILE_BLOCK_INDEX, - XFILE_BLOCK_SCRIPT, - - MAX_XFILE_COUNT - }; - - struct PhysPreset; - struct PhysCollmap; - struct XAnimParts; - struct XModelSurfs; - struct XModel; - struct Material; - struct MaterialPixelShader; - struct MaterialVertexShader; - struct MaterialVertexDeclaration; - struct MaterialTechniqueSet; - struct GfxImage; - struct snd_alias_list_t; - struct SndCurve; - struct LoadedSound; - struct clipMap_t; - struct ComWorld; - struct GlassWorld; - struct PathData; - struct VehicleTrack; - struct MapEnts; - struct FxWorld; - struct GfxWorld; - struct GfxLightDef; - struct Font_s; - struct MenuList; - struct menuDef_t; - struct LocalizeEntry; - struct WeaponAttachment; - struct WeaponCompleteDef; - struct FxEffectDef; - struct FxImpactTable; - struct SurfaceFxTable; - struct RawFile; - struct ScriptFile; - struct StringTable; - struct LeaderboardDef; - struct StructuredDataDefSet; - struct TracerDef; - struct VehicleDef; - struct AddonMapEnts; - - typedef unsigned short ScriptString; - - union XAssetHeader - { - PhysPreset* physPreset; - PhysCollmap* physCollmap; - XAnimParts* parts; - XModelSurfs* modelSurfs; - XModel* model; - Material* material; - MaterialPixelShader* pixelShader; - MaterialVertexShader* vertexShader; - MaterialVertexDeclaration* vertexDecl; - MaterialTechniqueSet* techniqueSet; - GfxImage* image; - snd_alias_list_t* sound; - SndCurve* sndCurve; - LoadedSound* loadSnd; - clipMap_t* clipMap; - ComWorld* comWorld; - GlassWorld* glassWorld; - PathData* pathData; - VehicleTrack* vehicleTrack; - MapEnts* mapEnts; - FxWorld* fxWorld; - GfxWorld* gfxWorld; - GfxLightDef* lightDef; - Font_s* font; - MenuList* menuList; - menuDef_t* menu; - LocalizeEntry* localize; - WeaponAttachment* attachment; - WeaponCompleteDef* weapon; - // SndDriverGlobals* sndDriverGlobals; // UNUSED ON PC - FxEffectDef* fx; - FxImpactTable* impactFx; - SurfaceFxTable* surfaceFx; - RawFile* rawfile; - ScriptFile* scriptfile; - StringTable* stringTable; - LeaderboardDef* leaderboardDef; - StructuredDataDefSet* structuredDataDefSet; - TracerDef* tracerDef; - VehicleDef* vehDef; - AddonMapEnts* addonMapEnts; - void* data; - }; - - typedef float vec2_t[2]; - typedef float vec3_t[3]; - typedef float vec4_t[4]; - - typedef tdef_align(16) uint16_t r_index16_t; - typedef tdef_align(16) char raw_byte16; - typedef tdef_align(16) float raw_float16; - typedef tdef_align(128) unsigned int raw_uint128; - typedef unsigned char raw_byte; - typedef unsigned int raw_uint; - typedef unsigned short r_index_t; - - enum PhysPresetScaling - { - PHYSPRESET_SCALING_LINEAR = 0x0, - PHYSPRESET_SCALING_QUADRATIC = 0x1, - PHYSPRESET_SCALING_COUNT = 0x2 - }; - - struct PhysPreset - { - const char* name; - int type; - float mass; - float bounce; - float friction; - float bulletForceScale; - float explosiveForceScale; - const char* sndAliasPrefix; - float piecesSpreadFraction; - float piecesUpwardVelocity; - float minMomentum; - float maxMomentum; - float minPitch; - float maxPitch; - PhysPresetScaling volumeType; - PhysPresetScaling pitchType; - bool tempDefaultToCylinder; - bool perSurfaceSndAlias; - }; - - struct Bounds - { - float midPoint[3]; - float halfSize[3]; - }; - - struct cplane_s - { - float normal[3]; - float dist; - unsigned char type; - unsigned char pad[3]; - }; - - struct cbrushside_t - { - cplane_s* plane; - unsigned short materialNum; - unsigned char firstAdjacentSideOffset; - unsigned char edgeCount; - }; - - typedef unsigned char cbrushedge_t; - - struct cbrushWrapper_t - { - unsigned short numsides; - unsigned short glassPieceIndex; - cbrushside_t* sides; - cbrushedge_t* baseAdjacentSide; - short axialMaterialNum[2][3]; - unsigned char firstAdjacentSideOffsets[2][3]; - unsigned char edgeCount[2][3]; - }; - - struct BrushWrapper - { - Bounds bounds; - cbrushWrapper_t brush; - int totalEdgeCount; - cplane_s* planes; - }; - - struct PhysGeomInfo - { - BrushWrapper* brushWrapper; - int type; - float orientation[3][3]; - Bounds bounds; - }; - - struct PhysMass - { - float centerOfMass[3]; - float momentsOfInertia[3]; - float productsOfInertia[3]; - }; - - struct PhysCollmap - { - const char* name; - unsigned int count; - PhysGeomInfo* geoms; - PhysMass mass; - Bounds bounds; - }; - - union XAnimIndices - { - unsigned char* _1; - unsigned short* _2; - void* data; - }; - - struct XAnimNotifyInfo - { - ScriptString name; - float time; - }; - - typedef unsigned char ByteVec[3]; - typedef tdef_align(4) unsigned short UShortVec[3]; - - union XAnimDynamicFrames - { - ByteVec* _1; - UShortVec* _2; - }; - - union XAnimDynamicIndicesTrans - { - char _1[1]; - uint16_t _2[1]; - }; - - struct type_align(4) XAnimPartTransFrames - { - float mins[3]; - float size[3]; - XAnimDynamicFrames frames; - XAnimDynamicIndicesTrans indices; - }; - - union XAnimPartTransData - { - XAnimPartTransFrames frames; - vec3_t frame0; - }; - - struct XAnimPartTrans - { - unsigned short size; - unsigned char smallTrans; - XAnimPartTransData u; - }; - - union XAnimDynamicIndicesQuat2 - { - char _1[1]; - uint16_t _2[1]; - }; - - typedef tdef_align(4) short XQuat2[2]; - - struct type_align(4) XAnimDeltaPartQuatDataFrames2 - { - XQuat2* frames; - XAnimDynamicIndicesQuat2 indices; - }; - - union XAnimDeltaPartQuatData2 - { - XAnimDeltaPartQuatDataFrames2 frames; - short frame0[2]; - }; - - struct XAnimDeltaPartQuat2 - { - unsigned short size; - XAnimDeltaPartQuatData2 u; - }; - - union XAnimDynamicIndicesQuat - { - char _1[1]; - uint16_t _2[1]; - }; - - typedef tdef_align(4) short XQuat[4]; - - struct XAnimDeltaPartQuatDataFrames - { - XQuat* frames; - XAnimDynamicIndicesQuat indices; - }; - - union XAnimDeltaPartQuatData - { - XAnimDeltaPartQuatDataFrames frames; - short frame0[4]; - }; - - struct XAnimDeltaPartQuat - { - uint16_t size; - XAnimDeltaPartQuatData u; - }; - - struct XAnimDeltaPart - { - XAnimPartTrans* trans; - XAnimDeltaPartQuat2* quat2; - XAnimDeltaPartQuat* quat; - }; - - struct XAnimParts - { - const char* name; - unsigned short dataByteCount; - unsigned short dataShortCount; - unsigned short dataIntCount; - unsigned short randomDataByteCount; - unsigned short randomDataIntCount; - unsigned short numframes; - unsigned char flags; - unsigned char boneCount[10]; - unsigned char notifyCount; - unsigned char assetType; - bool isDefault; - unsigned int randomDataShortCount; - unsigned int indexCount; - float framerate; - float frequency; - ScriptString* names; - unsigned char* dataByte; - short* dataShort; - int* dataInt; - short* randomDataShort; - unsigned char* randomDataByte; - int* randomDataInt; - XAnimIndices indices; - XAnimNotifyInfo* notify; - XAnimDeltaPart* deltaPart; - }; - - struct DObjSkelMat - { - float axis[3][4]; - float origin[4]; - }; - - struct XSurfaceVertexInfo - { - short vertCount[4]; - unsigned short* vertsBlend; - }; - - union PackedUnitVec - { - unsigned int packed; - char array[4]; - }; - - union PackedTexCoords - { - unsigned int packed; - }; - - struct GfxQuantizedNoColorVertex - { - short xyz[3]; - short binormalSign; - PackedUnitVec normal; - PackedUnitVec tangent; - PackedTexCoords texCoord; - }; - - union GfxColor - { - unsigned int packed; - unsigned char array[4]; - }; - - struct GfxQuantizedVertex - { - short xyz[3]; - short binormalSign; - PackedUnitVec normal; - PackedUnitVec tangent; - PackedTexCoords texCoord; - GfxColor color; - }; - - struct type_align(16) GfxPackedVertex - { - float xyz[3]; - float binormalSign; - GfxColor color; - PackedTexCoords texCoord; - PackedUnitVec normal; - PackedUnitVec tangent; - }; - - union GfxVertexUnion0 - { - GfxQuantizedNoColorVertex* quantizedNoColorVerts0; - GfxQuantizedVertex* quantizedVerts0; - GfxPackedVertex* packedVerts0; - void* verts0; - }; - - struct XSurfaceCollisionAabb - { - unsigned short mins[3]; - unsigned short maxs[3]; - }; - - struct type_align(16) XSurfaceCollisionNode - { - XSurfaceCollisionAabb aabb; - unsigned short childBeginIndex; - unsigned short childCount; - }; - - struct XSurfaceCollisionLeaf - { - unsigned short triangleBeginIndex; - }; - - struct XSurfaceCollisionTree - { - float trans[3]; - float scale[3]; - unsigned int nodeCount; - XSurfaceCollisionNode* nodes; - unsigned int leafCount; - XSurfaceCollisionLeaf* leafs; - }; - - struct XRigidVertList - { - unsigned short boneOffset; - unsigned short vertCount; - unsigned short triOffset; - unsigned short triCount; - XSurfaceCollisionTree* collisionTree; - }; - - struct XSurface - { - unsigned char tileMode; - unsigned char flags; - unsigned short vertCount; - unsigned short triCount; - char zoneHandle; - uint16_t baseTriIndex; - uint16_t baseVertIndex; - float quantizeScale; - r_index16_t(*triIndices)[3]; - XSurfaceVertexInfo vertInfo; - GfxVertexUnion0 verts0; - unsigned int vertListCount; - XRigidVertList* vertList; - int partBits[6]; - }; - - struct XModelSurfs - { - const char* name; - XSurface* surfs; - unsigned short numsurfs; - int partBits[6]; - }; - - struct DObjAnimMat - { - float quat[4]; - float trans[3]; - float transWeight; - }; - - struct XModelLodInfo - { - float dist; - unsigned short numsurfs; - unsigned short surfIndex; - XModelSurfs* modelSurfs; - int partBits[6]; - XSurface* surfs; - char lod; - char smcBaseIndexPlusOne; - char smcSubIndexMask; - char smcBucket; - }; - - struct XModelCollTri_s - { - float plane[4]; - float svec[4]; - float tvec[4]; - }; - - struct XModelCollSurf_s - { - XModelCollTri_s* collTris; - int numCollTris; - Bounds bounds; - int boneIdx; - int contents; - int surfFlags; - }; - - struct XBoneInfo - { - Bounds bounds; - float radiusSquared; - }; - - struct XModel - { - const char* name; - unsigned char numBones; - unsigned char numRootBones; - unsigned char numsurfs; - float scale; - unsigned int noScalePartBits[6]; - ScriptString* boneNames; - unsigned char* parentList; - short(*quats)[4]; - float(*trans)[3]; - unsigned char* partClassification; - DObjAnimMat* baseMat; - Material** materialHandles; - XModelLodInfo lodInfo[4]; - char maxLoadedLod; - unsigned char numLods; - unsigned char collLod; - unsigned char flags; - XModelCollSurf_s* collSurfs; - int numCollSurfs; - int contents; - XBoneInfo* boneInfo; - float radius; - Bounds bounds; - unsigned short* invHighMipRadius; - int memUsage; - PhysPreset* physPreset; - PhysCollmap* physCollmap; - float quantization; - }; - - struct gcc_align(8) GfxDrawSurfFields - { - uint64_t unused : 1; - uint64_t primarySortKey : 6; - uint64_t surfType : 4; - uint64_t viewModelRender : 1; - uint64_t sceneLightIndex : 8; - uint64_t useHeroLighting : 1; - uint64_t prepass : 2; - uint64_t materialSortedIndex : 12; - uint64_t customIndex : 5; - uint64_t hasGfxEntIndex : 1; - uint64_t reflectionProbeIndex : 8; - uint64_t objectId : 15; - }; - - union GfxDrawSurf - { - gcc_align(8) GfxDrawSurfFields fields; - gcc_align(8) uint64_t packed; - }; - - struct MaterialInfo - { - const char* name; - unsigned char gameFlags; - unsigned char sortKey; - unsigned char textureAtlasRowCount; - unsigned char textureAtlasColumnCount; - GfxDrawSurf drawSurf; - unsigned int surfaceTypeBits; - }; - - struct WaterWritable - { - float floatTime; - }; - - struct complex_s - { - float real; - float imag; - }; - - struct water_t - { - WaterWritable writable; - complex_s* H0; - float* wTerm; - int M; - int N; - float Lx; - float Lz; - float gravity; - float windvel; - float winddir[2]; - float amplitude; - float codeConstant[4]; - GfxImage* image; - }; - - enum TextureSemantic - { - TS_2D = 0x0, - TS_FUNCTION = 0x1, - TS_COLOR_MAP = 0x2, - TS_DETAIL_MAP = 0x3, - TS_UNUSED_2 = 0x4, - TS_NORMAL_MAP = 0x5, - TS_UNUSED_3 = 0x6, - TS_UNUSED_4 = 0x7, - TS_SPECULAR_MAP = 0x8, - TS_UNUSED_5 = 0x9, - TS_UNUSED_6 = 0xA, - TS_WATER_MAP = 0xB, - TS_DISPLACEMENT_MAP = 0xC - }; - - union MaterialTextureDefInfo - { - GfxImage* image; - water_t* water; - }; - - struct MaterialTextureDef - { - unsigned int nameHash; - char nameStart; - char nameEnd; - unsigned char samplerState; - unsigned char semantic; - MaterialTextureDefInfo u; - }; - - struct type_align(16) MaterialConstantDef - { - unsigned int nameHash; - char name[12]; - float literal[4]; - }; - - struct GfxStateBits - { - unsigned int loadBits[2]; - }; - - struct Material - { - MaterialInfo info; - unsigned char stateBitsEntry[54]; - unsigned char textureCount; - unsigned char constantCount; - unsigned char stateBitsCount; - unsigned char stateFlags; - unsigned char cameraRegion; - MaterialTechniqueSet* techniqueSet; - MaterialTextureDef* textureTable; - MaterialConstantDef* constantTable; - GfxStateBits* stateBitsTable; - const char** subMaterials; - }; - - struct GfxShaderLoadDef - { - unsigned char* cachedPart; - unsigned char* physicalPart; - unsigned short cachedPartSize; - unsigned short physicalPartSize; - }; - - struct GfxPixelShaderLoadDef - { - unsigned int* program; - uint16_t programSize; - uint16_t loadForRenderer; - }; - - struct MaterialPixelShaderProgram - { - void* ps; - GfxPixelShaderLoadDef loadDef; - }; - - struct MaterialPixelShader - { - const char* name; - MaterialPixelShaderProgram prog; - }; - - struct GfxVertexShaderLoadDef - { - unsigned int* program; - uint16_t programSize; - uint16_t loadForRenderer; - }; - - struct MaterialVertexShaderProgram - { - void* vs; - GfxVertexShaderLoadDef loadDef; - }; - - struct MaterialVertexShader - { - const char* name; - MaterialVertexShaderProgram prog; - }; - - struct MaterialStreamRouting - { - char source; - char dest; - }; - - struct MaterialVertexStreamRouting - { - MaterialStreamRouting data[13]; - void* decl[16]; - }; - - struct MaterialVertexDeclaration - { - const char* name; - char streamCount; - bool hasOptionalSource; - MaterialVertexStreamRouting routing; - }; - - enum MaterialShaderArgumentType - { - MTL_ARG_MATERIAL_VERTEX_CONST = 0x0, - MTL_ARG_LITERAL_VERTEX_CONST = 0x1, - MTL_ARG_MATERIAL_VERTEX_SAMPLER = 0x2, - MTL_ARG_MATERIAL_PIXEL_SAMPLER = 0x3, - MTL_ARG_CODE_PRIM_BEGIN = 0x4, - MTL_ARG_CODE_VERTEX_CONST = 0x4, - MTL_ARG_CODE_PIXEL_SAMPLER = 0x5, - MTL_ARG_CODE_PIXEL_CONST = 0x6, - MTL_ARG_CODE_PRIM_END = 0x7, - MTL_ARG_MATERIAL_PIXEL_CONST = 0x7, - MTL_ARG_LITERAL_PIXEL_CONST = 0x8, - - MTL_ARG_COUNT - }; - - struct MaterialArgumentCodeConst - { - unsigned short index; - unsigned char firstRow; - unsigned char rowCount; - }; - - union MaterialArgumentDef - { - const float(*literalConst)[4]; - MaterialArgumentCodeConst codeConst; - unsigned int codeSampler; - unsigned int nameHash; - }; - - struct MaterialShaderArgument - { - unsigned short type; - unsigned short dest; - MaterialArgumentDef u; - }; - - struct MaterialPass - { - MaterialVertexDeclaration* vertexDecl; - MaterialVertexShader* vertexShader; - MaterialPixelShader* pixelShader; - unsigned char perPrimArgCount; - unsigned char perObjArgCount; - unsigned char stableArgCount; - unsigned char customSamplerFlags; - MaterialShaderArgument* args; - }; - - struct MaterialTechnique - { - const char* name; - unsigned short flags; - unsigned short passCount; - MaterialPass passArray[1]; - }; - - struct MaterialTechniqueSet - { - const char* name; - unsigned char worldVertFormat; - unsigned char unused[2]; - MaterialTechniqueSet* remappedTechniqueSet; - MaterialTechnique* techniques[54]; - }; - - struct type_align(4) GfxImageLoadDef - { - char levelCount; - char pad[3]; - int flags; - int format; - int resourceSize; - char data[1]; - }; - - union GfxTexture - { - // IDirect3DBaseTexture9* basemap; - // IDirect3DTexture9* map; - // IDirect3DVolumeTexture9* volmap; - // IDirect3DCubeTexture9* cubemap; +enum XAssetType { + ASSET_TYPE_PHYSPRESET = 0x0, + ASSET_TYPE_PHYSCOLLMAP = 0x1, + ASSET_TYPE_XANIMPARTS = 0x2, + ASSET_TYPE_XMODEL_SURFS = 0x3, + ASSET_TYPE_XMODEL = 0x4, + ASSET_TYPE_MATERIAL = 0x5, + ASSET_TYPE_PIXELSHADER = 0x6, + ASSET_TYPE_VERTEXSHADER = 0x7, + ASSET_TYPE_VERTEXDECL = 0x8, + ASSET_TYPE_TECHNIQUE_SET = 0x9, + ASSET_TYPE_IMAGE = 0xA, + ASSET_TYPE_SOUND = 0xB, + ASSET_TYPE_SOUND_CURVE = 0xC, + ASSET_TYPE_LOADED_SOUND = 0xD, + ASSET_TYPE_CLIPMAP = 0xE, + ASSET_TYPE_COMWORLD = 0xF, + ASSET_TYPE_GLASSWORLD = 0x10, + ASSET_TYPE_PATHDATA = 0x11, + ASSET_TYPE_VEHICLE_TRACK = 0x12, + ASSET_TYPE_MAP_ENTS = 0x13, + ASSET_TYPE_FXWORLD = 0x14, + ASSET_TYPE_GFXWORLD = 0x15, + ASSET_TYPE_LIGHT_DEF = 0x16, + ASSET_TYPE_UI_MAP = 0x17, + ASSET_TYPE_FONT = 0x18, + ASSET_TYPE_MENULIST = 0x19, + ASSET_TYPE_MENU = 0x1A, + ASSET_TYPE_LOCALIZE_ENTRY = 0x1B, + ASSET_TYPE_ATTACHMENT = 0x1C, + ASSET_TYPE_WEAPON = 0x1D, + ASSET_TYPE_SNDDRIVER_GLOBALS = 0x1E, + ASSET_TYPE_FX = 0x1F, + ASSET_TYPE_IMPACT_FX = 0x20, + ASSET_TYPE_SURFACE_FX = 0x21, + ASSET_TYPE_AITYPE = 0x22, + ASSET_TYPE_MPTYPE = 0x23, + ASSET_TYPE_CHARACTER = 0x24, + ASSET_TYPE_XMODELALIAS = 0x25, + ASSET_TYPE_RAWFILE = 0x26, + ASSET_TYPE_SCRIPTFILE = 0x27, + ASSET_TYPE_STRINGTABLE = 0x28, + ASSET_TYPE_LEADERBOARD = 0x29, + ASSET_TYPE_STRUCTURED_DATA_DEF = 0x2A, + ASSET_TYPE_TRACER = 0x2B, + ASSET_TYPE_VEHICLE = 0x2C, + ASSET_TYPE_ADDON_MAP_ENTS = 0x2D, + ASSET_TYPE_COUNT, + + ASSET_TYPE_STRING = ASSET_TYPE_COUNT, + ASSET_TYPE_ASSETLIST = 0x2F, + + ASSET_TYPE_FULLCOUNT +}; + +enum XFileBlock { + XFILE_BLOCK_TEMP, + XFILE_BLOCK_PHYSICAL, + XFILE_BLOCK_RUNTIME, + XFILE_BLOCK_VIRTUAL, + XFILE_BLOCK_LARGE, + XFILE_BLOCK_CALLBACK, + XFILE_BLOCK_VERTEX, + XFILE_BLOCK_INDEX, + XFILE_BLOCK_SCRIPT, + + MAX_XFILE_COUNT +}; + +struct PhysPreset; +struct PhysCollmap; +struct XAnimParts; +struct XModelSurfs; +struct XModel; +struct Material; +struct MaterialPixelShader; +struct MaterialVertexShader; +struct MaterialVertexDeclaration; +struct MaterialTechniqueSet; +struct GfxImage; +struct snd_alias_list_t; +struct SndCurve; +struct LoadedSound; +struct clipMap_t; +struct ComWorld; +struct GlassWorld; +struct PathData; +struct VehicleTrack; +struct MapEnts; +struct FxWorld; +struct GfxWorld; +struct GfxLightDef; +struct Font_s; +struct MenuList; +struct menuDef_t; +struct LocalizeEntry; +struct WeaponAttachment; +struct WeaponCompleteDef; +struct FxEffectDef; +struct FxImpactTable; +struct SurfaceFxTable; +struct RawFile; +struct ScriptFile; +struct StringTable; +struct LeaderboardDef; +struct StructuredDataDefSet; +struct TracerDef; +struct VehicleDef; +struct AddonMapEnts; + +typedef unsigned short ScriptString; + +union XAssetHeader { + PhysPreset *physPreset; + PhysCollmap *physCollmap; + XAnimParts *parts; + XModelSurfs *modelSurfs; + XModel *model; + Material *material; + MaterialPixelShader *pixelShader; + MaterialVertexShader *vertexShader; + MaterialVertexDeclaration *vertexDecl; + MaterialTechniqueSet *techniqueSet; + GfxImage *image; + snd_alias_list_t *sound; + SndCurve *sndCurve; + LoadedSound *loadSnd; + clipMap_t *clipMap; + ComWorld *comWorld; + GlassWorld *glassWorld; + PathData *pathData; + VehicleTrack *vehicleTrack; + MapEnts *mapEnts; + FxWorld *fxWorld; + GfxWorld *gfxWorld; + GfxLightDef *lightDef; + Font_s *font; + MenuList *menuList; + menuDef_t *menu; + LocalizeEntry *localize; + WeaponAttachment *attachment; + WeaponCompleteDef *weapon; + // SndDriverGlobals* sndDriverGlobals; // UNUSED ON PC + FxEffectDef *fx; + FxImpactTable *impactFx; + SurfaceFxTable *surfaceFx; + RawFile *rawfile; + ScriptFile *scriptfile; + StringTable *stringTable; + LeaderboardDef *leaderboardDef; + StructuredDataDefSet *structuredDataDefSet; + TracerDef *tracerDef; + VehicleDef *vehDef; + AddonMapEnts *addonMapEnts; + void *data; +}; + +typedef float vec2_t[2]; +typedef float vec3_t[3]; +typedef float vec4_t[4]; + +typedef tdef_align(16) uint16_t r_index16_t; +typedef tdef_align(16) char raw_byte16; +typedef tdef_align(16) float raw_float16; +typedef tdef_align(128) unsigned int raw_uint128; +typedef unsigned char raw_byte; +typedef unsigned int raw_uint; +typedef unsigned short r_index_t; + +enum PhysPresetScaling { PHYSPRESET_SCALING_LINEAR = 0x0, PHYSPRESET_SCALING_QUADRATIC = 0x1, PHYSPRESET_SCALING_COUNT = 0x2 }; + +struct PhysPreset { + const char *name; + int type; + float mass; + float bounce; + float friction; + float bulletForceScale; + float explosiveForceScale; + const char *sndAliasPrefix; + float piecesSpreadFraction; + float piecesUpwardVelocity; + float minMomentum; + float maxMomentum; + float minPitch; + float maxPitch; + PhysPresetScaling volumeType; + PhysPresetScaling pitchType; + bool tempDefaultToCylinder; + bool perSurfaceSndAlias; +}; + +struct Bounds { + float midPoint[3]; + float halfSize[3]; +}; + +struct cplane_s { + float normal[3]; + float dist; + unsigned char type; + unsigned char pad[3]; +}; + +struct cbrushside_t { + cplane_s *plane; + unsigned short materialNum; + unsigned char firstAdjacentSideOffset; + unsigned char edgeCount; +}; + +typedef unsigned char cbrushedge_t; + +struct cbrushWrapper_t { + unsigned short numsides; + unsigned short glassPieceIndex; + cbrushside_t *sides; + cbrushedge_t *baseAdjacentSide; + short axialMaterialNum[2][3]; + unsigned char firstAdjacentSideOffsets[2][3]; + unsigned char edgeCount[2][3]; +}; + +struct BrushWrapper { + Bounds bounds; + cbrushWrapper_t brush; + int totalEdgeCount; + cplane_s *planes; +}; + +struct PhysGeomInfo { + BrushWrapper *brushWrapper; + int type; + float orientation[3][3]; + Bounds bounds; +}; + +struct PhysMass { + float centerOfMass[3]; + float momentsOfInertia[3]; + float productsOfInertia[3]; +}; + +struct PhysCollmap { + const char *name; + unsigned int count; + PhysGeomInfo *geoms; + PhysMass mass; + Bounds bounds; +}; + +union XAnimIndices { + unsigned char *_1; + unsigned short *_2; + void *data; +}; + +struct XAnimNotifyInfo { + ScriptString name; + float time; +}; + +typedef unsigned char ByteVec[3]; +typedef tdef_align(4) unsigned short UShortVec[3]; + +union XAnimDynamicFrames { + ByteVec *_1; + UShortVec *_2; +}; + +union XAnimDynamicIndicesTrans { + char _1[1]; + uint16_t _2[1]; +}; + +struct type_align(4) XAnimPartTransFrames { + float mins[3]; + float size[3]; + XAnimDynamicFrames frames; + XAnimDynamicIndicesTrans indices; +}; + +union XAnimPartTransData { + XAnimPartTransFrames frames; + vec3_t frame0; +}; + +struct XAnimPartTrans { + unsigned short size; + unsigned char smallTrans; + XAnimPartTransData u; +}; + +union XAnimDynamicIndicesQuat2 { + char _1[1]; + uint16_t _2[1]; +}; + +typedef tdef_align(4) short XQuat2[2]; + +struct type_align(4) XAnimDeltaPartQuatDataFrames2 { + XQuat2 *frames; + XAnimDynamicIndicesQuat2 indices; +}; + +union XAnimDeltaPartQuatData2 { + XAnimDeltaPartQuatDataFrames2 frames; + short frame0[2]; +}; + +struct XAnimDeltaPartQuat2 { + unsigned short size; + XAnimDeltaPartQuatData2 u; +}; + +union XAnimDynamicIndicesQuat { + char _1[1]; + uint16_t _2[1]; +}; + +typedef tdef_align(4) short XQuat[4]; + +struct XAnimDeltaPartQuatDataFrames { + XQuat *frames; + XAnimDynamicIndicesQuat indices; +}; + +union XAnimDeltaPartQuatData { + XAnimDeltaPartQuatDataFrames frames; + short frame0[4]; +}; + +struct XAnimDeltaPartQuat { + uint16_t size; + XAnimDeltaPartQuatData u; +}; + +struct XAnimDeltaPart { + XAnimPartTrans *trans; + XAnimDeltaPartQuat2 *quat2; + XAnimDeltaPartQuat *quat; +}; + +struct XAnimParts { + const char *name; + unsigned short dataByteCount; + unsigned short dataShortCount; + unsigned short dataIntCount; + unsigned short randomDataByteCount; + unsigned short randomDataIntCount; + unsigned short numframes; + unsigned char flags; + unsigned char boneCount[10]; + unsigned char notifyCount; + unsigned char assetType; + bool isDefault; + unsigned int randomDataShortCount; + unsigned int indexCount; + float framerate; + float frequency; + ScriptString *names; + unsigned char *dataByte; + short *dataShort; + int *dataInt; + short *randomDataShort; + unsigned char *randomDataByte; + int *randomDataInt; + XAnimIndices indices; + XAnimNotifyInfo *notify; + XAnimDeltaPart *deltaPart; +}; + +struct DObjSkelMat { + float axis[3][4]; + float origin[4]; +}; + +struct XSurfaceVertexInfo { + short vertCount[4]; + unsigned short *vertsBlend; +}; + +union PackedUnitVec { + unsigned int packed; + char array[4]; +}; + +union PackedTexCoords { + unsigned int packed; +}; + +struct GfxQuantizedNoColorVertex { + short xyz[3]; + short binormalSign; + PackedUnitVec normal; + PackedUnitVec tangent; + PackedTexCoords texCoord; +}; + +union GfxColor { + unsigned int packed; + unsigned char array[4]; +}; + +struct GfxQuantizedVertex { + short xyz[3]; + short binormalSign; + PackedUnitVec normal; + PackedUnitVec tangent; + PackedTexCoords texCoord; + GfxColor color; +}; + +struct type_align(16) GfxPackedVertex { + float xyz[3]; + float binormalSign; + GfxColor color; + PackedTexCoords texCoord; + PackedUnitVec normal; + PackedUnitVec tangent; +}; + +union GfxVertexUnion0 { + GfxQuantizedNoColorVertex *quantizedNoColorVerts0; + GfxQuantizedVertex *quantizedVerts0; + GfxPackedVertex *packedVerts0; + void *verts0; +}; + +struct XSurfaceCollisionAabb { + unsigned short mins[3]; + unsigned short maxs[3]; +}; + +struct type_align(16) XSurfaceCollisionNode { + XSurfaceCollisionAabb aabb; + unsigned short childBeginIndex; + unsigned short childCount; +}; + +struct XSurfaceCollisionLeaf { + unsigned short triangleBeginIndex; +}; + +struct XSurfaceCollisionTree { + float trans[3]; + float scale[3]; + unsigned int nodeCount; + XSurfaceCollisionNode *nodes; + unsigned int leafCount; + XSurfaceCollisionLeaf *leafs; +}; + +struct XRigidVertList { + unsigned short boneOffset; + unsigned short vertCount; + unsigned short triOffset; + unsigned short triCount; + XSurfaceCollisionTree *collisionTree; +}; + +struct XSurface { + unsigned char tileMode; + unsigned char flags; + unsigned short vertCount; + unsigned short triCount; + char zoneHandle; + uint16_t baseTriIndex; + uint16_t baseVertIndex; + float quantizeScale; + r_index16_t (*triIndices)[3]; + XSurfaceVertexInfo vertInfo; + GfxVertexUnion0 verts0; + unsigned int vertListCount; + XRigidVertList *vertList; + int partBits[6]; +}; + +struct XModelSurfs { + const char *name; + XSurface *surfs; + unsigned short numsurfs; + int partBits[6]; +}; + +struct DObjAnimMat { + float quat[4]; + float trans[3]; + float transWeight; +}; + +struct XModelLodInfo { + float dist; + unsigned short numsurfs; + unsigned short surfIndex; + XModelSurfs *modelSurfs; + int partBits[6]; + XSurface *surfs; + char lod; + char smcBaseIndexPlusOne; + char smcSubIndexMask; + char smcBucket; +}; + +struct XModelCollTri_s { + float plane[4]; + float svec[4]; + float tvec[4]; +}; + +struct XModelCollSurf_s { + XModelCollTri_s *collTris; + int numCollTris; + Bounds bounds; + int boneIdx; + int contents; + int surfFlags; +}; + +struct XBoneInfo { + Bounds bounds; + float radiusSquared; +}; + +struct XModel { + const char *name; + unsigned char numBones; + unsigned char numRootBones; + unsigned char numsurfs; + float scale; + unsigned int noScalePartBits[6]; + ScriptString *boneNames; + unsigned char *parentList; + short (*quats)[4]; + float (*trans)[3]; + unsigned char *partClassification; + DObjAnimMat *baseMat; + Material **materialHandles; + XModelLodInfo lodInfo[4]; + char maxLoadedLod; + unsigned char numLods; + unsigned char collLod; + unsigned char flags; + XModelCollSurf_s *collSurfs; + int numCollSurfs; + int contents; + XBoneInfo *boneInfo; + float radius; + Bounds bounds; + unsigned short *invHighMipRadius; + int memUsage; + PhysPreset *physPreset; + PhysCollmap *physCollmap; + float quantization; +}; + +struct gcc_align(8) GfxDrawSurfFields { + uint64_t unused : 1; + uint64_t primarySortKey : 6; + uint64_t surfType : 4; + uint64_t viewModelRender : 1; + uint64_t sceneLightIndex : 8; + uint64_t useHeroLighting : 1; + uint64_t prepass : 2; + uint64_t materialSortedIndex : 12; + uint64_t customIndex : 5; + uint64_t hasGfxEntIndex : 1; + uint64_t reflectionProbeIndex : 8; + uint64_t objectId : 15; +}; + +union GfxDrawSurf { + gcc_align(8) GfxDrawSurfFields fields; + gcc_align(8) uint64_t packed; +}; + +struct MaterialInfo { + const char *name; + unsigned char gameFlags; + unsigned char sortKey; + unsigned char textureAtlasRowCount; + unsigned char textureAtlasColumnCount; + GfxDrawSurf drawSurf; + unsigned int surfaceTypeBits; +}; + +struct WaterWritable { + float floatTime; +}; + +struct complex_s { + float real; + float imag; +}; + +struct water_t { + WaterWritable writable; + complex_s *H0; + float *wTerm; + int M; + int N; + float Lx; + float Lz; + float gravity; + float windvel; + float winddir[2]; + float amplitude; + float codeConstant[4]; + GfxImage *image; +}; + +enum TextureSemantic { + TS_2D = 0x0, + TS_FUNCTION = 0x1, + TS_COLOR_MAP = 0x2, + TS_DETAIL_MAP = 0x3, + TS_UNUSED_2 = 0x4, + TS_NORMAL_MAP = 0x5, + TS_UNUSED_3 = 0x6, + TS_UNUSED_4 = 0x7, + TS_SPECULAR_MAP = 0x8, + TS_UNUSED_5 = 0x9, + TS_UNUSED_6 = 0xA, + TS_WATER_MAP = 0xB, + TS_DISPLACEMENT_MAP = 0xC +}; + +union MaterialTextureDefInfo { + GfxImage *image; + water_t *water; +}; + +struct MaterialTextureDef { + unsigned int nameHash; + char nameStart; + char nameEnd; + unsigned char samplerState; + unsigned char semantic; + MaterialTextureDefInfo u; +}; + +struct type_align(16) MaterialConstantDef { + unsigned int nameHash; + char name[12]; + float literal[4]; +}; + +struct GfxStateBits { + unsigned int loadBits[2]; +}; + +struct Material { + MaterialInfo info; + unsigned char stateBitsEntry[54]; + unsigned char textureCount; + unsigned char constantCount; + unsigned char stateBitsCount; + unsigned char stateFlags; + unsigned char cameraRegion; + MaterialTechniqueSet *techniqueSet; + MaterialTextureDef *textureTable; + MaterialConstantDef *constantTable; + GfxStateBits *stateBitsTable; + const char **subMaterials; +}; + +struct GfxShaderLoadDef { + unsigned char *cachedPart; + unsigned char *physicalPart; + unsigned short cachedPartSize; + unsigned short physicalPartSize; +}; + +struct GfxPixelShaderLoadDef { + unsigned int *program; + uint16_t programSize; + uint16_t loadForRenderer; +}; + +struct MaterialPixelShaderProgram { + void *ps; + GfxPixelShaderLoadDef loadDef; +}; + +struct MaterialPixelShader { + const char *name; + MaterialPixelShaderProgram prog; +}; + +struct GfxVertexShaderLoadDef { + unsigned int *program; + uint16_t programSize; + uint16_t loadForRenderer; +}; + +struct MaterialVertexShaderProgram { + void *vs; + GfxVertexShaderLoadDef loadDef; +}; + +struct MaterialVertexShader { + const char *name; + MaterialVertexShaderProgram prog; +}; + +struct MaterialStreamRouting { + char source; + char dest; +}; + +struct MaterialVertexStreamRouting { + MaterialStreamRouting data[13]; + void *decl[16]; +}; + +struct MaterialVertexDeclaration { + const char *name; + char streamCount; + bool hasOptionalSource; + MaterialVertexStreamRouting routing; +}; + +enum MaterialShaderArgumentType { + MTL_ARG_MATERIAL_VERTEX_CONST = 0x0, + MTL_ARG_LITERAL_VERTEX_CONST = 0x1, + MTL_ARG_MATERIAL_VERTEX_SAMPLER = 0x2, + MTL_ARG_MATERIAL_PIXEL_SAMPLER = 0x3, + MTL_ARG_CODE_PRIM_BEGIN = 0x4, + MTL_ARG_CODE_VERTEX_CONST = 0x4, + MTL_ARG_CODE_PIXEL_SAMPLER = 0x5, + MTL_ARG_CODE_PIXEL_CONST = 0x6, + MTL_ARG_CODE_PRIM_END = 0x7, + MTL_ARG_MATERIAL_PIXEL_CONST = 0x7, + MTL_ARG_LITERAL_PIXEL_CONST = 0x8, + + MTL_ARG_COUNT +}; + +struct MaterialArgumentCodeConst { + unsigned short index; + unsigned char firstRow; + unsigned char rowCount; +}; + +union MaterialArgumentDef { + const float (*literalConst)[4]; + MaterialArgumentCodeConst codeConst; + unsigned int codeSampler; + unsigned int nameHash; +}; + +struct MaterialShaderArgument { + unsigned short type; + unsigned short dest; + MaterialArgumentDef u; +}; + +struct MaterialPass { + MaterialVertexDeclaration *vertexDecl; + MaterialVertexShader *vertexShader; + MaterialPixelShader *pixelShader; + unsigned char perPrimArgCount; + unsigned char perObjArgCount; + unsigned char stableArgCount; + unsigned char customSamplerFlags; + MaterialShaderArgument *args; +}; + +struct MaterialTechnique { + const char *name; + unsigned short flags; + unsigned short passCount; + MaterialPass passArray[1]; +}; + +struct MaterialTechniqueSet { + const char *name; + unsigned char worldVertFormat; + unsigned char unused[2]; + MaterialTechniqueSet *remappedTechniqueSet; + MaterialTechnique *techniques[54]; +}; + +struct type_align(4) GfxImageLoadDef { + char levelCount; + char pad[3]; + int flags; + int format; + int resourceSize; + char data[1]; +}; + +union GfxTexture { + // IDirect3DBaseTexture9* basemap; + // IDirect3DTexture9* map; + // IDirect3DVolumeTexture9* volmap; + // IDirect3DCubeTexture9* cubemap; #ifndef __ida - Texture* texture; + Texture *texture; #endif - GfxImageLoadDef* loadDef; - }; - - struct Picmip - { - char platform[2]; - }; - - struct CardMemory - { - int platform[2]; - }; - - struct GfxImage - { - GfxTexture texture; - char mapType; - char semantic; - char category; - unsigned char flags; - Picmip picmip; - bool noPicmip; - char track; - CardMemory cardMemory; - unsigned short width; - unsigned short height; - unsigned short depth; - unsigned char levelCount; - const char* name; - }; - - enum snd_alias_type_t - { - SAT_UNKNOWN = 0x0, - SAT_LOADED = 0x1, - SAT_STREAMED = 0x2, - SAT_VOICED = 0x3, - SAT_COUNT = 0x4 - }; - - struct StreamedSound - { - const char* dir; - const char* name; - }; - - struct AILSOUNDINFO - { - int format; - const void* data_ptr; - unsigned int data_len; - unsigned int rate; - int bits; - int channels; - unsigned int samples; - unsigned int block_size; - const void* initial_ptr; - }; - - struct MssSound - { - AILSOUNDINFO info; - char* data; - }; - - struct LoadedSound - { - const char* name; - MssSound sound; - }; - - union SoundFileRef - { - LoadedSound* loadSnd; - StreamedSound streamSnd; - }; - - struct SoundFile - { - unsigned char type; - unsigned char exists; - SoundFileRef u; - }; - - struct MSSSpeakerLevels - { - int speaker; - int numLevels; - float levels[2]; - }; - - struct MSSChannelMap - { - int speakerCount; - MSSSpeakerLevels speakers[6]; - }; - - struct SpeakerMap - { - bool isDefault; - const char* name; - MSSChannelMap channelMaps[2][2]; - }; - - struct SndCurve - { - const char* filename; - unsigned short knotCount; - float knots[16][2]; - }; - - struct snd_alias_t - { - const char* aliasName; - const char* subtitle; - const char* secondaryAliasName; - const char* chainAliasName; - const char* mixerGroup; - SoundFile* soundFile; - int sequence; - float volMin; - float volMax; - int volModIndex; - float pitchMin; - float pitchMax; - float distMin; - float distMax; - float velocityMin; - int flags; - unsigned char masterPriority; - float masterPercentage; - float slavePercentage; - float probability; - float lfePercentage; - float centerPercentage; - int startDelay; - SndCurve* volumeFalloffCurve; - float envelopMin; - float envelopMax; - float envelopPercentage; - SpeakerMap* speakerMap; - }; - - struct snd_alias_list_t - { - const char* aliasName; - snd_alias_t* head; - int count; - }; - - typedef unsigned short LeafBrush; - - struct ClipMaterial - { - const char* name; - int surfaceFlags; - int contents; - }; - - struct cLeafBrushNodeLeaf_t - { - LeafBrush* brushes; - }; - - struct cLeafBrushNodeChildren_t - { - float dist; - float range; - unsigned short childOffset[2]; - }; - - union cLeafBrushNodeData_t - { - cLeafBrushNodeLeaf_t leaf; - cLeafBrushNodeChildren_t children; - }; - - struct cLeafBrushNode_s - { - unsigned char axis; - short leafBrushCount; - int contents; - cLeafBrushNodeData_t data; - }; - - struct cbrush_t - { - unsigned short numsides; - unsigned short glassPieceIndex; - cbrushside_t* sides; - cbrushedge_t* baseAdjacentSide; - short axialMaterialNum[2][3]; - unsigned char firstAdjacentSideOffsets[2][3]; - unsigned char edgeCount[2][3]; - }; - - typedef tdef_align(128) cbrush_t cbrush_array_t; - typedef tdef_align(128) Bounds BoundsArray; - - struct ClipInfo - { - int planeCount; - cplane_s* planes; - unsigned int numMaterials; - ClipMaterial* materials; - unsigned int numBrushSides; - cbrushside_t* brushsides; - unsigned int numBrushEdges; - cbrushedge_t* brushEdges; - unsigned int leafbrushNodesCount; - cLeafBrushNode_s* leafbrushNodes; - unsigned int numLeafBrushes; - LeafBrush* leafbrushes; - unsigned short numBrushes; - cbrush_array_t* brushes; - BoundsArray* brushBounds; - int* brushContents; - }; - - struct cStaticModel_s - { - XModel* xmodel; - float origin[3]; - float invScaledAxis[3][3]; - Bounds absBounds; - }; - - struct cNode_t - { - cplane_s* plane; - short children[2]; - }; - - struct cLeaf_t - { - unsigned short firstCollAabbIndex; - unsigned short collAabbCount; - int brushContents; - int terrainContents; - Bounds bounds; - int leafBrushNode; - }; - - struct CollisionBorder - { - float distEq[3]; - float zBase; - float zSlope; - float start; - float length; - }; - - struct CollisionPartition - { - unsigned char triCount; - unsigned char borderCount; - unsigned char firstVertSegment; - int firstTri; - CollisionBorder* borders; - }; - - union CollisionAabbTreeIndex - { - int firstChildIndex; - int partitionIndex; - }; - - struct type_align(16) CollisionAabbTree - { - float midPoint[3]; - unsigned short materialIndex; - unsigned short childCount; - float halfSize[3]; - CollisionAabbTreeIndex u; - }; - - struct cmodel_t - { - Bounds bounds; - float radius; - ClipInfo* info; - cLeaf_t leaf; - }; - - struct Stage - { - const char* name; - float origin[3]; - unsigned short triggerIndex; - unsigned char sunPrimaryLightIndex; - }; - - struct TriggerModel - { - int contents; - unsigned short hullCount; - unsigned short firstHull; - }; - - struct TriggerHull - { - Bounds bounds; - int contents; - unsigned short slabCount; - unsigned short firstSlab; - }; - - struct TriggerSlab - { - float dir[3]; - float midPoint; - float halfSize; - }; - - struct MapTriggers - { - unsigned int count; - TriggerModel* models; - unsigned int hullCount; - TriggerHull* hulls; - unsigned int slabCount; - TriggerSlab* slabs; - }; - - struct SModelAabbNode - { - Bounds bounds; - unsigned short firstChild; - unsigned short childCount; - }; - - enum DynEntityType - { - DYNENT_TYPE_INVALID = 0x0, - DYNENT_TYPE_CLUTTER = 0x1, - DYNENT_TYPE_DESTRUCT = 0x2, - DYNENT_TYPE_HINGE = 0x3, - DYNENT_TYPE_COUNT = 0x4 - }; - - struct GfxPlacement - { - float quat[4]; - float origin[3]; - }; - - struct DynEntityHingeDef - { - float axisOrigin[3]; - float axisDir[3]; - bool isLimited; - float angleMin; - float angleMax; - float momentOfInertia; - float friction; - }; - - struct DynEntityDef - { - DynEntityType type; - GfxPlacement pose; - XModel* xModel; - unsigned short brushModel; - unsigned short physicsBrushModel; - FxEffectDef* destroyFx; - PhysPreset* physPreset; - int health; - DynEntityHingeDef* hinge; - PhysMass mass; - int contents; - }; - - struct DynEntityPose - { - GfxPlacement pose; - float radius; - }; - - struct Hinge - { - float angle; - float quat[4]; - float angularVel; - float torqueAccum; - bool active; - float autoDisableTimeLeft; - DynEntityHingeDef* def; - PhysPreset* physPreset; - float centerOfMassRelToAxisOriginAtAngleZero[3]; - }; - - struct DynEntityClient - { - int physObjId; - unsigned short flags; - unsigned short lightingHandle; - int health; - Hinge* hinge; - }; - - struct DynEntityColl - { - unsigned short sector; - unsigned short nextEntInSector; - float linkMins[2]; - float linkMaxs[2]; - }; - - struct clipMap_t - { - const char* name; - int isInUse; - ClipInfo info; - ClipInfo* pInfo; - unsigned int numStaticModels; - cStaticModel_s* staticModelList; - unsigned int numNodes; - cNode_t* nodes; - unsigned int numLeafs; - cLeaf_t* leafs; - unsigned int vertCount; - vec3_t* verts; - int triCount; - unsigned short* triIndices; - unsigned char* triEdgeIsWalkable; - int borderCount; - CollisionBorder* borders; - int partitionCount; - CollisionPartition* partitions; - int aabbTreeCount; - CollisionAabbTree* aabbTrees; - unsigned int numSubModels; - cmodel_t* cmodels; - MapEnts* mapEnts; - Stage* stages; - unsigned char stageCount; - MapTriggers stageTrigger; - unsigned short smodelNodeCount; - SModelAabbNode* smodelNodes; - unsigned short dynEntCount[2]; - DynEntityDef* dynEntDefList[2]; - DynEntityPose* dynEntPoseList[2]; - DynEntityClient* dynEntClientList[2]; - DynEntityColl* dynEntCollList[2]; - unsigned int checksum; - unsigned char padding[20]; - }; - - struct ComPrimaryLight - { - unsigned char type; - unsigned char canUseShadowMap; - unsigned char exponent; - unsigned char unused; - float color[3]; - float dir[3]; - float up[3]; - float origin[3]; - float radius; - float cosHalfFovOuter; - float cosHalfFovInner; - float cosHalfFovExpanded; - float rotationLimit; - float translationLimit; - const char* defName; - }; - - struct ComWorld - { - const char* name; - int isInUse; - unsigned int primaryLightCount; - ComPrimaryLight* primaryLights; - }; - - struct G_GlassName - { - char* nameStr; - unsigned short name; - unsigned short pieceCount; - unsigned short* pieceIndices; - }; - - struct G_GlassPiece - { - unsigned short damageTaken; - unsigned short collapseTime; - int lastStateChangeTime; - unsigned char impactDir; - unsigned char impactPos[2]; - }; - - struct G_GlassData - { - G_GlassPiece* glassPieces; - unsigned int pieceCount; - unsigned short damageToWeaken; - unsigned short damageToDestroy; - unsigned int glassNameCount; - G_GlassName* glassNames; - unsigned char pad[108]; - }; - - struct GlassWorld - { - const char* name; - G_GlassData* g_glassData; - }; - - struct pathlink_s - { - float fDist; - unsigned short nodeNum; - unsigned char disconnectCount; - unsigned char negotiationLink; - unsigned char flags; - unsigned char ubBadPlaceCount[3]; - }; - - enum nodeType - { - NODE_ERROR = 0x0, - NODE_PATHNODE = 0x1, - NODE_COVER_STAND = 0x2, - NODE_COVER_CROUCH = 0x3, - NODE_COVER_CROUCH_WINDOW = 0x4, - NODE_COVER_PRONE = 0x5, - NODE_COVER_RIGHT = 0x6, - NODE_COVER_LEFT = 0x7, - NODE_AMBUSH = 0x8, - NODE_EXPOSED = 0x9, - NODE_CONCEALMENT_STAND = 0xA, - NODE_CONCEALMENT_CROUCH = 0xB, - NODE_CONCEALMENT_PRONE = 0xC, - NODE_DOOR = 0xD, - NODE_DOOR_INTERIOR = 0xE, - NODE_SCRIPTED = 0xF, - NODE_NEGOTIATION_BEGIN = 0x10, - NODE_NEGOTIATION_END = 0x11, - NODE_TURRET = 0x12, - NODE_GUARD = 0x13, - NODE_NUMTYPES = 0x14, - NODE_DONTLINK = 0x14 - }; - - enum PathNodeErrorCode - { - PNERR_NONE = 0x0, - PNERR_INSOLID = 0x1, - PNERR_FLOATING = 0x2, - PNERR_NOLINK = 0x3, - PNERR_DUPLICATE = 0x4, - PNERR_NOSTANCE = 0x5, - PNERR_INVALIDDOOR = 0x6, - PNERR_NOANGLES = 0x7, - PNERR_BADPLACEMENT = 0x8, - NUM_PATH_NODE_ERRORS = 0x9 - }; - - struct pathnode_constant_t - { - nodeType type; - unsigned short spawnflags; - ScriptString targetname; - ScriptString script_linkName; - ScriptString script_noteworthy; - ScriptString target; - ScriptString animscript; - int animscriptfunc; - float vOrigin[3]; - float fAngle; - float forward[2]; - float minUseDistSq; - PathNodeErrorCode error; - short wOverlapNode[2]; - unsigned short totalLinkCount; - pathlink_s* Links; - }; - - struct pathnode_dynamic_t - { - void* pOwner; - int iFreeTime; - int iValidTime[3]; - int dangerousNodeTime[3]; - int inPlayerLOSTime; - short wLinkCount; - short wOverlapCount; - short turretEntNumber; - unsigned char userCount; - bool hasBadPlaceLink; - }; - - struct pathnode_t; - - struct pathnode_transient_t - { - int iSearchFrame; - pathnode_t* pNextOpen; - pathnode_t* pPrevOpen; - pathnode_t* pParent; - float fCost; - float fHeuristic; - union - { - float nodeCost; - int linkIndex; - }; - }; - - struct pathnode_t - { - pathnode_constant_t constant; - pathnode_dynamic_t dynamic; - pathnode_transient_t transient; - }; - - struct type_align(16) pathbasenode_t - { - float vOrigin[3]; - unsigned int type; - }; - - struct pathnode_tree_nodes_t - { - int nodeCount; - unsigned short* nodes; - }; - - struct pathnode_tree_t; - - union pathnode_tree_info_t - { - pathnode_tree_t* child[2]; - pathnode_tree_nodes_t s; - }; - - struct pathnode_tree_t - { - int axis; - float dist; - pathnode_tree_info_t u; - }; - - struct PathData - { - const char* name; - unsigned int nodeCount; - pathnode_t* nodes; - pathbasenode_t* basenodes; - unsigned int chainNodeCount; - unsigned short* chainNodeForNode; - unsigned short* nodeForChainNode; - int visBytes; - unsigned char* pathVis; - int nodeTreeCount; - pathnode_tree_t* nodeTree; - }; - - struct VehicleTrackObstacle - { - float origin[2]; - float radius; - }; - - struct VehicleTrackSector - { - float startEdgeDir[2]; - float startEdgeDist; - float leftEdgeDir[2]; - float leftEdgeDist; - float rightEdgeDir[2]; - float rightEdgeDist; - float sectorLength; - float sectorWidth; - float totalPriorLength; - float totalFollowingLength; - VehicleTrackObstacle* obstacles; - unsigned int obstacleCount; - }; - - struct VehicleTrackSegment - { - const char* targetName; - VehicleTrackSector* sectors; - unsigned int sectorCount; - VehicleTrackSegment** nextBranches; - unsigned int nextBranchesCount; - VehicleTrackSegment** prevBranches; - unsigned int prevBranchesCount; - float endEdgeDir[2]; - float endEdgeDist; - float totalLength; - }; - - struct VehicleTrack - { - const char* name; - VehicleTrackSegment* segments; - unsigned int segmentCount; - }; - - struct ClientTriggerAabbNode - { - Bounds bounds; - unsigned short firstChild; - unsigned short childCount; - }; - - struct ClientTriggers - { - MapTriggers trigger; - unsigned short numClientTriggerNodes; - ClientTriggerAabbNode* clientTriggerAabbTree; - unsigned int triggerStringLength; - char* triggerString; - unsigned short* triggerStringOffsets; - unsigned char* triggerType; - vec3_t* origins; - float* scriptDelay; - short* audioTriggers; - }; - - struct MapEnts - { - const char* name; - char* entityString; - int numEntityChars; - MapTriggers trigger; - ClientTriggers clientTrigger; - }; - - struct FxGlassDef - { - float halfThickness; - float texVecs[2][2]; - GfxColor color; - Material* material; - Material* materialShattered; - PhysPreset* physPreset; - }; - - struct FxSpatialFrame - { - float quat[4]; - float origin[3]; - }; - - union FxGlassPiecePlace - { - struct - { - FxSpatialFrame frame; - float radius; - }; - unsigned int nextFree; - }; - - struct FxGlassPieceState - { - float texCoordOrigin[2]; - unsigned int supportMask; - unsigned short initIndex; - unsigned short geoDataStart; - unsigned char defIndex; - unsigned char pad[5]; - unsigned char vertCount; - unsigned char holeDataCount; - unsigned char crackDataCount; - unsigned char fanDataCount; - unsigned short flags; - float areaX2; - }; - - struct FxGlassPieceDynamics - { - int fallTime; - int physObjId; - int physJointId; - float vel[3]; - float avel[3]; - }; - - struct FxGlassVertex - { - short x; - short y; - }; - - struct FxGlassHoleHeader - { - unsigned short uniqueVertCount; - unsigned char touchVert; - unsigned char pad[1]; - }; - - struct FxGlassCrackHeader - { - unsigned short uniqueVertCount; - unsigned char beginVertIndex; - unsigned char endVertIndex; - }; - - union type_align(4) FxGlassGeometryData - { - FxGlassVertex vert; - FxGlassHoleHeader hole; - FxGlassCrackHeader crack; - unsigned char asBytes[4]; - short anonymous[2]; - }; - - struct FxGlassInitPieceState - { - FxSpatialFrame frame; - float radius; - float texCoordOrigin[2]; - unsigned int supportMask; - float areaX2; - unsigned char defIndex; - unsigned char vertCount; - unsigned char fanDataCount; - unsigned char pad[1]; - }; - - struct FxGlassSystem - { - int time; - int prevTime; - unsigned int defCount; - unsigned int pieceLimit; - unsigned int pieceWordCount; - unsigned int initPieceCount; - unsigned int cellCount; - unsigned int activePieceCount; - unsigned int firstFreePiece; - unsigned int geoDataLimit; - unsigned int geoDataCount; - unsigned int initGeoDataCount; - FxGlassDef* defs; - FxGlassPiecePlace* piecePlaces; - FxGlassPieceState* pieceStates; - FxGlassPieceDynamics* pieceDynamics; - FxGlassGeometryData* geoData; - raw_uint* isInUse; - raw_uint* cellBits; - raw_byte16* visData; - vec3_t* linkOrg; - raw_float16* halfThickness; - unsigned short* lightingHandles; - FxGlassInitPieceState* initPieceStates; - FxGlassGeometryData* initGeoData; - bool needToCompactData; - unsigned char initCount; - float effectChanceAccum; - int lastPieceDeletionTime; - }; - - struct FxWorld - { - const char* name; - FxGlassSystem glassSys; - }; - - struct GfxSky - { - int skySurfCount; - int* skyStartSurfs; - GfxImage* skyImage; - unsigned char skySamplerState; - }; - - struct GfxWorldDpvsPlanes - { - int cellCount; - cplane_s* planes; - unsigned short* nodes; - raw_uint* sceneEntCellBits; - }; - - struct GfxCellTreeCount - { - int aabbTreeCount; - }; - - typedef unsigned short StaticModelIndex; - - struct GfxAabbTree - { - Bounds bounds; - unsigned short childCount; - unsigned short surfaceCount; - unsigned short startSurfIndex; - unsigned short surfaceCountNoDecal; - unsigned short startSurfIndexNoDecal; - unsigned short smodelIndexCount; - StaticModelIndex* smodelIndexes; - int childrenOffset; - }; - - struct GfxCellTree - { - GfxAabbTree* aabbTree; - }; - - struct GfxPortal; - - struct GfxPortalWritable - { - bool isQueued; - bool isAncestor; - unsigned char recursionDepth; - unsigned char hullPointCount; - float(*hullPoints)[2]; - GfxPortal* queuedParent; - }; - - struct DpvsPlane - { - float coeffs[4]; - }; - - struct GfxPortal - { - GfxPortalWritable writable; - DpvsPlane plane; - vec3_t* vertices; - unsigned short cellIndex; - unsigned char vertexCount; - float hullAxis[2][3]; - }; - - struct GfxCell - { - Bounds bounds; - int portalCount; - GfxPortal* portals; - unsigned char reflectionProbeCount; - unsigned char* reflectionProbes; - unsigned char reflectionProbeReferenceCount; - unsigned char* reflectionProbeReferences; - }; - - struct GfxReflectionProbe - { - float origin[3]; - }; - - struct GfxReflectionProbeReferenceOrigin - { - float origin[3]; - }; - - struct GfxReflectionProbeReference - { - unsigned char index; - }; - - struct GfxLightmapArray - { - GfxImage* primary; - GfxImage* secondary; - }; - - struct GfxWorldVertex - { - float xyz[3]; - float binormalSign; - GfxColor color; - float texCoord[2]; - float lmapCoord[2]; - PackedUnitVec normal; - PackedUnitVec tangent; - }; - - struct GfxWorldVertexData - { - GfxWorldVertex* vertices; - void* worldVb; - }; - - struct GfxWorldVertexLayerData - { - unsigned char* data; - void* layerVb; - }; - - struct GfxWorldDraw - { - unsigned int reflectionProbeCount; - GfxImage** reflectionProbes; - GfxReflectionProbe* reflectionProbeOrigins; - GfxTexture* reflectionProbeTextures; - unsigned int reflectionProbeReferenceCount; - GfxReflectionProbeReferenceOrigin* reflectionProbeReferenceOrigins; - GfxReflectionProbeReference* reflectionProbeReferences; - int lightmapCount; - GfxLightmapArray* lightmaps; - GfxTexture* lightmapPrimaryTextures; - GfxTexture* lightmapSecondaryTextures; - GfxImage* lightmapOverridePrimary; - GfxImage* lightmapOverrideSecondary; - unsigned int vertexCount; - GfxWorldVertexData vd; - unsigned int vertexLayerDataSize; - GfxWorldVertexLayerData vld; - unsigned int indexCount; - r_index_t* indices; - }; - - struct type_align(4) GfxLightGridEntry - { - unsigned short colorsIndex; - unsigned char primaryLightIndex; - unsigned char needsTrace; - }; - - struct type_align(4) GfxLightGridColors - { - unsigned char rgb[56][3]; - }; - - struct GfxLightGrid - { - bool hasLightRegions; - bool useSkyForLowZ; - unsigned int lastSunPrimaryLightIndex; - unsigned short mins[3]; - unsigned short maxs[3]; - unsigned int rowAxis; - unsigned int colAxis; - unsigned short* rowDataStart; - unsigned int rawRowDataSize; - unsigned char* rawRowData; - unsigned int entryCount; - GfxLightGridEntry* entries; - unsigned int colorCount; - GfxLightGridColors* colors; - }; - - struct GfxBrushModelWritable - { - Bounds bounds; - }; - - struct type_align(4) GfxBrushModel - { - GfxBrushModelWritable writable; - Bounds bounds; - float radius; - unsigned short surfaceCount; - unsigned short startSurfIndex; - uint16_t surfaceCountNoDecal; - }; - - struct MaterialMemory - { - Material* material; - int memory; - }; - - struct sunflare_t - { - bool hasValidData; - Material* spriteMaterial; - Material* flareMaterial; - float spriteSize; - float flareMinSize; - float flareMinDot; - float flareMaxSize; - float flareMaxDot; - float flareMaxAlpha; - int flareFadeInTime; - int flareFadeOutTime; - float blindMinDot; - float blindMaxDot; - float blindMaxDarken; - int blindFadeInTime; - int blindFadeOutTime; - float glareMinDot; - float glareMaxDot; - float glareMaxLighten; - int glareFadeInTime; - int glareFadeOutTime; - float sunFxPosition[3]; - }; - - struct XModelDrawInfo - { - unsigned char hasGfxEntIndex; - unsigned char lod; - unsigned short surfId; - }; - - struct GfxSceneDynModel - { - XModelDrawInfo info; - unsigned short dynEntId; - }; - - struct BModelDrawInfo - { - unsigned short surfId; - }; - - struct type_align(4) GfxSceneDynBrush - { - BModelDrawInfo info; - unsigned short dynEntId; - }; - - struct GfxShadowGeometry - { - unsigned short surfaceCount; - unsigned short smodelCount; - unsigned short* sortedSurfIndex; - unsigned short* smodelIndex; - }; - - struct GfxLightRegionAxis - { - float dir[3]; - float midPoint; - float halfSize; - }; - - struct GfxLightRegionHull - { - float kdopMidPoint[9]; - float kdopHalfSize[9]; - unsigned int axisCount; - GfxLightRegionAxis* axis; - }; - - struct GfxLightRegion - { - unsigned int hullCount; - GfxLightRegionHull* hulls; - }; - - struct GfxStaticModelInst - { - Bounds bounds; - float lightingOrigin[3]; - }; - - struct srfTriangles_t - { - unsigned int vertexLayerData; - unsigned int firstVertex; - unsigned short vertexCount; - unsigned short triCount; - unsigned int baseIndex; - }; - - struct GfxSurfaceLightingAndFlagsFields - { - unsigned char lightmapIndex; - unsigned char reflectionProbeIndex; - unsigned char primaryLightIndex; - unsigned char flags; - }; - - union GfxSurfaceLightingAndFlags - { - GfxSurfaceLightingAndFlagsFields fields; - unsigned int packed; - }; - - struct GfxSurface - { - srfTriangles_t tris; - Material* material; - GfxSurfaceLightingAndFlags laf; - }; - - struct GfxSurfaceBounds - { - Bounds bounds; - }; - - struct GfxPackedPlacement - { - float origin[3]; - float axis[3][3]; - float scale; - }; - - struct GfxStaticModelDrawInst - { - GfxPackedPlacement placement; - XModel* model; - unsigned short cullDist; - unsigned short lightingHandle; - unsigned char reflectionProbeIndex; - unsigned char primaryLightIndex; - unsigned char flags; - unsigned char firstMtlSkinIndex; - GfxColor groundLighting; - uint16_t cacheId[4]; - }; - - struct GfxWorldDpvsStatic - { - unsigned int smodelCount; - unsigned int staticSurfaceCount; - unsigned int staticSurfaceCountNoDecal; - unsigned int litOpaqueSurfsBegin; - unsigned int litOpaqueSurfsEnd; - unsigned int litTransSurfsBegin; - unsigned int litTransSurfsEnd; - unsigned int shadowCasterSurfsBegin; - unsigned int shadowCasterSurfsEnd; - unsigned int emissiveSurfsBegin; - unsigned int emissiveSurfsEnd; - unsigned int smodelVisDataCount; - unsigned int surfaceVisDataCount; - raw_byte* smodelVisData[3]; - raw_byte* surfaceVisData[3]; - unsigned short* sortedSurfIndex; - GfxStaticModelInst* smodelInsts; - GfxSurface* surfaces; - GfxSurfaceBounds* surfacesBounds; - GfxStaticModelDrawInst* smodelDrawInsts; - GfxDrawSurf* surfaceMaterials; - raw_uint128* surfaceCastsSunShadow; - volatile long usageCount; - }; - - struct GfxWorldDpvsDynamic - { - unsigned int dynEntClientWordCount[2]; - unsigned int dynEntClientCount[2]; - raw_uint* dynEntCellBits[2]; - raw_byte16* dynEntVisData[2][3]; - }; - - struct GfxHeroOnlyLight - { - unsigned char type; - unsigned char unused[3]; - float color[3]; - float dir[3]; - float up[3]; - float origin[3]; - float radius; - float cosHalfFovOuter; - float cosHalfFovInner; - int exponent; - }; - - typedef tdef_align(128) GfxCellTree GfxCellTree128; - - struct GfxWorld - { - const char* name; - const char* baseName; - int planeCount; - int nodeCount; - unsigned int surfaceCount; - int skyCount; - GfxSky* skies; - unsigned int lastSunPrimaryLightIndex; - unsigned int primaryLightCount; - unsigned int sortKeyLitDecal; - unsigned int sortKeyEffectDecal; - unsigned int sortKeyEffectAuto; - unsigned int sortKeyDistortion; - GfxWorldDpvsPlanes dpvsPlanes; - int/*GfxCellTreeCount*/* aabbTreeCounts; - GfxCellTree128* aabbTrees; - GfxCell* cells; - GfxWorldDraw draw; - GfxLightGrid lightGrid; - int modelCount; - GfxBrushModel* models; - Bounds bounds; - unsigned int checksum; - int materialMemoryCount; - MaterialMemory* materialMemory; - sunflare_t sun; - float outdoorLookupMatrix[4][4]; - GfxImage* outdoorImage; - raw_uint* cellCasterBits; - raw_uint* cellHasSunLitSurfsBits; - GfxSceneDynModel* sceneDynModel; - GfxSceneDynBrush* sceneDynBrush; - raw_uint* primaryLightEntityShadowVis; - raw_uint* primaryLightDynEntShadowVis[2]; - raw_byte* nonSunPrimaryLightForModelDynEnt; - GfxShadowGeometry* shadowGeom; - GfxLightRegion* lightRegion; - GfxWorldDpvsStatic dpvs; - GfxWorldDpvsDynamic dpvsDyn; - unsigned int mapVtxChecksum; - unsigned int heroOnlyLightCount; - GfxHeroOnlyLight* heroOnlyLights; - unsigned char fogTypesAllowed; - }; - - struct GfxLightImage - { - GfxImage* image; - unsigned char samplerState; - }; - - struct GfxLightDef - { - const char* name; - GfxLightImage attenuation; - GfxLightImage cucoloris; - int lmapLookupStart; - }; - - struct Glyph - { - unsigned short letter; - char x0; - char y0; - unsigned char dx; - unsigned char pixelWidth; - unsigned char pixelHeight; - float s0; - float t0; - float s1; - float t1; - }; - - struct Font_s - { - const char* fontName; - int pixelHeight; - int glyphCount; - Material* material; - Material* glowMaterial; - Glyph* glyphs; - }; - - struct MenuList - { - const char* name; - int menuCount; - menuDef_t** menus; - }; - - struct Statement_s; - - enum expDataType - { - VAL_INT = 0x0, - VAL_FLOAT = 0x1, - VAL_STRING = 0x2, - VAL_FUNCTION = 0x3, - - NUM_DATATYPES - }; - - struct ExpressionString - { - const char* string; - }; - - union operandInternalDataUnion - { - int intVal; - float floatVal; - ExpressionString stringVal; - Statement_s* function; - }; - - struct Operand - { - expDataType dataType; - operandInternalDataUnion internals; - }; - - enum expressionOperatorType_e - { - OP_NOOP = 0x0, - OP_RIGHTPAREN = 0x1, - OP_MULTIPLY = 0x2, - OP_DIVIDE = 0x3, - OP_MODULUS = 0x4, - OP_ADD = 0x5, - OP_SUBTRACT = 0x6, - OP_NOT = 0x7, - OP_LESSTHAN = 0x8, - OP_LESSTHANEQUALTO = 0x9, - OP_GREATERTHAN = 0xA, - OP_GREATERTHANEQUALTO = 0xB, - OP_EQUALS = 0xC, - OP_NOTEQUAL = 0xD, - OP_AND = 0xE, - OP_OR = 0xF, - OP_LEFTPAREN = 0x10, - OP_COMMA = 0x11, - OP_BITWISEAND = 0x12, - OP_BITWISEOR = 0x13, - OP_BITWISENOT = 0x14, - OP_BITSHIFTLEFT = 0x15, - OP_BITSHIFTRIGHT = 0x16, - - OP_COUNT - }; - - enum expressionFunction_e - { - EXP_FUNC_STATIC_DVAR_INT = OP_COUNT, - EXP_FUNC_STATIC_DVAR_BOOL, - EXP_FUNC_STATIC_DVAR_FLOAT, - EXP_FUNC_STATIC_DVAR_STRING, - - EXP_FUNC_DYN_START, - - EXP_FUNC_INT = EXP_FUNC_DYN_START, - EXP_FUNC_STRING, - EXP_FUNC_FLOAT, - EXP_FUNC_SIN, - EXP_FUNC_COS, - EXP_FUNC_MIN, - EXP_FUNC_MAX, - EXP_FUNC_MILLISECONDS, - EXP_FUNC_LOCAL_CLIENT_UI_MILLISECONDS, - EXP_FUNC_DVAR_INT, - EXP_FUNC_DVAR_BOOL, - EXP_FUNC_DVAR_FLOAT, - EXP_FUNC_DVAR_STRING - }; - - enum expressionEntryType : int - { - EET_OPERATOR = 0x0, - EET_OPERAND = 0x1, - }; - - union entryInternalData - { - int op; - Operand operand; - }; - - struct expressionEntry - { - int type; - entryInternalData data; - }; - - struct UIFunctionList - { - int totalFunctions; - Statement_s** functions; - }; - - union DvarValue - { - bool enabled; - int integer; - unsigned int unsignedInt; - float value; - float vector[4]; - const char* string; - unsigned char color[4]; - }; - - union DvarLimits - { - struct - { - int stringCount; - const char** strings; - } enumeration; - - struct - { - int min; - int max; - } integer; - - struct - { - float min; - float max; - } value; - - struct - { - float min; - float max; - } vector; - }; - - struct dvar_t - { - const char* name; - const char* description; - unsigned short flags; - unsigned char type; - bool modified; - DvarValue current; - DvarValue latched; - DvarValue reset; - DvarLimits domain; - dvar_t* hashNext; - }; - - struct StaticDvar - { - dvar_t* dvar; - char* dvarName; - }; - - struct StaticDvarList - { - int numStaticDvars; - StaticDvar** staticDvars; - }; - - struct StringList - { - int totalStrings; - const char** strings; - }; - - struct ExpressionSupportingData - { - UIFunctionList uifunctions; - StaticDvarList staticDvarList; - StringList uiStrings; - }; - - struct ExpressionPersistentState - { - int flags; - int playerDataKey[4]; - int lastExecuteTime[4]; - Operand lastResult[4]; - }; - - struct Statement_s - { - int numEntries; - expressionEntry* entries; - ExpressionSupportingData* supportingData; - ExpressionPersistentState persistentState; - }; - - struct MenuEventHandlerSet; - - struct ConditionalScript - { - MenuEventHandlerSet* eventHandlerSet; - Statement_s* eventExpression; - }; - - struct SetLocalVarData - { - const char* localVarName; - Statement_s* expression; - }; - - union EventData - { - const char* unconditionalScript; - ConditionalScript* conditionalScript; - MenuEventHandlerSet* elseScript; - SetLocalVarData* setLocalVarData; - }; - - enum EventType : unsigned char - { - EVENT_UNCONDITIONAL = 0x0, - EVENT_IF = 0x1, - EVENT_ELSE = 0x2, - EVENT_SET_LOCAL_VAR_BOOL = 0x3, - EVENT_SET_LOCAL_VAR_INT = 0x4, - EVENT_SET_LOCAL_VAR_FLOAT = 0x5, - EVENT_SET_LOCAL_VAR_STRING = 0x6, - - EVENT_COUNT - }; - - struct MenuEventHandler - { - EventData eventData; - EventType eventType; - }; - - struct MenuEventHandlerSet - { - int eventHandlerCount; - MenuEventHandler** eventHandlers; - }; - - struct ItemKeyHandler - { - int key; - MenuEventHandlerSet* action; - ItemKeyHandler* next; - }; - - struct menuTransition - { - int transitionType; - int startTime; - float startVal; - float endVal; - float time; - int endTriggerType; - }; - - struct menuData_t - { - int fullScreen; - int fadeCycle; - float fadeClamp; - float fadeAmount; - float fadeInAmount; - float blurRadius; - MenuEventHandlerSet* onOpen; - MenuEventHandlerSet* onCloseRequest; - MenuEventHandlerSet* onClose; - MenuEventHandlerSet* onESC; - MenuEventHandlerSet* onFocusDueToClose; - ItemKeyHandler* onKey; - Statement_s* visibleExp; - const char* allowedBinding; - const char* soundName; - float focusColor[4]; - Statement_s* rectXExp; - Statement_s* rectYExp; - Statement_s* rectWExp; - Statement_s* rectHExp; - Statement_s* openSoundExp; - Statement_s* closeSoundExp; - Statement_s* soundLoopExp; - int cursorItem[1]; - menuTransition scaleTransition[1]; - menuTransition alphaTransition[1]; - menuTransition xTransition[1]; - menuTransition yTransition[1]; - ExpressionSupportingData* expressionData; - unsigned char priority; - }; - - struct rectDef_s - { - float x; - float y; - float w; - float h; - unsigned char horzAlign; - unsigned char vertAlign; - }; - - // This is data from IW4, could be different for IW5, to be investigated - enum WindowDefStaticFlag : unsigned int - { - WINDOW_FLAG_DECORATION = 0x100000, - WINDOW_FLAG_HORIZONTAL_SCROLL = 0x200000, - WINDOW_FLAG_OUT_OF_BOUNDS_CLICK = 0x2000000, - WINDOW_FLAG_SCREEN_SPACE = 0x400000, - WINDOW_FLAG_AUTO_WRAPPED = 0x800000, - WINDOW_FLAG_POPUP = 0x1000000, - WINDOW_FLAG_LEGACY_SPLIT_SCREEN_SCALE = 0x4000000, - WINDOW_FLAG_HIDDEN_DURING_FLASH_BANG = 0x10000000, // confirmed - WINDOW_FLAG_HIDDEN_DURING_SCOPE = 0x20000000, // confirmed - WINDOW_FLAG_HIDDEN_DURING_UI = 0x40000000, // confirmed - WINDOW_FLAG_TEXT_ONLY_FOCUS = 0x80000000, - }; - - // This is data from IW4, could be different for IW5, to be investigated - enum WindowDefDynamicFlag : unsigned int - { - WINDOW_FLAG_HOVERED = 0x1, // guessed - WINDOW_FLAG_FOCUSED = 0x2, - WINDOW_FLAG_VISIBLE = 0x4, // confirmed - WINDOW_FLAG_FADING_OUT = 0x10, - WINDOW_FLAG_FADING_IN = 0x20, - WINDOW_FLAG_80 = 0x80, - WINDOW_FLAG_NON_DEFAULT_BACKCOLOR = 0x8000, - WINDOW_FLAG_NON_DEFAULT_FORECOLOR = 0x10000 - }; - - struct windowDef_t - { - const char* name; - rectDef_s rect; - rectDef_s rectClient; - const char* group; - int style; - int border; - int ownerDraw; - int ownerDrawFlags; - float borderSize; - int staticFlags; - int dynamicFlags[1]; - int nextTime; - float foreColor[4]; - float backColor[4]; - float borderColor[4]; - float outlineColor[4]; - float disableColor[4]; - Material* background; - }; - - // This is data from IW4, could be different for IW5, to be investigated - enum ItemDefFlag : unsigned int - { - ITEM_FLAG_SAVE_GAME_INFO = 0x1, - ITEM_FLAG_CINEMATIC_SUBTITLE = 0x2, - }; - - // This is data from IW4, could be different for IW5, to be investigated - enum ItemDefDvarFlag - { - ITEM_DVAR_FLAG_ENABLE = 0x1, - ITEM_DVAR_FLAG_DISABLE = 0x2, - ITEM_DVAR_FLAG_SHOW = 0x4, - ITEM_DVAR_FLAG_HIDE = 0x8, - ITEM_DVAR_FLAG_FOCUS = 0x10, - }; - - struct columnInfo_s - { - int xpos; - int ypos; - int width; - int height; - int maxChars; - int alignment; - }; - - struct listBoxDef_s - { - int mousePos; - int startPos[1]; - int endPos[1]; - int drawPadding; - float elementWidth; - float elementHeight; - int elementStyle; - int numColumns; - columnInfo_s columnInfo[16]; - MenuEventHandlerSet* onDoubleClick; - int notselectable; - int noScrollBars; - int usePaging; - float selectBorder[4]; - Material* selectIcon; - Statement_s* elementHeightExp; - }; - - struct editFieldDef_s - { - float minVal; - float maxVal; - float stepVal; - float range; - int maxChars; - int maxCharsGotoNext; - int maxPaintChars; - int paintOffset; - }; - - struct multiDef_s - { - const char* dvarList[32]; - const char* dvarStr[32]; - float dvarValue[32]; - int count; - int strDef; - }; - - struct newsTickerDef_s - { - int feedId; - int speed; - int spacing; - }; - - struct textScrollDef_s - { - int startTime; - }; - - union itemDefData_t - { - listBoxDef_s* listBox; - editFieldDef_s* editField; - multiDef_s* multi; - const char* enumDvarName; - newsTickerDef_s* ticker; - textScrollDef_s* scroll; - void* data; - }; - - enum ItemFloatExpressionTarget - { - ITEM_FLOATEXP_TGT_RECT_X = 0x0, - ITEM_FLOATEXP_TGT_RECT_Y = 0x1, - ITEM_FLOATEXP_TGT_RECT_W = 0x2, - ITEM_FLOATEXP_TGT_RECT_H = 0x3, - ITEM_FLOATEXP_TGT_FORECOLOR_R = 0x4, - ITEM_FLOATEXP_TGT_FORECOLOR_G = 0x5, - ITEM_FLOATEXP_TGT_FORECOLOR_B = 0x6, - ITEM_FLOATEXP_TGT_FORECOLOR_RGB = 0x7, - ITEM_FLOATEXP_TGT_FORECOLOR_A = 0x8, - ITEM_FLOATEXP_TGT_GLOWCOLOR_R = 0x9, - ITEM_FLOATEXP_TGT_GLOWCOLOR_G = 0xA, - ITEM_FLOATEXP_TGT_GLOWCOLOR_B = 0xB, - ITEM_FLOATEXP_TGT_GLOWCOLOR_RGB = 0xC, - ITEM_FLOATEXP_TGT_GLOWCOLOR_A = 0xD, - ITEM_FLOATEXP_TGT_BACKCOLOR_R = 0xE, - ITEM_FLOATEXP_TGT_BACKCOLOR_G = 0xF, - ITEM_FLOATEXP_TGT_BACKCOLOR_B = 0x10, - ITEM_FLOATEXP_TGT_BACKCOLOR_RGB = 0x11, - ITEM_FLOATEXP_TGT_BACKCOLOR_A = 0x12, - - ITEM_FLOATEXP_TGT_COUNT - }; - - struct ItemExpressionTargetBinding - { - int target; - const char* name; - const char* componentName; - }; - - struct ItemFloatExpression - { - int target; - Statement_s* expression; - }; - - enum ItemDefType - { - ITEM_TYPE_TEXT = 0x0, - ITEM_TYPE_BUTTON = 0x1, - ITEM_TYPE_RADIOBUTTON = 0x2, - ITEM_TYPE_CHECKBOX = 0x3, - ITEM_TYPE_EDITFIELD = 0x4, - ITEM_TYPE_COMBO = 0x5, - ITEM_TYPE_LISTBOX = 0x6, - ITEM_TYPE_MODEL = 0x7, - ITEM_TYPE_OWNERDRAW = 0x8, - ITEM_TYPE_NUMERICFIELD = 0x9, - ITEM_TYPE_SLIDER = 0xA, - ITEM_TYPE_YESNO = 0xB, - ITEM_TYPE_MULTI = 0xC, - ITEM_TYPE_DVARENUM = 0xD, - ITEM_TYPE_BIND = 0xE, - ITEM_TYPE_MENUMODEL = 0xF, - ITEM_TYPE_VALIDFILEFIELD = 0x10, - ITEM_TYPE_DECIMALFIELD = 0x11, - ITEM_TYPE_UPREDITFIELD = 0x12, - ITEM_TYPE_GAME_MESSAGE_WINDOW = 0x13, - ITEM_TYPE_NEWS_TICKER = 0x14, - ITEM_TYPE_TEXT_SCROLL = 0x15, - ITEM_TYPE_EMAILFIELD = 0x16, - ITEM_TYPE_PASSWORDFIELD = 0x17 - }; - - struct itemDef_s - { - windowDef_t window; - rectDef_s textRect[1]; - int type; - int dataType; - int alignment; - int fontEnum; - int textAlignMode; - float textalignx; - float textaligny; - float textscale; - int textStyle; - int gameMsgWindowIndex; - int gameMsgWindowMode; - const char* text; - int itemFlags; - menuDef_t* parent; - MenuEventHandlerSet* mouseEnterText; - MenuEventHandlerSet* mouseExitText; - MenuEventHandlerSet* mouseEnter; - MenuEventHandlerSet* mouseExit; - MenuEventHandlerSet* action; - MenuEventHandlerSet* accept; - MenuEventHandlerSet* onFocus; - MenuEventHandlerSet* hasFocus; - MenuEventHandlerSet* leaveFocus; - const char* dvar; - const char* dvarTest; - ItemKeyHandler* onKey; - const char* enableDvar; - const char* localVar; - int dvarFlags; - snd_alias_list_t* focusSound; - float special; - int cursorPos[1]; - itemDefData_t typeData; - int floatExpressionCount; - ItemFloatExpression* floatExpressions; - Statement_s* visibleExp; - Statement_s* disabledExp; - Statement_s* textExp; - Statement_s* materialExp; - float glowColor[4]; - bool decayActive; - int fxBirthTime; - int fxLetterTime; - int fxDecayStartTime; - int fxDecayDuration; - int lastSoundPlayedTime; - Statement_s* textAlignYExp; - }; - - struct menuDef_t - { - menuData_t* data; - windowDef_t window; - int itemCount; - itemDef_s** items; - }; - - struct LocalizeEntry - { - const char* value; - const char* name; - }; - - enum AttachmentType - { - ATTACHMENT_SCOPE = 0x0, - ATTACHMENT_UNDERBARREL = 0x1, - ATTACHMENT_OTHER = 0x2, - - ATTACHMENT_COUNT - }; - - enum weapType_t - { - WEAPTYPE_NONE = 0x0, - WEAPTYPE_BULLET = 0x1, - WEAPTYPE_GRENADE = 0x2, - WEAPTYPE_PROJECTILE = 0x3, - WEAPTYPE_RIOTSHIELD = 0x4, - - WEAPTYPE_NUM - }; - - enum weapClass_t - { - WEAPCLASS_RIFLE = 0x0, - WEAPCLASS_SNIPER = 0x1, - WEAPCLASS_MG = 0x2, - WEAPCLASS_SMG = 0x3, - WEAPCLASS_SPREAD = 0x4, - WEAPCLASS_PISTOL = 0x5, - WEAPCLASS_GRENADE = 0x6, - WEAPCLASS_ROCKETLAUNCHER = 0x7, - WEAPCLASS_TURRET = 0x8, - WEAPCLASS_THROWINGKNIFE = 0x9, - WEAPCLASS_NON_PLAYER = 0xA, - WEAPCLASS_ITEM = 0xB, - - WEAPCLASS_NUM - }; - - enum PenetrateType - { - PENETRATE_TYPE_NONE = 0x0, - PENETRATE_TYPE_SMALL = 0x1, - PENETRATE_TYPE_MEDIUM = 0x2, - PENETRATE_TYPE_LARGE = 0x3, - - PENETRATE_TYPE_COUNT - }; - - enum ImpactType - { - IMPACT_TYPE_NONE = 0x0, - IMPACT_TYPE_BULLET_SMALL = 0x1, - IMPACT_TYPE_BULLET_LARGE = 0x2, - IMPACT_TYPE_BULLET_AP = 0x3, - IMPACT_TYPE_BULLET_EXPLODE = 0x4, - IMPACT_TYPE_SHOTGUN = 0x5, - IMPACT_TYPE_SHOTGUN_EXPLODE = 0x6, - IMPACT_TYPE_GRENADE_BOUNCE = 0x7, - IMPACT_TYPE_GRENADE_EXPLODE = 0x8, - IMPACT_TYPE_ROCKET_EXPLODE = 0x9, - IMPACT_TYPE_PROJECTILE_DUD = 0xA, - - IMPACT_TYPE_COUNT - }; - - enum weapFireType_t - { - WEAPON_FIRETYPE_FULLAUTO = 0x0, - WEAPON_FIRETYPE_SINGLESHOT = 0x1, - WEAPON_FIRETYPE_BURSTFIRE2 = 0x2, - WEAPON_FIRETYPE_BURSTFIRE3 = 0x3, - WEAPON_FIRETYPE_BURSTFIRE4 = 0x4, - WEAPON_FIRETYPE_DOUBLEBARREL = 0x5, - - WEAPON_FIRETYPECOUNT, - WEAPON_FIRETYPE_BURSTFIRE_FIRST = WEAPON_FIRETYPE_BURSTFIRE2, - WEAPON_FIRETYPE_BURSTFIRE_LAST = WEAPON_FIRETYPE_BURSTFIRE4 - }; - - struct AttAmmoGeneral - { - PenetrateType penetrateType; - float penetrateMultiplier; - ImpactType impactType; - weapFireType_t fireType; - TracerDef* tracerType; - bool rifleBullet; - bool armorPiercing; - }; - - struct AttSight - { - bool aimDownSight; - bool adsFire; - bool rechamberWhileAds; - bool noAdsWhenMagEmpty; - bool canHoldBreath; - bool canVariableZoom; - bool hideRailWithThisScope; - }; - - struct AttReload - { - bool noPartialReload; - bool segmentedReload; - }; - - struct AttAddOns - { - bool motionTracker; - bool silenced; - }; - - struct AttGeneral - { - bool boltAction; - bool inheritsPerks; - float enemyCrosshairRange; - Material* reticleCenter; - Material* reticleSide; - int reticleCenterSize; - int reticleSideSize; - float moveSpeedScale; - float adsMoveSpeedScale; - }; - - struct AttAimAssist - { - float autoAimRange; - float aimAssistRange; - float aimAssistRangeAds; - }; - - struct AttAmmunition - { - int maxAmmo; - int startAmmo; - int clipSize; - int shotCount; - int reloadAmmoAdd; - int reloadStartAdd; - }; - - struct AttDamage - { - int damage; - int minDamage; - int meleeDamage; - float maxDamageRange; - float minDamageRange; - int playerDamage; - int minPlayerDamage; - }; - - struct AttLocationDamage - { - float locNone; - float locHelmet; - float locHead; - float locNeck; - float locTorsoUpper; - float locTorsoLower; - float locRightArmUpper; - float locRightArmLower; - float locRightHand; - float locLeftArmUpper; - float locLeftArmLower; - float locLeftHand; - float locRightLegUpper; - float locRightLegLower; - float locRightFoot; - float locLeftLegUpper; - float locLeftLegLower; - float locLeftFoot; - float locGun; - }; - - struct AttIdleSettings - { - float hipIdleAmount; - float hipIdleSpeed; - float idleCrouchFactor; - float idleProneFactor; - float adsIdleLerpStartTime; - float adsIdleLerpTime; - }; - - struct AttADSSettings - { - float adsSpread; - float adsAimPitch; - float adsTransInTime; - float adsTransOutTime; - int adsReloadTransTime; - float adsCrosshairInFrac; - float adsCrosshairOutFrac; - float adsZoomFov; - float adsZoomInFrac; - float adsZoomOutFrac; - float adsBobFactor; - float adsViewBobMult; - float adsViewErrorMin; - float adsViewErrorMax; - }; - - struct AttHipSpread - { - float hipSpreadStandMin; - float hipSpreadDuckedMin; - float hipSpreadProneMin; - float hipSpreadMax; - float hipSpreadDuckedMax; - float hipSpreadProneMax; - float hipSpreadFireAdd; - float hipSpreadTurnAdd; - float hipSpreadMoveAdd; - float hipSpreadDecayRate; - float hipSpreadDuckedDecay; - float hipSpreadProneDecay; - }; - - struct AttGunKick - { - int hipGunKickReducedKickBullets; - float hipGunKickReducedKickPercent; - float hipGunKickPitchMin; - float hipGunKickPitchMax; - float hipGunKickYawMin; - float hipGunKickYawMax; - float hipGunKickAccel; - float hipGunKickSpeedMax; - float hipGunKickSpeedDecay; - float hipGunKickStaticDecay; - int adsGunKickReducedKickBullets; - float adsGunKickReducedKickPercent; - float adsGunKickPitchMin; - float adsGunKickPitchMax; - float adsGunKickYawMin; - float adsGunKickYawMax; - float adsGunKickAccel; - float adsGunKickSpeedMax; - float adsGunKickSpeedDecay; - float adsGunKickStaticDecay; - }; - - struct AttViewKick - { - float hipViewKickPitchMin; - float hipViewKickPitchMax; - float hipViewKickYawMin; - float hipViewKickYawMax; - float hipViewKickCenterSpeed; - float adsViewKickPitchMin; - float adsViewKickPitchMax; - float adsViewKickYawMin; - float adsViewKickYawMax; - float adsViewKickCenterSpeed; - }; - - enum weapOverlayReticle_t - { - WEAPOVERLAYRETICLE_NONE = 0x0, - WEAPOVERLAYRETICLE_CROSSHAIR = 0x1, - - WEAPOVERLAYRETICLE_NUM - }; - - struct ADSOverlay - { - Material* shader; - Material* shaderLowRes; - Material* shaderEMP; - Material* shaderEMPLowRes; - weapOverlayReticle_t reticle; - float width; - float height; - float widthSplitscreen; - float heightSplitscreen; - }; - - struct AttADSOverlay - { - ADSOverlay overlay; - bool thermalScope; - }; - - enum weaponIconRatioType_t - { - WEAPON_ICON_RATIO_1TO1 = 0x0, - WEAPON_ICON_RATIO_2TO1 = 0x1, - WEAPON_ICON_RATIO_4TO1 = 0x2, - - WEAPON_ICON_RATIO_COUNT - }; - - enum ammoCounterClipType_t - { - AMMO_COUNTER_CLIP_NONE = 0x0, - AMMO_COUNTER_CLIP_MAGAZINE = 0x1, - AMMO_COUNTER_CLIP_SHORTMAGAZINE = 0x2, - AMMO_COUNTER_CLIP_SHOTGUN = 0x3, - AMMO_COUNTER_CLIP_ROCKET = 0x4, - AMMO_COUNTER_CLIP_BELTFED = 0x5, - AMMO_COUNTER_CLIP_ALTWEAPON = 0x6, - - AMMO_COUNTER_CLIP_COUNT - }; - - struct AttUI - { - Material* dpadIcon; - Material* ammoCounterIcon; - weaponIconRatioType_t dpadIconRatio; - weaponIconRatioType_t ammoCounterIconRatio; - ammoCounterClipType_t ammoCounterClip; - }; - - struct AttRumbles - { - const char* fireRumble; - const char* meleeImpactRumble; - }; - - enum weapProjExposion_t - { - WEAPPROJEXP_GRENADE = 0x0, - WEAPPROJEXP_ROCKET = 0x1, - WEAPPROJEXP_FLASHBANG = 0x2, - WEAPPROJEXP_NONE = 0x3, - WEAPPROJEXP_DUD = 0x4, - WEAPPROJEXP_SMOKE = 0x5, - WEAPPROJEXP_HEAVY = 0x6, - - WEAPPROJEXP_NUM - }; - - struct snd_alias_list_name - { - const char* soundName; - }; - - union SndAliasCustom - { - snd_alias_list_name* name; - snd_alias_list_t* sound; - }; - - struct AttProjectile - { - int explosionRadius; - int explosionInnerDamage; - int explosionOuterDamage; - float damageConeAngle; - int projectileSpeed; - int projectileSpeedUp; - int projectileActivateDist; - float projectileLifetime; - XModel* projectileModel; - weapProjExposion_t projExplosionType; - FxEffectDef* projExplosionEffect; - bool projExplosionEffectForceNormalUp; - SndAliasCustom projExplosionSound; - FxEffectDef* projDudEffect; - SndAliasCustom projDudSound; - bool projImpactExplode; - float destabilizationRateTime; - float destabilizationCurvatureMax; - int destabilizeDistance; - FxEffectDef* projTrailEffect; - int projIgnitionDelay; - FxEffectDef* projIgnitionEffect; - SndAliasCustom projIgnitionSound; - }; - - typedef tdef_align(4) AttSight AttSight4; - - struct WeaponAttachment - { - const char* szInternalName; - const char* szDisplayName; - AttachmentType type; - weapType_t weaponType; - weapClass_t weapClass; - XModel** worldModels; - XModel** viewModels; - XModel** reticleViewModels; - AttAmmoGeneral* ammogeneral; - AttSight4* sight; - AttReload* reload; - AttAddOns* addOns; - AttGeneral* general; - AttAimAssist* aimAssist; - AttAmmunition* ammunition; - AttDamage* damage; - AttLocationDamage* locationDamage; - AttIdleSettings* idleSettings; - AttADSSettings* adsSettings; - AttADSSettings* adsSettingsMain; - AttHipSpread* hipSpread; - AttGunKick* gunKick; - AttViewKick* viewKick; - AttADSOverlay* adsOverlay; - AttUI* ui; - AttRumbles* rumbles; - AttProjectile* projectile; - float ammunitionScale; - float damageScale; - float damageScaleMin; - float stateTimersScale; - float fireTimersScale; - float idleSettingsScale; - float adsSettingsScale; - float adsSettingsScaleMain; - float hipSpreadScale; - float gunKickScale; - float viewKickScale; - float viewCenterScale; - int loadIndex; - bool hideIronSightsWithThisAttachment; - bool shareAmmoWithAlt; - }; - - enum weapInventoryType_t - { - WEAPINVENTORY_PRIMARY = 0x0, - WEAPINVENTORY_OFFHAND = 0x1, - WEAPINVENTORY_ITEM = 0x2, - WEAPINVENTORY_ALTMODE = 0x3, - WEAPINVENTORY_EXCLUSIVE = 0x4, - WEAPINVENTORY_SCAVENGER = 0x5, - - WEAPINVENTORYCOUNT - }; - - enum OffhandClass - { - OFFHAND_CLASS_NONE = 0x0, - OFFHAND_CLASS_FRAG_GRENADE = 0x1, - OFFHAND_CLASS_SMOKE_GRENADE = 0x2, - OFFHAND_CLASS_FLASH_GRENADE = 0x3, - OFFHAND_CLASS_THROWINGKNIFE = 0x4, - OFFHAND_CLASS_OTHER = 0x5, - - OFFHAND_CLASS_COUNT - }; - - enum weapStance_t - { - WEAPSTANCE_STAND = 0x0, - WEAPSTANCE_DUCK = 0x1, - WEAPSTANCE_PRONE = 0x2, - - WEAPSTANCE_NUM - }; - - enum activeReticleType_t - { - VEH_ACTIVE_RETICLE_NONE = 0x0, - VEH_ACTIVE_RETICLE_PIP_ON_A_STICK = 0x1, - VEH_ACTIVE_RETICLE_BOUNCING_DIAMOND = 0x2, - - VEH_ACTIVE_RETICLE_COUNT - }; - - struct StateTimers - { - int iFireDelay; - int iMeleeDelay; - int meleeChargeDelay; - int iDetonateDelay; - int iRechamberTime; - int rechamberTimeOneHanded; - int iRechamberBoltTime; - int iHoldFireTime; - int iDetonateTime; - int iMeleeTime; - int meleeChargeTime; - int iReloadTime; - int reloadShowRocketTime; - int iReloadEmptyTime; - int iReloadAddTime; - int iReloadStartTime; - int iReloadStartAddTime; - int iReloadEndTime; - int iDropTime; - int iRaiseTime; - int iAltDropTime; - int quickDropTime; - int quickRaiseTime; - int iBreachRaiseTime; - int iEmptyRaiseTime; - int iEmptyDropTime; - int sprintInTime; - int sprintLoopTime; - int sprintOutTime; - int stunnedTimeBegin; - int stunnedTimeLoop; - int stunnedTimeEnd; - int nightVisionWearTime; - int nightVisionWearTimeFadeOutEnd; - int nightVisionWearTimePowerUp; - int nightVisionRemoveTime; - int nightVisionRemoveTimePowerDown; - int nightVisionRemoveTimeFadeInStart; - int fuseTime; - int aiFuseTime; - int blastFrontTime; - int blastRightTime; - int blastBackTime; - int blastLeftTime; - int raiseInterruptableTime; - int firstRaiseInterruptableTime; - int reloadInterruptableTime; - int reloadEmptyInterruptableTime; - int fireInterruptableTime; - }; - - enum WeapOverlayInteface_t - { - WEAPOVERLAYINTERFACE_NONE = 0x0, - WEAPOVERLAYINTERFACE_JAVELIN = 0x1, - WEAPOVERLAYINTERFACE_TURRETSCOPE = 0x2, - - WEAPOVERLAYINTERFACECOUNT - }; - - enum WeapStickinessType - { - WEAPSTICKINESS_NONE = 0x0, - WEAPSTICKINESS_ALL = 0x1, - WEAPSTICKINESS_ALL_ORIENT = 0x2, - WEAPSTICKINESS_GROUND = 0x3, - WEAPSTICKINESS_GROUND_WITH_YAW = 0x4, - WEAPSTICKINESS_KNIFE = 0x5, - - WEAPSTICKINESS_COUNT - }; - - enum guidedMissileType_t - { - MISSILE_GUIDANCE_NONE = 0x0, - MISSILE_GUIDANCE_SIDEWINDER = 0x1, - MISSILE_GUIDANCE_HELLFIRE = 0x2, - MISSILE_GUIDANCE_JAVELIN = 0x3, - - MISSILE_GUIDANCE_COUNT - }; - - enum weapAnimFiles_t - { - WEAP_ANIM_ROOT = 0x0, - WEAP_ANIM_IDLE = 0x1, - WEAP_ANIM_EMPTY_IDLE = 0x2, - WEAP_ANIM_FIRE = 0x3, - WEAP_ANIM_HOLD_FIRE = 0x4, - WEAP_ANIM_LASTSHOT = 0x5, - WEAP_ANIM_RECHAMBER = 0x6, - WEAP_ANIM_MELEE = 0x7, - WEAP_ANIM_MELEE_CHARGE = 0x8, - WEAP_ANIM_RELOAD = 0x9, - WEAP_ANIM_RELOAD_EMPTY = 0xA, - WEAP_ANIM_RELOAD_START = 0xB, - WEAP_ANIM_RELOAD_END = 0xC, - WEAP_ANIM_RAISE = 0xD, - WEAP_ANIM_FIRST_RAISE = 0xE, - WEAP_ANIM_BREACH_RAISE = 0xF, - WEAP_ANIM_DROP = 0x10, - WEAP_ANIM_ALT_RAISE = 0x11, - WEAP_ANIM_ALT_DROP = 0x12, - WEAP_ANIM_QUICK_RAISE = 0x13, - WEAP_ANIM_QUICK_DROP = 0x14, - WEAP_ANIM_EMPTY_RAISE = 0x15, - WEAP_ANIM_EMPTY_DROP = 0x16, - WEAP_ANIM_SPRINT_IN = 0x17, - WEAP_ANIM_SPRINT_LOOP = 0x18, - WEAP_ANIM_SPRINT_OUT = 0x19, - WEAP_ANIM_STUNNED_START = 0x1A, - WEAP_ANIM_STUNNED_LOOP = 0x1B, - WEAP_ANIM_STUNNED_END = 0x1C, - WEAP_ANIM_DETONATE = 0x1D, - WEAP_ANIM_NIGHTVISION_WEAR = 0x1E, - WEAP_ANIM_NIGHTVISION_REMOVE = 0x1F, - WEAP_ANIM_ADS_FIRE = 0x20, - WEAP_ANIM_ADS_LASTSHOT = 0x21, - WEAP_ANIM_ADS_RECHAMBER = 0x22, - WEAP_ANIM_BLAST_FRONT = 0x23, - WEAP_ANIM_BLAST_RIGHT = 0x24, - WEAP_ANIM_BLAST_BACK = 0x25, - WEAP_ANIM_BLAST_LEFT = 0x26, - WEAP_ANIM_ADS_UP = 0x27, - WEAP_ANIM_ADS_DOWN = 0x28, - WEAP_ALT_ANIM_ADJUST = 0x29, - - NUM_WEAP_ANIMS - }; - - enum hitLocation_t - { - HITLOC_NONE = 0x0, - HITLOC_HELMET = 0x1, - HITLOC_HEAD = 0x2, - HITLOC_NECK = 0x3, - HITLOC_TORSO_UPR = 0x4, - HITLOC_TORSO_LWR = 0x5, - HITLOC_R_ARM_UPR = 0x6, - HITLOC_L_ARM_UPR = 0x7, - HITLOC_R_ARM_LWR = 0x8, - HITLOC_L_ARM_LWR = 0x9, - HITLOC_R_HAND = 0xA, - HITLOC_L_HAND = 0xB, - HITLOC_R_LEG_UPR = 0xC, - HITLOC_L_LEG_UPR = 0xD, - HITLOC_R_LEG_LWR = 0xE, - HITLOC_L_LEG_LWR = 0xF, - HITLOC_R_FOOT = 0x10, - HITLOC_L_FOOT = 0x11, - HITLOC_GUN = 0x12, - HITLOC_SHIELD = 0x13, - - HITLOC_NUM - }; - - struct WeaponDef - { - const char* szOverlayName; - XModel** gunXModel; - XModel* handXModel; - const char** szXAnimsRightHanded; - const char** szXAnimsLeftHanded; - const char* szModeName; - ScriptString* notetrackSoundMapKeys; - ScriptString* notetrackSoundMapValues; - ScriptString* notetrackRumbleMapKeys; - ScriptString* notetrackRumbleMapValues; - int playerAnimType; - weapType_t weapType; - weapClass_t weapClass; - PenetrateType penetrateType; - weapInventoryType_t inventoryType; - weapFireType_t fireType; - OffhandClass offhandClass; - weapStance_t stance; - FxEffectDef* viewFlashEffect; - FxEffectDef* worldFlashEffect; - SndAliasCustom pickupSound; - SndAliasCustom pickupSoundPlayer; - SndAliasCustom ammoPickupSound; - SndAliasCustom ammoPickupSoundPlayer; - SndAliasCustom projectileSound; - SndAliasCustom pullbackSound; - SndAliasCustom pullbackSoundPlayer; - SndAliasCustom fireSound; - SndAliasCustom fireSoundPlayer; - SndAliasCustom fireSoundPlayerAkimbo; - SndAliasCustom fireLoopSound; - SndAliasCustom fireLoopSoundPlayer; - SndAliasCustom fireStopSound; - SndAliasCustom fireStopSoundPlayer; - SndAliasCustom fireLastSound; - SndAliasCustom fireLastSoundPlayer; - SndAliasCustom emptyFireSound; - SndAliasCustom emptyFireSoundPlayer; - SndAliasCustom meleeSwipeSound; - SndAliasCustom meleeSwipeSoundPlayer; - SndAliasCustom meleeHitSound; - SndAliasCustom meleeMissSound; - SndAliasCustom rechamberSound; - SndAliasCustom rechamberSoundPlayer; - SndAliasCustom reloadSound; - SndAliasCustom reloadSoundPlayer; - SndAliasCustom reloadEmptySound; - SndAliasCustom reloadEmptySoundPlayer; - SndAliasCustom reloadStartSound; - SndAliasCustom reloadStartSoundPlayer; - SndAliasCustom reloadEndSound; - SndAliasCustom reloadEndSoundPlayer; - SndAliasCustom detonateSound; - SndAliasCustom detonateSoundPlayer; - SndAliasCustom nightVisionWearSound; - SndAliasCustom nightVisionWearSoundPlayer; - SndAliasCustom nightVisionRemoveSound; - SndAliasCustom nightVisionRemoveSoundPlayer; - SndAliasCustom altSwitchSound; - SndAliasCustom altSwitchSoundPlayer; - SndAliasCustom raiseSound; - SndAliasCustom raiseSoundPlayer; - SndAliasCustom firstRaiseSound; - SndAliasCustom firstRaiseSoundPlayer; - SndAliasCustom putawaySound; - SndAliasCustom putawaySoundPlayer; - SndAliasCustom scanSound; - SndAliasCustom changeVariableZoomSound; - SndAliasCustom* bounceSound; - SndAliasCustom* rollingSound; - FxEffectDef* viewShellEjectEffect; - FxEffectDef* worldShellEjectEffect; - FxEffectDef* viewLastShotEjectEffect; - FxEffectDef* worldLastShotEjectEffect; - Material* reticleCenter; - Material* reticleSide; - int iReticleCenterSize; - int iReticleSideSize; - int iReticleMinOfs; - activeReticleType_t activeReticleType; - float vStandMove[3]; - float vStandRot[3]; - float strafeMove[3]; - float strafeRot[3]; - float vDuckedOfs[3]; - float vDuckedMove[3]; - float vDuckedRot[3]; - float vProneOfs[3]; - float vProneMove[3]; - float vProneRot[3]; - float fPosMoveRate; - float fPosProneMoveRate; - float fStandMoveMinSpeed; - float fDuckedMoveMinSpeed; - float fProneMoveMinSpeed; - float fPosRotRate; - float fPosProneRotRate; - float fStandRotMinSpeed; - float fDuckedRotMinSpeed; - float fProneRotMinSpeed; - XModel** worldModel; - XModel* worldClipModel; - XModel* rocketModel; - XModel* knifeModel; - XModel* worldKnifeModel; - Material* hudIcon; - weaponIconRatioType_t hudIconRatio; - Material* pickupIcon; - weaponIconRatioType_t pickupIconRatio; - Material* ammoCounterIcon; - weaponIconRatioType_t ammoCounterIconRatio; - ammoCounterClipType_t ammoCounterClip; - int iStartAmmo; - const char* szAmmoName; - int iAmmoIndex; - const char* szClipName; - int iClipIndex; - int iMaxAmmo; - int shotCount; - const char* szSharedAmmoCapName; - int iSharedAmmoCapIndex; - int iSharedAmmoCap; - int damage; - int playerDamage; - int iMeleeDamage; - int iDamageType; - StateTimers stateTimers; - StateTimers akimboStateTimers; - float autoAimRange; - float aimAssistRange; - float aimAssistRangeAds; - float aimPadding; - float enemyCrosshairRange; - float moveSpeedScale; - float adsMoveSpeedScale; - float sprintDurationScale; - float fAdsZoomInFrac; - float fAdsZoomOutFrac; - ADSOverlay overlay; - WeapOverlayInteface_t overlayInterface; - float fAdsBobFactor; - float fAdsViewBobMult; - float fHipSpreadStandMin; - float fHipSpreadDuckedMin; - float fHipSpreadProneMin; - float hipSpreadStandMax; - float hipSpreadDuckedMax; - float hipSpreadProneMax; - float fHipSpreadDecayRate; - float fHipSpreadFireAdd; - float fHipSpreadTurnAdd; - float fHipSpreadMoveAdd; - float fHipSpreadDuckedDecay; - float fHipSpreadProneDecay; - float fHipReticleSidePos; - float fAdsIdleAmount; - float fHipIdleAmount; - float adsIdleSpeed; - float hipIdleSpeed; - float fIdleCrouchFactor; - float fIdleProneFactor; - float fGunMaxPitch; - float fGunMaxYaw; - float adsIdleLerpStartTime; - float adsIdleLerpTime; - float swayMaxAngle; - float swayLerpSpeed; - float swayPitchScale; - float swayYawScale; - float swayHorizScale; - float swayVertScale; - float swayShellShockScale; - float adsSwayMaxAngle; - float adsSwayLerpSpeed; - float adsSwayPitchScale; - float adsSwayYawScale; - float adsSwayHorizScale; - float adsSwayVertScale; - float adsViewErrorMin; - float adsViewErrorMax; - PhysCollmap* physCollmap; - float dualWieldViewModelOffset; - weaponIconRatioType_t killIconRatio; - int iReloadAmmoAdd; - int iReloadStartAdd; - int ammoDropStockMin; - int ammoDropClipPercentMin; - int ammoDropClipPercentMax; - int iExplosionRadius; - int iExplosionRadiusMin; - int iExplosionInnerDamage; - int iExplosionOuterDamage; - float damageConeAngle; - float bulletExplDmgMult; - float bulletExplRadiusMult; - int iProjectileSpeed; - int iProjectileSpeedUp; - int iProjectileSpeedForward; - int iProjectileActivateDist; - float projLifetime; - float timeToAccelerate; - float projectileCurvature; - XModel* projectileModel; - weapProjExposion_t projExplosion; - FxEffectDef* projExplosionEffect; - FxEffectDef* projDudEffect; - SndAliasCustom projExplosionSound; - SndAliasCustom projDudSound; - WeapStickinessType stickiness; - float lowAmmoWarningThreshold; - float ricochetChance; - bool riotShieldEnableDamage; - int riotShieldHealth; - float riotShieldDamageMult; - float* parallelBounce; - float* perpendicularBounce; - FxEffectDef* projTrailEffect; - FxEffectDef* projBeaconEffect; - float vProjectileColor[3]; - guidedMissileType_t guidedMissileType; - float maxSteeringAccel; - int projIgnitionDelay; - FxEffectDef* projIgnitionEffect; - SndAliasCustom projIgnitionSound; - float fAdsAimPitch; - float fAdsCrosshairInFrac; - float fAdsCrosshairOutFrac; - int adsGunKickReducedKickBullets; - float adsGunKickReducedKickPercent; - float fAdsGunKickPitchMin; - float fAdsGunKickPitchMax; - float fAdsGunKickYawMin; - float fAdsGunKickYawMax; - float fAdsGunKickAccel; - float fAdsGunKickSpeedMax; - float fAdsGunKickSpeedDecay; - float fAdsGunKickStaticDecay; - float fAdsViewKickPitchMin; - float fAdsViewKickPitchMax; - float fAdsViewKickYawMin; - float fAdsViewKickYawMax; - float fAdsViewScatterMin; - float fAdsViewScatterMax; - float fAdsSpread; - int hipGunKickReducedKickBullets; - float hipGunKickReducedKickPercent; - float fHipGunKickPitchMin; - float fHipGunKickPitchMax; - float fHipGunKickYawMin; - float fHipGunKickYawMax; - float fHipGunKickAccel; - float fHipGunKickSpeedMax; - float fHipGunKickSpeedDecay; - float fHipGunKickStaticDecay; - float fHipViewKickPitchMin; - float fHipViewKickPitchMax; - float fHipViewKickYawMin; - float fHipViewKickYawMax; - float fHipViewScatterMin; - float fHipViewScatterMax; - float fightDist; - float maxDist; - // const char* accuracyGraphName[2];// TODO: Order is accuracyGraphName[0] -> originalAccuracyGraphKnots[0] -> accuracyGraphName[1] -> ... - // Which is currently not possible to do in code generation. Afaik this is the only place where this is the case. - // So might be something to fix but on the other hand it might be too much work for this little inconvenience. - // vec2_t* originalAccuracyGraphKnots[2]; - const char* accuracyGraphName0; - const char* accuracyGraphName1; - vec2_t* originalAccuracyGraphKnots0; - vec2_t* originalAccuracyGraphKnots1; - unsigned short originalAccuracyGraphKnotCount[2]; - int iPositionReloadTransTime; - float leftArc; - float rightArc; - float topArc; - float bottomArc; - float accuracy; - float aiSpread; - float playerSpread; - float minTurnSpeed[2]; - float maxTurnSpeed[2]; - float pitchConvergenceTime; - float yawConvergenceTime; - float suppressTime; - float maxRange; - float fAnimHorRotateInc; - float fPlayerPositionDist; - const char* szUseHintString; - const char* dropHintString; - int iUseHintStringIndex; - int dropHintStringIndex; - float horizViewJitter; - float vertViewJitter; - float scanSpeed; - float scanAccel; - int scanPauseTime; - const char* szScript; - float fOOPosAnimLength[2]; - int minDamage; - int minPlayerDamage; - float fMaxDamageRange; - float fMinDamageRange; - float destabilizationRateTime; - float destabilizationCurvatureMax; - int destabilizeDistance; - float* locationDamageMultipliers; - const char* fireRumble; - const char* meleeImpactRumble; - TracerDef* tracerType; - bool turretADSEnabled; - float turretADSTime; - float turretFov; - float turretFovADS; - float turretScopeZoomRate; - float turretScopeZoomMin; - float turretScopeZoomMax; - float turretOverheatUpRate; - float turretOverheatDownRate; - float turretOverheatPenalty; - SndAliasCustom turretOverheatSound; - FxEffectDef* turretOverheatEffect; - const char* turretBarrelSpinRumble; - float turretBarrelSpinSpeed; - float turretBarrelSpinUpTime; - float turretBarrelSpinDownTime; - SndAliasCustom turretBarrelSpinMaxSnd; - SndAliasCustom turretBarrelSpinUpSnd[4]; - SndAliasCustom turretBarrelSpinDownSnd[4]; - SndAliasCustom missileConeSoundAlias; - SndAliasCustom missileConeSoundAliasAtBase; - float missileConeSoundRadiusAtTop; - float missileConeSoundRadiusAtBase; - float missileConeSoundHeight; - float missileConeSoundOriginOffset; - float missileConeSoundVolumescaleAtCore; - float missileConeSoundVolumescaleAtEdge; - float missileConeSoundVolumescaleCoreSize; - float missileConeSoundPitchAtTop; - float missileConeSoundPitchAtBottom; - float missileConeSoundPitchTopSize; - float missileConeSoundPitchBottomSize; - float missileConeSoundCrossfadeTopSize; - float missileConeSoundCrossfadeBottomSize; - bool sharedAmmo; - bool lockonSupported; - bool requireLockonToFire; - bool isAirburstWeapon; - bool bigExplosion; - bool noAdsWhenMagEmpty; - bool avoidDropCleanup; - bool inheritsPerks; - bool crosshairColorChange; - bool bRifleBullet; - bool armorPiercing; - bool bBoltAction; - bool aimDownSight; - bool canHoldBreath; - bool canVariableZoom; - bool bRechamberWhileAds; - bool bBulletExplosiveDamage; - bool bCookOffHold; - bool bClipOnly; - bool noAmmoPickup; - bool adsFireOnly; - bool cancelAutoHolsterWhenEmpty; - bool disableSwitchToWhenEmpty; - bool suppressAmmoReserveDisplay; - bool laserSightDuringNightvision; - bool markableViewmodel; - bool noDualWield; - bool flipKillIcon; - bool bNoPartialReload; - bool bSegmentedReload; - bool blocksProne; - bool silenced; - bool isRollingGrenade; - bool projExplosionEffectForceNormalUp; - bool bProjImpactExplode; - bool stickToPlayers; - bool stickToVehicles; - bool stickToTurrets; - bool hasDetonator; - bool disableFiring; - bool timedDetonation; - bool rotate; - bool holdButtonToThrow; - bool freezeMovementWhenFiring; - bool thermalScope; - bool altModeSameWeapon; - bool turretBarrelSpinEnabled; - bool missileConeSoundEnabled; - bool missileConeSoundPitchshiftEnabled; - bool missileConeSoundCrossfadeEnabled; - bool offhandHoldIsCancelable; - bool doNotAllowAttachmentsToOverrideSpread; - ScriptString stowTag; - XModel* stowOffsetModel; - }; - - struct AnimOverrideEntry - { - unsigned short attachment1; - unsigned short attachment2; - const char* overrideAnim; - const char* altmodeAnim; - unsigned int animTreeType; - int animTime; - int altTime; - }; - - struct SoundOverrideEntry - { - unsigned short attachment1; - unsigned short attachment2; - SndAliasCustom overrideSound; - SndAliasCustom altmodeSound; - unsigned int soundType; - }; - - struct FXOverrideEntry - { - unsigned short attachment1; - unsigned short attachment2; - FxEffectDef* overrideFX; - FxEffectDef* altmodeFX; - unsigned int fxType; - }; - - struct ReloadStateTimerEntry - { - int attachment; - int reloadAddTime; - int reloadStartAddTime; - }; - - struct NoteTrackToSoundEntry - { - int attachment; - ScriptString* notetrackSoundMapKeys; - ScriptString* notetrackSoundMapValues; - }; - - struct WeaponCompleteDef - { - const char* szInternalName; - WeaponDef* weapDef; - const char* szDisplayName; - ScriptString* hideTags; - WeaponAttachment** scopes; - WeaponAttachment** underBarrels; - WeaponAttachment** others; - const char** szXAnims; - unsigned int numAnimOverrides; - AnimOverrideEntry* animOverrides; - unsigned int numSoundOverrides; - SoundOverrideEntry* soundOverrides; - unsigned int numFXOverrides; - FXOverrideEntry* fxOverrides; - unsigned int numReloadStateTimerOverrides; - ReloadStateTimerEntry* reloadOverrides; - unsigned int numNotetrackOverrides; - NoteTrackToSoundEntry* notetrackOverrides; - float fAdsZoomFov; - int iAdsTransInTime; - int iAdsTransOutTime; - int iClipSize; - ImpactType impactType; - int iFireTime; - int iFireTimeAkimbo; - weaponIconRatioType_t dpadIconRatio; - float penetrateMultiplier; - float fAdsViewKickCenterSpeed; - float fHipViewKickCenterSpeed; - const char* szAltWeaponName; - int altWeapon; - int iAltRaiseTime; - int iAltRaiseTimeAkimbo; - Material* killIcon; - Material* dpadIcon; - int fireAnimLength; - int fireAnimLengthAkimbo; - int iFirstRaiseTime; - int iFirstRaiseTimeAkimbo; - int ammoDropStockMax; - float adsDofStart; - float adsDofEnd; - unsigned short accuracyGraphKnotCount[2]; - vec2_t* accuracyGraphKnots[2]; - bool motionTracker; - bool enhanced; - bool dpadIconShowsAmmo; - }; - - struct FxFloatRange - { - float base; - float amplitude; - }; - - struct FxIntRange - { - int base; - int amplitude; - }; - - struct FxElemVec3Range - { - float base[3]; - float amplitude[3]; - }; - - struct FxSpawnDefLooping - { - int intervalMsec; - int count; - }; - - struct FxSpawnDefOneShot - { - FxIntRange count; - }; - - union FxSpawnDef - { - FxSpawnDefLooping looping; - FxSpawnDefOneShot oneShot; - }; - - struct FxElemAtlas - { - unsigned char behavior; - unsigned char index; - unsigned char fps; - unsigned char loopCount; - unsigned char colIndexBits; - unsigned char rowIndexBits; - short entryCount; - }; - - struct FxElemVelStateInFrame - { - FxElemVec3Range velocity; - FxElemVec3Range totalDelta; - }; - - struct FxElemVelStateSample - { - FxElemVelStateInFrame local; - FxElemVelStateInFrame world; - }; - - struct FxElemVisualState - { - unsigned char color[4]; - float rotationDelta; - float rotationTotal; - float size[2]; - float scale; - }; - - struct FxElemVisStateSample - { - FxElemVisualState base; - FxElemVisualState amplitude; - }; - - struct FxElemMarkVisuals - { - Material* materials[2]; - }; - - union FxEffectDefRef - { - FxEffectDef* handle; - const char* name; - }; - - union FxElemVisuals - { - const void* anonymous; - Material* material; - XModel* model; - FxEffectDefRef effectDef; - const char* soundName; - GfxLightDef* lightDef; - }; - - union FxElemDefVisuals - { - FxElemMarkVisuals* markArray; - FxElemVisuals* array; - FxElemVisuals instance; - }; - - struct FxTrailVertex - { - float pos[2]; - float normal[2]; - float texCoord; - }; - - struct FxTrailDef - { - int scrollTimeMsec; - int repeatDist; - float invSplitDist; - float invSplitArcDist; - float invSplitTime; - int vertCount; - FxTrailVertex* verts; - int indCount; - unsigned short* inds; - }; - - struct FxSparkFountainDef - { - float gravity; - float bounceFrac; - float bounceRand; - float sparkSpacing; - float sparkLength; - int sparkCount; - float loopTime; - float velMin; - float velMax; - float velConeFrac; - float restSpeed; - float boostTime; - float boostFactor; - }; - - struct FxSpotLightDef - { - float fovInnerFraction; - float startRadius; - float endRadius; - float brightness; - float maxLength; - int exponent; - }; - - union FxElemExtendedDefPtr - { - FxTrailDef* trailDef; - FxSparkFountainDef* sparkFountainDef; - FxSpotLightDef* spotLightDef; - char* unknownDef; - }; - - enum FxElemType - { - FX_ELEM_TYPE_SPRITE_BILLBOARD = 0x0, - FX_ELEM_TYPE_SPRITE_ORIENTED = 0x1, - FX_ELEM_TYPE_TAIL = 0x2, - FX_ELEM_TYPE_TRAIL = 0x3, - FX_ELEM_TYPE_CLOUD = 0x4, - FX_ELEM_TYPE_SPARK_CLOUD = 0x5, - FX_ELEM_TYPE_SPARK_FOUNTAIN = 0x6, - FX_ELEM_TYPE_MODEL = 0x7, - FX_ELEM_TYPE_OMNI_LIGHT = 0x8, - FX_ELEM_TYPE_SPOT_LIGHT = 0x9, - FX_ELEM_TYPE_SOUND = 0xA, - FX_ELEM_TYPE_DECAL = 0xB, - FX_ELEM_TYPE_RUNNER = 0xC, - FX_ELEM_TYPE_COUNT = 0xD, - FX_ELEM_TYPE_LAST_SPRITE = 0x3, - FX_ELEM_TYPE_LAST_DRAWN = 0x9 - }; - - struct FxElemDef - { - int flags; - FxSpawnDef spawn; - FxFloatRange spawnRange; - FxFloatRange fadeInRange; - FxFloatRange fadeOutRange; - float spawnFrustumCullRadius; - FxIntRange spawnDelayMsec; - FxIntRange lifeSpanMsec; - FxFloatRange spawnOrigin[3]; - FxFloatRange spawnOffsetRadius; - FxFloatRange spawnOffsetHeight; - FxFloatRange spawnAngles[3]; - FxFloatRange angularVelocity[3]; - FxFloatRange initialRotation; - FxFloatRange gravity; - FxFloatRange reflectionFactor; - FxElemAtlas atlas; - unsigned char elemType; - unsigned char visualCount; - unsigned char velIntervalCount; - unsigned char visStateIntervalCount; - FxElemVelStateSample* velSamples; - FxElemVisStateSample* visSamples; - FxElemDefVisuals visuals; - Bounds collBounds; - FxEffectDefRef effectOnImpact; - FxEffectDefRef effectOnDeath; - FxEffectDefRef effectEmitted; - FxFloatRange emitDist; - FxFloatRange emitDistVariance; - FxElemExtendedDefPtr extended; - unsigned char sortOrder; - unsigned char lightingFrac; - unsigned char useItemClip; - unsigned char fadeInfo; - int randomSeed; - }; - - struct FxEffectDef - { - const char* name; - int flags; - int totalSize; - int msecLoopingLife; - int elemDefCountLooping; - int elemDefCountOneShot; - int elemDefCountEmission; - float occlusionQueryDepthBias; - int occlusionQueryFadeIn; - int occlusionQueryFadeOut; - FxFloatRange occlusionQueryScaleRange; - FxElemDef* elemDefs; - }; - - struct FxImpactEntry - { - FxEffectDef* nonflesh[31]; - FxEffectDef* flesh[4]; - }; - - struct FxImpactTable - { - const char* name; - FxImpactEntry* table; - }; - - struct SurfaceFxEntry - { - FxEffectDef* surfaceEffect[31]; - }; - - struct SurfaceFxTable - { - const char* name; - SurfaceFxEntry* table; - }; - - struct RawFile - { - const char* name; - int compressedLen; - int len; - const char* buffer; - }; - - struct ScriptFile - { - const char* name; - int compressedLen; - int len; - int bytecodeLen; - const char* buffer; - unsigned char* bytecode; - }; - - struct StringTableCell - { - const char* string; - int hash; - }; - - struct StringTable - { - const char* name; - int columnCount; - int rowCount; - StringTableCell* values; - }; - - enum LbColType - { - LBCOL_TYPE_NUMBER = 0x0, - LBCOL_TYPE_TIME = 0x1, - LBCOL_TYPE_LEVELXP = 0x2, - LBCOL_TYPE_PRESTIGE = 0x3, - LBCOL_TYPE_BIGNUMBER = 0x4, - LBCOL_TYPE_PERCENT = 0x5, - LBCOL_TYPE_TIME_FULL = 0x6, - LBCOL_TYPE_COUNT = 0x7 - }; - - enum LbAggType - { - LBAGG_TYPE_MIN = 0x0, - LBAGG_TYPE_MAX = 0x1, - LBAGG_TYPE_SUM = 0x2, - LBAGG_TYPE_LAST = 0x3, - LBAGG_TYPE_COUNT = 0x4 - }; - - struct LbColumnDef - { - const char* name; - int id; - int propertyId; - bool hidden; - const char* statName; - LbColType type; - int precision; - LbAggType agg; - int uiCalColX; - int uiCalColY; - }; - - enum LbUpdateType - { - LBUPDATE_TYPE_NORMAL = 0x0, - LBUPDATE_TYPE_RANK = 0x1, - LBUPDATE_TYPE_COMBINE = 0x2, - LBUPDATE_TYPE_COUNT = 0x3 - }; - - struct LeaderboardDef - { - const char* name; - int id; - int columnCount; - int xpColId; - int prestigeColId; - LbColumnDef* columns; - LbUpdateType updateType; - int trackTypes; - }; - - struct StructuredDataEnumEntry - { - const char* string; - unsigned short index; - }; - - struct StructuredDataEnum - { - int entryCount; - int reservedEntryCount; - StructuredDataEnumEntry* entries; - }; - - enum StructuredDataTypeCategory - { - DATA_INT = 0x0, - DATA_BYTE = 0x1, - DATA_BOOL = 0x2, - DATA_STRING = 0x3, - DATA_ENUM = 0x4, - DATA_STRUCT = 0x5, - DATA_INDEXED_ARRAY = 0x6, - DATA_ENUM_ARRAY = 0x7, - DATA_FLOAT = 0x8, - DATA_SHORT = 0x9, - DATA_COUNT = 0xA - }; - - union StructuredDataTypeUnion - { - unsigned int stringDataLength; - int enumIndex; - int structIndex; - int indexedArrayIndex; - int enumedArrayIndex; - }; - - struct StructuredDataType - { - StructuredDataTypeCategory type; - StructuredDataTypeUnion u; - }; - - enum StructuredDataValidationType - { - VALIDATION_NONE = 0x0, - VALIDATION_CONSTANT = 0x1, - VALIDATION_INCREASECLAMP = 0x2, - VALIDATION_INCREASESTRICT = 0x3, - VALIDATION_DELTACLAMP = 0x4, - VALIDATION_DELTASTRICT = 0x5, - VALIDATION_XP = 0x6, - VALIDATION_COUNT = 0x7 - }; - - struct StructuredDataStructProperty - { - const char* name; - StructuredDataType type; - unsigned int offset; - StructuredDataValidationType validation; - }; - - struct StructuredDataStruct - { - int propertyCount; - StructuredDataStructProperty* properties; - int size; - unsigned int bitOffset; - }; - - struct StructuredDataIndexedArray - { - int arraySize; - StructuredDataType elementType; - unsigned int elementSize; - }; - - struct StructuredDataEnumedArray - { - int enumIndex; - StructuredDataType elementType; - unsigned int elementSize; - }; - - struct StructuredDataDef - { - int version; - unsigned int formatChecksum; - int enumCount; - StructuredDataEnum* enums; - int structCount; - StructuredDataStruct* structs; - int indexedArrayCount; - StructuredDataIndexedArray* indexedArrays; - int enumedArrayCount; - StructuredDataEnumedArray* enumedArrays; - StructuredDataType rootType; - unsigned int size; - }; - - struct StructuredDataDefSet - { - const char* name; - unsigned int defCount; - StructuredDataDef* defs; - }; - - struct TracerDef - { - const char* name; - Material* material; - unsigned int drawInterval; - float speed; - float beamLength; - float beamWidth; - float screwRadius; - float screwDist; - float colors[5][4]; - }; - - enum VehicleType - { - VEH_WHEELS_4 = 0x0, - VEH_TANK = 0x1, - VEH_PLANE = 0x2, - VEH_BOAT = 0x3, - VEH_ARTILLERY = 0x4, - VEH_HELICOPTER = 0x5, - VEH_SNOWMOBILE = 0x6, - VEH_SUBMARINE = 0x7, - VEH_UGV = 0x8, - VEH_TYPE_COUNT = 0x9 - }; - - enum VehicleAxleType - { - VEH_AXLE_FRONT = 0x0, - VEH_AXLE_REAR = 0x1, - VEH_AXLE_ALL = 0x2, - VEH_AXLE_COUNT = 0x3 - }; - - enum VehCamZOffsetMode - { - VEHCAM_ZMODE_WORLD = 0x0, - VEHCAM_ZMODE_VEHICLE = 0x1, - VEHCAM_ZMODE_VIEW = 0x2, - VEHCAM_ZMODE_COUNT = 0x3 - }; - - struct VehiclePhysDef - { - int physicsEnabled; - const char* physPresetName; - PhysPreset* physPreset; - const char* accelGraphName; - VehicleAxleType steeringAxle; - VehicleAxleType powerAxle; - VehicleAxleType brakingAxle; - float topSpeed; - float reverseSpeed; - float maxVelocity; - float maxPitch; - float maxRoll; - float suspensionTravelFront; - float suspensionTravelRear; - float suspensionStrengthFront; - float suspensionDampingFront; - float suspensionStrengthRear; - float suspensionDampingRear; - float frictionBraking; - float frictionCoasting; - float frictionTopSpeed; - float frictionSide; - float frictionSideRear; - float velocityDependentSlip; - float rollStability; - float rollResistance; - float pitchResistance; - float yawResistance; - float uprightStrengthPitch; - float uprightStrengthRoll; - float targetAirPitch; - float airYawTorque; - float airPitchTorque; - float minimumMomentumForCollision; - float collisionLaunchForceScale; - float wreckedMassScale; - float wreckedBodyFriction; - float minimumJoltForNotify; - float slipThresholdFront; - float slipThresholdRear; - float slipFricScaleFront; - float slipFricScaleRear; - float slipFricRateFront; - float slipFricRateRear; - float slipYawTorque; - }; - - struct VehicleDef - { - const char* name; - VehicleType type; - const char* useHintString; - int health; - int quadBarrel; - float texScrollScale; - float topSpeed; - float accel; - float rotRate; - float rotAccel; - float maxBodyPitch; - float maxBodyRoll; - int fakeBodyStabilizer; - float fakeBodyAccelPitch; - float fakeBodyAccelRoll; - float fakeBodyVelPitch; - float fakeBodyVelRoll; - float fakeBodySideVelPitch; - float fakeBodyPitchStrength; - float fakeBodyRollStrength; - float fakeBodyPitchDampening; - float fakeBodyRollDampening; - float fakeBodyBoatRockingAmplitude; - float fakeBodyBoatRockingPeriod; - float fakeBodyBoatRockingRotationPeriod; - float fakeBodyBoatRockingFadeoutSpeed; - float boatBouncingMinForce; - float boatBouncingMaxForce; - float boatBouncingRate; - float boatBouncingFadeinSpeed; - float boatBouncingFadeoutSteeringAngle; - float collisionDamage; - float collisionSpeed; - float killcamOffset[3]; - int playerProtected; - int bulletDamage; - int armorPiercingDamage; - int grenadeDamage; - int projectileDamage; - int projectileSplashDamage; - int heavyExplosiveDamage; - VehiclePhysDef vehPhysDef; - float boostDuration; - float boostRechargeTime; - float boostAcceleration; - float suspensionTravel; - float maxSteeringAngle; - float steeringLerp; - float minSteeringScale; - float minSteeringSpeed; - float vehHelicopterBoundsRadius; - float vehHelicopterMaxSpeed; - float vehHelicopterMaxSpeedVertical; - float vehHelicopterMaxAccel; - float vehHelicopterMaxAccelVertical; - float vehHelicopterDecelerationFwd; - float vehHelicopterDecelerationSide; - float vehHelicopterDecelerationUp; - float vehHelicopterMaxYawRate; - float vehHelicopterMaxYawAccel; - float vehHelicopterTiltFromVelocity; - float vehHelicopterTiltFromControllerAxes; - float vehHelicopterTiltFromAcceleration; - float vehHelicopterTiltFromDeceleration; - float vehHelicopterTiltFromFwdAndYaw_VelAtMaxTilt; - float vehHelicopterTiltFromFwdAndYaw; - float vehHelicopterTiltMomentum; - float vehHelicopterTiltSpeed; - float vehHelicopterMaxPitch; - float vehHelicopterMaxRoll; - float vehHelicopterHoverSpeedThreshold; - float vehHelicopterJitterJerkyness; - float vehHelicopterLookaheadTime; - int vehHelicopterSoftCollisions; - int camLookEnabled; - int camRelativeControl; - float camLerp; - float camHeight; - float camRadius; - float camPitchInfluence; - float camYawInfluence; - float camRollInfluence; - float camFovIncrease; - float camFovOffset; - float camFovSpeed; - float camReturnSpeed; - float camReturnLerp; - int vehCam_UseGDT; - float vehCam_anglesPitch; - float vehCam_anglesYaw; - float vehCam_anglesRoll; - float vehCam_offsetX; - float vehCam_offsetY; - float vehCam_offsetZ; - float vehCam_radius; - float vehCam_speedInfluence; - float vehCam_pitchTurnRate; - float vehCam_pitchClamp; - float vehCam_yawTurnRate; - float vehCam_yawClamp; - VehCamZOffsetMode vehCam_zOffsetMode; - float vehCam_anglesPitch3P; - float vehCam_anglesYaw3P; - float vehCam_anglesRoll3P; - float vehCam_offsetX3P; - float vehCam_offsetY3P; - float vehCam_offsetZ3P; - float vehCam_radius3P; - float vehCam_speedInfluence3P; - float vehCam_pitchTurnRate3P; - float vehCam_pitchClamp3P; - float vehCam_yawTurnRate3P; - float vehCam_yawClamp3P; - VehCamZOffsetMode vehCam_zOffsetMode3P; - const char* turretWeaponName; - WeaponCompleteDef* turretWeapon; - float turretHorizSpanLeft; - float turretHorizSpanRight; - float turretVertSpanUp; - float turretVertSpanDown; - float turretHorizResistLeft; - float turretHorizResistRight; - float turretVertResistUp; - float turretVertResistDown; - float turretRotRate; - SndAliasCustom turretSpinSnd; - SndAliasCustom turretStopSnd; - int trophyEnabled; - float trophyRadius; - float trophyInactiveRadius; - int trophyAmmoCount; - float trophyReloadTime; - ScriptString trophyTags[4]; - FxEffectDef* trophyExplodeFx; - FxEffectDef* trophyFlashFx; - Material* compassFriendlyIcon; - Material* compassEnemyIcon; - Material* compassFriendlyAltIcon; - Material* compassEnemyAltIcon; - int compassIconWidth; - int compassIconHeight; - SndAliasCustom idleLowSnd; - SndAliasCustom idleHighSnd; - SndAliasCustom engineLowSnd; - SndAliasCustom engineHighSnd; - float engineSndSpeed; - ScriptString audioOriginTag; - SndAliasCustom idleLowSndAlt; - SndAliasCustom idleHighSndAlt; - SndAliasCustom engineLowSndAlt; - SndAliasCustom engineHighSndAlt; - float engineSndSpeedAlt; - ScriptString audioOriginTagAlt; - SndAliasCustom turretSpinSndAlt; - SndAliasCustom turretStopSndAlt; - SndAliasCustom engineStartUpSnd; - int engineStartUpLength; - SndAliasCustom engineShutdownSnd; - SndAliasCustom engineIdleSnd; - SndAliasCustom engineSustainSnd; - SndAliasCustom engineRampUpSnd; - int engineRampUpLength; - SndAliasCustom engineRampDownSnd; - int engineRampDownLength; - SndAliasCustom suspensionSoftSnd; - float suspensionSoftCompression; - SndAliasCustom suspensionHardSnd; - float suspensionHardCompression; - SndAliasCustom collisionSnd; - float collisionBlendSpeed; - SndAliasCustom speedSnd; - float speedSndBlendSpeed; - const char* surfaceSndPrefix; - SndAliasCustom surfaceSnds[31]; - float surfaceSndBlendSpeed; - float slideVolume; - float slideBlendSpeed; - float inAirPitch; - }; - - struct cmodel2_t - { - Bounds bounds; - float radius; - ClipInfo* info; - cLeaf_t leaf; - }; - - struct AddonMapEnts - { - const char* name; - char* entityString; - int numEntityChars; - MapTriggers trigger; - ClipInfo* info; - unsigned int numSubModels; - cmodel2_t* cmodels; - GfxBrushModel* models; - }; + GfxImageLoadDef *loadDef; +}; + +struct Picmip { + char platform[2]; +}; + +struct CardMemory { + int platform[2]; +}; + +struct GfxImage { + GfxTexture texture; + char mapType; + char semantic; + char category; + unsigned char flags; + Picmip picmip; + bool noPicmip; + char track; + CardMemory cardMemory; + unsigned short width; + unsigned short height; + unsigned short depth; + unsigned char levelCount; + const char *name; +}; + +enum snd_alias_type_t { SAT_UNKNOWN = 0x0, SAT_LOADED = 0x1, SAT_STREAMED = 0x2, SAT_VOICED = 0x3, SAT_COUNT = 0x4 }; + +struct StreamedSound { + const char *dir; + const char *name; +}; + +struct AILSOUNDINFO { + int format; + const void *data_ptr; + unsigned int data_len; + unsigned int rate; + int bits; + int channels; + unsigned int samples; + unsigned int block_size; + const void *initial_ptr; +}; + +struct MssSound { + AILSOUNDINFO info; + char *data; +}; + +struct LoadedSound { + const char *name; + MssSound sound; +}; + +union SoundFileRef { + LoadedSound *loadSnd; + StreamedSound streamSnd; +}; + +struct SoundFile { + unsigned char type; + unsigned char exists; + SoundFileRef u; +}; + +struct MSSSpeakerLevels { + int speaker; + int numLevels; + float levels[2]; +}; + +struct MSSChannelMap { + int speakerCount; + MSSSpeakerLevels speakers[6]; +}; + +struct SpeakerMap { + bool isDefault; + const char *name; + MSSChannelMap channelMaps[2][2]; +}; + +struct SndCurve { + const char *filename; + unsigned short knotCount; + float knots[16][2]; +}; + +struct snd_alias_t { + const char *aliasName; + const char *subtitle; + const char *secondaryAliasName; + const char *chainAliasName; + const char *mixerGroup; + SoundFile *soundFile; + int sequence; + float volMin; + float volMax; + int volModIndex; + float pitchMin; + float pitchMax; + float distMin; + float distMax; + float velocityMin; + int flags; + unsigned char masterPriority; + float masterPercentage; + float slavePercentage; + float probability; + float lfePercentage; + float centerPercentage; + int startDelay; + SndCurve *volumeFalloffCurve; + float envelopMin; + float envelopMax; + float envelopPercentage; + SpeakerMap *speakerMap; +}; + +struct snd_alias_list_t { + const char *aliasName; + snd_alias_t *head; + int count; +}; + +typedef unsigned short LeafBrush; + +struct ClipMaterial { + const char *name; + int surfaceFlags; + int contents; +}; + +struct cLeafBrushNodeLeaf_t { + LeafBrush *brushes; +}; + +struct cLeafBrushNodeChildren_t { + float dist; + float range; + unsigned short childOffset[2]; +}; + +union cLeafBrushNodeData_t { + cLeafBrushNodeLeaf_t leaf; + cLeafBrushNodeChildren_t children; +}; + +struct cLeafBrushNode_s { + unsigned char axis; + short leafBrushCount; + int contents; + cLeafBrushNodeData_t data; +}; + +struct cbrush_t { + unsigned short numsides; + unsigned short glassPieceIndex; + cbrushside_t *sides; + cbrushedge_t *baseAdjacentSide; + short axialMaterialNum[2][3]; + unsigned char firstAdjacentSideOffsets[2][3]; + unsigned char edgeCount[2][3]; +}; + +typedef tdef_align(128) cbrush_t cbrush_array_t; +typedef tdef_align(128) Bounds BoundsArray; + +struct ClipInfo { + int planeCount; + cplane_s *planes; + unsigned int numMaterials; + ClipMaterial *materials; + unsigned int numBrushSides; + cbrushside_t *brushsides; + unsigned int numBrushEdges; + cbrushedge_t *brushEdges; + unsigned int leafbrushNodesCount; + cLeafBrushNode_s *leafbrushNodes; + unsigned int numLeafBrushes; + LeafBrush *leafbrushes; + unsigned short numBrushes; + cbrush_array_t *brushes; + BoundsArray *brushBounds; + int *brushContents; +}; + +struct cStaticModel_s { + XModel *xmodel; + float origin[3]; + float invScaledAxis[3][3]; + Bounds absBounds; +}; + +struct cNode_t { + cplane_s *plane; + short children[2]; +}; + +struct cLeaf_t { + unsigned short firstCollAabbIndex; + unsigned short collAabbCount; + int brushContents; + int terrainContents; + Bounds bounds; + int leafBrushNode; +}; + +struct CollisionBorder { + float distEq[3]; + float zBase; + float zSlope; + float start; + float length; +}; + +struct CollisionPartition { + unsigned char triCount; + unsigned char borderCount; + unsigned char firstVertSegment; + int firstTri; + CollisionBorder *borders; +}; + +union CollisionAabbTreeIndex { + int firstChildIndex; + int partitionIndex; +}; + +struct type_align(16) CollisionAabbTree { + float midPoint[3]; + unsigned short materialIndex; + unsigned short childCount; + float halfSize[3]; + CollisionAabbTreeIndex u; +}; + +struct cmodel_t { + Bounds bounds; + float radius; + ClipInfo *info; + cLeaf_t leaf; +}; + +struct Stage { + const char *name; + float origin[3]; + unsigned short triggerIndex; + unsigned char sunPrimaryLightIndex; +}; + +struct TriggerModel { + int contents; + unsigned short hullCount; + unsigned short firstHull; +}; + +struct TriggerHull { + Bounds bounds; + int contents; + unsigned short slabCount; + unsigned short firstSlab; +}; + +struct TriggerSlab { + float dir[3]; + float midPoint; + float halfSize; +}; + +struct MapTriggers { + unsigned int count; + TriggerModel *models; + unsigned int hullCount; + TriggerHull *hulls; + unsigned int slabCount; + TriggerSlab *slabs; +}; + +struct SModelAabbNode { + Bounds bounds; + unsigned short firstChild; + unsigned short childCount; +}; + +enum DynEntityType { DYNENT_TYPE_INVALID = 0x0, DYNENT_TYPE_CLUTTER = 0x1, DYNENT_TYPE_DESTRUCT = 0x2, DYNENT_TYPE_HINGE = 0x3, DYNENT_TYPE_COUNT = 0x4 }; + +struct GfxPlacement { + float quat[4]; + float origin[3]; +}; + +struct DynEntityHingeDef { + float axisOrigin[3]; + float axisDir[3]; + bool isLimited; + float angleMin; + float angleMax; + float momentOfInertia; + float friction; +}; + +struct DynEntityDef { + DynEntityType type; + GfxPlacement pose; + XModel *xModel; + unsigned short brushModel; + unsigned short physicsBrushModel; + FxEffectDef *destroyFx; + PhysPreset *physPreset; + int health; + DynEntityHingeDef *hinge; + PhysMass mass; + int contents; +}; + +struct DynEntityPose { + GfxPlacement pose; + float radius; +}; + +struct Hinge { + float angle; + float quat[4]; + float angularVel; + float torqueAccum; + bool active; + float autoDisableTimeLeft; + DynEntityHingeDef *def; + PhysPreset *physPreset; + float centerOfMassRelToAxisOriginAtAngleZero[3]; +}; + +struct DynEntityClient { + int physObjId; + unsigned short flags; + unsigned short lightingHandle; + int health; + Hinge *hinge; +}; + +struct DynEntityColl { + unsigned short sector; + unsigned short nextEntInSector; + float linkMins[2]; + float linkMaxs[2]; +}; + +struct clipMap_t { + const char *name; + int isInUse; + ClipInfo info; + ClipInfo *pInfo; + unsigned int numStaticModels; + cStaticModel_s *staticModelList; + unsigned int numNodes; + cNode_t *nodes; + unsigned int numLeafs; + cLeaf_t *leafs; + unsigned int vertCount; + vec3_t *verts; + int triCount; + unsigned short *triIndices; + unsigned char *triEdgeIsWalkable; + int borderCount; + CollisionBorder *borders; + int partitionCount; + CollisionPartition *partitions; + int aabbTreeCount; + CollisionAabbTree *aabbTrees; + unsigned int numSubModels; + cmodel_t *cmodels; + MapEnts *mapEnts; + Stage *stages; + unsigned char stageCount; + MapTriggers stageTrigger; + unsigned short smodelNodeCount; + SModelAabbNode *smodelNodes; + unsigned short dynEntCount[2]; + DynEntityDef *dynEntDefList[2]; + DynEntityPose *dynEntPoseList[2]; + DynEntityClient *dynEntClientList[2]; + DynEntityColl *dynEntCollList[2]; + unsigned int checksum; + unsigned char padding[20]; +}; + +struct ComPrimaryLight { + unsigned char type; + unsigned char canUseShadowMap; + unsigned char exponent; + unsigned char unused; + float color[3]; + float dir[3]; + float up[3]; + float origin[3]; + float radius; + float cosHalfFovOuter; + float cosHalfFovInner; + float cosHalfFovExpanded; + float rotationLimit; + float translationLimit; + const char *defName; +}; + +struct ComWorld { + const char *name; + int isInUse; + unsigned int primaryLightCount; + ComPrimaryLight *primaryLights; +}; + +struct G_GlassName { + char *nameStr; + unsigned short name; + unsigned short pieceCount; + unsigned short *pieceIndices; +}; + +struct G_GlassPiece { + unsigned short damageTaken; + unsigned short collapseTime; + int lastStateChangeTime; + unsigned char impactDir; + unsigned char impactPos[2]; +}; + +struct G_GlassData { + G_GlassPiece *glassPieces; + unsigned int pieceCount; + unsigned short damageToWeaken; + unsigned short damageToDestroy; + unsigned int glassNameCount; + G_GlassName *glassNames; + unsigned char pad[108]; +}; + +struct GlassWorld { + const char *name; + G_GlassData *g_glassData; +}; + +struct pathlink_s { + float fDist; + unsigned short nodeNum; + unsigned char disconnectCount; + unsigned char negotiationLink; + unsigned char flags; + unsigned char ubBadPlaceCount[3]; +}; + +enum nodeType { + NODE_ERROR = 0x0, + NODE_PATHNODE = 0x1, + NODE_COVER_STAND = 0x2, + NODE_COVER_CROUCH = 0x3, + NODE_COVER_CROUCH_WINDOW = 0x4, + NODE_COVER_PRONE = 0x5, + NODE_COVER_RIGHT = 0x6, + NODE_COVER_LEFT = 0x7, + NODE_AMBUSH = 0x8, + NODE_EXPOSED = 0x9, + NODE_CONCEALMENT_STAND = 0xA, + NODE_CONCEALMENT_CROUCH = 0xB, + NODE_CONCEALMENT_PRONE = 0xC, + NODE_DOOR = 0xD, + NODE_DOOR_INTERIOR = 0xE, + NODE_SCRIPTED = 0xF, + NODE_NEGOTIATION_BEGIN = 0x10, + NODE_NEGOTIATION_END = 0x11, + NODE_TURRET = 0x12, + NODE_GUARD = 0x13, + NODE_NUMTYPES = 0x14, + NODE_DONTLINK = 0x14 +}; + +enum PathNodeErrorCode { + PNERR_NONE = 0x0, + PNERR_INSOLID = 0x1, + PNERR_FLOATING = 0x2, + PNERR_NOLINK = 0x3, + PNERR_DUPLICATE = 0x4, + PNERR_NOSTANCE = 0x5, + PNERR_INVALIDDOOR = 0x6, + PNERR_NOANGLES = 0x7, + PNERR_BADPLACEMENT = 0x8, + NUM_PATH_NODE_ERRORS = 0x9 +}; + +struct pathnode_constant_t { + nodeType type; + unsigned short spawnflags; + ScriptString targetname; + ScriptString script_linkName; + ScriptString script_noteworthy; + ScriptString target; + ScriptString animscript; + int animscriptfunc; + float vOrigin[3]; + float fAngle; + float forward[2]; + float minUseDistSq; + PathNodeErrorCode error; + short wOverlapNode[2]; + unsigned short totalLinkCount; + pathlink_s *Links; +}; + +struct pathnode_dynamic_t { + void *pOwner; + int iFreeTime; + int iValidTime[3]; + int dangerousNodeTime[3]; + int inPlayerLOSTime; + short wLinkCount; + short wOverlapCount; + short turretEntNumber; + unsigned char userCount; + bool hasBadPlaceLink; +}; + +struct pathnode_t; + +struct pathnode_transient_t { + int iSearchFrame; + pathnode_t *pNextOpen; + pathnode_t *pPrevOpen; + pathnode_t *pParent; + float fCost; + float fHeuristic; + union { + float nodeCost; + int linkIndex; + }; +}; + +struct pathnode_t { + pathnode_constant_t constant; + pathnode_dynamic_t dynamic; + pathnode_transient_t transient; +}; + +struct type_align(16) pathbasenode_t { + float vOrigin[3]; + unsigned int type; +}; + +struct pathnode_tree_nodes_t { + int nodeCount; + unsigned short *nodes; +}; + +struct pathnode_tree_t; + +union pathnode_tree_info_t { + pathnode_tree_t *child[2]; + pathnode_tree_nodes_t s; +}; + +struct pathnode_tree_t { + int axis; + float dist; + pathnode_tree_info_t u; +}; + +struct PathData { + const char *name; + unsigned int nodeCount; + pathnode_t *nodes; + pathbasenode_t *basenodes; + unsigned int chainNodeCount; + unsigned short *chainNodeForNode; + unsigned short *nodeForChainNode; + int visBytes; + unsigned char *pathVis; + int nodeTreeCount; + pathnode_tree_t *nodeTree; +}; + +struct VehicleTrackObstacle { + float origin[2]; + float radius; +}; + +struct VehicleTrackSector { + float startEdgeDir[2]; + float startEdgeDist; + float leftEdgeDir[2]; + float leftEdgeDist; + float rightEdgeDir[2]; + float rightEdgeDist; + float sectorLength; + float sectorWidth; + float totalPriorLength; + float totalFollowingLength; + VehicleTrackObstacle *obstacles; + unsigned int obstacleCount; +}; + +struct VehicleTrackSegment { + const char *targetName; + VehicleTrackSector *sectors; + unsigned int sectorCount; + VehicleTrackSegment **nextBranches; + unsigned int nextBranchesCount; + VehicleTrackSegment **prevBranches; + unsigned int prevBranchesCount; + float endEdgeDir[2]; + float endEdgeDist; + float totalLength; +}; + +struct VehicleTrack { + const char *name; + VehicleTrackSegment *segments; + unsigned int segmentCount; +}; + +struct ClientTriggerAabbNode { + Bounds bounds; + unsigned short firstChild; + unsigned short childCount; +}; + +struct ClientTriggers { + MapTriggers trigger; + unsigned short numClientTriggerNodes; + ClientTriggerAabbNode *clientTriggerAabbTree; + unsigned int triggerStringLength; + char *triggerString; + unsigned short *triggerStringOffsets; + unsigned char *triggerType; + vec3_t *origins; + float *scriptDelay; + short *audioTriggers; +}; + +struct MapEnts { + const char *name; + char *entityString; + int numEntityChars; + MapTriggers trigger; + ClientTriggers clientTrigger; +}; + +struct FxGlassDef { + float halfThickness; + float texVecs[2][2]; + GfxColor color; + Material *material; + Material *materialShattered; + PhysPreset *physPreset; +}; + +struct FxSpatialFrame { + float quat[4]; + float origin[3]; +}; + +union FxGlassPiecePlace { + struct { + FxSpatialFrame frame; + float radius; + }; + unsigned int nextFree; +}; + +struct FxGlassPieceState { + float texCoordOrigin[2]; + unsigned int supportMask; + unsigned short initIndex; + unsigned short geoDataStart; + unsigned char defIndex; + unsigned char pad[5]; + unsigned char vertCount; + unsigned char holeDataCount; + unsigned char crackDataCount; + unsigned char fanDataCount; + unsigned short flags; + float areaX2; +}; + +struct FxGlassPieceDynamics { + int fallTime; + int physObjId; + int physJointId; + float vel[3]; + float avel[3]; +}; + +struct FxGlassVertex { + short x; + short y; +}; + +struct FxGlassHoleHeader { + unsigned short uniqueVertCount; + unsigned char touchVert; + unsigned char pad[1]; +}; + +struct FxGlassCrackHeader { + unsigned short uniqueVertCount; + unsigned char beginVertIndex; + unsigned char endVertIndex; +}; + +union type_align(4) FxGlassGeometryData { + FxGlassVertex vert; + FxGlassHoleHeader hole; + FxGlassCrackHeader crack; + unsigned char asBytes[4]; + short anonymous[2]; +}; + +struct FxGlassInitPieceState { + FxSpatialFrame frame; + float radius; + float texCoordOrigin[2]; + unsigned int supportMask; + float areaX2; + unsigned char defIndex; + unsigned char vertCount; + unsigned char fanDataCount; + unsigned char pad[1]; +}; + +struct FxGlassSystem { + int time; + int prevTime; + unsigned int defCount; + unsigned int pieceLimit; + unsigned int pieceWordCount; + unsigned int initPieceCount; + unsigned int cellCount; + unsigned int activePieceCount; + unsigned int firstFreePiece; + unsigned int geoDataLimit; + unsigned int geoDataCount; + unsigned int initGeoDataCount; + FxGlassDef *defs; + FxGlassPiecePlace *piecePlaces; + FxGlassPieceState *pieceStates; + FxGlassPieceDynamics *pieceDynamics; + FxGlassGeometryData *geoData; + raw_uint *isInUse; + raw_uint *cellBits; + raw_byte16 *visData; + vec3_t *linkOrg; + raw_float16 *halfThickness; + unsigned short *lightingHandles; + FxGlassInitPieceState *initPieceStates; + FxGlassGeometryData *initGeoData; + bool needToCompactData; + unsigned char initCount; + float effectChanceAccum; + int lastPieceDeletionTime; +}; + +struct FxWorld { + const char *name; + FxGlassSystem glassSys; +}; + +struct GfxSky { + int skySurfCount; + int *skyStartSurfs; + GfxImage *skyImage; + unsigned char skySamplerState; +}; + +struct GfxWorldDpvsPlanes { + int cellCount; + cplane_s *planes; + unsigned short *nodes; + raw_uint *sceneEntCellBits; +}; + +struct GfxCellTreeCount { + int aabbTreeCount; +}; + +typedef unsigned short StaticModelIndex; + +struct GfxAabbTree { + Bounds bounds; + unsigned short childCount; + unsigned short surfaceCount; + unsigned short startSurfIndex; + unsigned short surfaceCountNoDecal; + unsigned short startSurfIndexNoDecal; + unsigned short smodelIndexCount; + StaticModelIndex *smodelIndexes; + int childrenOffset; +}; + +struct GfxCellTree { + GfxAabbTree *aabbTree; +}; + +struct GfxPortal; + +struct GfxPortalWritable { + bool isQueued; + bool isAncestor; + unsigned char recursionDepth; + unsigned char hullPointCount; + float (*hullPoints)[2]; + GfxPortal *queuedParent; +}; + +struct DpvsPlane { + float coeffs[4]; +}; + +struct GfxPortal { + GfxPortalWritable writable; + DpvsPlane plane; + vec3_t *vertices; + unsigned short cellIndex; + unsigned char vertexCount; + float hullAxis[2][3]; +}; + +struct GfxCell { + Bounds bounds; + int portalCount; + GfxPortal *portals; + unsigned char reflectionProbeCount; + unsigned char *reflectionProbes; + unsigned char reflectionProbeReferenceCount; + unsigned char *reflectionProbeReferences; +}; + +struct GfxReflectionProbe { + float origin[3]; +}; + +struct GfxReflectionProbeReferenceOrigin { + float origin[3]; +}; + +struct GfxReflectionProbeReference { + unsigned char index; +}; + +struct GfxLightmapArray { + GfxImage *primary; + GfxImage *secondary; +}; + +struct GfxWorldVertex { + float xyz[3]; + float binormalSign; + GfxColor color; + float texCoord[2]; + float lmapCoord[2]; + PackedUnitVec normal; + PackedUnitVec tangent; +}; + +struct GfxWorldVertexData { + GfxWorldVertex *vertices; + void *worldVb; +}; + +struct GfxWorldVertexLayerData { + unsigned char *data; + void *layerVb; +}; + +struct GfxWorldDraw { + unsigned int reflectionProbeCount; + GfxImage **reflectionProbes; + GfxReflectionProbe *reflectionProbeOrigins; + GfxTexture *reflectionProbeTextures; + unsigned int reflectionProbeReferenceCount; + GfxReflectionProbeReferenceOrigin *reflectionProbeReferenceOrigins; + GfxReflectionProbeReference *reflectionProbeReferences; + int lightmapCount; + GfxLightmapArray *lightmaps; + GfxTexture *lightmapPrimaryTextures; + GfxTexture *lightmapSecondaryTextures; + GfxImage *lightmapOverridePrimary; + GfxImage *lightmapOverrideSecondary; + unsigned int vertexCount; + GfxWorldVertexData vd; + unsigned int vertexLayerDataSize; + GfxWorldVertexLayerData vld; + unsigned int indexCount; + r_index_t *indices; +}; + +struct type_align(4) GfxLightGridEntry { + unsigned short colorsIndex; + unsigned char primaryLightIndex; + unsigned char needsTrace; +}; + +struct type_align(4) GfxLightGridColors { unsigned char rgb[56][3]; }; + +struct GfxLightGrid { + bool hasLightRegions; + bool useSkyForLowZ; + unsigned int lastSunPrimaryLightIndex; + unsigned short mins[3]; + unsigned short maxs[3]; + unsigned int rowAxis; + unsigned int colAxis; + unsigned short *rowDataStart; + unsigned int rawRowDataSize; + unsigned char *rawRowData; + unsigned int entryCount; + GfxLightGridEntry *entries; + unsigned int colorCount; + GfxLightGridColors *colors; +}; + +struct GfxBrushModelWritable { + Bounds bounds; +}; + +struct type_align(4) GfxBrushModel { + GfxBrushModelWritable writable; + Bounds bounds; + float radius; + unsigned short surfaceCount; + unsigned short startSurfIndex; + uint16_t surfaceCountNoDecal; +}; + +struct MaterialMemory { + Material *material; + int memory; +}; + +struct sunflare_t { + bool hasValidData; + Material *spriteMaterial; + Material *flareMaterial; + float spriteSize; + float flareMinSize; + float flareMinDot; + float flareMaxSize; + float flareMaxDot; + float flareMaxAlpha; + int flareFadeInTime; + int flareFadeOutTime; + float blindMinDot; + float blindMaxDot; + float blindMaxDarken; + int blindFadeInTime; + int blindFadeOutTime; + float glareMinDot; + float glareMaxDot; + float glareMaxLighten; + int glareFadeInTime; + int glareFadeOutTime; + float sunFxPosition[3]; +}; + +struct XModelDrawInfo { + unsigned char hasGfxEntIndex; + unsigned char lod; + unsigned short surfId; +}; + +struct GfxSceneDynModel { + XModelDrawInfo info; + unsigned short dynEntId; +}; + +struct BModelDrawInfo { + unsigned short surfId; +}; + +struct type_align(4) GfxSceneDynBrush { + BModelDrawInfo info; + unsigned short dynEntId; +}; + +struct GfxShadowGeometry { + unsigned short surfaceCount; + unsigned short smodelCount; + unsigned short *sortedSurfIndex; + unsigned short *smodelIndex; +}; + +struct GfxLightRegionAxis { + float dir[3]; + float midPoint; + float halfSize; +}; + +struct GfxLightRegionHull { + float kdopMidPoint[9]; + float kdopHalfSize[9]; + unsigned int axisCount; + GfxLightRegionAxis *axis; +}; + +struct GfxLightRegion { + unsigned int hullCount; + GfxLightRegionHull *hulls; +}; + +struct GfxStaticModelInst { + Bounds bounds; + float lightingOrigin[3]; +}; + +struct srfTriangles_t { + unsigned int vertexLayerData; + unsigned int firstVertex; + unsigned short vertexCount; + unsigned short triCount; + unsigned int baseIndex; +}; + +struct GfxSurfaceLightingAndFlagsFields { + unsigned char lightmapIndex; + unsigned char reflectionProbeIndex; + unsigned char primaryLightIndex; + unsigned char flags; +}; + +union GfxSurfaceLightingAndFlags { + GfxSurfaceLightingAndFlagsFields fields; + unsigned int packed; +}; + +struct GfxSurface { + srfTriangles_t tris; + Material *material; + GfxSurfaceLightingAndFlags laf; +}; + +struct GfxSurfaceBounds { + Bounds bounds; +}; + +struct GfxPackedPlacement { + float origin[3]; + float axis[3][3]; + float scale; +}; + +struct GfxStaticModelDrawInst { + GfxPackedPlacement placement; + XModel *model; + unsigned short cullDist; + unsigned short lightingHandle; + unsigned char reflectionProbeIndex; + unsigned char primaryLightIndex; + unsigned char flags; + unsigned char firstMtlSkinIndex; + GfxColor groundLighting; + uint16_t cacheId[4]; +}; + +struct GfxWorldDpvsStatic { + unsigned int smodelCount; + unsigned int staticSurfaceCount; + unsigned int staticSurfaceCountNoDecal; + unsigned int litOpaqueSurfsBegin; + unsigned int litOpaqueSurfsEnd; + unsigned int litTransSurfsBegin; + unsigned int litTransSurfsEnd; + unsigned int shadowCasterSurfsBegin; + unsigned int shadowCasterSurfsEnd; + unsigned int emissiveSurfsBegin; + unsigned int emissiveSurfsEnd; + unsigned int smodelVisDataCount; + unsigned int surfaceVisDataCount; + raw_byte *smodelVisData[3]; + raw_byte *surfaceVisData[3]; + unsigned short *sortedSurfIndex; + GfxStaticModelInst *smodelInsts; + GfxSurface *surfaces; + GfxSurfaceBounds *surfacesBounds; + GfxStaticModelDrawInst *smodelDrawInsts; + GfxDrawSurf *surfaceMaterials; + raw_uint128 *surfaceCastsSunShadow; + volatile long usageCount; +}; + +struct GfxWorldDpvsDynamic { + unsigned int dynEntClientWordCount[2]; + unsigned int dynEntClientCount[2]; + raw_uint *dynEntCellBits[2]; + raw_byte16 *dynEntVisData[2][3]; +}; + +struct GfxHeroOnlyLight { + unsigned char type; + unsigned char unused[3]; + float color[3]; + float dir[3]; + float up[3]; + float origin[3]; + float radius; + float cosHalfFovOuter; + float cosHalfFovInner; + int exponent; +}; + +typedef tdef_align(128) GfxCellTree GfxCellTree128; + +struct GfxWorld { + const char *name; + const char *baseName; + int planeCount; + int nodeCount; + unsigned int surfaceCount; + int skyCount; + GfxSky *skies; + unsigned int lastSunPrimaryLightIndex; + unsigned int primaryLightCount; + unsigned int sortKeyLitDecal; + unsigned int sortKeyEffectDecal; + unsigned int sortKeyEffectAuto; + unsigned int sortKeyDistortion; + GfxWorldDpvsPlanes dpvsPlanes; + int /*GfxCellTreeCount*/ *aabbTreeCounts; + GfxCellTree128 *aabbTrees; + GfxCell *cells; + GfxWorldDraw draw; + GfxLightGrid lightGrid; + int modelCount; + GfxBrushModel *models; + Bounds bounds; + unsigned int checksum; + int materialMemoryCount; + MaterialMemory *materialMemory; + sunflare_t sun; + float outdoorLookupMatrix[4][4]; + GfxImage *outdoorImage; + raw_uint *cellCasterBits; + raw_uint *cellHasSunLitSurfsBits; + GfxSceneDynModel *sceneDynModel; + GfxSceneDynBrush *sceneDynBrush; + raw_uint *primaryLightEntityShadowVis; + raw_uint *primaryLightDynEntShadowVis[2]; + raw_byte *nonSunPrimaryLightForModelDynEnt; + GfxShadowGeometry *shadowGeom; + GfxLightRegion *lightRegion; + GfxWorldDpvsStatic dpvs; + GfxWorldDpvsDynamic dpvsDyn; + unsigned int mapVtxChecksum; + unsigned int heroOnlyLightCount; + GfxHeroOnlyLight *heroOnlyLights; + unsigned char fogTypesAllowed; +}; + +struct GfxLightImage { + GfxImage *image; + unsigned char samplerState; +}; + +struct GfxLightDef { + const char *name; + GfxLightImage attenuation; + GfxLightImage cucoloris; + int lmapLookupStart; +}; + +struct Glyph { + unsigned short letter; + char x0; + char y0; + unsigned char dx; + unsigned char pixelWidth; + unsigned char pixelHeight; + float s0; + float t0; + float s1; + float t1; +}; + +struct Font_s { + const char *fontName; + int pixelHeight; + int glyphCount; + Material *material; + Material *glowMaterial; + Glyph *glyphs; +}; + +struct MenuList { + const char *name; + int menuCount; + menuDef_t **menus; +}; + +struct Statement_s; + +enum expDataType { + VAL_INT = 0x0, + VAL_FLOAT = 0x1, + VAL_STRING = 0x2, + VAL_FUNCTION = 0x3, + + NUM_DATATYPES +}; + +struct ExpressionString { + const char *string; +}; + +union operandInternalDataUnion { + int intVal; + float floatVal; + ExpressionString stringVal; + Statement_s *function; +}; + +struct Operand { + expDataType dataType; + operandInternalDataUnion internals; +}; + +enum expressionOperatorType_e { + OP_NOOP = 0x0, + OP_RIGHTPAREN = 0x1, + OP_MULTIPLY = 0x2, + OP_DIVIDE = 0x3, + OP_MODULUS = 0x4, + OP_ADD = 0x5, + OP_SUBTRACT = 0x6, + OP_NOT = 0x7, + OP_LESSTHAN = 0x8, + OP_LESSTHANEQUALTO = 0x9, + OP_GREATERTHAN = 0xA, + OP_GREATERTHANEQUALTO = 0xB, + OP_EQUALS = 0xC, + OP_NOTEQUAL = 0xD, + OP_AND = 0xE, + OP_OR = 0xF, + OP_LEFTPAREN = 0x10, + OP_COMMA = 0x11, + OP_BITWISEAND = 0x12, + OP_BITWISEOR = 0x13, + OP_BITWISENOT = 0x14, + OP_BITSHIFTLEFT = 0x15, + OP_BITSHIFTRIGHT = 0x16, + + OP_COUNT +}; + +enum expressionFunction_e { + EXP_FUNC_STATIC_DVAR_INT = OP_COUNT, + EXP_FUNC_STATIC_DVAR_BOOL, + EXP_FUNC_STATIC_DVAR_FLOAT, + EXP_FUNC_STATIC_DVAR_STRING, + + EXP_FUNC_DYN_START, + + EXP_FUNC_INT = EXP_FUNC_DYN_START, + EXP_FUNC_STRING, + EXP_FUNC_FLOAT, + EXP_FUNC_SIN, + EXP_FUNC_COS, + EXP_FUNC_MIN, + EXP_FUNC_MAX, + EXP_FUNC_MILLISECONDS, + EXP_FUNC_LOCAL_CLIENT_UI_MILLISECONDS, + EXP_FUNC_DVAR_INT, + EXP_FUNC_DVAR_BOOL, + EXP_FUNC_DVAR_FLOAT, + EXP_FUNC_DVAR_STRING +}; + +enum expressionEntryType : int { + EET_OPERATOR = 0x0, + EET_OPERAND = 0x1, +}; + +union entryInternalData { + int op; + Operand operand; +}; + +struct expressionEntry { + int type; + entryInternalData data; +}; + +struct UIFunctionList { + int totalFunctions; + Statement_s **functions; +}; + +union DvarValue { + bool enabled; + int integer; + unsigned int unsignedInt; + float value; + float vector[4]; + const char *string; + unsigned char color[4]; +}; + +union DvarLimits { + struct { + int stringCount; + const char **strings; + } enumeration; + + struct { + int min; + int max; + } integer; + + struct { + float min; + float max; + } value; + + struct { + float min; + float max; + } vector; +}; + +struct dvar_t { + const char *name; + const char *description; + unsigned short flags; + unsigned char type; + bool modified; + DvarValue current; + DvarValue latched; + DvarValue reset; + DvarLimits domain; + dvar_t *hashNext; +}; + +struct StaticDvar { + dvar_t *dvar; + char *dvarName; +}; + +struct StaticDvarList { + int numStaticDvars; + StaticDvar **staticDvars; +}; + +struct StringList { + int totalStrings; + const char **strings; +}; + +struct ExpressionSupportingData { + UIFunctionList uifunctions; + StaticDvarList staticDvarList; + StringList uiStrings; +}; + +struct ExpressionPersistentState { + int flags; + int playerDataKey[4]; + int lastExecuteTime[4]; + Operand lastResult[4]; +}; + +struct Statement_s { + int numEntries; + expressionEntry *entries; + ExpressionSupportingData *supportingData; + ExpressionPersistentState persistentState; +}; + +struct MenuEventHandlerSet; + +struct ConditionalScript { + MenuEventHandlerSet *eventHandlerSet; + Statement_s *eventExpression; +}; + +struct SetLocalVarData { + const char *localVarName; + Statement_s *expression; +}; + +union EventData { + const char *unconditionalScript; + ConditionalScript *conditionalScript; + MenuEventHandlerSet *elseScript; + SetLocalVarData *setLocalVarData; +}; + +enum EventType : unsigned char { + EVENT_UNCONDITIONAL = 0x0, + EVENT_IF = 0x1, + EVENT_ELSE = 0x2, + EVENT_SET_LOCAL_VAR_BOOL = 0x3, + EVENT_SET_LOCAL_VAR_INT = 0x4, + EVENT_SET_LOCAL_VAR_FLOAT = 0x5, + EVENT_SET_LOCAL_VAR_STRING = 0x6, + + EVENT_COUNT +}; + +struct MenuEventHandler { + EventData eventData; + EventType eventType; +}; + +struct MenuEventHandlerSet { + int eventHandlerCount; + MenuEventHandler **eventHandlers; +}; + +struct ItemKeyHandler { + int key; + MenuEventHandlerSet *action; + ItemKeyHandler *next; +}; + +struct menuTransition { + int transitionType; + int startTime; + float startVal; + float endVal; + float time; + int endTriggerType; +}; + +struct menuData_t { + int fullScreen; + int fadeCycle; + float fadeClamp; + float fadeAmount; + float fadeInAmount; + float blurRadius; + MenuEventHandlerSet *onOpen; + MenuEventHandlerSet *onCloseRequest; + MenuEventHandlerSet *onClose; + MenuEventHandlerSet *onESC; + MenuEventHandlerSet *onFocusDueToClose; + ItemKeyHandler *onKey; + Statement_s *visibleExp; + const char *allowedBinding; + const char *soundName; + float focusColor[4]; + Statement_s *rectXExp; + Statement_s *rectYExp; + Statement_s *rectWExp; + Statement_s *rectHExp; + Statement_s *openSoundExp; + Statement_s *closeSoundExp; + Statement_s *soundLoopExp; + int cursorItem[1]; + menuTransition scaleTransition[1]; + menuTransition alphaTransition[1]; + menuTransition xTransition[1]; + menuTransition yTransition[1]; + ExpressionSupportingData *expressionData; + unsigned char priority; +}; + +struct rectDef_s { + float x; + float y; + float w; + float h; + unsigned char horzAlign; + unsigned char vertAlign; +}; + +// This is data from IW4, could be different for IW5, to be investigated +enum WindowDefStaticFlag : unsigned int { + WINDOW_FLAG_DECORATION = 0x100000, + WINDOW_FLAG_HORIZONTAL_SCROLL = 0x200000, + WINDOW_FLAG_OUT_OF_BOUNDS_CLICK = 0x2000000, + WINDOW_FLAG_SCREEN_SPACE = 0x400000, + WINDOW_FLAG_AUTO_WRAPPED = 0x800000, + WINDOW_FLAG_POPUP = 0x1000000, + WINDOW_FLAG_LEGACY_SPLIT_SCREEN_SCALE = 0x4000000, + WINDOW_FLAG_HIDDEN_DURING_FLASH_BANG = 0x10000000, // confirmed + WINDOW_FLAG_HIDDEN_DURING_SCOPE = 0x20000000, // confirmed + WINDOW_FLAG_HIDDEN_DURING_UI = 0x40000000, // confirmed + WINDOW_FLAG_TEXT_ONLY_FOCUS = 0x80000000, +}; + +// This is data from IW4, could be different for IW5, to be investigated +enum WindowDefDynamicFlag : unsigned int { + WINDOW_FLAG_HOVERED = 0x1, // guessed + WINDOW_FLAG_FOCUSED = 0x2, + WINDOW_FLAG_VISIBLE = 0x4, // confirmed + WINDOW_FLAG_FADING_OUT = 0x10, + WINDOW_FLAG_FADING_IN = 0x20, + WINDOW_FLAG_80 = 0x80, + WINDOW_FLAG_NON_DEFAULT_BACKCOLOR = 0x8000, + WINDOW_FLAG_NON_DEFAULT_FORECOLOR = 0x10000 +}; + +struct windowDef_t { + const char *name; + rectDef_s rect; + rectDef_s rectClient; + const char *group; + int style; + int border; + int ownerDraw; + int ownerDrawFlags; + float borderSize; + int staticFlags; + int dynamicFlags[1]; + int nextTime; + float foreColor[4]; + float backColor[4]; + float borderColor[4]; + float outlineColor[4]; + float disableColor[4]; + Material *background; +}; + +// This is data from IW4, could be different for IW5, to be investigated +enum ItemDefFlag : unsigned int { + ITEM_FLAG_SAVE_GAME_INFO = 0x1, + ITEM_FLAG_CINEMATIC_SUBTITLE = 0x2, +}; + +// This is data from IW4, could be different for IW5, to be investigated +enum ItemDefDvarFlag { + ITEM_DVAR_FLAG_ENABLE = 0x1, + ITEM_DVAR_FLAG_DISABLE = 0x2, + ITEM_DVAR_FLAG_SHOW = 0x4, + ITEM_DVAR_FLAG_HIDE = 0x8, + ITEM_DVAR_FLAG_FOCUS = 0x10, +}; + +struct columnInfo_s { + int xpos; + int ypos; + int width; + int height; + int maxChars; + int alignment; +}; + +struct listBoxDef_s { + int mousePos; + int startPos[1]; + int endPos[1]; + int drawPadding; + float elementWidth; + float elementHeight; + int elementStyle; + int numColumns; + columnInfo_s columnInfo[16]; + MenuEventHandlerSet *onDoubleClick; + int notselectable; + int noScrollBars; + int usePaging; + float selectBorder[4]; + Material *selectIcon; + Statement_s *elementHeightExp; +}; + +struct editFieldDef_s { + float minVal; + float maxVal; + float stepVal; + float range; + int maxChars; + int maxCharsGotoNext; + int maxPaintChars; + int paintOffset; +}; + +struct multiDef_s { + const char *dvarList[32]; + const char *dvarStr[32]; + float dvarValue[32]; + int count; + int strDef; +}; + +struct newsTickerDef_s { + int feedId; + int speed; + int spacing; +}; + +struct textScrollDef_s { + int startTime; +}; + +union itemDefData_t { + listBoxDef_s *listBox; + editFieldDef_s *editField; + multiDef_s *multi; + const char *enumDvarName; + newsTickerDef_s *ticker; + textScrollDef_s *scroll; + void *data; +}; + +enum ItemFloatExpressionTarget { + ITEM_FLOATEXP_TGT_RECT_X = 0x0, + ITEM_FLOATEXP_TGT_RECT_Y = 0x1, + ITEM_FLOATEXP_TGT_RECT_W = 0x2, + ITEM_FLOATEXP_TGT_RECT_H = 0x3, + ITEM_FLOATEXP_TGT_FORECOLOR_R = 0x4, + ITEM_FLOATEXP_TGT_FORECOLOR_G = 0x5, + ITEM_FLOATEXP_TGT_FORECOLOR_B = 0x6, + ITEM_FLOATEXP_TGT_FORECOLOR_RGB = 0x7, + ITEM_FLOATEXP_TGT_FORECOLOR_A = 0x8, + ITEM_FLOATEXP_TGT_GLOWCOLOR_R = 0x9, + ITEM_FLOATEXP_TGT_GLOWCOLOR_G = 0xA, + ITEM_FLOATEXP_TGT_GLOWCOLOR_B = 0xB, + ITEM_FLOATEXP_TGT_GLOWCOLOR_RGB = 0xC, + ITEM_FLOATEXP_TGT_GLOWCOLOR_A = 0xD, + ITEM_FLOATEXP_TGT_BACKCOLOR_R = 0xE, + ITEM_FLOATEXP_TGT_BACKCOLOR_G = 0xF, + ITEM_FLOATEXP_TGT_BACKCOLOR_B = 0x10, + ITEM_FLOATEXP_TGT_BACKCOLOR_RGB = 0x11, + ITEM_FLOATEXP_TGT_BACKCOLOR_A = 0x12, + + ITEM_FLOATEXP_TGT_COUNT +}; + +struct ItemExpressionTargetBinding { + int target; + const char *name; + const char *componentName; +}; + +struct ItemFloatExpression { + int target; + Statement_s *expression; +}; + +enum ItemDefType { + ITEM_TYPE_TEXT = 0x0, + ITEM_TYPE_BUTTON = 0x1, + ITEM_TYPE_RADIOBUTTON = 0x2, + ITEM_TYPE_CHECKBOX = 0x3, + ITEM_TYPE_EDITFIELD = 0x4, + ITEM_TYPE_COMBO = 0x5, + ITEM_TYPE_LISTBOX = 0x6, + ITEM_TYPE_MODEL = 0x7, + ITEM_TYPE_OWNERDRAW = 0x8, + ITEM_TYPE_NUMERICFIELD = 0x9, + ITEM_TYPE_SLIDER = 0xA, + ITEM_TYPE_YESNO = 0xB, + ITEM_TYPE_MULTI = 0xC, + ITEM_TYPE_DVARENUM = 0xD, + ITEM_TYPE_BIND = 0xE, + ITEM_TYPE_MENUMODEL = 0xF, + ITEM_TYPE_VALIDFILEFIELD = 0x10, + ITEM_TYPE_DECIMALFIELD = 0x11, + ITEM_TYPE_UPREDITFIELD = 0x12, + ITEM_TYPE_GAME_MESSAGE_WINDOW = 0x13, + ITEM_TYPE_NEWS_TICKER = 0x14, + ITEM_TYPE_TEXT_SCROLL = 0x15, + ITEM_TYPE_EMAILFIELD = 0x16, + ITEM_TYPE_PASSWORDFIELD = 0x17 +}; + +struct itemDef_s { + windowDef_t window; + rectDef_s textRect[1]; + int type; + int dataType; + int alignment; + int fontEnum; + int textAlignMode; + float textalignx; + float textaligny; + float textscale; + int textStyle; + int gameMsgWindowIndex; + int gameMsgWindowMode; + const char *text; + int itemFlags; + menuDef_t *parent; + MenuEventHandlerSet *mouseEnterText; + MenuEventHandlerSet *mouseExitText; + MenuEventHandlerSet *mouseEnter; + MenuEventHandlerSet *mouseExit; + MenuEventHandlerSet *action; + MenuEventHandlerSet *accept; + MenuEventHandlerSet *onFocus; + MenuEventHandlerSet *hasFocus; + MenuEventHandlerSet *leaveFocus; + const char *dvar; + const char *dvarTest; + ItemKeyHandler *onKey; + const char *enableDvar; + const char *localVar; + int dvarFlags; + snd_alias_list_t *focusSound; + float special; + int cursorPos[1]; + itemDefData_t typeData; + int floatExpressionCount; + ItemFloatExpression *floatExpressions; + Statement_s *visibleExp; + Statement_s *disabledExp; + Statement_s *textExp; + Statement_s *materialExp; + float glowColor[4]; + bool decayActive; + int fxBirthTime; + int fxLetterTime; + int fxDecayStartTime; + int fxDecayDuration; + int lastSoundPlayedTime; + Statement_s *textAlignYExp; +}; + +struct menuDef_t { + menuData_t *data; + windowDef_t window; + int itemCount; + itemDef_s **items; +}; + +struct LocalizeEntry { + const char *value; + const char *name; +}; + +enum AttachmentType { + ATTACHMENT_SCOPE = 0x0, + ATTACHMENT_UNDERBARREL = 0x1, + ATTACHMENT_OTHER = 0x2, + + ATTACHMENT_COUNT +}; + +enum weapType_t { + WEAPTYPE_NONE = 0x0, + WEAPTYPE_BULLET = 0x1, + WEAPTYPE_GRENADE = 0x2, + WEAPTYPE_PROJECTILE = 0x3, + WEAPTYPE_RIOTSHIELD = 0x4, + + WEAPTYPE_NUM +}; + +enum weapClass_t { + WEAPCLASS_RIFLE = 0x0, + WEAPCLASS_SNIPER = 0x1, + WEAPCLASS_MG = 0x2, + WEAPCLASS_SMG = 0x3, + WEAPCLASS_SPREAD = 0x4, + WEAPCLASS_PISTOL = 0x5, + WEAPCLASS_GRENADE = 0x6, + WEAPCLASS_ROCKETLAUNCHER = 0x7, + WEAPCLASS_TURRET = 0x8, + WEAPCLASS_THROWINGKNIFE = 0x9, + WEAPCLASS_NON_PLAYER = 0xA, + WEAPCLASS_ITEM = 0xB, + + WEAPCLASS_NUM +}; + +enum PenetrateType { + PENETRATE_TYPE_NONE = 0x0, + PENETRATE_TYPE_SMALL = 0x1, + PENETRATE_TYPE_MEDIUM = 0x2, + PENETRATE_TYPE_LARGE = 0x3, + + PENETRATE_TYPE_COUNT +}; + +enum ImpactType { + IMPACT_TYPE_NONE = 0x0, + IMPACT_TYPE_BULLET_SMALL = 0x1, + IMPACT_TYPE_BULLET_LARGE = 0x2, + IMPACT_TYPE_BULLET_AP = 0x3, + IMPACT_TYPE_BULLET_EXPLODE = 0x4, + IMPACT_TYPE_SHOTGUN = 0x5, + IMPACT_TYPE_SHOTGUN_EXPLODE = 0x6, + IMPACT_TYPE_GRENADE_BOUNCE = 0x7, + IMPACT_TYPE_GRENADE_EXPLODE = 0x8, + IMPACT_TYPE_ROCKET_EXPLODE = 0x9, + IMPACT_TYPE_PROJECTILE_DUD = 0xA, + + IMPACT_TYPE_COUNT +}; + +enum weapFireType_t { + WEAPON_FIRETYPE_FULLAUTO = 0x0, + WEAPON_FIRETYPE_SINGLESHOT = 0x1, + WEAPON_FIRETYPE_BURSTFIRE2 = 0x2, + WEAPON_FIRETYPE_BURSTFIRE3 = 0x3, + WEAPON_FIRETYPE_BURSTFIRE4 = 0x4, + WEAPON_FIRETYPE_DOUBLEBARREL = 0x5, + + WEAPON_FIRETYPECOUNT, + WEAPON_FIRETYPE_BURSTFIRE_FIRST = WEAPON_FIRETYPE_BURSTFIRE2, + WEAPON_FIRETYPE_BURSTFIRE_LAST = WEAPON_FIRETYPE_BURSTFIRE4 +}; + +struct AttAmmoGeneral { + PenetrateType penetrateType; + float penetrateMultiplier; + ImpactType impactType; + weapFireType_t fireType; + TracerDef *tracerType; + bool rifleBullet; + bool armorPiercing; +}; + +struct AttSight { + bool aimDownSight; + bool adsFire; + bool rechamberWhileAds; + bool noAdsWhenMagEmpty; + bool canHoldBreath; + bool canVariableZoom; + bool hideRailWithThisScope; +}; + +struct AttReload { + bool noPartialReload; + bool segmentedReload; +}; + +struct AttAddOns { + bool motionTracker; + bool silenced; +}; + +struct AttGeneral { + bool boltAction; + bool inheritsPerks; + float enemyCrosshairRange; + Material *reticleCenter; + Material *reticleSide; + int reticleCenterSize; + int reticleSideSize; + float moveSpeedScale; + float adsMoveSpeedScale; +}; + +struct AttAimAssist { + float autoAimRange; + float aimAssistRange; + float aimAssistRangeAds; +}; + +struct AttAmmunition { + int maxAmmo; + int startAmmo; + int clipSize; + int shotCount; + int reloadAmmoAdd; + int reloadStartAdd; +}; + +struct AttDamage { + int damage; + int minDamage; + int meleeDamage; + float maxDamageRange; + float minDamageRange; + int playerDamage; + int minPlayerDamage; +}; + +struct AttLocationDamage { + float locNone; + float locHelmet; + float locHead; + float locNeck; + float locTorsoUpper; + float locTorsoLower; + float locRightArmUpper; + float locRightArmLower; + float locRightHand; + float locLeftArmUpper; + float locLeftArmLower; + float locLeftHand; + float locRightLegUpper; + float locRightLegLower; + float locRightFoot; + float locLeftLegUpper; + float locLeftLegLower; + float locLeftFoot; + float locGun; +}; + +struct AttIdleSettings { + float hipIdleAmount; + float hipIdleSpeed; + float idleCrouchFactor; + float idleProneFactor; + float adsIdleLerpStartTime; + float adsIdleLerpTime; +}; + +struct AttADSSettings { + float adsSpread; + float adsAimPitch; + float adsTransInTime; + float adsTransOutTime; + int adsReloadTransTime; + float adsCrosshairInFrac; + float adsCrosshairOutFrac; + float adsZoomFov; + float adsZoomInFrac; + float adsZoomOutFrac; + float adsBobFactor; + float adsViewBobMult; + float adsViewErrorMin; + float adsViewErrorMax; +}; + +struct AttHipSpread { + float hipSpreadStandMin; + float hipSpreadDuckedMin; + float hipSpreadProneMin; + float hipSpreadMax; + float hipSpreadDuckedMax; + float hipSpreadProneMax; + float hipSpreadFireAdd; + float hipSpreadTurnAdd; + float hipSpreadMoveAdd; + float hipSpreadDecayRate; + float hipSpreadDuckedDecay; + float hipSpreadProneDecay; +}; + +struct AttGunKick { + int hipGunKickReducedKickBullets; + float hipGunKickReducedKickPercent; + float hipGunKickPitchMin; + float hipGunKickPitchMax; + float hipGunKickYawMin; + float hipGunKickYawMax; + float hipGunKickAccel; + float hipGunKickSpeedMax; + float hipGunKickSpeedDecay; + float hipGunKickStaticDecay; + int adsGunKickReducedKickBullets; + float adsGunKickReducedKickPercent; + float adsGunKickPitchMin; + float adsGunKickPitchMax; + float adsGunKickYawMin; + float adsGunKickYawMax; + float adsGunKickAccel; + float adsGunKickSpeedMax; + float adsGunKickSpeedDecay; + float adsGunKickStaticDecay; +}; + +struct AttViewKick { + float hipViewKickPitchMin; + float hipViewKickPitchMax; + float hipViewKickYawMin; + float hipViewKickYawMax; + float hipViewKickCenterSpeed; + float adsViewKickPitchMin; + float adsViewKickPitchMax; + float adsViewKickYawMin; + float adsViewKickYawMax; + float adsViewKickCenterSpeed; +}; + +enum weapOverlayReticle_t { + WEAPOVERLAYRETICLE_NONE = 0x0, + WEAPOVERLAYRETICLE_CROSSHAIR = 0x1, + + WEAPOVERLAYRETICLE_NUM +}; + +struct ADSOverlay { + Material *shader; + Material *shaderLowRes; + Material *shaderEMP; + Material *shaderEMPLowRes; + weapOverlayReticle_t reticle; + float width; + float height; + float widthSplitscreen; + float heightSplitscreen; +}; + +struct AttADSOverlay { + ADSOverlay overlay; + bool thermalScope; +}; + +enum weaponIconRatioType_t { + WEAPON_ICON_RATIO_1TO1 = 0x0, + WEAPON_ICON_RATIO_2TO1 = 0x1, + WEAPON_ICON_RATIO_4TO1 = 0x2, + + WEAPON_ICON_RATIO_COUNT +}; + +enum ammoCounterClipType_t { + AMMO_COUNTER_CLIP_NONE = 0x0, + AMMO_COUNTER_CLIP_MAGAZINE = 0x1, + AMMO_COUNTER_CLIP_SHORTMAGAZINE = 0x2, + AMMO_COUNTER_CLIP_SHOTGUN = 0x3, + AMMO_COUNTER_CLIP_ROCKET = 0x4, + AMMO_COUNTER_CLIP_BELTFED = 0x5, + AMMO_COUNTER_CLIP_ALTWEAPON = 0x6, + + AMMO_COUNTER_CLIP_COUNT +}; + +struct AttUI { + Material *dpadIcon; + Material *ammoCounterIcon; + weaponIconRatioType_t dpadIconRatio; + weaponIconRatioType_t ammoCounterIconRatio; + ammoCounterClipType_t ammoCounterClip; +}; + +struct AttRumbles { + const char *fireRumble; + const char *meleeImpactRumble; +}; + +enum weapProjExposion_t { + WEAPPROJEXP_GRENADE = 0x0, + WEAPPROJEXP_ROCKET = 0x1, + WEAPPROJEXP_FLASHBANG = 0x2, + WEAPPROJEXP_NONE = 0x3, + WEAPPROJEXP_DUD = 0x4, + WEAPPROJEXP_SMOKE = 0x5, + WEAPPROJEXP_HEAVY = 0x6, + + WEAPPROJEXP_NUM +}; + +struct snd_alias_list_name { + const char *soundName; +}; + +union SndAliasCustom { + snd_alias_list_name *name; + snd_alias_list_t *sound; +}; + +struct AttProjectile { + int explosionRadius; + int explosionInnerDamage; + int explosionOuterDamage; + float damageConeAngle; + int projectileSpeed; + int projectileSpeedUp; + int projectileActivateDist; + float projectileLifetime; + XModel *projectileModel; + weapProjExposion_t projExplosionType; + FxEffectDef *projExplosionEffect; + bool projExplosionEffectForceNormalUp; + SndAliasCustom projExplosionSound; + FxEffectDef *projDudEffect; + SndAliasCustom projDudSound; + bool projImpactExplode; + float destabilizationRateTime; + float destabilizationCurvatureMax; + int destabilizeDistance; + FxEffectDef *projTrailEffect; + int projIgnitionDelay; + FxEffectDef *projIgnitionEffect; + SndAliasCustom projIgnitionSound; +}; + +typedef tdef_align(4) AttSight AttSight4; + +struct WeaponAttachment { + const char *szInternalName; + const char *szDisplayName; + AttachmentType type; + weapType_t weaponType; + weapClass_t weapClass; + XModel **worldModels; + XModel **viewModels; + XModel **reticleViewModels; + AttAmmoGeneral *ammogeneral; + AttSight4 *sight; + AttReload *reload; + AttAddOns *addOns; + AttGeneral *general; + AttAimAssist *aimAssist; + AttAmmunition *ammunition; + AttDamage *damage; + AttLocationDamage *locationDamage; + AttIdleSettings *idleSettings; + AttADSSettings *adsSettings; + AttADSSettings *adsSettingsMain; + AttHipSpread *hipSpread; + AttGunKick *gunKick; + AttViewKick *viewKick; + AttADSOverlay *adsOverlay; + AttUI *ui; + AttRumbles *rumbles; + AttProjectile *projectile; + float ammunitionScale; + float damageScale; + float damageScaleMin; + float stateTimersScale; + float fireTimersScale; + float idleSettingsScale; + float adsSettingsScale; + float adsSettingsScaleMain; + float hipSpreadScale; + float gunKickScale; + float viewKickScale; + float viewCenterScale; + int loadIndex; + bool hideIronSightsWithThisAttachment; + bool shareAmmoWithAlt; +}; + +enum weapInventoryType_t { + WEAPINVENTORY_PRIMARY = 0x0, + WEAPINVENTORY_OFFHAND = 0x1, + WEAPINVENTORY_ITEM = 0x2, + WEAPINVENTORY_ALTMODE = 0x3, + WEAPINVENTORY_EXCLUSIVE = 0x4, + WEAPINVENTORY_SCAVENGER = 0x5, + + WEAPINVENTORYCOUNT +}; + +enum OffhandClass { + OFFHAND_CLASS_NONE = 0x0, + OFFHAND_CLASS_FRAG_GRENADE = 0x1, + OFFHAND_CLASS_SMOKE_GRENADE = 0x2, + OFFHAND_CLASS_FLASH_GRENADE = 0x3, + OFFHAND_CLASS_THROWINGKNIFE = 0x4, + OFFHAND_CLASS_OTHER = 0x5, + + OFFHAND_CLASS_COUNT +}; + +enum weapStance_t { + WEAPSTANCE_STAND = 0x0, + WEAPSTANCE_DUCK = 0x1, + WEAPSTANCE_PRONE = 0x2, + + WEAPSTANCE_NUM +}; + +enum activeReticleType_t { + VEH_ACTIVE_RETICLE_NONE = 0x0, + VEH_ACTIVE_RETICLE_PIP_ON_A_STICK = 0x1, + VEH_ACTIVE_RETICLE_BOUNCING_DIAMOND = 0x2, + + VEH_ACTIVE_RETICLE_COUNT +}; + +struct StateTimers { + int iFireDelay; + int iMeleeDelay; + int meleeChargeDelay; + int iDetonateDelay; + int iRechamberTime; + int rechamberTimeOneHanded; + int iRechamberBoltTime; + int iHoldFireTime; + int iDetonateTime; + int iMeleeTime; + int meleeChargeTime; + int iReloadTime; + int reloadShowRocketTime; + int iReloadEmptyTime; + int iReloadAddTime; + int iReloadStartTime; + int iReloadStartAddTime; + int iReloadEndTime; + int iDropTime; + int iRaiseTime; + int iAltDropTime; + int quickDropTime; + int quickRaiseTime; + int iBreachRaiseTime; + int iEmptyRaiseTime; + int iEmptyDropTime; + int sprintInTime; + int sprintLoopTime; + int sprintOutTime; + int stunnedTimeBegin; + int stunnedTimeLoop; + int stunnedTimeEnd; + int nightVisionWearTime; + int nightVisionWearTimeFadeOutEnd; + int nightVisionWearTimePowerUp; + int nightVisionRemoveTime; + int nightVisionRemoveTimePowerDown; + int nightVisionRemoveTimeFadeInStart; + int fuseTime; + int aiFuseTime; + int blastFrontTime; + int blastRightTime; + int blastBackTime; + int blastLeftTime; + int raiseInterruptableTime; + int firstRaiseInterruptableTime; + int reloadInterruptableTime; + int reloadEmptyInterruptableTime; + int fireInterruptableTime; +}; + +enum WeapOverlayInteface_t { + WEAPOVERLAYINTERFACE_NONE = 0x0, + WEAPOVERLAYINTERFACE_JAVELIN = 0x1, + WEAPOVERLAYINTERFACE_TURRETSCOPE = 0x2, + + WEAPOVERLAYINTERFACECOUNT +}; + +enum WeapStickinessType { + WEAPSTICKINESS_NONE = 0x0, + WEAPSTICKINESS_ALL = 0x1, + WEAPSTICKINESS_ALL_ORIENT = 0x2, + WEAPSTICKINESS_GROUND = 0x3, + WEAPSTICKINESS_GROUND_WITH_YAW = 0x4, + WEAPSTICKINESS_KNIFE = 0x5, + + WEAPSTICKINESS_COUNT +}; + +enum guidedMissileType_t { + MISSILE_GUIDANCE_NONE = 0x0, + MISSILE_GUIDANCE_SIDEWINDER = 0x1, + MISSILE_GUIDANCE_HELLFIRE = 0x2, + MISSILE_GUIDANCE_JAVELIN = 0x3, + + MISSILE_GUIDANCE_COUNT +}; + +enum weapAnimFiles_t { + WEAP_ANIM_ROOT = 0x0, + WEAP_ANIM_IDLE = 0x1, + WEAP_ANIM_EMPTY_IDLE = 0x2, + WEAP_ANIM_FIRE = 0x3, + WEAP_ANIM_HOLD_FIRE = 0x4, + WEAP_ANIM_LASTSHOT = 0x5, + WEAP_ANIM_RECHAMBER = 0x6, + WEAP_ANIM_MELEE = 0x7, + WEAP_ANIM_MELEE_CHARGE = 0x8, + WEAP_ANIM_RELOAD = 0x9, + WEAP_ANIM_RELOAD_EMPTY = 0xA, + WEAP_ANIM_RELOAD_START = 0xB, + WEAP_ANIM_RELOAD_END = 0xC, + WEAP_ANIM_RAISE = 0xD, + WEAP_ANIM_FIRST_RAISE = 0xE, + WEAP_ANIM_BREACH_RAISE = 0xF, + WEAP_ANIM_DROP = 0x10, + WEAP_ANIM_ALT_RAISE = 0x11, + WEAP_ANIM_ALT_DROP = 0x12, + WEAP_ANIM_QUICK_RAISE = 0x13, + WEAP_ANIM_QUICK_DROP = 0x14, + WEAP_ANIM_EMPTY_RAISE = 0x15, + WEAP_ANIM_EMPTY_DROP = 0x16, + WEAP_ANIM_SPRINT_IN = 0x17, + WEAP_ANIM_SPRINT_LOOP = 0x18, + WEAP_ANIM_SPRINT_OUT = 0x19, + WEAP_ANIM_STUNNED_START = 0x1A, + WEAP_ANIM_STUNNED_LOOP = 0x1B, + WEAP_ANIM_STUNNED_END = 0x1C, + WEAP_ANIM_DETONATE = 0x1D, + WEAP_ANIM_NIGHTVISION_WEAR = 0x1E, + WEAP_ANIM_NIGHTVISION_REMOVE = 0x1F, + WEAP_ANIM_ADS_FIRE = 0x20, + WEAP_ANIM_ADS_LASTSHOT = 0x21, + WEAP_ANIM_ADS_RECHAMBER = 0x22, + WEAP_ANIM_BLAST_FRONT = 0x23, + WEAP_ANIM_BLAST_RIGHT = 0x24, + WEAP_ANIM_BLAST_BACK = 0x25, + WEAP_ANIM_BLAST_LEFT = 0x26, + WEAP_ANIM_ADS_UP = 0x27, + WEAP_ANIM_ADS_DOWN = 0x28, + WEAP_ALT_ANIM_ADJUST = 0x29, + + NUM_WEAP_ANIMS +}; + +enum hitLocation_t { + HITLOC_NONE = 0x0, + HITLOC_HELMET = 0x1, + HITLOC_HEAD = 0x2, + HITLOC_NECK = 0x3, + HITLOC_TORSO_UPR = 0x4, + HITLOC_TORSO_LWR = 0x5, + HITLOC_R_ARM_UPR = 0x6, + HITLOC_L_ARM_UPR = 0x7, + HITLOC_R_ARM_LWR = 0x8, + HITLOC_L_ARM_LWR = 0x9, + HITLOC_R_HAND = 0xA, + HITLOC_L_HAND = 0xB, + HITLOC_R_LEG_UPR = 0xC, + HITLOC_L_LEG_UPR = 0xD, + HITLOC_R_LEG_LWR = 0xE, + HITLOC_L_LEG_LWR = 0xF, + HITLOC_R_FOOT = 0x10, + HITLOC_L_FOOT = 0x11, + HITLOC_GUN = 0x12, + HITLOC_SHIELD = 0x13, + + HITLOC_NUM +}; + +struct WeaponDef { + const char *szOverlayName; + XModel **gunXModel; + XModel *handXModel; + const char **szXAnimsRightHanded; + const char **szXAnimsLeftHanded; + const char *szModeName; + ScriptString *notetrackSoundMapKeys; + ScriptString *notetrackSoundMapValues; + ScriptString *notetrackRumbleMapKeys; + ScriptString *notetrackRumbleMapValues; + int playerAnimType; + weapType_t weapType; + weapClass_t weapClass; + PenetrateType penetrateType; + weapInventoryType_t inventoryType; + weapFireType_t fireType; + OffhandClass offhandClass; + weapStance_t stance; + FxEffectDef *viewFlashEffect; + FxEffectDef *worldFlashEffect; + SndAliasCustom pickupSound; + SndAliasCustom pickupSoundPlayer; + SndAliasCustom ammoPickupSound; + SndAliasCustom ammoPickupSoundPlayer; + SndAliasCustom projectileSound; + SndAliasCustom pullbackSound; + SndAliasCustom pullbackSoundPlayer; + SndAliasCustom fireSound; + SndAliasCustom fireSoundPlayer; + SndAliasCustom fireSoundPlayerAkimbo; + SndAliasCustom fireLoopSound; + SndAliasCustom fireLoopSoundPlayer; + SndAliasCustom fireStopSound; + SndAliasCustom fireStopSoundPlayer; + SndAliasCustom fireLastSound; + SndAliasCustom fireLastSoundPlayer; + SndAliasCustom emptyFireSound; + SndAliasCustom emptyFireSoundPlayer; + SndAliasCustom meleeSwipeSound; + SndAliasCustom meleeSwipeSoundPlayer; + SndAliasCustom meleeHitSound; + SndAliasCustom meleeMissSound; + SndAliasCustom rechamberSound; + SndAliasCustom rechamberSoundPlayer; + SndAliasCustom reloadSound; + SndAliasCustom reloadSoundPlayer; + SndAliasCustom reloadEmptySound; + SndAliasCustom reloadEmptySoundPlayer; + SndAliasCustom reloadStartSound; + SndAliasCustom reloadStartSoundPlayer; + SndAliasCustom reloadEndSound; + SndAliasCustom reloadEndSoundPlayer; + SndAliasCustom detonateSound; + SndAliasCustom detonateSoundPlayer; + SndAliasCustom nightVisionWearSound; + SndAliasCustom nightVisionWearSoundPlayer; + SndAliasCustom nightVisionRemoveSound; + SndAliasCustom nightVisionRemoveSoundPlayer; + SndAliasCustom altSwitchSound; + SndAliasCustom altSwitchSoundPlayer; + SndAliasCustom raiseSound; + SndAliasCustom raiseSoundPlayer; + SndAliasCustom firstRaiseSound; + SndAliasCustom firstRaiseSoundPlayer; + SndAliasCustom putawaySound; + SndAliasCustom putawaySoundPlayer; + SndAliasCustom scanSound; + SndAliasCustom changeVariableZoomSound; + SndAliasCustom *bounceSound; + SndAliasCustom *rollingSound; + FxEffectDef *viewShellEjectEffect; + FxEffectDef *worldShellEjectEffect; + FxEffectDef *viewLastShotEjectEffect; + FxEffectDef *worldLastShotEjectEffect; + Material *reticleCenter; + Material *reticleSide; + int iReticleCenterSize; + int iReticleSideSize; + int iReticleMinOfs; + activeReticleType_t activeReticleType; + float vStandMove[3]; + float vStandRot[3]; + float strafeMove[3]; + float strafeRot[3]; + float vDuckedOfs[3]; + float vDuckedMove[3]; + float vDuckedRot[3]; + float vProneOfs[3]; + float vProneMove[3]; + float vProneRot[3]; + float fPosMoveRate; + float fPosProneMoveRate; + float fStandMoveMinSpeed; + float fDuckedMoveMinSpeed; + float fProneMoveMinSpeed; + float fPosRotRate; + float fPosProneRotRate; + float fStandRotMinSpeed; + float fDuckedRotMinSpeed; + float fProneRotMinSpeed; + XModel **worldModel; + XModel *worldClipModel; + XModel *rocketModel; + XModel *knifeModel; + XModel *worldKnifeModel; + Material *hudIcon; + weaponIconRatioType_t hudIconRatio; + Material *pickupIcon; + weaponIconRatioType_t pickupIconRatio; + Material *ammoCounterIcon; + weaponIconRatioType_t ammoCounterIconRatio; + ammoCounterClipType_t ammoCounterClip; + int iStartAmmo; + const char *szAmmoName; + int iAmmoIndex; + const char *szClipName; + int iClipIndex; + int iMaxAmmo; + int shotCount; + const char *szSharedAmmoCapName; + int iSharedAmmoCapIndex; + int iSharedAmmoCap; + int damage; + int playerDamage; + int iMeleeDamage; + int iDamageType; + StateTimers stateTimers; + StateTimers akimboStateTimers; + float autoAimRange; + float aimAssistRange; + float aimAssistRangeAds; + float aimPadding; + float enemyCrosshairRange; + float moveSpeedScale; + float adsMoveSpeedScale; + float sprintDurationScale; + float fAdsZoomInFrac; + float fAdsZoomOutFrac; + ADSOverlay overlay; + WeapOverlayInteface_t overlayInterface; + float fAdsBobFactor; + float fAdsViewBobMult; + float fHipSpreadStandMin; + float fHipSpreadDuckedMin; + float fHipSpreadProneMin; + float hipSpreadStandMax; + float hipSpreadDuckedMax; + float hipSpreadProneMax; + float fHipSpreadDecayRate; + float fHipSpreadFireAdd; + float fHipSpreadTurnAdd; + float fHipSpreadMoveAdd; + float fHipSpreadDuckedDecay; + float fHipSpreadProneDecay; + float fHipReticleSidePos; + float fAdsIdleAmount; + float fHipIdleAmount; + float adsIdleSpeed; + float hipIdleSpeed; + float fIdleCrouchFactor; + float fIdleProneFactor; + float fGunMaxPitch; + float fGunMaxYaw; + float adsIdleLerpStartTime; + float adsIdleLerpTime; + float swayMaxAngle; + float swayLerpSpeed; + float swayPitchScale; + float swayYawScale; + float swayHorizScale; + float swayVertScale; + float swayShellShockScale; + float adsSwayMaxAngle; + float adsSwayLerpSpeed; + float adsSwayPitchScale; + float adsSwayYawScale; + float adsSwayHorizScale; + float adsSwayVertScale; + float adsViewErrorMin; + float adsViewErrorMax; + PhysCollmap *physCollmap; + float dualWieldViewModelOffset; + weaponIconRatioType_t killIconRatio; + int iReloadAmmoAdd; + int iReloadStartAdd; + int ammoDropStockMin; + int ammoDropClipPercentMin; + int ammoDropClipPercentMax; + int iExplosionRadius; + int iExplosionRadiusMin; + int iExplosionInnerDamage; + int iExplosionOuterDamage; + float damageConeAngle; + float bulletExplDmgMult; + float bulletExplRadiusMult; + int iProjectileSpeed; + int iProjectileSpeedUp; + int iProjectileSpeedForward; + int iProjectileActivateDist; + float projLifetime; + float timeToAccelerate; + float projectileCurvature; + XModel *projectileModel; + weapProjExposion_t projExplosion; + FxEffectDef *projExplosionEffect; + FxEffectDef *projDudEffect; + SndAliasCustom projExplosionSound; + SndAliasCustom projDudSound; + WeapStickinessType stickiness; + float lowAmmoWarningThreshold; + float ricochetChance; + bool riotShieldEnableDamage; + int riotShieldHealth; + float riotShieldDamageMult; + float *parallelBounce; + float *perpendicularBounce; + FxEffectDef *projTrailEffect; + FxEffectDef *projBeaconEffect; + float vProjectileColor[3]; + guidedMissileType_t guidedMissileType; + float maxSteeringAccel; + int projIgnitionDelay; + FxEffectDef *projIgnitionEffect; + SndAliasCustom projIgnitionSound; + float fAdsAimPitch; + float fAdsCrosshairInFrac; + float fAdsCrosshairOutFrac; + int adsGunKickReducedKickBullets; + float adsGunKickReducedKickPercent; + float fAdsGunKickPitchMin; + float fAdsGunKickPitchMax; + float fAdsGunKickYawMin; + float fAdsGunKickYawMax; + float fAdsGunKickAccel; + float fAdsGunKickSpeedMax; + float fAdsGunKickSpeedDecay; + float fAdsGunKickStaticDecay; + float fAdsViewKickPitchMin; + float fAdsViewKickPitchMax; + float fAdsViewKickYawMin; + float fAdsViewKickYawMax; + float fAdsViewScatterMin; + float fAdsViewScatterMax; + float fAdsSpread; + int hipGunKickReducedKickBullets; + float hipGunKickReducedKickPercent; + float fHipGunKickPitchMin; + float fHipGunKickPitchMax; + float fHipGunKickYawMin; + float fHipGunKickYawMax; + float fHipGunKickAccel; + float fHipGunKickSpeedMax; + float fHipGunKickSpeedDecay; + float fHipGunKickStaticDecay; + float fHipViewKickPitchMin; + float fHipViewKickPitchMax; + float fHipViewKickYawMin; + float fHipViewKickYawMax; + float fHipViewScatterMin; + float fHipViewScatterMax; + float fightDist; + float maxDist; + // const char* accuracyGraphName[2];// TODO: Order is accuracyGraphName[0] -> originalAccuracyGraphKnots[0] -> accuracyGraphName[1] -> ... + // Which is currently not possible to do in code generation. Afaik this is the only place where this is the case. + // So might be something to fix but on the other hand it might be too much work for this little inconvenience. + // vec2_t* originalAccuracyGraphKnots[2]; + const char *accuracyGraphName0; + const char *accuracyGraphName1; + vec2_t *originalAccuracyGraphKnots0; + vec2_t *originalAccuracyGraphKnots1; + unsigned short originalAccuracyGraphKnotCount[2]; + int iPositionReloadTransTime; + float leftArc; + float rightArc; + float topArc; + float bottomArc; + float accuracy; + float aiSpread; + float playerSpread; + float minTurnSpeed[2]; + float maxTurnSpeed[2]; + float pitchConvergenceTime; + float yawConvergenceTime; + float suppressTime; + float maxRange; + float fAnimHorRotateInc; + float fPlayerPositionDist; + const char *szUseHintString; + const char *dropHintString; + int iUseHintStringIndex; + int dropHintStringIndex; + float horizViewJitter; + float vertViewJitter; + float scanSpeed; + float scanAccel; + int scanPauseTime; + const char *szScript; + float fOOPosAnimLength[2]; + int minDamage; + int minPlayerDamage; + float fMaxDamageRange; + float fMinDamageRange; + float destabilizationRateTime; + float destabilizationCurvatureMax; + int destabilizeDistance; + float *locationDamageMultipliers; + const char *fireRumble; + const char *meleeImpactRumble; + TracerDef *tracerType; + bool turretADSEnabled; + float turretADSTime; + float turretFov; + float turretFovADS; + float turretScopeZoomRate; + float turretScopeZoomMin; + float turretScopeZoomMax; + float turretOverheatUpRate; + float turretOverheatDownRate; + float turretOverheatPenalty; + SndAliasCustom turretOverheatSound; + FxEffectDef *turretOverheatEffect; + const char *turretBarrelSpinRumble; + float turretBarrelSpinSpeed; + float turretBarrelSpinUpTime; + float turretBarrelSpinDownTime; + SndAliasCustom turretBarrelSpinMaxSnd; + SndAliasCustom turretBarrelSpinUpSnd[4]; + SndAliasCustom turretBarrelSpinDownSnd[4]; + SndAliasCustom missileConeSoundAlias; + SndAliasCustom missileConeSoundAliasAtBase; + float missileConeSoundRadiusAtTop; + float missileConeSoundRadiusAtBase; + float missileConeSoundHeight; + float missileConeSoundOriginOffset; + float missileConeSoundVolumescaleAtCore; + float missileConeSoundVolumescaleAtEdge; + float missileConeSoundVolumescaleCoreSize; + float missileConeSoundPitchAtTop; + float missileConeSoundPitchAtBottom; + float missileConeSoundPitchTopSize; + float missileConeSoundPitchBottomSize; + float missileConeSoundCrossfadeTopSize; + float missileConeSoundCrossfadeBottomSize; + bool sharedAmmo; + bool lockonSupported; + bool requireLockonToFire; + bool isAirburstWeapon; + bool bigExplosion; + bool noAdsWhenMagEmpty; + bool avoidDropCleanup; + bool inheritsPerks; + bool crosshairColorChange; + bool bRifleBullet; + bool armorPiercing; + bool bBoltAction; + bool aimDownSight; + bool canHoldBreath; + bool canVariableZoom; + bool bRechamberWhileAds; + bool bBulletExplosiveDamage; + bool bCookOffHold; + bool bClipOnly; + bool noAmmoPickup; + bool adsFireOnly; + bool cancelAutoHolsterWhenEmpty; + bool disableSwitchToWhenEmpty; + bool suppressAmmoReserveDisplay; + bool laserSightDuringNightvision; + bool markableViewmodel; + bool noDualWield; + bool flipKillIcon; + bool bNoPartialReload; + bool bSegmentedReload; + bool blocksProne; + bool silenced; + bool isRollingGrenade; + bool projExplosionEffectForceNormalUp; + bool bProjImpactExplode; + bool stickToPlayers; + bool stickToVehicles; + bool stickToTurrets; + bool hasDetonator; + bool disableFiring; + bool timedDetonation; + bool rotate; + bool holdButtonToThrow; + bool freezeMovementWhenFiring; + bool thermalScope; + bool altModeSameWeapon; + bool turretBarrelSpinEnabled; + bool missileConeSoundEnabled; + bool missileConeSoundPitchshiftEnabled; + bool missileConeSoundCrossfadeEnabled; + bool offhandHoldIsCancelable; + bool doNotAllowAttachmentsToOverrideSpread; + ScriptString stowTag; + XModel *stowOffsetModel; +}; + +struct AnimOverrideEntry { + unsigned short attachment1; + unsigned short attachment2; + const char *overrideAnim; + const char *altmodeAnim; + unsigned int animTreeType; + int animTime; + int altTime; +}; + +struct SoundOverrideEntry { + unsigned short attachment1; + unsigned short attachment2; + SndAliasCustom overrideSound; + SndAliasCustom altmodeSound; + unsigned int soundType; +}; + +struct FXOverrideEntry { + unsigned short attachment1; + unsigned short attachment2; + FxEffectDef *overrideFX; + FxEffectDef *altmodeFX; + unsigned int fxType; +}; + +struct ReloadStateTimerEntry { + int attachment; + int reloadAddTime; + int reloadStartAddTime; +}; + +struct NoteTrackToSoundEntry { + int attachment; + ScriptString *notetrackSoundMapKeys; + ScriptString *notetrackSoundMapValues; +}; + +struct WeaponCompleteDef { + const char *szInternalName; + WeaponDef *weapDef; + const char *szDisplayName; + ScriptString *hideTags; + WeaponAttachment **scopes; + WeaponAttachment **underBarrels; + WeaponAttachment **others; + const char **szXAnims; + unsigned int numAnimOverrides; + AnimOverrideEntry *animOverrides; + unsigned int numSoundOverrides; + SoundOverrideEntry *soundOverrides; + unsigned int numFXOverrides; + FXOverrideEntry *fxOverrides; + unsigned int numReloadStateTimerOverrides; + ReloadStateTimerEntry *reloadOverrides; + unsigned int numNotetrackOverrides; + NoteTrackToSoundEntry *notetrackOverrides; + float fAdsZoomFov; + int iAdsTransInTime; + int iAdsTransOutTime; + int iClipSize; + ImpactType impactType; + int iFireTime; + int iFireTimeAkimbo; + weaponIconRatioType_t dpadIconRatio; + float penetrateMultiplier; + float fAdsViewKickCenterSpeed; + float fHipViewKickCenterSpeed; + const char *szAltWeaponName; + int altWeapon; + int iAltRaiseTime; + int iAltRaiseTimeAkimbo; + Material *killIcon; + Material *dpadIcon; + int fireAnimLength; + int fireAnimLengthAkimbo; + int iFirstRaiseTime; + int iFirstRaiseTimeAkimbo; + int ammoDropStockMax; + float adsDofStart; + float adsDofEnd; + unsigned short accuracyGraphKnotCount[2]; + vec2_t *accuracyGraphKnots[2]; + bool motionTracker; + bool enhanced; + bool dpadIconShowsAmmo; +}; + +struct FxFloatRange { + float base; + float amplitude; +}; + +struct FxIntRange { + int base; + int amplitude; +}; + +struct FxElemVec3Range { + float base[3]; + float amplitude[3]; +}; + +struct FxSpawnDefLooping { + int intervalMsec; + int count; +}; + +struct FxSpawnDefOneShot { + FxIntRange count; +}; + +union FxSpawnDef { + FxSpawnDefLooping looping; + FxSpawnDefOneShot oneShot; +}; + +struct FxElemAtlas { + unsigned char behavior; + unsigned char index; + unsigned char fps; + unsigned char loopCount; + unsigned char colIndexBits; + unsigned char rowIndexBits; + short entryCount; +}; + +struct FxElemVelStateInFrame { + FxElemVec3Range velocity; + FxElemVec3Range totalDelta; +}; + +struct FxElemVelStateSample { + FxElemVelStateInFrame local; + FxElemVelStateInFrame world; +}; + +struct FxElemVisualState { + unsigned char color[4]; + float rotationDelta; + float rotationTotal; + float size[2]; + float scale; +}; + +struct FxElemVisStateSample { + FxElemVisualState base; + FxElemVisualState amplitude; +}; + +struct FxElemMarkVisuals { + Material *materials[2]; +}; + +union FxEffectDefRef { + FxEffectDef *handle; + const char *name; +}; + +union FxElemVisuals { + const void *anonymous; + Material *material; + XModel *model; + FxEffectDefRef effectDef; + const char *soundName; + GfxLightDef *lightDef; +}; + +union FxElemDefVisuals { + FxElemMarkVisuals *markArray; + FxElemVisuals *array; + FxElemVisuals instance; +}; + +struct FxTrailVertex { + float pos[2]; + float normal[2]; + float texCoord; +}; + +struct FxTrailDef { + int scrollTimeMsec; + int repeatDist; + float invSplitDist; + float invSplitArcDist; + float invSplitTime; + int vertCount; + FxTrailVertex *verts; + int indCount; + unsigned short *inds; +}; + +struct FxSparkFountainDef { + float gravity; + float bounceFrac; + float bounceRand; + float sparkSpacing; + float sparkLength; + int sparkCount; + float loopTime; + float velMin; + float velMax; + float velConeFrac; + float restSpeed; + float boostTime; + float boostFactor; +}; + +struct FxSpotLightDef { + float fovInnerFraction; + float startRadius; + float endRadius; + float brightness; + float maxLength; + int exponent; +}; + +union FxElemExtendedDefPtr { + FxTrailDef *trailDef; + FxSparkFountainDef *sparkFountainDef; + FxSpotLightDef *spotLightDef; + char *unknownDef; +}; + +enum FxElemType { + FX_ELEM_TYPE_SPRITE_BILLBOARD = 0x0, + FX_ELEM_TYPE_SPRITE_ORIENTED = 0x1, + FX_ELEM_TYPE_TAIL = 0x2, + FX_ELEM_TYPE_TRAIL = 0x3, + FX_ELEM_TYPE_CLOUD = 0x4, + FX_ELEM_TYPE_SPARK_CLOUD = 0x5, + FX_ELEM_TYPE_SPARK_FOUNTAIN = 0x6, + FX_ELEM_TYPE_MODEL = 0x7, + FX_ELEM_TYPE_OMNI_LIGHT = 0x8, + FX_ELEM_TYPE_SPOT_LIGHT = 0x9, + FX_ELEM_TYPE_SOUND = 0xA, + FX_ELEM_TYPE_DECAL = 0xB, + FX_ELEM_TYPE_RUNNER = 0xC, + FX_ELEM_TYPE_COUNT = 0xD, + FX_ELEM_TYPE_LAST_SPRITE = 0x3, + FX_ELEM_TYPE_LAST_DRAWN = 0x9 +}; + +struct FxElemDef { + int flags; + FxSpawnDef spawn; + FxFloatRange spawnRange; + FxFloatRange fadeInRange; + FxFloatRange fadeOutRange; + float spawnFrustumCullRadius; + FxIntRange spawnDelayMsec; + FxIntRange lifeSpanMsec; + FxFloatRange spawnOrigin[3]; + FxFloatRange spawnOffsetRadius; + FxFloatRange spawnOffsetHeight; + FxFloatRange spawnAngles[3]; + FxFloatRange angularVelocity[3]; + FxFloatRange initialRotation; + FxFloatRange gravity; + FxFloatRange reflectionFactor; + FxElemAtlas atlas; + unsigned char elemType; + unsigned char visualCount; + unsigned char velIntervalCount; + unsigned char visStateIntervalCount; + FxElemVelStateSample *velSamples; + FxElemVisStateSample *visSamples; + FxElemDefVisuals visuals; + Bounds collBounds; + FxEffectDefRef effectOnImpact; + FxEffectDefRef effectOnDeath; + FxEffectDefRef effectEmitted; + FxFloatRange emitDist; + FxFloatRange emitDistVariance; + FxElemExtendedDefPtr extended; + unsigned char sortOrder; + unsigned char lightingFrac; + unsigned char useItemClip; + unsigned char fadeInfo; + int randomSeed; +}; + +struct FxEffectDef { + const char *name; + int flags; + int totalSize; + int msecLoopingLife; + int elemDefCountLooping; + int elemDefCountOneShot; + int elemDefCountEmission; + float occlusionQueryDepthBias; + int occlusionQueryFadeIn; + int occlusionQueryFadeOut; + FxFloatRange occlusionQueryScaleRange; + FxElemDef *elemDefs; +}; + +struct FxImpactEntry { + FxEffectDef *nonflesh[31]; + FxEffectDef *flesh[4]; +}; + +struct FxImpactTable { + const char *name; + FxImpactEntry *table; +}; + +struct SurfaceFxEntry { + FxEffectDef *surfaceEffect[31]; +}; + +struct SurfaceFxTable { + const char *name; + SurfaceFxEntry *table; +}; + +struct RawFile { + const char *name; + int compressedLen; + int len; + const char *buffer; +}; + +struct ScriptFile { + const char *name; + int compressedLen; + int len; + int bytecodeLen; + const char *buffer; + unsigned char *bytecode; +}; + +struct StringTableCell { + const char *string; + int hash; +}; + +struct StringTable { + const char *name; + int columnCount; + int rowCount; + StringTableCell *values; +}; + +enum LbColType { + LBCOL_TYPE_NUMBER = 0x0, + LBCOL_TYPE_TIME = 0x1, + LBCOL_TYPE_LEVELXP = 0x2, + LBCOL_TYPE_PRESTIGE = 0x3, + LBCOL_TYPE_BIGNUMBER = 0x4, + LBCOL_TYPE_PERCENT = 0x5, + LBCOL_TYPE_TIME_FULL = 0x6, + LBCOL_TYPE_COUNT = 0x7 +}; + +enum LbAggType { LBAGG_TYPE_MIN = 0x0, LBAGG_TYPE_MAX = 0x1, LBAGG_TYPE_SUM = 0x2, LBAGG_TYPE_LAST = 0x3, LBAGG_TYPE_COUNT = 0x4 }; + +struct LbColumnDef { + const char *name; + int id; + int propertyId; + bool hidden; + const char *statName; + LbColType type; + int precision; + LbAggType agg; + int uiCalColX; + int uiCalColY; +}; + +enum LbUpdateType { LBUPDATE_TYPE_NORMAL = 0x0, LBUPDATE_TYPE_RANK = 0x1, LBUPDATE_TYPE_COMBINE = 0x2, LBUPDATE_TYPE_COUNT = 0x3 }; + +struct LeaderboardDef { + const char *name; + int id; + int columnCount; + int xpColId; + int prestigeColId; + LbColumnDef *columns; + LbUpdateType updateType; + int trackTypes; +}; + +struct StructuredDataEnumEntry { + const char *string; + unsigned short index; +}; + +struct StructuredDataEnum { + int entryCount; + int reservedEntryCount; + StructuredDataEnumEntry *entries; +}; + +enum StructuredDataTypeCategory { + DATA_INT = 0x0, + DATA_BYTE = 0x1, + DATA_BOOL = 0x2, + DATA_STRING = 0x3, + DATA_ENUM = 0x4, + DATA_STRUCT = 0x5, + DATA_INDEXED_ARRAY = 0x6, + DATA_ENUM_ARRAY = 0x7, + DATA_FLOAT = 0x8, + DATA_SHORT = 0x9, + DATA_COUNT = 0xA +}; + +union StructuredDataTypeUnion { + unsigned int stringDataLength; + int enumIndex; + int structIndex; + int indexedArrayIndex; + int enumedArrayIndex; +}; + +struct StructuredDataType { + StructuredDataTypeCategory type; + StructuredDataTypeUnion u; +}; + +enum StructuredDataValidationType { + VALIDATION_NONE = 0x0, + VALIDATION_CONSTANT = 0x1, + VALIDATION_INCREASECLAMP = 0x2, + VALIDATION_INCREASESTRICT = 0x3, + VALIDATION_DELTACLAMP = 0x4, + VALIDATION_DELTASTRICT = 0x5, + VALIDATION_XP = 0x6, + VALIDATION_COUNT = 0x7 +}; + +struct StructuredDataStructProperty { + const char *name; + StructuredDataType type; + unsigned int offset; + StructuredDataValidationType validation; +}; + +struct StructuredDataStruct { + int propertyCount; + StructuredDataStructProperty *properties; + int size; + unsigned int bitOffset; +}; + +struct StructuredDataIndexedArray { + int arraySize; + StructuredDataType elementType; + unsigned int elementSize; +}; + +struct StructuredDataEnumedArray { + int enumIndex; + StructuredDataType elementType; + unsigned int elementSize; +}; + +struct StructuredDataDef { + int version; + unsigned int formatChecksum; + int enumCount; + StructuredDataEnum *enums; + int structCount; + StructuredDataStruct *structs; + int indexedArrayCount; + StructuredDataIndexedArray *indexedArrays; + int enumedArrayCount; + StructuredDataEnumedArray *enumedArrays; + StructuredDataType rootType; + unsigned int size; +}; + +struct StructuredDataDefSet { + const char *name; + unsigned int defCount; + StructuredDataDef *defs; +}; + +struct TracerDef { + const char *name; + Material *material; + unsigned int drawInterval; + float speed; + float beamLength; + float beamWidth; + float screwRadius; + float screwDist; + float colors[5][4]; +}; + +enum VehicleType { + VEH_WHEELS_4 = 0x0, + VEH_TANK = 0x1, + VEH_PLANE = 0x2, + VEH_BOAT = 0x3, + VEH_ARTILLERY = 0x4, + VEH_HELICOPTER = 0x5, + VEH_SNOWMOBILE = 0x6, + VEH_SUBMARINE = 0x7, + VEH_UGV = 0x8, + VEH_TYPE_COUNT = 0x9 +}; + +enum VehicleAxleType { VEH_AXLE_FRONT = 0x0, VEH_AXLE_REAR = 0x1, VEH_AXLE_ALL = 0x2, VEH_AXLE_COUNT = 0x3 }; + +enum VehCamZOffsetMode { VEHCAM_ZMODE_WORLD = 0x0, VEHCAM_ZMODE_VEHICLE = 0x1, VEHCAM_ZMODE_VIEW = 0x2, VEHCAM_ZMODE_COUNT = 0x3 }; + +struct VehiclePhysDef { + int physicsEnabled; + const char *physPresetName; + PhysPreset *physPreset; + const char *accelGraphName; + VehicleAxleType steeringAxle; + VehicleAxleType powerAxle; + VehicleAxleType brakingAxle; + float topSpeed; + float reverseSpeed; + float maxVelocity; + float maxPitch; + float maxRoll; + float suspensionTravelFront; + float suspensionTravelRear; + float suspensionStrengthFront; + float suspensionDampingFront; + float suspensionStrengthRear; + float suspensionDampingRear; + float frictionBraking; + float frictionCoasting; + float frictionTopSpeed; + float frictionSide; + float frictionSideRear; + float velocityDependentSlip; + float rollStability; + float rollResistance; + float pitchResistance; + float yawResistance; + float uprightStrengthPitch; + float uprightStrengthRoll; + float targetAirPitch; + float airYawTorque; + float airPitchTorque; + float minimumMomentumForCollision; + float collisionLaunchForceScale; + float wreckedMassScale; + float wreckedBodyFriction; + float minimumJoltForNotify; + float slipThresholdFront; + float slipThresholdRear; + float slipFricScaleFront; + float slipFricScaleRear; + float slipFricRateFront; + float slipFricRateRear; + float slipYawTorque; +}; + +struct VehicleDef { + const char *name; + VehicleType type; + const char *useHintString; + int health; + int quadBarrel; + float texScrollScale; + float topSpeed; + float accel; + float rotRate; + float rotAccel; + float maxBodyPitch; + float maxBodyRoll; + int fakeBodyStabilizer; + float fakeBodyAccelPitch; + float fakeBodyAccelRoll; + float fakeBodyVelPitch; + float fakeBodyVelRoll; + float fakeBodySideVelPitch; + float fakeBodyPitchStrength; + float fakeBodyRollStrength; + float fakeBodyPitchDampening; + float fakeBodyRollDampening; + float fakeBodyBoatRockingAmplitude; + float fakeBodyBoatRockingPeriod; + float fakeBodyBoatRockingRotationPeriod; + float fakeBodyBoatRockingFadeoutSpeed; + float boatBouncingMinForce; + float boatBouncingMaxForce; + float boatBouncingRate; + float boatBouncingFadeinSpeed; + float boatBouncingFadeoutSteeringAngle; + float collisionDamage; + float collisionSpeed; + float killcamOffset[3]; + int playerProtected; + int bulletDamage; + int armorPiercingDamage; + int grenadeDamage; + int projectileDamage; + int projectileSplashDamage; + int heavyExplosiveDamage; + VehiclePhysDef vehPhysDef; + float boostDuration; + float boostRechargeTime; + float boostAcceleration; + float suspensionTravel; + float maxSteeringAngle; + float steeringLerp; + float minSteeringScale; + float minSteeringSpeed; + float vehHelicopterBoundsRadius; + float vehHelicopterMaxSpeed; + float vehHelicopterMaxSpeedVertical; + float vehHelicopterMaxAccel; + float vehHelicopterMaxAccelVertical; + float vehHelicopterDecelerationFwd; + float vehHelicopterDecelerationSide; + float vehHelicopterDecelerationUp; + float vehHelicopterMaxYawRate; + float vehHelicopterMaxYawAccel; + float vehHelicopterTiltFromVelocity; + float vehHelicopterTiltFromControllerAxes; + float vehHelicopterTiltFromAcceleration; + float vehHelicopterTiltFromDeceleration; + float vehHelicopterTiltFromFwdAndYaw_VelAtMaxTilt; + float vehHelicopterTiltFromFwdAndYaw; + float vehHelicopterTiltMomentum; + float vehHelicopterTiltSpeed; + float vehHelicopterMaxPitch; + float vehHelicopterMaxRoll; + float vehHelicopterHoverSpeedThreshold; + float vehHelicopterJitterJerkyness; + float vehHelicopterLookaheadTime; + int vehHelicopterSoftCollisions; + int camLookEnabled; + int camRelativeControl; + float camLerp; + float camHeight; + float camRadius; + float camPitchInfluence; + float camYawInfluence; + float camRollInfluence; + float camFovIncrease; + float camFovOffset; + float camFovSpeed; + float camReturnSpeed; + float camReturnLerp; + int vehCam_UseGDT; + float vehCam_anglesPitch; + float vehCam_anglesYaw; + float vehCam_anglesRoll; + float vehCam_offsetX; + float vehCam_offsetY; + float vehCam_offsetZ; + float vehCam_radius; + float vehCam_speedInfluence; + float vehCam_pitchTurnRate; + float vehCam_pitchClamp; + float vehCam_yawTurnRate; + float vehCam_yawClamp; + VehCamZOffsetMode vehCam_zOffsetMode; + float vehCam_anglesPitch3P; + float vehCam_anglesYaw3P; + float vehCam_anglesRoll3P; + float vehCam_offsetX3P; + float vehCam_offsetY3P; + float vehCam_offsetZ3P; + float vehCam_radius3P; + float vehCam_speedInfluence3P; + float vehCam_pitchTurnRate3P; + float vehCam_pitchClamp3P; + float vehCam_yawTurnRate3P; + float vehCam_yawClamp3P; + VehCamZOffsetMode vehCam_zOffsetMode3P; + const char *turretWeaponName; + WeaponCompleteDef *turretWeapon; + float turretHorizSpanLeft; + float turretHorizSpanRight; + float turretVertSpanUp; + float turretVertSpanDown; + float turretHorizResistLeft; + float turretHorizResistRight; + float turretVertResistUp; + float turretVertResistDown; + float turretRotRate; + SndAliasCustom turretSpinSnd; + SndAliasCustom turretStopSnd; + int trophyEnabled; + float trophyRadius; + float trophyInactiveRadius; + int trophyAmmoCount; + float trophyReloadTime; + ScriptString trophyTags[4]; + FxEffectDef *trophyExplodeFx; + FxEffectDef *trophyFlashFx; + Material *compassFriendlyIcon; + Material *compassEnemyIcon; + Material *compassFriendlyAltIcon; + Material *compassEnemyAltIcon; + int compassIconWidth; + int compassIconHeight; + SndAliasCustom idleLowSnd; + SndAliasCustom idleHighSnd; + SndAliasCustom engineLowSnd; + SndAliasCustom engineHighSnd; + float engineSndSpeed; + ScriptString audioOriginTag; + SndAliasCustom idleLowSndAlt; + SndAliasCustom idleHighSndAlt; + SndAliasCustom engineLowSndAlt; + SndAliasCustom engineHighSndAlt; + float engineSndSpeedAlt; + ScriptString audioOriginTagAlt; + SndAliasCustom turretSpinSndAlt; + SndAliasCustom turretStopSndAlt; + SndAliasCustom engineStartUpSnd; + int engineStartUpLength; + SndAliasCustom engineShutdownSnd; + SndAliasCustom engineIdleSnd; + SndAliasCustom engineSustainSnd; + SndAliasCustom engineRampUpSnd; + int engineRampUpLength; + SndAliasCustom engineRampDownSnd; + int engineRampDownLength; + SndAliasCustom suspensionSoftSnd; + float suspensionSoftCompression; + SndAliasCustom suspensionHardSnd; + float suspensionHardCompression; + SndAliasCustom collisionSnd; + float collisionBlendSpeed; + SndAliasCustom speedSnd; + float speedSndBlendSpeed; + const char *surfaceSndPrefix; + SndAliasCustom surfaceSnds[31]; + float surfaceSndBlendSpeed; + float slideVolume; + float slideBlendSpeed; + float inAirPitch; +}; + +struct cmodel2_t { + Bounds bounds; + float radius; + ClipInfo *info; + cLeaf_t leaf; +}; + +struct AddonMapEnts { + const char *name; + char *entityString; + int numEntityChars; + MapTriggers trigger; + ClipInfo *info; + unsigned int numSubModels; + cmodel2_t *cmodels; + GfxBrushModel *models; +}; #ifndef __zonecodegenerator #ifndef __ida diff --git a/src/Common/Game/T5/CommonT5.cpp b/src/Common/Game/T5/CommonT5.cpp index 48e76a1b8..cda5cb33b 100644 --- a/src/Common/Game/T5/CommonT5.cpp +++ b/src/Common/Game/T5/CommonT5.cpp @@ -6,84 +6,60 @@ using namespace T5; -int Common::Com_HashKey(const char* str, const int maxLen) -{ - if (str == nullptr) - return 0; +int Common::Com_HashKey(const char *str, const int maxLen) { + if (str == nullptr) + return 0; - int hash = 0; - for (int i = 0; i < maxLen; i++) - { - if (str[i] == '\0') - break; + int hash = 0; + for (int i = 0; i < maxLen; i++) { + if (str[i] == '\0') + break; - hash += str[i] * (0x77 + i); - } + hash += str[i] * (0x77 + i); + } - return hash ^ ((hash ^ (hash >> 10)) >> 10); + return hash ^ ((hash ^ (hash >> 10)) >> 10); } -int Common::Com_HashString(const char* str) -{ - if (!str) - return 0; +int Common::Com_HashString(const char *str) { + if (!str) + return 0; - auto result = 0x1505; - auto offset = 0; - while (str[offset]) - { - const auto c = tolower(str[offset++]); - result = c + 33 * result; - } + auto result = 0x1505; + auto offset = 0; + while (str[offset]) { + const auto c = tolower(str[offset++]); + result = c + 33 * result; + } - return result; + return result; } -int Common::Com_HashString(const char* str, const int len) -{ - if (!str) - return 0; +int Common::Com_HashString(const char *str, const int len) { + if (!str) + return 0; - int result = 0x1505; - int offset = 0; - while (str[offset]) - { - if (len > 0 && offset >= len) - break; + int result = 0x1505; + int offset = 0; + while (str[offset]) { + if (len > 0 && offset >= len) + break; - const int c = tolower(str[offset++]); - result = c + 33 * result; - } + const int c = tolower(str[offset++]); + result = c + 33 * result; + } - return result; + return result; } -PackedTexCoords Common::Vec2PackTexCoords(const vec2_t* in) -{ - return PackedTexCoords{Pack32::Vec2PackTexCoords(reinterpret_cast(in))}; -} +PackedTexCoords Common::Vec2PackTexCoords(const vec2_t *in) { return PackedTexCoords{Pack32::Vec2PackTexCoords(reinterpret_cast(in))}; } -PackedUnitVec Common::Vec3PackUnitVec(const vec3_t* in) -{ - return PackedUnitVec{Pack32::Vec3PackUnitVec(reinterpret_cast(in))}; -} +PackedUnitVec Common::Vec3PackUnitVec(const vec3_t *in) { return PackedUnitVec{Pack32::Vec3PackUnitVec(reinterpret_cast(in))}; } -GfxColor Common::Vec4PackGfxColor(const vec4_t* in) -{ - return GfxColor{Pack32::Vec4PackGfxColor(reinterpret_cast(in))}; -} +GfxColor Common::Vec4PackGfxColor(const vec4_t *in) { return GfxColor{Pack32::Vec4PackGfxColor(reinterpret_cast(in))}; } -void Common::Vec2UnpackTexCoords(const PackedTexCoords& in, vec2_t* out) -{ - Pack32::Vec2UnpackTexCoordsVU(in.packed, reinterpret_cast(out)); -} +void Common::Vec2UnpackTexCoords(const PackedTexCoords &in, vec2_t *out) { Pack32::Vec2UnpackTexCoordsVU(in.packed, reinterpret_cast(out)); } -void Common::Vec3UnpackUnitVec(const PackedUnitVec& in, vec3_t* out) -{ - Pack32::Vec3UnpackUnitVecScaleBased(in.packed, reinterpret_cast(out)); -} +void Common::Vec3UnpackUnitVec(const PackedUnitVec &in, vec3_t *out) { Pack32::Vec3UnpackUnitVecScaleBased(in.packed, reinterpret_cast(out)); } -void Common::Vec4UnpackGfxColor(const GfxColor& in, vec4_t* out) -{ - Pack32::Vec4UnpackGfxColor(in.packed, reinterpret_cast(out)); -} +void Common::Vec4UnpackGfxColor(const GfxColor &in, vec4_t *out) { Pack32::Vec4UnpackGfxColor(in.packed, reinterpret_cast(out)); } diff --git a/src/Common/Game/T5/CommonT5.h b/src/Common/Game/T5/CommonT5.h index 2f431858e..33d7db2c1 100644 --- a/src/Common/Game/T5/CommonT5.h +++ b/src/Common/Game/T5/CommonT5.h @@ -2,20 +2,18 @@ #include "T5.h" -namespace T5 -{ - class Common - { - public: - static int Com_HashKey(const char* str, int maxLen); - static int Com_HashString(const char* str); - static int Com_HashString(const char* str, int len); +namespace T5 { +class Common { +public: + static int Com_HashKey(const char *str, int maxLen); + static int Com_HashString(const char *str); + static int Com_HashString(const char *str, int len); - static PackedTexCoords Vec2PackTexCoords(const vec2_t* in); - static PackedUnitVec Vec3PackUnitVec(const vec3_t* in); - static GfxColor Vec4PackGfxColor(const vec4_t* in); - static void Vec2UnpackTexCoords(const PackedTexCoords& in, vec2_t* out); - static void Vec3UnpackUnitVec(const PackedUnitVec& in, vec3_t* out); - static void Vec4UnpackGfxColor(const GfxColor& in, vec4_t* out); - }; -} \ No newline at end of file + static PackedTexCoords Vec2PackTexCoords(const vec2_t *in); + static PackedUnitVec Vec3PackUnitVec(const vec3_t *in); + static GfxColor Vec4PackGfxColor(const vec4_t *in); + static void Vec2UnpackTexCoords(const PackedTexCoords &in, vec2_t *out); + static void Vec3UnpackUnitVec(const PackedUnitVec &in, vec3_t *out); + static void Vec4UnpackGfxColor(const GfxColor &in, vec4_t *out); +}; +} // namespace T5 \ No newline at end of file diff --git a/src/Common/Game/T5/GameT5.cpp b/src/Common/Game/T5/GameT5.cpp index a0c6edcc8..747f5799d 100644 --- a/src/Common/Game/T5/GameT5.cpp +++ b/src/Common/Game/T5/GameT5.cpp @@ -8,51 +8,37 @@ using namespace T5; GameT5 g_GameT5; -std::string GameT5::GetFullName() -{ - return "Call Of Duty: Black Ops"; -} +std::string GameT5::GetFullName() { return "Call Of Duty: Black Ops"; } -std::string GameT5::GetShortName() -{ - return "T5"; -} +std::string GameT5::GetShortName() { return "T5"; } -void GameT5::AddZone(Zone* zone) -{ - m_zones.push_back(zone); -} +void GameT5::AddZone(Zone *zone) { m_zones.push_back(zone); } -void GameT5::RemoveZone(Zone* zone) -{ - const auto foundEntry = std::find(m_zones.begin(), m_zones.end(), zone); - - if (foundEntry != m_zones.end()) - m_zones.erase(foundEntry); -} +void GameT5::RemoveZone(Zone *zone) { + const auto foundEntry = std::find(m_zones.begin(), m_zones.end(), zone); -std::vector GameT5::GetZones() -{ - return m_zones; + if (foundEntry != m_zones.end()) + m_zones.erase(foundEntry); } -std::vector GameT5::GetLanguagePrefixes() -{ - std::vector prefixes; - - prefixes.emplace_back(GameLanguage::LANGUAGE_ENGLISH, "en_"); - prefixes.emplace_back(GameLanguage::LANGUAGE_FRENCH, "fr_"); - prefixes.emplace_back(GameLanguage::LANGUAGE_FRENCH_CAN, "fc_"); - prefixes.emplace_back(GameLanguage::LANGUAGE_GERMAN, "ge_"); - prefixes.emplace_back(GameLanguage::LANGUAGE_AUSTRIAN, "ge_"); - prefixes.emplace_back(GameLanguage::LANGUAGE_ITALIAN, "it_"); - prefixes.emplace_back(GameLanguage::LANGUAGE_SPANISH, "sp_"); - prefixes.emplace_back(GameLanguage::LANGUAGE_BRITISH, "br_"); - prefixes.emplace_back(GameLanguage::LANGUAGE_RUSSIAN, "ru_"); - prefixes.emplace_back(GameLanguage::LANGUAGE_POLISH, "po_"); - prefixes.emplace_back(GameLanguage::LANGUAGE_KOREAN, "ko_"); - prefixes.emplace_back(GameLanguage::LANGUAGE_JAPANESE, "ja_"); - prefixes.emplace_back(GameLanguage::LANGUAGE_CZECH, "cz_"); - - return prefixes; +std::vector GameT5::GetZones() { return m_zones; } + +std::vector GameT5::GetLanguagePrefixes() { + std::vector prefixes; + + prefixes.emplace_back(GameLanguage::LANGUAGE_ENGLISH, "en_"); + prefixes.emplace_back(GameLanguage::LANGUAGE_FRENCH, "fr_"); + prefixes.emplace_back(GameLanguage::LANGUAGE_FRENCH_CAN, "fc_"); + prefixes.emplace_back(GameLanguage::LANGUAGE_GERMAN, "ge_"); + prefixes.emplace_back(GameLanguage::LANGUAGE_AUSTRIAN, "ge_"); + prefixes.emplace_back(GameLanguage::LANGUAGE_ITALIAN, "it_"); + prefixes.emplace_back(GameLanguage::LANGUAGE_SPANISH, "sp_"); + prefixes.emplace_back(GameLanguage::LANGUAGE_BRITISH, "br_"); + prefixes.emplace_back(GameLanguage::LANGUAGE_RUSSIAN, "ru_"); + prefixes.emplace_back(GameLanguage::LANGUAGE_POLISH, "po_"); + prefixes.emplace_back(GameLanguage::LANGUAGE_KOREAN, "ko_"); + prefixes.emplace_back(GameLanguage::LANGUAGE_JAPANESE, "ja_"); + prefixes.emplace_back(GameLanguage::LANGUAGE_CZECH, "cz_"); + + return prefixes; } diff --git a/src/Common/Game/T5/GameT5.h b/src/Common/Game/T5/GameT5.h index 4efd025dd..b03e65333 100644 --- a/src/Common/Game/T5/GameT5.h +++ b/src/Common/Game/T5/GameT5.h @@ -1,17 +1,16 @@ #pragma once #include "Game/IGame.h" -class GameT5 : public IGame -{ - std::vector m_zones; +class GameT5 : public IGame { + std::vector m_zones; public: - std::string GetFullName() override; - std::string GetShortName() override; - void AddZone(Zone* zone) override; - void RemoveZone(Zone* zone) override; - std::vector GetZones() override; - std::vector GetLanguagePrefixes() override; + std::string GetFullName() override; + std::string GetShortName() override; + void AddZone(Zone *zone) override; + void RemoveZone(Zone *zone) override; + std::vector GetZones() override; + std::vector GetLanguagePrefixes() override; }; extern GameT5 g_GameT5; \ No newline at end of file diff --git a/src/Common/Game/T5/T5.h b/src/Common/Game/T5/T5.h index 512458e35..6f2af8ecb 100644 --- a/src/Common/Game/T5/T5.h +++ b/src/Common/Game/T5/T5.h @@ -1,113 +1,104 @@ #pragma once -//#include +// #include #include "Image/Texture.h" #include "T5_Assets.h" -namespace T5 -{ - struct ScriptStringList - { - int count; - const char** strings; - }; +namespace T5 { +struct ScriptStringList { + int count; + const char **strings; +}; - struct XAsset - { - XAssetType type; - XAssetHeader header; - }; +struct XAsset { + XAssetType type; + XAssetHeader header; +}; - struct XAssetList - { - ScriptStringList stringList; - int assetCount; - XAsset* assets; - }; +struct XAssetList { + ScriptStringList stringList; + int assetCount; + XAsset *assets; +}; - struct cspField_t - { - const char* szName; - int iOffset; - int iFieldType; - }; +struct cspField_t { + const char *szName; + int iOffset; + int iFieldType; +}; - enum csParseFieldType_t - { - CSPFT_STRING, - CSPFT_STRING_MAX_STRING_CHARS, - CSPFT_STRING_MAX_QPATH, - CSPFT_STRING_MAX_OSPATH, - CSPFT_INT, - CSPFT_BOOL, - CSPFT_QBOOLEAN, - CSPFT_FLOAT, - CSPFT_MILLISECONDS, - CSPFT_FX, - CSPFT_XMODEL, - CSPFT_MATERIAL, - CSPFT_MATERIAL_STREAM, - CSPFT_PHYS_PRESET, - CSPFT_SCRIPT_STRING, +enum csParseFieldType_t { + CSPFT_STRING, + CSPFT_STRING_MAX_STRING_CHARS, + CSPFT_STRING_MAX_QPATH, + CSPFT_STRING_MAX_OSPATH, + CSPFT_INT, + CSPFT_BOOL, + CSPFT_QBOOLEAN, + CSPFT_FLOAT, + CSPFT_MILLISECONDS, + CSPFT_FX, + CSPFT_XMODEL, + CSPFT_MATERIAL, + CSPFT_MATERIAL_STREAM, + CSPFT_PHYS_PRESET, + CSPFT_SCRIPT_STRING, - CSPFT_NUM_BASE_FIELD_TYPES - }; + CSPFT_NUM_BASE_FIELD_TYPES +}; - enum weapFieldType_t - { - WFT_WEAPONTYPE = CSPFT_NUM_BASE_FIELD_TYPES, - WFT_WEAPONCLASS, - WFT_OVERLAYRETICLE, - WFT_PENETRATE_TYPE, - WFT_IMPACT_TYPE, - WFT_STANCE, - WFT_PROJ_EXPLOSION, - WFT_OFFHAND_CLASS, - WFT_OFFHAND_SLOT, - WFT_ANIMTYPE, - WFT_ACTIVE_RETICLE_TYPE, - WFT_GUIDED_MISSILE_TYPE, - WFT_BOUNCE_SOUND, - WFT_STICKINESS, - WFT_ROTATETYPE, - WFT_OVERLAYINTERFACE, - WFT_INVENTORYTYPE, - WFT_FIRETYPE, - WFT_CLIPTYPE, - WFT_AMMOCOUNTER_CLIPTYPE, - WFT_ICONRATIO_HUD, - WFT_ICONRATIO_AMMOCOUNTER, - WFT_ICONRATIO_KILL, - WFT_ICONRATIO_DPAD, - WFT_ICONRATIO_INDICATOR, - WFT_HIDETAGS, - WFT_EXPLOSION_TAG, - WFT_NOTETRACKSOUNDMAP, +enum weapFieldType_t { + WFT_WEAPONTYPE = CSPFT_NUM_BASE_FIELD_TYPES, + WFT_WEAPONCLASS, + WFT_OVERLAYRETICLE, + WFT_PENETRATE_TYPE, + WFT_IMPACT_TYPE, + WFT_STANCE, + WFT_PROJ_EXPLOSION, + WFT_OFFHAND_CLASS, + WFT_OFFHAND_SLOT, + WFT_ANIMTYPE, + WFT_ACTIVE_RETICLE_TYPE, + WFT_GUIDED_MISSILE_TYPE, + WFT_BOUNCE_SOUND, + WFT_STICKINESS, + WFT_ROTATETYPE, + WFT_OVERLAYINTERFACE, + WFT_INVENTORYTYPE, + WFT_FIRETYPE, + WFT_CLIPTYPE, + WFT_AMMOCOUNTER_CLIPTYPE, + WFT_ICONRATIO_HUD, + WFT_ICONRATIO_AMMOCOUNTER, + WFT_ICONRATIO_KILL, + WFT_ICONRATIO_DPAD, + WFT_ICONRATIO_INDICATOR, + WFT_HIDETAGS, + WFT_EXPLOSION_TAG, + WFT_NOTETRACKSOUNDMAP, - WFT_NUM_FIELD_TYPES - }; + WFT_NUM_FIELD_TYPES +}; - enum VehicleFieldType - { - VFT_TYPE = CSPFT_NUM_BASE_FIELD_TYPES, - VFT_CAMERAMODE, - VFT_BOOSTMODE, - VFT_TRACTION_TYPE, - VFT_MPH_TO_INCHES_PER_SECOND, - VFT_POUNDS_TO_GAME_MASS, - VFT_SCR_STRING, - VFT_TEAM, - VFT_KEY_BINDING, - VFT_GRAPH, +enum VehicleFieldType { + VFT_TYPE = CSPFT_NUM_BASE_FIELD_TYPES, + VFT_CAMERAMODE, + VFT_BOOSTMODE, + VFT_TRACTION_TYPE, + VFT_MPH_TO_INCHES_PER_SECOND, + VFT_POUNDS_TO_GAME_MASS, + VFT_SCR_STRING, + VFT_TEAM, + VFT_KEY_BINDING, + VFT_GRAPH, - VFT_NUM - }; + VFT_NUM +}; - enum constraintsFieldType_t - { - CFT_TYPE = CSPFT_NUM_BASE_FIELD_TYPES, +enum constraintsFieldType_t { + CFT_TYPE = CSPFT_NUM_BASE_FIELD_TYPES, - CFT_NUM_FIELD_TYPES - }; -} + CFT_NUM_FIELD_TYPES +}; +} // namespace T5 diff --git a/src/Common/Game/T5/T5_Assets.h b/src/Common/Game/T5/T5_Assets.h index 35c9eba80..3a85a8eba 100644 --- a/src/Common/Game/T5/T5_Assets.h +++ b/src/Common/Game/T5/T5_Assets.h @@ -6,4542 +6,4207 @@ #include "../../Utils/TypeAlignment.h" #ifndef __zonecodegenerator -namespace T5 -{ +namespace T5 { #endif - struct PhysPreset; - struct PhysConstraints; - struct DestructibleDef; - struct XAnimParts; - struct XModel; - struct Material; - struct MaterialTechniqueSet; - struct GfxImage; - struct SndBank; - struct SndPatch; - struct clipMap_t; - struct ComWorld; - struct GameWorldSp; - struct GameWorldMp; - struct MapEnts; - struct GfxWorld; - struct GfxLightDef; - struct Font_s; - struct MenuList; - struct menuDef_t; - struct LocalizeEntry; - struct WeaponVariantDef; - struct SndDriverGlobals; - struct FxEffectDef; - struct FxImpactTable; - struct RawFile; - struct StringTable; - struct PackIndex; - struct XGlobals; - struct ddlRoot_t; - struct Glasses; - struct EmblemSet; - - enum XAssetType - { - ASSET_TYPE_XMODELPIECES = 0x0, - ASSET_TYPE_PHYSPRESET = 0x1, - ASSET_TYPE_PHYSCONSTRAINTS = 0x2, - ASSET_TYPE_DESTRUCTIBLEDEF = 0x3, - ASSET_TYPE_XANIMPARTS = 0x4, - ASSET_TYPE_XMODEL = 0x5, - ASSET_TYPE_MATERIAL = 0x6, - ASSET_TYPE_TECHNIQUE_SET = 0x7, - ASSET_TYPE_IMAGE = 0x8, - ASSET_TYPE_SOUND = 0x9, - ASSET_TYPE_SOUND_PATCH = 0xA, - ASSET_TYPE_CLIPMAP = 0xB, - ASSET_TYPE_CLIPMAP_PVS = 0xC, - ASSET_TYPE_COMWORLD = 0xD, - ASSET_TYPE_GAMEWORLD_SP = 0xE, - ASSET_TYPE_GAMEWORLD_MP = 0xF, - ASSET_TYPE_MAP_ENTS = 0x10, - ASSET_TYPE_GFXWORLD = 0x11, - ASSET_TYPE_LIGHT_DEF = 0x12, - ASSET_TYPE_UI_MAP = 0x13, - ASSET_TYPE_FONT = 0x14, - ASSET_TYPE_MENULIST = 0x15, - ASSET_TYPE_MENU = 0x16, - ASSET_TYPE_LOCALIZE_ENTRY = 0x17, - ASSET_TYPE_WEAPON = 0x18, - ASSET_TYPE_WEAPONDEF = 0x19, - ASSET_TYPE_WEAPON_VARIANT = 0x1A, - ASSET_TYPE_SNDDRIVER_GLOBALS = 0x1B, - ASSET_TYPE_FX = 0x1C, - ASSET_TYPE_IMPACT_FX = 0x1D, - ASSET_TYPE_AITYPE = 0x1E, - ASSET_TYPE_MPTYPE = 0x1F, - ASSET_TYPE_MPBODY = 0x20, - ASSET_TYPE_MPHEAD = 0x21, - ASSET_TYPE_CHARACTER = 0x22, - ASSET_TYPE_XMODELALIAS = 0x23, - ASSET_TYPE_RAWFILE = 0x24, - ASSET_TYPE_STRINGTABLE = 0x25, - ASSET_TYPE_PACK_INDEX = 0x26, - ASSET_TYPE_XGLOBALS = 0x27, - ASSET_TYPE_DDL = 0x28, - ASSET_TYPE_GLASSES = 0x29, - ASSET_TYPE_EMBLEMSET = 0x2A, - ASSET_TYPE_COUNT = 0x2B, - ASSET_TYPE_STRING = 0x2B, - ASSET_TYPE_ASSETLIST = 0x2C, - - ASSET_TYPE_FULL_COUNT - }; - - enum XFileBlock - { - XFILE_BLOCK_TEMP, - XFILE_BLOCK_RUNTIME, - XFILE_BLOCK_LARGE_RUNTIME, - XFILE_BLOCK_PHYSICAL_RUNTIME, - XFILE_BLOCK_VIRTUAL, - XFILE_BLOCK_LARGE, - XFILE_BLOCK_PHYSICAL, - - MAX_XFILE_COUNT - }; - - typedef float vec2_t[2]; - typedef float vec3_t[3]; - typedef float vec4_t[4]; - - union XAssetHeader - { - //XModelPieces *xmodelPieces; // Not an asset - PhysPreset *physPreset; - PhysConstraints *physConstraints; - DestructibleDef *destructibleDef; - XAnimParts *parts; - XModel *model; - Material *material; - //MaterialPixelShader *pixelShader; // Not an asset - //MaterialVertexShader *vertexShader; // Not an asset - MaterialTechniqueSet *techniqueSet; - GfxImage *image; - SndBank *sound; - SndPatch *soundPatch; - clipMap_t *clipMap; - ComWorld *comWorld; - GameWorldSp *gameWorldSp; - GameWorldMp *gameWorldMp; - MapEnts *mapEnts; - GfxWorld *gfxWorld; - GfxLightDef *lightDef; - Font_s *font; - MenuList *menuList; - menuDef_t *menu; - LocalizeEntry *localize; - WeaponVariantDef *weapon; - SndDriverGlobals *sndDriverGlobals; - FxEffectDef *fx; - FxImpactTable *impactFx; - RawFile *rawfile; - StringTable *stringTable; - PackIndex *packIndex; - XGlobals *xGlobals; - ddlRoot_t *ddlRoot; - Glasses *glasses; - //TextureList *textureList; // Not an asset - EmblemSet *emblemSet; - void *data; - }; - - typedef tdef_align(16) char char16; - typedef tdef_align(32) char byte32; - typedef tdef_align(128) char byte128; - - typedef tdef_align(4) char char_align4; - typedef tdef_align(128) char char_align128; - - typedef tdef_align(16) char raw_byte16; - typedef tdef_align(128) char raw_byte128; - - typedef tdef_align(128) float float_align128; - - typedef char cbrushedge_t; - typedef float vec2_t[2]; - typedef float vec3_t[3]; - typedef tdef_align(128) unsigned int raw_uint128; - - struct PhysPreset - { - const char* name; - int flags; - float mass; - float bounce; - float friction; - float bulletForceScale; - float explosiveForceScale; - const char* sndAliasPrefix; - float piecesSpreadFraction; - float piecesUpwardVelocity; - int canFloat; - float gravityScale; - vec3_t centerOfMassOffset; - vec3_t buoyancyBoxMin; - vec3_t buoyancyBoxMax; - }; - - enum ConstraintType - { - CONSTRAINT_NONE = 0x0, - CONSTRAINT_POINT = 0x1, - CONSTRAINT_DISTANCE = 0x2, - CONSTRAINT_HINGE = 0x3, - CONSTRAINT_JOINT = 0x4, - CONSTRAINT_ACTUATOR = 0x5, - CONSTRAINT_FAKE_SHAKE = 0x6, - CONSTRAINT_LAUNCH = 0x7, - CONSTRAINT_ROPE = 0x8, - CONSTRAINT_LIGHT = 0x9, - - NUM_CONSTRAINT_TYPES - }; - - enum AttachPointType - { - ATTACH_POINT_WORLD = 0x0, - ATTACH_POINT_DYNENT = 0x1, - ATTACH_POINT_ENT = 0x2, - ATTACH_POINT_BONE = 0x3, - }; - - struct PhysConstraint - { - uint16_t targetname; - ConstraintType type; - AttachPointType attach_point_type1; - int target_index1; - uint16_t target_ent1; - const char* target_bone1; - AttachPointType attach_point_type2; - int target_index2; - uint16_t target_ent2; - const char* target_bone2; - vec3_t offset; - vec3_t pos; - vec3_t pos2; - vec3_t dir; - int flags; - int timeout; - int min_health; - int max_health; - float distance; - float damp; - float power; - vec3_t scale; - float spin_scale; - float minAngle; - float maxAngle; - Material* material; - int constraintHandle; - int rope_index; - int centity_num[4]; - }; - - struct PhysConstraints - { - const char* name; - unsigned int count; - PhysConstraint data[16]; - }; - - struct DestructibleStage - { - uint16_t showBone; - float breakHealth; - float maxTime; - unsigned int flags; - FxEffectDef* breakEffect; - const char* breakSound; - const char* breakNotify; - const char* loopSound; - XModel* spawnModel[3]; - PhysPreset* physPreset; - }; - - struct DestructiblePiece - { - DestructibleStage stages[5]; - char parentPiece; - float parentDamagePercent; - float bulletDamageScale; - float explosiveDamageScale; - float meleeDamageScale; - float impactDamageScale; - float entityDamageTransfer; - PhysConstraints* physConstraints; - int health; - const char* damageSound; - FxEffectDef* burnEffect; - const char* burnSound; - uint16_t enableLabel; - int hideBones[5]; - }; - - struct DestructibleDef - { - const char* name; - XModel* model; - XModel* pristineModel; - int numPieces; - DestructiblePiece* pieces; - int clientOnly; - }; - - union XAnimIndices - { - char* _1; - uint16_t* _2; - void* data; - }; - - struct XAnimNotifyInfo - { - uint16_t name; - float time; - }; - - typedef unsigned char ByteVec[3]; - typedef tdef_align(4) unsigned short UShortVec[3]; - - union XAnimDynamicFrames - { - ByteVec* _1; - UShortVec* _2; - }; - - union XAnimDynamicIndicesTrans - { - char _1[1]; - uint16_t _2[1]; - }; - - struct XAnimPartTransFrames - { - float mins[3]; - float size[3]; - XAnimDynamicFrames frames; - XAnimDynamicIndicesTrans indices; - }; - - union XAnimPartTransData - { - XAnimPartTransFrames frames; - vec3_t frame0; - }; - - struct XAnimPartTrans - { - uint16_t size; - char smallTrans; - XAnimPartTransData u; - }; - - typedef tdef_align(4) short XQuat[2]; - - union XAnimDynamicIndicesQuat - { - char _1[1]; - uint16_t _2[1]; - }; - - struct XAnimDeltaPartQuatDataFrames - { - XQuat* frames; - XAnimDynamicIndicesQuat indices; - }; - - union XAnimDeltaPartQuatData - { - XAnimDeltaPartQuatDataFrames frames; - int16_t frame0[2]; - }; - - struct XAnimDeltaPartQuat - { - uint16_t size; - XAnimDeltaPartQuatData u; - }; - - struct XAnimDeltaPart - { - XAnimPartTrans* trans; - XAnimDeltaPartQuat* quat; - }; - - struct XAnimParts - { - const char* name; - uint16_t dataByteCount; - uint16_t dataShortCount; - uint16_t dataIntCount; - uint16_t randomDataByteCount; - uint16_t randomDataIntCount; - uint16_t numframes; - bool bLoop; - bool bDelta; - bool bLeftHandGripIK; - bool bStreamable; - unsigned int streamedFileSize; - unsigned char boneCount[10]; - unsigned char notifyCount; - char assetType; - bool isDefault; - unsigned int randomDataShortCount; - unsigned int indexCount; - float framerate; - float frequency; - float primedLength; - float loopEntryTime; - uint16_t* names; - char* dataByte; - int16_t* dataShort; - int* dataInt; - int16_t* randomDataShort; - char* randomDataByte; - int* randomDataInt; - XAnimIndices indices; - XAnimNotifyInfo* notify; - XAnimDeltaPart* deltaPart; - }; - - struct DObjSkelMat - { - float axis[3][4]; - float origin[4]; - }; - - struct DObjAnimMat - { - float quat[4]; - float trans[3]; - float transWeight; - }; - - struct XSurfaceVertexInfo - { - int16_t vertCount[4]; - uint16_t* vertsBlend; - float* tensionData; - }; - - union GfxColor - { - unsigned int packed; - char array[4]; - }; - - union PackedTexCoords - { - unsigned int packed; - }; - - union PackedUnitVec - { - unsigned int packed; - char array[4]; - }; - - struct type_align(16) GfxPackedVertex - { - float xyz[3]; - float binormalSign; - GfxColor color; - PackedTexCoords texCoord; - PackedUnitVec normal; - PackedUnitVec tangent; - }; - - struct XSurfaceCollisionLeaf - { - uint16_t triangleBeginIndex; - }; - - struct XSurfaceCollisionAabb - { - uint16_t mins[3]; - uint16_t maxs[3]; - }; - - struct type_align(16) XSurfaceCollisionNode - { - XSurfaceCollisionAabb aabb; - uint16_t childBeginIndex; - uint16_t childCount; - }; - - struct XSurfaceCollisionTree - { - float trans[3]; - float scale[3]; - unsigned int nodeCount; - XSurfaceCollisionNode* nodes; - unsigned int leafCount; - XSurfaceCollisionLeaf* leafs; - }; - - struct XRigidVertList - { - uint16_t boneOffset; - uint16_t vertCount; - uint16_t triOffset; - uint16_t triCount; - XSurfaceCollisionTree* collisionTree; - }; - - typedef tdef_align(16) uint16_t r_index16_t; - - struct XSurface - { - char tileMode; - unsigned char vertListCount; - uint16_t flags; - uint16_t vertCount; - uint16_t triCount; - uint16_t baseTriIndex; - uint16_t baseVertIndex; - r_index16_t(*triIndices)[3]; - XSurfaceVertexInfo vertInfo; - GfxPackedVertex* verts0; - void/*IDirect3DVertexBuffer9*/* vb0; - XRigidVertList* vertList; - void/*IDirect3DIndexBuffer9*/* indexBuffer; - int partBits[5]; - }; - - struct XModelLodInfo - { - float dist; - uint16_t numsurfs; - uint16_t surfIndex; - int partBits[5]; - char lod; - char smcIndexPlusOne; - char smcAllocBits; - char unused; - }; - - struct XModelCollTri_s - { - float plane[4]; - float svec[4]; - float tvec[4]; - }; - - struct XModelCollSurf_s - { - XModelCollTri_s* collTris; - int numCollTris; - float mins[3]; - float maxs[3]; - int boneIdx; - int contents; - int surfFlags; - }; - - struct XBoneInfo - { - float bounds[2][3]; - float offset[3]; - float radiusSquared; - char collmap; - }; - - struct XModelHighMipBounds - { - float center[3]; - float himipRadiusSq; - }; - - struct XModelStreamInfo - { - XModelHighMipBounds* highMipBounds; - }; - - struct cplane_s - { - vec3_t normal; - float dist; - char type; - char signbits; - char pad[2]; - }; - - struct cbrushside_t - { - cplane_s* plane; - int cflags; - int sflags; - }; - - struct type_align(16) BrushWrapper - { - vec3_t mins; - int contents; - vec3_t maxs; - unsigned int numsides; - cbrushside_t* sides; - int axial_cflags[2][3]; - int axial_sflags[2][3]; - unsigned int numverts; - vec3_t* verts; - cplane_s* planes; - }; - - struct PhysGeomInfo - { - BrushWrapper* brush; - int type; - vec3_t orientation[3]; - vec3_t offset; - vec3_t halfLengths; - }; - - typedef tdef_align(16) PhysGeomInfo PhysGeomInfo16; - - struct PhysGeomList - { - unsigned int count; - PhysGeomInfo16* geoms; - int contents; - }; - - struct Collmap - { - PhysGeomList* geomList; - }; - - struct XModel - { - const char* name; - unsigned char numBones; - unsigned char numRootBones; - unsigned char numsurfs; - char lodRampType; - uint16_t* boneNames; - char* parentList; - int16_t(*quats)[4]; - float(*trans)[4]; - char* partClassification; - DObjAnimMat* baseMat; - XSurface* surfs; - Material** materialHandles; - XModelLodInfo lodInfo[4]; - char lodDistAutoGenerated; - XModelCollSurf_s* collSurfs; - int numCollSurfs; - int contents; - XBoneInfo* boneInfo; - float radius; - float mins[3]; - float maxs[3]; - uint16_t numLods; - uint16_t collLod; - XModelStreamInfo streamInfo; - int memUsage; - int flags; - bool bad; - PhysPreset* physPreset; - unsigned char numCollmaps; - Collmap* collmaps; - PhysConstraints* physConstraints; - }; - - struct gcc_align(8) GfxDrawSurfFields - { - uint64_t objectId : 16; - uint64_t fade : 4; - uint64_t customIndex : 5; - uint64_t reflectionProbeIndex : 3; - uint64_t hdrBits : 1; - uint64_t glightRender : 1; - uint64_t dlightRender : 1; - uint64_t materialSortedIndex : 12; - uint64_t primaryLightIndex : 8; - uint64_t surfType : 4; - uint64_t prepass : 2; - uint64_t noDynamicShadow : 1; - uint64_t primarySortKey : 6; - }; - - union GfxDrawSurf - { - gcc_align(8) GfxDrawSurfFields fields; - gcc_align(8) uint64_t packed; - }; - - struct MaterialInfo - { - const char* name; - unsigned int gameFlags; - char pad; - char sortKey; - char textureAtlasRowCount; - char textureAtlasColumnCount; - GfxDrawSurf drawSurf; - unsigned int surfaceTypeBits; - unsigned int layeredSurfaceTypes; - uint16_t hashIndex; - }; - - struct WaterWritable - { - float floatTime; - }; - - struct complex_s - { - float real; - float imag; - }; - - struct water_t - { - WaterWritable writable; - complex_s* H0; - float* wTerm; - int M; - int N; - float Lx; - float Lz; - float gravity; - float windvel; - float winddir[2]; - float amplitude; - float codeConstant[4]; - GfxImage* image; - }; - - union MaterialTextureDefInfo - { - GfxImage* image; - water_t* water; - }; - - struct MaterialTextureDef - { - unsigned int nameHash; - char nameStart; - char nameEnd; - char samplerState; - char semantic; - char isMatureContent; - char pad[3]; - MaterialTextureDefInfo u; - }; - - struct type_align(16) MaterialConstantDef - { - unsigned int nameHash; - char name[12]; - float literal[4]; - }; - - enum GfxStateBitsEnum : unsigned int - { - GFXS0_SRCBLEND_RGB_SHIFT = 0x0, - GFXS0_SRCBLEND_RGB_MASK = 0xF, - GFXS0_DSTBLEND_RGB_SHIFT = 0x4, - GFXS0_DSTBLEND_RGB_MASK = 0xF0, - GFXS0_BLENDOP_RGB_SHIFT = 0x8, - GFXS0_BLENDOP_RGB_MASK = 0x700, - GFXS0_BLEND_RGB_MASK = 0x7FF, - GFXS0_ATEST_DISABLE = 0x800, - GFXS0_ATEST_GT_0 = 0x1000, - GFXS0_ATEST_GE_255 = 0x2000, - GFXS0_ATEST_GE_128 = 0x3000, - GFXS0_ATEST_MASK = 0x3000, - GFXS0_CULL_SHIFT = 0xE, - GFXS0_CULL_NONE = 0x4000, - GFXS0_CULL_BACK = 0x8000, - GFXS0_CULL_FRONT = 0xC000, - GFXS0_CULL_MASK = 0xC000, - GFXS0_SRCBLEND_ALPHA_SHIFT = 0x10, - GFXS0_SRCBLEND_ALPHA_MASK = 0xF0000, - GFXS0_DSTBLEND_ALPHA_SHIFT = 0x14, - GFXS0_DSTBLEND_ALPHA_MASK = 0xF00000, - GFXS0_BLENDOP_ALPHA_SHIFT = 0x18, - GFXS0_BLENDOP_ALPHA_MASK = 0x7000000, - GFXS0_BLEND_ALPHA_MASK = 0x7FF0000, - GFXS0_COLORWRITE_RGB = 0x8000000, - GFXS0_COLORWRITE_ALPHA = 0x10000000, - GFXS0_COLORWRITE_MASK = 0x18000000, - GFXS0_POLYMODE_LINE = 0x80000000, - GFXS1_DEPTHWRITE = 0x1, - GFXS1_DEPTHTEST_DISABLE = 0x2, - GFXS1_DEPTHTEST_SHIFT = 0x2, - GFXS1_DEPTHTEST_ALWAYS = 0x0, - GFXS1_DEPTHTEST_LESS = 0x4, - GFXS1_DEPTHTEST_EQUAL = 0x8, - GFXS1_DEPTHTEST_LESSEQUAL = 0xC, - GFXS1_DEPTHTEST_MASK = 0xC, - GFXS1_DEPTHFUNC_MASK = 0xF, - GFXS1_POLYGON_OFFSET_SHIFT = 0x4, - GFXS1_POLYGON_OFFSET_0 = 0x0, - GFXS1_POLYGON_OFFSET_1 = 0x10, - GFXS1_POLYGON_OFFSET_2 = 0x20, - GFXS1_POLYGON_OFFSET_SHADOWMAP = 0x30, - GFXS1_POLYGON_OFFSET_MASK = 0x30, - GFXS1_STENCIL_FRONT_ENABLE = 0x40, - GFXS1_STENCIL_BACK_ENABLE = 0x80, - GFXS1_STENCIL_MASK = 0xC0, - GFXS1_STENCIL_FRONT_PASS_SHIFT = 0x8, - GFXS1_STENCIL_FRONT_FAIL_SHIFT = 0xB, - GFXS1_STENCIL_FRONT_ZFAIL_SHIFT = 0xE, - GFXS1_STENCIL_FRONT_FUNC_SHIFT = 0x11, - GFXS1_STENCIL_FRONT_MASK = 0xFFF00, - GFXS1_STENCIL_BACK_PASS_SHIFT = 0x14, - GFXS1_STENCIL_BACK_FAIL_SHIFT = 0x17, - GFXS1_STENCIL_BACK_ZFAIL_SHIFT = 0x1A, - GFXS1_STENCIL_BACK_FUNC_SHIFT = 0x1D, - GFXS1_STENCIL_BACK_MASK = 0xFFF00000, - GFXS1_STENCILFUNC_FRONTBACK_MASK = 0xE00E0000, - GFXS1_STENCILOP_FRONTBACK_MASK = 0x1FF1FF00, - }; - - struct GfxStateBits - { - unsigned int loadBits[2]; - }; - - struct Material - { - MaterialInfo info; - char stateBitsEntry[130]; - unsigned char textureCount; - unsigned char constantCount; - unsigned char stateBitsCount; - char stateFlags; - char cameraRegion; - unsigned char maxStreamedMips; - MaterialTechniqueSet* techniqueSet; - MaterialTextureDef* textureTable; - MaterialConstantDef* constantTable; - GfxStateBits* stateBitsTable; - }; - - struct MaterialStreamRouting - { - char source; - char dest; - }; - - struct MaterialVertexStreamRouting - { - MaterialStreamRouting data[16]; - void/*IDirect3DVertexDeclaration9*/* decl[18]; - }; - - struct MaterialVertexDeclaration - { - char streamCount; - bool hasOptionalSource; - bool isLoaded; - MaterialVertexStreamRouting routing; - }; - - struct GfxVertexShaderLoadDef - { - unsigned int* program; - uint16_t programSize; - }; - - struct MaterialVertexShaderProgram - { - void/*IDirect3DVertexShader9*/* vs; - GfxVertexShaderLoadDef loadDef; - }; - - struct MaterialVertexShader - { - const char* name; - MaterialVertexShaderProgram prog; - }; - - struct GfxPixelShaderLoadDef - { - unsigned int* program; - uint16_t programSize; - }; - - struct MaterialPixelShaderProgram - { - void/*IDirect3DPixelShader9*/* ps; - GfxPixelShaderLoadDef loadDef; - }; - - struct MaterialPixelShader - { - const char* name; - MaterialPixelShaderProgram prog; - }; - - struct MaterialArgumentCodeConst - { - uint16_t index; - char firstRow; - char rowCount; - }; - - union MaterialArgumentDef - { - const float(*literalConst)[4]; - MaterialArgumentCodeConst codeConst; - unsigned int codeSampler; - unsigned int nameHash; - }; - - enum MaterialShaderArgumentType - { - MTL_ARG_MATERIAL_VERTEX_CONST = 0x0, - MTL_ARG_LITERAL_VERTEX_CONST = 0x1, - MTL_ARG_MATERIAL_PIXEL_SAMPLER = 0x2, - MTL_ARG_CODE_PRIM_BEGIN = 0x3, - MTL_ARG_CODE_VERTEX_CONST = 0x3, - MTL_ARG_CODE_PIXEL_SAMPLER = 0x4, - MTL_ARG_CODE_PIXEL_CONST = 0x5, - MTL_ARG_CODE_PRIM_END = 0x6, - MTL_ARG_MATERIAL_PIXEL_CONST = 0x6, - MTL_ARG_LITERAL_PIXEL_CONST = 0x7, - - MLT_ARG_COUNT - }; - - struct MaterialShaderArgument - { - uint16_t type; - uint16_t dest; - MaterialArgumentDef u; - }; - - struct MaterialPass - { - MaterialVertexDeclaration* vertexDecl; - MaterialVertexShader* vertexShader; - MaterialPixelShader* pixelShader; - char perPrimArgCount; - char perObjArgCount; - char stableArgCount; - char customSamplerFlags; - MaterialShaderArgument* args; - }; - - struct MaterialTechnique - { - const char* name; - uint16_t flags; - uint16_t passCount; - MaterialPass passArray[1]; - }; - - struct MaterialTechniqueSet - { - const char* name; - char worldVertFormat; - char unused[1]; - uint16_t techsetFlags; - MaterialTechnique* techniques[130]; - }; - - struct GfxImageLoadDef - { - char levelCount; - char flags; - int format; - int resourceSize; - char data[1]; - }; - - union GfxTexture - { - // IDirect3DBaseTexture9* basemap; - // IDirect3DTexture9* map; - // IDirect3DVolumeTexture9* volmap; - // IDirect3DCubeTexture9* cubemap; - Texture* texture; - GfxImageLoadDef* loadDef; - }; - - struct Picmip - { - char platform[2]; - }; - - struct CardMemory - { - int platform[2]; - }; - - enum TextureSemantic - { - TS_2D = 0x0, - TS_FUNCTION = 0x1, - TS_COLOR_MAP = 0x2, - TS_UNUSED_1 = 0x3, - TS_UNUSED_2 = 0x4, - TS_NORMAL_MAP = 0x5, - TS_UNUSED_3 = 0x6, - TS_UNUSED_4 = 0x7, - TS_SPECULAR_MAP = 0x8, - TS_UNUSED_5 = 0x9, - TS_UNUSED_6 = 0xA, - TS_WATER_MAP = 0xB, - TS_COLOR0_MAP = 0xC, - TS_COLOR1_MAP = 0xD, - TS_COLOR2_MAP = 0xE, - TS_COLOR3_MAP = 0xF, - TS_COLOR4_MAP = 0x10, - TS_COLOR5_MAP = 0x11, - TS_COLOR6_MAP = 0x12, - TS_COLOR7_MAP = 0x13, - TS_COLOR8_MAP = 0x14, - TS_COLOR9_MAP = 0x15, - TS_COLOR10_MAP = 0x16, - TS_COLOR11_MAP = 0x17, - TS_COLOR12_MAP = 0x18, - TS_COLOR13_MAP = 0x19, - TS_COLOR14_MAP = 0x1A, - TS_COLOR15_MAP = 0x1B, - TS_THROW_MAP = 0x1C, - }; - - enum ImageCategory - { - IMG_CATEGORY_UNKNOWN = 0x0, - IMG_CATEGORY_AUTO_GENERATED = 0x1, - IMG_CATEGORY_LIGHTMAP = 0x2, - IMG_CATEGORY_LOAD_FROM_FILE = 0x3, - IMG_CATEGORY_RAW = 0x4, - IMG_CATEGORY_FIRST_UNMANAGED = 0x5, - IMG_CATEGORY_WATER = 0x5, - IMG_CATEGORY_RENDERTARGET = 0x6, - IMG_CATEGORY_TEMP = 0x7, - }; - - struct GfxImage - { - GfxTexture texture; - char mapType; - char semantic; - char category; - bool delayLoadPixels; - Picmip picmip; - bool noPicmip; - char track; - CardMemory cardMemory; - uint16_t width; - uint16_t height; - uint16_t depth; - char levelCount; - char streaming; - unsigned int baseSize; - char* pixels; - unsigned int loadedSize; - char skippedMipLevels; - const char* name; - unsigned int hash; - }; - - enum snd_asset_format - { - SND_ASSET_FORMAT_PCMS16 = 0x0, - SND_ASSET_FORMAT_PCMS24 = 0x1, - SND_ASSET_FORMAT_PCMS32 = 0x2, - SND_ASSET_FORMAT_IEEE = 0x3, - SND_ASSET_FORMAT_XMA4 = 0x4, - SND_ASSET_FORMAT_MP3 = 0x5, - SND_ASSET_FORMAT_MSADPCM = 0x6, - SND_ASSET_FORMAT_WMA = 0x7, - }; - - enum snd_asset_channel - { - SND_ASSET_CHANNEL_L = 0x1, - SND_ASSET_CHANNEL_R = 0x2, - SND_ASSET_CHANNEL_C = 0x4, - SND_ASSET_CHANNEL_LFE = 0x8, - SND_ASSET_CHANNEL_LS = 0x10, - SND_ASSET_CHANNEL_RS = 0x20, - SND_ASSET_CHANNEL_LB = 0x40, - SND_ASSET_CHANNEL_RB = 0x80, - }; - - enum snd_asset_flags - { - SND_ASSET_FLAG_DEFAULT = 0x0, - SND_ASSET_FLAG_LOOPING = 0x1, - SND_ASSET_FLAG_PAD_LOOP_BUFFER = 0x2, - }; - - typedef tdef_align(2048) char snd_align_char; - - struct snd_asset - { - unsigned int version; - unsigned int frame_count; - unsigned int frame_rate; - unsigned int channel_count; - unsigned int header_size; - unsigned int block_size; - unsigned int buffer_size; - snd_asset_format format; - snd_asset_channel channel_flags; - snd_asset_flags flags; - unsigned int seek_table_count; - unsigned int* seek_table; - unsigned int data_size; - snd_align_char* data; - }; - - struct LoadedSound - { - const char* name; - snd_asset sound; - }; - - typedef tdef_align(2048) char char_align_2048; - - struct PrimedSound - { - const char* name; - char_align_2048* buffer; - unsigned int size; - }; - - struct StreamedSound - { - char* filename; - PrimedSound* primeSnd; - }; - - union SoundFileRef - { - LoadedSound* loadSnd; - StreamedSound* streamSnd; - }; - - enum snd_alias_type_t - { - SAT_UNKNOWN = 0x0, - SAT_LOADED = 0x1, - SAT_STREAMED = 0x2, - SAT_PRIMED = 0x3, - SAT_COUNT = 0x4, - }; - - struct SoundFile - { - SoundFileRef u; - char type; - char exists; - }; - - struct snd_alias_t - { - const char* name; - unsigned int id; - const char* subtitle; - const char* secondaryname; - SoundFile* soundFile; - unsigned int flags; - unsigned int duck; - unsigned int contextType; - unsigned int contextValue; - uint16_t fluxTime; - uint16_t startDelay; - uint16_t reverbSend; - uint16_t centerSend; - uint16_t volMin; - uint16_t volMax; - uint16_t teamVolMod; - uint16_t pitchMin; - uint16_t pitchMax; - uint16_t teamPitchMod; - uint16_t distMin; - uint16_t distMax; - uint16_t distReverbMax; - uint16_t envelopMin; - uint16_t envelopMax; - uint16_t envelopPercentage; - char minPriorityThreshold; - char maxPriorityThreshold; - char probability; - char occlusionLevel; - char occlusionWetDry; - char minPriority; - char maxPriority; - char pan; - char dryCurve; - char wetCurve; - char dryMinCurve; - char wetMinCurve; - char limitCount; - char entityLimitCount; - char snapshotGroup; - }; - - struct snd_alias_list_t - { - const char* name; - unsigned int id; - snd_alias_t* head; - int count; - int sequence; - }; - - struct type_align(4) SndIndexEntry - { - uint16_t value; - uint16_t next; - }; - - struct snd_radverb - { - char name[32]; - unsigned int id; - float smoothing; - float earlyTime; - float lateTime; - float earlyGain; - float lateGain; - float returnGain; - float earlyLpf; - float lateLpf; - float inputLpf; - float dampLpf; - float wallReflect; - float dryGain; - float earlySize; - float lateSize; - float diffusion; - }; - - struct snd_snapshot - { - char name[32]; - unsigned int id; - char occlusionName[32]; - unsigned int occlusionId; - float fadeIn; - float fadeOut; - float distance; - unsigned int fadeInCurve; - unsigned int fadeOutCurve; - float attenuation[64]; - }; - - struct SndBank - { - const char* name; - unsigned int aliasCount; - snd_alias_list_t* alias; - SndIndexEntry* aliasIndex; - unsigned int packHash; - unsigned int packLocation; - unsigned int radverbCount; - snd_radverb* radverbs; - unsigned int snapshotCount; - snd_snapshot* snapshots; - }; - - struct SndPatch - { - char* name; - unsigned int elementCount; - unsigned int* elements; - unsigned int fileCount; - SoundFile* files; - }; - - struct cStaticModelWritable - { - uint16_t nextModelInWorldSector; - }; - - struct cStaticModel_s - { - cStaticModelWritable writable; - XModel* xmodel; - float origin[3]; - float invScaledAxis[3][3]; - float absmin[3]; - float absmax[3]; - }; - - struct dmaterial_t - { - char material[64]; - int surfaceFlags; - int contentFlags; - }; - - struct cNode_t - { - cplane_s* plane; - int16_t children[2]; - }; - - struct cLeaf_s - { - uint16_t firstCollAabbIndex; - uint16_t collAabbCount; - int brushContents; - int terrainContents; - float mins[3]; - float maxs[3]; - int leafBrushNode; - int16_t cluster; - }; - - struct cLeafBrushNodeChildren_t - { - float dist; - float range; - uint16_t childOffset[2]; - }; - - struct cLeafBrushNodeLeaf_t - { - uint16_t* brushes; - }; - - union cLeafBrushNodeData_t - { - cLeafBrushNodeLeaf_t leaf; - cLeafBrushNodeChildren_t children; - }; - - struct cLeafBrushNode_s - { - char axis; - int16_t leafBrushCount; - int contents; - cLeafBrushNodeData_t data; - }; - - struct CollisionBorder - { - float distEq[3]; - float zBase; - float zSlope; - float start; - float length; - }; - - struct CollisionPartition - { - char triCount; - char borderCount; - int firstTri; - int nuinds; - int fuind; - CollisionBorder* borders; - }; - - union CollisionAabbTreeIndex - { - int firstChildIndex; - int partitionIndex; - }; - - struct type_align(16) CollisionAabbTree - { - float origin[3]; - uint16_t materialIndex; - uint16_t childCount; - float halfSize[3]; - CollisionAabbTreeIndex u; - }; - - struct cmodel_t - { - float mins[3]; - float maxs[3]; - float radius; - cLeaf_s leaf; - }; - - struct type_align(16) cbrush_t - { - float mins[3]; - int contents; - float maxs[3]; - unsigned int numsides; - cbrushside_t* sides; - int axial_cflags[2][3]; - int axial_sflags[2][3]; - unsigned int numverts; - vec3_t* verts; - }; - - enum DynEntityType - { - DYNENT_TYPE_INVALID = 0x0, - DYNENT_TYPE_CLUTTER = 0x1, - DYNENT_TYPE_DESTRUCT = 0x2, - DYNENT_TYPE_COUNT = 0x3, - }; - - struct GfxPlacement - { - float quat[4]; - float origin[3]; - }; - - struct XModelPiece - { - XModel* model; - float offset[3]; - }; - - struct XModelPieces - { - const char* name; - int numpieces; - XModelPiece* pieces; - }; - - struct DynEntityDef - { - DynEntityType type; - GfxPlacement pose; - XModel* xModel; - XModel* destroyedxModel; - uint16_t brushModel; - uint16_t physicsBrushModel; - FxEffectDef* destroyFx; - unsigned int destroySound; - XModelPieces* destroyPieces; - PhysPreset* physPreset; - int16_t physConstraints[4]; - int health; - int flags; - int contents; - uint16_t targetname; - uint16_t target; - }; - - struct DynEntityPose - { - GfxPlacement pose; - float radius; - }; - - struct DynEntityClient - { - int physObjId; - uint16_t flags; - uint16_t lightingHandle; - int health; - uint16_t burnTime; - uint16_t fadeTime; - int physicsStartTime; - }; - - struct DynEntityServer - { - uint16_t flags; - int health; - }; - - struct DynEntityColl - { - uint16_t sector; - uint16_t nextEntInSector; - float linkMins[3]; - float linkMaxs[3]; - int contents; - }; - - struct par_t - { - float p[3]; - float p0[3]; - float p_prev[3]; - int flags; - }; - - enum rope_constraint_e - { - ROPE_PAIR_CONSTRAINT = 0x0, - ROPE_WORLD_CONSTRAINT = 0x1, - ROPE_DENTITY_CONSTRAINT = 0x2, - ROPE_CENTITY_CONSTRAINT = 0x3, - }; - - struct constraint_t - { - float p[3]; - rope_constraint_e type; - int entity_index; - int bone_name_hash; - char pi1; - char pi2; - }; - - struct rope_frame_verts_t - { - int num_verts; - float v[50][3]; - }; - - struct rope_client_verts_t - { - rope_frame_verts_t frame_verts[2]; - unsigned int frame_index; - }; - - struct rope_t - { - par_t m_particles[25]; - constraint_t m_constraints[30]; - int m_entity_anchors[3]; - int m_num_particles; - int m_num_constraints; - int m_num_entity_anchors; - int m_num_draw_verts; - rope_client_verts_t m_client_verts; - float m_min[3]; - float m_max[3]; - float m_start[3]; - float m_end[3]; - int m_in_use; - int m_visible; - int m_dist_constraint; - int m_flags; - Material* m_material; - float m_seglen; - float m_length; - float m_width; - float m_scale; - float m_force_scale; - int m_health; - int m_frame; - int m_stable_count; - int m_static_rope; - uint16_t m_lightingHandle; - }; - - struct clipMap_t - { - const char* name; - int isInUse; - int planeCount; - cplane_s* planes; - unsigned int numStaticModels; - cStaticModel_s* staticModelList; - unsigned int numMaterials; - dmaterial_t* materials; - unsigned int numBrushSides; - cbrushside_t* brushsides; - unsigned int numNodes; - cNode_t* nodes; - unsigned int numLeafs; - cLeaf_s* leafs; - unsigned int leafbrushNodesCount; - cLeafBrushNode_s* leafbrushNodes; - unsigned int numLeafBrushes; - uint16_t* leafbrushes; - unsigned int numLeafSurfaces; - unsigned int* leafsurfaces; - unsigned int vertCount; - vec3_t* verts; - unsigned int numBrushVerts; - vec3_t* brushVerts; - unsigned int nuinds; - uint16_t* uinds; - int triCount; - uint16_t* triIndices; - char* triEdgeIsWalkable; - int borderCount; - CollisionBorder* borders; - int partitionCount; - CollisionPartition* partitions; - int aabbTreeCount; - CollisionAabbTree* aabbTrees; - unsigned int numSubModels; - cmodel_t* cmodels; - uint16_t numBrushes; - cbrush_t* brushes; - int numClusters; - int clusterBytes; - char* visibility; - int vised; - MapEnts* mapEnts; - cbrush_t* box_brush; - cmodel_t box_model; - uint16_t originalDynEntCount; - uint16_t dynEntCount[4]; - DynEntityDef* dynEntDefList[2]; - DynEntityPose* dynEntPoseList[2]; - DynEntityClient* dynEntClientList[2]; - DynEntityServer* dynEntServerList[2]; - DynEntityColl* dynEntCollList[4]; - int num_constraints; - PhysConstraint* constraints; - int max_ropes; - rope_t* ropes; - unsigned int checksum; - }; - - struct ComPrimaryLight - { - char type; - char canUseShadowMap; - char exponent; - char priority; - int16_t cullDist; - char _pad[2]; - float color[3]; - float dir[3]; - float origin[3]; - float radius; - float cosHalfFovOuter; - float cosHalfFovInner; - float cosHalfFovExpanded; - float rotationLimit; - float translationLimit; - float mipDistance; - float diffuseColor[4]; - float specularColor[4]; - float attenuation[4]; - float falloff[4]; - float angle[4]; - float aAbB[4]; - float cookieControl0[4]; - float cookieControl1[4]; - float cookieControl2[4]; - const char* defName; - }; - - struct ComWaterHeader - { - int minx; - int miny; - int maxx; - int maxy; - }; - - struct type_align(4) ComWaterCell - { - int16_t waterheight; - char flooroffset; - char shoredist; - char color[4]; - }; - - struct ComBurnableHeader - { - int minx; - int miny; - int maxx; - int maxy; - }; - - struct ComBurnableSample - { - char state; - }; - - struct ComBurnableCell - { - int x; - int y; - ComBurnableSample* data; - }; - - struct ComWorld - { - const char* name; - int isInUse; - unsigned int primaryLightCount; - ComPrimaryLight* primaryLights; - ComWaterHeader waterHeader; - unsigned int numWaterCells; - ComWaterCell* waterCells; - ComBurnableHeader burnableHeader; - unsigned int numBurnableCells; - ComBurnableCell* burnableCells; - }; - - struct pathnode_t; - - enum nodeType - { - NODE_BADNODE = 0x0, - NODE_PATHNODE = 0x1, - NODE_COVER_STAND = 0x2, - NODE_COVER_CROUCH = 0x3, - NODE_COVER_CROUCH_WINDOW = 0x4, - NODE_COVER_PRONE = 0x5, - NODE_COVER_RIGHT = 0x6, - NODE_COVER_LEFT = 0x7, - NODE_COVER_WIDE_RIGHT = 0x8, - NODE_COVER_WIDE_LEFT = 0x9, - NODE_COVER_PILLAR = 0xA, - NODE_CONCEALMENT_STAND = 0xB, - NODE_CONCEALMENT_CROUCH = 0xC, - NODE_CONCEALMENT_PRONE = 0xD, - NODE_REACQUIRE = 0xE, - NODE_BALCONY = 0xF, - NODE_SCRIPTED = 0x10, - NODE_NEGOTIATION_BEGIN = 0x11, - NODE_NEGOTIATION_END = 0x12, - NODE_TURRET = 0x13, - NODE_GUARD = 0x14, - NODE_NUMTYPES = 0x15, - NODE_DONTLINK = 0x15, - }; - - struct pathlink_s - { - float fDist; - uint16_t nodeNum; - char disconnectCount; - char negotiationLink; - char ubBadPlaceCount[4]; - }; - - struct pathnode_constant_t - { - nodeType type; - uint16_t spawnflags; - uint16_t targetname; - uint16_t script_linkName; - uint16_t script_noteworthy; - uint16_t target; - uint16_t animscript; - int animscriptfunc; - float vOrigin[3]; - float fAngle; - float forward[2]; - float fRadius; - float minUseDistSq; - int16_t wOverlapNode[2]; - int16_t wChainId; - int16_t wChainDepth; - int16_t wChainParent; - uint16_t totalLinkCount; - pathlink_s* Links; - }; - - struct SentientHandle - { - uint16_t number; - uint16_t infoIndex; - }; - - struct pathnode_dynamic_t - { - SentientHandle pOwner; - int iFreeTime; - int iValidTime[3]; - int inPlayerLOSTime; - int16_t wLinkCount; - int16_t wOverlapCount; - int16_t turretEntNumber; - int16_t userCount; - }; - - struct pathnode_transient_t - { - int iSearchFrame; - pathnode_t* pNextOpen; - pathnode_t* pPrevOpen; - pathnode_t* pParent; - float fCost; - float fHeuristic; - float costFactor; - }; - - struct pathnode_t - { - pathnode_constant_t constant; - pathnode_dynamic_t dynamic; - pathnode_transient_t transient; - }; - - struct type_align(16) pathbasenode_t - { - float vOrigin[3]; - unsigned int type; - }; - - struct pathnode_tree_t; - - struct pathnode_tree_nodes_t - { - int nodeCount; - uint16_t* nodes; - }; - - union pathnode_tree_info_t - { - pathnode_tree_t* child[2]; - pathnode_tree_nodes_t s; - }; - - struct pathnode_tree_t - { - int axis; - float dist; - pathnode_tree_info_t u; - }; - - struct PathData - { - unsigned int nodeCount; - pathnode_t* nodes; - pathbasenode_t* basenodes; - unsigned int chainNodeCount; - uint16_t* chainNodeForNode; - uint16_t* nodeForChainNode; - int visBytes; - char* pathVis; - int nodeTreeCount; - pathnode_tree_t* nodeTree; - }; - - struct GameWorldSp - { - const char* name; - PathData path; - }; - - struct GameWorldMp - { - const char* name; - PathData path; - }; - - struct MapEnts - { - const char* name; - char* entityString; - int numEntityChars; - }; - - struct GfxStreamingAabbTree - { - uint16_t firstItem; - uint16_t itemCount; - uint16_t firstChild; - uint16_t childCount; - float mins[3]; - float maxs[3]; - }; - - struct GfxWorldStreamInfo - { - int aabbTreeCount; - GfxStreamingAabbTree* aabbTrees; - int leafRefCount; - int* leafRefs; - }; - - struct GfxWorldSunColor - { - unsigned int control; - float angles[3]; - float ambientColor[4]; - float sunDiffuseColor[4]; - float sunSpecularColor[4]; - float skyColor[4]; - float groundColor[4]; - float exposure; - float sunShadowSampleSizeNear; - float skyboxHDRScale; - }; - - struct SunLightParseParams - { - char name[64]; - float treeScatterIntensity; - float treeScatterAmount; - GfxWorldSunColor sunSettings[1]; - }; - - struct type_align(16) float44 - { - union - { - vec4_t m[4]; - float member[16]; - }; - }; - - struct type_align(16) GfxLight - { - char type; - char canUseShadowMap; - int16_t cullDist; - float color[3]; - float dir[3]; - float origin[3]; - float radius; - float cosHalfFovOuter; - float cosHalfFovInner; - int exponent; - unsigned int spotShadowIndex; - float angles[3]; - float spotShadowHiDistance; - float diffuseColor[4]; - float specularColor[4]; - float shadowColor[4]; - float falloff[4]; - float attenuation[4]; - float aAbB[4]; - float cookieControl0[4]; - float cookieControl1[4]; - float cookieControl2[4]; - float44 viewMatrix; - float44 projMatrix; - GfxLightDef* def; - }; - - struct GfxLightCorona - { - float origin[3]; - float radius; - float color[3]; - float intensity; - }; - - struct GfxShadowMapVolume - { - unsigned int control; - unsigned int padding1; - unsigned int padding2; - unsigned int padding3; - }; - - struct GfxVolumePlane - { - float plane[4]; - }; - - struct GfxExposureVolume - { - unsigned int control; - float exposure; - float luminanceIncreaseScale; - float luminanceDecreaseScale; - float featherRange; - float featherAdjust; - }; - - struct GfxSkyDynamicIntensity - { - float angle0; - float angle1; - float factor0; - float factor1; - }; - - struct GfxWorldDpvsPlanes - { - int cellCount; - cplane_s* planes; - uint16_t* nodes; - unsigned int* sceneEntCellBits; - }; - - struct GfxCell; - struct GfxPortal; - - struct GfxPortalWritable - { - bool isQueued; - bool isAncestor; - char recursionDepth; - char hullPointCount; - float(*hullPoints)[2]; - GfxPortal* queuedParent; - }; - - struct DpvsPlane - { - float coeffs[4]; - char side[3]; - char pad; - }; - - struct GfxPortal - { - GfxPortalWritable writable; - DpvsPlane plane; - GfxCell* cell; - vec3_t* vertices; - char vertexCount; - float hullAxis[2][3]; - }; - - struct GfxAabbTree - { - float mins[3]; - float maxs[3]; - uint16_t childCount; - uint16_t surfaceCount; - uint16_t startSurfIndex; - uint16_t smodelIndexCount; - uint16_t* smodelIndexes; - int childrenOffset; - }; - - struct GfxCell - { - float mins[3]; - float maxs[3]; - int aabbTreeCount; - GfxAabbTree* aabbTree; - int portalCount; - GfxPortal* portals; - int cullGroupCount; - int* cullGroups; - char reflectionProbeCount; - char* reflectionProbes; - }; - - struct GfxReflectionProbeVolumeData - { - float volumePlanes[6][4]; - }; - - struct GfxReflectionProbe - { - float origin[3]; - GfxImage* reflectionImage; - GfxReflectionProbeVolumeData* probeVolumes; - unsigned int probeVolumeCount; - }; - - struct GfxLightmapArray - { - GfxImage* primary; - GfxImage* secondary; - GfxImage* secondaryB; - }; - - struct GfxWorldVertex - { - float xyz[3]; - float binormalSign; - GfxColor color; - float texCoord[2]; - float lmapCoord[2]; - PackedUnitVec normal; - PackedUnitVec tangent; - }; - - struct GfxWorldVertexData - { - GfxWorldVertex* vertices; - void/*IDirect3DVertexBuffer9*/* worldVb; - }; - - struct GfxWorldVertexLayerData - { - char* data; - void/*IDirect3DVertexBuffer9*/* layerVb; - }; - - struct GfxWorldDraw - { - unsigned int reflectionProbeCount; - GfxReflectionProbe* reflectionProbes; - GfxTexture* reflectionProbeTextures; - int lightmapCount; - GfxLightmapArray* lightmaps; - GfxTexture* lightmapPrimaryTextures; - GfxTexture* lightmapSecondaryTextures; - GfxTexture* lightmapSecondaryTexturesB; - GfxImage* terrainScorchImages[31]; - unsigned int vertexCount; - GfxWorldVertexData vd; - unsigned int vertexLayerDataSize; - GfxWorldVertexLayerData vld; - unsigned int vertexStream2DataSize; - int indexCount; - uint16_t* indices; - }; - - struct type_align(4) GfxLightGridEntry - { - uint16_t colorsIndex; - char primaryLightIndex; - char needsTrace; - }; - - struct type_align(4) GfxCompressedLightGridColors - { - char rgb[56][3]; - }; - - typedef tdef_align(4) char aligned_byte_pointer; - - struct GfxLightGrid - { - bool hasLightRegions; - unsigned int sunPrimaryLightIndex; - uint16_t mins[3]; - uint16_t maxs[3]; - unsigned int rowAxis; - unsigned int colAxis; - uint16_t* rowDataStart; - unsigned int rawRowDataSize; - aligned_byte_pointer* rawRowData; - unsigned int entryCount; - GfxLightGridEntry* entries; - unsigned int colorCount; - GfxCompressedLightGridColors* colors; - }; - - struct GfxBrushModelWritable - { - float mins[3]; - float maxs[3]; - float mip1radiusSq; - }; - - struct GfxBrushModel - { - GfxBrushModelWritable writable; - float bounds[2][3]; - unsigned int surfaceCount; - unsigned int startSurfIndex; - }; - - struct MaterialMemory - { - Material* material; - int memory; - }; - - struct sunflare_t - { - bool hasValidData; - Material* spriteMaterial; - Material* flareMaterial; - float spriteSize; - float flareMinSize; - float flareMinDot; - float flareMaxSize; - float flareMaxDot; - float flareMaxAlpha; - int flareFadeInTime; - int flareFadeOutTime; - float blindMinDot; - float blindMaxDot; - float blindMaxDarken; - int blindFadeInTime; - int blindFadeOutTime; - float glareMinDot; - float glareMaxDot; - float glareMaxLighten; - int glareFadeInTime; - int glareFadeOutTime; - float sunFxPosition[3]; - }; - - struct XModelDrawInfo - { - uint16_t lod; - uint16_t surfId; - }; - - struct GfxSceneDynModel - { - XModelDrawInfo info; - uint16_t dynEntId; - }; - - typedef tdef_align(4) GfxSceneDynModel GfxSceneDynModel4; - - struct BModelDrawInfo - { - uint16_t surfId; - }; - - struct type_align(4) GfxSceneDynBrush - { - BModelDrawInfo info; - uint16_t dynEntId; - }; - - struct GfxShadowGeometry - { - uint16_t surfaceCount; - uint16_t smodelCount; - uint16_t* sortedSurfIndex; - uint16_t* smodelIndex; - }; - - struct GfxLightRegionAxis - { - float dir[3]; - float midPoint; - float halfSize; - }; - - struct GfxLightRegionHull - { - float kdopMidPoint[9]; - float kdopHalfSize[9]; - unsigned int axisCount; - GfxLightRegionAxis* axis; - }; - - struct GfxLightRegion - { - unsigned int hullCount; - GfxLightRegionHull* hulls; - }; - - struct GfxStaticModelInst - { - float mins[3]; - float maxs[3]; - float lightingOrigin[3]; - GfxColor groundLighting; - }; - - struct srfTriangles_t - { - float mins[3]; - int vertexLayerData; - float maxs[3]; - int firstVertex; - uint16_t vertexCount; - uint16_t triCount; - int baseIndex; - float himipRadiusSq; - int stream2ByteOffset; - }; - - struct type_align(16) GfxSurface - { - srfTriangles_t tris; - Material* material; - char lightmapIndex; - char reflectionProbeIndex; - char primaryLightIndex; - char flags; - float bounds[2][3]; - }; - - struct GfxCullGroup - { - float mins[3]; - float maxs[3]; - int surfaceCount; - int startSurfIndex; - }; - - struct GfxPackedPlacement - { - float origin[3]; - float axis[3][3]; - float scale; - }; - - struct GfxStaticModelDrawInst - { - float cullDist; - GfxPackedPlacement placement; - XModel* model; - int flags; - uint16_t smodelCacheIndex[4]; - uint16_t lightingHandle; - char reflectionProbeIndex; - char primaryLightIndex; - }; - - struct GfxWorldDpvsStatic - { - unsigned int smodelCount; - unsigned int dynamicSModelCount; - unsigned int staticSurfaceCount; - unsigned int litSurfsBegin; - unsigned int litSurfsEnd; - unsigned int decalSurfsBegin; - unsigned int decalSurfsEnd; - unsigned int emissiveSurfsBegin; - unsigned int emissiveSurfsEnd; - unsigned int smodelVisDataCount; - unsigned int surfaceVisDataCount; - char* smodelVisData[3]; - char* surfaceVisData[3]; - char* smodelVisDataCameraSaved; - char* surfaceVisDataCameraSaved; - raw_uint128* lodData; - uint16_t* sortedSurfIndex; - GfxStaticModelInst* smodelInsts; - GfxSurface* surfaces; - GfxCullGroup* cullGroups; - GfxStaticModelDrawInst* smodelDrawInsts; - GfxDrawSurf* surfaceMaterials; - raw_uint128* surfaceCastsSunShadow; - volatile int usageCount; - }; - - struct GfxWorldDpvsDynamic - { - unsigned int dynEntClientWordCount[2]; - unsigned int dynEntClientCount[2]; - unsigned int* dynEntCellBits[2]; - char* dynEntVisData[2][3]; - }; - - struct GfxWorldLodChain - { - float origin[3]; - float lastDist; - unsigned int firstLodInfo; - uint16_t lodInfoCount; - }; - - struct GfxWorldLodInfo - { - float dist; - unsigned int firstSurf; - uint16_t surfCount; - }; - - struct GfxWaterBuffer - { - unsigned int bufferSize; - vec4_t* buffer; - }; - - struct Occluder - { - unsigned int flags; - char name[16]; - float points[4][3]; - }; - - struct GfxOutdoorBounds - { - float bounds[2][3]; - }; - - struct GfxHeroLight - { - char type; - char unused[3]; - float color[3]; - float dir[3]; - float origin[3]; - float radius; - float cosHalfFovOuter; - float cosHalfFovInner; - int exponent; - }; - - struct GfxHeroLightTree - { - float mins[3]; - float maxs[3]; - }; - - struct GfxWorld - { - const char* name; - const char* baseName; - int planeCount; - int nodeCount; - int surfaceCount; - GfxWorldStreamInfo streamInfo; - int skySurfCount; - int* skyStartSurfs; - GfxImage* skyImage; - char skySamplerState; - const char* skyBoxModel; - SunLightParseParams sunParse; - GfxLight* sunLight; - float sunColorFromBsp[3]; - unsigned int sunPrimaryLightIndex; - unsigned int primaryLightCount; - int cullGroupCount; - unsigned int coronaCount; - GfxLightCorona* coronas; - unsigned int shadowMapVolumeCount; - GfxShadowMapVolume* shadowMapVolumes; - unsigned int shadowMapVolumePlaneCount; - GfxVolumePlane* shadowMapVolumePlanes; - unsigned int exposureVolumeCount; - GfxExposureVolume* exposureVolumes; - unsigned int exposureVolumePlaneCount; - GfxVolumePlane* exposureVolumePlanes; - GfxSkyDynamicIntensity skyDynIntensity; - GfxWorldDpvsPlanes dpvsPlanes; - int cellBitsCount; - GfxCell* cells; - GfxWorldDraw draw; - GfxLightGrid lightGrid; - int modelCount; - GfxBrushModel* models; - float mins[3]; - float maxs[3]; - unsigned int checksum; - int materialMemoryCount; - MaterialMemory* materialMemory; - sunflare_t sun; - float outdoorLookupMatrix[4][4]; - GfxImage* outdoorImage; - unsigned int* cellCasterBits; - GfxSceneDynModel4* sceneDynModel; - GfxSceneDynBrush* sceneDynBrush; - unsigned int* primaryLightEntityShadowVis; - unsigned int* primaryLightDynEntShadowVis[2]; - char* nonSunPrimaryLightForModelDynEnt; - GfxShadowGeometry* shadowGeom; - GfxLightRegion* lightRegion; - GfxWorldDpvsStatic dpvs; - GfxWorldDpvsDynamic dpvsDyn; - unsigned int worldLodChainCount; - GfxWorldLodChain* worldLodChains; - unsigned int worldLodInfoCount; - GfxWorldLodInfo* worldLodInfos; - unsigned int worldLodSurfaceCount; - unsigned int* worldLodSurfaces; - float waterDirection; - GfxWaterBuffer waterBuffers[2]; - Material* waterMaterial; - Material* coronaMaterial; - Material* ropeMaterial; - unsigned int numOccluders; - Occluder* occluders; - unsigned int numOutdoorBounds; - GfxOutdoorBounds* outdoorBounds; - unsigned int heroLightCount; - unsigned int heroLightTreeCount; - GfxHeroLight* heroLights; - GfxHeroLightTree* heroLightTree; - }; - - enum SamplerStateBits_e - { - SAMPLER_FILTER_SHIFT = 0x0, - SAMPLER_FILTER_NEAREST = 0x1, - SAMPLER_FILTER_LINEAR = 0x2, - SAMPLER_FILTER_ANISO2X = 0x3, - SAMPLER_FILTER_ANISO4X = 0x4, - SAMPLER_FILTER_MASK = 0x7, - SAMPLER_MIPMAP_SHIFT = 0x3, - SAMPLER_MIPMAP_DISABLED = 0x0, - SAMPLER_MIPMAP_NEAREST = 0x8, - SAMPLER_MIPMAP_LINEAR = 0x10, - SAMPLER_MIPMAP_COUNT = 0x3, - SAMPLER_MIPMAP_MASK = 0x18, - SAMPLER_CLAMP_U_SHIFT = 0x5, - SAMPLER_CLAMP_V_SHIFT = 0x6, - SAMPLER_CLAMP_W_SHIFT = 0x7, - SAMPLER_CLAMP_U = 0x20, - SAMPLER_CLAMP_V = 0x40, - SAMPLER_CLAMP_W = 0x80, - SAMPLER_CLAMP_MASK = 0xE0, - SAMPLER_ANISO_SHIFT = 0x8, - SAMPLER_ANISO_1X = 0x0, - SAMPLER_ANISO_2X = 0x100, - SAMPLER_ANISO_4X = 0x200, - SAMPLER_ANISO_6X = 0x300, - SAMPLER_ANISO_8X = 0x400, - SAMPLER_ANISO_10X = 0x500, - SAMPLER_ANISO_12X = 0x600, - SAMPLER_ANISO_16X = 0x700, - SAMPLER_ANISO_MASK = 0x700, - SAMPLER_CONVOLUTION = 0x20000, - SAMPLER_GAMMA = 0x40000, - SAMPLER_UNNORMALIZED_UV = 0x80000, - SAMPLER_DIRECT_FILTER_UNNORMALIZED = 0x80000, - }; - - struct GfxLightImage - { - GfxImage* image; - char samplerState; - }; - - struct GfxLightDef - { - const char* name; - GfxLightImage attenuation; - int lmapLookupStart; - }; - - struct Glyph - { - uint16_t letter; - char x0; - char y0; - char dx; - char pixelWidth; - char pixelHeight; - float s0; - float t0; - float s1; - float t1; - }; - - struct Font_s - { - const char* fontName; - int pixelHeight; - int glyphCount; - Material* material; - Material* glowMaterial; - Glyph* glyphs; - }; - - struct MenuList - { - const char* name; - int menuCount; - menuDef_t** menus; - }; - - struct rectDef_s - { - float x; - float y; - float w; - float h; - int horzAlign; - int vertAlign; - }; - - struct windowDef_t - { - const char* name; - rectDef_s rect; - rectDef_s rectClient; - const char* group; - char style; - char border; - char modal; - char frameSides; - float frameTexSize; - float frameSize; - int ownerDraw; - int ownerDrawFlags; - float borderSize; - int staticFlags; - int dynamicFlags[1]; - int nextTime; - float foreColor[4]; - float backColor[4]; - float borderColor[4]; - float outlineColor[4]; - float rotation; - Material* background; - }; - - struct ScriptCondition - { - bool fireOnTrue; - int constructID; - int blockID; - ScriptCondition* next; - }; - - enum expDataType - { - VAL_INT = 0x0, - VAL_FLOAT = 0x1, - VAL_STRING = 0x2, - }; - - union operandInternalDataUnion - { - int intVal; - float floatVal; - const char* string; - }; - - struct Operand - { - expDataType dataType; - operandInternalDataUnion internals; - }; - - enum expressionRpnEnum - { - RPN_CONSTANT = 0x0, - RPN_CMD_IDX = 0x1, - RPN_CMD = 0x2, - RPN_END = 0x3, - }; - - enum expressionOperatorType_e - { - OP_NOOP = 0x0, - OP_RIGHTPAREN = 0x1, - OP_MUL = 0x2, - OP_DIV = 0x3, - OP_MOD = 0x4, - OP_PLUS = 0x5, - OP_MINUS = 0x6, - OP_MINUS_2 = 0x7, - OP_NEG = 0x8, - OP_SMALLER = 0x9, - OP_SMALLEREQ = 0xA, - OP_GREATER = 0xB, - OP_GREATEREQ = 0xC, - OP_EQ = 0xD, - OP_NOTEQ = 0xE, - OP_LOGAND = 0xF, - OP_LOGOR = 0x10, - OP_LEFTPAREN = 0x11, - OP_COMMA = 0x12, - OP_BITAND = 0x13, - OP_BITOR = 0x14, - OP_BITNEG = 0x15, - OP_SHIFTLEFT = 0x16, - OP_SHIFTRIGHT = 0x17, - - OP_COUNT - }; - - union expressionRpnDataUnion - { - Operand constant; - void* cmd; - int cmdIdx; - }; - - struct expressionRpn - { - int type; - expressionRpnDataUnion data; - }; - - struct ExpressionStatement - { - char* filename; - int line; - int numRpn; - expressionRpn* rpn; - }; - - struct GenericEventScript - { - ScriptCondition* prerequisites; - ExpressionStatement condition; - int type; - bool fireOnTrue; - const char* action; - int blockID; - int constructID; - GenericEventScript* next; - }; - - struct GenericEventHandler - { - const char* name; - GenericEventScript* eventScript; - GenericEventHandler* next; - }; - - struct ItemKeyHandler - { - int key; - GenericEventScript* keyScript; - ItemKeyHandler* next; - }; - - struct textExp_s - { - ExpressionStatement textExp; - }; - - struct enumDvarDef_s - { - const char* enumDvarName; - }; - - struct editFieldDef_s - { - int cursorPos[1]; - float minVal; - float maxVal; - float defVal; - float range; - int maxChars; - int maxCharsGotoNext; - int maxPaintChars; - int paintOffset; - }; - - struct columnInfo_s - { - int elementStyle; - int maxChars; - rectDef_s rect; - }; - - struct MenuCell - { - int type; - int maxChars; - char* stringValue; - }; - - struct MenuRow - { - MenuCell* cells; - char* eventName; - char* onFocusEventName; - bool disableArg; - int status; - int name; - }; - - struct listBoxDef_s - { - int mousePos; - int cursorPos[1]; - int startPos[1]; - int endPos[1]; - int drawPadding; - float elementWidth; - float elementHeight; - int numColumns; - float special; - columnInfo_s columnInfo[16]; - int notselectable; - int noScrollBars; - int usePaging; - float selectBorder[4]; - float disableColor[4]; - float focusColor[4]; - float elementHighlightColor[4]; - float elementBackgroundColor[4]; - Material* selectIcon; - Material* backgroundItemListbox; - Material* highlightTexture; - int noBlinkingHighlight; - MenuRow* rows; - int maxRows; - int rowCount; - }; - - struct multiDef_s - { - const char* dvarList[32]; - const char* dvarStr[32]; - float dvarValue[32]; - int count; - int actionOnEnterPressOnly; - int strDef; - }; - - union focusDefData_t - { - listBoxDef_s* listBox; - multiDef_s* multi; - editFieldDef_s* editField; - enumDvarDef_s* enumDvar; - void* data; - }; - - struct focusItemDef_s - { - const char* mouseEnterText; - const char* mouseExitText; - const char* mouseEnter; - const char* mouseExit; - ItemKeyHandler* onKey; - focusDefData_t focusTypeData; - }; - - struct gameMsgDef_s - { - int gameMsgWindowIndex; - int gameMsgWindowMode; - }; - - union textDefData_t - { - focusItemDef_s* focusItemDef; - gameMsgDef_s* gameMsgDef; - void* data; - }; - - struct textDef_s - { - rectDef_s textRect[1]; - int alignment; - int fontEnum; - int itemFlags; - int textAlignMode; - float textalignx; - float textaligny; - float textscale; - int textStyle; - const char* text; - textExp_s* textExpData; - textDefData_t textTypeData; - }; - - struct imageDef_s - { - ExpressionStatement materialExp; - }; - - struct ownerDrawDef_s - { - ExpressionStatement dataExp; - }; - - union itemDefData_t - { - textDef_s* textDef; - imageDef_s* imageDef; - focusItemDef_s* blankButtonDef; - ownerDrawDef_s* ownerDrawDef; - void* data; - }; - - struct rectData_s - { - ExpressionStatement rectXExp; - ExpressionStatement rectYExp; - ExpressionStatement rectWExp; - ExpressionStatement rectHExp; - }; - - struct animParamsDef_t - { - const char* name; - rectDef_s rectClient; - float borderSize; - float foreColor[4]; - float backColor[4]; - float borderColor[4]; - float outlineColor[4]; - float textScale; - float rotation; - GenericEventHandler* onEvent; - }; - - struct UIAnimInfo - { - int animStateCount; - animParamsDef_t** animStates; - animParamsDef_t currentAnimState; - animParamsDef_t nextAnimState; - int animating; - int animStartTime; - int animDuration; - }; - - enum ItemDefType - { - ITEM_TYPE_DEFAULT = 0x0, - ITEM_TYPE_TEXT = 0x1, - ITEM_TYPE_IMAGE = 0x2, - ITEM_TYPE_BUTTON = 0x3, - ITEM_TYPE_LISTBOX = 0x4, - ITEM_TYPE_EDITFIELD = 0x5, - ITEM_TYPE_OWNERDRAW = 0x6, - ITEM_TYPE_NUMERICFIELD = 0x7, - ITEM_TYPE_SLIDER = 0x8, - ITEM_TYPE_YESNO = 0x9, - ITEM_TYPE_MULTI = 0xA, - ITEM_TYPE_DVARENUM = 0xB, - ITEM_TYPE_BIND = 0xC, - ITEM_TYPE_VALIDFILEFIELD = 0xD, - ITEM_TYPE_UPREDITFIELD = 0xE, - ITEM_TYPE_GAME_MESSAGE_WINDOW = 0xF, - ITEM_TYPE_BIND2 = 0x10, - ITEM_TYPE_HIGHLIGHT = 0x11, - ITEM_TYPE_OWNERDRAW_TEXT = 0x12, - ITEM_TYPE_OD_BUTTON = 0x13, - ITEM_TYPE_OD_TEXT_BUTTON = 0x14, - ITEM_TYPE_BUTTON_NO_TEXT = 0x15, - ITEM_TYPE_ALPHANUMERICFIELD = 0x16, - ITEM_TYPE_RADIOBUTTON = 0x19, - ITEM_TYPE_MODEL = 0x1A, - ITEM_TYPE_CHECKBOX = 0x1B, - ITEM_TYPE_COMBO = 0x1C, - ITEM_TYPE_DECIMALFIELD = 0x1E, - ITEM_TYPE_CONFEDITFIELD = 0x1F, - ITEM_TYPE_MENUMODEL = 0x27 - }; - - struct type_align(8) itemDef_s - { - windowDef_t window; - int type; - int dataType; - int imageTrack; - const char* dvar; - const char* dvarTest; - const char* enableDvar; - int dvarFlags; - itemDefData_t typeData; - menuDef_t* parent; - rectData_s* rectExpData; - ExpressionStatement visibleExp; - gcc_align(8) uint64_t showBits; - gcc_align(8) uint64_t hideBits; - ExpressionStatement forecolorAExp; - int ui3dWindowId; - GenericEventHandler* onEvent; - UIAnimInfo* animInfo; - }; - - struct type_align(8) menuDef_t - { - windowDef_t window; - const char* font; - int fullScreen; - int ui3dWindowId; - int itemCount; - int fontIndex; - int cursorItem[1]; - int fadeCycle; - int priority; - float fadeClamp; - float fadeAmount; - float fadeInAmount; - float blurRadius; - int openSlideSpeed; - int closeSlideSpeed; - int openSlideDirection; - int closeSlideDirection; - rectDef_s initialRectInfo; - int openFadingTime; - int closeFadingTime; - int fadeTimeCounter; - int slideTimeCounter; - GenericEventHandler* onEvent; - ItemKeyHandler* onKey; - ExpressionStatement visibleExp; - gcc_align(8) uint64_t showBits; - gcc_align(8) uint64_t hideBits; - const char* allowedBinding; - const char* soundName; - int imageTrack; - int control; - float focusColor[4]; - float disableColor[4]; - ExpressionStatement rectXExp; - ExpressionStatement rectYExp; - itemDef_s** items; - }; - - struct LocalizeEntry - { - const char* value; - const char* name; - }; - - enum weaponIconRatioType_t - { - WEAPON_ICON_RATIO_1TO1 = 0x0, - WEAPON_ICON_RATIO_2TO1 = 0x1, - WEAPON_ICON_RATIO_4TO1 = 0x2, - WEAPON_ICON_RATIO_COUNT = 0x3, - }; - - enum weapType_t - { - WEAPTYPE_BULLET = 0x0, - WEAPTYPE_GRENADE = 0x1, - WEAPTYPE_PROJECTILE = 0x2, - WEAPTYPE_BINOCULARS = 0x3, - WEAPTYPE_GAS = 0x4, - WEAPTYPE_BOMB = 0x5, - WEAPTYPE_MINE = 0x6, - WEAPTYPE_MELEE = 0x7, - WEAPTYPE_NUM = 0x8, - }; - - enum weapClass_t - { - WEAPCLASS_RIFLE = 0x0, - WEAPCLASS_MG = 0x1, - WEAPCLASS_SMG = 0x2, - WEAPCLASS_SPREAD = 0x3, - WEAPCLASS_PISTOL = 0x4, - WEAPCLASS_GRENADE = 0x5, - WEAPCLASS_ROCKETLAUNCHER = 0x6, - WEAPCLASS_TURRET = 0x7, - WEAPCLASS_NON_PLAYER = 0x8, - WEAPCLASS_GAS = 0x9, - WEAPCLASS_ITEM = 0xA, - WEAPCLASS_MELEE = 0xB, - WEAPCLASS_KILLSTREAK_ALT_STORED_WEAPON = 0xC, - WEAPCLASS_NUM = 0xD, - }; - - enum PenetrateType - { - PENETRATE_TYPE_NONE = 0x0, - PENETRATE_TYPE_SMALL = 0x1, - PENETRATE_TYPE_MEDIUM = 0x2, - PENETRATE_TYPE_LARGE = 0x3, - PENETRATE_TYPE_COUNT = 0x4, - }; - - enum ImpactType - { - IMPACT_TYPE_NONE = 0x0, - IMPACT_TYPE_BULLET_SMALL = 0x1, - IMPACT_TYPE_BULLET_LARGE = 0x2, - IMPACT_TYPE_BULLET_AP = 0x3, - IMPACT_TYPE_BULLET_XTREME = 0x4, - IMPACT_TYPE_SHOTGUN = 0x5, - IMPACT_TYPE_GRENADE_BOUNCE = 0x6, - IMPACT_TYPE_GRENADE_EXPLODE = 0x7, - IMPACT_TYPE_RIFLE_GRENADE = 0x8, - IMPACT_TYPE_ROCKET_EXPLODE = 0x9, - IMPACT_TYPE_ROCKET_EXPLODE_XTREME = 0xA, - IMPACT_TYPE_PROJECTILE_DUD = 0xB, - IMPACT_TYPE_MORTAR_SHELL = 0xC, - IMPACT_TYPE_TANK_SHELL = 0xD, - IMPACT_TYPE_BOLT = 0xE, - IMPACT_TYPE_BLADE = 0xF, - IMPACT_TYPE_COUNT = 0x10, - }; - - enum weapInventoryType_t - { - WEAPINVENTORY_PRIMARY = 0x0, - WEAPINVENTORY_OFFHAND = 0x1, - WEAPINVENTORY_ITEM = 0x2, - WEAPINVENTORY_ALTMODE = 0x3, - WEAPINVENTORY_MELEE = 0x4, - WEAPINVENTORYCOUNT = 0x5, - }; - - enum weapFireType_t - { - WEAPON_FIRETYPE_FULLAUTO = 0x0, - WEAPON_FIRETYPE_SINGLESHOT = 0x1, - WEAPON_FIRETYPE_BURSTFIRE2 = 0x2, - WEAPON_FIRETYPE_BURSTFIRE3 = 0x3, - WEAPON_FIRETYPE_BURSTFIRE4 = 0x4, - WEAPON_FIRETYPE_STACKED = 0x5, - WEAPON_FIRETYPE_MINIGUN = 0x6, - WEAPON_FIRETYPECOUNT = 0x7, - }; - - enum weapClipType_t - { - WEAPON_CLIPTYPE_BOTTOM = 0x0, - WEAPON_CLIPTYPE_TOP = 0x1, - WEAPON_CLIPTYPE_LEFT = 0x2, - WEAPON_CLIPTYPE_DP28 = 0x3, - WEAPON_CLIPTYPE_PTRS = 0x4, - WEAPON_CLIPTYPE_LMG = 0x5, - WEAPON_CLIPTYPECOUNT = 0x6, - }; - - enum OffhandClass - { - OFFHAND_CLASS_NONE = 0x0, - OFFHAND_CLASS_FRAG_GRENADE = 0x1, - OFFHAND_CLASS_SMOKE_GRENADE = 0x2, - OFFHAND_CLASS_FLASH_GRENADE = 0x3, - OFFHAND_CLASS_GEAR = 0x4, - OFFHAND_CLASS_COUNT = 0x5, - }; - - enum OffhandSlot - { - OFFHAND_SLOT_NONE = 0x0, - OFFHAND_SLOT_LETHAL_GRENADE = 0x1, - OFFHAND_SLOT_TACTICAL_GRENADE = 0x2, - OFFHAND_SLOT_EQUIPMENT = 0x3, - OFFHAND_SLOT_SPECIFIC_USE = 0x4, - OFFHAND_SLOT_COUNT = 0x5, - }; - - enum weapStance_t - { - WEAPSTANCE_STAND = 0x0, - WEAPSTANCE_DUCK = 0x1, - WEAPSTANCE_PRONE = 0x2, - WEAPSTANCE_NUM = 0x3, - }; - - enum activeReticleType_t - { - VEH_ACTIVE_RETICLE_NONE = 0x0, - VEH_ACTIVE_RETICLE_PIP_ON_A_STICK = 0x1, - VEH_ACTIVE_RETICLE_BOUNCING_DIAMOND = 0x2, - VEH_ACTIVE_RETICLE_COUNT = 0x3, - }; - - enum ammoCounterClipType_t - { - AMMO_COUNTER_CLIP_NONE = 0x0, - AMMO_COUNTER_CLIP_MAGAZINE = 0x1, - AMMO_COUNTER_CLIP_SHORTMAGAZINE = 0x2, - AMMO_COUNTER_CLIP_SHOTGUN = 0x3, - AMMO_COUNTER_CLIP_ROCKET = 0x4, - AMMO_COUNTER_CLIP_BELTFED = 0x5, - AMMO_COUNTER_CLIP_ALTWEAPON = 0x6, - AMMO_COUNTER_CLIP_COUNT = 0x7, - }; - - enum weapOverlayReticle_t - { - WEAPOVERLAYRETICLE_NONE = 0x0, - WEAPOVERLAYRETICLE_CROSSHAIR = 0x1, - WEAPOVERLAYRETICLE_NUM = 0x2, - }; - - enum WeapOverlayInteface_t - { - WEAPOVERLAYINTERFACE_NONE = 0x0, - WEAPOVERLAYINTERFACE_JAVELIN = 0x1, - WEAPOVERLAYINTERFACE_TURRETSCOPE = 0x2, - WEAPOVERLAYINTERFACECOUNT = 0x3, - }; - - enum weapProjExposion_t - { - WEAPPROJEXP_GRENADE = 0x0, - WEAPPROJEXP_ROCKET = 0x1, - WEAPPROJEXP_FLASHBANG = 0x2, - WEAPPROJEXP_NONE = 0x3, - WEAPPROJEXP_DUD = 0x4, - WEAPPROJEXP_SMOKE = 0x5, - WEAPPROJEXP_HEAVY = 0x6, - WEAPPROJEXP_FIRE = 0x7, - WEAPPROJEXP_NAPALMBLOB = 0x8, - WEAPPROJEXP_BOLT = 0x9, - WEAPPROJEXP_NUM = 0xA, - }; - - enum WeapStickinessType - { - WEAPSTICKINESS_NONE = 0x0, - WEAPSTICKINESS_ALL = 0x1, - WEAPSTICKINESS_ALL_NO_SENTIENTS = 0x2, - WEAPSTICKINESS_GROUND = 0x3, - WEAPSTICKINESS_GROUND_WITH_YAW = 0x4, - WEAPSTICKINESS_FLESH = 0x5, - WEAPSTICKINESS_COUNT = 0x6, - }; - - enum WeapRotateType - { - WEAPROTATE_GRENADE_ROTATE = 0x0, - WEAPROTATE_BLADE_ROTATE = 0x1, - WEAPROTATE_CYLINDER_ROTATE = 0x2, - WEAPROTATE_COUNT = 0x3, - }; - - enum guidedMissileType_t - { - MISSILE_GUIDANCE_NONE = 0x0, - MISSILE_GUIDANCE_SIDEWINDER = 0x1, - MISSILE_GUIDANCE_HELLFIRE = 0x2, - MISSILE_GUIDANCE_JAVELIN = 0x3, - MISSILE_GUIDANCE_BALLISTIC = 0x4, - MISSILE_GUIDANCE_WIREGUIDED = 0x5, - MISSILE_GUIDANCE_TVGUIDED = 0x6, - MISSILE_GUIDANCE_COUNT = 0x7, - }; - - enum weapAnimFiles_t - { - WEAP_ANIM_ROOT = 0x0, - WEAP_ANIM_IDLE = 0x1, - WEAP_ANIM_EMPTY_IDLE = 0x2, - WEAP_ANIM_FIRE = 0x3, - WEAP_ANIM_HOLD_FIRE = 0x4, - WEAP_ANIM_LASTSHOT = 0x5, - WEAP_ANIM_RECHAMBER = 0x6, - WEAP_ANIM_MELEE = 0x7, - WEAP_ANIM_MELEE_CHARGE = 0x8, - WEAP_ANIM_RELOAD = 0x9, - WEAP_ANIM_RELOAD_RIGHT = 0xA, - WEAP_ANIM_RELOAD_EMPTY = 0xB, - WEAP_ANIM_RELOAD_START = 0xC, - WEAP_ANIM_RELOAD_END = 0xD, - WEAP_ANIM_RELOAD_QUICK = 0xE, - WEAP_ANIM_RELOAD_QUICK_EMPTY = 0xF, - WEAP_ANIM_RAISE = 0x10, - WEAP_ANIM_FIRST_RAISE = 0x11, - WEAP_ANIM_DROP = 0x12, - WEAP_ANIM_ALT_RAISE = 0x13, - WEAP_ANIM_ALT_DROP = 0x14, - WEAP_ANIM_QUICK_RAISE = 0x15, - WEAP_ANIM_QUICK_DROP = 0x16, - WEAP_ANIM_EMPTY_RAISE = 0x17, - WEAP_ANIM_EMPTY_DROP = 0x18, - WEAP_ANIM_SPRINT_IN = 0x19, - WEAP_ANIM_SPRINT_LOOP = 0x1A, - WEAP_ANIM_SPRINT_OUT = 0x1B, - WEAP_ANIM_SPRINT_EMPTY_IN = 0x1C, - WEAP_ANIM_SPRINT_EMPTY_LOOP = 0x1D, - WEAP_ANIM_SPRINT_EMPTY_OUT = 0x1E, - WEAP_ANIM_LOWREADY_IN = 0x1F, - WEAP_ANIM_LOWREADY_LOOP = 0x20, - WEAP_ANIM_LOWREADY_OUT = 0x21, - WEAP_ANIM_CONT_FIRE_IN = 0x22, - WEAP_ANIM_CONT_FIRE_LOOP = 0x23, - WEAP_ANIM_CONT_FIRE_OUT = 0x24, - WEAP_ANIM_DEPLOY = 0x25, - WEAP_ANIM_BREAKDOWN = 0x26, - WEAP_ANIM_DETONATE = 0x27, - WEAP_ANIM_NIGHTVISION_WEAR = 0x28, - WEAP_ANIM_NIGHTVISION_REMOVE = 0x29, - WEAP_ANIM_ADS_FIRE = 0x2A, - WEAP_ANIM_ADS_LASTSHOT = 0x2B, - WEAP_ANIM_ADS_RECHAMBER = 0x2C, - WEAP_ANIM_DTP_IN = 0x2D, - WEAP_ANIM_DTP_LOOP = 0x2E, - WEAP_ANIM_DTP_OUT = 0x2F, - WEAP_ANIM_DTP_EMPTY_IN = 0x30, - WEAP_ANIM_DTP_EMPTY_LOOP = 0x31, - WEAP_ANIM_DTP_EMPTY_OUT = 0x32, - WEAP_ANIM_SLIDE_IN = 0x33, - WEAP_ANIM_MANTLE = 0x34, - WEAP_ANIM_CAMERA_SPRINT_LOOP = 0x35, - WEAP_ANIM_CAMERA_DTP_IN = 0x36, - WEAP_ANIM_CAMERA_DTP_LOOP = 0x37, - WEAP_ANIM_CAMERA_DTP_OUT = 0x38, - WEAP_ANIM_CAMERA_MANTLE = 0x39, - WEAP_ANIM_FIRE_LEFT = 0x3A, - WEAP_ANIM_LASTSHOT_LEFT = 0x3B, - WEAP_ANIM_IDLE_LEFT = 0x3C, - WEAP_ANIM_EMPTY_IDLE_LEFT = 0x3D, - WEAP_ANIM_RELOAD_EMPTY_LEFT = 0x3E, - WEAP_ANIM_RELOAD_LEFT = 0x3F, - WEAP_ANIM_ADS_UP = 0x40, - WEAP_ANIM_ADS_DOWN = 0x41, - - NUM_WEAP_ANIMS - }; - - enum materialSurfType_t - { - SURF_TYPE_DEFAULT, - SURF_TYPE_BARK, - SURF_TYPE_BRICK, - SURF_TYPE_CARPET, - SURF_TYPE_CLOTH, - SURF_TYPE_CONCRETE, - SURF_TYPE_DIRT, - SURF_TYPE_FLESH, - SURF_TYPE_FOLIAGE, - SURF_TYPE_GLASS, - SURF_TYPE_GRASS, - SURF_TYPE_GRAVEL, - SURF_TYPE_ICE, - SURF_TYPE_METAL, - SURF_TYPE_MUD, - SURF_TYPE_PAPER, - SURF_TYPE_PLASTER, - SURF_TYPE_ROCK, - SURF_TYPE_SAND, - SURF_TYPE_SNOW, - SURF_TYPE_WATER, - SURF_TYPE_WOOD, - SURF_TYPE_ASPHALT, - SURF_TYPE_CERAMIC, - SURF_TYPE_PLASTIC, - SURF_TYPE_RUBBER, - SURF_TYPE_CUSHION, - SURF_TYPE_FRUIT, - SURF_TYPE_PAINTED_METAL, - SURF_TYPE_PLAYER, - SURF_TYPE_TALL_GRASS, - - SURF_TYPE_NUM - }; - - enum hitLocation_t - { - HITLOC_NONE = 0x0, - HITLOC_HELMET = 0x1, - HITLOC_HEAD = 0x2, - HITLOC_NECK = 0x3, - HITLOC_TORSO_UPR = 0x4, - HITLOC_TORSO_LWR = 0x5, - HITLOC_R_ARM_UPR = 0x6, - HITLOC_L_ARM_UPR = 0x7, - HITLOC_R_ARM_LWR = 0x8, - HITLOC_L_ARM_LWR = 0x9, - HITLOC_R_HAND = 0xA, - HITLOC_L_HAND = 0xB, - HITLOC_R_LEG_UPR = 0xC, - HITLOC_L_LEG_UPR = 0xD, - HITLOC_R_LEG_LWR = 0xE, - HITLOC_L_LEG_LWR = 0xF, - HITLOC_R_FOOT = 0x10, - HITLOC_L_FOOT = 0x11, - HITLOC_GUN = 0x12, - - HITLOC_NUM - }; - - struct flameTable - { - float flameVar_streamChunkGravityStart; - float flameVar_streamChunkGravityEnd; - float flameVar_streamChunkMaxSize; - float flameVar_streamChunkStartSize; - float flameVar_streamChunkEndSize; - float flameVar_streamChunkStartSizeRand; - float flameVar_streamChunkEndSizeRand; - float flameVar_streamChunkDistScalar; - float flameVar_streamChunkDistSwayScale; - float flameVar_streamChunkDistSwayVelMax; - float flameVar_streamChunkSpeed; - float flameVar_streamChunkDecel; - float flameVar_streamChunkVelocityAddScale; - float flameVar_streamChunkDuration; - float flameVar_streamChunkDurationScaleMaxVel; - float flameVar_streamChunkDurationVelScalar; - float flameVar_streamChunkSizeSpeedScale; - float flameVar_streamChunkSizeAgeScale; - float flameVar_streamChunkSpawnFireIntervalStart; - float flameVar_streamChunkSpawnFireIntervalEnd; - float flameVar_streamChunkSpawnFireMinLifeFrac; - float flameVar_streamChunkSpawnFireMaxLifeFrac; - float flameVar_streamChunkFireMinLifeFrac; - float flameVar_streamChunkFireMinLifeFracStart; - float flameVar_streamChunkFireMinLifeFracEnd; - float flameVar_streamChunkDripsMinLifeFrac; - float flameVar_streamChunkDripsMinLifeFracStart; - float flameVar_streamChunkDripsMinLifeFracEnd; - float flameVar_streamChunkRotationRange; - float flameVar_streamSizeRandSinWave; - float flameVar_streamSizeRandCosWave; - float flameVar_streamDripsChunkInterval; - float flameVar_streamDripsChunkMinFrac; - float flameVar_streamDripsChunkRandFrac; - float flameVar_streamSmokeChunkInterval; - float flameVar_streamSmokeChunkMinFrac; - float flameVar_streamSmokeChunkRandFrac; - float flameVar_streamChunkCullDistSizeFrac; - float flameVar_streamChunkCullMinLife; - float flameVar_streamChunkCullMaxLife; - float flameVar_streamFuelSizeStart; - float flameVar_streamFuelSizeEnd; - float flameVar_streamFuelLength; - float flameVar_streamFuelNumSegments; - float flameVar_streamFuelAnimLoopTime; - float flameVar_streamFlameSizeStart; - float flameVar_streamFlameSizeEnd; - float flameVar_streamFlameLength; - float flameVar_streamFlameNumSegments; - float flameVar_streamFlameAnimLoopTime; - float flameVar_streamPrimaryLightRadius; - float flameVar_streamPrimaryLightRadiusFlutter; - float flameVar_streamPrimaryLightR; - float flameVar_streamPrimaryLightG; - float flameVar_streamPrimaryLightB; - float flameVar_streamPrimaryLightFlutterR; - float flameVar_streamPrimaryLightFlutterG; - float flameVar_streamPrimaryLightFlutterB; - float flameVar_fireLife; - float flameVar_fireLifeRand; - float flameVar_fireSpeedScale; - float flameVar_fireSpeedScaleRand; - float flameVar_fireVelocityAddZ; - float flameVar_fireVelocityAddZRand; - float flameVar_fireVelocityAddSideways; - float flameVar_fireGravity; - float flameVar_fireGravityEnd; - float flameVar_fireMaxRotVel; - float flameVar_fireFriction; - float flameVar_fireEndSizeAdd; - float flameVar_fireStartSizeScale; - float flameVar_fireEndSizeScale; - float flameVar_dripsLife; - float flameVar_dripsLifeRand; - float flameVar_dripsSpeedScale; - float flameVar_dripsSpeedScaleRand; - float flameVar_dripsVelocityAddZ; - float flameVar_dripsVelocityAddZRand; - float flameVar_dripsVelocityAddSideways; - float flameVar_dripsGravity; - float flameVar_dripsGravityEnd; - float flameVar_dripsMaxRotVel; - float flameVar_dripsFriction; - float flameVar_dripsEndSizeAdd; - float flameVar_dripsStartSizeScale; - float flameVar_dripsEndSizeScale; - float flameVar_smokeLife; - float flameVar_smokeLifeRand; - float flameVar_smokeSpeedScale; - float flameVar_smokeVelocityAddZ; - float flameVar_smokeGravity; - float flameVar_smokeGravityEnd; - float flameVar_smokeMaxRotation; - float flameVar_smokeMaxRotVel; - float flameVar_smokeFriction; - float flameVar_smokeEndSizeAdd; - float flameVar_smokeStartSizeAdd; - float flameVar_smokeOriginSizeOfsZScale; - float flameVar_smokeOriginOfsZ; - float flameVar_smokeFadein; - float flameVar_smokeFadeout; - float flameVar_smokeMaxAlpha; - float flameVar_smokeBrightness; - float flameVar_smokeOriginOffset; - float flameVar_collisionSpeedScale; - float flameVar_collisionVolumeScale; - const char* name; - Material* fire; - Material* smoke; - Material* heat; - Material* drips; - Material* streamFuel; - Material* streamFuel2; - Material* streamFlame; - Material* streamFlame2; - const char* flameOffLoopSound; - const char* flameIgniteSound; - const char* flameOnLoopSound; - const char* flameCooldownSound; - }; - - struct WeaponDef - { - const char* szOverlayName; - XModel** gunXModel; - XModel* handXModel; - const char* szModeName; - uint16_t* notetrackSoundMapKeys; - uint16_t* notetrackSoundMapValues; - int playerAnimType; - weapType_t weapType; - weapClass_t weapClass; - PenetrateType penetrateType; - ImpactType impactType; - weapInventoryType_t inventoryType; - weapFireType_t fireType; - weapClipType_t clipType; - int itemIndex; - const char* parentWeaponName; - int iJamFireTime; - int tracerFrequency; - float tracerWidth; - float tracerLength; - int overheatWeapon; - float overheatRate; - float cooldownRate; - float overheatEndVal; - bool coolWhileFiring; - bool fuelTankWeapon; - int iTankLifeTime; - OffhandClass offhandClass; - OffhandSlot offhandSlot; - weapStance_t stance; - FxEffectDef* viewFlashEffect; - FxEffectDef* worldFlashEffect; - const char* pickupSound; - const char* pickupSoundPlayer; - const char* ammoPickupSound; - const char* ammoPickupSoundPlayer; - const char* projectileSound; - const char* pullbackSound; - const char* pullbackSoundPlayer; - const char* fireSound; - const char* fireSoundPlayer; - const char* fireLoopSound; - const char* fireLoopSoundPlayer; - const char* fireLoopEndSound; - const char* fireLoopEndSoundPlayer; - const char* fireStopSound; - const char* fireStopSoundPlayer; - const char* fireLastSound; - const char* fireLastSoundPlayer; - const char* emptyFireSound; - const char* emptyFireSoundPlayer; - const char* crackSound; - const char* whizbySound; - const char* meleeSwipeSound; - const char* meleeSwipeSoundPlayer; - const char* meleeHitSound; - const char* meleeMissSound; - const char* rechamberSound; - const char* rechamberSoundPlayer; - const char* reloadSound; - const char* reloadSoundPlayer; - const char* reloadEmptySound; - const char* reloadEmptySoundPlayer; - const char* reloadStartSound; - const char* reloadStartSoundPlayer; - const char* reloadEndSound; - const char* reloadEndSoundPlayer; - const char* rotateLoopSound; - const char* rotateLoopSoundPlayer; - const char* deploySound; - const char* deploySoundPlayer; - const char* finishDeploySound; - const char* finishDeploySoundPlayer; - const char* breakdownSound; - const char* breakdownSoundPlayer; - const char* finishBreakdownSound; - const char* finishBreakdownSoundPlayer; - const char* detonateSound; - const char* detonateSoundPlayer; - const char* nightVisionWearSound; - const char* nightVisionWearSoundPlayer; - const char* nightVisionRemoveSound; - const char* nightVisionRemoveSoundPlayer; - const char* altSwitchSound; - const char* altSwitchSoundPlayer; - const char* raiseSound; - const char* raiseSoundPlayer; - const char* firstRaiseSound; - const char* firstRaiseSoundPlayer; - const char* putawaySound; - const char* putawaySoundPlayer; - const char* overheatSound; - const char* overheatSoundPlayer; - const char* adsZoomSound; - const char** bounceSound; - const char* standMountedWeapdef; - const char* crouchMountedWeapdef; - const char* proneMountedWeapdef; - int standMountedIndex; - int crouchMountedIndex; - int proneMountedIndex; - FxEffectDef* viewShellEjectEffect; - FxEffectDef* worldShellEjectEffect; - FxEffectDef* viewLastShotEjectEffect; - FxEffectDef* worldLastShotEjectEffect; - Material* reticleCenter; - Material* reticleSide; - int iReticleCenterSize; - int iReticleSideSize; - int iReticleMinOfs; - activeReticleType_t activeReticleType; - float vStandMove[3]; - float vStandRot[3]; - float vDuckedOfs[3]; - float vDuckedMove[3]; - float vDuckedSprintOfs[3]; - float vDuckedSprintRot[3]; - float vDuckedSprintBob[2]; - float fDuckedSprintCycleScale; - float vSprintOfs[3]; - float vSprintRot[3]; - float vSprintBob[2]; - float fSprintCycleScale; - float vLowReadyOfs[3]; - float vLowReadyRot[3]; - float vDtpOfs[3]; - float vDtpRot[3]; - float vDtpBob[2]; - float fDtpCycleScale; - float vMantleOfs[3]; - float vMantleRot[3]; - float vSlideOfs[3]; - float vSlideRot[3]; - float vDuckedRot[3]; - float vProneOfs[3]; - float vProneMove[3]; - float vProneRot[3]; - float vStrafeMove[3]; - float vStrafeRot[3]; - float fPosMoveRate; - float fPosProneMoveRate; - float fStandMoveMinSpeed; - float fDuckedMoveMinSpeed; - float fProneMoveMinSpeed; - float fPosRotRate; - float fPosProneRotRate; - float fStandRotMinSpeed; - float fDuckedRotMinSpeed; - float fProneRotMinSpeed; - XModel** worldModel; - XModel* worldClipModel; - XModel* rocketModel; - XModel* mountedModel; - XModel* additionalMeleeModel; - Material* hudIcon; - weaponIconRatioType_t hudIconRatio; - Material* indicatorIcon; - weaponIconRatioType_t indicatorIconRatio; - Material* ammoCounterIcon; - weaponIconRatioType_t ammoCounterIconRatio; - ammoCounterClipType_t ammoCounterClip; - int iStartAmmo; - int iHeatIndex; - int iMaxAmmo; - int shotCount; - const char* szSharedAmmoCapName; - int iSharedAmmoCapIndex; - int iSharedAmmoCap; - bool unlimitedAmmo; - bool ammoCountClipRelative; - int damage; - float damageDuration; - float damageInterval; - int playerDamage; - int iMeleeDamage; - int iDamageType; - uint16_t explosionTag; - int iFireDelay; - int iMeleeDelay; - int meleeChargeDelay; - int iDetonateDelay; - int iSpinUpTime; - int iSpinDownTime; - float spinRate; - const char* spinLoopSound; - const char* spinLoopSoundPlayer; - const char* startSpinSound; - const char* startSpinSoundPlayer; - const char* stopSpinSound; - const char* stopSpinSoundPlayer; - int iFireTime; - int iLastFireTime; - int iRechamberTime; - int iRechamberBoltTime; - int iHoldFireTime; - int iDetonateTime; - int iMeleeTime; - int meleeChargeTime; - int iReloadTimeRight; - int iReloadTimeLeft; - int reloadShowRocketTime; - int iReloadEmptyTimeLeft; - int iReloadAddTime; - int iReloadEmptyAddTime; - int iReloadQuickAddTime; - int iReloadQuickEmptyAddTime; - int iReloadStartTime; - int iReloadStartAddTime; - int iReloadEndTime; - int iDropTime; - int iRaiseTime; - int iAltDropTime; - int quickDropTime; - int quickRaiseTime; - int iFirstRaiseTime; - int iEmptyRaiseTime; - int iEmptyDropTime; - int sprintInTime; - int sprintLoopTime; - int sprintOutTime; - int lowReadyInTime; - int lowReadyLoopTime; - int lowReadyOutTime; - int contFireInTime; - int contFireLoopTime; - int contFireOutTime; - int dtpInTime; - int dtpLoopTime; - int dtpOutTime; - int slideInTime; - int deployTime; - int breakdownTime; - int nightVisionWearTime; - int nightVisionWearTimeFadeOutEnd; - int nightVisionWearTimePowerUp; - int nightVisionRemoveTime; - int nightVisionRemoveTimePowerDown; - int nightVisionRemoveTimeFadeInStart; - int fuseTime; - int aiFuseTime; - int lockOnRadius; - int lockOnSpeed; - bool requireLockonToFire; - bool noAdsWhenMagEmpty; - bool avoidDropCleanup; - unsigned int stackFire; - float stackFireSpread; - float stackFireAccuracyDecay; - const char* stackSound; - float autoAimRange; - float aimAssistRange; - bool mountableWeapon; - float aimPadding; - float enemyCrosshairRange; - bool crosshairColorChange; - float moveSpeedScale; - float adsMoveSpeedScale; - float sprintDurationScale; - weapOverlayReticle_t overlayReticle; - WeapOverlayInteface_t overlayInterface; - float overlayWidth; - float overlayHeight; - float fAdsBobFactor; - float fAdsViewBobMult; - float fHipSpreadStandMin; - float fHipSpreadDuckedMin; - float fHipSpreadProneMin; - float hipSpreadStandMax; - float hipSpreadDuckedMax; - float hipSpreadProneMax; - float fHipSpreadDecayRate; - float fHipSpreadFireAdd; - float fHipSpreadTurnAdd; - float fHipSpreadMoveAdd; - float fHipSpreadDuckedDecay; - float fHipSpreadProneDecay; - float fHipReticleSidePos; - float fAdsIdleAmount; - float fHipIdleAmount; - float adsIdleSpeed; - float hipIdleSpeed; - float fIdleCrouchFactor; - float fIdleProneFactor; - float fGunMaxPitch; - float fGunMaxYaw; - float swayMaxAngle; - float swayLerpSpeed; - float swayPitchScale; - float swayYawScale; - float swayHorizScale; - float swayVertScale; - float swayShellShockScale; - float adsSwayMaxAngle; - float adsSwayLerpSpeed; - float adsSwayPitchScale; - float adsSwayYawScale; - bool sharedAmmo; - bool bRifleBullet; - bool armorPiercing; - bool bBoltAction; - bool bUseAltTagFlash; - bool bUseAntiLagRewind; - bool bIsCarriedKillstreakWeapon; - bool aimDownSight; - bool bRechamberWhileAds; - bool bReloadWhileAds; - float adsViewErrorMin; - float adsViewErrorMax; - bool bCookOffHold; - bool bClipOnly; - bool bCanUseInVehicle; - bool bNoDropsOrRaises; - bool adsFireOnly; - bool cancelAutoHolsterWhenEmpty; - bool suppressAmmoReserveDisplay; - bool laserSightDuringNightvision; - bool bHideThirdPerson; - bool bHasBayonet; - bool bDualWield; - bool bExplodeOnGround; - bool bThrowBack; - bool bRetrievable; - bool bDieOnRespawn; - bool bNoThirdPersonDropsOrRaises; - bool bContinuousFire; - bool bNoPing; - bool bForceBounce; - bool bUseDroppedModelAsStowed; - bool bNoQuickDropWhenEmpty; - bool bKeepCrosshairWhenADS; - bool bUseOnlyAltWeaoponHideTagsInAltMode; - Material* killIcon; - weaponIconRatioType_t killIconRatio; - bool flipKillIcon; - bool bNoPartialReload; - bool bSegmentedReload; - bool bNoADSAutoReload; - int iReloadAmmoAdd; - int iReloadStartAdd; - const char* szSpawnedGrenadeWeaponName; - const char* szDualWieldWeaponName; - unsigned int dualWieldWeaponIndex; - int iDropAmmoMin; - int iDropAmmoMax; - int iDropClipAmmoMin; - int iDropClipAmmoMax; - bool blocksProne; - bool bShowIndicator; - int isRollingGrenade; - int iExplosionRadius; - int iExplosionRadiusMin; - int iIndicatorRadius; - int iExplosionInnerDamage; - int iExplosionOuterDamage; - float damageConeAngle; - int iProjectileSpeed; - int iProjectileSpeedUp; - int iProjectileSpeedRelativeUp; - int iProjectileSpeedForward; - int iProjectileActivateDist; - float projLifetime; - float timeToAccelerate; - float projectileCurvature; - XModel* projectileModel; - weapProjExposion_t projExplosion; - FxEffectDef* projExplosionEffect; - bool projExplosionEffectForceNormalUp; - FxEffectDef* projExplosionEffect2; - bool projExplosionEffect2ForceNormalUp; - FxEffectDef* projExplosionEffect3; - bool projExplosionEffect3ForceNormalUp; - FxEffectDef* projExplosionEffect4; - bool projExplosionEffect4ForceNormalUp; - FxEffectDef* projExplosionEffect5; - bool projExplosionEffect5ForceNormalUp; - FxEffectDef* projDudEffect; - const char* projExplosionSound; - const char* projDudSound; - const char* mortarShellSound; - const char* tankShellSound; - bool bProjImpactExplode; - bool bBulletImpactExplode; - WeapStickinessType stickiness; - WeapRotateType rotateType; - bool plantable; - bool hasDetonator; - bool timedDetonation; - bool bNoCrumpleMissile; - bool rotate; - bool bKeepRolling; - bool holdButtonToThrow; - bool offhandHoldIsCancelable; - bool freezeMovementWhenFiring; - float lowAmmoWarningThreshold; - float meleeChargeRange; - bool bUseAsMelee; - bool isCameraSensor; - bool isAcousticSensor; - float* parallelBounce; - float* perpendicularBounce; - FxEffectDef* projTrailEffect; - float vProjectileColor[3]; - guidedMissileType_t guidedMissileType; - float maxSteeringAccel; - int projIgnitionDelay; - FxEffectDef* projIgnitionEffect; - const char* projIgnitionSound; - float fAdsAimPitch; - float fAdsCrosshairInFrac; - float fAdsCrosshairOutFrac; - int adsGunKickReducedKickBullets; - float adsGunKickReducedKickPercent; - float fAdsGunKickPitchMin; - float fAdsGunKickPitchMax; - float fAdsGunKickYawMin; - float fAdsGunKickYawMax; - float fAdsGunKickAccel; - float fAdsGunKickSpeedMax; - float fAdsGunKickSpeedDecay; - float fAdsGunKickStaticDecay; - float fAdsViewKickPitchMin; - float fAdsViewKickPitchMax; - float fAdsViewKickYawMin; - float fAdsViewKickYawMax; - float fAdsViewScatterMin; - float fAdsViewScatterMax; - float fAdsSpread; - int hipGunKickReducedKickBullets; - float hipGunKickReducedKickPercent; - float fHipGunKickPitchMin; - float fHipGunKickPitchMax; - float fHipGunKickYawMin; - float fHipGunKickYawMax; - float fHipGunKickAccel; - float fHipGunKickSpeedMax; - float fHipGunKickSpeedDecay; - float fHipGunKickStaticDecay; - float fHipViewKickPitchMin; - float fHipViewKickPitchMax; - float fHipViewKickYawMin; - float fHipViewKickYawMax; - float fHipViewScatterMin; - float fHipViewScatterMax; - float fightDist; - float maxDist; - //const char *accuracyGraphName[2]; // TODO: Order is accuracyGraphName[0] -> accuracyGraphKnots[0] -> originalAccuracyGraphKnots[0] -> accuracyGraphName[1] -> ... - // Which is currently not possible to do in code generation. Afaik this is the only place where this is the case. - // So might be something to fix but on the other hand it might be too much work for this little inconvenience. - const char* accuracyGraphName0; - const char* accuracyGraphName1; - //vec2_t *accuracyGraphKnots[2]; - vec2_t* accuracyGraphKnots0; - vec2_t* accuracyGraphKnots1; - //vec2_t *originalAccuracyGraphKnots[2]; - vec2_t* originalAccuracyGraphKnots0; - vec2_t* originalAccuracyGraphKnots1; - int accuracyGraphKnotCount[2]; - int originalAccuracyGraphKnotCount[2]; - int iPositionReloadTransTime; - float leftArc; - float rightArc; - float topArc; - float bottomArc; - float accuracy; - float aiSpread; - float playerSpread; - float minTurnSpeed[2]; - float maxTurnSpeed[2]; - float pitchConvergenceTime; - float yawConvergenceTime; - float suppressTime; - float maxRange; - float fAnimHorRotateInc; - float fPlayerPositionDist; - const char* szUseHintString; - const char* dropHintString; - int iUseHintStringIndex; - int dropHintStringIndex; - float horizViewJitter; - float vertViewJitter; - const char* szScript; - int minDamage; - int minPlayerDamage; - float fMaxDamageRange; - float fMinDamageRange; - float destabilizationRateTime; - float destabilizationCurvatureMax; - int destabilizeDistance; - float* locationDamageMultipliers; - const char* fireRumble; - const char* meleeImpactRumble; - const char* reloadRumble; - float adsDofStart; - float adsDofEnd; - float hipDofStart; - float hipDofEnd; - float scanSpeed; - float scanAccel; - int scanPauseTime; - const char* flameTableFirstPerson; - const char* flameTableThirdPerson; - flameTable* flameTableFirstPersonPtr; - flameTable* flameTableThirdPersonPtr; - FxEffectDef* tagFx_preparationEffect; - FxEffectDef* tagFlash_preparationEffect; - bool doGibbing; - float maxGibDistance; - }; - - struct WeaponVariantDef - { - const char* szInternalName; - int iVariantCount; - WeaponDef* weapDef; - const char* szDisplayName; - const char** szXAnims; - const char* szAltWeaponName; - uint16_t* hideTags; - unsigned int altWeaponIndex; - int iClipSize; - int iReloadTime; - int iReloadEmptyTime; - int iReloadQuickTime; - int iReloadQuickEmptyTime; - int iAdsTransInTime; - int iAdsTransOutTime; - int iAltRaiseTime; - const char* szAmmoName; - int iAmmoIndex; - const char* szClipName; - int iClipIndex; - float fAimAssistRangeAds; - float fAdsSwayHorizScale; - float fAdsSwayVertScale; - float fAdsViewKickCenterSpeed; - float fHipViewKickCenterSpeed; - float fAdsZoomFov1; - float fAdsZoomFov2; - float fAdsZoomFov3; - float fAdsZoomInFrac; - float fAdsZoomOutFrac; - float fOverlayAlphaScale; - float fOOPosAnimLength[2]; - bool bSilenced; - bool bDualMag; - bool bFullMetalJacket; - bool bHollowPoint; - bool bRapidFire; - Material* overlayMaterial; - Material* overlayMaterialLowRes; - Material* dpadIcon; - weaponIconRatioType_t dpadIconRatio; - float ikLeftHandOffset[3]; - float ikLeftHandRotation[3]; - float ikLeftHandProneOffset[3]; - float ikLeftHandProneRotation[3]; - float ikLeftHandUiViewerOffset[3]; - float ikLeftHandUiViewerRotation[3]; - }; - - struct WeaponFullDef - { - WeaponVariantDef weapVariantDef; - WeaponDef weapDef; - XModel* gunXModel[16]; - const char* szXAnims[66]; - uint16_t hideTags[32]; - uint16_t notetrackSoundMapKeys[20]; - uint16_t notetrackSoundMapValues[20]; - XModel* worldModel[16]; - float parallelBounce[31]; - float perpendicularBounce[31]; - float locationDamageMultipliers[19]; - }; - - enum snd_category_t - { - SND_CATEGORY_SFX = 0x0, - SND_CATEGORY_MUSIC = 0x1, - SND_CATEGORY_VOICE = 0x2, - SND_CATEGORY_UI = 0x3, - SND_CATEGORY_COUNT = 0x4, - }; - - struct snd_group - { - char name[32]; - char parentName[32]; - unsigned int id; - int parentIndex; - snd_category_t category; - uint16_t attenuationSp; - uint16_t attenuationMp; - }; - - struct snd_curve - { - char name[32]; - unsigned int id; - float points[8][2]; - }; - - struct snd_pan - { - char name[32]; - unsigned int id; - float front; - float back; - float center; - float lfe; - float left; - float right; - }; - - struct snd_snapshot_group - { - char name[32]; - }; - - struct snd_context - { - unsigned int type; - unsigned int valueCount; - unsigned int values[8]; - }; - - struct snd_master - { - char name[32]; - unsigned int id; - float notchE; - float notchG; - float notchF; - float notchQ; - float lowE; - float lowG; - float lowF; - float lowQ; - float peak1E; - float peak1G; - float peak1F; - float peak1Q; - float peak2E; - float peak2G; - float peak2F; - float peak2Q; - float hiE; - float hiG; - float hiF; - float hiQ; - float eqG; - float compE; - float compPG; - float compMG; - float compT; - float compR; - float compTA; - float compTR; - float limitE; - float limitPG; - float limitMG; - float limitT; - float limitR; - float limitTA; - float limitTR; - }; - - struct SndDriverGlobals - { - const char* name; - unsigned int groupCount; - snd_group* groups; - unsigned int curveCount; - snd_curve* curves; - unsigned int panCount; - snd_pan* pans; - unsigned int snapshotGroupCount; - snd_snapshot_group* snapshotGroups; - unsigned int contextCount; - snd_context* contexts; - unsigned int masterCount; - snd_master* masters; - }; - - struct FxIntRange - { - int base; - int amplitude; - }; - - struct FxFloatRange - { - float base; - float amplitude; - }; - - struct FxElemVec3Range - { - float base[3]; - float amplitude[3]; - }; - - struct FxSpawnDefLooping - { - int intervalMsec; - int count; - }; - - struct FxSpawnDefOneShot - { - FxIntRange count; - }; - - union FxSpawnDef - { - FxSpawnDefLooping looping; - FxSpawnDefOneShot oneShot; - }; - - struct FxElemAtlas - { - char behavior; - char index; - char fps; - char loopCount; - char colIndexBits; - char rowIndexBits; - uint16_t entryCountAndIndexRange; - }; - - struct FxElemVelStateInFrame - { - FxElemVec3Range velocity; - FxElemVec3Range totalDelta; - }; - - struct FxElemVelStateSample - { - FxElemVelStateInFrame local; - FxElemVelStateInFrame world; - }; - - struct FxElemVisualState - { - char color[4]; - float rotationDelta; - float rotationTotal; - float size[2]; - float scale; - }; - - struct FxElemVisStateSample - { - FxElemVisualState base; - FxElemVisualState amplitude; - }; - - struct FxElemMarkVisuals - { - Material* materials[2]; - }; - - union FxEffectDefRef - { - FxEffectDef* handle; - const char* name; - }; - - union FxElemVisuals - { - void* anonymous; - Material* material; - XModel* model; - FxEffectDefRef effectDef; - const char* soundName; - }; - - union FxElemDefVisuals - { - FxElemMarkVisuals* markArray; - FxElemVisuals* array; - FxElemVisuals instance; - }; - - struct FxTrailVertex - { - float pos[2]; - float normal[2]; - float texCoord; - }; - - struct FxTrailDef - { - int scrollTimeMsec; - int repeatDist; - int splitDist; - int vertCount; - FxTrailVertex* verts; - int indCount; - uint16_t* inds; - }; - - struct FxBillboardTrim - { - float topWidth; - float bottomWidth; - }; - - union FxElemDefUnion - { - FxBillboardTrim billboard; - FxIntRange cloudDensityRange; - }; - - struct FxElemSpawnSound - { - const char* spawnSound; - }; - - enum FxElemType : char - { - FX_ELEM_TYPE_SPRITE_BILLBOARD = 0x0, - FX_ELEM_TYPE_SPRITE_ORIENTED = 0x1, - FX_ELEM_TYPE_SPRITE_ROTATED = 0x2, - FX_ELEM_TYPE_TAIL = 0x3, - FX_ELEM_TYPE_LINE = 0x4, - FX_ELEM_TYPE_TRAIL = 0x5, - FX_ELEM_TYPE_CLOUD = 0x6, - FX_ELEM_TYPE_MODEL = 0x7, - FX_ELEM_TYPE_OMNI_LIGHT = 0x8, - FX_ELEM_TYPE_SPOT_LIGHT = 0x9, - FX_ELEM_TYPE_SOUND = 0xA, - FX_ELEM_TYPE_DECAL = 0xB, - FX_ELEM_TYPE_RUNNER = 0xC, - FX_ELEM_TYPE_COUNT = 0xD, - FX_ELEM_TYPE_LAST_SPRITE = 0x5, - FX_ELEM_TYPE_LAST_DRAWN = 0x9, - }; - - struct FxElemDef - { - int flags; - FxSpawnDef spawn; - FxFloatRange spawnRange; - FxFloatRange fadeInRange; - FxFloatRange fadeOutRange; - float spawnFrustumCullRadius; - FxIntRange spawnDelayMsec; - FxIntRange lifeSpanMsec; - FxFloatRange spawnOrigin[3]; - FxFloatRange spawnOffsetRadius; - FxFloatRange spawnOffsetHeight; - FxFloatRange spawnAngles[3]; - FxFloatRange angularVelocity[3]; - FxFloatRange initialRotation; - unsigned int rotationAxis; - FxFloatRange gravity; - FxFloatRange reflectionFactor; - FxElemAtlas atlas; - float windInfluence; - char elemType; - char visualCount; - char velIntervalCount; - char visStateIntervalCount; - FxElemVelStateSample* velSamples; - FxElemVisStateSample* visSamples; - FxElemDefVisuals visuals; - float collMins[3]; - float collMaxs[3]; - FxEffectDefRef effectOnImpact; - FxEffectDefRef effectOnDeath; - FxEffectDefRef effectEmitted; - FxFloatRange emitDist; - FxFloatRange emitDistVariance; - FxEffectDefRef effectAttached; - FxTrailDef* trailDef; - char sortOrder; - char lightingFrac; - char unused[2]; - uint16_t alphaFadeTimeMsec; - uint16_t maxWindStrength; - uint16_t spawnIntervalAtMaxWind; - uint16_t lifespanAtMaxWind; - FxElemDefUnion u; - FxElemSpawnSound spawnSound; - float billboardPivot[2]; - }; - - struct FxEffectDef - { - const char* name; - char flags; - char efPriority; - char reserved[2]; - int totalSize; - int msecLoopingLife; - int elemDefCountLooping; - int elemDefCountOneShot; - int elemDefCountEmission; - FxElemDef* elemDefs; - float boundingBoxDim[3]; - float boundingSphere[4]; - }; - - struct FxImpactEntry - { - FxEffectDef* nonflesh[31]; - FxEffectDef* flesh[4]; - }; - - struct FxImpactTable - { - const char* name; - FxImpactEntry* table; - }; - - struct RawFile - { - const char* name; - int len; - const char* buffer; - }; - - struct StringTableCell - { - const char* string; - int hash; - }; - - struct StringTable - { - const char* name; - int columnCount; - int rowCount; - StringTableCell* values; - int16_t* cellIndex; - }; - - struct PackIndexHeader - { - unsigned int magic; - unsigned int timestamp; - unsigned int count; - unsigned int alignment; - unsigned int data_start; - }; - - struct PackIndexEntry - { - unsigned int hash; - unsigned int offset; - unsigned int size; - }; - - struct PackIndex - { - const char* name; - PackIndexHeader header; - PackIndexEntry* entries; - }; - - struct XGlobals - { - const char* name; - int xanimStreamBufferSize; - int cinematicMaxWidth; - int cinematicMaxHeight; - int extracamResolution; - int gumpReserve; - float screenClearColor[4]; - }; - - struct ddlMemberDef_t - { - const char* name; - int size; - int offset; - int type; - int externalIndex; - unsigned int min; - unsigned int max; - unsigned int serverDelta; - unsigned int clientDelta; - int arraySize; - int enumIndex; - int permission; - }; - - struct ddlStructDef_t - { - const char* name; - int size; - int memberCount; - ddlMemberDef_t* members; - }; - - struct ddlEnumDef_t - { - const char* name; - int memberCount; - const char** members; - }; - - struct ddlDef_t - { - int version; - int size; - ddlStructDef_t* structList; - int structCount; - ddlEnumDef_t* enumList; - int enumCount; - ddlDef_t* next; - }; - - struct ddlRoot_t - { - const char* name; - ddlDef_t* ddlDef; - }; - - struct GlassDef - { - const char* name; - int maxHealth; - float thickness; - float minShardSize; - float maxShardSize; - float shardLifeProbablility; - int maxShards; - Material* pristineMaterial; - Material* crackedMaterial; - Material* shardMaterial; - const char* crackSound; - const char* shatterShound; - const char* autoShatterShound; - FxEffectDef* crackEffect; - FxEffectDef* shatterEffect; - }; - - struct Glass - { - GlassDef* glassDef; - unsigned int index; - unsigned int brushModel; - vec3_t origin; - vec3_t angles; - vec3_t absmin; - vec3_t absmax; - bool isPlanar; - char numOutlineVerts; - vec2_t* outline; - vec3_t outlineAxis[3]; - vec3_t outlineOrigin; - float uvScale; - float thickness; - }; - - struct Glasses - { - const char* name; - unsigned int numGlasses; - Glass* glasses; - char* workMemory; - unsigned int workMemorySize; - unsigned int smallAllocatorBlocks; - unsigned int maxGroups; - unsigned int maxShards; - unsigned int maxPhysics; - unsigned int shardMemorySize; - unsigned int maxFreeCmd; - unsigned int numSlots; - unsigned int numVerts; - unsigned int numIndices; - }; - - struct EmblemLayer - { - int cost; - int unlockLevel; - int unlockPLevel; - }; - - struct EmblemCategory - { - const char* name; - const char* description; - }; - - struct EmblemIcon - { - GfxImage* image; - const char* description; - float outlineSize; - int defaultColor; - int cost; - int unlockLevel; - int unlockPLevel; - int unclassifyAt; - int sortKey; - unsigned int category; - }; - - struct EmblemBackground - { - Material* material; - const char* description; - int cost; - int unlockLevel; - int unlockPLevel; - int unclassifyAt; - }; - - struct EmblemSet - { - int colorCount; - int layerCount; - EmblemLayer* layers; - int categoryCount; - EmblemCategory* categories; - int iconCount; - EmblemIcon* icons; - int backgroundCount; - EmblemBackground* backgrounds; - int backgroundLookupCount; - int16_t* backgroundLookup; - }; +struct PhysPreset; +struct PhysConstraints; +struct DestructibleDef; +struct XAnimParts; +struct XModel; +struct Material; +struct MaterialTechniqueSet; +struct GfxImage; +struct SndBank; +struct SndPatch; +struct clipMap_t; +struct ComWorld; +struct GameWorldSp; +struct GameWorldMp; +struct MapEnts; +struct GfxWorld; +struct GfxLightDef; +struct Font_s; +struct MenuList; +struct menuDef_t; +struct LocalizeEntry; +struct WeaponVariantDef; +struct SndDriverGlobals; +struct FxEffectDef; +struct FxImpactTable; +struct RawFile; +struct StringTable; +struct PackIndex; +struct XGlobals; +struct ddlRoot_t; +struct Glasses; +struct EmblemSet; + +enum XAssetType { + ASSET_TYPE_XMODELPIECES = 0x0, + ASSET_TYPE_PHYSPRESET = 0x1, + ASSET_TYPE_PHYSCONSTRAINTS = 0x2, + ASSET_TYPE_DESTRUCTIBLEDEF = 0x3, + ASSET_TYPE_XANIMPARTS = 0x4, + ASSET_TYPE_XMODEL = 0x5, + ASSET_TYPE_MATERIAL = 0x6, + ASSET_TYPE_TECHNIQUE_SET = 0x7, + ASSET_TYPE_IMAGE = 0x8, + ASSET_TYPE_SOUND = 0x9, + ASSET_TYPE_SOUND_PATCH = 0xA, + ASSET_TYPE_CLIPMAP = 0xB, + ASSET_TYPE_CLIPMAP_PVS = 0xC, + ASSET_TYPE_COMWORLD = 0xD, + ASSET_TYPE_GAMEWORLD_SP = 0xE, + ASSET_TYPE_GAMEWORLD_MP = 0xF, + ASSET_TYPE_MAP_ENTS = 0x10, + ASSET_TYPE_GFXWORLD = 0x11, + ASSET_TYPE_LIGHT_DEF = 0x12, + ASSET_TYPE_UI_MAP = 0x13, + ASSET_TYPE_FONT = 0x14, + ASSET_TYPE_MENULIST = 0x15, + ASSET_TYPE_MENU = 0x16, + ASSET_TYPE_LOCALIZE_ENTRY = 0x17, + ASSET_TYPE_WEAPON = 0x18, + ASSET_TYPE_WEAPONDEF = 0x19, + ASSET_TYPE_WEAPON_VARIANT = 0x1A, + ASSET_TYPE_SNDDRIVER_GLOBALS = 0x1B, + ASSET_TYPE_FX = 0x1C, + ASSET_TYPE_IMPACT_FX = 0x1D, + ASSET_TYPE_AITYPE = 0x1E, + ASSET_TYPE_MPTYPE = 0x1F, + ASSET_TYPE_MPBODY = 0x20, + ASSET_TYPE_MPHEAD = 0x21, + ASSET_TYPE_CHARACTER = 0x22, + ASSET_TYPE_XMODELALIAS = 0x23, + ASSET_TYPE_RAWFILE = 0x24, + ASSET_TYPE_STRINGTABLE = 0x25, + ASSET_TYPE_PACK_INDEX = 0x26, + ASSET_TYPE_XGLOBALS = 0x27, + ASSET_TYPE_DDL = 0x28, + ASSET_TYPE_GLASSES = 0x29, + ASSET_TYPE_EMBLEMSET = 0x2A, + ASSET_TYPE_COUNT = 0x2B, + ASSET_TYPE_STRING = 0x2B, + ASSET_TYPE_ASSETLIST = 0x2C, + + ASSET_TYPE_FULL_COUNT +}; + +enum XFileBlock { + XFILE_BLOCK_TEMP, + XFILE_BLOCK_RUNTIME, + XFILE_BLOCK_LARGE_RUNTIME, + XFILE_BLOCK_PHYSICAL_RUNTIME, + XFILE_BLOCK_VIRTUAL, + XFILE_BLOCK_LARGE, + XFILE_BLOCK_PHYSICAL, + + MAX_XFILE_COUNT +}; + +typedef float vec2_t[2]; +typedef float vec3_t[3]; +typedef float vec4_t[4]; + +union XAssetHeader { + // XModelPieces *xmodelPieces; // Not an asset + PhysPreset *physPreset; + PhysConstraints *physConstraints; + DestructibleDef *destructibleDef; + XAnimParts *parts; + XModel *model; + Material *material; + // MaterialPixelShader *pixelShader; // Not an asset + // MaterialVertexShader *vertexShader; // Not an asset + MaterialTechniqueSet *techniqueSet; + GfxImage *image; + SndBank *sound; + SndPatch *soundPatch; + clipMap_t *clipMap; + ComWorld *comWorld; + GameWorldSp *gameWorldSp; + GameWorldMp *gameWorldMp; + MapEnts *mapEnts; + GfxWorld *gfxWorld; + GfxLightDef *lightDef; + Font_s *font; + MenuList *menuList; + menuDef_t *menu; + LocalizeEntry *localize; + WeaponVariantDef *weapon; + SndDriverGlobals *sndDriverGlobals; + FxEffectDef *fx; + FxImpactTable *impactFx; + RawFile *rawfile; + StringTable *stringTable; + PackIndex *packIndex; + XGlobals *xGlobals; + ddlRoot_t *ddlRoot; + Glasses *glasses; + // TextureList *textureList; // Not an asset + EmblemSet *emblemSet; + void *data; +}; + +typedef tdef_align(16) char char16; +typedef tdef_align(32) char byte32; +typedef tdef_align(128) char byte128; + +typedef tdef_align(4) char char_align4; +typedef tdef_align(128) char char_align128; + +typedef tdef_align(16) char raw_byte16; +typedef tdef_align(128) char raw_byte128; + +typedef tdef_align(128) float float_align128; + +typedef char cbrushedge_t; +typedef float vec2_t[2]; +typedef float vec3_t[3]; +typedef tdef_align(128) unsigned int raw_uint128; + +struct PhysPreset { + const char *name; + int flags; + float mass; + float bounce; + float friction; + float bulletForceScale; + float explosiveForceScale; + const char *sndAliasPrefix; + float piecesSpreadFraction; + float piecesUpwardVelocity; + int canFloat; + float gravityScale; + vec3_t centerOfMassOffset; + vec3_t buoyancyBoxMin; + vec3_t buoyancyBoxMax; +}; + +enum ConstraintType { + CONSTRAINT_NONE = 0x0, + CONSTRAINT_POINT = 0x1, + CONSTRAINT_DISTANCE = 0x2, + CONSTRAINT_HINGE = 0x3, + CONSTRAINT_JOINT = 0x4, + CONSTRAINT_ACTUATOR = 0x5, + CONSTRAINT_FAKE_SHAKE = 0x6, + CONSTRAINT_LAUNCH = 0x7, + CONSTRAINT_ROPE = 0x8, + CONSTRAINT_LIGHT = 0x9, + + NUM_CONSTRAINT_TYPES +}; + +enum AttachPointType { + ATTACH_POINT_WORLD = 0x0, + ATTACH_POINT_DYNENT = 0x1, + ATTACH_POINT_ENT = 0x2, + ATTACH_POINT_BONE = 0x3, +}; + +struct PhysConstraint { + uint16_t targetname; + ConstraintType type; + AttachPointType attach_point_type1; + int target_index1; + uint16_t target_ent1; + const char *target_bone1; + AttachPointType attach_point_type2; + int target_index2; + uint16_t target_ent2; + const char *target_bone2; + vec3_t offset; + vec3_t pos; + vec3_t pos2; + vec3_t dir; + int flags; + int timeout; + int min_health; + int max_health; + float distance; + float damp; + float power; + vec3_t scale; + float spin_scale; + float minAngle; + float maxAngle; + Material *material; + int constraintHandle; + int rope_index; + int centity_num[4]; +}; + +struct PhysConstraints { + const char *name; + unsigned int count; + PhysConstraint data[16]; +}; + +struct DestructibleStage { + uint16_t showBone; + float breakHealth; + float maxTime; + unsigned int flags; + FxEffectDef *breakEffect; + const char *breakSound; + const char *breakNotify; + const char *loopSound; + XModel *spawnModel[3]; + PhysPreset *physPreset; +}; + +struct DestructiblePiece { + DestructibleStage stages[5]; + char parentPiece; + float parentDamagePercent; + float bulletDamageScale; + float explosiveDamageScale; + float meleeDamageScale; + float impactDamageScale; + float entityDamageTransfer; + PhysConstraints *physConstraints; + int health; + const char *damageSound; + FxEffectDef *burnEffect; + const char *burnSound; + uint16_t enableLabel; + int hideBones[5]; +}; + +struct DestructibleDef { + const char *name; + XModel *model; + XModel *pristineModel; + int numPieces; + DestructiblePiece *pieces; + int clientOnly; +}; + +union XAnimIndices { + char *_1; + uint16_t *_2; + void *data; +}; + +struct XAnimNotifyInfo { + uint16_t name; + float time; +}; + +typedef unsigned char ByteVec[3]; +typedef tdef_align(4) unsigned short UShortVec[3]; + +union XAnimDynamicFrames { + ByteVec *_1; + UShortVec *_2; +}; + +union XAnimDynamicIndicesTrans { + char _1[1]; + uint16_t _2[1]; +}; + +struct XAnimPartTransFrames { + float mins[3]; + float size[3]; + XAnimDynamicFrames frames; + XAnimDynamicIndicesTrans indices; +}; + +union XAnimPartTransData { + XAnimPartTransFrames frames; + vec3_t frame0; +}; + +struct XAnimPartTrans { + uint16_t size; + char smallTrans; + XAnimPartTransData u; +}; + +typedef tdef_align(4) short XQuat[2]; + +union XAnimDynamicIndicesQuat { + char _1[1]; + uint16_t _2[1]; +}; + +struct XAnimDeltaPartQuatDataFrames { + XQuat *frames; + XAnimDynamicIndicesQuat indices; +}; + +union XAnimDeltaPartQuatData { + XAnimDeltaPartQuatDataFrames frames; + int16_t frame0[2]; +}; + +struct XAnimDeltaPartQuat { + uint16_t size; + XAnimDeltaPartQuatData u; +}; + +struct XAnimDeltaPart { + XAnimPartTrans *trans; + XAnimDeltaPartQuat *quat; +}; + +struct XAnimParts { + const char *name; + uint16_t dataByteCount; + uint16_t dataShortCount; + uint16_t dataIntCount; + uint16_t randomDataByteCount; + uint16_t randomDataIntCount; + uint16_t numframes; + bool bLoop; + bool bDelta; + bool bLeftHandGripIK; + bool bStreamable; + unsigned int streamedFileSize; + unsigned char boneCount[10]; + unsigned char notifyCount; + char assetType; + bool isDefault; + unsigned int randomDataShortCount; + unsigned int indexCount; + float framerate; + float frequency; + float primedLength; + float loopEntryTime; + uint16_t *names; + char *dataByte; + int16_t *dataShort; + int *dataInt; + int16_t *randomDataShort; + char *randomDataByte; + int *randomDataInt; + XAnimIndices indices; + XAnimNotifyInfo *notify; + XAnimDeltaPart *deltaPart; +}; + +struct DObjSkelMat { + float axis[3][4]; + float origin[4]; +}; + +struct DObjAnimMat { + float quat[4]; + float trans[3]; + float transWeight; +}; + +struct XSurfaceVertexInfo { + int16_t vertCount[4]; + uint16_t *vertsBlend; + float *tensionData; +}; + +union GfxColor { + unsigned int packed; + char array[4]; +}; + +union PackedTexCoords { + unsigned int packed; +}; + +union PackedUnitVec { + unsigned int packed; + char array[4]; +}; + +struct type_align(16) GfxPackedVertex { + float xyz[3]; + float binormalSign; + GfxColor color; + PackedTexCoords texCoord; + PackedUnitVec normal; + PackedUnitVec tangent; +}; + +struct XSurfaceCollisionLeaf { + uint16_t triangleBeginIndex; +}; + +struct XSurfaceCollisionAabb { + uint16_t mins[3]; + uint16_t maxs[3]; +}; + +struct type_align(16) XSurfaceCollisionNode { + XSurfaceCollisionAabb aabb; + uint16_t childBeginIndex; + uint16_t childCount; +}; + +struct XSurfaceCollisionTree { + float trans[3]; + float scale[3]; + unsigned int nodeCount; + XSurfaceCollisionNode *nodes; + unsigned int leafCount; + XSurfaceCollisionLeaf *leafs; +}; + +struct XRigidVertList { + uint16_t boneOffset; + uint16_t vertCount; + uint16_t triOffset; + uint16_t triCount; + XSurfaceCollisionTree *collisionTree; +}; + +typedef tdef_align(16) uint16_t r_index16_t; + +struct XSurface { + char tileMode; + unsigned char vertListCount; + uint16_t flags; + uint16_t vertCount; + uint16_t triCount; + uint16_t baseTriIndex; + uint16_t baseVertIndex; + r_index16_t (*triIndices)[3]; + XSurfaceVertexInfo vertInfo; + GfxPackedVertex *verts0; + void /*IDirect3DVertexBuffer9*/ *vb0; + XRigidVertList *vertList; + void /*IDirect3DIndexBuffer9*/ *indexBuffer; + int partBits[5]; +}; + +struct XModelLodInfo { + float dist; + uint16_t numsurfs; + uint16_t surfIndex; + int partBits[5]; + char lod; + char smcIndexPlusOne; + char smcAllocBits; + char unused; +}; + +struct XModelCollTri_s { + float plane[4]; + float svec[4]; + float tvec[4]; +}; + +struct XModelCollSurf_s { + XModelCollTri_s *collTris; + int numCollTris; + float mins[3]; + float maxs[3]; + int boneIdx; + int contents; + int surfFlags; +}; + +struct XBoneInfo { + float bounds[2][3]; + float offset[3]; + float radiusSquared; + char collmap; +}; + +struct XModelHighMipBounds { + float center[3]; + float himipRadiusSq; +}; + +struct XModelStreamInfo { + XModelHighMipBounds *highMipBounds; +}; + +struct cplane_s { + vec3_t normal; + float dist; + char type; + char signbits; + char pad[2]; +}; + +struct cbrushside_t { + cplane_s *plane; + int cflags; + int sflags; +}; + +struct type_align(16) BrushWrapper { + vec3_t mins; + int contents; + vec3_t maxs; + unsigned int numsides; + cbrushside_t *sides; + int axial_cflags[2][3]; + int axial_sflags[2][3]; + unsigned int numverts; + vec3_t *verts; + cplane_s *planes; +}; + +struct PhysGeomInfo { + BrushWrapper *brush; + int type; + vec3_t orientation[3]; + vec3_t offset; + vec3_t halfLengths; +}; + +typedef tdef_align(16) PhysGeomInfo PhysGeomInfo16; + +struct PhysGeomList { + unsigned int count; + PhysGeomInfo16 *geoms; + int contents; +}; + +struct Collmap { + PhysGeomList *geomList; +}; + +struct XModel { + const char *name; + unsigned char numBones; + unsigned char numRootBones; + unsigned char numsurfs; + char lodRampType; + uint16_t *boneNames; + char *parentList; + int16_t (*quats)[4]; + float (*trans)[4]; + char *partClassification; + DObjAnimMat *baseMat; + XSurface *surfs; + Material **materialHandles; + XModelLodInfo lodInfo[4]; + char lodDistAutoGenerated; + XModelCollSurf_s *collSurfs; + int numCollSurfs; + int contents; + XBoneInfo *boneInfo; + float radius; + float mins[3]; + float maxs[3]; + uint16_t numLods; + uint16_t collLod; + XModelStreamInfo streamInfo; + int memUsage; + int flags; + bool bad; + PhysPreset *physPreset; + unsigned char numCollmaps; + Collmap *collmaps; + PhysConstraints *physConstraints; +}; + +struct gcc_align(8) GfxDrawSurfFields { + uint64_t objectId : 16; + uint64_t fade : 4; + uint64_t customIndex : 5; + uint64_t reflectionProbeIndex : 3; + uint64_t hdrBits : 1; + uint64_t glightRender : 1; + uint64_t dlightRender : 1; + uint64_t materialSortedIndex : 12; + uint64_t primaryLightIndex : 8; + uint64_t surfType : 4; + uint64_t prepass : 2; + uint64_t noDynamicShadow : 1; + uint64_t primarySortKey : 6; +}; + +union GfxDrawSurf { + gcc_align(8) GfxDrawSurfFields fields; + gcc_align(8) uint64_t packed; +}; + +struct MaterialInfo { + const char *name; + unsigned int gameFlags; + char pad; + char sortKey; + char textureAtlasRowCount; + char textureAtlasColumnCount; + GfxDrawSurf drawSurf; + unsigned int surfaceTypeBits; + unsigned int layeredSurfaceTypes; + uint16_t hashIndex; +}; + +struct WaterWritable { + float floatTime; +}; + +struct complex_s { + float real; + float imag; +}; + +struct water_t { + WaterWritable writable; + complex_s *H0; + float *wTerm; + int M; + int N; + float Lx; + float Lz; + float gravity; + float windvel; + float winddir[2]; + float amplitude; + float codeConstant[4]; + GfxImage *image; +}; + +union MaterialTextureDefInfo { + GfxImage *image; + water_t *water; +}; + +struct MaterialTextureDef { + unsigned int nameHash; + char nameStart; + char nameEnd; + char samplerState; + char semantic; + char isMatureContent; + char pad[3]; + MaterialTextureDefInfo u; +}; + +struct type_align(16) MaterialConstantDef { + unsigned int nameHash; + char name[12]; + float literal[4]; +}; + +enum GfxStateBitsEnum : unsigned int { + GFXS0_SRCBLEND_RGB_SHIFT = 0x0, + GFXS0_SRCBLEND_RGB_MASK = 0xF, + GFXS0_DSTBLEND_RGB_SHIFT = 0x4, + GFXS0_DSTBLEND_RGB_MASK = 0xF0, + GFXS0_BLENDOP_RGB_SHIFT = 0x8, + GFXS0_BLENDOP_RGB_MASK = 0x700, + GFXS0_BLEND_RGB_MASK = 0x7FF, + GFXS0_ATEST_DISABLE = 0x800, + GFXS0_ATEST_GT_0 = 0x1000, + GFXS0_ATEST_GE_255 = 0x2000, + GFXS0_ATEST_GE_128 = 0x3000, + GFXS0_ATEST_MASK = 0x3000, + GFXS0_CULL_SHIFT = 0xE, + GFXS0_CULL_NONE = 0x4000, + GFXS0_CULL_BACK = 0x8000, + GFXS0_CULL_FRONT = 0xC000, + GFXS0_CULL_MASK = 0xC000, + GFXS0_SRCBLEND_ALPHA_SHIFT = 0x10, + GFXS0_SRCBLEND_ALPHA_MASK = 0xF0000, + GFXS0_DSTBLEND_ALPHA_SHIFT = 0x14, + GFXS0_DSTBLEND_ALPHA_MASK = 0xF00000, + GFXS0_BLENDOP_ALPHA_SHIFT = 0x18, + GFXS0_BLENDOP_ALPHA_MASK = 0x7000000, + GFXS0_BLEND_ALPHA_MASK = 0x7FF0000, + GFXS0_COLORWRITE_RGB = 0x8000000, + GFXS0_COLORWRITE_ALPHA = 0x10000000, + GFXS0_COLORWRITE_MASK = 0x18000000, + GFXS0_POLYMODE_LINE = 0x80000000, + GFXS1_DEPTHWRITE = 0x1, + GFXS1_DEPTHTEST_DISABLE = 0x2, + GFXS1_DEPTHTEST_SHIFT = 0x2, + GFXS1_DEPTHTEST_ALWAYS = 0x0, + GFXS1_DEPTHTEST_LESS = 0x4, + GFXS1_DEPTHTEST_EQUAL = 0x8, + GFXS1_DEPTHTEST_LESSEQUAL = 0xC, + GFXS1_DEPTHTEST_MASK = 0xC, + GFXS1_DEPTHFUNC_MASK = 0xF, + GFXS1_POLYGON_OFFSET_SHIFT = 0x4, + GFXS1_POLYGON_OFFSET_0 = 0x0, + GFXS1_POLYGON_OFFSET_1 = 0x10, + GFXS1_POLYGON_OFFSET_2 = 0x20, + GFXS1_POLYGON_OFFSET_SHADOWMAP = 0x30, + GFXS1_POLYGON_OFFSET_MASK = 0x30, + GFXS1_STENCIL_FRONT_ENABLE = 0x40, + GFXS1_STENCIL_BACK_ENABLE = 0x80, + GFXS1_STENCIL_MASK = 0xC0, + GFXS1_STENCIL_FRONT_PASS_SHIFT = 0x8, + GFXS1_STENCIL_FRONT_FAIL_SHIFT = 0xB, + GFXS1_STENCIL_FRONT_ZFAIL_SHIFT = 0xE, + GFXS1_STENCIL_FRONT_FUNC_SHIFT = 0x11, + GFXS1_STENCIL_FRONT_MASK = 0xFFF00, + GFXS1_STENCIL_BACK_PASS_SHIFT = 0x14, + GFXS1_STENCIL_BACK_FAIL_SHIFT = 0x17, + GFXS1_STENCIL_BACK_ZFAIL_SHIFT = 0x1A, + GFXS1_STENCIL_BACK_FUNC_SHIFT = 0x1D, + GFXS1_STENCIL_BACK_MASK = 0xFFF00000, + GFXS1_STENCILFUNC_FRONTBACK_MASK = 0xE00E0000, + GFXS1_STENCILOP_FRONTBACK_MASK = 0x1FF1FF00, +}; + +struct GfxStateBits { + unsigned int loadBits[2]; +}; + +struct Material { + MaterialInfo info; + char stateBitsEntry[130]; + unsigned char textureCount; + unsigned char constantCount; + unsigned char stateBitsCount; + char stateFlags; + char cameraRegion; + unsigned char maxStreamedMips; + MaterialTechniqueSet *techniqueSet; + MaterialTextureDef *textureTable; + MaterialConstantDef *constantTable; + GfxStateBits *stateBitsTable; +}; + +struct MaterialStreamRouting { + char source; + char dest; +}; + +struct MaterialVertexStreamRouting { + MaterialStreamRouting data[16]; + void /*IDirect3DVertexDeclaration9*/ *decl[18]; +}; + +struct MaterialVertexDeclaration { + char streamCount; + bool hasOptionalSource; + bool isLoaded; + MaterialVertexStreamRouting routing; +}; + +struct GfxVertexShaderLoadDef { + unsigned int *program; + uint16_t programSize; +}; + +struct MaterialVertexShaderProgram { + void /*IDirect3DVertexShader9*/ *vs; + GfxVertexShaderLoadDef loadDef; +}; + +struct MaterialVertexShader { + const char *name; + MaterialVertexShaderProgram prog; +}; + +struct GfxPixelShaderLoadDef { + unsigned int *program; + uint16_t programSize; +}; + +struct MaterialPixelShaderProgram { + void /*IDirect3DPixelShader9*/ *ps; + GfxPixelShaderLoadDef loadDef; +}; + +struct MaterialPixelShader { + const char *name; + MaterialPixelShaderProgram prog; +}; + +struct MaterialArgumentCodeConst { + uint16_t index; + char firstRow; + char rowCount; +}; + +union MaterialArgumentDef { + const float (*literalConst)[4]; + MaterialArgumentCodeConst codeConst; + unsigned int codeSampler; + unsigned int nameHash; +}; + +enum MaterialShaderArgumentType { + MTL_ARG_MATERIAL_VERTEX_CONST = 0x0, + MTL_ARG_LITERAL_VERTEX_CONST = 0x1, + MTL_ARG_MATERIAL_PIXEL_SAMPLER = 0x2, + MTL_ARG_CODE_PRIM_BEGIN = 0x3, + MTL_ARG_CODE_VERTEX_CONST = 0x3, + MTL_ARG_CODE_PIXEL_SAMPLER = 0x4, + MTL_ARG_CODE_PIXEL_CONST = 0x5, + MTL_ARG_CODE_PRIM_END = 0x6, + MTL_ARG_MATERIAL_PIXEL_CONST = 0x6, + MTL_ARG_LITERAL_PIXEL_CONST = 0x7, + + MLT_ARG_COUNT +}; + +struct MaterialShaderArgument { + uint16_t type; + uint16_t dest; + MaterialArgumentDef u; +}; + +struct MaterialPass { + MaterialVertexDeclaration *vertexDecl; + MaterialVertexShader *vertexShader; + MaterialPixelShader *pixelShader; + char perPrimArgCount; + char perObjArgCount; + char stableArgCount; + char customSamplerFlags; + MaterialShaderArgument *args; +}; + +struct MaterialTechnique { + const char *name; + uint16_t flags; + uint16_t passCount; + MaterialPass passArray[1]; +}; + +struct MaterialTechniqueSet { + const char *name; + char worldVertFormat; + char unused[1]; + uint16_t techsetFlags; + MaterialTechnique *techniques[130]; +}; + +struct GfxImageLoadDef { + char levelCount; + char flags; + int format; + int resourceSize; + char data[1]; +}; + +union GfxTexture { + // IDirect3DBaseTexture9* basemap; + // IDirect3DTexture9* map; + // IDirect3DVolumeTexture9* volmap; + // IDirect3DCubeTexture9* cubemap; + Texture *texture; + GfxImageLoadDef *loadDef; +}; + +struct Picmip { + char platform[2]; +}; + +struct CardMemory { + int platform[2]; +}; + +enum TextureSemantic { + TS_2D = 0x0, + TS_FUNCTION = 0x1, + TS_COLOR_MAP = 0x2, + TS_UNUSED_1 = 0x3, + TS_UNUSED_2 = 0x4, + TS_NORMAL_MAP = 0x5, + TS_UNUSED_3 = 0x6, + TS_UNUSED_4 = 0x7, + TS_SPECULAR_MAP = 0x8, + TS_UNUSED_5 = 0x9, + TS_UNUSED_6 = 0xA, + TS_WATER_MAP = 0xB, + TS_COLOR0_MAP = 0xC, + TS_COLOR1_MAP = 0xD, + TS_COLOR2_MAP = 0xE, + TS_COLOR3_MAP = 0xF, + TS_COLOR4_MAP = 0x10, + TS_COLOR5_MAP = 0x11, + TS_COLOR6_MAP = 0x12, + TS_COLOR7_MAP = 0x13, + TS_COLOR8_MAP = 0x14, + TS_COLOR9_MAP = 0x15, + TS_COLOR10_MAP = 0x16, + TS_COLOR11_MAP = 0x17, + TS_COLOR12_MAP = 0x18, + TS_COLOR13_MAP = 0x19, + TS_COLOR14_MAP = 0x1A, + TS_COLOR15_MAP = 0x1B, + TS_THROW_MAP = 0x1C, +}; + +enum ImageCategory { + IMG_CATEGORY_UNKNOWN = 0x0, + IMG_CATEGORY_AUTO_GENERATED = 0x1, + IMG_CATEGORY_LIGHTMAP = 0x2, + IMG_CATEGORY_LOAD_FROM_FILE = 0x3, + IMG_CATEGORY_RAW = 0x4, + IMG_CATEGORY_FIRST_UNMANAGED = 0x5, + IMG_CATEGORY_WATER = 0x5, + IMG_CATEGORY_RENDERTARGET = 0x6, + IMG_CATEGORY_TEMP = 0x7, +}; + +struct GfxImage { + GfxTexture texture; + char mapType; + char semantic; + char category; + bool delayLoadPixels; + Picmip picmip; + bool noPicmip; + char track; + CardMemory cardMemory; + uint16_t width; + uint16_t height; + uint16_t depth; + char levelCount; + char streaming; + unsigned int baseSize; + char *pixels; + unsigned int loadedSize; + char skippedMipLevels; + const char *name; + unsigned int hash; +}; + +enum snd_asset_format { + SND_ASSET_FORMAT_PCMS16 = 0x0, + SND_ASSET_FORMAT_PCMS24 = 0x1, + SND_ASSET_FORMAT_PCMS32 = 0x2, + SND_ASSET_FORMAT_IEEE = 0x3, + SND_ASSET_FORMAT_XMA4 = 0x4, + SND_ASSET_FORMAT_MP3 = 0x5, + SND_ASSET_FORMAT_MSADPCM = 0x6, + SND_ASSET_FORMAT_WMA = 0x7, +}; + +enum snd_asset_channel { + SND_ASSET_CHANNEL_L = 0x1, + SND_ASSET_CHANNEL_R = 0x2, + SND_ASSET_CHANNEL_C = 0x4, + SND_ASSET_CHANNEL_LFE = 0x8, + SND_ASSET_CHANNEL_LS = 0x10, + SND_ASSET_CHANNEL_RS = 0x20, + SND_ASSET_CHANNEL_LB = 0x40, + SND_ASSET_CHANNEL_RB = 0x80, +}; + +enum snd_asset_flags { + SND_ASSET_FLAG_DEFAULT = 0x0, + SND_ASSET_FLAG_LOOPING = 0x1, + SND_ASSET_FLAG_PAD_LOOP_BUFFER = 0x2, +}; + +typedef tdef_align(2048) char snd_align_char; + +struct snd_asset { + unsigned int version; + unsigned int frame_count; + unsigned int frame_rate; + unsigned int channel_count; + unsigned int header_size; + unsigned int block_size; + unsigned int buffer_size; + snd_asset_format format; + snd_asset_channel channel_flags; + snd_asset_flags flags; + unsigned int seek_table_count; + unsigned int *seek_table; + unsigned int data_size; + snd_align_char *data; +}; + +struct LoadedSound { + const char *name; + snd_asset sound; +}; + +typedef tdef_align(2048) char char_align_2048; + +struct PrimedSound { + const char *name; + char_align_2048 *buffer; + unsigned int size; +}; + +struct StreamedSound { + char *filename; + PrimedSound *primeSnd; +}; + +union SoundFileRef { + LoadedSound *loadSnd; + StreamedSound *streamSnd; +}; + +enum snd_alias_type_t { + SAT_UNKNOWN = 0x0, + SAT_LOADED = 0x1, + SAT_STREAMED = 0x2, + SAT_PRIMED = 0x3, + SAT_COUNT = 0x4, +}; + +struct SoundFile { + SoundFileRef u; + char type; + char exists; +}; + +struct snd_alias_t { + const char *name; + unsigned int id; + const char *subtitle; + const char *secondaryname; + SoundFile *soundFile; + unsigned int flags; + unsigned int duck; + unsigned int contextType; + unsigned int contextValue; + uint16_t fluxTime; + uint16_t startDelay; + uint16_t reverbSend; + uint16_t centerSend; + uint16_t volMin; + uint16_t volMax; + uint16_t teamVolMod; + uint16_t pitchMin; + uint16_t pitchMax; + uint16_t teamPitchMod; + uint16_t distMin; + uint16_t distMax; + uint16_t distReverbMax; + uint16_t envelopMin; + uint16_t envelopMax; + uint16_t envelopPercentage; + char minPriorityThreshold; + char maxPriorityThreshold; + char probability; + char occlusionLevel; + char occlusionWetDry; + char minPriority; + char maxPriority; + char pan; + char dryCurve; + char wetCurve; + char dryMinCurve; + char wetMinCurve; + char limitCount; + char entityLimitCount; + char snapshotGroup; +}; + +struct snd_alias_list_t { + const char *name; + unsigned int id; + snd_alias_t *head; + int count; + int sequence; +}; + +struct type_align(4) SndIndexEntry { + uint16_t value; + uint16_t next; +}; + +struct snd_radverb { + char name[32]; + unsigned int id; + float smoothing; + float earlyTime; + float lateTime; + float earlyGain; + float lateGain; + float returnGain; + float earlyLpf; + float lateLpf; + float inputLpf; + float dampLpf; + float wallReflect; + float dryGain; + float earlySize; + float lateSize; + float diffusion; +}; + +struct snd_snapshot { + char name[32]; + unsigned int id; + char occlusionName[32]; + unsigned int occlusionId; + float fadeIn; + float fadeOut; + float distance; + unsigned int fadeInCurve; + unsigned int fadeOutCurve; + float attenuation[64]; +}; + +struct SndBank { + const char *name; + unsigned int aliasCount; + snd_alias_list_t *alias; + SndIndexEntry *aliasIndex; + unsigned int packHash; + unsigned int packLocation; + unsigned int radverbCount; + snd_radverb *radverbs; + unsigned int snapshotCount; + snd_snapshot *snapshots; +}; + +struct SndPatch { + char *name; + unsigned int elementCount; + unsigned int *elements; + unsigned int fileCount; + SoundFile *files; +}; + +struct cStaticModelWritable { + uint16_t nextModelInWorldSector; +}; + +struct cStaticModel_s { + cStaticModelWritable writable; + XModel *xmodel; + float origin[3]; + float invScaledAxis[3][3]; + float absmin[3]; + float absmax[3]; +}; + +struct dmaterial_t { + char material[64]; + int surfaceFlags; + int contentFlags; +}; + +struct cNode_t { + cplane_s *plane; + int16_t children[2]; +}; + +struct cLeaf_s { + uint16_t firstCollAabbIndex; + uint16_t collAabbCount; + int brushContents; + int terrainContents; + float mins[3]; + float maxs[3]; + int leafBrushNode; + int16_t cluster; +}; + +struct cLeafBrushNodeChildren_t { + float dist; + float range; + uint16_t childOffset[2]; +}; + +struct cLeafBrushNodeLeaf_t { + uint16_t *brushes; +}; + +union cLeafBrushNodeData_t { + cLeafBrushNodeLeaf_t leaf; + cLeafBrushNodeChildren_t children; +}; + +struct cLeafBrushNode_s { + char axis; + int16_t leafBrushCount; + int contents; + cLeafBrushNodeData_t data; +}; + +struct CollisionBorder { + float distEq[3]; + float zBase; + float zSlope; + float start; + float length; +}; + +struct CollisionPartition { + char triCount; + char borderCount; + int firstTri; + int nuinds; + int fuind; + CollisionBorder *borders; +}; + +union CollisionAabbTreeIndex { + int firstChildIndex; + int partitionIndex; +}; + +struct type_align(16) CollisionAabbTree { + float origin[3]; + uint16_t materialIndex; + uint16_t childCount; + float halfSize[3]; + CollisionAabbTreeIndex u; +}; + +struct cmodel_t { + float mins[3]; + float maxs[3]; + float radius; + cLeaf_s leaf; +}; + +struct type_align(16) cbrush_t { + float mins[3]; + int contents; + float maxs[3]; + unsigned int numsides; + cbrushside_t *sides; + int axial_cflags[2][3]; + int axial_sflags[2][3]; + unsigned int numverts; + vec3_t *verts; +}; + +enum DynEntityType { + DYNENT_TYPE_INVALID = 0x0, + DYNENT_TYPE_CLUTTER = 0x1, + DYNENT_TYPE_DESTRUCT = 0x2, + DYNENT_TYPE_COUNT = 0x3, +}; + +struct GfxPlacement { + float quat[4]; + float origin[3]; +}; + +struct XModelPiece { + XModel *model; + float offset[3]; +}; + +struct XModelPieces { + const char *name; + int numpieces; + XModelPiece *pieces; +}; + +struct DynEntityDef { + DynEntityType type; + GfxPlacement pose; + XModel *xModel; + XModel *destroyedxModel; + uint16_t brushModel; + uint16_t physicsBrushModel; + FxEffectDef *destroyFx; + unsigned int destroySound; + XModelPieces *destroyPieces; + PhysPreset *physPreset; + int16_t physConstraints[4]; + int health; + int flags; + int contents; + uint16_t targetname; + uint16_t target; +}; + +struct DynEntityPose { + GfxPlacement pose; + float radius; +}; + +struct DynEntityClient { + int physObjId; + uint16_t flags; + uint16_t lightingHandle; + int health; + uint16_t burnTime; + uint16_t fadeTime; + int physicsStartTime; +}; + +struct DynEntityServer { + uint16_t flags; + int health; +}; + +struct DynEntityColl { + uint16_t sector; + uint16_t nextEntInSector; + float linkMins[3]; + float linkMaxs[3]; + int contents; +}; + +struct par_t { + float p[3]; + float p0[3]; + float p_prev[3]; + int flags; +}; + +enum rope_constraint_e { + ROPE_PAIR_CONSTRAINT = 0x0, + ROPE_WORLD_CONSTRAINT = 0x1, + ROPE_DENTITY_CONSTRAINT = 0x2, + ROPE_CENTITY_CONSTRAINT = 0x3, +}; + +struct constraint_t { + float p[3]; + rope_constraint_e type; + int entity_index; + int bone_name_hash; + char pi1; + char pi2; +}; + +struct rope_frame_verts_t { + int num_verts; + float v[50][3]; +}; + +struct rope_client_verts_t { + rope_frame_verts_t frame_verts[2]; + unsigned int frame_index; +}; + +struct rope_t { + par_t m_particles[25]; + constraint_t m_constraints[30]; + int m_entity_anchors[3]; + int m_num_particles; + int m_num_constraints; + int m_num_entity_anchors; + int m_num_draw_verts; + rope_client_verts_t m_client_verts; + float m_min[3]; + float m_max[3]; + float m_start[3]; + float m_end[3]; + int m_in_use; + int m_visible; + int m_dist_constraint; + int m_flags; + Material *m_material; + float m_seglen; + float m_length; + float m_width; + float m_scale; + float m_force_scale; + int m_health; + int m_frame; + int m_stable_count; + int m_static_rope; + uint16_t m_lightingHandle; +}; + +struct clipMap_t { + const char *name; + int isInUse; + int planeCount; + cplane_s *planes; + unsigned int numStaticModels; + cStaticModel_s *staticModelList; + unsigned int numMaterials; + dmaterial_t *materials; + unsigned int numBrushSides; + cbrushside_t *brushsides; + unsigned int numNodes; + cNode_t *nodes; + unsigned int numLeafs; + cLeaf_s *leafs; + unsigned int leafbrushNodesCount; + cLeafBrushNode_s *leafbrushNodes; + unsigned int numLeafBrushes; + uint16_t *leafbrushes; + unsigned int numLeafSurfaces; + unsigned int *leafsurfaces; + unsigned int vertCount; + vec3_t *verts; + unsigned int numBrushVerts; + vec3_t *brushVerts; + unsigned int nuinds; + uint16_t *uinds; + int triCount; + uint16_t *triIndices; + char *triEdgeIsWalkable; + int borderCount; + CollisionBorder *borders; + int partitionCount; + CollisionPartition *partitions; + int aabbTreeCount; + CollisionAabbTree *aabbTrees; + unsigned int numSubModels; + cmodel_t *cmodels; + uint16_t numBrushes; + cbrush_t *brushes; + int numClusters; + int clusterBytes; + char *visibility; + int vised; + MapEnts *mapEnts; + cbrush_t *box_brush; + cmodel_t box_model; + uint16_t originalDynEntCount; + uint16_t dynEntCount[4]; + DynEntityDef *dynEntDefList[2]; + DynEntityPose *dynEntPoseList[2]; + DynEntityClient *dynEntClientList[2]; + DynEntityServer *dynEntServerList[2]; + DynEntityColl *dynEntCollList[4]; + int num_constraints; + PhysConstraint *constraints; + int max_ropes; + rope_t *ropes; + unsigned int checksum; +}; + +struct ComPrimaryLight { + char type; + char canUseShadowMap; + char exponent; + char priority; + int16_t cullDist; + char _pad[2]; + float color[3]; + float dir[3]; + float origin[3]; + float radius; + float cosHalfFovOuter; + float cosHalfFovInner; + float cosHalfFovExpanded; + float rotationLimit; + float translationLimit; + float mipDistance; + float diffuseColor[4]; + float specularColor[4]; + float attenuation[4]; + float falloff[4]; + float angle[4]; + float aAbB[4]; + float cookieControl0[4]; + float cookieControl1[4]; + float cookieControl2[4]; + const char *defName; +}; + +struct ComWaterHeader { + int minx; + int miny; + int maxx; + int maxy; +}; + +struct type_align(4) ComWaterCell { + int16_t waterheight; + char flooroffset; + char shoredist; + char color[4]; +}; + +struct ComBurnableHeader { + int minx; + int miny; + int maxx; + int maxy; +}; + +struct ComBurnableSample { + char state; +}; + +struct ComBurnableCell { + int x; + int y; + ComBurnableSample *data; +}; + +struct ComWorld { + const char *name; + int isInUse; + unsigned int primaryLightCount; + ComPrimaryLight *primaryLights; + ComWaterHeader waterHeader; + unsigned int numWaterCells; + ComWaterCell *waterCells; + ComBurnableHeader burnableHeader; + unsigned int numBurnableCells; + ComBurnableCell *burnableCells; +}; + +struct pathnode_t; + +enum nodeType { + NODE_BADNODE = 0x0, + NODE_PATHNODE = 0x1, + NODE_COVER_STAND = 0x2, + NODE_COVER_CROUCH = 0x3, + NODE_COVER_CROUCH_WINDOW = 0x4, + NODE_COVER_PRONE = 0x5, + NODE_COVER_RIGHT = 0x6, + NODE_COVER_LEFT = 0x7, + NODE_COVER_WIDE_RIGHT = 0x8, + NODE_COVER_WIDE_LEFT = 0x9, + NODE_COVER_PILLAR = 0xA, + NODE_CONCEALMENT_STAND = 0xB, + NODE_CONCEALMENT_CROUCH = 0xC, + NODE_CONCEALMENT_PRONE = 0xD, + NODE_REACQUIRE = 0xE, + NODE_BALCONY = 0xF, + NODE_SCRIPTED = 0x10, + NODE_NEGOTIATION_BEGIN = 0x11, + NODE_NEGOTIATION_END = 0x12, + NODE_TURRET = 0x13, + NODE_GUARD = 0x14, + NODE_NUMTYPES = 0x15, + NODE_DONTLINK = 0x15, +}; + +struct pathlink_s { + float fDist; + uint16_t nodeNum; + char disconnectCount; + char negotiationLink; + char ubBadPlaceCount[4]; +}; + +struct pathnode_constant_t { + nodeType type; + uint16_t spawnflags; + uint16_t targetname; + uint16_t script_linkName; + uint16_t script_noteworthy; + uint16_t target; + uint16_t animscript; + int animscriptfunc; + float vOrigin[3]; + float fAngle; + float forward[2]; + float fRadius; + float minUseDistSq; + int16_t wOverlapNode[2]; + int16_t wChainId; + int16_t wChainDepth; + int16_t wChainParent; + uint16_t totalLinkCount; + pathlink_s *Links; +}; + +struct SentientHandle { + uint16_t number; + uint16_t infoIndex; +}; + +struct pathnode_dynamic_t { + SentientHandle pOwner; + int iFreeTime; + int iValidTime[3]; + int inPlayerLOSTime; + int16_t wLinkCount; + int16_t wOverlapCount; + int16_t turretEntNumber; + int16_t userCount; +}; + +struct pathnode_transient_t { + int iSearchFrame; + pathnode_t *pNextOpen; + pathnode_t *pPrevOpen; + pathnode_t *pParent; + float fCost; + float fHeuristic; + float costFactor; +}; + +struct pathnode_t { + pathnode_constant_t constant; + pathnode_dynamic_t dynamic; + pathnode_transient_t transient; +}; + +struct type_align(16) pathbasenode_t { + float vOrigin[3]; + unsigned int type; +}; + +struct pathnode_tree_t; + +struct pathnode_tree_nodes_t { + int nodeCount; + uint16_t *nodes; +}; + +union pathnode_tree_info_t { + pathnode_tree_t *child[2]; + pathnode_tree_nodes_t s; +}; + +struct pathnode_tree_t { + int axis; + float dist; + pathnode_tree_info_t u; +}; + +struct PathData { + unsigned int nodeCount; + pathnode_t *nodes; + pathbasenode_t *basenodes; + unsigned int chainNodeCount; + uint16_t *chainNodeForNode; + uint16_t *nodeForChainNode; + int visBytes; + char *pathVis; + int nodeTreeCount; + pathnode_tree_t *nodeTree; +}; + +struct GameWorldSp { + const char *name; + PathData path; +}; + +struct GameWorldMp { + const char *name; + PathData path; +}; + +struct MapEnts { + const char *name; + char *entityString; + int numEntityChars; +}; + +struct GfxStreamingAabbTree { + uint16_t firstItem; + uint16_t itemCount; + uint16_t firstChild; + uint16_t childCount; + float mins[3]; + float maxs[3]; +}; + +struct GfxWorldStreamInfo { + int aabbTreeCount; + GfxStreamingAabbTree *aabbTrees; + int leafRefCount; + int *leafRefs; +}; + +struct GfxWorldSunColor { + unsigned int control; + float angles[3]; + float ambientColor[4]; + float sunDiffuseColor[4]; + float sunSpecularColor[4]; + float skyColor[4]; + float groundColor[4]; + float exposure; + float sunShadowSampleSizeNear; + float skyboxHDRScale; +}; + +struct SunLightParseParams { + char name[64]; + float treeScatterIntensity; + float treeScatterAmount; + GfxWorldSunColor sunSettings[1]; +}; + +struct type_align(16) float44 { + union { + vec4_t m[4]; + float member[16]; + }; +}; + +struct type_align(16) GfxLight { + char type; + char canUseShadowMap; + int16_t cullDist; + float color[3]; + float dir[3]; + float origin[3]; + float radius; + float cosHalfFovOuter; + float cosHalfFovInner; + int exponent; + unsigned int spotShadowIndex; + float angles[3]; + float spotShadowHiDistance; + float diffuseColor[4]; + float specularColor[4]; + float shadowColor[4]; + float falloff[4]; + float attenuation[4]; + float aAbB[4]; + float cookieControl0[4]; + float cookieControl1[4]; + float cookieControl2[4]; + float44 viewMatrix; + float44 projMatrix; + GfxLightDef *def; +}; + +struct GfxLightCorona { + float origin[3]; + float radius; + float color[3]; + float intensity; +}; + +struct GfxShadowMapVolume { + unsigned int control; + unsigned int padding1; + unsigned int padding2; + unsigned int padding3; +}; + +struct GfxVolumePlane { + float plane[4]; +}; + +struct GfxExposureVolume { + unsigned int control; + float exposure; + float luminanceIncreaseScale; + float luminanceDecreaseScale; + float featherRange; + float featherAdjust; +}; + +struct GfxSkyDynamicIntensity { + float angle0; + float angle1; + float factor0; + float factor1; +}; + +struct GfxWorldDpvsPlanes { + int cellCount; + cplane_s *planes; + uint16_t *nodes; + unsigned int *sceneEntCellBits; +}; + +struct GfxCell; +struct GfxPortal; + +struct GfxPortalWritable { + bool isQueued; + bool isAncestor; + char recursionDepth; + char hullPointCount; + float (*hullPoints)[2]; + GfxPortal *queuedParent; +}; + +struct DpvsPlane { + float coeffs[4]; + char side[3]; + char pad; +}; + +struct GfxPortal { + GfxPortalWritable writable; + DpvsPlane plane; + GfxCell *cell; + vec3_t *vertices; + char vertexCount; + float hullAxis[2][3]; +}; + +struct GfxAabbTree { + float mins[3]; + float maxs[3]; + uint16_t childCount; + uint16_t surfaceCount; + uint16_t startSurfIndex; + uint16_t smodelIndexCount; + uint16_t *smodelIndexes; + int childrenOffset; +}; + +struct GfxCell { + float mins[3]; + float maxs[3]; + int aabbTreeCount; + GfxAabbTree *aabbTree; + int portalCount; + GfxPortal *portals; + int cullGroupCount; + int *cullGroups; + char reflectionProbeCount; + char *reflectionProbes; +}; + +struct GfxReflectionProbeVolumeData { + float volumePlanes[6][4]; +}; + +struct GfxReflectionProbe { + float origin[3]; + GfxImage *reflectionImage; + GfxReflectionProbeVolumeData *probeVolumes; + unsigned int probeVolumeCount; +}; + +struct GfxLightmapArray { + GfxImage *primary; + GfxImage *secondary; + GfxImage *secondaryB; +}; + +struct GfxWorldVertex { + float xyz[3]; + float binormalSign; + GfxColor color; + float texCoord[2]; + float lmapCoord[2]; + PackedUnitVec normal; + PackedUnitVec tangent; +}; + +struct GfxWorldVertexData { + GfxWorldVertex *vertices; + void /*IDirect3DVertexBuffer9*/ *worldVb; +}; + +struct GfxWorldVertexLayerData { + char *data; + void /*IDirect3DVertexBuffer9*/ *layerVb; +}; + +struct GfxWorldDraw { + unsigned int reflectionProbeCount; + GfxReflectionProbe *reflectionProbes; + GfxTexture *reflectionProbeTextures; + int lightmapCount; + GfxLightmapArray *lightmaps; + GfxTexture *lightmapPrimaryTextures; + GfxTexture *lightmapSecondaryTextures; + GfxTexture *lightmapSecondaryTexturesB; + GfxImage *terrainScorchImages[31]; + unsigned int vertexCount; + GfxWorldVertexData vd; + unsigned int vertexLayerDataSize; + GfxWorldVertexLayerData vld; + unsigned int vertexStream2DataSize; + int indexCount; + uint16_t *indices; +}; + +struct type_align(4) GfxLightGridEntry { + uint16_t colorsIndex; + char primaryLightIndex; + char needsTrace; +}; + +struct type_align(4) GfxCompressedLightGridColors { char rgb[56][3]; }; + +typedef tdef_align(4) char aligned_byte_pointer; + +struct GfxLightGrid { + bool hasLightRegions; + unsigned int sunPrimaryLightIndex; + uint16_t mins[3]; + uint16_t maxs[3]; + unsigned int rowAxis; + unsigned int colAxis; + uint16_t *rowDataStart; + unsigned int rawRowDataSize; + aligned_byte_pointer *rawRowData; + unsigned int entryCount; + GfxLightGridEntry *entries; + unsigned int colorCount; + GfxCompressedLightGridColors *colors; +}; + +struct GfxBrushModelWritable { + float mins[3]; + float maxs[3]; + float mip1radiusSq; +}; + +struct GfxBrushModel { + GfxBrushModelWritable writable; + float bounds[2][3]; + unsigned int surfaceCount; + unsigned int startSurfIndex; +}; + +struct MaterialMemory { + Material *material; + int memory; +}; + +struct sunflare_t { + bool hasValidData; + Material *spriteMaterial; + Material *flareMaterial; + float spriteSize; + float flareMinSize; + float flareMinDot; + float flareMaxSize; + float flareMaxDot; + float flareMaxAlpha; + int flareFadeInTime; + int flareFadeOutTime; + float blindMinDot; + float blindMaxDot; + float blindMaxDarken; + int blindFadeInTime; + int blindFadeOutTime; + float glareMinDot; + float glareMaxDot; + float glareMaxLighten; + int glareFadeInTime; + int glareFadeOutTime; + float sunFxPosition[3]; +}; + +struct XModelDrawInfo { + uint16_t lod; + uint16_t surfId; +}; + +struct GfxSceneDynModel { + XModelDrawInfo info; + uint16_t dynEntId; +}; + +typedef tdef_align(4) GfxSceneDynModel GfxSceneDynModel4; + +struct BModelDrawInfo { + uint16_t surfId; +}; + +struct type_align(4) GfxSceneDynBrush { + BModelDrawInfo info; + uint16_t dynEntId; +}; + +struct GfxShadowGeometry { + uint16_t surfaceCount; + uint16_t smodelCount; + uint16_t *sortedSurfIndex; + uint16_t *smodelIndex; +}; + +struct GfxLightRegionAxis { + float dir[3]; + float midPoint; + float halfSize; +}; + +struct GfxLightRegionHull { + float kdopMidPoint[9]; + float kdopHalfSize[9]; + unsigned int axisCount; + GfxLightRegionAxis *axis; +}; + +struct GfxLightRegion { + unsigned int hullCount; + GfxLightRegionHull *hulls; +}; + +struct GfxStaticModelInst { + float mins[3]; + float maxs[3]; + float lightingOrigin[3]; + GfxColor groundLighting; +}; + +struct srfTriangles_t { + float mins[3]; + int vertexLayerData; + float maxs[3]; + int firstVertex; + uint16_t vertexCount; + uint16_t triCount; + int baseIndex; + float himipRadiusSq; + int stream2ByteOffset; +}; + +struct type_align(16) GfxSurface { + srfTriangles_t tris; + Material *material; + char lightmapIndex; + char reflectionProbeIndex; + char primaryLightIndex; + char flags; + float bounds[2][3]; +}; + +struct GfxCullGroup { + float mins[3]; + float maxs[3]; + int surfaceCount; + int startSurfIndex; +}; + +struct GfxPackedPlacement { + float origin[3]; + float axis[3][3]; + float scale; +}; + +struct GfxStaticModelDrawInst { + float cullDist; + GfxPackedPlacement placement; + XModel *model; + int flags; + uint16_t smodelCacheIndex[4]; + uint16_t lightingHandle; + char reflectionProbeIndex; + char primaryLightIndex; +}; + +struct GfxWorldDpvsStatic { + unsigned int smodelCount; + unsigned int dynamicSModelCount; + unsigned int staticSurfaceCount; + unsigned int litSurfsBegin; + unsigned int litSurfsEnd; + unsigned int decalSurfsBegin; + unsigned int decalSurfsEnd; + unsigned int emissiveSurfsBegin; + unsigned int emissiveSurfsEnd; + unsigned int smodelVisDataCount; + unsigned int surfaceVisDataCount; + char *smodelVisData[3]; + char *surfaceVisData[3]; + char *smodelVisDataCameraSaved; + char *surfaceVisDataCameraSaved; + raw_uint128 *lodData; + uint16_t *sortedSurfIndex; + GfxStaticModelInst *smodelInsts; + GfxSurface *surfaces; + GfxCullGroup *cullGroups; + GfxStaticModelDrawInst *smodelDrawInsts; + GfxDrawSurf *surfaceMaterials; + raw_uint128 *surfaceCastsSunShadow; + volatile int usageCount; +}; + +struct GfxWorldDpvsDynamic { + unsigned int dynEntClientWordCount[2]; + unsigned int dynEntClientCount[2]; + unsigned int *dynEntCellBits[2]; + char *dynEntVisData[2][3]; +}; + +struct GfxWorldLodChain { + float origin[3]; + float lastDist; + unsigned int firstLodInfo; + uint16_t lodInfoCount; +}; + +struct GfxWorldLodInfo { + float dist; + unsigned int firstSurf; + uint16_t surfCount; +}; + +struct GfxWaterBuffer { + unsigned int bufferSize; + vec4_t *buffer; +}; + +struct Occluder { + unsigned int flags; + char name[16]; + float points[4][3]; +}; + +struct GfxOutdoorBounds { + float bounds[2][3]; +}; + +struct GfxHeroLight { + char type; + char unused[3]; + float color[3]; + float dir[3]; + float origin[3]; + float radius; + float cosHalfFovOuter; + float cosHalfFovInner; + int exponent; +}; + +struct GfxHeroLightTree { + float mins[3]; + float maxs[3]; +}; + +struct GfxWorld { + const char *name; + const char *baseName; + int planeCount; + int nodeCount; + int surfaceCount; + GfxWorldStreamInfo streamInfo; + int skySurfCount; + int *skyStartSurfs; + GfxImage *skyImage; + char skySamplerState; + const char *skyBoxModel; + SunLightParseParams sunParse; + GfxLight *sunLight; + float sunColorFromBsp[3]; + unsigned int sunPrimaryLightIndex; + unsigned int primaryLightCount; + int cullGroupCount; + unsigned int coronaCount; + GfxLightCorona *coronas; + unsigned int shadowMapVolumeCount; + GfxShadowMapVolume *shadowMapVolumes; + unsigned int shadowMapVolumePlaneCount; + GfxVolumePlane *shadowMapVolumePlanes; + unsigned int exposureVolumeCount; + GfxExposureVolume *exposureVolumes; + unsigned int exposureVolumePlaneCount; + GfxVolumePlane *exposureVolumePlanes; + GfxSkyDynamicIntensity skyDynIntensity; + GfxWorldDpvsPlanes dpvsPlanes; + int cellBitsCount; + GfxCell *cells; + GfxWorldDraw draw; + GfxLightGrid lightGrid; + int modelCount; + GfxBrushModel *models; + float mins[3]; + float maxs[3]; + unsigned int checksum; + int materialMemoryCount; + MaterialMemory *materialMemory; + sunflare_t sun; + float outdoorLookupMatrix[4][4]; + GfxImage *outdoorImage; + unsigned int *cellCasterBits; + GfxSceneDynModel4 *sceneDynModel; + GfxSceneDynBrush *sceneDynBrush; + unsigned int *primaryLightEntityShadowVis; + unsigned int *primaryLightDynEntShadowVis[2]; + char *nonSunPrimaryLightForModelDynEnt; + GfxShadowGeometry *shadowGeom; + GfxLightRegion *lightRegion; + GfxWorldDpvsStatic dpvs; + GfxWorldDpvsDynamic dpvsDyn; + unsigned int worldLodChainCount; + GfxWorldLodChain *worldLodChains; + unsigned int worldLodInfoCount; + GfxWorldLodInfo *worldLodInfos; + unsigned int worldLodSurfaceCount; + unsigned int *worldLodSurfaces; + float waterDirection; + GfxWaterBuffer waterBuffers[2]; + Material *waterMaterial; + Material *coronaMaterial; + Material *ropeMaterial; + unsigned int numOccluders; + Occluder *occluders; + unsigned int numOutdoorBounds; + GfxOutdoorBounds *outdoorBounds; + unsigned int heroLightCount; + unsigned int heroLightTreeCount; + GfxHeroLight *heroLights; + GfxHeroLightTree *heroLightTree; +}; + +enum SamplerStateBits_e { + SAMPLER_FILTER_SHIFT = 0x0, + SAMPLER_FILTER_NEAREST = 0x1, + SAMPLER_FILTER_LINEAR = 0x2, + SAMPLER_FILTER_ANISO2X = 0x3, + SAMPLER_FILTER_ANISO4X = 0x4, + SAMPLER_FILTER_MASK = 0x7, + SAMPLER_MIPMAP_SHIFT = 0x3, + SAMPLER_MIPMAP_DISABLED = 0x0, + SAMPLER_MIPMAP_NEAREST = 0x8, + SAMPLER_MIPMAP_LINEAR = 0x10, + SAMPLER_MIPMAP_COUNT = 0x3, + SAMPLER_MIPMAP_MASK = 0x18, + SAMPLER_CLAMP_U_SHIFT = 0x5, + SAMPLER_CLAMP_V_SHIFT = 0x6, + SAMPLER_CLAMP_W_SHIFT = 0x7, + SAMPLER_CLAMP_U = 0x20, + SAMPLER_CLAMP_V = 0x40, + SAMPLER_CLAMP_W = 0x80, + SAMPLER_CLAMP_MASK = 0xE0, + SAMPLER_ANISO_SHIFT = 0x8, + SAMPLER_ANISO_1X = 0x0, + SAMPLER_ANISO_2X = 0x100, + SAMPLER_ANISO_4X = 0x200, + SAMPLER_ANISO_6X = 0x300, + SAMPLER_ANISO_8X = 0x400, + SAMPLER_ANISO_10X = 0x500, + SAMPLER_ANISO_12X = 0x600, + SAMPLER_ANISO_16X = 0x700, + SAMPLER_ANISO_MASK = 0x700, + SAMPLER_CONVOLUTION = 0x20000, + SAMPLER_GAMMA = 0x40000, + SAMPLER_UNNORMALIZED_UV = 0x80000, + SAMPLER_DIRECT_FILTER_UNNORMALIZED = 0x80000, +}; + +struct GfxLightImage { + GfxImage *image; + char samplerState; +}; + +struct GfxLightDef { + const char *name; + GfxLightImage attenuation; + int lmapLookupStart; +}; + +struct Glyph { + uint16_t letter; + char x0; + char y0; + char dx; + char pixelWidth; + char pixelHeight; + float s0; + float t0; + float s1; + float t1; +}; + +struct Font_s { + const char *fontName; + int pixelHeight; + int glyphCount; + Material *material; + Material *glowMaterial; + Glyph *glyphs; +}; + +struct MenuList { + const char *name; + int menuCount; + menuDef_t **menus; +}; + +struct rectDef_s { + float x; + float y; + float w; + float h; + int horzAlign; + int vertAlign; +}; + +struct windowDef_t { + const char *name; + rectDef_s rect; + rectDef_s rectClient; + const char *group; + char style; + char border; + char modal; + char frameSides; + float frameTexSize; + float frameSize; + int ownerDraw; + int ownerDrawFlags; + float borderSize; + int staticFlags; + int dynamicFlags[1]; + int nextTime; + float foreColor[4]; + float backColor[4]; + float borderColor[4]; + float outlineColor[4]; + float rotation; + Material *background; +}; + +struct ScriptCondition { + bool fireOnTrue; + int constructID; + int blockID; + ScriptCondition *next; +}; + +enum expDataType { + VAL_INT = 0x0, + VAL_FLOAT = 0x1, + VAL_STRING = 0x2, +}; + +union operandInternalDataUnion { + int intVal; + float floatVal; + const char *string; +}; + +struct Operand { + expDataType dataType; + operandInternalDataUnion internals; +}; + +enum expressionRpnEnum { + RPN_CONSTANT = 0x0, + RPN_CMD_IDX = 0x1, + RPN_CMD = 0x2, + RPN_END = 0x3, +}; + +enum expressionOperatorType_e { + OP_NOOP = 0x0, + OP_RIGHTPAREN = 0x1, + OP_MUL = 0x2, + OP_DIV = 0x3, + OP_MOD = 0x4, + OP_PLUS = 0x5, + OP_MINUS = 0x6, + OP_MINUS_2 = 0x7, + OP_NEG = 0x8, + OP_SMALLER = 0x9, + OP_SMALLEREQ = 0xA, + OP_GREATER = 0xB, + OP_GREATEREQ = 0xC, + OP_EQ = 0xD, + OP_NOTEQ = 0xE, + OP_LOGAND = 0xF, + OP_LOGOR = 0x10, + OP_LEFTPAREN = 0x11, + OP_COMMA = 0x12, + OP_BITAND = 0x13, + OP_BITOR = 0x14, + OP_BITNEG = 0x15, + OP_SHIFTLEFT = 0x16, + OP_SHIFTRIGHT = 0x17, + + OP_COUNT +}; + +union expressionRpnDataUnion { + Operand constant; + void *cmd; + int cmdIdx; +}; + +struct expressionRpn { + int type; + expressionRpnDataUnion data; +}; + +struct ExpressionStatement { + char *filename; + int line; + int numRpn; + expressionRpn *rpn; +}; + +struct GenericEventScript { + ScriptCondition *prerequisites; + ExpressionStatement condition; + int type; + bool fireOnTrue; + const char *action; + int blockID; + int constructID; + GenericEventScript *next; +}; + +struct GenericEventHandler { + const char *name; + GenericEventScript *eventScript; + GenericEventHandler *next; +}; + +struct ItemKeyHandler { + int key; + GenericEventScript *keyScript; + ItemKeyHandler *next; +}; + +struct textExp_s { + ExpressionStatement textExp; +}; + +struct enumDvarDef_s { + const char *enumDvarName; +}; + +struct editFieldDef_s { + int cursorPos[1]; + float minVal; + float maxVal; + float defVal; + float range; + int maxChars; + int maxCharsGotoNext; + int maxPaintChars; + int paintOffset; +}; + +struct columnInfo_s { + int elementStyle; + int maxChars; + rectDef_s rect; +}; + +struct MenuCell { + int type; + int maxChars; + char *stringValue; +}; + +struct MenuRow { + MenuCell *cells; + char *eventName; + char *onFocusEventName; + bool disableArg; + int status; + int name; +}; + +struct listBoxDef_s { + int mousePos; + int cursorPos[1]; + int startPos[1]; + int endPos[1]; + int drawPadding; + float elementWidth; + float elementHeight; + int numColumns; + float special; + columnInfo_s columnInfo[16]; + int notselectable; + int noScrollBars; + int usePaging; + float selectBorder[4]; + float disableColor[4]; + float focusColor[4]; + float elementHighlightColor[4]; + float elementBackgroundColor[4]; + Material *selectIcon; + Material *backgroundItemListbox; + Material *highlightTexture; + int noBlinkingHighlight; + MenuRow *rows; + int maxRows; + int rowCount; +}; + +struct multiDef_s { + const char *dvarList[32]; + const char *dvarStr[32]; + float dvarValue[32]; + int count; + int actionOnEnterPressOnly; + int strDef; +}; + +union focusDefData_t { + listBoxDef_s *listBox; + multiDef_s *multi; + editFieldDef_s *editField; + enumDvarDef_s *enumDvar; + void *data; +}; + +struct focusItemDef_s { + const char *mouseEnterText; + const char *mouseExitText; + const char *mouseEnter; + const char *mouseExit; + ItemKeyHandler *onKey; + focusDefData_t focusTypeData; +}; + +struct gameMsgDef_s { + int gameMsgWindowIndex; + int gameMsgWindowMode; +}; + +union textDefData_t { + focusItemDef_s *focusItemDef; + gameMsgDef_s *gameMsgDef; + void *data; +}; + +struct textDef_s { + rectDef_s textRect[1]; + int alignment; + int fontEnum; + int itemFlags; + int textAlignMode; + float textalignx; + float textaligny; + float textscale; + int textStyle; + const char *text; + textExp_s *textExpData; + textDefData_t textTypeData; +}; + +struct imageDef_s { + ExpressionStatement materialExp; +}; + +struct ownerDrawDef_s { + ExpressionStatement dataExp; +}; + +union itemDefData_t { + textDef_s *textDef; + imageDef_s *imageDef; + focusItemDef_s *blankButtonDef; + ownerDrawDef_s *ownerDrawDef; + void *data; +}; + +struct rectData_s { + ExpressionStatement rectXExp; + ExpressionStatement rectYExp; + ExpressionStatement rectWExp; + ExpressionStatement rectHExp; +}; + +struct animParamsDef_t { + const char *name; + rectDef_s rectClient; + float borderSize; + float foreColor[4]; + float backColor[4]; + float borderColor[4]; + float outlineColor[4]; + float textScale; + float rotation; + GenericEventHandler *onEvent; +}; + +struct UIAnimInfo { + int animStateCount; + animParamsDef_t **animStates; + animParamsDef_t currentAnimState; + animParamsDef_t nextAnimState; + int animating; + int animStartTime; + int animDuration; +}; + +enum ItemDefType { + ITEM_TYPE_DEFAULT = 0x0, + ITEM_TYPE_TEXT = 0x1, + ITEM_TYPE_IMAGE = 0x2, + ITEM_TYPE_BUTTON = 0x3, + ITEM_TYPE_LISTBOX = 0x4, + ITEM_TYPE_EDITFIELD = 0x5, + ITEM_TYPE_OWNERDRAW = 0x6, + ITEM_TYPE_NUMERICFIELD = 0x7, + ITEM_TYPE_SLIDER = 0x8, + ITEM_TYPE_YESNO = 0x9, + ITEM_TYPE_MULTI = 0xA, + ITEM_TYPE_DVARENUM = 0xB, + ITEM_TYPE_BIND = 0xC, + ITEM_TYPE_VALIDFILEFIELD = 0xD, + ITEM_TYPE_UPREDITFIELD = 0xE, + ITEM_TYPE_GAME_MESSAGE_WINDOW = 0xF, + ITEM_TYPE_BIND2 = 0x10, + ITEM_TYPE_HIGHLIGHT = 0x11, + ITEM_TYPE_OWNERDRAW_TEXT = 0x12, + ITEM_TYPE_OD_BUTTON = 0x13, + ITEM_TYPE_OD_TEXT_BUTTON = 0x14, + ITEM_TYPE_BUTTON_NO_TEXT = 0x15, + ITEM_TYPE_ALPHANUMERICFIELD = 0x16, + ITEM_TYPE_RADIOBUTTON = 0x19, + ITEM_TYPE_MODEL = 0x1A, + ITEM_TYPE_CHECKBOX = 0x1B, + ITEM_TYPE_COMBO = 0x1C, + ITEM_TYPE_DECIMALFIELD = 0x1E, + ITEM_TYPE_CONFEDITFIELD = 0x1F, + ITEM_TYPE_MENUMODEL = 0x27 +}; + +struct type_align(8) itemDef_s { + windowDef_t window; + int type; + int dataType; + int imageTrack; + const char *dvar; + const char *dvarTest; + const char *enableDvar; + int dvarFlags; + itemDefData_t typeData; + menuDef_t *parent; + rectData_s *rectExpData; + ExpressionStatement visibleExp; + gcc_align(8) uint64_t showBits; + gcc_align(8) uint64_t hideBits; + ExpressionStatement forecolorAExp; + int ui3dWindowId; + GenericEventHandler *onEvent; + UIAnimInfo *animInfo; +}; + +struct type_align(8) menuDef_t { + windowDef_t window; + const char *font; + int fullScreen; + int ui3dWindowId; + int itemCount; + int fontIndex; + int cursorItem[1]; + int fadeCycle; + int priority; + float fadeClamp; + float fadeAmount; + float fadeInAmount; + float blurRadius; + int openSlideSpeed; + int closeSlideSpeed; + int openSlideDirection; + int closeSlideDirection; + rectDef_s initialRectInfo; + int openFadingTime; + int closeFadingTime; + int fadeTimeCounter; + int slideTimeCounter; + GenericEventHandler *onEvent; + ItemKeyHandler *onKey; + ExpressionStatement visibleExp; + gcc_align(8) uint64_t showBits; + gcc_align(8) uint64_t hideBits; + const char *allowedBinding; + const char *soundName; + int imageTrack; + int control; + float focusColor[4]; + float disableColor[4]; + ExpressionStatement rectXExp; + ExpressionStatement rectYExp; + itemDef_s **items; +}; + +struct LocalizeEntry { + const char *value; + const char *name; +}; + +enum weaponIconRatioType_t { + WEAPON_ICON_RATIO_1TO1 = 0x0, + WEAPON_ICON_RATIO_2TO1 = 0x1, + WEAPON_ICON_RATIO_4TO1 = 0x2, + WEAPON_ICON_RATIO_COUNT = 0x3, +}; + +enum weapType_t { + WEAPTYPE_BULLET = 0x0, + WEAPTYPE_GRENADE = 0x1, + WEAPTYPE_PROJECTILE = 0x2, + WEAPTYPE_BINOCULARS = 0x3, + WEAPTYPE_GAS = 0x4, + WEAPTYPE_BOMB = 0x5, + WEAPTYPE_MINE = 0x6, + WEAPTYPE_MELEE = 0x7, + WEAPTYPE_NUM = 0x8, +}; + +enum weapClass_t { + WEAPCLASS_RIFLE = 0x0, + WEAPCLASS_MG = 0x1, + WEAPCLASS_SMG = 0x2, + WEAPCLASS_SPREAD = 0x3, + WEAPCLASS_PISTOL = 0x4, + WEAPCLASS_GRENADE = 0x5, + WEAPCLASS_ROCKETLAUNCHER = 0x6, + WEAPCLASS_TURRET = 0x7, + WEAPCLASS_NON_PLAYER = 0x8, + WEAPCLASS_GAS = 0x9, + WEAPCLASS_ITEM = 0xA, + WEAPCLASS_MELEE = 0xB, + WEAPCLASS_KILLSTREAK_ALT_STORED_WEAPON = 0xC, + WEAPCLASS_NUM = 0xD, +}; + +enum PenetrateType { + PENETRATE_TYPE_NONE = 0x0, + PENETRATE_TYPE_SMALL = 0x1, + PENETRATE_TYPE_MEDIUM = 0x2, + PENETRATE_TYPE_LARGE = 0x3, + PENETRATE_TYPE_COUNT = 0x4, +}; + +enum ImpactType { + IMPACT_TYPE_NONE = 0x0, + IMPACT_TYPE_BULLET_SMALL = 0x1, + IMPACT_TYPE_BULLET_LARGE = 0x2, + IMPACT_TYPE_BULLET_AP = 0x3, + IMPACT_TYPE_BULLET_XTREME = 0x4, + IMPACT_TYPE_SHOTGUN = 0x5, + IMPACT_TYPE_GRENADE_BOUNCE = 0x6, + IMPACT_TYPE_GRENADE_EXPLODE = 0x7, + IMPACT_TYPE_RIFLE_GRENADE = 0x8, + IMPACT_TYPE_ROCKET_EXPLODE = 0x9, + IMPACT_TYPE_ROCKET_EXPLODE_XTREME = 0xA, + IMPACT_TYPE_PROJECTILE_DUD = 0xB, + IMPACT_TYPE_MORTAR_SHELL = 0xC, + IMPACT_TYPE_TANK_SHELL = 0xD, + IMPACT_TYPE_BOLT = 0xE, + IMPACT_TYPE_BLADE = 0xF, + IMPACT_TYPE_COUNT = 0x10, +}; + +enum weapInventoryType_t { + WEAPINVENTORY_PRIMARY = 0x0, + WEAPINVENTORY_OFFHAND = 0x1, + WEAPINVENTORY_ITEM = 0x2, + WEAPINVENTORY_ALTMODE = 0x3, + WEAPINVENTORY_MELEE = 0x4, + WEAPINVENTORYCOUNT = 0x5, +}; + +enum weapFireType_t { + WEAPON_FIRETYPE_FULLAUTO = 0x0, + WEAPON_FIRETYPE_SINGLESHOT = 0x1, + WEAPON_FIRETYPE_BURSTFIRE2 = 0x2, + WEAPON_FIRETYPE_BURSTFIRE3 = 0x3, + WEAPON_FIRETYPE_BURSTFIRE4 = 0x4, + WEAPON_FIRETYPE_STACKED = 0x5, + WEAPON_FIRETYPE_MINIGUN = 0x6, + WEAPON_FIRETYPECOUNT = 0x7, +}; + +enum weapClipType_t { + WEAPON_CLIPTYPE_BOTTOM = 0x0, + WEAPON_CLIPTYPE_TOP = 0x1, + WEAPON_CLIPTYPE_LEFT = 0x2, + WEAPON_CLIPTYPE_DP28 = 0x3, + WEAPON_CLIPTYPE_PTRS = 0x4, + WEAPON_CLIPTYPE_LMG = 0x5, + WEAPON_CLIPTYPECOUNT = 0x6, +}; + +enum OffhandClass { + OFFHAND_CLASS_NONE = 0x0, + OFFHAND_CLASS_FRAG_GRENADE = 0x1, + OFFHAND_CLASS_SMOKE_GRENADE = 0x2, + OFFHAND_CLASS_FLASH_GRENADE = 0x3, + OFFHAND_CLASS_GEAR = 0x4, + OFFHAND_CLASS_COUNT = 0x5, +}; + +enum OffhandSlot { + OFFHAND_SLOT_NONE = 0x0, + OFFHAND_SLOT_LETHAL_GRENADE = 0x1, + OFFHAND_SLOT_TACTICAL_GRENADE = 0x2, + OFFHAND_SLOT_EQUIPMENT = 0x3, + OFFHAND_SLOT_SPECIFIC_USE = 0x4, + OFFHAND_SLOT_COUNT = 0x5, +}; + +enum weapStance_t { + WEAPSTANCE_STAND = 0x0, + WEAPSTANCE_DUCK = 0x1, + WEAPSTANCE_PRONE = 0x2, + WEAPSTANCE_NUM = 0x3, +}; + +enum activeReticleType_t { + VEH_ACTIVE_RETICLE_NONE = 0x0, + VEH_ACTIVE_RETICLE_PIP_ON_A_STICK = 0x1, + VEH_ACTIVE_RETICLE_BOUNCING_DIAMOND = 0x2, + VEH_ACTIVE_RETICLE_COUNT = 0x3, +}; + +enum ammoCounterClipType_t { + AMMO_COUNTER_CLIP_NONE = 0x0, + AMMO_COUNTER_CLIP_MAGAZINE = 0x1, + AMMO_COUNTER_CLIP_SHORTMAGAZINE = 0x2, + AMMO_COUNTER_CLIP_SHOTGUN = 0x3, + AMMO_COUNTER_CLIP_ROCKET = 0x4, + AMMO_COUNTER_CLIP_BELTFED = 0x5, + AMMO_COUNTER_CLIP_ALTWEAPON = 0x6, + AMMO_COUNTER_CLIP_COUNT = 0x7, +}; + +enum weapOverlayReticle_t { + WEAPOVERLAYRETICLE_NONE = 0x0, + WEAPOVERLAYRETICLE_CROSSHAIR = 0x1, + WEAPOVERLAYRETICLE_NUM = 0x2, +}; + +enum WeapOverlayInteface_t { + WEAPOVERLAYINTERFACE_NONE = 0x0, + WEAPOVERLAYINTERFACE_JAVELIN = 0x1, + WEAPOVERLAYINTERFACE_TURRETSCOPE = 0x2, + WEAPOVERLAYINTERFACECOUNT = 0x3, +}; + +enum weapProjExposion_t { + WEAPPROJEXP_GRENADE = 0x0, + WEAPPROJEXP_ROCKET = 0x1, + WEAPPROJEXP_FLASHBANG = 0x2, + WEAPPROJEXP_NONE = 0x3, + WEAPPROJEXP_DUD = 0x4, + WEAPPROJEXP_SMOKE = 0x5, + WEAPPROJEXP_HEAVY = 0x6, + WEAPPROJEXP_FIRE = 0x7, + WEAPPROJEXP_NAPALMBLOB = 0x8, + WEAPPROJEXP_BOLT = 0x9, + WEAPPROJEXP_NUM = 0xA, +}; + +enum WeapStickinessType { + WEAPSTICKINESS_NONE = 0x0, + WEAPSTICKINESS_ALL = 0x1, + WEAPSTICKINESS_ALL_NO_SENTIENTS = 0x2, + WEAPSTICKINESS_GROUND = 0x3, + WEAPSTICKINESS_GROUND_WITH_YAW = 0x4, + WEAPSTICKINESS_FLESH = 0x5, + WEAPSTICKINESS_COUNT = 0x6, +}; + +enum WeapRotateType { + WEAPROTATE_GRENADE_ROTATE = 0x0, + WEAPROTATE_BLADE_ROTATE = 0x1, + WEAPROTATE_CYLINDER_ROTATE = 0x2, + WEAPROTATE_COUNT = 0x3, +}; + +enum guidedMissileType_t { + MISSILE_GUIDANCE_NONE = 0x0, + MISSILE_GUIDANCE_SIDEWINDER = 0x1, + MISSILE_GUIDANCE_HELLFIRE = 0x2, + MISSILE_GUIDANCE_JAVELIN = 0x3, + MISSILE_GUIDANCE_BALLISTIC = 0x4, + MISSILE_GUIDANCE_WIREGUIDED = 0x5, + MISSILE_GUIDANCE_TVGUIDED = 0x6, + MISSILE_GUIDANCE_COUNT = 0x7, +}; + +enum weapAnimFiles_t { + WEAP_ANIM_ROOT = 0x0, + WEAP_ANIM_IDLE = 0x1, + WEAP_ANIM_EMPTY_IDLE = 0x2, + WEAP_ANIM_FIRE = 0x3, + WEAP_ANIM_HOLD_FIRE = 0x4, + WEAP_ANIM_LASTSHOT = 0x5, + WEAP_ANIM_RECHAMBER = 0x6, + WEAP_ANIM_MELEE = 0x7, + WEAP_ANIM_MELEE_CHARGE = 0x8, + WEAP_ANIM_RELOAD = 0x9, + WEAP_ANIM_RELOAD_RIGHT = 0xA, + WEAP_ANIM_RELOAD_EMPTY = 0xB, + WEAP_ANIM_RELOAD_START = 0xC, + WEAP_ANIM_RELOAD_END = 0xD, + WEAP_ANIM_RELOAD_QUICK = 0xE, + WEAP_ANIM_RELOAD_QUICK_EMPTY = 0xF, + WEAP_ANIM_RAISE = 0x10, + WEAP_ANIM_FIRST_RAISE = 0x11, + WEAP_ANIM_DROP = 0x12, + WEAP_ANIM_ALT_RAISE = 0x13, + WEAP_ANIM_ALT_DROP = 0x14, + WEAP_ANIM_QUICK_RAISE = 0x15, + WEAP_ANIM_QUICK_DROP = 0x16, + WEAP_ANIM_EMPTY_RAISE = 0x17, + WEAP_ANIM_EMPTY_DROP = 0x18, + WEAP_ANIM_SPRINT_IN = 0x19, + WEAP_ANIM_SPRINT_LOOP = 0x1A, + WEAP_ANIM_SPRINT_OUT = 0x1B, + WEAP_ANIM_SPRINT_EMPTY_IN = 0x1C, + WEAP_ANIM_SPRINT_EMPTY_LOOP = 0x1D, + WEAP_ANIM_SPRINT_EMPTY_OUT = 0x1E, + WEAP_ANIM_LOWREADY_IN = 0x1F, + WEAP_ANIM_LOWREADY_LOOP = 0x20, + WEAP_ANIM_LOWREADY_OUT = 0x21, + WEAP_ANIM_CONT_FIRE_IN = 0x22, + WEAP_ANIM_CONT_FIRE_LOOP = 0x23, + WEAP_ANIM_CONT_FIRE_OUT = 0x24, + WEAP_ANIM_DEPLOY = 0x25, + WEAP_ANIM_BREAKDOWN = 0x26, + WEAP_ANIM_DETONATE = 0x27, + WEAP_ANIM_NIGHTVISION_WEAR = 0x28, + WEAP_ANIM_NIGHTVISION_REMOVE = 0x29, + WEAP_ANIM_ADS_FIRE = 0x2A, + WEAP_ANIM_ADS_LASTSHOT = 0x2B, + WEAP_ANIM_ADS_RECHAMBER = 0x2C, + WEAP_ANIM_DTP_IN = 0x2D, + WEAP_ANIM_DTP_LOOP = 0x2E, + WEAP_ANIM_DTP_OUT = 0x2F, + WEAP_ANIM_DTP_EMPTY_IN = 0x30, + WEAP_ANIM_DTP_EMPTY_LOOP = 0x31, + WEAP_ANIM_DTP_EMPTY_OUT = 0x32, + WEAP_ANIM_SLIDE_IN = 0x33, + WEAP_ANIM_MANTLE = 0x34, + WEAP_ANIM_CAMERA_SPRINT_LOOP = 0x35, + WEAP_ANIM_CAMERA_DTP_IN = 0x36, + WEAP_ANIM_CAMERA_DTP_LOOP = 0x37, + WEAP_ANIM_CAMERA_DTP_OUT = 0x38, + WEAP_ANIM_CAMERA_MANTLE = 0x39, + WEAP_ANIM_FIRE_LEFT = 0x3A, + WEAP_ANIM_LASTSHOT_LEFT = 0x3B, + WEAP_ANIM_IDLE_LEFT = 0x3C, + WEAP_ANIM_EMPTY_IDLE_LEFT = 0x3D, + WEAP_ANIM_RELOAD_EMPTY_LEFT = 0x3E, + WEAP_ANIM_RELOAD_LEFT = 0x3F, + WEAP_ANIM_ADS_UP = 0x40, + WEAP_ANIM_ADS_DOWN = 0x41, + + NUM_WEAP_ANIMS +}; + +enum materialSurfType_t { + SURF_TYPE_DEFAULT, + SURF_TYPE_BARK, + SURF_TYPE_BRICK, + SURF_TYPE_CARPET, + SURF_TYPE_CLOTH, + SURF_TYPE_CONCRETE, + SURF_TYPE_DIRT, + SURF_TYPE_FLESH, + SURF_TYPE_FOLIAGE, + SURF_TYPE_GLASS, + SURF_TYPE_GRASS, + SURF_TYPE_GRAVEL, + SURF_TYPE_ICE, + SURF_TYPE_METAL, + SURF_TYPE_MUD, + SURF_TYPE_PAPER, + SURF_TYPE_PLASTER, + SURF_TYPE_ROCK, + SURF_TYPE_SAND, + SURF_TYPE_SNOW, + SURF_TYPE_WATER, + SURF_TYPE_WOOD, + SURF_TYPE_ASPHALT, + SURF_TYPE_CERAMIC, + SURF_TYPE_PLASTIC, + SURF_TYPE_RUBBER, + SURF_TYPE_CUSHION, + SURF_TYPE_FRUIT, + SURF_TYPE_PAINTED_METAL, + SURF_TYPE_PLAYER, + SURF_TYPE_TALL_GRASS, + + SURF_TYPE_NUM +}; + +enum hitLocation_t { + HITLOC_NONE = 0x0, + HITLOC_HELMET = 0x1, + HITLOC_HEAD = 0x2, + HITLOC_NECK = 0x3, + HITLOC_TORSO_UPR = 0x4, + HITLOC_TORSO_LWR = 0x5, + HITLOC_R_ARM_UPR = 0x6, + HITLOC_L_ARM_UPR = 0x7, + HITLOC_R_ARM_LWR = 0x8, + HITLOC_L_ARM_LWR = 0x9, + HITLOC_R_HAND = 0xA, + HITLOC_L_HAND = 0xB, + HITLOC_R_LEG_UPR = 0xC, + HITLOC_L_LEG_UPR = 0xD, + HITLOC_R_LEG_LWR = 0xE, + HITLOC_L_LEG_LWR = 0xF, + HITLOC_R_FOOT = 0x10, + HITLOC_L_FOOT = 0x11, + HITLOC_GUN = 0x12, + + HITLOC_NUM +}; + +struct flameTable { + float flameVar_streamChunkGravityStart; + float flameVar_streamChunkGravityEnd; + float flameVar_streamChunkMaxSize; + float flameVar_streamChunkStartSize; + float flameVar_streamChunkEndSize; + float flameVar_streamChunkStartSizeRand; + float flameVar_streamChunkEndSizeRand; + float flameVar_streamChunkDistScalar; + float flameVar_streamChunkDistSwayScale; + float flameVar_streamChunkDistSwayVelMax; + float flameVar_streamChunkSpeed; + float flameVar_streamChunkDecel; + float flameVar_streamChunkVelocityAddScale; + float flameVar_streamChunkDuration; + float flameVar_streamChunkDurationScaleMaxVel; + float flameVar_streamChunkDurationVelScalar; + float flameVar_streamChunkSizeSpeedScale; + float flameVar_streamChunkSizeAgeScale; + float flameVar_streamChunkSpawnFireIntervalStart; + float flameVar_streamChunkSpawnFireIntervalEnd; + float flameVar_streamChunkSpawnFireMinLifeFrac; + float flameVar_streamChunkSpawnFireMaxLifeFrac; + float flameVar_streamChunkFireMinLifeFrac; + float flameVar_streamChunkFireMinLifeFracStart; + float flameVar_streamChunkFireMinLifeFracEnd; + float flameVar_streamChunkDripsMinLifeFrac; + float flameVar_streamChunkDripsMinLifeFracStart; + float flameVar_streamChunkDripsMinLifeFracEnd; + float flameVar_streamChunkRotationRange; + float flameVar_streamSizeRandSinWave; + float flameVar_streamSizeRandCosWave; + float flameVar_streamDripsChunkInterval; + float flameVar_streamDripsChunkMinFrac; + float flameVar_streamDripsChunkRandFrac; + float flameVar_streamSmokeChunkInterval; + float flameVar_streamSmokeChunkMinFrac; + float flameVar_streamSmokeChunkRandFrac; + float flameVar_streamChunkCullDistSizeFrac; + float flameVar_streamChunkCullMinLife; + float flameVar_streamChunkCullMaxLife; + float flameVar_streamFuelSizeStart; + float flameVar_streamFuelSizeEnd; + float flameVar_streamFuelLength; + float flameVar_streamFuelNumSegments; + float flameVar_streamFuelAnimLoopTime; + float flameVar_streamFlameSizeStart; + float flameVar_streamFlameSizeEnd; + float flameVar_streamFlameLength; + float flameVar_streamFlameNumSegments; + float flameVar_streamFlameAnimLoopTime; + float flameVar_streamPrimaryLightRadius; + float flameVar_streamPrimaryLightRadiusFlutter; + float flameVar_streamPrimaryLightR; + float flameVar_streamPrimaryLightG; + float flameVar_streamPrimaryLightB; + float flameVar_streamPrimaryLightFlutterR; + float flameVar_streamPrimaryLightFlutterG; + float flameVar_streamPrimaryLightFlutterB; + float flameVar_fireLife; + float flameVar_fireLifeRand; + float flameVar_fireSpeedScale; + float flameVar_fireSpeedScaleRand; + float flameVar_fireVelocityAddZ; + float flameVar_fireVelocityAddZRand; + float flameVar_fireVelocityAddSideways; + float flameVar_fireGravity; + float flameVar_fireGravityEnd; + float flameVar_fireMaxRotVel; + float flameVar_fireFriction; + float flameVar_fireEndSizeAdd; + float flameVar_fireStartSizeScale; + float flameVar_fireEndSizeScale; + float flameVar_dripsLife; + float flameVar_dripsLifeRand; + float flameVar_dripsSpeedScale; + float flameVar_dripsSpeedScaleRand; + float flameVar_dripsVelocityAddZ; + float flameVar_dripsVelocityAddZRand; + float flameVar_dripsVelocityAddSideways; + float flameVar_dripsGravity; + float flameVar_dripsGravityEnd; + float flameVar_dripsMaxRotVel; + float flameVar_dripsFriction; + float flameVar_dripsEndSizeAdd; + float flameVar_dripsStartSizeScale; + float flameVar_dripsEndSizeScale; + float flameVar_smokeLife; + float flameVar_smokeLifeRand; + float flameVar_smokeSpeedScale; + float flameVar_smokeVelocityAddZ; + float flameVar_smokeGravity; + float flameVar_smokeGravityEnd; + float flameVar_smokeMaxRotation; + float flameVar_smokeMaxRotVel; + float flameVar_smokeFriction; + float flameVar_smokeEndSizeAdd; + float flameVar_smokeStartSizeAdd; + float flameVar_smokeOriginSizeOfsZScale; + float flameVar_smokeOriginOfsZ; + float flameVar_smokeFadein; + float flameVar_smokeFadeout; + float flameVar_smokeMaxAlpha; + float flameVar_smokeBrightness; + float flameVar_smokeOriginOffset; + float flameVar_collisionSpeedScale; + float flameVar_collisionVolumeScale; + const char *name; + Material *fire; + Material *smoke; + Material *heat; + Material *drips; + Material *streamFuel; + Material *streamFuel2; + Material *streamFlame; + Material *streamFlame2; + const char *flameOffLoopSound; + const char *flameIgniteSound; + const char *flameOnLoopSound; + const char *flameCooldownSound; +}; + +struct WeaponDef { + const char *szOverlayName; + XModel **gunXModel; + XModel *handXModel; + const char *szModeName; + uint16_t *notetrackSoundMapKeys; + uint16_t *notetrackSoundMapValues; + int playerAnimType; + weapType_t weapType; + weapClass_t weapClass; + PenetrateType penetrateType; + ImpactType impactType; + weapInventoryType_t inventoryType; + weapFireType_t fireType; + weapClipType_t clipType; + int itemIndex; + const char *parentWeaponName; + int iJamFireTime; + int tracerFrequency; + float tracerWidth; + float tracerLength; + int overheatWeapon; + float overheatRate; + float cooldownRate; + float overheatEndVal; + bool coolWhileFiring; + bool fuelTankWeapon; + int iTankLifeTime; + OffhandClass offhandClass; + OffhandSlot offhandSlot; + weapStance_t stance; + FxEffectDef *viewFlashEffect; + FxEffectDef *worldFlashEffect; + const char *pickupSound; + const char *pickupSoundPlayer; + const char *ammoPickupSound; + const char *ammoPickupSoundPlayer; + const char *projectileSound; + const char *pullbackSound; + const char *pullbackSoundPlayer; + const char *fireSound; + const char *fireSoundPlayer; + const char *fireLoopSound; + const char *fireLoopSoundPlayer; + const char *fireLoopEndSound; + const char *fireLoopEndSoundPlayer; + const char *fireStopSound; + const char *fireStopSoundPlayer; + const char *fireLastSound; + const char *fireLastSoundPlayer; + const char *emptyFireSound; + const char *emptyFireSoundPlayer; + const char *crackSound; + const char *whizbySound; + const char *meleeSwipeSound; + const char *meleeSwipeSoundPlayer; + const char *meleeHitSound; + const char *meleeMissSound; + const char *rechamberSound; + const char *rechamberSoundPlayer; + const char *reloadSound; + const char *reloadSoundPlayer; + const char *reloadEmptySound; + const char *reloadEmptySoundPlayer; + const char *reloadStartSound; + const char *reloadStartSoundPlayer; + const char *reloadEndSound; + const char *reloadEndSoundPlayer; + const char *rotateLoopSound; + const char *rotateLoopSoundPlayer; + const char *deploySound; + const char *deploySoundPlayer; + const char *finishDeploySound; + const char *finishDeploySoundPlayer; + const char *breakdownSound; + const char *breakdownSoundPlayer; + const char *finishBreakdownSound; + const char *finishBreakdownSoundPlayer; + const char *detonateSound; + const char *detonateSoundPlayer; + const char *nightVisionWearSound; + const char *nightVisionWearSoundPlayer; + const char *nightVisionRemoveSound; + const char *nightVisionRemoveSoundPlayer; + const char *altSwitchSound; + const char *altSwitchSoundPlayer; + const char *raiseSound; + const char *raiseSoundPlayer; + const char *firstRaiseSound; + const char *firstRaiseSoundPlayer; + const char *putawaySound; + const char *putawaySoundPlayer; + const char *overheatSound; + const char *overheatSoundPlayer; + const char *adsZoomSound; + const char **bounceSound; + const char *standMountedWeapdef; + const char *crouchMountedWeapdef; + const char *proneMountedWeapdef; + int standMountedIndex; + int crouchMountedIndex; + int proneMountedIndex; + FxEffectDef *viewShellEjectEffect; + FxEffectDef *worldShellEjectEffect; + FxEffectDef *viewLastShotEjectEffect; + FxEffectDef *worldLastShotEjectEffect; + Material *reticleCenter; + Material *reticleSide; + int iReticleCenterSize; + int iReticleSideSize; + int iReticleMinOfs; + activeReticleType_t activeReticleType; + float vStandMove[3]; + float vStandRot[3]; + float vDuckedOfs[3]; + float vDuckedMove[3]; + float vDuckedSprintOfs[3]; + float vDuckedSprintRot[3]; + float vDuckedSprintBob[2]; + float fDuckedSprintCycleScale; + float vSprintOfs[3]; + float vSprintRot[3]; + float vSprintBob[2]; + float fSprintCycleScale; + float vLowReadyOfs[3]; + float vLowReadyRot[3]; + float vDtpOfs[3]; + float vDtpRot[3]; + float vDtpBob[2]; + float fDtpCycleScale; + float vMantleOfs[3]; + float vMantleRot[3]; + float vSlideOfs[3]; + float vSlideRot[3]; + float vDuckedRot[3]; + float vProneOfs[3]; + float vProneMove[3]; + float vProneRot[3]; + float vStrafeMove[3]; + float vStrafeRot[3]; + float fPosMoveRate; + float fPosProneMoveRate; + float fStandMoveMinSpeed; + float fDuckedMoveMinSpeed; + float fProneMoveMinSpeed; + float fPosRotRate; + float fPosProneRotRate; + float fStandRotMinSpeed; + float fDuckedRotMinSpeed; + float fProneRotMinSpeed; + XModel **worldModel; + XModel *worldClipModel; + XModel *rocketModel; + XModel *mountedModel; + XModel *additionalMeleeModel; + Material *hudIcon; + weaponIconRatioType_t hudIconRatio; + Material *indicatorIcon; + weaponIconRatioType_t indicatorIconRatio; + Material *ammoCounterIcon; + weaponIconRatioType_t ammoCounterIconRatio; + ammoCounterClipType_t ammoCounterClip; + int iStartAmmo; + int iHeatIndex; + int iMaxAmmo; + int shotCount; + const char *szSharedAmmoCapName; + int iSharedAmmoCapIndex; + int iSharedAmmoCap; + bool unlimitedAmmo; + bool ammoCountClipRelative; + int damage; + float damageDuration; + float damageInterval; + int playerDamage; + int iMeleeDamage; + int iDamageType; + uint16_t explosionTag; + int iFireDelay; + int iMeleeDelay; + int meleeChargeDelay; + int iDetonateDelay; + int iSpinUpTime; + int iSpinDownTime; + float spinRate; + const char *spinLoopSound; + const char *spinLoopSoundPlayer; + const char *startSpinSound; + const char *startSpinSoundPlayer; + const char *stopSpinSound; + const char *stopSpinSoundPlayer; + int iFireTime; + int iLastFireTime; + int iRechamberTime; + int iRechamberBoltTime; + int iHoldFireTime; + int iDetonateTime; + int iMeleeTime; + int meleeChargeTime; + int iReloadTimeRight; + int iReloadTimeLeft; + int reloadShowRocketTime; + int iReloadEmptyTimeLeft; + int iReloadAddTime; + int iReloadEmptyAddTime; + int iReloadQuickAddTime; + int iReloadQuickEmptyAddTime; + int iReloadStartTime; + int iReloadStartAddTime; + int iReloadEndTime; + int iDropTime; + int iRaiseTime; + int iAltDropTime; + int quickDropTime; + int quickRaiseTime; + int iFirstRaiseTime; + int iEmptyRaiseTime; + int iEmptyDropTime; + int sprintInTime; + int sprintLoopTime; + int sprintOutTime; + int lowReadyInTime; + int lowReadyLoopTime; + int lowReadyOutTime; + int contFireInTime; + int contFireLoopTime; + int contFireOutTime; + int dtpInTime; + int dtpLoopTime; + int dtpOutTime; + int slideInTime; + int deployTime; + int breakdownTime; + int nightVisionWearTime; + int nightVisionWearTimeFadeOutEnd; + int nightVisionWearTimePowerUp; + int nightVisionRemoveTime; + int nightVisionRemoveTimePowerDown; + int nightVisionRemoveTimeFadeInStart; + int fuseTime; + int aiFuseTime; + int lockOnRadius; + int lockOnSpeed; + bool requireLockonToFire; + bool noAdsWhenMagEmpty; + bool avoidDropCleanup; + unsigned int stackFire; + float stackFireSpread; + float stackFireAccuracyDecay; + const char *stackSound; + float autoAimRange; + float aimAssistRange; + bool mountableWeapon; + float aimPadding; + float enemyCrosshairRange; + bool crosshairColorChange; + float moveSpeedScale; + float adsMoveSpeedScale; + float sprintDurationScale; + weapOverlayReticle_t overlayReticle; + WeapOverlayInteface_t overlayInterface; + float overlayWidth; + float overlayHeight; + float fAdsBobFactor; + float fAdsViewBobMult; + float fHipSpreadStandMin; + float fHipSpreadDuckedMin; + float fHipSpreadProneMin; + float hipSpreadStandMax; + float hipSpreadDuckedMax; + float hipSpreadProneMax; + float fHipSpreadDecayRate; + float fHipSpreadFireAdd; + float fHipSpreadTurnAdd; + float fHipSpreadMoveAdd; + float fHipSpreadDuckedDecay; + float fHipSpreadProneDecay; + float fHipReticleSidePos; + float fAdsIdleAmount; + float fHipIdleAmount; + float adsIdleSpeed; + float hipIdleSpeed; + float fIdleCrouchFactor; + float fIdleProneFactor; + float fGunMaxPitch; + float fGunMaxYaw; + float swayMaxAngle; + float swayLerpSpeed; + float swayPitchScale; + float swayYawScale; + float swayHorizScale; + float swayVertScale; + float swayShellShockScale; + float adsSwayMaxAngle; + float adsSwayLerpSpeed; + float adsSwayPitchScale; + float adsSwayYawScale; + bool sharedAmmo; + bool bRifleBullet; + bool armorPiercing; + bool bBoltAction; + bool bUseAltTagFlash; + bool bUseAntiLagRewind; + bool bIsCarriedKillstreakWeapon; + bool aimDownSight; + bool bRechamberWhileAds; + bool bReloadWhileAds; + float adsViewErrorMin; + float adsViewErrorMax; + bool bCookOffHold; + bool bClipOnly; + bool bCanUseInVehicle; + bool bNoDropsOrRaises; + bool adsFireOnly; + bool cancelAutoHolsterWhenEmpty; + bool suppressAmmoReserveDisplay; + bool laserSightDuringNightvision; + bool bHideThirdPerson; + bool bHasBayonet; + bool bDualWield; + bool bExplodeOnGround; + bool bThrowBack; + bool bRetrievable; + bool bDieOnRespawn; + bool bNoThirdPersonDropsOrRaises; + bool bContinuousFire; + bool bNoPing; + bool bForceBounce; + bool bUseDroppedModelAsStowed; + bool bNoQuickDropWhenEmpty; + bool bKeepCrosshairWhenADS; + bool bUseOnlyAltWeaoponHideTagsInAltMode; + Material *killIcon; + weaponIconRatioType_t killIconRatio; + bool flipKillIcon; + bool bNoPartialReload; + bool bSegmentedReload; + bool bNoADSAutoReload; + int iReloadAmmoAdd; + int iReloadStartAdd; + const char *szSpawnedGrenadeWeaponName; + const char *szDualWieldWeaponName; + unsigned int dualWieldWeaponIndex; + int iDropAmmoMin; + int iDropAmmoMax; + int iDropClipAmmoMin; + int iDropClipAmmoMax; + bool blocksProne; + bool bShowIndicator; + int isRollingGrenade; + int iExplosionRadius; + int iExplosionRadiusMin; + int iIndicatorRadius; + int iExplosionInnerDamage; + int iExplosionOuterDamage; + float damageConeAngle; + int iProjectileSpeed; + int iProjectileSpeedUp; + int iProjectileSpeedRelativeUp; + int iProjectileSpeedForward; + int iProjectileActivateDist; + float projLifetime; + float timeToAccelerate; + float projectileCurvature; + XModel *projectileModel; + weapProjExposion_t projExplosion; + FxEffectDef *projExplosionEffect; + bool projExplosionEffectForceNormalUp; + FxEffectDef *projExplosionEffect2; + bool projExplosionEffect2ForceNormalUp; + FxEffectDef *projExplosionEffect3; + bool projExplosionEffect3ForceNormalUp; + FxEffectDef *projExplosionEffect4; + bool projExplosionEffect4ForceNormalUp; + FxEffectDef *projExplosionEffect5; + bool projExplosionEffect5ForceNormalUp; + FxEffectDef *projDudEffect; + const char *projExplosionSound; + const char *projDudSound; + const char *mortarShellSound; + const char *tankShellSound; + bool bProjImpactExplode; + bool bBulletImpactExplode; + WeapStickinessType stickiness; + WeapRotateType rotateType; + bool plantable; + bool hasDetonator; + bool timedDetonation; + bool bNoCrumpleMissile; + bool rotate; + bool bKeepRolling; + bool holdButtonToThrow; + bool offhandHoldIsCancelable; + bool freezeMovementWhenFiring; + float lowAmmoWarningThreshold; + float meleeChargeRange; + bool bUseAsMelee; + bool isCameraSensor; + bool isAcousticSensor; + float *parallelBounce; + float *perpendicularBounce; + FxEffectDef *projTrailEffect; + float vProjectileColor[3]; + guidedMissileType_t guidedMissileType; + float maxSteeringAccel; + int projIgnitionDelay; + FxEffectDef *projIgnitionEffect; + const char *projIgnitionSound; + float fAdsAimPitch; + float fAdsCrosshairInFrac; + float fAdsCrosshairOutFrac; + int adsGunKickReducedKickBullets; + float adsGunKickReducedKickPercent; + float fAdsGunKickPitchMin; + float fAdsGunKickPitchMax; + float fAdsGunKickYawMin; + float fAdsGunKickYawMax; + float fAdsGunKickAccel; + float fAdsGunKickSpeedMax; + float fAdsGunKickSpeedDecay; + float fAdsGunKickStaticDecay; + float fAdsViewKickPitchMin; + float fAdsViewKickPitchMax; + float fAdsViewKickYawMin; + float fAdsViewKickYawMax; + float fAdsViewScatterMin; + float fAdsViewScatterMax; + float fAdsSpread; + int hipGunKickReducedKickBullets; + float hipGunKickReducedKickPercent; + float fHipGunKickPitchMin; + float fHipGunKickPitchMax; + float fHipGunKickYawMin; + float fHipGunKickYawMax; + float fHipGunKickAccel; + float fHipGunKickSpeedMax; + float fHipGunKickSpeedDecay; + float fHipGunKickStaticDecay; + float fHipViewKickPitchMin; + float fHipViewKickPitchMax; + float fHipViewKickYawMin; + float fHipViewKickYawMax; + float fHipViewScatterMin; + float fHipViewScatterMax; + float fightDist; + float maxDist; + // const char *accuracyGraphName[2]; // TODO: Order is accuracyGraphName[0] -> accuracyGraphKnots[0] -> originalAccuracyGraphKnots[0] -> + // accuracyGraphName[1] -> ... + // Which is currently not possible to do in code generation. Afaik this is the only place where this is the case. + // So might be something to fix but on the other hand it might be too much work for this little inconvenience. + const char *accuracyGraphName0; + const char *accuracyGraphName1; + // vec2_t *accuracyGraphKnots[2]; + vec2_t *accuracyGraphKnots0; + vec2_t *accuracyGraphKnots1; + // vec2_t *originalAccuracyGraphKnots[2]; + vec2_t *originalAccuracyGraphKnots0; + vec2_t *originalAccuracyGraphKnots1; + int accuracyGraphKnotCount[2]; + int originalAccuracyGraphKnotCount[2]; + int iPositionReloadTransTime; + float leftArc; + float rightArc; + float topArc; + float bottomArc; + float accuracy; + float aiSpread; + float playerSpread; + float minTurnSpeed[2]; + float maxTurnSpeed[2]; + float pitchConvergenceTime; + float yawConvergenceTime; + float suppressTime; + float maxRange; + float fAnimHorRotateInc; + float fPlayerPositionDist; + const char *szUseHintString; + const char *dropHintString; + int iUseHintStringIndex; + int dropHintStringIndex; + float horizViewJitter; + float vertViewJitter; + const char *szScript; + int minDamage; + int minPlayerDamage; + float fMaxDamageRange; + float fMinDamageRange; + float destabilizationRateTime; + float destabilizationCurvatureMax; + int destabilizeDistance; + float *locationDamageMultipliers; + const char *fireRumble; + const char *meleeImpactRumble; + const char *reloadRumble; + float adsDofStart; + float adsDofEnd; + float hipDofStart; + float hipDofEnd; + float scanSpeed; + float scanAccel; + int scanPauseTime; + const char *flameTableFirstPerson; + const char *flameTableThirdPerson; + flameTable *flameTableFirstPersonPtr; + flameTable *flameTableThirdPersonPtr; + FxEffectDef *tagFx_preparationEffect; + FxEffectDef *tagFlash_preparationEffect; + bool doGibbing; + float maxGibDistance; +}; + +struct WeaponVariantDef { + const char *szInternalName; + int iVariantCount; + WeaponDef *weapDef; + const char *szDisplayName; + const char **szXAnims; + const char *szAltWeaponName; + uint16_t *hideTags; + unsigned int altWeaponIndex; + int iClipSize; + int iReloadTime; + int iReloadEmptyTime; + int iReloadQuickTime; + int iReloadQuickEmptyTime; + int iAdsTransInTime; + int iAdsTransOutTime; + int iAltRaiseTime; + const char *szAmmoName; + int iAmmoIndex; + const char *szClipName; + int iClipIndex; + float fAimAssistRangeAds; + float fAdsSwayHorizScale; + float fAdsSwayVertScale; + float fAdsViewKickCenterSpeed; + float fHipViewKickCenterSpeed; + float fAdsZoomFov1; + float fAdsZoomFov2; + float fAdsZoomFov3; + float fAdsZoomInFrac; + float fAdsZoomOutFrac; + float fOverlayAlphaScale; + float fOOPosAnimLength[2]; + bool bSilenced; + bool bDualMag; + bool bFullMetalJacket; + bool bHollowPoint; + bool bRapidFire; + Material *overlayMaterial; + Material *overlayMaterialLowRes; + Material *dpadIcon; + weaponIconRatioType_t dpadIconRatio; + float ikLeftHandOffset[3]; + float ikLeftHandRotation[3]; + float ikLeftHandProneOffset[3]; + float ikLeftHandProneRotation[3]; + float ikLeftHandUiViewerOffset[3]; + float ikLeftHandUiViewerRotation[3]; +}; + +struct WeaponFullDef { + WeaponVariantDef weapVariantDef; + WeaponDef weapDef; + XModel *gunXModel[16]; + const char *szXAnims[66]; + uint16_t hideTags[32]; + uint16_t notetrackSoundMapKeys[20]; + uint16_t notetrackSoundMapValues[20]; + XModel *worldModel[16]; + float parallelBounce[31]; + float perpendicularBounce[31]; + float locationDamageMultipliers[19]; +}; + +enum snd_category_t { + SND_CATEGORY_SFX = 0x0, + SND_CATEGORY_MUSIC = 0x1, + SND_CATEGORY_VOICE = 0x2, + SND_CATEGORY_UI = 0x3, + SND_CATEGORY_COUNT = 0x4, +}; + +struct snd_group { + char name[32]; + char parentName[32]; + unsigned int id; + int parentIndex; + snd_category_t category; + uint16_t attenuationSp; + uint16_t attenuationMp; +}; + +struct snd_curve { + char name[32]; + unsigned int id; + float points[8][2]; +}; + +struct snd_pan { + char name[32]; + unsigned int id; + float front; + float back; + float center; + float lfe; + float left; + float right; +}; + +struct snd_snapshot_group { + char name[32]; +}; + +struct snd_context { + unsigned int type; + unsigned int valueCount; + unsigned int values[8]; +}; + +struct snd_master { + char name[32]; + unsigned int id; + float notchE; + float notchG; + float notchF; + float notchQ; + float lowE; + float lowG; + float lowF; + float lowQ; + float peak1E; + float peak1G; + float peak1F; + float peak1Q; + float peak2E; + float peak2G; + float peak2F; + float peak2Q; + float hiE; + float hiG; + float hiF; + float hiQ; + float eqG; + float compE; + float compPG; + float compMG; + float compT; + float compR; + float compTA; + float compTR; + float limitE; + float limitPG; + float limitMG; + float limitT; + float limitR; + float limitTA; + float limitTR; +}; + +struct SndDriverGlobals { + const char *name; + unsigned int groupCount; + snd_group *groups; + unsigned int curveCount; + snd_curve *curves; + unsigned int panCount; + snd_pan *pans; + unsigned int snapshotGroupCount; + snd_snapshot_group *snapshotGroups; + unsigned int contextCount; + snd_context *contexts; + unsigned int masterCount; + snd_master *masters; +}; + +struct FxIntRange { + int base; + int amplitude; +}; + +struct FxFloatRange { + float base; + float amplitude; +}; + +struct FxElemVec3Range { + float base[3]; + float amplitude[3]; +}; + +struct FxSpawnDefLooping { + int intervalMsec; + int count; +}; + +struct FxSpawnDefOneShot { + FxIntRange count; +}; + +union FxSpawnDef { + FxSpawnDefLooping looping; + FxSpawnDefOneShot oneShot; +}; + +struct FxElemAtlas { + char behavior; + char index; + char fps; + char loopCount; + char colIndexBits; + char rowIndexBits; + uint16_t entryCountAndIndexRange; +}; + +struct FxElemVelStateInFrame { + FxElemVec3Range velocity; + FxElemVec3Range totalDelta; +}; + +struct FxElemVelStateSample { + FxElemVelStateInFrame local; + FxElemVelStateInFrame world; +}; + +struct FxElemVisualState { + char color[4]; + float rotationDelta; + float rotationTotal; + float size[2]; + float scale; +}; + +struct FxElemVisStateSample { + FxElemVisualState base; + FxElemVisualState amplitude; +}; + +struct FxElemMarkVisuals { + Material *materials[2]; +}; + +union FxEffectDefRef { + FxEffectDef *handle; + const char *name; +}; + +union FxElemVisuals { + void *anonymous; + Material *material; + XModel *model; + FxEffectDefRef effectDef; + const char *soundName; +}; + +union FxElemDefVisuals { + FxElemMarkVisuals *markArray; + FxElemVisuals *array; + FxElemVisuals instance; +}; + +struct FxTrailVertex { + float pos[2]; + float normal[2]; + float texCoord; +}; + +struct FxTrailDef { + int scrollTimeMsec; + int repeatDist; + int splitDist; + int vertCount; + FxTrailVertex *verts; + int indCount; + uint16_t *inds; +}; + +struct FxBillboardTrim { + float topWidth; + float bottomWidth; +}; + +union FxElemDefUnion { + FxBillboardTrim billboard; + FxIntRange cloudDensityRange; +}; + +struct FxElemSpawnSound { + const char *spawnSound; +}; + +enum FxElemType : char { + FX_ELEM_TYPE_SPRITE_BILLBOARD = 0x0, + FX_ELEM_TYPE_SPRITE_ORIENTED = 0x1, + FX_ELEM_TYPE_SPRITE_ROTATED = 0x2, + FX_ELEM_TYPE_TAIL = 0x3, + FX_ELEM_TYPE_LINE = 0x4, + FX_ELEM_TYPE_TRAIL = 0x5, + FX_ELEM_TYPE_CLOUD = 0x6, + FX_ELEM_TYPE_MODEL = 0x7, + FX_ELEM_TYPE_OMNI_LIGHT = 0x8, + FX_ELEM_TYPE_SPOT_LIGHT = 0x9, + FX_ELEM_TYPE_SOUND = 0xA, + FX_ELEM_TYPE_DECAL = 0xB, + FX_ELEM_TYPE_RUNNER = 0xC, + FX_ELEM_TYPE_COUNT = 0xD, + FX_ELEM_TYPE_LAST_SPRITE = 0x5, + FX_ELEM_TYPE_LAST_DRAWN = 0x9, +}; + +struct FxElemDef { + int flags; + FxSpawnDef spawn; + FxFloatRange spawnRange; + FxFloatRange fadeInRange; + FxFloatRange fadeOutRange; + float spawnFrustumCullRadius; + FxIntRange spawnDelayMsec; + FxIntRange lifeSpanMsec; + FxFloatRange spawnOrigin[3]; + FxFloatRange spawnOffsetRadius; + FxFloatRange spawnOffsetHeight; + FxFloatRange spawnAngles[3]; + FxFloatRange angularVelocity[3]; + FxFloatRange initialRotation; + unsigned int rotationAxis; + FxFloatRange gravity; + FxFloatRange reflectionFactor; + FxElemAtlas atlas; + float windInfluence; + char elemType; + char visualCount; + char velIntervalCount; + char visStateIntervalCount; + FxElemVelStateSample *velSamples; + FxElemVisStateSample *visSamples; + FxElemDefVisuals visuals; + float collMins[3]; + float collMaxs[3]; + FxEffectDefRef effectOnImpact; + FxEffectDefRef effectOnDeath; + FxEffectDefRef effectEmitted; + FxFloatRange emitDist; + FxFloatRange emitDistVariance; + FxEffectDefRef effectAttached; + FxTrailDef *trailDef; + char sortOrder; + char lightingFrac; + char unused[2]; + uint16_t alphaFadeTimeMsec; + uint16_t maxWindStrength; + uint16_t spawnIntervalAtMaxWind; + uint16_t lifespanAtMaxWind; + FxElemDefUnion u; + FxElemSpawnSound spawnSound; + float billboardPivot[2]; +}; + +struct FxEffectDef { + const char *name; + char flags; + char efPriority; + char reserved[2]; + int totalSize; + int msecLoopingLife; + int elemDefCountLooping; + int elemDefCountOneShot; + int elemDefCountEmission; + FxElemDef *elemDefs; + float boundingBoxDim[3]; + float boundingSphere[4]; +}; + +struct FxImpactEntry { + FxEffectDef *nonflesh[31]; + FxEffectDef *flesh[4]; +}; + +struct FxImpactTable { + const char *name; + FxImpactEntry *table; +}; + +struct RawFile { + const char *name; + int len; + const char *buffer; +}; + +struct StringTableCell { + const char *string; + int hash; +}; + +struct StringTable { + const char *name; + int columnCount; + int rowCount; + StringTableCell *values; + int16_t *cellIndex; +}; + +struct PackIndexHeader { + unsigned int magic; + unsigned int timestamp; + unsigned int count; + unsigned int alignment; + unsigned int data_start; +}; + +struct PackIndexEntry { + unsigned int hash; + unsigned int offset; + unsigned int size; +}; + +struct PackIndex { + const char *name; + PackIndexHeader header; + PackIndexEntry *entries; +}; + +struct XGlobals { + const char *name; + int xanimStreamBufferSize; + int cinematicMaxWidth; + int cinematicMaxHeight; + int extracamResolution; + int gumpReserve; + float screenClearColor[4]; +}; + +struct ddlMemberDef_t { + const char *name; + int size; + int offset; + int type; + int externalIndex; + unsigned int min; + unsigned int max; + unsigned int serverDelta; + unsigned int clientDelta; + int arraySize; + int enumIndex; + int permission; +}; + +struct ddlStructDef_t { + const char *name; + int size; + int memberCount; + ddlMemberDef_t *members; +}; + +struct ddlEnumDef_t { + const char *name; + int memberCount; + const char **members; +}; + +struct ddlDef_t { + int version; + int size; + ddlStructDef_t *structList; + int structCount; + ddlEnumDef_t *enumList; + int enumCount; + ddlDef_t *next; +}; + +struct ddlRoot_t { + const char *name; + ddlDef_t *ddlDef; +}; + +struct GlassDef { + const char *name; + int maxHealth; + float thickness; + float minShardSize; + float maxShardSize; + float shardLifeProbablility; + int maxShards; + Material *pristineMaterial; + Material *crackedMaterial; + Material *shardMaterial; + const char *crackSound; + const char *shatterShound; + const char *autoShatterShound; + FxEffectDef *crackEffect; + FxEffectDef *shatterEffect; +}; + +struct Glass { + GlassDef *glassDef; + unsigned int index; + unsigned int brushModel; + vec3_t origin; + vec3_t angles; + vec3_t absmin; + vec3_t absmax; + bool isPlanar; + char numOutlineVerts; + vec2_t *outline; + vec3_t outlineAxis[3]; + vec3_t outlineOrigin; + float uvScale; + float thickness; +}; + +struct Glasses { + const char *name; + unsigned int numGlasses; + Glass *glasses; + char *workMemory; + unsigned int workMemorySize; + unsigned int smallAllocatorBlocks; + unsigned int maxGroups; + unsigned int maxShards; + unsigned int maxPhysics; + unsigned int shardMemorySize; + unsigned int maxFreeCmd; + unsigned int numSlots; + unsigned int numVerts; + unsigned int numIndices; +}; + +struct EmblemLayer { + int cost; + int unlockLevel; + int unlockPLevel; +}; + +struct EmblemCategory { + const char *name; + const char *description; +}; + +struct EmblemIcon { + GfxImage *image; + const char *description; + float outlineSize; + int defaultColor; + int cost; + int unlockLevel; + int unlockPLevel; + int unclassifyAt; + int sortKey; + unsigned int category; +}; + +struct EmblemBackground { + Material *material; + const char *description; + int cost; + int unlockLevel; + int unlockPLevel; + int unclassifyAt; +}; + +struct EmblemSet { + int colorCount; + int layerCount; + EmblemLayer *layers; + int categoryCount; + EmblemCategory *categories; + int iconCount; + EmblemIcon *icons; + int backgroundCount; + EmblemBackground *backgrounds; + int backgroundLookupCount; + int16_t *backgroundLookup; +}; #ifndef __zonecodegenerator } // namespace T5 diff --git a/src/Common/Game/T6/CommonT6.cpp b/src/Common/Game/T6/CommonT6.cpp index 3d1816161..7882b430b 100644 --- a/src/Common/Game/T6/CommonT6.cpp +++ b/src/Common/Game/T6/CommonT6.cpp @@ -6,84 +6,60 @@ using namespace T6; -int Common::Com_HashKey(const char* str, const int maxLen) -{ - if (str == nullptr) - return 0; +int Common::Com_HashKey(const char *str, const int maxLen) { + if (str == nullptr) + return 0; - int hash = 0; - for (int i = 0; i < maxLen; i++) - { - if (str[i] == '\0') - break; + int hash = 0; + for (int i = 0; i < maxLen; i++) { + if (str[i] == '\0') + break; - hash += str[i] * (0x77 + i); - } + hash += str[i] * (0x77 + i); + } - return hash ^ ((hash ^ (hash >> 10)) >> 10); + return hash ^ ((hash ^ (hash >> 10)) >> 10); } -int Common::Com_HashString(const char* str) -{ - if (!str) - return 0; +int Common::Com_HashString(const char *str) { + if (!str) + return 0; - auto result = 0x1505; - auto offset = 0; - while(str[offset]) - { - const auto c = tolower(str[offset++]); - result = c + 33 * result; - } + auto result = 0x1505; + auto offset = 0; + while (str[offset]) { + const auto c = tolower(str[offset++]); + result = c + 33 * result; + } - return result; + return result; } -int Common::Com_HashString(const char* str, const int len) -{ - if (!str) - return 0; +int Common::Com_HashString(const char *str, const int len) { + if (!str) + return 0; - int result = 0x1505; - int offset = 0; - while(str[offset]) - { - if (len > 0 && offset >= len) - break; + int result = 0x1505; + int offset = 0; + while (str[offset]) { + if (len > 0 && offset >= len) + break; - const int c = tolower(str[offset++]); - result = c + 33 * result; - } + const int c = tolower(str[offset++]); + result = c + 33 * result; + } - return result; + return result; } -PackedTexCoords Common::Vec2PackTexCoords(const vec2_t* in) -{ - return PackedTexCoords{ Pack32::Vec2PackTexCoords(in->v) }; -} +PackedTexCoords Common::Vec2PackTexCoords(const vec2_t *in) { return PackedTexCoords{Pack32::Vec2PackTexCoords(in->v)}; } -PackedUnitVec Common::Vec3PackUnitVec(const vec3_t* in) -{ - return PackedUnitVec{ Pack32::Vec3PackUnitVec(in->v) }; -} +PackedUnitVec Common::Vec3PackUnitVec(const vec3_t *in) { return PackedUnitVec{Pack32::Vec3PackUnitVec(in->v)}; } -GfxColor Common::Vec4PackGfxColor(const vec4_t* in) -{ - return GfxColor{ Pack32::Vec4PackGfxColor(in->v) }; -} +GfxColor Common::Vec4PackGfxColor(const vec4_t *in) { return GfxColor{Pack32::Vec4PackGfxColor(in->v)}; } -void Common::Vec2UnpackTexCoords(const PackedTexCoords& in, vec2_t* out) -{ - Pack32::Vec2UnpackTexCoordsUV(in.packed, out->v); -} +void Common::Vec2UnpackTexCoords(const PackedTexCoords &in, vec2_t *out) { Pack32::Vec2UnpackTexCoordsUV(in.packed, out->v); } -void Common::Vec3UnpackUnitVec(const PackedUnitVec& in, vec3_t* out) -{ - Pack32::Vec3UnpackUnitVecThirdBased(in.packed, out->v); -} +void Common::Vec3UnpackUnitVec(const PackedUnitVec &in, vec3_t *out) { Pack32::Vec3UnpackUnitVecThirdBased(in.packed, out->v); } -void Common::Vec4UnpackGfxColor(const GfxColor& in, vec4_t* out) -{ - Pack32::Vec4UnpackGfxColor(in.packed, out->v); -} \ No newline at end of file +void Common::Vec4UnpackGfxColor(const GfxColor &in, vec4_t *out) { Pack32::Vec4UnpackGfxColor(in.packed, out->v); } \ No newline at end of file diff --git a/src/Common/Game/T6/CommonT6.h b/src/Common/Game/T6/CommonT6.h index ad8f38c06..1250e1f64 100644 --- a/src/Common/Game/T6/CommonT6.h +++ b/src/Common/Game/T6/CommonT6.h @@ -2,20 +2,18 @@ #include "T6.h" -namespace T6 -{ - class Common - { - public: - static int Com_HashKey(const char* str, int maxLen); - static int Com_HashString(const char* str); - static int Com_HashString(const char* str, int len); +namespace T6 { +class Common { +public: + static int Com_HashKey(const char *str, int maxLen); + static int Com_HashString(const char *str); + static int Com_HashString(const char *str, int len); - static PackedTexCoords Vec2PackTexCoords(const vec2_t* in); - static PackedUnitVec Vec3PackUnitVec(const vec3_t* in); - static GfxColor Vec4PackGfxColor(const vec4_t* in); - static void Vec2UnpackTexCoords(const PackedTexCoords& in, vec2_t* out); - static void Vec3UnpackUnitVec(const PackedUnitVec& in, vec3_t* out); - static void Vec4UnpackGfxColor(const GfxColor& in, vec4_t* out); - }; -} \ No newline at end of file + static PackedTexCoords Vec2PackTexCoords(const vec2_t *in); + static PackedUnitVec Vec3PackUnitVec(const vec3_t *in); + static GfxColor Vec4PackGfxColor(const vec4_t *in); + static void Vec2UnpackTexCoords(const PackedTexCoords &in, vec2_t *out); + static void Vec3UnpackUnitVec(const PackedUnitVec &in, vec3_t *out); + static void Vec4UnpackGfxColor(const GfxColor &in, vec4_t *out); +}; +} // namespace T6 \ No newline at end of file diff --git a/src/Common/Game/T6/GameT6.cpp b/src/Common/Game/T6/GameT6.cpp index e81f1552f..95f426503 100644 --- a/src/Common/Game/T6/GameT6.cpp +++ b/src/Common/Game/T6/GameT6.cpp @@ -8,54 +8,40 @@ using namespace T6; GameT6 g_GameT6; -std::string GameT6::GetFullName() -{ - return "Call Of Duty: Black Ops II"; -} +std::string GameT6::GetFullName() { return "Call Of Duty: Black Ops II"; } -std::string GameT6::GetShortName() -{ - return "T6"; -} +std::string GameT6::GetShortName() { return "T6"; } -void GameT6::AddZone(Zone* zone) -{ - m_zones.push_back(zone); -} +void GameT6::AddZone(Zone *zone) { m_zones.push_back(zone); } -void GameT6::RemoveZone(Zone* zone) -{ - const auto foundEntry = std::find(m_zones.begin(), m_zones.end(), zone); - - if (foundEntry != m_zones.end()) - m_zones.erase(foundEntry); -} +void GameT6::RemoveZone(Zone *zone) { + const auto foundEntry = std::find(m_zones.begin(), m_zones.end(), zone); -std::vector GameT6::GetZones() -{ - return m_zones; + if (foundEntry != m_zones.end()) + m_zones.erase(foundEntry); } -std::vector GameT6::GetLanguagePrefixes() -{ - std::vector prefixes; - - prefixes.emplace_back(GameLanguage::LANGUAGE_ENGLISH, "en_"); - prefixes.emplace_back(GameLanguage::LANGUAGE_FRENCH, "fr_"); - prefixes.emplace_back(GameLanguage::LANGUAGE_FRENCH_CAN, "fc_"); - prefixes.emplace_back(GameLanguage::LANGUAGE_GERMAN, "ge_"); - prefixes.emplace_back(GameLanguage::LANGUAGE_AUSTRIAN, "as_"); - prefixes.emplace_back(GameLanguage::LANGUAGE_ITALIAN, "it_"); - prefixes.emplace_back(GameLanguage::LANGUAGE_SPANISH, "sp_"); - prefixes.emplace_back(GameLanguage::LANGUAGE_BRITISH, "br_"); - prefixes.emplace_back(GameLanguage::LANGUAGE_RUSSIAN, "ru_"); - prefixes.emplace_back(GameLanguage::LANGUAGE_POLISH, "po_"); - prefixes.emplace_back(GameLanguage::LANGUAGE_KOREAN, "ko_"); - prefixes.emplace_back(GameLanguage::LANGUAGE_JAPANESE, "ja_"); - prefixes.emplace_back(GameLanguage::LANGUAGE_CZECH, "cz_"); - prefixes.emplace_back(GameLanguage::LANGUAGE_FULL_JAPANESE, "fj_"); - prefixes.emplace_back(GameLanguage::LANGUAGE_PORTUGUESE, "bp_"); - prefixes.emplace_back(GameLanguage::LANGUAGE_MEXICAN_SPANISH, "ms_"); - - return prefixes; +std::vector GameT6::GetZones() { return m_zones; } + +std::vector GameT6::GetLanguagePrefixes() { + std::vector prefixes; + + prefixes.emplace_back(GameLanguage::LANGUAGE_ENGLISH, "en_"); + prefixes.emplace_back(GameLanguage::LANGUAGE_FRENCH, "fr_"); + prefixes.emplace_back(GameLanguage::LANGUAGE_FRENCH_CAN, "fc_"); + prefixes.emplace_back(GameLanguage::LANGUAGE_GERMAN, "ge_"); + prefixes.emplace_back(GameLanguage::LANGUAGE_AUSTRIAN, "as_"); + prefixes.emplace_back(GameLanguage::LANGUAGE_ITALIAN, "it_"); + prefixes.emplace_back(GameLanguage::LANGUAGE_SPANISH, "sp_"); + prefixes.emplace_back(GameLanguage::LANGUAGE_BRITISH, "br_"); + prefixes.emplace_back(GameLanguage::LANGUAGE_RUSSIAN, "ru_"); + prefixes.emplace_back(GameLanguage::LANGUAGE_POLISH, "po_"); + prefixes.emplace_back(GameLanguage::LANGUAGE_KOREAN, "ko_"); + prefixes.emplace_back(GameLanguage::LANGUAGE_JAPANESE, "ja_"); + prefixes.emplace_back(GameLanguage::LANGUAGE_CZECH, "cz_"); + prefixes.emplace_back(GameLanguage::LANGUAGE_FULL_JAPANESE, "fj_"); + prefixes.emplace_back(GameLanguage::LANGUAGE_PORTUGUESE, "bp_"); + prefixes.emplace_back(GameLanguage::LANGUAGE_MEXICAN_SPANISH, "ms_"); + + return prefixes; } diff --git a/src/Common/Game/T6/GameT6.h b/src/Common/Game/T6/GameT6.h index 60ce25d10..1a69850e3 100644 --- a/src/Common/Game/T6/GameT6.h +++ b/src/Common/Game/T6/GameT6.h @@ -1,17 +1,16 @@ #pragma once #include "Game/IGame.h" -class GameT6 : public IGame -{ - std::vector m_zones; +class GameT6 : public IGame { + std::vector m_zones; public: - std::string GetFullName() override; - std::string GetShortName() override; - void AddZone(Zone* zone) override; - void RemoveZone(Zone* zone) override; - std::vector GetZones() override; - std::vector GetLanguagePrefixes() override; + std::string GetFullName() override; + std::string GetShortName() override; + void AddZone(Zone *zone) override; + void RemoveZone(Zone *zone) override; + std::vector GetZones() override; + std::vector GetLanguagePrefixes() override; }; extern GameT6 g_GameT6; \ No newline at end of file diff --git a/src/Common/Game/T6/T6.h b/src/Common/Game/T6/T6.h index 38cc82623..c411b665c 100644 --- a/src/Common/Game/T6/T6.h +++ b/src/Common/Game/T6/T6.h @@ -1,152 +1,140 @@ #pragma once -//#include +// #include #include "Image/Texture.h" #include "T6_Assets.h" -namespace T6 -{ - struct ScriptStringList - { - int count; - const char** strings; - }; - - struct XAsset - { - XAssetType type; - XAssetHeader header; - }; - - struct XAssetList - { - ScriptStringList stringList; - int dependCount; - const char** depends; - int assetCount; - XAsset* assets; - }; - - struct cspField_t - { - const char* szName; - int iOffset; - int iFieldType; - }; - - enum csParseFieldType_t - { - CSPFT_STRING = 0, - CSPFT_STRING_MAX_STRING_CHARS, - CSPFT_STRING_MAX_QPATH, - CSPFT_STRING_MAX_OSPATH, - CSPFT_INT, - CSPFT_UINT, - CSPFT_BOOL, - CSPFT_QBOOLEAN, - CSPFT_FLOAT, - CSPFT_MILLISECONDS, - CSPFT_FX, - CSPFT_XMODEL, - CSPFT_MATERIAL, - CSPFT_MATERIAL_STREAM, - CSPFT_PHYS_PRESET, - CSPFT_SCRIPT_STRING, - CSPFT_TRACER, - CSPFT_SOUND_ALIAS_ID, - - CSPFT_NUM_BASE_FIELD_TYPES - }; - - enum weapFieldType_t - { - WFT_WEAPONTYPE = CSPFT_NUM_BASE_FIELD_TYPES, - WFT_WEAPONCLASS, - WFT_OVERLAYRETICLE, - WFT_PENETRATE_TYPE, - WFT_IMPACT_TYPE, - WFT_STANCE, - WFT_PROJ_EXPLOSION, - WFT_OFFHAND_CLASS, - WFT_OFFHAND_SLOT, - WFT_ANIMTYPE, - WFT_ACTIVE_RETICLE_TYPE, - WFT_GUIDED_MISSILE_TYPE, - WFT_BOUNCE_SOUND, - WFT_STICKINESS, - WFT_ROTATETYPE, - WFT_OVERLAYINTERFACE, - WFT_INVENTORYTYPE, - WFT_FIRETYPE, - WFT_CLIPTYPE, - WFT_AMMOCOUNTER_CLIPTYPE, - WFT_ICONRATIO_HUD, - WFT_ICONRATIO_AMMOCOUNTER, - WFT_ICONRATIO_KILL, - WFT_ICONRATIO_DPAD, - WFT_ICONRATIO_INDICATOR, - WFT_BARRELTYPE, - WFT_HIDETAGS, - WFT_EXPLOSION_TAG, - WFT_NOTETRACKSOUNDMAP, - WFT_WEAPON_CAMO, - WFT_ATTACHMENTS, - WFT_ATTACHMENT_UNIQUES, - - WFT_NUM_FIELD_TYPES - }; - - enum VehicleFieldType - { - VFT_TYPE = CSPFT_NUM_BASE_FIELD_TYPES, - VFT_CAMERAMODE, - VFT_TRACTION_TYPE, - VFT_MPH_TO_INCHES_PER_SECOND, - VFT_POUNDS_TO_GAME_MASS, - VFT_TEAM, - VFT_KEY_BINDING, - VFT_GRAPH, - VFT_WIIUCONTROLOVERRIDE, - - VFT_NUM - }; - - enum tracerFieldType_t - { - TFT_TRACERTYPE = CSPFT_NUM_BASE_FIELD_TYPES, - - TFT_NUM_FIELD_TYPES - }; - - enum constraintsFieldType_t - { - CFT_TYPE = CSPFT_NUM_BASE_FIELD_TYPES, - - CFT_NUM_FIELD_TYPES - }; - - enum attachmentFieldType_t - { - AFT_ATTACHMENTTYPE = CSPFT_NUM_BASE_FIELD_TYPES, - AFT_UNKNOWN1, - AFT_UNKNOWN2, - AFT_UNKNOWN3, - AFT_UNKNOWN4, - AFT_PENETRATE_TYPE, - AFT_FIRETYPE, - - AFT_NUM - }; - - enum attachmentUniqueFieldType_t - { - AUFT_ATTACHMENTTYPE = CSPFT_NUM_BASE_FIELD_TYPES, - AUFT_HIDETAGS, - AUFT_OVERLAYRETICLE, - AUFT_CAMO, - - AUFT_NUM_FIELD_TYPES, - }; - -} +namespace T6 { +struct ScriptStringList { + int count; + const char **strings; +}; + +struct XAsset { + XAssetType type; + XAssetHeader header; +}; + +struct XAssetList { + ScriptStringList stringList; + int dependCount; + const char **depends; + int assetCount; + XAsset *assets; +}; + +struct cspField_t { + const char *szName; + int iOffset; + int iFieldType; +}; + +enum csParseFieldType_t { + CSPFT_STRING = 0, + CSPFT_STRING_MAX_STRING_CHARS, + CSPFT_STRING_MAX_QPATH, + CSPFT_STRING_MAX_OSPATH, + CSPFT_INT, + CSPFT_UINT, + CSPFT_BOOL, + CSPFT_QBOOLEAN, + CSPFT_FLOAT, + CSPFT_MILLISECONDS, + CSPFT_FX, + CSPFT_XMODEL, + CSPFT_MATERIAL, + CSPFT_MATERIAL_STREAM, + CSPFT_PHYS_PRESET, + CSPFT_SCRIPT_STRING, + CSPFT_TRACER, + CSPFT_SOUND_ALIAS_ID, + + CSPFT_NUM_BASE_FIELD_TYPES +}; + +enum weapFieldType_t { + WFT_WEAPONTYPE = CSPFT_NUM_BASE_FIELD_TYPES, + WFT_WEAPONCLASS, + WFT_OVERLAYRETICLE, + WFT_PENETRATE_TYPE, + WFT_IMPACT_TYPE, + WFT_STANCE, + WFT_PROJ_EXPLOSION, + WFT_OFFHAND_CLASS, + WFT_OFFHAND_SLOT, + WFT_ANIMTYPE, + WFT_ACTIVE_RETICLE_TYPE, + WFT_GUIDED_MISSILE_TYPE, + WFT_BOUNCE_SOUND, + WFT_STICKINESS, + WFT_ROTATETYPE, + WFT_OVERLAYINTERFACE, + WFT_INVENTORYTYPE, + WFT_FIRETYPE, + WFT_CLIPTYPE, + WFT_AMMOCOUNTER_CLIPTYPE, + WFT_ICONRATIO_HUD, + WFT_ICONRATIO_AMMOCOUNTER, + WFT_ICONRATIO_KILL, + WFT_ICONRATIO_DPAD, + WFT_ICONRATIO_INDICATOR, + WFT_BARRELTYPE, + WFT_HIDETAGS, + WFT_EXPLOSION_TAG, + WFT_NOTETRACKSOUNDMAP, + WFT_WEAPON_CAMO, + WFT_ATTACHMENTS, + WFT_ATTACHMENT_UNIQUES, + + WFT_NUM_FIELD_TYPES +}; + +enum VehicleFieldType { + VFT_TYPE = CSPFT_NUM_BASE_FIELD_TYPES, + VFT_CAMERAMODE, + VFT_TRACTION_TYPE, + VFT_MPH_TO_INCHES_PER_SECOND, + VFT_POUNDS_TO_GAME_MASS, + VFT_TEAM, + VFT_KEY_BINDING, + VFT_GRAPH, + VFT_WIIUCONTROLOVERRIDE, + + VFT_NUM +}; + +enum tracerFieldType_t { + TFT_TRACERTYPE = CSPFT_NUM_BASE_FIELD_TYPES, + + TFT_NUM_FIELD_TYPES +}; + +enum constraintsFieldType_t { + CFT_TYPE = CSPFT_NUM_BASE_FIELD_TYPES, + + CFT_NUM_FIELD_TYPES +}; + +enum attachmentFieldType_t { + AFT_ATTACHMENTTYPE = CSPFT_NUM_BASE_FIELD_TYPES, + AFT_UNKNOWN1, + AFT_UNKNOWN2, + AFT_UNKNOWN3, + AFT_UNKNOWN4, + AFT_PENETRATE_TYPE, + AFT_FIRETYPE, + + AFT_NUM +}; + +enum attachmentUniqueFieldType_t { + AUFT_ATTACHMENTTYPE = CSPFT_NUM_BASE_FIELD_TYPES, + AUFT_HIDETAGS, + AUFT_OVERLAYRETICLE, + AUFT_CAMO, + + AUFT_NUM_FIELD_TYPES, +}; + +} // namespace T6 diff --git a/src/Common/Game/T6/T6_Assets.h b/src/Common/Game/T6/T6_Assets.h index e41a57026..3b620726f 100644 --- a/src/Common/Game/T6/T6_Assets.h +++ b/src/Common/Game/T6/T6_Assets.h @@ -6,6720 +6,5926 @@ #include "../../Utils/TypeAlignment.h" #ifndef __zonecodegenerator -namespace T6 -{ +namespace T6 { #endif - typedef tdef_align(16) char char16; - typedef tdef_align(32) char byte32; - typedef tdef_align(128) char byte128; - - typedef tdef_align(4) char char_align4; - typedef tdef_align(128) char char_align128; - - typedef tdef_align(16) char raw_byte16; - typedef tdef_align(128) char raw_byte128; - - typedef tdef_align(128) float float_align128; - - struct dvar_t; - struct MenuCell; - struct cplane_s; - struct cbrushside_t; - struct MaterialVertexDeclaration; - struct MaterialVertexShader; - struct MaterialPixelShader; - struct MaterialShaderArgument; - struct MaterialTechnique; - struct MaterialTechniqueSet; - struct GfxImageLoadDef; - struct GfxImage; - struct MaterialTextureDef; - struct MaterialConstantDef; - struct GfxStateBits; - struct Material; - struct MenuRow; - struct Glyph; - struct KerningPairs; - struct Font_s; - struct BrushWrapper; - struct multiDef_s; - struct XModelCollTri_s; - struct PhysConstraints; - struct ScriptCondition; - struct listBoxDef_s; - struct expressionRpn; - struct GenericEventScript; - struct GenericEventHandler; - struct animParamsDef_t; - struct enumDvarDef_s; - struct PhysPreset; - struct profileMultiDef_s; - struct PhysGeomInfo; - struct XModelCollSurf_s; - struct gameMsgDef_s; - struct SndAlias; - struct SndAliasList; - struct XBoneInfo; - struct editFieldDef_s; - struct WeaponCamoMaterial; - struct PhysGeomList; - struct textExp_s; - struct ItemKeyHandler; - struct focusItemDef_s; - struct textDef_s; - struct imageDef_s; - struct ownerDrawDef_s; - struct menuDef_t; - struct rectData_s; - struct UIAnimInfo; - struct itemDef_s; - struct WeaponCamoMaterialSet; - struct Collmap; - struct TracerDef; - struct WeaponAttachment; - struct DObjAnimMat; - struct GfxPackedVertex; - struct XSurfaceCollisionNode; - struct XSurfaceCollisionLeaf; - struct XSurfaceCollisionTree; - struct XRigidVertList; - struct XSurface; - struct XModel; - struct flameTable; - struct cStaticModel_s; - struct FxElemVelStateSample; - struct FxElemVisStateSample; - struct FxElemMarkVisuals; - struct FxEffectDef; - struct GfxLightDef; - union FxElemVisuals; - struct FxTrailVertex; - struct FxTrailDef; - struct FxSpotLightDef; - struct FxElemDef; - struct WeaponCamoSet; - struct WeaponCamo; - struct WeaponDef; - struct WeaponAttachmentUnique; - struct WeaponVariantDef; - struct cLeafBrushNode_s; - struct cbrush_t; - struct ClipMaterial; - struct Bounds; - struct cLeaf_s; - struct cmodel_t; - struct CollisionAabbTree; - struct pathlink_s; - struct pathnode_t; - struct DestructiblePiece; - struct DestructibleDef; - struct GraphFloat; - struct VehicleDef; - struct XAnimNotifyInfo; - struct XAnimPartTrans; - struct XAnimDeltaPartQuat2; - struct XAnimDeltaPartQuat; - struct XAnimDeltaPart; - struct XAnimParts; - struct ZBarrierDef; - struct GfxLight; - struct ddlHash_t; - struct ddlEnumDef_t; - struct SndVolumeGroup; - struct XModelPiece; - struct XModelPieces; - struct DynEntityDef; - struct CollisionPartition; - struct ddlMemberDef_t; - struct ddlStructDef_t; - struct ddlDef_t; - struct GlassDef; - struct Glass; - struct GfxAabbTree; - struct FxImpactEntry; - struct StringTableCell; - struct ddlRoot_t; - struct StringTable; - struct FxImpactTable; - struct SndIndexEntry; - struct SndRadverb; - struct SndDuck; - struct SndAssetBankEntry; - struct SndDialogScriptIdLookup; - struct SndBank; - struct SndPatch; - struct cNode_t; - struct TriggerModel; - struct TriggerHull; - struct TriggerSlab; - struct MapEnts; - struct DynEntityPose; - struct DynEntityClient; - struct DynEntityServer; - struct DynEntityColl; - struct rope_t; - struct clipMap_t; - struct ComPrimaryLight; - struct ComWorld; - struct pathbasenode_t; - struct pathnode_tree_t; - struct GameWorldSp; - struct GameWorldMp; - struct GfxStreamingAabbTree; - struct GfxLightCorona; - struct GfxShadowMapVolume; - struct GfxVolumePlane; - struct GfxExposureVolume; - struct GfxWorldFogVolume; - struct GfxWorldFogModifierVolume; - struct GfxLutVolume; - struct GfxPortal; - struct GfxCell; - struct GfxReflectionProbeVolumeData; - struct GfxReflectionProbe; - struct GfxLightmapArray; - struct GfxLightGridEntry; - struct GfxCompressedLightGridColors; - struct GfxCompressedLightGridCoeffs; - struct GfxSkyGridVolume; - struct GfxBrushModel; - struct MaterialMemory; - struct GfxSceneDynModel; - struct GfxSceneDynBrush; - struct SSkinShaders; - struct SSkinVert; - struct SSkinModel; - struct SSkinAnim; - struct SSkinInstance; - struct GfxShadowGeometry; - struct GfxLightRegionAxis; - struct GfxLightRegionHull; - struct GfxLightRegion; - struct GfxStaticModelInst; - struct GfxSurface; - struct GfxStaticModelDrawInst; - struct Occluder; - struct GfxOutdoorBounds; - struct GfxHeroLight; - struct GfxHeroLightTree; - struct GfxWorld; - struct FontIconEntry; - struct FontIconAlias; - struct FontIcon; - struct MenuList; - struct LocalizeEntry; - struct SndCurve; - struct SndPan; - struct SndDuckGroup; - struct SndContext; - struct SndMaster; - struct SndSidechainDuck; - struct SndFutz; - struct SndDriverGlobals; - struct RawFile; - struct LbColumnDef; - struct LeaderboardDef; - struct XGlobals; - struct Glasses; - struct EmblemSet; - struct ScriptParseTree; - struct KeyValuePair; - struct KeyValuePairs; - struct MemoryBlock; - struct AddonMapEnts; - struct SkinnedVertsDef; - struct Qdb; - struct Slug; - struct FootstepTableDef; - struct FootstepFXTableDef; - - enum XAssetType - { - ASSET_TYPE_XMODELPIECES = 0x0, - ASSET_TYPE_PHYSPRESET = 0x1, - ASSET_TYPE_PHYSCONSTRAINTS = 0x2, - ASSET_TYPE_DESTRUCTIBLEDEF = 0x3, - ASSET_TYPE_XANIMPARTS = 0x4, - ASSET_TYPE_XMODEL = 0x5, - ASSET_TYPE_MATERIAL = 0x6, - ASSET_TYPE_TECHNIQUE_SET = 0x7, - ASSET_TYPE_IMAGE = 0x8, - ASSET_TYPE_SOUND = 0x9, - ASSET_TYPE_SOUND_PATCH = 0xA, - ASSET_TYPE_CLIPMAP = 0xB, - ASSET_TYPE_CLIPMAP_PVS = 0xC, - ASSET_TYPE_COMWORLD = 0xD, - ASSET_TYPE_GAMEWORLD_SP = 0xE, - ASSET_TYPE_GAMEWORLD_MP = 0xF, - ASSET_TYPE_MAP_ENTS = 0x10, - ASSET_TYPE_GFXWORLD = 0x11, - ASSET_TYPE_LIGHT_DEF = 0x12, - ASSET_TYPE_UI_MAP = 0x13, - ASSET_TYPE_FONT = 0x14, - ASSET_TYPE_FONTICON = 0x15, - ASSET_TYPE_MENULIST = 0x16, - ASSET_TYPE_MENU = 0x17, - ASSET_TYPE_LOCALIZE_ENTRY = 0x18, - ASSET_TYPE_WEAPON = 0x19, - ASSET_TYPE_WEAPONDEF = 0x1A, - ASSET_TYPE_WEAPON_VARIANT = 0x1B, - ASSET_TYPE_WEAPON_FULL = 0x1C, - ASSET_TYPE_ATTACHMENT = 0x1D, - ASSET_TYPE_ATTACHMENT_UNIQUE = 0x1E, - ASSET_TYPE_WEAPON_CAMO = 0x1F, - ASSET_TYPE_SNDDRIVER_GLOBALS = 0x20, - ASSET_TYPE_FX = 0x21, - ASSET_TYPE_IMPACT_FX = 0x22, - ASSET_TYPE_AITYPE = 0x23, - ASSET_TYPE_MPTYPE = 0x24, - ASSET_TYPE_MPBODY = 0x25, - ASSET_TYPE_MPHEAD = 0x26, - ASSET_TYPE_CHARACTER = 0x27, - ASSET_TYPE_XMODELALIAS = 0x28, - ASSET_TYPE_RAWFILE = 0x29, - ASSET_TYPE_STRINGTABLE = 0x2A, - ASSET_TYPE_LEADERBOARD = 0x2B, - ASSET_TYPE_XGLOBALS = 0x2C, - ASSET_TYPE_DDL = 0x2D, - ASSET_TYPE_GLASSES = 0x2E, - ASSET_TYPE_EMBLEMSET = 0x2F, - ASSET_TYPE_SCRIPTPARSETREE = 0x30, - ASSET_TYPE_KEYVALUEPAIRS = 0x31, - ASSET_TYPE_VEHICLEDEF = 0x32, - ASSET_TYPE_MEMORYBLOCK = 0x33, - ASSET_TYPE_ADDON_MAP_ENTS = 0x34, - ASSET_TYPE_TRACER = 0x35, - ASSET_TYPE_SKINNEDVERTS = 0x36, - ASSET_TYPE_QDB = 0x37, - ASSET_TYPE_SLUG = 0x38, - ASSET_TYPE_FOOTSTEP_TABLE = 0x39, - ASSET_TYPE_FOOTSTEPFX_TABLE = 0x3A, - ASSET_TYPE_ZBARRIER = 0x3B, - ASSET_TYPE_COUNT = 0x3C, - ASSET_TYPE_STRING = 0x3C, - ASSET_TYPE_ASSETLIST = 0x3D, - ASSET_TYPE_REPORT = 0x3E, - ASSET_TYPE_DEPEND = 0x3F, - ASSET_TYPE_FULL_COUNT = 0x40, - }; - - enum XFileBlock - { - XFILE_BLOCK_TEMP, - XFILE_BLOCK_RUNTIME_VIRTUAL, - XFILE_BLOCK_RUNTIME_PHYSICAL, - XFILE_BLOCK_DELAY_VIRTUAL, - XFILE_BLOCK_DELAY_PHYSICAL, - XFILE_BLOCK_VIRTUAL, - XFILE_BLOCK_PHYSICAL, - XFILE_BLOCK_STREAMER_RESERVE, - MAX_XFILE_COUNT, - }; - - - union XAssetHeader - { - //XModelPieces *xmodelPieces; // Not an asset - PhysPreset* physPreset; - PhysConstraints* physConstraints; - DestructibleDef* destructibleDef; - XAnimParts* parts; - XModel* model; - Material* material; - //MaterialPixelShader *pixelShader; // Not an asset - //MaterialVertexShader *vertexShader; // Not an asset - MaterialTechniqueSet* techniqueSet; - GfxImage* image; - SndBank* sound; - SndPatch* soundPatch; - clipMap_t* clipMap; - ComWorld* comWorld; - GameWorldSp* gameWorldSp; - GameWorldMp* gameWorldMp; - MapEnts* mapEnts; - GfxWorld* gfxWorld; - GfxLightDef* lightDef; - Font_s* font; - FontIcon* fontIcon; - MenuList* menuList; - menuDef_t* menu; - LocalizeEntry* localize; - WeaponVariantDef* weapon; - WeaponAttachment* attachment; - WeaponAttachmentUnique* attachmentUnique; - WeaponCamo* weaponCamo; - SndDriverGlobals* sndDriverGlobals; - FxEffectDef* fx; - FxImpactTable* impactFx; - RawFile* rawfile; - StringTable* stringTable; - LeaderboardDef* leaderboardDef; - XGlobals* xGlobals; - ddlRoot_t* ddlRoot; - Glasses* glasses; - //TextureList *textureList; // Does not exist in this game - EmblemSet* emblemSet; - ScriptParseTree* scriptParseTree; - KeyValuePairs* keyValuePairs; - VehicleDef* vehicleDef; - MemoryBlock* memoryBlock; - AddonMapEnts* addonMapEnts; - TracerDef* tracerDef; - SkinnedVertsDef* skinnedVertsDef; - Qdb* qdb; - Slug* slug; - FootstepTableDef* footstepTableDef; - FootstepFXTableDef* footstepFXTableDef; - ZBarrierDef* zbarrierDef; - void* data; - }; - - union vec2_t - { - float v[2]; - - struct - { - float x; - float y; - }; - }; - - union vec3_t - { - struct - { - float x; - float y; - float z; - }; - - float v[3]; - }; - - union vec4_t - { - float v[4]; - - struct - { - float x; - float y; - float z; - float w; - }; - - struct - { - float r; - float g; - float b; - float a; - }; - }; - - struct XModelPieces - { - const char* name; - int numpieces; - XModelPiece* pieces; - }; - - struct PhysPresetInfo - { - float mass; - float bounce; - float friction; - int isFrictionInfinity; - float bulletForceScale; - float explosiveForceScale; - float piecesSpreadFraction; - float piecesUpwardVelocity; - int canFloat; - float gravityScale; - vec3_t centerOfMassOffset; - vec3_t buoyancyBoxMin; - vec3_t buoyancyBoxMax; - }; - - struct PhysPreset - { - const char* name; - int flags; - float mass; - float bounce; - float friction; - float bulletForceScale; - float explosiveForceScale; - const char* sndAliasPrefix; - float piecesSpreadFraction; - float piecesUpwardVelocity; - int canFloat; - float gravityScale; - vec3_t centerOfMassOffset; - vec3_t buoyancyBoxMin; - vec3_t buoyancyBoxMax; - }; - - - enum ConstraintType - { - CONSTRAINT_NONE = 0x0, - CONSTRAINT_POINT = 0x1, - CONSTRAINT_DISTANCE = 0x2, - CONSTRAINT_HINGE = 0x3, - CONSTRAINT_JOINT = 0x4, - CONSTRAINT_ACTUATOR = 0x5, - CONSTRAINT_FAKE_SHAKE = 0x6, - CONSTRAINT_LAUNCH = 0x7, - CONSTRAINT_ROPE = 0x8, - CONSTRAINT_LIGHT = 0x9, - NUM_CONSTRAINT_TYPES = 0xA, - }; - - - enum AttachPointType - { - ATTACH_POINT_WORLD = 0x0, - ATTACH_POINT_DYNENT = 0x1, - ATTACH_POINT_ENT = 0x2, - ATTACH_POINT_BONE = 0x3, - }; - - - struct PhysConstraint - { - uint16_t targetname; - ConstraintType type; - AttachPointType attach_point_type1; - int target_index1; - uint16_t target_ent1; - const char* target_bone1; - AttachPointType attach_point_type2; - int target_index2; - uint16_t target_ent2; - const char* target_bone2; - vec3_t offset; - vec3_t pos; - vec3_t pos2; - vec3_t dir; - int flags; - int timeout; - int min_health; - int max_health; - float distance; - float damp; - float power; - vec3_t scale; - float spin_scale; - float minAngle; - float maxAngle; - Material* material; - int constraintHandle; - int rope_index; - int centity_num[4]; - }; - - - struct PhysConstraints - { - const char* name; - unsigned int count; - PhysConstraint data[16]; - }; - - - struct DestructibleDef - { - const char* name; - XModel* model; - XModel* pristineModel; - int numPieces; - DestructiblePiece* pieces; - int clientOnly; - }; - - - union XAnimIndices - { - char* _1; - uint16_t* _2; - void* data; - }; - - - struct XAnimParts - { - const char* name; - uint16_t dataByteCount; - uint16_t dataShortCount; - uint16_t dataIntCount; - uint16_t randomDataByteCount; - uint16_t randomDataIntCount; - uint16_t numframes; - bool bLoop; - bool bDelta; - bool bDelta3D; - bool bLeftHandGripIK; - unsigned int streamedFileSize; - unsigned char boneCount[10]; - unsigned char notifyCount; - char assetType; - bool isDefault; - unsigned int randomDataShortCount; - unsigned int indexCount; - float framerate; - float frequency; - float primedLength; - float loopEntryTime; - uint16_t* names; - char* dataByte; - int16_t* dataShort; - int* dataInt; - int16_t* randomDataShort; - char* randomDataByte; - int* randomDataInt; - XAnimIndices indices; - XAnimNotifyInfo* notify; - XAnimDeltaPart* deltaPart; - }; - - struct DObjSkelMat - { - vec4_t axis[3]; - vec4_t origin; - }; - - struct XModelLodInfo - { - float dist; - uint16_t numsurfs; - uint16_t surfIndex; - int partBits[5]; - }; - - - struct XModel - { - const char* name; - unsigned char numBones; - unsigned char numRootBones; - unsigned char numsurfs; - char lodRampType; - uint16_t* boneNames; - unsigned char* parentList; - uint16_t (*quats)[4]; - float (*trans)[4]; - char* partClassification; - DObjAnimMat* baseMat; - XSurface* surfs; - Material** materialHandles; - XModelLodInfo lodInfo[4]; - XModelCollSurf_s* collSurfs; - int numCollSurfs; - int contents; - XBoneInfo* boneInfo; - float radius; - vec3_t mins; - vec3_t maxs; - uint16_t numLods; - uint16_t collLod; - float* himipInvSqRadii; - int memUsage; - int flags; - bool bad; - PhysPreset* physPreset; - unsigned char numCollmaps; - Collmap* collmaps; - PhysConstraints* physConstraints; - vec3_t lightingOriginOffset; - float lightingOriginRange; - }; - - - struct gcc_align(8) GfxDrawSurfFields - { - uint64_t objectId : 16; - uint64_t customIndex : 9; - uint64_t reflectionProbeIndex : 5; - uint64_t dlightMask : 2; - uint64_t materialSortedIndex : 12; - uint64_t primaryLightIndex : 8; - uint64_t surfType : 4; - uint64_t prepass : 2; - uint64_t primarySortKey : 6; - }; - - - union GfxDrawSurf - { - gcc_align(8) GfxDrawSurfFields fields; - gcc_align(8) uint64_t packed; - }; - - - struct type_align(8) MaterialInfo - { - const char* name; - unsigned int gameFlags; - char pad; - char sortKey; - char textureAtlasRowCount; - char textureAtlasColumnCount; - GfxDrawSurf drawSurf; - unsigned int surfaceTypeBits; - unsigned int layeredSurfaceTypes; - uint16_t hashIndex; - int surfaceFlags; - int contents; - }; - - typedef tdef_align(8) GfxStateBits GfxStateBitsTable; - - - struct Material - { - MaterialInfo info; - char stateBitsEntry[36]; - unsigned char textureCount; - unsigned char constantCount; - unsigned char stateBitsCount; - char stateFlags; - char cameraRegion; - char probeMipBits; - MaterialTechniqueSet* techniqueSet; - MaterialTextureDef* textureTable; - MaterialConstantDef* constantTable; - GfxStateBitsTable* stateBitsTable; - Material* thermalMaterial; - }; - - - struct GfxPixelShaderLoadDef - { - char* program; - unsigned int programSize; - }; - - - struct MaterialPixelShaderProgram - { - void/*ID3D11PixelShader*/* ps; - GfxPixelShaderLoadDef loadDef; - }; - - - struct MaterialPixelShader - { - const char* name; - MaterialPixelShaderProgram prog; - }; - - - struct GfxVertexShaderLoadDef - { - char* program; - unsigned int programSize; - }; - - - struct MaterialVertexShaderProgram - { - void/*ID3D11VertexShader*/* vs; - GfxVertexShaderLoadDef loadDef; - }; - - - struct MaterialVertexShader - { - const char* name; - MaterialVertexShaderProgram prog; - }; - - - struct MaterialTechniqueSet - { - const char* name; - char worldVertFormat; - MaterialTechnique* techniques[36]; - }; - - - union GfxTexture - { - void/*ID3D11ShaderResourceView*/* basemap; - Texture* texture; - GfxImageLoadDef* loadDef; - }; - - - struct Picmip - { - char platform[2]; - }; - - - struct CardMemory - { - int platform[2]; - }; - - - struct GfxStreamedPartInfo - { - unsigned int levelCountAndSize; - unsigned int hash; - uint16_t width; - uint16_t height; - uint32_t offset : 32; - uint32_t size : 28; - uint32_t ipakIndex : 4; - uint32_t adjacentLeft : 15; - uint32_t adjacentRight : 15; - uint32_t compressed : 1; - uint32_t valid : 1; - }; - - enum TextureSemantic - { - TS_2D = 0x0, - TS_FUNCTION = 0x1, - TS_COLOR_MAP = 0x2, - TS_UNUSED_1 = 0x3, - TS_UNUSED_2 = 0x4, - TS_NORMAL_MAP = 0x5, - TS_UNUSED_3 = 0x6, - TS_UNUSED_4 = 0x7, - TS_SPECULAR_MAP = 0x8, - TS_UNUSED_5 = 0x9, - TS_OCCLUSION_MAP = 0xA, - TS_UNUSED_6 = 0xB, - TS_COLOR0_MAP = 0xC, - TS_COLOR1_MAP = 0xD, - TS_COLOR2_MAP = 0xE, - TS_COLOR3_MAP = 0xF, - TS_COLOR4_MAP = 0x10, - TS_COLOR5_MAP = 0x11, - TS_COLOR6_MAP = 0x12, - TS_COLOR7_MAP = 0x13, - TS_COLOR8_MAP = 0x14, - TS_COLOR9_MAP = 0x15, - TS_COLOR10_MAP = 0x16, - TS_COLOR11_MAP = 0x17, - TS_COLOR12_MAP = 0x18, - TS_COLOR13_MAP = 0x19, - TS_COLOR14_MAP = 0x1A, - TS_COLOR15_MAP = 0x1B, - TS_THROW_MAP = 0x1C, - }; - - enum ImageCategory - { - IMG_CATEGORY_UNKNOWN = 0x0, - IMG_CATEGORY_AUTO_GENERATED = 0x1, - IMG_CATEGORY_LIGHTMAP = 0x2, - IMG_CATEGORY_LOAD_FROM_FILE = 0x3, - IMG_CATEGORY_RAW = 0x4, - IMG_CATEGORY_FIRST_UNMANAGED = 0x5, - IMG_CATEGORY_RENDERTARGET = 0x5, - IMG_CATEGORY_TEMP = 0x6, - }; - - struct GfxImage - { - GfxTexture texture; - char mapType; - char semantic; - char category; - bool delayLoadPixels; - Picmip picmip; - bool noPicmip; - char track; - CardMemory cardMemory; - uint16_t width; - uint16_t height; - uint16_t depth; - char levelCount; - char streaming; - unsigned int baseSize; - char* pixels; - GfxStreamedPartInfo streamedParts[1]; - char streamedPartCount; - unsigned int loadedSize; - char skippedMipLevels; - const char* name; - unsigned int hash; - }; - - struct SndAssetBankHeader - { - unsigned int magic; - unsigned int version; - unsigned int entrySize; - unsigned int checksumSize; - unsigned int dependencySize; - unsigned int entryCount; - unsigned int dependencyCount; - unsigned int pad32; - gcc_align(8) int64_t fileSize; - gcc_align(8) int64_t entryOffset; - gcc_align(8) int64_t checksumOffset; - char checksumChecksum[16]; - char dependencies[512]; - char padding[1464]; - }; +typedef tdef_align(16) char char16; +typedef tdef_align(32) char byte32; +typedef tdef_align(128) char byte128; + +typedef tdef_align(4) char char_align4; +typedef tdef_align(128) char char_align128; + +typedef tdef_align(16) char raw_byte16; +typedef tdef_align(128) char raw_byte128; + +typedef tdef_align(128) float float_align128; + +struct dvar_t; +struct MenuCell; +struct cplane_s; +struct cbrushside_t; +struct MaterialVertexDeclaration; +struct MaterialVertexShader; +struct MaterialPixelShader; +struct MaterialShaderArgument; +struct MaterialTechnique; +struct MaterialTechniqueSet; +struct GfxImageLoadDef; +struct GfxImage; +struct MaterialTextureDef; +struct MaterialConstantDef; +struct GfxStateBits; +struct Material; +struct MenuRow; +struct Glyph; +struct KerningPairs; +struct Font_s; +struct BrushWrapper; +struct multiDef_s; +struct XModelCollTri_s; +struct PhysConstraints; +struct ScriptCondition; +struct listBoxDef_s; +struct expressionRpn; +struct GenericEventScript; +struct GenericEventHandler; +struct animParamsDef_t; +struct enumDvarDef_s; +struct PhysPreset; +struct profileMultiDef_s; +struct PhysGeomInfo; +struct XModelCollSurf_s; +struct gameMsgDef_s; +struct SndAlias; +struct SndAliasList; +struct XBoneInfo; +struct editFieldDef_s; +struct WeaponCamoMaterial; +struct PhysGeomList; +struct textExp_s; +struct ItemKeyHandler; +struct focusItemDef_s; +struct textDef_s; +struct imageDef_s; +struct ownerDrawDef_s; +struct menuDef_t; +struct rectData_s; +struct UIAnimInfo; +struct itemDef_s; +struct WeaponCamoMaterialSet; +struct Collmap; +struct TracerDef; +struct WeaponAttachment; +struct DObjAnimMat; +struct GfxPackedVertex; +struct XSurfaceCollisionNode; +struct XSurfaceCollisionLeaf; +struct XSurfaceCollisionTree; +struct XRigidVertList; +struct XSurface; +struct XModel; +struct flameTable; +struct cStaticModel_s; +struct FxElemVelStateSample; +struct FxElemVisStateSample; +struct FxElemMarkVisuals; +struct FxEffectDef; +struct GfxLightDef; +union FxElemVisuals; +struct FxTrailVertex; +struct FxTrailDef; +struct FxSpotLightDef; +struct FxElemDef; +struct WeaponCamoSet; +struct WeaponCamo; +struct WeaponDef; +struct WeaponAttachmentUnique; +struct WeaponVariantDef; +struct cLeafBrushNode_s; +struct cbrush_t; +struct ClipMaterial; +struct Bounds; +struct cLeaf_s; +struct cmodel_t; +struct CollisionAabbTree; +struct pathlink_s; +struct pathnode_t; +struct DestructiblePiece; +struct DestructibleDef; +struct GraphFloat; +struct VehicleDef; +struct XAnimNotifyInfo; +struct XAnimPartTrans; +struct XAnimDeltaPartQuat2; +struct XAnimDeltaPartQuat; +struct XAnimDeltaPart; +struct XAnimParts; +struct ZBarrierDef; +struct GfxLight; +struct ddlHash_t; +struct ddlEnumDef_t; +struct SndVolumeGroup; +struct XModelPiece; +struct XModelPieces; +struct DynEntityDef; +struct CollisionPartition; +struct ddlMemberDef_t; +struct ddlStructDef_t; +struct ddlDef_t; +struct GlassDef; +struct Glass; +struct GfxAabbTree; +struct FxImpactEntry; +struct StringTableCell; +struct ddlRoot_t; +struct StringTable; +struct FxImpactTable; +struct SndIndexEntry; +struct SndRadverb; +struct SndDuck; +struct SndAssetBankEntry; +struct SndDialogScriptIdLookup; +struct SndBank; +struct SndPatch; +struct cNode_t; +struct TriggerModel; +struct TriggerHull; +struct TriggerSlab; +struct MapEnts; +struct DynEntityPose; +struct DynEntityClient; +struct DynEntityServer; +struct DynEntityColl; +struct rope_t; +struct clipMap_t; +struct ComPrimaryLight; +struct ComWorld; +struct pathbasenode_t; +struct pathnode_tree_t; +struct GameWorldSp; +struct GameWorldMp; +struct GfxStreamingAabbTree; +struct GfxLightCorona; +struct GfxShadowMapVolume; +struct GfxVolumePlane; +struct GfxExposureVolume; +struct GfxWorldFogVolume; +struct GfxWorldFogModifierVolume; +struct GfxLutVolume; +struct GfxPortal; +struct GfxCell; +struct GfxReflectionProbeVolumeData; +struct GfxReflectionProbe; +struct GfxLightmapArray; +struct GfxLightGridEntry; +struct GfxCompressedLightGridColors; +struct GfxCompressedLightGridCoeffs; +struct GfxSkyGridVolume; +struct GfxBrushModel; +struct MaterialMemory; +struct GfxSceneDynModel; +struct GfxSceneDynBrush; +struct SSkinShaders; +struct SSkinVert; +struct SSkinModel; +struct SSkinAnim; +struct SSkinInstance; +struct GfxShadowGeometry; +struct GfxLightRegionAxis; +struct GfxLightRegionHull; +struct GfxLightRegion; +struct GfxStaticModelInst; +struct GfxSurface; +struct GfxStaticModelDrawInst; +struct Occluder; +struct GfxOutdoorBounds; +struct GfxHeroLight; +struct GfxHeroLightTree; +struct GfxWorld; +struct FontIconEntry; +struct FontIconAlias; +struct FontIcon; +struct MenuList; +struct LocalizeEntry; +struct SndCurve; +struct SndPan; +struct SndDuckGroup; +struct SndContext; +struct SndMaster; +struct SndSidechainDuck; +struct SndFutz; +struct SndDriverGlobals; +struct RawFile; +struct LbColumnDef; +struct LeaderboardDef; +struct XGlobals; +struct Glasses; +struct EmblemSet; +struct ScriptParseTree; +struct KeyValuePair; +struct KeyValuePairs; +struct MemoryBlock; +struct AddonMapEnts; +struct SkinnedVertsDef; +struct Qdb; +struct Slug; +struct FootstepTableDef; +struct FootstepFXTableDef; + +enum XAssetType { + ASSET_TYPE_XMODELPIECES = 0x0, + ASSET_TYPE_PHYSPRESET = 0x1, + ASSET_TYPE_PHYSCONSTRAINTS = 0x2, + ASSET_TYPE_DESTRUCTIBLEDEF = 0x3, + ASSET_TYPE_XANIMPARTS = 0x4, + ASSET_TYPE_XMODEL = 0x5, + ASSET_TYPE_MATERIAL = 0x6, + ASSET_TYPE_TECHNIQUE_SET = 0x7, + ASSET_TYPE_IMAGE = 0x8, + ASSET_TYPE_SOUND = 0x9, + ASSET_TYPE_SOUND_PATCH = 0xA, + ASSET_TYPE_CLIPMAP = 0xB, + ASSET_TYPE_CLIPMAP_PVS = 0xC, + ASSET_TYPE_COMWORLD = 0xD, + ASSET_TYPE_GAMEWORLD_SP = 0xE, + ASSET_TYPE_GAMEWORLD_MP = 0xF, + ASSET_TYPE_MAP_ENTS = 0x10, + ASSET_TYPE_GFXWORLD = 0x11, + ASSET_TYPE_LIGHT_DEF = 0x12, + ASSET_TYPE_UI_MAP = 0x13, + ASSET_TYPE_FONT = 0x14, + ASSET_TYPE_FONTICON = 0x15, + ASSET_TYPE_MENULIST = 0x16, + ASSET_TYPE_MENU = 0x17, + ASSET_TYPE_LOCALIZE_ENTRY = 0x18, + ASSET_TYPE_WEAPON = 0x19, + ASSET_TYPE_WEAPONDEF = 0x1A, + ASSET_TYPE_WEAPON_VARIANT = 0x1B, + ASSET_TYPE_WEAPON_FULL = 0x1C, + ASSET_TYPE_ATTACHMENT = 0x1D, + ASSET_TYPE_ATTACHMENT_UNIQUE = 0x1E, + ASSET_TYPE_WEAPON_CAMO = 0x1F, + ASSET_TYPE_SNDDRIVER_GLOBALS = 0x20, + ASSET_TYPE_FX = 0x21, + ASSET_TYPE_IMPACT_FX = 0x22, + ASSET_TYPE_AITYPE = 0x23, + ASSET_TYPE_MPTYPE = 0x24, + ASSET_TYPE_MPBODY = 0x25, + ASSET_TYPE_MPHEAD = 0x26, + ASSET_TYPE_CHARACTER = 0x27, + ASSET_TYPE_XMODELALIAS = 0x28, + ASSET_TYPE_RAWFILE = 0x29, + ASSET_TYPE_STRINGTABLE = 0x2A, + ASSET_TYPE_LEADERBOARD = 0x2B, + ASSET_TYPE_XGLOBALS = 0x2C, + ASSET_TYPE_DDL = 0x2D, + ASSET_TYPE_GLASSES = 0x2E, + ASSET_TYPE_EMBLEMSET = 0x2F, + ASSET_TYPE_SCRIPTPARSETREE = 0x30, + ASSET_TYPE_KEYVALUEPAIRS = 0x31, + ASSET_TYPE_VEHICLEDEF = 0x32, + ASSET_TYPE_MEMORYBLOCK = 0x33, + ASSET_TYPE_ADDON_MAP_ENTS = 0x34, + ASSET_TYPE_TRACER = 0x35, + ASSET_TYPE_SKINNEDVERTS = 0x36, + ASSET_TYPE_QDB = 0x37, + ASSET_TYPE_SLUG = 0x38, + ASSET_TYPE_FOOTSTEP_TABLE = 0x39, + ASSET_TYPE_FOOTSTEPFX_TABLE = 0x3A, + ASSET_TYPE_ZBARRIER = 0x3B, + ASSET_TYPE_COUNT = 0x3C, + ASSET_TYPE_STRING = 0x3C, + ASSET_TYPE_ASSETLIST = 0x3D, + ASSET_TYPE_REPORT = 0x3E, + ASSET_TYPE_DEPEND = 0x3F, + ASSET_TYPE_FULL_COUNT = 0x40, +}; + +enum XFileBlock { + XFILE_BLOCK_TEMP, + XFILE_BLOCK_RUNTIME_VIRTUAL, + XFILE_BLOCK_RUNTIME_PHYSICAL, + XFILE_BLOCK_DELAY_VIRTUAL, + XFILE_BLOCK_DELAY_PHYSICAL, + XFILE_BLOCK_VIRTUAL, + XFILE_BLOCK_PHYSICAL, + XFILE_BLOCK_STREAMER_RESERVE, + MAX_XFILE_COUNT, +}; + +union XAssetHeader { + // XModelPieces *xmodelPieces; // Not an asset + PhysPreset *physPreset; + PhysConstraints *physConstraints; + DestructibleDef *destructibleDef; + XAnimParts *parts; + XModel *model; + Material *material; + // MaterialPixelShader *pixelShader; // Not an asset + // MaterialVertexShader *vertexShader; // Not an asset + MaterialTechniqueSet *techniqueSet; + GfxImage *image; + SndBank *sound; + SndPatch *soundPatch; + clipMap_t *clipMap; + ComWorld *comWorld; + GameWorldSp *gameWorldSp; + GameWorldMp *gameWorldMp; + MapEnts *mapEnts; + GfxWorld *gfxWorld; + GfxLightDef *lightDef; + Font_s *font; + FontIcon *fontIcon; + MenuList *menuList; + menuDef_t *menu; + LocalizeEntry *localize; + WeaponVariantDef *weapon; + WeaponAttachment *attachment; + WeaponAttachmentUnique *attachmentUnique; + WeaponCamo *weaponCamo; + SndDriverGlobals *sndDriverGlobals; + FxEffectDef *fx; + FxImpactTable *impactFx; + RawFile *rawfile; + StringTable *stringTable; + LeaderboardDef *leaderboardDef; + XGlobals *xGlobals; + ddlRoot_t *ddlRoot; + Glasses *glasses; + // TextureList *textureList; // Does not exist in this game + EmblemSet *emblemSet; + ScriptParseTree *scriptParseTree; + KeyValuePairs *keyValuePairs; + VehicleDef *vehicleDef; + MemoryBlock *memoryBlock; + AddonMapEnts *addonMapEnts; + TracerDef *tracerDef; + SkinnedVertsDef *skinnedVertsDef; + Qdb *qdb; + Slug *slug; + FootstepTableDef *footstepTableDef; + FootstepFXTableDef *footstepFXTableDef; + ZBarrierDef *zbarrierDef; + void *data; +}; + +union vec2_t { + float v[2]; + + struct { + float x; + float y; + }; +}; + +union vec3_t { + struct { + float x; + float y; + float z; + }; + + float v[3]; +}; + +union vec4_t { + float v[4]; + + struct { + float x; + float y; + float z; + float w; + }; + + struct { + float r; + float g; + float b; + float a; + }; +}; + +struct XModelPieces { + const char *name; + int numpieces; + XModelPiece *pieces; +}; + +struct PhysPresetInfo { + float mass; + float bounce; + float friction; + int isFrictionInfinity; + float bulletForceScale; + float explosiveForceScale; + float piecesSpreadFraction; + float piecesUpwardVelocity; + int canFloat; + float gravityScale; + vec3_t centerOfMassOffset; + vec3_t buoyancyBoxMin; + vec3_t buoyancyBoxMax; +}; + +struct PhysPreset { + const char *name; + int flags; + float mass; + float bounce; + float friction; + float bulletForceScale; + float explosiveForceScale; + const char *sndAliasPrefix; + float piecesSpreadFraction; + float piecesUpwardVelocity; + int canFloat; + float gravityScale; + vec3_t centerOfMassOffset; + vec3_t buoyancyBoxMin; + vec3_t buoyancyBoxMax; +}; + +enum ConstraintType { + CONSTRAINT_NONE = 0x0, + CONSTRAINT_POINT = 0x1, + CONSTRAINT_DISTANCE = 0x2, + CONSTRAINT_HINGE = 0x3, + CONSTRAINT_JOINT = 0x4, + CONSTRAINT_ACTUATOR = 0x5, + CONSTRAINT_FAKE_SHAKE = 0x6, + CONSTRAINT_LAUNCH = 0x7, + CONSTRAINT_ROPE = 0x8, + CONSTRAINT_LIGHT = 0x9, + NUM_CONSTRAINT_TYPES = 0xA, +}; + +enum AttachPointType { + ATTACH_POINT_WORLD = 0x0, + ATTACH_POINT_DYNENT = 0x1, + ATTACH_POINT_ENT = 0x2, + ATTACH_POINT_BONE = 0x3, +}; + +struct PhysConstraint { + uint16_t targetname; + ConstraintType type; + AttachPointType attach_point_type1; + int target_index1; + uint16_t target_ent1; + const char *target_bone1; + AttachPointType attach_point_type2; + int target_index2; + uint16_t target_ent2; + const char *target_bone2; + vec3_t offset; + vec3_t pos; + vec3_t pos2; + vec3_t dir; + int flags; + int timeout; + int min_health; + int max_health; + float distance; + float damp; + float power; + vec3_t scale; + float spin_scale; + float minAngle; + float maxAngle; + Material *material; + int constraintHandle; + int rope_index; + int centity_num[4]; +}; + +struct PhysConstraints { + const char *name; + unsigned int count; + PhysConstraint data[16]; +}; + +struct DestructibleDef { + const char *name; + XModel *model; + XModel *pristineModel; + int numPieces; + DestructiblePiece *pieces; + int clientOnly; +}; + +union XAnimIndices { + char *_1; + uint16_t *_2; + void *data; +}; + +struct XAnimParts { + const char *name; + uint16_t dataByteCount; + uint16_t dataShortCount; + uint16_t dataIntCount; + uint16_t randomDataByteCount; + uint16_t randomDataIntCount; + uint16_t numframes; + bool bLoop; + bool bDelta; + bool bDelta3D; + bool bLeftHandGripIK; + unsigned int streamedFileSize; + unsigned char boneCount[10]; + unsigned char notifyCount; + char assetType; + bool isDefault; + unsigned int randomDataShortCount; + unsigned int indexCount; + float framerate; + float frequency; + float primedLength; + float loopEntryTime; + uint16_t *names; + char *dataByte; + int16_t *dataShort; + int *dataInt; + int16_t *randomDataShort; + char *randomDataByte; + int *randomDataInt; + XAnimIndices indices; + XAnimNotifyInfo *notify; + XAnimDeltaPart *deltaPart; +}; + +struct DObjSkelMat { + vec4_t axis[3]; + vec4_t origin; +}; + +struct XModelLodInfo { + float dist; + uint16_t numsurfs; + uint16_t surfIndex; + int partBits[5]; +}; + +struct XModel { + const char *name; + unsigned char numBones; + unsigned char numRootBones; + unsigned char numsurfs; + char lodRampType; + uint16_t *boneNames; + unsigned char *parentList; + uint16_t (*quats)[4]; + float (*trans)[4]; + char *partClassification; + DObjAnimMat *baseMat; + XSurface *surfs; + Material **materialHandles; + XModelLodInfo lodInfo[4]; + XModelCollSurf_s *collSurfs; + int numCollSurfs; + int contents; + XBoneInfo *boneInfo; + float radius; + vec3_t mins; + vec3_t maxs; + uint16_t numLods; + uint16_t collLod; + float *himipInvSqRadii; + int memUsage; + int flags; + bool bad; + PhysPreset *physPreset; + unsigned char numCollmaps; + Collmap *collmaps; + PhysConstraints *physConstraints; + vec3_t lightingOriginOffset; + float lightingOriginRange; +}; + +struct gcc_align(8) GfxDrawSurfFields { + uint64_t objectId : 16; + uint64_t customIndex : 9; + uint64_t reflectionProbeIndex : 5; + uint64_t dlightMask : 2; + uint64_t materialSortedIndex : 12; + uint64_t primaryLightIndex : 8; + uint64_t surfType : 4; + uint64_t prepass : 2; + uint64_t primarySortKey : 6; +}; + +union GfxDrawSurf { + gcc_align(8) GfxDrawSurfFields fields; + gcc_align(8) uint64_t packed; +}; + +struct type_align(8) MaterialInfo { + const char *name; + unsigned int gameFlags; + char pad; + char sortKey; + char textureAtlasRowCount; + char textureAtlasColumnCount; + GfxDrawSurf drawSurf; + unsigned int surfaceTypeBits; + unsigned int layeredSurfaceTypes; + uint16_t hashIndex; + int surfaceFlags; + int contents; +}; + +typedef tdef_align(8) GfxStateBits GfxStateBitsTable; + +struct Material { + MaterialInfo info; + char stateBitsEntry[36]; + unsigned char textureCount; + unsigned char constantCount; + unsigned char stateBitsCount; + char stateFlags; + char cameraRegion; + char probeMipBits; + MaterialTechniqueSet *techniqueSet; + MaterialTextureDef *textureTable; + MaterialConstantDef *constantTable; + GfxStateBitsTable *stateBitsTable; + Material *thermalMaterial; +}; + +struct GfxPixelShaderLoadDef { + char *program; + unsigned int programSize; +}; + +struct MaterialPixelShaderProgram { + void /*ID3D11PixelShader*/ *ps; + GfxPixelShaderLoadDef loadDef; +}; + +struct MaterialPixelShader { + const char *name; + MaterialPixelShaderProgram prog; +}; + +struct GfxVertexShaderLoadDef { + char *program; + unsigned int programSize; +}; + +struct MaterialVertexShaderProgram { + void /*ID3D11VertexShader*/ *vs; + GfxVertexShaderLoadDef loadDef; +}; + +struct MaterialVertexShader { + const char *name; + MaterialVertexShaderProgram prog; +}; + +struct MaterialTechniqueSet { + const char *name; + char worldVertFormat; + MaterialTechnique *techniques[36]; +}; + +union GfxTexture { + void /*ID3D11ShaderResourceView*/ *basemap; + Texture *texture; + GfxImageLoadDef *loadDef; +}; + +struct Picmip { + char platform[2]; +}; + +struct CardMemory { + int platform[2]; +}; + +struct GfxStreamedPartInfo { + unsigned int levelCountAndSize; + unsigned int hash; + uint16_t width; + uint16_t height; + uint32_t offset : 32; + uint32_t size : 28; + uint32_t ipakIndex : 4; + uint32_t adjacentLeft : 15; + uint32_t adjacentRight : 15; + uint32_t compressed : 1; + uint32_t valid : 1; +}; + +enum TextureSemantic { + TS_2D = 0x0, + TS_FUNCTION = 0x1, + TS_COLOR_MAP = 0x2, + TS_UNUSED_1 = 0x3, + TS_UNUSED_2 = 0x4, + TS_NORMAL_MAP = 0x5, + TS_UNUSED_3 = 0x6, + TS_UNUSED_4 = 0x7, + TS_SPECULAR_MAP = 0x8, + TS_UNUSED_5 = 0x9, + TS_OCCLUSION_MAP = 0xA, + TS_UNUSED_6 = 0xB, + TS_COLOR0_MAP = 0xC, + TS_COLOR1_MAP = 0xD, + TS_COLOR2_MAP = 0xE, + TS_COLOR3_MAP = 0xF, + TS_COLOR4_MAP = 0x10, + TS_COLOR5_MAP = 0x11, + TS_COLOR6_MAP = 0x12, + TS_COLOR7_MAP = 0x13, + TS_COLOR8_MAP = 0x14, + TS_COLOR9_MAP = 0x15, + TS_COLOR10_MAP = 0x16, + TS_COLOR11_MAP = 0x17, + TS_COLOR12_MAP = 0x18, + TS_COLOR13_MAP = 0x19, + TS_COLOR14_MAP = 0x1A, + TS_COLOR15_MAP = 0x1B, + TS_THROW_MAP = 0x1C, +}; + +enum ImageCategory { + IMG_CATEGORY_UNKNOWN = 0x0, + IMG_CATEGORY_AUTO_GENERATED = 0x1, + IMG_CATEGORY_LIGHTMAP = 0x2, + IMG_CATEGORY_LOAD_FROM_FILE = 0x3, + IMG_CATEGORY_RAW = 0x4, + IMG_CATEGORY_FIRST_UNMANAGED = 0x5, + IMG_CATEGORY_RENDERTARGET = 0x5, + IMG_CATEGORY_TEMP = 0x6, +}; + +struct GfxImage { + GfxTexture texture; + char mapType; + char semantic; + char category; + bool delayLoadPixels; + Picmip picmip; + bool noPicmip; + char track; + CardMemory cardMemory; + uint16_t width; + uint16_t height; + uint16_t depth; + char levelCount; + char streaming; + unsigned int baseSize; + char *pixels; + GfxStreamedPartInfo streamedParts[1]; + char streamedPartCount; + unsigned int loadedSize; + char skippedMipLevels; + const char *name; + unsigned int hash; +}; + +struct SndAssetBankHeader { + unsigned int magic; + unsigned int version; + unsigned int entrySize; + unsigned int checksumSize; + unsigned int dependencySize; + unsigned int entryCount; + unsigned int dependencyCount; + unsigned int pad32; + gcc_align(8) int64_t fileSize; + gcc_align(8) int64_t entryOffset; + gcc_align(8) int64_t checksumOffset; + char checksumChecksum[16]; + char dependencies[512]; + char padding[1464]; +}; #pragma pack(push, 1) - struct type_align(2) SndRuntimeAssetBank - { - const char* zone; - const char* language; - int fileHandle; - SndAssetBankHeader header; - unsigned int entryOffset; - char linkTimeChecksum[16]; - char filename[256]; - bool indicesLoaded; - bool indicesAllocated; - }; +struct type_align(2) SndRuntimeAssetBank { + const char *zone; + const char *language; + int fileHandle; + SndAssetBankHeader header; + unsigned int entryOffset; + char linkTimeChecksum[16]; + char filename[256]; + bool indicesLoaded; + bool indicesAllocated; +}; #pragma pack(pop) - typedef tdef_align(2048) char SndChar2048; - - - struct SndLoadedAssets - { - const char* zone; - const char* language; - unsigned int loadedCount; - unsigned int entryCount; - SndAssetBankEntry* entries; - unsigned int dataSize; - SndChar2048* data; - }; - - - enum SndBankState - { - SND_BANK_STATE_NEW = 0x0, - SND_BANK_STATE_STREAM_HEADER = 0x1, - SND_BANK_STATE_STREAM_TOC = 0x2, - SND_BANK_STATE_LOADED_HEADER = 0x3, - SND_BANK_STATE_LOADED_TOC = 0x4, - SND_BANK_STATE_LOADED_ASSET_WAIT = 0x5, - SND_BANK_STATE_LOADED_ASSETS = 0x6, - SND_BANK_STATE_READY_TO_USE = 0x7, - SND_BANK_STATE_ERROR = 0x8, - }; - - - struct SndBank - { - const char* name; - unsigned int aliasCount; - SndAliasList* alias; - SndIndexEntry* aliasIndex; - unsigned int radverbCount; - SndRadverb* radverbs; - unsigned int duckCount; - SndDuck* ducks; - SndRuntimeAssetBank streamAssetBank; - SndRuntimeAssetBank loadAssetBank; - SndLoadedAssets loadedAssets; - unsigned int scriptIdLookupCount; - SndDialogScriptIdLookup* scriptIdLookups; - SndBankState state; - int streamRequestId; - bool pendingIo; - bool ioError; - bool runtimeAssetLoad; - }; - - - struct SndPatch - { - const char* name; - unsigned int elementCount; - unsigned int* elements; - }; - - typedef unsigned short LeafBrush; - typedef tdef_align(128) cbrush_t cbrush_array_t; - typedef tdef_align(128) Bounds BoundsArray; - - - struct ClipInfo - { - int planeCount; - cplane_s* planes; - unsigned int numMaterials; - ClipMaterial* materials; - unsigned int numBrushSides; - cbrushside_t* brushsides; - unsigned int leafbrushNodesCount; - cLeafBrushNode_s* leafbrushNodes; - unsigned int numLeafBrushes; - LeafBrush* leafbrushes; - unsigned int numBrushVerts; - vec3_t* brushVerts; - unsigned int nuinds; - uint16_t* uinds; - uint16_t numBrushes; - cbrush_array_t* brushes; - BoundsArray* brushBounds; - int* brushContents; - }; - - - struct type_align(4) cLeaf_s - { - uint16_t firstCollAabbIndex; - uint16_t collAabbCount; - int brushContents; - int terrainContents; - vec3_t mins; - vec3_t maxs; - int leafBrushNode; - int16_t cluster; - }; - - - struct cmodel_t - { - vec3_t mins; - vec3_t maxs; - float radius; - ClipInfo* info; - cLeaf_s leaf; - }; - - - struct clipMap_t - { - const char* name; - int isInUse; - ClipInfo info; - ClipInfo* pInfo; - unsigned int numStaticModels; - cStaticModel_s* staticModelList; - unsigned int numNodes; - cNode_t* nodes; - unsigned int numLeafs; - cLeaf_s* leafs; - unsigned int vertCount; - vec3_t* verts; - int triCount; - uint16_t (*triIndices)[3]; - char* triEdgeIsWalkable; // Saved as 1 bit per edge rounded up to the next 4 bytes - int partitionCount; - CollisionPartition* partitions; - int aabbTreeCount; - CollisionAabbTree* aabbTrees; - unsigned int numSubModels; - cmodel_t* cmodels; - int numClusters; - int clusterBytes; - char* visibility; - int vised; - MapEnts* mapEnts; - cbrush_t* box_brush; - cmodel_t box_model; - uint16_t originalDynEntCount; - uint16_t dynEntCount[4]; - DynEntityDef* dynEntDefList[2]; - DynEntityPose* dynEntPoseList[2]; - DynEntityClient* dynEntClientList[2]; - DynEntityServer* dynEntServerList[2]; - DynEntityColl* dynEntCollList[4]; - int num_constraints; - PhysConstraint* constraints; - int max_ropes; - rope_t* ropes; - unsigned int checksum; - }; - - - struct ComWorld - { - const char* name; - int isInUse; - unsigned int primaryLightCount; - ComPrimaryLight* primaryLights; - }; - - - struct PathData - { - unsigned int nodeCount; - unsigned int originalNodeCount; - pathnode_t* nodes; - pathbasenode_t* basenodes; - int visBytes; - char* pathVis; - int smoothBytes; - char* smoothCache; - int nodeTreeCount; - pathnode_tree_t* nodeTree; - }; - - - struct GameWorldSp - { - const char* name; - PathData path; - }; - - - struct GameWorldMp - { - const char* name; - PathData path; - }; - - - struct MapTriggers - { - unsigned int count; - TriggerModel* models; - unsigned int hullCount; - TriggerHull* hulls; - unsigned int slabCount; - TriggerSlab* slabs; - }; - - - struct MapEnts - { - const char* name; - char* entityString; - int numEntityChars; - MapTriggers trigger; - }; - - - struct GfxWorldStreamInfo - { - int aabbTreeCount; - GfxStreamingAabbTree* aabbTrees; - int leafRefCount; - int* leafRefs; - }; - - struct GfxWorldSun - { - unsigned int control; - vec3_t angles; - vec4_t ambientColor; - vec4_t sunCd; - vec4_t sunCs; - vec4_t skyColor; - float exposure; - }; - - - struct GfxWorldFog - { - float baseDist; - float halfDist; - float baseHeight; - float halfHeight; - float sunFogPitch; - float sunFogYaw; - float sunFogInner; - float sunFogOuter; - vec3_t fogColor; - float fogOpacity; - vec3_t sunFogColor; - float sunFogOpacity; - }; - - - struct SunLightParseParams - { - char name[64]; - GfxWorldSun initWorldSun[1]; - float fogTransitionTime; - GfxWorldFog initWorldFog[1]; - }; - - - struct GfxSkyDynamicIntensity - { - float angle0; - float angle1; - float factor0; - float factor1; - }; - - - struct GfxWorldDpvsPlanes - { - int cellCount; - cplane_s* planes; - uint16_t* nodes; - unsigned int* sceneEntCellBits; - }; - - - struct GfxWorldVertexData0 - { - byte128* data; - void/*ID3D11Buffer*/* vb; - }; - - - struct GfxWorldVertexData1 - { - byte128* data; - void/*ID3D11Buffer*/* vb; - }; - - - struct GfxWorldDraw - { - unsigned int reflectionProbeCount; - GfxReflectionProbe* reflectionProbes; - GfxTexture* reflectionProbeTextures; - int lightmapCount; - GfxLightmapArray* lightmaps; - GfxTexture* lightmapPrimaryTextures; - GfxTexture* lightmapSecondaryTextures; - unsigned int vertexCount; - unsigned int vertexDataSize0; - GfxWorldVertexData0 vd0; - unsigned int vertexDataSize1; - GfxWorldVertexData1 vd1; - int indexCount; - uint16_t* indices; - void/*ID3D11Buffer*/* indexBuffer; - }; - - typedef tdef_align(4) char aligned_byte_pointer; - typedef tdef_align(4) GfxCompressedLightGridCoeffs GfxCompressedLightGridCoeffs_align4; - - struct GfxLightGrid - { - unsigned int sunPrimaryLightIndex; - uint16_t mins[3]; - uint16_t maxs[3]; - float offset; - unsigned int rowAxis; - unsigned int colAxis; - uint16_t* rowDataStart; - unsigned int rawRowDataSize; - aligned_byte_pointer* rawRowData; - unsigned int entryCount; - GfxLightGridEntry* entries; - unsigned int colorCount; - GfxCompressedLightGridColors* colors; - unsigned int coeffCount; - GfxCompressedLightGridCoeffs_align4* coeffs; - unsigned int skyGridVolumeCount; - GfxSkyGridVolume* skyGridVolumes; - }; - - - struct sunflare_t - { - bool hasValidData; - Material* spriteMaterial; - Material* flareMaterial; - float spriteSize; - float flareMinSize; - float flareMinDot; - float flareMaxSize; - float flareMaxDot; - float flareMaxAlpha; - int flareFadeInTime; - int flareFadeOutTime; - float blindMinDot; - float blindMaxDot; - float blindMaxDarken; - int blindFadeInTime; - int blindFadeOutTime; - float glareMinDot; - float glareMaxDot; - float glareMaxLighten; - int glareFadeInTime; - int glareFadeOutTime; - vec3_t sunFxPosition; - }; - - typedef tdef_align(4) GfxDrawSurf GfxDrawSurf_align4; - - - struct GfxWorldDpvsStatic - { - unsigned int smodelCount; - unsigned int staticSurfaceCount; - unsigned int litSurfsBegin; - unsigned int litSurfsEnd; - unsigned int litTransSurfsBegin; - unsigned int litTransSurfsEnd; - unsigned int emissiveOpaqueSurfsBegin; - unsigned int emissiveOpaqueSurfsEnd; - unsigned int emissiveTransSurfsBegin; - unsigned int emissiveTransSurfsEnd; - unsigned int smodelVisDataCount; - unsigned int surfaceVisDataCount; - raw_byte128* smodelVisData[3]; - raw_byte128* surfaceVisData[3]; - raw_byte128* smodelVisDataCameraSaved; - raw_byte128* surfaceVisDataCameraSaved; - uint16_t* sortedSurfIndex; - GfxStaticModelInst* smodelInsts; - GfxSurface* surfaces; - GfxStaticModelDrawInst* smodelDrawInsts; - GfxDrawSurf_align4* surfaceMaterials; - raw_byte128* surfaceCastsSunShadow; - raw_byte128* surfaceCastsShadow; - raw_byte128* smodelCastsShadow; - volatile int usageCount; - }; - - - struct GfxWorldDpvsDynamic - { - unsigned int dynEntClientWordCount[2]; - unsigned int dynEntClientCount[2]; - unsigned int* dynEntCellBits[2]; - raw_byte16* dynEntVisData[2][3]; - volatile int usageCount; - }; - - - struct GfxWaterBuffer - { - unsigned int bufferSize; - vec4_t* buffer; - }; - - - struct GfxWorld - { - const char* name; - const char* baseName; - int planeCount; - int nodeCount; - int surfaceCount; - GfxWorldStreamInfo streamInfo; - const char* skyBoxModel; - SunLightParseParams sunParse; - GfxLight* sunLight; - unsigned int sunPrimaryLightIndex; - unsigned int primaryLightCount; - unsigned int coronaCount; - GfxLightCorona* coronas; - unsigned int shadowMapVolumeCount; - GfxShadowMapVolume* shadowMapVolumes; - unsigned int shadowMapVolumePlaneCount; - GfxVolumePlane* shadowMapVolumePlanes; - unsigned int exposureVolumeCount; - GfxExposureVolume* exposureVolumes; - unsigned int exposureVolumePlaneCount; - GfxVolumePlane* exposureVolumePlanes; - unsigned int worldFogVolumeCount; - GfxWorldFogVolume* worldFogVolumes; - unsigned int worldFogVolumePlaneCount; - GfxVolumePlane* worldFogVolumePlanes; - unsigned int worldFogModifierVolumeCount; - GfxWorldFogModifierVolume* worldFogModifierVolumes; - unsigned int worldFogModifierVolumePlaneCount; - GfxVolumePlane* worldFogModifierVolumePlanes; - unsigned int lutVolumeCount; - GfxLutVolume* lutVolumes; - unsigned int lutVolumePlaneCount; - GfxVolumePlane* lutVolumePlanes; - GfxSkyDynamicIntensity skyDynIntensity; - GfxWorldDpvsPlanes dpvsPlanes; - int cellBitsCount; - GfxCell* cells; - GfxWorldDraw draw; - GfxLightGrid lightGrid; - int modelCount; - GfxBrushModel* models; - vec3_t mins; - vec3_t maxs; - unsigned int checksum; - int materialMemoryCount; - MaterialMemory* materialMemory; - sunflare_t sun; - vec4_t outdoorLookupMatrix[4]; - GfxImage* outdoorImage; - unsigned int* cellCasterBits; - GfxSceneDynModel* sceneDynModel; - GfxSceneDynBrush* sceneDynBrush; - unsigned int* primaryLightEntityShadowVis; - unsigned int* primaryLightDynEntShadowVis[2]; - unsigned int numSiegeSkinInsts; - SSkinInstance* siegeSkinInsts; - GfxShadowGeometry* shadowGeom; - GfxLightRegion* lightRegion; - GfxWorldDpvsStatic dpvs; - GfxWorldDpvsDynamic dpvsDyn; - float waterDirection; - GfxWaterBuffer waterBuffers[2]; - Material* waterMaterial; - Material* coronaMaterial; - Material* ropeMaterial; - Material* lutMaterial; - unsigned int numOccluders; - Occluder* occluders; - unsigned int numOutdoorBounds; - GfxOutdoorBounds* outdoorBounds; - unsigned int heroLightCount; - unsigned int heroLightTreeCount; - GfxHeroLight* heroLights; - GfxHeroLightTree* heroLightTree; - unsigned int lightingFlags; - int lightingQuality; - }; - - - struct type_align(4) GfxLightImage - { - GfxImage* image; - char samplerState; - }; - - - struct GfxLightDef - { - const char* name; - GfxLightImage attenuation; - int lmapLookupStart; - }; - - - struct Font_s - { - const char* fontName; - int pixelHeight; - int isScalingAllowed; - int glyphCount; - int kerningPairsCount; - Material* material; - Material* glowMaterial; - Glyph* glyphs; - KerningPairs* kerningPairs; - }; - - - struct FontIcon - { - const char* name; - int numEntries; - int numAliasEntries; - FontIconEntry* fontIconEntry; - FontIconAlias* fontIconAlias; - }; - - - struct MenuList - { - const char* name; - int menuCount; - menuDef_t** menus; - }; - - - struct rectDef_s - { - float x; - float y; - float w; - float h; - int horzAlign; - int vertAlign; - }; - - - struct windowDef_t - { - const char* name; - rectDef_s rect; - rectDef_s rectClient; - const char* group; - char style; - char border; - char modal; - char frameSides; - float frameTexSize; - float frameSize; - int ownerDraw; - int ownerDrawFlags; - float borderSize; - int staticFlags; - int dynamicFlags[1]; - int nextTime; - vec4_t foreColor; - vec4_t backColor; - vec4_t borderColor; - vec4_t outlineColor; - float rotation; - Material* background; - }; - - - struct ExpressionStatement - { - char* filename; - int line; - int numRpn; - expressionRpn* rpn; - }; - - - struct type_align(8) menuDef_t - { - windowDef_t window; - const char* font; - int fullScreen; - int ui3dWindowId; - int itemCount; - int fontIndex; - int cursorItem[1]; - int fadeCycle; - int priority; - float fadeClamp; - float fadeAmount; - float fadeInAmount; - float blurRadius; - int openSlideSpeed; - int closeSlideSpeed; - int openSlideDirection; - int closeSlideDirection; - rectDef_s initialRectInfo; - int openFadingTime; - int closeFadingTime; - int fadeTimeCounter; - int slideTimeCounter; - GenericEventHandler* onEvent; - ItemKeyHandler* onKey; - ExpressionStatement visibleExp; - gcc_align(8) uint64_t showBits; - gcc_align(8) uint64_t hideBits; - const char* allowedBinding; - const char* soundName; - int imageTrack; - int control; - vec4_t focusColor; - vec4_t disableColor; - ExpressionStatement rectXExp; - ExpressionStatement rectYExp; - itemDef_s** items; - }; - - - struct LocalizeEntry - { - const char* value; - const char* name; - }; - - - enum weaponIconRatioType_t - { - WEAPON_ICON_RATIO_1TO1 = 0x0, - WEAPON_ICON_RATIO_2TO1 = 0x1, - WEAPON_ICON_RATIO_4TO1 = 0x2, - WEAPON_ICON_RATIO_COUNT = 0x3, - }; - - enum eAttachment - { - ATTACHMENT_NONE = 0x0, - ATTACHMENT_ACOG = 0x1, - ATTACHMENT_DUALCLIP = 0x2, - ATTACHMENT_DUALOPTIC = 0x3, - ATTACHMENT_DW = 0x4, - ATTACHMENT_EXTBARREL = 0x5, - ATTACHMENT_EXTCLIP = 0x6, - ATTACHMENT_EXTRAMAGS = 0x7, - ATTACHMENT_FASTADS = 0x8, - ATTACHMENT_FASTRELOAD = 0x9, - ATTACHMENT_FMJ = 0xA, - ATTACHMENT_GL = 0xB, - ATTACHMENT_GRIP = 0xC, - ATTACHMENT_HOLO = 0xD, - ATTACHMENT_IR = 0xE, - ATTACHMENT_IRONSIGHTS = 0xF, - ATTACHMENT_LONGBREATH = 0x10, - ATTACHMENT_MK = 0x11, - ATTACHMENT_MMS = 0x12, - ATTACHMENT_RANGEFINDER = 0x13, - ATTACHMENT_REFLEX = 0x14, - ATTACHMENT_RF = 0x15, - ATTACHMENT_SELECTFIRE = 0x16, - ATTACHMENT_SILENCER = 0x17, - ATTACHMENT_STACKFIRE = 0x18, - ATTACHMENT_STALKER = 0x19, - ATTACHMENT_STEADYAIM = 0x1A, - ATTACHMENT_SWAYREDUC = 0x1B, - ATTACHMENT_TACKNIFE = 0x1C, - ATTACHMENT_VZOOM = 0x1D, - ATTACHMENT_TYPE_COUNT = 0x1E, - ATTACHMENT_INVALID = 0x1E, - }; - - - enum eAttachmentPoint - { - ATTACHMENT_POINT_NONE = 0x0, - ATTACHMENT_POINT_TOP = 0x1, - ATTACHMENT_POINT_FIRST = 0x1, - ATTACHMENT_POINT_BOTTOM = 0x2, - ATTACHMENT_POINT_TRIGGER = 0x3, - ATTACHMENT_POINT_MUZZLE = 0x4, - ATTACHMENT_POINT_GUNPERK = 0x5, - ATTACHMENT_POINT_COUNT = 0x6, - ATTACHMENT_POINT_INVALID = 0x6, - }; - - - enum PenetrateType - { - PENETRATE_TYPE_NONE = 0x0, - PENETRATE_TYPE_SMALL = 0x1, - PENETRATE_TYPE_MEDIUM = 0x2, - PENETRATE_TYPE_LARGE = 0x3, - PENETRATE_TYPE_COUNT = 0x4, - }; - - - enum weapFireType_t - { - WEAPON_FIRETYPE_FULLAUTO = 0x0, - WEAPON_FIRETYPE_SINGLESHOT = 0x1, - WEAPON_FIRETYPE_BURSTFIRE2 = 0x2, - WEAPON_FIRETYPE_BURSTFIRE3 = 0x3, - WEAPON_FIRETYPE_BURSTFIRE4 = 0x4, - WEAPON_FIRETYPE_BURSTFIRE5 = 0x5, - WEAPON_FIRETYPE_STACKED = 0x6, - WEAPON_FIRETYPE_MINIGUN = 0x7, - WEAPON_FIRETYPE_CHARGESHOT = 0x8, - WEAPON_FIRETYPE_JETGUN = 0x9, - WEAPON_FIRETYPECOUNT = 0xA, - }; - - enum eAttachmentOverrideSounds - { - ATTACHMENT_OVERRIDE_SOUND_FIRE, - ATTACHMENT_OVERRIDE_SOUND_FIRE_PLAYER, - ATTACHMENT_OVERRIDE_SOUND_FIRE_LOOP, - ATTACHMENT_OVERRIDE_SOUND_FIRE_LOOP_PLAYER, - ATTACHMENT_OVERRIDE_SOUND_FIRE_LOOP_END, - ATTACHMENT_OVERRIDE_SOUND_FIRE_LOOP_END_PLAYER, - ATTACHMENT_OVERRIDE_SOUND_FIRE_START, - ATTACHMENT_OVERRIDE_SOUND_FIRE_STOP, - ATTACHMENT_OVERRIDE_SOUND_FIRE_START_PLAYER, - ATTACHMENT_OVERRIDE_SOUND_FIRE_STOP_PLAYER, - ATTACHMENT_OVERRIDE_SOUND_FIRE_LAST, - ATTACHMENT_OVERRIDE_SOUND_FIRE_LAST_PLAYER, - - NUM_ATTACHMENT_OVERRIDE_SOUNDS - }; - - enum eAttachmentOverrideEffects - { - ATTACHMENT_OVERRIDE_EFFECT_VIEW_FLASH, - ATTACHMENT_OVERRIDE_EFFECT_WORLD_FLASH, - - NUM_ATTACHMENT_OVERRIDE_EFFECTS - }; - - struct WeaponAttachment - { - const char* szInternalName; - const char* szDisplayName; - eAttachment attachmentType; - eAttachmentPoint attachmentPoint; - PenetrateType penetrateType; - weapFireType_t fireType; - int firstRaisePriority; - float fHipIdleAmount; - bool bAltWeaponAdsOnly; - bool bAltWeaponDisableSwitching; - float altScopeADSTransInTime; - float altScopeADSTransOutTime; - bool bSilenced; - bool bDualMag; - bool laserSight; - bool bInfraRed; - bool bUseAsMelee; - bool bDualWield; - bool sharedAmmo; - float fDamageRangeScale; - float fAdsZoomFov1; - float fAdsZoomFov2; - float fAdsZoomFov3; - float fAdsZoomInFrac; - float fAdsZoomOutFrac; - float fAdsTransInTimeScale; - float fAdsTransOutTimeScale; - float fAdsRecoilReductionRate; - float fAdsRecoilReductionLimit; - float fAdsViewKickCenterSpeedScale; - float fAdsIdleAmountScale; - bool swayOverride; - float swayMaxAngle; - float swayLerpSpeed; - float swayPitchScale; - float swayYawScale; - float swayHorizScale; - float swayVertScale; - bool adsSwayOverride; - float adsSwayMaxAngle; - float adsSwayLerpSpeed; - float adsSwayPitchScale; - float adsSwayYawScale; - float fAdsSwayHorizScale; - float fAdsSwayVertScale; - float adsMoveSpeedScale; - float fHipSpreadMinScale; - float fHipSpreadMaxScale; - float strafeRotR; - float standMoveF; - vec3_t vStandRot; - float fFireTimeScale; - float fReloadTimeScale; - float fReloadEmptyTimeScale; - float fReloadAddTimeScale; - float fReloadQuickTimeScale; - float fReloadQuickEmptyTimeScale; - float fReloadQuickAddTimeScale; - bool mmsWeapon; - bool mmsInScope; - float mmsFOV; - float mmsAspect; - float mmsMaxDist; - float clipSizeScale; - int iClipSize; - unsigned int stackFire; - float stackFireSpread; - float stackFireAccuracyDecay; - unsigned int perks[2]; - float customFloat0; - float customFloat1; - float customFloat2; - int customBool0; - int customBool1; - int customBool2; - }; - - - enum weapOverlayReticle_t - { - WEAPOVERLAYRETICLE_NONE = 0x0, - WEAPOVERLAYRETICLE_CROSSHAIR = 0x1, - WEAPOVERLAYRETICLE_NUM = 0x2, - }; - - - struct WeaponAttachmentUnique - { - const char* szInternalName; - eAttachment attachmentType; - int siblingLink; - int childLink; - int combinedAttachmentTypeMask; - const char* szAltWeaponName; - unsigned int altWeaponIndex; - const char* szDualWieldWeaponName; - unsigned int dualWieldWeaponIndex; - uint16_t* hideTags; - XModel* viewModel; - XModel* viewModelAdditional; - XModel* viewModelADS; - XModel* worldModel; - XModel* worldModelAdditional; - const char* viewModelTag; - const char* worldModelTag; - vec3_t viewModelOffsets; - vec3_t worldModelOffsets; - vec3_t viewModelRotations; - vec3_t worldModelRotations; - vec3_t viewModelAddOffsets; - vec3_t worldModelAddOffsets; - vec3_t viewModelAddRotations; - vec3_t worldModelAddRotations; - WeaponCamo* weaponCamo; - bool disableBaseWeaponAttachment; - bool disableBaseWeaponClip; - bool overrideBaseWeaponAttachmentOffsets; - vec3_t viewModelOffsetBaseAttachment; - vec3_t worldModelOffsetBaseAttachment; - Material* overlayMaterial; - Material* overlayMaterialLowRes; - weapOverlayReticle_t overlayReticle; - int iFirstRaiseTime; - int iAltRaiseTime; - int iAltDropTime; - int iReloadAmmoAdd; - int iReloadStartAdd; - bool bSegmentedReload; - const char** szXAnims; - int animationOverrides[3]; - float* locationDamageMultipliers; - int soundOverrides; - const char* fireSound; - const char* fireSoundPlayer; - const char* fireLoopSound; - const char* fireLoopSoundPlayer; - const char* fireLoopEndSound; - const char* fireLoopEndSoundPlayer; - const char* fireStartSound; - const char* fireStopSound; - const char* fireStartSoundPlayer; - const char* fireStopSoundPlayer; - const char* fireLastSound; - const char* fireLastSoundPlayer; - const char* fireKillcamSound; - const char* fireKillcamSoundPlayer; - int effectOverrides; - FxEffectDef* viewFlashEffect; - FxEffectDef* worldFlashEffect; - TracerDef* tracerType; - TracerDef* enemyTracerType; - float adsDofStart; - float adsDofEnd; - int iAmmoIndex; - int iClipIndex; - bool bOverrideLeftHandIK; - bool bOverrideLeftHandProneIK; - vec3_t ikLeftHandOffset; - vec3_t ikLeftHandRotation; - vec3_t ikLeftHandProneOffset; - vec3_t ikLeftHandProneRotation; - float customFloat0; - float customFloat1; - float customFloat2; - int customBool0; - int customBool1; - int customBool2; - }; - - struct WeaponAttachmentUniqueFull - { - WeaponAttachmentUnique attachment; - const char* szXAnims[88]; - uint16_t hideTags[32]; - float locationDamageMultipliers[21]; - }; - - struct WeaponCamo - { - const char* name; - GfxImage* solidBaseImage; - GfxImage* patternBaseImage; - WeaponCamoSet* camoSets; - unsigned int numCamoSets; - WeaponCamoMaterialSet* camoMaterials; - unsigned int numCamoMaterials; - }; - - - struct SndDriverGlobals - { - const char* name; - unsigned int groupCount; - SndVolumeGroup* groups; - unsigned int curveCount; - SndCurve* curves; - unsigned int panCount; - SndPan* pans; - unsigned int duckGroupCount; - SndDuckGroup* duckGroups; - unsigned int contextCount; - SndContext* contexts; - unsigned int masterCount; - SndMaster* masters; - unsigned int voiceDuckCount; - SndSidechainDuck* voiceDucks; - unsigned int futzCount; - SndFutz* futzes; - }; - - - struct FxFloatRange - { - float base; - float amplitude; - }; - - - struct FxEffectDef - { - const char* name; - uint16_t flags; - char efPriority; - int16_t elemDefCountLooping; - int16_t elemDefCountOneShot; - int16_t elemDefCountEmission; - int totalSize; - int msecLoopingLife; - int msecNonLoopingLife; - FxElemDef* elemDefs; - vec3_t boundingBoxDim; - vec3_t boundingBoxCentre; - float occlusionQueryDepthBias; - int occlusionQueryFadeIn; - int occlusionQueryFadeOut; - FxFloatRange occlusionQueryScaleRange; - }; - - - struct FxImpactTable - { - const char* name; - FxImpactEntry* table; - }; - - - struct RawFile - { - const char* name; - int len; - const char16* buffer; - }; - - - struct StringTable - { - const char* name; - int columnCount; - int rowCount; - StringTableCell* values; - int16_t* cellIndex; - }; - - - enum LbUpdateType - { - LBUPDATE_TYPE_NORMAL = 0x0, - LBUPDATE_TYPE_RANK = 0x1, - LBUPDATE_TYPE_COMBINE = 0x2, - LBUPDATE_TYPE_COUNT = 0x3, - }; - - - struct LeaderboardDef - { - const char* name; - unsigned int id; - int columnCount; - int dwColumnCount; - int xpColId; - int prestigeColId; - LbColumnDef* columns; - LbUpdateType updateType; - int trackTypes; - }; - - - struct gump_info_t - { - char* name; - int size; - }; - - - struct overlay_info_t - { - char* name; - int size; - }; - - - struct XGlobals - { - const char* name; - int xanimStreamBufferSize; - int cinematicMaxWidth; - int cinematicMaxHeight; - int extracamResolution; - vec4_t screenClearColor; - int bigestGumpSize; - int gumpsCount; - gump_info_t gumps[32]; - int bigestOverlaySize; - int overlayCount; - overlay_info_t overlays[32]; - }; - - - struct ddlRoot_t - { - const char* name; - ddlDef_t* ddlDef; - }; - - - struct Glasses - { - const char* name; - unsigned int numGlasses; - Glass* glasses; - char* workMemory; - unsigned int workMemorySize; - unsigned int smallAllocatorBlocks; - unsigned int maxGroups; - unsigned int maxShards; - unsigned int maxPhysics; - unsigned int shardMemorySize; - unsigned int maxFreeCmd; - unsigned int numSlots; - unsigned int numVerts; - unsigned int numIndices; - }; - - - struct EmblemLayer - { - int cost; - int unlockLevel; - int unlockPLevel; - }; - - - struct EmblemCategory - { - const char* name; - const char* description; - }; - - - struct EmblemIconType - { - const char* name; - const char* description; - }; - - - struct EmblemBGCategory - { - const char* name; - const char* description; - }; - - - struct EmblemIcon - { - GfxImage* image; - const char* description; - float outlineSize; - int cost; - int unlockLevel; - int unlockPLevel; - int unclassifyAt; - int sortKey; - uint16_t iconType; - uint16_t category; - }; - - - struct EmblemBackground - { - Material* material; - const char* description; - int cost; - int unlockLevel; - int unlockPLevel; - int unclassifyAt; - int sortKey; - uint16_t bgCategory; - int mtxIndex; - }; - - - struct EmblemSet - { - int colorCount; - int layerCount; - EmblemLayer* layers; - int categoryCount; - EmblemCategory* categories; - int iconTypeCount; - EmblemIconType* iconTypes; - int bgCategoryCount; - EmblemBGCategory* bgCategories; - int iconCount; - EmblemIcon* icons; - int backgroundCount; - EmblemBackground* backgrounds; - int backgroundLookupCount; - int16_t* backgroundLookup; - }; - - - struct ScriptParseTree - { - const char* name; - int len; - byte32* buffer; - }; - - - struct KeyValuePairs - { - const char* name; - int numVariables; - KeyValuePair* keyValuePairs; - }; - - - struct view_limits_t - { - float horizSpanLeft; - float horizSpanRight; - float vertSpanUp; - float vertSpanDown; - float horizResistLeft; - float horizResistRight; - float vertResistUp; - float vertResistDown; - }; - - enum TractionType - { - TRACTION_TYPE_FRONT = 0x0, - TRACTION_TYPE_BACK = 0x1, - TRACTION_TYPE_ALL_WD = 0x2, - NUM_TRACTION_TYPES = 0x3, - }; - - - struct VehicleParameter - { - float m_speed_max; - float m_accel_max; - float m_reverse_scale; - float m_steer_angle_max; - float m_steer_angle_speed_scale; - float m_steer_speed; - float m_wheel_radius; - float m_susp_spring_k; - float m_susp_damp_k; - float m_susp_adj; - float m_susp_hard_limit; - float m_susp_min_height; - float m_tire_fric_fwd; - float m_tire_fric_side; - float m_tire_fric_brake; - float m_tire_fric_hand_brake; - float m_body_mass; - float m_roll_stability; - float m_pitch_stability; - float m_pitch_roll_resistance; - float m_yaw_resistance; - float m_upright_strength; - float m_tilt_fakey; - float m_peel_out_max_speed; - float m_tire_damp_coast; - float m_tire_damp_brake; - float m_tire_damp_hand; - float m_auto_hand_brake_min_speed; - TractionType m_traction_type; - const char* m_name; - vec3_t m_bbox_min; - vec3_t m_bbox_max; - vec3_t m_mass_center_offset; - vec3_t m_buoyancybox_min; - vec3_t m_buoyancybox_max; - float m_water_speed_max; - float m_water_accel_max; - float m_water_turn_accel; - float m_water_turn_speed_max; - float m_water_ebrake_power; - vec3_t m_boat_motor_offset; - float m_boat_speed_rise; - float m_boat_speed_tilt; - float m_boat_side_fric_scale; - float m_boat_forward_fric_scale; - float m_boat_vertical_fric_scale; - float m_jump_force; - float m_tire_fric_side_max; - bool m_drive_on_walls; - float m_linear_drag_scale; - float m_angular_drag_scale; - }; - - - struct VehicleDriveBySound - { - int apex; - const char* name; - unsigned int alias; - }; - - - struct VehicleEngineSound - { - const char* name; - unsigned int alias; - float params[5]; - }; - - - struct VehicleGearData - { - float minRPM; - float maxRPM; - float ratio; - }; - - - struct VehicleEngine - { - float idleRpms; - float maxRpms; - float maxTorque; - float brakingCoeff; - vec4_t loadFadeParams; - float loadScale; - float loadSmoothing; - float throttleLag; - float pitchScale; - VehicleEngineSound onload[5]; - VehicleEngineSound offload[5]; - int numGears; - int loopLastGear; - VehicleGearData gears[10]; - }; - - - struct VehicleAntenna - { - float springK; - float damp; - float length; - float gravity; - }; - - enum VehicleSeatPositions - { - VEH_POS_NONE = 0xFFFFFFFF, - VEH_POS_DRIVER = 0x0, - VEH_POS_MIN_GUNNER = 0x1, - VEH_POS_GUNNER_1 = 0x1, - VEH_POS_GUNNER_2 = 0x2, - VEH_POS_GUNNER_3 = 0x3, - VEH_POS_GUNNER_4 = 0x4, - VEH_POS_MAX_GUNNER = 0x4, - VEH_POS_MIN_PASSENGER = 0x5, - VEH_POS_PASSENGER_1 = 0x5, - VEH_POS_PASSENGER_2 = 0x6, - VEH_POS_PASSENGER_3 = 0x7, - VEH_POS_PASSENGER_4 = 0x8, - VEH_POS_PASSENGER_5 = 0x9, - VEH_POS_PASSENGER_6 = 0xA, - VEH_POS_MAX_PASSENGER = 0xA, - NUM_VEHICLE_POSITIONS = 0xB, - }; - - enum VehicleSound - { - VEH_TURRET_SPIN_SND = 0x0, - VEH_TURRET_STOP_SND = 0x1, - NUM_VEHICLE_SNDS = 0x2, - }; - - enum VehicleMaterialSound - { - VEH_WHEEL_ROAD_NOISE = 0x0, - VEH_WHEEL_SLIDING = 0x1, - VEH_WHEEL_PEELING_OUT = 0x2, - NUM_VEHICLE_MATERIAL_SNDS = 0x3, - }; - - enum VehicleMantlePoints - { - MANTLE_ANGLE_FRONT = 0x0, - MANTLE_ANGLE_BACK = 0x1, - MANTLE_ANGLE_LEFT = 0x2, - MANTLE_ANGLE_RIGHT = 0x3, - MANTLE_ANGLE_MAX = 0x4, - }; - - enum VehicleWheelType - { - FL_WHEEL = 0x0, - FR_WHEEL = 0x1, - BL_WHEEL = 0x2, - BR_WHEEL = 0x3, - ML_WHEEL = 0x4, - MR_WHEEL = 0x5, - NUM_VEHICLE_WHEELS = 0x6, - }; - - enum VehicleEngineSoundParam - { - VEH_ENGINESND_FADE_IN_START = 0x0, - VEH_ENGINESND_FADE_IN_END = 0x1, - VEH_ENGINESND_FADE_OUT_START = 0x2, - VEH_ENGINESND_FADE_OUT_END = 0x3, - VEH_ENGINESND_PITCH_REF = 0x4, - NUM_VEHICLE_ENGINESND_PARAMS = 0x5, - }; - - enum team_t - { - TEAM_FREE = 0x0, - TEAM_BAD = 0x0, - TEAM_ALLIES = 0x1, - TEAM_AXIS = 0x2, - TEAM_THREE = 0x3, - TEAM_FOUR = 0x4, - TEAM_FIVE = 0x5, - TEAM_SIX = 0x6, - TEAM_SEVEN = 0x7, - TEAM_EIGHT = 0x8, - TEAM_NUM_PLAYING_TEAMS = 0x9, - TEAM_SPECTATOR = 0x9, - TEAM_NUM_TEAMS = 0xA, - TEAM_LOCALPLAYERS = 0xB, - TEAM_FIRST_PLAYING_TEAM = 0x1, - TEAM_LAST_PLAYING_TEAM = 0x8, - }; - - struct VehicleDef - { - const char* name; - int16_t type; - int remoteControl; - int bulletDamage; - int armorPiercingDamage; - int grenadeDamage; - int projectileDamage; - int projectileSplashDamage; - int heavyExplosiveDamage; - int16_t cameraMode; - int autoRecenterOnAccel; - int thirdPersonDriver; - int thirdPersonUseVehicleRoll; - int thirdPersonCameraPitchVehicleRelative; - int thirdPersonCameraHeightWorldRelative; - float thirdPersonCameraRange; - float thirdPersonCameraMinPitchClamp; - float thirdPersonCameraMaxPitchClamp; - float thirdPersonCameraHeight[2]; - float thirdPersonCameraPitch[2]; - int cameraAlwaysAutoCenter; - float cameraAutoCenterLerpRate; - float cameraAutoCenterMaxLerpRate; - float thirdPersonCameraSpringDistance; - float thirdPersonCameraSpringTime; - float thirdPersonCameraHandbrakeTurnRateInc; - float cameraFOV; - float cameraRollFraction; - vec3_t tagPlayerOffset; - int killcamCollision; - float killcamDist; - float killcamZDist; - float killcamMinDist; - float killcamZTargetOffset; - float killcamFOV; - float killcamNearBlur; - float killcamNearBlurStart; - float killcamNearBlurEnd; - float killcamFarBlur; - float killcamFarBlurStart; - float killcamFarBlurEnd; - int isDrivable; - int numberOfSeats; - int numberOfGunners; - int seatSwitchOrder[11]; - int driverControlledGunPos; - float entryPointRadius[5]; - float texScrollScale; - float wheelRotRate; - float extraWheelRotScale; - int wheelChildTakesSteerYaw; - float maxSpeed; - float maxSpeedVertical; - float accel; - float accelVertical; - float rotRate; - float rotAccel; - float maxBodyPitch; - float maxBodyRoll; - float collisionDamage; - float collisionSpeed; - float suspensionTravel; - float heliCollisionScalar; - float viewPitchOffset; - float viewInfluence; - float tiltFromAcceleration[2]; - float tiltFromDeceleration[2]; - float tiltFromVelocity[2]; - float tiltSpeed[2]; - const char* turretWeapon; - view_limits_t turretViewLimits; - float turretRotRate; - int turretClampPlayerView; - int turretLockTurretToPlayerView; - const char* gunnerWeapon[4]; - uint16_t gunnerWeaponIndex[4]; - float gunnerRotRate; - vec2_t gunnerRestAngles[4]; - view_limits_t passengerViewLimits[6]; - const char* sndNames[2]; - unsigned int sndIndices[2]; - const char* sndMaterialNames[3]; - float skidSpeedMin; - float skidSpeedMax; - const char* futzName; - float futzBlend; - int animType; - const char* animSet; - int scriptedAnimationEntry; - float mantleAngles[4]; - uint16_t extraWheelTags[4]; - uint16_t driverHideTag; - XModel* attachmentModels[4]; - uint16_t attachmentTags[4]; - XModel* deathAttachmentModels[4]; - uint16_t deathAttachmentTags[4]; - float tracerOffset[2]; - XModel* model; - XModel* viewModel; - XModel* deathModel; - XModel* enemyModel; - float modelSwapDelay; - FxEffectDef* exhaustFx; - int oneExhaust; - FxEffectDef* treadFx[32]; - FxEffectDef* deathFx; - uint16_t deathFxTag; - const char* deathFxSound; - FxEffectDef* lightFx[4]; - uint16_t lightFxTag[4]; - FxEffectDef* friendlyLightFx; - uint16_t friendlyLightFxTag; - FxEffectDef* enemyLightFx; - uint16_t enemyLightFxTag; - float radiusDamageMin; - float radiusDamageMax; - float radiusDamageRadius; - const char* shootShock; - const char* shootRumble; - float deathQuakeScale; - float deathQuakeDuration; - float deathQuakeRadius; - const char* rumbleType; - float rumbleScale; - float rumbleDuration; - float rumbleRadius; - float rumbleBaseTime; - float rumbleAdditionalTime; - int healthDefault; - int healthMin; - int healthMax; - int eTeam; - int boostAccelMultiplier; - float boostDuration; - float boostSpeedIncrease; - int addToCompass; - int addToCompassEnemy; - const char* compassIcon; - Material* compassIconMaterial; - const char* gasButtonName; - int gasButton; - const char* reverseBrakeButtonName; - int reverseBrakeButton; - const char* handBrakeButtonName; - int handBrakeButton; - const char* attackButtonName; - int attackButton; - const char* attackSecondaryButtonName; - int attackSecondaryButton; - const char* boostButtonName; - int boostButton; - const char* moveUpButtonName; - int moveUpButton; - const char* moveDownButtonName; - int moveDownButton; - const char* switchSeatButtonName; - int switchSeatButton; - const char* steerGraphName; - GraphFloat* steerGraph; - const char* accelGraphName; - GraphFloat* accelGraph; - int isNitrous; - int isFourWheelSteering; - int useCollmap; - float radius; - float minHeight; - float maxHeight; - float max_fric_tilt_angle; - float max_fric_tilt; - int noDirectionalDamage; - int fakeBodyStabilizer; - float vehHelicopterBoundsRadius; - float vehHelicopterDecelerationFwd; - float vehHelicopterDecelerationSide; - float vehHelicopterDecelerationUp; - float vehHelicopterTiltFromControllerAxes; - float vehHelicopterTiltFromFwdAndYaw; - float vehHelicopterTiltFromFwdAndYaw_VelAtMaxTilt; - float vehHelicopterTiltMomentum; - int vehHelicopterQuadRotor; - int vehHelicopterAccelTwardsView; - float maxRotorArmMovementAngle; - float maxRotorArmRotationAngle; - int vehHelicopterMaintainHeight; - int vehHelicopterMaintainMaxHeight; - float vehHelicopterMaintainHeightLimit; - float vehHelicopterMaintainHeightAccel; - float vehHelicopterMaintainHeightMinimum; - float vehHelicopterMaintainHeightMaximum; - float vehHelicopterMaintainCeilingMinimum; - int joltVehicle; - int joltVehicleDriver; - float joltMaxTime; - float joltTime; - float joltWaves; - float joltIntensity; - VehicleParameter nitrousVehParams; - float driveBySoundRadius[2]; - VehicleDriveBySound driveBySounds[40]; - int doFootSteps; - int isSentient; - VehicleEngine engine; - VehicleAntenna antenna[2]; - char* csvInclude; - float customFloat0; - float customFloat1; - float customFloat2; - int customBool0; - int customBool1; - int customBool2; - }; - - union MemoryBlockData - { - char* mainData; - char* videoData; - char* streamData; - }; - - struct MemoryBlock - { - const char* name; - bool mainMem; - bool videoMem; - bool streamMem; - unsigned int size; - unsigned int alignment; - MemoryBlockData data; - }; - - struct cmodel_t2 - { - vec3_t mins; - vec3_t maxs; - float radius; - ClipInfo* info; - cLeaf_s leaf; - }; - - - struct AddonMapEnts - { - const char* name; - char* entityString; - int numEntityChars; - MapTriggers trigger; - ClipInfo* info; - unsigned int numSubModels; - cmodel_t2* cmodels; - GfxBrushModel* models; - }; - - - enum tracerType_t - { - TRACERTYPE_LASER = 0x0, - TRACERTYPE_SMOKE = 0x1, - TRACERTYPE_NUM = 0x2, - }; - - - struct TracerDef - { - const char* name; - tracerType_t type; - Material* material; - unsigned int drawInterval; - float speed; - float beamLength; - float beamWidth; - float screwRadius; - float screwDist; - float fadeTime; - float fadeScale; - float texRepeatRate; - vec4_t colors[5]; - }; - - - struct SkinnedVertsDef - { - const char* name; - unsigned int maxSkinnedVerts; - }; - - - struct Qdb - { - const char* name; - int len; - byte32* buffer; - }; - - - struct Slug - { - const char* name; - int len; - byte32* buffer; - }; - - - struct FootstepTableDef - { - const char* name; - unsigned int sndAliasTable[32][7]; - }; - - - struct FootstepFXTableDef - { - const char* name; - FxEffectDef* footstepFX[32]; - }; - - - struct ZBarrierBoard - { - XModel* pBoardModel; - XModel* pAlternateBoardModel; - XModel* pUpgradedBoardModel; - const char* pTearAnim; - const char* pBoardAnim; - FxEffectDef* repairEffect1; - FxEffectDef* repairEffect2; - vec3_t repairEffect1Offset; - vec3_t repairEffect2Offset; - unsigned int boardRepairSound; - unsigned int boardRepairHoverSound; - unsigned int pauseAndRepeatRepSound; - float minPause; - float maxPause; - uint16_t zombieBoardTearStateName; - uint16_t zombieBoardTearSubStateName; - unsigned int numRepsToPullProBoard; - }; - - - struct ZBarrierDef - { - const char* name; - unsigned int generalRepairSound1; - unsigned int generalRepairSound2; - unsigned int upgradedGeneralRepairSound1; - unsigned int upgradedGeneralRepairSound2; - unsigned int delayBetweenRepSounds; - float delayBetweenRepSoundsDuration; - unsigned int earthquakeOnRepair; - float earthquakeMinScale; - float earthquakeMaxScale; - float earthquakeMinDuration; - float earthquakeMaxDuration; - float earthquakeRadius; - int numBoardsInBarrier; - unsigned int autoHideOpenPieces; - unsigned int taunts; - unsigned int reachThroughAttacks; - uint16_t zombieTauntAnimState; - uint16_t zombieReachThroughAnimState; - int numAttackSlots; - float attackSpotHorzOffset; - ZBarrierBoard boards[6]; - }; - - - struct XModelPiece - { - XModel* model; - vec3_t offset; - }; - - - struct DestructibleStage - { - uint16_t showBone; - float breakHealth; - float maxTime; - unsigned int flags; - FxEffectDef* breakEffect; - const char* breakSound; - const char* breakNotify; - const char* loopSound; - XModel* spawnModel[3]; - PhysPreset* physPreset; - }; - - - struct DestructiblePiece - { - DestructibleStage stages[5]; - char parentPiece; - float parentDamagePercent; - float bulletDamageScale; - float explosiveDamageScale; - float meleeDamageScale; - float impactDamageScale; - float entityDamageTransfer; - PhysConstraints* physConstraints; - int health; - const char* damageSound; - FxEffectDef* burnEffect; - const char* burnSound; - uint16_t enableLabel; - int hideBones[5]; - }; - - - struct XAnimNotifyInfo - { - uint16_t name; - float time; - }; - - - struct XAnimDeltaPart - { - XAnimPartTrans* trans; - XAnimDeltaPartQuat2* quat2; - XAnimDeltaPartQuat* quat; - }; - - - struct DObjAnimMat - { - vec4_t quat; - vec3_t trans; - float transWeight; - }; - - - struct XSurfaceVertexInfo - { - int16_t vertCount[4]; - uint16_t* vertsBlend; - float* tensionData; - }; - - typedef tdef_align(16) unsigned short r_index16_t; - - - struct type_align(16) XSurface - { - char tileMode; - unsigned char vertListCount; - uint16_t flags; - uint16_t vertCount; - uint16_t triCount; - uint16_t baseVertIndex; - r_index16_t (*triIndices)[3]; - XSurfaceVertexInfo vertInfo; - GfxPackedVertex* verts0; - void/*ID3D11Buffer*/* vb0; - XRigidVertList* vertList; - void/*ID3D11Buffer*/* indexBuffer; - int partBits[5]; - }; - - - struct XModelCollSurf_s - { - XModelCollTri_s* collTris; - int numCollTris; - vec3_t mins; - vec3_t maxs; - int boneIdx; - int contents; - int surfFlags; - }; - - - struct type_align(4) XBoneInfo - { - vec3_t bounds[2]; - vec3_t offset; - float radiusSquared; - char collmap; - }; - - - struct Collmap - { - PhysGeomList* geomList; - }; - - - struct MaterialTextureDef - { - unsigned int nameHash; - char nameStart; - char nameEnd; - char samplerState; - char semantic; - char isMatureContent; - char pad[3]; - GfxImage* image; - }; - - - struct type_align(16) MaterialConstantDef - { - unsigned int nameHash; - char name[12]; - vec4_t literal; - }; - - enum GfxStateBitsEnum : unsigned int - { - GFXS0_SRCBLEND_RGB_SHIFT = 0x0, - GFXS0_SRCBLEND_RGB_MASK = 0xF, - GFXS0_DSTBLEND_RGB_SHIFT = 0x4, - GFXS0_DSTBLEND_RGB_MASK = 0xF0, - GFXS0_BLENDOP_RGB_SHIFT = 0x8, - GFXS0_BLENDOP_RGB_MASK = 0x700, - GFXS0_BLEND_RGB_MASK = 0x7FF, - GFXS0_ATEST_SHIFT = 0xB, - GFXS0_ATEST_DISABLE = 0x800, - GFXS0_ATEST_GT_0 = 0x0, - GFXS0_ATEST_GE_128 = 0x1000, - GFXS0_ATEST_MASK = 0x1000, - GFXS0_CULL_SHIFT = 0xE, - GFXS0_CULL_NONE = 0x4000, - GFXS0_CULL_BACK = 0x8000, - GFXS0_CULL_FRONT = 0xC000, - GFXS0_CULL_MASK = 0xC000, - GFXS0_SRCBLEND_ALPHA_SHIFT = 0x10, - GFXS0_SRCBLEND_ALPHA_MASK = 0xF0000, - GFXS0_DSTBLEND_ALPHA_SHIFT = 0x14, - GFXS0_DSTBLEND_ALPHA_MASK = 0xF00000, - GFXS0_BLENDOP_ALPHA_SHIFT = 0x18, - GFXS0_BLENDOP_ALPHA_MASK = 0x7000000, - GFXS0_BLEND_ALPHA_MASK = 0x7FF0000, - GFXS0_COLORWRITE_RGB = 0x8000000, - GFXS0_COLORWRITE_ALPHA = 0x10000000, - GFXS0_COLORWRITE_MASK = 0x18000000, - GFXS0_POLYMODE_LINE = 0x80000000, - GFXS1_DEPTHWRITE = 0x1, - GFXS1_DEPTHTEST_DISABLE = 0x2, - GFXS1_DEPTHTEST_SHIFT = 0x2, - GFXS1_DEPTHTEST_ALWAYS = 0x0, - GFXS1_DEPTHTEST_LESS = 0x4, - GFXS1_DEPTHTEST_EQUAL = 0x8, - GFXS1_DEPTHTEST_LESSEQUAL = 0xC, - GFXS1_DEPTHTEST_MASK = 0xC, - GFXS1_DEPTHFUNC_MASK = 0xF, - GFXS1_POLYGON_OFFSET_SHIFT = 0x4, - GFXS1_POLYGON_OFFSET_0 = 0x0, - GFXS1_POLYGON_OFFSET_1 = 0x10, - GFXS1_POLYGON_OFFSET_2 = 0x20, - GFXS1_POLYGON_OFFSET_SHADOWMAP = 0x30, - GFXS1_POLYGON_OFFSET_MASK = 0x30, - GFXS1_STENCIL_FRONT_ENABLE = 0x40, - GFXS1_STENCIL_BACK_ENABLE = 0x80, - GFXS1_STENCIL_MASK = 0xC0, - GFXS1_STENCIL_FRONT_PASS_SHIFT = 0x8, - GFXS1_STENCIL_FRONT_FAIL_SHIFT = 0xB, - GFXS1_STENCIL_FRONT_ZFAIL_SHIFT = 0xE, - GFXS1_STENCIL_FRONT_FUNC_SHIFT = 0x11, - GFXS1_STENCIL_FRONT_MASK = 0xFFF00, - GFXS1_STENCIL_BACK_PASS_SHIFT = 0x14, - GFXS1_STENCIL_BACK_FAIL_SHIFT = 0x17, - GFXS1_STENCIL_BACK_ZFAIL_SHIFT = 0x1A, - GFXS1_STENCIL_BACK_FUNC_SHIFT = 0x1D, - GFXS1_STENCIL_BACK_MASK = 0xFFF00000, - GFXS1_STENCILFUNC_FRONTBACK_MASK = 0xE00E0000, - GFXS1_STENCILOP_FRONTBACK_MASK = 0x1FF1FF00, - }; - - struct GfxStateBits - { - unsigned int loadBits[2]; - void/*ID3D11BlendState*/* blendState; - void/*ID3D11DepthStencilState*/* depthStencilState; - void/*ID3D11RasterizerState*/* rasterizerState; - }; - - /* struct IUnknown - { - IUnknownVtbl *vfptr; - };*/ - - /* struct __cppobj ID3D11DeviceChild : IUnknown - { - };*/ - - /* struct __cppobj ID3D11PixelShader : ID3D11DeviceChild - { - };*/ - - /* struct __cppobj ID3D11VertexShader : ID3D11DeviceChild - { - };*/ - - - struct MaterialPass - { - MaterialVertexDeclaration* vertexDecl; - MaterialVertexShader* vertexShader; - MaterialPixelShader* pixelShader; - char perPrimArgCount; - char perObjArgCount; - char stableArgCount; - char customSamplerFlags; - char precompiledIndex; - char materialType; - MaterialShaderArgument* args; - }; - - - struct MaterialTechnique - { - const char* name; - uint16_t flags; - uint16_t passCount; - MaterialPass passArray[1]; - }; - - /* struct __cppobj ID3D11View : ID3D11DeviceChild - { - };*/ - - /* struct __cppobj ID3D11ShaderResourceView : ID3D11View - { - };*/ - - - struct type_align(4) GfxImageLoadDef - { - char levelCount; - char flags; - int format; - int resourceSize; - char data[1]; - }; - - - struct SndAliasList - { - const char* name; - unsigned int id; - SndAlias* head; - int count; - int sequence; - }; - - - struct type_align(4) SndIndexEntry - { - uint16_t value; - uint16_t next; - }; - - - struct SndRadverb - { - char name[32]; - unsigned int id; - float smoothing; - float earlyTime; - float lateTime; - float earlyGain; - float lateGain; - float returnGain; - float earlyLpf; - float lateLpf; - float inputLpf; - float dampLpf; - float wallReflect; - float dryGain; - float earlySize; - float lateSize; - float diffusion; - float returnHighpass; - }; - - typedef tdef_align(16) float SndFloatAlign16; - - - struct SndDuck - { - char name[32]; - unsigned int id; - float fadeIn; - float fadeOut; - float startDelay; - float distance; - float length; - unsigned int fadeInCurve; - unsigned int fadeOutCurve; - SndFloatAlign16* attenuation; - SndFloatAlign16* filter; - int updateWhilePaused; - }; - - enum snd_asset_format - { - SND_ASSET_FORMAT_PCMS16 = 0x0, - SND_ASSET_FORMAT_PCMS24 = 0x1, - SND_ASSET_FORMAT_PCMS32 = 0x2, - SND_ASSET_FORMAT_IEEE = 0x3, - SND_ASSET_FORMAT_XMA4 = 0x4, - SND_ASSET_FORMAT_MP3 = 0x5, - SND_ASSET_FORMAT_MSADPCM = 0x6, - SND_ASSET_FORMAT_WMA = 0x7, - SND_ASSET_FORMAT_FLAC = 0x8, - SND_ASSET_FORMAT_WIIUADPCM = 0x9, - SND_ASSET_FORMAT_MPC = 0xA, - - SND_ASSET_FORMAT_COUNT - }; - - struct SndAssetBankEntry - { - unsigned int id; - unsigned int size; - unsigned int offset; - unsigned int frameCount; - char frameRateIndex; - char channelCount; - char looping; - char format; - }; - - - struct SndDialogScriptIdLookup - { - unsigned int scriptId; - unsigned int aliasId; - }; - - - struct cplane_s - { - vec3_t normal; - float dist; - char type; - char signbits; - char pad[2]; - }; - - - struct ClipMaterial - { - const char* name; - int surfaceFlags; - int contentFlags; - }; - - - struct cbrushside_t - { - cplane_s* plane; - int cflags; - int sflags; - }; - - - struct cLeafBrushNodeLeaf_t - { - LeafBrush* brushes; - }; - - - struct cLeafBrushNodeChildren_t - { - float dist; - float range; - uint16_t childOffset[2]; - }; - - - union cLeafBrushNodeData_t - { - cLeafBrushNodeLeaf_t leaf; - cLeafBrushNodeChildren_t children; - }; - - - struct cLeafBrushNode_s - { - char axis; - int16_t leafBrushCount; - int contents; - cLeafBrushNodeData_t data; - }; - - - struct type_align(16) cbrush_t - { - vec3_t mins; - int contents; - vec3_t maxs; - unsigned int numsides; - cbrushside_t* sides; - int axial_cflags[2][3]; - int axial_sflags[2][3]; - unsigned int numverts; - vec3_t* verts; - }; - - - struct Bounds - { - vec3_t midPoint; - vec3_t halfSize; - }; - - - struct cStaticModelWritable - { - uint16_t nextModelInWorldSector; - }; - - - struct cStaticModel_s - { - cStaticModelWritable writable; - XModel* xmodel; - int contents; - vec3_t origin; - vec3_t invScaledAxis[3]; - vec3_t absmin; - vec3_t absmax; - }; - - - struct cNode_t - { - cplane_s* plane; - int16_t children[2]; - }; - - - struct CollisionPartition - { - char triCount; - int firstTri; - int nuinds; - int fuind; - }; - - - union CollisionAabbTreeIndex - { - int firstChildIndex; - int partitionIndex; - }; - - - struct type_align(16) CollisionAabbTree - { - vec3_t origin; - uint16_t materialIndex; - uint16_t childCount; - vec3_t halfSize; - CollisionAabbTreeIndex u; - }; - - - enum DynEntityType - { - DYNENT_TYPE_INVALID = 0x0, - DYNENT_TYPE_CLUTTER = 0x1, - DYNENT_TYPE_DESTRUCT = 0x2, - DYNENT_TYPE_COUNT = 0x3, - }; - - - struct GfxPlacement - { - vec4_t quat; - vec3_t origin; - }; - - - struct DynEntityDef - { - DynEntityType type; - GfxPlacement pose; - XModel* xModel; - XModel* destroyedxModel; - uint16_t brushModel; - uint16_t physicsBrushModel; - FxEffectDef* destroyFx; - unsigned int destroySound; - XModelPieces* destroyPieces; - PhysPreset* physPreset; - int16_t physConstraints[4]; - int health; - int flags; - int contents; - uint16_t targetname; - uint16_t target; - }; - - - struct DynEntityPose - { - GfxPlacement pose; - float radius; - }; - - - struct DynEntityClient - { - int physObjId; - uint16_t flags; - uint16_t lightingHandle; - int health; - uint16_t burnTime; - uint16_t fadeTime; - int physicsStartTime; - }; - - - struct DynEntityServer - { - uint16_t flags; - int health; - }; - - - struct DynEntityColl - { - uint16_t sector; - uint16_t nextEntInSector; - vec3_t linkMins; - vec3_t linkMaxs; - int contents; - }; - - - struct par_t - { - vec3_t p; - vec3_t p0; - vec3_t p_prev; - int flags; - }; - - - enum rope_constraint_e - { - ROPE_PAIR_CONSTRAINT = 0x0, - ROPE_WORLD_CONSTRAINT = 0x1, - ROPE_DENTITY_CONSTRAINT = 0x2, - ROPE_CENTITY_CONSTRAINT = 0x3, - }; - - - struct type_align(4) constraint_t - { - vec3_t p; - rope_constraint_e type; - int entity_index; - int bone_name_hash; - char pi1; - char pi2; - }; - - - struct rope_frame_verts_t - { - int num_verts; - vec3_t v[50]; - }; - - - struct rope_client_verts_t - { - rope_frame_verts_t frame_verts[2]; - unsigned int frame_index; - }; - - - struct type_align(4) rope_t - { - par_t m_particles[25]; - constraint_t m_constraints[30]; - int m_entity_anchors[3]; - int m_num_particles; - int m_num_constraints; - int m_num_entity_anchors; - int m_num_draw_verts; - rope_client_verts_t m_client_verts; - vec3_t m_min; - vec3_t m_max; - vec3_t m_start; - vec3_t m_end; - int m_in_use; - int m_visible; - int m_dist_constraint; - int m_flags; - Material* m_material; - float m_seglen; - float m_length; - float m_width; - float m_scale; - float m_force_scale; - int m_health; - int m_frame; - int m_stable_count; - int m_static_rope; - uint16_t m_lightingHandle; - }; - - - struct ComPrimaryLight - { - char type; - char canUseShadowMap; - char exponent; - char priority; - int16_t cullDist; - char useCookie; - char shadowmapVolume; - vec3_t color; - vec3_t dir; - vec3_t origin; - float radius; - float cosHalfFovOuter; - float cosHalfFovInner; - float cosHalfFovExpanded; - float rotationLimit; - float translationLimit; - float mipDistance; - float dAttenuation; - float roundness; - vec4_t diffuseColor; - vec4_t falloff; - vec4_t angle; - vec4_t aAbB; - vec4_t cookieControl0; - vec4_t cookieControl1; - vec4_t cookieControl2; - const char* defName; - }; - - - enum nodeType - { - NODE_BADNODE = 0x0, - NODE_PATHNODE = 0x1, - NODE_COVER_STAND = 0x2, - NODE_COVER_CROUCH = 0x3, - NODE_COVER_CROUCH_WINDOW = 0x4, - NODE_COVER_PRONE = 0x5, - NODE_COVER_RIGHT = 0x6, - NODE_COVER_LEFT = 0x7, - NODE_COVER_PILLAR = 0x8, - NODE_AMBUSH = 0x9, - NODE_EXPOSED = 0xA, - NODE_CONCEALMENT_STAND = 0xB, - NODE_CONCEALMENT_CROUCH = 0xC, - NODE_CONCEALMENT_PRONE = 0xD, - NODE_REACQUIRE = 0xE, - NODE_BALCONY = 0xF, - NODE_SCRIPTED = 0x10, - NODE_NEGOTIATION_BEGIN = 0x11, - NODE_NEGOTIATION_END = 0x12, - NODE_TURRET = 0x13, - NODE_GUARD = 0x14, - NODE_NUMTYPES = 0x15, - NODE_DONTLINK = 0x15, - }; - - - struct pathnode_constant_t - { - nodeType type; - int spawnflags; - uint16_t targetname; - uint16_t script_linkName; - uint16_t script_noteworthy; - uint16_t target; - uint16_t animscript; - int animscriptfunc; - vec3_t vOrigin; - float fAngle; - vec2_t forward; - float fRadius; - float minUseDistSq; - int16_t wOverlapNode[2]; - uint16_t totalLinkCount; - pathlink_s* Links; - }; - - - struct SentientHandle - { - uint16_t number; - uint16_t infoIndex; - }; - - - struct type_align(4) pathnode_dynamic_t - { - SentientHandle pOwner; - int iFreeTime; - int iValidTime[3]; - int dangerousNodeTime[3]; - int inPlayerLOSTime; - int16_t wLinkCount; - int16_t wOverlapCount; - int16_t turretEntNumber; - int16_t userCount; - bool hasBadPlaceLink; - }; - - - struct pathnode_transient_t - { - int iSearchFrame; - pathnode_t* pNextOpen; - pathnode_t* pPrevOpen; - pathnode_t* pParent; - float fCost; - float fHeuristic; - - union - { - float nodeCost; - int linkIndex; - }; - }; - - - struct pathnode_t - { - pathnode_constant_t constant; - pathnode_dynamic_t dynamic; - pathnode_transient_t transient; - }; - - - struct type_align(16) pathbasenode_t - { - vec3_t vOrigin; - unsigned int type; - }; - - - struct pathnode_tree_nodes_t - { - int nodeCount; - uint16_t* nodes; - }; - - - union pathnode_tree_info_t - { - pathnode_tree_t* child[2]; - pathnode_tree_nodes_t s; - }; - - - struct pathnode_tree_t - { - int axis; - float dist; - pathnode_tree_info_t u; - }; - - - struct TriggerModel - { - int contents; - uint16_t hullCount; - uint16_t firstHull; - }; - - - struct TriggerHull - { - Bounds bounds; - int contents; - uint16_t slabCount; - uint16_t firstSlab; - }; - - - struct TriggerSlab - { - vec3_t dir; - float midPoint; - float halfSize; - }; - - - struct type_align(16) GfxStreamingAabbTree - { - vec4_t mins; - vec4_t maxs; - float maxStreamingDistance; - uint16_t firstItem; - uint16_t itemCount; - uint16_t firstChild; - uint16_t childCount; - uint16_t smodelCount; - uint16_t surfaceCount; - }; - - - struct type_align(16) float44 - { - union - { - vec4_t m[4]; - float member[16]; - }; - }; - - - struct type_align(16) GfxLight - { - char type; - char canUseShadowMap; - char shadowmapVolume; - int16_t cullDist; - vec3_t color; - vec3_t dir; - vec3_t origin; - float radius; - float cosHalfFovOuter; - float cosHalfFovInner; - int exponent; - unsigned int spotShadowIndex; - float dAttenuation; - float roundness; - vec3_t angles; - float spotShadowHiDistance; - vec4_t diffuseColor; - vec4_t shadowColor; - vec4_t falloff; - vec4_t aAbB; - vec4_t cookieControl0; - vec4_t cookieControl1; - vec4_t cookieControl2; - float44 viewMatrix; - float44 projMatrix; - GfxLightDef* def; - }; - - - struct GfxLightCorona - { - vec3_t origin; - float radius; - vec3_t color; - float intensity; - }; - - - struct GfxShadowMapVolume - { - unsigned int control; - unsigned int padding1; - unsigned int padding2; - unsigned int padding3; - }; - - - struct GfxVolumePlane - { - vec4_t plane; - }; - - - struct GfxExposureVolume - { - unsigned int control; - float exposure; - float luminanceIncreaseScale; - float luminanceDecreaseScale; - float featherRange; - float featherAdjust; - }; - - - struct GfxWorldFogVolume - { - vec3_t mins; - unsigned int control; - vec3_t maxs; - float fogTransitionTime; - unsigned int controlEx; - GfxWorldFog volumeWorldFog[1]; - }; - - - struct GfxWorldFogModifierVolume - { - unsigned int control; - uint16_t minX; - uint16_t minY; - uint16_t minZ; - uint16_t maxX; - uint16_t maxY; - uint16_t maxZ; - unsigned int controlEx; - float transitionTime; - float depthScale; - float heightScale; - vec4_t colorAdjust; - }; - - - struct GfxLutVolume - { - vec3_t mins; - unsigned int control; - vec3_t maxs; - float lutTransitionTime; - unsigned int lutIndex; - }; - - - struct GfxCell - { - vec3_t mins; - vec3_t maxs; - int aabbTreeCount; - GfxAabbTree* aabbTree; - int portalCount; - GfxPortal* portals; - char reflectionProbeCount; - char* reflectionProbes; - }; - - - struct GfxLightingSH - { - vec4_t V0; - vec4_t V1; - vec4_t V2; - }; - - - struct GfxReflectionProbe - { - vec3_t origin; - GfxLightingSH lightingSH; - GfxImage* reflectionImage; - GfxReflectionProbeVolumeData* probeVolumes; - unsigned int probeVolumeCount; - float mipLodBias; - }; - - - struct GfxLightmapArray - { - GfxImage* primary; - GfxImage* secondary; - }; - - /* struct __cppobj ID3D11Resource : ID3D11DeviceChild - { - };*/ - - /* struct __cppobj ID3D11Buffer : ID3D11Resource - { - };*/ - - - struct type_align(4) GfxLightGridEntry - { - uint16_t colorsIndex; - char primaryLightIndex; - char visibility; - }; - - - struct type_align(4) GfxCompressedLightGridColors - { - char rgb[56][3]; - }; - - - struct GfxCompressedLightGridCoeffs - { - uint16_t coeffs[9][3]; - }; - - - struct GfxSkyGridVolume - { - vec3_t mins; - vec3_t maxs; - vec3_t lightingOrigin; - uint16_t colorsIndex; - char primaryLightIndex; - char visibility; - }; - - - struct GfxBrushModelWritable - { - vec3_t mins; - float padding1; - vec3_t maxs; - float padding2; - }; - - - struct type_align(16) GfxBrushModel - { - GfxBrushModelWritable writable; - vec3_t bounds[2]; - unsigned int surfaceCount; - unsigned int startSurfIndex; - }; - - - struct MaterialMemory - { - Material* material; - int memory; - }; - - - union XModelDrawInfo - { - struct - { - char state; - char lod; - uint16_t surfId; - }; - - unsigned int packed; - }; - - - struct GfxSceneDynModel - { - XModelDrawInfo info; - uint16_t dynEntId; - char primaryLightIndex; - char reflectionProbeIndex; - }; - - - struct BModelDrawInfo - { - uint16_t surfId; - }; - - - struct type_align(4) GfxSceneDynBrush - { - BModelDrawInfo info; - uint16_t dynEntId; - }; - - - union gcc_align(8) __m128 - { - float m128_f32[4]; - uint64_t m128_u64[2]; - char m128_i8[16]; - int16_t m128_i16[8]; - int m128_i32[4]; - int64_t m128_i64[2]; - char m128_u8[16]; - uint16_t m128_u16[8]; - unsigned int m128_u32[4]; - }; - - struct vector3 - { - __m128 x; - __m128 y; - __m128 z; - }; - - struct vector4 - { - __m128 x; - __m128 y; - __m128 z; - __m128 w; - }; - - - struct type_align(16) SSkinInstance - { - union - { - vector4 mat; - float disk_mat[16]; - }; - - SSkinShaders* shaders; - SSkinModel* model; - SSkinAnim* anim; - SSkinVert* instVerts; - float frame; - int pad1; - int pad2; - int pad3; - }; - - - struct GfxShadowGeometry - { - uint16_t surfaceCount; - uint16_t smodelCount; - uint16_t* sortedSurfIndex; - uint16_t* smodelIndex; - }; - - - struct GfxLightRegion - { - unsigned int hullCount; - GfxLightRegionHull* hulls; - }; - - - struct GfxStaticModelInst - { - vec3_t mins; - vec3_t maxs; - vec3_t lightingOrigin; - }; - - - struct srfTriangles_t - { - vec3_t mins; - int vertexDataOffset0; - vec3_t maxs; - int vertexDataOffset1; - int firstVertex; - float himipRadiusInvSq; - uint16_t vertexCount; - uint16_t triCount; - int baseIndex; - }; - - - struct type_align(16) GfxSurface - { - srfTriangles_t tris; - Material* material; - char lightmapIndex; - char reflectionProbeIndex; - char primaryLightIndex; - char flags; - vec3_t bounds[2]; - }; - - - struct GfxPackedPlacement - { - vec3_t origin; - vec3_t axis[3]; - float scale; - }; - - - struct GfxLightingSHQuantized - { - uint16_t V0[4]; - uint16_t V1[4]; - uint16_t V2[4]; - }; - - - struct type_align(4) GfxStaticModelLmapVertexInfo - { - unsigned int* lmapVertexColors; - void/*ID3D11Buffer*/* lmapVertexColorsVB; - uint16_t numLmapVertexColors; - }; - - - struct GfxStaticModelDrawInst - { - float cullDist; - GfxPackedPlacement placement; - XModel* model; - int flags; - float invScaleSq; - uint16_t lightingHandle; - uint16_t colorsIndex; - GfxLightingSHQuantized lightingSH; - char primaryLightIndex; - char visibility; - char reflectionProbeIndex; - unsigned int smid; - GfxStaticModelLmapVertexInfo lmapVertexInfo[4]; - }; - - - struct Occluder - { - unsigned int flags; - char name[16]; - vec3_t points[4]; - }; - - - struct GfxOutdoorBounds - { - vec3_t bounds[2]; - }; - - - struct GfxHeroLight - { - char type; - char unused[3]; - vec3_t color; - vec3_t dir; - vec3_t origin; - float radius; - float cosHalfFovOuter; - float cosHalfFovInner; - int exponent; - }; - - - struct GfxHeroLightTree - { - vec3_t mins; - vec3_t maxs; - int leftNode; - int rightNode; - }; - - - struct Glyph - { - uint16_t letter; - char x0; - char y0; - char dx; - char pixelWidth; - char pixelHeight; - float s0; - float t0; - float s1; - float t1; - }; - - - struct KerningPairs - { - uint16_t wFirst; - uint16_t wSecond; - int iKernAmount; - }; - - - struct FontIconName - { - const char* string; - int hash; - }; - - - struct FontIconEntry - { - FontIconName fontIconName; - Material* fontIconMaterialHandle; - int fontIconSize; - float xScale; - float yScale; - }; - - - struct FontIconAlias - { - int aliasHash; - int buttonHash; - }; - - - struct GenericEventHandler - { - const char* name; - GenericEventScript* eventScript; - GenericEventHandler* next; - }; - - - struct ItemKeyHandler - { - int key; - GenericEventScript* keyScript; - ItemKeyHandler* next; - }; - - - enum expDataType - { - VAL_INT = 0x0, - VAL_FLOAT = 0x1, - VAL_STRING = 0x2, - VAL_ADDRESS = 0x3, - VAL_DVAR = 0x4, - }; - - - union operandInternalDataUnion - { - int intVal; - float floatVal; - const char* string; - dvar_t* dvar; - }; - - - struct Operand - { - expDataType dataType; - operandInternalDataUnion internals; - }; - - - union expressionRpnDataUnion - { - Operand constant; - void* cmd; - int cmdIdx; - }; - - enum expressionRpnEnum - { - RPN_CONSTANT = 0x0, - RPN_CMD_IDX = 0x1, - RPN_CMD = 0x2, - RPN_END = 0x3, - }; - - - struct expressionRpn - { - int type; - expressionRpnDataUnion data; - }; - - enum ItemType - { - ITEM_TYPE_DEFAULT = 0x0, - ITEM_TYPE_TEXT = 0x1, - ITEM_TYPE_IMAGE = 0x2, - ITEM_TYPE_BUTTON = 0x3, - ITEM_TYPE_LISTBOX = 0x4, - ITEM_TYPE_EDITFIELD = 0x5, - ITEM_TYPE_OWNERDRAW = 0x6, - ITEM_TYPE_NUMERICFIELD = 0x7, - ITEM_TYPE_SLIDER = 0x8, - ITEM_TYPE_YESNO = 0x9, - ITEM_TYPE_MULTI = 0xA, - ITEM_TYPE_DVARENUM = 0xB, - ITEM_TYPE_BIND = 0xC, - ITEM_TYPE_VALIDFILEFIELD = 0xD, - ITEM_TYPE_UPREDITFIELD = 0xE, - ITEM_TYPE_GAME_MESSAGE_WINDOW = 0xF, - ITEM_TYPE_BIND2 = 0x10, - ITEM_TYPE_HIGHLIGHT = 0x11, - ITEM_TYPE_OWNERDRAW_TEXT = 0x12, - ITEM_TYPE_OD_BUTTON = 0x13, - ITEM_TYPE_OD_TEXT_BUTTON = 0x14, - ITEM_TYPE_BUTTON_NO_TEXT = 0x15, - ITEM_TYPE_PROFILEMULTI = 0x16, - ITEM_TYPE_RADIOBUTTON = 0x19, - ITEM_TYPE_MODEL = 0x1A, - ITEM_TYPE_CHECKBOX = 0x1B, - ITEM_TYPE_COMBO = 0x1C, - ITEM_TYPE_DVAR_FLOAT = 0x1E, - ITEM_TYPE_CONFEDITFIELD = 0x1F, - ITEM_TYPE_MENUMODEL = 0x27 - }; - - - union itemDefData_t - { - textDef_s* textDef; - imageDef_s* imageDef; - focusItemDef_s* blankButtonDef; - ownerDrawDef_s* ownerDrawDef; - void* data; - }; - - - struct type_align(8) itemDef_s - { - windowDef_t window; - int type; - int dataType; - int imageTrack; - const char* dvar; - const char* profileVar; - const char* dvarTest; - const char* enableDvar; - int dvarFlags; - itemDefData_t typeData; - menuDef_t* parent; - rectData_s* rectExpData; - ExpressionStatement visibleExp; - uint64_t showBits; - uint64_t hideBits; - ExpressionStatement forecolorAExp; - int ui3dWindowId; - GenericEventHandler* onEvent; - UIAnimInfo* animInfo; - }; - - - enum weapType_t - { - WEAPTYPE_BULLET = 0x0, - WEAPTYPE_GRENADE = 0x1, - WEAPTYPE_PROJECTILE = 0x2, - WEAPTYPE_BINOCULARS = 0x3, - WEAPTYPE_GAS = 0x4, - WEAPTYPE_BOMB = 0x5, - WEAPTYPE_MINE = 0x6, - WEAPTYPE_MELEE = 0x7, - WEAPTYPE_RIOTSHIELD = 0x8, - WEAPTYPE_NUM = 0x9, - }; - - - enum weapClass_t - { - WEAPCLASS_RIFLE = 0x0, - WEAPCLASS_MG = 0x1, - WEAPCLASS_SMG = 0x2, - WEAPCLASS_SPREAD = 0x3, - WEAPCLASS_PISTOL = 0x4, - WEAPCLASS_GRENADE = 0x5, - WEAPCLASS_ROCKETLAUNCHER = 0x6, - WEAPCLASS_TURRET = 0x7, - WEAPCLASS_NON_PLAYER = 0x8, - WEAPCLASS_GAS = 0x9, - WEAPCLASS_ITEM = 0xA, - WEAPCLASS_MELEE = 0xB, - WEAPCLASS_KILLSTREAK_ALT_STORED_WEAPON = 0xC, - WEAPCLASS_PISTOL_SPREAD = 0xD, - WEAPCLASS_NUM = 0xE, - }; - - - enum ImpactType - { - IMPACT_TYPE_NONE = 0x0, - IMPACT_TYPE_BULLET_SMALL = 0x1, - IMPACT_TYPE_BULLET_LARGE = 0x2, - IMPACT_TYPE_BULLET_AP = 0x3, - IMPACT_TYPE_BULLET_XTREME = 0x4, - IMPACT_TYPE_SHOTGUN = 0x5, - IMPACT_TYPE_GRENADE_BOUNCE = 0x6, - IMPACT_TYPE_GRENADE_EXPLODE = 0x7, - IMPACT_TYPE_RIFLE_GRENADE = 0x8, - IMPACT_TYPE_ROCKET_EXPLODE = 0x9, - IMPACT_TYPE_ROCKET_EXPLODE_XTREME = 0xA, - IMPACT_TYPE_PROJECTILE_DUD = 0xB, - IMPACT_TYPE_MORTAR_SHELL = 0xC, - IMPACT_TYPE_TANK_SHELL = 0xD, - IMPACT_TYPE_BOLT = 0xE, - IMPACT_TYPE_BLADE = 0xF, - IMPACT_TYPE_COUNT = 0x10, - }; - - - enum weapInventoryType_t - { - WEAPINVENTORY_PRIMARY = 0x0, - WEAPINVENTORY_OFFHAND = 0x1, - WEAPINVENTORY_ITEM = 0x2, - WEAPINVENTORY_ALTMODE = 0x3, - WEAPINVENTORY_MELEE = 0x4, - WEAPINVENTORY_DWLEFTHAND = 0x5, - WEAPINVENTORYCOUNT = 0x6, - }; - - - enum weapClipType_t - { - WEAPON_CLIPTYPE_BOTTOM = 0x0, - WEAPON_CLIPTYPE_TOP = 0x1, - WEAPON_CLIPTYPE_LEFT = 0x2, - WEAPON_CLIPTYPE_DP28 = 0x3, - WEAPON_CLIPTYPE_PTRS = 0x4, - WEAPON_CLIPTYPE_LMG = 0x5, - WEAPON_CLIPTYPECOUNT = 0x6, - }; - - - enum barrelType_t - { - BARREL_TYPE_SINGLE = 0x0, - BARREL_TYPE_DUAL = 0x1, - BARREL_TYPE_DUAL_ALTERNATE = 0x2, - BARREL_TYPE_QUAD = 0x3, - BARREL_TYPE_QUAD_ALTERNATE = 0x4, - BARREL_TYPE_QUAD_DOUBLE_ALTERNATE = 0x5, - BARREL_TYPE_COUNT = 0x6, - }; - - - enum OffhandClass - { - OFFHAND_CLASS_NONE = 0x0, - OFFHAND_CLASS_FRAG_GRENADE = 0x1, - OFFHAND_CLASS_SMOKE_GRENADE = 0x2, - OFFHAND_CLASS_FLASH_GRENADE = 0x3, - OFFHAND_CLASS_GEAR = 0x4, - OFFHAND_CLASS_SUPPLYDROP_MARKER = 0x5, - OFFHAND_CLASS_COUNT = 0x6, - }; - - - enum OffhandSlot - { - OFFHAND_SLOT_NONE = 0x0, - OFFHAND_SLOT_LETHAL_GRENADE = 0x1, - OFFHAND_SLOT_TACTICAL_GRENADE = 0x2, - OFFHAND_SLOT_EQUIPMENT = 0x3, - OFFHAND_SLOT_SPECIFIC_USE = 0x4, - OFFHAND_SLOT_COUNT = 0x5, - }; - - - enum weapStance_t - { - WEAPSTANCE_STAND = 0x0, - WEAPSTANCE_DUCK = 0x1, - WEAPSTANCE_PRONE = 0x2, - WEAPSTANCE_NUM = 0x3, - }; - - - enum activeReticleType_t - { - VEH_ACTIVE_RETICLE_NONE = 0x0, - VEH_ACTIVE_RETICLE_PIP_ON_A_STICK = 0x1, - VEH_ACTIVE_RETICLE_BOUNCING_DIAMOND = 0x2, - VEH_ACTIVE_RETICLE_MISSILE_LOCK = 0x3, - VEH_ACTIVE_RETICLE_COUNT = 0x4, - }; - - - enum ammoCounterClipType_t - { - AMMO_COUNTER_CLIP_NONE = 0x0, - AMMO_COUNTER_CLIP_MAGAZINE = 0x1, - AMMO_COUNTER_CLIP_SHORTMAGAZINE = 0x2, - AMMO_COUNTER_CLIP_SHOTGUN = 0x3, - AMMO_COUNTER_CLIP_ROCKET = 0x4, - AMMO_COUNTER_CLIP_BELTFED = 0x5, - AMMO_COUNTER_CLIP_ALTWEAPON = 0x6, - AMMO_COUNTER_CLIP_COUNT = 0x7, - }; - - - enum WeapOverlayInteface_t - { - WEAPOVERLAYINTERFACE_NONE = 0x0, - WEAPOVERLAYINTERFACE_JAVELIN = 0x1, - WEAPOVERLAYINTERFACE_TURRETSCOPE = 0x2, - WEAPOVERLAYINTERFACECOUNT = 0x3, - }; - - - enum weapProjExposion_t - { - WEAPPROJEXP_GRENADE = 0x0, - WEAPPROJEXP_ROCKET = 0x1, - WEAPPROJEXP_FLASHBANG = 0x2, - WEAPPROJEXP_NONE = 0x3, - WEAPPROJEXP_DUD = 0x4, - WEAPPROJEXP_SMOKE = 0x5, - WEAPPROJEXP_HEAVY = 0x6, - WEAPPROJEXP_FIRE = 0x7, - WEAPPROJEXP_NAPALMBLOB = 0x8, - WEAPPROJEXP_BOLT = 0x9, - WEAPPROJEXP_SHRAPNELSPAN = 0xA, - WEAPPROJEXP_NUM = 0xB, - }; - - - enum WeapStickinessType - { - WEAPSTICKINESS_NONE = 0x0, - WEAPSTICKINESS_ALL = 0x1, - WEAPSTICKINESS_ALL_NO_SENTIENTS = 0x2, - WEAPSTICKINESS_GROUND = 0x3, - WEAPSTICKINESS_GROUND_WITH_YAW = 0x4, - WEAPSTICKINESS_FLESH = 0x5, - WEAPSTICKINESS_COUNT = 0x6, - }; - - - enum WeapRotateType - { - WEAPROTATE_GRENADE_ROTATE = 0x0, - WEAPROTATE_BLADE_ROTATE = 0x1, - WEAPROTATE_CYLINDER_ROTATE = 0x2, - WEAPROTATE_COUNT = 0x3, - }; - - - enum guidedMissileType_t - { - MISSILE_GUIDANCE_NONE = 0x0, - MISSILE_GUIDANCE_SIDEWINDER = 0x1, - MISSILE_GUIDANCE_HELLFIRE = 0x2, - MISSILE_GUIDANCE_JAVELIN = 0x3, - MISSILE_GUIDANCE_BALLISTIC = 0x4, - MISSILE_GUIDANCE_WIREGUIDED = 0x5, - MISSILE_GUIDANCE_TVGUIDED = 0x6, - MISSILE_GUIDANCE_DRONE = 0x7, - MISSILE_GUIDANCE_HEATSEEKING = 0x8, - MISSILE_GUIDANCE_COUNT = 0x9, - }; - - enum hitLocation_t - { - HITLOC_NONE = 0x0, - HITLOC_HELMET = 0x1, - HITLOC_HEAD = 0x2, - HITLOC_NECK = 0x3, - HITLOC_TORSO_UPR = 0x4, - HITLOC_TORSO_MID = 0x5, - HITLOC_TORSO_LWR = 0x6, - HITLOC_R_ARM_UPR = 0x7, - HITLOC_L_ARM_UPR = 0x8, - HITLOC_R_ARM_LWR = 0x9, - HITLOC_L_ARM_LWR = 0xA, - HITLOC_R_HAND = 0xB, - HITLOC_L_HAND = 0xC, - HITLOC_R_LEG_UPR = 0xD, - HITLOC_L_LEG_UPR = 0xE, - HITLOC_R_LEG_LWR = 0xF, - HITLOC_L_LEG_LWR = 0x10, - HITLOC_R_FOOT = 0x11, - HITLOC_L_FOOT = 0x12, - HITLOC_GUN = 0x13, - HITLOC_SHIELD = 0x14, - - HITLOC_NUM, - }; - - struct WeaponDef - { - const char* szOverlayName; // covered - XModel** gunXModel; // covered - XModel* handXModel; // covered - const char* szModeName; // covered - uint16_t* notetrackSoundMapKeys; // covered - uint16_t* notetrackSoundMapValues; // covered - int playerAnimType; // covered - weapType_t weapType; - weapClass_t weapClass; - PenetrateType penetrateTWeaponAttachmentype; - ImpactType impactType; - weapInventoryType_t inventoryType; - weapFireType_t fireType; - weapClipType_t clipType; - barrelType_t barrelType; - int itemIndex; - const char* parentWeaponName; - int iJamFireTime; - int overheatWeapon; - float overheatRate; - float cooldownRate; - float overheatEndVal; - bool coolWhileFiring; - bool fuelTankWeapon; - int iTankLifeTime; - OffhandClass offhandClass; - OffhandSlot offhandSlot; - weapStance_t stance; - FxEffectDef* viewFlashEffect; - FxEffectDef* worldFlashEffect; - FxEffectDef* barrelCooldownEffect; - int barrelCooldownMinCount; - vec3_t vViewFlashOffset; - vec3_t vWorldFlashOffset; - const char* pickupSound; - const char* pickupSoundPlayer; - const char* ammoPickupSound; - const char* ammoPickupSoundPlayer; - const char* projectileSound; - const char* pullbackSound; - const char* pullbackSoundPlayer; - const char* fireSound; - const char* fireSoundPlayer; - const char* fireLoopSound; - const char* fireLoopSoundPlayer; - const char* fireLoopEndSound; - const char* fireLoopEndSoundPlayer; - const char* fireStartSound; - const char* fireStopSound; - const char* fireKillcamSound; - const char* fireStartSoundPlayer; - const char* fireStopSoundPlayer; - const char* fireKillcamSoundPlayer; - const char* fireLastSound; - const char* fireLastSoundPlayer; - const char* emptyFireSound; - const char* emptyFireSoundPlayer; - const char* crackSound; - const char* whizbySound; - const char* meleeSwipeSound; - const char* meleeSwipeSoundPlayer; - const char* meleeHitSound; - const char* meleeMissSound; - const char* rechamberSound; - const char* rechamberSoundPlayer; - const char* reloadSound; - const char* reloadSoundPlayer; - const char* reloadEmptySound; - const char* reloadEmptySoundPlayer; - const char* reloadStartSound; - const char* reloadStartSoundPlayer; - const char* reloadEndSound; - const char* reloadEndSoundPlayer; - const char* rotateLoopSound; - const char* rotateLoopSoundPlayer; - const char* rotateStopSound; - const char* rotateStopSoundPlayer; - const char* deploySound; - const char* deploySoundPlayer; - const char* finishDeploySound; - const char* finishDeploySoundPlayer; - const char* breakdownSound; - const char* breakdownSoundPlayer; - const char* finishBreakdownSound; - const char* finishBreakdownSoundPlayer; - const char* detonateSound; - const char* detonateSoundPlayer; - const char* nightVisionWearSound; - const char* nightVisionWearSoundPlayer; - const char* nightVisionRemoveSound; - const char* nightVisionRemoveSoundPlayer; - const char* altSwitchSound; - const char* altSwitchSoundPlayer; - const char* raiseSound; - const char* raiseSoundPlayer; - const char* firstRaiseSound; - const char* firstRaiseSoundPlayer; - const char* adsRaiseSoundPlayer; - const char* adsLowerSoundPlayer; - const char* putawaySound; - const char* putawaySoundPlayer; - const char* overheatSound; - const char* overheatSoundPlayer; - const char* adsZoomSound; - const char* shellCasing; - const char* shellCasingPlayer; - const char** bounceSound; - const char* standMountedWeapdef; - const char* crouchMountedWeapdef; - const char* proneMountedWeapdef; - int standMountedIndex; - int crouchMountedIndex; - int proneMountedIndex; - FxEffectDef* viewShellEjectEffect; - FxEffectDef* worldShellEjectEffect; - FxEffectDef* viewLastShotEjectEffect; - FxEffectDef* worldLastShotEjectEffect; - vec3_t vViewShellEjectOffset; - vec3_t vWorldShellEjectOffset; - vec3_t vViewShellEjectRotation; - vec3_t vWorldShellEjectRotation; - Material* reticleCenter; - Material* reticleSide; - int iReticleCenterSize; - int iReticleSideSize; - int iReticleMinOfs; - activeReticleType_t activeReticleType; - vec3_t vStandMove; - vec3_t vStandRot; - vec3_t vDuckedOfs; - vec3_t vDuckedMove; - vec3_t vDuckedSprintOfs; - vec3_t vDuckedSprintRot; - vec2_t vDuckedSprintBob; - float fDuckedSprintCycleScale; - vec3_t vSprintOfs; - vec3_t vSprintRot; - vec2_t vSprintBob; - float fSprintCycleScale; - vec3_t vLowReadyOfs; - vec3_t vLowReadyRot; - vec3_t vRideOfs; - vec3_t vRideRot; - vec3_t vDtpOfs; - vec3_t vDtpRot; - vec2_t vDtpBob; - float fDtpCycleScale; - vec3_t vMantleOfs; - vec3_t vMantleRot; - vec3_t vSlideOfs; - vec3_t vSlideRot; - vec3_t vDuckedRot; - vec3_t vProneOfs; - vec3_t vProneMove; - vec3_t vProneRot; - vec3_t vStrafeMove; - vec3_t vStrafeRot; - float fPosMoveRate; - float fPosProneMoveRate; - float fStandMoveMinSpeed; - float fDuckedMoveMinSpeed; - float fProneMoveMinSpeed; - float fPosRotRate; - float fPosProneRotRate; - float fStandRotMinSpeed; - float fDuckedRotMinSpeed; - float fProneRotMinSpeed; - XModel** worldModel; - XModel* worldClipModel; - XModel* rocketModel; - XModel* mountedModel; - XModel* additionalMeleeModel; - Material* fireTypeIcon; - Material* hudIcon; - weaponIconRatioType_t hudIconRatio; - Material* indicatorIcon; - weaponIconRatioType_t indicatorIconRatio; - Material* ammoCounterIcon; - weaponIconRatioType_t ammoCounterIconRatio; - ammoCounterClipType_t ammoCounterClip; - int iStartAmmo; - int iMaxAmmo; - int shotCount; - const char* szSharedAmmoCapName; - int iSharedAmmoCapIndex; - int iSharedAmmoCap; - bool unlimitedAmmo; - bool ammoCountClipRelative; - int damage[6]; - float damageRange[6]; - int minPlayerDamage; - float damageDuration; - float damageInterval; - int playerDamage; - int iMeleeDamage; - int iDamageType; - uint16_t explosionTag; - int iFireDelay; - int iMeleeDelay; - int meleeChargeDelay; - int iDetonateDelay; - int iSpinUpTime; - int iSpinDownTime; - float spinRate; - const char* spinLoopSound; - const char* spinLoopSoundPlayer; - const char* startSpinSound; - const char* startSpinSoundPlayer; - const char* stopSpinSound; - const char* stopSpinSoundPlayer; - bool applySpinPitch; - int iFireTime; - int iLastFireTime; - int iRechamberTime; - int iRechamberBoltTime; - int iHoldFireTime; - int iDetonateTime; - int iMeleeTime; - int iBurstDelayTime; - int meleeChargeTime; - int iReloadTimeRight; - int iReloadTimeLeft; - int reloadShowRocketTime; - int iReloadEmptyTimeLeft; - int iReloadAddTime; - int iReloadEmptyAddTime; - int iReloadQuickAddTime; - int iReloadQuickEmptyAddTime; - int iReloadStartTime; - int iReloadStartAddTime; - int iReloadEndTime; - int iDropTime; - int iRaiseTime; - int iAltDropTime; - int quickDropTime; - int quickRaiseTime; - int iFirstRaiseTime; - int iEmptyRaiseTime; - int iEmptyDropTime; - int sprintInTime; - int sprintLoopTime; - int sprintOutTime; - int lowReadyInTime; - int lowReadyLoopTime; - int lowReadyOutTime; - int contFireInTime; - int contFireLoopTime; - int contFireOutTime; - int dtpInTime; - int dtpLoopTime; - int dtpOutTime; - int crawlInTime; - int crawlForwardTime; - int crawlBackTime; - int crawlRightTime; - int crawlLeftTime; - int crawlOutFireTime; - int crawlOutTime; - int slideInTime; - int deployTime; - int breakdownTime; - int iFlourishTime; - int nightVisionWearTime; - int nightVisionWearTimeFadeOutEnd; - int nightVisionWearTimePowerUp; - int nightVisionRemoveTime; - int nightVisionRemoveTimePowerDown; - int nightVisionRemoveTimeFadeInStart; - int fuseTime; - int aiFuseTime; - int lockOnRadius; - int lockOnSpeed; - bool requireLockonToFire; - bool noAdsWhenMagEmpty; - bool avoidDropCleanup; - unsigned int stackFire; - float stackFireSpread; - float stackFireAccuracyDecay; - const char* stackSound; - float autoAimRange; - float aimAssistRange; - bool mountableWeapon; - float aimPadding; - float enemyCrosshairRange; - bool crosshairColorChange; - float moveSpeedScale; - float adsMoveSpeedScale; - float sprintDurationScale; - weapOverlayReticle_t overlayReticle; - WeapOverlayInteface_t overlayInterface; - float overlayWidth; - float overlayHeight; - float fAdsBobFactor; - float fAdsViewBobMult; - bool bHoldBreathToSteady; - float fHipSpreadStandMin; - float fHipSpreadDuckedMin; - float fHipSpreadProneMin; - float hipSpreadStandMax; - float hipSpreadDuckedMax; - float hipSpreadProneMax; - float fHipSpreadDecayRate; - float fHipSpreadFireAdd; - float fHipSpreadTurnAdd; - float fHipSpreadMoveAdd; - float fHipSpreadDuckedDecay; - float fHipSpreadProneDecay; - float fHipReticleSidePos; - float fAdsIdleAmount; - float fHipIdleAmount; - float adsIdleSpeed; - float hipIdleSpeed; - float fIdleCrouchFactor; - float fIdleProneFactor; - float fGunMaxPitch; - float fGunMaxYaw; - float swayMaxAngle; - float swayLerpSpeed; - float swayPitchScale; - float swayYawScale; - float swayHorizScale; - float swayVertScale; - float swayShellShockScale; - float adsSwayMaxAngle; - float adsSwayLerpSpeed; - float adsSwayPitchScale; - float adsSwayYawScale; - bool sharedAmmo; - bool bRifleBullet; - bool armorPiercing; - bool bAirburstWeapon; - bool bBoltAction; - bool bUseAltTagFlash; - bool bUseAntiLagRewind; - bool bIsCarriedKillstreakWeapon; - bool aimDownSight; - bool bRechamberWhileAds; - bool bReloadWhileAds; - float adsViewErrorMin; - float adsViewErrorMax; - bool bCookOffHold; - bool bClipOnly; - bool bCanUseInVehicle; - bool bNoDropsOrRaises; - bool adsFireOnly; - bool cancelAutoHolsterWhenEmpty; - bool suppressAmmoReserveDisplay; - bool laserSight; - bool laserSightDuringNightvision; - bool bHideThirdPerson; - bool bHasBayonet; - bool bDualWield; - bool bExplodeOnGround; - bool bThrowBack; - bool bRetrievable; - bool bDieOnRespawn; - bool bNoThirdPersonDropsOrRaises; - bool bContinuousFire; - bool bNoPing; - bool bForceBounce; - bool bUseDroppedModelAsStowed; - bool bNoQuickDropWhenEmpty; - bool bKeepCrosshairWhenADS; - bool bUseOnlyAltWeaoponHideTagsInAltMode; - bool bAltWeaponAdsOnly; - bool bAltWeaponDisableSwitching; - Material* killIcon; - weaponIconRatioType_t killIconRatio; - bool flipKillIcon; - bool bNoPartialReload; - bool bSegmentedReload; - bool bNoADSAutoReload; - int iReloadAmmoAdd; - int iReloadStartAdd; - const char* szSpawnedGrenadeWeaponName; - const char* szDualWieldWeaponName; - unsigned int dualWieldWeaponIndex; - int iDropAmmoMin; - int iDropAmmoMax; - int iDropClipAmmoMin; - int iDropClipAmmoMax; - int iShotsBeforeRechamber; - bool blocksProne; - bool bShowIndicator; - int isRollingGrenade; - int useBallisticPrediction; - int isValuable; - int isTacticalInsertion; - bool isReviveWeapon; - bool bUseRigidBodyOnVehicle; - int iExplosionRadius; - int iExplosionRadiusMin; - int iIndicatorRadius; - int iExplosionInnerDamage; - int iExplosionOuterDamage; - float damageConeAngle; - int iProjectileSpeed; - int iProjectileSpeedUp; - int iProjectileSpeedRelativeUp; - int iProjectileSpeedForward; - float fProjectileTakeParentVelocity; - int iProjectileActivateDist; - float projLifetime; - float timeToAccelerate; - float projectileCurvature; - XModel* projectileModel; - weapProjExposion_t projExplosion; - FxEffectDef* projExplosionEffect; - bool projExplosionEffectForceNormalUp; - FxEffectDef* projExplosionEffect2; - bool projExplosionEffect2ForceNormalUp; - FxEffectDef* projExplosionEffect3; - bool projExplosionEffect3ForceNormalUp; - FxEffectDef* projExplosionEffect4; - bool projExplosionEffect4ForceNormalUp; - FxEffectDef* projExplosionEffect5; - bool projExplosionEffect5ForceNormalUp; - FxEffectDef* projDudEffect; - const char* projExplosionSound; - const char* projDudSound; - const char* mortarShellSound; - const char* tankShellSound; - bool bProjImpactExplode; - bool bProjSentientImpactExplode; - bool bProjExplodeWhenStationary; - bool bBulletImpactExplode; - WeapStickinessType stickiness; - WeapRotateType rotateType; - bool plantable; - bool hasDetonator; - bool timedDetonation; - bool bNoCrumpleMissile; - bool rotate; - bool bKeepRolling; - bool holdButtonToThrow; - bool offhandHoldIsCancelable; - bool freezeMovementWhenFiring; - float lowAmmoWarningThreshold; - bool bDisallowAtMatchStart; - float meleeChargeRange; - bool bUseAsMelee; - bool isCameraSensor; - bool isAcousticSensor; - bool isLaserSensor; - bool isHoldUseGrenade; - float* parallelBounce; - float* perpendicularBounce; - FxEffectDef* projTrailEffect; - vec3_t vProjectileColor; - guidedMissileType_t guidedMissileType; - float maxSteeringAccel; - int projIgnitionDelay; - FxEffectDef* projIgnitionEffect; - const char* projIgnitionSound; - float fAdsAimPitch; - float fAdsCrosshairInFrac; - float fAdsCrosshairOutFrac; - int adsGunKickReducedKickBullets; - float adsGunKickReducedKickPercent; - float fAdsGunKickPitchMin; - float fAdsGunKickPitchMax; - float fAdsGunKickYawMin; - float fAdsGunKickYawMax; - float fAdsGunKickAccel; - float fAdsGunKickSpeedMax; - float fAdsGunKickSpeedDecay; - float fAdsGunKickStaticDecay; - float fAdsViewKickPitchMin; - float fAdsViewKickPitchMax; - float fAdsViewKickMinMagnitude; - float fAdsViewKickYawMin; - float fAdsViewKickYawMax; - float fAdsRecoilReductionRate; - float fAdsRecoilReductionLimit; - float fAdsRecoilReturnRate; - float fAdsViewScatterMin; - float fAdsViewScatterMax; - float fAdsSpread; - int hipGunKickReducedKickBullets; - float hipGunKickReducedKickPercent; - float fHipGunKickPitchMin; - float fHipGunKickPitchMax; - float fHipGunKickYawMin; - float fHipGunKickYawMax; - float fHipGunKickAccel; - float fHipGunKickSpeedMax; - float fHipGunKickSpeedDecay; - float fHipGunKickStaticDecay; - float fHipViewKickPitchMin; - float fHipViewKickPitchMax; - float fHipViewKickMinMagnitude; - float fHipViewKickYawMin; - float fHipViewKickYawMax; - float fHipViewScatterMin; - float fHipViewScatterMax; - float fAdsViewKickCenterDuckedScale; - float fAdsViewKickCenterProneScale; - float fAntiQuickScopeTime; - float fAntiQuickScopeScale; - float fAntiQuickScopeSpreadMultiplier; - float fAntiQuickScopeSpreadMax; - float fAntiQuickScopeSwayFactor; - float fightDist; - float maxDist; - //const char *accuracyGraphName[2]; // TODO: Order is accuracyGraphName[0] -> accuracyGraphKnots[0] -> originalAccuracyGraphKnots[0] -> accuracyGraphName[1] -> ... - // Which is currently not possible to do in code generation. Afaik this is the only place where this is the case. - // So might be something to fix but on the other hand it might be too much work for this little inconvenience. - const char* accuracyGraphName0; - const char* accuracyGraphName1; - //vec2_t *accuracyGraphKnots[2]; - vec2_t* accuracyGraphKnots0; - vec2_t* accuracyGraphKnots1; - //vec2_t *originalAccuracyGraphKnots[2]; - vec2_t* originalAccuracyGraphKnots0; - vec2_t* originalAccuracyGraphKnots1; - int accuracyGraphKnotCount[2]; - int originalAccuracyGraphKnotCount[2]; - int iPositionReloadTransTime; - float leftArc; - float rightArc; - float topArc; - float bottomArc; - float accuracy; - float aiSpread; - float playerSpread; - float minTurnSpeed[2]; - float maxTurnSpeed[2]; - float pitchConvergenceTime; - float yawConvergenceTime; - float suppressTime; - float maxRange; - float fAnimHorRotateInc; - float fPlayerPositionDist; - const char* szUseHintString; - const char* dropHintString; - int iUseHintStringIndex; - int dropHintStringIndex; - float horizViewJitter; - float vertViewJitter; - float cameraShakeScale; - int cameraShakeDuration; - int cameraShakeRadius; - float explosionCameraShakeScale; - int explosionCameraShakeDuration; - int explosionCameraShakeRadius; - const char* szScript; - float destabilizationRateTime; - float destabilizationCurvatureMax; - int destabilizeDistance; - float* locationDamageMultipliers; - const char* fireRumble; - const char* meleeImpactRumble; - const char* reloadRumble; - const char* explosionRumble; - TracerDef* tracerType; - TracerDef* enemyTracerType; - float adsDofStart; - float adsDofEnd; - float hipDofStart; - float hipDofEnd; - float scanSpeed; - float scanAccel; - int scanPauseTime; - const char* flameTableFirstPerson; - const char* flameTableThirdPerson; - flameTable* flameTableFirstPersonPtr; - flameTable* flameTableThirdPersonPtr; - FxEffectDef* tagFx_preparationEffect; - FxEffectDef* tagFlash_preparationEffect; - bool doGibbing; - float maxGibDistance; - float altScopeADSTransInTime; - float altScopeADSTransOutTime; - int iIntroFireTime; - int iIntroFireLength; - FxEffectDef* meleeSwipeEffect; - FxEffectDef* meleeImpactEffect; - FxEffectDef* meleeImpactNoBloodEffect; - const char* throwBackType; - WeaponCamo* weaponCamo; - float customFloat0; - float customFloat1; - float customFloat2; - int customBool0; - int customBool1; - int customBool2; - }; - - enum weapAnimFiles_t - { - WEAP_ANIM_ROOT = 0x0, - WEAP_ANIM_IDLE = 0x1, - WEAP_ANIM_EMPTY_IDLE = 0x2, - WEAP_ANIM_FIRE_INTRO = 0x3, - WEAP_ANIM_FIRE = 0x4, - WEAP_ANIM_HOLD_FIRE = 0x5, - WEAP_ANIM_LASTSHOT = 0x6, - WEAP_ANIM_FINALSHOT = 0x7, - WEAP_ANIM_RECHAMBER = 0x8, - WEAP_ANIM_MELEE = 0x9, - WEAP_ANIM_MELEE1 = 0xA, - WEAP_ANIM_MELEE2 = 0xB, - WEAP_ANIM_MELEE3 = 0xC, - WEAP_ANIM_MELEE_EMPTY = 0xD, - WEAP_ANIM_MELEE_CHARGE = 0xE, - WEAP_ANIM_MELEE_CHARGE_EMPTY = 0xF, - WEAP_ANIM_RELOAD = 0x10, - WEAP_ANIM_RELOAD_RIGHT = 0x11, - WEAP_ANIM_RELOAD_EMPTY = 0x12, - WEAP_ANIM_RELOAD_START = 0x13, - WEAP_ANIM_RELOAD_END = 0x14, - WEAP_ANIM_RELOAD_QUICK = 0x15, - WEAP_ANIM_RELOAD_QUICK_EMPTY = 0x16, - WEAP_ANIM_RAISE = 0x17, - WEAP_ANIM_FIRST_RAISE = 0x18, - WEAP_ANIM_DROP = 0x19, - WEAP_ANIM_ALT_RAISE = 0x1A, - WEAP_ANIM_ALT_DROP = 0x1B, - WEAP_ANIM_QUICK_RAISE = 0x1C, - WEAP_ANIM_QUICK_DROP = 0x1D, - WEAP_ANIM_EMPTY_RAISE = 0x1E, - WEAP_ANIM_EMPTY_DROP = 0x1F, - WEAP_ANIM_SPRINT_IN = 0x20, - WEAP_ANIM_SPRINT_LOOP = 0x21, - WEAP_ANIM_SPRINT_OUT = 0x22, - WEAP_ANIM_SPRINT_EMPTY_IN = 0x23, - WEAP_ANIM_SPRINT_EMPTY_LOOP = 0x24, - WEAP_ANIM_SPRINT_EMPTY_OUT = 0x25, - WEAP_ANIM_LOWREADY_IN = 0x26, - WEAP_ANIM_LOWREADY_LOOP = 0x27, - WEAP_ANIM_LOWREADY_OUT = 0x28, - WEAP_ANIM_CONT_FIRE_IN = 0x29, - WEAP_ANIM_CONT_FIRE_LOOP = 0x2A, - WEAP_ANIM_CONT_FIRE_OUT = 0x2B, - WEAP_ANIM_CRAWL_IN = 0x2C, - WEAP_ANIM_CRAWL_FORWARD = 0x2D, - WEAP_ANIM_CRAWL_BACK = 0x2E, - WEAP_ANIM_CRAWL_RIGHT = 0x2F, - WEAP_ANIM_CRAWL_LEFT = 0x30, - WEAP_ANIM_CRAWL_OUT = 0x31, - WEAP_ANIM_CRAWL_EMPTY_IN = 0x32, - WEAP_ANIM_CRAWL_EMPTY_FORWARD = 0x33, - WEAP_ANIM_CRAWL_EMPTY_BACK = 0x34, - WEAP_ANIM_CRAWL_EMPTY_RIGHT = 0x35, - WEAP_ANIM_CRAWL_EMPTY_LEFT = 0x36, - WEAP_ANIM_CRAWL_EMPTY_OUT = 0x37, - WEAP_ANIM_DEPLOY = 0x38, - WEAP_ANIM_BREAKDOWN = 0x39, - WEAP_ANIM_DETONATE = 0x3A, - WEAP_ANIM_NIGHTVISION_WEAR = 0x3B, - WEAP_ANIM_NIGHTVISION_REMOVE = 0x3C, - WEAP_ANIM_ADS_FIRE = 0x3D, - WEAP_ANIM_ADS_LASTSHOT = 0x3E, - WEAP_ANIM_ADS_FIRE_INTRO = 0x3F, - WEAP_ANIM_ADS_RECHAMBER = 0x40, - WEAP_ANIM_DTP_IN = 0x41, - WEAP_ANIM_DTP_LOOP = 0x42, - WEAP_ANIM_DTP_OUT = 0x43, - WEAP_ANIM_DTP_EMPTY_IN = 0x44, - WEAP_ANIM_DTP_EMPTY_LOOP = 0x45, - WEAP_ANIM_DTP_EMPTY_OUT = 0x46, - WEAP_ANIM_SLIDE_IN = 0x47, - WEAP_ANIM_MANTLE = 0x48, - WEAP_ANIM_CAMERA_SPRINT_LOOP = 0x49, - WEAP_ANIM_CAMERA_DTP_IN = 0x4A, - WEAP_ANIM_CAMERA_DTP_LOOP = 0x4B, - WEAP_ANIM_CAMERA_DTP_OUT = 0x4C, - WEAP_ANIM_CAMERA_MANTLE = 0x4D, - WEAP_ANIM_FIRE_LEFT = 0x4E, - WEAP_ANIM_LASTSHOT_LEFT = 0x4F, - WEAP_ANIM_FINALSHOT_LEFT = 0x50, - WEAP_ANIM_IDLE_LEFT = 0x51, - WEAP_ANIM_EMPTY_IDLE_LEFT = 0x52, - WEAP_ANIM_RELOAD_EMPTY_LEFT = 0x53, - WEAP_ANIM_RELOAD_LEFT = 0x54, - WEAP_ANIM_ADS_UP = 0x55, - WEAP_ANIM_ADS_DOWN = 0x56, - WEAP_ANIM_ADS_UP_OTHER_SCOPE = 0x57, - NUM_WEAP_ANIMS = 0x58, - }; - - enum materialSurfType_t - { - SURF_TYPE_DEFAULT, - SURF_TYPE_BARK, - SURF_TYPE_BRICK, - SURF_TYPE_CARPET, - SURF_TYPE_CLOTH, - SURF_TYPE_CONCRETE, - SURF_TYPE_DIRT, - SURF_TYPE_FLESH, - SURF_TYPE_FOLIAGE, - SURF_TYPE_GLASS, - SURF_TYPE_GRASS, - SURF_TYPE_GRAVEL, - SURF_TYPE_ICE, - SURF_TYPE_METAL, - SURF_TYPE_MUD, - SURF_TYPE_PAPER, - SURF_TYPE_PLASTER, - SURF_TYPE_ROCK, - SURF_TYPE_SAND, - SURF_TYPE_SNOW, - SURF_TYPE_WATER, - SURF_TYPE_WOOD, - SURF_TYPE_ASPHALT, - SURF_TYPE_CERAMIC, - SURF_TYPE_PLASTIC, - SURF_TYPE_RUBBER, - SURF_TYPE_CUSHION, - SURF_TYPE_FRUIT, - SURF_TYPE_PAINTED_METAL, - SURF_TYPE_PLAYER, - SURF_TYPE_TALL_GRASS, - SURF_TYPE_RIOT_SHIELD, - - SURF_TYPE_NUM - }; - - struct WeaponVariantDef - { - const char* szInternalName; - int iVariantCount; - WeaponDef* weapDef; - const char* szDisplayName; - const char* szAltWeaponName; - const char* szAttachmentUnique; - WeaponAttachment** attachments; - WeaponAttachmentUnique** attachmentUniques; - const char** szXAnims; - uint16_t* hideTags; - XModel** attachViewModel; - XModel** attachWorldModel; - const char** attachViewModelTag; - const char** attachWorldModelTag; - float attachViewModelOffsets[24]; - float attachWorldModelOffsets[24]; - float attachViewModelRotations[24]; - float attachWorldModelRotations[24]; - vec3_t stowedModelOffsets; - vec3_t stowedModelRotations; - unsigned int altWeaponIndex; - int iAttachments; - bool bIgnoreAttachments; - int iClipSize; - int iReloadTime; - int iReloadEmptyTime; - int iReloadQuickTime; - int iReloadQuickEmptyTime; - int iAdsTransInTime; - int iAdsTransOutTime; - int iAltRaiseTime; - const char* szAmmoDisplayName; - const char* szAmmoName; - int iAmmoIndex; - const char* szClipName; - int iClipIndex; - float fAimAssistRangeAds; - float fAdsSwayHorizScale; - float fAdsSwayVertScale; - float fAdsViewKickCenterSpeed; - float fHipViewKickCenterSpeed; - float fAdsZoomFov1; - float fAdsZoomFov2; - float fAdsZoomFov3; - float fAdsZoomInFrac; - float fAdsZoomOutFrac; - float fOverlayAlphaScale; - float fOOPosAnimLength[2]; - bool bSilenced; - bool bDualMag; - bool bInfraRed; - bool bTVGuided; - unsigned int perks[2]; - bool bAntiQuickScope; - Material* overlayMaterial; - Material* overlayMaterialLowRes; - Material* dpadIcon; - weaponIconRatioType_t dpadIconRatio; - bool noAmmoOnDpadIcon; - bool mmsWeapon; - bool mmsInScope; - float mmsFOV; - float mmsAspect; - float mmsMaxDist; - vec3_t ikLeftHandIdlePos; - vec3_t ikLeftHandOffset; - vec3_t ikLeftHandRotation; - bool bUsingLeftHandProneIK; - vec3_t ikLeftHandProneOffset; - vec3_t ikLeftHandProneRotation; - vec3_t ikLeftHandUiViewerOffset; - vec3_t ikLeftHandUiViewerRotation; - }; - - struct WeaponFullDef - { - WeaponVariantDef weapVariantDef; - WeaponDef weapDef; - WeaponAttachment* attachments[63]; - WeaponAttachmentUnique* attachmentUniques[95]; - XModel* gunXModel[16]; - const char* szXAnims[88]; - uint16_t hideTags[32]; - uint16_t notetrackSoundMapKeys[20]; - uint16_t notetrackSoundMapValues[20]; - XModel* worldModel[16]; - XModel* attachViewModel[8]; - XModel* attachWorldModel[8]; - const char* attachViewModelTag[8]; - const char* attachWorldModelTag[8]; - float parallelBounce[32]; - float perpendicularBounce[32]; - float locationDamageMultipliers[21]; - char weaponCamo[64]; - }; - - - struct WeaponCamoSet - { - GfxImage* solidCamoImage; - GfxImage* patternCamoImage; - vec2_t patternOffset; - float patternScale; - }; - - - struct WeaponCamoMaterialSet - { - unsigned int numMaterials; - WeaponCamoMaterial* materials; - }; - - - enum SndMenuCategory - { - SND_CATEGORY_SFX = 0x0, - SND_CATEGORY_MUSIC = 0x1, - SND_CATEGORY_VOICE = 0x2, - SND_CATEGORY_UI = 0x3, - SND_CATEGORY_CINEMATIC = 0x4, - SND_CATEGORY_COUNT = 0x5, - }; - - - struct SndVolumeGroup - { - char name[32]; - char parentName[32]; - unsigned int id; - int parentIndex; - SndMenuCategory category; - uint16_t attenuationSp; - uint16_t attenuationMp; - }; - - - struct SndCurve - { - char name[32]; - unsigned int id; - vec2_t points[8]; - }; - - - struct SndPan - { - char name[32]; - unsigned int id; - float front; - float back; - float center; - float lfe; - float left; - float right; - }; - - - struct SndDuckGroup - { - char name[32]; - unsigned int id; - }; - - - struct SndContext - { - unsigned int type; - unsigned int values[8]; - }; - - - struct SndMaster - { - char name[32]; - unsigned int id; - int lowE; - float lowG; - float lowF; - float lowQ; - int peak1E; - float peak1G; - float peak1F; - float peak1Q; - int peak2E; - float peak2G; - float peak2F; - float peak2Q; - int hiE; - float hiG; - float hiF; - float hiQ; - float eqG; - int compE; - float compPG; - float compMG; - float compT; - float compR; - float compTA; - float compTR; - int limitE; - float limitPG; - float limitMG; - float limitT; - float limitR; - float limitTA; - float limitTR; - float busReverbG; - float busFxG; - float busVoiceG; - float busPfutzG; - float busHdrfxG; - float busUiG; - float busMusicG; - float busMovieG; - float busVcsG; - int busReverbE; - int busFxE; - int busVoiceE; - int busPfutzE; - int busHdrfxE; - int busUiE; - int busMusicE; - int busMovieE; - int hdrfxCompE; - int voiceEqE; - int voiceCompE; - }; - - - struct SndSidechainDuck - { - char name[32]; - unsigned int id; - float g; - float f; - float q; - float ta; - float tr; - float tf; - }; - - - struct SndFutz - { - char name[32]; - unsigned int id; - float bpfF; - float bpfQ; - float lsG; - float lsF; - float lsQ; - float dist; - float preG; - float postG; - float th; - float tg; - float clippre; - float clippost; - float blend; - unsigned int startAliasId; - unsigned int stopAliasId; - unsigned int loopAliasId; - }; - - - struct FxSpawnDefLooping - { - int intervalMsec; - int count; - }; - - - struct FxIntRange - { - int base; - int amplitude; - }; - - - struct FxSpawnDefOneShot - { - FxIntRange count; - }; - - - union FxSpawnDef - { - FxSpawnDefLooping looping; - FxSpawnDefOneShot oneShot; - }; - - - struct FxElemAtlas - { - char behavior; - char index; - char fps; - char loopCount; - char colIndexBits; - char rowIndexBits; - uint16_t entryCountAndIndexRange; - }; - - - union FxEffectDefRef - { - FxEffectDef* handle; - const char* name; - }; - - - union FxElemVisuals - { - void* anonymous; - Material* material; - XModel* model; - FxEffectDefRef effectDef; - const char* soundName; - GfxLightDef* lightDef; - }; - - - union FxElemDefVisuals - { - FxElemMarkVisuals* markArray; - FxElemVisuals* array; - FxElemVisuals instance; - }; - - - union FxElemExtendedDefPtr - { - FxTrailDef* trailDef; - FxSpotLightDef* spotLightDef; - char* unknownDef; - }; - - - struct FxBillboardTrim - { - float topWidth; - float bottomWidth; - }; - - - union FxElemDefUnion - { - FxBillboardTrim billboard; - FxIntRange cloudDensityRange; - }; - - - struct FxElemSpawnSound - { - const char* spawnSound; - }; - - enum FxElemType : char - { - FX_ELEM_TYPE_SPRITE_BILLBOARD = 0x0, - FX_ELEM_TYPE_SPRITE_ORIENTED = 0x1, - FX_ELEM_TYPE_SPRITE_ROTATED = 0x2, - FX_ELEM_TYPE_TAIL = 0x3, - FX_ELEM_TYPE_LINE = 0x4, - FX_ELEM_TYPE_TRAIL = 0x5, - FX_ELEM_TYPE_CLOUD = 0x6, - FX_ELEM_TYPE_MODEL = 0x7, - FX_ELEM_TYPE_OMNI_LIGHT = 0x8, - FX_ELEM_TYPE_SPOT_LIGHT = 0x9, - FX_ELEM_TYPE_SOUND = 0xA, - FX_ELEM_TYPE_DECAL = 0xB, - FX_ELEM_TYPE_RUNNER = 0xC, - FX_ELEM_TYPE_COUNT = 0xD, - FX_ELEM_TYPE_LAST_SPRITE = 0x5, - FX_ELEM_TYPE_LAST_DRAWN = 0x9, - }; - - - struct FxElemDef - { - int flags; - FxSpawnDef spawn; - FxFloatRange spawnRange; - FxFloatRange fadeInRange; - FxFloatRange fadeOutRange; - float spawnFrustumCullRadius; - FxIntRange spawnDelayMsec; - FxIntRange lifeSpanMsec; - FxFloatRange spawnOrigin[3]; - FxFloatRange spawnOffsetRadius; - FxFloatRange spawnOffsetHeight; - FxFloatRange spawnAngles[3]; - FxFloatRange angularVelocity[3]; - FxFloatRange initialRotation; - unsigned int rotationAxis; - FxFloatRange gravity; - FxFloatRange reflectionFactor; - FxElemAtlas atlas; - float windInfluence; - FxElemType elemType; - char visualCount; - char velIntervalCount; - char visStateIntervalCount; - FxElemVelStateSample* velSamples; - FxElemVisStateSample* visSamples; - FxElemDefVisuals visuals; - vec3_t collMins; - vec3_t collMaxs; - FxEffectDefRef effectOnImpact; - FxEffectDefRef effectOnDeath; - FxEffectDefRef effectEmitted; - FxFloatRange emitDist; - FxFloatRange emitDistVariance; - FxEffectDefRef effectAttached; - FxElemExtendedDefPtr extended; - char sortOrder; - char lightingFrac; - char unused[2]; - uint16_t alphaFadeTimeMsec; - uint16_t maxWindStrength; - uint16_t spawnIntervalAtMaxWind; - uint16_t lifespanAtMaxWind; - FxElemDefUnion u; - FxElemSpawnSound spawnSound; - vec2_t billboardPivot; - }; - - - struct FxImpactEntry - { - FxEffectDef* nonflesh[32]; - FxEffectDef* flesh[4]; - }; - - - struct StringTableCell - { - const char* string; - int hash; - }; - - - enum LbColType - { - LBCOL_TYPE_NUMBER = 0x0, - LBCOL_TYPE_TIME = 0x1, - LBCOL_TYPE_LEVELXP = 0x2, - LBCOL_TYPE_PRESTIGE = 0x3, - LBCOL_TYPE_BIGNUMBER = 0x4, - LBCOL_TYPE_PERCENT = 0x5, - LBCOL_TYPE_TIME_FULL = 0x6, - LBCOL_TYPE_COUNT = 0x7, - }; - - - enum LbAggType - { - LBAGG_TYPE_MIN = 0x0, - LBAGG_TYPE_MAX = 0x1, - LBAGG_TYPE_ADD = 0x2, - LBAGG_TYPE_REPLACE = 0x3, - LBAGG_TYPE_COUNT = 0x4, - }; - - - struct LbColumnDef - { - const char* name; - int colId; - int dwColIndex; - bool hidden; - const char* statName; - LbColType type; - int precision; - LbAggType agg; - const char* localization; - int uiCalColX; - int uiCalColY; - }; - - - struct ddlDef_t - { - int version; - int size; - ddlStructDef_t* structList; - int structCount; - ddlEnumDef_t* enumList; - int enumCount; - ddlDef_t* next; - }; - - - struct Glass - { - unsigned int numCellIndices; - uint16_t cellIndices[6]; - GlassDef* glassDef; - unsigned int index; - unsigned int brushModel; - vec3_t origin; - vec3_t angles; - vec3_t absmin; - vec3_t absmax; - bool isPlanar; - char numOutlineVerts; - char binormalSign; - vec2_t* outline; - vec3_t outlineAxis[3]; - vec3_t outlineOrigin; - float uvScale; - float thickness; - }; - - - struct KeyValuePair - { - int keyHash; - int namespaceHash; - const char* value; - }; - - - enum DevEventType - { - EVENT_ACTIVATE = 0x0, - EVENT_DEACTIVATE = 0x1, - EVENT_ACCEPT = 0x2, - EVENT_UPDATE = 0x3, - EVENT_DRAW = 0x4, - EVENT_SAVE = 0x5, - }; - - - enum LocalClientNum_t - { - INVALID_LOCAL_CLIENT = 0xFFFFFFFF, - LOCAL_CLIENT_FIRST = 0x0, - LOCAL_CLIENT_0 = 0x0, - ONLY_LOCAL_CLIENT = 0x0, - LOCAL_CLIENT_COUNT = 0x1, - }; - - - struct type_align(4) DevGraph - { - vec2_t* knots; - int* knotCount; - int knotCountMax; - int selectedKnot; - void* eventCallback; //void (__cdecl *eventCallback)(DevGraph *, DevEventType, LocalClientNum_t); - void* textCallback; //void (__cdecl *textCallback)(DevGraph *, const float, const float, char *, const int); - void* data; - bool disableEditingEndPoints; - }; - - - struct GraphFloat - { - char name[64]; - vec2_t knots[32]; - int knotCount; - float scale; - DevGraph devguiGraph; - }; - - typedef char ByteVec[3]; - typedef tdef_align(4) uint16_t UShortVec[3]; - - union XAnimDynamicFrames - { - ByteVec *_1; - UShortVec *_2; - }; - - - union XAnimDynamicIndicesTrans - { - char _1[1]; - uint16_t _2[1]; - }; - - - struct type_align(4) XAnimPartTransFrames - { - vec3_t mins; - vec3_t size; - XAnimDynamicFrames frames; - XAnimDynamicIndicesTrans indices; - }; - - - union XAnimPartTransData - { - XAnimPartTransFrames frames; - vec3_t frame0; - }; - - - struct XAnimPartTrans - { - uint16_t size; - char smallTrans; - XAnimPartTransData u; - }; - - union XAnimDynamicIndicesDeltaQuat2 - { - char _1[1]; - uint16_t _2[1]; - }; - - typedef tdef_align(4) int16_t XQuat2[2]; - - struct type_align(4) XAnimDeltaPartQuatDataFrames2 - { - XQuat2 *frames; - XAnimDynamicIndicesDeltaQuat2 indices; - }; - - - union XAnimDeltaPartQuatData2 - { - XAnimDeltaPartQuatDataFrames2 frames; - XQuat2 frame0; - }; - - - struct XAnimDeltaPartQuat2 - { - uint16_t size; - XAnimDeltaPartQuatData2 u; - }; - - union XAnimDynamicIndicesDeltaQuat - { - char _1[1]; - uint16_t _2[1]; - }; - - typedef tdef_align(4) int16_t XQuat[4]; - - struct type_align(4) XAnimDeltaPartQuatDataFrames - { - XQuat *frames; - XAnimDynamicIndicesDeltaQuat indices; - }; - - - union XAnimDeltaPartQuatData - { - XAnimDeltaPartQuatDataFrames frames; - XQuat frame0; - }; - - - struct XAnimDeltaPartQuat - { - uint16_t size; - XAnimDeltaPartQuatData u; - }; - +typedef tdef_align(2048) char SndChar2048; + +struct SndLoadedAssets { + const char *zone; + const char *language; + unsigned int loadedCount; + unsigned int entryCount; + SndAssetBankEntry *entries; + unsigned int dataSize; + SndChar2048 *data; +}; + +enum SndBankState { + SND_BANK_STATE_NEW = 0x0, + SND_BANK_STATE_STREAM_HEADER = 0x1, + SND_BANK_STATE_STREAM_TOC = 0x2, + SND_BANK_STATE_LOADED_HEADER = 0x3, + SND_BANK_STATE_LOADED_TOC = 0x4, + SND_BANK_STATE_LOADED_ASSET_WAIT = 0x5, + SND_BANK_STATE_LOADED_ASSETS = 0x6, + SND_BANK_STATE_READY_TO_USE = 0x7, + SND_BANK_STATE_ERROR = 0x8, +}; + +struct SndBank { + const char *name; + unsigned int aliasCount; + SndAliasList *alias; + SndIndexEntry *aliasIndex; + unsigned int radverbCount; + SndRadverb *radverbs; + unsigned int duckCount; + SndDuck *ducks; + SndRuntimeAssetBank streamAssetBank; + SndRuntimeAssetBank loadAssetBank; + SndLoadedAssets loadedAssets; + unsigned int scriptIdLookupCount; + SndDialogScriptIdLookup *scriptIdLookups; + SndBankState state; + int streamRequestId; + bool pendingIo; + bool ioError; + bool runtimeAssetLoad; +}; + +struct SndPatch { + const char *name; + unsigned int elementCount; + unsigned int *elements; +}; + +typedef unsigned short LeafBrush; +typedef tdef_align(128) cbrush_t cbrush_array_t; +typedef tdef_align(128) Bounds BoundsArray; + +struct ClipInfo { + int planeCount; + cplane_s *planes; + unsigned int numMaterials; + ClipMaterial *materials; + unsigned int numBrushSides; + cbrushside_t *brushsides; + unsigned int leafbrushNodesCount; + cLeafBrushNode_s *leafbrushNodes; + unsigned int numLeafBrushes; + LeafBrush *leafbrushes; + unsigned int numBrushVerts; + vec3_t *brushVerts; + unsigned int nuinds; + uint16_t *uinds; + uint16_t numBrushes; + cbrush_array_t *brushes; + BoundsArray *brushBounds; + int *brushContents; +}; + +struct type_align(4) cLeaf_s { + uint16_t firstCollAabbIndex; + uint16_t collAabbCount; + int brushContents; + int terrainContents; + vec3_t mins; + vec3_t maxs; + int leafBrushNode; + int16_t cluster; +}; + +struct cmodel_t { + vec3_t mins; + vec3_t maxs; + float radius; + ClipInfo *info; + cLeaf_s leaf; +}; + +struct clipMap_t { + const char *name; + int isInUse; + ClipInfo info; + ClipInfo *pInfo; + unsigned int numStaticModels; + cStaticModel_s *staticModelList; + unsigned int numNodes; + cNode_t *nodes; + unsigned int numLeafs; + cLeaf_s *leafs; + unsigned int vertCount; + vec3_t *verts; + int triCount; + uint16_t (*triIndices)[3]; + char *triEdgeIsWalkable; // Saved as 1 bit per edge rounded up to the next 4 bytes + int partitionCount; + CollisionPartition *partitions; + int aabbTreeCount; + CollisionAabbTree *aabbTrees; + unsigned int numSubModels; + cmodel_t *cmodels; + int numClusters; + int clusterBytes; + char *visibility; + int vised; + MapEnts *mapEnts; + cbrush_t *box_brush; + cmodel_t box_model; + uint16_t originalDynEntCount; + uint16_t dynEntCount[4]; + DynEntityDef *dynEntDefList[2]; + DynEntityPose *dynEntPoseList[2]; + DynEntityClient *dynEntClientList[2]; + DynEntityServer *dynEntServerList[2]; + DynEntityColl *dynEntCollList[4]; + int num_constraints; + PhysConstraint *constraints; + int max_ropes; + rope_t *ropes; + unsigned int checksum; +}; + +struct ComWorld { + const char *name; + int isInUse; + unsigned int primaryLightCount; + ComPrimaryLight *primaryLights; +}; + +struct PathData { + unsigned int nodeCount; + unsigned int originalNodeCount; + pathnode_t *nodes; + pathbasenode_t *basenodes; + int visBytes; + char *pathVis; + int smoothBytes; + char *smoothCache; + int nodeTreeCount; + pathnode_tree_t *nodeTree; +}; + +struct GameWorldSp { + const char *name; + PathData path; +}; + +struct GameWorldMp { + const char *name; + PathData path; +}; + +struct MapTriggers { + unsigned int count; + TriggerModel *models; + unsigned int hullCount; + TriggerHull *hulls; + unsigned int slabCount; + TriggerSlab *slabs; +}; + +struct MapEnts { + const char *name; + char *entityString; + int numEntityChars; + MapTriggers trigger; +}; + +struct GfxWorldStreamInfo { + int aabbTreeCount; + GfxStreamingAabbTree *aabbTrees; + int leafRefCount; + int *leafRefs; +}; + +struct GfxWorldSun { + unsigned int control; + vec3_t angles; + vec4_t ambientColor; + vec4_t sunCd; + vec4_t sunCs; + vec4_t skyColor; + float exposure; +}; + +struct GfxWorldFog { + float baseDist; + float halfDist; + float baseHeight; + float halfHeight; + float sunFogPitch; + float sunFogYaw; + float sunFogInner; + float sunFogOuter; + vec3_t fogColor; + float fogOpacity; + vec3_t sunFogColor; + float sunFogOpacity; +}; + +struct SunLightParseParams { + char name[64]; + GfxWorldSun initWorldSun[1]; + float fogTransitionTime; + GfxWorldFog initWorldFog[1]; +}; + +struct GfxSkyDynamicIntensity { + float angle0; + float angle1; + float factor0; + float factor1; +}; + +struct GfxWorldDpvsPlanes { + int cellCount; + cplane_s *planes; + uint16_t *nodes; + unsigned int *sceneEntCellBits; +}; + +struct GfxWorldVertexData0 { + byte128 *data; + void /*ID3D11Buffer*/ *vb; +}; + +struct GfxWorldVertexData1 { + byte128 *data; + void /*ID3D11Buffer*/ *vb; +}; + +struct GfxWorldDraw { + unsigned int reflectionProbeCount; + GfxReflectionProbe *reflectionProbes; + GfxTexture *reflectionProbeTextures; + int lightmapCount; + GfxLightmapArray *lightmaps; + GfxTexture *lightmapPrimaryTextures; + GfxTexture *lightmapSecondaryTextures; + unsigned int vertexCount; + unsigned int vertexDataSize0; + GfxWorldVertexData0 vd0; + unsigned int vertexDataSize1; + GfxWorldVertexData1 vd1; + int indexCount; + uint16_t *indices; + void /*ID3D11Buffer*/ *indexBuffer; +}; + +typedef tdef_align(4) char aligned_byte_pointer; +typedef tdef_align(4) GfxCompressedLightGridCoeffs GfxCompressedLightGridCoeffs_align4; + +struct GfxLightGrid { + unsigned int sunPrimaryLightIndex; + uint16_t mins[3]; + uint16_t maxs[3]; + float offset; + unsigned int rowAxis; + unsigned int colAxis; + uint16_t *rowDataStart; + unsigned int rawRowDataSize; + aligned_byte_pointer *rawRowData; + unsigned int entryCount; + GfxLightGridEntry *entries; + unsigned int colorCount; + GfxCompressedLightGridColors *colors; + unsigned int coeffCount; + GfxCompressedLightGridCoeffs_align4 *coeffs; + unsigned int skyGridVolumeCount; + GfxSkyGridVolume *skyGridVolumes; +}; + +struct sunflare_t { + bool hasValidData; + Material *spriteMaterial; + Material *flareMaterial; + float spriteSize; + float flareMinSize; + float flareMinDot; + float flareMaxSize; + float flareMaxDot; + float flareMaxAlpha; + int flareFadeInTime; + int flareFadeOutTime; + float blindMinDot; + float blindMaxDot; + float blindMaxDarken; + int blindFadeInTime; + int blindFadeOutTime; + float glareMinDot; + float glareMaxDot; + float glareMaxLighten; + int glareFadeInTime; + int glareFadeOutTime; + vec3_t sunFxPosition; +}; + +typedef tdef_align(4) GfxDrawSurf GfxDrawSurf_align4; + +struct GfxWorldDpvsStatic { + unsigned int smodelCount; + unsigned int staticSurfaceCount; + unsigned int litSurfsBegin; + unsigned int litSurfsEnd; + unsigned int litTransSurfsBegin; + unsigned int litTransSurfsEnd; + unsigned int emissiveOpaqueSurfsBegin; + unsigned int emissiveOpaqueSurfsEnd; + unsigned int emissiveTransSurfsBegin; + unsigned int emissiveTransSurfsEnd; + unsigned int smodelVisDataCount; + unsigned int surfaceVisDataCount; + raw_byte128 *smodelVisData[3]; + raw_byte128 *surfaceVisData[3]; + raw_byte128 *smodelVisDataCameraSaved; + raw_byte128 *surfaceVisDataCameraSaved; + uint16_t *sortedSurfIndex; + GfxStaticModelInst *smodelInsts; + GfxSurface *surfaces; + GfxStaticModelDrawInst *smodelDrawInsts; + GfxDrawSurf_align4 *surfaceMaterials; + raw_byte128 *surfaceCastsSunShadow; + raw_byte128 *surfaceCastsShadow; + raw_byte128 *smodelCastsShadow; + volatile int usageCount; +}; + +struct GfxWorldDpvsDynamic { + unsigned int dynEntClientWordCount[2]; + unsigned int dynEntClientCount[2]; + unsigned int *dynEntCellBits[2]; + raw_byte16 *dynEntVisData[2][3]; + volatile int usageCount; +}; + +struct GfxWaterBuffer { + unsigned int bufferSize; + vec4_t *buffer; +}; + +struct GfxWorld { + const char *name; + const char *baseName; + int planeCount; + int nodeCount; + int surfaceCount; + GfxWorldStreamInfo streamInfo; + const char *skyBoxModel; + SunLightParseParams sunParse; + GfxLight *sunLight; + unsigned int sunPrimaryLightIndex; + unsigned int primaryLightCount; + unsigned int coronaCount; + GfxLightCorona *coronas; + unsigned int shadowMapVolumeCount; + GfxShadowMapVolume *shadowMapVolumes; + unsigned int shadowMapVolumePlaneCount; + GfxVolumePlane *shadowMapVolumePlanes; + unsigned int exposureVolumeCount; + GfxExposureVolume *exposureVolumes; + unsigned int exposureVolumePlaneCount; + GfxVolumePlane *exposureVolumePlanes; + unsigned int worldFogVolumeCount; + GfxWorldFogVolume *worldFogVolumes; + unsigned int worldFogVolumePlaneCount; + GfxVolumePlane *worldFogVolumePlanes; + unsigned int worldFogModifierVolumeCount; + GfxWorldFogModifierVolume *worldFogModifierVolumes; + unsigned int worldFogModifierVolumePlaneCount; + GfxVolumePlane *worldFogModifierVolumePlanes; + unsigned int lutVolumeCount; + GfxLutVolume *lutVolumes; + unsigned int lutVolumePlaneCount; + GfxVolumePlane *lutVolumePlanes; + GfxSkyDynamicIntensity skyDynIntensity; + GfxWorldDpvsPlanes dpvsPlanes; + int cellBitsCount; + GfxCell *cells; + GfxWorldDraw draw; + GfxLightGrid lightGrid; + int modelCount; + GfxBrushModel *models; + vec3_t mins; + vec3_t maxs; + unsigned int checksum; + int materialMemoryCount; + MaterialMemory *materialMemory; + sunflare_t sun; + vec4_t outdoorLookupMatrix[4]; + GfxImage *outdoorImage; + unsigned int *cellCasterBits; + GfxSceneDynModel *sceneDynModel; + GfxSceneDynBrush *sceneDynBrush; + unsigned int *primaryLightEntityShadowVis; + unsigned int *primaryLightDynEntShadowVis[2]; + unsigned int numSiegeSkinInsts; + SSkinInstance *siegeSkinInsts; + GfxShadowGeometry *shadowGeom; + GfxLightRegion *lightRegion; + GfxWorldDpvsStatic dpvs; + GfxWorldDpvsDynamic dpvsDyn; + float waterDirection; + GfxWaterBuffer waterBuffers[2]; + Material *waterMaterial; + Material *coronaMaterial; + Material *ropeMaterial; + Material *lutMaterial; + unsigned int numOccluders; + Occluder *occluders; + unsigned int numOutdoorBounds; + GfxOutdoorBounds *outdoorBounds; + unsigned int heroLightCount; + unsigned int heroLightTreeCount; + GfxHeroLight *heroLights; + GfxHeroLightTree *heroLightTree; + unsigned int lightingFlags; + int lightingQuality; +}; + +struct type_align(4) GfxLightImage { + GfxImage *image; + char samplerState; +}; + +struct GfxLightDef { + const char *name; + GfxLightImage attenuation; + int lmapLookupStart; +}; + +struct Font_s { + const char *fontName; + int pixelHeight; + int isScalingAllowed; + int glyphCount; + int kerningPairsCount; + Material *material; + Material *glowMaterial; + Glyph *glyphs; + KerningPairs *kerningPairs; +}; + +struct FontIcon { + const char *name; + int numEntries; + int numAliasEntries; + FontIconEntry *fontIconEntry; + FontIconAlias *fontIconAlias; +}; + +struct MenuList { + const char *name; + int menuCount; + menuDef_t **menus; +}; + +struct rectDef_s { + float x; + float y; + float w; + float h; + int horzAlign; + int vertAlign; +}; + +struct windowDef_t { + const char *name; + rectDef_s rect; + rectDef_s rectClient; + const char *group; + char style; + char border; + char modal; + char frameSides; + float frameTexSize; + float frameSize; + int ownerDraw; + int ownerDrawFlags; + float borderSize; + int staticFlags; + int dynamicFlags[1]; + int nextTime; + vec4_t foreColor; + vec4_t backColor; + vec4_t borderColor; + vec4_t outlineColor; + float rotation; + Material *background; +}; + +struct ExpressionStatement { + char *filename; + int line; + int numRpn; + expressionRpn *rpn; +}; + +struct type_align(8) menuDef_t { + windowDef_t window; + const char *font; + int fullScreen; + int ui3dWindowId; + int itemCount; + int fontIndex; + int cursorItem[1]; + int fadeCycle; + int priority; + float fadeClamp; + float fadeAmount; + float fadeInAmount; + float blurRadius; + int openSlideSpeed; + int closeSlideSpeed; + int openSlideDirection; + int closeSlideDirection; + rectDef_s initialRectInfo; + int openFadingTime; + int closeFadingTime; + int fadeTimeCounter; + int slideTimeCounter; + GenericEventHandler *onEvent; + ItemKeyHandler *onKey; + ExpressionStatement visibleExp; + gcc_align(8) uint64_t showBits; + gcc_align(8) uint64_t hideBits; + const char *allowedBinding; + const char *soundName; + int imageTrack; + int control; + vec4_t focusColor; + vec4_t disableColor; + ExpressionStatement rectXExp; + ExpressionStatement rectYExp; + itemDef_s **items; +}; + +struct LocalizeEntry { + const char *value; + const char *name; +}; + +enum weaponIconRatioType_t { + WEAPON_ICON_RATIO_1TO1 = 0x0, + WEAPON_ICON_RATIO_2TO1 = 0x1, + WEAPON_ICON_RATIO_4TO1 = 0x2, + WEAPON_ICON_RATIO_COUNT = 0x3, +}; + +enum eAttachment { + ATTACHMENT_NONE = 0x0, + ATTACHMENT_ACOG = 0x1, + ATTACHMENT_DUALCLIP = 0x2, + ATTACHMENT_DUALOPTIC = 0x3, + ATTACHMENT_DW = 0x4, + ATTACHMENT_EXTBARREL = 0x5, + ATTACHMENT_EXTCLIP = 0x6, + ATTACHMENT_EXTRAMAGS = 0x7, + ATTACHMENT_FASTADS = 0x8, + ATTACHMENT_FASTRELOAD = 0x9, + ATTACHMENT_FMJ = 0xA, + ATTACHMENT_GL = 0xB, + ATTACHMENT_GRIP = 0xC, + ATTACHMENT_HOLO = 0xD, + ATTACHMENT_IR = 0xE, + ATTACHMENT_IRONSIGHTS = 0xF, + ATTACHMENT_LONGBREATH = 0x10, + ATTACHMENT_MK = 0x11, + ATTACHMENT_MMS = 0x12, + ATTACHMENT_RANGEFINDER = 0x13, + ATTACHMENT_REFLEX = 0x14, + ATTACHMENT_RF = 0x15, + ATTACHMENT_SELECTFIRE = 0x16, + ATTACHMENT_SILENCER = 0x17, + ATTACHMENT_STACKFIRE = 0x18, + ATTACHMENT_STALKER = 0x19, + ATTACHMENT_STEADYAIM = 0x1A, + ATTACHMENT_SWAYREDUC = 0x1B, + ATTACHMENT_TACKNIFE = 0x1C, + ATTACHMENT_VZOOM = 0x1D, + ATTACHMENT_TYPE_COUNT = 0x1E, + ATTACHMENT_INVALID = 0x1E, +}; + +enum eAttachmentPoint { + ATTACHMENT_POINT_NONE = 0x0, + ATTACHMENT_POINT_TOP = 0x1, + ATTACHMENT_POINT_FIRST = 0x1, + ATTACHMENT_POINT_BOTTOM = 0x2, + ATTACHMENT_POINT_TRIGGER = 0x3, + ATTACHMENT_POINT_MUZZLE = 0x4, + ATTACHMENT_POINT_GUNPERK = 0x5, + ATTACHMENT_POINT_COUNT = 0x6, + ATTACHMENT_POINT_INVALID = 0x6, +}; + +enum PenetrateType { + PENETRATE_TYPE_NONE = 0x0, + PENETRATE_TYPE_SMALL = 0x1, + PENETRATE_TYPE_MEDIUM = 0x2, + PENETRATE_TYPE_LARGE = 0x3, + PENETRATE_TYPE_COUNT = 0x4, +}; + +enum weapFireType_t { + WEAPON_FIRETYPE_FULLAUTO = 0x0, + WEAPON_FIRETYPE_SINGLESHOT = 0x1, + WEAPON_FIRETYPE_BURSTFIRE2 = 0x2, + WEAPON_FIRETYPE_BURSTFIRE3 = 0x3, + WEAPON_FIRETYPE_BURSTFIRE4 = 0x4, + WEAPON_FIRETYPE_BURSTFIRE5 = 0x5, + WEAPON_FIRETYPE_STACKED = 0x6, + WEAPON_FIRETYPE_MINIGUN = 0x7, + WEAPON_FIRETYPE_CHARGESHOT = 0x8, + WEAPON_FIRETYPE_JETGUN = 0x9, + WEAPON_FIRETYPECOUNT = 0xA, +}; + +enum eAttachmentOverrideSounds { + ATTACHMENT_OVERRIDE_SOUND_FIRE, + ATTACHMENT_OVERRIDE_SOUND_FIRE_PLAYER, + ATTACHMENT_OVERRIDE_SOUND_FIRE_LOOP, + ATTACHMENT_OVERRIDE_SOUND_FIRE_LOOP_PLAYER, + ATTACHMENT_OVERRIDE_SOUND_FIRE_LOOP_END, + ATTACHMENT_OVERRIDE_SOUND_FIRE_LOOP_END_PLAYER, + ATTACHMENT_OVERRIDE_SOUND_FIRE_START, + ATTACHMENT_OVERRIDE_SOUND_FIRE_STOP, + ATTACHMENT_OVERRIDE_SOUND_FIRE_START_PLAYER, + ATTACHMENT_OVERRIDE_SOUND_FIRE_STOP_PLAYER, + ATTACHMENT_OVERRIDE_SOUND_FIRE_LAST, + ATTACHMENT_OVERRIDE_SOUND_FIRE_LAST_PLAYER, + + NUM_ATTACHMENT_OVERRIDE_SOUNDS +}; + +enum eAttachmentOverrideEffects { + ATTACHMENT_OVERRIDE_EFFECT_VIEW_FLASH, + ATTACHMENT_OVERRIDE_EFFECT_WORLD_FLASH, + + NUM_ATTACHMENT_OVERRIDE_EFFECTS +}; + +struct WeaponAttachment { + const char *szInternalName; + const char *szDisplayName; + eAttachment attachmentType; + eAttachmentPoint attachmentPoint; + PenetrateType penetrateType; + weapFireType_t fireType; + int firstRaisePriority; + float fHipIdleAmount; + bool bAltWeaponAdsOnly; + bool bAltWeaponDisableSwitching; + float altScopeADSTransInTime; + float altScopeADSTransOutTime; + bool bSilenced; + bool bDualMag; + bool laserSight; + bool bInfraRed; + bool bUseAsMelee; + bool bDualWield; + bool sharedAmmo; + float fDamageRangeScale; + float fAdsZoomFov1; + float fAdsZoomFov2; + float fAdsZoomFov3; + float fAdsZoomInFrac; + float fAdsZoomOutFrac; + float fAdsTransInTimeScale; + float fAdsTransOutTimeScale; + float fAdsRecoilReductionRate; + float fAdsRecoilReductionLimit; + float fAdsViewKickCenterSpeedScale; + float fAdsIdleAmountScale; + bool swayOverride; + float swayMaxAngle; + float swayLerpSpeed; + float swayPitchScale; + float swayYawScale; + float swayHorizScale; + float swayVertScale; + bool adsSwayOverride; + float adsSwayMaxAngle; + float adsSwayLerpSpeed; + float adsSwayPitchScale; + float adsSwayYawScale; + float fAdsSwayHorizScale; + float fAdsSwayVertScale; + float adsMoveSpeedScale; + float fHipSpreadMinScale; + float fHipSpreadMaxScale; + float strafeRotR; + float standMoveF; + vec3_t vStandRot; + float fFireTimeScale; + float fReloadTimeScale; + float fReloadEmptyTimeScale; + float fReloadAddTimeScale; + float fReloadQuickTimeScale; + float fReloadQuickEmptyTimeScale; + float fReloadQuickAddTimeScale; + bool mmsWeapon; + bool mmsInScope; + float mmsFOV; + float mmsAspect; + float mmsMaxDist; + float clipSizeScale; + int iClipSize; + unsigned int stackFire; + float stackFireSpread; + float stackFireAccuracyDecay; + unsigned int perks[2]; + float customFloat0; + float customFloat1; + float customFloat2; + int customBool0; + int customBool1; + int customBool2; +}; + +enum weapOverlayReticle_t { + WEAPOVERLAYRETICLE_NONE = 0x0, + WEAPOVERLAYRETICLE_CROSSHAIR = 0x1, + WEAPOVERLAYRETICLE_NUM = 0x2, +}; + +struct WeaponAttachmentUnique { + const char *szInternalName; + eAttachment attachmentType; + int siblingLink; + int childLink; + int combinedAttachmentTypeMask; + const char *szAltWeaponName; + unsigned int altWeaponIndex; + const char *szDualWieldWeaponName; + unsigned int dualWieldWeaponIndex; + uint16_t *hideTags; + XModel *viewModel; + XModel *viewModelAdditional; + XModel *viewModelADS; + XModel *worldModel; + XModel *worldModelAdditional; + const char *viewModelTag; + const char *worldModelTag; + vec3_t viewModelOffsets; + vec3_t worldModelOffsets; + vec3_t viewModelRotations; + vec3_t worldModelRotations; + vec3_t viewModelAddOffsets; + vec3_t worldModelAddOffsets; + vec3_t viewModelAddRotations; + vec3_t worldModelAddRotations; + WeaponCamo *weaponCamo; + bool disableBaseWeaponAttachment; + bool disableBaseWeaponClip; + bool overrideBaseWeaponAttachmentOffsets; + vec3_t viewModelOffsetBaseAttachment; + vec3_t worldModelOffsetBaseAttachment; + Material *overlayMaterial; + Material *overlayMaterialLowRes; + weapOverlayReticle_t overlayReticle; + int iFirstRaiseTime; + int iAltRaiseTime; + int iAltDropTime; + int iReloadAmmoAdd; + int iReloadStartAdd; + bool bSegmentedReload; + const char **szXAnims; + int animationOverrides[3]; + float *locationDamageMultipliers; + int soundOverrides; + const char *fireSound; + const char *fireSoundPlayer; + const char *fireLoopSound; + const char *fireLoopSoundPlayer; + const char *fireLoopEndSound; + const char *fireLoopEndSoundPlayer; + const char *fireStartSound; + const char *fireStopSound; + const char *fireStartSoundPlayer; + const char *fireStopSoundPlayer; + const char *fireLastSound; + const char *fireLastSoundPlayer; + const char *fireKillcamSound; + const char *fireKillcamSoundPlayer; + int effectOverrides; + FxEffectDef *viewFlashEffect; + FxEffectDef *worldFlashEffect; + TracerDef *tracerType; + TracerDef *enemyTracerType; + float adsDofStart; + float adsDofEnd; + int iAmmoIndex; + int iClipIndex; + bool bOverrideLeftHandIK; + bool bOverrideLeftHandProneIK; + vec3_t ikLeftHandOffset; + vec3_t ikLeftHandRotation; + vec3_t ikLeftHandProneOffset; + vec3_t ikLeftHandProneRotation; + float customFloat0; + float customFloat1; + float customFloat2; + int customBool0; + int customBool1; + int customBool2; +}; + +struct WeaponAttachmentUniqueFull { + WeaponAttachmentUnique attachment; + const char *szXAnims[88]; + uint16_t hideTags[32]; + float locationDamageMultipliers[21]; +}; + +struct WeaponCamo { + const char *name; + GfxImage *solidBaseImage; + GfxImage *patternBaseImage; + WeaponCamoSet *camoSets; + unsigned int numCamoSets; + WeaponCamoMaterialSet *camoMaterials; + unsigned int numCamoMaterials; +}; + +struct SndDriverGlobals { + const char *name; + unsigned int groupCount; + SndVolumeGroup *groups; + unsigned int curveCount; + SndCurve *curves; + unsigned int panCount; + SndPan *pans; + unsigned int duckGroupCount; + SndDuckGroup *duckGroups; + unsigned int contextCount; + SndContext *contexts; + unsigned int masterCount; + SndMaster *masters; + unsigned int voiceDuckCount; + SndSidechainDuck *voiceDucks; + unsigned int futzCount; + SndFutz *futzes; +}; + +struct FxFloatRange { + float base; + float amplitude; +}; + +struct FxEffectDef { + const char *name; + uint16_t flags; + char efPriority; + int16_t elemDefCountLooping; + int16_t elemDefCountOneShot; + int16_t elemDefCountEmission; + int totalSize; + int msecLoopingLife; + int msecNonLoopingLife; + FxElemDef *elemDefs; + vec3_t boundingBoxDim; + vec3_t boundingBoxCentre; + float occlusionQueryDepthBias; + int occlusionQueryFadeIn; + int occlusionQueryFadeOut; + FxFloatRange occlusionQueryScaleRange; +}; + +struct FxImpactTable { + const char *name; + FxImpactEntry *table; +}; + +struct RawFile { + const char *name; + int len; + const char16 *buffer; +}; + +struct StringTable { + const char *name; + int columnCount; + int rowCount; + StringTableCell *values; + int16_t *cellIndex; +}; + +enum LbUpdateType { + LBUPDATE_TYPE_NORMAL = 0x0, + LBUPDATE_TYPE_RANK = 0x1, + LBUPDATE_TYPE_COMBINE = 0x2, + LBUPDATE_TYPE_COUNT = 0x3, +}; + +struct LeaderboardDef { + const char *name; + unsigned int id; + int columnCount; + int dwColumnCount; + int xpColId; + int prestigeColId; + LbColumnDef *columns; + LbUpdateType updateType; + int trackTypes; +}; + +struct gump_info_t { + char *name; + int size; +}; + +struct overlay_info_t { + char *name; + int size; +}; + +struct XGlobals { + const char *name; + int xanimStreamBufferSize; + int cinematicMaxWidth; + int cinematicMaxHeight; + int extracamResolution; + vec4_t screenClearColor; + int bigestGumpSize; + int gumpsCount; + gump_info_t gumps[32]; + int bigestOverlaySize; + int overlayCount; + overlay_info_t overlays[32]; +}; + +struct ddlRoot_t { + const char *name; + ddlDef_t *ddlDef; +}; + +struct Glasses { + const char *name; + unsigned int numGlasses; + Glass *glasses; + char *workMemory; + unsigned int workMemorySize; + unsigned int smallAllocatorBlocks; + unsigned int maxGroups; + unsigned int maxShards; + unsigned int maxPhysics; + unsigned int shardMemorySize; + unsigned int maxFreeCmd; + unsigned int numSlots; + unsigned int numVerts; + unsigned int numIndices; +}; + +struct EmblemLayer { + int cost; + int unlockLevel; + int unlockPLevel; +}; + +struct EmblemCategory { + const char *name; + const char *description; +}; + +struct EmblemIconType { + const char *name; + const char *description; +}; + +struct EmblemBGCategory { + const char *name; + const char *description; +}; + +struct EmblemIcon { + GfxImage *image; + const char *description; + float outlineSize; + int cost; + int unlockLevel; + int unlockPLevel; + int unclassifyAt; + int sortKey; + uint16_t iconType; + uint16_t category; +}; + +struct EmblemBackground { + Material *material; + const char *description; + int cost; + int unlockLevel; + int unlockPLevel; + int unclassifyAt; + int sortKey; + uint16_t bgCategory; + int mtxIndex; +}; + +struct EmblemSet { + int colorCount; + int layerCount; + EmblemLayer *layers; + int categoryCount; + EmblemCategory *categories; + int iconTypeCount; + EmblemIconType *iconTypes; + int bgCategoryCount; + EmblemBGCategory *bgCategories; + int iconCount; + EmblemIcon *icons; + int backgroundCount; + EmblemBackground *backgrounds; + int backgroundLookupCount; + int16_t *backgroundLookup; +}; + +struct ScriptParseTree { + const char *name; + int len; + byte32 *buffer; +}; + +struct KeyValuePairs { + const char *name; + int numVariables; + KeyValuePair *keyValuePairs; +}; + +struct view_limits_t { + float horizSpanLeft; + float horizSpanRight; + float vertSpanUp; + float vertSpanDown; + float horizResistLeft; + float horizResistRight; + float vertResistUp; + float vertResistDown; +}; + +enum TractionType { + TRACTION_TYPE_FRONT = 0x0, + TRACTION_TYPE_BACK = 0x1, + TRACTION_TYPE_ALL_WD = 0x2, + NUM_TRACTION_TYPES = 0x3, +}; + +struct VehicleParameter { + float m_speed_max; + float m_accel_max; + float m_reverse_scale; + float m_steer_angle_max; + float m_steer_angle_speed_scale; + float m_steer_speed; + float m_wheel_radius; + float m_susp_spring_k; + float m_susp_damp_k; + float m_susp_adj; + float m_susp_hard_limit; + float m_susp_min_height; + float m_tire_fric_fwd; + float m_tire_fric_side; + float m_tire_fric_brake; + float m_tire_fric_hand_brake; + float m_body_mass; + float m_roll_stability; + float m_pitch_stability; + float m_pitch_roll_resistance; + float m_yaw_resistance; + float m_upright_strength; + float m_tilt_fakey; + float m_peel_out_max_speed; + float m_tire_damp_coast; + float m_tire_damp_brake; + float m_tire_damp_hand; + float m_auto_hand_brake_min_speed; + TractionType m_traction_type; + const char *m_name; + vec3_t m_bbox_min; + vec3_t m_bbox_max; + vec3_t m_mass_center_offset; + vec3_t m_buoyancybox_min; + vec3_t m_buoyancybox_max; + float m_water_speed_max; + float m_water_accel_max; + float m_water_turn_accel; + float m_water_turn_speed_max; + float m_water_ebrake_power; + vec3_t m_boat_motor_offset; + float m_boat_speed_rise; + float m_boat_speed_tilt; + float m_boat_side_fric_scale; + float m_boat_forward_fric_scale; + float m_boat_vertical_fric_scale; + float m_jump_force; + float m_tire_fric_side_max; + bool m_drive_on_walls; + float m_linear_drag_scale; + float m_angular_drag_scale; +}; + +struct VehicleDriveBySound { + int apex; + const char *name; + unsigned int alias; +}; + +struct VehicleEngineSound { + const char *name; + unsigned int alias; + float params[5]; +}; + +struct VehicleGearData { + float minRPM; + float maxRPM; + float ratio; +}; + +struct VehicleEngine { + float idleRpms; + float maxRpms; + float maxTorque; + float brakingCoeff; + vec4_t loadFadeParams; + float loadScale; + float loadSmoothing; + float throttleLag; + float pitchScale; + VehicleEngineSound onload[5]; + VehicleEngineSound offload[5]; + int numGears; + int loopLastGear; + VehicleGearData gears[10]; +}; + +struct VehicleAntenna { + float springK; + float damp; + float length; + float gravity; +}; + +enum VehicleSeatPositions { + VEH_POS_NONE = 0xFFFFFFFF, + VEH_POS_DRIVER = 0x0, + VEH_POS_MIN_GUNNER = 0x1, + VEH_POS_GUNNER_1 = 0x1, + VEH_POS_GUNNER_2 = 0x2, + VEH_POS_GUNNER_3 = 0x3, + VEH_POS_GUNNER_4 = 0x4, + VEH_POS_MAX_GUNNER = 0x4, + VEH_POS_MIN_PASSENGER = 0x5, + VEH_POS_PASSENGER_1 = 0x5, + VEH_POS_PASSENGER_2 = 0x6, + VEH_POS_PASSENGER_3 = 0x7, + VEH_POS_PASSENGER_4 = 0x8, + VEH_POS_PASSENGER_5 = 0x9, + VEH_POS_PASSENGER_6 = 0xA, + VEH_POS_MAX_PASSENGER = 0xA, + NUM_VEHICLE_POSITIONS = 0xB, +}; + +enum VehicleSound { + VEH_TURRET_SPIN_SND = 0x0, + VEH_TURRET_STOP_SND = 0x1, + NUM_VEHICLE_SNDS = 0x2, +}; + +enum VehicleMaterialSound { + VEH_WHEEL_ROAD_NOISE = 0x0, + VEH_WHEEL_SLIDING = 0x1, + VEH_WHEEL_PEELING_OUT = 0x2, + NUM_VEHICLE_MATERIAL_SNDS = 0x3, +}; + +enum VehicleMantlePoints { + MANTLE_ANGLE_FRONT = 0x0, + MANTLE_ANGLE_BACK = 0x1, + MANTLE_ANGLE_LEFT = 0x2, + MANTLE_ANGLE_RIGHT = 0x3, + MANTLE_ANGLE_MAX = 0x4, +}; + +enum VehicleWheelType { + FL_WHEEL = 0x0, + FR_WHEEL = 0x1, + BL_WHEEL = 0x2, + BR_WHEEL = 0x3, + ML_WHEEL = 0x4, + MR_WHEEL = 0x5, + NUM_VEHICLE_WHEELS = 0x6, +}; + +enum VehicleEngineSoundParam { + VEH_ENGINESND_FADE_IN_START = 0x0, + VEH_ENGINESND_FADE_IN_END = 0x1, + VEH_ENGINESND_FADE_OUT_START = 0x2, + VEH_ENGINESND_FADE_OUT_END = 0x3, + VEH_ENGINESND_PITCH_REF = 0x4, + NUM_VEHICLE_ENGINESND_PARAMS = 0x5, +}; + +enum team_t { + TEAM_FREE = 0x0, + TEAM_BAD = 0x0, + TEAM_ALLIES = 0x1, + TEAM_AXIS = 0x2, + TEAM_THREE = 0x3, + TEAM_FOUR = 0x4, + TEAM_FIVE = 0x5, + TEAM_SIX = 0x6, + TEAM_SEVEN = 0x7, + TEAM_EIGHT = 0x8, + TEAM_NUM_PLAYING_TEAMS = 0x9, + TEAM_SPECTATOR = 0x9, + TEAM_NUM_TEAMS = 0xA, + TEAM_LOCALPLAYERS = 0xB, + TEAM_FIRST_PLAYING_TEAM = 0x1, + TEAM_LAST_PLAYING_TEAM = 0x8, +}; + +struct VehicleDef { + const char *name; + int16_t type; + int remoteControl; + int bulletDamage; + int armorPiercingDamage; + int grenadeDamage; + int projectileDamage; + int projectileSplashDamage; + int heavyExplosiveDamage; + int16_t cameraMode; + int autoRecenterOnAccel; + int thirdPersonDriver; + int thirdPersonUseVehicleRoll; + int thirdPersonCameraPitchVehicleRelative; + int thirdPersonCameraHeightWorldRelative; + float thirdPersonCameraRange; + float thirdPersonCameraMinPitchClamp; + float thirdPersonCameraMaxPitchClamp; + float thirdPersonCameraHeight[2]; + float thirdPersonCameraPitch[2]; + int cameraAlwaysAutoCenter; + float cameraAutoCenterLerpRate; + float cameraAutoCenterMaxLerpRate; + float thirdPersonCameraSpringDistance; + float thirdPersonCameraSpringTime; + float thirdPersonCameraHandbrakeTurnRateInc; + float cameraFOV; + float cameraRollFraction; + vec3_t tagPlayerOffset; + int killcamCollision; + float killcamDist; + float killcamZDist; + float killcamMinDist; + float killcamZTargetOffset; + float killcamFOV; + float killcamNearBlur; + float killcamNearBlurStart; + float killcamNearBlurEnd; + float killcamFarBlur; + float killcamFarBlurStart; + float killcamFarBlurEnd; + int isDrivable; + int numberOfSeats; + int numberOfGunners; + int seatSwitchOrder[11]; + int driverControlledGunPos; + float entryPointRadius[5]; + float texScrollScale; + float wheelRotRate; + float extraWheelRotScale; + int wheelChildTakesSteerYaw; + float maxSpeed; + float maxSpeedVertical; + float accel; + float accelVertical; + float rotRate; + float rotAccel; + float maxBodyPitch; + float maxBodyRoll; + float collisionDamage; + float collisionSpeed; + float suspensionTravel; + float heliCollisionScalar; + float viewPitchOffset; + float viewInfluence; + float tiltFromAcceleration[2]; + float tiltFromDeceleration[2]; + float tiltFromVelocity[2]; + float tiltSpeed[2]; + const char *turretWeapon; + view_limits_t turretViewLimits; + float turretRotRate; + int turretClampPlayerView; + int turretLockTurretToPlayerView; + const char *gunnerWeapon[4]; + uint16_t gunnerWeaponIndex[4]; + float gunnerRotRate; + vec2_t gunnerRestAngles[4]; + view_limits_t passengerViewLimits[6]; + const char *sndNames[2]; + unsigned int sndIndices[2]; + const char *sndMaterialNames[3]; + float skidSpeedMin; + float skidSpeedMax; + const char *futzName; + float futzBlend; + int animType; + const char *animSet; + int scriptedAnimationEntry; + float mantleAngles[4]; + uint16_t extraWheelTags[4]; + uint16_t driverHideTag; + XModel *attachmentModels[4]; + uint16_t attachmentTags[4]; + XModel *deathAttachmentModels[4]; + uint16_t deathAttachmentTags[4]; + float tracerOffset[2]; + XModel *model; + XModel *viewModel; + XModel *deathModel; + XModel *enemyModel; + float modelSwapDelay; + FxEffectDef *exhaustFx; + int oneExhaust; + FxEffectDef *treadFx[32]; + FxEffectDef *deathFx; + uint16_t deathFxTag; + const char *deathFxSound; + FxEffectDef *lightFx[4]; + uint16_t lightFxTag[4]; + FxEffectDef *friendlyLightFx; + uint16_t friendlyLightFxTag; + FxEffectDef *enemyLightFx; + uint16_t enemyLightFxTag; + float radiusDamageMin; + float radiusDamageMax; + float radiusDamageRadius; + const char *shootShock; + const char *shootRumble; + float deathQuakeScale; + float deathQuakeDuration; + float deathQuakeRadius; + const char *rumbleType; + float rumbleScale; + float rumbleDuration; + float rumbleRadius; + float rumbleBaseTime; + float rumbleAdditionalTime; + int healthDefault; + int healthMin; + int healthMax; + int eTeam; + int boostAccelMultiplier; + float boostDuration; + float boostSpeedIncrease; + int addToCompass; + int addToCompassEnemy; + const char *compassIcon; + Material *compassIconMaterial; + const char *gasButtonName; + int gasButton; + const char *reverseBrakeButtonName; + int reverseBrakeButton; + const char *handBrakeButtonName; + int handBrakeButton; + const char *attackButtonName; + int attackButton; + const char *attackSecondaryButtonName; + int attackSecondaryButton; + const char *boostButtonName; + int boostButton; + const char *moveUpButtonName; + int moveUpButton; + const char *moveDownButtonName; + int moveDownButton; + const char *switchSeatButtonName; + int switchSeatButton; + const char *steerGraphName; + GraphFloat *steerGraph; + const char *accelGraphName; + GraphFloat *accelGraph; + int isNitrous; + int isFourWheelSteering; + int useCollmap; + float radius; + float minHeight; + float maxHeight; + float max_fric_tilt_angle; + float max_fric_tilt; + int noDirectionalDamage; + int fakeBodyStabilizer; + float vehHelicopterBoundsRadius; + float vehHelicopterDecelerationFwd; + float vehHelicopterDecelerationSide; + float vehHelicopterDecelerationUp; + float vehHelicopterTiltFromControllerAxes; + float vehHelicopterTiltFromFwdAndYaw; + float vehHelicopterTiltFromFwdAndYaw_VelAtMaxTilt; + float vehHelicopterTiltMomentum; + int vehHelicopterQuadRotor; + int vehHelicopterAccelTwardsView; + float maxRotorArmMovementAngle; + float maxRotorArmRotationAngle; + int vehHelicopterMaintainHeight; + int vehHelicopterMaintainMaxHeight; + float vehHelicopterMaintainHeightLimit; + float vehHelicopterMaintainHeightAccel; + float vehHelicopterMaintainHeightMinimum; + float vehHelicopterMaintainHeightMaximum; + float vehHelicopterMaintainCeilingMinimum; + int joltVehicle; + int joltVehicleDriver; + float joltMaxTime; + float joltTime; + float joltWaves; + float joltIntensity; + VehicleParameter nitrousVehParams; + float driveBySoundRadius[2]; + VehicleDriveBySound driveBySounds[40]; + int doFootSteps; + int isSentient; + VehicleEngine engine; + VehicleAntenna antenna[2]; + char *csvInclude; + float customFloat0; + float customFloat1; + float customFloat2; + int customBool0; + int customBool1; + int customBool2; +}; + +union MemoryBlockData { + char *mainData; + char *videoData; + char *streamData; +}; + +struct MemoryBlock { + const char *name; + bool mainMem; + bool videoMem; + bool streamMem; + unsigned int size; + unsigned int alignment; + MemoryBlockData data; +}; + +struct cmodel_t2 { + vec3_t mins; + vec3_t maxs; + float radius; + ClipInfo *info; + cLeaf_s leaf; +}; + +struct AddonMapEnts { + const char *name; + char *entityString; + int numEntityChars; + MapTriggers trigger; + ClipInfo *info; + unsigned int numSubModels; + cmodel_t2 *cmodels; + GfxBrushModel *models; +}; + +enum tracerType_t { + TRACERTYPE_LASER = 0x0, + TRACERTYPE_SMOKE = 0x1, + TRACERTYPE_NUM = 0x2, +}; + +struct TracerDef { + const char *name; + tracerType_t type; + Material *material; + unsigned int drawInterval; + float speed; + float beamLength; + float beamWidth; + float screwRadius; + float screwDist; + float fadeTime; + float fadeScale; + float texRepeatRate; + vec4_t colors[5]; +}; + +struct SkinnedVertsDef { + const char *name; + unsigned int maxSkinnedVerts; +}; + +struct Qdb { + const char *name; + int len; + byte32 *buffer; +}; + +struct Slug { + const char *name; + int len; + byte32 *buffer; +}; + +struct FootstepTableDef { + const char *name; + unsigned int sndAliasTable[32][7]; +}; + +struct FootstepFXTableDef { + const char *name; + FxEffectDef *footstepFX[32]; +}; + +struct ZBarrierBoard { + XModel *pBoardModel; + XModel *pAlternateBoardModel; + XModel *pUpgradedBoardModel; + const char *pTearAnim; + const char *pBoardAnim; + FxEffectDef *repairEffect1; + FxEffectDef *repairEffect2; + vec3_t repairEffect1Offset; + vec3_t repairEffect2Offset; + unsigned int boardRepairSound; + unsigned int boardRepairHoverSound; + unsigned int pauseAndRepeatRepSound; + float minPause; + float maxPause; + uint16_t zombieBoardTearStateName; + uint16_t zombieBoardTearSubStateName; + unsigned int numRepsToPullProBoard; +}; + +struct ZBarrierDef { + const char *name; + unsigned int generalRepairSound1; + unsigned int generalRepairSound2; + unsigned int upgradedGeneralRepairSound1; + unsigned int upgradedGeneralRepairSound2; + unsigned int delayBetweenRepSounds; + float delayBetweenRepSoundsDuration; + unsigned int earthquakeOnRepair; + float earthquakeMinScale; + float earthquakeMaxScale; + float earthquakeMinDuration; + float earthquakeMaxDuration; + float earthquakeRadius; + int numBoardsInBarrier; + unsigned int autoHideOpenPieces; + unsigned int taunts; + unsigned int reachThroughAttacks; + uint16_t zombieTauntAnimState; + uint16_t zombieReachThroughAnimState; + int numAttackSlots; + float attackSpotHorzOffset; + ZBarrierBoard boards[6]; +}; + +struct XModelPiece { + XModel *model; + vec3_t offset; +}; + +struct DestructibleStage { + uint16_t showBone; + float breakHealth; + float maxTime; + unsigned int flags; + FxEffectDef *breakEffect; + const char *breakSound; + const char *breakNotify; + const char *loopSound; + XModel *spawnModel[3]; + PhysPreset *physPreset; +}; + +struct DestructiblePiece { + DestructibleStage stages[5]; + char parentPiece; + float parentDamagePercent; + float bulletDamageScale; + float explosiveDamageScale; + float meleeDamageScale; + float impactDamageScale; + float entityDamageTransfer; + PhysConstraints *physConstraints; + int health; + const char *damageSound; + FxEffectDef *burnEffect; + const char *burnSound; + uint16_t enableLabel; + int hideBones[5]; +}; + +struct XAnimNotifyInfo { + uint16_t name; + float time; +}; + +struct XAnimDeltaPart { + XAnimPartTrans *trans; + XAnimDeltaPartQuat2 *quat2; + XAnimDeltaPartQuat *quat; +}; + +struct DObjAnimMat { + vec4_t quat; + vec3_t trans; + float transWeight; +}; + +struct XSurfaceVertexInfo { + int16_t vertCount[4]; + uint16_t *vertsBlend; + float *tensionData; +}; + +typedef tdef_align(16) unsigned short r_index16_t; + +struct type_align(16) XSurface { + char tileMode; + unsigned char vertListCount; + uint16_t flags; + uint16_t vertCount; + uint16_t triCount; + uint16_t baseVertIndex; + r_index16_t(*triIndices)[3]; + XSurfaceVertexInfo vertInfo; + GfxPackedVertex *verts0; + void /*ID3D11Buffer*/ *vb0; + XRigidVertList *vertList; + void /*ID3D11Buffer*/ *indexBuffer; + int partBits[5]; +}; + +struct XModelCollSurf_s { + XModelCollTri_s *collTris; + int numCollTris; + vec3_t mins; + vec3_t maxs; + int boneIdx; + int contents; + int surfFlags; +}; + +struct type_align(4) XBoneInfo { + vec3_t bounds[2]; + vec3_t offset; + float radiusSquared; + char collmap; +}; + +struct Collmap { + PhysGeomList *geomList; +}; + +struct MaterialTextureDef { + unsigned int nameHash; + char nameStart; + char nameEnd; + char samplerState; + char semantic; + char isMatureContent; + char pad[3]; + GfxImage *image; +}; + +struct type_align(16) MaterialConstantDef { + unsigned int nameHash; + char name[12]; + vec4_t literal; +}; + +enum GfxStateBitsEnum : unsigned int { + GFXS0_SRCBLEND_RGB_SHIFT = 0x0, + GFXS0_SRCBLEND_RGB_MASK = 0xF, + GFXS0_DSTBLEND_RGB_SHIFT = 0x4, + GFXS0_DSTBLEND_RGB_MASK = 0xF0, + GFXS0_BLENDOP_RGB_SHIFT = 0x8, + GFXS0_BLENDOP_RGB_MASK = 0x700, + GFXS0_BLEND_RGB_MASK = 0x7FF, + GFXS0_ATEST_SHIFT = 0xB, + GFXS0_ATEST_DISABLE = 0x800, + GFXS0_ATEST_GT_0 = 0x0, + GFXS0_ATEST_GE_128 = 0x1000, + GFXS0_ATEST_MASK = 0x1000, + GFXS0_CULL_SHIFT = 0xE, + GFXS0_CULL_NONE = 0x4000, + GFXS0_CULL_BACK = 0x8000, + GFXS0_CULL_FRONT = 0xC000, + GFXS0_CULL_MASK = 0xC000, + GFXS0_SRCBLEND_ALPHA_SHIFT = 0x10, + GFXS0_SRCBLEND_ALPHA_MASK = 0xF0000, + GFXS0_DSTBLEND_ALPHA_SHIFT = 0x14, + GFXS0_DSTBLEND_ALPHA_MASK = 0xF00000, + GFXS0_BLENDOP_ALPHA_SHIFT = 0x18, + GFXS0_BLENDOP_ALPHA_MASK = 0x7000000, + GFXS0_BLEND_ALPHA_MASK = 0x7FF0000, + GFXS0_COLORWRITE_RGB = 0x8000000, + GFXS0_COLORWRITE_ALPHA = 0x10000000, + GFXS0_COLORWRITE_MASK = 0x18000000, + GFXS0_POLYMODE_LINE = 0x80000000, + GFXS1_DEPTHWRITE = 0x1, + GFXS1_DEPTHTEST_DISABLE = 0x2, + GFXS1_DEPTHTEST_SHIFT = 0x2, + GFXS1_DEPTHTEST_ALWAYS = 0x0, + GFXS1_DEPTHTEST_LESS = 0x4, + GFXS1_DEPTHTEST_EQUAL = 0x8, + GFXS1_DEPTHTEST_LESSEQUAL = 0xC, + GFXS1_DEPTHTEST_MASK = 0xC, + GFXS1_DEPTHFUNC_MASK = 0xF, + GFXS1_POLYGON_OFFSET_SHIFT = 0x4, + GFXS1_POLYGON_OFFSET_0 = 0x0, + GFXS1_POLYGON_OFFSET_1 = 0x10, + GFXS1_POLYGON_OFFSET_2 = 0x20, + GFXS1_POLYGON_OFFSET_SHADOWMAP = 0x30, + GFXS1_POLYGON_OFFSET_MASK = 0x30, + GFXS1_STENCIL_FRONT_ENABLE = 0x40, + GFXS1_STENCIL_BACK_ENABLE = 0x80, + GFXS1_STENCIL_MASK = 0xC0, + GFXS1_STENCIL_FRONT_PASS_SHIFT = 0x8, + GFXS1_STENCIL_FRONT_FAIL_SHIFT = 0xB, + GFXS1_STENCIL_FRONT_ZFAIL_SHIFT = 0xE, + GFXS1_STENCIL_FRONT_FUNC_SHIFT = 0x11, + GFXS1_STENCIL_FRONT_MASK = 0xFFF00, + GFXS1_STENCIL_BACK_PASS_SHIFT = 0x14, + GFXS1_STENCIL_BACK_FAIL_SHIFT = 0x17, + GFXS1_STENCIL_BACK_ZFAIL_SHIFT = 0x1A, + GFXS1_STENCIL_BACK_FUNC_SHIFT = 0x1D, + GFXS1_STENCIL_BACK_MASK = 0xFFF00000, + GFXS1_STENCILFUNC_FRONTBACK_MASK = 0xE00E0000, + GFXS1_STENCILOP_FRONTBACK_MASK = 0x1FF1FF00, +}; + +struct GfxStateBits { + unsigned int loadBits[2]; + void /*ID3D11BlendState*/ *blendState; + void /*ID3D11DepthStencilState*/ *depthStencilState; + void /*ID3D11RasterizerState*/ *rasterizerState; +}; + +/* struct IUnknown +{ + IUnknownVtbl *vfptr; +};*/ - union GfxColor - { - unsigned int packed; - char array[4]; - }; +/* struct __cppobj ID3D11DeviceChild : IUnknown +{ +};*/ +/* struct __cppobj ID3D11PixelShader : ID3D11DeviceChild +{ +};*/ - union PackedTexCoords - { - unsigned int packed; - }; +/* struct __cppobj ID3D11VertexShader : ID3D11DeviceChild +{ +};*/ + +struct MaterialPass { + MaterialVertexDeclaration *vertexDecl; + MaterialVertexShader *vertexShader; + MaterialPixelShader *pixelShader; + char perPrimArgCount; + char perObjArgCount; + char stableArgCount; + char customSamplerFlags; + char precompiledIndex; + char materialType; + MaterialShaderArgument *args; +}; + +struct MaterialTechnique { + const char *name; + uint16_t flags; + uint16_t passCount; + MaterialPass passArray[1]; +}; + +/* struct __cppobj ID3D11View : ID3D11DeviceChild +{ +};*/ +/* struct __cppobj ID3D11ShaderResourceView : ID3D11View +{ +};*/ + +struct type_align(4) GfxImageLoadDef { + char levelCount; + char flags; + int format; + int resourceSize; + char data[1]; +}; + +struct SndAliasList { + const char *name; + unsigned int id; + SndAlias *head; + int count; + int sequence; +}; + +struct type_align(4) SndIndexEntry { + uint16_t value; + uint16_t next; +}; + +struct SndRadverb { + char name[32]; + unsigned int id; + float smoothing; + float earlyTime; + float lateTime; + float earlyGain; + float lateGain; + float returnGain; + float earlyLpf; + float lateLpf; + float inputLpf; + float dampLpf; + float wallReflect; + float dryGain; + float earlySize; + float lateSize; + float diffusion; + float returnHighpass; +}; + +typedef tdef_align(16) float SndFloatAlign16; + +struct SndDuck { + char name[32]; + unsigned int id; + float fadeIn; + float fadeOut; + float startDelay; + float distance; + float length; + unsigned int fadeInCurve; + unsigned int fadeOutCurve; + SndFloatAlign16 *attenuation; + SndFloatAlign16 *filter; + int updateWhilePaused; +}; + +enum snd_asset_format { + SND_ASSET_FORMAT_PCMS16 = 0x0, + SND_ASSET_FORMAT_PCMS24 = 0x1, + SND_ASSET_FORMAT_PCMS32 = 0x2, + SND_ASSET_FORMAT_IEEE = 0x3, + SND_ASSET_FORMAT_XMA4 = 0x4, + SND_ASSET_FORMAT_MP3 = 0x5, + SND_ASSET_FORMAT_MSADPCM = 0x6, + SND_ASSET_FORMAT_WMA = 0x7, + SND_ASSET_FORMAT_FLAC = 0x8, + SND_ASSET_FORMAT_WIIUADPCM = 0x9, + SND_ASSET_FORMAT_MPC = 0xA, + + SND_ASSET_FORMAT_COUNT +}; + +struct SndAssetBankEntry { + unsigned int id; + unsigned int size; + unsigned int offset; + unsigned int frameCount; + char frameRateIndex; + char channelCount; + char looping; + char format; +}; + +struct SndDialogScriptIdLookup { + unsigned int scriptId; + unsigned int aliasId; +}; + +struct cplane_s { + vec3_t normal; + float dist; + char type; + char signbits; + char pad[2]; +}; + +struct ClipMaterial { + const char *name; + int surfaceFlags; + int contentFlags; +}; + +struct cbrushside_t { + cplane_s *plane; + int cflags; + int sflags; +}; + +struct cLeafBrushNodeLeaf_t { + LeafBrush *brushes; +}; + +struct cLeafBrushNodeChildren_t { + float dist; + float range; + uint16_t childOffset[2]; +}; + +union cLeafBrushNodeData_t { + cLeafBrushNodeLeaf_t leaf; + cLeafBrushNodeChildren_t children; +}; + +struct cLeafBrushNode_s { + char axis; + int16_t leafBrushCount; + int contents; + cLeafBrushNodeData_t data; +}; + +struct type_align(16) cbrush_t { + vec3_t mins; + int contents; + vec3_t maxs; + unsigned int numsides; + cbrushside_t *sides; + int axial_cflags[2][3]; + int axial_sflags[2][3]; + unsigned int numverts; + vec3_t *verts; +}; + +struct Bounds { + vec3_t midPoint; + vec3_t halfSize; +}; + +struct cStaticModelWritable { + uint16_t nextModelInWorldSector; +}; + +struct cStaticModel_s { + cStaticModelWritable writable; + XModel *xmodel; + int contents; + vec3_t origin; + vec3_t invScaledAxis[3]; + vec3_t absmin; + vec3_t absmax; +}; + +struct cNode_t { + cplane_s *plane; + int16_t children[2]; +}; + +struct CollisionPartition { + char triCount; + int firstTri; + int nuinds; + int fuind; +}; + +union CollisionAabbTreeIndex { + int firstChildIndex; + int partitionIndex; +}; + +struct type_align(16) CollisionAabbTree { + vec3_t origin; + uint16_t materialIndex; + uint16_t childCount; + vec3_t halfSize; + CollisionAabbTreeIndex u; +}; + +enum DynEntityType { + DYNENT_TYPE_INVALID = 0x0, + DYNENT_TYPE_CLUTTER = 0x1, + DYNENT_TYPE_DESTRUCT = 0x2, + DYNENT_TYPE_COUNT = 0x3, +}; + +struct GfxPlacement { + vec4_t quat; + vec3_t origin; +}; + +struct DynEntityDef { + DynEntityType type; + GfxPlacement pose; + XModel *xModel; + XModel *destroyedxModel; + uint16_t brushModel; + uint16_t physicsBrushModel; + FxEffectDef *destroyFx; + unsigned int destroySound; + XModelPieces *destroyPieces; + PhysPreset *physPreset; + int16_t physConstraints[4]; + int health; + int flags; + int contents; + uint16_t targetname; + uint16_t target; +}; + +struct DynEntityPose { + GfxPlacement pose; + float radius; +}; + +struct DynEntityClient { + int physObjId; + uint16_t flags; + uint16_t lightingHandle; + int health; + uint16_t burnTime; + uint16_t fadeTime; + int physicsStartTime; +}; + +struct DynEntityServer { + uint16_t flags; + int health; +}; + +struct DynEntityColl { + uint16_t sector; + uint16_t nextEntInSector; + vec3_t linkMins; + vec3_t linkMaxs; + int contents; +}; + +struct par_t { + vec3_t p; + vec3_t p0; + vec3_t p_prev; + int flags; +}; + +enum rope_constraint_e { + ROPE_PAIR_CONSTRAINT = 0x0, + ROPE_WORLD_CONSTRAINT = 0x1, + ROPE_DENTITY_CONSTRAINT = 0x2, + ROPE_CENTITY_CONSTRAINT = 0x3, +}; + +struct type_align(4) constraint_t { + vec3_t p; + rope_constraint_e type; + int entity_index; + int bone_name_hash; + char pi1; + char pi2; +}; + +struct rope_frame_verts_t { + int num_verts; + vec3_t v[50]; +}; + +struct rope_client_verts_t { + rope_frame_verts_t frame_verts[2]; + unsigned int frame_index; +}; + +struct type_align(4) rope_t { + par_t m_particles[25]; + constraint_t m_constraints[30]; + int m_entity_anchors[3]; + int m_num_particles; + int m_num_constraints; + int m_num_entity_anchors; + int m_num_draw_verts; + rope_client_verts_t m_client_verts; + vec3_t m_min; + vec3_t m_max; + vec3_t m_start; + vec3_t m_end; + int m_in_use; + int m_visible; + int m_dist_constraint; + int m_flags; + Material *m_material; + float m_seglen; + float m_length; + float m_width; + float m_scale; + float m_force_scale; + int m_health; + int m_frame; + int m_stable_count; + int m_static_rope; + uint16_t m_lightingHandle; +}; + +struct ComPrimaryLight { + char type; + char canUseShadowMap; + char exponent; + char priority; + int16_t cullDist; + char useCookie; + char shadowmapVolume; + vec3_t color; + vec3_t dir; + vec3_t origin; + float radius; + float cosHalfFovOuter; + float cosHalfFovInner; + float cosHalfFovExpanded; + float rotationLimit; + float translationLimit; + float mipDistance; + float dAttenuation; + float roundness; + vec4_t diffuseColor; + vec4_t falloff; + vec4_t angle; + vec4_t aAbB; + vec4_t cookieControl0; + vec4_t cookieControl1; + vec4_t cookieControl2; + const char *defName; +}; + +enum nodeType { + NODE_BADNODE = 0x0, + NODE_PATHNODE = 0x1, + NODE_COVER_STAND = 0x2, + NODE_COVER_CROUCH = 0x3, + NODE_COVER_CROUCH_WINDOW = 0x4, + NODE_COVER_PRONE = 0x5, + NODE_COVER_RIGHT = 0x6, + NODE_COVER_LEFT = 0x7, + NODE_COVER_PILLAR = 0x8, + NODE_AMBUSH = 0x9, + NODE_EXPOSED = 0xA, + NODE_CONCEALMENT_STAND = 0xB, + NODE_CONCEALMENT_CROUCH = 0xC, + NODE_CONCEALMENT_PRONE = 0xD, + NODE_REACQUIRE = 0xE, + NODE_BALCONY = 0xF, + NODE_SCRIPTED = 0x10, + NODE_NEGOTIATION_BEGIN = 0x11, + NODE_NEGOTIATION_END = 0x12, + NODE_TURRET = 0x13, + NODE_GUARD = 0x14, + NODE_NUMTYPES = 0x15, + NODE_DONTLINK = 0x15, +}; + +struct pathnode_constant_t { + nodeType type; + int spawnflags; + uint16_t targetname; + uint16_t script_linkName; + uint16_t script_noteworthy; + uint16_t target; + uint16_t animscript; + int animscriptfunc; + vec3_t vOrigin; + float fAngle; + vec2_t forward; + float fRadius; + float minUseDistSq; + int16_t wOverlapNode[2]; + uint16_t totalLinkCount; + pathlink_s *Links; +}; + +struct SentientHandle { + uint16_t number; + uint16_t infoIndex; +}; + +struct type_align(4) pathnode_dynamic_t { + SentientHandle pOwner; + int iFreeTime; + int iValidTime[3]; + int dangerousNodeTime[3]; + int inPlayerLOSTime; + int16_t wLinkCount; + int16_t wOverlapCount; + int16_t turretEntNumber; + int16_t userCount; + bool hasBadPlaceLink; +}; + +struct pathnode_transient_t { + int iSearchFrame; + pathnode_t *pNextOpen; + pathnode_t *pPrevOpen; + pathnode_t *pParent; + float fCost; + float fHeuristic; + + union { + float nodeCost; + int linkIndex; + }; +}; + +struct pathnode_t { + pathnode_constant_t constant; + pathnode_dynamic_t dynamic; + pathnode_transient_t transient; +}; + +struct type_align(16) pathbasenode_t { + vec3_t vOrigin; + unsigned int type; +}; + +struct pathnode_tree_nodes_t { + int nodeCount; + uint16_t *nodes; +}; + +union pathnode_tree_info_t { + pathnode_tree_t *child[2]; + pathnode_tree_nodes_t s; +}; + +struct pathnode_tree_t { + int axis; + float dist; + pathnode_tree_info_t u; +}; + +struct TriggerModel { + int contents; + uint16_t hullCount; + uint16_t firstHull; +}; + +struct TriggerHull { + Bounds bounds; + int contents; + uint16_t slabCount; + uint16_t firstSlab; +}; + +struct TriggerSlab { + vec3_t dir; + float midPoint; + float halfSize; +}; + +struct type_align(16) GfxStreamingAabbTree { + vec4_t mins; + vec4_t maxs; + float maxStreamingDistance; + uint16_t firstItem; + uint16_t itemCount; + uint16_t firstChild; + uint16_t childCount; + uint16_t smodelCount; + uint16_t surfaceCount; +}; + +struct type_align(16) float44 { + union { + vec4_t m[4]; + float member[16]; + }; +}; + +struct type_align(16) GfxLight { + char type; + char canUseShadowMap; + char shadowmapVolume; + int16_t cullDist; + vec3_t color; + vec3_t dir; + vec3_t origin; + float radius; + float cosHalfFovOuter; + float cosHalfFovInner; + int exponent; + unsigned int spotShadowIndex; + float dAttenuation; + float roundness; + vec3_t angles; + float spotShadowHiDistance; + vec4_t diffuseColor; + vec4_t shadowColor; + vec4_t falloff; + vec4_t aAbB; + vec4_t cookieControl0; + vec4_t cookieControl1; + vec4_t cookieControl2; + float44 viewMatrix; + float44 projMatrix; + GfxLightDef *def; +}; + +struct GfxLightCorona { + vec3_t origin; + float radius; + vec3_t color; + float intensity; +}; + +struct GfxShadowMapVolume { + unsigned int control; + unsigned int padding1; + unsigned int padding2; + unsigned int padding3; +}; + +struct GfxVolumePlane { + vec4_t plane; +}; + +struct GfxExposureVolume { + unsigned int control; + float exposure; + float luminanceIncreaseScale; + float luminanceDecreaseScale; + float featherRange; + float featherAdjust; +}; + +struct GfxWorldFogVolume { + vec3_t mins; + unsigned int control; + vec3_t maxs; + float fogTransitionTime; + unsigned int controlEx; + GfxWorldFog volumeWorldFog[1]; +}; + +struct GfxWorldFogModifierVolume { + unsigned int control; + uint16_t minX; + uint16_t minY; + uint16_t minZ; + uint16_t maxX; + uint16_t maxY; + uint16_t maxZ; + unsigned int controlEx; + float transitionTime; + float depthScale; + float heightScale; + vec4_t colorAdjust; +}; + +struct GfxLutVolume { + vec3_t mins; + unsigned int control; + vec3_t maxs; + float lutTransitionTime; + unsigned int lutIndex; +}; + +struct GfxCell { + vec3_t mins; + vec3_t maxs; + int aabbTreeCount; + GfxAabbTree *aabbTree; + int portalCount; + GfxPortal *portals; + char reflectionProbeCount; + char *reflectionProbes; +}; + +struct GfxLightingSH { + vec4_t V0; + vec4_t V1; + vec4_t V2; +}; + +struct GfxReflectionProbe { + vec3_t origin; + GfxLightingSH lightingSH; + GfxImage *reflectionImage; + GfxReflectionProbeVolumeData *probeVolumes; + unsigned int probeVolumeCount; + float mipLodBias; +}; + +struct GfxLightmapArray { + GfxImage *primary; + GfxImage *secondary; +}; + +/* struct __cppobj ID3D11Resource : ID3D11DeviceChild +{ +};*/ - union PackedUnitVec - { - unsigned int packed; - }; +/* struct __cppobj ID3D11Buffer : ID3D11Resource +{ +};*/ + +struct type_align(4) GfxLightGridEntry { + uint16_t colorsIndex; + char primaryLightIndex; + char visibility; +}; + +struct type_align(4) GfxCompressedLightGridColors { char rgb[56][3]; }; + +struct GfxCompressedLightGridCoeffs { + uint16_t coeffs[9][3]; +}; + +struct GfxSkyGridVolume { + vec3_t mins; + vec3_t maxs; + vec3_t lightingOrigin; + uint16_t colorsIndex; + char primaryLightIndex; + char visibility; +}; + +struct GfxBrushModelWritable { + vec3_t mins; + float padding1; + vec3_t maxs; + float padding2; +}; + +struct type_align(16) GfxBrushModel { + GfxBrushModelWritable writable; + vec3_t bounds[2]; + unsigned int surfaceCount; + unsigned int startSurfIndex; +}; + +struct MaterialMemory { + Material *material; + int memory; +}; + +union XModelDrawInfo { + struct { + char state; + char lod; + uint16_t surfId; + }; + + unsigned int packed; +}; + +struct GfxSceneDynModel { + XModelDrawInfo info; + uint16_t dynEntId; + char primaryLightIndex; + char reflectionProbeIndex; +}; + +struct BModelDrawInfo { + uint16_t surfId; +}; + +struct type_align(4) GfxSceneDynBrush { + BModelDrawInfo info; + uint16_t dynEntId; +}; + +union gcc_align(8) __m128 { + float m128_f32[4]; + uint64_t m128_u64[2]; + char m128_i8[16]; + int16_t m128_i16[8]; + int m128_i32[4]; + int64_t m128_i64[2]; + char m128_u8[16]; + uint16_t m128_u16[8]; + unsigned int m128_u32[4]; +}; + +struct vector3 { + __m128 x; + __m128 y; + __m128 z; +}; + +struct vector4 { + __m128 x; + __m128 y; + __m128 z; + __m128 w; +}; + +struct type_align(16) SSkinInstance { + union { + vector4 mat; + float disk_mat[16]; + }; + + SSkinShaders *shaders; + SSkinModel *model; + SSkinAnim *anim; + SSkinVert *instVerts; + float frame; + int pad1; + int pad2; + int pad3; +}; + +struct GfxShadowGeometry { + uint16_t surfaceCount; + uint16_t smodelCount; + uint16_t *sortedSurfIndex; + uint16_t *smodelIndex; +}; + +struct GfxLightRegion { + unsigned int hullCount; + GfxLightRegionHull *hulls; +}; + +struct GfxStaticModelInst { + vec3_t mins; + vec3_t maxs; + vec3_t lightingOrigin; +}; + +struct srfTriangles_t { + vec3_t mins; + int vertexDataOffset0; + vec3_t maxs; + int vertexDataOffset1; + int firstVertex; + float himipRadiusInvSq; + uint16_t vertexCount; + uint16_t triCount; + int baseIndex; +}; + +struct type_align(16) GfxSurface { + srfTriangles_t tris; + Material *material; + char lightmapIndex; + char reflectionProbeIndex; + char primaryLightIndex; + char flags; + vec3_t bounds[2]; +}; + +struct GfxPackedPlacement { + vec3_t origin; + vec3_t axis[3]; + float scale; +}; + +struct GfxLightingSHQuantized { + uint16_t V0[4]; + uint16_t V1[4]; + uint16_t V2[4]; +}; + +struct type_align(4) GfxStaticModelLmapVertexInfo { + unsigned int *lmapVertexColors; + void /*ID3D11Buffer*/ *lmapVertexColorsVB; + uint16_t numLmapVertexColors; +}; + +struct GfxStaticModelDrawInst { + float cullDist; + GfxPackedPlacement placement; + XModel *model; + int flags; + float invScaleSq; + uint16_t lightingHandle; + uint16_t colorsIndex; + GfxLightingSHQuantized lightingSH; + char primaryLightIndex; + char visibility; + char reflectionProbeIndex; + unsigned int smid; + GfxStaticModelLmapVertexInfo lmapVertexInfo[4]; +}; + +struct Occluder { + unsigned int flags; + char name[16]; + vec3_t points[4]; +}; + +struct GfxOutdoorBounds { + vec3_t bounds[2]; +}; + +struct GfxHeroLight { + char type; + char unused[3]; + vec3_t color; + vec3_t dir; + vec3_t origin; + float radius; + float cosHalfFovOuter; + float cosHalfFovInner; + int exponent; +}; + +struct GfxHeroLightTree { + vec3_t mins; + vec3_t maxs; + int leftNode; + int rightNode; +}; + +struct Glyph { + uint16_t letter; + char x0; + char y0; + char dx; + char pixelWidth; + char pixelHeight; + float s0; + float t0; + float s1; + float t1; +}; + +struct KerningPairs { + uint16_t wFirst; + uint16_t wSecond; + int iKernAmount; +}; + +struct FontIconName { + const char *string; + int hash; +}; + +struct FontIconEntry { + FontIconName fontIconName; + Material *fontIconMaterialHandle; + int fontIconSize; + float xScale; + float yScale; +}; + +struct FontIconAlias { + int aliasHash; + int buttonHash; +}; + +struct GenericEventHandler { + const char *name; + GenericEventScript *eventScript; + GenericEventHandler *next; +}; + +struct ItemKeyHandler { + int key; + GenericEventScript *keyScript; + ItemKeyHandler *next; +}; + +enum expDataType { + VAL_INT = 0x0, + VAL_FLOAT = 0x1, + VAL_STRING = 0x2, + VAL_ADDRESS = 0x3, + VAL_DVAR = 0x4, +}; + +union operandInternalDataUnion { + int intVal; + float floatVal; + const char *string; + dvar_t *dvar; +}; + +struct Operand { + expDataType dataType; + operandInternalDataUnion internals; +}; + +union expressionRpnDataUnion { + Operand constant; + void *cmd; + int cmdIdx; +}; + +enum expressionRpnEnum { + RPN_CONSTANT = 0x0, + RPN_CMD_IDX = 0x1, + RPN_CMD = 0x2, + RPN_END = 0x3, +}; + +struct expressionRpn { + int type; + expressionRpnDataUnion data; +}; + +enum ItemType { + ITEM_TYPE_DEFAULT = 0x0, + ITEM_TYPE_TEXT = 0x1, + ITEM_TYPE_IMAGE = 0x2, + ITEM_TYPE_BUTTON = 0x3, + ITEM_TYPE_LISTBOX = 0x4, + ITEM_TYPE_EDITFIELD = 0x5, + ITEM_TYPE_OWNERDRAW = 0x6, + ITEM_TYPE_NUMERICFIELD = 0x7, + ITEM_TYPE_SLIDER = 0x8, + ITEM_TYPE_YESNO = 0x9, + ITEM_TYPE_MULTI = 0xA, + ITEM_TYPE_DVARENUM = 0xB, + ITEM_TYPE_BIND = 0xC, + ITEM_TYPE_VALIDFILEFIELD = 0xD, + ITEM_TYPE_UPREDITFIELD = 0xE, + ITEM_TYPE_GAME_MESSAGE_WINDOW = 0xF, + ITEM_TYPE_BIND2 = 0x10, + ITEM_TYPE_HIGHLIGHT = 0x11, + ITEM_TYPE_OWNERDRAW_TEXT = 0x12, + ITEM_TYPE_OD_BUTTON = 0x13, + ITEM_TYPE_OD_TEXT_BUTTON = 0x14, + ITEM_TYPE_BUTTON_NO_TEXT = 0x15, + ITEM_TYPE_PROFILEMULTI = 0x16, + ITEM_TYPE_RADIOBUTTON = 0x19, + ITEM_TYPE_MODEL = 0x1A, + ITEM_TYPE_CHECKBOX = 0x1B, + ITEM_TYPE_COMBO = 0x1C, + ITEM_TYPE_DVAR_FLOAT = 0x1E, + ITEM_TYPE_CONFEDITFIELD = 0x1F, + ITEM_TYPE_MENUMODEL = 0x27 +}; + +union itemDefData_t { + textDef_s *textDef; + imageDef_s *imageDef; + focusItemDef_s *blankButtonDef; + ownerDrawDef_s *ownerDrawDef; + void *data; +}; + +struct type_align(8) itemDef_s { + windowDef_t window; + int type; + int dataType; + int imageTrack; + const char *dvar; + const char *profileVar; + const char *dvarTest; + const char *enableDvar; + int dvarFlags; + itemDefData_t typeData; + menuDef_t *parent; + rectData_s *rectExpData; + ExpressionStatement visibleExp; + uint64_t showBits; + uint64_t hideBits; + ExpressionStatement forecolorAExp; + int ui3dWindowId; + GenericEventHandler *onEvent; + UIAnimInfo *animInfo; +}; + +enum weapType_t { + WEAPTYPE_BULLET = 0x0, + WEAPTYPE_GRENADE = 0x1, + WEAPTYPE_PROJECTILE = 0x2, + WEAPTYPE_BINOCULARS = 0x3, + WEAPTYPE_GAS = 0x4, + WEAPTYPE_BOMB = 0x5, + WEAPTYPE_MINE = 0x6, + WEAPTYPE_MELEE = 0x7, + WEAPTYPE_RIOTSHIELD = 0x8, + WEAPTYPE_NUM = 0x9, +}; + +enum weapClass_t { + WEAPCLASS_RIFLE = 0x0, + WEAPCLASS_MG = 0x1, + WEAPCLASS_SMG = 0x2, + WEAPCLASS_SPREAD = 0x3, + WEAPCLASS_PISTOL = 0x4, + WEAPCLASS_GRENADE = 0x5, + WEAPCLASS_ROCKETLAUNCHER = 0x6, + WEAPCLASS_TURRET = 0x7, + WEAPCLASS_NON_PLAYER = 0x8, + WEAPCLASS_GAS = 0x9, + WEAPCLASS_ITEM = 0xA, + WEAPCLASS_MELEE = 0xB, + WEAPCLASS_KILLSTREAK_ALT_STORED_WEAPON = 0xC, + WEAPCLASS_PISTOL_SPREAD = 0xD, + WEAPCLASS_NUM = 0xE, +}; + +enum ImpactType { + IMPACT_TYPE_NONE = 0x0, + IMPACT_TYPE_BULLET_SMALL = 0x1, + IMPACT_TYPE_BULLET_LARGE = 0x2, + IMPACT_TYPE_BULLET_AP = 0x3, + IMPACT_TYPE_BULLET_XTREME = 0x4, + IMPACT_TYPE_SHOTGUN = 0x5, + IMPACT_TYPE_GRENADE_BOUNCE = 0x6, + IMPACT_TYPE_GRENADE_EXPLODE = 0x7, + IMPACT_TYPE_RIFLE_GRENADE = 0x8, + IMPACT_TYPE_ROCKET_EXPLODE = 0x9, + IMPACT_TYPE_ROCKET_EXPLODE_XTREME = 0xA, + IMPACT_TYPE_PROJECTILE_DUD = 0xB, + IMPACT_TYPE_MORTAR_SHELL = 0xC, + IMPACT_TYPE_TANK_SHELL = 0xD, + IMPACT_TYPE_BOLT = 0xE, + IMPACT_TYPE_BLADE = 0xF, + IMPACT_TYPE_COUNT = 0x10, +}; + +enum weapInventoryType_t { + WEAPINVENTORY_PRIMARY = 0x0, + WEAPINVENTORY_OFFHAND = 0x1, + WEAPINVENTORY_ITEM = 0x2, + WEAPINVENTORY_ALTMODE = 0x3, + WEAPINVENTORY_MELEE = 0x4, + WEAPINVENTORY_DWLEFTHAND = 0x5, + WEAPINVENTORYCOUNT = 0x6, +}; + +enum weapClipType_t { + WEAPON_CLIPTYPE_BOTTOM = 0x0, + WEAPON_CLIPTYPE_TOP = 0x1, + WEAPON_CLIPTYPE_LEFT = 0x2, + WEAPON_CLIPTYPE_DP28 = 0x3, + WEAPON_CLIPTYPE_PTRS = 0x4, + WEAPON_CLIPTYPE_LMG = 0x5, + WEAPON_CLIPTYPECOUNT = 0x6, +}; + +enum barrelType_t { + BARREL_TYPE_SINGLE = 0x0, + BARREL_TYPE_DUAL = 0x1, + BARREL_TYPE_DUAL_ALTERNATE = 0x2, + BARREL_TYPE_QUAD = 0x3, + BARREL_TYPE_QUAD_ALTERNATE = 0x4, + BARREL_TYPE_QUAD_DOUBLE_ALTERNATE = 0x5, + BARREL_TYPE_COUNT = 0x6, +}; + +enum OffhandClass { + OFFHAND_CLASS_NONE = 0x0, + OFFHAND_CLASS_FRAG_GRENADE = 0x1, + OFFHAND_CLASS_SMOKE_GRENADE = 0x2, + OFFHAND_CLASS_FLASH_GRENADE = 0x3, + OFFHAND_CLASS_GEAR = 0x4, + OFFHAND_CLASS_SUPPLYDROP_MARKER = 0x5, + OFFHAND_CLASS_COUNT = 0x6, +}; + +enum OffhandSlot { + OFFHAND_SLOT_NONE = 0x0, + OFFHAND_SLOT_LETHAL_GRENADE = 0x1, + OFFHAND_SLOT_TACTICAL_GRENADE = 0x2, + OFFHAND_SLOT_EQUIPMENT = 0x3, + OFFHAND_SLOT_SPECIFIC_USE = 0x4, + OFFHAND_SLOT_COUNT = 0x5, +}; + +enum weapStance_t { + WEAPSTANCE_STAND = 0x0, + WEAPSTANCE_DUCK = 0x1, + WEAPSTANCE_PRONE = 0x2, + WEAPSTANCE_NUM = 0x3, +}; + +enum activeReticleType_t { + VEH_ACTIVE_RETICLE_NONE = 0x0, + VEH_ACTIVE_RETICLE_PIP_ON_A_STICK = 0x1, + VEH_ACTIVE_RETICLE_BOUNCING_DIAMOND = 0x2, + VEH_ACTIVE_RETICLE_MISSILE_LOCK = 0x3, + VEH_ACTIVE_RETICLE_COUNT = 0x4, +}; + +enum ammoCounterClipType_t { + AMMO_COUNTER_CLIP_NONE = 0x0, + AMMO_COUNTER_CLIP_MAGAZINE = 0x1, + AMMO_COUNTER_CLIP_SHORTMAGAZINE = 0x2, + AMMO_COUNTER_CLIP_SHOTGUN = 0x3, + AMMO_COUNTER_CLIP_ROCKET = 0x4, + AMMO_COUNTER_CLIP_BELTFED = 0x5, + AMMO_COUNTER_CLIP_ALTWEAPON = 0x6, + AMMO_COUNTER_CLIP_COUNT = 0x7, +}; + +enum WeapOverlayInteface_t { + WEAPOVERLAYINTERFACE_NONE = 0x0, + WEAPOVERLAYINTERFACE_JAVELIN = 0x1, + WEAPOVERLAYINTERFACE_TURRETSCOPE = 0x2, + WEAPOVERLAYINTERFACECOUNT = 0x3, +}; + +enum weapProjExposion_t { + WEAPPROJEXP_GRENADE = 0x0, + WEAPPROJEXP_ROCKET = 0x1, + WEAPPROJEXP_FLASHBANG = 0x2, + WEAPPROJEXP_NONE = 0x3, + WEAPPROJEXP_DUD = 0x4, + WEAPPROJEXP_SMOKE = 0x5, + WEAPPROJEXP_HEAVY = 0x6, + WEAPPROJEXP_FIRE = 0x7, + WEAPPROJEXP_NAPALMBLOB = 0x8, + WEAPPROJEXP_BOLT = 0x9, + WEAPPROJEXP_SHRAPNELSPAN = 0xA, + WEAPPROJEXP_NUM = 0xB, +}; + +enum WeapStickinessType { + WEAPSTICKINESS_NONE = 0x0, + WEAPSTICKINESS_ALL = 0x1, + WEAPSTICKINESS_ALL_NO_SENTIENTS = 0x2, + WEAPSTICKINESS_GROUND = 0x3, + WEAPSTICKINESS_GROUND_WITH_YAW = 0x4, + WEAPSTICKINESS_FLESH = 0x5, + WEAPSTICKINESS_COUNT = 0x6, +}; + +enum WeapRotateType { + WEAPROTATE_GRENADE_ROTATE = 0x0, + WEAPROTATE_BLADE_ROTATE = 0x1, + WEAPROTATE_CYLINDER_ROTATE = 0x2, + WEAPROTATE_COUNT = 0x3, +}; + +enum guidedMissileType_t { + MISSILE_GUIDANCE_NONE = 0x0, + MISSILE_GUIDANCE_SIDEWINDER = 0x1, + MISSILE_GUIDANCE_HELLFIRE = 0x2, + MISSILE_GUIDANCE_JAVELIN = 0x3, + MISSILE_GUIDANCE_BALLISTIC = 0x4, + MISSILE_GUIDANCE_WIREGUIDED = 0x5, + MISSILE_GUIDANCE_TVGUIDED = 0x6, + MISSILE_GUIDANCE_DRONE = 0x7, + MISSILE_GUIDANCE_HEATSEEKING = 0x8, + MISSILE_GUIDANCE_COUNT = 0x9, +}; + +enum hitLocation_t { + HITLOC_NONE = 0x0, + HITLOC_HELMET = 0x1, + HITLOC_HEAD = 0x2, + HITLOC_NECK = 0x3, + HITLOC_TORSO_UPR = 0x4, + HITLOC_TORSO_MID = 0x5, + HITLOC_TORSO_LWR = 0x6, + HITLOC_R_ARM_UPR = 0x7, + HITLOC_L_ARM_UPR = 0x8, + HITLOC_R_ARM_LWR = 0x9, + HITLOC_L_ARM_LWR = 0xA, + HITLOC_R_HAND = 0xB, + HITLOC_L_HAND = 0xC, + HITLOC_R_LEG_UPR = 0xD, + HITLOC_L_LEG_UPR = 0xE, + HITLOC_R_LEG_LWR = 0xF, + HITLOC_L_LEG_LWR = 0x10, + HITLOC_R_FOOT = 0x11, + HITLOC_L_FOOT = 0x12, + HITLOC_GUN = 0x13, + HITLOC_SHIELD = 0x14, + + HITLOC_NUM, +}; + +struct WeaponDef { + const char *szOverlayName; // covered + XModel **gunXModel; // covered + XModel *handXModel; // covered + const char *szModeName; // covered + uint16_t *notetrackSoundMapKeys; // covered + uint16_t *notetrackSoundMapValues; // covered + int playerAnimType; // covered + weapType_t weapType; + weapClass_t weapClass; + PenetrateType penetrateTWeaponAttachmentype; + ImpactType impactType; + weapInventoryType_t inventoryType; + weapFireType_t fireType; + weapClipType_t clipType; + barrelType_t barrelType; + int itemIndex; + const char *parentWeaponName; + int iJamFireTime; + int overheatWeapon; + float overheatRate; + float cooldownRate; + float overheatEndVal; + bool coolWhileFiring; + bool fuelTankWeapon; + int iTankLifeTime; + OffhandClass offhandClass; + OffhandSlot offhandSlot; + weapStance_t stance; + FxEffectDef *viewFlashEffect; + FxEffectDef *worldFlashEffect; + FxEffectDef *barrelCooldownEffect; + int barrelCooldownMinCount; + vec3_t vViewFlashOffset; + vec3_t vWorldFlashOffset; + const char *pickupSound; + const char *pickupSoundPlayer; + const char *ammoPickupSound; + const char *ammoPickupSoundPlayer; + const char *projectileSound; + const char *pullbackSound; + const char *pullbackSoundPlayer; + const char *fireSound; + const char *fireSoundPlayer; + const char *fireLoopSound; + const char *fireLoopSoundPlayer; + const char *fireLoopEndSound; + const char *fireLoopEndSoundPlayer; + const char *fireStartSound; + const char *fireStopSound; + const char *fireKillcamSound; + const char *fireStartSoundPlayer; + const char *fireStopSoundPlayer; + const char *fireKillcamSoundPlayer; + const char *fireLastSound; + const char *fireLastSoundPlayer; + const char *emptyFireSound; + const char *emptyFireSoundPlayer; + const char *crackSound; + const char *whizbySound; + const char *meleeSwipeSound; + const char *meleeSwipeSoundPlayer; + const char *meleeHitSound; + const char *meleeMissSound; + const char *rechamberSound; + const char *rechamberSoundPlayer; + const char *reloadSound; + const char *reloadSoundPlayer; + const char *reloadEmptySound; + const char *reloadEmptySoundPlayer; + const char *reloadStartSound; + const char *reloadStartSoundPlayer; + const char *reloadEndSound; + const char *reloadEndSoundPlayer; + const char *rotateLoopSound; + const char *rotateLoopSoundPlayer; + const char *rotateStopSound; + const char *rotateStopSoundPlayer; + const char *deploySound; + const char *deploySoundPlayer; + const char *finishDeploySound; + const char *finishDeploySoundPlayer; + const char *breakdownSound; + const char *breakdownSoundPlayer; + const char *finishBreakdownSound; + const char *finishBreakdownSoundPlayer; + const char *detonateSound; + const char *detonateSoundPlayer; + const char *nightVisionWearSound; + const char *nightVisionWearSoundPlayer; + const char *nightVisionRemoveSound; + const char *nightVisionRemoveSoundPlayer; + const char *altSwitchSound; + const char *altSwitchSoundPlayer; + const char *raiseSound; + const char *raiseSoundPlayer; + const char *firstRaiseSound; + const char *firstRaiseSoundPlayer; + const char *adsRaiseSoundPlayer; + const char *adsLowerSoundPlayer; + const char *putawaySound; + const char *putawaySoundPlayer; + const char *overheatSound; + const char *overheatSoundPlayer; + const char *adsZoomSound; + const char *shellCasing; + const char *shellCasingPlayer; + const char **bounceSound; + const char *standMountedWeapdef; + const char *crouchMountedWeapdef; + const char *proneMountedWeapdef; + int standMountedIndex; + int crouchMountedIndex; + int proneMountedIndex; + FxEffectDef *viewShellEjectEffect; + FxEffectDef *worldShellEjectEffect; + FxEffectDef *viewLastShotEjectEffect; + FxEffectDef *worldLastShotEjectEffect; + vec3_t vViewShellEjectOffset; + vec3_t vWorldShellEjectOffset; + vec3_t vViewShellEjectRotation; + vec3_t vWorldShellEjectRotation; + Material *reticleCenter; + Material *reticleSide; + int iReticleCenterSize; + int iReticleSideSize; + int iReticleMinOfs; + activeReticleType_t activeReticleType; + vec3_t vStandMove; + vec3_t vStandRot; + vec3_t vDuckedOfs; + vec3_t vDuckedMove; + vec3_t vDuckedSprintOfs; + vec3_t vDuckedSprintRot; + vec2_t vDuckedSprintBob; + float fDuckedSprintCycleScale; + vec3_t vSprintOfs; + vec3_t vSprintRot; + vec2_t vSprintBob; + float fSprintCycleScale; + vec3_t vLowReadyOfs; + vec3_t vLowReadyRot; + vec3_t vRideOfs; + vec3_t vRideRot; + vec3_t vDtpOfs; + vec3_t vDtpRot; + vec2_t vDtpBob; + float fDtpCycleScale; + vec3_t vMantleOfs; + vec3_t vMantleRot; + vec3_t vSlideOfs; + vec3_t vSlideRot; + vec3_t vDuckedRot; + vec3_t vProneOfs; + vec3_t vProneMove; + vec3_t vProneRot; + vec3_t vStrafeMove; + vec3_t vStrafeRot; + float fPosMoveRate; + float fPosProneMoveRate; + float fStandMoveMinSpeed; + float fDuckedMoveMinSpeed; + float fProneMoveMinSpeed; + float fPosRotRate; + float fPosProneRotRate; + float fStandRotMinSpeed; + float fDuckedRotMinSpeed; + float fProneRotMinSpeed; + XModel **worldModel; + XModel *worldClipModel; + XModel *rocketModel; + XModel *mountedModel; + XModel *additionalMeleeModel; + Material *fireTypeIcon; + Material *hudIcon; + weaponIconRatioType_t hudIconRatio; + Material *indicatorIcon; + weaponIconRatioType_t indicatorIconRatio; + Material *ammoCounterIcon; + weaponIconRatioType_t ammoCounterIconRatio; + ammoCounterClipType_t ammoCounterClip; + int iStartAmmo; + int iMaxAmmo; + int shotCount; + const char *szSharedAmmoCapName; + int iSharedAmmoCapIndex; + int iSharedAmmoCap; + bool unlimitedAmmo; + bool ammoCountClipRelative; + int damage[6]; + float damageRange[6]; + int minPlayerDamage; + float damageDuration; + float damageInterval; + int playerDamage; + int iMeleeDamage; + int iDamageType; + uint16_t explosionTag; + int iFireDelay; + int iMeleeDelay; + int meleeChargeDelay; + int iDetonateDelay; + int iSpinUpTime; + int iSpinDownTime; + float spinRate; + const char *spinLoopSound; + const char *spinLoopSoundPlayer; + const char *startSpinSound; + const char *startSpinSoundPlayer; + const char *stopSpinSound; + const char *stopSpinSoundPlayer; + bool applySpinPitch; + int iFireTime; + int iLastFireTime; + int iRechamberTime; + int iRechamberBoltTime; + int iHoldFireTime; + int iDetonateTime; + int iMeleeTime; + int iBurstDelayTime; + int meleeChargeTime; + int iReloadTimeRight; + int iReloadTimeLeft; + int reloadShowRocketTime; + int iReloadEmptyTimeLeft; + int iReloadAddTime; + int iReloadEmptyAddTime; + int iReloadQuickAddTime; + int iReloadQuickEmptyAddTime; + int iReloadStartTime; + int iReloadStartAddTime; + int iReloadEndTime; + int iDropTime; + int iRaiseTime; + int iAltDropTime; + int quickDropTime; + int quickRaiseTime; + int iFirstRaiseTime; + int iEmptyRaiseTime; + int iEmptyDropTime; + int sprintInTime; + int sprintLoopTime; + int sprintOutTime; + int lowReadyInTime; + int lowReadyLoopTime; + int lowReadyOutTime; + int contFireInTime; + int contFireLoopTime; + int contFireOutTime; + int dtpInTime; + int dtpLoopTime; + int dtpOutTime; + int crawlInTime; + int crawlForwardTime; + int crawlBackTime; + int crawlRightTime; + int crawlLeftTime; + int crawlOutFireTime; + int crawlOutTime; + int slideInTime; + int deployTime; + int breakdownTime; + int iFlourishTime; + int nightVisionWearTime; + int nightVisionWearTimeFadeOutEnd; + int nightVisionWearTimePowerUp; + int nightVisionRemoveTime; + int nightVisionRemoveTimePowerDown; + int nightVisionRemoveTimeFadeInStart; + int fuseTime; + int aiFuseTime; + int lockOnRadius; + int lockOnSpeed; + bool requireLockonToFire; + bool noAdsWhenMagEmpty; + bool avoidDropCleanup; + unsigned int stackFire; + float stackFireSpread; + float stackFireAccuracyDecay; + const char *stackSound; + float autoAimRange; + float aimAssistRange; + bool mountableWeapon; + float aimPadding; + float enemyCrosshairRange; + bool crosshairColorChange; + float moveSpeedScale; + float adsMoveSpeedScale; + float sprintDurationScale; + weapOverlayReticle_t overlayReticle; + WeapOverlayInteface_t overlayInterface; + float overlayWidth; + float overlayHeight; + float fAdsBobFactor; + float fAdsViewBobMult; + bool bHoldBreathToSteady; + float fHipSpreadStandMin; + float fHipSpreadDuckedMin; + float fHipSpreadProneMin; + float hipSpreadStandMax; + float hipSpreadDuckedMax; + float hipSpreadProneMax; + float fHipSpreadDecayRate; + float fHipSpreadFireAdd; + float fHipSpreadTurnAdd; + float fHipSpreadMoveAdd; + float fHipSpreadDuckedDecay; + float fHipSpreadProneDecay; + float fHipReticleSidePos; + float fAdsIdleAmount; + float fHipIdleAmount; + float adsIdleSpeed; + float hipIdleSpeed; + float fIdleCrouchFactor; + float fIdleProneFactor; + float fGunMaxPitch; + float fGunMaxYaw; + float swayMaxAngle; + float swayLerpSpeed; + float swayPitchScale; + float swayYawScale; + float swayHorizScale; + float swayVertScale; + float swayShellShockScale; + float adsSwayMaxAngle; + float adsSwayLerpSpeed; + float adsSwayPitchScale; + float adsSwayYawScale; + bool sharedAmmo; + bool bRifleBullet; + bool armorPiercing; + bool bAirburstWeapon; + bool bBoltAction; + bool bUseAltTagFlash; + bool bUseAntiLagRewind; + bool bIsCarriedKillstreakWeapon; + bool aimDownSight; + bool bRechamberWhileAds; + bool bReloadWhileAds; + float adsViewErrorMin; + float adsViewErrorMax; + bool bCookOffHold; + bool bClipOnly; + bool bCanUseInVehicle; + bool bNoDropsOrRaises; + bool adsFireOnly; + bool cancelAutoHolsterWhenEmpty; + bool suppressAmmoReserveDisplay; + bool laserSight; + bool laserSightDuringNightvision; + bool bHideThirdPerson; + bool bHasBayonet; + bool bDualWield; + bool bExplodeOnGround; + bool bThrowBack; + bool bRetrievable; + bool bDieOnRespawn; + bool bNoThirdPersonDropsOrRaises; + bool bContinuousFire; + bool bNoPing; + bool bForceBounce; + bool bUseDroppedModelAsStowed; + bool bNoQuickDropWhenEmpty; + bool bKeepCrosshairWhenADS; + bool bUseOnlyAltWeaoponHideTagsInAltMode; + bool bAltWeaponAdsOnly; + bool bAltWeaponDisableSwitching; + Material *killIcon; + weaponIconRatioType_t killIconRatio; + bool flipKillIcon; + bool bNoPartialReload; + bool bSegmentedReload; + bool bNoADSAutoReload; + int iReloadAmmoAdd; + int iReloadStartAdd; + const char *szSpawnedGrenadeWeaponName; + const char *szDualWieldWeaponName; + unsigned int dualWieldWeaponIndex; + int iDropAmmoMin; + int iDropAmmoMax; + int iDropClipAmmoMin; + int iDropClipAmmoMax; + int iShotsBeforeRechamber; + bool blocksProne; + bool bShowIndicator; + int isRollingGrenade; + int useBallisticPrediction; + int isValuable; + int isTacticalInsertion; + bool isReviveWeapon; + bool bUseRigidBodyOnVehicle; + int iExplosionRadius; + int iExplosionRadiusMin; + int iIndicatorRadius; + int iExplosionInnerDamage; + int iExplosionOuterDamage; + float damageConeAngle; + int iProjectileSpeed; + int iProjectileSpeedUp; + int iProjectileSpeedRelativeUp; + int iProjectileSpeedForward; + float fProjectileTakeParentVelocity; + int iProjectileActivateDist; + float projLifetime; + float timeToAccelerate; + float projectileCurvature; + XModel *projectileModel; + weapProjExposion_t projExplosion; + FxEffectDef *projExplosionEffect; + bool projExplosionEffectForceNormalUp; + FxEffectDef *projExplosionEffect2; + bool projExplosionEffect2ForceNormalUp; + FxEffectDef *projExplosionEffect3; + bool projExplosionEffect3ForceNormalUp; + FxEffectDef *projExplosionEffect4; + bool projExplosionEffect4ForceNormalUp; + FxEffectDef *projExplosionEffect5; + bool projExplosionEffect5ForceNormalUp; + FxEffectDef *projDudEffect; + const char *projExplosionSound; + const char *projDudSound; + const char *mortarShellSound; + const char *tankShellSound; + bool bProjImpactExplode; + bool bProjSentientImpactExplode; + bool bProjExplodeWhenStationary; + bool bBulletImpactExplode; + WeapStickinessType stickiness; + WeapRotateType rotateType; + bool plantable; + bool hasDetonator; + bool timedDetonation; + bool bNoCrumpleMissile; + bool rotate; + bool bKeepRolling; + bool holdButtonToThrow; + bool offhandHoldIsCancelable; + bool freezeMovementWhenFiring; + float lowAmmoWarningThreshold; + bool bDisallowAtMatchStart; + float meleeChargeRange; + bool bUseAsMelee; + bool isCameraSensor; + bool isAcousticSensor; + bool isLaserSensor; + bool isHoldUseGrenade; + float *parallelBounce; + float *perpendicularBounce; + FxEffectDef *projTrailEffect; + vec3_t vProjectileColor; + guidedMissileType_t guidedMissileType; + float maxSteeringAccel; + int projIgnitionDelay; + FxEffectDef *projIgnitionEffect; + const char *projIgnitionSound; + float fAdsAimPitch; + float fAdsCrosshairInFrac; + float fAdsCrosshairOutFrac; + int adsGunKickReducedKickBullets; + float adsGunKickReducedKickPercent; + float fAdsGunKickPitchMin; + float fAdsGunKickPitchMax; + float fAdsGunKickYawMin; + float fAdsGunKickYawMax; + float fAdsGunKickAccel; + float fAdsGunKickSpeedMax; + float fAdsGunKickSpeedDecay; + float fAdsGunKickStaticDecay; + float fAdsViewKickPitchMin; + float fAdsViewKickPitchMax; + float fAdsViewKickMinMagnitude; + float fAdsViewKickYawMin; + float fAdsViewKickYawMax; + float fAdsRecoilReductionRate; + float fAdsRecoilReductionLimit; + float fAdsRecoilReturnRate; + float fAdsViewScatterMin; + float fAdsViewScatterMax; + float fAdsSpread; + int hipGunKickReducedKickBullets; + float hipGunKickReducedKickPercent; + float fHipGunKickPitchMin; + float fHipGunKickPitchMax; + float fHipGunKickYawMin; + float fHipGunKickYawMax; + float fHipGunKickAccel; + float fHipGunKickSpeedMax; + float fHipGunKickSpeedDecay; + float fHipGunKickStaticDecay; + float fHipViewKickPitchMin; + float fHipViewKickPitchMax; + float fHipViewKickMinMagnitude; + float fHipViewKickYawMin; + float fHipViewKickYawMax; + float fHipViewScatterMin; + float fHipViewScatterMax; + float fAdsViewKickCenterDuckedScale; + float fAdsViewKickCenterProneScale; + float fAntiQuickScopeTime; + float fAntiQuickScopeScale; + float fAntiQuickScopeSpreadMultiplier; + float fAntiQuickScopeSpreadMax; + float fAntiQuickScopeSwayFactor; + float fightDist; + float maxDist; + // const char *accuracyGraphName[2]; // TODO: Order is accuracyGraphName[0] -> accuracyGraphKnots[0] -> originalAccuracyGraphKnots[0] -> + // accuracyGraphName[1] -> ... + // Which is currently not possible to do in code generation. Afaik this is the only place where this is the case. + // So might be something to fix but on the other hand it might be too much work for this little inconvenience. + const char *accuracyGraphName0; + const char *accuracyGraphName1; + // vec2_t *accuracyGraphKnots[2]; + vec2_t *accuracyGraphKnots0; + vec2_t *accuracyGraphKnots1; + // vec2_t *originalAccuracyGraphKnots[2]; + vec2_t *originalAccuracyGraphKnots0; + vec2_t *originalAccuracyGraphKnots1; + int accuracyGraphKnotCount[2]; + int originalAccuracyGraphKnotCount[2]; + int iPositionReloadTransTime; + float leftArc; + float rightArc; + float topArc; + float bottomArc; + float accuracy; + float aiSpread; + float playerSpread; + float minTurnSpeed[2]; + float maxTurnSpeed[2]; + float pitchConvergenceTime; + float yawConvergenceTime; + float suppressTime; + float maxRange; + float fAnimHorRotateInc; + float fPlayerPositionDist; + const char *szUseHintString; + const char *dropHintString; + int iUseHintStringIndex; + int dropHintStringIndex; + float horizViewJitter; + float vertViewJitter; + float cameraShakeScale; + int cameraShakeDuration; + int cameraShakeRadius; + float explosionCameraShakeScale; + int explosionCameraShakeDuration; + int explosionCameraShakeRadius; + const char *szScript; + float destabilizationRateTime; + float destabilizationCurvatureMax; + int destabilizeDistance; + float *locationDamageMultipliers; + const char *fireRumble; + const char *meleeImpactRumble; + const char *reloadRumble; + const char *explosionRumble; + TracerDef *tracerType; + TracerDef *enemyTracerType; + float adsDofStart; + float adsDofEnd; + float hipDofStart; + float hipDofEnd; + float scanSpeed; + float scanAccel; + int scanPauseTime; + const char *flameTableFirstPerson; + const char *flameTableThirdPerson; + flameTable *flameTableFirstPersonPtr; + flameTable *flameTableThirdPersonPtr; + FxEffectDef *tagFx_preparationEffect; + FxEffectDef *tagFlash_preparationEffect; + bool doGibbing; + float maxGibDistance; + float altScopeADSTransInTime; + float altScopeADSTransOutTime; + int iIntroFireTime; + int iIntroFireLength; + FxEffectDef *meleeSwipeEffect; + FxEffectDef *meleeImpactEffect; + FxEffectDef *meleeImpactNoBloodEffect; + const char *throwBackType; + WeaponCamo *weaponCamo; + float customFloat0; + float customFloat1; + float customFloat2; + int customBool0; + int customBool1; + int customBool2; +}; + +enum weapAnimFiles_t { + WEAP_ANIM_ROOT = 0x0, + WEAP_ANIM_IDLE = 0x1, + WEAP_ANIM_EMPTY_IDLE = 0x2, + WEAP_ANIM_FIRE_INTRO = 0x3, + WEAP_ANIM_FIRE = 0x4, + WEAP_ANIM_HOLD_FIRE = 0x5, + WEAP_ANIM_LASTSHOT = 0x6, + WEAP_ANIM_FINALSHOT = 0x7, + WEAP_ANIM_RECHAMBER = 0x8, + WEAP_ANIM_MELEE = 0x9, + WEAP_ANIM_MELEE1 = 0xA, + WEAP_ANIM_MELEE2 = 0xB, + WEAP_ANIM_MELEE3 = 0xC, + WEAP_ANIM_MELEE_EMPTY = 0xD, + WEAP_ANIM_MELEE_CHARGE = 0xE, + WEAP_ANIM_MELEE_CHARGE_EMPTY = 0xF, + WEAP_ANIM_RELOAD = 0x10, + WEAP_ANIM_RELOAD_RIGHT = 0x11, + WEAP_ANIM_RELOAD_EMPTY = 0x12, + WEAP_ANIM_RELOAD_START = 0x13, + WEAP_ANIM_RELOAD_END = 0x14, + WEAP_ANIM_RELOAD_QUICK = 0x15, + WEAP_ANIM_RELOAD_QUICK_EMPTY = 0x16, + WEAP_ANIM_RAISE = 0x17, + WEAP_ANIM_FIRST_RAISE = 0x18, + WEAP_ANIM_DROP = 0x19, + WEAP_ANIM_ALT_RAISE = 0x1A, + WEAP_ANIM_ALT_DROP = 0x1B, + WEAP_ANIM_QUICK_RAISE = 0x1C, + WEAP_ANIM_QUICK_DROP = 0x1D, + WEAP_ANIM_EMPTY_RAISE = 0x1E, + WEAP_ANIM_EMPTY_DROP = 0x1F, + WEAP_ANIM_SPRINT_IN = 0x20, + WEAP_ANIM_SPRINT_LOOP = 0x21, + WEAP_ANIM_SPRINT_OUT = 0x22, + WEAP_ANIM_SPRINT_EMPTY_IN = 0x23, + WEAP_ANIM_SPRINT_EMPTY_LOOP = 0x24, + WEAP_ANIM_SPRINT_EMPTY_OUT = 0x25, + WEAP_ANIM_LOWREADY_IN = 0x26, + WEAP_ANIM_LOWREADY_LOOP = 0x27, + WEAP_ANIM_LOWREADY_OUT = 0x28, + WEAP_ANIM_CONT_FIRE_IN = 0x29, + WEAP_ANIM_CONT_FIRE_LOOP = 0x2A, + WEAP_ANIM_CONT_FIRE_OUT = 0x2B, + WEAP_ANIM_CRAWL_IN = 0x2C, + WEAP_ANIM_CRAWL_FORWARD = 0x2D, + WEAP_ANIM_CRAWL_BACK = 0x2E, + WEAP_ANIM_CRAWL_RIGHT = 0x2F, + WEAP_ANIM_CRAWL_LEFT = 0x30, + WEAP_ANIM_CRAWL_OUT = 0x31, + WEAP_ANIM_CRAWL_EMPTY_IN = 0x32, + WEAP_ANIM_CRAWL_EMPTY_FORWARD = 0x33, + WEAP_ANIM_CRAWL_EMPTY_BACK = 0x34, + WEAP_ANIM_CRAWL_EMPTY_RIGHT = 0x35, + WEAP_ANIM_CRAWL_EMPTY_LEFT = 0x36, + WEAP_ANIM_CRAWL_EMPTY_OUT = 0x37, + WEAP_ANIM_DEPLOY = 0x38, + WEAP_ANIM_BREAKDOWN = 0x39, + WEAP_ANIM_DETONATE = 0x3A, + WEAP_ANIM_NIGHTVISION_WEAR = 0x3B, + WEAP_ANIM_NIGHTVISION_REMOVE = 0x3C, + WEAP_ANIM_ADS_FIRE = 0x3D, + WEAP_ANIM_ADS_LASTSHOT = 0x3E, + WEAP_ANIM_ADS_FIRE_INTRO = 0x3F, + WEAP_ANIM_ADS_RECHAMBER = 0x40, + WEAP_ANIM_DTP_IN = 0x41, + WEAP_ANIM_DTP_LOOP = 0x42, + WEAP_ANIM_DTP_OUT = 0x43, + WEAP_ANIM_DTP_EMPTY_IN = 0x44, + WEAP_ANIM_DTP_EMPTY_LOOP = 0x45, + WEAP_ANIM_DTP_EMPTY_OUT = 0x46, + WEAP_ANIM_SLIDE_IN = 0x47, + WEAP_ANIM_MANTLE = 0x48, + WEAP_ANIM_CAMERA_SPRINT_LOOP = 0x49, + WEAP_ANIM_CAMERA_DTP_IN = 0x4A, + WEAP_ANIM_CAMERA_DTP_LOOP = 0x4B, + WEAP_ANIM_CAMERA_DTP_OUT = 0x4C, + WEAP_ANIM_CAMERA_MANTLE = 0x4D, + WEAP_ANIM_FIRE_LEFT = 0x4E, + WEAP_ANIM_LASTSHOT_LEFT = 0x4F, + WEAP_ANIM_FINALSHOT_LEFT = 0x50, + WEAP_ANIM_IDLE_LEFT = 0x51, + WEAP_ANIM_EMPTY_IDLE_LEFT = 0x52, + WEAP_ANIM_RELOAD_EMPTY_LEFT = 0x53, + WEAP_ANIM_RELOAD_LEFT = 0x54, + WEAP_ANIM_ADS_UP = 0x55, + WEAP_ANIM_ADS_DOWN = 0x56, + WEAP_ANIM_ADS_UP_OTHER_SCOPE = 0x57, + NUM_WEAP_ANIMS = 0x58, +}; + +enum materialSurfType_t { + SURF_TYPE_DEFAULT, + SURF_TYPE_BARK, + SURF_TYPE_BRICK, + SURF_TYPE_CARPET, + SURF_TYPE_CLOTH, + SURF_TYPE_CONCRETE, + SURF_TYPE_DIRT, + SURF_TYPE_FLESH, + SURF_TYPE_FOLIAGE, + SURF_TYPE_GLASS, + SURF_TYPE_GRASS, + SURF_TYPE_GRAVEL, + SURF_TYPE_ICE, + SURF_TYPE_METAL, + SURF_TYPE_MUD, + SURF_TYPE_PAPER, + SURF_TYPE_PLASTER, + SURF_TYPE_ROCK, + SURF_TYPE_SAND, + SURF_TYPE_SNOW, + SURF_TYPE_WATER, + SURF_TYPE_WOOD, + SURF_TYPE_ASPHALT, + SURF_TYPE_CERAMIC, + SURF_TYPE_PLASTIC, + SURF_TYPE_RUBBER, + SURF_TYPE_CUSHION, + SURF_TYPE_FRUIT, + SURF_TYPE_PAINTED_METAL, + SURF_TYPE_PLAYER, + SURF_TYPE_TALL_GRASS, + SURF_TYPE_RIOT_SHIELD, + + SURF_TYPE_NUM +}; + +struct WeaponVariantDef { + const char *szInternalName; + int iVariantCount; + WeaponDef *weapDef; + const char *szDisplayName; + const char *szAltWeaponName; + const char *szAttachmentUnique; + WeaponAttachment **attachments; + WeaponAttachmentUnique **attachmentUniques; + const char **szXAnims; + uint16_t *hideTags; + XModel **attachViewModel; + XModel **attachWorldModel; + const char **attachViewModelTag; + const char **attachWorldModelTag; + float attachViewModelOffsets[24]; + float attachWorldModelOffsets[24]; + float attachViewModelRotations[24]; + float attachWorldModelRotations[24]; + vec3_t stowedModelOffsets; + vec3_t stowedModelRotations; + unsigned int altWeaponIndex; + int iAttachments; + bool bIgnoreAttachments; + int iClipSize; + int iReloadTime; + int iReloadEmptyTime; + int iReloadQuickTime; + int iReloadQuickEmptyTime; + int iAdsTransInTime; + int iAdsTransOutTime; + int iAltRaiseTime; + const char *szAmmoDisplayName; + const char *szAmmoName; + int iAmmoIndex; + const char *szClipName; + int iClipIndex; + float fAimAssistRangeAds; + float fAdsSwayHorizScale; + float fAdsSwayVertScale; + float fAdsViewKickCenterSpeed; + float fHipViewKickCenterSpeed; + float fAdsZoomFov1; + float fAdsZoomFov2; + float fAdsZoomFov3; + float fAdsZoomInFrac; + float fAdsZoomOutFrac; + float fOverlayAlphaScale; + float fOOPosAnimLength[2]; + bool bSilenced; + bool bDualMag; + bool bInfraRed; + bool bTVGuided; + unsigned int perks[2]; + bool bAntiQuickScope; + Material *overlayMaterial; + Material *overlayMaterialLowRes; + Material *dpadIcon; + weaponIconRatioType_t dpadIconRatio; + bool noAmmoOnDpadIcon; + bool mmsWeapon; + bool mmsInScope; + float mmsFOV; + float mmsAspect; + float mmsMaxDist; + vec3_t ikLeftHandIdlePos; + vec3_t ikLeftHandOffset; + vec3_t ikLeftHandRotation; + bool bUsingLeftHandProneIK; + vec3_t ikLeftHandProneOffset; + vec3_t ikLeftHandProneRotation; + vec3_t ikLeftHandUiViewerOffset; + vec3_t ikLeftHandUiViewerRotation; +}; + +struct WeaponFullDef { + WeaponVariantDef weapVariantDef; + WeaponDef weapDef; + WeaponAttachment *attachments[63]; + WeaponAttachmentUnique *attachmentUniques[95]; + XModel *gunXModel[16]; + const char *szXAnims[88]; + uint16_t hideTags[32]; + uint16_t notetrackSoundMapKeys[20]; + uint16_t notetrackSoundMapValues[20]; + XModel *worldModel[16]; + XModel *attachViewModel[8]; + XModel *attachWorldModel[8]; + const char *attachViewModelTag[8]; + const char *attachWorldModelTag[8]; + float parallelBounce[32]; + float perpendicularBounce[32]; + float locationDamageMultipliers[21]; + char weaponCamo[64]; +}; + +struct WeaponCamoSet { + GfxImage *solidCamoImage; + GfxImage *patternCamoImage; + vec2_t patternOffset; + float patternScale; +}; + +struct WeaponCamoMaterialSet { + unsigned int numMaterials; + WeaponCamoMaterial *materials; +}; + +enum SndMenuCategory { + SND_CATEGORY_SFX = 0x0, + SND_CATEGORY_MUSIC = 0x1, + SND_CATEGORY_VOICE = 0x2, + SND_CATEGORY_UI = 0x3, + SND_CATEGORY_CINEMATIC = 0x4, + SND_CATEGORY_COUNT = 0x5, +}; + +struct SndVolumeGroup { + char name[32]; + char parentName[32]; + unsigned int id; + int parentIndex; + SndMenuCategory category; + uint16_t attenuationSp; + uint16_t attenuationMp; +}; + +struct SndCurve { + char name[32]; + unsigned int id; + vec2_t points[8]; +}; + +struct SndPan { + char name[32]; + unsigned int id; + float front; + float back; + float center; + float lfe; + float left; + float right; +}; + +struct SndDuckGroup { + char name[32]; + unsigned int id; +}; + +struct SndContext { + unsigned int type; + unsigned int values[8]; +}; + +struct SndMaster { + char name[32]; + unsigned int id; + int lowE; + float lowG; + float lowF; + float lowQ; + int peak1E; + float peak1G; + float peak1F; + float peak1Q; + int peak2E; + float peak2G; + float peak2F; + float peak2Q; + int hiE; + float hiG; + float hiF; + float hiQ; + float eqG; + int compE; + float compPG; + float compMG; + float compT; + float compR; + float compTA; + float compTR; + int limitE; + float limitPG; + float limitMG; + float limitT; + float limitR; + float limitTA; + float limitTR; + float busReverbG; + float busFxG; + float busVoiceG; + float busPfutzG; + float busHdrfxG; + float busUiG; + float busMusicG; + float busMovieG; + float busVcsG; + int busReverbE; + int busFxE; + int busVoiceE; + int busPfutzE; + int busHdrfxE; + int busUiE; + int busMusicE; + int busMovieE; + int hdrfxCompE; + int voiceEqE; + int voiceCompE; +}; + +struct SndSidechainDuck { + char name[32]; + unsigned int id; + float g; + float f; + float q; + float ta; + float tr; + float tf; +}; + +struct SndFutz { + char name[32]; + unsigned int id; + float bpfF; + float bpfQ; + float lsG; + float lsF; + float lsQ; + float dist; + float preG; + float postG; + float th; + float tg; + float clippre; + float clippost; + float blend; + unsigned int startAliasId; + unsigned int stopAliasId; + unsigned int loopAliasId; +}; + +struct FxSpawnDefLooping { + int intervalMsec; + int count; +}; + +struct FxIntRange { + int base; + int amplitude; +}; + +struct FxSpawnDefOneShot { + FxIntRange count; +}; + +union FxSpawnDef { + FxSpawnDefLooping looping; + FxSpawnDefOneShot oneShot; +}; + +struct FxElemAtlas { + char behavior; + char index; + char fps; + char loopCount; + char colIndexBits; + char rowIndexBits; + uint16_t entryCountAndIndexRange; +}; + +union FxEffectDefRef { + FxEffectDef *handle; + const char *name; +}; + +union FxElemVisuals { + void *anonymous; + Material *material; + XModel *model; + FxEffectDefRef effectDef; + const char *soundName; + GfxLightDef *lightDef; +}; + +union FxElemDefVisuals { + FxElemMarkVisuals *markArray; + FxElemVisuals *array; + FxElemVisuals instance; +}; + +union FxElemExtendedDefPtr { + FxTrailDef *trailDef; + FxSpotLightDef *spotLightDef; + char *unknownDef; +}; + +struct FxBillboardTrim { + float topWidth; + float bottomWidth; +}; + +union FxElemDefUnion { + FxBillboardTrim billboard; + FxIntRange cloudDensityRange; +}; + +struct FxElemSpawnSound { + const char *spawnSound; +}; + +enum FxElemType : char { + FX_ELEM_TYPE_SPRITE_BILLBOARD = 0x0, + FX_ELEM_TYPE_SPRITE_ORIENTED = 0x1, + FX_ELEM_TYPE_SPRITE_ROTATED = 0x2, + FX_ELEM_TYPE_TAIL = 0x3, + FX_ELEM_TYPE_LINE = 0x4, + FX_ELEM_TYPE_TRAIL = 0x5, + FX_ELEM_TYPE_CLOUD = 0x6, + FX_ELEM_TYPE_MODEL = 0x7, + FX_ELEM_TYPE_OMNI_LIGHT = 0x8, + FX_ELEM_TYPE_SPOT_LIGHT = 0x9, + FX_ELEM_TYPE_SOUND = 0xA, + FX_ELEM_TYPE_DECAL = 0xB, + FX_ELEM_TYPE_RUNNER = 0xC, + FX_ELEM_TYPE_COUNT = 0xD, + FX_ELEM_TYPE_LAST_SPRITE = 0x5, + FX_ELEM_TYPE_LAST_DRAWN = 0x9, +}; + +struct FxElemDef { + int flags; + FxSpawnDef spawn; + FxFloatRange spawnRange; + FxFloatRange fadeInRange; + FxFloatRange fadeOutRange; + float spawnFrustumCullRadius; + FxIntRange spawnDelayMsec; + FxIntRange lifeSpanMsec; + FxFloatRange spawnOrigin[3]; + FxFloatRange spawnOffsetRadius; + FxFloatRange spawnOffsetHeight; + FxFloatRange spawnAngles[3]; + FxFloatRange angularVelocity[3]; + FxFloatRange initialRotation; + unsigned int rotationAxis; + FxFloatRange gravity; + FxFloatRange reflectionFactor; + FxElemAtlas atlas; + float windInfluence; + FxElemType elemType; + char visualCount; + char velIntervalCount; + char visStateIntervalCount; + FxElemVelStateSample *velSamples; + FxElemVisStateSample *visSamples; + FxElemDefVisuals visuals; + vec3_t collMins; + vec3_t collMaxs; + FxEffectDefRef effectOnImpact; + FxEffectDefRef effectOnDeath; + FxEffectDefRef effectEmitted; + FxFloatRange emitDist; + FxFloatRange emitDistVariance; + FxEffectDefRef effectAttached; + FxElemExtendedDefPtr extended; + char sortOrder; + char lightingFrac; + char unused[2]; + uint16_t alphaFadeTimeMsec; + uint16_t maxWindStrength; + uint16_t spawnIntervalAtMaxWind; + uint16_t lifespanAtMaxWind; + FxElemDefUnion u; + FxElemSpawnSound spawnSound; + vec2_t billboardPivot; +}; + +struct FxImpactEntry { + FxEffectDef *nonflesh[32]; + FxEffectDef *flesh[4]; +}; + +struct StringTableCell { + const char *string; + int hash; +}; + +enum LbColType { + LBCOL_TYPE_NUMBER = 0x0, + LBCOL_TYPE_TIME = 0x1, + LBCOL_TYPE_LEVELXP = 0x2, + LBCOL_TYPE_PRESTIGE = 0x3, + LBCOL_TYPE_BIGNUMBER = 0x4, + LBCOL_TYPE_PERCENT = 0x5, + LBCOL_TYPE_TIME_FULL = 0x6, + LBCOL_TYPE_COUNT = 0x7, +}; + +enum LbAggType { + LBAGG_TYPE_MIN = 0x0, + LBAGG_TYPE_MAX = 0x1, + LBAGG_TYPE_ADD = 0x2, + LBAGG_TYPE_REPLACE = 0x3, + LBAGG_TYPE_COUNT = 0x4, +}; + +struct LbColumnDef { + const char *name; + int colId; + int dwColIndex; + bool hidden; + const char *statName; + LbColType type; + int precision; + LbAggType agg; + const char *localization; + int uiCalColX; + int uiCalColY; +}; + +struct ddlDef_t { + int version; + int size; + ddlStructDef_t *structList; + int structCount; + ddlEnumDef_t *enumList; + int enumCount; + ddlDef_t *next; +}; + +struct Glass { + unsigned int numCellIndices; + uint16_t cellIndices[6]; + GlassDef *glassDef; + unsigned int index; + unsigned int brushModel; + vec3_t origin; + vec3_t angles; + vec3_t absmin; + vec3_t absmax; + bool isPlanar; + char numOutlineVerts; + char binormalSign; + vec2_t *outline; + vec3_t outlineAxis[3]; + vec3_t outlineOrigin; + float uvScale; + float thickness; +}; + +struct KeyValuePair { + int keyHash; + int namespaceHash; + const char *value; +}; + +enum DevEventType { + EVENT_ACTIVATE = 0x0, + EVENT_DEACTIVATE = 0x1, + EVENT_ACCEPT = 0x2, + EVENT_UPDATE = 0x3, + EVENT_DRAW = 0x4, + EVENT_SAVE = 0x5, +}; + +enum LocalClientNum_t { + INVALID_LOCAL_CLIENT = 0xFFFFFFFF, + LOCAL_CLIENT_FIRST = 0x0, + LOCAL_CLIENT_0 = 0x0, + ONLY_LOCAL_CLIENT = 0x0, + LOCAL_CLIENT_COUNT = 0x1, +}; + +struct type_align(4) DevGraph { + vec2_t *knots; + int *knotCount; + int knotCountMax; + int selectedKnot; + void *eventCallback; // void (__cdecl *eventCallback)(DevGraph *, DevEventType, LocalClientNum_t); + void *textCallback; // void (__cdecl *textCallback)(DevGraph *, const float, const float, char *, const int); + void *data; + bool disableEditingEndPoints; +}; + +struct GraphFloat { + char name[64]; + vec2_t knots[32]; + int knotCount; + float scale; + DevGraph devguiGraph; +}; + +typedef char ByteVec[3]; +typedef tdef_align(4) uint16_t UShortVec[3]; + +union XAnimDynamicFrames { + ByteVec *_1; + UShortVec *_2; +}; + +union XAnimDynamicIndicesTrans { + char _1[1]; + uint16_t _2[1]; +}; + +struct type_align(4) XAnimPartTransFrames { + vec3_t mins; + vec3_t size; + XAnimDynamicFrames frames; + XAnimDynamicIndicesTrans indices; +}; + +union XAnimPartTransData { + XAnimPartTransFrames frames; + vec3_t frame0; +}; + +struct XAnimPartTrans { + uint16_t size; + char smallTrans; + XAnimPartTransData u; +}; + +union XAnimDynamicIndicesDeltaQuat2 { + char _1[1]; + uint16_t _2[1]; +}; + +typedef tdef_align(4) int16_t XQuat2[2]; + +struct type_align(4) XAnimDeltaPartQuatDataFrames2 { + XQuat2 *frames; + XAnimDynamicIndicesDeltaQuat2 indices; +}; + +union XAnimDeltaPartQuatData2 { + XAnimDeltaPartQuatDataFrames2 frames; + XQuat2 frame0; +}; + +struct XAnimDeltaPartQuat2 { + uint16_t size; + XAnimDeltaPartQuatData2 u; +}; + +union XAnimDynamicIndicesDeltaQuat { + char _1[1]; + uint16_t _2[1]; +}; + +typedef tdef_align(4) int16_t XQuat[4]; + +struct type_align(4) XAnimDeltaPartQuatDataFrames { + XQuat *frames; + XAnimDynamicIndicesDeltaQuat indices; +}; + +union XAnimDeltaPartQuatData { + XAnimDeltaPartQuatDataFrames frames; + XQuat frame0; +}; + +struct XAnimDeltaPartQuat { + uint16_t size; + XAnimDeltaPartQuatData u; +}; + +union GfxColor { + unsigned int packed; + char array[4]; +}; + +union PackedTexCoords { + unsigned int packed; +}; + +union PackedUnitVec { + unsigned int packed; +}; + +struct type_align(16) GfxPackedVertex { + vec3_t xyz; + float binormalSign; + GfxColor color; + PackedTexCoords texCoord; + PackedUnitVec normal; + PackedUnitVec tangent; +}; + +struct XRigidVertList { + uint16_t boneOffset; + uint16_t vertCount; + uint16_t triOffset; + uint16_t triCount; + XSurfaceCollisionTree *collisionTree; +}; + +struct XModelCollTri_s { + vec4_t plane; + vec4_t svec; + vec4_t tvec; +}; + +typedef tdef_align(16) PhysGeomInfo PhysGeomInfo16; + +struct PhysGeomList { + unsigned int count; + PhysGeomInfo16 *geoms; + int contents; +}; + +/* struct __cppobj ID3D11BlendState : ID3D11DeviceChild +{ +};*/ +/* struct __cppobj ID3D11DepthStencilState : ID3D11DeviceChild +{ +};*/ - struct type_align(16) GfxPackedVertex - { - vec3_t xyz; - float binormalSign; - GfxColor color; - PackedTexCoords texCoord; - PackedUnitVec normal; - PackedUnitVec tangent; - }; +/* struct __cppobj ID3D11RasterizerState : ID3D11DeviceChild +{ +};*/ - - struct XRigidVertList - { - uint16_t boneOffset; - uint16_t vertCount; - uint16_t triOffset; - uint16_t triCount; - XSurfaceCollisionTree* collisionTree; - }; - - - struct XModelCollTri_s - { - vec4_t plane; - vec4_t svec; - vec4_t tvec; - }; - - typedef tdef_align(16) PhysGeomInfo PhysGeomInfo16; - - - struct PhysGeomList - { - unsigned int count; - PhysGeomInfo16* geoms; - int contents; - }; - - /* struct __cppobj ID3D11BlendState : ID3D11DeviceChild - { - };*/ - - /* struct __cppobj ID3D11DepthStencilState : ID3D11DeviceChild - { - };*/ - - /* struct __cppobj ID3D11RasterizerState : ID3D11DeviceChild - { - };*/ - - /* struct IUnknownVtbl - { - HRESULT (__stdcall *QueryInterface)(IUnknown *this, _GUID *, void **); - unsigned int (__stdcall *AddRef)(IUnknown *this); - unsigned int (__stdcall *Release)(IUnknown *this); - };*/ - - - struct MaterialStreamRouting - { - char source; - char dest; - }; - - - struct MaterialVertexStreamRouting - { - MaterialStreamRouting data[16]; - void/*ID3D11InputLayout*/* decl[20]; - }; - - - struct MaterialVertexDeclaration - { - char streamCount; - bool hasOptionalSource; - bool isLoaded; - MaterialVertexStreamRouting routing; - }; - - - union MaterialArgumentLocation - { - uint16_t offset; - - struct - { - char textureIndex; - char samplerIndex; - }; - }; - - - struct MaterialArgumentCodeConst - { - uint16_t index; - char firstRow; - char rowCount; - }; - - - union MaterialArgumentDef - { - const float (*literalConst)[4]; - MaterialArgumentCodeConst codeConst; - unsigned int codeSampler; - unsigned int nameHash; - }; - - enum MaterialShaderArgumentType - { - MTL_ARG_MATERIAL_VERTEX_CONST = 0x0, - MTL_ARG_LITERAL_VERTEX_CONST = 0x1, - MTL_ARG_MATERIAL_PIXEL_SAMPLER = 0x2, - MTL_ARG_CODE_PRIM_BEGIN = 0x3, - MTL_ARG_CODE_VERTEX_CONST = 0x3, - MTL_ARG_CODE_PIXEL_SAMPLER = 0x4, - MTL_ARG_CODE_PIXEL_CONST = 0x5, - MTL_ARG_CODE_PRIM_END = 0x6, - MTL_ARG_MATERIAL_PIXEL_CONST = 0x6, - MTL_ARG_LITERAL_PIXEL_CONST = 0x7, - MLT_ARG_COUNT = 0x8, - }; - - - struct MaterialShaderArgument - { - uint16_t type; - MaterialArgumentLocation location; - uint16_t size; - uint16_t buffer; - MaterialArgumentDef u; - }; - - enum SndAliasType - { - SAT_UNKNOWN = 0x0, - SAT_LOADED = 0x1, - SAT_STREAMED = 0x2, - SAT_PRIMED = 0x3, - SAT_COUNT = 0x4, - }; - - struct SndAlias - { - const char* name; - unsigned int id; - const char* subtitle; - const char* secondaryname; - unsigned int assetId; - const char* assetFileName; - unsigned int flags0; // Bits 15/16 are SndAliasType - unsigned int flags1; - unsigned int duck; - unsigned int contextType; - unsigned int contextValue; - unsigned int stopOnPlay; - unsigned int futzPatch; - uint16_t fluxTime; - uint16_t startDelay; - uint16_t reverbSend; - uint16_t centerSend; - uint16_t volMin; - uint16_t volMax; - uint16_t pitchMin; - uint16_t pitchMax; - uint16_t distMin; - uint16_t distMax; - uint16_t distReverbMax; - uint16_t envelopMin; - uint16_t envelopMax; - uint16_t envelopPercentage; - int16_t fadeIn; - int16_t fadeOut; - int16_t dopplerScale; - char minPriorityThreshold; - char maxPriorityThreshold; - char probability; - char occlusionLevel; - char minPriority; - char maxPriority; - char pan; - char limitCount; - char entityLimitCount; - char duckGroup; - }; - - - struct type_align(4) pathlink_s - { - float fDist; - uint16_t nodeNum; - char disconnectCount; - char negotiationLink; - char flags; - char ubBadPlaceCount[5]; - }; - - - struct GfxAabbTree - { - vec3_t mins; - vec3_t maxs; - uint16_t childCount; - uint16_t surfaceCount; - uint16_t startSurfIndex; - uint16_t smodelIndexCount; - uint16_t* smodelIndexes; - int childrenOffset; - }; - - - struct GfxPortalWritable - { - bool isQueued; - bool isAncestor; - char recursionDepth; - char hullPointCount; - vec2_t* hullPoints; - GfxPortal* queuedParent; - }; - - - struct DpvsPlane - { - vec4_t coeffs; - char side[3]; - char pad; - }; - - - struct GfxPortal - { - GfxPortalWritable writable; - DpvsPlane plane; - GfxCell* cell; - vec3_t* vertices; - char vertexCount; - vec3_t hullAxis[2]; - vec3_t bounds[2]; - }; - - - struct GfxReflectionProbeVolumeData - { - vec4_t volumePlanes[6]; - }; - - - struct SSkinShaders - { - char_align128* pixelShaderAlign; - char_align4* pixelShader; - char_align4* vertexShader; - int pixelShaderSize; - int vertexShaderSize; - }; - - - struct SSkinModel - { - int numVerts; - int numTris; - SSkinVert* verts; - uint16_t* tris; - }; - - - struct SSkinAnim - { - int bones; - int width; - int frames; - float_align128* data; - }; - - - struct half - { - uint16_t v; - }; - - - union half4 - { - struct - { - half x; - half y; - half z; - half w; - }; - - // uint64_t v; - }; - - - union half2 - { - struct - { - half x; - half y; - }; - - unsigned int v; - }; - - - struct type_align(4) SSkinVert - { - half4 pos_bone; - PackedUnitVec normal; - half2 uv; - }; - - - struct GfxLightRegionHull - { - float kdopMidPoint[9]; - float kdopHalfSize[9]; - unsigned int axisCount; - GfxLightRegionAxis* axis; - }; - - - struct GenericEventScript - { - ScriptCondition* prerequisites; - ExpressionStatement condition; - int type; - bool fireOnTrue; - const char* action; - int blockID; - int constructID; - GenericEventScript* next; - }; - - - enum dvarType_t - { - DVAR_TYPE_INVALID = 0x0, - DVAR_TYPE_BOOL = 0x1, - DVAR_TYPE_FLOAT = 0x2, - DVAR_TYPE_FLOAT_2 = 0x3, - DVAR_TYPE_FLOAT_3 = 0x4, - DVAR_TYPE_FLOAT_4 = 0x5, - DVAR_TYPE_INT = 0x6, - DVAR_TYPE_ENUM = 0x7, - DVAR_TYPE_STRING = 0x8, - DVAR_TYPE_COLOR = 0x9, - DVAR_TYPE_INT64 = 0xA, - DVAR_TYPE_LINEAR_COLOR_RGB = 0xB, - DVAR_TYPE_COLOR_XYZ = 0xC, - DVAR_TYPE_COUNT = 0xD, - }; - - - union DvarValue - { - bool enabled; - int integer; - unsigned int unsignedInt; - int64_t integer64; - uint64_t unsignedInt64; - float value; - vec4_t vector; - const char* string; - char color[4]; - }; - - - union DvarLimits - { - struct - { - int stringCount; - const char** strings; - } enumeration; - - struct - { - int min; - int max; - } integer; - - struct - { - int64_t min; - int64_t max; - } integer64; - - struct - { - float min; - float max; - } value; - - struct - { - float min; - float max; - } vector; - }; - - - struct type_align(8) dvar_t - { - const char* name; - const char* description; - int hash; - unsigned int flags; - dvarType_t type; - bool modified; - DvarValue current; - DvarValue latched; - DvarValue reset; - DvarLimits domain; - dvar_t* hashNext; - }; - - - union textDefData_t - { - focusItemDef_s* focusItemDef; - gameMsgDef_s* gameMsgDef; - void* data; - }; - - - struct textDef_s - { - rectDef_s textRect[1]; - int alignment; - int fontEnum; - int itemFlags; - int textAlignMode; - float textalignx; - float textaligny; - float textscale; - float textpadding; - int textStyle; - vec4_t fontColor; - vec4_t glowColor; - vec4_t shadowColor; - float fontBlur; - float glowSize; - float shadowSize; - vec2_t shadowOffset; - const char* text; - textExp_s* textExpData; - textDefData_t textTypeData; - }; - - - struct imageDef_s - { - ExpressionStatement materialExp; - }; - - - union focusDefData_t - { - listBoxDef_s* listBox; - multiDef_s* multi; - profileMultiDef_s* profileMulti; - editFieldDef_s* editField; - enumDvarDef_s* enumDvar; - void* data; - }; - - - struct focusItemDef_s - { - const char* mouseEnterText; - const char* mouseExitText; - const char* mouseEnter; - const char* mouseExit; - ItemKeyHandler* onKey; - focusDefData_t focusTypeData; - }; - - - struct ownerDrawDef_s - { - ExpressionStatement dataExp; - }; - - - struct rectData_s - { - ExpressionStatement rectXExp; - ExpressionStatement rectYExp; - ExpressionStatement rectWExp; - ExpressionStatement rectHExp; - }; - - - struct animParamsDef_t - { - const char* name; - rectDef_s rectClient; - float borderSize; - vec4_t foreColor; - vec4_t backColor; - vec4_t borderColor; - vec4_t outlineColor; - float textScale; - float rotation; - GenericEventHandler* onEvent; - }; - - - struct UIAnimInfo - { - int animStateCount; - animParamsDef_t** animStates; - animParamsDef_t currentAnimState; - animParamsDef_t nextAnimState; - int animating; - int animStartTime; - int animDuration; - }; - - - struct flameTable - { - float flameVar_streamChunkGravityStart; - float flameVar_streamChunkGravityEnd; - float flameVar_streamChunkMaxSize; - float flameVar_streamChunkStartSize; - float flameVar_streamChunkEndSize; - float flameVar_streamChunkStartSizeRand; - float flameVar_streamChunkEndSizeRand; - float flameVar_streamChunkDistScalar; - float flameVar_streamChunkDistSwayScale; - float flameVar_streamChunkDistSwayVelMax; - float flameVar_streamChunkSpeed; - float flameVar_streamChunkDecel; - float flameVar_streamChunkVelocityAddScale; - float flameVar_streamChunkDuration; - float flameVar_streamChunkDurationScaleMaxVel; - float flameVar_streamChunkDurationVelScalar; - float flameVar_streamChunkSizeSpeedScale; - float flameVar_streamChunkSizeAgeScale; - float flameVar_streamChunkSpawnFireIntervalStart; - float flameVar_streamChunkSpawnFireIntervalEnd; - float flameVar_streamChunkSpawnFireMinLifeFrac; - float flameVar_streamChunkSpawnFireMaxLifeFrac; - float flameVar_streamChunkFireMinLifeFrac; - float flameVar_streamChunkFireMinLifeFracStart; - float flameVar_streamChunkFireMinLifeFracEnd; - float flameVar_streamChunkDripsMinLifeFrac; - float flameVar_streamChunkDripsMinLifeFracStart; - float flameVar_streamChunkDripsMinLifeFracEnd; - float flameVar_streamChunkRotationRange; - float flameVar_streamSizeRandSinWave; - float flameVar_streamSizeRandCosWave; - float flameVar_streamDripsChunkInterval; - float flameVar_streamDripsChunkMinFrac; - float flameVar_streamDripsChunkRandFrac; - float flameVar_streamSmokeChunkInterval; - float flameVar_streamSmokeChunkMinFrac; - float flameVar_streamSmokeChunkRandFrac; - float flameVar_streamChunkCullDistSizeFrac; - float flameVar_streamChunkCullMinLife; - float flameVar_streamChunkCullMaxLife; - float flameVar_streamFuelSizeStart; - float flameVar_streamFuelSizeEnd; - float flameVar_streamFuelLength; - float flameVar_streamFuelNumSegments; - float flameVar_streamFuelAnimLoopTime; - float flameVar_streamFlameSizeStart; - float flameVar_streamFlameSizeEnd; - float flameVar_streamFlameLength; - float flameVar_streamFlameNumSegments; - float flameVar_streamFlameAnimLoopTime; - float flameVar_streamPrimaryLightRadius; - float flameVar_streamPrimaryLightRadiusFlutter; - float flameVar_streamPrimaryLightR; - float flameVar_streamPrimaryLightG; - float flameVar_streamPrimaryLightB; - float flameVar_streamPrimaryLightFlutterR; - float flameVar_streamPrimaryLightFlutterG; - float flameVar_streamPrimaryLightFlutterB; - float flameVar_fireLife; - float flameVar_fireLifeRand; - float flameVar_fireSpeedScale; - float flameVar_fireSpeedScaleRand; - float flameVar_fireVelocityAddZ; - float flameVar_fireVelocityAddZRand; - float flameVar_fireVelocityAddSideways; - float flameVar_fireGravity; - float flameVar_fireGravityEnd; - float flameVar_fireMaxRotVel; - float flameVar_fireFriction; - float flameVar_fireEndSizeAdd; - float flameVar_fireStartSizeScale; - float flameVar_fireEndSizeScale; - float flameVar_fireBrightness; - float flameVar_dripsLife; - float flameVar_dripsLifeRand; - float flameVar_dripsSpeedScale; - float flameVar_dripsSpeedScaleRand; - float flameVar_dripsVelocityAddZ; - float flameVar_dripsVelocityAddZRand; - float flameVar_dripsVelocityAddSideways; - float flameVar_dripsGravity; - float flameVar_dripsGravityEnd; - float flameVar_dripsMaxRotVel; - float flameVar_dripsFriction; - float flameVar_dripsEndSizeAdd; - float flameVar_dripsStartSizeScale; - float flameVar_dripsEndSizeScale; - float flameVar_dripsBrightness; - float flameVar_smokeLife; - float flameVar_smokeLifeRand; - float flameVar_smokeSpeedScale; - float flameVar_smokeVelocityAddZ; - float flameVar_smokeGravity; - float flameVar_smokeGravityEnd; - float flameVar_smokeMaxRotation; - float flameVar_smokeMaxRotVel; - float flameVar_smokeFriction; - float flameVar_smokeEndSizeAdd; - float flameVar_smokeStartSizeAdd; - float flameVar_smokeOriginSizeOfsZScale; - float flameVar_smokeOriginOfsZ; - float flameVar_smokeFadein; - float flameVar_smokeFadeout; - float flameVar_smokeMaxAlpha; - float flameVar_smokeBrightness; - float flameVar_smokeOriginOffset; - float flameVar_collisionSpeedScale; - float flameVar_collisionVolumeScale; - const char* name; - Material* fire; - Material* smoke; - Material* heat; - Material* drips; - Material* streamFuel; - Material* streamFuel2; - Material* streamFlame; - Material* streamFlame2; - const char* flameOffLoopSound; - const char* flameIgniteSound; - const char* flameOnLoopSound; - const char* flameCooldownSound; - }; - - - struct WeaponCamoMaterial - { - uint16_t replaceFlags; - uint16_t numBaseMaterials; - Material** baseMaterials; - Material** camoMaterials; - float shaderConsts[8]; - }; - - - struct FxElemVec3Range - { - vec3_t base; - vec3_t amplitude; - }; - - - struct FxElemVelStateInFrame - { - FxElemVec3Range velocity; - FxElemVec3Range totalDelta; - }; - - - struct FxElemVelStateSample - { - FxElemVelStateInFrame local; - FxElemVelStateInFrame world; - }; - - - struct FxElemVisualState - { - char color[4]; - float rotationDelta; - float rotationTotal; - float size[2]; - float scale; - }; - - - struct FxElemVisStateSample - { - FxElemVisualState base; - FxElemVisualState amplitude; - }; - - - struct FxElemMarkVisuals - { - Material* materials[2]; - }; - - - struct FxTrailDef - { - int scrollTimeMsec; - int repeatDist; - int splitDist; - int vertCount; - FxTrailVertex* verts; - int indCount; - uint16_t* inds; - }; - - - struct FxSpotLightDef - { - float fovInnerFraction; - float startRadius; - float endRadius; - }; - - - struct ddlStructDef_t - { - const char* name; - int size; - int memberCount; - ddlMemberDef_t* members; - ddlHash_t* hashTable; - }; - - - struct ddlEnumDef_t - { - const char* name; - int memberCount; - const char** members; - ddlHash_t* hashTable; - }; - - - struct GlassDef - { - const char* name; - int maxHealth; - float thickness; - float minShardSize; - float maxShardSize; - float shardLifeProbablility; - int maxShards; - Material* pristineMaterial; - Material* crackedMaterial; - Material* shardMaterial; - const char* crackSound; - const char* shatterShound; - const char* autoShatterShound; - FxEffectDef* crackEffect; - FxEffectDef* shatterEffect; - }; - - - struct XSurfaceCollisionTree - { - vec3_t trans; - vec3_t scale; - unsigned int nodeCount; - XSurfaceCollisionNode* nodes; - unsigned int leafCount; - XSurfaceCollisionLeaf* leafs; - }; - - - struct PhysGeomInfo - { - BrushWrapper* brush; - int type; - vec3_t orientation[3]; - vec3_t offset; - vec3_t halfLengths; - }; - - /* struct __cppobj ID3D11InputLayout : ID3D11DeviceChild - { - };*/ - - - struct GfxLightRegionAxis - { - vec3_t dir; - float midPoint; - float halfSize; - }; - - - struct ScriptCondition - { - bool fireOnTrue; - int constructID; - int blockID; - ScriptCondition* next; - }; - - - struct textExp_s - { - ExpressionStatement textExp; - }; - - - struct gameMsgDef_s - { - int gameMsgWindowIndex; - int gameMsgWindowMode; - }; - - - struct columnInfo_s - { - int elementStyle; - int maxChars; - rectDef_s rect; - }; - - - struct listBoxDef_s - { - int mousePos; - int cursorPos[1]; - int startPos[1]; - int endPos[1]; - int drawPadding; - float elementWidth; - float elementHeight; - int numColumns; - float special; - columnInfo_s columnInfo[16]; - int notselectable; - int noScrollBars; - int usePaging; - vec4_t selectBorder; - vec4_t disableColor; - vec4_t focusColor; - vec4_t elementHighlightColor; - vec4_t elementBackgroundColor; - Material* selectIcon; - Material* backgroundItemListbox; - Material* highlightTexture; - int noBlinkingHighlight; - MenuRow* rows; - int maxRows; - int rowCount; - }; - - - struct multiDef_s - { - const char* dvarList[32]; - const char* dvarStr[32]; - float dvarValue[32]; - int count; - int actionOnEnterPressOnly; - int strDef; - }; - - - struct profileMultiDef_s - { - const char* profileVarList[32]; - const char* profileVarStr[32]; - float profileVarValue[32]; - int count; - int actionOnEnterPressOnly; - int strDef; - }; - - - struct editFieldDef_s - { - int cursorPos[1]; - float minVal; - float maxVal; - float defVal; - float range; - int maxChars; - int maxCharsGotoNext; - int maxPaintChars; - int paintOffset; - }; - - - struct enumDvarDef_s - { - const char* enumDvarName; - }; - - - struct FxTrailVertex - { - vec2_t pos; - vec2_t normal; - float texCoord; - }; - - - struct ddlMemberDef_t - { - const char* name; - int size; - int offset; - int type; - int externalIndex; - unsigned int rangeLimit; - unsigned int serverDelta; - unsigned int clientDelta; - int arraySize; - int enumIndex; - int permission; - }; - - - struct ddlHash_t - { - int hash; - int index; - }; - - - struct XSurfaceCollisionAabb - { - uint16_t mins[3]; - uint16_t maxs[3]; - }; - - - struct type_align(16) XSurfaceCollisionNode - { - XSurfaceCollisionAabb aabb; - uint16_t childBeginIndex; - uint16_t childCount; - }; - - - struct XSurfaceCollisionLeaf - { - uint16_t triangleBeginIndex; - }; - - - struct type_align(16) BrushWrapper - { - vec3_t mins; - int contents; - vec3_t maxs; - unsigned int numsides; - cbrushside_t* sides; - int axial_cflags[2][3]; - int axial_sflags[2][3]; - unsigned int numverts; - vec3_t* verts; - cplane_s* planes; - }; - - - struct MenuRow - { - MenuCell* cells; - char* eventName; - char* onFocusEventName; - bool disableArg; - int status; - int name; - }; - - - struct MenuCell - { - int type; - int maxChars; - char* stringValue; - }; +/* struct IUnknownVtbl +{ + HRESULT (__stdcall *QueryInterface)(IUnknown *this, _GUID *, void **); + unsigned int (__stdcall *AddRef)(IUnknown *this); + unsigned int (__stdcall *Release)(IUnknown *this); +};*/ + +struct MaterialStreamRouting { + char source; + char dest; +}; + +struct MaterialVertexStreamRouting { + MaterialStreamRouting data[16]; + void /*ID3D11InputLayout*/ *decl[20]; +}; + +struct MaterialVertexDeclaration { + char streamCount; + bool hasOptionalSource; + bool isLoaded; + MaterialVertexStreamRouting routing; +}; + +union MaterialArgumentLocation { + uint16_t offset; + + struct { + char textureIndex; + char samplerIndex; + }; +}; + +struct MaterialArgumentCodeConst { + uint16_t index; + char firstRow; + char rowCount; +}; + +union MaterialArgumentDef { + const float (*literalConst)[4]; + MaterialArgumentCodeConst codeConst; + unsigned int codeSampler; + unsigned int nameHash; +}; + +enum MaterialShaderArgumentType { + MTL_ARG_MATERIAL_VERTEX_CONST = 0x0, + MTL_ARG_LITERAL_VERTEX_CONST = 0x1, + MTL_ARG_MATERIAL_PIXEL_SAMPLER = 0x2, + MTL_ARG_CODE_PRIM_BEGIN = 0x3, + MTL_ARG_CODE_VERTEX_CONST = 0x3, + MTL_ARG_CODE_PIXEL_SAMPLER = 0x4, + MTL_ARG_CODE_PIXEL_CONST = 0x5, + MTL_ARG_CODE_PRIM_END = 0x6, + MTL_ARG_MATERIAL_PIXEL_CONST = 0x6, + MTL_ARG_LITERAL_PIXEL_CONST = 0x7, + MLT_ARG_COUNT = 0x8, +}; + +struct MaterialShaderArgument { + uint16_t type; + MaterialArgumentLocation location; + uint16_t size; + uint16_t buffer; + MaterialArgumentDef u; +}; + +enum SndAliasType { + SAT_UNKNOWN = 0x0, + SAT_LOADED = 0x1, + SAT_STREAMED = 0x2, + SAT_PRIMED = 0x3, + SAT_COUNT = 0x4, +}; + +struct SndAlias { + const char *name; + unsigned int id; + const char *subtitle; + const char *secondaryname; + unsigned int assetId; + const char *assetFileName; + unsigned int flags0; // Bits 15/16 are SndAliasType + unsigned int flags1; + unsigned int duck; + unsigned int contextType; + unsigned int contextValue; + unsigned int stopOnPlay; + unsigned int futzPatch; + uint16_t fluxTime; + uint16_t startDelay; + uint16_t reverbSend; + uint16_t centerSend; + uint16_t volMin; + uint16_t volMax; + uint16_t pitchMin; + uint16_t pitchMax; + uint16_t distMin; + uint16_t distMax; + uint16_t distReverbMax; + uint16_t envelopMin; + uint16_t envelopMax; + uint16_t envelopPercentage; + int16_t fadeIn; + int16_t fadeOut; + int16_t dopplerScale; + char minPriorityThreshold; + char maxPriorityThreshold; + char probability; + char occlusionLevel; + char minPriority; + char maxPriority; + char pan; + char limitCount; + char entityLimitCount; + char duckGroup; +}; + +struct type_align(4) pathlink_s { + float fDist; + uint16_t nodeNum; + char disconnectCount; + char negotiationLink; + char flags; + char ubBadPlaceCount[5]; +}; + +struct GfxAabbTree { + vec3_t mins; + vec3_t maxs; + uint16_t childCount; + uint16_t surfaceCount; + uint16_t startSurfIndex; + uint16_t smodelIndexCount; + uint16_t *smodelIndexes; + int childrenOffset; +}; + +struct GfxPortalWritable { + bool isQueued; + bool isAncestor; + char recursionDepth; + char hullPointCount; + vec2_t *hullPoints; + GfxPortal *queuedParent; +}; + +struct DpvsPlane { + vec4_t coeffs; + char side[3]; + char pad; +}; + +struct GfxPortal { + GfxPortalWritable writable; + DpvsPlane plane; + GfxCell *cell; + vec3_t *vertices; + char vertexCount; + vec3_t hullAxis[2]; + vec3_t bounds[2]; +}; + +struct GfxReflectionProbeVolumeData { + vec4_t volumePlanes[6]; +}; + +struct SSkinShaders { + char_align128 *pixelShaderAlign; + char_align4 *pixelShader; + char_align4 *vertexShader; + int pixelShaderSize; + int vertexShaderSize; +}; + +struct SSkinModel { + int numVerts; + int numTris; + SSkinVert *verts; + uint16_t *tris; +}; + +struct SSkinAnim { + int bones; + int width; + int frames; + float_align128 *data; +}; + +struct half { + uint16_t v; +}; + +union half4 { + struct { + half x; + half y; + half z; + half w; + }; + + // uint64_t v; +}; + +union half2 { + struct { + half x; + half y; + }; + + unsigned int v; +}; + +struct type_align(4) SSkinVert { + half4 pos_bone; + PackedUnitVec normal; + half2 uv; +}; + +struct GfxLightRegionHull { + float kdopMidPoint[9]; + float kdopHalfSize[9]; + unsigned int axisCount; + GfxLightRegionAxis *axis; +}; + +struct GenericEventScript { + ScriptCondition *prerequisites; + ExpressionStatement condition; + int type; + bool fireOnTrue; + const char *action; + int blockID; + int constructID; + GenericEventScript *next; +}; + +enum dvarType_t { + DVAR_TYPE_INVALID = 0x0, + DVAR_TYPE_BOOL = 0x1, + DVAR_TYPE_FLOAT = 0x2, + DVAR_TYPE_FLOAT_2 = 0x3, + DVAR_TYPE_FLOAT_3 = 0x4, + DVAR_TYPE_FLOAT_4 = 0x5, + DVAR_TYPE_INT = 0x6, + DVAR_TYPE_ENUM = 0x7, + DVAR_TYPE_STRING = 0x8, + DVAR_TYPE_COLOR = 0x9, + DVAR_TYPE_INT64 = 0xA, + DVAR_TYPE_LINEAR_COLOR_RGB = 0xB, + DVAR_TYPE_COLOR_XYZ = 0xC, + DVAR_TYPE_COUNT = 0xD, +}; + +union DvarValue { + bool enabled; + int integer; + unsigned int unsignedInt; + int64_t integer64; + uint64_t unsignedInt64; + float value; + vec4_t vector; + const char *string; + char color[4]; +}; + +union DvarLimits { + struct { + int stringCount; + const char **strings; + } enumeration; + + struct { + int min; + int max; + } integer; + + struct { + int64_t min; + int64_t max; + } integer64; + + struct { + float min; + float max; + } value; + + struct { + float min; + float max; + } vector; +}; + +struct type_align(8) dvar_t { + const char *name; + const char *description; + int hash; + unsigned int flags; + dvarType_t type; + bool modified; + DvarValue current; + DvarValue latched; + DvarValue reset; + DvarLimits domain; + dvar_t *hashNext; +}; + +union textDefData_t { + focusItemDef_s *focusItemDef; + gameMsgDef_s *gameMsgDef; + void *data; +}; + +struct textDef_s { + rectDef_s textRect[1]; + int alignment; + int fontEnum; + int itemFlags; + int textAlignMode; + float textalignx; + float textaligny; + float textscale; + float textpadding; + int textStyle; + vec4_t fontColor; + vec4_t glowColor; + vec4_t shadowColor; + float fontBlur; + float glowSize; + float shadowSize; + vec2_t shadowOffset; + const char *text; + textExp_s *textExpData; + textDefData_t textTypeData; +}; + +struct imageDef_s { + ExpressionStatement materialExp; +}; + +union focusDefData_t { + listBoxDef_s *listBox; + multiDef_s *multi; + profileMultiDef_s *profileMulti; + editFieldDef_s *editField; + enumDvarDef_s *enumDvar; + void *data; +}; + +struct focusItemDef_s { + const char *mouseEnterText; + const char *mouseExitText; + const char *mouseEnter; + const char *mouseExit; + ItemKeyHandler *onKey; + focusDefData_t focusTypeData; +}; + +struct ownerDrawDef_s { + ExpressionStatement dataExp; +}; + +struct rectData_s { + ExpressionStatement rectXExp; + ExpressionStatement rectYExp; + ExpressionStatement rectWExp; + ExpressionStatement rectHExp; +}; + +struct animParamsDef_t { + const char *name; + rectDef_s rectClient; + float borderSize; + vec4_t foreColor; + vec4_t backColor; + vec4_t borderColor; + vec4_t outlineColor; + float textScale; + float rotation; + GenericEventHandler *onEvent; +}; + +struct UIAnimInfo { + int animStateCount; + animParamsDef_t **animStates; + animParamsDef_t currentAnimState; + animParamsDef_t nextAnimState; + int animating; + int animStartTime; + int animDuration; +}; + +struct flameTable { + float flameVar_streamChunkGravityStart; + float flameVar_streamChunkGravityEnd; + float flameVar_streamChunkMaxSize; + float flameVar_streamChunkStartSize; + float flameVar_streamChunkEndSize; + float flameVar_streamChunkStartSizeRand; + float flameVar_streamChunkEndSizeRand; + float flameVar_streamChunkDistScalar; + float flameVar_streamChunkDistSwayScale; + float flameVar_streamChunkDistSwayVelMax; + float flameVar_streamChunkSpeed; + float flameVar_streamChunkDecel; + float flameVar_streamChunkVelocityAddScale; + float flameVar_streamChunkDuration; + float flameVar_streamChunkDurationScaleMaxVel; + float flameVar_streamChunkDurationVelScalar; + float flameVar_streamChunkSizeSpeedScale; + float flameVar_streamChunkSizeAgeScale; + float flameVar_streamChunkSpawnFireIntervalStart; + float flameVar_streamChunkSpawnFireIntervalEnd; + float flameVar_streamChunkSpawnFireMinLifeFrac; + float flameVar_streamChunkSpawnFireMaxLifeFrac; + float flameVar_streamChunkFireMinLifeFrac; + float flameVar_streamChunkFireMinLifeFracStart; + float flameVar_streamChunkFireMinLifeFracEnd; + float flameVar_streamChunkDripsMinLifeFrac; + float flameVar_streamChunkDripsMinLifeFracStart; + float flameVar_streamChunkDripsMinLifeFracEnd; + float flameVar_streamChunkRotationRange; + float flameVar_streamSizeRandSinWave; + float flameVar_streamSizeRandCosWave; + float flameVar_streamDripsChunkInterval; + float flameVar_streamDripsChunkMinFrac; + float flameVar_streamDripsChunkRandFrac; + float flameVar_streamSmokeChunkInterval; + float flameVar_streamSmokeChunkMinFrac; + float flameVar_streamSmokeChunkRandFrac; + float flameVar_streamChunkCullDistSizeFrac; + float flameVar_streamChunkCullMinLife; + float flameVar_streamChunkCullMaxLife; + float flameVar_streamFuelSizeStart; + float flameVar_streamFuelSizeEnd; + float flameVar_streamFuelLength; + float flameVar_streamFuelNumSegments; + float flameVar_streamFuelAnimLoopTime; + float flameVar_streamFlameSizeStart; + float flameVar_streamFlameSizeEnd; + float flameVar_streamFlameLength; + float flameVar_streamFlameNumSegments; + float flameVar_streamFlameAnimLoopTime; + float flameVar_streamPrimaryLightRadius; + float flameVar_streamPrimaryLightRadiusFlutter; + float flameVar_streamPrimaryLightR; + float flameVar_streamPrimaryLightG; + float flameVar_streamPrimaryLightB; + float flameVar_streamPrimaryLightFlutterR; + float flameVar_streamPrimaryLightFlutterG; + float flameVar_streamPrimaryLightFlutterB; + float flameVar_fireLife; + float flameVar_fireLifeRand; + float flameVar_fireSpeedScale; + float flameVar_fireSpeedScaleRand; + float flameVar_fireVelocityAddZ; + float flameVar_fireVelocityAddZRand; + float flameVar_fireVelocityAddSideways; + float flameVar_fireGravity; + float flameVar_fireGravityEnd; + float flameVar_fireMaxRotVel; + float flameVar_fireFriction; + float flameVar_fireEndSizeAdd; + float flameVar_fireStartSizeScale; + float flameVar_fireEndSizeScale; + float flameVar_fireBrightness; + float flameVar_dripsLife; + float flameVar_dripsLifeRand; + float flameVar_dripsSpeedScale; + float flameVar_dripsSpeedScaleRand; + float flameVar_dripsVelocityAddZ; + float flameVar_dripsVelocityAddZRand; + float flameVar_dripsVelocityAddSideways; + float flameVar_dripsGravity; + float flameVar_dripsGravityEnd; + float flameVar_dripsMaxRotVel; + float flameVar_dripsFriction; + float flameVar_dripsEndSizeAdd; + float flameVar_dripsStartSizeScale; + float flameVar_dripsEndSizeScale; + float flameVar_dripsBrightness; + float flameVar_smokeLife; + float flameVar_smokeLifeRand; + float flameVar_smokeSpeedScale; + float flameVar_smokeVelocityAddZ; + float flameVar_smokeGravity; + float flameVar_smokeGravityEnd; + float flameVar_smokeMaxRotation; + float flameVar_smokeMaxRotVel; + float flameVar_smokeFriction; + float flameVar_smokeEndSizeAdd; + float flameVar_smokeStartSizeAdd; + float flameVar_smokeOriginSizeOfsZScale; + float flameVar_smokeOriginOfsZ; + float flameVar_smokeFadein; + float flameVar_smokeFadeout; + float flameVar_smokeMaxAlpha; + float flameVar_smokeBrightness; + float flameVar_smokeOriginOffset; + float flameVar_collisionSpeedScale; + float flameVar_collisionVolumeScale; + const char *name; + Material *fire; + Material *smoke; + Material *heat; + Material *drips; + Material *streamFuel; + Material *streamFuel2; + Material *streamFlame; + Material *streamFlame2; + const char *flameOffLoopSound; + const char *flameIgniteSound; + const char *flameOnLoopSound; + const char *flameCooldownSound; +}; + +struct WeaponCamoMaterial { + uint16_t replaceFlags; + uint16_t numBaseMaterials; + Material **baseMaterials; + Material **camoMaterials; + float shaderConsts[8]; +}; + +struct FxElemVec3Range { + vec3_t base; + vec3_t amplitude; +}; + +struct FxElemVelStateInFrame { + FxElemVec3Range velocity; + FxElemVec3Range totalDelta; +}; + +struct FxElemVelStateSample { + FxElemVelStateInFrame local; + FxElemVelStateInFrame world; +}; + +struct FxElemVisualState { + char color[4]; + float rotationDelta; + float rotationTotal; + float size[2]; + float scale; +}; + +struct FxElemVisStateSample { + FxElemVisualState base; + FxElemVisualState amplitude; +}; + +struct FxElemMarkVisuals { + Material *materials[2]; +}; + +struct FxTrailDef { + int scrollTimeMsec; + int repeatDist; + int splitDist; + int vertCount; + FxTrailVertex *verts; + int indCount; + uint16_t *inds; +}; + +struct FxSpotLightDef { + float fovInnerFraction; + float startRadius; + float endRadius; +}; + +struct ddlStructDef_t { + const char *name; + int size; + int memberCount; + ddlMemberDef_t *members; + ddlHash_t *hashTable; +}; + +struct ddlEnumDef_t { + const char *name; + int memberCount; + const char **members; + ddlHash_t *hashTable; +}; + +struct GlassDef { + const char *name; + int maxHealth; + float thickness; + float minShardSize; + float maxShardSize; + float shardLifeProbablility; + int maxShards; + Material *pristineMaterial; + Material *crackedMaterial; + Material *shardMaterial; + const char *crackSound; + const char *shatterShound; + const char *autoShatterShound; + FxEffectDef *crackEffect; + FxEffectDef *shatterEffect; +}; + +struct XSurfaceCollisionTree { + vec3_t trans; + vec3_t scale; + unsigned int nodeCount; + XSurfaceCollisionNode *nodes; + unsigned int leafCount; + XSurfaceCollisionLeaf *leafs; +}; + +struct PhysGeomInfo { + BrushWrapper *brush; + int type; + vec3_t orientation[3]; + vec3_t offset; + vec3_t halfLengths; +}; + +/* struct __cppobj ID3D11InputLayout : ID3D11DeviceChild +{ +};*/ + +struct GfxLightRegionAxis { + vec3_t dir; + float midPoint; + float halfSize; +}; + +struct ScriptCondition { + bool fireOnTrue; + int constructID; + int blockID; + ScriptCondition *next; +}; + +struct textExp_s { + ExpressionStatement textExp; +}; + +struct gameMsgDef_s { + int gameMsgWindowIndex; + int gameMsgWindowMode; +}; + +struct columnInfo_s { + int elementStyle; + int maxChars; + rectDef_s rect; +}; + +struct listBoxDef_s { + int mousePos; + int cursorPos[1]; + int startPos[1]; + int endPos[1]; + int drawPadding; + float elementWidth; + float elementHeight; + int numColumns; + float special; + columnInfo_s columnInfo[16]; + int notselectable; + int noScrollBars; + int usePaging; + vec4_t selectBorder; + vec4_t disableColor; + vec4_t focusColor; + vec4_t elementHighlightColor; + vec4_t elementBackgroundColor; + Material *selectIcon; + Material *backgroundItemListbox; + Material *highlightTexture; + int noBlinkingHighlight; + MenuRow *rows; + int maxRows; + int rowCount; +}; + +struct multiDef_s { + const char *dvarList[32]; + const char *dvarStr[32]; + float dvarValue[32]; + int count; + int actionOnEnterPressOnly; + int strDef; +}; + +struct profileMultiDef_s { + const char *profileVarList[32]; + const char *profileVarStr[32]; + float profileVarValue[32]; + int count; + int actionOnEnterPressOnly; + int strDef; +}; + +struct editFieldDef_s { + int cursorPos[1]; + float minVal; + float maxVal; + float defVal; + float range; + int maxChars; + int maxCharsGotoNext; + int maxPaintChars; + int paintOffset; +}; + +struct enumDvarDef_s { + const char *enumDvarName; +}; + +struct FxTrailVertex { + vec2_t pos; + vec2_t normal; + float texCoord; +}; + +struct ddlMemberDef_t { + const char *name; + int size; + int offset; + int type; + int externalIndex; + unsigned int rangeLimit; + unsigned int serverDelta; + unsigned int clientDelta; + int arraySize; + int enumIndex; + int permission; +}; + +struct ddlHash_t { + int hash; + int index; +}; + +struct XSurfaceCollisionAabb { + uint16_t mins[3]; + uint16_t maxs[3]; +}; + +struct type_align(16) XSurfaceCollisionNode { + XSurfaceCollisionAabb aabb; + uint16_t childBeginIndex; + uint16_t childCount; +}; + +struct XSurfaceCollisionLeaf { + uint16_t triangleBeginIndex; +}; + +struct type_align(16) BrushWrapper { + vec3_t mins; + int contents; + vec3_t maxs; + unsigned int numsides; + cbrushside_t *sides; + int axial_cflags[2][3]; + int axial_sflags[2][3]; + unsigned int numverts; + vec3_t *verts; + cplane_s *planes; +}; + +struct MenuRow { + MenuCell *cells; + char *eventName; + char *onFocusEventName; + bool disableArg; + int status; + int name; +}; + +struct MenuCell { + int type; + int maxChars; + char *stringValue; +}; #ifndef __zonecodegenerator } // namespace T6 diff --git a/src/Common/Image/D3DFormat.h b/src/Common/Image/D3DFormat.h index 0aba3ce71..75279dcfa 100644 --- a/src/Common/Image/D3DFormat.h +++ b/src/Common/Image/D3DFormat.h @@ -2,109 +2,106 @@ #include "Utils/FileUtils.h" -enum D3DFORMAT -{ - D3DFMT_UNKNOWN = 0, - - D3DFMT_R8G8B8 = 20, - D3DFMT_A8R8G8B8 = 21, - D3DFMT_X8R8G8B8 = 22, - D3DFMT_R5G6B5 = 23, - D3DFMT_X1R5G5B5 = 24, - D3DFMT_A1R5G5B5 = 25, - D3DFMT_A4R4G4B4 = 26, - D3DFMT_R3G3B2 = 27, - D3DFMT_A8 = 28, - D3DFMT_A8R3G3B2 = 29, - D3DFMT_X4R4G4B4 = 30, - D3DFMT_A2B10G10R10 = 31, - D3DFMT_A8B8G8R8 = 32, - D3DFMT_X8B8G8R8 = 33, - D3DFMT_G16R16 = 34, - D3DFMT_A2R10G10B10 = 35, - D3DFMT_A16B16G16R16 = 36, - - D3DFMT_A8P8 = 40, - D3DFMT_P8 = 41, - - D3DFMT_L8 = 50, - D3DFMT_A8L8 = 51, - D3DFMT_A4L4 = 52, - - D3DFMT_V8U8 = 60, - D3DFMT_L6V5U5 = 61, - D3DFMT_X8L8V8U8 = 62, - D3DFMT_Q8W8V8U8 = 63, - D3DFMT_V16U16 = 64, - D3DFMT_A2W10V10U10 = 67, - - D3DFMT_UYVY = FileUtils::MakeMagic32('U', 'Y', 'V', 'Y'), - D3DFMT_R8G8_B8G8 = FileUtils::MakeMagic32('R', 'G', 'B', 'G'), - D3DFMT_YUY2 = FileUtils::MakeMagic32('Y', 'U', 'Y', '2'), - D3DFMT_G8R8_G8B8 = FileUtils::MakeMagic32('G', 'R', 'G', 'B'), - D3DFMT_DXT1 = FileUtils::MakeMagic32('D', 'X', 'T', '1'), - D3DFMT_DXT2 = FileUtils::MakeMagic32('D', 'X', 'T', '2'), - D3DFMT_DXT3 = FileUtils::MakeMagic32('D', 'X', 'T', '3'), - D3DFMT_DXT4 = FileUtils::MakeMagic32('D', 'X', 'T', '4'), - D3DFMT_DXT5 = FileUtils::MakeMagic32('D', 'X', 'T', '5'), - - D3DFMT_D16_LOCKABLE = 70, - D3DFMT_D32 = 71, - D3DFMT_D15S1 = 73, - D3DFMT_D24S8 = 75, - D3DFMT_D24X8 = 77, - D3DFMT_D24X4S4 = 79, - D3DFMT_D16 = 80, - - D3DFMT_D32F_LOCKABLE = 82, - D3DFMT_D24FS8 = 83, - - /* D3D9Ex only -- */ - - /* Z-Stencil formats valid for CPU access */ - D3DFMT_D32_LOCKABLE = 84, - D3DFMT_S8_LOCKABLE = 85, - - /* -- D3D9Ex only */ - - D3DFMT_L16 = 81, - - D3DFMT_VERTEXDATA = 100, - D3DFMT_INDEX16 = 101, - D3DFMT_INDEX32 = 102, - - D3DFMT_Q16W16V16U16 = 110, - - D3DFMT_MULTI2_ARGB8 = FileUtils::MakeMagic32('M', 'E', 'T', '1'), - - // Floating point surface formats - - // s10e5 formats (16-bits per channel) - D3DFMT_R16F = 111, - D3DFMT_G16R16F = 112, - D3DFMT_A16B16G16R16F = 113, - - // IEEE s23e8 formats (32-bits per channel) - D3DFMT_R32F = 114, - D3DFMT_G32R32F = 115, - D3DFMT_A32B32G32R32F = 116, - - D3DFMT_CxV8U8 = 117, - - /* D3D9Ex only -- */ - - // Monochrome 1 bit per pixel format - D3DFMT_A1 = 118, - - // 2.8 biased fixed point - D3DFMT_A2B10G10R10_XR_BIAS = 119, - - - // Binary format indicating that the data has no inherent type - D3DFMT_BINARYBUFFER = 199, - - /* -- D3D9Ex only */ - - - D3DFMT_FORCE_DWORD = 0x7fffffff +enum D3DFORMAT { + D3DFMT_UNKNOWN = 0, + + D3DFMT_R8G8B8 = 20, + D3DFMT_A8R8G8B8 = 21, + D3DFMT_X8R8G8B8 = 22, + D3DFMT_R5G6B5 = 23, + D3DFMT_X1R5G5B5 = 24, + D3DFMT_A1R5G5B5 = 25, + D3DFMT_A4R4G4B4 = 26, + D3DFMT_R3G3B2 = 27, + D3DFMT_A8 = 28, + D3DFMT_A8R3G3B2 = 29, + D3DFMT_X4R4G4B4 = 30, + D3DFMT_A2B10G10R10 = 31, + D3DFMT_A8B8G8R8 = 32, + D3DFMT_X8B8G8R8 = 33, + D3DFMT_G16R16 = 34, + D3DFMT_A2R10G10B10 = 35, + D3DFMT_A16B16G16R16 = 36, + + D3DFMT_A8P8 = 40, + D3DFMT_P8 = 41, + + D3DFMT_L8 = 50, + D3DFMT_A8L8 = 51, + D3DFMT_A4L4 = 52, + + D3DFMT_V8U8 = 60, + D3DFMT_L6V5U5 = 61, + D3DFMT_X8L8V8U8 = 62, + D3DFMT_Q8W8V8U8 = 63, + D3DFMT_V16U16 = 64, + D3DFMT_A2W10V10U10 = 67, + + D3DFMT_UYVY = FileUtils::MakeMagic32('U', 'Y', 'V', 'Y'), + D3DFMT_R8G8_B8G8 = FileUtils::MakeMagic32('R', 'G', 'B', 'G'), + D3DFMT_YUY2 = FileUtils::MakeMagic32('Y', 'U', 'Y', '2'), + D3DFMT_G8R8_G8B8 = FileUtils::MakeMagic32('G', 'R', 'G', 'B'), + D3DFMT_DXT1 = FileUtils::MakeMagic32('D', 'X', 'T', '1'), + D3DFMT_DXT2 = FileUtils::MakeMagic32('D', 'X', 'T', '2'), + D3DFMT_DXT3 = FileUtils::MakeMagic32('D', 'X', 'T', '3'), + D3DFMT_DXT4 = FileUtils::MakeMagic32('D', 'X', 'T', '4'), + D3DFMT_DXT5 = FileUtils::MakeMagic32('D', 'X', 'T', '5'), + + D3DFMT_D16_LOCKABLE = 70, + D3DFMT_D32 = 71, + D3DFMT_D15S1 = 73, + D3DFMT_D24S8 = 75, + D3DFMT_D24X8 = 77, + D3DFMT_D24X4S4 = 79, + D3DFMT_D16 = 80, + + D3DFMT_D32F_LOCKABLE = 82, + D3DFMT_D24FS8 = 83, + + /* D3D9Ex only -- */ + + /* Z-Stencil formats valid for CPU access */ + D3DFMT_D32_LOCKABLE = 84, + D3DFMT_S8_LOCKABLE = 85, + + /* -- D3D9Ex only */ + + D3DFMT_L16 = 81, + + D3DFMT_VERTEXDATA = 100, + D3DFMT_INDEX16 = 101, + D3DFMT_INDEX32 = 102, + + D3DFMT_Q16W16V16U16 = 110, + + D3DFMT_MULTI2_ARGB8 = FileUtils::MakeMagic32('M', 'E', 'T', '1'), + + // Floating point surface formats + + // s10e5 formats (16-bits per channel) + D3DFMT_R16F = 111, + D3DFMT_G16R16F = 112, + D3DFMT_A16B16G16R16F = 113, + + // IEEE s23e8 formats (32-bits per channel) + D3DFMT_R32F = 114, + D3DFMT_G32R32F = 115, + D3DFMT_A32B32G32R32F = 116, + + D3DFMT_CxV8U8 = 117, + + /* D3D9Ex only -- */ + + // Monochrome 1 bit per pixel format + D3DFMT_A1 = 118, + + // 2.8 biased fixed point + D3DFMT_A2B10G10R10_XR_BIAS = 119, + + // Binary format indicating that the data has no inherent type + D3DFMT_BINARYBUFFER = 199, + + /* -- D3D9Ex only */ + + D3DFMT_FORCE_DWORD = 0x7fffffff }; \ No newline at end of file diff --git a/src/Common/Image/DdsTypes.h b/src/Common/Image/DdsTypes.h index 320381f91..200951f9b 100644 --- a/src/Common/Image/DdsTypes.h +++ b/src/Common/Image/DdsTypes.h @@ -2,113 +2,90 @@ #include -constexpr uint32_t MakeFourCc(const char ch0, const char ch1, const char ch2, const char ch3) -{ - return static_cast(ch0) - | static_cast(ch1) << 8 - | static_cast(ch2) << 16 - | static_cast(ch3) << 24; +constexpr uint32_t MakeFourCc(const char ch0, const char ch1, const char ch2, const char ch3) { + return static_cast(ch0) | static_cast(ch1) << 8 | static_cast(ch2) << 16 | static_cast(ch3) << 24; } -enum DDP_FLAGS -{ - DDPF_ALPHAPIXELS = 0x1, - DDPF_ALPHA = 0x2, - DDPF_FOURCC = 0x4, - DDPF_RGB = 0x40, - DDPF_YUV = 0x200, - DDPF_LUMINANCE = 0x20000 -}; +enum DDP_FLAGS { DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000 }; -enum DDS_HEADER_FLAGS -{ - DDSD_CAPS = 0x1, - DDSD_HEIGHT = 0x2, - DDSD_WIDTH = 0x4, - DDSD_PITCH = 0x8, - DDSD_PIXELFORMAT = 0x1000, - DDSD_MIPMAPCOUNT = 0x20000, - DDSD_LINEARSIZE = 0x80000, - DDSD_DEPTH = 0x800000, +enum DDS_HEADER_FLAGS { + DDSD_CAPS = 0x1, + DDSD_HEIGHT = 0x2, + DDSD_WIDTH = 0x4, + DDSD_PITCH = 0x8, + DDSD_PIXELFORMAT = 0x1000, + DDSD_MIPMAPCOUNT = 0x20000, + DDSD_LINEARSIZE = 0x80000, + DDSD_DEPTH = 0x800000, }; -enum DDS_HEADER_CAPS -{ - DDSCAPS_COMPLEX = 0x8, - DDSCAPS_TEXTURE = 0x1000, - DDSCAPS_MIPMAP = 0x400000, +enum DDS_HEADER_CAPS { + DDSCAPS_COMPLEX = 0x8, + DDSCAPS_TEXTURE = 0x1000, + DDSCAPS_MIPMAP = 0x400000, }; -enum DDS_HEADER_CAPS2 -{ - DDSCAPS2_CUBEMAP = 0x200, - DDSCAPS2_CUBEMAP_POSITIVEX = 0x400, - DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800, - DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000, - DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000, - DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000, - DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000, - DDSCAPS2_VOLUME = 0x200000, +enum DDS_HEADER_CAPS2 { + DDSCAPS2_CUBEMAP = 0x200, + DDSCAPS2_CUBEMAP_POSITIVEX = 0x400, + DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800, + DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000, + DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000, + DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000, + DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000, + DDSCAPS2_VOLUME = 0x200000, }; -struct DDS_PIXELFORMAT -{ - uint32_t dwSize; - uint32_t dwFlags; - uint32_t dwFourCC; - uint32_t dwRGBBitCount; - uint32_t dwRBitMask; - uint32_t dwGBitMask; - uint32_t dwBBitMask; - uint32_t dwABitMask; +struct DDS_PIXELFORMAT { + uint32_t dwSize; + uint32_t dwFlags; + uint32_t dwFourCC; + uint32_t dwRGBBitCount; + uint32_t dwRBitMask; + uint32_t dwGBitMask; + uint32_t dwBBitMask; + uint32_t dwABitMask; }; -struct DDS_HEADER -{ - uint32_t dwSize; - uint32_t dwFlags; - uint32_t dwHeight; - uint32_t dwWidth; - uint32_t dwPitchOrLinearSize; - uint32_t dwDepth; - uint32_t dwMipMapCount; - uint32_t dwReserved1[11]; - DDS_PIXELFORMAT ddspf; - uint32_t dwCaps; - uint32_t dwCaps2; - uint32_t dwCaps3; - uint32_t dwCaps4; - uint32_t dwReserved2; +struct DDS_HEADER { + uint32_t dwSize; + uint32_t dwFlags; + uint32_t dwHeight; + uint32_t dwWidth; + uint32_t dwPitchOrLinearSize; + uint32_t dwDepth; + uint32_t dwMipMapCount; + uint32_t dwReserved1[11]; + DDS_PIXELFORMAT ddspf; + uint32_t dwCaps; + uint32_t dwCaps2; + uint32_t dwCaps3; + uint32_t dwCaps4; + uint32_t dwReserved2; }; -enum D3D10_RESOURCE_DIMENSION -{ - D3D10_RESOURCE_DIMENSION_UNKNOWN, - D3D10_RESOURCE_DIMENSION_BUFFER, - D3D10_RESOURCE_DIMENSION_TEXTURE1D, - D3D10_RESOURCE_DIMENSION_TEXTURE2D, - D3D10_RESOURCE_DIMENSION_TEXTURE3D +enum D3D10_RESOURCE_DIMENSION { + D3D10_RESOURCE_DIMENSION_UNKNOWN, + D3D10_RESOURCE_DIMENSION_BUFFER, + D3D10_RESOURCE_DIMENSION_TEXTURE1D, + D3D10_RESOURCE_DIMENSION_TEXTURE2D, + D3D10_RESOURCE_DIMENSION_TEXTURE3D }; -enum DDS_HEADER_DXT10_MISC -{ - DDS_RESOURCE_MISC_TEXTURECUBE = 0x4 -}; +enum DDS_HEADER_DXT10_MISC { DDS_RESOURCE_MISC_TEXTURECUBE = 0x4 }; -enum DDS_HEADER_DXT10_MISC2 -{ - DDS_ALPHA_MODE_UNKNOWN = 0x0, - DDS_ALPHA_MODE_STRAIGHT = 0x1, - DDS_ALPHA_MODE_PREMULTIPLIED = 0x2, - DDS_ALPHA_MODE_OPAQUE = 0x3, - DDS_ALPHA_MODE_CUSTOM = 0x4, +enum DDS_HEADER_DXT10_MISC2 { + DDS_ALPHA_MODE_UNKNOWN = 0x0, + DDS_ALPHA_MODE_STRAIGHT = 0x1, + DDS_ALPHA_MODE_PREMULTIPLIED = 0x2, + DDS_ALPHA_MODE_OPAQUE = 0x3, + DDS_ALPHA_MODE_CUSTOM = 0x4, }; -struct DDS_HEADER_DXT10 -{ - DXGI_FORMAT dxgiFormat; - D3D10_RESOURCE_DIMENSION resourceDimension; - uint32_t miscFlag; - uint32_t arraySize; - uint32_t miscFlags2; +struct DDS_HEADER_DXT10 { + DXGI_FORMAT dxgiFormat; + D3D10_RESOURCE_DIMENSION resourceDimension; + uint32_t miscFlag; + uint32_t arraySize; + uint32_t miscFlags2; }; diff --git a/src/Common/Image/DxgiFormat.h b/src/Common/Image/DxgiFormat.h index 4f410b5d2..bf8eb9db1 100644 --- a/src/Common/Image/DxgiFormat.h +++ b/src/Common/Image/DxgiFormat.h @@ -20,128 +20,127 @@ const unsigned int DXGI_FORMAT_DEFINED = 1; -enum DXGI_FORMAT -{ - DXGI_FORMAT_UNKNOWN = 0x00, - DXGI_FORMAT_R32G32B32A32_TYPELESS = 0x01, - DXGI_FORMAT_R32G32B32A32_FLOAT = 0x02, - DXGI_FORMAT_R32G32B32A32_UINT = 0x03, - DXGI_FORMAT_R32G32B32A32_SINT = 0x04, - DXGI_FORMAT_R32G32B32_TYPELESS = 0x05, - DXGI_FORMAT_R32G32B32_FLOAT = 0x06, - DXGI_FORMAT_R32G32B32_UINT = 0x07, - DXGI_FORMAT_R32G32B32_SINT = 0x08, - DXGI_FORMAT_R16G16B16A16_TYPELESS = 0x09, - DXGI_FORMAT_R16G16B16A16_FLOAT = 0x0a, - DXGI_FORMAT_R16G16B16A16_UNORM = 0x0b, - DXGI_FORMAT_R16G16B16A16_UINT = 0x0c, - DXGI_FORMAT_R16G16B16A16_SNORM = 0x0d, - DXGI_FORMAT_R16G16B16A16_SINT = 0x0e, - DXGI_FORMAT_R32G32_TYPELESS = 0x0f, - DXGI_FORMAT_R32G32_FLOAT = 0x10, - DXGI_FORMAT_R32G32_UINT = 0x11, - DXGI_FORMAT_R32G32_SINT = 0x12, - DXGI_FORMAT_R32G8X24_TYPELESS = 0x13, - DXGI_FORMAT_D32_FLOAT_S8X24_UINT = 0x14, - DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS = 0x15, - DXGI_FORMAT_X32_TYPELESS_G8X24_UINT = 0x16, - DXGI_FORMAT_R10G10B10A2_TYPELESS = 0x17, - DXGI_FORMAT_R10G10B10A2_UNORM = 0x18, - DXGI_FORMAT_R10G10B10A2_UINT = 0x19, - DXGI_FORMAT_R11G11B10_FLOAT = 0x1a, - DXGI_FORMAT_R8G8B8A8_TYPELESS = 0x1b, - DXGI_FORMAT_R8G8B8A8_UNORM = 0x1c, - DXGI_FORMAT_R8G8B8A8_UNORM_SRGB = 0x1d, - DXGI_FORMAT_R8G8B8A8_UINT = 0x1e, - DXGI_FORMAT_R8G8B8A8_SNORM = 0x1f, - DXGI_FORMAT_R8G8B8A8_SINT = 0x20, - DXGI_FORMAT_R16G16_TYPELESS = 0x21, - DXGI_FORMAT_R16G16_FLOAT = 0x22, - DXGI_FORMAT_R16G16_UNORM = 0x23, - DXGI_FORMAT_R16G16_UINT = 0x24, - DXGI_FORMAT_R16G16_SNORM = 0x25, - DXGI_FORMAT_R16G16_SINT = 0x26, - DXGI_FORMAT_R32_TYPELESS = 0x27, - DXGI_FORMAT_D32_FLOAT = 0x28, - DXGI_FORMAT_R32_FLOAT = 0x29, - DXGI_FORMAT_R32_UINT = 0x2a, - DXGI_FORMAT_R32_SINT = 0x2b, - DXGI_FORMAT_R24G8_TYPELESS = 0x2c, - DXGI_FORMAT_D24_UNORM_S8_UINT = 0x2d, - DXGI_FORMAT_R24_UNORM_X8_TYPELESS = 0x2e, - DXGI_FORMAT_X24_TYPELESS_G8_UINT = 0x2f, - DXGI_FORMAT_R8G8_TYPELESS = 0x30, - DXGI_FORMAT_R8G8_UNORM = 0x31, - DXGI_FORMAT_R8G8_UINT = 0x32, - DXGI_FORMAT_R8G8_SNORM = 0x33, - DXGI_FORMAT_R8G8_SINT = 0x34, - DXGI_FORMAT_R16_TYPELESS = 0x35, - DXGI_FORMAT_R16_FLOAT = 0x36, - DXGI_FORMAT_D16_UNORM = 0x37, - DXGI_FORMAT_R16_UNORM = 0x38, - DXGI_FORMAT_R16_UINT = 0x39, - DXGI_FORMAT_R16_SNORM = 0x3a, - DXGI_FORMAT_R16_SINT = 0x3b, - DXGI_FORMAT_R8_TYPELESS = 0x3c, - DXGI_FORMAT_R8_UNORM = 0x3d, - DXGI_FORMAT_R8_UINT = 0x3e, - DXGI_FORMAT_R8_SNORM = 0x3f, - DXGI_FORMAT_R8_SINT = 0x40, - DXGI_FORMAT_A8_UNORM = 0x41, - DXGI_FORMAT_R1_UNORM = 0x42, - DXGI_FORMAT_R9G9B9E5_SHAREDEXP = 0x43, - DXGI_FORMAT_R8G8_B8G8_UNORM = 0x44, - DXGI_FORMAT_G8R8_G8B8_UNORM = 0x45, - DXGI_FORMAT_BC1_TYPELESS = 0x46, - DXGI_FORMAT_BC1_UNORM = 0x47, - DXGI_FORMAT_BC1_UNORM_SRGB = 0x48, - DXGI_FORMAT_BC2_TYPELESS = 0x49, - DXGI_FORMAT_BC2_UNORM = 0x4a, - DXGI_FORMAT_BC2_UNORM_SRGB = 0x4b, - DXGI_FORMAT_BC3_TYPELESS = 0x4c, - DXGI_FORMAT_BC3_UNORM = 0x4d, - DXGI_FORMAT_BC3_UNORM_SRGB = 0x4e, - DXGI_FORMAT_BC4_TYPELESS = 0x4f, - DXGI_FORMAT_BC4_UNORM = 0x50, - DXGI_FORMAT_BC4_SNORM = 0x51, - DXGI_FORMAT_BC5_TYPELESS = 0x52, - DXGI_FORMAT_BC5_UNORM = 0x53, - DXGI_FORMAT_BC5_SNORM = 0x54, - DXGI_FORMAT_B5G6R5_UNORM = 0x55, - DXGI_FORMAT_B5G5R5A1_UNORM = 0x56, - DXGI_FORMAT_B8G8R8A8_UNORM = 0x57, - DXGI_FORMAT_B8G8R8X8_UNORM = 0x58, - DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM = 0x59, - DXGI_FORMAT_B8G8R8A8_TYPELESS = 0x5a, - DXGI_FORMAT_B8G8R8A8_UNORM_SRGB = 0x5b, - DXGI_FORMAT_B8G8R8X8_TYPELESS = 0x5c, - DXGI_FORMAT_B8G8R8X8_UNORM_SRGB = 0x5d, - DXGI_FORMAT_BC6H_TYPELESS = 0x5e, - DXGI_FORMAT_BC6H_UF16 = 0x5f, - DXGI_FORMAT_BC6H_SF16 = 0x60, - DXGI_FORMAT_BC7_TYPELESS = 0x61, - DXGI_FORMAT_BC7_UNORM = 0x62, - DXGI_FORMAT_BC7_UNORM_SRGB = 0x63, - DXGI_FORMAT_AYUV = 0x64, - DXGI_FORMAT_Y410 = 0x65, - DXGI_FORMAT_Y416 = 0x66, - DXGI_FORMAT_NV12 = 0x67, - DXGI_FORMAT_P010 = 0x68, - DXGI_FORMAT_P016 = 0x69, - DXGI_FORMAT_420_OPAQUE = 0x6a, - DXGI_FORMAT_YUY2 = 0x6b, - DXGI_FORMAT_Y210 = 0x6c, - DXGI_FORMAT_Y216 = 0x6d, - DXGI_FORMAT_NV11 = 0x6e, - DXGI_FORMAT_AI44 = 0x6f, - DXGI_FORMAT_IA44 = 0x70, - DXGI_FORMAT_P8 = 0x71, - DXGI_FORMAT_A8P8 = 0x72, - DXGI_FORMAT_B4G4R4A4_UNORM = 0x73, +enum DXGI_FORMAT { + DXGI_FORMAT_UNKNOWN = 0x00, + DXGI_FORMAT_R32G32B32A32_TYPELESS = 0x01, + DXGI_FORMAT_R32G32B32A32_FLOAT = 0x02, + DXGI_FORMAT_R32G32B32A32_UINT = 0x03, + DXGI_FORMAT_R32G32B32A32_SINT = 0x04, + DXGI_FORMAT_R32G32B32_TYPELESS = 0x05, + DXGI_FORMAT_R32G32B32_FLOAT = 0x06, + DXGI_FORMAT_R32G32B32_UINT = 0x07, + DXGI_FORMAT_R32G32B32_SINT = 0x08, + DXGI_FORMAT_R16G16B16A16_TYPELESS = 0x09, + DXGI_FORMAT_R16G16B16A16_FLOAT = 0x0a, + DXGI_FORMAT_R16G16B16A16_UNORM = 0x0b, + DXGI_FORMAT_R16G16B16A16_UINT = 0x0c, + DXGI_FORMAT_R16G16B16A16_SNORM = 0x0d, + DXGI_FORMAT_R16G16B16A16_SINT = 0x0e, + DXGI_FORMAT_R32G32_TYPELESS = 0x0f, + DXGI_FORMAT_R32G32_FLOAT = 0x10, + DXGI_FORMAT_R32G32_UINT = 0x11, + DXGI_FORMAT_R32G32_SINT = 0x12, + DXGI_FORMAT_R32G8X24_TYPELESS = 0x13, + DXGI_FORMAT_D32_FLOAT_S8X24_UINT = 0x14, + DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS = 0x15, + DXGI_FORMAT_X32_TYPELESS_G8X24_UINT = 0x16, + DXGI_FORMAT_R10G10B10A2_TYPELESS = 0x17, + DXGI_FORMAT_R10G10B10A2_UNORM = 0x18, + DXGI_FORMAT_R10G10B10A2_UINT = 0x19, + DXGI_FORMAT_R11G11B10_FLOAT = 0x1a, + DXGI_FORMAT_R8G8B8A8_TYPELESS = 0x1b, + DXGI_FORMAT_R8G8B8A8_UNORM = 0x1c, + DXGI_FORMAT_R8G8B8A8_UNORM_SRGB = 0x1d, + DXGI_FORMAT_R8G8B8A8_UINT = 0x1e, + DXGI_FORMAT_R8G8B8A8_SNORM = 0x1f, + DXGI_FORMAT_R8G8B8A8_SINT = 0x20, + DXGI_FORMAT_R16G16_TYPELESS = 0x21, + DXGI_FORMAT_R16G16_FLOAT = 0x22, + DXGI_FORMAT_R16G16_UNORM = 0x23, + DXGI_FORMAT_R16G16_UINT = 0x24, + DXGI_FORMAT_R16G16_SNORM = 0x25, + DXGI_FORMAT_R16G16_SINT = 0x26, + DXGI_FORMAT_R32_TYPELESS = 0x27, + DXGI_FORMAT_D32_FLOAT = 0x28, + DXGI_FORMAT_R32_FLOAT = 0x29, + DXGI_FORMAT_R32_UINT = 0x2a, + DXGI_FORMAT_R32_SINT = 0x2b, + DXGI_FORMAT_R24G8_TYPELESS = 0x2c, + DXGI_FORMAT_D24_UNORM_S8_UINT = 0x2d, + DXGI_FORMAT_R24_UNORM_X8_TYPELESS = 0x2e, + DXGI_FORMAT_X24_TYPELESS_G8_UINT = 0x2f, + DXGI_FORMAT_R8G8_TYPELESS = 0x30, + DXGI_FORMAT_R8G8_UNORM = 0x31, + DXGI_FORMAT_R8G8_UINT = 0x32, + DXGI_FORMAT_R8G8_SNORM = 0x33, + DXGI_FORMAT_R8G8_SINT = 0x34, + DXGI_FORMAT_R16_TYPELESS = 0x35, + DXGI_FORMAT_R16_FLOAT = 0x36, + DXGI_FORMAT_D16_UNORM = 0x37, + DXGI_FORMAT_R16_UNORM = 0x38, + DXGI_FORMAT_R16_UINT = 0x39, + DXGI_FORMAT_R16_SNORM = 0x3a, + DXGI_FORMAT_R16_SINT = 0x3b, + DXGI_FORMAT_R8_TYPELESS = 0x3c, + DXGI_FORMAT_R8_UNORM = 0x3d, + DXGI_FORMAT_R8_UINT = 0x3e, + DXGI_FORMAT_R8_SNORM = 0x3f, + DXGI_FORMAT_R8_SINT = 0x40, + DXGI_FORMAT_A8_UNORM = 0x41, + DXGI_FORMAT_R1_UNORM = 0x42, + DXGI_FORMAT_R9G9B9E5_SHAREDEXP = 0x43, + DXGI_FORMAT_R8G8_B8G8_UNORM = 0x44, + DXGI_FORMAT_G8R8_G8B8_UNORM = 0x45, + DXGI_FORMAT_BC1_TYPELESS = 0x46, + DXGI_FORMAT_BC1_UNORM = 0x47, + DXGI_FORMAT_BC1_UNORM_SRGB = 0x48, + DXGI_FORMAT_BC2_TYPELESS = 0x49, + DXGI_FORMAT_BC2_UNORM = 0x4a, + DXGI_FORMAT_BC2_UNORM_SRGB = 0x4b, + DXGI_FORMAT_BC3_TYPELESS = 0x4c, + DXGI_FORMAT_BC3_UNORM = 0x4d, + DXGI_FORMAT_BC3_UNORM_SRGB = 0x4e, + DXGI_FORMAT_BC4_TYPELESS = 0x4f, + DXGI_FORMAT_BC4_UNORM = 0x50, + DXGI_FORMAT_BC4_SNORM = 0x51, + DXGI_FORMAT_BC5_TYPELESS = 0x52, + DXGI_FORMAT_BC5_UNORM = 0x53, + DXGI_FORMAT_BC5_SNORM = 0x54, + DXGI_FORMAT_B5G6R5_UNORM = 0x55, + DXGI_FORMAT_B5G5R5A1_UNORM = 0x56, + DXGI_FORMAT_B8G8R8A8_UNORM = 0x57, + DXGI_FORMAT_B8G8R8X8_UNORM = 0x58, + DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM = 0x59, + DXGI_FORMAT_B8G8R8A8_TYPELESS = 0x5a, + DXGI_FORMAT_B8G8R8A8_UNORM_SRGB = 0x5b, + DXGI_FORMAT_B8G8R8X8_TYPELESS = 0x5c, + DXGI_FORMAT_B8G8R8X8_UNORM_SRGB = 0x5d, + DXGI_FORMAT_BC6H_TYPELESS = 0x5e, + DXGI_FORMAT_BC6H_UF16 = 0x5f, + DXGI_FORMAT_BC6H_SF16 = 0x60, + DXGI_FORMAT_BC7_TYPELESS = 0x61, + DXGI_FORMAT_BC7_UNORM = 0x62, + DXGI_FORMAT_BC7_UNORM_SRGB = 0x63, + DXGI_FORMAT_AYUV = 0x64, + DXGI_FORMAT_Y410 = 0x65, + DXGI_FORMAT_Y416 = 0x66, + DXGI_FORMAT_NV12 = 0x67, + DXGI_FORMAT_P010 = 0x68, + DXGI_FORMAT_P016 = 0x69, + DXGI_FORMAT_420_OPAQUE = 0x6a, + DXGI_FORMAT_YUY2 = 0x6b, + DXGI_FORMAT_Y210 = 0x6c, + DXGI_FORMAT_Y216 = 0x6d, + DXGI_FORMAT_NV11 = 0x6e, + DXGI_FORMAT_AI44 = 0x6f, + DXGI_FORMAT_IA44 = 0x70, + DXGI_FORMAT_P8 = 0x71, + DXGI_FORMAT_A8P8 = 0x72, + DXGI_FORMAT_B4G4R4A4_UNORM = 0x73, - DXGI_FORMAT_P208 = 0x82, - DXGI_FORMAT_V208 = 0x83, - DXGI_FORMAT_V408 = 0x84, + DXGI_FORMAT_P208 = 0x82, + DXGI_FORMAT_V208 = 0x83, + DXGI_FORMAT_V408 = 0x84, - DXGI_FORMAT_FORCE_UINT = 0xffffffff, + DXGI_FORMAT_FORCE_UINT = 0xffffffff, }; \ No newline at end of file diff --git a/src/Common/Image/ImageFormat.cpp b/src/Common/Image/ImageFormat.cpp index f13918a84..4c0a6bec3 100644 --- a/src/Common/Image/ImageFormat.cpp +++ b/src/Common/Image/ImageFormat.cpp @@ -1,147 +1,96 @@ #include "ImageFormat.h" ImageFormat::ImageFormat(const ImageFormatId id, const D3DFORMAT d3dFormat, const DXGI_FORMAT dxgiFormat) - : m_id(id), - m_d3d_format(d3dFormat), - m_dxgi_format(dxgiFormat) -{ -} + : m_id(id), m_d3d_format(d3dFormat), m_dxgi_format(dxgiFormat) {} -ImageFormatId ImageFormat::GetId() const -{ - return m_id; -} +ImageFormatId ImageFormat::GetId() const { return m_id; } -D3DFORMAT ImageFormat::GetD3DFormat() const -{ - return m_d3d_format; -} +D3DFORMAT ImageFormat::GetD3DFormat() const { return m_d3d_format; } -DXGI_FORMAT ImageFormat::GetDxgiFormat() const -{ - return m_dxgi_format; -} +DXGI_FORMAT ImageFormat::GetDxgiFormat() const { return m_dxgi_format; } -ImageFormatUnsigned::ImageFormatUnsigned(const ImageFormatId id, const D3DFORMAT d3dFormat, const DXGI_FORMAT dxgiFormat, - const unsigned bitsPerPixel, const unsigned rOffset, const unsigned rSize, - const unsigned gOffset, const unsigned gSize, const unsigned bOffset, +ImageFormatUnsigned::ImageFormatUnsigned(const ImageFormatId id, const D3DFORMAT d3dFormat, const DXGI_FORMAT dxgiFormat, const unsigned bitsPerPixel, + const unsigned rOffset, const unsigned rSize, const unsigned gOffset, const unsigned gSize, const unsigned bOffset, const unsigned bSize, const unsigned aOffset, const unsigned aSize) - : ImageFormat(id, d3dFormat, dxgiFormat), - m_bits_per_pixel(bitsPerPixel), - m_r_offset(rOffset), - m_r_size(rSize), - m_g_offset(gOffset), - m_g_size(gSize), - m_b_offset(bOffset), - m_b_size(bSize), - m_a_offset(aOffset), - m_a_size(aSize) -{ -} + : ImageFormat(id, d3dFormat, dxgiFormat), m_bits_per_pixel(bitsPerPixel), m_r_offset(rOffset), m_r_size(rSize), m_g_offset(gOffset), m_g_size(gSize), + m_b_offset(bOffset), m_b_size(bSize), m_a_offset(aOffset), m_a_size(aSize) {} -ImageFormatType ImageFormatUnsigned::GetType() const -{ - return ImageFormatType::UNSIGNED; -} +ImageFormatType ImageFormatUnsigned::GetType() const { return ImageFormatType::UNSIGNED; } -size_t ImageFormatUnsigned::GetPitch(const unsigned mipLevel, const unsigned width) const -{ - unsigned mipWidth = width >> mipLevel; - if (mipWidth == 0) - mipWidth = 1; +size_t ImageFormatUnsigned::GetPitch(const unsigned mipLevel, const unsigned width) const { + unsigned mipWidth = width >> mipLevel; + if (mipWidth == 0) + mipWidth = 1; - return mipWidth * m_bits_per_pixel / 8; + return mipWidth * m_bits_per_pixel / 8; } -size_t ImageFormatUnsigned::GetSizeOfMipLevel(const unsigned mipLevel, const unsigned width, const unsigned height, - const unsigned depth) const -{ - unsigned mipWidth = width >> mipLevel; - unsigned mipHeight = height >> mipLevel; - unsigned mipDepth = depth >> mipLevel; - - if (mipWidth == 0) - mipWidth = 1; - if (mipHeight == 0) - mipHeight = 1; - if (mipDepth == 0) - mipDepth = 1; - - return mipWidth * mipHeight * mipDepth * m_bits_per_pixel / 8; +size_t ImageFormatUnsigned::GetSizeOfMipLevel(const unsigned mipLevel, const unsigned width, const unsigned height, const unsigned depth) const { + unsigned mipWidth = width >> mipLevel; + unsigned mipHeight = height >> mipLevel; + unsigned mipDepth = depth >> mipLevel; + + if (mipWidth == 0) + mipWidth = 1; + if (mipHeight == 0) + mipHeight = 1; + if (mipDepth == 0) + mipDepth = 1; + + return mipWidth * mipHeight * mipDepth * m_bits_per_pixel / 8; } ImageFormatBlockCompressed::ImageFormatBlockCompressed(const ImageFormatId id, const D3DFORMAT d3dFormat, const DXGI_FORMAT dxgiFormat, const unsigned blockSize, const unsigned bitsPerBlock) - : ImageFormat(id, d3dFormat, dxgiFormat), - m_block_size(blockSize), - m_bits_per_block(bitsPerBlock) -{ -} + : ImageFormat(id, d3dFormat, dxgiFormat), m_block_size(blockSize), m_bits_per_block(bitsPerBlock) {} -ImageFormatType ImageFormatBlockCompressed::GetType() const -{ - return ImageFormatType::BLOCK_COMPRESSED; -} +ImageFormatType ImageFormatBlockCompressed::GetType() const { return ImageFormatType::BLOCK_COMPRESSED; } -size_t ImageFormatBlockCompressed::GetPitch(const unsigned mipLevel, const unsigned width) const -{ - unsigned mipWidth = width >> mipLevel; +size_t ImageFormatBlockCompressed::GetPitch(const unsigned mipLevel, const unsigned width) const { + unsigned mipWidth = width >> mipLevel; - if (mipWidth == 0) - mipWidth = 1; + if (mipWidth == 0) + mipWidth = 1; - const unsigned blockCount = (mipWidth + m_block_size - 1) / m_block_size; + const unsigned blockCount = (mipWidth + m_block_size - 1) / m_block_size; - return blockCount * m_bits_per_block / 8; + return blockCount * m_bits_per_block / 8; } -size_t ImageFormatBlockCompressed::GetSizeOfMipLevel(const unsigned mipLevel, const unsigned width, - const unsigned height, const unsigned depth) const -{ - unsigned mipWidth = width >> mipLevel; - unsigned mipHeight = height >> mipLevel; - unsigned mipDepth = depth >> mipLevel; - - if (mipWidth == 0) - mipWidth = 1; - if (mipHeight == 0) - mipHeight = 1; - if (mipDepth == 0) - mipDepth = 1; - - const unsigned blockCount = ((mipWidth + m_block_size - 1) / m_block_size) - * ((mipHeight + m_block_size - 1) / m_block_size) - * mipDepth; - - return blockCount * m_bits_per_block / 8; -} +size_t ImageFormatBlockCompressed::GetSizeOfMipLevel(const unsigned mipLevel, const unsigned width, const unsigned height, const unsigned depth) const { + unsigned mipWidth = width >> mipLevel; + unsigned mipHeight = height >> mipLevel; + unsigned mipDepth = depth >> mipLevel; -bool ImageFormatUnsigned::HasR() const -{ - return m_r_size > 0; -} + if (mipWidth == 0) + mipWidth = 1; + if (mipHeight == 0) + mipHeight = 1; + if (mipDepth == 0) + mipDepth = 1; -bool ImageFormatUnsigned::HasG() const -{ - return m_g_size > 0; -} + const unsigned blockCount = ((mipWidth + m_block_size - 1) / m_block_size) * ((mipHeight + m_block_size - 1) / m_block_size) * mipDepth; -bool ImageFormatUnsigned::HasB() const -{ - return m_b_size > 0; + return blockCount * m_bits_per_block / 8; } -bool ImageFormatUnsigned::HasA() const -{ - return m_a_size > 0; -} +bool ImageFormatUnsigned::HasR() const { return m_r_size > 0; } + +bool ImageFormatUnsigned::HasG() const { return m_g_size > 0; } + +bool ImageFormatUnsigned::HasB() const { return m_b_size > 0; } + +bool ImageFormatUnsigned::HasA() const { return m_a_size > 0; } const ImageFormatUnsigned ImageFormat::FORMAT_R8_G8_B8(ImageFormatId::R8_G8_B8, D3DFMT_R8G8B8, DXGI_FORMAT_UNKNOWN, 24, 0, 8, 8, 8, 16, 8, 0, 0); const ImageFormatUnsigned ImageFormat::FORMAT_B8_G8_R8_X8(ImageFormatId::B8_G8_R8_X8, D3DFMT_X8R8G8B8, DXGI_FORMAT_B8G8R8X8_UNORM, 32, 16, 8, 8, 8, 0, 8, 0, 0); -const ImageFormatUnsigned ImageFormat::FORMAT_R8_G8_B8_A8(ImageFormatId::R8_G8_B8_A8, D3DFMT_A8B8G8R8, DXGI_FORMAT_R8G8B8A8_UNORM, 32, 0, 8, 8, 8, 16, 8, 24, 8); -const ImageFormatUnsigned ImageFormat::FORMAT_B8_G8_R8_A8(ImageFormatId::B8_G8_R8_A8, D3DFMT_A8R8G8B8, DXGI_FORMAT_B8G8R8A8_UNORM, 32, 16, 8, 8, 8, 0, 8, 24, 8); +const ImageFormatUnsigned ImageFormat::FORMAT_R8_G8_B8_A8(ImageFormatId::R8_G8_B8_A8, D3DFMT_A8B8G8R8, DXGI_FORMAT_R8G8B8A8_UNORM, 32, 0, 8, 8, 8, 16, 8, 24, + 8); +const ImageFormatUnsigned ImageFormat::FORMAT_B8_G8_R8_A8(ImageFormatId::B8_G8_R8_A8, D3DFMT_A8R8G8B8, DXGI_FORMAT_B8G8R8A8_UNORM, 32, 16, 8, 8, 8, 0, 8, 24, + 8); const ImageFormatUnsigned ImageFormat::FORMAT_A8(ImageFormatId::A8, D3DFMT_A8, DXGI_FORMAT_A8_UNORM, 8, 0, 0, 0, 0, 0, 0, 0, 8); -const ImageFormatUnsigned ImageFormat::FORMAT_R16_G16_B16_A16_FLOAT(ImageFormatId::R16_G16_B16_A16_FLOAT, D3DFMT_A16B16G16R16F, DXGI_FORMAT_R16G16B16A16_FLOAT, 128, 0, 0, 0, 0, 0, 0, 0, 8); +const ImageFormatUnsigned ImageFormat::FORMAT_R16_G16_B16_A16_FLOAT(ImageFormatId::R16_G16_B16_A16_FLOAT, D3DFMT_A16B16G16R16F, DXGI_FORMAT_R16G16B16A16_FLOAT, + 128, 0, 0, 0, 0, 0, 0, 0, 8); const ImageFormatUnsigned ImageFormat::FORMAT_R8(ImageFormatId::R8, D3DFMT_L8, DXGI_FORMAT_R8_UNORM, 8, 0, 8, 0, 0, 0, 0, 0, 0); const ImageFormatUnsigned ImageFormat::FORMAT_R8_A8(ImageFormatId::R8_A8, D3DFMT_A8L8, DXGI_FORMAT_UNKNOWN, 16, 0, 8, 0, 0, 0, 0, 8, 8); const ImageFormatBlockCompressed ImageFormat::FORMAT_BC1(ImageFormatId::BC1, D3DFMT_DXT1, DXGI_FORMAT_BC1_UNORM, 4, 64); @@ -150,19 +99,7 @@ const ImageFormatBlockCompressed ImageFormat::FORMAT_BC3(ImageFormatId::BC3, D3D const ImageFormatBlockCompressed ImageFormat::FORMAT_BC4(ImageFormatId::BC4, D3DFMT_UNKNOWN, DXGI_FORMAT_BC4_UNORM, 4, 64); const ImageFormatBlockCompressed ImageFormat::FORMAT_BC5(ImageFormatId::BC5, D3DFMT_UNKNOWN, DXGI_FORMAT_BC5_UNORM, 4, 128); -const ImageFormat* const ImageFormat::ALL_FORMATS[static_cast(ImageFormatId::MAX)] -{ - &FORMAT_R8_G8_B8, - &FORMAT_B8_G8_R8_X8, - &FORMAT_R8_G8_B8_A8, - &FORMAT_B8_G8_R8_A8, - &FORMAT_A8, - &FORMAT_R16_G16_B16_A16_FLOAT, - &FORMAT_R8, - &FORMAT_R8_A8, - &FORMAT_BC1, - &FORMAT_BC2, - &FORMAT_BC3, - &FORMAT_BC4, - &FORMAT_BC5, +const ImageFormat *const ImageFormat::ALL_FORMATS[static_cast(ImageFormatId::MAX)]{ + &FORMAT_R8_G8_B8, &FORMAT_B8_G8_R8_X8, &FORMAT_R8_G8_B8_A8, &FORMAT_B8_G8_R8_A8, &FORMAT_A8, &FORMAT_R16_G16_B16_A16_FLOAT, &FORMAT_R8, &FORMAT_R8_A8, + &FORMAT_BC1, &FORMAT_BC2, &FORMAT_BC3, &FORMAT_BC4, &FORMAT_BC5, }; diff --git a/src/Common/Image/ImageFormat.h b/src/Common/Image/ImageFormat.h index 70b559af6..135e539ef 100644 --- a/src/Common/Image/ImageFormat.h +++ b/src/Common/Image/ImageFormat.h @@ -1,112 +1,102 @@ #pragma once -#include -#include #include "D3DFormat.h" #include "DxgiFormat.h" +#include +#include -enum class ImageFormatId -{ - UNKNOWN = -1, - R8_G8_B8, - B8_G8_R8_X8, - R8_G8_B8_A8, - B8_G8_R8_A8, - A8, - R16_G16_B16_A16_FLOAT, - R8, - R8_A8, - BC1, - BC2, - BC3, - BC4, - BC5, - - MAX +enum class ImageFormatId { + UNKNOWN = -1, + R8_G8_B8, + B8_G8_R8_X8, + R8_G8_B8_A8, + B8_G8_R8_A8, + A8, + R16_G16_B16_A16_FLOAT, + R8, + R8_A8, + BC1, + BC2, + BC3, + BC4, + BC5, + + MAX }; -enum class ImageFormatType -{ - UNKNOWN, - UNSIGNED, - BLOCK_COMPRESSED -}; +enum class ImageFormatType { UNKNOWN, UNSIGNED, BLOCK_COMPRESSED }; class ImageFormatUnsigned; class ImageFormatBlockCompressed; -class ImageFormat -{ - ImageFormatId m_id; - D3DFORMAT m_d3d_format; - DXGI_FORMAT m_dxgi_format; +class ImageFormat { + ImageFormatId m_id; + D3DFORMAT m_d3d_format; + DXGI_FORMAT m_dxgi_format; protected: - ImageFormat(ImageFormatId id, D3DFORMAT d3dFormat, DXGI_FORMAT dxgiFormat); + ImageFormat(ImageFormatId id, D3DFORMAT d3dFormat, DXGI_FORMAT dxgiFormat); public: - virtual ~ImageFormat() = default; - - ImageFormatId GetId() const; - D3DFORMAT GetD3DFormat() const; - DXGI_FORMAT GetDxgiFormat() const; - - virtual ImageFormatType GetType() const = 0; - virtual size_t GetPitch(unsigned mipLevel, unsigned width) const = 0; - virtual size_t GetSizeOfMipLevel(unsigned mipLevel, unsigned width, unsigned height, unsigned depth) const = 0; - - static const ImageFormatUnsigned FORMAT_R8_G8_B8; - static const ImageFormatUnsigned FORMAT_B8_G8_R8_X8; - static const ImageFormatUnsigned FORMAT_R8_G8_B8_A8; - static const ImageFormatUnsigned FORMAT_B8_G8_R8_A8; - static const ImageFormatUnsigned FORMAT_A8; - static const ImageFormatUnsigned FORMAT_R16_G16_B16_A16_FLOAT; //TODO: Float not unsigned - static const ImageFormatUnsigned FORMAT_R8; - static const ImageFormatUnsigned FORMAT_R8_A8; - static const ImageFormatBlockCompressed FORMAT_BC1; - static const ImageFormatBlockCompressed FORMAT_BC2; - static const ImageFormatBlockCompressed FORMAT_BC3; - static const ImageFormatBlockCompressed FORMAT_BC4; - static const ImageFormatBlockCompressed FORMAT_BC5; - static const ImageFormat* const ALL_FORMATS[static_cast(ImageFormatId::MAX)]; + virtual ~ImageFormat() = default; + + ImageFormatId GetId() const; + D3DFORMAT GetD3DFormat() const; + DXGI_FORMAT GetDxgiFormat() const; + + virtual ImageFormatType GetType() const = 0; + virtual size_t GetPitch(unsigned mipLevel, unsigned width) const = 0; + virtual size_t GetSizeOfMipLevel(unsigned mipLevel, unsigned width, unsigned height, unsigned depth) const = 0; + + static const ImageFormatUnsigned FORMAT_R8_G8_B8; + static const ImageFormatUnsigned FORMAT_B8_G8_R8_X8; + static const ImageFormatUnsigned FORMAT_R8_G8_B8_A8; + static const ImageFormatUnsigned FORMAT_B8_G8_R8_A8; + static const ImageFormatUnsigned FORMAT_A8; + static const ImageFormatUnsigned FORMAT_R16_G16_B16_A16_FLOAT; // TODO: Float not unsigned + static const ImageFormatUnsigned FORMAT_R8; + static const ImageFormatUnsigned FORMAT_R8_A8; + static const ImageFormatBlockCompressed FORMAT_BC1; + static const ImageFormatBlockCompressed FORMAT_BC2; + static const ImageFormatBlockCompressed FORMAT_BC3; + static const ImageFormatBlockCompressed FORMAT_BC4; + static const ImageFormatBlockCompressed FORMAT_BC5; + static const ImageFormat *const ALL_FORMATS[static_cast(ImageFormatId::MAX)]; }; -class ImageFormatUnsigned final : public ImageFormat -{ +class ImageFormatUnsigned final : public ImageFormat { public: - unsigned m_bits_per_pixel; - unsigned m_r_offset; - unsigned m_r_size; - unsigned m_g_offset; - unsigned m_g_size; - unsigned m_b_offset; - unsigned m_b_size; - unsigned m_a_offset; - unsigned m_a_size; - - ImageFormatUnsigned(ImageFormatId id, D3DFORMAT d3dFormat, DXGI_FORMAT dxgiFormat, unsigned bitsPerPixel, unsigned rOffset, - unsigned rSize, unsigned gOffset, unsigned gSize, unsigned bOffset, unsigned bSize, - unsigned aOffset, unsigned aSize); - - ImageFormatType GetType() const override; - size_t GetPitch(unsigned mipLevel, unsigned width) const override; - size_t GetSizeOfMipLevel(unsigned mipLevel, unsigned width, unsigned height, unsigned depth) const override; - - bool HasR() const; - bool HasG() const; - bool HasB() const; - bool HasA() const; + unsigned m_bits_per_pixel; + unsigned m_r_offset; + unsigned m_r_size; + unsigned m_g_offset; + unsigned m_g_size; + unsigned m_b_offset; + unsigned m_b_size; + unsigned m_a_offset; + unsigned m_a_size; + + ImageFormatUnsigned(ImageFormatId id, D3DFORMAT d3dFormat, DXGI_FORMAT dxgiFormat, unsigned bitsPerPixel, unsigned rOffset, unsigned rSize, unsigned gOffset, + unsigned gSize, unsigned bOffset, unsigned bSize, unsigned aOffset, unsigned aSize); + + ImageFormatType GetType() const override; + size_t GetPitch(unsigned mipLevel, unsigned width) const override; + size_t GetSizeOfMipLevel(unsigned mipLevel, unsigned width, unsigned height, unsigned depth) const override; + + bool HasR() const; + bool HasG() const; + bool HasB() const; + bool HasA() const; }; -class ImageFormatBlockCompressed final : public ImageFormat -{ +class ImageFormatBlockCompressed final : public ImageFormat { public: - unsigned m_block_size; - unsigned m_bits_per_block; + unsigned m_block_size; + unsigned m_bits_per_block; - ImageFormatBlockCompressed(ImageFormatId id, D3DFORMAT d3dFormat, DXGI_FORMAT dxgiFormat, unsigned blockSize, unsigned bitsPerBlock); + ImageFormatBlockCompressed(ImageFormatId id, D3DFORMAT d3dFormat, DXGI_FORMAT dxgiFormat, unsigned blockSize, unsigned bitsPerBlock); - ImageFormatType GetType() const override; - size_t GetPitch(unsigned mipLevel, unsigned width) const override; - size_t GetSizeOfMipLevel(unsigned mipLevel, unsigned width, unsigned height, unsigned depth) const override; + ImageFormatType GetType() const override; + size_t GetPitch(unsigned mipLevel, unsigned width) const override; + size_t GetSizeOfMipLevel(unsigned mipLevel, unsigned width, unsigned height, unsigned depth) const override; }; diff --git a/src/Common/Image/IwiTypes.h b/src/Common/Image/IwiTypes.h index f0f0794e9..cf14dc8fd 100644 --- a/src/Common/Image/IwiTypes.h +++ b/src/Common/Image/IwiTypes.h @@ -2,234 +2,217 @@ #include -struct IwiVersion -{ - char tag[3]; - char version; +struct IwiVersion { + char tag[3]; + char version; }; // IW3 -namespace iwi6 -{ - struct IwiHeader - { - int8_t format; - int8_t flags; - uint16_t dimensions[3]; - uint32_t fileSizeForPicmip[4]; - }; - - enum class IwiFormat - { - IMG_FORMAT_INVALID = 0x0, - IMG_FORMAT_BITMAP_RGBA = 0x1, - IMG_FORMAT_BITMAP_RGB = 0x2, - IMG_FORMAT_BITMAP_LUMINANCE_ALPHA = 0x3, - IMG_FORMAT_BITMAP_LUMINANCE = 0x4, - IMG_FORMAT_BITMAP_ALPHA = 0x5, - IMG_FORMAT_WAVELET_RGBA = 0x6, - IMG_FORMAT_WAVELET_RGB = 0x7, - IMG_FORMAT_WAVELET_LUMINANCE_ALPHA = 0x8, - IMG_FORMAT_WAVELET_LUMINANCE = 0x9, - IMG_FORMAT_WAVELET_ALPHA = 0xA, - IMG_FORMAT_DXT1 = 0xB, - IMG_FORMAT_DXT3 = 0xC, - IMG_FORMAT_DXT5 = 0xD, - IMG_FORMAT_DXN = 0xE, - - IMG_FORMAT_COUNT - }; - - enum IwiFlags - { - IMG_FLAG_NOPICMIP = 1 << 0, - IMG_FLAG_NOMIPMAPS = 1 << 1, - IMG_FLAG_CUBEMAP = 1 << 2, - IMG_FLAG_VOLMAP = 1 << 3, - IMG_FLAG_STREAMING = 1 << 4, - IMG_FLAG_LEGACY_NORMALS = 1 << 5, - IMG_FLAG_CLAMP_U = 1 << 6, - IMG_FLAG_CLAMP_V = 1 << 7, - IMG_FLAG_DYNAMIC = 1 << 16, - IMG_FLAG_RENDER_TARGET = 1 << 17, - IMG_FLAG_SYSTEMMEM = 1 << 18 - }; -} +namespace iwi6 { +struct IwiHeader { + int8_t format; + int8_t flags; + uint16_t dimensions[3]; + uint32_t fileSizeForPicmip[4]; +}; + +enum class IwiFormat { + IMG_FORMAT_INVALID = 0x0, + IMG_FORMAT_BITMAP_RGBA = 0x1, + IMG_FORMAT_BITMAP_RGB = 0x2, + IMG_FORMAT_BITMAP_LUMINANCE_ALPHA = 0x3, + IMG_FORMAT_BITMAP_LUMINANCE = 0x4, + IMG_FORMAT_BITMAP_ALPHA = 0x5, + IMG_FORMAT_WAVELET_RGBA = 0x6, + IMG_FORMAT_WAVELET_RGB = 0x7, + IMG_FORMAT_WAVELET_LUMINANCE_ALPHA = 0x8, + IMG_FORMAT_WAVELET_LUMINANCE = 0x9, + IMG_FORMAT_WAVELET_ALPHA = 0xA, + IMG_FORMAT_DXT1 = 0xB, + IMG_FORMAT_DXT3 = 0xC, + IMG_FORMAT_DXT5 = 0xD, + IMG_FORMAT_DXN = 0xE, + + IMG_FORMAT_COUNT +}; + +enum IwiFlags { + IMG_FLAG_NOPICMIP = 1 << 0, + IMG_FLAG_NOMIPMAPS = 1 << 1, + IMG_FLAG_CUBEMAP = 1 << 2, + IMG_FLAG_VOLMAP = 1 << 3, + IMG_FLAG_STREAMING = 1 << 4, + IMG_FLAG_LEGACY_NORMALS = 1 << 5, + IMG_FLAG_CLAMP_U = 1 << 6, + IMG_FLAG_CLAMP_V = 1 << 7, + IMG_FLAG_DYNAMIC = 1 << 16, + IMG_FLAG_RENDER_TARGET = 1 << 17, + IMG_FLAG_SYSTEMMEM = 1 << 18 +}; +} // namespace iwi6 // IW4 -namespace iwi8 -{ - struct IwiHeader - { - uint32_t flags; - int8_t format; - int8_t unused; - uint16_t dimensions[3]; - uint32_t fileSizeForPicmip[4]; - }; - - enum class IwiFormat - { - IMG_FORMAT_INVALID = 0x0, - IMG_FORMAT_BITMAP_RGBA = 0x1, - IMG_FORMAT_BITMAP_RGB = 0x2, - IMG_FORMAT_BITMAP_LUMINANCE_ALPHA = 0x3, - IMG_FORMAT_BITMAP_LUMINANCE = 0x4, - IMG_FORMAT_BITMAP_ALPHA = 0x5, - IMG_FORMAT_WAVELET_RGBA = 0x6, - IMG_FORMAT_WAVELET_RGB = 0x7, - IMG_FORMAT_WAVELET_LUMINANCE_ALPHA = 0x8, - IMG_FORMAT_WAVELET_LUMINANCE = 0x9, - IMG_FORMAT_WAVELET_ALPHA = 0xA, - IMG_FORMAT_DXT1 = 0xB, - IMG_FORMAT_DXT3 = 0xC, - IMG_FORMAT_DXT5 = 0xD, - IMG_FORMAT_DXN = 0xE, - IMG_FORMAT_DXT3A_AS_LUMINANCE = 0xF, - IMG_FORMAT_DXT5A_AS_LUMINANCE = 0x10, - IMG_FORMAT_DXT3A_AS_ALPHA = 0x11, - IMG_FORMAT_DXT5A_AS_ALPHA = 0x12, - IMG_FORMAT_DXT1_AS_LUMINANCE_ALPHA = 0x13, - IMG_FORMAT_DXN_AS_LUMINANCE_ALPHA = 0x14, - IMG_FORMAT_DXT1_AS_LUMINANCE = 0x15, - IMG_FORMAT_DXT1_AS_ALPHA = 0x16, - - IMG_FORMAT_COUNT - }; - - enum IwiFlags - { - IMG_FLAG_NOPICMIP = 1 << 0, - IMG_FLAG_NOMIPMAPS = 1 << 1, - IMG_FLAG_STREAMING = 1 << 2, - IMG_FLAG_LEGACY_NORMALS = 1 << 3, - IMG_FLAG_CLAMP_U = 1 << 4, - IMG_FLAG_CLAMP_V = 1 << 5, - IMG_FLAG_ALPHA_WEIGHTED_COLORS = 1 << 6, - IMG_FLAG_DXTC_APPROX_WEIGHTS = 1 << 7, - IMG_FLAG_GAMMA_NONE = 0, - IMG_FLAG_GAMMA_SRGB = 1 << 8, - IMG_FLAG_GAMMA_PWL = 1 << 9, - IMG_FLAG_GAMMA_2 = IMG_FLAG_GAMMA_SRGB | IMG_FLAG_GAMMA_PWL, - IMG_FLAG_MAPTYPE_2D = 0, - IMG_FLAG_MAPTYPE_CUBE = 1 << 16, - IMG_FLAG_MAPTYPE_3D = 1 << 17, - IMG_FLAG_MAPTYPE_1D = IMG_FLAG_MAPTYPE_CUBE | IMG_FLAG_MAPTYPE_3D, - IMG_FLAG_MAPTYPE_MASK = IMG_FLAG_MAPTYPE_2D | IMG_FLAG_MAPTYPE_CUBE | IMG_FLAG_MAPTYPE_3D | IMG_FLAG_MAPTYPE_1D, - IMG_FLAG_NORMALMAP = 1 << 18, - IMG_FLAG_INTENSITY_TO_ALPHA = 1 << 19, - IMG_FLAG_DYNAMIC = 1 << 24, - IMG_FLAG_RENDER_TARGET = 1 << 25, - IMG_FLAG_SYSTEMMEM = 1 << 26 - }; -} +namespace iwi8 { +struct IwiHeader { + uint32_t flags; + int8_t format; + int8_t unused; + uint16_t dimensions[3]; + uint32_t fileSizeForPicmip[4]; +}; + +enum class IwiFormat { + IMG_FORMAT_INVALID = 0x0, + IMG_FORMAT_BITMAP_RGBA = 0x1, + IMG_FORMAT_BITMAP_RGB = 0x2, + IMG_FORMAT_BITMAP_LUMINANCE_ALPHA = 0x3, + IMG_FORMAT_BITMAP_LUMINANCE = 0x4, + IMG_FORMAT_BITMAP_ALPHA = 0x5, + IMG_FORMAT_WAVELET_RGBA = 0x6, + IMG_FORMAT_WAVELET_RGB = 0x7, + IMG_FORMAT_WAVELET_LUMINANCE_ALPHA = 0x8, + IMG_FORMAT_WAVELET_LUMINANCE = 0x9, + IMG_FORMAT_WAVELET_ALPHA = 0xA, + IMG_FORMAT_DXT1 = 0xB, + IMG_FORMAT_DXT3 = 0xC, + IMG_FORMAT_DXT5 = 0xD, + IMG_FORMAT_DXN = 0xE, + IMG_FORMAT_DXT3A_AS_LUMINANCE = 0xF, + IMG_FORMAT_DXT5A_AS_LUMINANCE = 0x10, + IMG_FORMAT_DXT3A_AS_ALPHA = 0x11, + IMG_FORMAT_DXT5A_AS_ALPHA = 0x12, + IMG_FORMAT_DXT1_AS_LUMINANCE_ALPHA = 0x13, + IMG_FORMAT_DXN_AS_LUMINANCE_ALPHA = 0x14, + IMG_FORMAT_DXT1_AS_LUMINANCE = 0x15, + IMG_FORMAT_DXT1_AS_ALPHA = 0x16, + + IMG_FORMAT_COUNT +}; + +enum IwiFlags { + IMG_FLAG_NOPICMIP = 1 << 0, + IMG_FLAG_NOMIPMAPS = 1 << 1, + IMG_FLAG_STREAMING = 1 << 2, + IMG_FLAG_LEGACY_NORMALS = 1 << 3, + IMG_FLAG_CLAMP_U = 1 << 4, + IMG_FLAG_CLAMP_V = 1 << 5, + IMG_FLAG_ALPHA_WEIGHTED_COLORS = 1 << 6, + IMG_FLAG_DXTC_APPROX_WEIGHTS = 1 << 7, + IMG_FLAG_GAMMA_NONE = 0, + IMG_FLAG_GAMMA_SRGB = 1 << 8, + IMG_FLAG_GAMMA_PWL = 1 << 9, + IMG_FLAG_GAMMA_2 = IMG_FLAG_GAMMA_SRGB | IMG_FLAG_GAMMA_PWL, + IMG_FLAG_MAPTYPE_2D = 0, + IMG_FLAG_MAPTYPE_CUBE = 1 << 16, + IMG_FLAG_MAPTYPE_3D = 1 << 17, + IMG_FLAG_MAPTYPE_1D = IMG_FLAG_MAPTYPE_CUBE | IMG_FLAG_MAPTYPE_3D, + IMG_FLAG_MAPTYPE_MASK = IMG_FLAG_MAPTYPE_2D | IMG_FLAG_MAPTYPE_CUBE | IMG_FLAG_MAPTYPE_3D | IMG_FLAG_MAPTYPE_1D, + IMG_FLAG_NORMALMAP = 1 << 18, + IMG_FLAG_INTENSITY_TO_ALPHA = 1 << 19, + IMG_FLAG_DYNAMIC = 1 << 24, + IMG_FLAG_RENDER_TARGET = 1 << 25, + IMG_FLAG_SYSTEMMEM = 1 << 26 +}; +} // namespace iwi8 // T5 -namespace iwi13 -{ - struct IwiHeader - { - int8_t format; - int8_t flags; - uint16_t dimensions[3]; - float gamma; - uint32_t fileSizeForPicmip[8]; - }; - - enum class IwiFormat - { - IMG_FORMAT_INVALID = 0x0, - IMG_FORMAT_BITMAP_RGBA = 0x1, - IMG_FORMAT_BITMAP_RGB = 0x2, - IMG_FORMAT_BITMAP_LUMINANCE_ALPHA = 0x3, - IMG_FORMAT_BITMAP_LUMINANCE = 0x4, - IMG_FORMAT_BITMAP_ALPHA = 0x5, - IMG_FORMAT_WAVELET_RGBA = 0x6, - IMG_FORMAT_WAVELET_RGB = 0x7, - IMG_FORMAT_WAVELET_LUMINANCE_ALPHA = 0x8, - IMG_FORMAT_WAVELET_LUMINANCE = 0x9, - IMG_FORMAT_WAVELET_ALPHA = 0xA, - IMG_FORMAT_DXT1 = 0xB, - IMG_FORMAT_DXT3 = 0xC, - IMG_FORMAT_DXT5 = 0xD, - IMG_FORMAT_DXN = 0xE, - IMG_FORMAT_BITMAP_RGB565 = 0xF, - IMG_FORMAT_BITMAP_RGB5A3 = 0x10, - IMG_FORMAT_BITMAP_C8 = 0x11, - IMG_FORMAT_BITMAP_RGBA8 = 0x12, - IMG_FORMAT_A16B16G16R16F = 0x13, - IMG_FORMAT_COUNT = 0x14, - }; - - enum IwiFlags - { - IMG_FLAG_NOPICMIP = 1 << 0, - IMG_FLAG_NOMIPMAPS = 1 << 1, - IMG_FLAG_CUBEMAP = 1 << 2, - IMG_FLAG_VOLMAP = 1 << 3, - IMG_FLAG_STREAMING = 1 << 4, - IMG_FLAG_LEGACY_NORMALS = 1 << 5, - IMG_FLAG_CLAMP_U = 1 << 6, - IMG_FLAG_CLAMP_V = 1 << 7, - IMG_FLAG_FORCE_SYSTEM = 1 << 8, - IMG_FLAG_DYNAMIC = 1 << 16, - IMG_FLAG_RENDER_TARGET = 1 << 17, - IMG_FLAG_SYSTEMMEM = 1 << 18, - }; - -} +namespace iwi13 { +struct IwiHeader { + int8_t format; + int8_t flags; + uint16_t dimensions[3]; + float gamma; + uint32_t fileSizeForPicmip[8]; +}; + +enum class IwiFormat { + IMG_FORMAT_INVALID = 0x0, + IMG_FORMAT_BITMAP_RGBA = 0x1, + IMG_FORMAT_BITMAP_RGB = 0x2, + IMG_FORMAT_BITMAP_LUMINANCE_ALPHA = 0x3, + IMG_FORMAT_BITMAP_LUMINANCE = 0x4, + IMG_FORMAT_BITMAP_ALPHA = 0x5, + IMG_FORMAT_WAVELET_RGBA = 0x6, + IMG_FORMAT_WAVELET_RGB = 0x7, + IMG_FORMAT_WAVELET_LUMINANCE_ALPHA = 0x8, + IMG_FORMAT_WAVELET_LUMINANCE = 0x9, + IMG_FORMAT_WAVELET_ALPHA = 0xA, + IMG_FORMAT_DXT1 = 0xB, + IMG_FORMAT_DXT3 = 0xC, + IMG_FORMAT_DXT5 = 0xD, + IMG_FORMAT_DXN = 0xE, + IMG_FORMAT_BITMAP_RGB565 = 0xF, + IMG_FORMAT_BITMAP_RGB5A3 = 0x10, + IMG_FORMAT_BITMAP_C8 = 0x11, + IMG_FORMAT_BITMAP_RGBA8 = 0x12, + IMG_FORMAT_A16B16G16R16F = 0x13, + IMG_FORMAT_COUNT = 0x14, +}; + +enum IwiFlags { + IMG_FLAG_NOPICMIP = 1 << 0, + IMG_FLAG_NOMIPMAPS = 1 << 1, + IMG_FLAG_CUBEMAP = 1 << 2, + IMG_FLAG_VOLMAP = 1 << 3, + IMG_FLAG_STREAMING = 1 << 4, + IMG_FLAG_LEGACY_NORMALS = 1 << 5, + IMG_FLAG_CLAMP_U = 1 << 6, + IMG_FLAG_CLAMP_V = 1 << 7, + IMG_FLAG_FORCE_SYSTEM = 1 << 8, + IMG_FLAG_DYNAMIC = 1 << 16, + IMG_FLAG_RENDER_TARGET = 1 << 17, + IMG_FLAG_SYSTEMMEM = 1 << 18, +}; + +} // namespace iwi13 // T6 -namespace iwi27 -{ - struct IwiHeader - { - int8_t format; - int8_t flags; - uint16_t dimensions[3]; - float gamma; - int8_t maxGlossForMip[16]; - uint32_t fileSizeForPicmip[8]; - }; - - enum class IwiFormat - { - IMG_FORMAT_INVALID = 0x0, - IMG_FORMAT_BITMAP_RGBA = 0x1, - IMG_FORMAT_BITMAP_RGB = 0x2, - IMG_FORMAT_BITMAP_LUMINANCE_ALPHA = 0x3, - IMG_FORMAT_BITMAP_LUMINANCE = 0x4, - IMG_FORMAT_BITMAP_ALPHA = 0x5, - IMG_FORMAT_WAVELET_RGBA = 0x6, - IMG_FORMAT_WAVELET_RGB = 0x7, - IMG_FORMAT_WAVELET_LUMINANCE_ALPHA = 0x8, - IMG_FORMAT_WAVELET_LUMINANCE = 0x9, - IMG_FORMAT_WAVELET_ALPHA = 0xA, - IMG_FORMAT_DXT1 = 0xB, - IMG_FORMAT_DXT3 = 0xC, - IMG_FORMAT_DXT5 = 0xD, - IMG_FORMAT_DXN = 0xE, - IMG_FORMAT_BITMAP_RGB565 = 0xF, - IMG_FORMAT_BITMAP_RGB5A3 = 0x10, - IMG_FORMAT_BITMAP_C8 = 0x11, - IMG_FORMAT_BITMAP_RGBA8 = 0x12, - IMG_FORMAT_A16B16G16R16F = 0x13, - IMG_FORMAT_COUNT, - }; - - enum IwiFlags - { - IMG_FLAG_NOPICMIP = 1 << 0, - IMG_FLAG_NOMIPMAPS = 1 << 1, - IMG_FLAG_CUBEMAP = 1 << 2, - IMG_FLAG_VOLMAP = 1 << 3, - IMG_FLAG_STREAMING = 1 << 4, - IMG_FLAG_CLAMP_U = 1 << 6, - IMG_FLAG_CLAMP_V = 1 << 7, - IMG_FLAG_FORCE_SYSTEM = 1 << 8, - IMG_FLAG_DYNAMIC = 1 << 16, - IMG_FLAG_RENDER_TARGET = 1 << 17, - IMG_FLAG_MULTISAMPLE = 1 << 18, - }; - -} +namespace iwi27 { +struct IwiHeader { + int8_t format; + int8_t flags; + uint16_t dimensions[3]; + float gamma; + int8_t maxGlossForMip[16]; + uint32_t fileSizeForPicmip[8]; +}; + +enum class IwiFormat { + IMG_FORMAT_INVALID = 0x0, + IMG_FORMAT_BITMAP_RGBA = 0x1, + IMG_FORMAT_BITMAP_RGB = 0x2, + IMG_FORMAT_BITMAP_LUMINANCE_ALPHA = 0x3, + IMG_FORMAT_BITMAP_LUMINANCE = 0x4, + IMG_FORMAT_BITMAP_ALPHA = 0x5, + IMG_FORMAT_WAVELET_RGBA = 0x6, + IMG_FORMAT_WAVELET_RGB = 0x7, + IMG_FORMAT_WAVELET_LUMINANCE_ALPHA = 0x8, + IMG_FORMAT_WAVELET_LUMINANCE = 0x9, + IMG_FORMAT_WAVELET_ALPHA = 0xA, + IMG_FORMAT_DXT1 = 0xB, + IMG_FORMAT_DXT3 = 0xC, + IMG_FORMAT_DXT5 = 0xD, + IMG_FORMAT_DXN = 0xE, + IMG_FORMAT_BITMAP_RGB565 = 0xF, + IMG_FORMAT_BITMAP_RGB5A3 = 0x10, + IMG_FORMAT_BITMAP_C8 = 0x11, + IMG_FORMAT_BITMAP_RGBA8 = 0x12, + IMG_FORMAT_A16B16G16R16F = 0x13, + IMG_FORMAT_COUNT, +}; + +enum IwiFlags { + IMG_FLAG_NOPICMIP = 1 << 0, + IMG_FLAG_NOMIPMAPS = 1 << 1, + IMG_FLAG_CUBEMAP = 1 << 2, + IMG_FLAG_VOLMAP = 1 << 3, + IMG_FLAG_STREAMING = 1 << 4, + IMG_FLAG_CLAMP_U = 1 << 6, + IMG_FLAG_CLAMP_V = 1 << 7, + IMG_FLAG_FORCE_SYSTEM = 1 << 8, + IMG_FLAG_DYNAMIC = 1 << 16, + IMG_FLAG_RENDER_TARGET = 1 << 17, + IMG_FLAG_MULTISAMPLE = 1 << 18, +}; + +} // namespace iwi27 diff --git a/src/Common/Image/Texture.cpp b/src/Common/Image/Texture.cpp index 79de68116..5f7b7adb6 100644 --- a/src/Common/Image/Texture.cpp +++ b/src/Common/Image/Texture.cpp @@ -7,180 +7,128 @@ // ============================================== // ================= Texture ==================== // ============================================== -Texture::Texture(const ImageFormat* format, const bool mipMaps) -{ - m_format = format; - m_has_mip_maps = mipMaps; - m_data = nullptr; +Texture::Texture(const ImageFormat *format, const bool mipMaps) { + m_format = format; + m_has_mip_maps = mipMaps; + m_data = nullptr; } -Texture::Texture(Texture&& other) noexcept -{ - m_format = other.m_format; - m_has_mip_maps = other.m_has_mip_maps; - m_data = other.m_data; +Texture::Texture(Texture &&other) noexcept { + m_format = other.m_format; + m_has_mip_maps = other.m_has_mip_maps; + m_data = other.m_data; - other.m_data = nullptr; + other.m_data = nullptr; } -Texture& Texture::operator=(Texture&& other) noexcept -{ - m_format = other.m_format; - m_has_mip_maps = other.m_has_mip_maps; - m_data = other.m_data; +Texture &Texture::operator=(Texture &&other) noexcept { + m_format = other.m_format; + m_has_mip_maps = other.m_has_mip_maps; + m_data = other.m_data; - other.m_data = nullptr; + other.m_data = nullptr; - return *this; + return *this; } -Texture::~Texture() -{ - delete[] m_data; - m_data = nullptr; +Texture::~Texture() { + delete[] m_data; + m_data = nullptr; } -const ImageFormat* Texture::GetFormat() const -{ - return m_format; -} +const ImageFormat *Texture::GetFormat() const { return m_format; } -void Texture::Allocate() -{ - size_t storageRequirement = 0; - const int mipLevelCount = m_has_mip_maps ? GetMipMapCount() : 1; - - for (int currentMipLevel = 0; currentMipLevel < mipLevelCount; currentMipLevel++) - { - storageRequirement += GetSizeOfMipLevel(currentMipLevel) * GetFaceCount(); - } - - if (storageRequirement > 0) - { - m_data = new uint8_t[storageRequirement]; - memset(m_data, 0, storageRequirement); - } -} +void Texture::Allocate() { + size_t storageRequirement = 0; + const int mipLevelCount = m_has_mip_maps ? GetMipMapCount() : 1; -bool Texture::Empty() const -{ - return m_data == nullptr; -} + for (int currentMipLevel = 0; currentMipLevel < mipLevelCount; currentMipLevel++) { + storageRequirement += GetSizeOfMipLevel(currentMipLevel) * GetFaceCount(); + } -bool Texture::HasMipMaps() const -{ - return m_has_mip_maps; + if (storageRequirement > 0) { + m_data = new uint8_t[storageRequirement]; + memset(m_data, 0, storageRequirement); + } } -uint8_t* Texture::GetBufferForMipLevel(const int mipLevel) -{ - return GetBufferForMipLevel(mipLevel, 0); -} +bool Texture::Empty() const { return m_data == nullptr; } + +bool Texture::HasMipMaps() const { return m_has_mip_maps; } + +uint8_t *Texture::GetBufferForMipLevel(const int mipLevel) { return GetBufferForMipLevel(mipLevel, 0); } // ============================================== // ================ Texture2D =================== // ============================================== -Texture2D::Texture2D(const ImageFormat* format, const unsigned width, const unsigned height) - : Texture2D(format, width, height, false) -{ -} +Texture2D::Texture2D(const ImageFormat *format, const unsigned width, const unsigned height) : Texture2D(format, width, height, false) {} -Texture2D::Texture2D(const ImageFormat* format, const unsigned width, const unsigned height, const bool mipMaps) - : Texture(format, mipMaps) -{ - m_width = width; - m_height = height; +Texture2D::Texture2D(const ImageFormat *format, const unsigned width, const unsigned height, const bool mipMaps) : Texture(format, mipMaps) { + m_width = width; + m_height = height; } -Texture2D::Texture2D(Texture2D&& other) noexcept - : Texture(std::move(other)), - m_width(other.m_width), - m_height(other.m_height) -{ -} +Texture2D::Texture2D(Texture2D &&other) noexcept : Texture(std::move(other)), m_width(other.m_width), m_height(other.m_height) {} Texture2D::~Texture2D() = default; -Texture2D& Texture2D::operator=(Texture2D&& other) noexcept -{ - if (this == &other) - return *this; +Texture2D &Texture2D::operator=(Texture2D &&other) noexcept { + if (this == &other) + return *this; - Texture::operator=(std::move(other)); - m_width = other.m_width; - m_height = other.m_height; + Texture::operator=(std::move(other)); + m_width = other.m_width; + m_height = other.m_height; - return *this; + return *this; } -TextureType Texture2D::GetTextureType() const -{ - return TextureType::T_2D; -} +TextureType Texture2D::GetTextureType() const { return TextureType::T_2D; } -unsigned Texture2D::GetWidth() const -{ - return m_width; -} +unsigned Texture2D::GetWidth() const { return m_width; } -unsigned Texture2D::GetHeight() const -{ - return m_height; -} +unsigned Texture2D::GetHeight() const { return m_height; } -unsigned Texture2D::GetDepth() const -{ - return 1; -} +unsigned Texture2D::GetDepth() const { return 1; } -int Texture2D::GetFaceCount() const -{ - return 1; -} +int Texture2D::GetFaceCount() const { return 1; } -size_t Texture2D::GetSizeOfMipLevel(const int mipLevel) const -{ - return m_format->GetSizeOfMipLevel(mipLevel, m_width, m_height, 1); -} +size_t Texture2D::GetSizeOfMipLevel(const int mipLevel) const { return m_format->GetSizeOfMipLevel(mipLevel, m_width, m_height, 1); } -int Texture2D::GetMipMapCount() const -{ - unsigned maxDimension = std::max(m_width, m_height); +int Texture2D::GetMipMapCount() const { + unsigned maxDimension = std::max(m_width, m_height); - int mipMapCount = 0; + int mipMapCount = 0; - while (maxDimension != 0) - { - maxDimension >>= 1; - mipMapCount++; - } + while (maxDimension != 0) { + maxDimension >>= 1; + mipMapCount++; + } - return mipMapCount; + return mipMapCount; } -uint8_t* Texture2D::GetBufferForMipLevel(const int mipLevel, const int face) -{ - assert(mipLevel >= 0); - assert(mipLevel < (m_has_mip_maps ? GetMipMapCount() : 1)); - assert(face == 0); - assert(m_data); +uint8_t *Texture2D::GetBufferForMipLevel(const int mipLevel, const int face) { + assert(mipLevel >= 0); + assert(mipLevel < (m_has_mip_maps ? GetMipMapCount() : 1)); + assert(face == 0); + assert(m_data); - if (mipLevel < 0 || mipLevel >= (m_has_mip_maps ? GetMipMapCount() : 1)) - return nullptr; + if (mipLevel < 0 || mipLevel >= (m_has_mip_maps ? GetMipMapCount() : 1)) + return nullptr; - if (face != 0) - return nullptr; + if (face != 0) + return nullptr; - if (!m_data) - return nullptr; + if (!m_data) + return nullptr; - size_t bufferOffset = 0; - for (int previousMipLevel = 0; previousMipLevel < mipLevel; previousMipLevel++) - { - bufferOffset += GetSizeOfMipLevel(previousMipLevel); - } + size_t bufferOffset = 0; + for (int previousMipLevel = 0; previousMipLevel < mipLevel; previousMipLevel++) { + bufferOffset += GetSizeOfMipLevel(previousMipLevel); + } - return &m_data[bufferOffset]; + return &m_data[bufferOffset]; } // ============================================== @@ -188,176 +136,126 @@ uint8_t* Texture2D::GetBufferForMipLevel(const int mipLevel, const int face) // ============================================== const int TextureCube::FACE_COUNT = 6; -TextureCube::TextureCube(const ImageFormat* format, const unsigned width, const unsigned height) - : Texture2D(format, width, height) -{ -} +TextureCube::TextureCube(const ImageFormat *format, const unsigned width, const unsigned height) : Texture2D(format, width, height) {} -TextureCube::TextureCube(const ImageFormat* format, const unsigned width, const unsigned height, const bool mipMaps) - : Texture2D(format, width, height, mipMaps) -{ -} +TextureCube::TextureCube(const ImageFormat *format, const unsigned width, const unsigned height, const bool mipMaps) + : Texture2D(format, width, height, mipMaps) {} -TextureCube::TextureCube(TextureCube&& other) noexcept - : Texture2D(std::move(other)) -{ -} +TextureCube::TextureCube(TextureCube &&other) noexcept : Texture2D(std::move(other)) {} TextureCube::~TextureCube() = default; -TextureCube& TextureCube::operator=(TextureCube&& other) noexcept -{ - if (this == &other) - return *this; +TextureCube &TextureCube::operator=(TextureCube &&other) noexcept { + if (this == &other) + return *this; - Texture2D::operator=(std::move(other)); + Texture2D::operator=(std::move(other)); - return *this; + return *this; } -TextureType TextureCube::GetTextureType() const -{ - return TextureType::T_CUBE; -} +TextureType TextureCube::GetTextureType() const { return TextureType::T_CUBE; } -int TextureCube::GetFaceCount() const -{ - return FACE_COUNT; -} +int TextureCube::GetFaceCount() const { return FACE_COUNT; } -uint8_t* TextureCube::GetBufferForMipLevel(const int mipLevel, const int face) -{ - assert(mipLevel >= 0); - assert(mipLevel < (m_has_mip_maps ? GetMipMapCount() : 1)); - assert(face >= 0); - assert(face < FACE_COUNT); - assert(m_data); +uint8_t *TextureCube::GetBufferForMipLevel(const int mipLevel, const int face) { + assert(mipLevel >= 0); + assert(mipLevel < (m_has_mip_maps ? GetMipMapCount() : 1)); + assert(face >= 0); + assert(face < FACE_COUNT); + assert(m_data); - if (mipLevel < 0 || mipLevel >= (m_has_mip_maps ? GetMipMapCount() : 1)) - return nullptr; + if (mipLevel < 0 || mipLevel >= (m_has_mip_maps ? GetMipMapCount() : 1)) + return nullptr; - if (face < 0 || face >= FACE_COUNT) - return nullptr; + if (face < 0 || face >= FACE_COUNT) + return nullptr; - if (!m_data) - return nullptr; + if (!m_data) + return nullptr; - size_t bufferOffset = 0; - for (int previousMipLevel = 0; previousMipLevel < mipLevel; previousMipLevel++) - { - bufferOffset += GetSizeOfMipLevel(previousMipLevel) * FACE_COUNT; - } + size_t bufferOffset = 0; + for (int previousMipLevel = 0; previousMipLevel < mipLevel; previousMipLevel++) { + bufferOffset += GetSizeOfMipLevel(previousMipLevel) * FACE_COUNT; + } - return &m_data[bufferOffset + GetSizeOfMipLevel(mipLevel) * face]; + return &m_data[bufferOffset + GetSizeOfMipLevel(mipLevel) * face]; } // ============================================== // ================ Texture3D =================== // ============================================== -Texture3D::Texture3D(const ImageFormat* format, const unsigned width, const unsigned height, const unsigned depth) - : Texture3D(format, width, height, depth, false) -{ -} +Texture3D::Texture3D(const ImageFormat *format, const unsigned width, const unsigned height, const unsigned depth) + : Texture3D(format, width, height, depth, false) {} -Texture3D::Texture3D(const ImageFormat* format, const unsigned width, const unsigned height, const unsigned depth, - const bool mipMaps) - : Texture(format, mipMaps) -{ - m_width = width; - m_height = height; - m_depth = depth; +Texture3D::Texture3D(const ImageFormat *format, const unsigned width, const unsigned height, const unsigned depth, const bool mipMaps) + : Texture(format, mipMaps) { + m_width = width; + m_height = height; + m_depth = depth; } -Texture3D::Texture3D(Texture3D&& other) noexcept - : Texture(std::move(other)), - m_width(other.m_width), - m_height(other.m_height), - m_depth(other.m_depth) -{ -} +Texture3D::Texture3D(Texture3D &&other) noexcept : Texture(std::move(other)), m_width(other.m_width), m_height(other.m_height), m_depth(other.m_depth) {} Texture3D::~Texture3D() = default; -Texture3D& Texture3D::operator=(Texture3D&& other) noexcept -{ - if (this == &other) - return *this; +Texture3D &Texture3D::operator=(Texture3D &&other) noexcept { + if (this == &other) + return *this; - Texture::operator=(std::move(other)); - m_width = other.m_width; - m_height = other.m_height; - m_depth = other.m_depth; + Texture::operator=(std::move(other)); + m_width = other.m_width; + m_height = other.m_height; + m_depth = other.m_depth; - return *this; + return *this; } -TextureType Texture3D::GetTextureType() const -{ - return TextureType::T_3D; -} +TextureType Texture3D::GetTextureType() const { return TextureType::T_3D; } -unsigned Texture3D::GetWidth() const -{ - return m_width; -} +unsigned Texture3D::GetWidth() const { return m_width; } -unsigned Texture3D::GetHeight() const -{ - return m_height; -} +unsigned Texture3D::GetHeight() const { return m_height; } -unsigned Texture3D::GetDepth() const -{ - return m_depth; -} +unsigned Texture3D::GetDepth() const { return m_depth; } -int Texture3D::GetFaceCount() const -{ - return 1; -} +int Texture3D::GetFaceCount() const { return 1; } -size_t Texture3D::GetSizeOfMipLevel(const int mipLevel) const -{ - return m_format->GetSizeOfMipLevel(mipLevel, m_width, m_height, m_depth); -} +size_t Texture3D::GetSizeOfMipLevel(const int mipLevel) const { return m_format->GetSizeOfMipLevel(mipLevel, m_width, m_height, m_depth); } -int Texture3D::GetMipMapCount() const -{ - unsigned maxDimension = std::max(std::max(m_width, m_height), m_depth); +int Texture3D::GetMipMapCount() const { + unsigned maxDimension = std::max(std::max(m_width, m_height), m_depth); - int mipMapCount = 0; + int mipMapCount = 0; - while (maxDimension != 0) - { - maxDimension >>= 1; - mipMapCount++; - } + while (maxDimension != 0) { + maxDimension >>= 1; + mipMapCount++; + } - return mipMapCount; + return mipMapCount; } -uint8_t* Texture3D::GetBufferForMipLevel(const int mipLevel, const int face) -{ - assert(mipLevel >= 0); - assert(mipLevel < (m_has_mip_maps ? GetMipMapCount() : 1)); - assert(face == 0); - assert(m_data); +uint8_t *Texture3D::GetBufferForMipLevel(const int mipLevel, const int face) { + assert(mipLevel >= 0); + assert(mipLevel < (m_has_mip_maps ? GetMipMapCount() : 1)); + assert(face == 0); + assert(m_data); - if (mipLevel < 0 || mipLevel >= (m_has_mip_maps ? GetMipMapCount() : 1)) - return nullptr; + if (mipLevel < 0 || mipLevel >= (m_has_mip_maps ? GetMipMapCount() : 1)) + return nullptr; - if (face != 0) - return nullptr; + if (face != 0) + return nullptr; - if (!m_data) - return nullptr; + if (!m_data) + return nullptr; - size_t bufferOffset = 0; - for (int previousMipLevel = 0; previousMipLevel < mipLevel; previousMipLevel++) - { - bufferOffset += GetSizeOfMipLevel(previousMipLevel); - } + size_t bufferOffset = 0; + for (int previousMipLevel = 0; previousMipLevel < mipLevel; previousMipLevel++) { + bufferOffset += GetSizeOfMipLevel(previousMipLevel); + } - return &m_data[bufferOffset]; + return &m_data[bufferOffset]; } diff --git a/src/Common/Image/Texture.h b/src/Common/Image/Texture.h index 8df7cf45b..cfaa73756 100644 --- a/src/Common/Image/Texture.h +++ b/src/Common/Image/Texture.h @@ -2,125 +2,116 @@ #include "ImageFormat.h" #include -enum class TextureType -{ - T_2D, - T_CUBE, - T_3D -}; +enum class TextureType { T_2D, T_CUBE, T_3D }; -class Texture -{ +class Texture { protected: - const ImageFormat* m_format; - bool m_has_mip_maps; - uint8_t* m_data; + const ImageFormat *m_format; + bool m_has_mip_maps; + uint8_t *m_data; - Texture(const ImageFormat* format, bool mipMaps); - Texture(Texture&& other) noexcept; + Texture(const ImageFormat *format, bool mipMaps); + Texture(Texture &&other) noexcept; - Texture& operator=(Texture&& other) noexcept; + Texture &operator=(Texture &&other) noexcept; public: - Texture(const Texture& other) = delete; - virtual ~Texture(); + Texture(const Texture &other) = delete; + virtual ~Texture(); - Texture& operator=(const Texture& other) = delete; + Texture &operator=(const Texture &other) = delete; - virtual TextureType GetTextureType() const = 0; - const ImageFormat* GetFormat() const; + virtual TextureType GetTextureType() const = 0; + const ImageFormat *GetFormat() const; - virtual unsigned GetWidth() const = 0; - virtual unsigned GetHeight() const = 0; - virtual unsigned GetDepth() const = 0; - virtual int GetFaceCount() const = 0; + virtual unsigned GetWidth() const = 0; + virtual unsigned GetHeight() const = 0; + virtual unsigned GetDepth() const = 0; + virtual int GetFaceCount() const = 0; - void Allocate(); - bool Empty() const; + void Allocate(); + bool Empty() const; - virtual size_t GetSizeOfMipLevel(int mipLevel) const = 0; - virtual uint8_t* GetBufferForMipLevel(int mipLevel, int face) = 0; - uint8_t* GetBufferForMipLevel(int mipLevel); + virtual size_t GetSizeOfMipLevel(int mipLevel) const = 0; + virtual uint8_t *GetBufferForMipLevel(int mipLevel, int face) = 0; + uint8_t *GetBufferForMipLevel(int mipLevel); - bool HasMipMaps() const; - virtual int GetMipMapCount() const = 0; + bool HasMipMaps() const; + virtual int GetMipMapCount() const = 0; }; -class Texture2D : public Texture -{ +class Texture2D : public Texture { protected: - unsigned m_width; - unsigned m_height; + unsigned m_width; + unsigned m_height; public: - Texture2D(const ImageFormat* format, unsigned width, unsigned height); - Texture2D(const ImageFormat* format, unsigned width, unsigned height, bool mipMaps); - Texture2D(const Texture2D& other) = delete; - Texture2D(Texture2D&& other) noexcept; - ~Texture2D() override; + Texture2D(const ImageFormat *format, unsigned width, unsigned height); + Texture2D(const ImageFormat *format, unsigned width, unsigned height, bool mipMaps); + Texture2D(const Texture2D &other) = delete; + Texture2D(Texture2D &&other) noexcept; + ~Texture2D() override; - Texture2D& operator=(const Texture2D& other) = delete; - Texture2D& operator=(Texture2D&& other) noexcept; + Texture2D &operator=(const Texture2D &other) = delete; + Texture2D &operator=(Texture2D &&other) noexcept; - TextureType GetTextureType() const override; + TextureType GetTextureType() const override; - unsigned GetWidth() const override; - unsigned GetHeight() const override; - unsigned GetDepth() const override; - int GetFaceCount() const override; + unsigned GetWidth() const override; + unsigned GetHeight() const override; + unsigned GetDepth() const override; + int GetFaceCount() const override; - size_t GetSizeOfMipLevel(int mipLevel) const override; - uint8_t* GetBufferForMipLevel(int mipLevel, int face) override; + size_t GetSizeOfMipLevel(int mipLevel) const override; + uint8_t *GetBufferForMipLevel(int mipLevel, int face) override; - int GetMipMapCount() const override; + int GetMipMapCount() const override; }; -class TextureCube final : public Texture2D -{ - static const int FACE_COUNT; +class TextureCube final : public Texture2D { + static const int FACE_COUNT; public: - TextureCube(const ImageFormat* format, unsigned width, unsigned height); - TextureCube(const ImageFormat* format, unsigned width, unsigned height, bool mipMaps); - TextureCube(const TextureCube& other) = delete; - TextureCube(TextureCube&& other) noexcept; - ~TextureCube() override; + TextureCube(const ImageFormat *format, unsigned width, unsigned height); + TextureCube(const ImageFormat *format, unsigned width, unsigned height, bool mipMaps); + TextureCube(const TextureCube &other) = delete; + TextureCube(TextureCube &&other) noexcept; + ~TextureCube() override; - TextureCube& operator=(const TextureCube& other) = delete; - TextureCube& operator=(TextureCube&& other) noexcept; + TextureCube &operator=(const TextureCube &other) = delete; + TextureCube &operator=(TextureCube &&other) noexcept; - TextureType GetTextureType() const override; + TextureType GetTextureType() const override; - int GetFaceCount() const override; + int GetFaceCount() const override; - uint8_t* GetBufferForMipLevel(int mipLevel, int face) override; + uint8_t *GetBufferForMipLevel(int mipLevel, int face) override; }; -class Texture3D final : public Texture -{ - unsigned m_width; - unsigned m_height; - unsigned m_depth; +class Texture3D final : public Texture { + unsigned m_width; + unsigned m_height; + unsigned m_depth; public: - Texture3D(const ImageFormat* format, unsigned width, unsigned height, unsigned depth); - Texture3D(const ImageFormat* format, unsigned width, unsigned height, unsigned depth, bool mipMaps); - Texture3D(const Texture3D& other) = delete; - Texture3D(Texture3D&& other) noexcept; - ~Texture3D() override; + Texture3D(const ImageFormat *format, unsigned width, unsigned height, unsigned depth); + Texture3D(const ImageFormat *format, unsigned width, unsigned height, unsigned depth, bool mipMaps); + Texture3D(const Texture3D &other) = delete; + Texture3D(Texture3D &&other) noexcept; + ~Texture3D() override; - Texture3D& operator=(const Texture3D& other) = delete; - Texture3D& operator=(Texture3D&& other) noexcept; + Texture3D &operator=(const Texture3D &other) = delete; + Texture3D &operator=(Texture3D &&other) noexcept; - TextureType GetTextureType() const override; + TextureType GetTextureType() const override; - unsigned GetWidth() const override; - unsigned GetHeight() const override; - unsigned GetDepth() const override; - int GetFaceCount() const override; + unsigned GetWidth() const override; + unsigned GetHeight() const override; + unsigned GetDepth() const override; + int GetFaceCount() const override; - size_t GetSizeOfMipLevel(int mipLevel) const override; - uint8_t* GetBufferForMipLevel(int mipLevel, int face) override; + size_t GetSizeOfMipLevel(int mipLevel) const override; + uint8_t *GetBufferForMipLevel(int mipLevel, int face) override; - int GetMipMapCount() const override; + int GetMipMapCount() const override; }; \ No newline at end of file diff --git a/src/Common/Image/TextureConverter.cpp b/src/Common/Image/TextureConverter.cpp index 7a9cf0e15..fc491ada4 100644 --- a/src/Common/Image/TextureConverter.cpp +++ b/src/Common/Image/TextureConverter.cpp @@ -2,228 +2,166 @@ #include -constexpr uint64_t TextureConverter::Mask1(const unsigned length) -{ - if (length >= sizeof(uint64_t) * 8) - return UINT64_MAX; +constexpr uint64_t TextureConverter::Mask1(const unsigned length) { + if (length >= sizeof(uint64_t) * 8) + return UINT64_MAX; - return UINT64_MAX >> (sizeof(uint64_t) * 8 - length); + return UINT64_MAX >> (sizeof(uint64_t) * 8 - length); } -void TextureConverter::SetPixelFunctions(const unsigned inBitCount, const unsigned outBitCount) -{ - switch (inBitCount) - { - case 16: - m_read_pixel_func = [](const void* offset, unsigned bitCount) - { - return static_cast(*static_cast(offset)); - }; - break; - - case 32: - m_read_pixel_func = [](const void* offset, unsigned bitCount) - { - return static_cast(*static_cast(offset)); - }; - break; - - case 64: - m_read_pixel_func = [](const void* offset, unsigned bitCount) - { - return *static_cast(offset); - }; - break; - - default: - if (inBitCount <= 64) - { - m_read_pixel_func = [](const void* offset, const unsigned bitCount) - { - uint64_t result = 0; - - for (auto pixelOffset = 0u; pixelOffset < bitCount; pixelOffset += 8) - { - result |= (static_cast(*(static_cast(offset) + (pixelOffset / 8))) << - pixelOffset); - } - - return result; - }; - } - else - { - assert(false); - m_read_pixel_func = [](const void* offset, unsigned bitCount) - { - return 0ull; - }; - } - break; - } +void TextureConverter::SetPixelFunctions(const unsigned inBitCount, const unsigned outBitCount) { + switch (inBitCount) { + case 16: + m_read_pixel_func = [](const void *offset, unsigned bitCount) { return static_cast(*static_cast(offset)); }; + break; + + case 32: + m_read_pixel_func = [](const void *offset, unsigned bitCount) { return static_cast(*static_cast(offset)); }; + break; + + case 64: + m_read_pixel_func = [](const void *offset, unsigned bitCount) { return *static_cast(offset); }; + break; - switch (outBitCount) - { - case 16: - m_write_pixel_func = [](void* offset, const uint64_t pixel, unsigned bitCount) - { - *static_cast(offset) = static_cast(pixel); - }; - break; - - case 32: - m_write_pixel_func = [](void* offset, const uint64_t pixel, unsigned bitCount) - { - *static_cast(offset) = static_cast(pixel); - }; - break; - - case 64: - m_write_pixel_func = [](void* offset, const uint64_t pixel, unsigned bitCount) - { - *static_cast(offset) = pixel; - }; - break; - - default: - if (inBitCount <= 64) - { - m_write_pixel_func = [](void* offset, const uint64_t pixel, const unsigned bitCount) - { - for (auto pixelOffset = 0u; pixelOffset < bitCount; pixelOffset += 8) - { - *(static_cast(offset) + (pixelOffset / 8)) = static_cast(pixel >> pixelOffset); - } - }; + default: + if (inBitCount <= 64) { + m_read_pixel_func = [](const void *offset, const unsigned bitCount) { + uint64_t result = 0; + + for (auto pixelOffset = 0u; pixelOffset < bitCount; pixelOffset += 8) { + result |= (static_cast(*(static_cast(offset) + (pixelOffset / 8))) << pixelOffset); } - else - { - assert(false); - m_write_pixel_func = [](void* offset, uint64_t pixel, unsigned bitCount) - { - }; + + return result; + }; + } else { + assert(false); + m_read_pixel_func = [](const void *offset, unsigned bitCount) { return 0ull; }; + } + break; + } + + switch (outBitCount) { + case 16: + m_write_pixel_func = [](void *offset, const uint64_t pixel, unsigned bitCount) { *static_cast(offset) = static_cast(pixel); }; + break; + + case 32: + m_write_pixel_func = [](void *offset, const uint64_t pixel, unsigned bitCount) { *static_cast(offset) = static_cast(pixel); }; + break; + + case 64: + m_write_pixel_func = [](void *offset, const uint64_t pixel, unsigned bitCount) { *static_cast(offset) = pixel; }; + break; + + default: + if (inBitCount <= 64) { + m_write_pixel_func = [](void *offset, const uint64_t pixel, const unsigned bitCount) { + for (auto pixelOffset = 0u; pixelOffset < bitCount; pixelOffset += 8) { + *(static_cast(offset) + (pixelOffset / 8)) = static_cast(pixel >> pixelOffset); } - break; + }; + } else { + assert(false); + m_write_pixel_func = [](void *offset, uint64_t pixel, unsigned bitCount) {}; } + break; + } } -TextureConverter::TextureConverter(Texture* inputTexture, const ImageFormat* targetFormat) - : m_input_texture(inputTexture), - m_output_texture(nullptr), - m_input_format(inputTexture->GetFormat()), - m_output_format(targetFormat) -{ +TextureConverter::TextureConverter(Texture *inputTexture, const ImageFormat *targetFormat) + : m_input_texture(inputTexture), m_output_texture(nullptr), m_input_format(inputTexture->GetFormat()), m_output_format(targetFormat) {} + +void TextureConverter::CreateOutputTexture() { + switch (m_input_texture->GetTextureType()) { + case TextureType::T_2D: + m_output_texture = new Texture2D(m_output_format, m_input_texture->GetWidth(), m_input_texture->GetHeight(), m_input_texture->HasMipMaps()); + break; + + case TextureType::T_CUBE: + m_output_texture = new TextureCube(m_output_format, m_input_texture->GetWidth(), m_input_texture->GetHeight(), m_input_texture->HasMipMaps()); + break; + + case TextureType::T_3D: + m_output_texture = + new Texture3D(m_output_format, m_input_texture->GetWidth(), m_input_texture->GetHeight(), m_input_texture->GetDepth(), m_input_texture->HasMipMaps()); + break; + default: + assert(false); + break; + } + + m_output_texture->Allocate(); } -void TextureConverter::CreateOutputTexture() -{ - switch (m_input_texture->GetTextureType()) - { - case TextureType::T_2D: - m_output_texture = new Texture2D(m_output_format, m_input_texture->GetWidth(), m_input_texture->GetHeight(), - m_input_texture->HasMipMaps()); - break; - - case TextureType::T_CUBE: - m_output_texture = new TextureCube(m_output_format, m_input_texture->GetWidth(), m_input_texture->GetHeight(), - m_input_texture->HasMipMaps()); - break; - - case TextureType::T_3D: - m_output_texture = new Texture3D(m_output_format, m_input_texture->GetWidth(), m_input_texture->GetHeight(), - m_input_texture->GetDepth(), m_input_texture->HasMipMaps()); - break; - default: - assert(false); - break; +void TextureConverter::ReorderUnsignedToUnsigned() const { + const auto *inputFormat = dynamic_cast(m_input_format); + const auto *outputFormat = dynamic_cast(m_output_format); + const auto mipCount = m_input_texture->HasMipMaps() ? m_input_texture->GetMipMapCount() : 1; + + const auto rInputMask = inputFormat->HasR() ? Mask1(inputFormat->m_r_size) << inputFormat->m_r_offset : 0; + const auto gInputMask = inputFormat->HasG() ? Mask1(inputFormat->m_g_size) << inputFormat->m_g_offset : 0; + const auto bInputMask = inputFormat->HasB() ? Mask1(inputFormat->m_b_size) << inputFormat->m_b_offset : 0; + const auto aInputMask = inputFormat->HasA() ? Mask1(inputFormat->m_a_size) << inputFormat->m_a_offset : 0; + const bool rConvert = rInputMask != 0 && outputFormat->m_r_size > 0; + const bool gConvert = gInputMask != 0 && outputFormat->m_g_size > 0; + const bool bConvert = bInputMask != 0 && outputFormat->m_b_size > 0; + const bool aConvert = aInputMask != 0 && outputFormat->m_a_size > 0; + + for (auto mipLevel = 0; mipLevel < mipCount; mipLevel++) { + const auto mipLevelSize = m_input_texture->GetSizeOfMipLevel(mipLevel) * m_input_texture->GetFaceCount(); + const auto *inputBuffer = m_input_texture->GetBufferForMipLevel(mipLevel); + auto *outputBuffer = m_output_texture->GetBufferForMipLevel(mipLevel); + + const auto inputBytePerPixel = inputFormat->m_bits_per_pixel / 8; + const auto outputBytePerPixel = outputFormat->m_bits_per_pixel / 8; + + auto outputOffset = 0u; + for (auto inputOffset = 0u; inputOffset < mipLevelSize; inputOffset += inputBytePerPixel, outputOffset += outputBytePerPixel) { + uint64_t outPixel = 0; + const auto inPixel = m_read_pixel_func(&inputBuffer[inputOffset], inputFormat->m_bits_per_pixel); + + if (rConvert) + outPixel |= (inPixel & rInputMask) >> inputFormat->m_r_offset << outputFormat->m_r_offset; + if (gConvert) + outPixel |= (inPixel & gInputMask) >> inputFormat->m_g_offset << outputFormat->m_g_offset; + if (bConvert) + outPixel |= (inPixel & bInputMask) >> inputFormat->m_b_offset << outputFormat->m_b_offset; + if (aConvert) + outPixel |= (inPixel & aInputMask) >> inputFormat->m_a_offset << outputFormat->m_a_offset; + + m_write_pixel_func(&outputBuffer[outputOffset], outPixel, outputFormat->m_bits_per_pixel); } - - m_output_texture->Allocate(); + } } -void TextureConverter::ReorderUnsignedToUnsigned() const -{ - const auto* inputFormat = dynamic_cast(m_input_format); - const auto* outputFormat = dynamic_cast(m_output_format); - const auto mipCount = m_input_texture->HasMipMaps() ? m_input_texture->GetMipMapCount() : 1; - - const auto rInputMask = inputFormat->HasR() ? Mask1(inputFormat->m_r_size) << inputFormat->m_r_offset : 0; - const auto gInputMask = inputFormat->HasG() ? Mask1(inputFormat->m_g_size) << inputFormat->m_g_offset : 0; - const auto bInputMask = inputFormat->HasB() ? Mask1(inputFormat->m_b_size) << inputFormat->m_b_offset : 0; - const auto aInputMask = inputFormat->HasA() ? Mask1(inputFormat->m_a_size) << inputFormat->m_a_offset : 0; - const bool rConvert = rInputMask != 0 && outputFormat->m_r_size > 0; - const bool gConvert = gInputMask != 0 && outputFormat->m_g_size > 0; - const bool bConvert = bInputMask != 0 && outputFormat->m_b_size > 0; - const bool aConvert = aInputMask != 0 && outputFormat->m_a_size > 0; - - for (auto mipLevel = 0; mipLevel < mipCount; mipLevel++) - { - const auto mipLevelSize = m_input_texture->GetSizeOfMipLevel(mipLevel) * m_input_texture->GetFaceCount(); - const auto* inputBuffer = m_input_texture->GetBufferForMipLevel(mipLevel); - auto* outputBuffer = m_output_texture->GetBufferForMipLevel(mipLevel); - - const auto inputBytePerPixel = inputFormat->m_bits_per_pixel / 8; - const auto outputBytePerPixel = outputFormat->m_bits_per_pixel / 8; - - auto outputOffset = 0u; - for (auto inputOffset = 0u; inputOffset < mipLevelSize; inputOffset += inputBytePerPixel, outputOffset += - outputBytePerPixel) - { - uint64_t outPixel = 0; - const auto inPixel = m_read_pixel_func(&inputBuffer[inputOffset], inputFormat->m_bits_per_pixel); - - if (rConvert) - outPixel |= (inPixel & rInputMask) >> inputFormat->m_r_offset << outputFormat->m_r_offset; - if (gConvert) - outPixel |= (inPixel & gInputMask) >> inputFormat->m_g_offset << outputFormat->m_g_offset; - if (bConvert) - outPixel |= (inPixel & bInputMask) >> inputFormat->m_b_offset << outputFormat->m_b_offset; - if (aConvert) - outPixel |= (inPixel & aInputMask) >> inputFormat->m_a_offset << outputFormat->m_a_offset; - - m_write_pixel_func(&outputBuffer[outputOffset], outPixel, outputFormat->m_bits_per_pixel); - } - } -} - -void TextureConverter::ConvertUnsignedToUnsigned() -{ - const auto* inputFormat = dynamic_cast(m_input_format); - const auto* outputFormat = dynamic_cast(m_output_format); +void TextureConverter::ConvertUnsignedToUnsigned() { + const auto *inputFormat = dynamic_cast(m_input_format); + const auto *outputFormat = dynamic_cast(m_output_format); - assert(inputFormat->m_bits_per_pixel <= 64); - assert(outputFormat->m_bits_per_pixel <= 64); + assert(inputFormat->m_bits_per_pixel <= 64); + assert(outputFormat->m_bits_per_pixel <= 64); - SetPixelFunctions(inputFormat->m_bits_per_pixel, outputFormat->m_bits_per_pixel); + SetPixelFunctions(inputFormat->m_bits_per_pixel, outputFormat->m_bits_per_pixel); - if (inputFormat->m_r_size == outputFormat->m_r_size - && inputFormat->m_g_size == outputFormat->m_g_size - && inputFormat->m_b_size == outputFormat->m_b_size - && inputFormat->m_a_size == outputFormat->m_a_size) - { - ReorderUnsignedToUnsigned(); - } - else - { - // Unsupported as of now - assert(false); - } + if (inputFormat->m_r_size == outputFormat->m_r_size && inputFormat->m_g_size == outputFormat->m_g_size && inputFormat->m_b_size == outputFormat->m_b_size && + inputFormat->m_a_size == outputFormat->m_a_size) { + ReorderUnsignedToUnsigned(); + } else { + // Unsupported as of now + assert(false); + } } -Texture* TextureConverter::Convert() -{ - CreateOutputTexture(); +Texture *TextureConverter::Convert() { + CreateOutputTexture(); - if (m_input_format->GetType() == ImageFormatType::UNSIGNED - && m_output_format->GetType() == ImageFormatType::UNSIGNED) - { - ConvertUnsignedToUnsigned(); - } - else - { - // Unsupported as of now - assert(false); - } + if (m_input_format->GetType() == ImageFormatType::UNSIGNED && m_output_format->GetType() == ImageFormatType::UNSIGNED) { + ConvertUnsignedToUnsigned(); + } else { + // Unsupported as of now + assert(false); + } - return m_output_texture; + return m_output_texture; } diff --git a/src/Common/Image/TextureConverter.h b/src/Common/Image/TextureConverter.h index b1cacfb92..8d5b3e457 100644 --- a/src/Common/Image/TextureConverter.h +++ b/src/Common/Image/TextureConverter.h @@ -4,27 +4,25 @@ #include "Texture.h" -class TextureConverter -{ - Texture* m_input_texture; - Texture* m_output_texture; - const ImageFormat* m_input_format; - const ImageFormat* m_output_format; +class TextureConverter { + Texture *m_input_texture; + Texture *m_output_texture; + const ImageFormat *m_input_format; + const ImageFormat *m_output_format; - std::function m_read_pixel_func; - std::function m_write_pixel_func; + std::function m_read_pixel_func; + std::function m_write_pixel_func; - static constexpr uint64_t Mask1(unsigned length); - void SetPixelFunctions(unsigned inBitCount, unsigned outBitCount); + static constexpr uint64_t Mask1(unsigned length); + void SetPixelFunctions(unsigned inBitCount, unsigned outBitCount); - void CreateOutputTexture(); + void CreateOutputTexture(); - void ReorderUnsignedToUnsigned() const; - void ConvertUnsignedToUnsigned(); + void ReorderUnsignedToUnsigned() const; + void ConvertUnsignedToUnsigned(); public: + TextureConverter(Texture *inputTexture, const ImageFormat *targetFormat); - TextureConverter(Texture* inputTexture, const ImageFormat* targetFormat); - - Texture* Convert(); + Texture *Convert(); }; \ No newline at end of file diff --git a/src/Common/StateMap/StateMapLayout.cpp b/src/Common/StateMap/StateMapLayout.cpp index fc07b265f..669e80e1d 100644 --- a/src/Common/StateMap/StateMapLayout.cpp +++ b/src/Common/StateMap/StateMapLayout.cpp @@ -5,88 +5,58 @@ using namespace state_map; -namespace state_map -{ +namespace state_map { #ifdef _DEBUG - void ValidateStateMapLayout(const StateMapLayout& layout) - { - // Must have at least one state bits field - assert(layout.m_state_bits_count > 0); - - for (const auto& var : layout.m_var_layout.m_vars) - { - // Cannot exceed state bits fields - assert(var.m_state_bits_index < layout.m_state_bits_count); - - for (auto i = 0u; i < var.m_values.size(); i++) - { - const auto& value = var.m_values[i]; - - // Zero mask values must be last - assert(value.m_state_bits_mask != 0 || i == var.m_values.size() - 1); - } - } - - for (const auto& entry : layout.m_entry_layout.m_entries) - { - // Cannot exceed state bits fields - assert(entry.m_state_bits_index < layout.m_state_bits_count); - - // Has to have a mask for passthrough - assert(entry.m_state_bits_mask != 0); - - for (auto& resultVar : entry.m_result_vars) - { - const auto correspondingVar = std::find_if(layout.m_var_layout.m_vars.begin(), layout.m_var_layout.m_vars.end(), [&resultVar](const StateMapLayoutVar& var) - { - return var.m_name == resultVar; - }); - - // Has to have a corresponding var - assert(correspondingVar != layout.m_var_layout.m_vars.end()); - } - } +void ValidateStateMapLayout(const StateMapLayout &layout) { + // Must have at least one state bits field + assert(layout.m_state_bits_count > 0); + + for (const auto &var : layout.m_var_layout.m_vars) { + // Cannot exceed state bits fields + assert(var.m_state_bits_index < layout.m_state_bits_count); + + for (auto i = 0u; i < var.m_values.size(); i++) { + const auto &value = var.m_values[i]; + + // Zero mask values must be last + assert(value.m_state_bits_mask != 0 || i == var.m_values.size() - 1); } -#endif + } + + for (const auto &entry : layout.m_entry_layout.m_entries) { + // Cannot exceed state bits fields + assert(entry.m_state_bits_index < layout.m_state_bits_count); + + // Has to have a mask for passthrough + assert(entry.m_state_bits_mask != 0); + + for (auto &resultVar : entry.m_result_vars) { + const auto correspondingVar = std::find_if(layout.m_var_layout.m_vars.begin(), layout.m_var_layout.m_vars.end(), + [&resultVar](const StateMapLayoutVar &var) { return var.m_name == resultVar; }); + + // Has to have a corresponding var + assert(correspondingVar != layout.m_var_layout.m_vars.end()); + } + } } +#endif +} // namespace state_map StateMapLayoutEntry::StateMapLayoutEntry(std::string name, const size_t stateBitsIndex, const size_t stateBitsMask, std::vector resultVars) - : m_name(std::move(name)), - m_state_bits_index(stateBitsIndex), - m_state_bits_mask(stateBitsMask), - m_result_vars(std::move(resultVars)) -{ -} + : m_name(std::move(name)), m_state_bits_index(stateBitsIndex), m_state_bits_mask(stateBitsMask), m_result_vars(std::move(resultVars)) {} -StateMapLayoutEntries::StateMapLayoutEntries(std::vector entryList) - : m_entries(std::move(entryList)) -{ -} +StateMapLayoutEntries::StateMapLayoutEntries(std::vector entryList) : m_entries(std::move(entryList)) {} -StateMapLayoutVarValue::StateMapLayoutVarValue(std::string name, const size_t stateBitsMask) - : m_name(std::move(name)), - m_state_bits_mask(stateBitsMask) -{ -} +StateMapLayoutVarValue::StateMapLayoutVarValue(std::string name, const size_t stateBitsMask) : m_name(std::move(name)), m_state_bits_mask(stateBitsMask) {} StateMapLayoutVar::StateMapLayoutVar(std::string name, const size_t stateBitsIndex, std::vector values) - : m_name(std::move(name)), - m_state_bits_index(stateBitsIndex), - m_values(std::move(values)) -{ -} + : m_name(std::move(name)), m_state_bits_index(stateBitsIndex), m_values(std::move(values)) {} -StateMapLayoutVars::StateMapLayoutVars(std::vector varList) - : m_vars(std::move(varList)) -{ -} +StateMapLayoutVars::StateMapLayoutVars(std::vector varList) : m_vars(std::move(varList)) {} -StateMapLayout::StateMapLayout(const size_t stateBitsCount, const StateMapLayoutEntries& entryLayout, const StateMapLayoutVars& varLayout) - : m_state_bits_count(stateBitsCount), - m_entry_layout(entryLayout), - m_var_layout(varLayout) -{ +StateMapLayout::StateMapLayout(const size_t stateBitsCount, const StateMapLayoutEntries &entryLayout, const StateMapLayoutVars &varLayout) + : m_state_bits_count(stateBitsCount), m_entry_layout(entryLayout), m_var_layout(varLayout) { #ifdef _DEBUG - ValidateStateMapLayout(*this); + ValidateStateMapLayout(*this); #endif } diff --git a/src/Common/StateMap/StateMapLayout.h b/src/Common/StateMap/StateMapLayout.h index e68c1492e..b8cd45be7 100644 --- a/src/Common/StateMap/StateMapLayout.h +++ b/src/Common/StateMap/StateMapLayout.h @@ -3,61 +3,54 @@ #include #include -namespace state_map -{ - class StateMapLayoutEntry - { - public: - StateMapLayoutEntry(std::string name, size_t stateBitsIndex, size_t stateBitsMask, std::vector resultVars); - - std::string m_name; - size_t m_state_bits_index; - size_t m_state_bits_mask; - std::vector m_result_vars; - }; - - class StateMapLayoutEntries - { - public: - explicit StateMapLayoutEntries(std::vector entryList); - - std::vector m_entries; - }; - - class StateMapLayoutVarValue - { - public: - StateMapLayoutVarValue(std::string name, size_t stateBitsMask); - - std::string m_name; - size_t m_state_bits_mask; - }; - - class StateMapLayoutVar - { - public: - StateMapLayoutVar(std::string name, size_t stateBitsIndex, std::vector values); - - std::string m_name; - size_t m_state_bits_index; - std::vector m_values; - }; - - class StateMapLayoutVars - { - public: - explicit StateMapLayoutVars(std::vector varList); - - std::vector m_vars; - }; - - class StateMapLayout - { - public: - StateMapLayout(size_t stateBitsCount, const StateMapLayoutEntries& entryLayout, const StateMapLayoutVars& varLayout); - - size_t m_state_bits_count; - const StateMapLayoutEntries& m_entry_layout; - const StateMapLayoutVars& m_var_layout; - }; -} +namespace state_map { +class StateMapLayoutEntry { +public: + StateMapLayoutEntry(std::string name, size_t stateBitsIndex, size_t stateBitsMask, std::vector resultVars); + + std::string m_name; + size_t m_state_bits_index; + size_t m_state_bits_mask; + std::vector m_result_vars; +}; + +class StateMapLayoutEntries { +public: + explicit StateMapLayoutEntries(std::vector entryList); + + std::vector m_entries; +}; + +class StateMapLayoutVarValue { +public: + StateMapLayoutVarValue(std::string name, size_t stateBitsMask); + + std::string m_name; + size_t m_state_bits_mask; +}; + +class StateMapLayoutVar { +public: + StateMapLayoutVar(std::string name, size_t stateBitsIndex, std::vector values); + + std::string m_name; + size_t m_state_bits_index; + std::vector m_values; +}; + +class StateMapLayoutVars { +public: + explicit StateMapLayoutVars(std::vector varList); + + std::vector m_vars; +}; + +class StateMapLayout { +public: + StateMapLayout(size_t stateBitsCount, const StateMapLayoutEntries &entryLayout, const StateMapLayoutVars &varLayout); + + size_t m_state_bits_count; + const StateMapLayoutEntries &m_entry_layout; + const StateMapLayoutVars &m_var_layout; +}; +} // namespace state_map diff --git a/src/Common/Utils/HalfFloat.cpp b/src/Common/Utils/HalfFloat.cpp index 1261b4a61..f2b2b078b 100644 --- a/src/Common/Utils/HalfFloat.cpp +++ b/src/Common/Utils/HalfFloat.cpp @@ -1,24 +1,17 @@ #include "HalfFloat.h" -float HalfFloat::ToFloat(const half_float_t half) -{ - if (half) - { - union - { - uint32_t u; - float f; - } result{}; +float HalfFloat::ToFloat(const half_float_t half) { + if (half) { + union { + uint32_t u; + float f; + } result{}; - result.u = ((half << 16) & 0x80000000) | (((((half << 14) & 0xFFFC000) - - (~(half << 14) & 0x10000000)) ^ 0x80000000) >> 1); - return result.f; - } + result.u = ((half << 16) & 0x80000000) | (((((half << 14) & 0xFFFC000) - (~(half << 14) & 0x10000000)) ^ 0x80000000) >> 1); + return result.f; + } - return 0.0f; + return 0.0f; } -half_float_t HalfFloat::ToHalf(float f) -{ - return 0; -} +half_float_t HalfFloat::ToHalf(float f) { return 0; } diff --git a/src/Common/Utils/HalfFloat.h b/src/Common/Utils/HalfFloat.h index 1729228f8..ed3268879 100644 --- a/src/Common/Utils/HalfFloat.h +++ b/src/Common/Utils/HalfFloat.h @@ -4,11 +4,10 @@ typedef uint16_t half_float_t; -class HalfFloat -{ - HalfFloat() = default; +class HalfFloat { + HalfFloat() = default; public: - static float ToFloat(half_float_t half); - static half_float_t ToHalf(float f); + static float ToFloat(half_float_t half); + static half_float_t ToHalf(float f); }; \ No newline at end of file diff --git a/src/Common/Utils/Pack.cpp b/src/Common/Utils/Pack.cpp index 42f61ca3c..5b35a1647 100644 --- a/src/Common/Utils/Pack.cpp +++ b/src/Common/Utils/Pack.cpp @@ -5,82 +5,68 @@ #include "HalfFloat.h" -union PackUtil32 -{ - uint32_t u; - int32_t i; - float f; - int8_t c[4]; - uint8_t uc[4]; +union PackUtil32 { + uint32_t u; + int32_t i; + float f; + int8_t c[4]; + uint8_t uc[4]; }; -uint32_t Pack32::Vec2PackTexCoords(const float* in) -{ - return static_cast(HalfFloat::ToHalf(in[0])) << 16 - | HalfFloat::ToHalf(in[1]); -} +uint32_t Pack32::Vec2PackTexCoords(const float *in) { return static_cast(HalfFloat::ToHalf(in[0])) << 16 | HalfFloat::ToHalf(in[1]); } -uint32_t Pack32::Vec3PackUnitVec(const float* in) -{ - // TODO - return 0; +uint32_t Pack32::Vec3PackUnitVec(const float *in) { + // TODO + return 0; } -uint32_t Pack32::Vec4PackGfxColor(const float* in) -{ - return static_cast(std::clamp(in[0], 0.0f, 1.0f) * 255.0f) - | static_cast(std::clamp(in[1], 0.0f, 1.0f) * 255.0f) << 8 - | static_cast(std::clamp(in[2], 0.0f, 1.0f) * 255.0f) << 16 - | static_cast(std::clamp(in[3], 0.0f, 1.0f) * 255.0f) << 24; +uint32_t Pack32::Vec4PackGfxColor(const float *in) { + return static_cast(std::clamp(in[0], 0.0f, 1.0f) * 255.0f) | static_cast(std::clamp(in[1], 0.0f, 1.0f) * 255.0f) << 8 | + static_cast(std::clamp(in[2], 0.0f, 1.0f) * 255.0f) << 16 | static_cast(std::clamp(in[3], 0.0f, 1.0f) * 255.0f) << 24; } -void Pack32::Vec2UnpackTexCoordsUV(const uint32_t in, float* out) -{ - const auto inHiDw = static_cast((in >> 16) & UINT16_MAX); - const auto inLoDw = static_cast(in & UINT16_MAX); +void Pack32::Vec2UnpackTexCoordsUV(const uint32_t in, float *out) { + const auto inHiDw = static_cast((in >> 16) & UINT16_MAX); + const auto inLoDw = static_cast(in & UINT16_MAX); - out[0] = HalfFloat::ToFloat(inLoDw); - out[1] = HalfFloat::ToFloat(inHiDw); + out[0] = HalfFloat::ToFloat(inLoDw); + out[1] = HalfFloat::ToFloat(inHiDw); } -void Pack32::Vec2UnpackTexCoordsVU(const uint32_t in, float* out) -{ - const auto inHiDw = static_cast((in >> 16) & UINT16_MAX); - const auto inLoDw = static_cast(in & UINT16_MAX); +void Pack32::Vec2UnpackTexCoordsVU(const uint32_t in, float *out) { + const auto inHiDw = static_cast((in >> 16) & UINT16_MAX); + const auto inLoDw = static_cast(in & UINT16_MAX); - out[0] = HalfFloat::ToFloat(inHiDw); - out[1] = HalfFloat::ToFloat(inLoDw); + out[0] = HalfFloat::ToFloat(inHiDw); + out[1] = HalfFloat::ToFloat(inLoDw); } -void Pack32::Vec3UnpackUnitVecScaleBased(const uint32_t in, float* out) -{ - assert(out != nullptr); +void Pack32::Vec3UnpackUnitVecScaleBased(const uint32_t in, float *out) { + assert(out != nullptr); - PackUtil32 _in{in}; - const float decodeScale = (static_cast(_in.uc[3]) - -192.0f) / 32385.0f; - out[0] = (static_cast(_in.uc[0]) + -127.0f) * decodeScale; - out[1] = (static_cast(_in.uc[1]) + -127.0f) * decodeScale; - out[2] = (static_cast(_in.uc[2]) + -127.0f) * decodeScale; + PackUtil32 _in{in}; + const float decodeScale = (static_cast(_in.uc[3]) - -192.0f) / 32385.0f; + out[0] = (static_cast(_in.uc[0]) + -127.0f) * decodeScale; + out[1] = (static_cast(_in.uc[1]) + -127.0f) * decodeScale; + out[2] = (static_cast(_in.uc[2]) + -127.0f) * decodeScale; } -void Pack32::Vec3UnpackUnitVecThirdBased(const uint32_t in, float* out) -{ - PackUtil32 v0{ (in >> 0) & 0x3FF }; - PackUtil32 v1{ (in >> 10) & 0x3FF }; - PackUtil32 v2{ (in >> 20) & 0x3FF }; +void Pack32::Vec3UnpackUnitVecThirdBased(const uint32_t in, float *out) { + PackUtil32 v0{(in >> 0) & 0x3FF}; + PackUtil32 v1{(in >> 10) & 0x3FF}; + PackUtil32 v2{(in >> 20) & 0x3FF}; - v0.u = v0.u - 2 * (v0.u & 0x200) + 0x40400000; - v1.u = v1.u - 2 * (v1.u & 0x200) + 0x40400000; - v2.u = v2.u - 2 * (v2.u & 0x200) + 0x40400000; - out[0] = (v0.f - 3.0f) * 8208.0312f; - out[1] = (v1.f - 3.0f) * 8208.0312f; - out[2] = (v2.f - 3.0f) * 8208.0312f; + v0.u = v0.u - 2 * (v0.u & 0x200) + 0x40400000; + v1.u = v1.u - 2 * (v1.u & 0x200) + 0x40400000; + v2.u = v2.u - 2 * (v2.u & 0x200) + 0x40400000; + out[0] = (v0.f - 3.0f) * 8208.0312f; + out[1] = (v1.f - 3.0f) * 8208.0312f; + out[2] = (v2.f - 3.0f) * 8208.0312f; } -void Pack32::Vec4UnpackGfxColor(uint32_t in, float* out) -{ - out[0] = static_cast(in & UINT8_MAX) / 255.0f; - out[1] = static_cast((in >> 8) & UINT8_MAX) / 255.0f; - out[2] = static_cast((in >> 16) & UINT8_MAX) / 255.0f; - out[3] = static_cast((in >> 24) & UINT8_MAX) / 255.0f; +void Pack32::Vec4UnpackGfxColor(uint32_t in, float *out) { + out[0] = static_cast(in & UINT8_MAX) / 255.0f; + out[1] = static_cast((in >> 8) & UINT8_MAX) / 255.0f; + out[2] = static_cast((in >> 16) & UINT8_MAX) / 255.0f; + out[3] = static_cast((in >> 24) & UINT8_MAX) / 255.0f; } diff --git a/src/Common/Utils/Pack.h b/src/Common/Utils/Pack.h index 7dc1fdcb3..5a0dbc0cc 100644 --- a/src/Common/Utils/Pack.h +++ b/src/Common/Utils/Pack.h @@ -2,17 +2,16 @@ #include -class Pack32 -{ - Pack32() = default; +class Pack32 { + Pack32() = default; public: - static uint32_t Vec2PackTexCoords(const float* in); - static uint32_t Vec3PackUnitVec(const float* in); - static uint32_t Vec4PackGfxColor(const float* in); - static void Vec2UnpackTexCoordsUV(uint32_t in, float* out); - static void Vec2UnpackTexCoordsVU(uint32_t in, float* out); - static void Vec3UnpackUnitVecScaleBased(uint32_t in, float* out); - static void Vec3UnpackUnitVecThirdBased(uint32_t in, float* out); - static void Vec4UnpackGfxColor(uint32_t in, float* out); + static uint32_t Vec2PackTexCoords(const float *in); + static uint32_t Vec3PackUnitVec(const float *in); + static uint32_t Vec4PackGfxColor(const float *in); + static void Vec2UnpackTexCoordsUV(uint32_t in, float *out); + static void Vec2UnpackTexCoordsVU(uint32_t in, float *out); + static void Vec3UnpackUnitVecScaleBased(uint32_t in, float *out); + static void Vec3UnpackUnitVecThirdBased(uint32_t in, float *out); + static void Vec4UnpackGfxColor(uint32_t in, float *out); }; \ No newline at end of file diff --git a/src/Common/Utils/QuatInt16.cpp b/src/Common/Utils/QuatInt16.cpp index cc0933f23..289bd9853 100644 --- a/src/Common/Utils/QuatInt16.cpp +++ b/src/Common/Utils/QuatInt16.cpp @@ -1,11 +1,5 @@ #include "QuatInt16.h" -quat_int_16 QuatInt16::ToInt16(const float quat) -{ - return static_cast(quat * INT16_MAX); -} +quat_int_16 QuatInt16::ToInt16(const float quat) { return static_cast(quat * INT16_MAX); } -float QuatInt16::ToFloat(const quat_int_16 quat) -{ - return static_cast(quat) / static_cast(INT16_MAX); -} +float QuatInt16::ToFloat(const quat_int_16 quat) { return static_cast(quat) / static_cast(INT16_MAX); } diff --git a/src/Common/Utils/QuatInt16.h b/src/Common/Utils/QuatInt16.h index b2f660fdf..ad8100cb9 100644 --- a/src/Common/Utils/QuatInt16.h +++ b/src/Common/Utils/QuatInt16.h @@ -4,11 +4,10 @@ typedef int16_t quat_int_16; -class QuatInt16 -{ - QuatInt16() = default; +class QuatInt16 { + QuatInt16() = default; public: - static quat_int_16 ToInt16(float quat); - static float ToFloat(quat_int_16 quat); + static quat_int_16 ToInt16(float quat); + static float ToFloat(quat_int_16 quat); }; \ No newline at end of file diff --git a/src/Common/Zone/ZoneTypes.h b/src/Common/Zone/ZoneTypes.h index a52d0f392..305efa4fa 100644 --- a/src/Common/Zone/ZoneTypes.h +++ b/src/Common/Zone/ZoneTypes.h @@ -1,10 +1,9 @@ #pragma once #include -struct ZoneHeader -{ - uint8_t m_magic[8]; - uint32_t m_version; +struct ZoneHeader { + uint8_t m_magic[8]; + uint32_t m_version; }; #ifdef ARCH_x64 diff --git a/src/Crypto/Crypto.cpp b/src/Crypto/Crypto.cpp index 94a3cfb4a..6a66f4254 100644 --- a/src/Crypto/Crypto.cpp +++ b/src/Crypto/Crypto.cpp @@ -1,25 +1,17 @@ #include "Crypto.h" #include "Impl/AlgorithmRSA.h" #include "Impl/AlgorithmSHA1.h" -#include "Impl/AlgorithmSalsa20.h" #include "Impl/AlgorithmSHA256.h" +#include "Impl/AlgorithmSalsa20.h" -std::unique_ptr Crypto::CreateSHA1() -{ - return std::make_unique(); -} +std::unique_ptr Crypto::CreateSHA1() { return std::make_unique(); } -std::unique_ptr Crypto::CreateSHA256() -{ - return std::make_unique(); -} +std::unique_ptr Crypto::CreateSHA256() { return std::make_unique(); } -std::unique_ptr Crypto::CreateSalsa20(const uint8_t* keyBytes, const size_t keySize) -{ - return std::make_unique(keyBytes, keySize); +std::unique_ptr Crypto::CreateSalsa20(const uint8_t *keyBytes, const size_t keySize) { + return std::make_unique(keyBytes, keySize); } -std::unique_ptr Crypto::CreateRSA(const IPublicKeyAlgorithm::HashingAlgorithm hashingAlgorithm, const RSAPaddingMode paddingMode) -{ - return std::make_unique(hashingAlgorithm, paddingMode); +std::unique_ptr Crypto::CreateRSA(const IPublicKeyAlgorithm::HashingAlgorithm hashingAlgorithm, const RSAPaddingMode paddingMode) { + return std::make_unique(hashingAlgorithm, paddingMode); } \ No newline at end of file diff --git a/src/Crypto/Crypto.h b/src/Crypto/Crypto.h index 910f49464..d663de728 100644 --- a/src/Crypto/Crypto.h +++ b/src/Crypto/Crypto.h @@ -3,24 +3,21 @@ #include #include - #include "IHashFunction.h" -#include "IStreamCipher.h" #include "IPublicKeyAlgorithm.h" +#include "IStreamCipher.h" -class Crypto -{ +class Crypto { public: - enum class RSAPaddingMode - { - RSA_PADDING_PKS1, - RSA_PADDING_PSS, - }; + enum class RSAPaddingMode { + RSA_PADDING_PKS1, + RSA_PADDING_PSS, + }; - static std::unique_ptr CreateSHA1(); - static std::unique_ptr CreateSHA256(); + static std::unique_ptr CreateSHA1(); + static std::unique_ptr CreateSHA256(); - static std::unique_ptr CreateSalsa20(const uint8_t* keyBytes, size_t keySize); + static std::unique_ptr CreateSalsa20(const uint8_t *keyBytes, size_t keySize); - static std::unique_ptr CreateRSA(IPublicKeyAlgorithm::HashingAlgorithm hashingAlgorithm, RSAPaddingMode paddingMode); + static std::unique_ptr CreateRSA(IPublicKeyAlgorithm::HashingAlgorithm hashingAlgorithm, RSAPaddingMode paddingMode); }; diff --git a/src/Crypto/IHashFunction.h b/src/Crypto/IHashFunction.h index 81dbec510..0cac3e50f 100644 --- a/src/Crypto/IHashFunction.h +++ b/src/Crypto/IHashFunction.h @@ -2,13 +2,12 @@ #include -class IHashFunction -{ +class IHashFunction { public: - virtual ~IHashFunction() = default; + virtual ~IHashFunction() = default; - virtual size_t GetHashSize() = 0; - virtual void Init() = 0; - virtual void Process(const void* input, size_t inputSize) = 0; - virtual void Finish(void* hashBuffer) = 0; + virtual size_t GetHashSize() = 0; + virtual void Init() = 0; + virtual void Process(const void *input, size_t inputSize) = 0; + virtual void Finish(void *hashBuffer) = 0; }; diff --git a/src/Crypto/IPublicKeyAlgorithm.h b/src/Crypto/IPublicKeyAlgorithm.h index 039697518..b84aaec1a 100644 --- a/src/Crypto/IPublicKeyAlgorithm.h +++ b/src/Crypto/IPublicKeyAlgorithm.h @@ -1,22 +1,17 @@ #pragma once -#include #include +#include -class IPublicKeyAlgorithm -{ +class IPublicKeyAlgorithm { public: - enum class HashingAlgorithm - { - RSA_HASH_SHA256, - RSA_HASH_SHA512 - }; + enum class HashingAlgorithm { RSA_HASH_SHA256, RSA_HASH_SHA512 }; - virtual ~IPublicKeyAlgorithm() = default; + virtual ~IPublicKeyAlgorithm() = default; - virtual bool SetKey(const uint8_t* keyData, size_t keySize) = 0; + virtual bool SetKey(const uint8_t *keyData, size_t keySize) = 0; - // If needed add a signing method + // If needed add a signing method - virtual bool Verify(const uint8_t* signedData, size_t signedDataSize, const uint8_t* signature, size_t signatureSize) = 0; + virtual bool Verify(const uint8_t *signedData, size_t signedDataSize, const uint8_t *signature, size_t signatureSize) = 0; }; diff --git a/src/Crypto/IStreamCipher.h b/src/Crypto/IStreamCipher.h index 75ad103c6..35673761b 100644 --- a/src/Crypto/IStreamCipher.h +++ b/src/Crypto/IStreamCipher.h @@ -1,14 +1,13 @@ #pragma once -#include #include +#include -class IStreamCipher -{ +class IStreamCipher { public: - virtual ~IStreamCipher() = default; + virtual ~IStreamCipher() = default; - virtual void SetIV(const uint8_t* iv, size_t ivSize) = 0; + virtual void SetIV(const uint8_t *iv, size_t ivSize) = 0; - virtual void Process(const void* plainText, void* cipherText, size_t amount) = 0; + virtual void Process(const void *plainText, void *cipherText, size_t amount) = 0; }; diff --git a/src/Crypto/Impl/AlgorithmRSA.cpp b/src/Crypto/Impl/AlgorithmRSA.cpp index c0e84cf12..3e994a047 100644 --- a/src/Crypto/Impl/AlgorithmRSA.cpp +++ b/src/Crypto/Impl/AlgorithmRSA.cpp @@ -3,116 +3,92 @@ #include "CryptoLibrary.h" -class AlgorithmRSA::AlgorithmRSAImpl -{ - rsa_key m_key{}; - HashingAlgorithm m_hash; - Crypto::RSAPaddingMode m_padding; - - const ltc_hash_descriptor* GetHashDescriptor() const - { - switch(m_hash) - { - case HashingAlgorithm::RSA_HASH_SHA256: - return &sha256_desc; - - default: - case HashingAlgorithm::RSA_HASH_SHA512: - return &sha512_desc; - } +class AlgorithmRSA::AlgorithmRSAImpl { + rsa_key m_key{}; + HashingAlgorithm m_hash; + Crypto::RSAPaddingMode m_padding; + + const ltc_hash_descriptor *GetHashDescriptor() const { + switch (m_hash) { + case HashingAlgorithm::RSA_HASH_SHA256: + return &sha256_desc; + + default: + case HashingAlgorithm::RSA_HASH_SHA512: + return &sha512_desc; } + } - int GetPaddingMode() const - { - switch(m_padding) - { - case Crypto::RSAPaddingMode::RSA_PADDING_PKS1: - return LTC_PKCS_1_V1_5; - - default: - case Crypto::RSAPaddingMode::RSA_PADDING_PSS: - return LTC_PKCS_1_PSS; - } + int GetPaddingMode() const { + switch (m_padding) { + case Crypto::RSAPaddingMode::RSA_PADDING_PKS1: + return LTC_PKCS_1_V1_5; + + default: + case Crypto::RSAPaddingMode::RSA_PADDING_PSS: + return LTC_PKCS_1_PSS; } + } public: - AlgorithmRSAImpl(const HashingAlgorithm hash, const Crypto::RSAPaddingMode padding) - { - m_hash = hash; - m_padding = padding; + AlgorithmRSAImpl(const HashingAlgorithm hash, const Crypto::RSAPaddingMode padding) { + m_hash = hash; + m_padding = padding; - CryptoLibrary::Init(); - } + CryptoLibrary::Init(); + } - ~AlgorithmRSAImpl() = default; + ~AlgorithmRSAImpl() = default; - AlgorithmRSAImpl(AlgorithmRSAImpl& other) = default; - AlgorithmRSAImpl(AlgorithmRSAImpl&& other) = delete; + AlgorithmRSAImpl(AlgorithmRSAImpl &other) = default; + AlgorithmRSAImpl(AlgorithmRSAImpl &&other) = delete; - AlgorithmRSAImpl& operator=(AlgorithmRSAImpl const& other) = default; - AlgorithmRSAImpl& operator=(AlgorithmRSAImpl&& other) = delete; + AlgorithmRSAImpl &operator=(AlgorithmRSAImpl const &other) = default; + AlgorithmRSAImpl &operator=(AlgorithmRSAImpl &&other) = delete; - bool SetKey(const uint8_t* keyData, const size_t keySize) - { - return rsa_import(keyData, keySize, &m_key) == CRYPT_OK; - } - - bool Verify(const uint8_t* signedData, const size_t signedDataSize, const uint8_t* signature, const size_t signatureSize) - { - const ltc_hash_descriptor* hashDesc = GetHashDescriptor(); - const int hashId = register_hash(hashDesc); - const int padding = GetPaddingMode(); + bool SetKey(const uint8_t *keyData, const size_t keySize) { return rsa_import(keyData, keySize, &m_key) == CRYPT_OK; } - int result; - rsa_verify_hash_ex(signature, signatureSize, signedData, signedDataSize, padding, hashId, 8, &result, &m_key); + bool Verify(const uint8_t *signedData, const size_t signedDataSize, const uint8_t *signature, const size_t signatureSize) { + const ltc_hash_descriptor *hashDesc = GetHashDescriptor(); + const int hashId = register_hash(hashDesc); + const int padding = GetPaddingMode(); - return result == 1; - } + int result; + rsa_verify_hash_ex(signature, signatureSize, signedData, signedDataSize, padding, hashId, 8, &result, &m_key); + + return result == 1; + } }; -AlgorithmRSA::AlgorithmRSA(const HashingAlgorithm hash, const Crypto::RSAPaddingMode padding) -{ - m_impl = new AlgorithmRSAImpl(hash, padding); -} +AlgorithmRSA::AlgorithmRSA(const HashingAlgorithm hash, const Crypto::RSAPaddingMode padding) { m_impl = new AlgorithmRSAImpl(hash, padding); } -AlgorithmRSA::~AlgorithmRSA() -{ - delete m_impl; - m_impl = nullptr; +AlgorithmRSA::~AlgorithmRSA() { + delete m_impl; + m_impl = nullptr; } -AlgorithmRSA::AlgorithmRSA(AlgorithmRSA& other) -{ - m_impl = new AlgorithmRSAImpl(*other.m_impl); -} +AlgorithmRSA::AlgorithmRSA(AlgorithmRSA &other) { m_impl = new AlgorithmRSAImpl(*other.m_impl); } -AlgorithmRSA::AlgorithmRSA(AlgorithmRSA&& other) noexcept -{ - m_impl = other.m_impl; - other.m_impl = nullptr; +AlgorithmRSA::AlgorithmRSA(AlgorithmRSA &&other) noexcept { + m_impl = other.m_impl; + other.m_impl = nullptr; } -AlgorithmRSA& AlgorithmRSA::operator=(AlgorithmRSA const& other) -{ - m_impl = new AlgorithmRSAImpl(*other.m_impl); +AlgorithmRSA &AlgorithmRSA::operator=(AlgorithmRSA const &other) { + m_impl = new AlgorithmRSAImpl(*other.m_impl); - return *this; + return *this; } -AlgorithmRSA& AlgorithmRSA::operator=(AlgorithmRSA&& other) noexcept -{ - m_impl = other.m_impl; - other.m_impl = nullptr; +AlgorithmRSA &AlgorithmRSA::operator=(AlgorithmRSA &&other) noexcept { + m_impl = other.m_impl; + other.m_impl = nullptr; - return *this; + return *this; } -bool AlgorithmRSA::SetKey(const uint8_t* keyData, size_t keySize) -{ - return m_impl->SetKey(keyData, keySize); -} +bool AlgorithmRSA::SetKey(const uint8_t *keyData, size_t keySize) { return m_impl->SetKey(keyData, keySize); } -bool AlgorithmRSA::Verify(const uint8_t* signedData, const size_t signedDataSize, const uint8_t* signature, const size_t signatureSize) -{ - return m_impl->Verify(signedData, signedDataSize, signature, signatureSize); +bool AlgorithmRSA::Verify(const uint8_t *signedData, const size_t signedDataSize, const uint8_t *signature, const size_t signatureSize) { + return m_impl->Verify(signedData, signedDataSize, signature, signatureSize); } \ No newline at end of file diff --git a/src/Crypto/Impl/AlgorithmRSA.h b/src/Crypto/Impl/AlgorithmRSA.h index eb3c7d86d..99e9a0dbf 100644 --- a/src/Crypto/Impl/AlgorithmRSA.h +++ b/src/Crypto/Impl/AlgorithmRSA.h @@ -1,24 +1,23 @@ #pragma once -#include "IPublicKeyAlgorithm.h" #include "Crypto.h" +#include "IPublicKeyAlgorithm.h" #include -class AlgorithmRSA final : public IPublicKeyAlgorithm -{ - class AlgorithmRSAImpl; - AlgorithmRSAImpl* m_impl; +class AlgorithmRSA final : public IPublicKeyAlgorithm { + class AlgorithmRSAImpl; + AlgorithmRSAImpl *m_impl; public: - AlgorithmRSA(HashingAlgorithm hash, Crypto::RSAPaddingMode padding); - ~AlgorithmRSA() override; + AlgorithmRSA(HashingAlgorithm hash, Crypto::RSAPaddingMode padding); + ~AlgorithmRSA() override; - AlgorithmRSA(AlgorithmRSA& other); - AlgorithmRSA(AlgorithmRSA&& other) noexcept; + AlgorithmRSA(AlgorithmRSA &other); + AlgorithmRSA(AlgorithmRSA &&other) noexcept; - AlgorithmRSA& operator=(AlgorithmRSA const& other); - AlgorithmRSA& operator=(AlgorithmRSA&& other) noexcept; + AlgorithmRSA &operator=(AlgorithmRSA const &other); + AlgorithmRSA &operator=(AlgorithmRSA &&other) noexcept; - bool SetKey(const uint8_t* keyData, size_t keySize) override; + bool SetKey(const uint8_t *keyData, size_t keySize) override; - bool Verify(const uint8_t* signedData, size_t signedDataSize, const uint8_t* signature, size_t signatureSize) override; + bool Verify(const uint8_t *signedData, size_t signedDataSize, const uint8_t *signature, size_t signatureSize) override; }; diff --git a/src/Crypto/Impl/AlgorithmSHA1.cpp b/src/Crypto/Impl/AlgorithmSHA1.cpp index 881345fd9..ce1a72fae 100644 --- a/src/Crypto/Impl/AlgorithmSHA1.cpp +++ b/src/Crypto/Impl/AlgorithmSHA1.cpp @@ -3,61 +3,34 @@ #include "CryptoLibrary.h" #include -class AlgorithmSHA1::AlgorithmSHA1Impl -{ - hash_state m_state{}; +class AlgorithmSHA1::AlgorithmSHA1Impl { + hash_state m_state{}; public: - AlgorithmSHA1Impl() - { - CryptoLibrary::Init(); - - Init(); - } - - void Init() - { - sha1_init(&m_state); - } - - void Process(const void* input, const size_t inputSize) - { - sha1_process(&m_state, static_cast(input), inputSize); - } - - void Finish(void* hashBuffer) - { - sha1_done(&m_state, static_cast(hashBuffer)); - } + AlgorithmSHA1Impl() { + CryptoLibrary::Init(); + + Init(); + } + + void Init() { sha1_init(&m_state); } + + void Process(const void *input, const size_t inputSize) { sha1_process(&m_state, static_cast(input), inputSize); } + + void Finish(void *hashBuffer) { sha1_done(&m_state, static_cast(hashBuffer)); } }; -AlgorithmSHA1::AlgorithmSHA1() -{ - m_impl = new AlgorithmSHA1Impl(); -} +AlgorithmSHA1::AlgorithmSHA1() { m_impl = new AlgorithmSHA1Impl(); } -AlgorithmSHA1::~AlgorithmSHA1() -{ - delete m_impl; - m_impl = nullptr; +AlgorithmSHA1::~AlgorithmSHA1() { + delete m_impl; + m_impl = nullptr; } -size_t AlgorithmSHA1::GetHashSize() -{ - return HASH_SIZE; -} +size_t AlgorithmSHA1::GetHashSize() { return HASH_SIZE; } -void AlgorithmSHA1::Init() -{ - m_impl->Init(); -} +void AlgorithmSHA1::Init() { m_impl->Init(); } -void AlgorithmSHA1::Process(const void* input, const size_t inputSize) -{ - m_impl->Process(input, inputSize); -} +void AlgorithmSHA1::Process(const void *input, const size_t inputSize) { m_impl->Process(input, inputSize); } -void AlgorithmSHA1::Finish(void* hashBuffer) -{ - m_impl->Finish(hashBuffer); -} \ No newline at end of file +void AlgorithmSHA1::Finish(void *hashBuffer) { m_impl->Finish(hashBuffer); } \ No newline at end of file diff --git a/src/Crypto/Impl/AlgorithmSHA1.h b/src/Crypto/Impl/AlgorithmSHA1.h index f9ae05143..cf5707225 100644 --- a/src/Crypto/Impl/AlgorithmSHA1.h +++ b/src/Crypto/Impl/AlgorithmSHA1.h @@ -1,20 +1,19 @@ #pragma once #include "IHashFunction.h" -class AlgorithmSHA1 : public IHashFunction -{ - class AlgorithmSHA1Impl; - AlgorithmSHA1Impl* m_impl; +class AlgorithmSHA1 : public IHashFunction { + class AlgorithmSHA1Impl; + AlgorithmSHA1Impl *m_impl; public: - static const int HASH_SIZE = 20; + static const int HASH_SIZE = 20; - AlgorithmSHA1(); - ~AlgorithmSHA1() override; + AlgorithmSHA1(); + ~AlgorithmSHA1() override; - size_t GetHashSize() override; + size_t GetHashSize() override; - void Init() override; - void Process(const void* input, size_t inputSize) override; - void Finish(void* hashBuffer) override; + void Init() override; + void Process(const void *input, size_t inputSize) override; + void Finish(void *hashBuffer) override; }; diff --git a/src/Crypto/Impl/AlgorithmSHA256.cpp b/src/Crypto/Impl/AlgorithmSHA256.cpp index 7de8948b2..92989f2bf 100644 --- a/src/Crypto/Impl/AlgorithmSHA256.cpp +++ b/src/Crypto/Impl/AlgorithmSHA256.cpp @@ -3,61 +3,34 @@ #include "CryptoLibrary.h" #include -class AlgorithmSHA256::Impl -{ - hash_state m_state{}; +class AlgorithmSHA256::Impl { + hash_state m_state{}; public: - Impl() - { - CryptoLibrary::Init(); - - Init(); - } - - void Init() - { - sha256_init(&m_state); - } - - void Process(const void* input, const size_t inputSize) - { - sha256_process(&m_state, static_cast(input), inputSize); - } - - void Finish(void* hashBuffer) - { - sha256_done(&m_state, static_cast(hashBuffer)); - } + Impl() { + CryptoLibrary::Init(); + + Init(); + } + + void Init() { sha256_init(&m_state); } + + void Process(const void *input, const size_t inputSize) { sha256_process(&m_state, static_cast(input), inputSize); } + + void Finish(void *hashBuffer) { sha256_done(&m_state, static_cast(hashBuffer)); } }; -AlgorithmSHA256::AlgorithmSHA256() -{ - m_impl = new Impl(); -} +AlgorithmSHA256::AlgorithmSHA256() { m_impl = new Impl(); } -AlgorithmSHA256::~AlgorithmSHA256() -{ - delete m_impl; - m_impl = nullptr; +AlgorithmSHA256::~AlgorithmSHA256() { + delete m_impl; + m_impl = nullptr; } -size_t AlgorithmSHA256::GetHashSize() -{ - return HASH_SIZE; -} +size_t AlgorithmSHA256::GetHashSize() { return HASH_SIZE; } -void AlgorithmSHA256::Init() -{ - m_impl->Init(); -} +void AlgorithmSHA256::Init() { m_impl->Init(); } -void AlgorithmSHA256::Process(const void* input, const size_t inputSize) -{ - m_impl->Process(input, inputSize); -} +void AlgorithmSHA256::Process(const void *input, const size_t inputSize) { m_impl->Process(input, inputSize); } -void AlgorithmSHA256::Finish(void* hashBuffer) -{ - m_impl->Finish(hashBuffer); -} \ No newline at end of file +void AlgorithmSHA256::Finish(void *hashBuffer) { m_impl->Finish(hashBuffer); } \ No newline at end of file diff --git a/src/Crypto/Impl/AlgorithmSHA256.h b/src/Crypto/Impl/AlgorithmSHA256.h index 54875a2a6..6d97cefc9 100644 --- a/src/Crypto/Impl/AlgorithmSHA256.h +++ b/src/Crypto/Impl/AlgorithmSHA256.h @@ -1,20 +1,19 @@ #pragma once #include "IHashFunction.h" -class AlgorithmSHA256 : public IHashFunction -{ - class Impl; - Impl* m_impl; +class AlgorithmSHA256 : public IHashFunction { + class Impl; + Impl *m_impl; public: - static const int HASH_SIZE = 32; + static const int HASH_SIZE = 32; - AlgorithmSHA256(); - ~AlgorithmSHA256() override; + AlgorithmSHA256(); + ~AlgorithmSHA256() override; - size_t GetHashSize() override; + size_t GetHashSize() override; - void Init() override; - void Process(const void* input, size_t inputSize) override; - void Finish(void* hashBuffer) override; + void Init() override; + void Process(const void *input, size_t inputSize) override; + void Finish(void *hashBuffer) override; }; diff --git a/src/Crypto/Impl/AlgorithmSalsa20.cpp b/src/Crypto/Impl/AlgorithmSalsa20.cpp index 4b2869b78..67516f114 100644 --- a/src/Crypto/Impl/AlgorithmSalsa20.cpp +++ b/src/Crypto/Impl/AlgorithmSalsa20.cpp @@ -3,85 +3,62 @@ #include #include -class AlgorithmSalsa20::AlgorithmSalsa20Impl -{ - salsa20_ctx m_context{}; +class AlgorithmSalsa20::AlgorithmSalsa20Impl { + salsa20_ctx m_context{}; public: - AlgorithmSalsa20Impl(const uint8_t* keyBytes, const size_t keySize) - { - Salsa20_KeySetup(&m_context, keyBytes, keySize * 8); - } - - ~AlgorithmSalsa20Impl() = default; + AlgorithmSalsa20Impl(const uint8_t *keyBytes, const size_t keySize) { Salsa20_KeySetup(&m_context, keyBytes, keySize * 8); } - AlgorithmSalsa20Impl(AlgorithmSalsa20Impl& other) = default; - AlgorithmSalsa20Impl(AlgorithmSalsa20Impl&& other) = delete; + ~AlgorithmSalsa20Impl() = default; - AlgorithmSalsa20Impl& operator=(AlgorithmSalsa20Impl const& other) = default; - AlgorithmSalsa20Impl& operator=(AlgorithmSalsa20Impl&& other) = delete; + AlgorithmSalsa20Impl(AlgorithmSalsa20Impl &other) = default; + AlgorithmSalsa20Impl(AlgorithmSalsa20Impl &&other) = delete; - void SetIV(const uint8_t* iv, const size_t ivSize) - { - assert(ivSize == 8); + AlgorithmSalsa20Impl &operator=(AlgorithmSalsa20Impl const &other) = default; + AlgorithmSalsa20Impl &operator=(AlgorithmSalsa20Impl &&other) = delete; - if(ivSize != 8) - { - throw std::invalid_argument("Salsa20 IV size must be 8"); - } + void SetIV(const uint8_t *iv, const size_t ivSize) { + assert(ivSize == 8); - Salsa20_IVSetup(&m_context, iv); + if (ivSize != 8) { + throw std::invalid_argument("Salsa20 IV size must be 8"); } - void Process(const void* plainText, void* cipherText, const size_t amount) - { - Salsa20_Encrypt_Bytes(&m_context, static_cast(plainText), static_cast(cipherText), amount); - } + Salsa20_IVSetup(&m_context, iv); + } + + void Process(const void *plainText, void *cipherText, const size_t amount) { + Salsa20_Encrypt_Bytes(&m_context, static_cast(plainText), static_cast(cipherText), amount); + } }; -AlgorithmSalsa20::AlgorithmSalsa20(const uint8_t* keyBytes, const size_t keySize) -{ - m_impl = new AlgorithmSalsa20Impl(keyBytes, keySize); -} +AlgorithmSalsa20::AlgorithmSalsa20(const uint8_t *keyBytes, const size_t keySize) { m_impl = new AlgorithmSalsa20Impl(keyBytes, keySize); } -AlgorithmSalsa20::~AlgorithmSalsa20() -{ - delete m_impl; - m_impl = nullptr; +AlgorithmSalsa20::~AlgorithmSalsa20() { + delete m_impl; + m_impl = nullptr; } -AlgorithmSalsa20::AlgorithmSalsa20(AlgorithmSalsa20& other) -{ - m_impl = new AlgorithmSalsa20Impl(*other.m_impl); -} +AlgorithmSalsa20::AlgorithmSalsa20(AlgorithmSalsa20 &other) { m_impl = new AlgorithmSalsa20Impl(*other.m_impl); } -AlgorithmSalsa20::AlgorithmSalsa20(AlgorithmSalsa20&& other) noexcept -{ - m_impl = other.m_impl; - other.m_impl = nullptr; +AlgorithmSalsa20::AlgorithmSalsa20(AlgorithmSalsa20 &&other) noexcept { + m_impl = other.m_impl; + other.m_impl = nullptr; } -AlgorithmSalsa20& AlgorithmSalsa20::operator=(AlgorithmSalsa20 const& other) -{ - m_impl = new AlgorithmSalsa20Impl(*other.m_impl); +AlgorithmSalsa20 &AlgorithmSalsa20::operator=(AlgorithmSalsa20 const &other) { + m_impl = new AlgorithmSalsa20Impl(*other.m_impl); - return *this; + return *this; } -AlgorithmSalsa20& AlgorithmSalsa20::operator=(AlgorithmSalsa20&& other) noexcept -{ - m_impl = other.m_impl; - other.m_impl = nullptr; +AlgorithmSalsa20 &AlgorithmSalsa20::operator=(AlgorithmSalsa20 &&other) noexcept { + m_impl = other.m_impl; + other.m_impl = nullptr; - return *this; + return *this; } -void AlgorithmSalsa20::SetIV(const uint8_t* iv, const size_t ivSize) -{ - m_impl->SetIV(iv, ivSize); -} +void AlgorithmSalsa20::SetIV(const uint8_t *iv, const size_t ivSize) { m_impl->SetIV(iv, ivSize); } -void AlgorithmSalsa20::Process(const void* plainText, void* cipherText, const size_t amount) -{ - m_impl->Process(plainText, cipherText, amount); -} +void AlgorithmSalsa20::Process(const void *plainText, void *cipherText, const size_t amount) { m_impl->Process(plainText, cipherText, amount); } diff --git a/src/Crypto/Impl/AlgorithmSalsa20.h b/src/Crypto/Impl/AlgorithmSalsa20.h index 88c0d6cac..6b682da98 100644 --- a/src/Crypto/Impl/AlgorithmSalsa20.h +++ b/src/Crypto/Impl/AlgorithmSalsa20.h @@ -1,21 +1,20 @@ #pragma once #include "IStreamCipher.h" -class AlgorithmSalsa20 final : public IStreamCipher -{ - class AlgorithmSalsa20Impl; - AlgorithmSalsa20Impl* m_impl; +class AlgorithmSalsa20 final : public IStreamCipher { + class AlgorithmSalsa20Impl; + AlgorithmSalsa20Impl *m_impl; public: - AlgorithmSalsa20(const uint8_t* keyBytes, size_t keySize); - ~AlgorithmSalsa20() override; + AlgorithmSalsa20(const uint8_t *keyBytes, size_t keySize); + ~AlgorithmSalsa20() override; - AlgorithmSalsa20(AlgorithmSalsa20& other); - AlgorithmSalsa20(AlgorithmSalsa20&& other) noexcept; + AlgorithmSalsa20(AlgorithmSalsa20 &other); + AlgorithmSalsa20(AlgorithmSalsa20 &&other) noexcept; - AlgorithmSalsa20& operator=(AlgorithmSalsa20 const& other); - AlgorithmSalsa20& operator=(AlgorithmSalsa20&& other) noexcept; + AlgorithmSalsa20 &operator=(AlgorithmSalsa20 const &other); + AlgorithmSalsa20 &operator=(AlgorithmSalsa20 &&other) noexcept; - void SetIV(const uint8_t* iv, size_t ivSize) override; - void Process(const void* plainText, void* cipherText, size_t amount) override; + void SetIV(const uint8_t *iv, size_t ivSize) override; + void Process(const void *plainText, void *cipherText, size_t amount) override; }; diff --git a/src/Crypto/Impl/CryptoLibrary.cpp b/src/Crypto/Impl/CryptoLibrary.cpp index 698467dab..fa12ebe61 100644 --- a/src/Crypto/Impl/CryptoLibrary.cpp +++ b/src/Crypto/Impl/CryptoLibrary.cpp @@ -1,14 +1,12 @@ #include "CryptoLibrary.h" #include "tommath.h" -void CryptoLibrary::Init() -{ - static bool initialized = false; +void CryptoLibrary::Init() { + static bool initialized = false; - if (!initialized) - { - initialized = true; + if (!initialized) { + initialized = true; - ltc_mp = ltm_desc; - } + ltc_mp = ltm_desc; + } } \ No newline at end of file diff --git a/src/Crypto/Impl/CryptoLibrary.h b/src/Crypto/Impl/CryptoLibrary.h index c1d0da627..06bf57b5a 100644 --- a/src/Crypto/Impl/CryptoLibrary.h +++ b/src/Crypto/Impl/CryptoLibrary.h @@ -3,8 +3,7 @@ #define LTC_NO_PROTOTYPES #include "tomcrypt.h" -class CryptoLibrary -{ +class CryptoLibrary { public: - static void Init(); + static void Init(); }; \ No newline at end of file diff --git a/src/Linker/Game/IW3/ZoneCreatorIW3.cpp b/src/Linker/Game/IW3/ZoneCreatorIW3.cpp index 23d230c2b..5f48f5032 100644 --- a/src/Linker/Game/IW3/ZoneCreatorIW3.cpp +++ b/src/Linker/Game/IW3/ZoneCreatorIW3.cpp @@ -2,97 +2,80 @@ #include -#include "ObjLoading.h" #include "AssetLoading/AssetLoadingContext.h" -#include "Game/IW3/GameIW3.h" #include "Game/IW3/GameAssetPoolIW3.h" +#include "Game/IW3/GameIW3.h" +#include "ObjLoading.h" using namespace IW3; -ZoneCreator::ZoneCreator() -{ - for (auto assetType = 0; assetType < ASSET_TYPE_COUNT; assetType++) - { - AddAssetTypeName(assetType, GameAssetPoolIW3::AssetTypeNameByType(assetType)); - } +ZoneCreator::ZoneCreator() { + for (auto assetType = 0; assetType < ASSET_TYPE_COUNT; assetType++) { + AddAssetTypeName(assetType, GameAssetPoolIW3::AssetTypeNameByType(assetType)); + } } -void ZoneCreator::AddAssetTypeName(asset_type_t assetType, std::string name) -{ - m_asset_types_by_name.emplace(std::make_pair(std::move(name), assetType)); -} +void ZoneCreator::AddAssetTypeName(asset_type_t assetType, std::string name) { m_asset_types_by_name.emplace(std::make_pair(std::move(name), assetType)); } -std::vector ZoneCreator::CreateGdtList(ZoneCreationContext& context) -{ - std::vector gdtList; - gdtList.reserve(context.m_gdt_files.size()); - for (const auto& gdt : context.m_gdt_files) - gdtList.push_back(gdt.get()); +std::vector ZoneCreator::CreateGdtList(ZoneCreationContext &context) { + std::vector gdtList; + gdtList.reserve(context.m_gdt_files.size()); + for (const auto &gdt : context.m_gdt_files) + gdtList.push_back(gdt.get()); - return gdtList; + return gdtList; } -bool ZoneCreator::CreateIgnoredAssetMap(ZoneCreationContext& context, std::unordered_map& ignoredAssetMap) const -{ - for (const auto& ignoreEntry : context.m_ignored_assets) - { - const auto foundAssetTypeEntry = m_asset_types_by_name.find(ignoreEntry.m_type); - if (foundAssetTypeEntry == m_asset_types_by_name.end()) - { - std::cout << "Unknown asset type \"" << ignoreEntry.m_type << "\" for ignore \"" << ignoreEntry.m_name << "\"" << std::endl; - return false; - } - - ignoredAssetMap[ignoreEntry.m_name] = foundAssetTypeEntry->second; +bool ZoneCreator::CreateIgnoredAssetMap(ZoneCreationContext &context, std::unordered_map &ignoredAssetMap) const { + for (const auto &ignoreEntry : context.m_ignored_assets) { + const auto foundAssetTypeEntry = m_asset_types_by_name.find(ignoreEntry.m_type); + if (foundAssetTypeEntry == m_asset_types_by_name.end()) { + std::cout << "Unknown asset type \"" << ignoreEntry.m_type << "\" for ignore \"" << ignoreEntry.m_name << "\"" << std::endl; + return false; } - return true; + ignoredAssetMap[ignoreEntry.m_name] = foundAssetTypeEntry->second; + } + + return true; } -void ZoneCreator::CreateZoneAssetPools(Zone* zone) const -{ - zone->m_pools = std::make_unique(zone, zone->m_priority); +void ZoneCreator::CreateZoneAssetPools(Zone *zone) const { + zone->m_pools = std::make_unique(zone, zone->m_priority); - for (auto assetType = 0; assetType < ASSET_TYPE_COUNT; assetType++) - zone->m_pools->InitPoolDynamic(assetType); + for (auto assetType = 0; assetType < ASSET_TYPE_COUNT; assetType++) + zone->m_pools->InitPoolDynamic(assetType); } -bool ZoneCreator::SupportsGame(const std::string& gameName) const -{ - return gameName == g_GameIW3.GetShortName(); -} +bool ZoneCreator::SupportsGame(const std::string &gameName) const { return gameName == g_GameIW3.GetShortName(); } -std::unique_ptr ZoneCreator::CreateZoneForDefinition(ZoneCreationContext& context) const -{ - auto zone = std::make_unique(context.m_definition->m_name, 0, &g_GameIW3); - CreateZoneAssetPools(zone.get()); +std::unique_ptr ZoneCreator::CreateZoneForDefinition(ZoneCreationContext &context) const { + auto zone = std::make_unique(context.m_definition->m_name, 0, &g_GameIW3); + CreateZoneAssetPools(zone.get()); - for (const auto& assetEntry : context.m_definition->m_assets) - { - if (!assetEntry.m_is_reference) - continue; + for (const auto &assetEntry : context.m_definition->m_assets) { + if (!assetEntry.m_is_reference) + continue; - context.m_ignored_assets.emplace_back(assetEntry.m_asset_type, assetEntry.m_asset_name); - } + context.m_ignored_assets.emplace_back(assetEntry.m_asset_type, assetEntry.m_asset_name); + } - const auto assetLoadingContext = std::make_unique(zone.get(), context.m_asset_search_path, CreateGdtList(context)); - if (!CreateIgnoredAssetMap(context, assetLoadingContext->m_ignored_asset_map)) - return nullptr; - - for (const auto& assetEntry : context.m_definition->m_assets) - { - const auto foundAssetTypeEntry = m_asset_types_by_name.find(assetEntry.m_asset_type); - if (foundAssetTypeEntry == m_asset_types_by_name.end()) - { - std::cout << "Unknown asset type \"" << assetEntry.m_asset_type << "\"" << std::endl; - return nullptr; - } - - if (!ObjLoading::LoadAssetForZone(assetLoadingContext.get(), foundAssetTypeEntry->second, assetEntry.m_asset_name)) - return nullptr; + const auto assetLoadingContext = std::make_unique(zone.get(), context.m_asset_search_path, CreateGdtList(context)); + if (!CreateIgnoredAssetMap(context, assetLoadingContext->m_ignored_asset_map)) + return nullptr; + + for (const auto &assetEntry : context.m_definition->m_assets) { + const auto foundAssetTypeEntry = m_asset_types_by_name.find(assetEntry.m_asset_type); + if (foundAssetTypeEntry == m_asset_types_by_name.end()) { + std::cout << "Unknown asset type \"" << assetEntry.m_asset_type << "\"" << std::endl; + return nullptr; } - ObjLoading::FinalizeAssetsForZone(assetLoadingContext.get()); + if (!ObjLoading::LoadAssetForZone(assetLoadingContext.get(), foundAssetTypeEntry->second, assetEntry.m_asset_name)) + return nullptr; + } + + ObjLoading::FinalizeAssetsForZone(assetLoadingContext.get()); - return zone; + return zone; } diff --git a/src/Linker/Game/IW3/ZoneCreatorIW3.h b/src/Linker/Game/IW3/ZoneCreatorIW3.h index 37c772629..6383f74c2 100644 --- a/src/Linker/Game/IW3/ZoneCreatorIW3.h +++ b/src/Linker/Game/IW3/ZoneCreatorIW3.h @@ -1,25 +1,23 @@ #pragma once -#include #include +#include #include "Zone/ZoneTypes.h" #include "ZoneCreation/IZoneCreator.h" -namespace IW3 -{ - class ZoneCreator final : public IZoneCreator - { - std::unordered_map m_asset_types_by_name; +namespace IW3 { +class ZoneCreator final : public IZoneCreator { + std::unordered_map m_asset_types_by_name; - void AddAssetTypeName(asset_type_t assetType, std::string name); - static std::vector CreateGdtList(ZoneCreationContext& context); - bool CreateIgnoredAssetMap(ZoneCreationContext& context, std::unordered_map& ignoredAssetMap) const; - void CreateZoneAssetPools(Zone* zone) const; + void AddAssetTypeName(asset_type_t assetType, std::string name); + static std::vector CreateGdtList(ZoneCreationContext &context); + bool CreateIgnoredAssetMap(ZoneCreationContext &context, std::unordered_map &ignoredAssetMap) const; + void CreateZoneAssetPools(Zone *zone) const; - public: - ZoneCreator(); +public: + ZoneCreator(); - _NODISCARD bool SupportsGame(const std::string& gameName) const override; - _NODISCARD std::unique_ptr CreateZoneForDefinition(ZoneCreationContext& context) const override; - }; -} + _NODISCARD bool SupportsGame(const std::string &gameName) const override; + _NODISCARD std::unique_ptr CreateZoneForDefinition(ZoneCreationContext &context) const override; +}; +} // namespace IW3 diff --git a/src/Linker/Game/IW4/ZoneCreatorIW4.cpp b/src/Linker/Game/IW4/ZoneCreatorIW4.cpp index 3f1751684..c1d88ce9a 100644 --- a/src/Linker/Game/IW4/ZoneCreatorIW4.cpp +++ b/src/Linker/Game/IW4/ZoneCreatorIW4.cpp @@ -2,96 +2,79 @@ #include -#include "ObjLoading.h" -#include "Game/IW4/GameIW4.h" #include "Game/IW4/GameAssetPoolIW4.h" +#include "Game/IW4/GameIW4.h" +#include "ObjLoading.h" using namespace IW4; -ZoneCreator::ZoneCreator() -{ - for (auto assetType = 0; assetType < ASSET_TYPE_COUNT; assetType++) - { - AddAssetTypeName(assetType, GameAssetPoolIW4::AssetTypeNameByType(assetType)); - } +ZoneCreator::ZoneCreator() { + for (auto assetType = 0; assetType < ASSET_TYPE_COUNT; assetType++) { + AddAssetTypeName(assetType, GameAssetPoolIW4::AssetTypeNameByType(assetType)); + } } -void ZoneCreator::AddAssetTypeName(asset_type_t assetType, std::string name) -{ - m_asset_types_by_name.emplace(std::make_pair(std::move(name), assetType)); -} +void ZoneCreator::AddAssetTypeName(asset_type_t assetType, std::string name) { m_asset_types_by_name.emplace(std::make_pair(std::move(name), assetType)); } -std::vector ZoneCreator::CreateGdtList(ZoneCreationContext& context) -{ - std::vector gdtList; - gdtList.reserve(context.m_gdt_files.size()); - for (const auto& gdt : context.m_gdt_files) - gdtList.push_back(gdt.get()); +std::vector ZoneCreator::CreateGdtList(ZoneCreationContext &context) { + std::vector gdtList; + gdtList.reserve(context.m_gdt_files.size()); + for (const auto &gdt : context.m_gdt_files) + gdtList.push_back(gdt.get()); - return gdtList; + return gdtList; } -bool ZoneCreator::CreateIgnoredAssetMap(ZoneCreationContext& context, std::unordered_map& ignoredAssetMap) const -{ - for (const auto& ignoreEntry : context.m_ignored_assets) - { - const auto foundAssetTypeEntry = m_asset_types_by_name.find(ignoreEntry.m_type); - if (foundAssetTypeEntry == m_asset_types_by_name.end()) - { - std::cout << "Unknown asset type \"" << ignoreEntry.m_type << "\" for ignore \"" << ignoreEntry.m_name << "\"" << std::endl; - return false; - } - - ignoredAssetMap[ignoreEntry.m_name] = foundAssetTypeEntry->second; +bool ZoneCreator::CreateIgnoredAssetMap(ZoneCreationContext &context, std::unordered_map &ignoredAssetMap) const { + for (const auto &ignoreEntry : context.m_ignored_assets) { + const auto foundAssetTypeEntry = m_asset_types_by_name.find(ignoreEntry.m_type); + if (foundAssetTypeEntry == m_asset_types_by_name.end()) { + std::cout << "Unknown asset type \"" << ignoreEntry.m_type << "\" for ignore \"" << ignoreEntry.m_name << "\"" << std::endl; + return false; } - return true; + ignoredAssetMap[ignoreEntry.m_name] = foundAssetTypeEntry->second; + } + + return true; } -void ZoneCreator::CreateZoneAssetPools(Zone* zone) const -{ - zone->m_pools = std::make_unique(zone, zone->m_priority); +void ZoneCreator::CreateZoneAssetPools(Zone *zone) const { + zone->m_pools = std::make_unique(zone, zone->m_priority); - for (auto assetType = 0; assetType < ASSET_TYPE_COUNT; assetType++) - zone->m_pools->InitPoolDynamic(assetType); + for (auto assetType = 0; assetType < ASSET_TYPE_COUNT; assetType++) + zone->m_pools->InitPoolDynamic(assetType); } -bool ZoneCreator::SupportsGame(const std::string& gameName) const -{ - return gameName == g_GameIW4.GetShortName(); -} +bool ZoneCreator::SupportsGame(const std::string &gameName) const { return gameName == g_GameIW4.GetShortName(); } -std::unique_ptr ZoneCreator::CreateZoneForDefinition(ZoneCreationContext& context) const -{ - auto zone = std::make_unique(context.m_definition->m_name, 0, &g_GameIW4); - CreateZoneAssetPools(zone.get()); +std::unique_ptr ZoneCreator::CreateZoneForDefinition(ZoneCreationContext &context) const { + auto zone = std::make_unique(context.m_definition->m_name, 0, &g_GameIW4); + CreateZoneAssetPools(zone.get()); - for (const auto& assetEntry : context.m_definition->m_assets) - { - if (!assetEntry.m_is_reference) - continue; + for (const auto &assetEntry : context.m_definition->m_assets) { + if (!assetEntry.m_is_reference) + continue; - context.m_ignored_assets.emplace_back(assetEntry.m_asset_type, assetEntry.m_asset_name); - } + context.m_ignored_assets.emplace_back(assetEntry.m_asset_type, assetEntry.m_asset_name); + } - const auto assetLoadingContext = std::make_unique(zone.get(), context.m_asset_search_path, CreateGdtList(context)); - if (!CreateIgnoredAssetMap(context, assetLoadingContext->m_ignored_asset_map)) - return nullptr; - - for (const auto& assetEntry : context.m_definition->m_assets) - { - const auto foundAssetTypeEntry = m_asset_types_by_name.find(assetEntry.m_asset_type); - if (foundAssetTypeEntry == m_asset_types_by_name.end()) - { - std::cout << "Unknown asset type \"" << assetEntry.m_asset_type << "\"" << std::endl; - return nullptr; - } - - if (!ObjLoading::LoadAssetForZone(assetLoadingContext.get(), foundAssetTypeEntry->second, assetEntry.m_asset_name)) - return nullptr; + const auto assetLoadingContext = std::make_unique(zone.get(), context.m_asset_search_path, CreateGdtList(context)); + if (!CreateIgnoredAssetMap(context, assetLoadingContext->m_ignored_asset_map)) + return nullptr; + + for (const auto &assetEntry : context.m_definition->m_assets) { + const auto foundAssetTypeEntry = m_asset_types_by_name.find(assetEntry.m_asset_type); + if (foundAssetTypeEntry == m_asset_types_by_name.end()) { + std::cout << "Unknown asset type \"" << assetEntry.m_asset_type << "\"" << std::endl; + return nullptr; } - ObjLoading::FinalizeAssetsForZone(assetLoadingContext.get()); + if (!ObjLoading::LoadAssetForZone(assetLoadingContext.get(), foundAssetTypeEntry->second, assetEntry.m_asset_name)) + return nullptr; + } + + ObjLoading::FinalizeAssetsForZone(assetLoadingContext.get()); - return zone; + return zone; } diff --git a/src/Linker/Game/IW4/ZoneCreatorIW4.h b/src/Linker/Game/IW4/ZoneCreatorIW4.h index 2906af3df..0ce0ed0ac 100644 --- a/src/Linker/Game/IW4/ZoneCreatorIW4.h +++ b/src/Linker/Game/IW4/ZoneCreatorIW4.h @@ -1,25 +1,23 @@ #pragma once -#include #include +#include #include "Zone/ZoneTypes.h" #include "ZoneCreation/IZoneCreator.h" -namespace IW4 -{ - class ZoneCreator final : public IZoneCreator - { - std::unordered_map m_asset_types_by_name; +namespace IW4 { +class ZoneCreator final : public IZoneCreator { + std::unordered_map m_asset_types_by_name; - void AddAssetTypeName(asset_type_t assetType, std::string name); - static std::vector CreateGdtList(ZoneCreationContext& context); - bool CreateIgnoredAssetMap(ZoneCreationContext& context, std::unordered_map& ignoredAssetMap) const; - void CreateZoneAssetPools(Zone* zone) const; + void AddAssetTypeName(asset_type_t assetType, std::string name); + static std::vector CreateGdtList(ZoneCreationContext &context); + bool CreateIgnoredAssetMap(ZoneCreationContext &context, std::unordered_map &ignoredAssetMap) const; + void CreateZoneAssetPools(Zone *zone) const; - public: - ZoneCreator(); +public: + ZoneCreator(); - _NODISCARD bool SupportsGame(const std::string& gameName) const override; - _NODISCARD std::unique_ptr CreateZoneForDefinition(ZoneCreationContext& context) const override; - }; -} + _NODISCARD bool SupportsGame(const std::string &gameName) const override; + _NODISCARD std::unique_ptr CreateZoneForDefinition(ZoneCreationContext &context) const override; +}; +} // namespace IW4 diff --git a/src/Linker/Game/IW5/ZoneCreatorIW5.cpp b/src/Linker/Game/IW5/ZoneCreatorIW5.cpp index 9a1b1ac24..9e95a333a 100644 --- a/src/Linker/Game/IW5/ZoneCreatorIW5.cpp +++ b/src/Linker/Game/IW5/ZoneCreatorIW5.cpp @@ -2,96 +2,79 @@ #include -#include "ObjLoading.h" -#include "Game/IW5/GameIW5.h" #include "Game/IW5/GameAssetPoolIW5.h" +#include "Game/IW5/GameIW5.h" +#include "ObjLoading.h" using namespace IW5; -ZoneCreator::ZoneCreator() -{ - for (auto assetType = 0; assetType < ASSET_TYPE_COUNT; assetType++) - { - AddAssetTypeName(assetType, GameAssetPoolIW5::AssetTypeNameByType(assetType)); - } +ZoneCreator::ZoneCreator() { + for (auto assetType = 0; assetType < ASSET_TYPE_COUNT; assetType++) { + AddAssetTypeName(assetType, GameAssetPoolIW5::AssetTypeNameByType(assetType)); + } } -void ZoneCreator::AddAssetTypeName(asset_type_t assetType, std::string name) -{ - m_asset_types_by_name.emplace(std::make_pair(std::move(name), assetType)); -} +void ZoneCreator::AddAssetTypeName(asset_type_t assetType, std::string name) { m_asset_types_by_name.emplace(std::make_pair(std::move(name), assetType)); } -std::vector ZoneCreator::CreateGdtList(ZoneCreationContext& context) -{ - std::vector gdtList; - gdtList.reserve(context.m_gdt_files.size()); - for (const auto& gdt : context.m_gdt_files) - gdtList.push_back(gdt.get()); +std::vector ZoneCreator::CreateGdtList(ZoneCreationContext &context) { + std::vector gdtList; + gdtList.reserve(context.m_gdt_files.size()); + for (const auto &gdt : context.m_gdt_files) + gdtList.push_back(gdt.get()); - return gdtList; + return gdtList; } -bool ZoneCreator::CreateIgnoredAssetMap(ZoneCreationContext& context, std::unordered_map& ignoredAssetMap) const -{ - for (const auto& ignoreEntry : context.m_ignored_assets) - { - const auto foundAssetTypeEntry = m_asset_types_by_name.find(ignoreEntry.m_type); - if (foundAssetTypeEntry == m_asset_types_by_name.end()) - { - std::cout << "Unknown asset type \"" << ignoreEntry.m_type << "\" for ignore \"" << ignoreEntry.m_name << "\"" << std::endl; - return false; - } - - ignoredAssetMap[ignoreEntry.m_name] = foundAssetTypeEntry->second; +bool ZoneCreator::CreateIgnoredAssetMap(ZoneCreationContext &context, std::unordered_map &ignoredAssetMap) const { + for (const auto &ignoreEntry : context.m_ignored_assets) { + const auto foundAssetTypeEntry = m_asset_types_by_name.find(ignoreEntry.m_type); + if (foundAssetTypeEntry == m_asset_types_by_name.end()) { + std::cout << "Unknown asset type \"" << ignoreEntry.m_type << "\" for ignore \"" << ignoreEntry.m_name << "\"" << std::endl; + return false; } - return true; + ignoredAssetMap[ignoreEntry.m_name] = foundAssetTypeEntry->second; + } + + return true; } -void ZoneCreator::CreateZoneAssetPools(Zone* zone) const -{ - zone->m_pools = std::make_unique(zone, zone->m_priority); +void ZoneCreator::CreateZoneAssetPools(Zone *zone) const { + zone->m_pools = std::make_unique(zone, zone->m_priority); - for (auto assetType = 0; assetType < ASSET_TYPE_COUNT; assetType++) - zone->m_pools->InitPoolDynamic(assetType); + for (auto assetType = 0; assetType < ASSET_TYPE_COUNT; assetType++) + zone->m_pools->InitPoolDynamic(assetType); } -bool ZoneCreator::SupportsGame(const std::string& gameName) const -{ - return gameName == g_GameIW5.GetShortName(); -} +bool ZoneCreator::SupportsGame(const std::string &gameName) const { return gameName == g_GameIW5.GetShortName(); } -std::unique_ptr ZoneCreator::CreateZoneForDefinition(ZoneCreationContext& context) const -{ - auto zone = std::make_unique(context.m_definition->m_name, 0, &g_GameIW5); - CreateZoneAssetPools(zone.get()); +std::unique_ptr ZoneCreator::CreateZoneForDefinition(ZoneCreationContext &context) const { + auto zone = std::make_unique(context.m_definition->m_name, 0, &g_GameIW5); + CreateZoneAssetPools(zone.get()); - for (const auto& assetEntry : context.m_definition->m_assets) - { - if (!assetEntry.m_is_reference) - continue; + for (const auto &assetEntry : context.m_definition->m_assets) { + if (!assetEntry.m_is_reference) + continue; - context.m_ignored_assets.emplace_back(assetEntry.m_asset_type, assetEntry.m_asset_name); - } + context.m_ignored_assets.emplace_back(assetEntry.m_asset_type, assetEntry.m_asset_name); + } - const auto assetLoadingContext = std::make_unique(zone.get(), context.m_asset_search_path, CreateGdtList(context)); - if (!CreateIgnoredAssetMap(context, assetLoadingContext->m_ignored_asset_map)) - return nullptr; - - for (const auto& assetEntry : context.m_definition->m_assets) - { - const auto foundAssetTypeEntry = m_asset_types_by_name.find(assetEntry.m_asset_type); - if (foundAssetTypeEntry == m_asset_types_by_name.end()) - { - std::cout << "Unknown asset type \"" << assetEntry.m_asset_type << "\"" << std::endl; - return nullptr; - } - - if (!ObjLoading::LoadAssetForZone(assetLoadingContext.get(), foundAssetTypeEntry->second, assetEntry.m_asset_name)) - return nullptr; + const auto assetLoadingContext = std::make_unique(zone.get(), context.m_asset_search_path, CreateGdtList(context)); + if (!CreateIgnoredAssetMap(context, assetLoadingContext->m_ignored_asset_map)) + return nullptr; + + for (const auto &assetEntry : context.m_definition->m_assets) { + const auto foundAssetTypeEntry = m_asset_types_by_name.find(assetEntry.m_asset_type); + if (foundAssetTypeEntry == m_asset_types_by_name.end()) { + std::cout << "Unknown asset type \"" << assetEntry.m_asset_type << "\"" << std::endl; + return nullptr; } - ObjLoading::FinalizeAssetsForZone(assetLoadingContext.get()); + if (!ObjLoading::LoadAssetForZone(assetLoadingContext.get(), foundAssetTypeEntry->second, assetEntry.m_asset_name)) + return nullptr; + } + + ObjLoading::FinalizeAssetsForZone(assetLoadingContext.get()); - return zone; + return zone; } diff --git a/src/Linker/Game/IW5/ZoneCreatorIW5.h b/src/Linker/Game/IW5/ZoneCreatorIW5.h index 7584ebfc5..ed3ebc692 100644 --- a/src/Linker/Game/IW5/ZoneCreatorIW5.h +++ b/src/Linker/Game/IW5/ZoneCreatorIW5.h @@ -1,25 +1,23 @@ #pragma once -#include #include +#include #include "Zone/ZoneTypes.h" #include "ZoneCreation/IZoneCreator.h" -namespace IW5 -{ - class ZoneCreator final : public IZoneCreator - { - std::unordered_map m_asset_types_by_name; +namespace IW5 { +class ZoneCreator final : public IZoneCreator { + std::unordered_map m_asset_types_by_name; - void AddAssetTypeName(asset_type_t assetType, std::string name); - static std::vector CreateGdtList(ZoneCreationContext& context); - bool CreateIgnoredAssetMap(ZoneCreationContext& context, std::unordered_map& ignoredAssetMap) const; - void CreateZoneAssetPools(Zone* zone) const; + void AddAssetTypeName(asset_type_t assetType, std::string name); + static std::vector CreateGdtList(ZoneCreationContext &context); + bool CreateIgnoredAssetMap(ZoneCreationContext &context, std::unordered_map &ignoredAssetMap) const; + void CreateZoneAssetPools(Zone *zone) const; - public: - ZoneCreator(); +public: + ZoneCreator(); - _NODISCARD bool SupportsGame(const std::string& gameName) const override; - _NODISCARD std::unique_ptr CreateZoneForDefinition(ZoneCreationContext& context) const override; - }; -} + _NODISCARD bool SupportsGame(const std::string &gameName) const override; + _NODISCARD std::unique_ptr CreateZoneForDefinition(ZoneCreationContext &context) const override; +}; +} // namespace IW5 diff --git a/src/Linker/Game/T5/ZoneCreatorT5.cpp b/src/Linker/Game/T5/ZoneCreatorT5.cpp index 7bd314781..55309ac6c 100644 --- a/src/Linker/Game/T5/ZoneCreatorT5.cpp +++ b/src/Linker/Game/T5/ZoneCreatorT5.cpp @@ -2,97 +2,80 @@ #include -#include "ObjLoading.h" #include "AssetLoading/AssetLoadingContext.h" -#include "Game/T5/GameT5.h" #include "Game/T5/GameAssetPoolT5.h" +#include "Game/T5/GameT5.h" +#include "ObjLoading.h" using namespace T5; -ZoneCreator::ZoneCreator() -{ - for (auto assetType = 0; assetType < ASSET_TYPE_COUNT; assetType++) - { - AddAssetTypeName(assetType, GameAssetPoolT5::AssetTypeNameByType(assetType)); - } +ZoneCreator::ZoneCreator() { + for (auto assetType = 0; assetType < ASSET_TYPE_COUNT; assetType++) { + AddAssetTypeName(assetType, GameAssetPoolT5::AssetTypeNameByType(assetType)); + } } -void ZoneCreator::AddAssetTypeName(asset_type_t assetType, std::string name) -{ - m_asset_types_by_name.emplace(std::make_pair(std::move(name), assetType)); -} +void ZoneCreator::AddAssetTypeName(asset_type_t assetType, std::string name) { m_asset_types_by_name.emplace(std::make_pair(std::move(name), assetType)); } -std::vector ZoneCreator::CreateGdtList(ZoneCreationContext& context) -{ - std::vector gdtList; - gdtList.reserve(context.m_gdt_files.size()); - for (const auto& gdt : context.m_gdt_files) - gdtList.push_back(gdt.get()); +std::vector ZoneCreator::CreateGdtList(ZoneCreationContext &context) { + std::vector gdtList; + gdtList.reserve(context.m_gdt_files.size()); + for (const auto &gdt : context.m_gdt_files) + gdtList.push_back(gdt.get()); - return gdtList; + return gdtList; } -bool ZoneCreator::CreateIgnoredAssetMap(ZoneCreationContext& context, std::unordered_map& ignoredAssetMap) const -{ - for (const auto& ignoreEntry : context.m_ignored_assets) - { - const auto foundAssetTypeEntry = m_asset_types_by_name.find(ignoreEntry.m_type); - if (foundAssetTypeEntry == m_asset_types_by_name.end()) - { - std::cout << "Unknown asset type \"" << ignoreEntry.m_type << "\" for ignore \"" << ignoreEntry.m_name << "\"" << std::endl; - return false; - } - - ignoredAssetMap[ignoreEntry.m_name] = foundAssetTypeEntry->second; +bool ZoneCreator::CreateIgnoredAssetMap(ZoneCreationContext &context, std::unordered_map &ignoredAssetMap) const { + for (const auto &ignoreEntry : context.m_ignored_assets) { + const auto foundAssetTypeEntry = m_asset_types_by_name.find(ignoreEntry.m_type); + if (foundAssetTypeEntry == m_asset_types_by_name.end()) { + std::cout << "Unknown asset type \"" << ignoreEntry.m_type << "\" for ignore \"" << ignoreEntry.m_name << "\"" << std::endl; + return false; } - return true; + ignoredAssetMap[ignoreEntry.m_name] = foundAssetTypeEntry->second; + } + + return true; } -void ZoneCreator::CreateZoneAssetPools(Zone* zone) const -{ - zone->m_pools = std::make_unique(zone, zone->m_priority); +void ZoneCreator::CreateZoneAssetPools(Zone *zone) const { + zone->m_pools = std::make_unique(zone, zone->m_priority); - for (auto assetType = 0; assetType < ASSET_TYPE_COUNT; assetType++) - zone->m_pools->InitPoolDynamic(assetType); + for (auto assetType = 0; assetType < ASSET_TYPE_COUNT; assetType++) + zone->m_pools->InitPoolDynamic(assetType); } -bool ZoneCreator::SupportsGame(const std::string& gameName) const -{ - return gameName == g_GameT5.GetShortName(); -} +bool ZoneCreator::SupportsGame(const std::string &gameName) const { return gameName == g_GameT5.GetShortName(); } -std::unique_ptr ZoneCreator::CreateZoneForDefinition(ZoneCreationContext& context) const -{ - auto zone = std::make_unique(context.m_definition->m_name, 0, &g_GameT5); - CreateZoneAssetPools(zone.get()); +std::unique_ptr ZoneCreator::CreateZoneForDefinition(ZoneCreationContext &context) const { + auto zone = std::make_unique(context.m_definition->m_name, 0, &g_GameT5); + CreateZoneAssetPools(zone.get()); - for (const auto& assetEntry : context.m_definition->m_assets) - { - if (!assetEntry.m_is_reference) - continue; + for (const auto &assetEntry : context.m_definition->m_assets) { + if (!assetEntry.m_is_reference) + continue; - context.m_ignored_assets.emplace_back(assetEntry.m_asset_type, assetEntry.m_asset_name); - } + context.m_ignored_assets.emplace_back(assetEntry.m_asset_type, assetEntry.m_asset_name); + } - const auto assetLoadingContext = std::make_unique(zone.get(), context.m_asset_search_path, CreateGdtList(context)); - if (!CreateIgnoredAssetMap(context, assetLoadingContext->m_ignored_asset_map)) - return nullptr; - - for (const auto& assetEntry : context.m_definition->m_assets) - { - const auto foundAssetTypeEntry = m_asset_types_by_name.find(assetEntry.m_asset_type); - if (foundAssetTypeEntry == m_asset_types_by_name.end()) - { - std::cout << "Unknown asset type \"" << assetEntry.m_asset_type << "\"" << std::endl; - return nullptr; - } - - if (!ObjLoading::LoadAssetForZone(assetLoadingContext.get(), foundAssetTypeEntry->second, assetEntry.m_asset_name)) - return nullptr; + const auto assetLoadingContext = std::make_unique(zone.get(), context.m_asset_search_path, CreateGdtList(context)); + if (!CreateIgnoredAssetMap(context, assetLoadingContext->m_ignored_asset_map)) + return nullptr; + + for (const auto &assetEntry : context.m_definition->m_assets) { + const auto foundAssetTypeEntry = m_asset_types_by_name.find(assetEntry.m_asset_type); + if (foundAssetTypeEntry == m_asset_types_by_name.end()) { + std::cout << "Unknown asset type \"" << assetEntry.m_asset_type << "\"" << std::endl; + return nullptr; } - ObjLoading::FinalizeAssetsForZone(assetLoadingContext.get()); + if (!ObjLoading::LoadAssetForZone(assetLoadingContext.get(), foundAssetTypeEntry->second, assetEntry.m_asset_name)) + return nullptr; + } + + ObjLoading::FinalizeAssetsForZone(assetLoadingContext.get()); - return zone; + return zone; } diff --git a/src/Linker/Game/T5/ZoneCreatorT5.h b/src/Linker/Game/T5/ZoneCreatorT5.h index 0c6760194..ee2c480da 100644 --- a/src/Linker/Game/T5/ZoneCreatorT5.h +++ b/src/Linker/Game/T5/ZoneCreatorT5.h @@ -1,25 +1,23 @@ #pragma once -#include #include +#include #include "Zone/ZoneTypes.h" #include "ZoneCreation/IZoneCreator.h" -namespace T5 -{ - class ZoneCreator final : public IZoneCreator - { - std::unordered_map m_asset_types_by_name; +namespace T5 { +class ZoneCreator final : public IZoneCreator { + std::unordered_map m_asset_types_by_name; - void AddAssetTypeName(asset_type_t assetType, std::string name); - static std::vector CreateGdtList(ZoneCreationContext& context); - bool CreateIgnoredAssetMap(ZoneCreationContext& context, std::unordered_map& ignoredAssetMap) const; - void CreateZoneAssetPools(Zone* zone) const; + void AddAssetTypeName(asset_type_t assetType, std::string name); + static std::vector CreateGdtList(ZoneCreationContext &context); + bool CreateIgnoredAssetMap(ZoneCreationContext &context, std::unordered_map &ignoredAssetMap) const; + void CreateZoneAssetPools(Zone *zone) const; - public: - ZoneCreator(); +public: + ZoneCreator(); - _NODISCARD bool SupportsGame(const std::string& gameName) const override; - _NODISCARD std::unique_ptr CreateZoneForDefinition(ZoneCreationContext& context) const override; - }; -} + _NODISCARD bool SupportsGame(const std::string &gameName) const override; + _NODISCARD std::unique_ptr CreateZoneForDefinition(ZoneCreationContext &context) const override; +}; +} // namespace T5 diff --git a/src/Linker/Game/T6/ZoneCreatorT6.cpp b/src/Linker/Game/T6/ZoneCreatorT6.cpp index 90f5f14d8..3f266fa97 100644 --- a/src/Linker/Game/T6/ZoneCreatorT6.cpp +++ b/src/Linker/Game/T6/ZoneCreatorT6.cpp @@ -2,153 +2,123 @@ #include -#include "ObjLoading.h" #include "Game/T6/CommonT6.h" -#include "Game/T6/T6.h" -#include "Game/T6/GameT6.h" #include "Game/T6/GameAssetPoolT6.h" +#include "Game/T6/GameT6.h" +#include "Game/T6/T6.h" +#include "ObjLoading.h" using namespace T6; -ZoneCreator::ZoneCreator() -{ - for (auto assetType = 0; assetType < ASSET_TYPE_COUNT; assetType++) - { - AddAssetTypeName(assetType, GameAssetPoolT6::AssetTypeNameByType(assetType)); - } +ZoneCreator::ZoneCreator() { + for (auto assetType = 0; assetType < ASSET_TYPE_COUNT; assetType++) { + AddAssetTypeName(assetType, GameAssetPoolT6::AssetTypeNameByType(assetType)); + } } -void ZoneCreator::AddAssetTypeName(asset_type_t assetType, std::string name) -{ - m_asset_types_by_name.emplace(std::make_pair(std::move(name), assetType)); -} +void ZoneCreator::AddAssetTypeName(asset_type_t assetType, std::string name) { m_asset_types_by_name.emplace(std::make_pair(std::move(name), assetType)); } -std::vector ZoneCreator::CreateGdtList(ZoneCreationContext& context) -{ - std::vector gdtList; - gdtList.reserve(context.m_gdt_files.size()); - for (const auto& gdt : context.m_gdt_files) - gdtList.push_back(gdt.get()); +std::vector ZoneCreator::CreateGdtList(ZoneCreationContext &context) { + std::vector gdtList; + gdtList.reserve(context.m_gdt_files.size()); + for (const auto &gdt : context.m_gdt_files) + gdtList.push_back(gdt.get()); - return gdtList; + return gdtList; } -bool ZoneCreator::CreateIgnoredAssetMap(ZoneCreationContext& context, std::unordered_map& ignoredAssetMap) const -{ - for (const auto& ignoreEntry : context.m_ignored_assets) - { - const auto foundAssetTypeEntry = m_asset_types_by_name.find(ignoreEntry.m_type); - if (foundAssetTypeEntry == m_asset_types_by_name.end()) - { - std::cout << "Unknown asset type \"" << ignoreEntry.m_type << "\" for ignore \"" << ignoreEntry.m_name << "\"" << std::endl; - return false; - } - - ignoredAssetMap[ignoreEntry.m_name] = foundAssetTypeEntry->second; +bool ZoneCreator::CreateIgnoredAssetMap(ZoneCreationContext &context, std::unordered_map &ignoredAssetMap) const { + for (const auto &ignoreEntry : context.m_ignored_assets) { + const auto foundAssetTypeEntry = m_asset_types_by_name.find(ignoreEntry.m_type); + if (foundAssetTypeEntry == m_asset_types_by_name.end()) { + std::cout << "Unknown asset type \"" << ignoreEntry.m_type << "\" for ignore \"" << ignoreEntry.m_name << "\"" << std::endl; + return false; } - return true; + ignoredAssetMap[ignoreEntry.m_name] = foundAssetTypeEntry->second; + } + + return true; } -void ZoneCreator::CreateZoneAssetPools(Zone* zone) const -{ - zone->m_pools = std::make_unique(zone, zone->m_priority); +void ZoneCreator::CreateZoneAssetPools(Zone *zone) const { + zone->m_pools = std::make_unique(zone, zone->m_priority); - for (auto assetType = 0; assetType < ASSET_TYPE_COUNT; assetType++) - zone->m_pools->InitPoolDynamic(assetType); + for (auto assetType = 0; assetType < ASSET_TYPE_COUNT; assetType++) + zone->m_pools->InitPoolDynamic(assetType); } -void ZoneCreator::HandleMetadata(Zone* zone, ZoneCreationContext& context) const -{ - std::vector kvpList; - - for (const auto& metaData : context.m_definition->m_metadata) - { - if (metaData->m_key.rfind("level.", 0) == 0) - { - const std::string strValue = metaData->m_key.substr(std::char_traits::length("level.")); - if (strValue.empty()) - continue; - - int keyHash; - if (strValue[0] == '@') - { - char* endPtr; - keyHash = strtol(&strValue[1], &endPtr, 16); - - if (endPtr != &strValue[strValue.size()]) - { - std::cout << "Could not parse metadata key \"" << metaData->m_key << "\" as hash" << std::endl; - continue; - } - } - else - { - keyHash = Common::Com_HashKey(strValue.c_str(), 64); - } - - KeyValuePair kvp - { - keyHash, - Common::Com_HashKey(zone->m_name.c_str(), 64), - zone->GetMemory()->Dup(metaData->m_value.c_str()) - }; - kvpList.push_back(kvp); - } - } +void ZoneCreator::HandleMetadata(Zone *zone, ZoneCreationContext &context) const { + std::vector kvpList; - if (!kvpList.empty()) - { - auto* kvps = zone->GetMemory()->Create(); - kvps->name = zone->GetMemory()->Dup(zone->m_name.c_str()); - kvps->numVariables = kvpList.size(); - kvps->keyValuePairs = static_cast(zone->GetMemory()->Alloc(sizeof(KeyValuePair) * kvpList.size())); + for (const auto &metaData : context.m_definition->m_metadata) { + if (metaData->m_key.rfind("level.", 0) == 0) { + const std::string strValue = metaData->m_key.substr(std::char_traits::length("level.")); + if (strValue.empty()) + continue; - for (auto i = 0u; i < kvpList.size(); i++) - kvps->keyValuePairs[i] = kvpList[i]; + int keyHash; + if (strValue[0] == '@') { + char *endPtr; + keyHash = strtol(&strValue[1], &endPtr, 16); - zone->m_pools->AddAsset(ASSET_TYPE_KEYVALUEPAIRS, zone->m_name, kvps, std::vector(), std::vector()); + if (endPtr != &strValue[strValue.size()]) { + std::cout << "Could not parse metadata key \"" << metaData->m_key << "\" as hash" << std::endl; + continue; + } + } else { + keyHash = Common::Com_HashKey(strValue.c_str(), 64); + } + + KeyValuePair kvp{keyHash, Common::Com_HashKey(zone->m_name.c_str(), 64), zone->GetMemory()->Dup(metaData->m_value.c_str())}; + kvpList.push_back(kvp); } -} + } -bool ZoneCreator::SupportsGame(const std::string& gameName) const -{ - return gameName == g_GameT6.GetShortName(); + if (!kvpList.empty()) { + auto *kvps = zone->GetMemory()->Create(); + kvps->name = zone->GetMemory()->Dup(zone->m_name.c_str()); + kvps->numVariables = kvpList.size(); + kvps->keyValuePairs = static_cast(zone->GetMemory()->Alloc(sizeof(KeyValuePair) * kvpList.size())); + + for (auto i = 0u; i < kvpList.size(); i++) + kvps->keyValuePairs[i] = kvpList[i]; + + zone->m_pools->AddAsset(ASSET_TYPE_KEYVALUEPAIRS, zone->m_name, kvps, std::vector(), std::vector()); + } } -std::unique_ptr ZoneCreator::CreateZoneForDefinition(ZoneCreationContext& context) const -{ - auto zone = std::make_unique(context.m_definition->m_name, 0, &g_GameT6); - CreateZoneAssetPools(zone.get()); +bool ZoneCreator::SupportsGame(const std::string &gameName) const { return gameName == g_GameT6.GetShortName(); } - for (const auto& assetEntry : context.m_definition->m_assets) - { - if (!assetEntry.m_is_reference) - continue; +std::unique_ptr ZoneCreator::CreateZoneForDefinition(ZoneCreationContext &context) const { + auto zone = std::make_unique(context.m_definition->m_name, 0, &g_GameT6); + CreateZoneAssetPools(zone.get()); - context.m_ignored_assets.emplace_back(assetEntry.m_asset_type, assetEntry.m_asset_name); - } + for (const auto &assetEntry : context.m_definition->m_assets) { + if (!assetEntry.m_is_reference) + continue; - const auto assetLoadingContext = std::make_unique(zone.get(), context.m_asset_search_path, CreateGdtList(context)); - if (!CreateIgnoredAssetMap(context, assetLoadingContext->m_ignored_asset_map)) - return nullptr; + context.m_ignored_assets.emplace_back(assetEntry.m_asset_type, assetEntry.m_asset_name); + } - HandleMetadata(zone.get(), context); + const auto assetLoadingContext = std::make_unique(zone.get(), context.m_asset_search_path, CreateGdtList(context)); + if (!CreateIgnoredAssetMap(context, assetLoadingContext->m_ignored_asset_map)) + return nullptr; - for (const auto& assetEntry : context.m_definition->m_assets) - { - const auto foundAssetTypeEntry = m_asset_types_by_name.find(assetEntry.m_asset_type); - if (foundAssetTypeEntry == m_asset_types_by_name.end()) - { - std::cout << "Unknown asset type \"" << assetEntry.m_asset_type << "\"" << std::endl; - return nullptr; - } + HandleMetadata(zone.get(), context); - if (!ObjLoading::LoadAssetForZone(assetLoadingContext.get(), foundAssetTypeEntry->second, assetEntry.m_asset_name)) - return nullptr; + for (const auto &assetEntry : context.m_definition->m_assets) { + const auto foundAssetTypeEntry = m_asset_types_by_name.find(assetEntry.m_asset_type); + if (foundAssetTypeEntry == m_asset_types_by_name.end()) { + std::cout << "Unknown asset type \"" << assetEntry.m_asset_type << "\"" << std::endl; + return nullptr; } - ObjLoading::FinalizeAssetsForZone(assetLoadingContext.get()); + if (!ObjLoading::LoadAssetForZone(assetLoadingContext.get(), foundAssetTypeEntry->second, assetEntry.m_asset_name)) + return nullptr; + } + + ObjLoading::FinalizeAssetsForZone(assetLoadingContext.get()); - return zone; + return zone; } diff --git a/src/Linker/Game/T6/ZoneCreatorT6.h b/src/Linker/Game/T6/ZoneCreatorT6.h index ff0bcc7da..9f20169c4 100644 --- a/src/Linker/Game/T6/ZoneCreatorT6.h +++ b/src/Linker/Game/T6/ZoneCreatorT6.h @@ -1,26 +1,24 @@ #pragma once -#include #include +#include #include "Zone/ZoneTypes.h" #include "ZoneCreation/IZoneCreator.h" -namespace T6 -{ - class ZoneCreator final : public IZoneCreator - { - std::unordered_map m_asset_types_by_name; +namespace T6 { +class ZoneCreator final : public IZoneCreator { + std::unordered_map m_asset_types_by_name; - void AddAssetTypeName(asset_type_t assetType, std::string name); - static std::vector CreateGdtList(ZoneCreationContext& context); - bool CreateIgnoredAssetMap(ZoneCreationContext& context, std::unordered_map& ignoredAssetMap) const; - void CreateZoneAssetPools(Zone* zone) const; - void HandleMetadata(Zone* zone, ZoneCreationContext& context) const; + void AddAssetTypeName(asset_type_t assetType, std::string name); + static std::vector CreateGdtList(ZoneCreationContext &context); + bool CreateIgnoredAssetMap(ZoneCreationContext &context, std::unordered_map &ignoredAssetMap) const; + void CreateZoneAssetPools(Zone *zone) const; + void HandleMetadata(Zone *zone, ZoneCreationContext &context) const; - public: - ZoneCreator(); +public: + ZoneCreator(); - _NODISCARD bool SupportsGame(const std::string& gameName) const override; - _NODISCARD std::unique_ptr CreateZoneForDefinition(ZoneCreationContext& context) const override; - }; -} + _NODISCARD bool SupportsGame(const std::string &gameName) const override; + _NODISCARD std::unique_ptr CreateZoneForDefinition(ZoneCreationContext &context) const override; +}; +} // namespace T6 diff --git a/src/Linker/Linker.cpp b/src/Linker/Linker.cpp index 511b881bf..b48b75161 100644 --- a/src/Linker/Linker.cpp +++ b/src/Linker/Linker.cpp @@ -1,28 +1,28 @@ #include "Linker.h" -#include -#include +#include #include #include -#include +#include +#include -#include "Utils/ClassUtils.h" -#include "Utils/Arguments/ArgumentParser.h" -#include "ZoneLoading.h" -#include "ObjWriting.h" -#include "ObjLoading.h" -#include "SearchPath/SearchPaths.h" -#include "SearchPath/SearchPathFilesystem.h" -#include "ObjContainer/IWD/IWD.h" -#include "LinkerArgs.h" -#include "ZoneWriting.h" #include "Game/IW3/ZoneCreatorIW3.h" -#include "ZoneCreation/ZoneCreationContext.h" -#include "ZoneCreation/IZoneCreator.h" #include "Game/IW4/ZoneCreatorIW4.h" #include "Game/IW5/ZoneCreatorIW5.h" #include "Game/T5/ZoneCreatorT5.h" #include "Game/T6/ZoneCreatorT6.h" +#include "LinkerArgs.h" +#include "ObjContainer/IWD/IWD.h" +#include "ObjLoading.h" +#include "ObjWriting.h" +#include "SearchPath/SearchPathFilesystem.h" +#include "SearchPath/SearchPaths.h" +#include "Utils/Arguments/ArgumentParser.h" +#include "Utils/ClassUtils.h" +#include "ZoneCreation/IZoneCreator.h" +#include "ZoneCreation/ZoneCreationContext.h" +#include "ZoneLoading.h" +#include "ZoneWriting.h" #include "Utils/ObjFileStream.h" #include "Zone/AssetList/AssetList.h" @@ -31,596 +31,509 @@ namespace fs = std::filesystem; -const IZoneCreator* const ZONE_CREATORS[] -{ - new IW3::ZoneCreator(), - new IW4::ZoneCreator(), - new IW5::ZoneCreator(), - new T5::ZoneCreator(), - new T6::ZoneCreator() -}; - -class Linker::Impl -{ - static constexpr const char* METADATA_NAME = "name"; - static constexpr const char* METADATA_GAME = "game"; - static constexpr const char* METADATA_GDT = "gdt"; - - LinkerArgs m_args; - std::vector> m_loaded_project_search_paths; - SearchPaths m_asset_search_paths; - SearchPaths m_gdt_search_paths; - SearchPaths m_source_search_paths; - std::vector> m_loaded_zones; - - /** - * \brief Loads a search path. - * \param searchPath The search path to load. - */ - void LoadSearchPath(ISearchPath* searchPath) const - { - if (m_args.m_verbose) - { - printf("Loading search path: \"%s\"\n", searchPath->GetPath().c_str()); - } - - ObjLoading::LoadIWDsInSearchPath(searchPath); +const IZoneCreator *const ZONE_CREATORS[]{new IW3::ZoneCreator(), new IW4::ZoneCreator(), new IW5::ZoneCreator(), new T5::ZoneCreator(), new T6::ZoneCreator()}; + +class Linker::Impl { + static constexpr const char *METADATA_NAME = "name"; + static constexpr const char *METADATA_GAME = "game"; + static constexpr const char *METADATA_GDT = "gdt"; + + LinkerArgs m_args; + std::vector> m_loaded_project_search_paths; + SearchPaths m_asset_search_paths; + SearchPaths m_gdt_search_paths; + SearchPaths m_source_search_paths; + std::vector> m_loaded_zones; + + /** + * \brief Loads a search path. + * \param searchPath The search path to load. + */ + void LoadSearchPath(ISearchPath *searchPath) const { + if (m_args.m_verbose) { + printf("Loading search path: \"%s\"\n", searchPath->GetPath().c_str()); } - /** - * \brief Unloads a search path. - * \param searchPath The search path to unload. - */ - void UnloadSearchPath(ISearchPath* searchPath) const - { - if (m_args.m_verbose) - { - printf("Unloading search path: \"%s\"\n", searchPath->GetPath().c_str()); - } + ObjLoading::LoadIWDsInSearchPath(searchPath); + } - ObjLoading::UnloadIWDsInSearchPath(searchPath); + /** + * \brief Unloads a search path. + * \param searchPath The search path to unload. + */ + void UnloadSearchPath(ISearchPath *searchPath) const { + if (m_args.m_verbose) { + printf("Unloading search path: \"%s\"\n", searchPath->GetPath().c_str()); } - SearchPaths GetAssetSearchPathsForProject(const std::string& gameName, const std::string& projectName) - { - SearchPaths searchPathsForProject; + ObjLoading::UnloadIWDsInSearchPath(searchPath); + } - for (const auto& searchPathStr : m_args.GetAssetSearchPathsForProject(gameName, projectName)) - { - auto absolutePath = fs::absolute(searchPathStr); - - if (!fs::is_directory(absolutePath)) - { - if (m_args.m_verbose) - std::cout << "Adding asset search path (Not found): " << absolutePath.string() << std::endl; - continue; - } - - if (m_args.m_verbose) - std::cout << "Adding asset search path: " << absolutePath.string() << std::endl; - - auto searchPath = std::make_unique(searchPathStr); - LoadSearchPath(searchPath.get()); - searchPathsForProject.IncludeSearchPath(searchPath.get()); - m_loaded_project_search_paths.emplace_back(std::move(searchPath)); - } + SearchPaths GetAssetSearchPathsForProject(const std::string &gameName, const std::string &projectName) { + SearchPaths searchPathsForProject; - searchPathsForProject.IncludeSearchPath(&m_asset_search_paths); + for (const auto &searchPathStr : m_args.GetAssetSearchPathsForProject(gameName, projectName)) { + auto absolutePath = fs::absolute(searchPathStr); - for (auto* iwd : IWD::Repository) - { - searchPathsForProject.IncludeSearchPath(iwd); - } + if (!fs::is_directory(absolutePath)) { + if (m_args.m_verbose) + std::cout << "Adding asset search path (Not found): " << absolutePath.string() << std::endl; + continue; + } - return searchPathsForProject; + if (m_args.m_verbose) + std::cout << "Adding asset search path: " << absolutePath.string() << std::endl; + + auto searchPath = std::make_unique(searchPathStr); + LoadSearchPath(searchPath.get()); + searchPathsForProject.IncludeSearchPath(searchPath.get()); + m_loaded_project_search_paths.emplace_back(std::move(searchPath)); } - SearchPaths GetGdtSearchPathsForProject(const std::string& gameName, const std::string& projectName) - { - SearchPaths searchPathsForProject; + searchPathsForProject.IncludeSearchPath(&m_asset_search_paths); - for (const auto& searchPathStr : m_args.GetGdtSearchPathsForProject(gameName, projectName)) - { - auto absolutePath = fs::absolute(searchPathStr); + for (auto *iwd : IWD::Repository) { + searchPathsForProject.IncludeSearchPath(iwd); + } - if (!fs::is_directory(absolutePath)) - { - if (m_args.m_verbose) - std::cout << "Adding gdt search path (Not found): " << absolutePath.string() << std::endl; - continue; - } + return searchPathsForProject; + } - if (m_args.m_verbose) - std::cout << "Adding gdt search path: " << absolutePath.string() << std::endl; + SearchPaths GetGdtSearchPathsForProject(const std::string &gameName, const std::string &projectName) { + SearchPaths searchPathsForProject; - searchPathsForProject.CommitSearchPath(std::make_unique(searchPathStr)); - } + for (const auto &searchPathStr : m_args.GetGdtSearchPathsForProject(gameName, projectName)) { + auto absolutePath = fs::absolute(searchPathStr); - searchPathsForProject.IncludeSearchPath(&m_gdt_search_paths); + if (!fs::is_directory(absolutePath)) { + if (m_args.m_verbose) + std::cout << "Adding gdt search path (Not found): " << absolutePath.string() << std::endl; + continue; + } + + if (m_args.m_verbose) + std::cout << "Adding gdt search path: " << absolutePath.string() << std::endl; - return searchPathsForProject; + searchPathsForProject.CommitSearchPath(std::make_unique(searchPathStr)); } - SearchPaths GetSourceSearchPathsForProject(const std::string& projectName) - { - SearchPaths searchPathsForProject; + searchPathsForProject.IncludeSearchPath(&m_gdt_search_paths); - for (const auto& searchPathStr : m_args.GetSourceSearchPathsForProject(projectName)) - { - auto absolutePath = fs::absolute(searchPathStr); + return searchPathsForProject; + } - if (!fs::is_directory(absolutePath)) - { - if (m_args.m_verbose) - std::cout << "Adding source search path (Not found): " << absolutePath.string() << std::endl; - continue; - } + SearchPaths GetSourceSearchPathsForProject(const std::string &projectName) { + SearchPaths searchPathsForProject; - if (m_args.m_verbose) - std::cout << "Adding source search path: " << absolutePath.string() << std::endl; + for (const auto &searchPathStr : m_args.GetSourceSearchPathsForProject(projectName)) { + auto absolutePath = fs::absolute(searchPathStr); - searchPathsForProject.CommitSearchPath(std::make_unique(searchPathStr)); - } + if (!fs::is_directory(absolutePath)) { + if (m_args.m_verbose) + std::cout << "Adding source search path (Not found): " << absolutePath.string() << std::endl; + continue; + } - searchPathsForProject.IncludeSearchPath(&m_source_search_paths); + if (m_args.m_verbose) + std::cout << "Adding source search path: " << absolutePath.string() << std::endl; - return searchPathsForProject; + searchPathsForProject.CommitSearchPath(std::make_unique(searchPathStr)); } - /** - * \brief Initializes the Linker object's search paths based on the user's input. - * \return \c true if building the search paths was successful, otherwise \c false. - */ - bool BuildProjectIndependentSearchPaths() - { - for (const auto& path : m_args.GetProjectIndependentAssetSearchPaths()) - { - auto absolutePath = fs::absolute(path); + searchPathsForProject.IncludeSearchPath(&m_source_search_paths); - if (!fs::is_directory(absolutePath)) - { - if (m_args.m_verbose) - std::cout << "Adding asset search path (Not found): " << absolutePath.string() << std::endl; - continue; - } + return searchPathsForProject; + } - if (m_args.m_verbose) - std::cout << "Adding asset search path: " << absolutePath.string() << std::endl; + /** + * \brief Initializes the Linker object's search paths based on the user's input. + * \return \c true if building the search paths was successful, otherwise \c false. + */ + bool BuildProjectIndependentSearchPaths() { + for (const auto &path : m_args.GetProjectIndependentAssetSearchPaths()) { + auto absolutePath = fs::absolute(path); - auto searchPath = std::make_unique(absolutePath.string()); - LoadSearchPath(searchPath.get()); - m_asset_search_paths.CommitSearchPath(std::move(searchPath)); - } + if (!fs::is_directory(absolutePath)) { + if (m_args.m_verbose) + std::cout << "Adding asset search path (Not found): " << absolutePath.string() << std::endl; + continue; + } - for (const auto& path : m_args.GetProjectIndependentGdtSearchPaths()) - { - auto absolutePath = fs::absolute(path); + if (m_args.m_verbose) + std::cout << "Adding asset search path: " << absolutePath.string() << std::endl; - if (!fs::is_directory(absolutePath)) - { - if (m_args.m_verbose) - std::cout << "Loading gdt search path (Not found): " << absolutePath.string() << std::endl; - continue; - } + auto searchPath = std::make_unique(absolutePath.string()); + LoadSearchPath(searchPath.get()); + m_asset_search_paths.CommitSearchPath(std::move(searchPath)); + } - if (m_args.m_verbose) - std::cout << "Adding gdt search path: " << absolutePath.string() << std::endl; + for (const auto &path : m_args.GetProjectIndependentGdtSearchPaths()) { + auto absolutePath = fs::absolute(path); - m_gdt_search_paths.CommitSearchPath(std::make_unique(absolutePath.string())); - } + if (!fs::is_directory(absolutePath)) { + if (m_args.m_verbose) + std::cout << "Loading gdt search path (Not found): " << absolutePath.string() << std::endl; + continue; + } - for (const auto& path : m_args.GetProjectIndependentSourceSearchPaths()) - { - auto absolutePath = fs::absolute(path); + if (m_args.m_verbose) + std::cout << "Adding gdt search path: " << absolutePath.string() << std::endl; - if (!fs::is_directory(absolutePath)) - { - if (m_args.m_verbose) - std::cout << "Loading source search path (Not found): " << absolutePath.string() << std::endl; - continue; - } + m_gdt_search_paths.CommitSearchPath(std::make_unique(absolutePath.string())); + } - if (m_args.m_verbose) - std::cout << "Adding source search path: " << absolutePath.string() << std::endl; + for (const auto &path : m_args.GetProjectIndependentSourceSearchPaths()) { + auto absolutePath = fs::absolute(path); - m_source_search_paths.CommitSearchPath(std::make_unique(absolutePath.string())); - } + if (!fs::is_directory(absolutePath)) { + if (m_args.m_verbose) + std::cout << "Loading source search path (Not found): " << absolutePath.string() << std::endl; + continue; + } - return true; + if (m_args.m_verbose) + std::cout << "Adding source search path: " << absolutePath.string() << std::endl; + + m_source_search_paths.CommitSearchPath(std::make_unique(absolutePath.string())); } - bool IncludeAdditionalZoneDefinitions(const std::string& initialFileName, ZoneDefinition& zoneDefinition, ISearchPath* sourceSearchPath) const - { - std::set sourceNames; - sourceNames.emplace(initialFileName); + return true; + } - std::deque toIncludeQueue; - for (const auto& include : zoneDefinition.m_includes) - toIncludeQueue.emplace_back(include); + bool IncludeAdditionalZoneDefinitions(const std::string &initialFileName, ZoneDefinition &zoneDefinition, ISearchPath *sourceSearchPath) const { + std::set sourceNames; + sourceNames.emplace(initialFileName); - while (!toIncludeQueue.empty()) - { - const auto& source = toIncludeQueue.front(); - - if (sourceNames.find(source) == sourceNames.end()) - { - sourceNames.emplace(source); - - std::unique_ptr includeDefinition; - { - const auto definitionFileName = source + ".zone"; - const auto definitionStream = sourceSearchPath->Open(definitionFileName); - if (!definitionStream.IsOpen()) - { - std::cout << "Could not find zone definition file for project \"" << source << "\"." << std::endl; - return false; - } - - ZoneDefinitionInputStream zoneDefinitionInputStream(*definitionStream.m_stream, definitionFileName, m_args.m_verbose); - includeDefinition = zoneDefinitionInputStream.ReadDefinition(); - } - - if (!includeDefinition) - { - std::cout << "Failed to read zone definition file for project \"" << source << "\"." << std::endl; - return false; - } - - for (const auto& include : includeDefinition->m_includes) - toIncludeQueue.emplace_back(include); - - zoneDefinition.Include(*includeDefinition); - } - - toIncludeQueue.pop_front(); - } + std::deque toIncludeQueue; + for (const auto &include : zoneDefinition.m_includes) + toIncludeQueue.emplace_back(include); - return true; - } + while (!toIncludeQueue.empty()) { + const auto &source = toIncludeQueue.front(); - static bool GetNameFromZoneDefinition(std::string& name, const std::string& projectName, const ZoneDefinition& zoneDefinition) - { - auto firstNameEntry = true; - const auto [rangeBegin, rangeEnd] = zoneDefinition.m_metadata_lookup.equal_range(METADATA_NAME); - for (auto i = rangeBegin; i != rangeEnd; ++i) + if (sourceNames.find(source) == sourceNames.end()) { + sourceNames.emplace(source); + + std::unique_ptr includeDefinition; { - if (firstNameEntry) - { - name = i->second->m_value; - firstNameEntry = false; - } - else - { - if (name != i->second->m_value) - { - std::cout << "Conflicting names in project \"" << projectName << "\": " << name << " != " << i->second << std::endl; - return false; - } - } + const auto definitionFileName = source + ".zone"; + const auto definitionStream = sourceSearchPath->Open(definitionFileName); + if (!definitionStream.IsOpen()) { + std::cout << "Could not find zone definition file for project \"" << source << "\"." << std::endl; + return false; + } + + ZoneDefinitionInputStream zoneDefinitionInputStream(*definitionStream.m_stream, definitionFileName, m_args.m_verbose); + includeDefinition = zoneDefinitionInputStream.ReadDefinition(); + } + + if (!includeDefinition) { + std::cout << "Failed to read zone definition file for project \"" << source << "\"." << std::endl; + return false; } - if (firstNameEntry) - name = projectName; + for (const auto &include : includeDefinition->m_includes) + toIncludeQueue.emplace_back(include); - return true; + zoneDefinition.Include(*includeDefinition); + } + + toIncludeQueue.pop_front(); } - std::unique_ptr ReadZoneDefinition(const std::string& projectName, ISearchPath* sourceSearchPath) const - { - std::unique_ptr zoneDefinition; - { - const auto definitionFileName = projectName + ".zone"; - const auto definitionStream = sourceSearchPath->Open(definitionFileName); - if (!definitionStream.IsOpen()) - { - std::cout << "Could not find zone definition file for project \"" << projectName << "\"." << std::endl; - return nullptr; - } - - ZoneDefinitionInputStream zoneDefinitionInputStream(*definitionStream.m_stream, definitionFileName, m_args.m_verbose); - zoneDefinition = zoneDefinitionInputStream.ReadDefinition(); + return true; + } + + static bool GetNameFromZoneDefinition(std::string &name, const std::string &projectName, const ZoneDefinition &zoneDefinition) { + auto firstNameEntry = true; + const auto [rangeBegin, rangeEnd] = zoneDefinition.m_metadata_lookup.equal_range(METADATA_NAME); + for (auto i = rangeBegin; i != rangeEnd; ++i) { + if (firstNameEntry) { + name = i->second->m_value; + firstNameEntry = false; + } else { + if (name != i->second->m_value) { + std::cout << "Conflicting names in project \"" << projectName << "\": " << name << " != " << i->second << std::endl; + return false; } + } + } - if (!zoneDefinition) - { - std::cout << "Failed to read zone definition file for project \"" << projectName << "\"." << std::endl; - return nullptr; - } + if (firstNameEntry) + name = projectName; - if (!GetNameFromZoneDefinition(zoneDefinition->m_name, projectName, *zoneDefinition)) - return nullptr; + return true; + } - if (!IncludeAdditionalZoneDefinitions(projectName, *zoneDefinition, sourceSearchPath)) - return nullptr; + std::unique_ptr ReadZoneDefinition(const std::string &projectName, ISearchPath *sourceSearchPath) const { + std::unique_ptr zoneDefinition; + { + const auto definitionFileName = projectName + ".zone"; + const auto definitionStream = sourceSearchPath->Open(definitionFileName); + if (!definitionStream.IsOpen()) { + std::cout << "Could not find zone definition file for project \"" << projectName << "\"." << std::endl; + return nullptr; + } - return zoneDefinition; + ZoneDefinitionInputStream zoneDefinitionInputStream(*definitionStream.m_stream, definitionFileName, m_args.m_verbose); + zoneDefinition = zoneDefinitionInputStream.ReadDefinition(); } - bool ReadAssetList(const std::string& zoneName, std::vector& assetList, ISearchPath* sourceSearchPath) const - { - { - const auto assetListFileName = "assetlist/" + zoneName + ".csv"; - const auto assetListStream = sourceSearchPath->Open(assetListFileName); - - if (assetListStream.IsOpen()) - { - const AssetListInputStream stream(*assetListStream.m_stream); - AssetListEntry entry; - - while (stream.NextEntry(entry)) - { - assetList.emplace_back(std::move(entry)); - } - return true; - } - } + if (!zoneDefinition) { + std::cout << "Failed to read zone definition file for project \"" << projectName << "\"." << std::endl; + return nullptr; + } - { - const auto zoneDefinition = ReadZoneDefinition(zoneName, sourceSearchPath); - - if (zoneDefinition) - { - for (const auto& entry : zoneDefinition->m_assets) - { - assetList.emplace_back(entry.m_asset_type, entry.m_asset_name); - } - return true; - } - } + if (!GetNameFromZoneDefinition(zoneDefinition->m_name, projectName, *zoneDefinition)) + return nullptr; - return false; - } + if (!IncludeAdditionalZoneDefinitions(projectName, *zoneDefinition, sourceSearchPath)) + return nullptr; + + return zoneDefinition; + } - bool ProcessZoneDefinitionIgnores(const std::string& projectName, ZoneCreationContext& context, ISearchPath* sourceSearchPath) const + bool ReadAssetList(const std::string &zoneName, std::vector &assetList, ISearchPath *sourceSearchPath) const { { - if (context.m_definition->m_ignores.empty()) - return true; + const auto assetListFileName = "assetlist/" + zoneName + ".csv"; + const auto assetListStream = sourceSearchPath->Open(assetListFileName); - std::map> zoneDefinitionAssetsByName; - for (auto& entry : context.m_definition->m_assets) - { - zoneDefinitionAssetsByName.try_emplace(entry.m_asset_name, entry); - } + if (assetListStream.IsOpen()) { + const AssetListInputStream stream(*assetListStream.m_stream); + AssetListEntry entry; - for (const auto& ignore : context.m_definition->m_ignores) - { - if (ignore == projectName) - continue; - - std::vector assetList; - if (!ReadAssetList(ignore, context.m_ignored_assets, sourceSearchPath)) - { - std::cout << "Failed to read asset listing for ignoring assets of project \"" << ignore << "\"." << std::endl; - return false; - } + while (stream.NextEntry(entry)) { + assetList.emplace_back(std::move(entry)); } return true; + } } - static bool GetGameNameFromZoneDefinition(std::string& gameName, const std::string& projectName, const ZoneDefinition& zoneDefinition) { - auto firstGameEntry = true; - const auto [rangeBegin, rangeEnd] = zoneDefinition.m_metadata_lookup.equal_range(METADATA_GAME); - for (auto i = rangeBegin; i != rangeEnd; ++i) - { - if (firstGameEntry) - { - gameName = i->second->m_value; - firstGameEntry = false; - } - else - { - if (gameName != i->second->m_value) - { - std::cout << "Conflicting game names in project \"" << projectName << "\": " << gameName << " != " << i->second << std::endl; - return false; - } - } - } + const auto zoneDefinition = ReadZoneDefinition(zoneName, sourceSearchPath); - if (firstGameEntry) - { - std::cout << "No game name was specified for project \"" << projectName << "\"" << std::endl; - return false; + if (zoneDefinition) { + for (const auto &entry : zoneDefinition->m_assets) { + assetList.emplace_back(entry.m_asset_type, entry.m_asset_name); } - return true; + } } - static bool LoadGdtFilesFromZoneDefinition(std::vector>& gdtList, const ZoneDefinition& zoneDefinition, ISearchPath* gdtSearchPath) - { - const auto [rangeBegin, rangeEnd] = zoneDefinition.m_metadata_lookup.equal_range(METADATA_GDT); - for (auto i = rangeBegin; i != rangeEnd; ++i) - { - const auto gdtFile = gdtSearchPath->Open(i->second->m_value + ".gdt"); - if (!gdtFile.IsOpen()) - { - std::cout << "Failed to open file for gdt \"" << i->second->m_value << "\"" << std::endl; - return false; - } - - GdtReader gdtReader(*gdtFile.m_stream); - auto gdt = std::make_unique(); - if (!gdtReader.Read(*gdt)) - { - std::cout << "Failed to read gdt file \"" << i->second << "\"" << std::endl; - return false; - } - - gdtList.emplace_back(std::move(gdt)); - } + return false; + } - return true; + bool ProcessZoneDefinitionIgnores(const std::string &projectName, ZoneCreationContext &context, ISearchPath *sourceSearchPath) const { + if (context.m_definition->m_ignores.empty()) + return true; + + std::map> zoneDefinitionAssetsByName; + for (auto &entry : context.m_definition->m_assets) { + zoneDefinitionAssetsByName.try_emplace(entry.m_asset_name, entry); } - std::unique_ptr CreateZoneForDefinition(const std::string& projectName, ZoneDefinition& zoneDefinition, ISearchPath* assetSearchPath, ISearchPath* gdtSearchPath, - ISearchPath* sourceSearchPath) const - { - const auto context = std::make_unique(assetSearchPath, &zoneDefinition); - if (!ProcessZoneDefinitionIgnores(projectName, *context, sourceSearchPath)) - return nullptr; - if (!GetGameNameFromZoneDefinition(context->m_game_name, projectName, zoneDefinition)) - return nullptr; - if (!LoadGdtFilesFromZoneDefinition(context->m_gdt_files, zoneDefinition, gdtSearchPath)) - return nullptr; - - for (const auto* assetLoader : ZONE_CREATORS) - { - if (assetLoader->SupportsGame(context->m_game_name)) - return assetLoader->CreateZoneForDefinition(*context); + for (const auto &ignore : context.m_definition->m_ignores) { + if (ignore == projectName) + continue; + + std::vector assetList; + if (!ReadAssetList(ignore, context.m_ignored_assets, sourceSearchPath)) { + std::cout << "Failed to read asset listing for ignoring assets of project \"" << ignore << "\"." << std::endl; + return false; + } + } + return true; + } + + static bool GetGameNameFromZoneDefinition(std::string &gameName, const std::string &projectName, const ZoneDefinition &zoneDefinition) { + auto firstGameEntry = true; + const auto [rangeBegin, rangeEnd] = zoneDefinition.m_metadata_lookup.equal_range(METADATA_GAME); + for (auto i = rangeBegin; i != rangeEnd; ++i) { + if (firstGameEntry) { + gameName = i->second->m_value; + firstGameEntry = false; + } else { + if (gameName != i->second->m_value) { + std::cout << "Conflicting game names in project \"" << projectName << "\": " << gameName << " != " << i->second << std::endl; + return false; } + } + } - return nullptr; + if (firstGameEntry) { + std::cout << "No game name was specified for project \"" << projectName << "\"" << std::endl; + return false; } - bool WriteZoneToFile(const std::string& projectName, Zone* zone) const - { - const fs::path zoneFolderPath(m_args.GetOutputFolderPathForProject(projectName)); - auto zoneFilePath(zoneFolderPath); - zoneFilePath.append(zone->m_name + ".ff"); + return true; + } + + static bool LoadGdtFilesFromZoneDefinition(std::vector> &gdtList, const ZoneDefinition &zoneDefinition, ISearchPath *gdtSearchPath) { + const auto [rangeBegin, rangeEnd] = zoneDefinition.m_metadata_lookup.equal_range(METADATA_GDT); + for (auto i = rangeBegin; i != rangeEnd; ++i) { + const auto gdtFile = gdtSearchPath->Open(i->second->m_value + ".gdt"); + if (!gdtFile.IsOpen()) { + std::cout << "Failed to open file for gdt \"" << i->second->m_value << "\"" << std::endl; + return false; + } - fs::create_directories(zoneFolderPath); + GdtReader gdtReader(*gdtFile.m_stream); + auto gdt = std::make_unique(); + if (!gdtReader.Read(*gdt)) { + std::cout << "Failed to read gdt file \"" << i->second << "\"" << std::endl; + return false; + } - std::ofstream stream(zoneFilePath, std::fstream::out | std::fstream::binary); - if (!stream.is_open()) - return false; + gdtList.emplace_back(std::move(gdt)); + } - if (!ZoneWriting::WriteZone(stream, zone)) - { - std::cout << "Writing zone failed." << std::endl; - stream.close(); - return false; - } + return true; + } + + std::unique_ptr CreateZoneForDefinition(const std::string &projectName, ZoneDefinition &zoneDefinition, ISearchPath *assetSearchPath, + ISearchPath *gdtSearchPath, ISearchPath *sourceSearchPath) const { + const auto context = std::make_unique(assetSearchPath, &zoneDefinition); + if (!ProcessZoneDefinitionIgnores(projectName, *context, sourceSearchPath)) + return nullptr; + if (!GetGameNameFromZoneDefinition(context->m_game_name, projectName, zoneDefinition)) + return nullptr; + if (!LoadGdtFilesFromZoneDefinition(context->m_gdt_files, zoneDefinition, gdtSearchPath)) + return nullptr; + + for (const auto *assetLoader : ZONE_CREATORS) { + if (assetLoader->SupportsGame(context->m_game_name)) + return assetLoader->CreateZoneForDefinition(*context); + } - std::cout << "Created zone \"" << zoneFilePath.string() << "\"\n"; + return nullptr; + } - stream.close(); - return true; + bool WriteZoneToFile(const std::string &projectName, Zone *zone) const { + const fs::path zoneFolderPath(m_args.GetOutputFolderPathForProject(projectName)); + auto zoneFilePath(zoneFolderPath); + zoneFilePath.append(zone->m_name + ".ff"); + + fs::create_directories(zoneFolderPath); + + std::ofstream stream(zoneFilePath, std::fstream::out | std::fstream::binary); + if (!stream.is_open()) + return false; + + if (!ZoneWriting::WriteZone(stream, zone)) { + std::cout << "Writing zone failed." << std::endl; + stream.close(); + return false; } - bool BuildProject(const std::string& projectName) - { - auto sourceSearchPaths = GetSourceSearchPathsForProject(projectName); + std::cout << "Created zone \"" << zoneFilePath.string() << "\"\n"; - const auto zoneDefinition = ReadZoneDefinition(projectName, &sourceSearchPaths); - if (!zoneDefinition) - return false; + stream.close(); + return true; + } - std::string gameName; - if (!GetGameNameFromZoneDefinition(gameName, projectName, *zoneDefinition)) - return false; + bool BuildProject(const std::string &projectName) { + auto sourceSearchPaths = GetSourceSearchPathsForProject(projectName); - for (auto& c : gameName) - c = static_cast(std::tolower(c)); + const auto zoneDefinition = ReadZoneDefinition(projectName, &sourceSearchPaths); + if (!zoneDefinition) + return false; - auto assetSearchPaths = GetAssetSearchPathsForProject(gameName, projectName); - auto gdtSearchPaths = GetGdtSearchPathsForProject(gameName, projectName); + std::string gameName; + if (!GetGameNameFromZoneDefinition(gameName, projectName, *zoneDefinition)) + return false; - const auto zone = CreateZoneForDefinition(projectName, *zoneDefinition, &assetSearchPaths, &gdtSearchPaths, &sourceSearchPaths); - auto result = zone != nullptr; - if (zone) - result = WriteZoneToFile(projectName, zone.get()); + for (auto &c : gameName) + c = static_cast(std::tolower(c)); - for (const auto& loadedSearchPath : m_loaded_project_search_paths) - { - UnloadSearchPath(loadedSearchPath.get()); - } - m_loaded_project_search_paths.clear(); + auto assetSearchPaths = GetAssetSearchPathsForProject(gameName, projectName); + auto gdtSearchPaths = GetGdtSearchPathsForProject(gameName, projectName); + + const auto zone = CreateZoneForDefinition(projectName, *zoneDefinition, &assetSearchPaths, &gdtSearchPaths, &sourceSearchPaths); + auto result = zone != nullptr; + if (zone) + result = WriteZoneToFile(projectName, zone.get()); - return result; + for (const auto &loadedSearchPath : m_loaded_project_search_paths) { + UnloadSearchPath(loadedSearchPath.get()); } + m_loaded_project_search_paths.clear(); - bool LoadZones() - { - for (const auto& zonePath : m_args.m_zones_to_load) - { - if (!fs::is_regular_file(zonePath)) - { - printf("Could not find file \"%s\".\n", zonePath.c_str()); - continue; - } - - auto absoluteZoneDirectory = absolute(std::filesystem::path(zonePath).remove_filename()).string(); - - auto zone = std::unique_ptr(ZoneLoading::LoadZone(zonePath)); - if (zone == nullptr) - { - printf("Failed to load zone \"%s\".\n", zonePath.c_str()); - return false; - } - - if (m_args.m_verbose) - { - printf("Loaded zone \"%s\"\n", zone->m_name.c_str()); - } - - m_loaded_zones.emplace_back(std::move(zone)); - } + return result; + } - return true; - } + bool LoadZones() { + for (const auto &zonePath : m_args.m_zones_to_load) { + if (!fs::is_regular_file(zonePath)) { + printf("Could not find file \"%s\".\n", zonePath.c_str()); + continue; + } - void UnloadZones() - { - for (auto i = m_loaded_zones.rbegin(); i != m_loaded_zones.rend(); ++i) - { - auto& loadedZone = *i; - std::string zoneName = loadedZone->m_name; + auto absoluteZoneDirectory = absolute(std::filesystem::path(zonePath).remove_filename()).string(); + + auto zone = std::unique_ptr(ZoneLoading::LoadZone(zonePath)); + if (zone == nullptr) { + printf("Failed to load zone \"%s\".\n", zonePath.c_str()); + return false; + } - loadedZone.reset(); + if (m_args.m_verbose) { + printf("Loaded zone \"%s\"\n", zone->m_name.c_str()); + } - if (m_args.m_verbose) - std::cout << "Unloaded zone \"" << zoneName << "\"\n"; - } - m_loaded_zones.clear(); + m_loaded_zones.emplace_back(std::move(zone)); } -public: - Impl() - = default; + return true; + } - /** - * \copydoc Linker::Start - */ - bool Start(const int argc, const char** argv) - { - if (!m_args.ParseArgs(argc, argv)) - return false; + void UnloadZones() { + for (auto i = m_loaded_zones.rbegin(); i != m_loaded_zones.rend(); ++i) { + auto &loadedZone = *i; + std::string zoneName = loadedZone->m_name; - if (!BuildProjectIndependentSearchPaths()) - return false; + loadedZone.reset(); - if (!LoadZones()) - return false; + if (m_args.m_verbose) + std::cout << "Unloaded zone \"" << zoneName << "\"\n"; + } + m_loaded_zones.clear(); + } - auto result = true; - for (const auto& projectName : m_args.m_projects_to_build) - { - if (!BuildProject(projectName)) - { - result = false; - break; - } - } +public: + Impl() = default; + + /** + * \copydoc Linker::Start + */ + bool Start(const int argc, const char **argv) { + if (!m_args.ParseArgs(argc, argv)) + return false; + + if (!BuildProjectIndependentSearchPaths()) + return false; + + if (!LoadZones()) + return false; + + auto result = true; + for (const auto &projectName : m_args.m_projects_to_build) { + if (!BuildProject(projectName)) { + result = false; + break; + } + } - UnloadZones(); + UnloadZones(); - return result; - } + return result; + } }; -Linker::Linker() -{ - m_impl = new Impl(); -} +Linker::Linker() { m_impl = new Impl(); } -Linker::~Linker() -{ - delete m_impl; - m_impl = nullptr; +Linker::~Linker() { + delete m_impl; + m_impl = nullptr; } -bool Linker::Start(const int argc, const char** argv) const -{ - return m_impl->Start(argc, argv); -} +bool Linker::Start(const int argc, const char **argv) const { return m_impl->Start(argc, argv); } diff --git a/src/Linker/Linker.h b/src/Linker/Linker.h index 3e452c906..48793f926 100644 --- a/src/Linker/Linker.h +++ b/src/Linker/Linker.h @@ -1,24 +1,23 @@ #pragma once -class Linker -{ - class Impl; - Impl* m_impl; +class Linker { + class Impl; + Impl *m_impl; public: - Linker(); - ~Linker(); + Linker(); + ~Linker(); - Linker(const Linker& other) = delete; - Linker(Linker&& other) noexcept = delete; - Linker& operator=(const Linker& other) = delete; - Linker& operator=(Linker&& other) noexcept = delete; + Linker(const Linker &other) = delete; + Linker(Linker &&other) noexcept = delete; + Linker &operator=(const Linker &other) = delete; + Linker &operator=(Linker &&other) noexcept = delete; - /** - * \brief Starts the Linker application logic. - * \param argc The amount of command line arguments specified. - * \param argv The command line arguments. - * \return \c true if the application was successful or \c false if an error occurred. - */ - bool Start(int argc, const char** argv) const; + /** + * \brief Starts the Linker application logic. + * \param argc The amount of command line arguments specified. + * \param argv The command line arguments. + * \return \c true if the application was successful or \c false if an error occurred. + */ + bool Start(int argc, const char **argv) const; }; \ No newline at end of file diff --git a/src/Linker/LinkerArgs.cpp b/src/Linker/LinkerArgs.cpp index 83f52e8c1..ae91f0598 100644 --- a/src/Linker/LinkerArgs.cpp +++ b/src/Linker/LinkerArgs.cpp @@ -4,319 +4,259 @@ #include #include -#include "Utils/Arguments/UsageInformation.h" #include "ObjLoading.h" #include "ObjWriting.h" +#include "Utils/Arguments/UsageInformation.h" #include "Utils/FileUtils.h" namespace fs = std::filesystem; -const CommandLineOption* const OPTION_HELP = - CommandLineOption::Builder::Create() - .WithShortName("?") - .WithLongName("help") - .WithDescription("Displays usage information.") - .Build(); - -const CommandLineOption* const OPTION_VERBOSE = - CommandLineOption::Builder::Create() - .WithShortName("v") - .WithLongName("verbose") - .WithDescription("Outputs a lot more and more detailed messages.") - .Build(); +const CommandLineOption *const OPTION_HELP = + CommandLineOption::Builder::Create().WithShortName("?").WithLongName("help").WithDescription("Displays usage information.").Build(); -const CommandLineOption* const OPTION_BASE_FOLDER = - CommandLineOption::Builder::Create() - .WithShortName("b") - .WithLongName("base-folder") - .WithDescription("Specifies the base folder that can be used to specify other folders. Defaults to the current directory.") - .WithParameter("baseFolderPath") - .Build(); +const CommandLineOption *const OPTION_VERBOSE = + CommandLineOption::Builder::Create().WithShortName("v").WithLongName("verbose").WithDescription("Outputs a lot more and more detailed messages.").Build(); -const CommandLineOption* const OPTION_OUTPUT_FOLDER = +const CommandLineOption *const OPTION_BASE_FOLDER = CommandLineOption::Builder::Create() - .WithLongName("output-folder") - .WithDescription("Specifies the output folder containing the build artifacts. Defaults to \"" + std::string(LinkerArgs::DEFAULT_OUTPUT_FOLDER) + "\".") - .WithParameter("outputFolderPath") - .Build(); + .WithShortName("b") + .WithLongName("base-folder") + .WithDescription("Specifies the base folder that can be used to specify other folders. Defaults to the current directory.") + .WithParameter("baseFolderPath") + .Build(); -const CommandLineOption* const OPTION_ASSET_SEARCH_PATH = +const CommandLineOption *const OPTION_OUTPUT_FOLDER = CommandLineOption::Builder::Create() - .WithLongName("asset-search-path") - .WithDescription("Specifies the search paths used for assets. Defaults to \"" + std::string(LinkerArgs::DEFAULT_ASSET_SEARCH_PATH) + "\".") - .WithParameter("assetSearchPathString") - .Build(); + .WithLongName("output-folder") + .WithDescription("Specifies the output folder containing the build artifacts. Defaults to \"" + std::string(LinkerArgs::DEFAULT_OUTPUT_FOLDER) + "\".") + .WithParameter("outputFolderPath") + .Build(); -const CommandLineOption* const OPTION_GDT_SEARCH_PATH = +const CommandLineOption *const OPTION_ASSET_SEARCH_PATH = CommandLineOption::Builder::Create() - .WithLongName("gdt-search-path") - .WithDescription("Specifies the search paths used for assets. Defaults to \"" + std::string(LinkerArgs::DEFAULT_GDT_SEARCH_PATH) + "\".") - .WithParameter("gdtSearchPathString") - .Build(); + .WithLongName("asset-search-path") + .WithDescription("Specifies the search paths used for assets. Defaults to \"" + std::string(LinkerArgs::DEFAULT_ASSET_SEARCH_PATH) + "\".") + .WithParameter("assetSearchPathString") + .Build(); -const CommandLineOption* const OPTION_SOURCE_SEARCH_PATH = +const CommandLineOption *const OPTION_GDT_SEARCH_PATH = CommandLineOption::Builder::Create() - .WithLongName("source-search-path") - .WithDescription("Specifies the search paths used for assets. Defaults to \"" + std::string(LinkerArgs::DEFAULT_SOURCE_SEARCH_PATH) + "\".") - .WithParameter("sourceSearchPathString") - .Build(); + .WithLongName("gdt-search-path") + .WithDescription("Specifies the search paths used for assets. Defaults to \"" + std::string(LinkerArgs::DEFAULT_GDT_SEARCH_PATH) + "\".") + .WithParameter("gdtSearchPathString") + .Build(); -const CommandLineOption* const OPTION_LOAD = +const CommandLineOption *const OPTION_SOURCE_SEARCH_PATH = CommandLineOption::Builder::Create() - .WithShortName("l") - .WithLongName("load") - .WithDescription("Loads an existing zone to be able to use its assets when building.") - .WithParameter("zonePath") - .Reusable() - .Build(); - -const CommandLineOption* const OPTION_MENU_PERMISSIVE = - CommandLineOption::Builder::Create() - .WithLongName("menu-permissive") - .WithDescription("Allows the usage of unknown script commands that can be compiled.") - .Build(); - -const CommandLineOption* const OPTION_MENU_NO_OPTIMIZATION = + .WithLongName("source-search-path") + .WithDescription("Specifies the search paths used for assets. Defaults to \"" + std::string(LinkerArgs::DEFAULT_SOURCE_SEARCH_PATH) + "\".") + .WithParameter("sourceSearchPathString") + .Build(); + +const CommandLineOption *const OPTION_LOAD = CommandLineOption::Builder::Create() + .WithShortName("l") + .WithLongName("load") + .WithDescription("Loads an existing zone to be able to use its assets when building.") + .WithParameter("zonePath") + .Reusable() + .Build(); + +const CommandLineOption *const OPTION_MENU_PERMISSIVE = CommandLineOption::Builder::Create() + .WithLongName("menu-permissive") + .WithDescription("Allows the usage of unknown script commands that can be compiled.") + .Build(); + +const CommandLineOption *const OPTION_MENU_NO_OPTIMIZATION = CommandLineOption::Builder::Create() - .WithLongName("menu-no-optimization") - .WithDescription("Refrain from applying optimizations to parsed menus. (Optimizations increase menu performance and size. May result in less source information when dumped though.)") - .Build(); - -const CommandLineOption* const COMMAND_LINE_OPTIONS[] -{ - OPTION_HELP, - OPTION_VERBOSE, - OPTION_BASE_FOLDER, - OPTION_OUTPUT_FOLDER, - OPTION_ASSET_SEARCH_PATH, - OPTION_GDT_SEARCH_PATH, - OPTION_SOURCE_SEARCH_PATH, - OPTION_LOAD, - OPTION_MENU_PERMISSIVE, - OPTION_MENU_NO_OPTIMIZATION -}; + .WithLongName("menu-no-optimization") + .WithDescription("Refrain from applying optimizations to parsed menus. (Optimizations increase menu performance and size. May result in less source " + "information when dumped though.)") + .Build(); + +const CommandLineOption *const COMMAND_LINE_OPTIONS[]{OPTION_HELP, + OPTION_VERBOSE, + OPTION_BASE_FOLDER, + OPTION_OUTPUT_FOLDER, + OPTION_ASSET_SEARCH_PATH, + OPTION_GDT_SEARCH_PATH, + OPTION_SOURCE_SEARCH_PATH, + OPTION_LOAD, + OPTION_MENU_PERMISSIVE, + OPTION_MENU_NO_OPTIMIZATION}; LinkerArgs::LinkerArgs() - : m_argument_parser(COMMAND_LINE_OPTIONS, std::extent::value), - m_base_pattern(R"(\?base\?)"), - m_game_pattern(R"(\?game\?)"), - m_project_pattern(R"(\?project\?)"), - m_base_folder_depends_on_project(false), - m_out_folder_depends_on_project(false), - m_verbose(false) -{ -} - -void LinkerArgs::PrintUsage() -{ - UsageInformation usage("Linker.exe"); + : m_argument_parser(COMMAND_LINE_OPTIONS, std::extent::value), m_base_pattern(R"(\?base\?)"), m_game_pattern(R"(\?game\?)"), + m_project_pattern(R"(\?project\?)"), m_base_folder_depends_on_project(false), m_out_folder_depends_on_project(false), m_verbose(false) {} - for (const auto* commandLineOption : COMMAND_LINE_OPTIONS) - { - usage.AddCommandLineOption(commandLineOption); - } +void LinkerArgs::PrintUsage() { + UsageInformation usage("Linker.exe"); - usage.AddArgument("projectName"); - usage.SetVariableArguments(true); + for (const auto *commandLineOption : COMMAND_LINE_OPTIONS) { + usage.AddCommandLineOption(commandLineOption); + } - usage.Print(); -} + usage.AddArgument("projectName"); + usage.SetVariableArguments(true); -void LinkerArgs::SetVerbose(const bool isVerbose) -{ - m_verbose = isVerbose; - ObjLoading::Configuration.Verbose = isVerbose; - ObjWriting::Configuration.Verbose = isVerbose; + usage.Print(); } -std::string LinkerArgs::GetBasePathForProject(const std::string& projectName) const -{ - return std::regex_replace(m_base_folder, m_project_pattern, projectName); +void LinkerArgs::SetVerbose(const bool isVerbose) { + m_verbose = isVerbose; + ObjLoading::Configuration.Verbose = isVerbose; + ObjWriting::Configuration.Verbose = isVerbose; } -void LinkerArgs::SetDefaultBasePath() -{ - const auto currentDir = fs::absolute(fs::current_path()); - - if (currentDir.filename() == "bin") - { - m_base_folder = currentDir.parent_path().string(); - } - else - { - m_base_folder = currentDir.string(); - } +std::string LinkerArgs::GetBasePathForProject(const std::string &projectName) const { + return std::regex_replace(m_base_folder, m_project_pattern, projectName); } -std::set LinkerArgs::GetProjectIndependentSearchPaths(const std::set& set) const -{ - std::set out; - - for (const auto& path : set) - { - if (path.find(PATTERN_GAME) != std::string::npos) - continue; - if (path.find(PATTERN_PROJECT) != std::string::npos) - continue; - - if (path.find(PATTERN_BASE) != std::string::npos) - { - if (m_base_folder_depends_on_project) - continue; - - out.emplace(std::regex_replace(path, m_base_pattern, m_base_folder)); - } - else - { - out.emplace(path); - } - } +void LinkerArgs::SetDefaultBasePath() { + const auto currentDir = fs::absolute(fs::current_path()); - return out; + if (currentDir.filename() == "bin") { + m_base_folder = currentDir.parent_path().string(); + } else { + m_base_folder = currentDir.string(); + } } -std::set LinkerArgs::GetSearchPathsForProject(const std::set& set, const std::string& gameName, const std::string& projectName) const -{ - std::set out; - const auto basePath = GetBasePathForProject(projectName); - - for (const auto& path : set) - { - if (path.find(PATTERN_GAME) == std::string::npos - && path.find(PATTERN_PROJECT) == std::string::npos - && (!m_base_folder_depends_on_project || path.find(PATTERN_BASE) == std::string::npos)) - { - continue; - } - - out.emplace(std::regex_replace(std::regex_replace(std::regex_replace(path, m_project_pattern, projectName), m_game_pattern, gameName), m_base_pattern, basePath)); - } - - return out; -} +std::set LinkerArgs::GetProjectIndependentSearchPaths(const std::set &set) const { + std::set out; -bool LinkerArgs::ParseArgs(const int argc, const char** argv) -{ - if (!m_argument_parser.ParseArguments(argc - 1, &argv[1])) - { - PrintUsage(); - return false; - } + for (const auto &path : set) { + if (path.find(PATTERN_GAME) != std::string::npos) + continue; + if (path.find(PATTERN_PROJECT) != std::string::npos) + continue; - // Check if the user requested help - if (m_argument_parser.IsOptionSpecified(OPTION_HELP)) - { - PrintUsage(); - return false; - } + if (path.find(PATTERN_BASE) != std::string::npos) { + if (m_base_folder_depends_on_project) + continue; - m_projects_to_build = m_argument_parser.GetArguments(); - if (m_projects_to_build.empty()) - { - // No projects to build specified... - PrintUsage(); - return false; + out.emplace(std::regex_replace(path, m_base_pattern, m_base_folder)); + } else { + out.emplace(path); } + } - // -v; --verbose - SetVerbose(m_argument_parser.IsOptionSpecified(OPTION_VERBOSE)); - - // b; --base-folder - if (m_argument_parser.IsOptionSpecified(OPTION_BASE_FOLDER)) - m_base_folder = m_argument_parser.GetValueForOption(OPTION_BASE_FOLDER); - else - SetDefaultBasePath(); - m_base_folder_depends_on_project = m_base_folder.find(PATTERN_GAME) != std::string::npos || m_base_folder.find(PATTERN_PROJECT) != std::string::npos; - - // --output-folder - if (m_argument_parser.IsOptionSpecified(OPTION_OUTPUT_FOLDER)) - m_out_folder = m_argument_parser.GetValueForOption(OPTION_OUTPUT_FOLDER); - else - m_out_folder = DEFAULT_OUTPUT_FOLDER; - m_out_folder_depends_on_project = m_out_folder.find(PATTERN_PROJECT) != std::string::npos; - - // --asset-search-path - if (m_argument_parser.IsOptionSpecified(OPTION_ASSET_SEARCH_PATH)) - { - if (!FileUtils::ParsePathsString(m_argument_parser.GetValueForOption(OPTION_ASSET_SEARCH_PATH), m_asset_search_paths)) - return false; - } - else - { - if (!FileUtils::ParsePathsString(DEFAULT_ASSET_SEARCH_PATH, m_asset_search_paths)) - return false; - } + return out; +} - // --gdt-search-path - if (m_argument_parser.IsOptionSpecified(OPTION_GDT_SEARCH_PATH)) - { - if (!FileUtils::ParsePathsString(m_argument_parser.GetValueForOption(OPTION_GDT_SEARCH_PATH), m_gdt_search_paths)) - return false; - } - else - { - if (!FileUtils::ParsePathsString(DEFAULT_GDT_SEARCH_PATH, m_gdt_search_paths)) - return false; - } +std::set LinkerArgs::GetSearchPathsForProject(const std::set &set, const std::string &gameName, + const std::string &projectName) const { + std::set out; + const auto basePath = GetBasePathForProject(projectName); - // --source-search-path - if (m_argument_parser.IsOptionSpecified(OPTION_SOURCE_SEARCH_PATH)) - { - if (!FileUtils::ParsePathsString(m_argument_parser.GetValueForOption(OPTION_SOURCE_SEARCH_PATH), m_source_search_paths)) - return false; + for (const auto &path : set) { + if (path.find(PATTERN_GAME) == std::string::npos && path.find(PATTERN_PROJECT) == std::string::npos && + (!m_base_folder_depends_on_project || path.find(PATTERN_BASE) == std::string::npos)) { + continue; } - else - { - if (!FileUtils::ParsePathsString(DEFAULT_SOURCE_SEARCH_PATH, m_source_search_paths)) - return false; - } - - // -l; --load - if (m_argument_parser.IsOptionSpecified(OPTION_LOAD)) - m_zones_to_load = m_argument_parser.GetParametersForOption(OPTION_LOAD); - // --menu-permissive - if (m_argument_parser.IsOptionSpecified(OPTION_MENU_PERMISSIVE)) - ObjLoading::Configuration.MenuPermissiveParsing = true; + out.emplace( + std::regex_replace(std::regex_replace(std::regex_replace(path, m_project_pattern, projectName), m_game_pattern, gameName), m_base_pattern, basePath)); + } - // --menu-no-optimization - if (m_argument_parser.IsOptionSpecified(OPTION_MENU_NO_OPTIMIZATION)) - ObjLoading::Configuration.MenuNoOptimization = true; - - return true; + return out; } -std::string LinkerArgs::GetOutputFolderPathForProject(const std::string& projectName) const -{ - return std::regex_replace(std::regex_replace(m_out_folder, m_project_pattern, projectName), m_base_pattern, GetBasePathForProject(projectName)); +bool LinkerArgs::ParseArgs(const int argc, const char **argv) { + if (!m_argument_parser.ParseArguments(argc - 1, &argv[1])) { + PrintUsage(); + return false; + } + + // Check if the user requested help + if (m_argument_parser.IsOptionSpecified(OPTION_HELP)) { + PrintUsage(); + return false; + } + + m_projects_to_build = m_argument_parser.GetArguments(); + if (m_projects_to_build.empty()) { + // No projects to build specified... + PrintUsage(); + return false; + } + + // -v; --verbose + SetVerbose(m_argument_parser.IsOptionSpecified(OPTION_VERBOSE)); + + // b; --base-folder + if (m_argument_parser.IsOptionSpecified(OPTION_BASE_FOLDER)) + m_base_folder = m_argument_parser.GetValueForOption(OPTION_BASE_FOLDER); + else + SetDefaultBasePath(); + m_base_folder_depends_on_project = m_base_folder.find(PATTERN_GAME) != std::string::npos || m_base_folder.find(PATTERN_PROJECT) != std::string::npos; + + // --output-folder + if (m_argument_parser.IsOptionSpecified(OPTION_OUTPUT_FOLDER)) + m_out_folder = m_argument_parser.GetValueForOption(OPTION_OUTPUT_FOLDER); + else + m_out_folder = DEFAULT_OUTPUT_FOLDER; + m_out_folder_depends_on_project = m_out_folder.find(PATTERN_PROJECT) != std::string::npos; + + // --asset-search-path + if (m_argument_parser.IsOptionSpecified(OPTION_ASSET_SEARCH_PATH)) { + if (!FileUtils::ParsePathsString(m_argument_parser.GetValueForOption(OPTION_ASSET_SEARCH_PATH), m_asset_search_paths)) + return false; + } else { + if (!FileUtils::ParsePathsString(DEFAULT_ASSET_SEARCH_PATH, m_asset_search_paths)) + return false; + } + + // --gdt-search-path + if (m_argument_parser.IsOptionSpecified(OPTION_GDT_SEARCH_PATH)) { + if (!FileUtils::ParsePathsString(m_argument_parser.GetValueForOption(OPTION_GDT_SEARCH_PATH), m_gdt_search_paths)) + return false; + } else { + if (!FileUtils::ParsePathsString(DEFAULT_GDT_SEARCH_PATH, m_gdt_search_paths)) + return false; + } + + // --source-search-path + if (m_argument_parser.IsOptionSpecified(OPTION_SOURCE_SEARCH_PATH)) { + if (!FileUtils::ParsePathsString(m_argument_parser.GetValueForOption(OPTION_SOURCE_SEARCH_PATH), m_source_search_paths)) + return false; + } else { + if (!FileUtils::ParsePathsString(DEFAULT_SOURCE_SEARCH_PATH, m_source_search_paths)) + return false; + } + + // -l; --load + if (m_argument_parser.IsOptionSpecified(OPTION_LOAD)) + m_zones_to_load = m_argument_parser.GetParametersForOption(OPTION_LOAD); + + // --menu-permissive + if (m_argument_parser.IsOptionSpecified(OPTION_MENU_PERMISSIVE)) + ObjLoading::Configuration.MenuPermissiveParsing = true; + + // --menu-no-optimization + if (m_argument_parser.IsOptionSpecified(OPTION_MENU_NO_OPTIMIZATION)) + ObjLoading::Configuration.MenuNoOptimization = true; + + return true; } -std::set LinkerArgs::GetProjectIndependentAssetSearchPaths() const -{ - return GetProjectIndependentSearchPaths(m_asset_search_paths); +std::string LinkerArgs::GetOutputFolderPathForProject(const std::string &projectName) const { + return std::regex_replace(std::regex_replace(m_out_folder, m_project_pattern, projectName), m_base_pattern, GetBasePathForProject(projectName)); } -std::set LinkerArgs::GetProjectIndependentGdtSearchPaths() const -{ - return GetProjectIndependentSearchPaths(m_gdt_search_paths); -} +std::set LinkerArgs::GetProjectIndependentAssetSearchPaths() const { return GetProjectIndependentSearchPaths(m_asset_search_paths); } -std::set LinkerArgs::GetProjectIndependentSourceSearchPaths() const -{ - return GetProjectIndependentSearchPaths(m_source_search_paths); -} +std::set LinkerArgs::GetProjectIndependentGdtSearchPaths() const { return GetProjectIndependentSearchPaths(m_gdt_search_paths); } + +std::set LinkerArgs::GetProjectIndependentSourceSearchPaths() const { return GetProjectIndependentSearchPaths(m_source_search_paths); } -std::set LinkerArgs::GetAssetSearchPathsForProject(const std::string& gameName, const std::string& projectName) const -{ - return GetSearchPathsForProject(m_asset_search_paths, gameName, projectName); +std::set LinkerArgs::GetAssetSearchPathsForProject(const std::string &gameName, const std::string &projectName) const { + return GetSearchPathsForProject(m_asset_search_paths, gameName, projectName); } -std::set LinkerArgs::GetGdtSearchPathsForProject(const std::string& gameName, const std::string& projectName) const -{ - return GetSearchPathsForProject(m_gdt_search_paths, gameName, projectName); +std::set LinkerArgs::GetGdtSearchPathsForProject(const std::string &gameName, const std::string &projectName) const { + return GetSearchPathsForProject(m_gdt_search_paths, gameName, projectName); } -std::set LinkerArgs::GetSourceSearchPathsForProject(const std::string& projectName) const -{ - return GetSearchPathsForProject(m_source_search_paths, "", projectName); +std::set LinkerArgs::GetSourceSearchPathsForProject(const std::string &projectName) const { + return GetSearchPathsForProject(m_source_search_paths, "", projectName); } diff --git a/src/Linker/LinkerArgs.h b/src/Linker/LinkerArgs.h index 6247724ee..46d486460 100644 --- a/src/Linker/LinkerArgs.h +++ b/src/Linker/LinkerArgs.h @@ -1,74 +1,74 @@ #pragma once -#include -#include #include +#include +#include -#include "Utils/ClassUtils.h" #include "Utils/Arguments/ArgumentParser.h" +#include "Utils/ClassUtils.h" #include "Zone/Zone.h" -class LinkerArgs -{ +class LinkerArgs { public: - static constexpr const char* PATTERN_BASE = "?base?"; - static constexpr const char* PATTERN_GAME = "?game?"; - static constexpr const char* PATTERN_PROJECT = "?project?"; + static constexpr const char *PATTERN_BASE = "?base?"; + static constexpr const char *PATTERN_GAME = "?game?"; + static constexpr const char *PATTERN_PROJECT = "?project?"; - static constexpr const char* DEFAULT_BASE_FOLDER = "."; - static constexpr const char* DEFAULT_BASE_FOLDER_MOD_TOOLS = ".."; - static constexpr const char* DEFAULT_OUTPUT_FOLDER = "?base?/zone_out/?project?"; - static constexpr const char* DEFAULT_ASSET_SEARCH_PATH = "?base?/raw;?base?/raw/?game?;?base?/zone_raw/?project?"; - static constexpr const char* DEFAULT_GDT_SEARCH_PATH = "?base?/source_data;?base?/zone_raw/?project?/source_data"; - static constexpr const char* DEFAULT_SOURCE_SEARCH_PATH = "?base?/zone_source;?base?/zone_raw/?project?/zone_source"; + static constexpr const char *DEFAULT_BASE_FOLDER = "."; + static constexpr const char *DEFAULT_BASE_FOLDER_MOD_TOOLS = ".."; + static constexpr const char *DEFAULT_OUTPUT_FOLDER = "?base?/zone_out/?project?"; + static constexpr const char *DEFAULT_ASSET_SEARCH_PATH = "?base?/raw;?base?/raw/?game?;?base?/zone_raw/?project?"; + static constexpr const char *DEFAULT_GDT_SEARCH_PATH = "?base?/source_data;?base?/zone_raw/?project?/source_data"; + static constexpr const char *DEFAULT_SOURCE_SEARCH_PATH = "?base?/zone_source;?base?/zone_raw/?project?/zone_source"; private: - ArgumentParser m_argument_parser; - std::regex m_base_pattern; - std::regex m_game_pattern; - std::regex m_project_pattern; + ArgumentParser m_argument_parser; + std::regex m_base_pattern; + std::regex m_game_pattern; + std::regex m_project_pattern; - /** - * \brief Prints a command line usage help text for the Linker tool to stdout. - */ - static void PrintUsage(); + /** + * \brief Prints a command line usage help text for the Linker tool to stdout. + */ + static void PrintUsage(); - void SetVerbose(bool isVerbose); + void SetVerbose(bool isVerbose); - _NODISCARD std::string GetBasePathForProject(const std::string& projectName) const; - void SetDefaultBasePath(); - _NODISCARD std::set GetProjectIndependentSearchPaths(const std::set& set) const; - _NODISCARD std::set GetSearchPathsForProject(const std::set& set, const std::string& gameName, const std::string& projectName) const; + _NODISCARD std::string GetBasePathForProject(const std::string &projectName) const; + void SetDefaultBasePath(); + _NODISCARD std::set GetProjectIndependentSearchPaths(const std::set &set) const; + _NODISCARD std::set GetSearchPathsForProject(const std::set &set, const std::string &gameName, + const std::string &projectName) const; public: - std::vector m_zones_to_load; - std::vector m_projects_to_build; - - std::string m_base_folder; - std::string m_out_folder; - bool m_base_folder_depends_on_project; - bool m_out_folder_depends_on_project; + std::vector m_zones_to_load; + std::vector m_projects_to_build; + + std::string m_base_folder; + std::string m_out_folder; + bool m_base_folder_depends_on_project; + bool m_out_folder_depends_on_project; + + std::set m_asset_search_paths; + std::set m_gdt_search_paths; + std::set m_source_search_paths; - std::set m_asset_search_paths; - std::set m_gdt_search_paths; - std::set m_source_search_paths; + bool m_verbose; - bool m_verbose; + LinkerArgs(); + bool ParseArgs(int argc, const char **argv); - LinkerArgs(); - bool ParseArgs(int argc, const char** argv); + /** + * \brief Converts the output path specified by command line arguments to a path applies for the specified project. + * \param projectName The name of the project to resolve the path input for. + * \return An output path for the project based on the user input. + */ + _NODISCARD std::string GetOutputFolderPathForProject(const std::string &projectName) const; - /** - * \brief Converts the output path specified by command line arguments to a path applies for the specified project. - * \param projectName The name of the project to resolve the path input for. - * \return An output path for the project based on the user input. - */ - _NODISCARD std::string GetOutputFolderPathForProject(const std::string& projectName) const; + _NODISCARD std::set GetProjectIndependentAssetSearchPaths() const; + _NODISCARD std::set GetProjectIndependentGdtSearchPaths() const; + _NODISCARD std::set GetProjectIndependentSourceSearchPaths() const; - _NODISCARD std::set GetProjectIndependentAssetSearchPaths() const; - _NODISCARD std::set GetProjectIndependentGdtSearchPaths() const; - _NODISCARD std::set GetProjectIndependentSourceSearchPaths() const; - - _NODISCARD std::set GetAssetSearchPathsForProject(const std::string& gameName, const std::string& projectName) const; - _NODISCARD std::set GetGdtSearchPathsForProject(const std::string& gameName, const std::string& projectName) const; - _NODISCARD std::set GetSourceSearchPathsForProject(const std::string& projectName) const; + _NODISCARD std::set GetAssetSearchPathsForProject(const std::string &gameName, const std::string &projectName) const; + _NODISCARD std::set GetGdtSearchPathsForProject(const std::string &gameName, const std::string &projectName) const; + _NODISCARD std::set GetSourceSearchPathsForProject(const std::string &projectName) const; }; diff --git a/src/Linker/ZoneCreation/IZoneCreator.h b/src/Linker/ZoneCreation/IZoneCreator.h index 52e2d2007..2a8191c1a 100644 --- a/src/Linker/ZoneCreation/IZoneCreator.h +++ b/src/Linker/ZoneCreation/IZoneCreator.h @@ -2,19 +2,18 @@ #include #include "Utils/ClassUtils.h" -#include "ZoneCreationContext.h" #include "Zone/Zone.h" +#include "ZoneCreationContext.h" -class IZoneCreator -{ +class IZoneCreator { public: - IZoneCreator() = default; - virtual ~IZoneCreator() = default; - IZoneCreator(const IZoneCreator& other) = default; - IZoneCreator(IZoneCreator&& other) noexcept = default; - IZoneCreator& operator=(const IZoneCreator& other) = default; - IZoneCreator& operator=(IZoneCreator&& other) noexcept = default; + IZoneCreator() = default; + virtual ~IZoneCreator() = default; + IZoneCreator(const IZoneCreator &other) = default; + IZoneCreator(IZoneCreator &&other) noexcept = default; + IZoneCreator &operator=(const IZoneCreator &other) = default; + IZoneCreator &operator=(IZoneCreator &&other) noexcept = default; - _NODISCARD virtual bool SupportsGame(const std::string& gameName) const = 0; - _NODISCARD virtual std::unique_ptr CreateZoneForDefinition(ZoneCreationContext& context) const = 0; + _NODISCARD virtual bool SupportsGame(const std::string &gameName) const = 0; + _NODISCARD virtual std::unique_ptr CreateZoneForDefinition(ZoneCreationContext &context) const = 0; }; diff --git a/src/Linker/ZoneCreation/ZoneCreationContext.cpp b/src/Linker/ZoneCreation/ZoneCreationContext.cpp index 481816943..eefdd50e7 100644 --- a/src/Linker/ZoneCreation/ZoneCreationContext.cpp +++ b/src/Linker/ZoneCreation/ZoneCreationContext.cpp @@ -1,13 +1,6 @@ #include "ZoneCreationContext.h" -ZoneCreationContext::ZoneCreationContext() - : m_asset_search_path(nullptr), - m_definition(nullptr) -{ -} +ZoneCreationContext::ZoneCreationContext() : m_asset_search_path(nullptr), m_definition(nullptr) {} -ZoneCreationContext::ZoneCreationContext(ISearchPath* assetSearchPath, ZoneDefinition* definition) - : m_asset_search_path(assetSearchPath), - m_definition(definition) -{ -} +ZoneCreationContext::ZoneCreationContext(ISearchPath *assetSearchPath, ZoneDefinition *definition) + : m_asset_search_path(assetSearchPath), m_definition(definition) {} diff --git a/src/Linker/ZoneCreation/ZoneCreationContext.h b/src/Linker/ZoneCreation/ZoneCreationContext.h index 2db20e1d4..0fb2c03a3 100644 --- a/src/Linker/ZoneCreation/ZoneCreationContext.h +++ b/src/Linker/ZoneCreation/ZoneCreationContext.h @@ -1,23 +1,22 @@ #pragma once -#include -#include #include +#include #include +#include -#include "SearchPath/ISearchPath.h" #include "Obj/Gdt/Gdt.h" +#include "SearchPath/ISearchPath.h" #include "Zone/AssetList/AssetList.h" #include "Zone/Definition/ZoneDefinition.h" -class ZoneCreationContext -{ +class ZoneCreationContext { public: - std::string m_game_name; - ISearchPath* m_asset_search_path; - ZoneDefinition* m_definition; - std::vector> m_gdt_files; - std::vector m_ignored_assets; + std::string m_game_name; + ISearchPath *m_asset_search_path; + ZoneDefinition *m_definition; + std::vector> m_gdt_files; + std::vector m_ignored_assets; - ZoneCreationContext(); - ZoneCreationContext(ISearchPath* assetSearchPath, ZoneDefinition* definition); + ZoneCreationContext(); + ZoneCreationContext(ISearchPath *assetSearchPath, ZoneDefinition *definition); }; diff --git a/src/Linker/main.cpp b/src/Linker/main.cpp index 6e78bec12..a40d8dcf1 100644 --- a/src/Linker/main.cpp +++ b/src/Linker/main.cpp @@ -1,8 +1,7 @@ #include "Linker.h" -int main(const int argc, const char** argv) -{ - Linker linker; +int main(const int argc, const char **argv) { + Linker linker; - return linker.Start(argc, argv) ? 0 : 1; + return linker.Start(argc, argv) ? 0 : 1; } diff --git a/src/ObjCommon/Csv/CsvStream.cpp b/src/ObjCommon/Csv/CsvStream.cpp index bf3747b02..12ea7b104 100644 --- a/src/ObjCommon/Csv/CsvStream.cpp +++ b/src/ObjCommon/Csv/CsvStream.cpp @@ -4,120 +4,87 @@ constexpr char CSV_SEPARATOR = ','; -CsvInputStream::CsvInputStream(std::istream& stream) - : m_stream(stream) -{ -} - -bool CsvInputStream::NextRow(std::vector& out) const -{ - if (!out.empty()) - out.clear(); - - auto c = m_stream.get(); - const auto isEof = c == EOF; - std::ostringstream col; - while(c != EOF) - { - if(c == CSV_SEPARATOR) - { - out.emplace_back(col.str()); - col.clear(); - col.str(std::string()); - } - else if(c == '\r') - { - c = m_stream.get(); - if (c == '\n') - break; - col << '\r'; - } - else if(c == '\n') - { - break; - } - else - { - col << static_cast(c); - } - - c = m_stream.get(); +CsvInputStream::CsvInputStream(std::istream &stream) : m_stream(stream) {} + +bool CsvInputStream::NextRow(std::vector &out) const { + if (!out.empty()) + out.clear(); + + auto c = m_stream.get(); + const auto isEof = c == EOF; + std::ostringstream col; + while (c != EOF) { + if (c == CSV_SEPARATOR) { + out.emplace_back(col.str()); + col.clear(); + col.str(std::string()); + } else if (c == '\r') { + c = m_stream.get(); + if (c == '\n') + break; + col << '\r'; + } else if (c == '\n') { + break; + } else { + col << static_cast(c); } - if(!isEof) - { - out.emplace_back(col.str()); - } + c = m_stream.get(); + } - return !isEof; -} + if (!isEof) { + out.emplace_back(col.str()); + } -CsvOutputStream::CsvOutputStream(std::ostream& stream) - : m_stream(stream), - m_column_count(0), - m_current_column(0), - m_first_row(true) -{ + return !isEof; } -void CsvOutputStream::WriteColumn(const std::string& value) -{ - if (m_current_column++ > 0) - m_stream << CSV_SEPARATOR; - - auto containsSeparator = false; - auto containsQuote = false; - for (const auto& c : value) - { - if (c == '"') - { - containsQuote = true; - break; - } - - if (c == CSV_SEPARATOR) - containsSeparator = true; - } +CsvOutputStream::CsvOutputStream(std::ostream &stream) : m_stream(stream), m_column_count(0), m_current_column(0), m_first_row(true) {} - if (containsQuote) - { - m_stream << "\""; - for (const auto& c : value) - { - if (c == '"') - m_stream << "\"\""; - else - m_stream << c; - } - - m_stream << "\""; - } - else if (containsSeparator) - { - m_stream << "\"" << value << "\""; +void CsvOutputStream::WriteColumn(const std::string &value) { + if (m_current_column++ > 0) + m_stream << CSV_SEPARATOR; + + auto containsSeparator = false; + auto containsQuote = false; + for (const auto &c : value) { + if (c == '"') { + containsQuote = true; + break; } - else - { - m_stream << value; + + if (c == CSV_SEPARATOR) + containsSeparator = true; + } + + if (containsQuote) { + m_stream << "\""; + for (const auto &c : value) { + if (c == '"') + m_stream << "\"\""; + else + m_stream << c; } + + m_stream << "\""; + } else if (containsSeparator) { + m_stream << "\"" << value << "\""; + } else { + m_stream << value; + } } -void CsvOutputStream::NextRow() -{ - if (m_first_row) - { - m_first_row = false; - m_column_count = m_current_column; - } - else - { - while (m_current_column < m_column_count) - { - m_stream << CSV_SEPARATOR; - m_current_column++; - } +void CsvOutputStream::NextRow() { + if (m_first_row) { + m_first_row = false; + m_column_count = m_current_column; + } else { + while (m_current_column < m_column_count) { + m_stream << CSV_SEPARATOR; + m_current_column++; } + } - m_stream << "\n"; - m_current_column = 0; + m_stream << "\n"; + m_current_column = 0; } diff --git a/src/ObjCommon/Csv/CsvStream.h b/src/ObjCommon/Csv/CsvStream.h index 1e039d2e6..3099521e9 100644 --- a/src/ObjCommon/Csv/CsvStream.h +++ b/src/ObjCommon/Csv/CsvStream.h @@ -3,26 +3,24 @@ #include #include -class CsvInputStream -{ - std::istream& m_stream; +class CsvInputStream { + std::istream &m_stream; public: - explicit CsvInputStream(std::istream& stream); + explicit CsvInputStream(std::istream &stream); - bool NextRow(std::vector& out) const; + bool NextRow(std::vector &out) const; }; -class CsvOutputStream -{ - std::ostream& m_stream; - unsigned m_column_count; - unsigned m_current_column; - bool m_first_row; +class CsvOutputStream { + std::ostream &m_stream; + unsigned m_column_count; + unsigned m_current_column; + bool m_first_row; public: - explicit CsvOutputStream(std::ostream& stream); + explicit CsvOutputStream(std::ostream &stream); - void WriteColumn(const std::string& value); - void NextRow(); + void WriteColumn(const std::string &value); + void NextRow(); }; \ No newline at end of file diff --git a/src/ObjCommon/Game/IW3/MaterialConstantsIW3.h b/src/ObjCommon/Game/IW3/MaterialConstantsIW3.h index 0c22c5c49..4f9338c65 100644 --- a/src/ObjCommon/Game/IW3/MaterialConstantsIW3.h +++ b/src/ObjCommon/Game/IW3/MaterialConstantsIW3.h @@ -1,43 +1,13 @@ #pragma once -#include #include +#include #include "Game/IW3/IW3.h" -namespace IW3 -{ - inline const char* surfaceTypeNames[] - { - "default", - "bark", - "brick", - "carpet", - "cloth", - "concrete", - "dirt", - "flesh", - "foliage", - "glass", - "grass", - "gravel", - "ice", - "metal", - "mud", - "paper", - "plaster", - "rock", - "sand", - "snow", - "water", - "wood", - "asphalt", - "ceramic", - "plastic", - "rubber", - "cushion", - "fruit", - "paintedmetal" - }; - static_assert(std::extent_v == SURF_TYPE_NUM); -} +namespace IW3 { +inline const char *surfaceTypeNames[]{"default", "bark", "brick", "carpet", "cloth", "concrete", "dirt", "flesh", "foliage", "glass", + "grass", "gravel", "ice", "metal", "mud", "paper", "plaster", "rock", "sand", "snow", + "water", "wood", "asphalt", "ceramic", "plastic", "rubber", "cushion", "fruit", "paintedmetal"}; +static_assert(std::extent_v == SURF_TYPE_NUM); +} // namespace IW3 diff --git a/src/ObjCommon/Game/IW3/TechsetConstantsIW3.h b/src/ObjCommon/Game/IW3/TechsetConstantsIW3.h index 44a7878a2..f059b13ca 100644 --- a/src/ObjCommon/Game/IW3/TechsetConstantsIW3.h +++ b/src/ObjCommon/Game/IW3/TechsetConstantsIW3.h @@ -1,138 +1,79 @@ #pragma once -#include #include +#include #include "Game/IW3/CommonIW3.h" #include "Game/IW3/IW3.h" -namespace IW3 -{ - inline const char* techniqueTypeNames[] - { - "depth prepass", - "build floatz", - "build shadowmap depth", - "build shadowmap color", - "unlit", - "emissive", - "emissive shadow", - "lit", - "lit sun", - "lit sun shadow", - "lit spot", - "lit spot shadow", - "lit omni", - "lit omni shadow", - "lit instanced", - "lit instanced sun", - "lit instanced sun shadow", - "lit instanced spot", - "lit instanced spot shadow", - "lit instanced omni", - "lit instanced omni shadow", - "light spot", - "light omni", - "light spot shadow", - "fakelight normal", - "fakelight view", - "sunlight preview", - "case texture", - "solid wireframe", - "shaded wireframe", - "shadowcookie caster", - "shadowcookie receiver", - "debug bumpmap", - "debug bumpmap instanced", - }; - static_assert(std::extent_v == TECHNIQUE_COUNT); +namespace IW3 { +inline const char *techniqueTypeNames[]{ + "depth prepass", + "build floatz", + "build shadowmap depth", + "build shadowmap color", + "unlit", + "emissive", + "emissive shadow", + "lit", + "lit sun", + "lit sun shadow", + "lit spot", + "lit spot shadow", + "lit omni", + "lit omni shadow", + "lit instanced", + "lit instanced sun", + "lit instanced sun shadow", + "lit instanced spot", + "lit instanced spot shadow", + "lit instanced omni", + "lit instanced omni shadow", + "light spot", + "light omni", + "light spot shadow", + "fakelight normal", + "fakelight view", + "sunlight preview", + "case texture", + "solid wireframe", + "shaded wireframe", + "shadowcookie caster", + "shadowcookie receiver", + "debug bumpmap", + "debug bumpmap instanced", +}; +static_assert(std::extent_v == TECHNIQUE_COUNT); - static const char* materialStreamDestinationNames[] - { - "position", - "normal", - "color[0]", - "color[1]", - "texcoord[0]", - "texcoord[1]", - "texcoord[2]", - "texcoord[3]", - "texcoord[4]", - "texcoord[5]", - "texcoord[6]", - "texcoord[7]", - }; - static_assert(std::extent_v == STREAM_DST_COUNT); +static const char *materialStreamDestinationNames[]{ + "position", "normal", "color[0]", "color[1]", "texcoord[0]", "texcoord[1]", + "texcoord[2]", "texcoord[3]", "texcoord[4]", "texcoord[5]", "texcoord[6]", "texcoord[7]", +}; +static_assert(std::extent_v == STREAM_DST_COUNT); - static const char* materialStreamSourceNames[] - { - "position", - "color", - "texcoord[0]", - "normal", - "tangent", - "texcoord[1]", - "texcoord[2]", - "normalTransform[0]", - "normalTransform[1]" - }; - static_assert(std::extent_v == STREAM_SRC_COUNT); +static const char *materialStreamSourceNames[]{ + "position", "color", "texcoord[0]", "normal", "tangent", "texcoord[1]", "texcoord[2]", "normalTransform[0]", "normalTransform[1]"}; +static_assert(std::extent_v == STREAM_SRC_COUNT); - static constexpr std::pair KnownMaterialSource(const char* name) - { - return std::make_pair(Common::R_HashString(name, 0u), name); - } +static constexpr std::pair KnownMaterialSource(const char *name) { return std::make_pair(Common::R_HashString(name, 0u), name); } - inline std::unordered_map knownMaterialSourceNames - { - KnownMaterialSource("colorMap"), - KnownMaterialSource("colorMap0"), - KnownMaterialSource("colorMap1"), - KnownMaterialSource("colorMap2"), - KnownMaterialSource("colorMap3"), - KnownMaterialSource("colorMap4"), - KnownMaterialSource("colorMap5"), - KnownMaterialSource("colorMap6"), - KnownMaterialSource("colorMap7"), - KnownMaterialSource("normalMap"), - KnownMaterialSource("normalMap0"), - KnownMaterialSource("normalMap1"), - KnownMaterialSource("normalMap2"), - KnownMaterialSource("normalMap3"), - KnownMaterialSource("normalMap4"), - KnownMaterialSource("normalMap5"), - KnownMaterialSource("normalMap6"), - KnownMaterialSource("normalMap7"), - KnownMaterialSource("specularMap"), - KnownMaterialSource("specularMap0"), - KnownMaterialSource("specularMap1"), - KnownMaterialSource("specularMap2"), - KnownMaterialSource("specularMap3"), - KnownMaterialSource("specularMap4"), - KnownMaterialSource("specularMap5"), - KnownMaterialSource("specularMap6"), - KnownMaterialSource("specularMap7"), - KnownMaterialSource("detailMap"), - KnownMaterialSource("detailMap0"), - KnownMaterialSource("detailMap1"), - KnownMaterialSource("detailMap2"), - KnownMaterialSource("detailMap3"), - KnownMaterialSource("detailMap4"), - KnownMaterialSource("detailMap5"), - KnownMaterialSource("detailMap6"), - KnownMaterialSource("detailMap7"), - KnownMaterialSource("attenuationMap"), - KnownMaterialSource("attenuationMap0"), - KnownMaterialSource("attenuationMap1"), - KnownMaterialSource("attenuationMap2"), - KnownMaterialSource("attenuationMap3"), - KnownMaterialSource("attenuationMap4"), - KnownMaterialSource("attenuationMap5"), - KnownMaterialSource("attenuationMap6"), - KnownMaterialSource("attenuationMap7"), - KnownMaterialSource("distortionScale"), - KnownMaterialSource("eyeOffsetParms"), - KnownMaterialSource("falloffBeginColor"), - KnownMaterialSource("falloffEndColor"), - }; -} +inline std::unordered_map knownMaterialSourceNames{ + KnownMaterialSource("colorMap"), KnownMaterialSource("colorMap0"), KnownMaterialSource("colorMap1"), + KnownMaterialSource("colorMap2"), KnownMaterialSource("colorMap3"), KnownMaterialSource("colorMap4"), + KnownMaterialSource("colorMap5"), KnownMaterialSource("colorMap6"), KnownMaterialSource("colorMap7"), + KnownMaterialSource("normalMap"), KnownMaterialSource("normalMap0"), KnownMaterialSource("normalMap1"), + KnownMaterialSource("normalMap2"), KnownMaterialSource("normalMap3"), KnownMaterialSource("normalMap4"), + KnownMaterialSource("normalMap5"), KnownMaterialSource("normalMap6"), KnownMaterialSource("normalMap7"), + KnownMaterialSource("specularMap"), KnownMaterialSource("specularMap0"), KnownMaterialSource("specularMap1"), + KnownMaterialSource("specularMap2"), KnownMaterialSource("specularMap3"), KnownMaterialSource("specularMap4"), + KnownMaterialSource("specularMap5"), KnownMaterialSource("specularMap6"), KnownMaterialSource("specularMap7"), + KnownMaterialSource("detailMap"), KnownMaterialSource("detailMap0"), KnownMaterialSource("detailMap1"), + KnownMaterialSource("detailMap2"), KnownMaterialSource("detailMap3"), KnownMaterialSource("detailMap4"), + KnownMaterialSource("detailMap5"), KnownMaterialSource("detailMap6"), KnownMaterialSource("detailMap7"), + KnownMaterialSource("attenuationMap"), KnownMaterialSource("attenuationMap0"), KnownMaterialSource("attenuationMap1"), + KnownMaterialSource("attenuationMap2"), KnownMaterialSource("attenuationMap3"), KnownMaterialSource("attenuationMap4"), + KnownMaterialSource("attenuationMap5"), KnownMaterialSource("attenuationMap6"), KnownMaterialSource("attenuationMap7"), + KnownMaterialSource("distortionScale"), KnownMaterialSource("eyeOffsetParms"), KnownMaterialSource("falloffBeginColor"), + KnownMaterialSource("falloffEndColor"), +}; +} // namespace IW3 diff --git a/src/ObjCommon/Game/IW4/InfoString/EnumStrings.h b/src/ObjCommon/Game/IW4/InfoString/EnumStrings.h index fce1bdc9d..714e1f971 100644 --- a/src/ObjCommon/Game/IW4/InfoString/EnumStrings.h +++ b/src/ObjCommon/Game/IW4/InfoString/EnumStrings.h @@ -1,195 +1,101 @@ #pragma once -namespace IW4 -{ - inline const char* szWeapTypeNames[] - { - "bullet", - "grenade", - "projectile", - "riotshield", - }; - - inline const char* szWeapClassNames[] - { - "rifle", - "sniper", - "mg", - "smg", - "spread", - "pistol", - "grenade", - "rocketlauncher", - "turret", - "throwingknife", - "non-player", - "item", - }; - - inline const char* szWeapOverlayReticleNames[] - { - "none", - "crosshair", - }; - - inline const char* szWeapInventoryTypeNames[] - { - "primary", - "offhand", - "item", - "altmode", - "exclusive", - "scavenger", - }; - - inline const char* szWeapFireTypeNames[] - { - "Full Auto", - "Single Shot", - "2-Round Burst", - "3-Round Burst", - "4-Round Burst", - "Double Barrel", - }; - - inline const char* penetrateTypeNames[] - { - "none", - "small", - "medium", - "large", - }; - - inline const char* impactTypeNames[] - { - "none", - "bullet_small", - "bullet_large", - "bullet_ap", - "bullet_explode", - "shotgun", - "shotgun_explode", - "grenade_bounce", - "grenade_explode", - "rocket_explode", - "projectile_dud", - }; - - inline const char* szWeapStanceNames[] - { - "stand", - "duck", - "prone", - }; - - inline const char* szProjectileExplosionNames[] - { - "grenade", - "rocket", - "flashbang", - "none", - "dud", - "smoke", - "heavy explosive", - }; - - inline const char* offhandClassNames[] - { - "None", - "Frag Grenade", - "Smoke Grenade", - "Flash Grenade", - "Throwing Knife", - "Other", - }; - - inline const char* playerAnimTypeNames[] - { - "none", - "other", - "pistol", - "smg", - "autorifle", - "mg", - "sniper", - "rocketlauncher", - "explosive", - "grenade", - "turret", - "c4", - "m203", - "hold", - "briefcase", - "riotshield", - "laptop", - "throwingknife", - }; - - inline const char* activeReticleNames[] - { - "None", - "Pip-On-A-Stick", - "Bouncing diamond", - }; - - inline const char* guidedMissileNames[] - { - "None", - "Sidewinder", - "Hellfire", - "Javelin", - }; - - inline const char* stickinessNames[] - { - "Don't stick", - "Stick to all", - "Stick to all, orient to surface", - "Stick to ground", - "Stick to ground, maintain yaw", - "Knife", - }; - - inline const char* overlayInterfaceNames[] - { - "None", - "Javelin", - "Turret Scope", - }; - - inline const char* ammoCounterClipNames[] - { - "None", - "Magazine", - "ShortMagazine", - "Shotgun", - "Rocket", - "Beltfed", - "AltWeapon", - }; - - inline const char* weapIconRatioNames[] - { - "1:1", - "2:1", - "4:1", - }; - - inline const char* s_vehicleClassNames[] - { - "4 wheel", - "tank", - "plane", - "boat", - "artillery", - "helicopter", - "snowmobile", - }; - - inline const char* s_vehicleAxleTypeNames[] - { - "front", - "rear", - "all", - }; -} +namespace IW4 { +inline const char *szWeapTypeNames[]{ + "bullet", + "grenade", + "projectile", + "riotshield", +}; + +inline const char *szWeapClassNames[]{ + "rifle", "sniper", "mg", "smg", "spread", "pistol", "grenade", "rocketlauncher", "turret", "throwingknife", "non-player", "item", +}; + +inline const char *szWeapOverlayReticleNames[]{ + "none", + "crosshair", +}; + +inline const char *szWeapInventoryTypeNames[]{ + "primary", "offhand", "item", "altmode", "exclusive", "scavenger", +}; + +inline const char *szWeapFireTypeNames[]{ + "Full Auto", "Single Shot", "2-Round Burst", "3-Round Burst", "4-Round Burst", "Double Barrel", +}; + +inline const char *penetrateTypeNames[]{ + "none", + "small", + "medium", + "large", +}; + +inline const char *impactTypeNames[]{ + "none", "bullet_small", "bullet_large", "bullet_ap", "bullet_explode", "shotgun", "shotgun_explode", + "grenade_bounce", "grenade_explode", "rocket_explode", "projectile_dud", +}; + +inline const char *szWeapStanceNames[]{ + "stand", + "duck", + "prone", +}; + +inline const char *szProjectileExplosionNames[]{ + "grenade", "rocket", "flashbang", "none", "dud", "smoke", "heavy explosive", +}; + +inline const char *offhandClassNames[]{ + "None", "Frag Grenade", "Smoke Grenade", "Flash Grenade", "Throwing Knife", "Other", +}; + +inline const char *playerAnimTypeNames[]{ + "none", "other", "pistol", "smg", "autorifle", "mg", "sniper", "rocketlauncher", "explosive", + "grenade", "turret", "c4", "m203", "hold", "briefcase", "riotshield", "laptop", "throwingknife", +}; + +inline const char *activeReticleNames[]{ + "None", + "Pip-On-A-Stick", + "Bouncing diamond", +}; + +inline const char *guidedMissileNames[]{ + "None", + "Sidewinder", + "Hellfire", + "Javelin", +}; + +inline const char *stickinessNames[]{ + "Don't stick", "Stick to all", "Stick to all, orient to surface", "Stick to ground", "Stick to ground, maintain yaw", "Knife", +}; + +inline const char *overlayInterfaceNames[]{ + "None", + "Javelin", + "Turret Scope", +}; + +inline const char *ammoCounterClipNames[]{ + "None", "Magazine", "ShortMagazine", "Shotgun", "Rocket", "Beltfed", "AltWeapon", +}; + +inline const char *weapIconRatioNames[]{ + "1:1", + "2:1", + "4:1", +}; + +inline const char *s_vehicleClassNames[]{ + "4 wheel", "tank", "plane", "boat", "artillery", "helicopter", "snowmobile", +}; + +inline const char *s_vehicleAxleTypeNames[]{ + "front", + "rear", + "all", +}; +} // namespace IW4 diff --git a/src/ObjCommon/Game/IW4/InfoString/PhysPresetFields.h b/src/ObjCommon/Game/IW4/InfoString/PhysPresetFields.h index be5a6f7bc..dbcf0665e 100644 --- a/src/ObjCommon/Game/IW4/InfoString/PhysPresetFields.h +++ b/src/ObjCommon/Game/IW4/InfoString/PhysPresetFields.h @@ -1,20 +1,18 @@ #pragma once #include "Game/IW4/IW4.h" -namespace IW4 -{ - inline cspField_t phys_preset_fields[] - { - { "mass", offsetof(PhysPresetInfo, mass), CSPFT_FLOAT }, - { "bounce", offsetof(PhysPresetInfo, bounce), CSPFT_FLOAT }, - { "friction", offsetof(PhysPresetInfo, friction), CSPFT_FLOAT }, - { "isFrictionInfinity", offsetof(PhysPresetInfo, isFrictionInfinity), CSPFT_QBOOLEAN }, - { "bulletForceScale", offsetof(PhysPresetInfo, bulletForceScale), CSPFT_FLOAT }, - { "explosiveForceScale", offsetof(PhysPresetInfo, explosiveForceScale), CSPFT_FLOAT }, - { "sndAliasPrefix", offsetof(PhysPresetInfo, sndAliasPrefix), CSPFT_STRING }, - { "piecesSpreadFraction", offsetof(PhysPresetInfo, piecesSpreadFraction), CSPFT_FLOAT }, - { "piecesUpwardVelocity", offsetof(PhysPresetInfo, piecesUpwardVelocity), CSPFT_FLOAT }, - { "tempDefaultToCylinder", offsetof(PhysPresetInfo, tempDefaultToCylinder), CSPFT_QBOOLEAN }, - { "perSurfaceSndAlias", offsetof(PhysPresetInfo, perSurfaceSndAlias), CSPFT_QBOOLEAN }, - }; +namespace IW4 { +inline cspField_t phys_preset_fields[]{ + {"mass", offsetof(PhysPresetInfo, mass), CSPFT_FLOAT }, + {"bounce", offsetof(PhysPresetInfo, bounce), CSPFT_FLOAT }, + {"friction", offsetof(PhysPresetInfo, friction), CSPFT_FLOAT }, + {"isFrictionInfinity", offsetof(PhysPresetInfo, isFrictionInfinity), CSPFT_QBOOLEAN}, + {"bulletForceScale", offsetof(PhysPresetInfo, bulletForceScale), CSPFT_FLOAT }, + {"explosiveForceScale", offsetof(PhysPresetInfo, explosiveForceScale), CSPFT_FLOAT }, + {"sndAliasPrefix", offsetof(PhysPresetInfo, sndAliasPrefix), CSPFT_STRING }, + {"piecesSpreadFraction", offsetof(PhysPresetInfo, piecesSpreadFraction), CSPFT_FLOAT }, + {"piecesUpwardVelocity", offsetof(PhysPresetInfo, piecesUpwardVelocity), CSPFT_FLOAT }, + {"tempDefaultToCylinder", offsetof(PhysPresetInfo, tempDefaultToCylinder), CSPFT_QBOOLEAN}, + {"perSurfaceSndAlias", offsetof(PhysPresetInfo, perSurfaceSndAlias), CSPFT_QBOOLEAN}, +}; } \ No newline at end of file diff --git a/src/ObjCommon/Game/IW4/InfoString/TracerFields.h b/src/ObjCommon/Game/IW4/InfoString/TracerFields.h index bba335658..56987674c 100644 --- a/src/ObjCommon/Game/IW4/InfoString/TracerFields.h +++ b/src/ObjCommon/Game/IW4/InfoString/TracerFields.h @@ -1,36 +1,34 @@ #pragma once #include "Game/IW4/IW4.h" -namespace IW4 -{ - inline cspField_t tracer_fields[] - { - { "material", offsetof(TracerDef, material), CSPFT_MATERIAL }, - { "drawInterval", offsetof(TracerDef, drawInterval), CSPFT_INT }, - { "speed", offsetof(TracerDef, speed), CSPFT_FLOAT }, - { "beamLength", offsetof(TracerDef, beamLength), CSPFT_FLOAT }, - { "beamWidth", offsetof(TracerDef, beamWidth), CSPFT_FLOAT }, - { "screwRadius", offsetof(TracerDef, screwRadius), CSPFT_FLOAT }, - { "screwDist", offsetof(TracerDef, screwDist), CSPFT_FLOAT }, - { "colorR0", offsetof(TracerDef, colors[0][0]), CSPFT_FLOAT}, - { "colorG0", offsetof(TracerDef, colors[0][1]), CSPFT_FLOAT }, - { "colorB0", offsetof(TracerDef, colors[0][2]), CSPFT_FLOAT }, - { "colorA0", offsetof(TracerDef, colors[0][3]), CSPFT_FLOAT }, - { "colorR1", offsetof(TracerDef, colors[1][0]), CSPFT_FLOAT }, - { "colorG1", offsetof(TracerDef, colors[1][1]), CSPFT_FLOAT }, - { "colorB1", offsetof(TracerDef, colors[1][2]), CSPFT_FLOAT }, - { "colorA1", offsetof(TracerDef, colors[1][3]), CSPFT_FLOAT }, - { "colorR2", offsetof(TracerDef, colors[2][0]), CSPFT_FLOAT }, - { "colorG2", offsetof(TracerDef, colors[2][1]), CSPFT_FLOAT }, - { "colorB2", offsetof(TracerDef, colors[2][2]), CSPFT_FLOAT }, - { "colorA2", offsetof(TracerDef, colors[2][3]), CSPFT_FLOAT }, - { "colorR3", offsetof(TracerDef, colors[3][0]), CSPFT_FLOAT }, - { "colorG3", offsetof(TracerDef, colors[3][1]), CSPFT_FLOAT }, - { "colorB3", offsetof(TracerDef, colors[3][2]), CSPFT_FLOAT }, - { "colorA3", offsetof(TracerDef, colors[3][3]), CSPFT_FLOAT }, - { "colorR4", offsetof(TracerDef, colors[4][0]), CSPFT_FLOAT }, - { "colorG4", offsetof(TracerDef, colors[4][1]), CSPFT_FLOAT }, - { "colorB4", offsetof(TracerDef, colors[4][2]), CSPFT_FLOAT }, - { "colorA4", offsetof(TracerDef, colors[4][3]), CSPFT_FLOAT }, - }; +namespace IW4 { +inline cspField_t tracer_fields[]{ + {"material", offsetof(TracerDef, material), CSPFT_MATERIAL}, + {"drawInterval", offsetof(TracerDef, drawInterval), CSPFT_INT }, + {"speed", offsetof(TracerDef, speed), CSPFT_FLOAT }, + {"beamLength", offsetof(TracerDef, beamLength), CSPFT_FLOAT }, + {"beamWidth", offsetof(TracerDef, beamWidth), CSPFT_FLOAT }, + {"screwRadius", offsetof(TracerDef, screwRadius), CSPFT_FLOAT }, + {"screwDist", offsetof(TracerDef, screwDist), CSPFT_FLOAT }, + {"colorR0", offsetof(TracerDef, colors[0][0]), CSPFT_FLOAT }, + {"colorG0", offsetof(TracerDef, colors[0][1]), CSPFT_FLOAT }, + {"colorB0", offsetof(TracerDef, colors[0][2]), CSPFT_FLOAT }, + {"colorA0", offsetof(TracerDef, colors[0][3]), CSPFT_FLOAT }, + {"colorR1", offsetof(TracerDef, colors[1][0]), CSPFT_FLOAT }, + {"colorG1", offsetof(TracerDef, colors[1][1]), CSPFT_FLOAT }, + {"colorB1", offsetof(TracerDef, colors[1][2]), CSPFT_FLOAT }, + {"colorA1", offsetof(TracerDef, colors[1][3]), CSPFT_FLOAT }, + {"colorR2", offsetof(TracerDef, colors[2][0]), CSPFT_FLOAT }, + {"colorG2", offsetof(TracerDef, colors[2][1]), CSPFT_FLOAT }, + {"colorB2", offsetof(TracerDef, colors[2][2]), CSPFT_FLOAT }, + {"colorA2", offsetof(TracerDef, colors[2][3]), CSPFT_FLOAT }, + {"colorR3", offsetof(TracerDef, colors[3][0]), CSPFT_FLOAT }, + {"colorG3", offsetof(TracerDef, colors[3][1]), CSPFT_FLOAT }, + {"colorB3", offsetof(TracerDef, colors[3][2]), CSPFT_FLOAT }, + {"colorA3", offsetof(TracerDef, colors[3][3]), CSPFT_FLOAT }, + {"colorR4", offsetof(TracerDef, colors[4][0]), CSPFT_FLOAT }, + {"colorG4", offsetof(TracerDef, colors[4][1]), CSPFT_FLOAT }, + {"colorB4", offsetof(TracerDef, colors[4][2]), CSPFT_FLOAT }, + {"colorA4", offsetof(TracerDef, colors[4][3]), CSPFT_FLOAT }, +}; } diff --git a/src/ObjCommon/Game/IW4/InfoString/VehicleFields.h b/src/ObjCommon/Game/IW4/InfoString/VehicleFields.h index 94f54078c..52de7e07d 100644 --- a/src/ObjCommon/Game/IW4/InfoString/VehicleFields.h +++ b/src/ObjCommon/Game/IW4/InfoString/VehicleFields.h @@ -1,152 +1,150 @@ #pragma once #include "Game/IW4/IW4.h" -namespace IW4 -{ - inline cspField_t vehicle_fields[] - { - {"type", offsetof(VehicleDef, type), VFT_TYPE}, - {"useHintString", offsetof(VehicleDef, useHintString), CSPFT_STRING}, - {"health", offsetof(VehicleDef, health), CSPFT_INT}, - {"quadBarrel", offsetof(VehicleDef, quadBarrel), CSPFT_QBOOLEAN}, - {"texureScrollScale", offsetof(VehicleDef, texScrollScale), CSPFT_FLOAT}, - {"topSpeed", offsetof(VehicleDef, topSpeed), CSPFT_MPH_TO_INCHES_PER_SEC}, - {"accel", offsetof(VehicleDef, accel), CSPFT_MPH_TO_INCHES_PER_SEC}, - {"rotRate", offsetof(VehicleDef, rotRate), CSPFT_FLOAT}, - {"rotAccel", offsetof(VehicleDef, rotAccel), CSPFT_FLOAT}, - {"maxBodyPitch", offsetof(VehicleDef, maxBodyPitch), CSPFT_FLOAT}, - {"maxBodyRoll", offsetof(VehicleDef, maxBodyRoll), CSPFT_FLOAT}, - {"fakeBodyAccelPitch", offsetof(VehicleDef, fakeBodyAccelPitch), CSPFT_FLOAT}, - {"fakeBodyAccelRoll", offsetof(VehicleDef, fakeBodyAccelRoll), CSPFT_FLOAT}, - {"fakeBodyVelPitch", offsetof(VehicleDef, fakeBodyVelPitch), CSPFT_FLOAT}, - {"fakeBodyVelRoll", offsetof(VehicleDef, fakeBodyVelRoll), CSPFT_FLOAT}, - {"fakeBodySideVelPitch", offsetof(VehicleDef, fakeBodySideVelPitch), CSPFT_FLOAT}, - {"fakeBodyPitchStrength", offsetof(VehicleDef, fakeBodyPitchStrength), CSPFT_FLOAT}, - {"fakeBodyRollStrength", offsetof(VehicleDef, fakeBodyRollStrength), CSPFT_FLOAT}, - {"fakeBodyPitchDampening", offsetof(VehicleDef, fakeBodyPitchDampening), CSPFT_FLOAT}, - {"fakeBodyRollDampening", offsetof(VehicleDef, fakeBodyRollDampening), CSPFT_FLOAT}, - {"fakeBodyBoatRockingAmplitude", offsetof(VehicleDef, fakeBodyBoatRockingAmplitude), CSPFT_FLOAT}, - {"fakeBodyBoatRockingPeriod", offsetof(VehicleDef, fakeBodyBoatRockingPeriod), CSPFT_FLOAT}, - {"fakeBodyBoatRockingRotationPeriod", offsetof(VehicleDef, fakeBodyBoatRockingRotationPeriod), CSPFT_FLOAT}, - {"fakeBodyBoatRockingFadeoutSpeed", offsetof(VehicleDef, fakeBodyBoatRockingFadeoutSpeed), CSPFT_MPH_TO_INCHES_PER_SEC}, - {"boatBouncingMinForce", offsetof(VehicleDef, boatBouncingMinForce), CSPFT_MPH_TO_INCHES_PER_SEC}, - {"boatBouncingMaxForce", offsetof(VehicleDef, boatBouncingMaxForce), CSPFT_MPH_TO_INCHES_PER_SEC}, - {"boatBouncingRate", offsetof(VehicleDef, boatBouncingRate), CSPFT_FLOAT}, - {"boatBouncingFadeinSpeed", offsetof(VehicleDef, boatBouncingFadeinSpeed), CSPFT_MPH_TO_INCHES_PER_SEC}, - {"boatBouncingFadeoutSteeringAngle", offsetof(VehicleDef, boatBouncingFadeoutSteeringAngle), CSPFT_FLOAT}, - {"collisionDamage", offsetof(VehicleDef, collisionDamage), CSPFT_FLOAT}, - {"collisionSpeed", offsetof(VehicleDef, collisionSpeed), CSPFT_MPH_TO_INCHES_PER_SEC}, - {"killcamZDist", offsetof(VehicleDef, killcamOffset[0]), CSPFT_FLOAT}, - {"killcamBackDist", offsetof(VehicleDef, killcamOffset[1]), CSPFT_FLOAT}, - {"killcamUpDist", offsetof(VehicleDef, killcamOffset[2]), CSPFT_FLOAT}, - {"playerProtected", offsetof(VehicleDef, playerProtected), CSPFT_QBOOLEAN}, - {"bulletDamage", offsetof(VehicleDef, bulletDamage), CSPFT_QBOOLEAN}, - {"armorPiercingDamage", offsetof(VehicleDef, armorPiercingDamage), CSPFT_QBOOLEAN}, - {"grenadeDamage", offsetof(VehicleDef, grenadeDamage), CSPFT_QBOOLEAN}, - {"projectileDamage", offsetof(VehicleDef, projectileDamage), CSPFT_QBOOLEAN}, - {"projectileSplashDamage", offsetof(VehicleDef, projectileSplashDamage), CSPFT_QBOOLEAN}, - {"heavyExplosiveDamage", offsetof(VehicleDef, heavyExplosiveDamage), CSPFT_QBOOLEAN}, - {"physicsEnabled", offsetof(VehicleDef, vehPhysDef.physicsEnabled), CSPFT_QBOOLEAN}, - {"physicsPreset", offsetof(VehicleDef, vehPhysDef.physPresetName), CSPFT_STRING}, - {"accelerationGraph", offsetof(VehicleDef, vehPhysDef.accelGraphName), CSPFT_STRING}, - {"steeringAxle", offsetof(VehicleDef, vehPhysDef.steeringAxle), VFT_AXLE_STEERING}, - {"powerAxle", offsetof(VehicleDef, vehPhysDef.powerAxle), VFT_AXLE_POWER}, - {"brakingAxle", offsetof(VehicleDef, vehPhysDef.brakingAxle), VFT_AXLE_BRAKING}, - {"reverseSpeed", offsetof(VehicleDef, vehPhysDef.reverseSpeed), CSPFT_MPH_TO_INCHES_PER_SEC}, - {"maxVelocity", offsetof(VehicleDef, vehPhysDef.maxVelocity), CSPFT_MPH_TO_INCHES_PER_SEC}, - {"maxPitch", offsetof(VehicleDef, vehPhysDef.maxPitch), CSPFT_FLOAT}, - {"maxRoll", offsetof(VehicleDef, vehPhysDef.maxRoll), CSPFT_FLOAT}, - {"suspensionTravelRear", offsetof(VehicleDef, vehPhysDef.suspensionTravelRear), CSPFT_FLOAT}, - {"suspensionStrengthFront", offsetof(VehicleDef, vehPhysDef.suspensionStrengthFront), CSPFT_FLOAT}, - {"suspensionDampingFront", offsetof(VehicleDef, vehPhysDef.suspensionDampingFront), CSPFT_FLOAT}, - {"suspensionStrengthRear", offsetof(VehicleDef, vehPhysDef.suspensionStrengthRear), CSPFT_FLOAT}, - {"suspensionDampingRear", offsetof(VehicleDef, vehPhysDef.suspensionDampingRear), CSPFT_FLOAT}, - {"frictionBraking", offsetof(VehicleDef, vehPhysDef.frictionBraking), CSPFT_FLOAT}, - {"frictionCoasting", offsetof(VehicleDef, vehPhysDef.frictionCoasting), CSPFT_FLOAT}, - {"frictionTopSpeed", offsetof(VehicleDef, vehPhysDef.frictionTopSpeed), CSPFT_FLOAT}, - {"frictionSide", offsetof(VehicleDef, vehPhysDef.frictionSide), CSPFT_FLOAT}, - {"frictionSideRear", offsetof(VehicleDef, vehPhysDef.frictionSideRear), CSPFT_FLOAT}, - {"velocityDependentSlip", offsetof(VehicleDef, vehPhysDef.velocityDependentSlip), CSPFT_FLOAT}, - {"rollStability", offsetof(VehicleDef, vehPhysDef.rollStability), CSPFT_FLOAT}, - {"rollResistance", offsetof(VehicleDef, vehPhysDef.rollResistance), CSPFT_MPH_TO_INCHES_PER_SEC}, - {"pitchResistance", offsetof(VehicleDef, vehPhysDef.pitchResistance), CSPFT_MPH_TO_INCHES_PER_SEC}, - {"yawResistance", offsetof(VehicleDef, vehPhysDef.yawResistance), CSPFT_MPH_TO_INCHES_PER_SEC}, - {"uprightStrengthPitch", offsetof(VehicleDef, vehPhysDef.uprightStrengthPitch), CSPFT_MPH_TO_INCHES_PER_SEC}, - {"uprightStrengthRoll", offsetof(VehicleDef, vehPhysDef.uprightStrengthRoll), CSPFT_MPH_TO_INCHES_PER_SEC}, - {"targetAirPitch", offsetof(VehicleDef, vehPhysDef.targetAirPitch), CSPFT_FLOAT}, - {"airYawTorque", offsetof(VehicleDef, vehPhysDef.airYawTorque), CSPFT_MPH_TO_INCHES_PER_SEC}, - {"airPitchTorque", offsetof(VehicleDef, vehPhysDef.airPitchTorque), CSPFT_MPH_TO_INCHES_PER_SEC}, - {"minimumMomentumForCollision", offsetof(VehicleDef, vehPhysDef.minimumMomentumForCollision), CSPFT_MPH_TO_INCHES_PER_SEC}, - {"collisionLaunchForceScale", offsetof(VehicleDef, vehPhysDef.collisionLaunchForceScale), CSPFT_FLOAT}, - {"wreckedMassScale", offsetof(VehicleDef, vehPhysDef.wreckedMassScale), CSPFT_FLOAT}, - {"wreckedBodyFriction", offsetof(VehicleDef, vehPhysDef.wreckedBodyFriction), CSPFT_FLOAT}, - {"minimumJoltForNotify", offsetof(VehicleDef, vehPhysDef.minimumJoltForNotify), CSPFT_MPH_TO_INCHES_PER_SEC}, - {"slipThresholdFront", offsetof(VehicleDef, vehPhysDef.slipThresholdFront), CSPFT_FLOAT}, - {"slipThresholdRear", offsetof(VehicleDef, vehPhysDef.slipThresholdRear), CSPFT_FLOAT}, - {"slipFricScaleFront", offsetof(VehicleDef, vehPhysDef.slipFricScaleFront), CSPFT_FLOAT}, - {"slipFricScaleRear", offsetof(VehicleDef, vehPhysDef.slipFricScaleRear), CSPFT_FLOAT}, - {"slipFricRateFront", offsetof(VehicleDef, vehPhysDef.slipFricRateFront), CSPFT_FLOAT}, - {"slipFricRateRear", offsetof(VehicleDef, vehPhysDef.slipFricRateRear), CSPFT_FLOAT}, - {"slipYawTorque", offsetof(VehicleDef, vehPhysDef.slipYawTorque), CSPFT_MPH_TO_INCHES_PER_SEC}, - {"boostDuration", offsetof(VehicleDef, boostDuration), CSPFT_FLOAT}, - {"boostRechargeTime", offsetof(VehicleDef, boostRechargeTime), CSPFT_FLOAT}, - {"boostAcceleration", offsetof(VehicleDef, boostAcceleration), CSPFT_MPH_TO_INCHES_PER_SEC}, - {"suspensionTravel", offsetof(VehicleDef, suspensionTravel), CSPFT_FLOAT}, - {"maxSteeringAngle", offsetof(VehicleDef, maxSteeringAngle), CSPFT_FLOAT}, - {"steeringLerp", offsetof(VehicleDef, steeringLerp), CSPFT_FLOAT}, - {"minSteeringScale", offsetof(VehicleDef, minSteeringScale), CSPFT_FLOAT}, - {"minSteeringSpeed", offsetof(VehicleDef, minSteeringSpeed), CSPFT_MPH_TO_INCHES_PER_SEC}, - {"camLookEnabled", offsetof(VehicleDef, camLookEnabled), CSPFT_QBOOLEAN}, - {"camLerp", offsetof(VehicleDef, camLerp), CSPFT_FLOAT}, - {"camPitchInfluence", offsetof(VehicleDef, camPitchInfluence), CSPFT_FLOAT}, - {"camRollInfluence", offsetof(VehicleDef, camRollInfluence), CSPFT_FLOAT}, - {"camFovIncrease", offsetof(VehicleDef, camFovIncrease), CSPFT_FLOAT}, - {"camFovOffset", offsetof(VehicleDef, camFovOffset), CSPFT_FLOAT}, - {"camFovSpeed", offsetof(VehicleDef, camFovSpeed), CSPFT_FLOAT}, - {"turretWeaponName", offsetof(VehicleDef, turretWeaponName), CSPFT_STRING}, - {"turretHorizSpanLeft", offsetof(VehicleDef, turretHorizSpanLeft), CSPFT_FLOAT}, - {"turretHorizSpanRight", offsetof(VehicleDef, turretHorizSpanRight), CSPFT_FLOAT}, - {"turretVertSpanUp", offsetof(VehicleDef, turretVertSpanUp), CSPFT_FLOAT}, - {"turretVertSpanDown", offsetof(VehicleDef, turretVertSpanDown), CSPFT_FLOAT}, - {"turretRotRate", offsetof(VehicleDef, turretRotRate), CSPFT_FLOAT}, - {"turretSpinSnd", offsetof(VehicleDef, turretSpinSnd), CSPFT_SOUND}, - {"turretStopSnd", offsetof(VehicleDef, turretStopSnd), CSPFT_SOUND}, - {"trophyEnabled", offsetof(VehicleDef, trophyEnabled), CSPFT_QBOOLEAN}, - {"trophyRadius", offsetof(VehicleDef, trophyRadius), CSPFT_FLOAT}, - {"trophyInactiveRadius", offsetof(VehicleDef, trophyInactiveRadius), CSPFT_FLOAT}, - {"trophyAmmoCount", offsetof(VehicleDef, trophyAmmoCount), CSPFT_INT}, - {"trophyReloadTime", offsetof(VehicleDef, trophyReloadTime), CSPFT_FLOAT}, - {"trophyTags", offsetof(VehicleDef, trophyTags), VFT_TROPHY_TAGS}, - {"compassFriendlyIcon", offsetof(VehicleDef, compassFriendlyIcon), CSPFT_MATERIAL}, - {"compassEnemyIcon", offsetof(VehicleDef, compassEnemyIcon), CSPFT_MATERIAL}, - {"compassIconWidth", offsetof(VehicleDef, compassIconWidth), CSPFT_INT}, - {"compassIconHeight", offsetof(VehicleDef, compassIconHeight), CSPFT_INT}, - {"lowIdleSnd", offsetof(VehicleDef, idleLowSnd), CSPFT_SOUND}, - {"highIdleSnd", offsetof(VehicleDef, idleHighSnd), CSPFT_SOUND}, - {"lowEngineSnd", offsetof(VehicleDef, engineLowSnd), CSPFT_SOUND}, - {"highEngineSnd", offsetof(VehicleDef, engineHighSnd), CSPFT_SOUND}, - {"engineSndSpeed", offsetof(VehicleDef, engineSndSpeed), CSPFT_MPH_TO_INCHES_PER_SEC}, - {"engineStartUpSnd", offsetof(VehicleDef, engineStartUpSnd), CSPFT_SOUND}, - {"engineStartUpLength", offsetof(VehicleDef, engineStartUpLength), CSPFT_MILLISECONDS}, - {"engineShutdownSnd", offsetof(VehicleDef, engineShutdownSnd), CSPFT_SOUND}, - {"engineIdleSnd", offsetof(VehicleDef, engineIdleSnd), CSPFT_SOUND}, - {"engineSustainSnd", offsetof(VehicleDef, engineSustainSnd), CSPFT_SOUND}, - {"engineRampUpSnd", offsetof(VehicleDef, engineRampUpSnd), CSPFT_SOUND}, - {"engineRampUpLength", offsetof(VehicleDef, engineRampUpLength), CSPFT_MILLISECONDS}, - {"engineRampDownSnd", offsetof(VehicleDef, engineRampDownSnd), CSPFT_SOUND}, - {"engineRampDownLength", offsetof(VehicleDef, engineRampDownLength), CSPFT_MILLISECONDS}, - {"suspensionSoftSnd", offsetof(VehicleDef, suspensionSoftSnd), CSPFT_SOUND}, - {"suspensionSoftCompression", offsetof(VehicleDef, suspensionSoftCompression), CSPFT_FLOAT}, - {"suspensionHardSnd", offsetof(VehicleDef, suspensionHardSnd), CSPFT_SOUND}, - {"suspensionHardCompression", offsetof(VehicleDef, suspensionHardCompression), CSPFT_FLOAT}, - {"collisionSnd", offsetof(VehicleDef, collisionSnd), CSPFT_SOUND}, - {"collisionBlendSpeed", offsetof(VehicleDef, collisionBlendSpeed), CSPFT_MPH_TO_INCHES_PER_SEC}, - {"speedSnd", offsetof(VehicleDef, speedSnd), CSPFT_SOUND}, - {"speedSndBlendSpeed", offsetof(VehicleDef, speedSndBlendSpeed), CSPFT_MPH_TO_INCHES_PER_SEC}, - {"surfaceSndPrefix", offsetof(VehicleDef, surfaceSndPrefix), CSPFT_STRING}, - {"surfaceSndBlendSpeed", offsetof(VehicleDef, surfaceSndBlendSpeed), CSPFT_MPH_TO_INCHES_PER_SEC}, - {"slideVolume", offsetof(VehicleDef, slideVolume), CSPFT_FLOAT}, - {"slideBlendSpeed", offsetof(VehicleDef, slideBlendSpeed), CSPFT_MPH_TO_INCHES_PER_SEC}, - {"inAirPitch", offsetof(VehicleDef, inAirPitch), CSPFT_FLOAT}, - }; +namespace IW4 { +inline cspField_t vehicle_fields[]{ + {"type", offsetof(VehicleDef, type), VFT_TYPE }, + {"useHintString", offsetof(VehicleDef, useHintString), CSPFT_STRING }, + {"health", offsetof(VehicleDef, health), CSPFT_INT }, + {"quadBarrel", offsetof(VehicleDef, quadBarrel), CSPFT_QBOOLEAN }, + {"texureScrollScale", offsetof(VehicleDef, texScrollScale), CSPFT_FLOAT }, + {"topSpeed", offsetof(VehicleDef, topSpeed), CSPFT_MPH_TO_INCHES_PER_SEC}, + {"accel", offsetof(VehicleDef, accel), CSPFT_MPH_TO_INCHES_PER_SEC}, + {"rotRate", offsetof(VehicleDef, rotRate), CSPFT_FLOAT }, + {"rotAccel", offsetof(VehicleDef, rotAccel), CSPFT_FLOAT }, + {"maxBodyPitch", offsetof(VehicleDef, maxBodyPitch), CSPFT_FLOAT }, + {"maxBodyRoll", offsetof(VehicleDef, maxBodyRoll), CSPFT_FLOAT }, + {"fakeBodyAccelPitch", offsetof(VehicleDef, fakeBodyAccelPitch), CSPFT_FLOAT }, + {"fakeBodyAccelRoll", offsetof(VehicleDef, fakeBodyAccelRoll), CSPFT_FLOAT }, + {"fakeBodyVelPitch", offsetof(VehicleDef, fakeBodyVelPitch), CSPFT_FLOAT }, + {"fakeBodyVelRoll", offsetof(VehicleDef, fakeBodyVelRoll), CSPFT_FLOAT }, + {"fakeBodySideVelPitch", offsetof(VehicleDef, fakeBodySideVelPitch), CSPFT_FLOAT }, + {"fakeBodyPitchStrength", offsetof(VehicleDef, fakeBodyPitchStrength), CSPFT_FLOAT }, + {"fakeBodyRollStrength", offsetof(VehicleDef, fakeBodyRollStrength), CSPFT_FLOAT }, + {"fakeBodyPitchDampening", offsetof(VehicleDef, fakeBodyPitchDampening), CSPFT_FLOAT }, + {"fakeBodyRollDampening", offsetof(VehicleDef, fakeBodyRollDampening), CSPFT_FLOAT }, + {"fakeBodyBoatRockingAmplitude", offsetof(VehicleDef, fakeBodyBoatRockingAmplitude), CSPFT_FLOAT }, + {"fakeBodyBoatRockingPeriod", offsetof(VehicleDef, fakeBodyBoatRockingPeriod), CSPFT_FLOAT }, + {"fakeBodyBoatRockingRotationPeriod", offsetof(VehicleDef, fakeBodyBoatRockingRotationPeriod), CSPFT_FLOAT }, + {"fakeBodyBoatRockingFadeoutSpeed", offsetof(VehicleDef, fakeBodyBoatRockingFadeoutSpeed), CSPFT_MPH_TO_INCHES_PER_SEC}, + {"boatBouncingMinForce", offsetof(VehicleDef, boatBouncingMinForce), CSPFT_MPH_TO_INCHES_PER_SEC}, + {"boatBouncingMaxForce", offsetof(VehicleDef, boatBouncingMaxForce), CSPFT_MPH_TO_INCHES_PER_SEC}, + {"boatBouncingRate", offsetof(VehicleDef, boatBouncingRate), CSPFT_FLOAT }, + {"boatBouncingFadeinSpeed", offsetof(VehicleDef, boatBouncingFadeinSpeed), CSPFT_MPH_TO_INCHES_PER_SEC}, + {"boatBouncingFadeoutSteeringAngle", offsetof(VehicleDef, boatBouncingFadeoutSteeringAngle), CSPFT_FLOAT }, + {"collisionDamage", offsetof(VehicleDef, collisionDamage), CSPFT_FLOAT }, + {"collisionSpeed", offsetof(VehicleDef, collisionSpeed), CSPFT_MPH_TO_INCHES_PER_SEC}, + {"killcamZDist", offsetof(VehicleDef, killcamOffset[0]), CSPFT_FLOAT }, + {"killcamBackDist", offsetof(VehicleDef, killcamOffset[1]), CSPFT_FLOAT }, + {"killcamUpDist", offsetof(VehicleDef, killcamOffset[2]), CSPFT_FLOAT }, + {"playerProtected", offsetof(VehicleDef, playerProtected), CSPFT_QBOOLEAN }, + {"bulletDamage", offsetof(VehicleDef, bulletDamage), CSPFT_QBOOLEAN }, + {"armorPiercingDamage", offsetof(VehicleDef, armorPiercingDamage), CSPFT_QBOOLEAN }, + {"grenadeDamage", offsetof(VehicleDef, grenadeDamage), CSPFT_QBOOLEAN }, + {"projectileDamage", offsetof(VehicleDef, projectileDamage), CSPFT_QBOOLEAN }, + {"projectileSplashDamage", offsetof(VehicleDef, projectileSplashDamage), CSPFT_QBOOLEAN }, + {"heavyExplosiveDamage", offsetof(VehicleDef, heavyExplosiveDamage), CSPFT_QBOOLEAN }, + {"physicsEnabled", offsetof(VehicleDef, vehPhysDef.physicsEnabled), CSPFT_QBOOLEAN }, + {"physicsPreset", offsetof(VehicleDef, vehPhysDef.physPresetName), CSPFT_STRING }, + {"accelerationGraph", offsetof(VehicleDef, vehPhysDef.accelGraphName), CSPFT_STRING }, + {"steeringAxle", offsetof(VehicleDef, vehPhysDef.steeringAxle), VFT_AXLE_STEERING }, + {"powerAxle", offsetof(VehicleDef, vehPhysDef.powerAxle), VFT_AXLE_POWER }, + {"brakingAxle", offsetof(VehicleDef, vehPhysDef.brakingAxle), VFT_AXLE_BRAKING }, + {"reverseSpeed", offsetof(VehicleDef, vehPhysDef.reverseSpeed), CSPFT_MPH_TO_INCHES_PER_SEC}, + {"maxVelocity", offsetof(VehicleDef, vehPhysDef.maxVelocity), CSPFT_MPH_TO_INCHES_PER_SEC}, + {"maxPitch", offsetof(VehicleDef, vehPhysDef.maxPitch), CSPFT_FLOAT }, + {"maxRoll", offsetof(VehicleDef, vehPhysDef.maxRoll), CSPFT_FLOAT }, + {"suspensionTravelRear", offsetof(VehicleDef, vehPhysDef.suspensionTravelRear), CSPFT_FLOAT }, + {"suspensionStrengthFront", offsetof(VehicleDef, vehPhysDef.suspensionStrengthFront), CSPFT_FLOAT }, + {"suspensionDampingFront", offsetof(VehicleDef, vehPhysDef.suspensionDampingFront), CSPFT_FLOAT }, + {"suspensionStrengthRear", offsetof(VehicleDef, vehPhysDef.suspensionStrengthRear), CSPFT_FLOAT }, + {"suspensionDampingRear", offsetof(VehicleDef, vehPhysDef.suspensionDampingRear), CSPFT_FLOAT }, + {"frictionBraking", offsetof(VehicleDef, vehPhysDef.frictionBraking), CSPFT_FLOAT }, + {"frictionCoasting", offsetof(VehicleDef, vehPhysDef.frictionCoasting), CSPFT_FLOAT }, + {"frictionTopSpeed", offsetof(VehicleDef, vehPhysDef.frictionTopSpeed), CSPFT_FLOAT }, + {"frictionSide", offsetof(VehicleDef, vehPhysDef.frictionSide), CSPFT_FLOAT }, + {"frictionSideRear", offsetof(VehicleDef, vehPhysDef.frictionSideRear), CSPFT_FLOAT }, + {"velocityDependentSlip", offsetof(VehicleDef, vehPhysDef.velocityDependentSlip), CSPFT_FLOAT }, + {"rollStability", offsetof(VehicleDef, vehPhysDef.rollStability), CSPFT_FLOAT }, + {"rollResistance", offsetof(VehicleDef, vehPhysDef.rollResistance), CSPFT_MPH_TO_INCHES_PER_SEC}, + {"pitchResistance", offsetof(VehicleDef, vehPhysDef.pitchResistance), CSPFT_MPH_TO_INCHES_PER_SEC}, + {"yawResistance", offsetof(VehicleDef, vehPhysDef.yawResistance), CSPFT_MPH_TO_INCHES_PER_SEC}, + {"uprightStrengthPitch", offsetof(VehicleDef, vehPhysDef.uprightStrengthPitch), CSPFT_MPH_TO_INCHES_PER_SEC}, + {"uprightStrengthRoll", offsetof(VehicleDef, vehPhysDef.uprightStrengthRoll), CSPFT_MPH_TO_INCHES_PER_SEC}, + {"targetAirPitch", offsetof(VehicleDef, vehPhysDef.targetAirPitch), CSPFT_FLOAT }, + {"airYawTorque", offsetof(VehicleDef, vehPhysDef.airYawTorque), CSPFT_MPH_TO_INCHES_PER_SEC}, + {"airPitchTorque", offsetof(VehicleDef, vehPhysDef.airPitchTorque), CSPFT_MPH_TO_INCHES_PER_SEC}, + {"minimumMomentumForCollision", offsetof(VehicleDef, vehPhysDef.minimumMomentumForCollision), CSPFT_MPH_TO_INCHES_PER_SEC}, + {"collisionLaunchForceScale", offsetof(VehicleDef, vehPhysDef.collisionLaunchForceScale), CSPFT_FLOAT }, + {"wreckedMassScale", offsetof(VehicleDef, vehPhysDef.wreckedMassScale), CSPFT_FLOAT }, + {"wreckedBodyFriction", offsetof(VehicleDef, vehPhysDef.wreckedBodyFriction), CSPFT_FLOAT }, + {"minimumJoltForNotify", offsetof(VehicleDef, vehPhysDef.minimumJoltForNotify), CSPFT_MPH_TO_INCHES_PER_SEC}, + {"slipThresholdFront", offsetof(VehicleDef, vehPhysDef.slipThresholdFront), CSPFT_FLOAT }, + {"slipThresholdRear", offsetof(VehicleDef, vehPhysDef.slipThresholdRear), CSPFT_FLOAT }, + {"slipFricScaleFront", offsetof(VehicleDef, vehPhysDef.slipFricScaleFront), CSPFT_FLOAT }, + {"slipFricScaleRear", offsetof(VehicleDef, vehPhysDef.slipFricScaleRear), CSPFT_FLOAT }, + {"slipFricRateFront", offsetof(VehicleDef, vehPhysDef.slipFricRateFront), CSPFT_FLOAT }, + {"slipFricRateRear", offsetof(VehicleDef, vehPhysDef.slipFricRateRear), CSPFT_FLOAT }, + {"slipYawTorque", offsetof(VehicleDef, vehPhysDef.slipYawTorque), CSPFT_MPH_TO_INCHES_PER_SEC}, + {"boostDuration", offsetof(VehicleDef, boostDuration), CSPFT_FLOAT }, + {"boostRechargeTime", offsetof(VehicleDef, boostRechargeTime), CSPFT_FLOAT }, + {"boostAcceleration", offsetof(VehicleDef, boostAcceleration), CSPFT_MPH_TO_INCHES_PER_SEC}, + {"suspensionTravel", offsetof(VehicleDef, suspensionTravel), CSPFT_FLOAT }, + {"maxSteeringAngle", offsetof(VehicleDef, maxSteeringAngle), CSPFT_FLOAT }, + {"steeringLerp", offsetof(VehicleDef, steeringLerp), CSPFT_FLOAT }, + {"minSteeringScale", offsetof(VehicleDef, minSteeringScale), CSPFT_FLOAT }, + {"minSteeringSpeed", offsetof(VehicleDef, minSteeringSpeed), CSPFT_MPH_TO_INCHES_PER_SEC}, + {"camLookEnabled", offsetof(VehicleDef, camLookEnabled), CSPFT_QBOOLEAN }, + {"camLerp", offsetof(VehicleDef, camLerp), CSPFT_FLOAT }, + {"camPitchInfluence", offsetof(VehicleDef, camPitchInfluence), CSPFT_FLOAT }, + {"camRollInfluence", offsetof(VehicleDef, camRollInfluence), CSPFT_FLOAT }, + {"camFovIncrease", offsetof(VehicleDef, camFovIncrease), CSPFT_FLOAT }, + {"camFovOffset", offsetof(VehicleDef, camFovOffset), CSPFT_FLOAT }, + {"camFovSpeed", offsetof(VehicleDef, camFovSpeed), CSPFT_FLOAT }, + {"turretWeaponName", offsetof(VehicleDef, turretWeaponName), CSPFT_STRING }, + {"turretHorizSpanLeft", offsetof(VehicleDef, turretHorizSpanLeft), CSPFT_FLOAT }, + {"turretHorizSpanRight", offsetof(VehicleDef, turretHorizSpanRight), CSPFT_FLOAT }, + {"turretVertSpanUp", offsetof(VehicleDef, turretVertSpanUp), CSPFT_FLOAT }, + {"turretVertSpanDown", offsetof(VehicleDef, turretVertSpanDown), CSPFT_FLOAT }, + {"turretRotRate", offsetof(VehicleDef, turretRotRate), CSPFT_FLOAT }, + {"turretSpinSnd", offsetof(VehicleDef, turretSpinSnd), CSPFT_SOUND }, + {"turretStopSnd", offsetof(VehicleDef, turretStopSnd), CSPFT_SOUND }, + {"trophyEnabled", offsetof(VehicleDef, trophyEnabled), CSPFT_QBOOLEAN }, + {"trophyRadius", offsetof(VehicleDef, trophyRadius), CSPFT_FLOAT }, + {"trophyInactiveRadius", offsetof(VehicleDef, trophyInactiveRadius), CSPFT_FLOAT }, + {"trophyAmmoCount", offsetof(VehicleDef, trophyAmmoCount), CSPFT_INT }, + {"trophyReloadTime", offsetof(VehicleDef, trophyReloadTime), CSPFT_FLOAT }, + {"trophyTags", offsetof(VehicleDef, trophyTags), VFT_TROPHY_TAGS }, + {"compassFriendlyIcon", offsetof(VehicleDef, compassFriendlyIcon), CSPFT_MATERIAL }, + {"compassEnemyIcon", offsetof(VehicleDef, compassEnemyIcon), CSPFT_MATERIAL }, + {"compassIconWidth", offsetof(VehicleDef, compassIconWidth), CSPFT_INT }, + {"compassIconHeight", offsetof(VehicleDef, compassIconHeight), CSPFT_INT }, + {"lowIdleSnd", offsetof(VehicleDef, idleLowSnd), CSPFT_SOUND }, + {"highIdleSnd", offsetof(VehicleDef, idleHighSnd), CSPFT_SOUND }, + {"lowEngineSnd", offsetof(VehicleDef, engineLowSnd), CSPFT_SOUND }, + {"highEngineSnd", offsetof(VehicleDef, engineHighSnd), CSPFT_SOUND }, + {"engineSndSpeed", offsetof(VehicleDef, engineSndSpeed), CSPFT_MPH_TO_INCHES_PER_SEC}, + {"engineStartUpSnd", offsetof(VehicleDef, engineStartUpSnd), CSPFT_SOUND }, + {"engineStartUpLength", offsetof(VehicleDef, engineStartUpLength), CSPFT_MILLISECONDS }, + {"engineShutdownSnd", offsetof(VehicleDef, engineShutdownSnd), CSPFT_SOUND }, + {"engineIdleSnd", offsetof(VehicleDef, engineIdleSnd), CSPFT_SOUND }, + {"engineSustainSnd", offsetof(VehicleDef, engineSustainSnd), CSPFT_SOUND }, + {"engineRampUpSnd", offsetof(VehicleDef, engineRampUpSnd), CSPFT_SOUND }, + {"engineRampUpLength", offsetof(VehicleDef, engineRampUpLength), CSPFT_MILLISECONDS }, + {"engineRampDownSnd", offsetof(VehicleDef, engineRampDownSnd), CSPFT_SOUND }, + {"engineRampDownLength", offsetof(VehicleDef, engineRampDownLength), CSPFT_MILLISECONDS }, + {"suspensionSoftSnd", offsetof(VehicleDef, suspensionSoftSnd), CSPFT_SOUND }, + {"suspensionSoftCompression", offsetof(VehicleDef, suspensionSoftCompression), CSPFT_FLOAT }, + {"suspensionHardSnd", offsetof(VehicleDef, suspensionHardSnd), CSPFT_SOUND }, + {"suspensionHardCompression", offsetof(VehicleDef, suspensionHardCompression), CSPFT_FLOAT }, + {"collisionSnd", offsetof(VehicleDef, collisionSnd), CSPFT_SOUND }, + {"collisionBlendSpeed", offsetof(VehicleDef, collisionBlendSpeed), CSPFT_MPH_TO_INCHES_PER_SEC}, + {"speedSnd", offsetof(VehicleDef, speedSnd), CSPFT_SOUND }, + {"speedSndBlendSpeed", offsetof(VehicleDef, speedSndBlendSpeed), CSPFT_MPH_TO_INCHES_PER_SEC}, + {"surfaceSndPrefix", offsetof(VehicleDef, surfaceSndPrefix), CSPFT_STRING }, + {"surfaceSndBlendSpeed", offsetof(VehicleDef, surfaceSndBlendSpeed), CSPFT_MPH_TO_INCHES_PER_SEC}, + {"slideVolume", offsetof(VehicleDef, slideVolume), CSPFT_FLOAT }, + {"slideBlendSpeed", offsetof(VehicleDef, slideBlendSpeed), CSPFT_MPH_TO_INCHES_PER_SEC}, + {"inAirPitch", offsetof(VehicleDef, inAirPitch), CSPFT_FLOAT }, +}; } diff --git a/src/ObjCommon/Game/IW4/InfoString/WeaponFields.h b/src/ObjCommon/Game/IW4/InfoString/WeaponFields.h index 7d79731ba..b481d8fe3 100644 --- a/src/ObjCommon/Game/IW4/InfoString/WeaponFields.h +++ b/src/ObjCommon/Game/IW4/InfoString/WeaponFields.h @@ -1,681 +1,679 @@ #pragma once #include "Game/IW4/IW4.h" -namespace IW4 -{ - inline cspField_t weapon_fields[] - { - {"displayName", offsetof(WeaponFullDef, weapCompleteDef.szDisplayName), CSPFT_STRING}, - {"AIOverlayDescription", offsetof(WeaponFullDef, weapDef.szOverlayName), CSPFT_STRING}, - {"modeName", offsetof(WeaponFullDef, weapDef.szModeName), CSPFT_STRING}, - {"playerAnimType", offsetof(WeaponFullDef, weapDef.playerAnimType), WFT_ANIMTYPE}, - {"gunModel", offsetof(WeaponFullDef, gunXModel[0]), CSPFT_XMODEL}, - {"gunModel2", offsetof(WeaponFullDef, gunXModel[1]), CSPFT_XMODEL}, - {"gunModel3", offsetof(WeaponFullDef, gunXModel[2]), CSPFT_XMODEL}, - {"gunModel4", offsetof(WeaponFullDef, gunXModel[3]), CSPFT_XMODEL}, - {"gunModel5", offsetof(WeaponFullDef, gunXModel[4]), CSPFT_XMODEL}, - {"gunModel6", offsetof(WeaponFullDef, gunXModel[5]), CSPFT_XMODEL}, - {"gunModel7", offsetof(WeaponFullDef, gunXModel[6]), CSPFT_XMODEL}, - {"gunModel8", offsetof(WeaponFullDef, gunXModel[7]), CSPFT_XMODEL}, - {"gunModel9", offsetof(WeaponFullDef, gunXModel[8]), CSPFT_XMODEL}, - {"gunModel10", offsetof(WeaponFullDef, gunXModel[9]), CSPFT_XMODEL}, - {"gunModel11", offsetof(WeaponFullDef, gunXModel[10]), CSPFT_XMODEL}, - {"gunModel12", offsetof(WeaponFullDef, gunXModel[11]), CSPFT_XMODEL}, - {"gunModel13", offsetof(WeaponFullDef, gunXModel[12]), CSPFT_XMODEL}, - {"gunModel14", offsetof(WeaponFullDef, gunXModel[13]), CSPFT_XMODEL}, - {"gunModel15", offsetof(WeaponFullDef, gunXModel[14]), CSPFT_XMODEL}, - {"gunModel16", offsetof(WeaponFullDef, gunXModel[15]), CSPFT_XMODEL}, - {"handModel", offsetof(WeaponFullDef, weapDef.handXModel), CSPFT_XMODEL}, - {"hideTags", offsetof(WeaponFullDef, hideTags), WFT_HIDETAGS}, - {"notetrackSoundMap", offsetof(WeaponFullDef, notetrackSoundMapKeys), WFT_NOTETRACKSOUNDMAP}, - {"notetrackRumbleMap", offsetof(WeaponFullDef, notetrackRumbleMapKeys), WFT_NOTETRACKRUMBLEMAP}, - {"idleAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_IDLE]), CSPFT_STRING}, - {"emptyIdleAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_EMPTY_IDLE]), CSPFT_STRING}, - {"fireAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_FIRE]), CSPFT_STRING}, - {"holdFireAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_HOLD_FIRE]), CSPFT_STRING}, - {"lastShotAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_LASTSHOT]), CSPFT_STRING}, - {"detonateAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_DETONATE]), CSPFT_STRING}, - {"rechamberAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_RECHAMBER]), CSPFT_STRING}, - {"meleeAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_MELEE]), CSPFT_STRING}, - {"meleeChargeAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_MELEE_CHARGE]), CSPFT_STRING}, - {"reloadAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_RELOAD]), CSPFT_STRING}, - {"reloadEmptyAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_RELOAD_EMPTY]), CSPFT_STRING}, - {"reloadStartAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_RELOAD_START]), CSPFT_STRING}, - {"reloadEndAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_RELOAD_END]), CSPFT_STRING}, - {"raiseAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_RAISE]), CSPFT_STRING}, - {"dropAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_DROP]), CSPFT_STRING}, - {"firstRaiseAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_FIRST_RAISE]), CSPFT_STRING}, - {"breachRaiseAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_BREACH_RAISE]), CSPFT_STRING}, - {"altRaiseAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_ALT_RAISE]), CSPFT_STRING}, - {"altDropAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_ALT_DROP]), CSPFT_STRING}, - {"quickRaiseAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_QUICK_RAISE]), CSPFT_STRING}, - {"quickDropAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_QUICK_DROP]), CSPFT_STRING}, - {"emptyRaiseAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_EMPTY_RAISE]), CSPFT_STRING}, - {"emptyDropAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_EMPTY_DROP]), CSPFT_STRING}, - {"sprintInAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_SPRINT_IN]), CSPFT_STRING}, - {"sprintLoopAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_SPRINT_LOOP]), CSPFT_STRING}, - {"sprintOutAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_SPRINT_OUT]), CSPFT_STRING}, - {"stunnedAnimStart", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_STUNNED_START]), CSPFT_STRING}, - {"stunnedAnimLoop", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_STUNNED_LOOP]), CSPFT_STRING}, - {"stunnedAnimEnd", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_STUNNED_END]), CSPFT_STRING}, - {"nightVisionWearAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_NIGHTVISION_WEAR]), CSPFT_STRING}, - {"nightVisionRemoveAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_NIGHTVISION_REMOVE]), CSPFT_STRING}, - {"adsFireAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_ADS_FIRE]), CSPFT_STRING}, - {"adsLastShotAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_ADS_LASTSHOT]), CSPFT_STRING}, - {"adsRechamberAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_ADS_RECHAMBER]), CSPFT_STRING}, - {"adsUpAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_ADS_UP]), CSPFT_STRING}, - {"adsDownAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_ADS_DOWN]), CSPFT_STRING}, - {"idleAnimR", offsetof(WeaponFullDef, szXAnimsRightHanded[WEAP_ANIM_IDLE]), CSPFT_STRING}, - {"emptyIdleAnimR", offsetof(WeaponFullDef, szXAnimsRightHanded[WEAP_ANIM_EMPTY_IDLE]), CSPFT_STRING}, - {"fireAnimR", offsetof(WeaponFullDef, szXAnimsRightHanded[WEAP_ANIM_FIRE]), CSPFT_STRING}, - {"holdFireAnimR", offsetof(WeaponFullDef, szXAnimsRightHanded[WEAP_ANIM_HOLD_FIRE]), CSPFT_STRING}, - {"lastShotAnimR", offsetof(WeaponFullDef, szXAnimsRightHanded[WEAP_ANIM_LASTSHOT]), CSPFT_STRING}, - {"detonateAnimR", offsetof(WeaponFullDef, szXAnimsRightHanded[WEAP_ANIM_DETONATE]), CSPFT_STRING}, - {"rechamberAnimR", offsetof(WeaponFullDef, szXAnimsRightHanded[WEAP_ANIM_RECHAMBER]), CSPFT_STRING}, - {"meleeAnimR", offsetof(WeaponFullDef, szXAnimsRightHanded[WEAP_ANIM_MELEE]), CSPFT_STRING}, - {"meleeChargeAnimR", offsetof(WeaponFullDef, szXAnimsRightHanded[WEAP_ANIM_MELEE_CHARGE]), CSPFT_STRING}, - {"reloadAnimR", offsetof(WeaponFullDef, szXAnimsRightHanded[WEAP_ANIM_RELOAD]), CSPFT_STRING}, - {"reloadEmptyAnimR", offsetof(WeaponFullDef, szXAnimsRightHanded[WEAP_ANIM_RELOAD_EMPTY]), CSPFT_STRING}, - {"reloadStartAnimR", offsetof(WeaponFullDef, szXAnimsRightHanded[WEAP_ANIM_RELOAD_START]), CSPFT_STRING}, - {"reloadEndAnimR", offsetof(WeaponFullDef, szXAnimsRightHanded[WEAP_ANIM_RELOAD_END]), CSPFT_STRING}, - {"raiseAnimR", offsetof(WeaponFullDef, szXAnimsRightHanded[WEAP_ANIM_RAISE]), CSPFT_STRING}, - {"dropAnimR", offsetof(WeaponFullDef, szXAnimsRightHanded[WEAP_ANIM_DROP]), CSPFT_STRING}, - {"firstRaiseAnimR", offsetof(WeaponFullDef, szXAnimsRightHanded[WEAP_ANIM_FIRST_RAISE]), CSPFT_STRING}, - {"breachRaiseAnimR", offsetof(WeaponFullDef, szXAnimsRightHanded[WEAP_ANIM_BREACH_RAISE]), CSPFT_STRING}, - {"altRaiseAnimR", offsetof(WeaponFullDef, szXAnimsRightHanded[WEAP_ANIM_ALT_RAISE]), CSPFT_STRING}, - {"altDropAnimR", offsetof(WeaponFullDef, szXAnimsRightHanded[WEAP_ANIM_ALT_DROP]), CSPFT_STRING}, - {"quickRaiseAnimR", offsetof(WeaponFullDef, szXAnimsRightHanded[WEAP_ANIM_QUICK_RAISE]), CSPFT_STRING}, - {"quickDropAnimR", offsetof(WeaponFullDef, szXAnimsRightHanded[WEAP_ANIM_QUICK_DROP]), CSPFT_STRING}, - {"emptyRaiseAnimR", offsetof(WeaponFullDef, szXAnimsRightHanded[WEAP_ANIM_EMPTY_RAISE]), CSPFT_STRING}, - {"emptyDropAnimR", offsetof(WeaponFullDef, szXAnimsRightHanded[WEAP_ANIM_EMPTY_DROP]), CSPFT_STRING}, - {"sprintInAnimR", offsetof(WeaponFullDef, szXAnimsRightHanded[WEAP_ANIM_SPRINT_IN]), CSPFT_STRING}, - {"sprintLoopAnimR", offsetof(WeaponFullDef, szXAnimsRightHanded[WEAP_ANIM_SPRINT_LOOP]), CSPFT_STRING}, - {"sprintOutAnimR", offsetof(WeaponFullDef, szXAnimsRightHanded[WEAP_ANIM_SPRINT_OUT]), CSPFT_STRING}, - {"stunnedAnimStartR", offsetof(WeaponFullDef, szXAnimsRightHanded[WEAP_ANIM_STUNNED_START]), CSPFT_STRING}, - {"stunnedAnimLoopR", offsetof(WeaponFullDef, szXAnimsRightHanded[WEAP_ANIM_STUNNED_LOOP]), CSPFT_STRING}, - {"stunnedAnimEndR", offsetof(WeaponFullDef, szXAnimsRightHanded[WEAP_ANIM_STUNNED_END]), CSPFT_STRING}, - {"nightVisionWearAnimR", offsetof(WeaponFullDef, szXAnimsRightHanded[WEAP_ANIM_NIGHTVISION_WEAR]), CSPFT_STRING}, - {"nightVisionRemoveAnimR", offsetof(WeaponFullDef, szXAnimsRightHanded[WEAP_ANIM_NIGHTVISION_REMOVE]), CSPFT_STRING}, - {"adsFireAnimR", offsetof(WeaponFullDef, szXAnimsRightHanded[WEAP_ANIM_ADS_FIRE]), CSPFT_STRING}, - {"adsLastShotAnimR", offsetof(WeaponFullDef, szXAnimsRightHanded[WEAP_ANIM_ADS_LASTSHOT]), CSPFT_STRING}, - {"adsRechamberAnimR", offsetof(WeaponFullDef, szXAnimsRightHanded[WEAP_ANIM_ADS_RECHAMBER]), CSPFT_STRING}, - {"adsUpAnimR", offsetof(WeaponFullDef, szXAnimsRightHanded[WEAP_ANIM_ADS_UP]), CSPFT_STRING}, - {"adsDownAnimR", offsetof(WeaponFullDef, szXAnimsRightHanded[WEAP_ANIM_ADS_DOWN]), CSPFT_STRING}, - {"idleAnimL", offsetof(WeaponFullDef, szXAnimsLeftHanded[WEAP_ANIM_IDLE]), CSPFT_STRING}, - {"emptyIdleAnimL", offsetof(WeaponFullDef, szXAnimsLeftHanded[WEAP_ANIM_EMPTY_IDLE]), CSPFT_STRING}, - {"fireAnimL", offsetof(WeaponFullDef, szXAnimsLeftHanded[WEAP_ANIM_FIRE]), CSPFT_STRING}, - {"holdFireAnimL", offsetof(WeaponFullDef, szXAnimsLeftHanded[WEAP_ANIM_HOLD_FIRE]), CSPFT_STRING}, - {"lastShotAnimL", offsetof(WeaponFullDef, szXAnimsLeftHanded[WEAP_ANIM_LASTSHOT]), CSPFT_STRING}, - {"detonateAnimL", offsetof(WeaponFullDef, szXAnimsLeftHanded[WEAP_ANIM_DETONATE]), CSPFT_STRING}, - {"rechamberAnimL", offsetof(WeaponFullDef, szXAnimsLeftHanded[WEAP_ANIM_RECHAMBER]), CSPFT_STRING}, - {"meleeAnimL", offsetof(WeaponFullDef, szXAnimsLeftHanded[WEAP_ANIM_MELEE]), CSPFT_STRING}, - {"meleeChargeAnimL", offsetof(WeaponFullDef, szXAnimsLeftHanded[WEAP_ANIM_MELEE_CHARGE]), CSPFT_STRING}, - {"reloadAnimL", offsetof(WeaponFullDef, szXAnimsLeftHanded[WEAP_ANIM_RELOAD]), CSPFT_STRING}, - {"reloadEmptyAnimL", offsetof(WeaponFullDef, szXAnimsLeftHanded[WEAP_ANIM_RELOAD_EMPTY]), CSPFT_STRING}, - {"reloadStartAnimL", offsetof(WeaponFullDef, szXAnimsLeftHanded[WEAP_ANIM_RELOAD_START]), CSPFT_STRING}, - {"reloadEndAnimL", offsetof(WeaponFullDef, szXAnimsLeftHanded[WEAP_ANIM_RELOAD_END]), CSPFT_STRING}, - {"raiseAnimL", offsetof(WeaponFullDef, szXAnimsLeftHanded[WEAP_ANIM_RAISE]), CSPFT_STRING}, - {"dropAnimL", offsetof(WeaponFullDef, szXAnimsLeftHanded[WEAP_ANIM_DROP]), CSPFT_STRING}, - {"firstRaiseAnimL", offsetof(WeaponFullDef, szXAnimsLeftHanded[WEAP_ANIM_FIRST_RAISE]), CSPFT_STRING}, - {"breachRaiseAnimL", offsetof(WeaponFullDef, szXAnimsLeftHanded[WEAP_ANIM_BREACH_RAISE]), CSPFT_STRING}, - {"altRaiseAnimL", offsetof(WeaponFullDef, szXAnimsLeftHanded[WEAP_ANIM_ALT_RAISE]), CSPFT_STRING}, - {"altDropAnimL", offsetof(WeaponFullDef, szXAnimsLeftHanded[WEAP_ANIM_ALT_DROP]), CSPFT_STRING}, - {"quickRaiseAnimL", offsetof(WeaponFullDef, szXAnimsLeftHanded[WEAP_ANIM_QUICK_RAISE]), CSPFT_STRING}, - {"quickDropAnimL", offsetof(WeaponFullDef, szXAnimsLeftHanded[WEAP_ANIM_QUICK_DROP]), CSPFT_STRING}, - {"emptyRaiseAnimL", offsetof(WeaponFullDef, szXAnimsLeftHanded[WEAP_ANIM_EMPTY_RAISE]), CSPFT_STRING}, - {"emptyDropAnimL", offsetof(WeaponFullDef, szXAnimsLeftHanded[WEAP_ANIM_EMPTY_DROP]), CSPFT_STRING}, - {"sprintInAnimL", offsetof(WeaponFullDef, szXAnimsLeftHanded[WEAP_ANIM_SPRINT_IN]), CSPFT_STRING}, - {"sprintLoopAnimL", offsetof(WeaponFullDef, szXAnimsLeftHanded[WEAP_ANIM_SPRINT_LOOP]), CSPFT_STRING}, - {"sprintOutAnimL", offsetof(WeaponFullDef, szXAnimsLeftHanded[WEAP_ANIM_SPRINT_OUT]), CSPFT_STRING}, - {"stunnedAnimStartL", offsetof(WeaponFullDef, szXAnimsLeftHanded[WEAP_ANIM_STUNNED_START]), CSPFT_STRING}, - {"stunnedAnimLoopL", offsetof(WeaponFullDef, szXAnimsLeftHanded[WEAP_ANIM_STUNNED_LOOP]), CSPFT_STRING}, - {"stunnedAnimEndL", offsetof(WeaponFullDef, szXAnimsLeftHanded[WEAP_ANIM_STUNNED_END]), CSPFT_STRING}, - {"nightVisionWearAnimL", offsetof(WeaponFullDef, szXAnimsLeftHanded[WEAP_ANIM_NIGHTVISION_WEAR]), CSPFT_STRING}, - {"nightVisionRemoveAnimL", offsetof(WeaponFullDef, szXAnimsLeftHanded[WEAP_ANIM_NIGHTVISION_REMOVE]), CSPFT_STRING}, - {"adsFireAnimL", offsetof(WeaponFullDef, szXAnimsLeftHanded[WEAP_ANIM_ADS_FIRE]), CSPFT_STRING}, - {"adsLastShotAnimL", offsetof(WeaponFullDef, szXAnimsLeftHanded[WEAP_ANIM_ADS_LASTSHOT]), CSPFT_STRING}, - {"adsRechamberAnimL", offsetof(WeaponFullDef, szXAnimsLeftHanded[WEAP_ANIM_ADS_RECHAMBER]), CSPFT_STRING}, - {"adsUpAnimL", offsetof(WeaponFullDef, szXAnimsLeftHanded[WEAP_ANIM_ADS_UP]), CSPFT_STRING}, - {"adsDownAnimL", offsetof(WeaponFullDef, szXAnimsLeftHanded[WEAP_ANIM_ADS_DOWN]), CSPFT_STRING}, - {"script", offsetof(WeaponFullDef, weapDef.szScript), CSPFT_STRING}, - {"weaponType", offsetof(WeaponFullDef, weapDef.weapType), WFT_WEAPONTYPE}, - {"weaponClass", offsetof(WeaponFullDef, weapDef.weapClass), WFT_WEAPONCLASS}, - {"penetrateType", offsetof(WeaponFullDef, weapDef.penetrateType), WFT_PENETRATE_TYPE}, - {"penetrateMultiplier", offsetof(WeaponFullDef, weapCompleteDef.penetrateMultiplier), CSPFT_FLOAT}, - {"impactType", offsetof(WeaponFullDef, weapCompleteDef.impactType), WFT_IMPACT_TYPE}, - {"inventoryType", offsetof(WeaponFullDef, weapDef.inventoryType), WFT_INVENTORYTYPE}, - {"fireType", offsetof(WeaponFullDef, weapDef.fireType), WFT_FIRETYPE}, - {"offhandClass", offsetof(WeaponFullDef, weapDef.offhandClass), WFT_OFFHAND_CLASS}, - {"viewFlashEffect", offsetof(WeaponFullDef, weapDef.viewFlashEffect), CSPFT_FX}, - {"worldFlashEffect", offsetof(WeaponFullDef, weapDef.worldFlashEffect), CSPFT_FX}, - {"pickupSound", offsetof(WeaponFullDef, weapDef.pickupSound), CSPFT_SOUND}, - {"pickupSoundPlayer", offsetof(WeaponFullDef, weapDef.pickupSoundPlayer), CSPFT_SOUND}, - {"ammoPickupSound", offsetof(WeaponFullDef, weapDef.ammoPickupSound), CSPFT_SOUND}, - {"ammoPickupSoundPlayer", offsetof(WeaponFullDef, weapDef.ammoPickupSoundPlayer), CSPFT_SOUND}, - {"projectileSound", offsetof(WeaponFullDef, weapDef.projectileSound), CSPFT_SOUND}, - {"pullbackSound", offsetof(WeaponFullDef, weapDef.pullbackSound), CSPFT_SOUND}, - {"pullbackSoundPlayer", offsetof(WeaponFullDef, weapDef.pullbackSoundPlayer), CSPFT_SOUND}, - {"fireSound", offsetof(WeaponFullDef, weapDef.fireSound), CSPFT_SOUND}, - {"fireSoundPlayer", offsetof(WeaponFullDef, weapDef.fireSoundPlayer), CSPFT_SOUND}, - {"fireSoundPlayerAkimbo", offsetof(WeaponFullDef, weapDef.fireSoundPlayerAkimbo), CSPFT_SOUND}, - {"loopFireSound", offsetof(WeaponFullDef, weapDef.fireLoopSound), CSPFT_SOUND}, - {"loopFireSoundPlayer", offsetof(WeaponFullDef, weapDef.fireLoopSoundPlayer), CSPFT_SOUND}, - {"stopFireSound", offsetof(WeaponFullDef, weapDef.fireStopSound), CSPFT_SOUND}, - {"stopFireSoundPlayer", offsetof(WeaponFullDef, weapDef.fireStopSoundPlayer), CSPFT_SOUND}, - {"lastShotSound", offsetof(WeaponFullDef, weapDef.fireLastSound), CSPFT_SOUND}, - {"lastShotSoundPlayer", offsetof(WeaponFullDef, weapDef.fireLastSoundPlayer), CSPFT_SOUND}, - {"emptyFireSound", offsetof(WeaponFullDef, weapDef.emptyFireSound), CSPFT_SOUND}, - {"emptyFireSoundPlayer", offsetof(WeaponFullDef, weapDef.emptyFireSoundPlayer), CSPFT_SOUND}, - {"meleeSwipeSound", offsetof(WeaponFullDef, weapDef.meleeSwipeSound), CSPFT_SOUND}, - {"meleeSwipeSoundPlayer", offsetof(WeaponFullDef, weapDef.meleeSwipeSoundPlayer), CSPFT_SOUND}, - {"meleeHitSound", offsetof(WeaponFullDef, weapDef.meleeHitSound), CSPFT_SOUND}, - {"meleeMissSound", offsetof(WeaponFullDef, weapDef.meleeMissSound), CSPFT_SOUND}, - {"rechamberSound", offsetof(WeaponFullDef, weapDef.rechamberSound), CSPFT_SOUND}, - {"rechamberSoundPlayer", offsetof(WeaponFullDef, weapDef.rechamberSoundPlayer), CSPFT_SOUND}, - {"reloadSound", offsetof(WeaponFullDef, weapDef.reloadSound), CSPFT_SOUND}, - {"reloadSoundPlayer", offsetof(WeaponFullDef, weapDef.reloadSoundPlayer), CSPFT_SOUND}, - {"reloadEmptySound", offsetof(WeaponFullDef, weapDef.reloadEmptySound), CSPFT_SOUND}, - {"reloadEmptySoundPlayer", offsetof(WeaponFullDef, weapDef.reloadEmptySoundPlayer), CSPFT_SOUND}, - {"reloadStartSound", offsetof(WeaponFullDef, weapDef.reloadStartSound), CSPFT_SOUND}, - {"reloadStartSoundPlayer", offsetof(WeaponFullDef, weapDef.reloadStartSoundPlayer), CSPFT_SOUND}, - {"reloadEndSound", offsetof(WeaponFullDef, weapDef.reloadEndSound), CSPFT_SOUND}, - {"reloadEndSoundPlayer", offsetof(WeaponFullDef, weapDef.reloadEndSoundPlayer), CSPFT_SOUND}, - {"detonateSound", offsetof(WeaponFullDef, weapDef.detonateSound), CSPFT_SOUND}, - {"detonateSoundPlayer", offsetof(WeaponFullDef, weapDef.detonateSoundPlayer), CSPFT_SOUND}, - {"nightVisionWearSound", offsetof(WeaponFullDef, weapDef.nightVisionWearSound), CSPFT_SOUND}, - {"nightVisionWearSoundPlayer", offsetof(WeaponFullDef, weapDef.nightVisionWearSoundPlayer), CSPFT_SOUND}, - {"nightVisionRemoveSound", offsetof(WeaponFullDef, weapDef.nightVisionRemoveSound), CSPFT_SOUND}, - {"nightVisionRemoveSoundPlayer", offsetof(WeaponFullDef, weapDef.nightVisionRemoveSoundPlayer), CSPFT_SOUND}, - {"raiseSound", offsetof(WeaponFullDef, weapDef.raiseSound), CSPFT_SOUND}, - {"raiseSoundPlayer", offsetof(WeaponFullDef, weapDef.raiseSoundPlayer), CSPFT_SOUND}, - {"firstRaiseSound", offsetof(WeaponFullDef, weapDef.firstRaiseSound), CSPFT_SOUND}, - {"firstRaiseSoundPlayer", offsetof(WeaponFullDef, weapDef.firstRaiseSoundPlayer), CSPFT_SOUND}, - {"altSwitchSound", offsetof(WeaponFullDef, weapDef.altSwitchSound), CSPFT_SOUND}, - {"altSwitchSoundPlayer", offsetof(WeaponFullDef, weapDef.altSwitchSoundPlayer), CSPFT_SOUND}, - {"putawaySound", offsetof(WeaponFullDef, weapDef.putawaySound), CSPFT_SOUND}, - {"putawaySoundPlayer", offsetof(WeaponFullDef, weapDef.putawaySoundPlayer), CSPFT_SOUND}, - {"scanSound", offsetof(WeaponFullDef, weapDef.scanSound), CSPFT_SOUND}, - {"bounceSound", offsetof(WeaponFullDef, weapDef.bounceSound), WFT_BOUNCE_SOUND}, - {"viewShellEjectEffect", offsetof(WeaponFullDef, weapDef.viewShellEjectEffect), CSPFT_FX}, - {"worldShellEjectEffect", offsetof(WeaponFullDef, weapDef.worldShellEjectEffect), CSPFT_FX}, - {"viewLastShotEjectEffect", offsetof(WeaponFullDef, weapDef.viewLastShotEjectEffect), CSPFT_FX}, - {"worldLastShotEjectEffect", offsetof(WeaponFullDef, weapDef.worldLastShotEjectEffect), CSPFT_FX}, - {"reticleCenter", offsetof(WeaponFullDef, weapDef.reticleCenter), CSPFT_MATERIAL}, - {"reticleSide", offsetof(WeaponFullDef, weapDef.reticleSide), CSPFT_MATERIAL}, - {"reticleCenterSize", offsetof(WeaponFullDef, weapDef.iReticleCenterSize), CSPFT_INT}, - {"reticleSideSize", offsetof(WeaponFullDef, weapDef.iReticleSideSize), CSPFT_INT}, - {"reticleMinOfs", offsetof(WeaponFullDef, weapDef.iReticleMinOfs), CSPFT_INT}, - {"activeReticleType", offsetof(WeaponFullDef, weapDef.activeReticleType), WFT_ACTIVE_RETICLE_TYPE}, - {"standMoveF", offsetof(WeaponFullDef, weapDef.vStandMove[0]), CSPFT_FLOAT}, - {"standMoveR", offsetof(WeaponFullDef, weapDef.vStandMove[1]), CSPFT_FLOAT}, - {"standMoveU", offsetof(WeaponFullDef, weapDef.vStandMove[2]), CSPFT_FLOAT}, - {"standRotP", offsetof(WeaponFullDef, weapDef.vStandRot[0]), CSPFT_FLOAT}, - {"standRotY", offsetof(WeaponFullDef, weapDef.vStandRot[1]), CSPFT_FLOAT}, - {"standRotR", offsetof(WeaponFullDef, weapDef.vStandRot[2]), CSPFT_FLOAT}, - {"strafeMoveF", offsetof(WeaponFullDef, weapDef.strafeMove[0]), CSPFT_FLOAT}, - {"strafeMoveR", offsetof(WeaponFullDef, weapDef.strafeMove[1]), CSPFT_FLOAT}, - {"strafeMoveU", offsetof(WeaponFullDef, weapDef.strafeMove[2]), CSPFT_FLOAT}, - {"strafeRotP", offsetof(WeaponFullDef, weapDef.strafeRot[0]), CSPFT_FLOAT}, - {"strafeRotY", offsetof(WeaponFullDef, weapDef.strafeRot[1]), CSPFT_FLOAT}, - {"strafeRotR", offsetof(WeaponFullDef, weapDef.strafeRot[2]), CSPFT_FLOAT}, - {"duckedOfsF", offsetof(WeaponFullDef, weapDef.vDuckedOfs[0]), CSPFT_FLOAT}, - {"duckedOfsR", offsetof(WeaponFullDef, weapDef.vDuckedOfs[1]), CSPFT_FLOAT}, - {"duckedOfsU", offsetof(WeaponFullDef, weapDef.vDuckedOfs[2]), CSPFT_FLOAT}, - {"duckedMoveF", offsetof(WeaponFullDef, weapDef.vDuckedMove[0]), CSPFT_FLOAT}, - {"duckedMoveR", offsetof(WeaponFullDef, weapDef.vDuckedMove[1]), CSPFT_FLOAT}, - {"duckedMoveU", offsetof(WeaponFullDef, weapDef.vDuckedMove[2]), CSPFT_FLOAT}, - {"duckedRotP", offsetof(WeaponFullDef, weapDef.vDuckedRot[0]), CSPFT_FLOAT}, - {"duckedRotY", offsetof(WeaponFullDef, weapDef.vDuckedRot[1]), CSPFT_FLOAT}, - {"duckedRotR", offsetof(WeaponFullDef, weapDef.vDuckedRot[2]), CSPFT_FLOAT}, - {"proneOfsF", offsetof(WeaponFullDef, weapDef.vProneOfs[0]), CSPFT_FLOAT}, - {"proneOfsR", offsetof(WeaponFullDef, weapDef.vProneOfs[1]), CSPFT_FLOAT}, - {"proneOfsU", offsetof(WeaponFullDef, weapDef.vProneOfs[2]), CSPFT_FLOAT}, - {"proneMoveF", offsetof(WeaponFullDef, weapDef.vProneMove[0]), CSPFT_FLOAT}, - {"proneMoveR", offsetof(WeaponFullDef, weapDef.vProneMove[1]), CSPFT_FLOAT}, - {"proneMoveU", offsetof(WeaponFullDef, weapDef.vProneMove[2]), CSPFT_FLOAT}, - {"proneRotP", offsetof(WeaponFullDef, weapDef.vProneRot[0]), CSPFT_FLOAT}, - {"proneRotY", offsetof(WeaponFullDef, weapDef.vProneRot[1]), CSPFT_FLOAT}, - {"proneRotR", offsetof(WeaponFullDef, weapDef.vProneRot[2]), CSPFT_FLOAT}, - {"posMoveRate", offsetof(WeaponFullDef, weapDef.fPosMoveRate), CSPFT_FLOAT}, - {"posProneMoveRate", offsetof(WeaponFullDef, weapDef.fPosProneMoveRate), CSPFT_FLOAT}, - {"standMoveMinSpeed", offsetof(WeaponFullDef, weapDef.fStandMoveMinSpeed), CSPFT_FLOAT}, - {"duckedMoveMinSpeed", offsetof(WeaponFullDef, weapDef.fDuckedMoveMinSpeed), CSPFT_FLOAT}, - {"proneMoveMinSpeed", offsetof(WeaponFullDef, weapDef.fProneMoveMinSpeed), CSPFT_FLOAT}, - {"posRotRate", offsetof(WeaponFullDef, weapDef.fPosRotRate), CSPFT_FLOAT}, - {"posProneRotRate", offsetof(WeaponFullDef, weapDef.fPosProneRotRate), CSPFT_FLOAT}, - {"standRotMinSpeed", offsetof(WeaponFullDef, weapDef.fStandRotMinSpeed), CSPFT_FLOAT}, - {"duckedRotMinSpeed", offsetof(WeaponFullDef, weapDef.fDuckedRotMinSpeed), CSPFT_FLOAT}, - {"proneRotMinSpeed", offsetof(WeaponFullDef, weapDef.fProneRotMinSpeed), CSPFT_FLOAT}, - {"worldModel", offsetof(WeaponFullDef, worldModel[0]), CSPFT_XMODEL}, - {"worldModel2", offsetof(WeaponFullDef, worldModel[1]), CSPFT_XMODEL}, - {"worldModel3", offsetof(WeaponFullDef, worldModel[2]), CSPFT_XMODEL}, - {"worldModel4", offsetof(WeaponFullDef, worldModel[3]), CSPFT_XMODEL}, - {"worldModel5", offsetof(WeaponFullDef, worldModel[4]), CSPFT_XMODEL}, - {"worldModel6", offsetof(WeaponFullDef, worldModel[5]), CSPFT_XMODEL}, - {"worldModel7", offsetof(WeaponFullDef, worldModel[6]), CSPFT_XMODEL}, - {"worldModel8", offsetof(WeaponFullDef, worldModel[7]), CSPFT_XMODEL}, - {"worldModel9", offsetof(WeaponFullDef, worldModel[8]), CSPFT_XMODEL}, - {"worldModel10", offsetof(WeaponFullDef, worldModel[9]), CSPFT_XMODEL}, - {"worldModel11", offsetof(WeaponFullDef, worldModel[10]), CSPFT_XMODEL}, - {"worldModel12", offsetof(WeaponFullDef, worldModel[11]), CSPFT_XMODEL}, - {"worldModel13", offsetof(WeaponFullDef, worldModel[12]), CSPFT_XMODEL}, - {"worldModel14", offsetof(WeaponFullDef, worldModel[13]), CSPFT_XMODEL}, - {"worldModel15", offsetof(WeaponFullDef, worldModel[14]), CSPFT_XMODEL}, - {"worldModel16", offsetof(WeaponFullDef, worldModel[15]), CSPFT_XMODEL}, - {"worldClipModel", offsetof(WeaponFullDef, weapDef.worldClipModel), CSPFT_XMODEL}, - {"rocketModel", offsetof(WeaponFullDef, weapDef.rocketModel), CSPFT_XMODEL}, - {"knifeModel", offsetof(WeaponFullDef, weapDef.knifeModel), CSPFT_XMODEL}, - {"worldKnifeModel", offsetof(WeaponFullDef, weapDef.worldKnifeModel), CSPFT_XMODEL}, - {"hudIcon", offsetof(WeaponFullDef, weapDef.hudIcon), CSPFT_MATERIAL}, - {"hudIconRatio", offsetof(WeaponFullDef, weapDef.hudIconRatio), WFT_ICONRATIO_HUD}, - {"pickupIcon", offsetof(WeaponFullDef, weapDef.pickupIcon), CSPFT_MATERIAL}, - {"pickupIconRatio", offsetof(WeaponFullDef, weapDef.pickupIconRatio), WFT_ICONRATIO_PICKUP}, - {"ammoCounterIcon", offsetof(WeaponFullDef, weapDef.ammoCounterIcon), CSPFT_MATERIAL}, - {"ammoCounterIconRatio", offsetof(WeaponFullDef, weapDef.ammoCounterIconRatio), WFT_ICONRATIO_AMMOCOUNTER}, - {"ammoCounterClip", offsetof(WeaponFullDef, weapDef.ammoCounterClip), WFT_AMMOCOUNTER_CLIPTYPE}, - {"startAmmo", offsetof(WeaponFullDef, weapDef.iStartAmmo), CSPFT_INT}, - {"shareAmmo", offsetof(WeaponFullDef, weapDef.sharedAmmo), CSPFT_BOOL}, - {"ammoName", offsetof(WeaponFullDef, weapDef.szAmmoName), CSPFT_STRING}, - {"clipName", offsetof(WeaponFullDef, weapDef.szClipName), CSPFT_STRING}, - {"maxAmmo", offsetof(WeaponFullDef, weapDef.iMaxAmmo), CSPFT_INT}, - {"clipSize", offsetof(WeaponFullDef, weapCompleteDef.iClipSize), CSPFT_INT}, - {"shotCount", offsetof(WeaponFullDef, weapDef.shotCount), CSPFT_INT}, - {"sharedAmmoCapName", offsetof(WeaponFullDef, weapDef.szSharedAmmoCapName), CSPFT_STRING}, - {"sharedAmmoCap", offsetof(WeaponFullDef, weapDef.iSharedAmmoCap), CSPFT_INT}, - {"damage", offsetof(WeaponFullDef, weapDef.damage), CSPFT_INT}, - {"playerDamage", offsetof(WeaponFullDef, weapDef.playerDamage), CSPFT_INT}, - {"meleeDamage", offsetof(WeaponFullDef, weapDef.iMeleeDamage), CSPFT_INT}, - {"minDamage", offsetof(WeaponFullDef, weapDef.minDamage), CSPFT_INT}, - {"minPlayerDamage", offsetof(WeaponFullDef, weapDef.minPlayerDamage), CSPFT_INT}, - {"maxDamageRange", offsetof(WeaponFullDef, weapDef.fMaxDamageRange), CSPFT_FLOAT}, - {"minDamageRange", offsetof(WeaponFullDef, weapDef.fMinDamageRange), CSPFT_FLOAT}, - {"destabilizationRateTime", offsetof(WeaponFullDef, weapDef.destabilizationRateTime), CSPFT_FLOAT}, - {"destabilizationCurvatureMax", offsetof(WeaponFullDef, weapDef.destabilizationCurvatureMax), CSPFT_FLOAT}, - {"destabilizeDistance", offsetof(WeaponFullDef, weapDef.destabilizeDistance), CSPFT_INT}, - {"fireDelay", offsetof(WeaponFullDef, weapDef.iFireDelay), CSPFT_MILLISECONDS}, - {"meleeDelay", offsetof(WeaponFullDef, weapDef.iMeleeDelay), CSPFT_MILLISECONDS}, - {"meleeChargeDelay", offsetof(WeaponFullDef, weapDef.meleeChargeDelay), CSPFT_MILLISECONDS}, - {"fireTime", offsetof(WeaponFullDef, weapCompleteDef.iFireTime), CSPFT_MILLISECONDS}, - {"rechamberTime", offsetof(WeaponFullDef, weapDef.iRechamberTime), CSPFT_MILLISECONDS}, - {"rechamberTimeOneHanded", offsetof(WeaponFullDef, weapDef.rechamberTimeOneHanded), CSPFT_MILLISECONDS}, - {"rechamberBoltTime", offsetof(WeaponFullDef, weapDef.iRechamberBoltTime), CSPFT_MILLISECONDS}, - {"holdFireTime", offsetof(WeaponFullDef, weapDef.iHoldFireTime), CSPFT_MILLISECONDS}, - {"detonateTime", offsetof(WeaponFullDef, weapDef.iDetonateTime), CSPFT_MILLISECONDS}, - {"detonateDelay", offsetof(WeaponFullDef, weapDef.iDetonateDelay), CSPFT_MILLISECONDS}, - {"meleeTime", offsetof(WeaponFullDef, weapDef.iMeleeTime), CSPFT_MILLISECONDS}, - {"meleeChargeTime", offsetof(WeaponFullDef, weapDef.meleeChargeTime), CSPFT_MILLISECONDS}, - {"reloadTime", offsetof(WeaponFullDef, weapDef.iReloadTime), CSPFT_MILLISECONDS}, - {"reloadShowRocketTime", offsetof(WeaponFullDef, weapDef.reloadShowRocketTime), CSPFT_MILLISECONDS}, - {"reloadEmptyTime", offsetof(WeaponFullDef, weapDef.iReloadEmptyTime), CSPFT_MILLISECONDS}, - {"reloadAddTime", offsetof(WeaponFullDef, weapDef.iReloadAddTime), CSPFT_MILLISECONDS}, - {"reloadStartTime", offsetof(WeaponFullDef, weapDef.iReloadStartTime), CSPFT_MILLISECONDS}, - {"reloadStartAddTime", offsetof(WeaponFullDef, weapDef.iReloadStartAddTime), CSPFT_MILLISECONDS}, - {"reloadEndTime", offsetof(WeaponFullDef, weapDef.iReloadEndTime), CSPFT_MILLISECONDS}, - {"dropTime", offsetof(WeaponFullDef, weapDef.iDropTime), CSPFT_MILLISECONDS}, - {"raiseTime", offsetof(WeaponFullDef, weapDef.iRaiseTime), CSPFT_MILLISECONDS}, - {"altDropTime", offsetof(WeaponFullDef, weapDef.iAltDropTime), CSPFT_MILLISECONDS}, - {"altRaiseTime", offsetof(WeaponFullDef, weapCompleteDef.iAltRaiseTime), CSPFT_MILLISECONDS}, - {"quickDropTime", offsetof(WeaponFullDef, weapDef.quickDropTime), CSPFT_MILLISECONDS}, - {"quickRaiseTime", offsetof(WeaponFullDef, weapDef.quickRaiseTime), CSPFT_MILLISECONDS}, - {"firstRaiseTime", offsetof(WeaponFullDef, weapCompleteDef.iFirstRaiseTime), CSPFT_MILLISECONDS}, - {"breachRaiseTime", offsetof(WeaponFullDef, weapDef.iBreachRaiseTime), CSPFT_MILLISECONDS}, - {"emptyRaiseTime", offsetof(WeaponFullDef, weapDef.iEmptyRaiseTime), CSPFT_MILLISECONDS}, - {"emptyDropTime", offsetof(WeaponFullDef, weapDef.iEmptyDropTime), CSPFT_MILLISECONDS}, - {"sprintInTime", offsetof(WeaponFullDef, weapDef.sprintInTime), CSPFT_MILLISECONDS}, - {"sprintLoopTime", offsetof(WeaponFullDef, weapDef.sprintLoopTime), CSPFT_MILLISECONDS}, - {"sprintOutTime", offsetof(WeaponFullDef, weapDef.sprintOutTime), CSPFT_MILLISECONDS}, - {"stunnedTimeBegin", offsetof(WeaponFullDef, weapDef.stunnedTimeBegin), CSPFT_MILLISECONDS}, - {"stunnedTimeLoop", offsetof(WeaponFullDef, weapDef.stunnedTimeLoop), CSPFT_MILLISECONDS}, - {"stunnedTimeEnd", offsetof(WeaponFullDef, weapDef.stunnedTimeEnd), CSPFT_MILLISECONDS}, - {"nightVisionWearTime", offsetof(WeaponFullDef, weapDef.nightVisionWearTime), CSPFT_MILLISECONDS}, - {"nightVisionWearTimeFadeOutEnd", offsetof(WeaponFullDef, weapDef.nightVisionWearTimeFadeOutEnd), CSPFT_MILLISECONDS}, - {"nightVisionWearTimePowerUp", offsetof(WeaponFullDef, weapDef.nightVisionWearTimePowerUp), CSPFT_MILLISECONDS}, - {"nightVisionRemoveTime", offsetof(WeaponFullDef, weapDef.nightVisionRemoveTime), CSPFT_MILLISECONDS}, - {"nightVisionRemoveTimePowerDown", offsetof(WeaponFullDef, weapDef.nightVisionRemoveTimePowerDown), CSPFT_MILLISECONDS}, - {"nightVisionRemoveTimeFadeInStart", offsetof(WeaponFullDef, weapDef.nightVisionRemoveTimeFadeInStart), CSPFT_MILLISECONDS}, - {"fuseTime", offsetof(WeaponFullDef, weapDef.fuseTime), CSPFT_MILLISECONDS}, - {"aifuseTime", offsetof(WeaponFullDef, weapDef.aiFuseTime), CSPFT_MILLISECONDS}, - {"lockonSupported", offsetof(WeaponFullDef, weapDef.lockonSupported), CSPFT_BOOL}, - {"requireLockonToFire", offsetof(WeaponFullDef, weapDef.requireLockonToFire), CSPFT_BOOL}, - {"bigExplosion", offsetof(WeaponFullDef, weapDef.bigExplosion), CSPFT_BOOL}, - {"noAdsWhenMagEmpty", offsetof(WeaponFullDef, weapDef.noAdsWhenMagEmpty), CSPFT_BOOL}, - {"inheritsPerks", offsetof(WeaponFullDef, weapDef.inheritsPerks), CSPFT_BOOL}, - {"avoidDropCleanup", offsetof(WeaponFullDef, weapDef.avoidDropCleanup), CSPFT_BOOL}, - {"autoAimRange", offsetof(WeaponFullDef, weapDef.autoAimRange), CSPFT_FLOAT}, - {"aimAssistRange", offsetof(WeaponFullDef, weapDef.aimAssistRange), CSPFT_FLOAT}, - {"aimAssistRangeAds", offsetof(WeaponFullDef, weapDef.aimAssistRangeAds), CSPFT_FLOAT}, - {"aimPadding", offsetof(WeaponFullDef, weapDef.aimPadding), CSPFT_FLOAT}, - {"enemyCrosshairRange", offsetof(WeaponFullDef, weapDef.enemyCrosshairRange), CSPFT_FLOAT}, - {"crosshairColorChange", offsetof(WeaponFullDef, weapDef.crosshairColorChange), CSPFT_BOOL}, - {"moveSpeedScale", offsetof(WeaponFullDef, weapDef.moveSpeedScale), CSPFT_FLOAT}, - {"adsMoveSpeedScale", offsetof(WeaponFullDef, weapDef.adsMoveSpeedScale), CSPFT_FLOAT}, - {"sprintDurationScale", offsetof(WeaponFullDef, weapDef.sprintDurationScale), CSPFT_FLOAT}, - {"idleCrouchFactor", offsetof(WeaponFullDef, weapDef.fIdleCrouchFactor), CSPFT_FLOAT}, - {"idleProneFactor", offsetof(WeaponFullDef, weapDef.fIdleProneFactor), CSPFT_FLOAT}, - {"gunMaxPitch", offsetof(WeaponFullDef, weapDef.fGunMaxPitch), CSPFT_FLOAT}, - {"gunMaxYaw", offsetof(WeaponFullDef, weapDef.fGunMaxYaw), CSPFT_FLOAT}, - {"swayMaxAngle", offsetof(WeaponFullDef, weapDef.swayMaxAngle), CSPFT_FLOAT}, - {"swayLerpSpeed", offsetof(WeaponFullDef, weapDef.swayLerpSpeed), CSPFT_FLOAT}, - {"swayPitchScale", offsetof(WeaponFullDef, weapDef.swayPitchScale), CSPFT_FLOAT}, - {"swayYawScale", offsetof(WeaponFullDef, weapDef.swayYawScale), CSPFT_FLOAT}, - {"swayHorizScale", offsetof(WeaponFullDef, weapDef.swayHorizScale), CSPFT_FLOAT}, - {"swayVertScale", offsetof(WeaponFullDef, weapDef.swayVertScale), CSPFT_FLOAT}, - {"swayShellShockScale", offsetof(WeaponFullDef, weapDef.swayShellShockScale), CSPFT_FLOAT}, - {"adsSwayMaxAngle", offsetof(WeaponFullDef, weapDef.adsSwayMaxAngle), CSPFT_FLOAT}, - {"adsSwayLerpSpeed", offsetof(WeaponFullDef, weapDef.adsSwayLerpSpeed), CSPFT_FLOAT}, - {"adsSwayPitchScale", offsetof(WeaponFullDef, weapDef.adsSwayPitchScale), CSPFT_FLOAT}, - {"adsSwayYawScale", offsetof(WeaponFullDef, weapDef.adsSwayYawScale), CSPFT_FLOAT}, - {"adsSwayHorizScale", offsetof(WeaponFullDef, weapDef.adsSwayHorizScale), CSPFT_FLOAT}, - {"adsSwayVertScale", offsetof(WeaponFullDef, weapDef.adsSwayVertScale), CSPFT_FLOAT}, - {"rifleBullet", offsetof(WeaponFullDef, weapDef.bRifleBullet), CSPFT_BOOL}, - {"armorPiercing", offsetof(WeaponFullDef, weapDef.armorPiercing), CSPFT_BOOL}, - {"boltAction", offsetof(WeaponFullDef, weapDef.bBoltAction), CSPFT_BOOL}, - {"aimDownSight", offsetof(WeaponFullDef, weapDef.aimDownSight), CSPFT_BOOL}, - {"rechamberWhileAds", offsetof(WeaponFullDef, weapDef.bRechamberWhileAds), CSPFT_BOOL}, - {"bBulletExplosiveDamage", offsetof(WeaponFullDef, weapDef.bBulletExplosiveDamage), CSPFT_BOOL}, - {"adsViewErrorMin", offsetof(WeaponFullDef, weapDef.adsViewErrorMin), CSPFT_FLOAT}, - {"adsViewErrorMax", offsetof(WeaponFullDef, weapDef.adsViewErrorMax), CSPFT_FLOAT}, - {"clipOnly", offsetof(WeaponFullDef, weapDef.bClipOnly), CSPFT_BOOL}, - {"noAmmoPickup", offsetof(WeaponFullDef, weapDef.noAmmoPickup), CSPFT_BOOL}, - {"cookOffHold", offsetof(WeaponFullDef, weapDef.bCookOffHold), CSPFT_BOOL}, - {"adsFire", offsetof(WeaponFullDef, weapDef.adsFireOnly), CSPFT_BOOL}, - {"cancelAutoHolsterWhenEmpty", offsetof(WeaponFullDef, weapDef.cancelAutoHolsterWhenEmpty), CSPFT_BOOL}, - {"disableSwitchToWhenEmpty", offsetof(WeaponFullDef, weapDef.disableSwitchToWhenEmpty), CSPFT_BOOL}, - {"suppressAmmoReserveDisplay", offsetof(WeaponFullDef, weapDef.suppressAmmoReserveDisplay), CSPFT_BOOL}, - {"enhanced", offsetof(WeaponFullDef, weapCompleteDef.enhanced), CSPFT_BOOL}, - {"motionTracker", offsetof(WeaponFullDef, weapCompleteDef.motionTracker), CSPFT_BOOL}, - {"laserSightDuringNightvision", offsetof(WeaponFullDef, weapDef.laserSightDuringNightvision), CSPFT_BOOL}, - {"markableViewmodel", offsetof(WeaponFullDef, weapDef.markableViewmodel), CSPFT_BOOL}, - {"physCollmap", offsetof(WeaponFullDef, weapDef.physCollmap), CSPFT_PHYS_COLLMAP}, - {"noDualWield", offsetof(WeaponFullDef, weapDef.noDualWield), CSPFT_BOOL}, - {"dualWieldViewModelOffset", offsetof(WeaponFullDef, weapDef.dualWieldViewModelOffset), CSPFT_FLOAT}, - {"killIcon", offsetof(WeaponFullDef, weapCompleteDef.killIcon), CSPFT_MATERIAL}, - {"killIconRatio", offsetof(WeaponFullDef, weapDef.killIconRatio), WFT_ICONRATIO_KILL}, - {"flipKillIcon", offsetof(WeaponFullDef, weapDef.flipKillIcon), CSPFT_BOOL}, - {"dpadIcon", offsetof(WeaponFullDef, weapCompleteDef.dpadIcon), CSPFT_MATERIAL}, - {"dpadIconRatio", offsetof(WeaponFullDef, weapCompleteDef.dpadIconRatio), WFT_ICONRATIO_DPAD}, - {"dpadIconShowsAmmo", offsetof(WeaponFullDef, weapCompleteDef.dpadIconShowsAmmo), CSPFT_BOOL}, - {"noPartialReload", offsetof(WeaponFullDef, weapDef.bNoPartialReload), CSPFT_BOOL}, - {"segmentedReload", offsetof(WeaponFullDef, weapDef.bSegmentedReload), CSPFT_BOOL}, - {"reloadAmmoAdd", offsetof(WeaponFullDef, weapDef.iReloadAmmoAdd), CSPFT_INT}, - {"reloadStartAdd", offsetof(WeaponFullDef, weapDef.iReloadStartAdd), CSPFT_INT}, - {"altWeapon", offsetof(WeaponFullDef, weapCompleteDef.szAltWeaponName), CSPFT_STRING}, - {"dropAmmoMin", offsetof(WeaponFullDef, weapDef.ammoDropStockMin), CSPFT_INT}, - {"dropAmmoMax", offsetof(WeaponFullDef, weapCompleteDef.ammoDropStockMax), CSPFT_INT}, - {"ammoDropClipPercentMin", offsetof(WeaponFullDef, weapDef.ammoDropClipPercentMin), CSPFT_INT}, - {"ammoDropClipPercentMax", offsetof(WeaponFullDef, weapDef.ammoDropClipPercentMax), CSPFT_INT}, - {"blocksProne", offsetof(WeaponFullDef, weapDef.blocksProne), CSPFT_BOOL}, - {"silenced", offsetof(WeaponFullDef, weapDef.silenced), CSPFT_BOOL}, - {"isRollingGrenade", offsetof(WeaponFullDef, weapDef.isRollingGrenade), CSPFT_BOOL}, - {"explosionRadius", offsetof(WeaponFullDef, weapDef.iExplosionRadius), CSPFT_INT}, - {"explosionRadiusMin", offsetof(WeaponFullDef, weapDef.iExplosionRadiusMin), CSPFT_INT}, - {"explosionInnerDamage", offsetof(WeaponFullDef, weapDef.iExplosionInnerDamage), CSPFT_INT}, - {"explosionOuterDamage", offsetof(WeaponFullDef, weapDef.iExplosionOuterDamage), CSPFT_INT}, - {"damageConeAngle", offsetof(WeaponFullDef, weapDef.damageConeAngle), CSPFT_FLOAT}, - {"bulletExplDmgMult", offsetof(WeaponFullDef, weapDef.bulletExplDmgMult), CSPFT_FLOAT}, - {"bulletExplRadiusMult", offsetof(WeaponFullDef, weapDef.bulletExplRadiusMult), CSPFT_FLOAT}, - {"projectileSpeed", offsetof(WeaponFullDef, weapDef.iProjectileSpeed), CSPFT_INT}, - {"projectileSpeedUp", offsetof(WeaponFullDef, weapDef.iProjectileSpeedUp), CSPFT_INT}, - {"projectileSpeedForward", offsetof(WeaponFullDef, weapDef.iProjectileSpeedForward), CSPFT_INT}, - {"projectileActivateDist", offsetof(WeaponFullDef, weapDef.iProjectileActivateDist), CSPFT_INT}, - {"projectileLifetime", offsetof(WeaponFullDef, weapDef.projLifetime), CSPFT_FLOAT}, - {"timeToAccelerate", offsetof(WeaponFullDef, weapDef.timeToAccelerate), CSPFT_FLOAT}, - {"projectileCurvature", offsetof(WeaponFullDef, weapDef.projectileCurvature), CSPFT_FLOAT}, - {"projectileModel", offsetof(WeaponFullDef, weapDef.projectileModel), CSPFT_XMODEL}, - {"projExplosionType", offsetof(WeaponFullDef, weapDef.projExplosion), WFT_PROJ_EXPLOSION}, - {"projExplosionEffect", offsetof(WeaponFullDef, weapDef.projExplosionEffect), CSPFT_FX}, - {"projExplosionEffectForceNormalUp", offsetof(WeaponFullDef, weapDef.projExplosionEffectForceNormalUp), CSPFT_BOOL}, - {"projExplosionSound", offsetof(WeaponFullDef, weapDef.projExplosionSound), CSPFT_SOUND}, - {"projDudEffect", offsetof(WeaponFullDef, weapDef.projDudEffect), CSPFT_FX}, - {"projDudSound", offsetof(WeaponFullDef, weapDef.projDudSound), CSPFT_SOUND}, - {"projImpactExplode", offsetof(WeaponFullDef, weapDef.bProjImpactExplode), CSPFT_BOOL}, - {"stickiness", offsetof(WeaponFullDef, weapDef.stickiness), WFT_STICKINESS}, - {"stickToPlayers", offsetof(WeaponFullDef, weapDef.stickToPlayers), CSPFT_BOOL}, - {"hasDetonator", offsetof(WeaponFullDef, weapDef.hasDetonator), CSPFT_BOOL}, - {"disableFiring", offsetof(WeaponFullDef, weapDef.disableFiring), CSPFT_BOOL}, - {"timedDetonation", offsetof(WeaponFullDef, weapDef.timedDetonation), CSPFT_BOOL}, - {"rotate", offsetof(WeaponFullDef, weapDef.rotate), CSPFT_BOOL}, - {"holdButtonToThrow", offsetof(WeaponFullDef, weapDef.holdButtonToThrow), CSPFT_BOOL}, - {"freezeMovementWhenFiring", offsetof(WeaponFullDef, weapDef.freezeMovementWhenFiring), CSPFT_BOOL}, - {"lowAmmoWarningThreshold", offsetof(WeaponFullDef, weapDef.lowAmmoWarningThreshold), CSPFT_FLOAT}, - {"ricochetChance", offsetof(WeaponFullDef, weapDef.ricochetChance), CSPFT_FLOAT}, - {"offhandHoldIsCancelable", offsetof(WeaponFullDef, weapDef.offhandHoldIsCancelable), CSPFT_BOOL}, - {"parallelDefaultBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_DEFAULT]), CSPFT_FLOAT}, - {"parallelBarkBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_BARK]), CSPFT_FLOAT}, - {"parallelBrickBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_BRICK]), CSPFT_FLOAT}, - {"parallelCarpetBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_CARPET]), CSPFT_FLOAT}, - {"parallelClothBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_CLOTH]), CSPFT_FLOAT}, - {"parallelConcreteBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_CONCRETE]), CSPFT_FLOAT}, - {"parallelDirtBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_DIRT]), CSPFT_FLOAT}, - {"parallelFleshBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_FLESH]), CSPFT_FLOAT}, - {"parallelFoliageBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_FOLIAGE]), CSPFT_FLOAT}, - {"parallelGlassBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_GLASS]), CSPFT_FLOAT}, - {"parallelGrassBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_GRASS]), CSPFT_FLOAT}, - {"parallelGravelBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_GRAVEL]), CSPFT_FLOAT}, - {"parallelIceBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_ICE]), CSPFT_FLOAT}, - {"parallelMetalBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_METAL]), CSPFT_FLOAT}, - {"parallelMudBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_MUD]), CSPFT_FLOAT}, - {"parallelPaperBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_PAPER]), CSPFT_FLOAT}, - {"parallelPlasterBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_PLASTER]), CSPFT_FLOAT}, - {"parallelRockBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_ROCK]), CSPFT_FLOAT}, - {"parallelSandBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_SAND]), CSPFT_FLOAT}, - {"parallelSnowBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_SNOW]), CSPFT_FLOAT}, - {"parallelWaterBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_WATER]), CSPFT_FLOAT}, - {"parallelWoodBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_WOOD]), CSPFT_FLOAT}, - {"parallelAsphaltBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_ASPHALT]), CSPFT_FLOAT}, - {"parallelCeramicBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_CERAMIC]), CSPFT_FLOAT}, - {"parallelPlasticBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_PLASTIC]), CSPFT_FLOAT}, - {"parallelRubberBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_RUBBER]), CSPFT_FLOAT}, - {"parallelCushionBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_CUSHION]), CSPFT_FLOAT}, - {"parallelFruitBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_FRUIT]), CSPFT_FLOAT}, - {"parallelPaintedMetalBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_PAINTED_METAL]), CSPFT_FLOAT}, - {"parallelRiotShieldBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_RIOT_SHIELD]), CSPFT_FLOAT}, - {"parallelSlushBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_SLUSH]), CSPFT_FLOAT}, - {"perpendicularDefaultBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_DEFAULT]), CSPFT_FLOAT}, - {"perpendicularBarkBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_BARK]), CSPFT_FLOAT}, - {"perpendicularBrickBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_BRICK]), CSPFT_FLOAT}, - {"perpendicularCarpetBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_CARPET]), CSPFT_FLOAT}, - {"perpendicularClothBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_CLOTH]), CSPFT_FLOAT}, - {"perpendicularConcreteBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_CONCRETE]), CSPFT_FLOAT}, - {"perpendicularDirtBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_DIRT]), CSPFT_FLOAT}, - {"perpendicularFleshBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_FLESH]), CSPFT_FLOAT}, - {"perpendicularFoliageBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_FOLIAGE]), CSPFT_FLOAT}, - {"perpendicularGlassBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_GLASS]), CSPFT_FLOAT}, - {"perpendicularGrassBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_GRASS]), CSPFT_FLOAT}, - {"perpendicularGravelBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_GRAVEL]), CSPFT_FLOAT}, - {"perpendicularIceBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_ICE]), CSPFT_FLOAT}, - {"perpendicularMetalBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_METAL]), CSPFT_FLOAT}, - {"perpendicularMudBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_MUD]), CSPFT_FLOAT}, - {"perpendicularPaperBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_PAPER]), CSPFT_FLOAT}, - {"perpendicularPlasterBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_PLASTER]), CSPFT_FLOAT}, - {"perpendicularRockBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_ROCK]), CSPFT_FLOAT}, - {"perpendicularSandBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_SAND]), CSPFT_FLOAT}, - {"perpendicularSnowBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_SNOW]), CSPFT_FLOAT}, - {"perpendicularWaterBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_WATER]), CSPFT_FLOAT}, - {"perpendicularWoodBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_WOOD]), CSPFT_FLOAT}, - {"perpendicularAsphaltBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_ASPHALT]), CSPFT_FLOAT}, - {"perpendicularCeramicBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_CERAMIC]), CSPFT_FLOAT}, - {"perpendicularPlasticBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_PLASTIC]), CSPFT_FLOAT}, - {"perpendicularRubberBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_RUBBER]), CSPFT_FLOAT}, - {"perpendicularCushionBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_CUSHION]), CSPFT_FLOAT}, - {"perpendicularFruitBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_FRUIT]), CSPFT_FLOAT}, - {"perpendicularPaintedMetalBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_PAINTED_METAL]), CSPFT_FLOAT}, - {"perpendicularRiotShieldBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_RIOT_SHIELD]), CSPFT_FLOAT}, - {"perpendicularSlushBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_SLUSH]), CSPFT_FLOAT}, - {"projTrailEffect", offsetof(WeaponFullDef, weapDef.projTrailEffect), CSPFT_FX}, - {"projBeaconEffect", offsetof(WeaponFullDef, weapDef.projBeaconEffect), CSPFT_FX}, - {"projectileRed", offsetof(WeaponFullDef, weapDef.vProjectileColor[0]), CSPFT_FLOAT}, - {"projectileGreen", offsetof(WeaponFullDef, weapDef.vProjectileColor[1]), CSPFT_FLOAT}, - {"projectileBlue", offsetof(WeaponFullDef, weapDef.vProjectileColor[2]), CSPFT_FLOAT}, - {"guidedMissileType", offsetof(WeaponFullDef, weapDef.guidedMissileType), WFT_GUIDED_MISSILE_TYPE}, - {"maxSteeringAccel", offsetof(WeaponFullDef, weapDef.maxSteeringAccel), CSPFT_FLOAT}, - {"projIgnitionDelay", offsetof(WeaponFullDef, weapDef.projIgnitionDelay), CSPFT_INT}, - {"projIgnitionEffect", offsetof(WeaponFullDef, weapDef.projIgnitionEffect), CSPFT_FX}, - {"projIgnitionSound", offsetof(WeaponFullDef, weapDef.projIgnitionSound), CSPFT_SOUND}, - {"adsTransInTime", offsetof(WeaponFullDef, weapCompleteDef.iAdsTransInTime), CSPFT_MILLISECONDS}, - {"adsTransOutTime", offsetof(WeaponFullDef, weapCompleteDef.iAdsTransOutTime), CSPFT_MILLISECONDS}, - {"adsIdleAmount", offsetof(WeaponFullDef, weapDef.fAdsIdleAmount), CSPFT_FLOAT}, - {"adsIdleSpeed", offsetof(WeaponFullDef, weapDef.adsIdleSpeed), CSPFT_FLOAT}, - {"adsZoomFov", offsetof(WeaponFullDef, weapCompleteDef.fAdsZoomFov), CSPFT_FLOAT}, - {"adsZoomInFrac", offsetof(WeaponFullDef, weapDef.fAdsZoomInFrac), CSPFT_FLOAT}, - {"adsZoomOutFrac", offsetof(WeaponFullDef, weapDef.fAdsZoomOutFrac), CSPFT_FLOAT}, - {"adsOverlayShader", offsetof(WeaponFullDef, weapDef.overlayMaterial), CSPFT_MATERIAL}, - {"adsOverlayShaderLowRes", offsetof(WeaponFullDef, weapDef.overlayMaterialLowRes), CSPFT_MATERIAL}, - {"adsOverlayShaderEMP", offsetof(WeaponFullDef, weapDef.overlayMaterialEMP), CSPFT_MATERIAL}, - {"adsOverlayShaderEMPLowRes", offsetof(WeaponFullDef, weapDef.overlayMaterialEMPLowRes), CSPFT_MATERIAL}, - {"adsOverlayReticle", offsetof(WeaponFullDef, weapDef.overlayReticle), WFT_OVERLAYRETICLE}, - {"adsOverlayInterface", offsetof(WeaponFullDef, weapDef.overlayInterface), WFT_OVERLAYINTERFACE}, - {"adsOverlayWidth", offsetof(WeaponFullDef, weapDef.overlayWidth), CSPFT_FLOAT}, - {"adsOverlayHeight", offsetof(WeaponFullDef, weapDef.overlayHeight), CSPFT_FLOAT}, - {"adsOverlayWidthSplitscreen", offsetof(WeaponFullDef, weapDef.overlayWidthSplitscreen), CSPFT_FLOAT}, - {"adsOverlayHeightSplitscreen", offsetof(WeaponFullDef, weapDef.overlayHeightSplitscreen), CSPFT_FLOAT}, - {"adsBobFactor", offsetof(WeaponFullDef, weapDef.fAdsBobFactor), CSPFT_FLOAT}, - {"adsViewBobMult", offsetof(WeaponFullDef, weapDef.fAdsViewBobMult), CSPFT_FLOAT}, - {"adsAimPitch", offsetof(WeaponFullDef, weapDef.fAdsAimPitch), CSPFT_FLOAT}, - {"adsCrosshairInFrac", offsetof(WeaponFullDef, weapDef.fAdsCrosshairInFrac), CSPFT_FLOAT}, - {"adsCrosshairOutFrac", offsetof(WeaponFullDef, weapDef.fAdsCrosshairOutFrac), CSPFT_FLOAT}, - {"adsReloadTransTime", offsetof(WeaponFullDef, weapDef.iPositionReloadTransTime), CSPFT_MILLISECONDS}, - {"adsGunKickReducedKickBullets", offsetof(WeaponFullDef, weapDef.adsGunKickReducedKickBullets), CSPFT_INT}, - {"adsGunKickReducedKickPercent", offsetof(WeaponFullDef, weapDef.adsGunKickReducedKickPercent), CSPFT_FLOAT}, - {"adsGunKickPitchMin", offsetof(WeaponFullDef, weapDef.fAdsGunKickPitchMin), CSPFT_FLOAT}, - {"adsGunKickPitchMax", offsetof(WeaponFullDef, weapDef.fAdsGunKickPitchMax), CSPFT_FLOAT}, - {"adsGunKickYawMin", offsetof(WeaponFullDef, weapDef.fAdsGunKickYawMin), CSPFT_FLOAT}, - {"adsGunKickYawMax", offsetof(WeaponFullDef, weapDef.fAdsGunKickYawMax), CSPFT_FLOAT}, - {"adsGunKickAccel", offsetof(WeaponFullDef, weapDef.fAdsGunKickAccel), CSPFT_FLOAT}, - {"adsGunKickSpeedMax", offsetof(WeaponFullDef, weapDef.fAdsGunKickSpeedMax), CSPFT_FLOAT}, - {"adsGunKickSpeedDecay", offsetof(WeaponFullDef, weapDef.fAdsGunKickSpeedDecay), CSPFT_FLOAT}, - {"adsGunKickStaticDecay", offsetof(WeaponFullDef, weapDef.fAdsGunKickStaticDecay), CSPFT_FLOAT}, - {"adsViewKickPitchMin", offsetof(WeaponFullDef, weapDef.fAdsViewKickPitchMin), CSPFT_FLOAT}, - {"adsViewKickPitchMax", offsetof(WeaponFullDef, weapDef.fAdsViewKickPitchMax), CSPFT_FLOAT}, - {"adsViewKickYawMin", offsetof(WeaponFullDef, weapDef.fAdsViewKickYawMin), CSPFT_FLOAT}, - {"adsViewKickYawMax", offsetof(WeaponFullDef, weapDef.fAdsViewKickYawMax), CSPFT_FLOAT}, - {"adsViewKickCenterSpeed", offsetof(WeaponFullDef, weapCompleteDef.fAdsViewKickCenterSpeed), CSPFT_FLOAT}, - {"adsSpread", offsetof(WeaponFullDef, weapDef.fAdsSpread), CSPFT_FLOAT}, - {"guidedMissileType", offsetof(WeaponFullDef, weapDef.guidedMissileType), WFT_GUIDED_MISSILE_TYPE}, - {"hipSpreadStandMin", offsetof(WeaponFullDef, weapDef.fHipSpreadStandMin), CSPFT_FLOAT}, - {"hipSpreadDuckedMin", offsetof(WeaponFullDef, weapDef.fHipSpreadDuckedMin), CSPFT_FLOAT}, - {"hipSpreadProneMin", offsetof(WeaponFullDef, weapDef.fHipSpreadProneMin), CSPFT_FLOAT}, - {"hipSpreadMax", offsetof(WeaponFullDef, weapDef.hipSpreadStandMax), CSPFT_FLOAT}, - {"hipSpreadDuckedMax", offsetof(WeaponFullDef, weapDef.hipSpreadDuckedMax), CSPFT_FLOAT}, - {"hipSpreadProneMax", offsetof(WeaponFullDef, weapDef.hipSpreadProneMax), CSPFT_FLOAT}, - {"hipSpreadDecayRate", offsetof(WeaponFullDef, weapDef.fHipSpreadDecayRate), CSPFT_FLOAT}, - {"hipSpreadFireAdd", offsetof(WeaponFullDef, weapDef.fHipSpreadFireAdd), CSPFT_FLOAT}, - {"hipSpreadTurnAdd", offsetof(WeaponFullDef, weapDef.fHipSpreadTurnAdd), CSPFT_FLOAT}, - {"hipSpreadMoveAdd", offsetof(WeaponFullDef, weapDef.fHipSpreadMoveAdd), CSPFT_FLOAT}, - {"hipSpreadDuckedDecay", offsetof(WeaponFullDef, weapDef.fHipSpreadDuckedDecay), CSPFT_FLOAT}, - {"hipSpreadProneDecay", offsetof(WeaponFullDef, weapDef.fHipSpreadProneDecay), CSPFT_FLOAT}, - {"hipReticleSidePos", offsetof(WeaponFullDef, weapDef.fHipReticleSidePos), CSPFT_FLOAT}, - {"hipIdleAmount", offsetof(WeaponFullDef, weapDef.fHipIdleAmount), CSPFT_FLOAT}, - {"hipIdleSpeed", offsetof(WeaponFullDef, weapDef.hipIdleSpeed), CSPFT_FLOAT}, - {"hipGunKickReducedKickBullets", offsetof(WeaponFullDef, weapDef.hipGunKickReducedKickBullets), CSPFT_INT}, - {"hipGunKickReducedKickPercent", offsetof(WeaponFullDef, weapDef.hipGunKickReducedKickPercent), CSPFT_FLOAT}, - {"hipGunKickPitchMin", offsetof(WeaponFullDef, weapDef.fHipGunKickPitchMin), CSPFT_FLOAT}, - {"hipGunKickPitchMax", offsetof(WeaponFullDef, weapDef.fHipGunKickPitchMax), CSPFT_FLOAT}, - {"hipGunKickYawMin", offsetof(WeaponFullDef, weapDef.fHipGunKickYawMin), CSPFT_FLOAT}, - {"hipGunKickYawMax", offsetof(WeaponFullDef, weapDef.fHipGunKickYawMax), CSPFT_FLOAT}, - {"hipGunKickAccel", offsetof(WeaponFullDef, weapDef.fHipGunKickAccel), CSPFT_FLOAT}, - {"hipGunKickSpeedMax", offsetof(WeaponFullDef, weapDef.fHipGunKickSpeedMax), CSPFT_FLOAT}, - {"hipGunKickSpeedDecay", offsetof(WeaponFullDef, weapDef.fHipGunKickSpeedDecay), CSPFT_FLOAT}, - {"hipGunKickStaticDecay", offsetof(WeaponFullDef, weapDef.fHipGunKickStaticDecay), CSPFT_FLOAT}, - {"hipViewKickPitchMin", offsetof(WeaponFullDef, weapDef.fHipViewKickPitchMin), CSPFT_FLOAT}, - {"hipViewKickPitchMax", offsetof(WeaponFullDef, weapDef.fHipViewKickPitchMax), CSPFT_FLOAT}, - {"hipViewKickYawMin", offsetof(WeaponFullDef, weapDef.fHipViewKickYawMin), CSPFT_FLOAT}, - {"hipViewKickYawMax", offsetof(WeaponFullDef, weapDef.fHipViewKickYawMax), CSPFT_FLOAT}, - {"hipViewKickCenterSpeed", offsetof(WeaponFullDef, weapCompleteDef.fHipViewKickCenterSpeed), CSPFT_FLOAT}, - {"leftArc", offsetof(WeaponFullDef, weapDef.leftArc), CSPFT_FLOAT}, - {"rightArc", offsetof(WeaponFullDef, weapDef.rightArc), CSPFT_FLOAT}, - {"topArc", offsetof(WeaponFullDef, weapDef.topArc), CSPFT_FLOAT}, - {"bottomArc", offsetof(WeaponFullDef, weapDef.bottomArc), CSPFT_FLOAT}, - {"accuracy", offsetof(WeaponFullDef, weapDef.accuracy), CSPFT_FLOAT}, - {"aiSpread", offsetof(WeaponFullDef, weapDef.aiSpread), CSPFT_FLOAT}, - {"playerSpread", offsetof(WeaponFullDef, weapDef.playerSpread), CSPFT_FLOAT}, - {"maxVertTurnSpeed", offsetof(WeaponFullDef, weapDef.maxTurnSpeed[0]), CSPFT_FLOAT}, - {"maxHorTurnSpeed", offsetof(WeaponFullDef, weapDef.maxTurnSpeed[1]), CSPFT_FLOAT}, - {"minVertTurnSpeed", offsetof(WeaponFullDef, weapDef.minTurnSpeed[0]), CSPFT_FLOAT}, - {"minHorTurnSpeed", offsetof(WeaponFullDef, weapDef.minTurnSpeed[1]), CSPFT_FLOAT}, - {"pitchConvergenceTime", offsetof(WeaponFullDef, weapDef.pitchConvergenceTime), CSPFT_FLOAT}, - {"yawConvergenceTime", offsetof(WeaponFullDef, weapDef.yawConvergenceTime), CSPFT_FLOAT}, - {"suppressionTime", offsetof(WeaponFullDef, weapDef.suppressTime), CSPFT_FLOAT}, - {"maxRange", offsetof(WeaponFullDef, weapDef.maxRange), CSPFT_FLOAT}, - {"animHorRotateInc", offsetof(WeaponFullDef, weapDef.fAnimHorRotateInc), CSPFT_FLOAT}, - {"playerPositionDist", offsetof(WeaponFullDef, weapDef.fPlayerPositionDist), CSPFT_FLOAT}, - {"stance", offsetof(WeaponFullDef, weapDef.stance), WFT_STANCE}, - {"useHintString", offsetof(WeaponFullDef, weapDef.szUseHintString), CSPFT_STRING}, - {"dropHintString", offsetof(WeaponFullDef, weapDef.dropHintString), CSPFT_STRING}, - {"horizViewJitter", offsetof(WeaponFullDef, weapDef.horizViewJitter), CSPFT_FLOAT}, - {"vertViewJitter", offsetof(WeaponFullDef, weapDef.vertViewJitter), CSPFT_FLOAT}, - {"scanSpeed", offsetof(WeaponFullDef, weapDef.scanSpeed), CSPFT_FLOAT}, - {"scanAccel", offsetof(WeaponFullDef, weapDef.scanAccel), CSPFT_FLOAT}, - {"scanPauseTime", offsetof(WeaponFullDef, weapDef.scanPauseTime), CSPFT_MILLISECONDS}, - {"fightDist", offsetof(WeaponFullDef, weapDef.fightDist), CSPFT_FLOAT}, - {"maxDist", offsetof(WeaponFullDef, weapDef.maxDist), CSPFT_FLOAT}, - {"aiVsAiAccuracyGraph", offsetof(WeaponFullDef, weapDef.accuracyGraphName0), CSPFT_STRING}, - {"aiVsPlayerAccuracyGraph", offsetof(WeaponFullDef, weapDef.accuracyGraphName1), CSPFT_STRING}, - {"locNone", offsetof(WeaponFullDef, locationDamageMultipliers[HITLOC_NONE]), CSPFT_FLOAT}, - {"locHelmet", offsetof(WeaponFullDef, locationDamageMultipliers[HITLOC_HELMET]), CSPFT_FLOAT}, - {"locHead", offsetof(WeaponFullDef, locationDamageMultipliers[HITLOC_HEAD]), CSPFT_FLOAT}, - {"locNeck", offsetof(WeaponFullDef, locationDamageMultipliers[HITLOC_NECK]), CSPFT_FLOAT}, - {"locTorsoUpper", offsetof(WeaponFullDef, locationDamageMultipliers[HITLOC_TORSO_UPR]), CSPFT_FLOAT}, - {"locTorsoLower", offsetof(WeaponFullDef, locationDamageMultipliers[HITLOC_TORSO_LWR]), CSPFT_FLOAT}, - {"locRightArmUpper", offsetof(WeaponFullDef, locationDamageMultipliers[HITLOC_R_ARM_UPR]), CSPFT_FLOAT}, - {"locRightArmLower", offsetof(WeaponFullDef, locationDamageMultipliers[HITLOC_R_ARM_LWR]), CSPFT_FLOAT}, - {"locRightHand", offsetof(WeaponFullDef, locationDamageMultipliers[HITLOC_R_HAND]), CSPFT_FLOAT}, - {"locLeftArmUpper", offsetof(WeaponFullDef, locationDamageMultipliers[HITLOC_L_ARM_UPR]), CSPFT_FLOAT}, - {"locLeftArmLower", offsetof(WeaponFullDef, locationDamageMultipliers[HITLOC_L_ARM_LWR]), CSPFT_FLOAT}, - {"locLeftHand", offsetof(WeaponFullDef, locationDamageMultipliers[HITLOC_L_HAND]), CSPFT_FLOAT}, - {"locRightLegUpper", offsetof(WeaponFullDef, locationDamageMultipliers[HITLOC_R_LEG_UPR]), CSPFT_FLOAT}, - {"locRightLegLower", offsetof(WeaponFullDef, locationDamageMultipliers[HITLOC_R_LEG_LWR]), CSPFT_FLOAT}, - {"locRightFoot", offsetof(WeaponFullDef, locationDamageMultipliers[HITLOC_R_FOOT]), CSPFT_FLOAT}, - {"locLeftLegUpper", offsetof(WeaponFullDef, locationDamageMultipliers[HITLOC_L_LEG_UPR]), CSPFT_FLOAT}, - {"locLeftLegLower", offsetof(WeaponFullDef, locationDamageMultipliers[HITLOC_L_LEG_LWR]), CSPFT_FLOAT}, - {"locLeftFoot", offsetof(WeaponFullDef, locationDamageMultipliers[HITLOC_L_FOOT]), CSPFT_FLOAT}, - {"locGun", offsetof(WeaponFullDef, locationDamageMultipliers[HITLOC_GUN]), CSPFT_FLOAT}, - {"fireRumble", offsetof(WeaponFullDef, weapDef.fireRumble), CSPFT_STRING}, - {"meleeImpactRumble", offsetof(WeaponFullDef, weapDef.meleeImpactRumble), CSPFT_STRING}, - {"tracerType", offsetof(WeaponFullDef, weapDef.tracerType), CSPFT_TRACER}, - {"adsDofStart", offsetof(WeaponFullDef, weapCompleteDef.adsDofStart), CSPFT_FLOAT}, - {"adsDofEnd", offsetof(WeaponFullDef, weapCompleteDef.adsDofEnd), CSPFT_FLOAT}, - {"turretScopeZoomRate", offsetof(WeaponFullDef, weapDef.turretScopeZoomRate), CSPFT_FLOAT}, - {"turretScopeZoomMin", offsetof(WeaponFullDef, weapDef.turretScopeZoomMin), CSPFT_FLOAT}, - {"turretScopeZoomMax", offsetof(WeaponFullDef, weapDef.turretScopeZoomMax), CSPFT_FLOAT}, - {"thermalScope", offsetof(WeaponFullDef, weapDef.thermalScope), CSPFT_BOOL}, - {"altModeSameWeapon", offsetof(WeaponFullDef, weapDef.altModeSameWeapon), CSPFT_BOOL}, - {"turretOverheatUpRate", offsetof(WeaponFullDef, weapDef.turretOverheatUpRate), CSPFT_FLOAT}, - {"turretOverheatDownRate", offsetof(WeaponFullDef, weapDef.turretOverheatDownRate), CSPFT_FLOAT}, - {"turretOverheatPenalty", offsetof(WeaponFullDef, weapDef.turretOverheatPenalty), CSPFT_FLOAT}, - {"turretOverheatSound", offsetof(WeaponFullDef, weapDef.turretOverheatSound), CSPFT_SOUND}, - {"turretOverheatEffect", offsetof(WeaponFullDef, weapDef.turretOverheatEffect), CSPFT_FX}, - {"turretBarrelSpinEnabled", offsetof(WeaponFullDef, weapDef.turretBarrelSpinEnabled), CSPFT_BOOL}, - {"turretBarrelSpinUpTime", offsetof(WeaponFullDef, weapDef.turretBarrelSpinUpTime), CSPFT_FLOAT}, - {"turretBarrelSpinDownTime", offsetof(WeaponFullDef, weapDef.turretBarrelSpinDownTime), CSPFT_FLOAT}, - {"turretBarrelSpinRumble", offsetof(WeaponFullDef, weapDef.turretBarrelSpinRumble), CSPFT_STRING}, - {"turretBarrelSpinSpeed", offsetof(WeaponFullDef, weapDef.turretBarrelSpinSpeed), CSPFT_FLOAT}, - {"turretBarrelSpinMaxSnd", offsetof(WeaponFullDef, weapDef.turretBarrelSpinMaxSnd), CSPFT_SOUND}, - {"turretBarrelSpinUpSnd1", offsetof(WeaponFullDef, weapDef.turretBarrelSpinUpSnd[0]), CSPFT_SOUND}, - {"turretBarrelSpinUpSnd2", offsetof(WeaponFullDef, weapDef.turretBarrelSpinUpSnd[1]), CSPFT_SOUND}, - {"turretBarrelSpinUpSnd3", offsetof(WeaponFullDef, weapDef.turretBarrelSpinUpSnd[2]), CSPFT_SOUND}, - {"turretBarrelSpinUpSnd4", offsetof(WeaponFullDef, weapDef.turretBarrelSpinUpSnd[3]), CSPFT_SOUND}, - {"turretBarrelSpinDownSnd1", offsetof(WeaponFullDef, weapDef.turretBarrelSpinDownSnd[0]), CSPFT_SOUND}, - {"turretBarrelSpinDownSnd2", offsetof(WeaponFullDef, weapDef.turretBarrelSpinDownSnd[1]), CSPFT_SOUND}, - {"turretBarrelSpinDownSnd3", offsetof(WeaponFullDef, weapDef.turretBarrelSpinDownSnd[2]), CSPFT_SOUND}, - {"turretBarrelSpinDownSnd4", offsetof(WeaponFullDef, weapDef.turretBarrelSpinDownSnd[3]), CSPFT_SOUND}, - {"missileConeSoundEnabled", offsetof(WeaponFullDef, weapDef.missileConeSoundEnabled), CSPFT_BOOL}, - {"missileConeSoundAlias", offsetof(WeaponFullDef, weapDef.missileConeSoundAlias), CSPFT_SOUND}, - {"missileConeSoundAliasAtBase", offsetof(WeaponFullDef, weapDef.missileConeSoundAliasAtBase), CSPFT_SOUND}, - {"missileConeSoundRadiusAtTop", offsetof(WeaponFullDef, weapDef.missileConeSoundRadiusAtTop), CSPFT_FLOAT}, - {"missileConeSoundRadiusAtBase", offsetof(WeaponFullDef, weapDef.missileConeSoundRadiusAtBase), CSPFT_FLOAT}, - {"missileConeSoundHeight", offsetof(WeaponFullDef, weapDef.missileConeSoundHeight), CSPFT_FLOAT}, - {"missileConeSoundOriginOffset", offsetof(WeaponFullDef, weapDef.missileConeSoundOriginOffset), CSPFT_FLOAT}, - {"missileConeSoundVolumescaleAtCore", offsetof(WeaponFullDef, weapDef.missileConeSoundVolumescaleAtCore), CSPFT_FLOAT}, - {"missileConeSoundVolumescaleAtEdge", offsetof(WeaponFullDef, weapDef.missileConeSoundVolumescaleAtEdge), CSPFT_FLOAT}, - {"missileConeSoundVolumescaleCoreSize", offsetof(WeaponFullDef, weapDef.missileConeSoundVolumescaleCoreSize), CSPFT_FLOAT}, - {"missileConeSoundPitchshiftEnabled", offsetof(WeaponFullDef, weapDef.missileConeSoundPitchshiftEnabled), CSPFT_BOOL}, - {"missileConeSoundPitchAtTop", offsetof(WeaponFullDef, weapDef.missileConeSoundPitchAtTop), CSPFT_FLOAT}, - {"missileConeSoundPitchAtBottom", offsetof(WeaponFullDef, weapDef.missileConeSoundPitchAtBottom), CSPFT_FLOAT}, - {"missileConeSoundPitchTopSize", offsetof(WeaponFullDef, weapDef.missileConeSoundPitchTopSize), CSPFT_FLOAT}, - {"missileConeSoundPitchBottomSize", offsetof(WeaponFullDef, weapDef.missileConeSoundPitchBottomSize), CSPFT_FLOAT}, - {"missileConeSoundCrossfadeEnabled", offsetof(WeaponFullDef, weapDef.missileConeSoundCrossfadeEnabled), CSPFT_BOOL}, - {"missileConeSoundCrossfadeTopSize", offsetof(WeaponFullDef, weapDef.missileConeSoundCrossfadeTopSize), CSPFT_FLOAT}, - {"missileConeSoundCrossfadeBottomSize", offsetof(WeaponFullDef, weapDef.missileConeSoundCrossfadeBottomSize), CSPFT_FLOAT}, - }; +namespace IW4 { +inline cspField_t weapon_fields[]{ + {"displayName", offsetof(WeaponFullDef, weapCompleteDef.szDisplayName), CSPFT_STRING }, + {"AIOverlayDescription", offsetof(WeaponFullDef, weapDef.szOverlayName), CSPFT_STRING }, + {"modeName", offsetof(WeaponFullDef, weapDef.szModeName), CSPFT_STRING }, + {"playerAnimType", offsetof(WeaponFullDef, weapDef.playerAnimType), WFT_ANIMTYPE }, + {"gunModel", offsetof(WeaponFullDef, gunXModel[0]), CSPFT_XMODEL }, + {"gunModel2", offsetof(WeaponFullDef, gunXModel[1]), CSPFT_XMODEL }, + {"gunModel3", offsetof(WeaponFullDef, gunXModel[2]), CSPFT_XMODEL }, + {"gunModel4", offsetof(WeaponFullDef, gunXModel[3]), CSPFT_XMODEL }, + {"gunModel5", offsetof(WeaponFullDef, gunXModel[4]), CSPFT_XMODEL }, + {"gunModel6", offsetof(WeaponFullDef, gunXModel[5]), CSPFT_XMODEL }, + {"gunModel7", offsetof(WeaponFullDef, gunXModel[6]), CSPFT_XMODEL }, + {"gunModel8", offsetof(WeaponFullDef, gunXModel[7]), CSPFT_XMODEL }, + {"gunModel9", offsetof(WeaponFullDef, gunXModel[8]), CSPFT_XMODEL }, + {"gunModel10", offsetof(WeaponFullDef, gunXModel[9]), CSPFT_XMODEL }, + {"gunModel11", offsetof(WeaponFullDef, gunXModel[10]), CSPFT_XMODEL }, + {"gunModel12", offsetof(WeaponFullDef, gunXModel[11]), CSPFT_XMODEL }, + {"gunModel13", offsetof(WeaponFullDef, gunXModel[12]), CSPFT_XMODEL }, + {"gunModel14", offsetof(WeaponFullDef, gunXModel[13]), CSPFT_XMODEL }, + {"gunModel15", offsetof(WeaponFullDef, gunXModel[14]), CSPFT_XMODEL }, + {"gunModel16", offsetof(WeaponFullDef, gunXModel[15]), CSPFT_XMODEL }, + {"handModel", offsetof(WeaponFullDef, weapDef.handXModel), CSPFT_XMODEL }, + {"hideTags", offsetof(WeaponFullDef, hideTags), WFT_HIDETAGS }, + {"notetrackSoundMap", offsetof(WeaponFullDef, notetrackSoundMapKeys), WFT_NOTETRACKSOUNDMAP }, + {"notetrackRumbleMap", offsetof(WeaponFullDef, notetrackRumbleMapKeys), WFT_NOTETRACKRUMBLEMAP }, + {"idleAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_IDLE]), CSPFT_STRING }, + {"emptyIdleAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_EMPTY_IDLE]), CSPFT_STRING }, + {"fireAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_FIRE]), CSPFT_STRING }, + {"holdFireAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_HOLD_FIRE]), CSPFT_STRING }, + {"lastShotAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_LASTSHOT]), CSPFT_STRING }, + {"detonateAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_DETONATE]), CSPFT_STRING }, + {"rechamberAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_RECHAMBER]), CSPFT_STRING }, + {"meleeAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_MELEE]), CSPFT_STRING }, + {"meleeChargeAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_MELEE_CHARGE]), CSPFT_STRING }, + {"reloadAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_RELOAD]), CSPFT_STRING }, + {"reloadEmptyAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_RELOAD_EMPTY]), CSPFT_STRING }, + {"reloadStartAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_RELOAD_START]), CSPFT_STRING }, + {"reloadEndAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_RELOAD_END]), CSPFT_STRING }, + {"raiseAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_RAISE]), CSPFT_STRING }, + {"dropAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_DROP]), CSPFT_STRING }, + {"firstRaiseAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_FIRST_RAISE]), CSPFT_STRING }, + {"breachRaiseAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_BREACH_RAISE]), CSPFT_STRING }, + {"altRaiseAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_ALT_RAISE]), CSPFT_STRING }, + {"altDropAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_ALT_DROP]), CSPFT_STRING }, + {"quickRaiseAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_QUICK_RAISE]), CSPFT_STRING }, + {"quickDropAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_QUICK_DROP]), CSPFT_STRING }, + {"emptyRaiseAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_EMPTY_RAISE]), CSPFT_STRING }, + {"emptyDropAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_EMPTY_DROP]), CSPFT_STRING }, + {"sprintInAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_SPRINT_IN]), CSPFT_STRING }, + {"sprintLoopAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_SPRINT_LOOP]), CSPFT_STRING }, + {"sprintOutAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_SPRINT_OUT]), CSPFT_STRING }, + {"stunnedAnimStart", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_STUNNED_START]), CSPFT_STRING }, + {"stunnedAnimLoop", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_STUNNED_LOOP]), CSPFT_STRING }, + {"stunnedAnimEnd", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_STUNNED_END]), CSPFT_STRING }, + {"nightVisionWearAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_NIGHTVISION_WEAR]), CSPFT_STRING }, + {"nightVisionRemoveAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_NIGHTVISION_REMOVE]), CSPFT_STRING }, + {"adsFireAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_ADS_FIRE]), CSPFT_STRING }, + {"adsLastShotAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_ADS_LASTSHOT]), CSPFT_STRING }, + {"adsRechamberAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_ADS_RECHAMBER]), CSPFT_STRING }, + {"adsUpAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_ADS_UP]), CSPFT_STRING }, + {"adsDownAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_ADS_DOWN]), CSPFT_STRING }, + {"idleAnimR", offsetof(WeaponFullDef, szXAnimsRightHanded[WEAP_ANIM_IDLE]), CSPFT_STRING }, + {"emptyIdleAnimR", offsetof(WeaponFullDef, szXAnimsRightHanded[WEAP_ANIM_EMPTY_IDLE]), CSPFT_STRING }, + {"fireAnimR", offsetof(WeaponFullDef, szXAnimsRightHanded[WEAP_ANIM_FIRE]), CSPFT_STRING }, + {"holdFireAnimR", offsetof(WeaponFullDef, szXAnimsRightHanded[WEAP_ANIM_HOLD_FIRE]), CSPFT_STRING }, + {"lastShotAnimR", offsetof(WeaponFullDef, szXAnimsRightHanded[WEAP_ANIM_LASTSHOT]), CSPFT_STRING }, + {"detonateAnimR", offsetof(WeaponFullDef, szXAnimsRightHanded[WEAP_ANIM_DETONATE]), CSPFT_STRING }, + {"rechamberAnimR", offsetof(WeaponFullDef, szXAnimsRightHanded[WEAP_ANIM_RECHAMBER]), CSPFT_STRING }, + {"meleeAnimR", offsetof(WeaponFullDef, szXAnimsRightHanded[WEAP_ANIM_MELEE]), CSPFT_STRING }, + {"meleeChargeAnimR", offsetof(WeaponFullDef, szXAnimsRightHanded[WEAP_ANIM_MELEE_CHARGE]), CSPFT_STRING }, + {"reloadAnimR", offsetof(WeaponFullDef, szXAnimsRightHanded[WEAP_ANIM_RELOAD]), CSPFT_STRING }, + {"reloadEmptyAnimR", offsetof(WeaponFullDef, szXAnimsRightHanded[WEAP_ANIM_RELOAD_EMPTY]), CSPFT_STRING }, + {"reloadStartAnimR", offsetof(WeaponFullDef, szXAnimsRightHanded[WEAP_ANIM_RELOAD_START]), CSPFT_STRING }, + {"reloadEndAnimR", offsetof(WeaponFullDef, szXAnimsRightHanded[WEAP_ANIM_RELOAD_END]), CSPFT_STRING }, + {"raiseAnimR", offsetof(WeaponFullDef, szXAnimsRightHanded[WEAP_ANIM_RAISE]), CSPFT_STRING }, + {"dropAnimR", offsetof(WeaponFullDef, szXAnimsRightHanded[WEAP_ANIM_DROP]), CSPFT_STRING }, + {"firstRaiseAnimR", offsetof(WeaponFullDef, szXAnimsRightHanded[WEAP_ANIM_FIRST_RAISE]), CSPFT_STRING }, + {"breachRaiseAnimR", offsetof(WeaponFullDef, szXAnimsRightHanded[WEAP_ANIM_BREACH_RAISE]), CSPFT_STRING }, + {"altRaiseAnimR", offsetof(WeaponFullDef, szXAnimsRightHanded[WEAP_ANIM_ALT_RAISE]), CSPFT_STRING }, + {"altDropAnimR", offsetof(WeaponFullDef, szXAnimsRightHanded[WEAP_ANIM_ALT_DROP]), CSPFT_STRING }, + {"quickRaiseAnimR", offsetof(WeaponFullDef, szXAnimsRightHanded[WEAP_ANIM_QUICK_RAISE]), CSPFT_STRING }, + {"quickDropAnimR", offsetof(WeaponFullDef, szXAnimsRightHanded[WEAP_ANIM_QUICK_DROP]), CSPFT_STRING }, + {"emptyRaiseAnimR", offsetof(WeaponFullDef, szXAnimsRightHanded[WEAP_ANIM_EMPTY_RAISE]), CSPFT_STRING }, + {"emptyDropAnimR", offsetof(WeaponFullDef, szXAnimsRightHanded[WEAP_ANIM_EMPTY_DROP]), CSPFT_STRING }, + {"sprintInAnimR", offsetof(WeaponFullDef, szXAnimsRightHanded[WEAP_ANIM_SPRINT_IN]), CSPFT_STRING }, + {"sprintLoopAnimR", offsetof(WeaponFullDef, szXAnimsRightHanded[WEAP_ANIM_SPRINT_LOOP]), CSPFT_STRING }, + {"sprintOutAnimR", offsetof(WeaponFullDef, szXAnimsRightHanded[WEAP_ANIM_SPRINT_OUT]), CSPFT_STRING }, + {"stunnedAnimStartR", offsetof(WeaponFullDef, szXAnimsRightHanded[WEAP_ANIM_STUNNED_START]), CSPFT_STRING }, + {"stunnedAnimLoopR", offsetof(WeaponFullDef, szXAnimsRightHanded[WEAP_ANIM_STUNNED_LOOP]), CSPFT_STRING }, + {"stunnedAnimEndR", offsetof(WeaponFullDef, szXAnimsRightHanded[WEAP_ANIM_STUNNED_END]), CSPFT_STRING }, + {"nightVisionWearAnimR", offsetof(WeaponFullDef, szXAnimsRightHanded[WEAP_ANIM_NIGHTVISION_WEAR]), CSPFT_STRING }, + {"nightVisionRemoveAnimR", offsetof(WeaponFullDef, szXAnimsRightHanded[WEAP_ANIM_NIGHTVISION_REMOVE]), CSPFT_STRING }, + {"adsFireAnimR", offsetof(WeaponFullDef, szXAnimsRightHanded[WEAP_ANIM_ADS_FIRE]), CSPFT_STRING }, + {"adsLastShotAnimR", offsetof(WeaponFullDef, szXAnimsRightHanded[WEAP_ANIM_ADS_LASTSHOT]), CSPFT_STRING }, + {"adsRechamberAnimR", offsetof(WeaponFullDef, szXAnimsRightHanded[WEAP_ANIM_ADS_RECHAMBER]), CSPFT_STRING }, + {"adsUpAnimR", offsetof(WeaponFullDef, szXAnimsRightHanded[WEAP_ANIM_ADS_UP]), CSPFT_STRING }, + {"adsDownAnimR", offsetof(WeaponFullDef, szXAnimsRightHanded[WEAP_ANIM_ADS_DOWN]), CSPFT_STRING }, + {"idleAnimL", offsetof(WeaponFullDef, szXAnimsLeftHanded[WEAP_ANIM_IDLE]), CSPFT_STRING }, + {"emptyIdleAnimL", offsetof(WeaponFullDef, szXAnimsLeftHanded[WEAP_ANIM_EMPTY_IDLE]), CSPFT_STRING }, + {"fireAnimL", offsetof(WeaponFullDef, szXAnimsLeftHanded[WEAP_ANIM_FIRE]), CSPFT_STRING }, + {"holdFireAnimL", offsetof(WeaponFullDef, szXAnimsLeftHanded[WEAP_ANIM_HOLD_FIRE]), CSPFT_STRING }, + {"lastShotAnimL", offsetof(WeaponFullDef, szXAnimsLeftHanded[WEAP_ANIM_LASTSHOT]), CSPFT_STRING }, + {"detonateAnimL", offsetof(WeaponFullDef, szXAnimsLeftHanded[WEAP_ANIM_DETONATE]), CSPFT_STRING }, + {"rechamberAnimL", offsetof(WeaponFullDef, szXAnimsLeftHanded[WEAP_ANIM_RECHAMBER]), CSPFT_STRING }, + {"meleeAnimL", offsetof(WeaponFullDef, szXAnimsLeftHanded[WEAP_ANIM_MELEE]), CSPFT_STRING }, + {"meleeChargeAnimL", offsetof(WeaponFullDef, szXAnimsLeftHanded[WEAP_ANIM_MELEE_CHARGE]), CSPFT_STRING }, + {"reloadAnimL", offsetof(WeaponFullDef, szXAnimsLeftHanded[WEAP_ANIM_RELOAD]), CSPFT_STRING }, + {"reloadEmptyAnimL", offsetof(WeaponFullDef, szXAnimsLeftHanded[WEAP_ANIM_RELOAD_EMPTY]), CSPFT_STRING }, + {"reloadStartAnimL", offsetof(WeaponFullDef, szXAnimsLeftHanded[WEAP_ANIM_RELOAD_START]), CSPFT_STRING }, + {"reloadEndAnimL", offsetof(WeaponFullDef, szXAnimsLeftHanded[WEAP_ANIM_RELOAD_END]), CSPFT_STRING }, + {"raiseAnimL", offsetof(WeaponFullDef, szXAnimsLeftHanded[WEAP_ANIM_RAISE]), CSPFT_STRING }, + {"dropAnimL", offsetof(WeaponFullDef, szXAnimsLeftHanded[WEAP_ANIM_DROP]), CSPFT_STRING }, + {"firstRaiseAnimL", offsetof(WeaponFullDef, szXAnimsLeftHanded[WEAP_ANIM_FIRST_RAISE]), CSPFT_STRING }, + {"breachRaiseAnimL", offsetof(WeaponFullDef, szXAnimsLeftHanded[WEAP_ANIM_BREACH_RAISE]), CSPFT_STRING }, + {"altRaiseAnimL", offsetof(WeaponFullDef, szXAnimsLeftHanded[WEAP_ANIM_ALT_RAISE]), CSPFT_STRING }, + {"altDropAnimL", offsetof(WeaponFullDef, szXAnimsLeftHanded[WEAP_ANIM_ALT_DROP]), CSPFT_STRING }, + {"quickRaiseAnimL", offsetof(WeaponFullDef, szXAnimsLeftHanded[WEAP_ANIM_QUICK_RAISE]), CSPFT_STRING }, + {"quickDropAnimL", offsetof(WeaponFullDef, szXAnimsLeftHanded[WEAP_ANIM_QUICK_DROP]), CSPFT_STRING }, + {"emptyRaiseAnimL", offsetof(WeaponFullDef, szXAnimsLeftHanded[WEAP_ANIM_EMPTY_RAISE]), CSPFT_STRING }, + {"emptyDropAnimL", offsetof(WeaponFullDef, szXAnimsLeftHanded[WEAP_ANIM_EMPTY_DROP]), CSPFT_STRING }, + {"sprintInAnimL", offsetof(WeaponFullDef, szXAnimsLeftHanded[WEAP_ANIM_SPRINT_IN]), CSPFT_STRING }, + {"sprintLoopAnimL", offsetof(WeaponFullDef, szXAnimsLeftHanded[WEAP_ANIM_SPRINT_LOOP]), CSPFT_STRING }, + {"sprintOutAnimL", offsetof(WeaponFullDef, szXAnimsLeftHanded[WEAP_ANIM_SPRINT_OUT]), CSPFT_STRING }, + {"stunnedAnimStartL", offsetof(WeaponFullDef, szXAnimsLeftHanded[WEAP_ANIM_STUNNED_START]), CSPFT_STRING }, + {"stunnedAnimLoopL", offsetof(WeaponFullDef, szXAnimsLeftHanded[WEAP_ANIM_STUNNED_LOOP]), CSPFT_STRING }, + {"stunnedAnimEndL", offsetof(WeaponFullDef, szXAnimsLeftHanded[WEAP_ANIM_STUNNED_END]), CSPFT_STRING }, + {"nightVisionWearAnimL", offsetof(WeaponFullDef, szXAnimsLeftHanded[WEAP_ANIM_NIGHTVISION_WEAR]), CSPFT_STRING }, + {"nightVisionRemoveAnimL", offsetof(WeaponFullDef, szXAnimsLeftHanded[WEAP_ANIM_NIGHTVISION_REMOVE]), CSPFT_STRING }, + {"adsFireAnimL", offsetof(WeaponFullDef, szXAnimsLeftHanded[WEAP_ANIM_ADS_FIRE]), CSPFT_STRING }, + {"adsLastShotAnimL", offsetof(WeaponFullDef, szXAnimsLeftHanded[WEAP_ANIM_ADS_LASTSHOT]), CSPFT_STRING }, + {"adsRechamberAnimL", offsetof(WeaponFullDef, szXAnimsLeftHanded[WEAP_ANIM_ADS_RECHAMBER]), CSPFT_STRING }, + {"adsUpAnimL", offsetof(WeaponFullDef, szXAnimsLeftHanded[WEAP_ANIM_ADS_UP]), CSPFT_STRING }, + {"adsDownAnimL", offsetof(WeaponFullDef, szXAnimsLeftHanded[WEAP_ANIM_ADS_DOWN]), CSPFT_STRING }, + {"script", offsetof(WeaponFullDef, weapDef.szScript), CSPFT_STRING }, + {"weaponType", offsetof(WeaponFullDef, weapDef.weapType), WFT_WEAPONTYPE }, + {"weaponClass", offsetof(WeaponFullDef, weapDef.weapClass), WFT_WEAPONCLASS }, + {"penetrateType", offsetof(WeaponFullDef, weapDef.penetrateType), WFT_PENETRATE_TYPE }, + {"penetrateMultiplier", offsetof(WeaponFullDef, weapCompleteDef.penetrateMultiplier), CSPFT_FLOAT }, + {"impactType", offsetof(WeaponFullDef, weapCompleteDef.impactType), WFT_IMPACT_TYPE }, + {"inventoryType", offsetof(WeaponFullDef, weapDef.inventoryType), WFT_INVENTORYTYPE }, + {"fireType", offsetof(WeaponFullDef, weapDef.fireType), WFT_FIRETYPE }, + {"offhandClass", offsetof(WeaponFullDef, weapDef.offhandClass), WFT_OFFHAND_CLASS }, + {"viewFlashEffect", offsetof(WeaponFullDef, weapDef.viewFlashEffect), CSPFT_FX }, + {"worldFlashEffect", offsetof(WeaponFullDef, weapDef.worldFlashEffect), CSPFT_FX }, + {"pickupSound", offsetof(WeaponFullDef, weapDef.pickupSound), CSPFT_SOUND }, + {"pickupSoundPlayer", offsetof(WeaponFullDef, weapDef.pickupSoundPlayer), CSPFT_SOUND }, + {"ammoPickupSound", offsetof(WeaponFullDef, weapDef.ammoPickupSound), CSPFT_SOUND }, + {"ammoPickupSoundPlayer", offsetof(WeaponFullDef, weapDef.ammoPickupSoundPlayer), CSPFT_SOUND }, + {"projectileSound", offsetof(WeaponFullDef, weapDef.projectileSound), CSPFT_SOUND }, + {"pullbackSound", offsetof(WeaponFullDef, weapDef.pullbackSound), CSPFT_SOUND }, + {"pullbackSoundPlayer", offsetof(WeaponFullDef, weapDef.pullbackSoundPlayer), CSPFT_SOUND }, + {"fireSound", offsetof(WeaponFullDef, weapDef.fireSound), CSPFT_SOUND }, + {"fireSoundPlayer", offsetof(WeaponFullDef, weapDef.fireSoundPlayer), CSPFT_SOUND }, + {"fireSoundPlayerAkimbo", offsetof(WeaponFullDef, weapDef.fireSoundPlayerAkimbo), CSPFT_SOUND }, + {"loopFireSound", offsetof(WeaponFullDef, weapDef.fireLoopSound), CSPFT_SOUND }, + {"loopFireSoundPlayer", offsetof(WeaponFullDef, weapDef.fireLoopSoundPlayer), CSPFT_SOUND }, + {"stopFireSound", offsetof(WeaponFullDef, weapDef.fireStopSound), CSPFT_SOUND }, + {"stopFireSoundPlayer", offsetof(WeaponFullDef, weapDef.fireStopSoundPlayer), CSPFT_SOUND }, + {"lastShotSound", offsetof(WeaponFullDef, weapDef.fireLastSound), CSPFT_SOUND }, + {"lastShotSoundPlayer", offsetof(WeaponFullDef, weapDef.fireLastSoundPlayer), CSPFT_SOUND }, + {"emptyFireSound", offsetof(WeaponFullDef, weapDef.emptyFireSound), CSPFT_SOUND }, + {"emptyFireSoundPlayer", offsetof(WeaponFullDef, weapDef.emptyFireSoundPlayer), CSPFT_SOUND }, + {"meleeSwipeSound", offsetof(WeaponFullDef, weapDef.meleeSwipeSound), CSPFT_SOUND }, + {"meleeSwipeSoundPlayer", offsetof(WeaponFullDef, weapDef.meleeSwipeSoundPlayer), CSPFT_SOUND }, + {"meleeHitSound", offsetof(WeaponFullDef, weapDef.meleeHitSound), CSPFT_SOUND }, + {"meleeMissSound", offsetof(WeaponFullDef, weapDef.meleeMissSound), CSPFT_SOUND }, + {"rechamberSound", offsetof(WeaponFullDef, weapDef.rechamberSound), CSPFT_SOUND }, + {"rechamberSoundPlayer", offsetof(WeaponFullDef, weapDef.rechamberSoundPlayer), CSPFT_SOUND }, + {"reloadSound", offsetof(WeaponFullDef, weapDef.reloadSound), CSPFT_SOUND }, + {"reloadSoundPlayer", offsetof(WeaponFullDef, weapDef.reloadSoundPlayer), CSPFT_SOUND }, + {"reloadEmptySound", offsetof(WeaponFullDef, weapDef.reloadEmptySound), CSPFT_SOUND }, + {"reloadEmptySoundPlayer", offsetof(WeaponFullDef, weapDef.reloadEmptySoundPlayer), CSPFT_SOUND }, + {"reloadStartSound", offsetof(WeaponFullDef, weapDef.reloadStartSound), CSPFT_SOUND }, + {"reloadStartSoundPlayer", offsetof(WeaponFullDef, weapDef.reloadStartSoundPlayer), CSPFT_SOUND }, + {"reloadEndSound", offsetof(WeaponFullDef, weapDef.reloadEndSound), CSPFT_SOUND }, + {"reloadEndSoundPlayer", offsetof(WeaponFullDef, weapDef.reloadEndSoundPlayer), CSPFT_SOUND }, + {"detonateSound", offsetof(WeaponFullDef, weapDef.detonateSound), CSPFT_SOUND }, + {"detonateSoundPlayer", offsetof(WeaponFullDef, weapDef.detonateSoundPlayer), CSPFT_SOUND }, + {"nightVisionWearSound", offsetof(WeaponFullDef, weapDef.nightVisionWearSound), CSPFT_SOUND }, + {"nightVisionWearSoundPlayer", offsetof(WeaponFullDef, weapDef.nightVisionWearSoundPlayer), CSPFT_SOUND }, + {"nightVisionRemoveSound", offsetof(WeaponFullDef, weapDef.nightVisionRemoveSound), CSPFT_SOUND }, + {"nightVisionRemoveSoundPlayer", offsetof(WeaponFullDef, weapDef.nightVisionRemoveSoundPlayer), CSPFT_SOUND }, + {"raiseSound", offsetof(WeaponFullDef, weapDef.raiseSound), CSPFT_SOUND }, + {"raiseSoundPlayer", offsetof(WeaponFullDef, weapDef.raiseSoundPlayer), CSPFT_SOUND }, + {"firstRaiseSound", offsetof(WeaponFullDef, weapDef.firstRaiseSound), CSPFT_SOUND }, + {"firstRaiseSoundPlayer", offsetof(WeaponFullDef, weapDef.firstRaiseSoundPlayer), CSPFT_SOUND }, + {"altSwitchSound", offsetof(WeaponFullDef, weapDef.altSwitchSound), CSPFT_SOUND }, + {"altSwitchSoundPlayer", offsetof(WeaponFullDef, weapDef.altSwitchSoundPlayer), CSPFT_SOUND }, + {"putawaySound", offsetof(WeaponFullDef, weapDef.putawaySound), CSPFT_SOUND }, + {"putawaySoundPlayer", offsetof(WeaponFullDef, weapDef.putawaySoundPlayer), CSPFT_SOUND }, + {"scanSound", offsetof(WeaponFullDef, weapDef.scanSound), CSPFT_SOUND }, + {"bounceSound", offsetof(WeaponFullDef, weapDef.bounceSound), WFT_BOUNCE_SOUND }, + {"viewShellEjectEffect", offsetof(WeaponFullDef, weapDef.viewShellEjectEffect), CSPFT_FX }, + {"worldShellEjectEffect", offsetof(WeaponFullDef, weapDef.worldShellEjectEffect), CSPFT_FX }, + {"viewLastShotEjectEffect", offsetof(WeaponFullDef, weapDef.viewLastShotEjectEffect), CSPFT_FX }, + {"worldLastShotEjectEffect", offsetof(WeaponFullDef, weapDef.worldLastShotEjectEffect), CSPFT_FX }, + {"reticleCenter", offsetof(WeaponFullDef, weapDef.reticleCenter), CSPFT_MATERIAL }, + {"reticleSide", offsetof(WeaponFullDef, weapDef.reticleSide), CSPFT_MATERIAL }, + {"reticleCenterSize", offsetof(WeaponFullDef, weapDef.iReticleCenterSize), CSPFT_INT }, + {"reticleSideSize", offsetof(WeaponFullDef, weapDef.iReticleSideSize), CSPFT_INT }, + {"reticleMinOfs", offsetof(WeaponFullDef, weapDef.iReticleMinOfs), CSPFT_INT }, + {"activeReticleType", offsetof(WeaponFullDef, weapDef.activeReticleType), WFT_ACTIVE_RETICLE_TYPE }, + {"standMoveF", offsetof(WeaponFullDef, weapDef.vStandMove[0]), CSPFT_FLOAT }, + {"standMoveR", offsetof(WeaponFullDef, weapDef.vStandMove[1]), CSPFT_FLOAT }, + {"standMoveU", offsetof(WeaponFullDef, weapDef.vStandMove[2]), CSPFT_FLOAT }, + {"standRotP", offsetof(WeaponFullDef, weapDef.vStandRot[0]), CSPFT_FLOAT }, + {"standRotY", offsetof(WeaponFullDef, weapDef.vStandRot[1]), CSPFT_FLOAT }, + {"standRotR", offsetof(WeaponFullDef, weapDef.vStandRot[2]), CSPFT_FLOAT }, + {"strafeMoveF", offsetof(WeaponFullDef, weapDef.strafeMove[0]), CSPFT_FLOAT }, + {"strafeMoveR", offsetof(WeaponFullDef, weapDef.strafeMove[1]), CSPFT_FLOAT }, + {"strafeMoveU", offsetof(WeaponFullDef, weapDef.strafeMove[2]), CSPFT_FLOAT }, + {"strafeRotP", offsetof(WeaponFullDef, weapDef.strafeRot[0]), CSPFT_FLOAT }, + {"strafeRotY", offsetof(WeaponFullDef, weapDef.strafeRot[1]), CSPFT_FLOAT }, + {"strafeRotR", offsetof(WeaponFullDef, weapDef.strafeRot[2]), CSPFT_FLOAT }, + {"duckedOfsF", offsetof(WeaponFullDef, weapDef.vDuckedOfs[0]), CSPFT_FLOAT }, + {"duckedOfsR", offsetof(WeaponFullDef, weapDef.vDuckedOfs[1]), CSPFT_FLOAT }, + {"duckedOfsU", offsetof(WeaponFullDef, weapDef.vDuckedOfs[2]), CSPFT_FLOAT }, + {"duckedMoveF", offsetof(WeaponFullDef, weapDef.vDuckedMove[0]), CSPFT_FLOAT }, + {"duckedMoveR", offsetof(WeaponFullDef, weapDef.vDuckedMove[1]), CSPFT_FLOAT }, + {"duckedMoveU", offsetof(WeaponFullDef, weapDef.vDuckedMove[2]), CSPFT_FLOAT }, + {"duckedRotP", offsetof(WeaponFullDef, weapDef.vDuckedRot[0]), CSPFT_FLOAT }, + {"duckedRotY", offsetof(WeaponFullDef, weapDef.vDuckedRot[1]), CSPFT_FLOAT }, + {"duckedRotR", offsetof(WeaponFullDef, weapDef.vDuckedRot[2]), CSPFT_FLOAT }, + {"proneOfsF", offsetof(WeaponFullDef, weapDef.vProneOfs[0]), CSPFT_FLOAT }, + {"proneOfsR", offsetof(WeaponFullDef, weapDef.vProneOfs[1]), CSPFT_FLOAT }, + {"proneOfsU", offsetof(WeaponFullDef, weapDef.vProneOfs[2]), CSPFT_FLOAT }, + {"proneMoveF", offsetof(WeaponFullDef, weapDef.vProneMove[0]), CSPFT_FLOAT }, + {"proneMoveR", offsetof(WeaponFullDef, weapDef.vProneMove[1]), CSPFT_FLOAT }, + {"proneMoveU", offsetof(WeaponFullDef, weapDef.vProneMove[2]), CSPFT_FLOAT }, + {"proneRotP", offsetof(WeaponFullDef, weapDef.vProneRot[0]), CSPFT_FLOAT }, + {"proneRotY", offsetof(WeaponFullDef, weapDef.vProneRot[1]), CSPFT_FLOAT }, + {"proneRotR", offsetof(WeaponFullDef, weapDef.vProneRot[2]), CSPFT_FLOAT }, + {"posMoveRate", offsetof(WeaponFullDef, weapDef.fPosMoveRate), CSPFT_FLOAT }, + {"posProneMoveRate", offsetof(WeaponFullDef, weapDef.fPosProneMoveRate), CSPFT_FLOAT }, + {"standMoveMinSpeed", offsetof(WeaponFullDef, weapDef.fStandMoveMinSpeed), CSPFT_FLOAT }, + {"duckedMoveMinSpeed", offsetof(WeaponFullDef, weapDef.fDuckedMoveMinSpeed), CSPFT_FLOAT }, + {"proneMoveMinSpeed", offsetof(WeaponFullDef, weapDef.fProneMoveMinSpeed), CSPFT_FLOAT }, + {"posRotRate", offsetof(WeaponFullDef, weapDef.fPosRotRate), CSPFT_FLOAT }, + {"posProneRotRate", offsetof(WeaponFullDef, weapDef.fPosProneRotRate), CSPFT_FLOAT }, + {"standRotMinSpeed", offsetof(WeaponFullDef, weapDef.fStandRotMinSpeed), CSPFT_FLOAT }, + {"duckedRotMinSpeed", offsetof(WeaponFullDef, weapDef.fDuckedRotMinSpeed), CSPFT_FLOAT }, + {"proneRotMinSpeed", offsetof(WeaponFullDef, weapDef.fProneRotMinSpeed), CSPFT_FLOAT }, + {"worldModel", offsetof(WeaponFullDef, worldModel[0]), CSPFT_XMODEL }, + {"worldModel2", offsetof(WeaponFullDef, worldModel[1]), CSPFT_XMODEL }, + {"worldModel3", offsetof(WeaponFullDef, worldModel[2]), CSPFT_XMODEL }, + {"worldModel4", offsetof(WeaponFullDef, worldModel[3]), CSPFT_XMODEL }, + {"worldModel5", offsetof(WeaponFullDef, worldModel[4]), CSPFT_XMODEL }, + {"worldModel6", offsetof(WeaponFullDef, worldModel[5]), CSPFT_XMODEL }, + {"worldModel7", offsetof(WeaponFullDef, worldModel[6]), CSPFT_XMODEL }, + {"worldModel8", offsetof(WeaponFullDef, worldModel[7]), CSPFT_XMODEL }, + {"worldModel9", offsetof(WeaponFullDef, worldModel[8]), CSPFT_XMODEL }, + {"worldModel10", offsetof(WeaponFullDef, worldModel[9]), CSPFT_XMODEL }, + {"worldModel11", offsetof(WeaponFullDef, worldModel[10]), CSPFT_XMODEL }, + {"worldModel12", offsetof(WeaponFullDef, worldModel[11]), CSPFT_XMODEL }, + {"worldModel13", offsetof(WeaponFullDef, worldModel[12]), CSPFT_XMODEL }, + {"worldModel14", offsetof(WeaponFullDef, worldModel[13]), CSPFT_XMODEL }, + {"worldModel15", offsetof(WeaponFullDef, worldModel[14]), CSPFT_XMODEL }, + {"worldModel16", offsetof(WeaponFullDef, worldModel[15]), CSPFT_XMODEL }, + {"worldClipModel", offsetof(WeaponFullDef, weapDef.worldClipModel), CSPFT_XMODEL }, + {"rocketModel", offsetof(WeaponFullDef, weapDef.rocketModel), CSPFT_XMODEL }, + {"knifeModel", offsetof(WeaponFullDef, weapDef.knifeModel), CSPFT_XMODEL }, + {"worldKnifeModel", offsetof(WeaponFullDef, weapDef.worldKnifeModel), CSPFT_XMODEL }, + {"hudIcon", offsetof(WeaponFullDef, weapDef.hudIcon), CSPFT_MATERIAL }, + {"hudIconRatio", offsetof(WeaponFullDef, weapDef.hudIconRatio), WFT_ICONRATIO_HUD }, + {"pickupIcon", offsetof(WeaponFullDef, weapDef.pickupIcon), CSPFT_MATERIAL }, + {"pickupIconRatio", offsetof(WeaponFullDef, weapDef.pickupIconRatio), WFT_ICONRATIO_PICKUP }, + {"ammoCounterIcon", offsetof(WeaponFullDef, weapDef.ammoCounterIcon), CSPFT_MATERIAL }, + {"ammoCounterIconRatio", offsetof(WeaponFullDef, weapDef.ammoCounterIconRatio), WFT_ICONRATIO_AMMOCOUNTER}, + {"ammoCounterClip", offsetof(WeaponFullDef, weapDef.ammoCounterClip), WFT_AMMOCOUNTER_CLIPTYPE }, + {"startAmmo", offsetof(WeaponFullDef, weapDef.iStartAmmo), CSPFT_INT }, + {"shareAmmo", offsetof(WeaponFullDef, weapDef.sharedAmmo), CSPFT_BOOL }, + {"ammoName", offsetof(WeaponFullDef, weapDef.szAmmoName), CSPFT_STRING }, + {"clipName", offsetof(WeaponFullDef, weapDef.szClipName), CSPFT_STRING }, + {"maxAmmo", offsetof(WeaponFullDef, weapDef.iMaxAmmo), CSPFT_INT }, + {"clipSize", offsetof(WeaponFullDef, weapCompleteDef.iClipSize), CSPFT_INT }, + {"shotCount", offsetof(WeaponFullDef, weapDef.shotCount), CSPFT_INT }, + {"sharedAmmoCapName", offsetof(WeaponFullDef, weapDef.szSharedAmmoCapName), CSPFT_STRING }, + {"sharedAmmoCap", offsetof(WeaponFullDef, weapDef.iSharedAmmoCap), CSPFT_INT }, + {"damage", offsetof(WeaponFullDef, weapDef.damage), CSPFT_INT }, + {"playerDamage", offsetof(WeaponFullDef, weapDef.playerDamage), CSPFT_INT }, + {"meleeDamage", offsetof(WeaponFullDef, weapDef.iMeleeDamage), CSPFT_INT }, + {"minDamage", offsetof(WeaponFullDef, weapDef.minDamage), CSPFT_INT }, + {"minPlayerDamage", offsetof(WeaponFullDef, weapDef.minPlayerDamage), CSPFT_INT }, + {"maxDamageRange", offsetof(WeaponFullDef, weapDef.fMaxDamageRange), CSPFT_FLOAT }, + {"minDamageRange", offsetof(WeaponFullDef, weapDef.fMinDamageRange), CSPFT_FLOAT }, + {"destabilizationRateTime", offsetof(WeaponFullDef, weapDef.destabilizationRateTime), CSPFT_FLOAT }, + {"destabilizationCurvatureMax", offsetof(WeaponFullDef, weapDef.destabilizationCurvatureMax), CSPFT_FLOAT }, + {"destabilizeDistance", offsetof(WeaponFullDef, weapDef.destabilizeDistance), CSPFT_INT }, + {"fireDelay", offsetof(WeaponFullDef, weapDef.iFireDelay), CSPFT_MILLISECONDS }, + {"meleeDelay", offsetof(WeaponFullDef, weapDef.iMeleeDelay), CSPFT_MILLISECONDS }, + {"meleeChargeDelay", offsetof(WeaponFullDef, weapDef.meleeChargeDelay), CSPFT_MILLISECONDS }, + {"fireTime", offsetof(WeaponFullDef, weapCompleteDef.iFireTime), CSPFT_MILLISECONDS }, + {"rechamberTime", offsetof(WeaponFullDef, weapDef.iRechamberTime), CSPFT_MILLISECONDS }, + {"rechamberTimeOneHanded", offsetof(WeaponFullDef, weapDef.rechamberTimeOneHanded), CSPFT_MILLISECONDS }, + {"rechamberBoltTime", offsetof(WeaponFullDef, weapDef.iRechamberBoltTime), CSPFT_MILLISECONDS }, + {"holdFireTime", offsetof(WeaponFullDef, weapDef.iHoldFireTime), CSPFT_MILLISECONDS }, + {"detonateTime", offsetof(WeaponFullDef, weapDef.iDetonateTime), CSPFT_MILLISECONDS }, + {"detonateDelay", offsetof(WeaponFullDef, weapDef.iDetonateDelay), CSPFT_MILLISECONDS }, + {"meleeTime", offsetof(WeaponFullDef, weapDef.iMeleeTime), CSPFT_MILLISECONDS }, + {"meleeChargeTime", offsetof(WeaponFullDef, weapDef.meleeChargeTime), CSPFT_MILLISECONDS }, + {"reloadTime", offsetof(WeaponFullDef, weapDef.iReloadTime), CSPFT_MILLISECONDS }, + {"reloadShowRocketTime", offsetof(WeaponFullDef, weapDef.reloadShowRocketTime), CSPFT_MILLISECONDS }, + {"reloadEmptyTime", offsetof(WeaponFullDef, weapDef.iReloadEmptyTime), CSPFT_MILLISECONDS }, + {"reloadAddTime", offsetof(WeaponFullDef, weapDef.iReloadAddTime), CSPFT_MILLISECONDS }, + {"reloadStartTime", offsetof(WeaponFullDef, weapDef.iReloadStartTime), CSPFT_MILLISECONDS }, + {"reloadStartAddTime", offsetof(WeaponFullDef, weapDef.iReloadStartAddTime), CSPFT_MILLISECONDS }, + {"reloadEndTime", offsetof(WeaponFullDef, weapDef.iReloadEndTime), CSPFT_MILLISECONDS }, + {"dropTime", offsetof(WeaponFullDef, weapDef.iDropTime), CSPFT_MILLISECONDS }, + {"raiseTime", offsetof(WeaponFullDef, weapDef.iRaiseTime), CSPFT_MILLISECONDS }, + {"altDropTime", offsetof(WeaponFullDef, weapDef.iAltDropTime), CSPFT_MILLISECONDS }, + {"altRaiseTime", offsetof(WeaponFullDef, weapCompleteDef.iAltRaiseTime), CSPFT_MILLISECONDS }, + {"quickDropTime", offsetof(WeaponFullDef, weapDef.quickDropTime), CSPFT_MILLISECONDS }, + {"quickRaiseTime", offsetof(WeaponFullDef, weapDef.quickRaiseTime), CSPFT_MILLISECONDS }, + {"firstRaiseTime", offsetof(WeaponFullDef, weapCompleteDef.iFirstRaiseTime), CSPFT_MILLISECONDS }, + {"breachRaiseTime", offsetof(WeaponFullDef, weapDef.iBreachRaiseTime), CSPFT_MILLISECONDS }, + {"emptyRaiseTime", offsetof(WeaponFullDef, weapDef.iEmptyRaiseTime), CSPFT_MILLISECONDS }, + {"emptyDropTime", offsetof(WeaponFullDef, weapDef.iEmptyDropTime), CSPFT_MILLISECONDS }, + {"sprintInTime", offsetof(WeaponFullDef, weapDef.sprintInTime), CSPFT_MILLISECONDS }, + {"sprintLoopTime", offsetof(WeaponFullDef, weapDef.sprintLoopTime), CSPFT_MILLISECONDS }, + {"sprintOutTime", offsetof(WeaponFullDef, weapDef.sprintOutTime), CSPFT_MILLISECONDS }, + {"stunnedTimeBegin", offsetof(WeaponFullDef, weapDef.stunnedTimeBegin), CSPFT_MILLISECONDS }, + {"stunnedTimeLoop", offsetof(WeaponFullDef, weapDef.stunnedTimeLoop), CSPFT_MILLISECONDS }, + {"stunnedTimeEnd", offsetof(WeaponFullDef, weapDef.stunnedTimeEnd), CSPFT_MILLISECONDS }, + {"nightVisionWearTime", offsetof(WeaponFullDef, weapDef.nightVisionWearTime), CSPFT_MILLISECONDS }, + {"nightVisionWearTimeFadeOutEnd", offsetof(WeaponFullDef, weapDef.nightVisionWearTimeFadeOutEnd), CSPFT_MILLISECONDS }, + {"nightVisionWearTimePowerUp", offsetof(WeaponFullDef, weapDef.nightVisionWearTimePowerUp), CSPFT_MILLISECONDS }, + {"nightVisionRemoveTime", offsetof(WeaponFullDef, weapDef.nightVisionRemoveTime), CSPFT_MILLISECONDS }, + {"nightVisionRemoveTimePowerDown", offsetof(WeaponFullDef, weapDef.nightVisionRemoveTimePowerDown), CSPFT_MILLISECONDS }, + {"nightVisionRemoveTimeFadeInStart", offsetof(WeaponFullDef, weapDef.nightVisionRemoveTimeFadeInStart), CSPFT_MILLISECONDS }, + {"fuseTime", offsetof(WeaponFullDef, weapDef.fuseTime), CSPFT_MILLISECONDS }, + {"aifuseTime", offsetof(WeaponFullDef, weapDef.aiFuseTime), CSPFT_MILLISECONDS }, + {"lockonSupported", offsetof(WeaponFullDef, weapDef.lockonSupported), CSPFT_BOOL }, + {"requireLockonToFire", offsetof(WeaponFullDef, weapDef.requireLockonToFire), CSPFT_BOOL }, + {"bigExplosion", offsetof(WeaponFullDef, weapDef.bigExplosion), CSPFT_BOOL }, + {"noAdsWhenMagEmpty", offsetof(WeaponFullDef, weapDef.noAdsWhenMagEmpty), CSPFT_BOOL }, + {"inheritsPerks", offsetof(WeaponFullDef, weapDef.inheritsPerks), CSPFT_BOOL }, + {"avoidDropCleanup", offsetof(WeaponFullDef, weapDef.avoidDropCleanup), CSPFT_BOOL }, + {"autoAimRange", offsetof(WeaponFullDef, weapDef.autoAimRange), CSPFT_FLOAT }, + {"aimAssistRange", offsetof(WeaponFullDef, weapDef.aimAssistRange), CSPFT_FLOAT }, + {"aimAssistRangeAds", offsetof(WeaponFullDef, weapDef.aimAssistRangeAds), CSPFT_FLOAT }, + {"aimPadding", offsetof(WeaponFullDef, weapDef.aimPadding), CSPFT_FLOAT }, + {"enemyCrosshairRange", offsetof(WeaponFullDef, weapDef.enemyCrosshairRange), CSPFT_FLOAT }, + {"crosshairColorChange", offsetof(WeaponFullDef, weapDef.crosshairColorChange), CSPFT_BOOL }, + {"moveSpeedScale", offsetof(WeaponFullDef, weapDef.moveSpeedScale), CSPFT_FLOAT }, + {"adsMoveSpeedScale", offsetof(WeaponFullDef, weapDef.adsMoveSpeedScale), CSPFT_FLOAT }, + {"sprintDurationScale", offsetof(WeaponFullDef, weapDef.sprintDurationScale), CSPFT_FLOAT }, + {"idleCrouchFactor", offsetof(WeaponFullDef, weapDef.fIdleCrouchFactor), CSPFT_FLOAT }, + {"idleProneFactor", offsetof(WeaponFullDef, weapDef.fIdleProneFactor), CSPFT_FLOAT }, + {"gunMaxPitch", offsetof(WeaponFullDef, weapDef.fGunMaxPitch), CSPFT_FLOAT }, + {"gunMaxYaw", offsetof(WeaponFullDef, weapDef.fGunMaxYaw), CSPFT_FLOAT }, + {"swayMaxAngle", offsetof(WeaponFullDef, weapDef.swayMaxAngle), CSPFT_FLOAT }, + {"swayLerpSpeed", offsetof(WeaponFullDef, weapDef.swayLerpSpeed), CSPFT_FLOAT }, + {"swayPitchScale", offsetof(WeaponFullDef, weapDef.swayPitchScale), CSPFT_FLOAT }, + {"swayYawScale", offsetof(WeaponFullDef, weapDef.swayYawScale), CSPFT_FLOAT }, + {"swayHorizScale", offsetof(WeaponFullDef, weapDef.swayHorizScale), CSPFT_FLOAT }, + {"swayVertScale", offsetof(WeaponFullDef, weapDef.swayVertScale), CSPFT_FLOAT }, + {"swayShellShockScale", offsetof(WeaponFullDef, weapDef.swayShellShockScale), CSPFT_FLOAT }, + {"adsSwayMaxAngle", offsetof(WeaponFullDef, weapDef.adsSwayMaxAngle), CSPFT_FLOAT }, + {"adsSwayLerpSpeed", offsetof(WeaponFullDef, weapDef.adsSwayLerpSpeed), CSPFT_FLOAT }, + {"adsSwayPitchScale", offsetof(WeaponFullDef, weapDef.adsSwayPitchScale), CSPFT_FLOAT }, + {"adsSwayYawScale", offsetof(WeaponFullDef, weapDef.adsSwayYawScale), CSPFT_FLOAT }, + {"adsSwayHorizScale", offsetof(WeaponFullDef, weapDef.adsSwayHorizScale), CSPFT_FLOAT }, + {"adsSwayVertScale", offsetof(WeaponFullDef, weapDef.adsSwayVertScale), CSPFT_FLOAT }, + {"rifleBullet", offsetof(WeaponFullDef, weapDef.bRifleBullet), CSPFT_BOOL }, + {"armorPiercing", offsetof(WeaponFullDef, weapDef.armorPiercing), CSPFT_BOOL }, + {"boltAction", offsetof(WeaponFullDef, weapDef.bBoltAction), CSPFT_BOOL }, + {"aimDownSight", offsetof(WeaponFullDef, weapDef.aimDownSight), CSPFT_BOOL }, + {"rechamberWhileAds", offsetof(WeaponFullDef, weapDef.bRechamberWhileAds), CSPFT_BOOL }, + {"bBulletExplosiveDamage", offsetof(WeaponFullDef, weapDef.bBulletExplosiveDamage), CSPFT_BOOL }, + {"adsViewErrorMin", offsetof(WeaponFullDef, weapDef.adsViewErrorMin), CSPFT_FLOAT }, + {"adsViewErrorMax", offsetof(WeaponFullDef, weapDef.adsViewErrorMax), CSPFT_FLOAT }, + {"clipOnly", offsetof(WeaponFullDef, weapDef.bClipOnly), CSPFT_BOOL }, + {"noAmmoPickup", offsetof(WeaponFullDef, weapDef.noAmmoPickup), CSPFT_BOOL }, + {"cookOffHold", offsetof(WeaponFullDef, weapDef.bCookOffHold), CSPFT_BOOL }, + {"adsFire", offsetof(WeaponFullDef, weapDef.adsFireOnly), CSPFT_BOOL }, + {"cancelAutoHolsterWhenEmpty", offsetof(WeaponFullDef, weapDef.cancelAutoHolsterWhenEmpty), CSPFT_BOOL }, + {"disableSwitchToWhenEmpty", offsetof(WeaponFullDef, weapDef.disableSwitchToWhenEmpty), CSPFT_BOOL }, + {"suppressAmmoReserveDisplay", offsetof(WeaponFullDef, weapDef.suppressAmmoReserveDisplay), CSPFT_BOOL }, + {"enhanced", offsetof(WeaponFullDef, weapCompleteDef.enhanced), CSPFT_BOOL }, + {"motionTracker", offsetof(WeaponFullDef, weapCompleteDef.motionTracker), CSPFT_BOOL }, + {"laserSightDuringNightvision", offsetof(WeaponFullDef, weapDef.laserSightDuringNightvision), CSPFT_BOOL }, + {"markableViewmodel", offsetof(WeaponFullDef, weapDef.markableViewmodel), CSPFT_BOOL }, + {"physCollmap", offsetof(WeaponFullDef, weapDef.physCollmap), CSPFT_PHYS_COLLMAP }, + {"noDualWield", offsetof(WeaponFullDef, weapDef.noDualWield), CSPFT_BOOL }, + {"dualWieldViewModelOffset", offsetof(WeaponFullDef, weapDef.dualWieldViewModelOffset), CSPFT_FLOAT }, + {"killIcon", offsetof(WeaponFullDef, weapCompleteDef.killIcon), CSPFT_MATERIAL }, + {"killIconRatio", offsetof(WeaponFullDef, weapDef.killIconRatio), WFT_ICONRATIO_KILL }, + {"flipKillIcon", offsetof(WeaponFullDef, weapDef.flipKillIcon), CSPFT_BOOL }, + {"dpadIcon", offsetof(WeaponFullDef, weapCompleteDef.dpadIcon), CSPFT_MATERIAL }, + {"dpadIconRatio", offsetof(WeaponFullDef, weapCompleteDef.dpadIconRatio), WFT_ICONRATIO_DPAD }, + {"dpadIconShowsAmmo", offsetof(WeaponFullDef, weapCompleteDef.dpadIconShowsAmmo), CSPFT_BOOL }, + {"noPartialReload", offsetof(WeaponFullDef, weapDef.bNoPartialReload), CSPFT_BOOL }, + {"segmentedReload", offsetof(WeaponFullDef, weapDef.bSegmentedReload), CSPFT_BOOL }, + {"reloadAmmoAdd", offsetof(WeaponFullDef, weapDef.iReloadAmmoAdd), CSPFT_INT }, + {"reloadStartAdd", offsetof(WeaponFullDef, weapDef.iReloadStartAdd), CSPFT_INT }, + {"altWeapon", offsetof(WeaponFullDef, weapCompleteDef.szAltWeaponName), CSPFT_STRING }, + {"dropAmmoMin", offsetof(WeaponFullDef, weapDef.ammoDropStockMin), CSPFT_INT }, + {"dropAmmoMax", offsetof(WeaponFullDef, weapCompleteDef.ammoDropStockMax), CSPFT_INT }, + {"ammoDropClipPercentMin", offsetof(WeaponFullDef, weapDef.ammoDropClipPercentMin), CSPFT_INT }, + {"ammoDropClipPercentMax", offsetof(WeaponFullDef, weapDef.ammoDropClipPercentMax), CSPFT_INT }, + {"blocksProne", offsetof(WeaponFullDef, weapDef.blocksProne), CSPFT_BOOL }, + {"silenced", offsetof(WeaponFullDef, weapDef.silenced), CSPFT_BOOL }, + {"isRollingGrenade", offsetof(WeaponFullDef, weapDef.isRollingGrenade), CSPFT_BOOL }, + {"explosionRadius", offsetof(WeaponFullDef, weapDef.iExplosionRadius), CSPFT_INT }, + {"explosionRadiusMin", offsetof(WeaponFullDef, weapDef.iExplosionRadiusMin), CSPFT_INT }, + {"explosionInnerDamage", offsetof(WeaponFullDef, weapDef.iExplosionInnerDamage), CSPFT_INT }, + {"explosionOuterDamage", offsetof(WeaponFullDef, weapDef.iExplosionOuterDamage), CSPFT_INT }, + {"damageConeAngle", offsetof(WeaponFullDef, weapDef.damageConeAngle), CSPFT_FLOAT }, + {"bulletExplDmgMult", offsetof(WeaponFullDef, weapDef.bulletExplDmgMult), CSPFT_FLOAT }, + {"bulletExplRadiusMult", offsetof(WeaponFullDef, weapDef.bulletExplRadiusMult), CSPFT_FLOAT }, + {"projectileSpeed", offsetof(WeaponFullDef, weapDef.iProjectileSpeed), CSPFT_INT }, + {"projectileSpeedUp", offsetof(WeaponFullDef, weapDef.iProjectileSpeedUp), CSPFT_INT }, + {"projectileSpeedForward", offsetof(WeaponFullDef, weapDef.iProjectileSpeedForward), CSPFT_INT }, + {"projectileActivateDist", offsetof(WeaponFullDef, weapDef.iProjectileActivateDist), CSPFT_INT }, + {"projectileLifetime", offsetof(WeaponFullDef, weapDef.projLifetime), CSPFT_FLOAT }, + {"timeToAccelerate", offsetof(WeaponFullDef, weapDef.timeToAccelerate), CSPFT_FLOAT }, + {"projectileCurvature", offsetof(WeaponFullDef, weapDef.projectileCurvature), CSPFT_FLOAT }, + {"projectileModel", offsetof(WeaponFullDef, weapDef.projectileModel), CSPFT_XMODEL }, + {"projExplosionType", offsetof(WeaponFullDef, weapDef.projExplosion), WFT_PROJ_EXPLOSION }, + {"projExplosionEffect", offsetof(WeaponFullDef, weapDef.projExplosionEffect), CSPFT_FX }, + {"projExplosionEffectForceNormalUp", offsetof(WeaponFullDef, weapDef.projExplosionEffectForceNormalUp), CSPFT_BOOL }, + {"projExplosionSound", offsetof(WeaponFullDef, weapDef.projExplosionSound), CSPFT_SOUND }, + {"projDudEffect", offsetof(WeaponFullDef, weapDef.projDudEffect), CSPFT_FX }, + {"projDudSound", offsetof(WeaponFullDef, weapDef.projDudSound), CSPFT_SOUND }, + {"projImpactExplode", offsetof(WeaponFullDef, weapDef.bProjImpactExplode), CSPFT_BOOL }, + {"stickiness", offsetof(WeaponFullDef, weapDef.stickiness), WFT_STICKINESS }, + {"stickToPlayers", offsetof(WeaponFullDef, weapDef.stickToPlayers), CSPFT_BOOL }, + {"hasDetonator", offsetof(WeaponFullDef, weapDef.hasDetonator), CSPFT_BOOL }, + {"disableFiring", offsetof(WeaponFullDef, weapDef.disableFiring), CSPFT_BOOL }, + {"timedDetonation", offsetof(WeaponFullDef, weapDef.timedDetonation), CSPFT_BOOL }, + {"rotate", offsetof(WeaponFullDef, weapDef.rotate), CSPFT_BOOL }, + {"holdButtonToThrow", offsetof(WeaponFullDef, weapDef.holdButtonToThrow), CSPFT_BOOL }, + {"freezeMovementWhenFiring", offsetof(WeaponFullDef, weapDef.freezeMovementWhenFiring), CSPFT_BOOL }, + {"lowAmmoWarningThreshold", offsetof(WeaponFullDef, weapDef.lowAmmoWarningThreshold), CSPFT_FLOAT }, + {"ricochetChance", offsetof(WeaponFullDef, weapDef.ricochetChance), CSPFT_FLOAT }, + {"offhandHoldIsCancelable", offsetof(WeaponFullDef, weapDef.offhandHoldIsCancelable), CSPFT_BOOL }, + {"parallelDefaultBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_DEFAULT]), CSPFT_FLOAT }, + {"parallelBarkBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_BARK]), CSPFT_FLOAT }, + {"parallelBrickBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_BRICK]), CSPFT_FLOAT }, + {"parallelCarpetBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_CARPET]), CSPFT_FLOAT }, + {"parallelClothBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_CLOTH]), CSPFT_FLOAT }, + {"parallelConcreteBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_CONCRETE]), CSPFT_FLOAT }, + {"parallelDirtBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_DIRT]), CSPFT_FLOAT }, + {"parallelFleshBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_FLESH]), CSPFT_FLOAT }, + {"parallelFoliageBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_FOLIAGE]), CSPFT_FLOAT }, + {"parallelGlassBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_GLASS]), CSPFT_FLOAT }, + {"parallelGrassBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_GRASS]), CSPFT_FLOAT }, + {"parallelGravelBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_GRAVEL]), CSPFT_FLOAT }, + {"parallelIceBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_ICE]), CSPFT_FLOAT }, + {"parallelMetalBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_METAL]), CSPFT_FLOAT }, + {"parallelMudBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_MUD]), CSPFT_FLOAT }, + {"parallelPaperBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_PAPER]), CSPFT_FLOAT }, + {"parallelPlasterBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_PLASTER]), CSPFT_FLOAT }, + {"parallelRockBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_ROCK]), CSPFT_FLOAT }, + {"parallelSandBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_SAND]), CSPFT_FLOAT }, + {"parallelSnowBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_SNOW]), CSPFT_FLOAT }, + {"parallelWaterBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_WATER]), CSPFT_FLOAT }, + {"parallelWoodBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_WOOD]), CSPFT_FLOAT }, + {"parallelAsphaltBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_ASPHALT]), CSPFT_FLOAT }, + {"parallelCeramicBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_CERAMIC]), CSPFT_FLOAT }, + {"parallelPlasticBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_PLASTIC]), CSPFT_FLOAT }, + {"parallelRubberBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_RUBBER]), CSPFT_FLOAT }, + {"parallelCushionBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_CUSHION]), CSPFT_FLOAT }, + {"parallelFruitBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_FRUIT]), CSPFT_FLOAT }, + {"parallelPaintedMetalBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_PAINTED_METAL]), CSPFT_FLOAT }, + {"parallelRiotShieldBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_RIOT_SHIELD]), CSPFT_FLOAT }, + {"parallelSlushBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_SLUSH]), CSPFT_FLOAT }, + {"perpendicularDefaultBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_DEFAULT]), CSPFT_FLOAT }, + {"perpendicularBarkBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_BARK]), CSPFT_FLOAT }, + {"perpendicularBrickBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_BRICK]), CSPFT_FLOAT }, + {"perpendicularCarpetBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_CARPET]), CSPFT_FLOAT }, + {"perpendicularClothBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_CLOTH]), CSPFT_FLOAT }, + {"perpendicularConcreteBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_CONCRETE]), CSPFT_FLOAT }, + {"perpendicularDirtBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_DIRT]), CSPFT_FLOAT }, + {"perpendicularFleshBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_FLESH]), CSPFT_FLOAT }, + {"perpendicularFoliageBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_FOLIAGE]), CSPFT_FLOAT }, + {"perpendicularGlassBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_GLASS]), CSPFT_FLOAT }, + {"perpendicularGrassBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_GRASS]), CSPFT_FLOAT }, + {"perpendicularGravelBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_GRAVEL]), CSPFT_FLOAT }, + {"perpendicularIceBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_ICE]), CSPFT_FLOAT }, + {"perpendicularMetalBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_METAL]), CSPFT_FLOAT }, + {"perpendicularMudBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_MUD]), CSPFT_FLOAT }, + {"perpendicularPaperBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_PAPER]), CSPFT_FLOAT }, + {"perpendicularPlasterBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_PLASTER]), CSPFT_FLOAT }, + {"perpendicularRockBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_ROCK]), CSPFT_FLOAT }, + {"perpendicularSandBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_SAND]), CSPFT_FLOAT }, + {"perpendicularSnowBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_SNOW]), CSPFT_FLOAT }, + {"perpendicularWaterBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_WATER]), CSPFT_FLOAT }, + {"perpendicularWoodBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_WOOD]), CSPFT_FLOAT }, + {"perpendicularAsphaltBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_ASPHALT]), CSPFT_FLOAT }, + {"perpendicularCeramicBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_CERAMIC]), CSPFT_FLOAT }, + {"perpendicularPlasticBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_PLASTIC]), CSPFT_FLOAT }, + {"perpendicularRubberBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_RUBBER]), CSPFT_FLOAT }, + {"perpendicularCushionBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_CUSHION]), CSPFT_FLOAT }, + {"perpendicularFruitBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_FRUIT]), CSPFT_FLOAT }, + {"perpendicularPaintedMetalBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_PAINTED_METAL]), CSPFT_FLOAT }, + {"perpendicularRiotShieldBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_RIOT_SHIELD]), CSPFT_FLOAT }, + {"perpendicularSlushBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_SLUSH]), CSPFT_FLOAT }, + {"projTrailEffect", offsetof(WeaponFullDef, weapDef.projTrailEffect), CSPFT_FX }, + {"projBeaconEffect", offsetof(WeaponFullDef, weapDef.projBeaconEffect), CSPFT_FX }, + {"projectileRed", offsetof(WeaponFullDef, weapDef.vProjectileColor[0]), CSPFT_FLOAT }, + {"projectileGreen", offsetof(WeaponFullDef, weapDef.vProjectileColor[1]), CSPFT_FLOAT }, + {"projectileBlue", offsetof(WeaponFullDef, weapDef.vProjectileColor[2]), CSPFT_FLOAT }, + {"guidedMissileType", offsetof(WeaponFullDef, weapDef.guidedMissileType), WFT_GUIDED_MISSILE_TYPE }, + {"maxSteeringAccel", offsetof(WeaponFullDef, weapDef.maxSteeringAccel), CSPFT_FLOAT }, + {"projIgnitionDelay", offsetof(WeaponFullDef, weapDef.projIgnitionDelay), CSPFT_INT }, + {"projIgnitionEffect", offsetof(WeaponFullDef, weapDef.projIgnitionEffect), CSPFT_FX }, + {"projIgnitionSound", offsetof(WeaponFullDef, weapDef.projIgnitionSound), CSPFT_SOUND }, + {"adsTransInTime", offsetof(WeaponFullDef, weapCompleteDef.iAdsTransInTime), CSPFT_MILLISECONDS }, + {"adsTransOutTime", offsetof(WeaponFullDef, weapCompleteDef.iAdsTransOutTime), CSPFT_MILLISECONDS }, + {"adsIdleAmount", offsetof(WeaponFullDef, weapDef.fAdsIdleAmount), CSPFT_FLOAT }, + {"adsIdleSpeed", offsetof(WeaponFullDef, weapDef.adsIdleSpeed), CSPFT_FLOAT }, + {"adsZoomFov", offsetof(WeaponFullDef, weapCompleteDef.fAdsZoomFov), CSPFT_FLOAT }, + {"adsZoomInFrac", offsetof(WeaponFullDef, weapDef.fAdsZoomInFrac), CSPFT_FLOAT }, + {"adsZoomOutFrac", offsetof(WeaponFullDef, weapDef.fAdsZoomOutFrac), CSPFT_FLOAT }, + {"adsOverlayShader", offsetof(WeaponFullDef, weapDef.overlayMaterial), CSPFT_MATERIAL }, + {"adsOverlayShaderLowRes", offsetof(WeaponFullDef, weapDef.overlayMaterialLowRes), CSPFT_MATERIAL }, + {"adsOverlayShaderEMP", offsetof(WeaponFullDef, weapDef.overlayMaterialEMP), CSPFT_MATERIAL }, + {"adsOverlayShaderEMPLowRes", offsetof(WeaponFullDef, weapDef.overlayMaterialEMPLowRes), CSPFT_MATERIAL }, + {"adsOverlayReticle", offsetof(WeaponFullDef, weapDef.overlayReticle), WFT_OVERLAYRETICLE }, + {"adsOverlayInterface", offsetof(WeaponFullDef, weapDef.overlayInterface), WFT_OVERLAYINTERFACE }, + {"adsOverlayWidth", offsetof(WeaponFullDef, weapDef.overlayWidth), CSPFT_FLOAT }, + {"adsOverlayHeight", offsetof(WeaponFullDef, weapDef.overlayHeight), CSPFT_FLOAT }, + {"adsOverlayWidthSplitscreen", offsetof(WeaponFullDef, weapDef.overlayWidthSplitscreen), CSPFT_FLOAT }, + {"adsOverlayHeightSplitscreen", offsetof(WeaponFullDef, weapDef.overlayHeightSplitscreen), CSPFT_FLOAT }, + {"adsBobFactor", offsetof(WeaponFullDef, weapDef.fAdsBobFactor), CSPFT_FLOAT }, + {"adsViewBobMult", offsetof(WeaponFullDef, weapDef.fAdsViewBobMult), CSPFT_FLOAT }, + {"adsAimPitch", offsetof(WeaponFullDef, weapDef.fAdsAimPitch), CSPFT_FLOAT }, + {"adsCrosshairInFrac", offsetof(WeaponFullDef, weapDef.fAdsCrosshairInFrac), CSPFT_FLOAT }, + {"adsCrosshairOutFrac", offsetof(WeaponFullDef, weapDef.fAdsCrosshairOutFrac), CSPFT_FLOAT }, + {"adsReloadTransTime", offsetof(WeaponFullDef, weapDef.iPositionReloadTransTime), CSPFT_MILLISECONDS }, + {"adsGunKickReducedKickBullets", offsetof(WeaponFullDef, weapDef.adsGunKickReducedKickBullets), CSPFT_INT }, + {"adsGunKickReducedKickPercent", offsetof(WeaponFullDef, weapDef.adsGunKickReducedKickPercent), CSPFT_FLOAT }, + {"adsGunKickPitchMin", offsetof(WeaponFullDef, weapDef.fAdsGunKickPitchMin), CSPFT_FLOAT }, + {"adsGunKickPitchMax", offsetof(WeaponFullDef, weapDef.fAdsGunKickPitchMax), CSPFT_FLOAT }, + {"adsGunKickYawMin", offsetof(WeaponFullDef, weapDef.fAdsGunKickYawMin), CSPFT_FLOAT }, + {"adsGunKickYawMax", offsetof(WeaponFullDef, weapDef.fAdsGunKickYawMax), CSPFT_FLOAT }, + {"adsGunKickAccel", offsetof(WeaponFullDef, weapDef.fAdsGunKickAccel), CSPFT_FLOAT }, + {"adsGunKickSpeedMax", offsetof(WeaponFullDef, weapDef.fAdsGunKickSpeedMax), CSPFT_FLOAT }, + {"adsGunKickSpeedDecay", offsetof(WeaponFullDef, weapDef.fAdsGunKickSpeedDecay), CSPFT_FLOAT }, + {"adsGunKickStaticDecay", offsetof(WeaponFullDef, weapDef.fAdsGunKickStaticDecay), CSPFT_FLOAT }, + {"adsViewKickPitchMin", offsetof(WeaponFullDef, weapDef.fAdsViewKickPitchMin), CSPFT_FLOAT }, + {"adsViewKickPitchMax", offsetof(WeaponFullDef, weapDef.fAdsViewKickPitchMax), CSPFT_FLOAT }, + {"adsViewKickYawMin", offsetof(WeaponFullDef, weapDef.fAdsViewKickYawMin), CSPFT_FLOAT }, + {"adsViewKickYawMax", offsetof(WeaponFullDef, weapDef.fAdsViewKickYawMax), CSPFT_FLOAT }, + {"adsViewKickCenterSpeed", offsetof(WeaponFullDef, weapCompleteDef.fAdsViewKickCenterSpeed), CSPFT_FLOAT }, + {"adsSpread", offsetof(WeaponFullDef, weapDef.fAdsSpread), CSPFT_FLOAT }, + {"guidedMissileType", offsetof(WeaponFullDef, weapDef.guidedMissileType), WFT_GUIDED_MISSILE_TYPE }, + {"hipSpreadStandMin", offsetof(WeaponFullDef, weapDef.fHipSpreadStandMin), CSPFT_FLOAT }, + {"hipSpreadDuckedMin", offsetof(WeaponFullDef, weapDef.fHipSpreadDuckedMin), CSPFT_FLOAT }, + {"hipSpreadProneMin", offsetof(WeaponFullDef, weapDef.fHipSpreadProneMin), CSPFT_FLOAT }, + {"hipSpreadMax", offsetof(WeaponFullDef, weapDef.hipSpreadStandMax), CSPFT_FLOAT }, + {"hipSpreadDuckedMax", offsetof(WeaponFullDef, weapDef.hipSpreadDuckedMax), CSPFT_FLOAT }, + {"hipSpreadProneMax", offsetof(WeaponFullDef, weapDef.hipSpreadProneMax), CSPFT_FLOAT }, + {"hipSpreadDecayRate", offsetof(WeaponFullDef, weapDef.fHipSpreadDecayRate), CSPFT_FLOAT }, + {"hipSpreadFireAdd", offsetof(WeaponFullDef, weapDef.fHipSpreadFireAdd), CSPFT_FLOAT }, + {"hipSpreadTurnAdd", offsetof(WeaponFullDef, weapDef.fHipSpreadTurnAdd), CSPFT_FLOAT }, + {"hipSpreadMoveAdd", offsetof(WeaponFullDef, weapDef.fHipSpreadMoveAdd), CSPFT_FLOAT }, + {"hipSpreadDuckedDecay", offsetof(WeaponFullDef, weapDef.fHipSpreadDuckedDecay), CSPFT_FLOAT }, + {"hipSpreadProneDecay", offsetof(WeaponFullDef, weapDef.fHipSpreadProneDecay), CSPFT_FLOAT }, + {"hipReticleSidePos", offsetof(WeaponFullDef, weapDef.fHipReticleSidePos), CSPFT_FLOAT }, + {"hipIdleAmount", offsetof(WeaponFullDef, weapDef.fHipIdleAmount), CSPFT_FLOAT }, + {"hipIdleSpeed", offsetof(WeaponFullDef, weapDef.hipIdleSpeed), CSPFT_FLOAT }, + {"hipGunKickReducedKickBullets", offsetof(WeaponFullDef, weapDef.hipGunKickReducedKickBullets), CSPFT_INT }, + {"hipGunKickReducedKickPercent", offsetof(WeaponFullDef, weapDef.hipGunKickReducedKickPercent), CSPFT_FLOAT }, + {"hipGunKickPitchMin", offsetof(WeaponFullDef, weapDef.fHipGunKickPitchMin), CSPFT_FLOAT }, + {"hipGunKickPitchMax", offsetof(WeaponFullDef, weapDef.fHipGunKickPitchMax), CSPFT_FLOAT }, + {"hipGunKickYawMin", offsetof(WeaponFullDef, weapDef.fHipGunKickYawMin), CSPFT_FLOAT }, + {"hipGunKickYawMax", offsetof(WeaponFullDef, weapDef.fHipGunKickYawMax), CSPFT_FLOAT }, + {"hipGunKickAccel", offsetof(WeaponFullDef, weapDef.fHipGunKickAccel), CSPFT_FLOAT }, + {"hipGunKickSpeedMax", offsetof(WeaponFullDef, weapDef.fHipGunKickSpeedMax), CSPFT_FLOAT }, + {"hipGunKickSpeedDecay", offsetof(WeaponFullDef, weapDef.fHipGunKickSpeedDecay), CSPFT_FLOAT }, + {"hipGunKickStaticDecay", offsetof(WeaponFullDef, weapDef.fHipGunKickStaticDecay), CSPFT_FLOAT }, + {"hipViewKickPitchMin", offsetof(WeaponFullDef, weapDef.fHipViewKickPitchMin), CSPFT_FLOAT }, + {"hipViewKickPitchMax", offsetof(WeaponFullDef, weapDef.fHipViewKickPitchMax), CSPFT_FLOAT }, + {"hipViewKickYawMin", offsetof(WeaponFullDef, weapDef.fHipViewKickYawMin), CSPFT_FLOAT }, + {"hipViewKickYawMax", offsetof(WeaponFullDef, weapDef.fHipViewKickYawMax), CSPFT_FLOAT }, + {"hipViewKickCenterSpeed", offsetof(WeaponFullDef, weapCompleteDef.fHipViewKickCenterSpeed), CSPFT_FLOAT }, + {"leftArc", offsetof(WeaponFullDef, weapDef.leftArc), CSPFT_FLOAT }, + {"rightArc", offsetof(WeaponFullDef, weapDef.rightArc), CSPFT_FLOAT }, + {"topArc", offsetof(WeaponFullDef, weapDef.topArc), CSPFT_FLOAT }, + {"bottomArc", offsetof(WeaponFullDef, weapDef.bottomArc), CSPFT_FLOAT }, + {"accuracy", offsetof(WeaponFullDef, weapDef.accuracy), CSPFT_FLOAT }, + {"aiSpread", offsetof(WeaponFullDef, weapDef.aiSpread), CSPFT_FLOAT }, + {"playerSpread", offsetof(WeaponFullDef, weapDef.playerSpread), CSPFT_FLOAT }, + {"maxVertTurnSpeed", offsetof(WeaponFullDef, weapDef.maxTurnSpeed[0]), CSPFT_FLOAT }, + {"maxHorTurnSpeed", offsetof(WeaponFullDef, weapDef.maxTurnSpeed[1]), CSPFT_FLOAT }, + {"minVertTurnSpeed", offsetof(WeaponFullDef, weapDef.minTurnSpeed[0]), CSPFT_FLOAT }, + {"minHorTurnSpeed", offsetof(WeaponFullDef, weapDef.minTurnSpeed[1]), CSPFT_FLOAT }, + {"pitchConvergenceTime", offsetof(WeaponFullDef, weapDef.pitchConvergenceTime), CSPFT_FLOAT }, + {"yawConvergenceTime", offsetof(WeaponFullDef, weapDef.yawConvergenceTime), CSPFT_FLOAT }, + {"suppressionTime", offsetof(WeaponFullDef, weapDef.suppressTime), CSPFT_FLOAT }, + {"maxRange", offsetof(WeaponFullDef, weapDef.maxRange), CSPFT_FLOAT }, + {"animHorRotateInc", offsetof(WeaponFullDef, weapDef.fAnimHorRotateInc), CSPFT_FLOAT }, + {"playerPositionDist", offsetof(WeaponFullDef, weapDef.fPlayerPositionDist), CSPFT_FLOAT }, + {"stance", offsetof(WeaponFullDef, weapDef.stance), WFT_STANCE }, + {"useHintString", offsetof(WeaponFullDef, weapDef.szUseHintString), CSPFT_STRING }, + {"dropHintString", offsetof(WeaponFullDef, weapDef.dropHintString), CSPFT_STRING }, + {"horizViewJitter", offsetof(WeaponFullDef, weapDef.horizViewJitter), CSPFT_FLOAT }, + {"vertViewJitter", offsetof(WeaponFullDef, weapDef.vertViewJitter), CSPFT_FLOAT }, + {"scanSpeed", offsetof(WeaponFullDef, weapDef.scanSpeed), CSPFT_FLOAT }, + {"scanAccel", offsetof(WeaponFullDef, weapDef.scanAccel), CSPFT_FLOAT }, + {"scanPauseTime", offsetof(WeaponFullDef, weapDef.scanPauseTime), CSPFT_MILLISECONDS }, + {"fightDist", offsetof(WeaponFullDef, weapDef.fightDist), CSPFT_FLOAT }, + {"maxDist", offsetof(WeaponFullDef, weapDef.maxDist), CSPFT_FLOAT }, + {"aiVsAiAccuracyGraph", offsetof(WeaponFullDef, weapDef.accuracyGraphName0), CSPFT_STRING }, + {"aiVsPlayerAccuracyGraph", offsetof(WeaponFullDef, weapDef.accuracyGraphName1), CSPFT_STRING }, + {"locNone", offsetof(WeaponFullDef, locationDamageMultipliers[HITLOC_NONE]), CSPFT_FLOAT }, + {"locHelmet", offsetof(WeaponFullDef, locationDamageMultipliers[HITLOC_HELMET]), CSPFT_FLOAT }, + {"locHead", offsetof(WeaponFullDef, locationDamageMultipliers[HITLOC_HEAD]), CSPFT_FLOAT }, + {"locNeck", offsetof(WeaponFullDef, locationDamageMultipliers[HITLOC_NECK]), CSPFT_FLOAT }, + {"locTorsoUpper", offsetof(WeaponFullDef, locationDamageMultipliers[HITLOC_TORSO_UPR]), CSPFT_FLOAT }, + {"locTorsoLower", offsetof(WeaponFullDef, locationDamageMultipliers[HITLOC_TORSO_LWR]), CSPFT_FLOAT }, + {"locRightArmUpper", offsetof(WeaponFullDef, locationDamageMultipliers[HITLOC_R_ARM_UPR]), CSPFT_FLOAT }, + {"locRightArmLower", offsetof(WeaponFullDef, locationDamageMultipliers[HITLOC_R_ARM_LWR]), CSPFT_FLOAT }, + {"locRightHand", offsetof(WeaponFullDef, locationDamageMultipliers[HITLOC_R_HAND]), CSPFT_FLOAT }, + {"locLeftArmUpper", offsetof(WeaponFullDef, locationDamageMultipliers[HITLOC_L_ARM_UPR]), CSPFT_FLOAT }, + {"locLeftArmLower", offsetof(WeaponFullDef, locationDamageMultipliers[HITLOC_L_ARM_LWR]), CSPFT_FLOAT }, + {"locLeftHand", offsetof(WeaponFullDef, locationDamageMultipliers[HITLOC_L_HAND]), CSPFT_FLOAT }, + {"locRightLegUpper", offsetof(WeaponFullDef, locationDamageMultipliers[HITLOC_R_LEG_UPR]), CSPFT_FLOAT }, + {"locRightLegLower", offsetof(WeaponFullDef, locationDamageMultipliers[HITLOC_R_LEG_LWR]), CSPFT_FLOAT }, + {"locRightFoot", offsetof(WeaponFullDef, locationDamageMultipliers[HITLOC_R_FOOT]), CSPFT_FLOAT }, + {"locLeftLegUpper", offsetof(WeaponFullDef, locationDamageMultipliers[HITLOC_L_LEG_UPR]), CSPFT_FLOAT }, + {"locLeftLegLower", offsetof(WeaponFullDef, locationDamageMultipliers[HITLOC_L_LEG_LWR]), CSPFT_FLOAT }, + {"locLeftFoot", offsetof(WeaponFullDef, locationDamageMultipliers[HITLOC_L_FOOT]), CSPFT_FLOAT }, + {"locGun", offsetof(WeaponFullDef, locationDamageMultipliers[HITLOC_GUN]), CSPFT_FLOAT }, + {"fireRumble", offsetof(WeaponFullDef, weapDef.fireRumble), CSPFT_STRING }, + {"meleeImpactRumble", offsetof(WeaponFullDef, weapDef.meleeImpactRumble), CSPFT_STRING }, + {"tracerType", offsetof(WeaponFullDef, weapDef.tracerType), CSPFT_TRACER }, + {"adsDofStart", offsetof(WeaponFullDef, weapCompleteDef.adsDofStart), CSPFT_FLOAT }, + {"adsDofEnd", offsetof(WeaponFullDef, weapCompleteDef.adsDofEnd), CSPFT_FLOAT }, + {"turretScopeZoomRate", offsetof(WeaponFullDef, weapDef.turretScopeZoomRate), CSPFT_FLOAT }, + {"turretScopeZoomMin", offsetof(WeaponFullDef, weapDef.turretScopeZoomMin), CSPFT_FLOAT }, + {"turretScopeZoomMax", offsetof(WeaponFullDef, weapDef.turretScopeZoomMax), CSPFT_FLOAT }, + {"thermalScope", offsetof(WeaponFullDef, weapDef.thermalScope), CSPFT_BOOL }, + {"altModeSameWeapon", offsetof(WeaponFullDef, weapDef.altModeSameWeapon), CSPFT_BOOL }, + {"turretOverheatUpRate", offsetof(WeaponFullDef, weapDef.turretOverheatUpRate), CSPFT_FLOAT }, + {"turretOverheatDownRate", offsetof(WeaponFullDef, weapDef.turretOverheatDownRate), CSPFT_FLOAT }, + {"turretOverheatPenalty", offsetof(WeaponFullDef, weapDef.turretOverheatPenalty), CSPFT_FLOAT }, + {"turretOverheatSound", offsetof(WeaponFullDef, weapDef.turretOverheatSound), CSPFT_SOUND }, + {"turretOverheatEffect", offsetof(WeaponFullDef, weapDef.turretOverheatEffect), CSPFT_FX }, + {"turretBarrelSpinEnabled", offsetof(WeaponFullDef, weapDef.turretBarrelSpinEnabled), CSPFT_BOOL }, + {"turretBarrelSpinUpTime", offsetof(WeaponFullDef, weapDef.turretBarrelSpinUpTime), CSPFT_FLOAT }, + {"turretBarrelSpinDownTime", offsetof(WeaponFullDef, weapDef.turretBarrelSpinDownTime), CSPFT_FLOAT }, + {"turretBarrelSpinRumble", offsetof(WeaponFullDef, weapDef.turretBarrelSpinRumble), CSPFT_STRING }, + {"turretBarrelSpinSpeed", offsetof(WeaponFullDef, weapDef.turretBarrelSpinSpeed), CSPFT_FLOAT }, + {"turretBarrelSpinMaxSnd", offsetof(WeaponFullDef, weapDef.turretBarrelSpinMaxSnd), CSPFT_SOUND }, + {"turretBarrelSpinUpSnd1", offsetof(WeaponFullDef, weapDef.turretBarrelSpinUpSnd[0]), CSPFT_SOUND }, + {"turretBarrelSpinUpSnd2", offsetof(WeaponFullDef, weapDef.turretBarrelSpinUpSnd[1]), CSPFT_SOUND }, + {"turretBarrelSpinUpSnd3", offsetof(WeaponFullDef, weapDef.turretBarrelSpinUpSnd[2]), CSPFT_SOUND }, + {"turretBarrelSpinUpSnd4", offsetof(WeaponFullDef, weapDef.turretBarrelSpinUpSnd[3]), CSPFT_SOUND }, + {"turretBarrelSpinDownSnd1", offsetof(WeaponFullDef, weapDef.turretBarrelSpinDownSnd[0]), CSPFT_SOUND }, + {"turretBarrelSpinDownSnd2", offsetof(WeaponFullDef, weapDef.turretBarrelSpinDownSnd[1]), CSPFT_SOUND }, + {"turretBarrelSpinDownSnd3", offsetof(WeaponFullDef, weapDef.turretBarrelSpinDownSnd[2]), CSPFT_SOUND }, + {"turretBarrelSpinDownSnd4", offsetof(WeaponFullDef, weapDef.turretBarrelSpinDownSnd[3]), CSPFT_SOUND }, + {"missileConeSoundEnabled", offsetof(WeaponFullDef, weapDef.missileConeSoundEnabled), CSPFT_BOOL }, + {"missileConeSoundAlias", offsetof(WeaponFullDef, weapDef.missileConeSoundAlias), CSPFT_SOUND }, + {"missileConeSoundAliasAtBase", offsetof(WeaponFullDef, weapDef.missileConeSoundAliasAtBase), CSPFT_SOUND }, + {"missileConeSoundRadiusAtTop", offsetof(WeaponFullDef, weapDef.missileConeSoundRadiusAtTop), CSPFT_FLOAT }, + {"missileConeSoundRadiusAtBase", offsetof(WeaponFullDef, weapDef.missileConeSoundRadiusAtBase), CSPFT_FLOAT }, + {"missileConeSoundHeight", offsetof(WeaponFullDef, weapDef.missileConeSoundHeight), CSPFT_FLOAT }, + {"missileConeSoundOriginOffset", offsetof(WeaponFullDef, weapDef.missileConeSoundOriginOffset), CSPFT_FLOAT }, + {"missileConeSoundVolumescaleAtCore", offsetof(WeaponFullDef, weapDef.missileConeSoundVolumescaleAtCore), CSPFT_FLOAT }, + {"missileConeSoundVolumescaleAtEdge", offsetof(WeaponFullDef, weapDef.missileConeSoundVolumescaleAtEdge), CSPFT_FLOAT }, + {"missileConeSoundVolumescaleCoreSize", offsetof(WeaponFullDef, weapDef.missileConeSoundVolumescaleCoreSize), CSPFT_FLOAT }, + {"missileConeSoundPitchshiftEnabled", offsetof(WeaponFullDef, weapDef.missileConeSoundPitchshiftEnabled), CSPFT_BOOL }, + {"missileConeSoundPitchAtTop", offsetof(WeaponFullDef, weapDef.missileConeSoundPitchAtTop), CSPFT_FLOAT }, + {"missileConeSoundPitchAtBottom", offsetof(WeaponFullDef, weapDef.missileConeSoundPitchAtBottom), CSPFT_FLOAT }, + {"missileConeSoundPitchTopSize", offsetof(WeaponFullDef, weapDef.missileConeSoundPitchTopSize), CSPFT_FLOAT }, + {"missileConeSoundPitchBottomSize", offsetof(WeaponFullDef, weapDef.missileConeSoundPitchBottomSize), CSPFT_FLOAT }, + {"missileConeSoundCrossfadeEnabled", offsetof(WeaponFullDef, weapDef.missileConeSoundCrossfadeEnabled), CSPFT_BOOL }, + {"missileConeSoundCrossfadeTopSize", offsetof(WeaponFullDef, weapDef.missileConeSoundCrossfadeTopSize), CSPFT_FLOAT }, + {"missileConeSoundCrossfadeBottomSize", offsetof(WeaponFullDef, weapDef.missileConeSoundCrossfadeBottomSize), CSPFT_FLOAT }, +}; } diff --git a/src/ObjCommon/Game/IW4/MaterialConstantsIW4.h b/src/ObjCommon/Game/IW4/MaterialConstantsIW4.h index 3f198b2c5..f656497f5 100644 --- a/src/ObjCommon/Game/IW4/MaterialConstantsIW4.h +++ b/src/ObjCommon/Game/IW4/MaterialConstantsIW4.h @@ -2,643 +2,468 @@ #include "Game/IW4/IW4.h" -namespace IW4 -{ - inline infoParm_t infoParms[] - { - {"bark", 0x0, 0x100000, 0x0, 0x0}, - {"brick", 0x0, 0x200000, 0x0, 0x0}, - {"carpet", 0x0, 0x300000, 0x0, 0x0}, - {"cloth", 0x0, 0x400000, 0x0, 0x0}, - {"concrete", 0x0, 0x500000, 0x0, 0x0}, - {"dirt", 0x0, 0x600000, 0x0, 0x0}, - {"flesh", 0x0, 0x700000, 0x0, 0x0}, - {"foliage", 0x1, 0x800000, 0x2, 0x0}, - {"glass", 0x1, 0x900000, 0x10, 0x0}, - {"grass", 0x0, 0xa00000, 0x0, 0x0}, - {"gravel", 0x0, 0xb00000, 0x0, 0x0}, - {"ice", 0x0, 0xc00000, 0x0, 0x0}, - {"metal", 0x0, 0xd00000, 0x0, 0x0}, - {"mud", 0x0, 0xe00000, 0x0, 0x0}, - {"paper", 0x0, 0xf00000, 0x0, 0x0}, - {"plaster", 0x0, 0x1000000, 0x0, 0x0}, - {"rock", 0x0, 0x1100000, 0x0, 0x0}, - {"sand", 0x0, 0x1200000, 0x0, 0x0}, - {"snow", 0x0, 0x1300000, 0x0, 0x0}, - {"water", 0x1, 0x1400000, 0x20, 0x0}, - {"wood", 0x0, 0x1500000, 0x0, 0x0}, - {"asphalt", 0x0, 0x1600000, 0x0, 0x0}, - {"ceramic", 0x0, 0x1700000, 0x0, 0x0}, - {"plastic", 0x0, 0x1800000, 0x0, 0x0}, - {"rubber", 0x0, 0x1900000, 0x0, 0x0}, - {"cushion", 0x0, 0x1a00000, 0x0, 0x0}, - {"fruit", 0x0, 0x1b00000, 0x0, 0x0}, - {"paintedmetal", 0x0, 0x1c00000, 0x0, 0x0}, - {"riotshield", 0x0, 0x1d00000, 0x0, 0x0}, - {"slush", 0x0, 0x1e00000, 0x0, 0x0}, - {"opaqueglass", 0x0, 0x900000, 0x0, 0x0}, - {"clipmissile", 0x1, 0x0, 0x80, 0x0}, - {"ai_nosight", 0x1, 0x0, 0x1000, 0x0}, - {"clipshot", 0x1, 0x0, 0x2000, 0x0}, - {"playerclip", 0x1, 0x0, 0x10000, 0x0}, - {"monsterclip", 0x1, 0x0, 0x20000, 0x0}, - {"aiclipallowdeath", 0x1, 0x0, 0x4, 0x0}, - {"vehicleclip", 0x1, 0x0, 0x200, 0x0}, - {"itemclip", 0x1, 0x0, 0x400, 0x0}, - {"nodrop", 0x1, 0x0, 0x80000000, 0x0}, - {"nonsolid", 0x1, 0x4000, 0x0, 0x0}, - {"detail", 0x0, 0x0, 0x8000000, 0x0}, - {"structural", 0x0, 0x0, 0x10000000, 0x0}, - {"portal", 0x1, 0x80000000, 0x0, 0x0}, - {"canshootclip", 0x0, 0x0, 0x40, 0x0}, - {"origin", 0x1, 0x0, 0x0, 0x4}, - {"sky", 0x0, 0x4, 0x800, 0x0}, - {"nocastshadow", 0x0, 0x40000, 0x0, 0x0}, - {"physicsGeom", 0x0, 0x0, 0x0, 0x400}, - {"lightPortal", 0x0, 0x0, 0x0, 0x2000}, - {"outdoorBounds", 0x0, 0x0, 0x0, 0x8000}, - {"slick", 0x0, 0x2, 0x0, 0x0}, - {"noimpact", 0x0, 0x10, 0x0, 0x0}, - {"nomarks", 0x0, 0x20, 0x0, 0x0}, - {"nopenetrate", 0x0, 0x100, 0x0, 0x0}, - {"ladder", 0x0, 0x8, 0x0, 0x0}, - {"nodamage", 0x0, 0x1, 0x0, 0x0}, - {"mantleOn", 0x0, 0x2000000, 0x1000000, 0x0}, - {"mantleOver", 0x0, 0x4000000, 0x1000000, 0x0}, - {"stairs", 0x0, 0x200, 0x0, 0x0}, - {"soft", 0x0, 0x1000, 0x0, 0x0}, - {"nosteps", 0x0, 0x2000, 0x0, 0x0}, - {"nodraw", 0x0, 0x80, 0x0, 0x0}, - {"nolightmap", 0x0, 0x400, 0x0, 0x0}, - {"nodlight", 0x0, 0x20000, 0x0, 0x0} - }; - - inline const char* surfaceTypeNames[] - { - "default", - "bark", - "brick", - "carpet", - "cloth", - "concrete", - "dirt", - "flesh", - "foliage", - "glass", - "grass", - "gravel", - "ice", - "metal", - "mud", - "paper", - "plaster", - "rock", - "sand", - "snow", - "water", - "wood", - "asphalt", - "ceramic", - "plastic", - "rubber", - "cushion", - "fruit", - "paintedmetal", - "riotshield", - "slush" - }; - static_assert(std::extent_v == SURF_TYPE_NUM); - - - enum class BlendFunc_e - { - UNKNOWN, - CUSTOM, - REPLACE, - BLEND, - ADD, - MULTIPLY, - SCREEN_ADD, - - COUNT - }; - - constexpr auto GDT_BLEND_FUNC_UNKNOWN = ""; - constexpr auto GDT_BLEND_FUNC_CUSTOM = "Custom"; - constexpr auto GDT_BLEND_FUNC_REPLACE = "Replace*"; - constexpr auto GDT_BLEND_FUNC_BLEND = "Blend"; - constexpr auto GDT_BLEND_FUNC_ADD = "Add"; - constexpr auto GDT_BLEND_FUNC_MULTIPLY = "Multiply"; - constexpr auto GDT_BLEND_FUNC_SCREEN_ADD = "Screen Add"; - - inline const char* GdtBlendFuncNames[] - { - GDT_BLEND_FUNC_UNKNOWN, - GDT_BLEND_FUNC_CUSTOM, - GDT_BLEND_FUNC_REPLACE, - GDT_BLEND_FUNC_BLEND, - GDT_BLEND_FUNC_ADD, - GDT_BLEND_FUNC_MULTIPLY, - GDT_BLEND_FUNC_SCREEN_ADD - }; - static_assert(std::extent_v == static_cast(BlendFunc_e::COUNT)); - - enum class BlendOp_e - { - UNKNOWN, - DISABLE, - ADD, - SUBTRACT, - REV_SUBTRACT, - MIN, - MAX, - - COUNT - }; - - constexpr auto GDT_BLEND_OP_UNKNOWN = ""; - constexpr auto GDT_BLEND_OP_DISABLE = "Disable"; - constexpr auto GDT_BLEND_OP_ADD = "Add*"; - constexpr auto GDT_BLEND_OP_SUBTRACT = "Subtract"; - constexpr auto GDT_BLEND_OP_REV_SUBTRACT = "RevSubtract"; - constexpr auto GDT_BLEND_OP_MIN = "Min"; - constexpr auto GDT_BLEND_OP_MAX = "Max"; - - inline const char* GdtBlendOpNames[] - { - GDT_BLEND_OP_UNKNOWN, - GDT_BLEND_OP_DISABLE, - GDT_BLEND_OP_ADD, - GDT_BLEND_OP_SUBTRACT, - GDT_BLEND_OP_REV_SUBTRACT, - GDT_BLEND_OP_MIN, - GDT_BLEND_OP_MAX - }; - static_assert(std::extent_v == static_cast(BlendOp_e::COUNT)); - - enum class CustomBlendFunc_e - { - UNKNOWN, - DISABLED, - ZERO, - ONE, - SRC_COLOR, - INV_SRC_COLOR, - SRC_ALPHA, - INV_SRC_ALPHA, - DST_ALPHA, - INV_DST_ALPHA, - DEST_COLOR, - INV_DST_COLOR, - - COUNT - }; - - inline const char* GdtCustomBlendFuncNames[] - { - "", - "Disable", - "Zero", - "One*", - "SrcColor", - "InvSrcColor", - "SrcAlpha", - "InvSrcAlpha", - "DestAlpha", - "InvDestAlpha", - "DestColor", - "InvDestColor" - }; - static_assert(std::extent_v == static_cast(CustomBlendFunc_e::COUNT)); - - enum class AlphaTest_e - { - UNKNOWN, - ALWAYS, - GT0, - LT128, - GE128, - - COUNT - }; - - constexpr auto GDT_ALPHA_TEST_UNKNOWN = ""; - constexpr auto GDT_ALPHA_TEST_ALWAYS = "Always*"; - constexpr auto GDT_ALPHA_TEST_GT0 = "GT0"; - constexpr auto GDT_ALPHA_TEST_LT128 = "LT128"; - constexpr auto GDT_ALPHA_TEST_GE128 = "GE128"; - - inline const char* GdtAlphaTestNames[] - { - GDT_ALPHA_TEST_UNKNOWN, - GDT_ALPHA_TEST_ALWAYS, - GDT_ALPHA_TEST_GT0, - GDT_ALPHA_TEST_LT128, - GDT_ALPHA_TEST_GE128 - }; - static_assert(std::extent_v == static_cast(AlphaTest_e::COUNT)); - - enum class DepthTest_e - { - UNKNOWN, - LESS_EQUAL, - LESS, - EQUAL, - ALWAYS, - DISABLE, - - COUNT - }; - - inline const char* GdtDepthTestNames[] - { - "", - "LessEqual*", - "Less", - "Equal", - "Always", - "Disable" - }; - static_assert(std::extent_v == static_cast(DepthTest_e::COUNT)); - - enum class StateBitsEnabledStatus_e - { - UNKNOWN, - ENABLED, - DISABLED, - - COUNT - }; - - inline const char* GdtStateBitsEnabledStatusNames[] - { - "", - "Enable", - "Disable" - }; - static_assert(std::extent_v == static_cast(StateBitsEnabledStatus_e::COUNT)); - - inline const char* GdtStateBitsOnOffStatusNames[] - { - "", - "On", - "Off" - }; - static_assert(std::extent_v == static_cast(StateBitsEnabledStatus_e::COUNT)); - - enum class CullFace_e - { - UNKNOWN, - NONE, - BACK, - FRONT, - - COUNT - }; - - inline const char* GdtCullFaceNames[] - { - "", - "None", - "Back*", - "Front" - }; - static_assert(std::extent_v == static_cast(CullFace_e::COUNT)); - - enum class PolygonOffset_e - { - UNKNOWN, - OFFSET_0, - OFFSET_1, - OFFSET_2, - OFFSET_SHADOW_MAP, - - COUNT - }; - - inline const char* GdtPolygonOffsetNames[] - { - "", - "0", - "1", - "2", - "shadowMap" - }; - static_assert(std::extent_v == static_cast(PolygonOffset_e::COUNT)); - - enum class StencilIndex - { - FRONT, - BACK - }; - - enum class StencilMode_e - { - UNKNOWN, - DISABLED, - ONE_SIDED, - TWO_SIDED, - - COUNT - }; - - inline const char* GdtStencilModeNames[] - { - "", - "Disable", - "One-sided", - "Two-sided" - }; - static_assert(std::extent_v == static_cast(StencilMode_e::COUNT)); - - enum class StencilFunc_e - { - UNKNOWN, - NEVER, - LESS, - EQUAL, - LESS_EQUAL, - GREATER, - NOT_EQUAL, - GREATER_EQUAL, - ALWAYS, - - COUNT - }; - - inline const char* GdtStencilFuncNames[] - { - "", - "Never", - "Less", - "Equal", - "LessEqual", - "Greater", - "NotEqual", - "GreaterEqual", - "Always" - }; - static_assert(std::extent_v == static_cast(StencilFunc_e::COUNT)); - - enum class StencilOp_e - { - UNKNOWN, - KEEP, - ZERO, - REPLACE, - INCR_SAT, - DECR_SAT, - INVERT, - INCR, - DECR, - - COUNT - }; - - inline const char* GdtStencilOpNames[] - { - "", - "Keep", - "Zero", - "Replace", - "IncrSat", - "DecrSat", - "Invert", - "Incr", - "Decr" - }; - static_assert(std::extent_v == static_cast(StencilOp_e::COUNT)); - - enum class TileMode_e - { - UNKNOWN, - TILE_BOTH, - TILE_HORIZONTAL, - TILE_VERTICAL, - NO_TILE, - - COUNT - }; - - inline const char* GdtTileModeNames[] - { - "", - "tile both*", - "tile horizontal", - "tile vertical", - "no tile" - }; - static_assert(std::extent_v == static_cast(TileMode_e::COUNT)); - - enum class GdtFilter_e - { - UNKNOWN, - MIP_2X_BILINEAR, - MIP_4X_BILINEAR, - MIP_2X_TRILINEAR, - MIP_4X_TRILINEAR, - NOMIP_NEAREST, - NOMIP_BILINEAR, - - COUNT - }; - - static const char* GdtSamplerFilterNames[] - { - "", - "mip standard (2x bilinear)*", - "mip expensive (4x bilinear)", - "mip more expensive (2x trilinear)", - "mip most expensive (4x trilinear)", - "nomip nearest", - "nomip bilinear" - }; - static_assert(std::extent_v == static_cast(GdtFilter_e::COUNT)); - - enum GdtMaterialType - { - MATERIAL_TYPE_UNKNOWN, - MATERIAL_TYPE_2D, - MATERIAL_TYPE_CUSTOM, - MATERIAL_TYPE_DISTORTION, - MATERIAL_TYPE_EFFECT, - MATERIAL_TYPE_IMPACT_MARK, - MATERIAL_TYPE_MODEL_AMBIENT, - MATERIAL_TYPE_MODEL_PHONG, - MATERIAL_TYPE_MODEL_UNLIT, - MATERIAL_TYPE_OBJECTIVE, - MATERIAL_TYPE_PARTICLE_CLOUD, - MATERIAL_TYPE_SKY, - MATERIAL_TYPE_TOOLS, - MATERIAL_TYPE_UNLIT, - MATERIAL_TYPE_WATER, - MATERIAL_TYPE_WORLD_PHONG, - MATERIAL_TYPE_WORLD_UNLIT, - - MATERIAL_TYPE_COUNT - }; - - constexpr auto GDT_MATERIAL_TYPE_UNKNOWN = ""; - constexpr auto GDT_MATERIAL_TYPE_2D = "2d"; - constexpr auto GDT_MATERIAL_TYPE_CUSTOM = "custom"; - constexpr auto GDT_MATERIAL_TYPE_DISTORTION = "distortion"; - constexpr auto GDT_MATERIAL_TYPE_EFFECT = "effect"; - constexpr auto GDT_MATERIAL_TYPE_IMPACT_MARK = "impact mark"; - constexpr auto GDT_MATERIAL_TYPE_MODEL_AMBIENT = "model ambient"; - constexpr auto GDT_MATERIAL_TYPE_MODEL_PHONG = "model phong"; - constexpr auto GDT_MATERIAL_TYPE_MODEL_UNLIT = "model unlit"; - constexpr auto GDT_MATERIAL_TYPE_OBJECTIVE = "objective"; - constexpr auto GDT_MATERIAL_TYPE_PARTICLE_CLOUD = "particle cloud"; - constexpr auto GDT_MATERIAL_TYPE_SKY = "sky"; - constexpr auto GDT_MATERIAL_TYPE_TOOLS = "tools"; - constexpr auto GDT_MATERIAL_TYPE_UNLIT = "unlit"; - constexpr auto GDT_MATERIAL_TYPE_WATER = "water"; - constexpr auto GDT_MATERIAL_TYPE_WORLD_PHONG = "world phong"; - constexpr auto GDT_MATERIAL_TYPE_WORLD_UNLIT = "world unlit"; - - inline const char* GdtMaterialTypeNames[] - { - GDT_MATERIAL_TYPE_UNKNOWN, - GDT_MATERIAL_TYPE_2D, - GDT_MATERIAL_TYPE_CUSTOM, - GDT_MATERIAL_TYPE_DISTORTION, - GDT_MATERIAL_TYPE_EFFECT, - GDT_MATERIAL_TYPE_IMPACT_MARK, - GDT_MATERIAL_TYPE_MODEL_AMBIENT, - GDT_MATERIAL_TYPE_MODEL_PHONG, - GDT_MATERIAL_TYPE_MODEL_UNLIT, - GDT_MATERIAL_TYPE_OBJECTIVE, - GDT_MATERIAL_TYPE_PARTICLE_CLOUD, - GDT_MATERIAL_TYPE_SKY, - GDT_MATERIAL_TYPE_TOOLS, - GDT_MATERIAL_TYPE_UNLIT, - GDT_MATERIAL_TYPE_WATER, - GDT_MATERIAL_TYPE_WORLD_PHONG, - GDT_MATERIAL_TYPE_WORLD_UNLIT - }; - static_assert(std::extent_v == static_cast(MATERIAL_TYPE_COUNT)); - - constexpr auto GDT_SORTKEY_DEFAULT = ""; - constexpr auto GDT_SORTKEY_OPAQUE_AMBIENT = "opaque ambient"; - constexpr auto GDT_SORTKEY_OPAQUE = "opaque"; - constexpr auto GDT_SORTKEY_SKY = "sky"; - constexpr auto GDT_SORTKEY_SKYBOX = "skybox"; - constexpr auto GDT_SORTKEY_DECAL_BOTTOM_1 = "decal - bottom 1"; - constexpr auto GDT_SORTKEY_DECAL_BOTTOM_2 = "decal - bottom 2"; - constexpr auto GDT_SORTKEY_DECAL_BOTTOM_3 = "decal - bottom 3"; - constexpr auto GDT_SORTKEY_DECAL_STATIC = "decal - static decal"; - constexpr auto GDT_SORTKEY_DECAL_MIDDLE_1 = "decal - middle 1"; - constexpr auto GDT_SORTKEY_DECAL_MIDDLE_2 = "decal - middle 2"; - constexpr auto GDT_SORTKEY_DECAL_MIDDLE_3 = "decal - middle 3"; - constexpr auto GDT_SORTKEY_DECAL_WEAPON_IMPACT = "decal - weapon impact"; - constexpr auto GDT_SORTKEY_WINDOW_INSIDE = "window inside"; - constexpr auto GDT_SORTKEY_WINDOW_OUTSIDE = "window outside"; - constexpr auto GDT_SORTKEY_DISTORTION = "distortion"; - constexpr auto GDT_SORTKEY_BLEND_ADDITIVE = "blend / additive"; - constexpr auto GDT_SORTKEY_EFFECT_AUTO_SORT = "effect - auto sort"; - constexpr auto GDT_SORTKEY_AFTER_EFFECT_BOTTOM = "after effects - bottom"; - constexpr auto GDT_SORTKEY_AFTER_EFFECT_MIDDLE = "after effects - middle"; - constexpr auto GDT_SORTKEY_AFTER_EFFECT_TOP = "after effects - top"; - constexpr auto GDT_SORTKEY_VIEWMODEL_EFFECT = "viewmodel effect"; - - inline const char* SortKeyNames[] - { - GDT_SORTKEY_OPAQUE_AMBIENT, // 0 - GDT_SORTKEY_OPAQUE, // 1 - GDT_SORTKEY_SKY, // 2 - GDT_SORTKEY_SKYBOX, // 3 - nullptr, // ? 4 - nullptr, // ? 5 - GDT_SORTKEY_DECAL_BOTTOM_1, // 6 - GDT_SORTKEY_DECAL_BOTTOM_2, // 7 - GDT_SORTKEY_DECAL_BOTTOM_3, // 8 - GDT_SORTKEY_DECAL_STATIC, // 9 - GDT_SORTKEY_DECAL_MIDDLE_1, // 10 - GDT_SORTKEY_DECAL_MIDDLE_2, // 11 - GDT_SORTKEY_DECAL_MIDDLE_3, // 12 - GDT_SORTKEY_DECAL_WEAPON_IMPACT, // 13 - nullptr, // ? 14 - nullptr, // ? 15 - nullptr, // ? 16 - nullptr, // ? 17 - nullptr, // ? 18 - nullptr, // ? 19 - nullptr, // ? 20 - nullptr, // ? 21 - nullptr, // - 22 - nullptr, // - 23 - GDT_SORTKEY_WINDOW_INSIDE, // 24 - GDT_SORTKEY_WINDOW_OUTSIDE, // 25 - nullptr, // ? 26 - nullptr, // ? 27 - nullptr, // ? 28 - nullptr, // ? 29 - nullptr, // ? 30 - nullptr, // ? 31 - nullptr, // ? 32 - nullptr, // ? 33 - nullptr, // ? 34 - nullptr, // ? 35 - nullptr, // ? 36 - nullptr, // ? 37 - nullptr, // ? 38 - nullptr, // ? 39 - nullptr, // ? 40 - nullptr, // ? 41 - nullptr, // ? 42 - GDT_SORTKEY_DISTORTION, // 43 - nullptr, // ? 44 - nullptr, // ? 45 - nullptr, // - 46 - GDT_SORTKEY_BLEND_ADDITIVE, // 47 - GDT_SORTKEY_EFFECT_AUTO_SORT, // 48 - GDT_SORTKEY_AFTER_EFFECT_BOTTOM, // 49 - GDT_SORTKEY_AFTER_EFFECT_MIDDLE, // 50 - GDT_SORTKEY_AFTER_EFFECT_TOP, // 51 - nullptr, // - 52 - GDT_SORTKEY_VIEWMODEL_EFFECT, // 53 - }; - static_assert(std::extent_v == static_cast(SORTKEY_MAX)); - - enum GdtCustomMaterialTypes - { - CUSTOM_MATERIAL_TYPE_NONE, - // Uses custom techset with generic options - CUSTOM_MATERIAL_TYPE_CUSTOM, - CUSTOM_MATERIAL_TYPE_PHONG_FLAG, - CUSTOM_MATERIAL_TYPE_GRAIN_OVERLAY, - CUSTOM_MATERIAL_TYPE_EFFECT_EYE_OFFSET, - CUSTOM_MATERIAL_TYPE_REFLEX_SIGHT, - CUSTOM_MATERIAL_TYPE_SHADOW_CLEAR, - CUSTOM_MATERIAL_TYPE_SHADOW_OVERLAY, - - // Not part of IW3 - CUSTOM_MATERIAL_TYPE_SPLATTER, - - CUSTOM_MATERIAL_TYPE_COUNT - }; - - constexpr auto GDT_CUSTOM_MATERIAL_TYPE_NONE = ""; - constexpr auto GDT_CUSTOM_MATERIAL_TYPE_CUSTOM = "mtl_custom"; - constexpr auto GDT_CUSTOM_MATERIAL_TYPE_PHONG_FLAG = "mtl_phong_flag"; - constexpr auto GDT_CUSTOM_MATERIAL_TYPE_GRAIN_OVERLAY = "mtl_grain_overlay"; - constexpr auto GDT_CUSTOM_MATERIAL_TYPE_EFFECT_EYE_OFFSET = "mtl_effect_eyeoffset"; - constexpr auto GDT_CUSTOM_MATERIAL_TYPE_REFLEXSIGHT = "mtl_reflexsight"; - constexpr auto GDT_CUSTOM_MATERIAL_TYPE_SHADOWCLEAR = "mtl_shadowclear"; - constexpr auto GDT_CUSTOM_MATERIAL_TYPE_SHADOWOVERLAY = "mtl_shadowoverlay"; - constexpr auto GDT_CUSTOM_MATERIAL_TYPE_SPLATTER = "mtl_splatter"; - - inline const char* GdtCustomMaterialTypeNames[] - { - GDT_CUSTOM_MATERIAL_TYPE_NONE, - GDT_CUSTOM_MATERIAL_TYPE_CUSTOM, - GDT_CUSTOM_MATERIAL_TYPE_PHONG_FLAG, - GDT_CUSTOM_MATERIAL_TYPE_GRAIN_OVERLAY, - GDT_CUSTOM_MATERIAL_TYPE_EFFECT_EYE_OFFSET, - GDT_CUSTOM_MATERIAL_TYPE_REFLEXSIGHT, - GDT_CUSTOM_MATERIAL_TYPE_SHADOWCLEAR, - GDT_CUSTOM_MATERIAL_TYPE_SHADOWOVERLAY, - GDT_CUSTOM_MATERIAL_TYPE_SPLATTER - }; - static_assert(std::extent_v == static_cast(CUSTOM_MATERIAL_TYPE_COUNT)); -} +namespace IW4 { +inline infoParm_t infoParms[]{ + {"bark", 0x0, 0x100000, 0x0, 0x0 }, + {"brick", 0x0, 0x200000, 0x0, 0x0 }, + {"carpet", 0x0, 0x300000, 0x0, 0x0 }, + {"cloth", 0x0, 0x400000, 0x0, 0x0 }, + {"concrete", 0x0, 0x500000, 0x0, 0x0 }, + {"dirt", 0x0, 0x600000, 0x0, 0x0 }, + {"flesh", 0x0, 0x700000, 0x0, 0x0 }, + {"foliage", 0x1, 0x800000, 0x2, 0x0 }, + {"glass", 0x1, 0x900000, 0x10, 0x0 }, + {"grass", 0x0, 0xa00000, 0x0, 0x0 }, + {"gravel", 0x0, 0xb00000, 0x0, 0x0 }, + {"ice", 0x0, 0xc00000, 0x0, 0x0 }, + {"metal", 0x0, 0xd00000, 0x0, 0x0 }, + {"mud", 0x0, 0xe00000, 0x0, 0x0 }, + {"paper", 0x0, 0xf00000, 0x0, 0x0 }, + {"plaster", 0x0, 0x1000000, 0x0, 0x0 }, + {"rock", 0x0, 0x1100000, 0x0, 0x0 }, + {"sand", 0x0, 0x1200000, 0x0, 0x0 }, + {"snow", 0x0, 0x1300000, 0x0, 0x0 }, + {"water", 0x1, 0x1400000, 0x20, 0x0 }, + {"wood", 0x0, 0x1500000, 0x0, 0x0 }, + {"asphalt", 0x0, 0x1600000, 0x0, 0x0 }, + {"ceramic", 0x0, 0x1700000, 0x0, 0x0 }, + {"plastic", 0x0, 0x1800000, 0x0, 0x0 }, + {"rubber", 0x0, 0x1900000, 0x0, 0x0 }, + {"cushion", 0x0, 0x1a00000, 0x0, 0x0 }, + {"fruit", 0x0, 0x1b00000, 0x0, 0x0 }, + {"paintedmetal", 0x0, 0x1c00000, 0x0, 0x0 }, + {"riotshield", 0x0, 0x1d00000, 0x0, 0x0 }, + {"slush", 0x0, 0x1e00000, 0x0, 0x0 }, + {"opaqueglass", 0x0, 0x900000, 0x0, 0x0 }, + {"clipmissile", 0x1, 0x0, 0x80, 0x0 }, + {"ai_nosight", 0x1, 0x0, 0x1000, 0x0 }, + {"clipshot", 0x1, 0x0, 0x2000, 0x0 }, + {"playerclip", 0x1, 0x0, 0x10000, 0x0 }, + {"monsterclip", 0x1, 0x0, 0x20000, 0x0 }, + {"aiclipallowdeath", 0x1, 0x0, 0x4, 0x0 }, + {"vehicleclip", 0x1, 0x0, 0x200, 0x0 }, + {"itemclip", 0x1, 0x0, 0x400, 0x0 }, + {"nodrop", 0x1, 0x0, 0x80000000, 0x0 }, + {"nonsolid", 0x1, 0x4000, 0x0, 0x0 }, + {"detail", 0x0, 0x0, 0x8000000, 0x0 }, + {"structural", 0x0, 0x0, 0x10000000, 0x0 }, + {"portal", 0x1, 0x80000000, 0x0, 0x0 }, + {"canshootclip", 0x0, 0x0, 0x40, 0x0 }, + {"origin", 0x1, 0x0, 0x0, 0x4 }, + {"sky", 0x0, 0x4, 0x800, 0x0 }, + {"nocastshadow", 0x0, 0x40000, 0x0, 0x0 }, + {"physicsGeom", 0x0, 0x0, 0x0, 0x400 }, + {"lightPortal", 0x0, 0x0, 0x0, 0x2000}, + {"outdoorBounds", 0x0, 0x0, 0x0, 0x8000}, + {"slick", 0x0, 0x2, 0x0, 0x0 }, + {"noimpact", 0x0, 0x10, 0x0, 0x0 }, + {"nomarks", 0x0, 0x20, 0x0, 0x0 }, + {"nopenetrate", 0x0, 0x100, 0x0, 0x0 }, + {"ladder", 0x0, 0x8, 0x0, 0x0 }, + {"nodamage", 0x0, 0x1, 0x0, 0x0 }, + {"mantleOn", 0x0, 0x2000000, 0x1000000, 0x0 }, + {"mantleOver", 0x0, 0x4000000, 0x1000000, 0x0 }, + {"stairs", 0x0, 0x200, 0x0, 0x0 }, + {"soft", 0x0, 0x1000, 0x0, 0x0 }, + {"nosteps", 0x0, 0x2000, 0x0, 0x0 }, + {"nodraw", 0x0, 0x80, 0x0, 0x0 }, + {"nolightmap", 0x0, 0x400, 0x0, 0x0 }, + {"nodlight", 0x0, 0x20000, 0x0, 0x0 } +}; + +inline const char *surfaceTypeNames[]{"default", "bark", "brick", "carpet", "cloth", "concrete", "dirt", "flesh", + "foliage", "glass", "grass", "gravel", "ice", "metal", "mud", "paper", + "plaster", "rock", "sand", "snow", "water", "wood", "asphalt", "ceramic", + "plastic", "rubber", "cushion", "fruit", "paintedmetal", "riotshield", "slush"}; +static_assert(std::extent_v == SURF_TYPE_NUM); + +enum class BlendFunc_e { + UNKNOWN, + CUSTOM, + REPLACE, + BLEND, + ADD, + MULTIPLY, + SCREEN_ADD, + + COUNT +}; + +constexpr auto GDT_BLEND_FUNC_UNKNOWN = ""; +constexpr auto GDT_BLEND_FUNC_CUSTOM = "Custom"; +constexpr auto GDT_BLEND_FUNC_REPLACE = "Replace*"; +constexpr auto GDT_BLEND_FUNC_BLEND = "Blend"; +constexpr auto GDT_BLEND_FUNC_ADD = "Add"; +constexpr auto GDT_BLEND_FUNC_MULTIPLY = "Multiply"; +constexpr auto GDT_BLEND_FUNC_SCREEN_ADD = "Screen Add"; + +inline const char *GdtBlendFuncNames[]{GDT_BLEND_FUNC_UNKNOWN, GDT_BLEND_FUNC_CUSTOM, GDT_BLEND_FUNC_REPLACE, GDT_BLEND_FUNC_BLEND, + GDT_BLEND_FUNC_ADD, GDT_BLEND_FUNC_MULTIPLY, GDT_BLEND_FUNC_SCREEN_ADD}; +static_assert(std::extent_v == static_cast(BlendFunc_e::COUNT)); + +enum class BlendOp_e { + UNKNOWN, + DISABLE, + ADD, + SUBTRACT, + REV_SUBTRACT, + MIN, + MAX, + + COUNT +}; + +constexpr auto GDT_BLEND_OP_UNKNOWN = ""; +constexpr auto GDT_BLEND_OP_DISABLE = "Disable"; +constexpr auto GDT_BLEND_OP_ADD = "Add*"; +constexpr auto GDT_BLEND_OP_SUBTRACT = "Subtract"; +constexpr auto GDT_BLEND_OP_REV_SUBTRACT = "RevSubtract"; +constexpr auto GDT_BLEND_OP_MIN = "Min"; +constexpr auto GDT_BLEND_OP_MAX = "Max"; + +inline const char *GdtBlendOpNames[]{GDT_BLEND_OP_UNKNOWN, GDT_BLEND_OP_DISABLE, GDT_BLEND_OP_ADD, GDT_BLEND_OP_SUBTRACT, + GDT_BLEND_OP_REV_SUBTRACT, GDT_BLEND_OP_MIN, GDT_BLEND_OP_MAX}; +static_assert(std::extent_v == static_cast(BlendOp_e::COUNT)); + +enum class CustomBlendFunc_e { + UNKNOWN, + DISABLED, + ZERO, + ONE, + SRC_COLOR, + INV_SRC_COLOR, + SRC_ALPHA, + INV_SRC_ALPHA, + DST_ALPHA, + INV_DST_ALPHA, + DEST_COLOR, + INV_DST_COLOR, + + COUNT +}; + +inline const char *GdtCustomBlendFuncNames[]{"", "Disable", "Zero", "One*", "SrcColor", "InvSrcColor", + "SrcAlpha", "InvSrcAlpha", "DestAlpha", "InvDestAlpha", "DestColor", "InvDestColor"}; +static_assert(std::extent_v == static_cast(CustomBlendFunc_e::COUNT)); + +enum class AlphaTest_e { + UNKNOWN, + ALWAYS, + GT0, + LT128, + GE128, + + COUNT +}; + +constexpr auto GDT_ALPHA_TEST_UNKNOWN = ""; +constexpr auto GDT_ALPHA_TEST_ALWAYS = "Always*"; +constexpr auto GDT_ALPHA_TEST_GT0 = "GT0"; +constexpr auto GDT_ALPHA_TEST_LT128 = "LT128"; +constexpr auto GDT_ALPHA_TEST_GE128 = "GE128"; + +inline const char *GdtAlphaTestNames[]{GDT_ALPHA_TEST_UNKNOWN, GDT_ALPHA_TEST_ALWAYS, GDT_ALPHA_TEST_GT0, GDT_ALPHA_TEST_LT128, GDT_ALPHA_TEST_GE128}; +static_assert(std::extent_v == static_cast(AlphaTest_e::COUNT)); + +enum class DepthTest_e { + UNKNOWN, + LESS_EQUAL, + LESS, + EQUAL, + ALWAYS, + DISABLE, + + COUNT +}; + +inline const char *GdtDepthTestNames[]{"", "LessEqual*", "Less", "Equal", "Always", "Disable"}; +static_assert(std::extent_v == static_cast(DepthTest_e::COUNT)); + +enum class StateBitsEnabledStatus_e { + UNKNOWN, + ENABLED, + DISABLED, + + COUNT +}; + +inline const char *GdtStateBitsEnabledStatusNames[]{"", "Enable", "Disable"}; +static_assert(std::extent_v == static_cast(StateBitsEnabledStatus_e::COUNT)); + +inline const char *GdtStateBitsOnOffStatusNames[]{"", "On", "Off"}; +static_assert(std::extent_v == static_cast(StateBitsEnabledStatus_e::COUNT)); + +enum class CullFace_e { + UNKNOWN, + NONE, + BACK, + FRONT, + + COUNT +}; + +inline const char *GdtCullFaceNames[]{"", "None", "Back*", "Front"}; +static_assert(std::extent_v == static_cast(CullFace_e::COUNT)); + +enum class PolygonOffset_e { + UNKNOWN, + OFFSET_0, + OFFSET_1, + OFFSET_2, + OFFSET_SHADOW_MAP, + + COUNT +}; + +inline const char *GdtPolygonOffsetNames[]{"", "0", "1", "2", "shadowMap"}; +static_assert(std::extent_v == static_cast(PolygonOffset_e::COUNT)); + +enum class StencilIndex { FRONT, BACK }; + +enum class StencilMode_e { + UNKNOWN, + DISABLED, + ONE_SIDED, + TWO_SIDED, + + COUNT +}; + +inline const char *GdtStencilModeNames[]{"", "Disable", "One-sided", "Two-sided"}; +static_assert(std::extent_v == static_cast(StencilMode_e::COUNT)); + +enum class StencilFunc_e { + UNKNOWN, + NEVER, + LESS, + EQUAL, + LESS_EQUAL, + GREATER, + NOT_EQUAL, + GREATER_EQUAL, + ALWAYS, + + COUNT +}; + +inline const char *GdtStencilFuncNames[]{"", "Never", "Less", "Equal", "LessEqual", "Greater", "NotEqual", "GreaterEqual", "Always"}; +static_assert(std::extent_v == static_cast(StencilFunc_e::COUNT)); + +enum class StencilOp_e { + UNKNOWN, + KEEP, + ZERO, + REPLACE, + INCR_SAT, + DECR_SAT, + INVERT, + INCR, + DECR, + + COUNT +}; + +inline const char *GdtStencilOpNames[]{"", "Keep", "Zero", "Replace", "IncrSat", "DecrSat", "Invert", "Incr", "Decr"}; +static_assert(std::extent_v == static_cast(StencilOp_e::COUNT)); + +enum class TileMode_e { + UNKNOWN, + TILE_BOTH, + TILE_HORIZONTAL, + TILE_VERTICAL, + NO_TILE, + + COUNT +}; + +inline const char *GdtTileModeNames[]{"", "tile both*", "tile horizontal", "tile vertical", "no tile"}; +static_assert(std::extent_v == static_cast(TileMode_e::COUNT)); + +enum class GdtFilter_e { + UNKNOWN, + MIP_2X_BILINEAR, + MIP_4X_BILINEAR, + MIP_2X_TRILINEAR, + MIP_4X_TRILINEAR, + NOMIP_NEAREST, + NOMIP_BILINEAR, + + COUNT +}; + +static const char *GdtSamplerFilterNames[]{"", + "mip standard (2x bilinear)*", + "mip expensive (4x bilinear)", + "mip more expensive (2x trilinear)", + "mip most expensive (4x trilinear)", + "nomip nearest", + "nomip bilinear"}; +static_assert(std::extent_v == static_cast(GdtFilter_e::COUNT)); + +enum GdtMaterialType { + MATERIAL_TYPE_UNKNOWN, + MATERIAL_TYPE_2D, + MATERIAL_TYPE_CUSTOM, + MATERIAL_TYPE_DISTORTION, + MATERIAL_TYPE_EFFECT, + MATERIAL_TYPE_IMPACT_MARK, + MATERIAL_TYPE_MODEL_AMBIENT, + MATERIAL_TYPE_MODEL_PHONG, + MATERIAL_TYPE_MODEL_UNLIT, + MATERIAL_TYPE_OBJECTIVE, + MATERIAL_TYPE_PARTICLE_CLOUD, + MATERIAL_TYPE_SKY, + MATERIAL_TYPE_TOOLS, + MATERIAL_TYPE_UNLIT, + MATERIAL_TYPE_WATER, + MATERIAL_TYPE_WORLD_PHONG, + MATERIAL_TYPE_WORLD_UNLIT, + + MATERIAL_TYPE_COUNT +}; + +constexpr auto GDT_MATERIAL_TYPE_UNKNOWN = ""; +constexpr auto GDT_MATERIAL_TYPE_2D = "2d"; +constexpr auto GDT_MATERIAL_TYPE_CUSTOM = "custom"; +constexpr auto GDT_MATERIAL_TYPE_DISTORTION = "distortion"; +constexpr auto GDT_MATERIAL_TYPE_EFFECT = "effect"; +constexpr auto GDT_MATERIAL_TYPE_IMPACT_MARK = "impact mark"; +constexpr auto GDT_MATERIAL_TYPE_MODEL_AMBIENT = "model ambient"; +constexpr auto GDT_MATERIAL_TYPE_MODEL_PHONG = "model phong"; +constexpr auto GDT_MATERIAL_TYPE_MODEL_UNLIT = "model unlit"; +constexpr auto GDT_MATERIAL_TYPE_OBJECTIVE = "objective"; +constexpr auto GDT_MATERIAL_TYPE_PARTICLE_CLOUD = "particle cloud"; +constexpr auto GDT_MATERIAL_TYPE_SKY = "sky"; +constexpr auto GDT_MATERIAL_TYPE_TOOLS = "tools"; +constexpr auto GDT_MATERIAL_TYPE_UNLIT = "unlit"; +constexpr auto GDT_MATERIAL_TYPE_WATER = "water"; +constexpr auto GDT_MATERIAL_TYPE_WORLD_PHONG = "world phong"; +constexpr auto GDT_MATERIAL_TYPE_WORLD_UNLIT = "world unlit"; + +inline const char *GdtMaterialTypeNames[]{ + GDT_MATERIAL_TYPE_UNKNOWN, GDT_MATERIAL_TYPE_2D, GDT_MATERIAL_TYPE_CUSTOM, GDT_MATERIAL_TYPE_DISTORTION, + GDT_MATERIAL_TYPE_EFFECT, GDT_MATERIAL_TYPE_IMPACT_MARK, GDT_MATERIAL_TYPE_MODEL_AMBIENT, GDT_MATERIAL_TYPE_MODEL_PHONG, + GDT_MATERIAL_TYPE_MODEL_UNLIT, GDT_MATERIAL_TYPE_OBJECTIVE, GDT_MATERIAL_TYPE_PARTICLE_CLOUD, GDT_MATERIAL_TYPE_SKY, + GDT_MATERIAL_TYPE_TOOLS, GDT_MATERIAL_TYPE_UNLIT, GDT_MATERIAL_TYPE_WATER, GDT_MATERIAL_TYPE_WORLD_PHONG, + GDT_MATERIAL_TYPE_WORLD_UNLIT}; +static_assert(std::extent_v == static_cast(MATERIAL_TYPE_COUNT)); + +constexpr auto GDT_SORTKEY_DEFAULT = ""; +constexpr auto GDT_SORTKEY_OPAQUE_AMBIENT = "opaque ambient"; +constexpr auto GDT_SORTKEY_OPAQUE = "opaque"; +constexpr auto GDT_SORTKEY_SKY = "sky"; +constexpr auto GDT_SORTKEY_SKYBOX = "skybox"; +constexpr auto GDT_SORTKEY_DECAL_BOTTOM_1 = "decal - bottom 1"; +constexpr auto GDT_SORTKEY_DECAL_BOTTOM_2 = "decal - bottom 2"; +constexpr auto GDT_SORTKEY_DECAL_BOTTOM_3 = "decal - bottom 3"; +constexpr auto GDT_SORTKEY_DECAL_STATIC = "decal - static decal"; +constexpr auto GDT_SORTKEY_DECAL_MIDDLE_1 = "decal - middle 1"; +constexpr auto GDT_SORTKEY_DECAL_MIDDLE_2 = "decal - middle 2"; +constexpr auto GDT_SORTKEY_DECAL_MIDDLE_3 = "decal - middle 3"; +constexpr auto GDT_SORTKEY_DECAL_WEAPON_IMPACT = "decal - weapon impact"; +constexpr auto GDT_SORTKEY_WINDOW_INSIDE = "window inside"; +constexpr auto GDT_SORTKEY_WINDOW_OUTSIDE = "window outside"; +constexpr auto GDT_SORTKEY_DISTORTION = "distortion"; +constexpr auto GDT_SORTKEY_BLEND_ADDITIVE = "blend / additive"; +constexpr auto GDT_SORTKEY_EFFECT_AUTO_SORT = "effect - auto sort"; +constexpr auto GDT_SORTKEY_AFTER_EFFECT_BOTTOM = "after effects - bottom"; +constexpr auto GDT_SORTKEY_AFTER_EFFECT_MIDDLE = "after effects - middle"; +constexpr auto GDT_SORTKEY_AFTER_EFFECT_TOP = "after effects - top"; +constexpr auto GDT_SORTKEY_VIEWMODEL_EFFECT = "viewmodel effect"; + +inline const char *SortKeyNames[]{ + GDT_SORTKEY_OPAQUE_AMBIENT, // 0 + GDT_SORTKEY_OPAQUE, // 1 + GDT_SORTKEY_SKY, // 2 + GDT_SORTKEY_SKYBOX, // 3 + nullptr, // ? 4 + nullptr, // ? 5 + GDT_SORTKEY_DECAL_BOTTOM_1, // 6 + GDT_SORTKEY_DECAL_BOTTOM_2, // 7 + GDT_SORTKEY_DECAL_BOTTOM_3, // 8 + GDT_SORTKEY_DECAL_STATIC, // 9 + GDT_SORTKEY_DECAL_MIDDLE_1, // 10 + GDT_SORTKEY_DECAL_MIDDLE_2, // 11 + GDT_SORTKEY_DECAL_MIDDLE_3, // 12 + GDT_SORTKEY_DECAL_WEAPON_IMPACT, // 13 + nullptr, // ? 14 + nullptr, // ? 15 + nullptr, // ? 16 + nullptr, // ? 17 + nullptr, // ? 18 + nullptr, // ? 19 + nullptr, // ? 20 + nullptr, // ? 21 + nullptr, // - 22 + nullptr, // - 23 + GDT_SORTKEY_WINDOW_INSIDE, // 24 + GDT_SORTKEY_WINDOW_OUTSIDE, // 25 + nullptr, // ? 26 + nullptr, // ? 27 + nullptr, // ? 28 + nullptr, // ? 29 + nullptr, // ? 30 + nullptr, // ? 31 + nullptr, // ? 32 + nullptr, // ? 33 + nullptr, // ? 34 + nullptr, // ? 35 + nullptr, // ? 36 + nullptr, // ? 37 + nullptr, // ? 38 + nullptr, // ? 39 + nullptr, // ? 40 + nullptr, // ? 41 + nullptr, // ? 42 + GDT_SORTKEY_DISTORTION, // 43 + nullptr, // ? 44 + nullptr, // ? 45 + nullptr, // - 46 + GDT_SORTKEY_BLEND_ADDITIVE, // 47 + GDT_SORTKEY_EFFECT_AUTO_SORT, // 48 + GDT_SORTKEY_AFTER_EFFECT_BOTTOM, // 49 + GDT_SORTKEY_AFTER_EFFECT_MIDDLE, // 50 + GDT_SORTKEY_AFTER_EFFECT_TOP, // 51 + nullptr, // - 52 + GDT_SORTKEY_VIEWMODEL_EFFECT, // 53 +}; +static_assert(std::extent_v == static_cast(SORTKEY_MAX)); + +enum GdtCustomMaterialTypes { + CUSTOM_MATERIAL_TYPE_NONE, + // Uses custom techset with generic options + CUSTOM_MATERIAL_TYPE_CUSTOM, + CUSTOM_MATERIAL_TYPE_PHONG_FLAG, + CUSTOM_MATERIAL_TYPE_GRAIN_OVERLAY, + CUSTOM_MATERIAL_TYPE_EFFECT_EYE_OFFSET, + CUSTOM_MATERIAL_TYPE_REFLEX_SIGHT, + CUSTOM_MATERIAL_TYPE_SHADOW_CLEAR, + CUSTOM_MATERIAL_TYPE_SHADOW_OVERLAY, + + // Not part of IW3 + CUSTOM_MATERIAL_TYPE_SPLATTER, + + CUSTOM_MATERIAL_TYPE_COUNT +}; + +constexpr auto GDT_CUSTOM_MATERIAL_TYPE_NONE = ""; +constexpr auto GDT_CUSTOM_MATERIAL_TYPE_CUSTOM = "mtl_custom"; +constexpr auto GDT_CUSTOM_MATERIAL_TYPE_PHONG_FLAG = "mtl_phong_flag"; +constexpr auto GDT_CUSTOM_MATERIAL_TYPE_GRAIN_OVERLAY = "mtl_grain_overlay"; +constexpr auto GDT_CUSTOM_MATERIAL_TYPE_EFFECT_EYE_OFFSET = "mtl_effect_eyeoffset"; +constexpr auto GDT_CUSTOM_MATERIAL_TYPE_REFLEXSIGHT = "mtl_reflexsight"; +constexpr auto GDT_CUSTOM_MATERIAL_TYPE_SHADOWCLEAR = "mtl_shadowclear"; +constexpr auto GDT_CUSTOM_MATERIAL_TYPE_SHADOWOVERLAY = "mtl_shadowoverlay"; +constexpr auto GDT_CUSTOM_MATERIAL_TYPE_SPLATTER = "mtl_splatter"; + +inline const char *GdtCustomMaterialTypeNames[]{GDT_CUSTOM_MATERIAL_TYPE_NONE, + GDT_CUSTOM_MATERIAL_TYPE_CUSTOM, + GDT_CUSTOM_MATERIAL_TYPE_PHONG_FLAG, + GDT_CUSTOM_MATERIAL_TYPE_GRAIN_OVERLAY, + GDT_CUSTOM_MATERIAL_TYPE_EFFECT_EYE_OFFSET, + GDT_CUSTOM_MATERIAL_TYPE_REFLEXSIGHT, + GDT_CUSTOM_MATERIAL_TYPE_SHADOWCLEAR, + GDT_CUSTOM_MATERIAL_TYPE_SHADOWOVERLAY, + GDT_CUSTOM_MATERIAL_TYPE_SPLATTER}; +static_assert(std::extent_v == static_cast(CUSTOM_MATERIAL_TYPE_COUNT)); +} // namespace IW4 diff --git a/src/ObjCommon/Game/IW4/MenuConstantsIW4.h b/src/ObjCommon/Game/IW4/MenuConstantsIW4.h index 744fbf08a..a0eaeed83 100644 --- a/src/ObjCommon/Game/IW4/MenuConstantsIW4.h +++ b/src/ObjCommon/Game/IW4/MenuConstantsIW4.h @@ -2,218 +2,215 @@ #include "Game/IW4/IW4.h" -namespace IW4 -{ - inline const char* g_expFunctionNames[] - { - "NOOP", - ")", - "*", - "/", - "%", - "+", - "-", - "!", - "<", - "<=", - ">", - ">=", - "==", - "!=", - "&&", - "||", - "(", - ",", - "&", - "|", - "~", - "<<", - ">>", - "dvarint(static)\x01\x02", - "dvarbool(static)\x01\x03", - "dvarfloat(static)\x01\x04", - "dvarstring(static)\x01\x05", - "int", - "string", - "float", - "sin", - "cos", - "min", - "max", - "milliseconds", - "dvarint", - "dvarbool", - "dvarfloat", - "dvarstring", - "stat", - "ui_active", - "flashbanged", - "usingvehicle", - "missilecam", - "scoped", - "scopedthermal", - "scoreboard_visible", - "inkillcam", - "inkillcamnpc", - "player", - "getperk", - "selecting_location", - "selecting_direction", - "team", - "otherteam", - "marinesfield", - "opforfield", - "menuisopen", - "writingdata", - "inlobby", - "inprivateparty", - "privatepartyhost", - "privatepartyhostinlobby", - "aloneinparty", - "adsjavelin", - "weaplockblink", - "weapattacktop", - "weapattackdirect", - "weaplocking", - "weaplocked", - "weaplocktooclose", - "weaplockscreenposx", - "weaplockscreenposy", - "secondsastime", - "tablelookup", - "tablelookupbyrow", - "tablegetrownum", - "locstring", - "localvarint", - "localvarbool", - "localvarfloat", - "localvarstring", - "timeleft", - "secondsascountdown", - "gamemsgwndactive", - "gametypename", - "gametype", - "gametypedescription", - "scoreatrank", - "friendsonline", - "spectatingclient", - "spectatingfree", - "statrangeanybitsset", - "keybinding", - "actionslotusable", - "hudfade", - "maxrecommendedplayers", - "acceptinginvite", - "isintermission", - "gamehost", - "partyismissingmappack", - "partymissingmappackerror", - "anynewmappacks", - "amiselected", - "partystatusstring", - "attachedcontrollercount", - "issplitscreenonlinepossible", - "splitscreenplayercount", - "getplayerdata", - "getplayerdatasplitscreen", - "experienceforlevel", - "levelforexperience", - "isitemunlocked", - "isitemunlockedsplitscreen", - "debugprint", - "getplayerdataanybooltrue", - "weaponclassnew", - "weaponname", - "isreloading", - "savegameavailable", - "unlockeditemcount", - "unlockeditemcountsplitscreen", - "unlockeditem", - "unlockeditemsplitscreen", - "mailsubject", - "mailfrom", - "mailreceived", - "mailbody", - "maillootlocalized", - "mailgivesloot", - "anynewmail", - "mailtimetofollowup", - "mailloottype", - "mailranlottery", - "lotterylootlocalized", - "radarisjammed", - "radarjamintensity", - "radarisenabled", - "isempjammed", - "playerads", - "weaponheatactive", - "weaponheatvalue", - "weaponheatoverheated", - "getsplashtext", - "getsplashdescription", - "getsplashmaterial", - "splashhasicon", - "splashrownum", - "getfocuseditemname", - "getfocuseditemx", - "getfocuseditemy", - "getfocuseditemwidth", - "getfocuseditemheight", - "getitemx", - "getitemy", - "getitemwidth", - "getitemheight", - "playlist", - "scoreboardexternalmutenotice", - "getclientmatchdata", - "getclientmatchdatadef", - "getmapname", - "getmapimage", - "getmapcustom", - "getmigrationstatus", - "getplayercardinfo", - "isofflineprofileselected", - "coopplayer", - "iscoop", - "getpartystatus", - "getsearchparams", - "gettimeplayed", - "isselectedplayerfriend", - "getcharbyindex", - "getprofiledata", - "isprofilesignedin", - "getwaitpopupstatus", - "getnattype", - "getlocalizednattype", - "getadjustedsafeareahorizontal", - "getadjustedsafeareavertical", - "connectioninfo", - "offlineprofilecansave", - "allsplitscreenprofilescansave", - "allsplitscreenprofilesaresignedin", - "coopready", - }; +namespace IW4 { +inline const char *g_expFunctionNames[]{ + "NOOP", + ")", + "*", + "/", + "%", + "+", + "-", + "!", + "<", + "<=", + ">", + ">=", + "==", + "!=", + "&&", + "||", + "(", + ",", + "&", + "|", + "~", + "<<", + ">>", + "dvarint(static)\x01\x02", + "dvarbool(static)\x01\x03", + "dvarfloat(static)\x01\x04", + "dvarstring(static)\x01\x05", + "int", + "string", + "float", + "sin", + "cos", + "min", + "max", + "milliseconds", + "dvarint", + "dvarbool", + "dvarfloat", + "dvarstring", + "stat", + "ui_active", + "flashbanged", + "usingvehicle", + "missilecam", + "scoped", + "scopedthermal", + "scoreboard_visible", + "inkillcam", + "inkillcamnpc", + "player", + "getperk", + "selecting_location", + "selecting_direction", + "team", + "otherteam", + "marinesfield", + "opforfield", + "menuisopen", + "writingdata", + "inlobby", + "inprivateparty", + "privatepartyhost", + "privatepartyhostinlobby", + "aloneinparty", + "adsjavelin", + "weaplockblink", + "weapattacktop", + "weapattackdirect", + "weaplocking", + "weaplocked", + "weaplocktooclose", + "weaplockscreenposx", + "weaplockscreenposy", + "secondsastime", + "tablelookup", + "tablelookupbyrow", + "tablegetrownum", + "locstring", + "localvarint", + "localvarbool", + "localvarfloat", + "localvarstring", + "timeleft", + "secondsascountdown", + "gamemsgwndactive", + "gametypename", + "gametype", + "gametypedescription", + "scoreatrank", + "friendsonline", + "spectatingclient", + "spectatingfree", + "statrangeanybitsset", + "keybinding", + "actionslotusable", + "hudfade", + "maxrecommendedplayers", + "acceptinginvite", + "isintermission", + "gamehost", + "partyismissingmappack", + "partymissingmappackerror", + "anynewmappacks", + "amiselected", + "partystatusstring", + "attachedcontrollercount", + "issplitscreenonlinepossible", + "splitscreenplayercount", + "getplayerdata", + "getplayerdatasplitscreen", + "experienceforlevel", + "levelforexperience", + "isitemunlocked", + "isitemunlockedsplitscreen", + "debugprint", + "getplayerdataanybooltrue", + "weaponclassnew", + "weaponname", + "isreloading", + "savegameavailable", + "unlockeditemcount", + "unlockeditemcountsplitscreen", + "unlockeditem", + "unlockeditemsplitscreen", + "mailsubject", + "mailfrom", + "mailreceived", + "mailbody", + "maillootlocalized", + "mailgivesloot", + "anynewmail", + "mailtimetofollowup", + "mailloottype", + "mailranlottery", + "lotterylootlocalized", + "radarisjammed", + "radarjamintensity", + "radarisenabled", + "isempjammed", + "playerads", + "weaponheatactive", + "weaponheatvalue", + "weaponheatoverheated", + "getsplashtext", + "getsplashdescription", + "getsplashmaterial", + "splashhasicon", + "splashrownum", + "getfocuseditemname", + "getfocuseditemx", + "getfocuseditemy", + "getfocuseditemwidth", + "getfocuseditemheight", + "getitemx", + "getitemy", + "getitemwidth", + "getitemheight", + "playlist", + "scoreboardexternalmutenotice", + "getclientmatchdata", + "getclientmatchdatadef", + "getmapname", + "getmapimage", + "getmapcustom", + "getmigrationstatus", + "getplayercardinfo", + "isofflineprofileselected", + "coopplayer", + "iscoop", + "getpartystatus", + "getsearchparams", + "gettimeplayed", + "isselectedplayerfriend", + "getcharbyindex", + "getprofiledata", + "isprofilesignedin", + "getwaitpopupstatus", + "getnattype", + "getlocalizednattype", + "getadjustedsafeareahorizontal", + "getadjustedsafeareavertical", + "connectioninfo", + "offlineprofilecansave", + "allsplitscreenprofilescansave", + "allsplitscreenprofilesaresignedin", + "coopready", +}; - inline const ItemExpressionTargetBinding floatExpressionTargetBindings[ITEM_FLOATEXP_TGT_COUNT] - { - {ITEM_FLOATEXP_TGT_RECT_X, "rect", "x"}, - {ITEM_FLOATEXP_TGT_RECT_Y, "rect", "y"}, - {ITEM_FLOATEXP_TGT_RECT_W, "rect", "w"}, - {ITEM_FLOATEXP_TGT_RECT_H, "rect", "h"}, - {ITEM_FLOATEXP_TGT_FORECOLOR_R, "forecolor", "r"}, - {ITEM_FLOATEXP_TGT_FORECOLOR_G, "forecolor", "g"}, - {ITEM_FLOATEXP_TGT_FORECOLOR_B, "forecolor", "b"}, - {ITEM_FLOATEXP_TGT_FORECOLOR_RGB, "forecolor", "rgb"}, - {ITEM_FLOATEXP_TGT_FORECOLOR_A, "forecolor", "a"}, - {ITEM_FLOATEXP_TGT_GLOWCOLOR_R, "glowcolor", "r"}, - {ITEM_FLOATEXP_TGT_GLOWCOLOR_G, "glowcolor", "g"}, - {ITEM_FLOATEXP_TGT_GLOWCOLOR_B, "glowcolor", "b"}, - {ITEM_FLOATEXP_TGT_GLOWCOLOR_RGB, "glowcolor", "rgb"}, - {ITEM_FLOATEXP_TGT_GLOWCOLOR_A, "glowcolor", "a"}, - {ITEM_FLOATEXP_TGT_BACKCOLOR_R, "backcolor", "r"}, - {ITEM_FLOATEXP_TGT_BACKCOLOR_G, "backcolor", "g"}, - {ITEM_FLOATEXP_TGT_BACKCOLOR_B, "backcolor", "b"}, - {ITEM_FLOATEXP_TGT_BACKCOLOR_RGB, "backcolor", "rgb"}, - {ITEM_FLOATEXP_TGT_BACKCOLOR_A, "backcolor", "a"}, - }; -} \ No newline at end of file +inline const ItemExpressionTargetBinding floatExpressionTargetBindings[ITEM_FLOATEXP_TGT_COUNT]{ + {ITEM_FLOATEXP_TGT_RECT_X, "rect", "x" }, + {ITEM_FLOATEXP_TGT_RECT_Y, "rect", "y" }, + {ITEM_FLOATEXP_TGT_RECT_W, "rect", "w" }, + {ITEM_FLOATEXP_TGT_RECT_H, "rect", "h" }, + {ITEM_FLOATEXP_TGT_FORECOLOR_R, "forecolor", "r" }, + {ITEM_FLOATEXP_TGT_FORECOLOR_G, "forecolor", "g" }, + {ITEM_FLOATEXP_TGT_FORECOLOR_B, "forecolor", "b" }, + {ITEM_FLOATEXP_TGT_FORECOLOR_RGB, "forecolor", "rgb"}, + {ITEM_FLOATEXP_TGT_FORECOLOR_A, "forecolor", "a" }, + {ITEM_FLOATEXP_TGT_GLOWCOLOR_R, "glowcolor", "r" }, + {ITEM_FLOATEXP_TGT_GLOWCOLOR_G, "glowcolor", "g" }, + {ITEM_FLOATEXP_TGT_GLOWCOLOR_B, "glowcolor", "b" }, + {ITEM_FLOATEXP_TGT_GLOWCOLOR_RGB, "glowcolor", "rgb"}, + {ITEM_FLOATEXP_TGT_GLOWCOLOR_A, "glowcolor", "a" }, + {ITEM_FLOATEXP_TGT_BACKCOLOR_R, "backcolor", "r" }, + {ITEM_FLOATEXP_TGT_BACKCOLOR_G, "backcolor", "g" }, + {ITEM_FLOATEXP_TGT_BACKCOLOR_B, "backcolor", "b" }, + {ITEM_FLOATEXP_TGT_BACKCOLOR_RGB, "backcolor", "rgb"}, + {ITEM_FLOATEXP_TGT_BACKCOLOR_A, "backcolor", "a" }, +}; +} // namespace IW4 \ No newline at end of file diff --git a/src/ObjCommon/Game/IW4/ObjConstantsIW4.h b/src/ObjCommon/Game/IW4/ObjConstantsIW4.h index 3f43d9d09..dbeaa8d0a 100644 --- a/src/ObjCommon/Game/IW4/ObjConstantsIW4.h +++ b/src/ObjCommon/Game/IW4/ObjConstantsIW4.h @@ -1,21 +1,19 @@ #pragma once -namespace IW4 -{ - class ObjConstants - { - ObjConstants() = default; +namespace IW4 { +class ObjConstants { + ObjConstants() = default; - public: - static constexpr const char* INFO_STRING_PREFIX_PHYS_PRESET = "PHYSIC"; - static constexpr const char* INFO_STRING_PREFIX_TRACER = "TRACER"; - static constexpr const char* INFO_STRING_PREFIX_VEHICLE = "VEHICLEFILE"; - static constexpr const char* INFO_STRING_PREFIX_WEAPON = "WEAPONFILE"; +public: + static constexpr const char *INFO_STRING_PREFIX_PHYS_PRESET = "PHYSIC"; + static constexpr const char *INFO_STRING_PREFIX_TRACER = "TRACER"; + static constexpr const char *INFO_STRING_PREFIX_VEHICLE = "VEHICLEFILE"; + static constexpr const char *INFO_STRING_PREFIX_WEAPON = "WEAPONFILE"; - static constexpr const char* GDF_FILENAME_MATERIAL = "material.gdf"; - static constexpr const char* GDF_FILENAME_PHYS_PRESET = "physpreset.gdf"; - static constexpr const char* GDF_FILENAME_TRACER = "tracer.gdf"; - static constexpr const char* GDF_FILENAME_VEHICLE = "vehicle.gdf"; - static constexpr const char* GDF_FILENAME_WEAPON = "weapon.gdf"; - }; -} \ No newline at end of file + static constexpr const char *GDF_FILENAME_MATERIAL = "material.gdf"; + static constexpr const char *GDF_FILENAME_PHYS_PRESET = "physpreset.gdf"; + static constexpr const char *GDF_FILENAME_TRACER = "tracer.gdf"; + static constexpr const char *GDF_FILENAME_VEHICLE = "vehicle.gdf"; + static constexpr const char *GDF_FILENAME_WEAPON = "weapon.gdf"; +}; +} // namespace IW4 \ No newline at end of file diff --git a/src/ObjCommon/Game/IW4/TechsetConstantsIW4.h b/src/ObjCommon/Game/IW4/TechsetConstantsIW4.h index fa40a1cf6..0854c082b 100644 --- a/src/ObjCommon/Game/IW4/TechsetConstantsIW4.h +++ b/src/ObjCommon/Game/IW4/TechsetConstantsIW4.h @@ -1,897 +1,767 @@ #pragma once -#include #include +#include #include "Game/IW4/CommonIW4.h" #include "Game/IW4/IW4.h" #include "StateMap/StateMapLayout.h" -namespace IW4 -{ - inline const char* techniqueTypeNames[] - { - "depth prepass", - "build floatz", - "build shadowmap depth", - "build shadowmap color", - "unlit", - "emissive", - "emissive dfog", - "emissive shadow", - "emissive shadow dfog", - "lit", - "lit dfog", - "lit sun", - "lit sun dfog", - "lit sun shadow", - "lit sun shadow dfog", - "lit spot", - "lit spot dfog", - "lit spot shadow", - "lit spot shadow dfog", - "lit omni", - "lit omni dfog", - "lit omni shadow", - "lit omni shadow dfog", - "lit instanced", - "lit instanced dfog", - "lit instanced sun", - "lit instanced sun dfog", - "lit instanced sun shadow", - "lit instanced sun shadow dfog", - "lit instanced spot", - "lit instanced spot dfog", - "lit instanced spot shadow", - "lit instanced spot shadow dfog", - "lit instanced omni", - "lit instanced omni dfog", - "lit instanced omni shadow", - "lit instanced omni shadow dfog", - "light spot", - "light omni", - "light spot shadow", - "fakelight normal", - "fakelight view", - "sunlight preview", - "case texture", - "solid wireframe", - "shaded wireframe", - "debug bumpmap", - "debug bumpmap instanced", - }; - static_assert(std::extent_v == TECHNIQUE_COUNT); - - static const char* materialStreamDestinationNames[] - { - "position", - "normal", - "color[0]", - "color[1]", - "depth", - "texcoord[0]", - "texcoord[1]", - "texcoord[2]", - "texcoord[3]", - "texcoord[4]", - "texcoord[5]", - "texcoord[6]", - "texcoord[7]", - }; - static_assert(std::extent_v == STREAM_DST_COUNT); - static const char* materialStreamDestinationAbbreviation[] - { - "p", - "n", - "c0", - "c1", - "d", - "t0", - "t1", - "t2", - "t3", - "t4", - "t5", - "t6", - "t7", - }; - static_assert(std::extent_v == STREAM_DST_COUNT); +namespace IW4 { +inline const char *techniqueTypeNames[]{ + "depth prepass", + "build floatz", + "build shadowmap depth", + "build shadowmap color", + "unlit", + "emissive", + "emissive dfog", + "emissive shadow", + "emissive shadow dfog", + "lit", + "lit dfog", + "lit sun", + "lit sun dfog", + "lit sun shadow", + "lit sun shadow dfog", + "lit spot", + "lit spot dfog", + "lit spot shadow", + "lit spot shadow dfog", + "lit omni", + "lit omni dfog", + "lit omni shadow", + "lit omni shadow dfog", + "lit instanced", + "lit instanced dfog", + "lit instanced sun", + "lit instanced sun dfog", + "lit instanced sun shadow", + "lit instanced sun shadow dfog", + "lit instanced spot", + "lit instanced spot dfog", + "lit instanced spot shadow", + "lit instanced spot shadow dfog", + "lit instanced omni", + "lit instanced omni dfog", + "lit instanced omni shadow", + "lit instanced omni shadow dfog", + "light spot", + "light omni", + "light spot shadow", + "fakelight normal", + "fakelight view", + "sunlight preview", + "case texture", + "solid wireframe", + "shaded wireframe", + "debug bumpmap", + "debug bumpmap instanced", +}; +static_assert(std::extent_v == TECHNIQUE_COUNT); - static const char* materialStreamSourceNames[] - { - "position", - "color", - "texcoord[0]", - "normal", - "tangent", - "texcoord[1]", - "texcoord[2]", - "normalTransform[0]", - "normalTransform[1]" - }; - static_assert(std::extent_v == STREAM_SRC_COUNT); - static const char* materialStreamSourceAbbreviation[] - { - "p", - "c", - "t0", - "n", - "t", - "t1", - "t2", - "n0", - "n1" - }; - static_assert(std::extent_v == STREAM_SRC_COUNT); +static const char *materialStreamDestinationNames[]{ + "position", "normal", "color[0]", "color[1]", "depth", "texcoord[0]", "texcoord[1]", + "texcoord[2]", "texcoord[3]", "texcoord[4]", "texcoord[5]", "texcoord[6]", "texcoord[7]", +}; +static_assert(std::extent_v == STREAM_DST_COUNT); +static const char *materialStreamDestinationAbbreviation[]{ + "p", "n", "c0", "c1", "d", "t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7", +}; +static_assert(std::extent_v == STREAM_DST_COUNT); - inline CodeSamplerSource s_lightmapSamplers[] - { - {"primary", TEXTURE_SRC_CODE_LIGHTMAP_PRIMARY, nullptr, 0, 0}, - {"secondary", TEXTURE_SRC_CODE_LIGHTMAP_SECONDARY, nullptr, 0, 0}, - {} - }; +static const char *materialStreamSourceNames[]{ + "position", "color", "texcoord[0]", "normal", "tangent", "texcoord[1]", "texcoord[2]", "normalTransform[0]", "normalTransform[1]"}; +static_assert(std::extent_v == STREAM_SRC_COUNT); +static const char *materialStreamSourceAbbreviation[]{"p", "c", "t0", "n", "t", "t1", "t2", "n0", "n1"}; +static_assert(std::extent_v == STREAM_SRC_COUNT); - inline CodeSamplerSource s_lightSamplers[] - { - {"attenuation", TEXTURE_SRC_CODE_LIGHT_ATTENUATION, nullptr, 0, 0}, - {} - }; +inline CodeSamplerSource s_lightmapSamplers[]{ + {"primary", TEXTURE_SRC_CODE_LIGHTMAP_PRIMARY, nullptr, 0, 0}, + {"secondary", TEXTURE_SRC_CODE_LIGHTMAP_SECONDARY, nullptr, 0, 0}, + {} +}; - inline CodeSamplerSource s_codeSamplers[] - { - {"white", TEXTURE_SRC_CODE_WHITE, nullptr, 0, 0}, - {"black", TEXTURE_SRC_CODE_BLACK, nullptr, 0, 0}, - {"identityNormalMap", TEXTURE_SRC_CODE_IDENTITY_NORMAL_MAP, nullptr, 0, 0}, - {"lightmap", TEXTURE_SRC_CODE_LIGHTMAP_PRIMARY, s_lightmapSamplers, 0, 0}, - {"outdoor", TEXTURE_SRC_CODE_OUTDOOR, nullptr, 0, 0}, - {"shadowmapSun", TEXTURE_SRC_CODE_SHADOWMAP_SUN, nullptr, 0, 0}, - {"shadowmapSpot", TEXTURE_SRC_CODE_SHADOWMAP_SPOT, nullptr, 0, 0}, - {"feedback", TEXTURE_SRC_CODE_FEEDBACK, nullptr, 0, 0}, - {"resolvedPostSun", TEXTURE_SRC_CODE_RESOLVED_POST_SUN, nullptr, 0, 0}, - {"resolvedScene", TEXTURE_SRC_CODE_RESOLVED_SCENE, nullptr, 0, 0}, - {"postEffect0", TEXTURE_SRC_CODE_POST_EFFECT_0, nullptr, 0, 0}, - {"postEffect1", TEXTURE_SRC_CODE_POST_EFFECT_1, nullptr, 0, 0}, - {"light", TEXTURE_SRC_CODE_LIGHT_ATTENUATION, s_lightSamplers, 0, 0}, - {"floatZ", TEXTURE_SRC_CODE_FLOATZ, nullptr, 0, 0}, - {"processedFloatZ", TEXTURE_SRC_CODE_PROCESSED_FLOATZ, nullptr, 0, 0}, - {"rawFloatZ", TEXTURE_SRC_CODE_RAW_FLOATZ, nullptr, 0, 0}, - {"halfParticleColorSampler", TEXTURE_SRC_CODE_HALF_PARTICLES, nullptr, 0, 0}, - {"halfParticleDepthSampler", TEXTURE_SRC_CODE_HALF_PARTICLES_Z, nullptr, 0, 0}, - {"alternateScene", TEXTURE_SRC_CODE_ALTERNATE_SCENE, nullptr, 0, 0}, - {} - }; +inline CodeSamplerSource s_lightSamplers[]{ + {"attenuation", TEXTURE_SRC_CODE_LIGHT_ATTENUATION, nullptr, 0, 0}, + {} +}; - inline CodeSamplerSource s_defaultCodeSamplers[] - { - {"shadowmapSamplerSun", TEXTURE_SRC_CODE_SHADOWMAP_SUN, nullptr, 0, 0}, - {"shadowmapSamplerSpot", TEXTURE_SRC_CODE_SHADOWMAP_SPOT, nullptr, 0, 0}, - {"feedbackSampler", TEXTURE_SRC_CODE_FEEDBACK, nullptr, 0, 0}, - {"floatZSampler", TEXTURE_SRC_CODE_FLOATZ, nullptr, 0, 0}, - {"processedFloatZSampler", TEXTURE_SRC_CODE_PROCESSED_FLOATZ, nullptr, 0, 0}, - {"rawFloatZSampler", TEXTURE_SRC_CODE_RAW_FLOATZ, nullptr, 0, 0}, - {"halfParticleColorSampler", TEXTURE_SRC_CODE_HALF_PARTICLES, nullptr, 0, 0}, - {"halfParticleDepthSampler", TEXTURE_SRC_CODE_HALF_PARTICLES_Z, nullptr, 0, 0}, - {"attenuationSampler", TEXTURE_SRC_CODE_LIGHT_ATTENUATION, nullptr, 0, 0}, - {"lightmapSamplerPrimary", TEXTURE_SRC_CODE_LIGHTMAP_PRIMARY, nullptr, 0, 0}, - {"lightmapSamplerSecondary", TEXTURE_SRC_CODE_LIGHTMAP_SECONDARY, nullptr, 0, 0}, - {"modelLightingSampler", TEXTURE_SRC_CODE_MODEL_LIGHTING, nullptr, 0, 0}, - {"cinematicYSampler", TEXTURE_SRC_CODE_CINEMATIC_Y, nullptr, 0, 0}, - {"cinematicCrSampler", TEXTURE_SRC_CODE_CINEMATIC_CR, nullptr, 0, 0}, - {"cinematicCbSampler", TEXTURE_SRC_CODE_CINEMATIC_CB, nullptr, 0, 0}, - {"cinematicASampler", TEXTURE_SRC_CODE_CINEMATIC_A, nullptr, 0, 0}, - {"reflectionProbeSampler", TEXTURE_SRC_CODE_REFLECTION_PROBE, nullptr, 0, 0}, - {"alternateSceneSampler", TEXTURE_SRC_CODE_ALTERNATE_SCENE, nullptr, 0, 0}, - {} - }; +inline CodeSamplerSource s_codeSamplers[]{ + {"white", TEXTURE_SRC_CODE_WHITE, nullptr, 0, 0}, + {"black", TEXTURE_SRC_CODE_BLACK, nullptr, 0, 0}, + {"identityNormalMap", TEXTURE_SRC_CODE_IDENTITY_NORMAL_MAP, nullptr, 0, 0}, + {"lightmap", TEXTURE_SRC_CODE_LIGHTMAP_PRIMARY, s_lightmapSamplers, 0, 0}, + {"outdoor", TEXTURE_SRC_CODE_OUTDOOR, nullptr, 0, 0}, + {"shadowmapSun", TEXTURE_SRC_CODE_SHADOWMAP_SUN, nullptr, 0, 0}, + {"shadowmapSpot", TEXTURE_SRC_CODE_SHADOWMAP_SPOT, nullptr, 0, 0}, + {"feedback", TEXTURE_SRC_CODE_FEEDBACK, nullptr, 0, 0}, + {"resolvedPostSun", TEXTURE_SRC_CODE_RESOLVED_POST_SUN, nullptr, 0, 0}, + {"resolvedScene", TEXTURE_SRC_CODE_RESOLVED_SCENE, nullptr, 0, 0}, + {"postEffect0", TEXTURE_SRC_CODE_POST_EFFECT_0, nullptr, 0, 0}, + {"postEffect1", TEXTURE_SRC_CODE_POST_EFFECT_1, nullptr, 0, 0}, + {"light", TEXTURE_SRC_CODE_LIGHT_ATTENUATION, s_lightSamplers, 0, 0}, + {"floatZ", TEXTURE_SRC_CODE_FLOATZ, nullptr, 0, 0}, + {"processedFloatZ", TEXTURE_SRC_CODE_PROCESSED_FLOATZ, nullptr, 0, 0}, + {"rawFloatZ", TEXTURE_SRC_CODE_RAW_FLOATZ, nullptr, 0, 0}, + {"halfParticleColorSampler", TEXTURE_SRC_CODE_HALF_PARTICLES, nullptr, 0, 0}, + {"halfParticleDepthSampler", TEXTURE_SRC_CODE_HALF_PARTICLES_Z, nullptr, 0, 0}, + {"alternateScene", TEXTURE_SRC_CODE_ALTERNATE_SCENE, nullptr, 0, 0}, + {} +}; - inline CodeConstantSource s_sunConsts[] - { - {"position", CONST_SRC_CODE_LIGHT_POSITION, nullptr, 0, 0}, - {"diffuse", CONST_SRC_CODE_LIGHT_DIFFUSE, nullptr, 0, 0}, - {"specular", CONST_SRC_CODE_LIGHT_SPECULAR, nullptr, 0, 0}, - {"spotDir", CONST_SRC_CODE_LIGHT_SPOTDIR, nullptr, 0, 0}, - {"spotFactors", CONST_SRC_CODE_LIGHT_SPOTFACTORS, nullptr, 0, 0}, - {"falloffPlacement", CONST_SRC_CODE_LIGHT_FALLOFF_PLACEMENT, nullptr, 0, 0}, - {} - }; +inline CodeSamplerSource s_defaultCodeSamplers[]{ + {"shadowmapSamplerSun", TEXTURE_SRC_CODE_SHADOWMAP_SUN, nullptr, 0, 0}, + {"shadowmapSamplerSpot", TEXTURE_SRC_CODE_SHADOWMAP_SPOT, nullptr, 0, 0}, + {"feedbackSampler", TEXTURE_SRC_CODE_FEEDBACK, nullptr, 0, 0}, + {"floatZSampler", TEXTURE_SRC_CODE_FLOATZ, nullptr, 0, 0}, + {"processedFloatZSampler", TEXTURE_SRC_CODE_PROCESSED_FLOATZ, nullptr, 0, 0}, + {"rawFloatZSampler", TEXTURE_SRC_CODE_RAW_FLOATZ, nullptr, 0, 0}, + {"halfParticleColorSampler", TEXTURE_SRC_CODE_HALF_PARTICLES, nullptr, 0, 0}, + {"halfParticleDepthSampler", TEXTURE_SRC_CODE_HALF_PARTICLES_Z, nullptr, 0, 0}, + {"attenuationSampler", TEXTURE_SRC_CODE_LIGHT_ATTENUATION, nullptr, 0, 0}, + {"lightmapSamplerPrimary", TEXTURE_SRC_CODE_LIGHTMAP_PRIMARY, nullptr, 0, 0}, + {"lightmapSamplerSecondary", TEXTURE_SRC_CODE_LIGHTMAP_SECONDARY, nullptr, 0, 0}, + {"modelLightingSampler", TEXTURE_SRC_CODE_MODEL_LIGHTING, nullptr, 0, 0}, + {"cinematicYSampler", TEXTURE_SRC_CODE_CINEMATIC_Y, nullptr, 0, 0}, + {"cinematicCrSampler", TEXTURE_SRC_CODE_CINEMATIC_CR, nullptr, 0, 0}, + {"cinematicCbSampler", TEXTURE_SRC_CODE_CINEMATIC_CB, nullptr, 0, 0}, + {"cinematicASampler", TEXTURE_SRC_CODE_CINEMATIC_A, nullptr, 0, 0}, + {"reflectionProbeSampler", TEXTURE_SRC_CODE_REFLECTION_PROBE, nullptr, 0, 0}, + {"alternateSceneSampler", TEXTURE_SRC_CODE_ALTERNATE_SCENE, nullptr, 0, 0}, + {} +}; - inline CodeConstantSource s_nearPlaneConsts[] - { - {"org", CONST_SRC_CODE_NEARPLANE_ORG, nullptr, 0, 0}, - {"dx", CONST_SRC_CODE_NEARPLANE_DX, nullptr, 0, 0}, - {"dy", CONST_SRC_CODE_NEARPLANE_DY, nullptr, 0, 0}, - {} - }; +inline CodeConstantSource s_sunConsts[]{ + {"position", CONST_SRC_CODE_LIGHT_POSITION, nullptr, 0, 0}, + {"diffuse", CONST_SRC_CODE_LIGHT_DIFFUSE, nullptr, 0, 0}, + {"specular", CONST_SRC_CODE_LIGHT_SPECULAR, nullptr, 0, 0}, + {"spotDir", CONST_SRC_CODE_LIGHT_SPOTDIR, nullptr, 0, 0}, + {"spotFactors", CONST_SRC_CODE_LIGHT_SPOTFACTORS, nullptr, 0, 0}, + {"falloffPlacement", CONST_SRC_CODE_LIGHT_FALLOFF_PLACEMENT, nullptr, 0, 0}, + {} +}; - inline CodeConstantSource s_codeConsts[] - { - {"nearPlane", CONST_SRC_NONE, s_nearPlaneConsts, 0, 0}, - {"light", CONST_SRC_NONE, s_sunConsts, 0, 0}, - {"baseLightingCoords", CONST_SRC_CODE_BASE_LIGHTING_COORDS, nullptr, 0, 0}, - {"lightprobeAmbient", CONST_SRC_CODE_LIGHT_PROBE_AMBIENT, nullptr, 0, 0}, - {"fullscreenDistortion", CONST_SRC_CODE_COMPOSITE_FX_DISTORTION, nullptr, 0, 0}, - {"fadeEffect", CONST_SRC_CODE_POSTFX_FADE_EFFECT, nullptr, 0, 0}, - {"lightingLookupScale", CONST_SRC_CODE_LIGHTING_LOOKUP_SCALE, nullptr, 0, 0}, - {"debugBumpmap", CONST_SRC_CODE_DEBUG_BUMPMAP, nullptr, 0, 0}, - {"pixelCostFracs", CONST_SRC_CODE_PIXEL_COST_FRACS, nullptr, 0, 0}, - {"pixelCostDecode", CONST_SRC_CODE_PIXEL_COST_DECODE, nullptr, 0, 0}, - {"materialColor", CONST_SRC_CODE_MATERIAL_COLOR, nullptr, 0, 0}, - {"fogConsts", CONST_SRC_CODE_FOG, nullptr, 0, 0}, - {"fogColorLinear", CONST_SRC_CODE_FOG_COLOR_LINEAR, nullptr, 0, 0}, - {"fogColorGamma", CONST_SRC_CODE_FOG_COLOR_GAMMA, nullptr, 0, 0}, - {"fogSunConsts", CONST_SRC_CODE_FOG_SUN_CONSTS, nullptr, 0, 0}, - {"fogSunColorLinear", CONST_SRC_CODE_FOG_SUN_COLOR_LINEAR, nullptr, 0, 0}, - {"fogSunColorGamma", CONST_SRC_CODE_FOG_SUN_COLOR_GAMMA, nullptr, 0, 0}, - {"fogSunDir", CONST_SRC_CODE_FOG_SUN_DIR, nullptr, 0, 0}, - {"glowSetup", CONST_SRC_CODE_GLOW_SETUP, nullptr, 0, 0}, - {"glowApply", CONST_SRC_CODE_GLOW_APPLY, nullptr, 0, 0}, - {"filterTap", CONST_SRC_CODE_FILTER_TAP_0, nullptr, 8, 1}, - {"codeMeshArg", CONST_SRC_CODE_CODE_MESH_ARG_0, nullptr, 2, 1}, - {"renderTargetSize", CONST_SRC_CODE_RENDER_TARGET_SIZE, nullptr, 0, 0}, - {"shadowmapSwitchPartition", CONST_SRC_CODE_SHADOWMAP_SWITCH_PARTITION, nullptr, 0, 0}, - {"shadowmapScale", CONST_SRC_CODE_SHADOWMAP_SCALE, nullptr, 0, 0}, - {"shadowmapPolygonOffset", CONST_SRC_CODE_SHADOWMAP_POLYGON_OFFSET, nullptr, 0, 0}, - {"zNear", CONST_SRC_CODE_ZNEAR, nullptr, 0, 0}, - {"clipSpaceLookupScale", CONST_SRC_CODE_CLIP_SPACE_LOOKUP_SCALE, nullptr, 0, 0}, - {"clipSpaceLookupOffset", CONST_SRC_CODE_CLIP_SPACE_LOOKUP_OFFSET, nullptr, 0, 0}, - {"dofEquationViewModelAndFarBlur", CONST_SRC_CODE_DOF_EQUATION_VIEWMODEL_AND_FAR_BLUR, nullptr, 0, 0}, - {"dofEquationScene", CONST_SRC_CODE_DOF_EQUATION_SCENE, nullptr, 0, 0}, - {"dofLerpScale", CONST_SRC_CODE_DOF_LERP_SCALE, nullptr, 0, 0}, - {"dofLerpBias", CONST_SRC_CODE_DOF_LERP_BIAS, nullptr, 0, 0}, - {"dofRowDelta", CONST_SRC_CODE_DOF_ROW_DELTA, nullptr, 0, 0}, - {"depthFromClip", CONST_SRC_CODE_DEPTH_FROM_CLIP, nullptr, 0, 0}, - {"outdoorFeatherParms", CONST_SRC_CODE_OUTDOOR_FEATHER_PARMS, nullptr, 0, 0}, - {"envMapParms", CONST_SRC_CODE_ENVMAP_PARMS, nullptr, 0, 0}, - {"colorMatrixR", CONST_SRC_CODE_COLOR_MATRIX_R, nullptr, 0, 0}, - {"colorMatrixG", CONST_SRC_CODE_COLOR_MATRIX_G, nullptr, 0, 0}, - {"colorMatrixB", CONST_SRC_CODE_COLOR_MATRIX_B, nullptr, 0, 0}, - {"colorBias", CONST_SRC_CODE_COLOR_BIAS, nullptr, 0, 0}, - {"colorTintBase", CONST_SRC_CODE_COLOR_TINT_BASE, nullptr, 0, 0}, - {"colorTintDelta", CONST_SRC_CODE_COLOR_TINT_DELTA, nullptr, 0, 0}, - {"colorTintQuadraticDelta", CONST_SRC_CODE_COLOR_TINT_QUADRATIC_DELTA, nullptr, 0, 0}, - {"motionMatrixX", CONST_SRC_CODE_MOTION_MATRIX_X, nullptr, 0, 0}, - {"motionMatrixY", CONST_SRC_CODE_MOTION_MATRIX_Y, nullptr, 0, 0}, - {"motionMatrixW", CONST_SRC_CODE_MOTION_MATRIX_W, nullptr, 0, 0}, - {"gameTime", CONST_SRC_CODE_GAMETIME, nullptr, 0, 0}, - {"particleCloudColor", CONST_SRC_CODE_PARTICLE_CLOUD_COLOR, nullptr, 0, 0}, - {"particleCloudMatrix", CONST_SRC_CODE_PARTICLE_CLOUD_MATRIX0, nullptr, 0, 0}, - {"particleCloudMatrix1", CONST_SRC_CODE_PARTICLE_CLOUD_MATRIX1, nullptr, 0, 0}, - {"particleCloudMatrix2", CONST_SRC_CODE_PARTICLE_CLOUD_MATRIX2, nullptr, 0, 0}, - {"particleCloudSparkColor0", CONST_SRC_CODE_PARTICLE_CLOUD_SPARK_COLOR0, nullptr, 0, 0}, - {"particleCloudSparkColor1", CONST_SRC_CODE_PARTICLE_CLOUD_SPARK_COLOR1, nullptr, 0, 0}, - {"particleCloudSparkColor2", CONST_SRC_CODE_PARTICLE_CLOUD_SPARK_COLOR2, nullptr, 0, 0}, - {"particleFountainParms0", CONST_SRC_CODE_PARTICLE_FOUNTAIN_PARM0, nullptr, 0, 0}, - {"particleFountainParms1", CONST_SRC_CODE_PARTICLE_FOUNTAIN_PARM1, nullptr, 0, 0}, - {"viewportDimensions", CONST_SRC_CODE_VIEWPORT_DIMENSIONS, nullptr, 0, 0}, - {"framebufferRead", CONST_SRC_CODE_FRAMEBUFFER_READ, nullptr, 0, 0}, - {"viewMatrix", CONST_SRC_CODE_VIEW_MATRIX, nullptr, 0, 0}, - {"inverseViewMatrix", CONST_SRC_CODE_INVERSE_VIEW_MATRIX, nullptr, 0, 0}, - {"transposeViewMatrix", CONST_SRC_CODE_TRANSPOSE_VIEW_MATRIX, nullptr, 0, 0}, - {"inverseTransposeViewMatrix", CONST_SRC_CODE_INVERSE_TRANSPOSE_VIEW_MATRIX, nullptr, 0, 0}, - {"projectionMatrix", CONST_SRC_CODE_PROJECTION_MATRIX, nullptr, 0, 0}, - {"inverseProjectionMatrix", CONST_SRC_CODE_INVERSE_PROJECTION_MATRIX, nullptr, 0, 0}, - {"transposeProjectionMatrix", CONST_SRC_CODE_TRANSPOSE_PROJECTION_MATRIX, nullptr, 0, 0}, - {"inverseTransposeProjectionMatrix", CONST_SRC_CODE_INVERSE_TRANSPOSE_PROJECTION_MATRIX, nullptr, 0, 0}, - {"viewProjectionMatrix", CONST_SRC_CODE_VIEW_PROJECTION_MATRIX, nullptr, 0, 0}, - {"inverseViewProjectionMatrix", CONST_SRC_CODE_INVERSE_VIEW_PROJECTION_MATRIX, nullptr, 0, 0}, - {"transposeViewProjectionMatrix", CONST_SRC_CODE_TRANSPOSE_VIEW_PROJECTION_MATRIX, nullptr, 0, 0}, - {"inverseTransposeViewProjectionMatrix", CONST_SRC_CODE_INVERSE_TRANSPOSE_VIEW_PROJECTION_MATRIX, nullptr, 0, 0}, - {"shadowLookupMatrix", CONST_SRC_CODE_SHADOW_LOOKUP_MATRIX, nullptr, 0, 0}, - {"inverseShadowLookupMatrix", CONST_SRC_CODE_INVERSE_SHADOW_LOOKUP_MATRIX, nullptr, 0, 0}, - {"transposeShadowLookupMatrix", CONST_SRC_CODE_TRANSPOSE_SHADOW_LOOKUP_MATRIX, nullptr, 0, 0}, - {"inverseTransposeShadowLookupMatrix", CONST_SRC_CODE_INVERSE_TRANSPOSE_SHADOW_LOOKUP_MATRIX, nullptr, 0, 0}, - {"worldOutdoorLookupMatrix", CONST_SRC_CODE_WORLD_OUTDOOR_LOOKUP_MATRIX, nullptr, 0, 0}, - {"inverseWorldOutdoorLookupMatrix", CONST_SRC_CODE_INVERSE_WORLD_OUTDOOR_LOOKUP_MATRIX, nullptr, 0, 0}, - {"transposeWorldOutdoorLookupMatrix", CONST_SRC_CODE_TRANSPOSE_WORLD_OUTDOOR_LOOKUP_MATRIX, nullptr, 0, 0}, - {"inverseTransposeWorldOutdoorLookupMatrix", CONST_SRC_CODE_INVERSE_TRANSPOSE_WORLD_OUTDOOR_LOOKUP_MATRIX, nullptr, 0, 0}, - {"worldMatrix", CONST_SRC_CODE_WORLD_MATRIX0, nullptr, 0, 0}, - {"inverseWorldMatrix", CONST_SRC_CODE_INVERSE_WORLD_MATRIX0, nullptr, 0, 0}, - {"transposeWorldMatrix", CONST_SRC_CODE_TRANSPOSE_WORLD_MATRIX0, nullptr, 0, 0}, - {"inverseTransposeWorldMatrix", CONST_SRC_CODE_INVERSE_TRANSPOSE_WORLD_MATRIX0, nullptr, 0, 0}, - {"worldViewMatrix", CONST_SRC_CODE_WORLD_VIEW_MATRIX0, nullptr, 0, 0}, - {"inverseWorldViewMatrix", CONST_SRC_CODE_INVERSE_WORLD_VIEW_MATRIX0, nullptr, 0, 0}, - {"transposeWorldViewMatrix", CONST_SRC_CODE_TRANSPOSE_WORLD_VIEW_MATRIX0, nullptr, 0, 0}, - {"inverseTransposeWorldViewMatrix", CONST_SRC_CODE_INVERSE_TRANSPOSE_WORLD_VIEW_MATRIX0, nullptr, 0, 0}, - {"worldViewProjectionMatrix", CONST_SRC_CODE_WORLD_VIEW_PROJECTION_MATRIX0, nullptr, 0, 0}, - {"inverseWorldViewProjectionMatrix", CONST_SRC_CODE_INVERSE_WORLD_VIEW_PROJECTION_MATRIX0, nullptr, 0, 0}, - {"transposeWorldViewProjectionMatrix", CONST_SRC_CODE_TRANSPOSE_WORLD_VIEW_PROJECTION_MATRIX0, nullptr, 0, 0}, - {"inverseTransposeWorldViewProjectionMatrix", CONST_SRC_CODE_INVERSE_TRANSPOSE_WORLD_VIEW_PROJECTION_MATRIX0, nullptr, 0, 0}, - {"worldMatrix1", CONST_SRC_CODE_WORLD_MATRIX1, nullptr, 0, 0}, - {"inverseWorldMatrix1", CONST_SRC_CODE_INVERSE_WORLD_MATRIX1, nullptr, 0, 0}, - {"transposeWorldMatrix1", CONST_SRC_CODE_TRANSPOSE_WORLD_MATRIX1, nullptr, 0, 0}, - {"inverseTransposeWorldMatrix1", CONST_SRC_CODE_INVERSE_TRANSPOSE_WORLD_MATRIX1, nullptr, 0, 0}, - {"worldViewMatrix1", CONST_SRC_CODE_WORLD_VIEW_MATRIX1, nullptr, 0, 0}, - {"inverseWorldViewMatrix1", CONST_SRC_CODE_INVERSE_WORLD_VIEW_MATRIX1, nullptr, 0, 0}, - {"transposeWorldViewMatrix1", CONST_SRC_CODE_TRANSPOSE_WORLD_VIEW_MATRIX1, nullptr, 0, 0}, - {"inverseTransposeWorldViewMatrix1", CONST_SRC_CODE_INVERSE_TRANSPOSE_WORLD_VIEW_MATRIX1, nullptr, 0, 0}, - {"worldViewProjectionMatrix1", CONST_SRC_CODE_WORLD_VIEW_PROJECTION_MATRIX1, nullptr, 0, 0}, - {"inverseWorldViewProjectionMatrix1", CONST_SRC_CODE_INVERSE_WORLD_VIEW_PROJECTION_MATRIX1, nullptr, 0, 0}, - {"transposeWorldViewProjectionMatrix1", CONST_SRC_CODE_TRANSPOSE_WORLD_VIEW_PROJECTION_MATRIX1, nullptr, 0, 0}, - {"inverseTransposeWorldViewProjectionMatrix1", CONST_SRC_CODE_INVERSE_TRANSPOSE_WORLD_VIEW_PROJECTION_MATRIX1, nullptr, 0, 0}, - {"worldMatrix2", CONST_SRC_CODE_WORLD_MATRIX2, nullptr, 0, 0}, - {"inverseWorldMatrix2", CONST_SRC_CODE_INVERSE_WORLD_MATRIX2, nullptr, 0, 0}, - {"transposeWorldMatrix2", CONST_SRC_CODE_TRANSPOSE_WORLD_MATRIX2, nullptr, 0, 0}, - {"inverseTransposeWorldMatrix2", CONST_SRC_CODE_INVERSE_TRANSPOSE_WORLD_MATRIX2, nullptr, 0, 0}, - {"worldViewMatrix2", CONST_SRC_CODE_WORLD_VIEW_MATRIX2, nullptr, 0, 0}, - {"inverseWorldViewMatrix2", CONST_SRC_CODE_INVERSE_WORLD_VIEW_MATRIX2, nullptr, 0, 0}, - {"transposeWorldViewMatrix2", CONST_SRC_CODE_TRANSPOSE_WORLD_VIEW_MATRIX2, nullptr, 0, 0}, - {"inverseTransposeWorldViewMatrix2", CONST_SRC_CODE_INVERSE_TRANSPOSE_WORLD_VIEW_MATRIX2, nullptr, 0, 0}, - {"worldViewProjectionMatrix2", CONST_SRC_CODE_WORLD_VIEW_PROJECTION_MATRIX2, nullptr, 0, 0}, - {"inverseWorldViewProjectionMatrix2", CONST_SRC_CODE_INVERSE_WORLD_VIEW_PROJECTION_MATRIX2, nullptr, 0, 0}, - {"transposeWorldViewProjectionMatrix2", CONST_SRC_CODE_TRANSPOSE_WORLD_VIEW_PROJECTION_MATRIX2, nullptr, 0, 0}, - {"inverseTransposeWorldViewProjectionMatrix2", CONST_SRC_CODE_INVERSE_TRANSPOSE_WORLD_VIEW_PROJECTION_MATRIX2, nullptr, 0, 0}, - {} - }; +inline CodeConstantSource s_nearPlaneConsts[]{ + {"org", CONST_SRC_CODE_NEARPLANE_ORG, nullptr, 0, 0}, + {"dx", CONST_SRC_CODE_NEARPLANE_DX, nullptr, 0, 0}, + {"dy", CONST_SRC_CODE_NEARPLANE_DY, nullptr, 0, 0}, + {} +}; - inline CodeConstantSource s_defaultCodeConsts[] - { - {"nearPlaneOrg", CONST_SRC_CODE_NEARPLANE_ORG, nullptr, 0, 0}, - {"nearPlaneDx", CONST_SRC_CODE_NEARPLANE_DX, nullptr, 0, 0}, - {"nearPlaneDy", CONST_SRC_CODE_NEARPLANE_DY, nullptr, 0, 0}, - {"lightPosition", CONST_SRC_CODE_LIGHT_POSITION, nullptr, 0, 0}, - {"lightDiffuse", CONST_SRC_CODE_LIGHT_DIFFUSE, nullptr, 0, 0}, - {"lightSpecular", CONST_SRC_CODE_LIGHT_SPECULAR, nullptr, 0, 0}, - {"lightSpotDir", CONST_SRC_CODE_LIGHT_SPOTDIR, nullptr, 0, 0}, - {"lightSpotFactors", CONST_SRC_CODE_LIGHT_SPOTFACTORS, nullptr, 0, 0}, - {"lightFalloffPlacement", CONST_SRC_CODE_LIGHT_FALLOFF_PLACEMENT, nullptr, 0, 0}, - {"sunShadowmapPixelAdjust", CONST_SRC_CODE_SUN_SHADOWMAP_PIXEL_ADJUST, nullptr, 0, 0}, - {"spotShadowmapPixelAdjust", CONST_SRC_CODE_SPOT_SHADOWMAP_PIXEL_ADJUST, nullptr, 0, 0}, - {} - }; +inline CodeConstantSource s_codeConsts[]{ + {"nearPlane", CONST_SRC_NONE, s_nearPlaneConsts, 0, 0}, + {"light", CONST_SRC_NONE, s_sunConsts, 0, 0}, + {"baseLightingCoords", CONST_SRC_CODE_BASE_LIGHTING_COORDS, nullptr, 0, 0}, + {"lightprobeAmbient", CONST_SRC_CODE_LIGHT_PROBE_AMBIENT, nullptr, 0, 0}, + {"fullscreenDistortion", CONST_SRC_CODE_COMPOSITE_FX_DISTORTION, nullptr, 0, 0}, + {"fadeEffect", CONST_SRC_CODE_POSTFX_FADE_EFFECT, nullptr, 0, 0}, + {"lightingLookupScale", CONST_SRC_CODE_LIGHTING_LOOKUP_SCALE, nullptr, 0, 0}, + {"debugBumpmap", CONST_SRC_CODE_DEBUG_BUMPMAP, nullptr, 0, 0}, + {"pixelCostFracs", CONST_SRC_CODE_PIXEL_COST_FRACS, nullptr, 0, 0}, + {"pixelCostDecode", CONST_SRC_CODE_PIXEL_COST_DECODE, nullptr, 0, 0}, + {"materialColor", CONST_SRC_CODE_MATERIAL_COLOR, nullptr, 0, 0}, + {"fogConsts", CONST_SRC_CODE_FOG, nullptr, 0, 0}, + {"fogColorLinear", CONST_SRC_CODE_FOG_COLOR_LINEAR, nullptr, 0, 0}, + {"fogColorGamma", CONST_SRC_CODE_FOG_COLOR_GAMMA, nullptr, 0, 0}, + {"fogSunConsts", CONST_SRC_CODE_FOG_SUN_CONSTS, nullptr, 0, 0}, + {"fogSunColorLinear", CONST_SRC_CODE_FOG_SUN_COLOR_LINEAR, nullptr, 0, 0}, + {"fogSunColorGamma", CONST_SRC_CODE_FOG_SUN_COLOR_GAMMA, nullptr, 0, 0}, + {"fogSunDir", CONST_SRC_CODE_FOG_SUN_DIR, nullptr, 0, 0}, + {"glowSetup", CONST_SRC_CODE_GLOW_SETUP, nullptr, 0, 0}, + {"glowApply", CONST_SRC_CODE_GLOW_APPLY, nullptr, 0, 0}, + {"filterTap", CONST_SRC_CODE_FILTER_TAP_0, nullptr, 8, 1}, + {"codeMeshArg", CONST_SRC_CODE_CODE_MESH_ARG_0, nullptr, 2, 1}, + {"renderTargetSize", CONST_SRC_CODE_RENDER_TARGET_SIZE, nullptr, 0, 0}, + {"shadowmapSwitchPartition", CONST_SRC_CODE_SHADOWMAP_SWITCH_PARTITION, nullptr, 0, 0}, + {"shadowmapScale", CONST_SRC_CODE_SHADOWMAP_SCALE, nullptr, 0, 0}, + {"shadowmapPolygonOffset", CONST_SRC_CODE_SHADOWMAP_POLYGON_OFFSET, nullptr, 0, 0}, + {"zNear", CONST_SRC_CODE_ZNEAR, nullptr, 0, 0}, + {"clipSpaceLookupScale", CONST_SRC_CODE_CLIP_SPACE_LOOKUP_SCALE, nullptr, 0, 0}, + {"clipSpaceLookupOffset", CONST_SRC_CODE_CLIP_SPACE_LOOKUP_OFFSET, nullptr, 0, 0}, + {"dofEquationViewModelAndFarBlur", CONST_SRC_CODE_DOF_EQUATION_VIEWMODEL_AND_FAR_BLUR, nullptr, 0, 0}, + {"dofEquationScene", CONST_SRC_CODE_DOF_EQUATION_SCENE, nullptr, 0, 0}, + {"dofLerpScale", CONST_SRC_CODE_DOF_LERP_SCALE, nullptr, 0, 0}, + {"dofLerpBias", CONST_SRC_CODE_DOF_LERP_BIAS, nullptr, 0, 0}, + {"dofRowDelta", CONST_SRC_CODE_DOF_ROW_DELTA, nullptr, 0, 0}, + {"depthFromClip", CONST_SRC_CODE_DEPTH_FROM_CLIP, nullptr, 0, 0}, + {"outdoorFeatherParms", CONST_SRC_CODE_OUTDOOR_FEATHER_PARMS, nullptr, 0, 0}, + {"envMapParms", CONST_SRC_CODE_ENVMAP_PARMS, nullptr, 0, 0}, + {"colorMatrixR", CONST_SRC_CODE_COLOR_MATRIX_R, nullptr, 0, 0}, + {"colorMatrixG", CONST_SRC_CODE_COLOR_MATRIX_G, nullptr, 0, 0}, + {"colorMatrixB", CONST_SRC_CODE_COLOR_MATRIX_B, nullptr, 0, 0}, + {"colorBias", CONST_SRC_CODE_COLOR_BIAS, nullptr, 0, 0}, + {"colorTintBase", CONST_SRC_CODE_COLOR_TINT_BASE, nullptr, 0, 0}, + {"colorTintDelta", CONST_SRC_CODE_COLOR_TINT_DELTA, nullptr, 0, 0}, + {"colorTintQuadraticDelta", CONST_SRC_CODE_COLOR_TINT_QUADRATIC_DELTA, nullptr, 0, 0}, + {"motionMatrixX", CONST_SRC_CODE_MOTION_MATRIX_X, nullptr, 0, 0}, + {"motionMatrixY", CONST_SRC_CODE_MOTION_MATRIX_Y, nullptr, 0, 0}, + {"motionMatrixW", CONST_SRC_CODE_MOTION_MATRIX_W, nullptr, 0, 0}, + {"gameTime", CONST_SRC_CODE_GAMETIME, nullptr, 0, 0}, + {"particleCloudColor", CONST_SRC_CODE_PARTICLE_CLOUD_COLOR, nullptr, 0, 0}, + {"particleCloudMatrix", CONST_SRC_CODE_PARTICLE_CLOUD_MATRIX0, nullptr, 0, 0}, + {"particleCloudMatrix1", CONST_SRC_CODE_PARTICLE_CLOUD_MATRIX1, nullptr, 0, 0}, + {"particleCloudMatrix2", CONST_SRC_CODE_PARTICLE_CLOUD_MATRIX2, nullptr, 0, 0}, + {"particleCloudSparkColor0", CONST_SRC_CODE_PARTICLE_CLOUD_SPARK_COLOR0, nullptr, 0, 0}, + {"particleCloudSparkColor1", CONST_SRC_CODE_PARTICLE_CLOUD_SPARK_COLOR1, nullptr, 0, 0}, + {"particleCloudSparkColor2", CONST_SRC_CODE_PARTICLE_CLOUD_SPARK_COLOR2, nullptr, 0, 0}, + {"particleFountainParms0", CONST_SRC_CODE_PARTICLE_FOUNTAIN_PARM0, nullptr, 0, 0}, + {"particleFountainParms1", CONST_SRC_CODE_PARTICLE_FOUNTAIN_PARM1, nullptr, 0, 0}, + {"viewportDimensions", CONST_SRC_CODE_VIEWPORT_DIMENSIONS, nullptr, 0, 0}, + {"framebufferRead", CONST_SRC_CODE_FRAMEBUFFER_READ, nullptr, 0, 0}, + {"viewMatrix", CONST_SRC_CODE_VIEW_MATRIX, nullptr, 0, 0}, + {"inverseViewMatrix", CONST_SRC_CODE_INVERSE_VIEW_MATRIX, nullptr, 0, 0}, + {"transposeViewMatrix", CONST_SRC_CODE_TRANSPOSE_VIEW_MATRIX, nullptr, 0, 0}, + {"inverseTransposeViewMatrix", CONST_SRC_CODE_INVERSE_TRANSPOSE_VIEW_MATRIX, nullptr, 0, 0}, + {"projectionMatrix", CONST_SRC_CODE_PROJECTION_MATRIX, nullptr, 0, 0}, + {"inverseProjectionMatrix", CONST_SRC_CODE_INVERSE_PROJECTION_MATRIX, nullptr, 0, 0}, + {"transposeProjectionMatrix", CONST_SRC_CODE_TRANSPOSE_PROJECTION_MATRIX, nullptr, 0, 0}, + {"inverseTransposeProjectionMatrix", CONST_SRC_CODE_INVERSE_TRANSPOSE_PROJECTION_MATRIX, nullptr, 0, 0}, + {"viewProjectionMatrix", CONST_SRC_CODE_VIEW_PROJECTION_MATRIX, nullptr, 0, 0}, + {"inverseViewProjectionMatrix", CONST_SRC_CODE_INVERSE_VIEW_PROJECTION_MATRIX, nullptr, 0, 0}, + {"transposeViewProjectionMatrix", CONST_SRC_CODE_TRANSPOSE_VIEW_PROJECTION_MATRIX, nullptr, 0, 0}, + {"inverseTransposeViewProjectionMatrix", CONST_SRC_CODE_INVERSE_TRANSPOSE_VIEW_PROJECTION_MATRIX, nullptr, 0, 0}, + {"shadowLookupMatrix", CONST_SRC_CODE_SHADOW_LOOKUP_MATRIX, nullptr, 0, 0}, + {"inverseShadowLookupMatrix", CONST_SRC_CODE_INVERSE_SHADOW_LOOKUP_MATRIX, nullptr, 0, 0}, + {"transposeShadowLookupMatrix", CONST_SRC_CODE_TRANSPOSE_SHADOW_LOOKUP_MATRIX, nullptr, 0, 0}, + {"inverseTransposeShadowLookupMatrix", CONST_SRC_CODE_INVERSE_TRANSPOSE_SHADOW_LOOKUP_MATRIX, nullptr, 0, 0}, + {"worldOutdoorLookupMatrix", CONST_SRC_CODE_WORLD_OUTDOOR_LOOKUP_MATRIX, nullptr, 0, 0}, + {"inverseWorldOutdoorLookupMatrix", CONST_SRC_CODE_INVERSE_WORLD_OUTDOOR_LOOKUP_MATRIX, nullptr, 0, 0}, + {"transposeWorldOutdoorLookupMatrix", CONST_SRC_CODE_TRANSPOSE_WORLD_OUTDOOR_LOOKUP_MATRIX, nullptr, 0, 0}, + {"inverseTransposeWorldOutdoorLookupMatrix", CONST_SRC_CODE_INVERSE_TRANSPOSE_WORLD_OUTDOOR_LOOKUP_MATRIX, nullptr, 0, 0}, + {"worldMatrix", CONST_SRC_CODE_WORLD_MATRIX0, nullptr, 0, 0}, + {"inverseWorldMatrix", CONST_SRC_CODE_INVERSE_WORLD_MATRIX0, nullptr, 0, 0}, + {"transposeWorldMatrix", CONST_SRC_CODE_TRANSPOSE_WORLD_MATRIX0, nullptr, 0, 0}, + {"inverseTransposeWorldMatrix", CONST_SRC_CODE_INVERSE_TRANSPOSE_WORLD_MATRIX0, nullptr, 0, 0}, + {"worldViewMatrix", CONST_SRC_CODE_WORLD_VIEW_MATRIX0, nullptr, 0, 0}, + {"inverseWorldViewMatrix", CONST_SRC_CODE_INVERSE_WORLD_VIEW_MATRIX0, nullptr, 0, 0}, + {"transposeWorldViewMatrix", CONST_SRC_CODE_TRANSPOSE_WORLD_VIEW_MATRIX0, nullptr, 0, 0}, + {"inverseTransposeWorldViewMatrix", CONST_SRC_CODE_INVERSE_TRANSPOSE_WORLD_VIEW_MATRIX0, nullptr, 0, 0}, + {"worldViewProjectionMatrix", CONST_SRC_CODE_WORLD_VIEW_PROJECTION_MATRIX0, nullptr, 0, 0}, + {"inverseWorldViewProjectionMatrix", CONST_SRC_CODE_INVERSE_WORLD_VIEW_PROJECTION_MATRIX0, nullptr, 0, 0}, + {"transposeWorldViewProjectionMatrix", CONST_SRC_CODE_TRANSPOSE_WORLD_VIEW_PROJECTION_MATRIX0, nullptr, 0, 0}, + {"inverseTransposeWorldViewProjectionMatrix", CONST_SRC_CODE_INVERSE_TRANSPOSE_WORLD_VIEW_PROJECTION_MATRIX0, nullptr, 0, 0}, + {"worldMatrix1", CONST_SRC_CODE_WORLD_MATRIX1, nullptr, 0, 0}, + {"inverseWorldMatrix1", CONST_SRC_CODE_INVERSE_WORLD_MATRIX1, nullptr, 0, 0}, + {"transposeWorldMatrix1", CONST_SRC_CODE_TRANSPOSE_WORLD_MATRIX1, nullptr, 0, 0}, + {"inverseTransposeWorldMatrix1", CONST_SRC_CODE_INVERSE_TRANSPOSE_WORLD_MATRIX1, nullptr, 0, 0}, + {"worldViewMatrix1", CONST_SRC_CODE_WORLD_VIEW_MATRIX1, nullptr, 0, 0}, + {"inverseWorldViewMatrix1", CONST_SRC_CODE_INVERSE_WORLD_VIEW_MATRIX1, nullptr, 0, 0}, + {"transposeWorldViewMatrix1", CONST_SRC_CODE_TRANSPOSE_WORLD_VIEW_MATRIX1, nullptr, 0, 0}, + {"inverseTransposeWorldViewMatrix1", CONST_SRC_CODE_INVERSE_TRANSPOSE_WORLD_VIEW_MATRIX1, nullptr, 0, 0}, + {"worldViewProjectionMatrix1", CONST_SRC_CODE_WORLD_VIEW_PROJECTION_MATRIX1, nullptr, 0, 0}, + {"inverseWorldViewProjectionMatrix1", CONST_SRC_CODE_INVERSE_WORLD_VIEW_PROJECTION_MATRIX1, nullptr, 0, 0}, + {"transposeWorldViewProjectionMatrix1", CONST_SRC_CODE_TRANSPOSE_WORLD_VIEW_PROJECTION_MATRIX1, nullptr, 0, 0}, + {"inverseTransposeWorldViewProjectionMatrix1", CONST_SRC_CODE_INVERSE_TRANSPOSE_WORLD_VIEW_PROJECTION_MATRIX1, nullptr, 0, 0}, + {"worldMatrix2", CONST_SRC_CODE_WORLD_MATRIX2, nullptr, 0, 0}, + {"inverseWorldMatrix2", CONST_SRC_CODE_INVERSE_WORLD_MATRIX2, nullptr, 0, 0}, + {"transposeWorldMatrix2", CONST_SRC_CODE_TRANSPOSE_WORLD_MATRIX2, nullptr, 0, 0}, + {"inverseTransposeWorldMatrix2", CONST_SRC_CODE_INVERSE_TRANSPOSE_WORLD_MATRIX2, nullptr, 0, 0}, + {"worldViewMatrix2", CONST_SRC_CODE_WORLD_VIEW_MATRIX2, nullptr, 0, 0}, + {"inverseWorldViewMatrix2", CONST_SRC_CODE_INVERSE_WORLD_VIEW_MATRIX2, nullptr, 0, 0}, + {"transposeWorldViewMatrix2", CONST_SRC_CODE_TRANSPOSE_WORLD_VIEW_MATRIX2, nullptr, 0, 0}, + {"inverseTransposeWorldViewMatrix2", CONST_SRC_CODE_INVERSE_TRANSPOSE_WORLD_VIEW_MATRIX2, nullptr, 0, 0}, + {"worldViewProjectionMatrix2", CONST_SRC_CODE_WORLD_VIEW_PROJECTION_MATRIX2, nullptr, 0, 0}, + {"inverseWorldViewProjectionMatrix2", CONST_SRC_CODE_INVERSE_WORLD_VIEW_PROJECTION_MATRIX2, nullptr, 0, 0}, + {"transposeWorldViewProjectionMatrix2", CONST_SRC_CODE_TRANSPOSE_WORLD_VIEW_PROJECTION_MATRIX2, nullptr, 0, 0}, + {"inverseTransposeWorldViewProjectionMatrix2", CONST_SRC_CODE_INVERSE_TRANSPOSE_WORLD_VIEW_PROJECTION_MATRIX2, nullptr, 0, 0}, + {} +}; - inline MaterialUpdateFrequency s_codeConstUpdateFreq[] - { - MTL_UPDATE_RARELY, // LIGHT_POSITION - MTL_UPDATE_RARELY, // LIGHT_DIFFUSE - MTL_UPDATE_RARELY, // LIGHT_SPECULAR - MTL_UPDATE_RARELY, // LIGHT_SPOTDIR - MTL_UPDATE_RARELY, // LIGHT_SPOTFACTORS - MTL_UPDATE_RARELY, // LIGHT_FALLOFF_PLACEMENT - MTL_UPDATE_RARELY, // PARTICLE_CLOUD_COLOR - MTL_UPDATE_RARELY, // GAMETIME - MTL_UPDATE_RARELY, // PIXEL_COST_FRACS - MTL_UPDATE_RARELY, // PIXEL_COST_DECODE - MTL_UPDATE_RARELY, // FILTER_TAP_0 - MTL_UPDATE_RARELY, // FILTER_TAP_1 - MTL_UPDATE_RARELY, // FILTER_TAP_2 - MTL_UPDATE_RARELY, // FILTER_TAP_3 - MTL_UPDATE_RARELY, // FILTER_TAP_4 - MTL_UPDATE_RARELY, // FILTER_TAP_5 - MTL_UPDATE_RARELY, // FILTER_TAP_6 - MTL_UPDATE_RARELY, // FILTER_TAP_7 - MTL_UPDATE_RARELY, // COLOR_MATRIX_R - MTL_UPDATE_RARELY, // COLOR_MATRIX_G - MTL_UPDATE_RARELY, // COLOR_MATRIX_B - MTL_UPDATE_RARELY, // SHADOWMAP_POLYGON_OFFSET - MTL_UPDATE_RARELY, // RENDER_TARGET_SIZE - MTL_UPDATE_RARELY, // DOF_EQUATION_VIEWMODEL_AND_FAR_BLUR - MTL_UPDATE_RARELY, // DOF_EQUATION_SCENE - MTL_UPDATE_RARELY, // DOF_LERP_SCALE - MTL_UPDATE_RARELY, // DOF_LERP_BIAS - MTL_UPDATE_RARELY, // DOF_ROW_DELTA - MTL_UPDATE_RARELY, // MOTION_MATRIX_X - MTL_UPDATE_RARELY, // MOTION_MATRIX_Y - MTL_UPDATE_RARELY, // MOTION_MATRIX_W - MTL_UPDATE_RARELY, // SHADOWMAP_SWITCH_PARTITION - MTL_UPDATE_RARELY, // SHADOWMAP_SCALE - MTL_UPDATE_RARELY, // ZNEAR - MTL_UPDATE_RARELY, // LIGHTING_LOOKUP_SCALE - MTL_UPDATE_RARELY, // DEBUG_BUMPMAP - MTL_UPDATE_RARELY, // MATERIAL_COLOR - MTL_UPDATE_RARELY, // FOG - MTL_UPDATE_RARELY, // FOG_COLOR_LINEAR - MTL_UPDATE_RARELY, // FOG_COLOR_GAMMA - MTL_UPDATE_RARELY, // FOG_SUN_CONSTS - MTL_UPDATE_RARELY, // FOG_SUN_COLOR_LINEAR - MTL_UPDATE_RARELY, // FOG_SUN_COLOR_GAMMA - MTL_UPDATE_RARELY, // FOG_SUN_DIR - MTL_UPDATE_RARELY, // GLOW_SETUP - MTL_UPDATE_RARELY, // GLOW_APPLY - MTL_UPDATE_RARELY, // COLOR_BIAS - MTL_UPDATE_RARELY, // COLOR_TINT_BASE - MTL_UPDATE_RARELY, // COLOR_TINT_DELTA - MTL_UPDATE_RARELY, // COLOR_TINT_QUADRATIC_DELTA - MTL_UPDATE_RARELY, // OUTDOOR_FEATHER_PARMS - MTL_UPDATE_RARELY, // ENVMAP_PARMS - MTL_UPDATE_RARELY, // SUN_SHADOWMAP_PIXEL_ADJUST - MTL_UPDATE_RARELY, // SPOT_SHADOWMAP_PIXEL_ADJUST - MTL_UPDATE_RARELY, // COMPOSITE_FX_DISTORTION - MTL_UPDATE_RARELY, // POSTFX_FADE_EFFECT - MTL_UPDATE_RARELY, // VIEWPORT_DIMENSIONS - MTL_UPDATE_RARELY, // FRAMEBUFFER_READ - MTL_UPDATE_PER_PRIM, // BASE_LIGHTING_COORDS - MTL_UPDATE_PER_PRIM, // LIGHT_PROBE_AMBIENT - MTL_UPDATE_RARELY, // NEARPLANE_ORG - MTL_UPDATE_RARELY, // NEARPLANE_DX - MTL_UPDATE_RARELY, // NEARPLANE_DY - MTL_UPDATE_RARELY, // CLIP_SPACE_LOOKUP_SCALE - MTL_UPDATE_RARELY, // CLIP_SPACE_LOOKUP_OFFSET - MTL_UPDATE_PER_OBJECT, // PARTICLE_CLOUD_MATRIX0 - MTL_UPDATE_PER_OBJECT, // PARTICLE_CLOUD_MATRIX1 - MTL_UPDATE_PER_OBJECT, // PARTICLE_CLOUD_MATRIX2 - MTL_UPDATE_PER_OBJECT, // PARTICLE_CLOUD_SPARK_COLOR0 - MTL_UPDATE_PER_OBJECT, // PARTICLE_CLOUD_SPARK_COLOR1 - MTL_UPDATE_PER_OBJECT, // PARTICLE_CLOUD_SPARK_COLOR2 - MTL_UPDATE_PER_OBJECT, // PARTICLE_FOUNTAIN_PARM0 - MTL_UPDATE_PER_OBJECT, // PARTICLE_FOUNTAIN_PARM1 - MTL_UPDATE_PER_OBJECT, // DEPTH_FROM_CLIP - MTL_UPDATE_PER_OBJECT, // CODE_MESH_ARG_0 - MTL_UPDATE_PER_OBJECT, // CODE_MESH_ARG_1 - MTL_UPDATE_PER_OBJECT, // VIEW_MATRIX - MTL_UPDATE_PER_OBJECT, // INVERSE_VIEW_MATRIX - MTL_UPDATE_PER_OBJECT, // TRANSPOSE_VIEW_MATRIX - MTL_UPDATE_PER_OBJECT, // INVERSE_TRANSPOSE_VIEW_MATRIX - MTL_UPDATE_PER_OBJECT, // PROJECTION_MATRIX - MTL_UPDATE_PER_OBJECT, // INVERSE_PROJECTION_MATRIX - MTL_UPDATE_PER_OBJECT, // TRANSPOSE_PROJECTION_MATRIX - MTL_UPDATE_PER_OBJECT, // INVERSE_TRANSPOSE_PROJECTION_MATRIX - MTL_UPDATE_PER_OBJECT, // VIEW_PROJECTION_MATRIX - MTL_UPDATE_PER_OBJECT, // INVERSE_VIEW_PROJECTION_MATRIX - MTL_UPDATE_PER_OBJECT, // TRANSPOSE_VIEW_PROJECTION_MATRIX - MTL_UPDATE_PER_OBJECT, // INVERSE_TRANSPOSE_VIEW_PROJECTION_MATRIX - MTL_UPDATE_PER_OBJECT, // SHADOW_LOOKUP_MATRIX - MTL_UPDATE_PER_OBJECT, // INVERSE_SHADOW_LOOKUP_MATRIX - MTL_UPDATE_PER_OBJECT, // TRANSPOSE_SHADOW_LOOKUP_MATRIX - MTL_UPDATE_PER_OBJECT, // INVERSE_TRANSPOSE_SHADOW_LOOKUP_MATRIX - MTL_UPDATE_PER_PRIM, // WORLD_OUTDOOR_LOOKUP_MATRIX - MTL_UPDATE_PER_PRIM, // INVERSE_WORLD_OUTDOOR_LOOKUP_MATRIX - MTL_UPDATE_PER_PRIM, // TRANSPOSE_WORLD_OUTDOOR_LOOKUP_MATRIX - MTL_UPDATE_PER_PRIM, // INVERSE_TRANSPOSE_WORLD_OUTDOOR_LOOKUP_MATRIX - MTL_UPDATE_PER_PRIM, // WORLD_MATRIX0 - MTL_UPDATE_PER_PRIM, // INVERSE_WORLD_MATRIX0 - MTL_UPDATE_PER_PRIM, // TRANSPOSE_WORLD_MATRIX0 - MTL_UPDATE_PER_PRIM, // INVERSE_TRANSPOSE_WORLD_MATRIX0 - MTL_UPDATE_PER_PRIM, // WORLD_VIEW_MATRIX0 - MTL_UPDATE_PER_PRIM, // INVERSE_WORLD_VIEW_MATRIX0 - MTL_UPDATE_PER_PRIM, // TRANSPOSE_WORLD_VIEW_MATRIX0 - MTL_UPDATE_PER_PRIM, // INVERSE_TRANSPOSE_WORLD_VIEW_MATRIX0 - MTL_UPDATE_PER_PRIM, // WORLD_VIEW_PROJECTION_MATRIX0 - MTL_UPDATE_PER_PRIM, // INVERSE_WORLD_VIEW_PROJECTION_MATRIX0 - MTL_UPDATE_PER_PRIM, // TRANSPOSE_WORLD_VIEW_PROJECTION_MATRIX0 - MTL_UPDATE_PER_PRIM, // INVERSE_TRANSPOSE_WORLD_VIEW_PROJECTION_MATRIX0 - MTL_UPDATE_PER_PRIM, // WORLD_MATRIX1 - MTL_UPDATE_PER_PRIM, // INVERSE_WORLD_MATRIX1 - MTL_UPDATE_PER_PRIM, // TRANSPOSE_WORLD_MATRIX1 - MTL_UPDATE_PER_PRIM, // INVERSE_TRANSPOSE_WORLD_MATRIX1 - MTL_UPDATE_PER_PRIM, // WORLD_VIEW_MATRIX1 - MTL_UPDATE_PER_PRIM, // INVERSE_WORLD_VIEW_MATRIX1 - MTL_UPDATE_PER_PRIM, // TRANSPOSE_WORLD_VIEW_MATRIX1 - MTL_UPDATE_PER_PRIM, // INVERSE_TRANSPOSE_WORLD_VIEW_MATRIX1 - MTL_UPDATE_PER_PRIM, // WORLD_VIEW_PROJECTION_MATRIX1 - MTL_UPDATE_PER_PRIM, // INVERSE_WORLD_VIEW_PROJECTION_MATRIX1 - MTL_UPDATE_PER_PRIM, // TRANSPOSE_WORLD_VIEW_PROJECTION_MATRIX1 - MTL_UPDATE_PER_PRIM, // INVERSE_TRANSPOSE_WORLD_VIEW_PROJECTION_MATRIX1 - MTL_UPDATE_PER_PRIM, // WORLD_MATRIX2 - MTL_UPDATE_PER_PRIM, // INVERSE_WORLD_MATRIX2 - MTL_UPDATE_PER_PRIM, // TRANSPOSE_WORLD_MATRIX2 - MTL_UPDATE_PER_PRIM, // INVERSE_TRANSPOSE_WORLD_MATRIX2 - MTL_UPDATE_PER_PRIM, // WORLD_VIEW_MATRIX2 - MTL_UPDATE_PER_PRIM, // INVERSE_WORLD_VIEW_MATRIX2 - MTL_UPDATE_PER_PRIM, // TRANSPOSE_WORLD_VIEW_MATRIX2 - MTL_UPDATE_PER_PRIM, // INVERSE_TRANSPOSE_WORLD_VIEW_MATRIX2 - MTL_UPDATE_PER_PRIM, // WORLD_VIEW_PROJECTION_MATRIX2 - MTL_UPDATE_PER_PRIM, // INVERSE_WORLD_VIEW_PROJECTION_MATRIX2 - MTL_UPDATE_PER_PRIM, // TRANSPOSE_WORLD_VIEW_PROJECTION_MATRIX2 - MTL_UPDATE_PER_PRIM, // INVERSE_TRANSPOSE_WORLD_VIEW_PROJECTION_MATRIX2 - }; - static_assert(std::extent_v == CONST_SRC_TOTAL_COUNT); +inline CodeConstantSource s_defaultCodeConsts[]{ + {"nearPlaneOrg", CONST_SRC_CODE_NEARPLANE_ORG, nullptr, 0, 0}, + {"nearPlaneDx", CONST_SRC_CODE_NEARPLANE_DX, nullptr, 0, 0}, + {"nearPlaneDy", CONST_SRC_CODE_NEARPLANE_DY, nullptr, 0, 0}, + {"lightPosition", CONST_SRC_CODE_LIGHT_POSITION, nullptr, 0, 0}, + {"lightDiffuse", CONST_SRC_CODE_LIGHT_DIFFUSE, nullptr, 0, 0}, + {"lightSpecular", CONST_SRC_CODE_LIGHT_SPECULAR, nullptr, 0, 0}, + {"lightSpotDir", CONST_SRC_CODE_LIGHT_SPOTDIR, nullptr, 0, 0}, + {"lightSpotFactors", CONST_SRC_CODE_LIGHT_SPOTFACTORS, nullptr, 0, 0}, + {"lightFalloffPlacement", CONST_SRC_CODE_LIGHT_FALLOFF_PLACEMENT, nullptr, 0, 0}, + {"sunShadowmapPixelAdjust", CONST_SRC_CODE_SUN_SHADOWMAP_PIXEL_ADJUST, nullptr, 0, 0}, + {"spotShadowmapPixelAdjust", CONST_SRC_CODE_SPOT_SHADOWMAP_PIXEL_ADJUST, nullptr, 0, 0}, + {} +}; - inline MaterialUpdateFrequency s_codeSamplerUpdateFreq[] - { - MTL_UPDATE_RARELY, // BLACK - MTL_UPDATE_RARELY, // WHITE - MTL_UPDATE_RARELY, // IDENTITY_NORMAL_MAP - MTL_UPDATE_RARELY, // MODEL_LIGHTING - MTL_UPDATE_CUSTOM, // LIGHTMAP_PRIMARY - MTL_UPDATE_CUSTOM, // LIGHTMAP_SECONDARY - MTL_UPDATE_RARELY, // SHADOWMAP_SUN - MTL_UPDATE_RARELY, // SHADOWMAP_SPOT - MTL_UPDATE_PER_OBJECT, // FEEDBACK - MTL_UPDATE_RARELY, // RESOLVED_POST_SUN - MTL_UPDATE_RARELY, // RESOLVED_SCENE - MTL_UPDATE_RARELY, // POST_EFFECT_0 - MTL_UPDATE_RARELY, // POST_EFFECT_1 - MTL_UPDATE_PER_OBJECT, // LIGHT_ATTENUATION - MTL_UPDATE_RARELY, // OUTDOOR - MTL_UPDATE_RARELY, // FLOATZ - MTL_UPDATE_RARELY, // PROCESSED_FLOATZ - MTL_UPDATE_RARELY, // RAW_FLOATZ - MTL_UPDATE_RARELY, // HALF_PARTICLES - MTL_UPDATE_RARELY, // HALF_PARTICLES_Z - MTL_UPDATE_PER_OBJECT, // CASE_TEXTURE - MTL_UPDATE_PER_OBJECT, // CINEMATIC_Y - MTL_UPDATE_PER_OBJECT, // CINEMATIC_CR - MTL_UPDATE_PER_OBJECT, // CINEMATIC_CB - MTL_UPDATE_PER_OBJECT, // CINEMATIC_A - MTL_UPDATE_CUSTOM, // REFLECTION_PROBE - MTL_UPDATE_RARELY, // ALTERNATE_SCENE - }; - static_assert(std::extent_v == TEXTURE_SRC_CODE_COUNT); +inline MaterialUpdateFrequency s_codeConstUpdateFreq[]{ + MTL_UPDATE_RARELY, // LIGHT_POSITION + MTL_UPDATE_RARELY, // LIGHT_DIFFUSE + MTL_UPDATE_RARELY, // LIGHT_SPECULAR + MTL_UPDATE_RARELY, // LIGHT_SPOTDIR + MTL_UPDATE_RARELY, // LIGHT_SPOTFACTORS + MTL_UPDATE_RARELY, // LIGHT_FALLOFF_PLACEMENT + MTL_UPDATE_RARELY, // PARTICLE_CLOUD_COLOR + MTL_UPDATE_RARELY, // GAMETIME + MTL_UPDATE_RARELY, // PIXEL_COST_FRACS + MTL_UPDATE_RARELY, // PIXEL_COST_DECODE + MTL_UPDATE_RARELY, // FILTER_TAP_0 + MTL_UPDATE_RARELY, // FILTER_TAP_1 + MTL_UPDATE_RARELY, // FILTER_TAP_2 + MTL_UPDATE_RARELY, // FILTER_TAP_3 + MTL_UPDATE_RARELY, // FILTER_TAP_4 + MTL_UPDATE_RARELY, // FILTER_TAP_5 + MTL_UPDATE_RARELY, // FILTER_TAP_6 + MTL_UPDATE_RARELY, // FILTER_TAP_7 + MTL_UPDATE_RARELY, // COLOR_MATRIX_R + MTL_UPDATE_RARELY, // COLOR_MATRIX_G + MTL_UPDATE_RARELY, // COLOR_MATRIX_B + MTL_UPDATE_RARELY, // SHADOWMAP_POLYGON_OFFSET + MTL_UPDATE_RARELY, // RENDER_TARGET_SIZE + MTL_UPDATE_RARELY, // DOF_EQUATION_VIEWMODEL_AND_FAR_BLUR + MTL_UPDATE_RARELY, // DOF_EQUATION_SCENE + MTL_UPDATE_RARELY, // DOF_LERP_SCALE + MTL_UPDATE_RARELY, // DOF_LERP_BIAS + MTL_UPDATE_RARELY, // DOF_ROW_DELTA + MTL_UPDATE_RARELY, // MOTION_MATRIX_X + MTL_UPDATE_RARELY, // MOTION_MATRIX_Y + MTL_UPDATE_RARELY, // MOTION_MATRIX_W + MTL_UPDATE_RARELY, // SHADOWMAP_SWITCH_PARTITION + MTL_UPDATE_RARELY, // SHADOWMAP_SCALE + MTL_UPDATE_RARELY, // ZNEAR + MTL_UPDATE_RARELY, // LIGHTING_LOOKUP_SCALE + MTL_UPDATE_RARELY, // DEBUG_BUMPMAP + MTL_UPDATE_RARELY, // MATERIAL_COLOR + MTL_UPDATE_RARELY, // FOG + MTL_UPDATE_RARELY, // FOG_COLOR_LINEAR + MTL_UPDATE_RARELY, // FOG_COLOR_GAMMA + MTL_UPDATE_RARELY, // FOG_SUN_CONSTS + MTL_UPDATE_RARELY, // FOG_SUN_COLOR_LINEAR + MTL_UPDATE_RARELY, // FOG_SUN_COLOR_GAMMA + MTL_UPDATE_RARELY, // FOG_SUN_DIR + MTL_UPDATE_RARELY, // GLOW_SETUP + MTL_UPDATE_RARELY, // GLOW_APPLY + MTL_UPDATE_RARELY, // COLOR_BIAS + MTL_UPDATE_RARELY, // COLOR_TINT_BASE + MTL_UPDATE_RARELY, // COLOR_TINT_DELTA + MTL_UPDATE_RARELY, // COLOR_TINT_QUADRATIC_DELTA + MTL_UPDATE_RARELY, // OUTDOOR_FEATHER_PARMS + MTL_UPDATE_RARELY, // ENVMAP_PARMS + MTL_UPDATE_RARELY, // SUN_SHADOWMAP_PIXEL_ADJUST + MTL_UPDATE_RARELY, // SPOT_SHADOWMAP_PIXEL_ADJUST + MTL_UPDATE_RARELY, // COMPOSITE_FX_DISTORTION + MTL_UPDATE_RARELY, // POSTFX_FADE_EFFECT + MTL_UPDATE_RARELY, // VIEWPORT_DIMENSIONS + MTL_UPDATE_RARELY, // FRAMEBUFFER_READ + MTL_UPDATE_PER_PRIM, // BASE_LIGHTING_COORDS + MTL_UPDATE_PER_PRIM, // LIGHT_PROBE_AMBIENT + MTL_UPDATE_RARELY, // NEARPLANE_ORG + MTL_UPDATE_RARELY, // NEARPLANE_DX + MTL_UPDATE_RARELY, // NEARPLANE_DY + MTL_UPDATE_RARELY, // CLIP_SPACE_LOOKUP_SCALE + MTL_UPDATE_RARELY, // CLIP_SPACE_LOOKUP_OFFSET + MTL_UPDATE_PER_OBJECT, // PARTICLE_CLOUD_MATRIX0 + MTL_UPDATE_PER_OBJECT, // PARTICLE_CLOUD_MATRIX1 + MTL_UPDATE_PER_OBJECT, // PARTICLE_CLOUD_MATRIX2 + MTL_UPDATE_PER_OBJECT, // PARTICLE_CLOUD_SPARK_COLOR0 + MTL_UPDATE_PER_OBJECT, // PARTICLE_CLOUD_SPARK_COLOR1 + MTL_UPDATE_PER_OBJECT, // PARTICLE_CLOUD_SPARK_COLOR2 + MTL_UPDATE_PER_OBJECT, // PARTICLE_FOUNTAIN_PARM0 + MTL_UPDATE_PER_OBJECT, // PARTICLE_FOUNTAIN_PARM1 + MTL_UPDATE_PER_OBJECT, // DEPTH_FROM_CLIP + MTL_UPDATE_PER_OBJECT, // CODE_MESH_ARG_0 + MTL_UPDATE_PER_OBJECT, // CODE_MESH_ARG_1 + MTL_UPDATE_PER_OBJECT, // VIEW_MATRIX + MTL_UPDATE_PER_OBJECT, // INVERSE_VIEW_MATRIX + MTL_UPDATE_PER_OBJECT, // TRANSPOSE_VIEW_MATRIX + MTL_UPDATE_PER_OBJECT, // INVERSE_TRANSPOSE_VIEW_MATRIX + MTL_UPDATE_PER_OBJECT, // PROJECTION_MATRIX + MTL_UPDATE_PER_OBJECT, // INVERSE_PROJECTION_MATRIX + MTL_UPDATE_PER_OBJECT, // TRANSPOSE_PROJECTION_MATRIX + MTL_UPDATE_PER_OBJECT, // INVERSE_TRANSPOSE_PROJECTION_MATRIX + MTL_UPDATE_PER_OBJECT, // VIEW_PROJECTION_MATRIX + MTL_UPDATE_PER_OBJECT, // INVERSE_VIEW_PROJECTION_MATRIX + MTL_UPDATE_PER_OBJECT, // TRANSPOSE_VIEW_PROJECTION_MATRIX + MTL_UPDATE_PER_OBJECT, // INVERSE_TRANSPOSE_VIEW_PROJECTION_MATRIX + MTL_UPDATE_PER_OBJECT, // SHADOW_LOOKUP_MATRIX + MTL_UPDATE_PER_OBJECT, // INVERSE_SHADOW_LOOKUP_MATRIX + MTL_UPDATE_PER_OBJECT, // TRANSPOSE_SHADOW_LOOKUP_MATRIX + MTL_UPDATE_PER_OBJECT, // INVERSE_TRANSPOSE_SHADOW_LOOKUP_MATRIX + MTL_UPDATE_PER_PRIM, // WORLD_OUTDOOR_LOOKUP_MATRIX + MTL_UPDATE_PER_PRIM, // INVERSE_WORLD_OUTDOOR_LOOKUP_MATRIX + MTL_UPDATE_PER_PRIM, // TRANSPOSE_WORLD_OUTDOOR_LOOKUP_MATRIX + MTL_UPDATE_PER_PRIM, // INVERSE_TRANSPOSE_WORLD_OUTDOOR_LOOKUP_MATRIX + MTL_UPDATE_PER_PRIM, // WORLD_MATRIX0 + MTL_UPDATE_PER_PRIM, // INVERSE_WORLD_MATRIX0 + MTL_UPDATE_PER_PRIM, // TRANSPOSE_WORLD_MATRIX0 + MTL_UPDATE_PER_PRIM, // INVERSE_TRANSPOSE_WORLD_MATRIX0 + MTL_UPDATE_PER_PRIM, // WORLD_VIEW_MATRIX0 + MTL_UPDATE_PER_PRIM, // INVERSE_WORLD_VIEW_MATRIX0 + MTL_UPDATE_PER_PRIM, // TRANSPOSE_WORLD_VIEW_MATRIX0 + MTL_UPDATE_PER_PRIM, // INVERSE_TRANSPOSE_WORLD_VIEW_MATRIX0 + MTL_UPDATE_PER_PRIM, // WORLD_VIEW_PROJECTION_MATRIX0 + MTL_UPDATE_PER_PRIM, // INVERSE_WORLD_VIEW_PROJECTION_MATRIX0 + MTL_UPDATE_PER_PRIM, // TRANSPOSE_WORLD_VIEW_PROJECTION_MATRIX0 + MTL_UPDATE_PER_PRIM, // INVERSE_TRANSPOSE_WORLD_VIEW_PROJECTION_MATRIX0 + MTL_UPDATE_PER_PRIM, // WORLD_MATRIX1 + MTL_UPDATE_PER_PRIM, // INVERSE_WORLD_MATRIX1 + MTL_UPDATE_PER_PRIM, // TRANSPOSE_WORLD_MATRIX1 + MTL_UPDATE_PER_PRIM, // INVERSE_TRANSPOSE_WORLD_MATRIX1 + MTL_UPDATE_PER_PRIM, // WORLD_VIEW_MATRIX1 + MTL_UPDATE_PER_PRIM, // INVERSE_WORLD_VIEW_MATRIX1 + MTL_UPDATE_PER_PRIM, // TRANSPOSE_WORLD_VIEW_MATRIX1 + MTL_UPDATE_PER_PRIM, // INVERSE_TRANSPOSE_WORLD_VIEW_MATRIX1 + MTL_UPDATE_PER_PRIM, // WORLD_VIEW_PROJECTION_MATRIX1 + MTL_UPDATE_PER_PRIM, // INVERSE_WORLD_VIEW_PROJECTION_MATRIX1 + MTL_UPDATE_PER_PRIM, // TRANSPOSE_WORLD_VIEW_PROJECTION_MATRIX1 + MTL_UPDATE_PER_PRIM, // INVERSE_TRANSPOSE_WORLD_VIEW_PROJECTION_MATRIX1 + MTL_UPDATE_PER_PRIM, // WORLD_MATRIX2 + MTL_UPDATE_PER_PRIM, // INVERSE_WORLD_MATRIX2 + MTL_UPDATE_PER_PRIM, // TRANSPOSE_WORLD_MATRIX2 + MTL_UPDATE_PER_PRIM, // INVERSE_TRANSPOSE_WORLD_MATRIX2 + MTL_UPDATE_PER_PRIM, // WORLD_VIEW_MATRIX2 + MTL_UPDATE_PER_PRIM, // INVERSE_WORLD_VIEW_MATRIX2 + MTL_UPDATE_PER_PRIM, // TRANSPOSE_WORLD_VIEW_MATRIX2 + MTL_UPDATE_PER_PRIM, // INVERSE_TRANSPOSE_WORLD_VIEW_MATRIX2 + MTL_UPDATE_PER_PRIM, // WORLD_VIEW_PROJECTION_MATRIX2 + MTL_UPDATE_PER_PRIM, // INVERSE_WORLD_VIEW_PROJECTION_MATRIX2 + MTL_UPDATE_PER_PRIM, // TRANSPOSE_WORLD_VIEW_PROJECTION_MATRIX2 + MTL_UPDATE_PER_PRIM, // INVERSE_TRANSPOSE_WORLD_VIEW_PROJECTION_MATRIX2 +}; +static_assert(std::extent_v == CONST_SRC_TOTAL_COUNT); - inline MaterialTextureSource g_customSamplerSrc[] - { - TEXTURE_SRC_CODE_REFLECTION_PROBE, // CUSTOM_SAMPLER_REFLECTION_PROBE - TEXTURE_SRC_CODE_LIGHTMAP_PRIMARY, // CUSTOM_SAMPLER_LIGHTMAP_PRIMARY - TEXTURE_SRC_CODE_LIGHTMAP_SECONDARY // CUSTOM_SAMPLER_LIGHTMAP_SECONDARY - }; - static_assert(std::extent_v == CUSTOM_SAMPLER_COUNT); +inline MaterialUpdateFrequency s_codeSamplerUpdateFreq[]{ + MTL_UPDATE_RARELY, // BLACK + MTL_UPDATE_RARELY, // WHITE + MTL_UPDATE_RARELY, // IDENTITY_NORMAL_MAP + MTL_UPDATE_RARELY, // MODEL_LIGHTING + MTL_UPDATE_CUSTOM, // LIGHTMAP_PRIMARY + MTL_UPDATE_CUSTOM, // LIGHTMAP_SECONDARY + MTL_UPDATE_RARELY, // SHADOWMAP_SUN + MTL_UPDATE_RARELY, // SHADOWMAP_SPOT + MTL_UPDATE_PER_OBJECT, // FEEDBACK + MTL_UPDATE_RARELY, // RESOLVED_POST_SUN + MTL_UPDATE_RARELY, // RESOLVED_SCENE + MTL_UPDATE_RARELY, // POST_EFFECT_0 + MTL_UPDATE_RARELY, // POST_EFFECT_1 + MTL_UPDATE_PER_OBJECT, // LIGHT_ATTENUATION + MTL_UPDATE_RARELY, // OUTDOOR + MTL_UPDATE_RARELY, // FLOATZ + MTL_UPDATE_RARELY, // PROCESSED_FLOATZ + MTL_UPDATE_RARELY, // RAW_FLOATZ + MTL_UPDATE_RARELY, // HALF_PARTICLES + MTL_UPDATE_RARELY, // HALF_PARTICLES_Z + MTL_UPDATE_PER_OBJECT, // CASE_TEXTURE + MTL_UPDATE_PER_OBJECT, // CINEMATIC_Y + MTL_UPDATE_PER_OBJECT, // CINEMATIC_CR + MTL_UPDATE_PER_OBJECT, // CINEMATIC_CB + MTL_UPDATE_PER_OBJECT, // CINEMATIC_A + MTL_UPDATE_CUSTOM, // REFLECTION_PROBE + MTL_UPDATE_RARELY, // ALTERNATE_SCENE +}; +static_assert(std::extent_v == TEXTURE_SRC_CODE_COUNT); - inline MaterialTypeInfo g_materialTypeInfo[] - { - {"", ""}, - {"m/", "m_"}, - {"mc/", "mc_"}, - {"mg/", "mg_"}, - {"w/", "w_"}, - {"wc/", "wc_"} - }; - static_assert(std::extent_v == MTL_TYPE_COUNT); +inline MaterialTextureSource g_customSamplerSrc[]{ + TEXTURE_SRC_CODE_REFLECTION_PROBE, // CUSTOM_SAMPLER_REFLECTION_PROBE + TEXTURE_SRC_CODE_LIGHTMAP_PRIMARY, // CUSTOM_SAMPLER_LIGHTMAP_PRIMARY + TEXTURE_SRC_CODE_LIGHTMAP_SECONDARY // CUSTOM_SAMPLER_LIGHTMAP_SECONDARY +}; +static_assert(std::extent_v == CUSTOM_SAMPLER_COUNT); - struct KnownMaterialTextureMap - { - const char* m_name; - const char* m_additional_property_suffix; - }; +inline MaterialTypeInfo g_materialTypeInfo[]{ + {"", "" }, + {"m/", "m_" }, + {"mc/", "mc_"}, + {"mg/", "mg_"}, + {"w/", "w_" }, + {"wc/", "wc_"} +}; +static_assert(std::extent_v == MTL_TYPE_COUNT); - static constexpr std::pair MakeKnownTextureMap(const char* name, const char* additionalPropertySuffix) - { - return std::make_pair(Common::R_HashString(name, 0u), KnownMaterialTextureMap{name, additionalPropertySuffix}); - } +struct KnownMaterialTextureMap { + const char *m_name; + const char *m_additional_property_suffix; +}; - inline std::unordered_map knownTextureMaps - { - MakeKnownTextureMap("colorMap", "Color"), - MakeKnownTextureMap("colorMap0", "Color00"), - MakeKnownTextureMap("colorMap1", "Color01"), - MakeKnownTextureMap("colorMap2", "Color02"), - MakeKnownTextureMap("normalMap", "Normal"), - MakeKnownTextureMap("specularMap", "Specular"), - MakeKnownTextureMap("detailMap", "Detail"), - }; +static constexpr std::pair MakeKnownTextureMap(const char *name, const char *additionalPropertySuffix) { + return std::make_pair(Common::R_HashString(name, 0u), KnownMaterialTextureMap{name, additionalPropertySuffix}); +} - static constexpr std::pair MakeKnownConstantName(const char* name) - { - return std::make_pair(Common::R_HashString(name, 0u), name); - } +inline std::unordered_map knownTextureMaps{ + MakeKnownTextureMap("colorMap", "Color"), MakeKnownTextureMap("colorMap0", "Color00"), MakeKnownTextureMap("colorMap1", "Color01"), + MakeKnownTextureMap("colorMap2", "Color02"), MakeKnownTextureMap("normalMap", "Normal"), MakeKnownTextureMap("specularMap", "Specular"), + MakeKnownTextureMap("detailMap", "Detail"), +}; - inline std::unordered_map knownConstantNames - { - MakeKnownConstantName("distortionScale"), - MakeKnownConstantName("eyeOffsetParms"), - MakeKnownConstantName("falloffBeginColor"), - MakeKnownConstantName("falloffEndColor"), - }; +static constexpr std::pair MakeKnownConstantName(const char *name) { return std::make_pair(Common::R_HashString(name, 0u), name); } - enum class StateMapLayout_e - { - ALPHA_TEST, - BLEND_FUNC, - SEPARATE_ALPHA_BLEND_FUNC, - CULL_FACE, - DEPTH_TEST, - DEPTH_WRITE, - COLOR_WRITE, - GAMMA_WRITE, - POLYGON_OFFSET, - STENCIL, - WIREFRAME - }; +inline std::unordered_map knownConstantNames{ + MakeKnownConstantName("distortionScale"), + MakeKnownConstantName("eyeOffsetParms"), + MakeKnownConstantName("falloffBeginColor"), + MakeKnownConstantName("falloffEndColor"), +}; +enum class StateMapLayout_e { + ALPHA_TEST, + BLEND_FUNC, + SEPARATE_ALPHA_BLEND_FUNC, + CULL_FACE, + DEPTH_TEST, + DEPTH_WRITE, + COLOR_WRITE, + GAMMA_WRITE, + POLYGON_OFFSET, + STENCIL, + WIREFRAME +}; - inline state_map::StateMapLayoutEntries stateMapEntryLayout({ - { - "alphaTest", 0, GFXS0_ATEST_MASK | GFXS0_ATEST_DISABLE, { - "mtlAlphaTest" - } - }, - { - "blendFunc", 0, GFXS0_BLEND_RGB_MASK, { - "mtlBlendOp", - "mtlSrcBlend", - "mtlDestBlend" - } - }, - { - "separateAlphaBlendFunc", 0, GFXS0_BLEND_ALPHA_MASK, { - "mtlBlendOpAlpha", - "mtlSrcBlendAlpha", - "mtlDestBlendAlpha" - } - }, - { - "cullFace", 0, GFXS0_CULL_MASK, { - "mtlCullFace" - } - }, - { - "depthTest", 1, GFXS1_DEPTHTEST_MASK | GFXS1_DEPTHTEST_DISABLE, { - "mtlDepthTest" - } - }, - { - "depthWrite", 1, GFXS1_DEPTHWRITE, { - "mtlDepthWrite" - } - }, - { - "colorWrite", 0, GFXS0_COLORWRITE_MASK, { - "mtlColorWriteRgb", - "mtlColorWriteAlpha" - } - }, - { - "gammaWrite", 0, GFXS0_GAMMAWRITE, { - "mtlGammaWrite", - } - }, - { - "polygonOffset", 1, GFXS1_POLYGON_OFFSET_MASK, { - "mtlPolygonOffset", - } - }, - { - "stencil", 1, GFXS1_STENCILFUNC_FRONTBACK_MASK | GFXS1_STENCILOP_FRONTBACK_MASK, { - "mtlStencil", - "mtlStencilFuncFront", - "mtlStencilOpFrontPass", - "mtlStencilOpFrontFail", - "mtlStencilOpFrontZFail", - "mtlStencilFuncBack", - "mtlStencilOpBackPass", - "mtlStencilOpBackFail", - "mtlStencilOpBackZFail", - } - }, - { - "wireframe", 0, GFXS0_POLYMODE_LINE, { - "mtlWireframe", - } - } - }); +inline state_map::StateMapLayoutEntries stateMapEntryLayout({ + {"alphaTest", 0, GFXS0_ATEST_MASK | GFXS0_ATEST_DISABLE, {"mtlAlphaTest"} }, + {"blendFunc", 0, GFXS0_BLEND_RGB_MASK, {"mtlBlendOp", "mtlSrcBlend", "mtlDestBlend"} }, + {"separateAlphaBlendFunc", 0, GFXS0_BLEND_ALPHA_MASK, {"mtlBlendOpAlpha", "mtlSrcBlendAlpha", "mtlDestBlendAlpha"}}, + {"cullFace", 0, GFXS0_CULL_MASK, {"mtlCullFace"} }, + {"depthTest", 1, GFXS1_DEPTHTEST_MASK | GFXS1_DEPTHTEST_DISABLE, {"mtlDepthTest"} }, + {"depthWrite", 1, GFXS1_DEPTHWRITE, {"mtlDepthWrite"} }, + {"colorWrite", 0, GFXS0_COLORWRITE_MASK, {"mtlColorWriteRgb", "mtlColorWriteAlpha"} }, + {"gammaWrite", + 0, GFXS0_GAMMAWRITE, + { + "mtlGammaWrite", + } }, + {"polygonOffset", + 1, GFXS1_POLYGON_OFFSET_MASK, + { + "mtlPolygonOffset", + } }, + {"stencil", + 1, GFXS1_STENCILFUNC_FRONTBACK_MASK | GFXS1_STENCILOP_FRONTBACK_MASK, + { + "mtlStencil", + "mtlStencilFuncFront", + "mtlStencilOpFrontPass", + "mtlStencilOpFrontFail", + "mtlStencilOpFrontZFail", + "mtlStencilFuncBack", + "mtlStencilOpBackPass", + "mtlStencilOpBackFail", + "mtlStencilOpBackZFail", + } }, + {"wireframe", + 0, GFXS0_POLYMODE_LINE, + { + "mtlWireframe", + } } +}); - inline state_map::StateMapLayoutVars stateMapVarLayout({ - { - "mtlAlphaTest", 0, { - {"Always", GFXS0_ATEST_DISABLE}, - {"GE128", GFXS0_ATEST_GE_128}, - {"GT0", GFXS0_ATEST_GT_0}, - {"LT128", GFXS0_ATEST_LT_128}, - } - }, - { - "mtlBlendOp", 0, { - {"Add", GFXS_BLENDOP_ADD << GFXS0_BLENDOP_RGB_SHIFT}, - {"Subtract", GFXS_BLENDOP_SUBTRACT << GFXS0_BLENDOP_RGB_SHIFT}, - {"RevSubtract", GFXS_BLENDOP_REVSUBTRACT << GFXS0_BLENDOP_RGB_SHIFT}, - {"Min", GFXS_BLENDOP_MIN << GFXS0_BLENDOP_RGB_SHIFT}, - {"Max", GFXS_BLENDOP_MAX << GFXS0_BLENDOP_RGB_SHIFT}, - {"Disable", GFXS_BLENDOP_DISABLED << GFXS0_BLENDOP_RGB_SHIFT}, - } - }, - { - "mtlSrcBlend", 0, { - {"Zero", GFXS_BLEND_ZERO << GFXS0_SRCBLEND_RGB_SHIFT}, - {"One", GFXS_BLEND_ONE << GFXS0_SRCBLEND_RGB_SHIFT}, - {"SrcColor", GFXS_BLEND_SRCCOLOR << GFXS0_SRCBLEND_RGB_SHIFT}, - {"InvSrcColor", GFXS_BLEND_INVSRCCOLOR << GFXS0_SRCBLEND_RGB_SHIFT}, - {"SrcAlpha", GFXS_BLEND_SRCALPHA << GFXS0_SRCBLEND_RGB_SHIFT}, - {"InvSrcAlpha", GFXS_BLEND_INVSRCALPHA << GFXS0_SRCBLEND_RGB_SHIFT}, - {"DestAlpha", GFXS_BLEND_DESTALPHA << GFXS0_SRCBLEND_RGB_SHIFT}, - {"InvDestAlpha", GFXS_BLEND_INVDESTALPHA << GFXS0_SRCBLEND_RGB_SHIFT}, - {"DestColor", GFXS_BLEND_DESTCOLOR << GFXS0_SRCBLEND_RGB_SHIFT}, - {"InvDestColor", GFXS_BLEND_INVDESTCOLOR << GFXS0_SRCBLEND_RGB_SHIFT}, - } - }, - { - "mtlDestBlend", 0, { - {"Zero", GFXS_BLEND_ZERO << GFXS0_DSTBLEND_RGB_SHIFT}, - {"One", GFXS_BLEND_ONE << GFXS0_DSTBLEND_RGB_SHIFT}, - {"SrcColor", GFXS_BLEND_SRCCOLOR << GFXS0_DSTBLEND_RGB_SHIFT}, - {"InvSrcColor", GFXS_BLEND_INVSRCCOLOR << GFXS0_DSTBLEND_RGB_SHIFT}, - {"SrcAlpha", GFXS_BLEND_SRCALPHA << GFXS0_DSTBLEND_RGB_SHIFT}, - {"InvSrcAlpha", GFXS_BLEND_INVSRCALPHA << GFXS0_DSTBLEND_RGB_SHIFT}, - {"DestAlpha", GFXS_BLEND_DESTALPHA << GFXS0_DSTBLEND_RGB_SHIFT}, - {"InvDestAlpha", GFXS_BLEND_INVDESTALPHA << GFXS0_DSTBLEND_RGB_SHIFT}, - {"DestColor", GFXS_BLEND_DESTCOLOR << GFXS0_DSTBLEND_RGB_SHIFT}, - {"InvDestColor", GFXS_BLEND_INVDESTCOLOR << GFXS0_DSTBLEND_RGB_SHIFT}, - } - }, - { - "mtlBlendOpAlpha", 0, { - {"Add", GFXS_BLENDOP_ADD << GFXS0_BLENDOP_ALPHA_SHIFT}, - {"Subtract", GFXS_BLENDOP_SUBTRACT << GFXS0_BLENDOP_ALPHA_SHIFT}, - {"RevSubtract", GFXS_BLENDOP_REVSUBTRACT << GFXS0_BLENDOP_ALPHA_SHIFT}, - {"Min", GFXS_BLENDOP_MIN << GFXS0_BLENDOP_ALPHA_SHIFT}, - {"Max", GFXS_BLENDOP_MAX << GFXS0_BLENDOP_ALPHA_SHIFT}, - {"Disable", GFXS_BLENDOP_DISABLED << GFXS0_BLENDOP_ALPHA_SHIFT}, - } - }, - { - "mtlSrcBlendAlpha", 0, { - {"Zero", GFXS_BLEND_ZERO << GFXS0_SRCBLEND_ALPHA_SHIFT}, - {"One", GFXS_BLEND_ONE << GFXS0_SRCBLEND_ALPHA_SHIFT}, - {"SrcColor", GFXS_BLEND_SRCCOLOR << GFXS0_SRCBLEND_ALPHA_SHIFT}, - {"InvSrcColor", GFXS_BLEND_INVSRCCOLOR << GFXS0_SRCBLEND_ALPHA_SHIFT}, - {"SrcAlpha", GFXS_BLEND_SRCALPHA << GFXS0_SRCBLEND_ALPHA_SHIFT}, - {"InvSrcAlpha", GFXS_BLEND_INVSRCALPHA << GFXS0_SRCBLEND_ALPHA_SHIFT}, - {"DestAlpha", GFXS_BLEND_DESTALPHA << GFXS0_SRCBLEND_ALPHA_SHIFT}, - {"InvDestAlpha", GFXS_BLEND_INVDESTALPHA << GFXS0_SRCBLEND_ALPHA_SHIFT}, - {"DestColor", GFXS_BLEND_DESTCOLOR << GFXS0_SRCBLEND_ALPHA_SHIFT}, - {"InvDestColor", GFXS_BLEND_INVDESTCOLOR << GFXS0_SRCBLEND_ALPHA_SHIFT}, - } - }, - { - "mtlDestBlendAlpha", 0, { - {"Zero", GFXS_BLEND_ZERO << GFXS0_DSTBLEND_ALPHA_SHIFT}, - {"One", GFXS_BLEND_ONE << GFXS0_DSTBLEND_ALPHA_SHIFT}, - {"SrcColor", GFXS_BLEND_SRCCOLOR << GFXS0_DSTBLEND_ALPHA_SHIFT}, - {"InvSrcColor", GFXS_BLEND_INVSRCCOLOR << GFXS0_DSTBLEND_ALPHA_SHIFT}, - {"SrcAlpha", GFXS_BLEND_SRCALPHA << GFXS0_DSTBLEND_ALPHA_SHIFT}, - {"InvSrcAlpha", GFXS_BLEND_INVSRCALPHA << GFXS0_DSTBLEND_ALPHA_SHIFT}, - {"DestAlpha", GFXS_BLEND_DESTALPHA << GFXS0_DSTBLEND_ALPHA_SHIFT}, - {"InvDestAlpha", GFXS_BLEND_INVDESTALPHA << GFXS0_DSTBLEND_ALPHA_SHIFT}, - {"DestColor", GFXS_BLEND_DESTCOLOR << GFXS0_DSTBLEND_ALPHA_SHIFT}, - {"InvDestColor", GFXS_BLEND_INVDESTCOLOR << GFXS0_DSTBLEND_ALPHA_SHIFT}, - } - }, - { - "mtlCullFace", 0, { - {"None", GFXS0_CULL_NONE}, - {"Back", GFXS0_CULL_BACK}, - {"Front", GFXS0_CULL_FRONT}, - } - }, - { - "mtlColorWriteRgb", 0, { - {"Enable", GFXS0_COLORWRITE_RGB}, - {"Disable", 0}, - } - }, - { - "mtlColorWriteAlpha", 0, { - {"Enable", GFXS0_COLORWRITE_ALPHA}, - {"Disable", 0}, - } - }, - { - "mtlGammaWrite", 0, { - {"Enable", GFXS0_GAMMAWRITE}, - {"Disable", 0}, - } - }, - { - "mtlWireframe", 0, { - {"Enable", GFXS0_POLYMODE_LINE}, - {"Disable", 0}, - } - }, - { - "mtlDepthTest", 1, { - {"Disable", GFXS1_DEPTHTEST_DISABLE}, - {"Less", GFXS1_DEPTHTEST_LESS}, - {"LessEqual", GFXS1_DEPTHTEST_LESSEQUAL}, - {"Equal", GFXS1_DEPTHTEST_EQUAL}, - {"Always", GFXS1_DEPTHTEST_ALWAYS}, - } - }, - { - "mtlDepthWrite", 1, { - {"Enable", GFXS1_DEPTHWRITE}, - {"Disable", 0}, - } - }, - { - "mtlPolygonOffset", 1, { - {"1", GFXS1_POLYGON_OFFSET_1}, - {"2", GFXS1_POLYGON_OFFSET_2}, - {"shadowmap", GFXS1_POLYGON_OFFSET_SHADOWMAP}, - {"0", GFXS1_POLYGON_OFFSET_0}, - } - }, - { - "mtlStencil", 1, { - {"OneSided", GFXS1_STENCIL_FRONT_ENABLE}, - {"TwoSided", GFXS1_STENCIL_FRONT_ENABLE | GFXS1_STENCIL_BACK_ENABLE}, - {"Disable", 0}, - } - }, - { - "mtlStencilFuncFront", 1, { - {"Less", GFXS_STENCILFUNC_LESS << GFXS1_STENCIL_FRONT_FUNC_SHIFT}, - {"Equal", GFXS_STENCILFUNC_EQUAL << GFXS1_STENCIL_FRONT_FUNC_SHIFT}, - {"LessEqual", GFXS_STENCILFUNC_LESSEQUAL << GFXS1_STENCIL_FRONT_FUNC_SHIFT}, - {"Greater", GFXS_STENCILFUNC_GREATER << GFXS1_STENCIL_FRONT_FUNC_SHIFT}, - {"NotEqual", GFXS_STENCILFUNC_NOTEQUAL << GFXS1_STENCIL_FRONT_FUNC_SHIFT}, - {"GreaterEqual", GFXS_STENCILFUNC_GREATEREQUAL << GFXS1_STENCIL_FRONT_FUNC_SHIFT}, - {"Always", GFXS_STENCILFUNC_ALWAYS << GFXS1_STENCIL_FRONT_FUNC_SHIFT}, - {"Never", GFXS_STENCILFUNC_NEVER << GFXS1_STENCIL_FRONT_FUNC_SHIFT}, - } - }, - { - "mtlStencilOpFrontPass", 1, { - {"Zero", GFXS_STENCILOP_ZERO << GFXS1_STENCIL_FRONT_PASS_SHIFT}, - {"Replace", GFXS_STENCILOP_REPLACE << GFXS1_STENCIL_FRONT_PASS_SHIFT}, - {"IncrSat", GFXS_STENCILOP_INCRSAT << GFXS1_STENCIL_FRONT_PASS_SHIFT}, - {"DecrSat", GFXS_STENCILOP_DECRSAT << GFXS1_STENCIL_FRONT_PASS_SHIFT}, - {"Invert", GFXS_STENCILOP_INVERT << GFXS1_STENCIL_FRONT_PASS_SHIFT}, - {"Incr", GFXS_STENCILOP_INCR << GFXS1_STENCIL_FRONT_PASS_SHIFT}, - {"Decr", GFXS_STENCILOP_DECR << GFXS1_STENCIL_FRONT_PASS_SHIFT}, - {"Keep", GFXS_STENCILOP_KEEP << GFXS1_STENCIL_FRONT_PASS_SHIFT}, - } - }, - { - "mtlStencilOpFrontFail", 1, { - {"Zero", GFXS_STENCILOP_ZERO << GFXS1_STENCIL_FRONT_FAIL_SHIFT}, - {"Replace", GFXS_STENCILOP_REPLACE << GFXS1_STENCIL_FRONT_FAIL_SHIFT}, - {"IncrSat", GFXS_STENCILOP_INCRSAT << GFXS1_STENCIL_FRONT_FAIL_SHIFT}, - {"DecrSat", GFXS_STENCILOP_DECRSAT << GFXS1_STENCIL_FRONT_FAIL_SHIFT}, - {"Invert", GFXS_STENCILOP_INVERT << GFXS1_STENCIL_FRONT_FAIL_SHIFT}, - {"Incr", GFXS_STENCILOP_INCR << GFXS1_STENCIL_FRONT_FAIL_SHIFT}, - {"Decr", GFXS_STENCILOP_DECR << GFXS1_STENCIL_FRONT_FAIL_SHIFT}, - {"Keep", GFXS_STENCILOP_KEEP << GFXS1_STENCIL_FRONT_FAIL_SHIFT}, - } - }, - { - "mtlStencilOpFrontZFail", 1, { - {"Zero", GFXS_STENCILOP_ZERO << GFXS1_STENCIL_FRONT_ZFAIL_SHIFT}, - {"Replace", GFXS_STENCILOP_REPLACE << GFXS1_STENCIL_FRONT_ZFAIL_SHIFT}, - {"IncrSat", GFXS_STENCILOP_INCRSAT << GFXS1_STENCIL_FRONT_ZFAIL_SHIFT}, - {"DecrSat", GFXS_STENCILOP_DECRSAT << GFXS1_STENCIL_FRONT_ZFAIL_SHIFT}, - {"Invert", GFXS_STENCILOP_INVERT << GFXS1_STENCIL_FRONT_ZFAIL_SHIFT}, - {"Incr", GFXS_STENCILOP_INCR << GFXS1_STENCIL_FRONT_ZFAIL_SHIFT}, - {"Decr", GFXS_STENCILOP_DECR << GFXS1_STENCIL_FRONT_ZFAIL_SHIFT}, - {"Keep", GFXS_STENCILOP_KEEP << GFXS1_STENCIL_FRONT_ZFAIL_SHIFT}, - } - }, - { - "mtlStencilFuncBack", 1, { - {"Less", GFXS_STENCILFUNC_LESS << GFXS1_STENCIL_BACK_FUNC_SHIFT}, - {"Equal", GFXS_STENCILFUNC_EQUAL << GFXS1_STENCIL_BACK_FUNC_SHIFT}, - {"LessEqual", GFXS_STENCILFUNC_LESSEQUAL << GFXS1_STENCIL_BACK_FUNC_SHIFT}, - {"Greater", GFXS_STENCILFUNC_GREATER << GFXS1_STENCIL_BACK_FUNC_SHIFT}, - {"NotEqual", GFXS_STENCILFUNC_NOTEQUAL << GFXS1_STENCIL_BACK_FUNC_SHIFT}, - {"GreaterEqual", GFXS_STENCILFUNC_GREATEREQUAL << GFXS1_STENCIL_BACK_FUNC_SHIFT}, - {"Always", GFXS_STENCILFUNC_ALWAYS << GFXS1_STENCIL_BACK_FUNC_SHIFT}, - {"Never", GFXS_STENCILFUNC_NEVER << GFXS1_STENCIL_BACK_FUNC_SHIFT}, - } - }, - { - "mtlStencilOpBackPass", 1, { - {"Zero", GFXS_STENCILOP_ZERO << GFXS1_STENCIL_BACK_PASS_SHIFT}, - {"Replace", GFXS_STENCILOP_REPLACE << GFXS1_STENCIL_BACK_PASS_SHIFT}, - {"IncrSat", GFXS_STENCILOP_INCRSAT << GFXS1_STENCIL_BACK_PASS_SHIFT}, - {"DecrSat", GFXS_STENCILOP_DECRSAT << GFXS1_STENCIL_BACK_PASS_SHIFT}, - {"Invert", GFXS_STENCILOP_INVERT << GFXS1_STENCIL_BACK_PASS_SHIFT}, - {"Incr", GFXS_STENCILOP_INCR << GFXS1_STENCIL_BACK_PASS_SHIFT}, - {"Decr", GFXS_STENCILOP_DECR << GFXS1_STENCIL_BACK_PASS_SHIFT}, - {"Keep", GFXS_STENCILOP_KEEP << GFXS1_STENCIL_BACK_PASS_SHIFT}, - } - }, - { - "mtlStencilOpBackFail", 1, { - {"Zero", GFXS_STENCILOP_ZERO << GFXS1_STENCIL_BACK_FAIL_SHIFT}, - {"Replace", GFXS_STENCILOP_REPLACE << GFXS1_STENCIL_BACK_FAIL_SHIFT}, - {"IncrSat", GFXS_STENCILOP_INCRSAT << GFXS1_STENCIL_BACK_FAIL_SHIFT}, - {"DecrSat", GFXS_STENCILOP_DECRSAT << GFXS1_STENCIL_BACK_FAIL_SHIFT}, - {"Invert", GFXS_STENCILOP_INVERT << GFXS1_STENCIL_BACK_FAIL_SHIFT}, - {"Incr", GFXS_STENCILOP_INCR << GFXS1_STENCIL_BACK_FAIL_SHIFT}, - {"Decr", GFXS_STENCILOP_DECR << GFXS1_STENCIL_BACK_FAIL_SHIFT}, - {"Keep", GFXS_STENCILOP_KEEP << GFXS1_STENCIL_BACK_FAIL_SHIFT}, - } - }, - { - "mtlStencilOpBackZFail", 1, { - {"Zero", GFXS_STENCILOP_ZERO << GFXS1_STENCIL_BACK_ZFAIL_SHIFT}, - {"Replace", GFXS_STENCILOP_REPLACE << GFXS1_STENCIL_BACK_ZFAIL_SHIFT}, - {"IncrSat", GFXS_STENCILOP_INCRSAT << GFXS1_STENCIL_BACK_ZFAIL_SHIFT}, - {"DecrSat", GFXS_STENCILOP_DECRSAT << GFXS1_STENCIL_BACK_ZFAIL_SHIFT}, - {"Invert", GFXS_STENCILOP_INVERT << GFXS1_STENCIL_BACK_ZFAIL_SHIFT}, - {"Incr", GFXS_STENCILOP_INCR << GFXS1_STENCIL_BACK_ZFAIL_SHIFT}, - {"Decr", GFXS_STENCILOP_DECR << GFXS1_STENCIL_BACK_ZFAIL_SHIFT}, - {"Keep", GFXS_STENCILOP_KEEP << GFXS1_STENCIL_BACK_ZFAIL_SHIFT}, - } - }, - }); +inline state_map::StateMapLayoutVars stateMapVarLayout({ + {"mtlAlphaTest", + 0, { + {"Always", GFXS0_ATEST_DISABLE}, + {"GE128", GFXS0_ATEST_GE_128}, + {"GT0", GFXS0_ATEST_GT_0}, + {"LT128", GFXS0_ATEST_LT_128}, + }}, + {"mtlBlendOp", + 0, { + {"Add", GFXS_BLENDOP_ADD << GFXS0_BLENDOP_RGB_SHIFT}, + {"Subtract", GFXS_BLENDOP_SUBTRACT << GFXS0_BLENDOP_RGB_SHIFT}, + {"RevSubtract", GFXS_BLENDOP_REVSUBTRACT << GFXS0_BLENDOP_RGB_SHIFT}, + {"Min", GFXS_BLENDOP_MIN << GFXS0_BLENDOP_RGB_SHIFT}, + {"Max", GFXS_BLENDOP_MAX << GFXS0_BLENDOP_RGB_SHIFT}, + {"Disable", GFXS_BLENDOP_DISABLED << GFXS0_BLENDOP_RGB_SHIFT}, + }}, + {"mtlSrcBlend", + 0, { + {"Zero", GFXS_BLEND_ZERO << GFXS0_SRCBLEND_RGB_SHIFT}, + {"One", GFXS_BLEND_ONE << GFXS0_SRCBLEND_RGB_SHIFT}, + {"SrcColor", GFXS_BLEND_SRCCOLOR << GFXS0_SRCBLEND_RGB_SHIFT}, + {"InvSrcColor", GFXS_BLEND_INVSRCCOLOR << GFXS0_SRCBLEND_RGB_SHIFT}, + {"SrcAlpha", GFXS_BLEND_SRCALPHA << GFXS0_SRCBLEND_RGB_SHIFT}, + {"InvSrcAlpha", GFXS_BLEND_INVSRCALPHA << GFXS0_SRCBLEND_RGB_SHIFT}, + {"DestAlpha", GFXS_BLEND_DESTALPHA << GFXS0_SRCBLEND_RGB_SHIFT}, + {"InvDestAlpha", GFXS_BLEND_INVDESTALPHA << GFXS0_SRCBLEND_RGB_SHIFT}, + {"DestColor", GFXS_BLEND_DESTCOLOR << GFXS0_SRCBLEND_RGB_SHIFT}, + {"InvDestColor", GFXS_BLEND_INVDESTCOLOR << GFXS0_SRCBLEND_RGB_SHIFT}, + }}, + {"mtlDestBlend", + 0, { + {"Zero", GFXS_BLEND_ZERO << GFXS0_DSTBLEND_RGB_SHIFT}, + {"One", GFXS_BLEND_ONE << GFXS0_DSTBLEND_RGB_SHIFT}, + {"SrcColor", GFXS_BLEND_SRCCOLOR << GFXS0_DSTBLEND_RGB_SHIFT}, + {"InvSrcColor", GFXS_BLEND_INVSRCCOLOR << GFXS0_DSTBLEND_RGB_SHIFT}, + {"SrcAlpha", GFXS_BLEND_SRCALPHA << GFXS0_DSTBLEND_RGB_SHIFT}, + {"InvSrcAlpha", GFXS_BLEND_INVSRCALPHA << GFXS0_DSTBLEND_RGB_SHIFT}, + {"DestAlpha", GFXS_BLEND_DESTALPHA << GFXS0_DSTBLEND_RGB_SHIFT}, + {"InvDestAlpha", GFXS_BLEND_INVDESTALPHA << GFXS0_DSTBLEND_RGB_SHIFT}, + {"DestColor", GFXS_BLEND_DESTCOLOR << GFXS0_DSTBLEND_RGB_SHIFT}, + {"InvDestColor", GFXS_BLEND_INVDESTCOLOR << GFXS0_DSTBLEND_RGB_SHIFT}, + }}, + {"mtlBlendOpAlpha", + 0, { + {"Add", GFXS_BLENDOP_ADD << GFXS0_BLENDOP_ALPHA_SHIFT}, + {"Subtract", GFXS_BLENDOP_SUBTRACT << GFXS0_BLENDOP_ALPHA_SHIFT}, + {"RevSubtract", GFXS_BLENDOP_REVSUBTRACT << GFXS0_BLENDOP_ALPHA_SHIFT}, + {"Min", GFXS_BLENDOP_MIN << GFXS0_BLENDOP_ALPHA_SHIFT}, + {"Max", GFXS_BLENDOP_MAX << GFXS0_BLENDOP_ALPHA_SHIFT}, + {"Disable", GFXS_BLENDOP_DISABLED << GFXS0_BLENDOP_ALPHA_SHIFT}, + }}, + {"mtlSrcBlendAlpha", + 0, { + {"Zero", GFXS_BLEND_ZERO << GFXS0_SRCBLEND_ALPHA_SHIFT}, + {"One", GFXS_BLEND_ONE << GFXS0_SRCBLEND_ALPHA_SHIFT}, + {"SrcColor", GFXS_BLEND_SRCCOLOR << GFXS0_SRCBLEND_ALPHA_SHIFT}, + {"InvSrcColor", GFXS_BLEND_INVSRCCOLOR << GFXS0_SRCBLEND_ALPHA_SHIFT}, + {"SrcAlpha", GFXS_BLEND_SRCALPHA << GFXS0_SRCBLEND_ALPHA_SHIFT}, + {"InvSrcAlpha", GFXS_BLEND_INVSRCALPHA << GFXS0_SRCBLEND_ALPHA_SHIFT}, + {"DestAlpha", GFXS_BLEND_DESTALPHA << GFXS0_SRCBLEND_ALPHA_SHIFT}, + {"InvDestAlpha", GFXS_BLEND_INVDESTALPHA << GFXS0_SRCBLEND_ALPHA_SHIFT}, + {"DestColor", GFXS_BLEND_DESTCOLOR << GFXS0_SRCBLEND_ALPHA_SHIFT}, + {"InvDestColor", GFXS_BLEND_INVDESTCOLOR << GFXS0_SRCBLEND_ALPHA_SHIFT}, + }}, + {"mtlDestBlendAlpha", + 0, { + {"Zero", GFXS_BLEND_ZERO << GFXS0_DSTBLEND_ALPHA_SHIFT}, + {"One", GFXS_BLEND_ONE << GFXS0_DSTBLEND_ALPHA_SHIFT}, + {"SrcColor", GFXS_BLEND_SRCCOLOR << GFXS0_DSTBLEND_ALPHA_SHIFT}, + {"InvSrcColor", GFXS_BLEND_INVSRCCOLOR << GFXS0_DSTBLEND_ALPHA_SHIFT}, + {"SrcAlpha", GFXS_BLEND_SRCALPHA << GFXS0_DSTBLEND_ALPHA_SHIFT}, + {"InvSrcAlpha", GFXS_BLEND_INVSRCALPHA << GFXS0_DSTBLEND_ALPHA_SHIFT}, + {"DestAlpha", GFXS_BLEND_DESTALPHA << GFXS0_DSTBLEND_ALPHA_SHIFT}, + {"InvDestAlpha", GFXS_BLEND_INVDESTALPHA << GFXS0_DSTBLEND_ALPHA_SHIFT}, + {"DestColor", GFXS_BLEND_DESTCOLOR << GFXS0_DSTBLEND_ALPHA_SHIFT}, + {"InvDestColor", GFXS_BLEND_INVDESTCOLOR << GFXS0_DSTBLEND_ALPHA_SHIFT}, + }}, + {"mtlCullFace", + 0, { + {"None", GFXS0_CULL_NONE}, + {"Back", GFXS0_CULL_BACK}, + {"Front", GFXS0_CULL_FRONT}, + }}, + {"mtlColorWriteRgb", + 0, { + {"Enable", GFXS0_COLORWRITE_RGB}, + {"Disable", 0}, + }}, + {"mtlColorWriteAlpha", + 0, { + {"Enable", GFXS0_COLORWRITE_ALPHA}, + {"Disable", 0}, + }}, + {"mtlGammaWrite", + 0, { + {"Enable", GFXS0_GAMMAWRITE}, + {"Disable", 0}, + }}, + {"mtlWireframe", + 0, { + {"Enable", GFXS0_POLYMODE_LINE}, + {"Disable", 0}, + }}, + {"mtlDepthTest", + 1, { + {"Disable", GFXS1_DEPTHTEST_DISABLE}, + {"Less", GFXS1_DEPTHTEST_LESS}, + {"LessEqual", GFXS1_DEPTHTEST_LESSEQUAL}, + {"Equal", GFXS1_DEPTHTEST_EQUAL}, + {"Always", GFXS1_DEPTHTEST_ALWAYS}, + }}, + {"mtlDepthWrite", + 1, { + {"Enable", GFXS1_DEPTHWRITE}, + {"Disable", 0}, + }}, + {"mtlPolygonOffset", + 1, { + {"1", GFXS1_POLYGON_OFFSET_1}, + {"2", GFXS1_POLYGON_OFFSET_2}, + {"shadowmap", GFXS1_POLYGON_OFFSET_SHADOWMAP}, + {"0", GFXS1_POLYGON_OFFSET_0}, + }}, + {"mtlStencil", + 1, { + {"OneSided", GFXS1_STENCIL_FRONT_ENABLE}, + {"TwoSided", GFXS1_STENCIL_FRONT_ENABLE | GFXS1_STENCIL_BACK_ENABLE}, + {"Disable", 0}, + }}, + {"mtlStencilFuncFront", + 1, { + {"Less", GFXS_STENCILFUNC_LESS << GFXS1_STENCIL_FRONT_FUNC_SHIFT}, + {"Equal", GFXS_STENCILFUNC_EQUAL << GFXS1_STENCIL_FRONT_FUNC_SHIFT}, + {"LessEqual", GFXS_STENCILFUNC_LESSEQUAL << GFXS1_STENCIL_FRONT_FUNC_SHIFT}, + {"Greater", GFXS_STENCILFUNC_GREATER << GFXS1_STENCIL_FRONT_FUNC_SHIFT}, + {"NotEqual", GFXS_STENCILFUNC_NOTEQUAL << GFXS1_STENCIL_FRONT_FUNC_SHIFT}, + {"GreaterEqual", GFXS_STENCILFUNC_GREATEREQUAL << GFXS1_STENCIL_FRONT_FUNC_SHIFT}, + {"Always", GFXS_STENCILFUNC_ALWAYS << GFXS1_STENCIL_FRONT_FUNC_SHIFT}, + {"Never", GFXS_STENCILFUNC_NEVER << GFXS1_STENCIL_FRONT_FUNC_SHIFT}, + }}, + {"mtlStencilOpFrontPass", + 1, { + {"Zero", GFXS_STENCILOP_ZERO << GFXS1_STENCIL_FRONT_PASS_SHIFT}, + {"Replace", GFXS_STENCILOP_REPLACE << GFXS1_STENCIL_FRONT_PASS_SHIFT}, + {"IncrSat", GFXS_STENCILOP_INCRSAT << GFXS1_STENCIL_FRONT_PASS_SHIFT}, + {"DecrSat", GFXS_STENCILOP_DECRSAT << GFXS1_STENCIL_FRONT_PASS_SHIFT}, + {"Invert", GFXS_STENCILOP_INVERT << GFXS1_STENCIL_FRONT_PASS_SHIFT}, + {"Incr", GFXS_STENCILOP_INCR << GFXS1_STENCIL_FRONT_PASS_SHIFT}, + {"Decr", GFXS_STENCILOP_DECR << GFXS1_STENCIL_FRONT_PASS_SHIFT}, + {"Keep", GFXS_STENCILOP_KEEP << GFXS1_STENCIL_FRONT_PASS_SHIFT}, + }}, + {"mtlStencilOpFrontFail", + 1, { + {"Zero", GFXS_STENCILOP_ZERO << GFXS1_STENCIL_FRONT_FAIL_SHIFT}, + {"Replace", GFXS_STENCILOP_REPLACE << GFXS1_STENCIL_FRONT_FAIL_SHIFT}, + {"IncrSat", GFXS_STENCILOP_INCRSAT << GFXS1_STENCIL_FRONT_FAIL_SHIFT}, + {"DecrSat", GFXS_STENCILOP_DECRSAT << GFXS1_STENCIL_FRONT_FAIL_SHIFT}, + {"Invert", GFXS_STENCILOP_INVERT << GFXS1_STENCIL_FRONT_FAIL_SHIFT}, + {"Incr", GFXS_STENCILOP_INCR << GFXS1_STENCIL_FRONT_FAIL_SHIFT}, + {"Decr", GFXS_STENCILOP_DECR << GFXS1_STENCIL_FRONT_FAIL_SHIFT}, + {"Keep", GFXS_STENCILOP_KEEP << GFXS1_STENCIL_FRONT_FAIL_SHIFT}, + }}, + {"mtlStencilOpFrontZFail", + 1, { + {"Zero", GFXS_STENCILOP_ZERO << GFXS1_STENCIL_FRONT_ZFAIL_SHIFT}, + {"Replace", GFXS_STENCILOP_REPLACE << GFXS1_STENCIL_FRONT_ZFAIL_SHIFT}, + {"IncrSat", GFXS_STENCILOP_INCRSAT << GFXS1_STENCIL_FRONT_ZFAIL_SHIFT}, + {"DecrSat", GFXS_STENCILOP_DECRSAT << GFXS1_STENCIL_FRONT_ZFAIL_SHIFT}, + {"Invert", GFXS_STENCILOP_INVERT << GFXS1_STENCIL_FRONT_ZFAIL_SHIFT}, + {"Incr", GFXS_STENCILOP_INCR << GFXS1_STENCIL_FRONT_ZFAIL_SHIFT}, + {"Decr", GFXS_STENCILOP_DECR << GFXS1_STENCIL_FRONT_ZFAIL_SHIFT}, + {"Keep", GFXS_STENCILOP_KEEP << GFXS1_STENCIL_FRONT_ZFAIL_SHIFT}, + }}, + {"mtlStencilFuncBack", + 1, { + {"Less", GFXS_STENCILFUNC_LESS << GFXS1_STENCIL_BACK_FUNC_SHIFT}, + {"Equal", GFXS_STENCILFUNC_EQUAL << GFXS1_STENCIL_BACK_FUNC_SHIFT}, + {"LessEqual", GFXS_STENCILFUNC_LESSEQUAL << GFXS1_STENCIL_BACK_FUNC_SHIFT}, + {"Greater", GFXS_STENCILFUNC_GREATER << GFXS1_STENCIL_BACK_FUNC_SHIFT}, + {"NotEqual", GFXS_STENCILFUNC_NOTEQUAL << GFXS1_STENCIL_BACK_FUNC_SHIFT}, + {"GreaterEqual", GFXS_STENCILFUNC_GREATEREQUAL << GFXS1_STENCIL_BACK_FUNC_SHIFT}, + {"Always", GFXS_STENCILFUNC_ALWAYS << GFXS1_STENCIL_BACK_FUNC_SHIFT}, + {"Never", GFXS_STENCILFUNC_NEVER << GFXS1_STENCIL_BACK_FUNC_SHIFT}, + }}, + {"mtlStencilOpBackPass", + 1, { + {"Zero", GFXS_STENCILOP_ZERO << GFXS1_STENCIL_BACK_PASS_SHIFT}, + {"Replace", GFXS_STENCILOP_REPLACE << GFXS1_STENCIL_BACK_PASS_SHIFT}, + {"IncrSat", GFXS_STENCILOP_INCRSAT << GFXS1_STENCIL_BACK_PASS_SHIFT}, + {"DecrSat", GFXS_STENCILOP_DECRSAT << GFXS1_STENCIL_BACK_PASS_SHIFT}, + {"Invert", GFXS_STENCILOP_INVERT << GFXS1_STENCIL_BACK_PASS_SHIFT}, + {"Incr", GFXS_STENCILOP_INCR << GFXS1_STENCIL_BACK_PASS_SHIFT}, + {"Decr", GFXS_STENCILOP_DECR << GFXS1_STENCIL_BACK_PASS_SHIFT}, + {"Keep", GFXS_STENCILOP_KEEP << GFXS1_STENCIL_BACK_PASS_SHIFT}, + }}, + {"mtlStencilOpBackFail", + 1, { + {"Zero", GFXS_STENCILOP_ZERO << GFXS1_STENCIL_BACK_FAIL_SHIFT}, + {"Replace", GFXS_STENCILOP_REPLACE << GFXS1_STENCIL_BACK_FAIL_SHIFT}, + {"IncrSat", GFXS_STENCILOP_INCRSAT << GFXS1_STENCIL_BACK_FAIL_SHIFT}, + {"DecrSat", GFXS_STENCILOP_DECRSAT << GFXS1_STENCIL_BACK_FAIL_SHIFT}, + {"Invert", GFXS_STENCILOP_INVERT << GFXS1_STENCIL_BACK_FAIL_SHIFT}, + {"Incr", GFXS_STENCILOP_INCR << GFXS1_STENCIL_BACK_FAIL_SHIFT}, + {"Decr", GFXS_STENCILOP_DECR << GFXS1_STENCIL_BACK_FAIL_SHIFT}, + {"Keep", GFXS_STENCILOP_KEEP << GFXS1_STENCIL_BACK_FAIL_SHIFT}, + }}, + {"mtlStencilOpBackZFail", + 1, { + {"Zero", GFXS_STENCILOP_ZERO << GFXS1_STENCIL_BACK_ZFAIL_SHIFT}, + {"Replace", GFXS_STENCILOP_REPLACE << GFXS1_STENCIL_BACK_ZFAIL_SHIFT}, + {"IncrSat", GFXS_STENCILOP_INCRSAT << GFXS1_STENCIL_BACK_ZFAIL_SHIFT}, + {"DecrSat", GFXS_STENCILOP_DECRSAT << GFXS1_STENCIL_BACK_ZFAIL_SHIFT}, + {"Invert", GFXS_STENCILOP_INVERT << GFXS1_STENCIL_BACK_ZFAIL_SHIFT}, + {"Incr", GFXS_STENCILOP_INCR << GFXS1_STENCIL_BACK_ZFAIL_SHIFT}, + {"Decr", GFXS_STENCILOP_DECR << GFXS1_STENCIL_BACK_ZFAIL_SHIFT}, + {"Keep", GFXS_STENCILOP_KEEP << GFXS1_STENCIL_BACK_ZFAIL_SHIFT}, + }}, +}); - inline state_map::StateMapLayout stateMapLayout(std::extent_v, stateMapEntryLayout, stateMapVarLayout); -} +inline state_map::StateMapLayout stateMapLayout(std::extent_v, stateMapEntryLayout, stateMapVarLayout); +} // namespace IW4 diff --git a/src/ObjCommon/Game/IW5/MenuConstantsIW5.h b/src/ObjCommon/Game/IW5/MenuConstantsIW5.h index 390d47c93..713510d04 100644 --- a/src/ObjCommon/Game/IW5/MenuConstantsIW5.h +++ b/src/ObjCommon/Game/IW5/MenuConstantsIW5.h @@ -2,385 +2,382 @@ #include "Game/IW5/IW5.h" -namespace IW5 -{ - inline const char* g_expFunctionNames[] - { - "NOOP", - ")", - "*", - "/", - "%", - "+", - "-", - "!", - "<", - "<=", - ">", - ">=", - "==", - "!=", - "&&", - "||", - "(", - ",", - "&", - "|", - "~", - "<<", - ">>", - "dvarint(static)", - "dvarbool(static)", - "dvarfloat(static)", - "dvarstring(static)", - "int", - "string", - "float", - "sin", - "cos", - "min", - "max", - "milliseconds", - "localclientuimilliseconds", - "dvarint", - "dvarbool", - "dvarfloat", - "dvarstring", - "ui_active", - "flashbanged", - "usingvehicle", - "missilecam", - "scoped", - "scopedthermal", - "scoreboard_visible", - "inkillcam", - "inkillcamnpc", - "player", - "getperk", - "selecting_location", - "selecting_direction", - "team", - "otherteam", - "marinesfield", - "opforfield", - "menuisopen", - "writingdata", - "inlobby", - "ingamelobby", - "inprivateparty", - "privatepartyhost", - "privatepartyhostinlobby", - "aloneinparty", - "adsjavelin", - "weaplockblink", - "weapattacktop", - "weapattackdirect", - "weaplocking", - "weaplocked", - "weaplocktooclose", - "weaplockscreenposx", - "weaplockscreenposy", - "secondsastime", - "tablelookup", - "tablelookupbyrow", - "tablegetrownum", - "locstring", - "localvarint", - "localvarbool", - "localvarfloat", - "localvarstring", - "timeleft", - "secondsascountdown", - "gamemsgwndactive", - "gametypename", - "gametype", - "gametypedescription", - "scoreatrank", - "spectatingclient", - "spectatingfree", - "keybinding", - "actionslotusable", - "hudfade", - "maxrecommendedplayers", - "acceptinginvite", - "isintermission", - "gamehost", - "partyismissingmappack", - "partymissingmappackerror", - "anynewmappacks", - "amiselected", - "partystatusstring", - "attachedcontrollercount", - "issplitscreenonlinepossible", - "splitscreenplayercount", - "getplayerdata", - "getplayerdatasplitscreen", - "getmatchrulesdata", - "getsavedmatchrulesmetadata", - "levelforexperiencemp", - "levelforexperienceso", - "isitemunlocked", - "isitemunlockedsplitscreen", - "iscardiconunlocked", - "iscardtitleunlocked", - "iscardiconnew", - "iscardtitlenew", - "iscardiconunlockedsplitscreen", - "iscardtitleunlockedsplitscreen", - "iscardiconnewsplitscreen", - "iscardtitlenewsplitscreen", - "isprofileitemunlocked", - "isprofileitemunlockedsplitscreen", - "isprofileitemnew", - "isprofileitemnewsplitscreen", - "debugprint", - "getplayerdataanybooltrue", - "getprofileanybooltrue", - "weaponclassnew", - "weaponname", - "isreloading", - "savegameavailable", - "unlockeditemcount", - "unlockeditemcountsplitscreen", - "unlockeditem", - "unlockeditemsplitscreen", - "radarisjammed", - "radarjamintensity", - "radarisenabled", - "isempjammed", - "playerads", - "weaponheatactive", - "weaponheatvalue", - "weaponheatoverheated", - "getsplashtext", - "getsplashdescription", - "getsplashmaterial", - "splashhasicon", - "splashrownum", - "getfocuseditemname", - "getfocuseditemx", - "getfocuseditemy", - "getfocuseditemwidth", - "getfocuseditemheight", - "getitemx", - "getitemy", - "getitemwidth", - "getitemheight", - "playlist", - "scoreboardexternalmutenotice", - "getclientmatchdata", - "getclientmatchdatadef", - "getmapname", - "getmapimage", - "getmapcustom", - "getmigrationstatus", - "getplayercardinfo", - "isofflineprofileselected", - "coopplayer", - "iscoop", - "getpartystatus", - "getsearchparams", - "gettimeplayed", - "isselectedplayerfriend", - "getcharbyindex", - "getprofiledata", - "getprofiledatasplitscreen", - "isprofilesignedin", - "getwaitpopupstatus", - "getnattype", - "getlocalizednattype", - "getadjustedsafeareahorizontal", - "getadjustedsafeareavertical", - "connectioninfo", - "offlineprofilecansave", - "userwithoutofflineprofilewarning", - "allsplitscreenprofilescansave", - "allsplitscreenprofilesaresignedin", - "dowehavemappack", - "mayinviteplayertoparty", - "getpatchnotes", - "getgameinfos", - "coopready", - "votecast", - "votepassed", - "getmapvotemapimage", - "getmapvotemapname", - "mapvotegametypename", - "isfriendinvitable", - "isfriendjoinable", - "getsortedchallengeindex", - "getsortedchallengename", - "getsortedchallengecount", - "getfilterchallengecount", - "getfilterchallengelockedcount", - "getfilterchallengecompletecount", - "issortedchallengetiered", - "getchallengefiltercachecount", - "getchallengefiltercachecompletecount", - "iscoopsearching", - "coopshowpublictype", - "coopdisplayablegroupnum", - "coophasrequiredonlinefiles", - "getTextWidth", - "getTextHeight", - "isdeveloper", - "isusingairburst", - "getairburstmeters", - "getcrosshairtracemeters", - "getfacebookstatustext", - "isfacebookloggedin", - "isfacebookchecking", - "isfacebookallowed", - "getprivatepartystatus", - "includedinmaprotation", - "select", - "isdemoplaying", - "getusergrouptext", - "getusergroupcommoninteresttotal", - "isdemofollowcamera", - "isdemofreecamera", - "isdemocapturingscreenshot", - "ispartyhostwaitingonmembers", - "ispopuppartymemberaway", - "isselectedpartymemberaway", - "gettime", - "gameendtime", - "hasfocus", - "menuhasfocus", - "getdemosegmentcount", - "getdemosegmentinformation", - "isclipmodified", - "isusingmatchrulesdata", - "isguest", - "getfacebookhelptext", - "iseliteclanallowed", - "isentitlementsallowed", - "isusergroupsallowed", - "iswaitingforonlineservices", - "getTextWidthModCase", - "getSaveScreenTitle", - "getSaveScreenDescription", - "getOnlineVaultSelectedItemData", - "isOnlineVaultRestricted", - "isContentServerTaskInProgress", - "getContentServerTaskProgress", - "getRecentGamesSelectedItemData", - "gametypenameAbbreviated", - "mapvotegametypenameAbbreviated", - "isusersignedintolive", - "usercanplayonline", - "getPastTitleRank", - "getFeederData", - "partyclientsuptodate", - "truncateTextWithEllipsis", - "uistarted", - "canRenderClip", - "getpreviewmapcustom", - "getdlcmapsavailablecount", - "isusersignedin", - "isUsingIntermissionTimer", - "isUsingCustomMapRotation", - "menuistopmost", - "facebook_isplatfromfriend", - "eliteclan_isplatfromfriend", - "eliteclan_isme", - "eliteclan_isleader", - "isusersignedinforvault", - "getusingmatchrulesdata", - "canuseraccessonlinevault", - "friend_getgamertag", - "recentplayer_getgamertag", - "liveparty_getgamertag", - "facebook_getgamertag", - "eliteclan_getgamertag", - "liveparty_isme", - "liveparty_islocal", - "doubleclickwasrightclick", - "isdemocliprecording", - "getIndexFromString", - "getStringWithoutIndex", - "eliteclan_getname", - "eliteclan_gethelp", - "eliteclan_getmotd", - "eliteclan_ismember", - "eliteclan_isemblem_ok", - "facebook_friends_show_next", - "facebook_friends_show_prev", - "getOnlineVaultFriendGamerTag", - "getObjectiveListHeight", - "isClientDemoEnabled", - "isusersignedintodemonware", - "customClassIsRestricted", - "weaponIsRestricted", - "anysplitscreenprofilesaresignedin", - "isguestsplitscreen", - "isitemunlockedbyclient", - "isanyusersignedintolive", - "getPastTitlePrestige", - "splitscreenactivegamepadcount", - "showFriendPlayercard", - "getFriendPlayercardPresence", - "showRecentPlayerGroupIcon", - "getwrappedtextheight", - "canClientSave", - "getgameinvitescount", - "issplitscreengamerliveenabled", - "so_coopShowCommonGroupIcon", - "stripColorsFromString", - "DEPRECATED", - "ischallengeperiodic", - "getchallengedata", - "iseliteapppresent", - "eliteclan_selectedisme", - "enoughStorageSpaceForClientDemo", - "isusersignedinforcommerce", - "getfacebookmenutext", - "getfacebookisposting", - "meetplayer_isplatformfriend", - "isselectedplayerguest", - "getsplitscreencontrollerclientnum", - "isClientDemoEnabledSplitScreen", - "ItemCanTakeFocus", - "getTimeSinceLastDoubleClick", - "isServerListRefreshing", - "isRecipeNameValid", - "recipeExists", - "getfacebookoptionshelptext", - "dowehaveallavailablemappacks", - "isThereNewEliteItems", - "isPayingSubscriber", - "localuser_ismissingmappack", - "localuser_missingmappackerror", - "getFirstSpecOpsDLCMap", - "localuser_missingmapname", - "showStoreNew", - "commerce_getstatus", - "isManifestDownloaded", - "areAllItemsUnlocked", - "commerce_getstatuscond", - "doWeHaveMissingOwnedContent", - }; +namespace IW5 { +inline const char *g_expFunctionNames[]{ + "NOOP", + ")", + "*", + "/", + "%", + "+", + "-", + "!", + "<", + "<=", + ">", + ">=", + "==", + "!=", + "&&", + "||", + "(", + ",", + "&", + "|", + "~", + "<<", + ">>", + "dvarint(static)", + "dvarbool(static)", + "dvarfloat(static)", + "dvarstring(static)", + "int", + "string", + "float", + "sin", + "cos", + "min", + "max", + "milliseconds", + "localclientuimilliseconds", + "dvarint", + "dvarbool", + "dvarfloat", + "dvarstring", + "ui_active", + "flashbanged", + "usingvehicle", + "missilecam", + "scoped", + "scopedthermal", + "scoreboard_visible", + "inkillcam", + "inkillcamnpc", + "player", + "getperk", + "selecting_location", + "selecting_direction", + "team", + "otherteam", + "marinesfield", + "opforfield", + "menuisopen", + "writingdata", + "inlobby", + "ingamelobby", + "inprivateparty", + "privatepartyhost", + "privatepartyhostinlobby", + "aloneinparty", + "adsjavelin", + "weaplockblink", + "weapattacktop", + "weapattackdirect", + "weaplocking", + "weaplocked", + "weaplocktooclose", + "weaplockscreenposx", + "weaplockscreenposy", + "secondsastime", + "tablelookup", + "tablelookupbyrow", + "tablegetrownum", + "locstring", + "localvarint", + "localvarbool", + "localvarfloat", + "localvarstring", + "timeleft", + "secondsascountdown", + "gamemsgwndactive", + "gametypename", + "gametype", + "gametypedescription", + "scoreatrank", + "spectatingclient", + "spectatingfree", + "keybinding", + "actionslotusable", + "hudfade", + "maxrecommendedplayers", + "acceptinginvite", + "isintermission", + "gamehost", + "partyismissingmappack", + "partymissingmappackerror", + "anynewmappacks", + "amiselected", + "partystatusstring", + "attachedcontrollercount", + "issplitscreenonlinepossible", + "splitscreenplayercount", + "getplayerdata", + "getplayerdatasplitscreen", + "getmatchrulesdata", + "getsavedmatchrulesmetadata", + "levelforexperiencemp", + "levelforexperienceso", + "isitemunlocked", + "isitemunlockedsplitscreen", + "iscardiconunlocked", + "iscardtitleunlocked", + "iscardiconnew", + "iscardtitlenew", + "iscardiconunlockedsplitscreen", + "iscardtitleunlockedsplitscreen", + "iscardiconnewsplitscreen", + "iscardtitlenewsplitscreen", + "isprofileitemunlocked", + "isprofileitemunlockedsplitscreen", + "isprofileitemnew", + "isprofileitemnewsplitscreen", + "debugprint", + "getplayerdataanybooltrue", + "getprofileanybooltrue", + "weaponclassnew", + "weaponname", + "isreloading", + "savegameavailable", + "unlockeditemcount", + "unlockeditemcountsplitscreen", + "unlockeditem", + "unlockeditemsplitscreen", + "radarisjammed", + "radarjamintensity", + "radarisenabled", + "isempjammed", + "playerads", + "weaponheatactive", + "weaponheatvalue", + "weaponheatoverheated", + "getsplashtext", + "getsplashdescription", + "getsplashmaterial", + "splashhasicon", + "splashrownum", + "getfocuseditemname", + "getfocuseditemx", + "getfocuseditemy", + "getfocuseditemwidth", + "getfocuseditemheight", + "getitemx", + "getitemy", + "getitemwidth", + "getitemheight", + "playlist", + "scoreboardexternalmutenotice", + "getclientmatchdata", + "getclientmatchdatadef", + "getmapname", + "getmapimage", + "getmapcustom", + "getmigrationstatus", + "getplayercardinfo", + "isofflineprofileselected", + "coopplayer", + "iscoop", + "getpartystatus", + "getsearchparams", + "gettimeplayed", + "isselectedplayerfriend", + "getcharbyindex", + "getprofiledata", + "getprofiledatasplitscreen", + "isprofilesignedin", + "getwaitpopupstatus", + "getnattype", + "getlocalizednattype", + "getadjustedsafeareahorizontal", + "getadjustedsafeareavertical", + "connectioninfo", + "offlineprofilecansave", + "userwithoutofflineprofilewarning", + "allsplitscreenprofilescansave", + "allsplitscreenprofilesaresignedin", + "dowehavemappack", + "mayinviteplayertoparty", + "getpatchnotes", + "getgameinfos", + "coopready", + "votecast", + "votepassed", + "getmapvotemapimage", + "getmapvotemapname", + "mapvotegametypename", + "isfriendinvitable", + "isfriendjoinable", + "getsortedchallengeindex", + "getsortedchallengename", + "getsortedchallengecount", + "getfilterchallengecount", + "getfilterchallengelockedcount", + "getfilterchallengecompletecount", + "issortedchallengetiered", + "getchallengefiltercachecount", + "getchallengefiltercachecompletecount", + "iscoopsearching", + "coopshowpublictype", + "coopdisplayablegroupnum", + "coophasrequiredonlinefiles", + "getTextWidth", + "getTextHeight", + "isdeveloper", + "isusingairburst", + "getairburstmeters", + "getcrosshairtracemeters", + "getfacebookstatustext", + "isfacebookloggedin", + "isfacebookchecking", + "isfacebookallowed", + "getprivatepartystatus", + "includedinmaprotation", + "select", + "isdemoplaying", + "getusergrouptext", + "getusergroupcommoninteresttotal", + "isdemofollowcamera", + "isdemofreecamera", + "isdemocapturingscreenshot", + "ispartyhostwaitingonmembers", + "ispopuppartymemberaway", + "isselectedpartymemberaway", + "gettime", + "gameendtime", + "hasfocus", + "menuhasfocus", + "getdemosegmentcount", + "getdemosegmentinformation", + "isclipmodified", + "isusingmatchrulesdata", + "isguest", + "getfacebookhelptext", + "iseliteclanallowed", + "isentitlementsallowed", + "isusergroupsallowed", + "iswaitingforonlineservices", + "getTextWidthModCase", + "getSaveScreenTitle", + "getSaveScreenDescription", + "getOnlineVaultSelectedItemData", + "isOnlineVaultRestricted", + "isContentServerTaskInProgress", + "getContentServerTaskProgress", + "getRecentGamesSelectedItemData", + "gametypenameAbbreviated", + "mapvotegametypenameAbbreviated", + "isusersignedintolive", + "usercanplayonline", + "getPastTitleRank", + "getFeederData", + "partyclientsuptodate", + "truncateTextWithEllipsis", + "uistarted", + "canRenderClip", + "getpreviewmapcustom", + "getdlcmapsavailablecount", + "isusersignedin", + "isUsingIntermissionTimer", + "isUsingCustomMapRotation", + "menuistopmost", + "facebook_isplatfromfriend", + "eliteclan_isplatfromfriend", + "eliteclan_isme", + "eliteclan_isleader", + "isusersignedinforvault", + "getusingmatchrulesdata", + "canuseraccessonlinevault", + "friend_getgamertag", + "recentplayer_getgamertag", + "liveparty_getgamertag", + "facebook_getgamertag", + "eliteclan_getgamertag", + "liveparty_isme", + "liveparty_islocal", + "doubleclickwasrightclick", + "isdemocliprecording", + "getIndexFromString", + "getStringWithoutIndex", + "eliteclan_getname", + "eliteclan_gethelp", + "eliteclan_getmotd", + "eliteclan_ismember", + "eliteclan_isemblem_ok", + "facebook_friends_show_next", + "facebook_friends_show_prev", + "getOnlineVaultFriendGamerTag", + "getObjectiveListHeight", + "isClientDemoEnabled", + "isusersignedintodemonware", + "customClassIsRestricted", + "weaponIsRestricted", + "anysplitscreenprofilesaresignedin", + "isguestsplitscreen", + "isitemunlockedbyclient", + "isanyusersignedintolive", + "getPastTitlePrestige", + "splitscreenactivegamepadcount", + "showFriendPlayercard", + "getFriendPlayercardPresence", + "showRecentPlayerGroupIcon", + "getwrappedtextheight", + "canClientSave", + "getgameinvitescount", + "issplitscreengamerliveenabled", + "so_coopShowCommonGroupIcon", + "stripColorsFromString", + "DEPRECATED", + "ischallengeperiodic", + "getchallengedata", + "iseliteapppresent", + "eliteclan_selectedisme", + "enoughStorageSpaceForClientDemo", + "isusersignedinforcommerce", + "getfacebookmenutext", + "getfacebookisposting", + "meetplayer_isplatformfriend", + "isselectedplayerguest", + "getsplitscreencontrollerclientnum", + "isClientDemoEnabledSplitScreen", + "ItemCanTakeFocus", + "getTimeSinceLastDoubleClick", + "isServerListRefreshing", + "isRecipeNameValid", + "recipeExists", + "getfacebookoptionshelptext", + "dowehaveallavailablemappacks", + "isThereNewEliteItems", + "isPayingSubscriber", + "localuser_ismissingmappack", + "localuser_missingmappackerror", + "getFirstSpecOpsDLCMap", + "localuser_missingmapname", + "showStoreNew", + "commerce_getstatus", + "isManifestDownloaded", + "areAllItemsUnlocked", + "commerce_getstatuscond", + "doWeHaveMissingOwnedContent", +}; - inline const ItemExpressionTargetBinding floatExpressionTargetBindings[ITEM_FLOATEXP_TGT_COUNT] - { - {ITEM_FLOATEXP_TGT_RECT_X, "rect", "x"}, - {ITEM_FLOATEXP_TGT_RECT_Y, "rect", "y"}, - {ITEM_FLOATEXP_TGT_RECT_W, "rect", "w"}, - {ITEM_FLOATEXP_TGT_RECT_H, "rect", "h"}, - {ITEM_FLOATEXP_TGT_FORECOLOR_R, "forecolor", "r"}, - {ITEM_FLOATEXP_TGT_FORECOLOR_G, "forecolor", "g"}, - {ITEM_FLOATEXP_TGT_FORECOLOR_B, "forecolor", "b"}, - {ITEM_FLOATEXP_TGT_FORECOLOR_RGB, "forecolor", "rgb"}, - {ITEM_FLOATEXP_TGT_FORECOLOR_A, "forecolor", "a"}, - {ITEM_FLOATEXP_TGT_GLOWCOLOR_R, "glowcolor", "r"}, - {ITEM_FLOATEXP_TGT_GLOWCOLOR_G, "glowcolor", "g"}, - {ITEM_FLOATEXP_TGT_GLOWCOLOR_B, "glowcolor", "b"}, - {ITEM_FLOATEXP_TGT_GLOWCOLOR_RGB, "glowcolor", "rgb"}, - {ITEM_FLOATEXP_TGT_GLOWCOLOR_A, "glowcolor", "a"}, - {ITEM_FLOATEXP_TGT_BACKCOLOR_R, "backcolor", "r"}, - {ITEM_FLOATEXP_TGT_BACKCOLOR_G, "backcolor", "g"}, - {ITEM_FLOATEXP_TGT_BACKCOLOR_B, "backcolor", "b"}, - {ITEM_FLOATEXP_TGT_BACKCOLOR_RGB, "backcolor", "rgb"}, - {ITEM_FLOATEXP_TGT_BACKCOLOR_A, "backcolor", "a"}, - }; -} +inline const ItemExpressionTargetBinding floatExpressionTargetBindings[ITEM_FLOATEXP_TGT_COUNT]{ + {ITEM_FLOATEXP_TGT_RECT_X, "rect", "x" }, + {ITEM_FLOATEXP_TGT_RECT_Y, "rect", "y" }, + {ITEM_FLOATEXP_TGT_RECT_W, "rect", "w" }, + {ITEM_FLOATEXP_TGT_RECT_H, "rect", "h" }, + {ITEM_FLOATEXP_TGT_FORECOLOR_R, "forecolor", "r" }, + {ITEM_FLOATEXP_TGT_FORECOLOR_G, "forecolor", "g" }, + {ITEM_FLOATEXP_TGT_FORECOLOR_B, "forecolor", "b" }, + {ITEM_FLOATEXP_TGT_FORECOLOR_RGB, "forecolor", "rgb"}, + {ITEM_FLOATEXP_TGT_FORECOLOR_A, "forecolor", "a" }, + {ITEM_FLOATEXP_TGT_GLOWCOLOR_R, "glowcolor", "r" }, + {ITEM_FLOATEXP_TGT_GLOWCOLOR_G, "glowcolor", "g" }, + {ITEM_FLOATEXP_TGT_GLOWCOLOR_B, "glowcolor", "b" }, + {ITEM_FLOATEXP_TGT_GLOWCOLOR_RGB, "glowcolor", "rgb"}, + {ITEM_FLOATEXP_TGT_GLOWCOLOR_A, "glowcolor", "a" }, + {ITEM_FLOATEXP_TGT_BACKCOLOR_R, "backcolor", "r" }, + {ITEM_FLOATEXP_TGT_BACKCOLOR_G, "backcolor", "g" }, + {ITEM_FLOATEXP_TGT_BACKCOLOR_B, "backcolor", "b" }, + {ITEM_FLOATEXP_TGT_BACKCOLOR_RGB, "backcolor", "rgb"}, + {ITEM_FLOATEXP_TGT_BACKCOLOR_A, "backcolor", "a" }, +}; +} // namespace IW5 diff --git a/src/ObjCommon/Game/IW5/ObjConstantsIW5.h b/src/ObjCommon/Game/IW5/ObjConstantsIW5.h index d6aa36452..5e727f45f 100644 --- a/src/ObjCommon/Game/IW5/ObjConstantsIW5.h +++ b/src/ObjCommon/Game/IW5/ObjConstantsIW5.h @@ -1,20 +1,18 @@ #pragma once -namespace IW5 -{ - class ObjConstants - { - ObjConstants() = default; +namespace IW5 { +class ObjConstants { + ObjConstants() = default; - public: - static constexpr const char* INFO_STRING_PREFIX_PHYS_PRESET = "PHYSIC"; - static constexpr const char* INFO_STRING_PREFIX_TRACER = "TRACER"; - static constexpr const char* INFO_STRING_PREFIX_VEHICLE = "VEHICLEFILE"; - static constexpr const char* INFO_STRING_PREFIX_WEAPON = "WEAPONFILE"; +public: + static constexpr const char *INFO_STRING_PREFIX_PHYS_PRESET = "PHYSIC"; + static constexpr const char *INFO_STRING_PREFIX_TRACER = "TRACER"; + static constexpr const char *INFO_STRING_PREFIX_VEHICLE = "VEHICLEFILE"; + static constexpr const char *INFO_STRING_PREFIX_WEAPON = "WEAPONFILE"; - static constexpr const char* GDF_FILENAME_PHYS_PRESET = "physpreset.gdf"; - static constexpr const char* GDF_FILENAME_TRACER = "tracer.gdf"; - static constexpr const char* GDF_FILENAME_VEHICLE = "vehicle.gdf"; - static constexpr const char* GDF_FILENAME_WEAPON = "weapon.gdf"; - }; -} \ No newline at end of file + static constexpr const char *GDF_FILENAME_PHYS_PRESET = "physpreset.gdf"; + static constexpr const char *GDF_FILENAME_TRACER = "tracer.gdf"; + static constexpr const char *GDF_FILENAME_VEHICLE = "vehicle.gdf"; + static constexpr const char *GDF_FILENAME_WEAPON = "weapon.gdf"; +}; +} // namespace IW5 \ No newline at end of file diff --git a/src/ObjCommon/Game/T6/InfoString/EnumStrings.h b/src/ObjCommon/Game/T6/InfoString/EnumStrings.h index 219482d24..16912f017 100644 --- a/src/ObjCommon/Game/T6/InfoString/EnumStrings.h +++ b/src/ObjCommon/Game/T6/InfoString/EnumStrings.h @@ -1,370 +1,96 @@ #pragma once -namespace T6 -{ - inline const char* szWeapTypeNames[] - { - "bullet", - "grenade", - "projectile", - "binoculars", - "gas", - "bomb", - "mine", - "melee", - "riotshield" - }; +namespace T6 { +inline const char *szWeapTypeNames[]{"bullet", "grenade", "projectile", "binoculars", "gas", "bomb", "mine", "melee", "riotshield"}; - inline const char* szWeapClassNames[] - { - "rifle", - "mg", - "smg", - "spread", - "pistol", - "grenade", - "rocketlauncher", - "turret", - "non-player", - "gas", - "item", - "melee", - "Killstreak Alt Stored Weapon", - "pistol spread" - }; +inline const char *szWeapClassNames[]{"rifle", + "mg", + "smg", + "spread", + "pistol", + "grenade", + "rocketlauncher", + "turret", + "non-player", + "gas", + "item", + "melee", + "Killstreak Alt Stored Weapon", + "pistol spread"}; - inline const char* szWeapOverlayReticleNames[] - { - "none", - "crosshair" - }; +inline const char *szWeapOverlayReticleNames[]{"none", "crosshair"}; - inline const char* szWeapInventoryTypeNames[] - { - "primary", - "offhand", - "item", - "altmode", - "melee", - "dwlefthand" - }; +inline const char *szWeapInventoryTypeNames[]{"primary", "offhand", "item", "altmode", "melee", "dwlefthand"}; - inline const char* szWeapClipTypeNames[] - { - "bottom", - "top", - "left", - "dp28", - "ptrs", - "lmg" - }; +inline const char *szWeapClipTypeNames[]{"bottom", "top", "left", "dp28", "ptrs", "lmg"}; - inline const char* barrelTypeNames[] - { - "Single", - "Dual Barrel", - "Dual Barrel Alternate", - "Quad Barrel", - "Quad Barrel Alternate", - "Quad Barrel Double Alternate" - }; +inline const char *barrelTypeNames[]{"Single", "Dual Barrel", "Dual Barrel Alternate", "Quad Barrel", "Quad Barrel Alternate", "Quad Barrel Double Alternate"}; - inline const char* impactTypeNames[] - { - "none", - "bullet_small", - "bullet_large", - "bullet_ap", - "bullet_xtreme", - "shotgun", - "grenade_bounce", - "grenade_explode", - "rifle_grenade", - "rocket_explode", - "rocket_explode_xtreme", - "projectile_dud", - "mortar_shell", - "tank_shell", - "bolt", - "blade" - }; +inline const char *impactTypeNames[]{"none", "bullet_small", "bullet_large", "bullet_ap", "bullet_xtreme", "shotgun", + "grenade_bounce", "grenade_explode", "rifle_grenade", "rocket_explode", "rocket_explode_xtreme", "projectile_dud", + "mortar_shell", "tank_shell", "bolt", "blade"}; - inline const char* szWeapStanceNames[] - { - "stand", - "duck", - "prone" - }; +inline const char *szWeapStanceNames[]{"stand", "duck", "prone"}; - inline const char* szProjectileExplosionNames[] - { - "grenade", - "rocket", - "flashbang", - "none", - "dud", - "smoke", - "heavy explosive", - "fire", - "napalmblob", - "bolt", - "shrapnel span" - }; +inline const char *szProjectileExplosionNames[]{"grenade", "rocket", "flashbang", "none", "dud", "smoke", + "heavy explosive", "fire", "napalmblob", "bolt", "shrapnel span"}; - inline const char* offhandClassNames[] - { - "None", - "Frag Grenade", - "Smoke Grenade", - "Flash Grenade", - "Gear", - "Supply Drop Marker" - }; +inline const char *offhandClassNames[]{"None", "Frag Grenade", "Smoke Grenade", "Flash Grenade", "Gear", "Supply Drop Marker"}; - inline const char* offhandSlotNames[] - { - "None", - "Lethal grenade", - "Tactical grenade", - "Equipment", - "Specific use" - }; +inline const char *offhandSlotNames[]{"None", "Lethal grenade", "Tactical grenade", "Equipment", "Specific use"}; - inline const char* playerAnimTypeNames[] - { - "none", - "default", - "other", - "sniper", - "m203", - "hold", - "briefcase", - "reviver", - "radio", - "dualwield", - "remotecontrol", - "crossbow", - "minigun", - "beltfed", - "g11", - "rearclip", - "handleclip", - "rearclipsniper", - "ballisticknife", - "singleknife", - "nopump", - "hatchet", - "grimreaper", - "zipline", - "riotshield", - "tablet", - "turned", - "screecher", - "staff" - }; +inline const char *playerAnimTypeNames[]{"none", "default", "other", "sniper", "m203", "hold", "briefcase", "reviver", + "radio", "dualwield", "remotecontrol", "crossbow", "minigun", "beltfed", "g11", "rearclip", + "handleclip", "rearclipsniper", "ballisticknife", "singleknife", "nopump", "hatchet", "grimreaper", "zipline", + "riotshield", "tablet", "turned", "screecher", "staff"}; - inline const char* activeReticleNames[] - { - "None", - "Pip-On-A-Stick", - "Bouncing Diamond", - "Missile Lock" - }; +inline const char *activeReticleNames[]{"None", "Pip-On-A-Stick", "Bouncing Diamond", "Missile Lock"}; - inline const char* guidedMissileNames[] - { - "None", - "Sidewinder", - "Hellfire", - "Javelin", - "Ballistic", - "WireGuided", - "TVGuided", - "Drone", - "HeatSeeking" - }; +inline const char *guidedMissileNames[]{"None", "Sidewinder", "Hellfire", "Javelin", "Ballistic", "WireGuided", "TVGuided", "Drone", "HeatSeeking"}; - inline const char* stickinessNames[] - { - "Don't stick", - "Stick to all", - "Stick to all, except ai and clients", - "Stick to ground", - "Stick to ground, maintain yaw", - "Stick to flesh" - }; +inline const char *stickinessNames[]{"Don't stick", "Stick to all", "Stick to all, except ai and clients", "Stick to ground", "Stick to ground, maintain yaw", + "Stick to flesh"}; - inline const char* rotateTypeNames[] - { - "Rotate both axis, grenade style", - "Rotate one axis, blade style", - "Rotate like a cylinder" - }; +inline const char *rotateTypeNames[]{"Rotate both axis, grenade style", "Rotate one axis, blade style", "Rotate like a cylinder"}; - inline const char* overlayInterfaceNames[] - { - "None", - "Javelin", - "Turret Scope" - }; +inline const char *overlayInterfaceNames[]{"None", "Javelin", "Turret Scope"}; - inline const char* ammoCounterClipNames[] - { - "None", - "Magazine", - "ShortMagazine", - "Shotgun", - "Rocket", - "Beltfed", - "AltWeapon" - }; +inline const char *ammoCounterClipNames[]{"None", "Magazine", "ShortMagazine", "Shotgun", "Rocket", "Beltfed", "AltWeapon"}; - inline const char* weapIconRatioNames[] - { - "1:1", - "2:1", - "4:1" - }; +inline const char *weapIconRatioNames[]{"1:1", "2:1", "4:1"}; - inline const char* szAttachmentTypeNames[] - { - "none", - "acog", - "dualclip", - "dualoptic", - "dw", - "extbarrel", - "extclip", - "extramags", - "fastads", - "fastreload", - "fmj", - "gl", - "grip", - "holo", - "ir", - "is", - "longbreath", - "mk", - "mms", - "rangefinder", - "reflex", - "rf", - "sf", - "silencer", - "stackfire", - "stalker", - "steadyaim", - "swayreduc", - "tacknife", - "vzoom" - }; +inline const char *szAttachmentTypeNames[]{"none", "acog", "dualclip", "dualoptic", "dw", "extbarrel", "extclip", "extramags", + "fastads", "fastreload", "fmj", "gl", "grip", "holo", "ir", "is", + "longbreath", "mk", "mms", "rangefinder", "reflex", "rf", "sf", "silencer", + "stackfire", "stalker", "steadyaim", "swayreduc", "tacknife", "vzoom"}; - inline const char* szWeapFireTypeNames[] - { - "Full Auto", - "Single Shot", - "2-Round Burst", - "3-Round Burst", - "4-Round Burst", - "5-Round Burst", - "Stacked Fire", - "Minigun", - "Charge Shot", - "Jetgun" - }; +inline const char *szWeapFireTypeNames[]{"Full Auto", "Single Shot", "2-Round Burst", "3-Round Burst", "4-Round Burst", + "5-Round Burst", "Stacked Fire", "Minigun", "Charge Shot", "Jetgun"}; - inline const char* penetrateTypeNames[] - { - "none", - "small", - "medium", - "large" - }; +inline const char *penetrateTypeNames[]{"none", "small", "medium", "large"}; - inline const char* s_constraintTypeNames[] - { - "none", - "point", - "distance", - "hinge", - "joint", - "actuator", - "fake_shake", - "launch", - "rope", - "light", - }; +inline const char *s_constraintTypeNames[]{ + "none", "point", "distance", "hinge", "joint", "actuator", "fake_shake", "launch", "rope", "light", +}; - inline const char* s_vehicleClassNames[] - { - "4 wheel", - "motorcycle", - "tank", - "plane", - "boat", - "artillery", - "helicopter", - }; +inline const char *s_vehicleClassNames[]{ + "4 wheel", "motorcycle", "tank", "plane", "boat", "artillery", "helicopter", +}; - inline const char* s_vehicleCameraModes[] - { - "first", - "chase", - "view", - "strafe", - "horse", - "oldtank", - "hover", - "vtol", - }; +inline const char *s_vehicleCameraModes[]{ + "first", "chase", "view", "strafe", "horse", "oldtank", "hover", "vtol", +}; - inline const char* s_tractionTypeNames[] - { - "TRACTION_TYPE_FRONT", - "TRACTION_TYPE_BACK", - "TRACTION_TYPE_ALL_WD", - }; +inline const char *s_tractionTypeNames[]{ + "TRACTION_TYPE_FRONT", + "TRACTION_TYPE_BACK", + "TRACTION_TYPE_ALL_WD", +}; - inline const char* tracerTypeNames[] - { - "Laser", - "Smoke" - }; +inline const char *tracerTypeNames[]{"Laser", "Smoke"}; - inline const char* bounceSoundSuffixes[] - { - "_default", - "_bark", - "_brick", - "_carpet", - "_cloth", - "_concrete", - "_dirt", - "_flesh", - "_foliage", - "_glass", - "_grass", - "_gravel", - "_ice", - "_metal", - "_mud", - "_paper", - "_plaster", - "_rock", - "_sand", - "_snow", - "_water", - "_wood", - "_asphalt", - "_ceramic", - "_plastic", - "_rubber", - "_cushion", - "_fruit", - "_paintedmetal", - "_player", - "_tallgrass", - "_riotshield" - }; -} +inline const char *bounceSoundSuffixes[]{"_default", "_bark", "_brick", "_carpet", "_cloth", "_concrete", "_dirt", "_flesh", + "_foliage", "_glass", "_grass", "_gravel", "_ice", "_metal", "_mud", "_paper", + "_plaster", "_rock", "_sand", "_snow", "_water", "_wood", "_asphalt", "_ceramic", + "_plastic", "_rubber", "_cushion", "_fruit", "_paintedmetal", "_player", "_tallgrass", "_riotshield"}; +} // namespace T6 diff --git a/src/ObjCommon/Game/T6/InfoString/PhysConstraintsFields.h b/src/ObjCommon/Game/T6/InfoString/PhysConstraintsFields.h index bce6e3970..f50f12fde 100644 --- a/src/ObjCommon/Game/T6/InfoString/PhysConstraintsFields.h +++ b/src/ObjCommon/Game/T6/InfoString/PhysConstraintsFields.h @@ -1,85 +1,83 @@ #pragma once #include "Game/T6/T6.h" -namespace T6 -{ - inline cspField_t phys_constraints_fields[] - { - {"c1_type", offsetof(PhysConstraints, data[0].type), CFT_TYPE}, - {"c1_bone1_name", offsetof(PhysConstraints, data[0].target_bone1), CSPFT_STRING}, - {"c1_bone2_name", offsetof(PhysConstraints, data[0].target_bone2), CSPFT_STRING}, - {"c1_offsetX", offsetof(PhysConstraints, data[0].offset.x), CSPFT_FLOAT}, - {"c1_offsetY", offsetof(PhysConstraints, data[0].offset.y), CSPFT_FLOAT}, - {"c1_offsetZ", offsetof(PhysConstraints, data[0].offset.z), CSPFT_FLOAT}, - {"c1_timeout", offsetof(PhysConstraints, data[0].timeout), CSPFT_INT}, - {"c1_min_health", offsetof(PhysConstraints, data[0].min_health), CSPFT_INT}, - {"c1_max_health", offsetof(PhysConstraints, data[0].max_health), CSPFT_INT}, - {"c1_damp", offsetof(PhysConstraints, data[0].damp), CSPFT_FLOAT}, - {"c1_power", offsetof(PhysConstraints, data[0].power), CSPFT_FLOAT}, - {"c1_spin_scale", offsetof(PhysConstraints, data[0].spin_scale), CSPFT_FLOAT}, - {"c1_shakescalex", offsetof(PhysConstraints, data[0].scale.x), CSPFT_FLOAT}, - {"c1_shakescaley", offsetof(PhysConstraints, data[0].scale.y), CSPFT_FLOAT}, - {"c1_shakescalez", offsetof(PhysConstraints, data[0].scale.z), CSPFT_FLOAT}, - {"c1_min_angle", offsetof(PhysConstraints, data[0].minAngle), CSPFT_FLOAT}, - {"c1_max_angle", offsetof(PhysConstraints, data[0].maxAngle), CSPFT_FLOAT}, - {"c1_yaw", offsetof(PhysConstraints, data[0].scale.y), CSPFT_FLOAT}, - {"c1_pitch", offsetof(PhysConstraints, data[0].scale.x), CSPFT_FLOAT}, - {"c2_type", offsetof(PhysConstraints, data[1].type), CFT_TYPE}, - {"c2_bone1_name", offsetof(PhysConstraints, data[1].target_bone1), CSPFT_STRING}, - {"c2_bone2_name", offsetof(PhysConstraints, data[1].target_bone2), CSPFT_STRING}, - {"c2_offsetX", offsetof(PhysConstraints, data[1].offset.x), CSPFT_FLOAT}, - {"c2_offsetY", offsetof(PhysConstraints, data[1].offset.y), CSPFT_FLOAT}, - {"c2_offsetZ", offsetof(PhysConstraints, data[1].offset.z), CSPFT_FLOAT}, - {"c2_timeout", offsetof(PhysConstraints, data[1].timeout), CSPFT_INT}, - {"c2_min_health", offsetof(PhysConstraints, data[1].min_health), CSPFT_INT}, - {"c2_max_health", offsetof(PhysConstraints, data[1].max_health), CSPFT_INT}, - {"c2_damp", offsetof(PhysConstraints, data[1].damp), CSPFT_FLOAT}, - {"c2_power", offsetof(PhysConstraints, data[1].power), CSPFT_FLOAT}, - {"c2_spin_scale", offsetof(PhysConstraints, data[1].spin_scale), CSPFT_FLOAT}, - {"c2_shakescalex", offsetof(PhysConstraints, data[1].scale.x), CSPFT_FLOAT}, - {"c2_shakescaley", offsetof(PhysConstraints, data[1].scale.y), CSPFT_FLOAT}, - {"c2_shakescalez", offsetof(PhysConstraints, data[1].scale.z), CSPFT_FLOAT}, - {"c2_min_angle", offsetof(PhysConstraints, data[1].minAngle), CSPFT_FLOAT}, - {"c2_max_angle", offsetof(PhysConstraints, data[1].maxAngle), CSPFT_FLOAT}, - {"c2_yaw", offsetof(PhysConstraints, data[1].scale.y), CSPFT_FLOAT}, - {"c2_pitch", offsetof(PhysConstraints, data[1].scale.x), CSPFT_FLOAT}, - {"c3_type", offsetof(PhysConstraints, data[2].type), CFT_TYPE}, - {"c3_bone1_name", offsetof(PhysConstraints, data[2].target_bone1), CSPFT_STRING}, - {"c3_bone2_name", offsetof(PhysConstraints, data[2].target_bone2), CSPFT_STRING}, - {"c3_offsetX", offsetof(PhysConstraints, data[2].offset.x), CSPFT_FLOAT}, - {"c3_offsetY", offsetof(PhysConstraints, data[2].offset.y), CSPFT_FLOAT}, - {"c3_offsetZ", offsetof(PhysConstraints, data[2].offset.z), CSPFT_FLOAT}, - {"c3_timeout", offsetof(PhysConstraints, data[2].timeout), CSPFT_INT}, - {"c3_min_health", offsetof(PhysConstraints, data[2].min_health), CSPFT_INT}, - {"c3_max_health", offsetof(PhysConstraints, data[2].max_health), CSPFT_INT}, - {"c3_damp", offsetof(PhysConstraints, data[2].damp), CSPFT_FLOAT}, - {"c3_power", offsetof(PhysConstraints, data[2].power), CSPFT_FLOAT}, - {"c3_spin_scale", offsetof(PhysConstraints, data[2].spin_scale), CSPFT_FLOAT}, - {"c3_shakescalex", offsetof(PhysConstraints, data[2].scale.x), CSPFT_FLOAT}, - {"c3_shakescaley", offsetof(PhysConstraints, data[2].scale.y), CSPFT_FLOAT}, - {"c3_shakescalez", offsetof(PhysConstraints, data[2].scale.z), CSPFT_FLOAT}, - {"c3_min_angle", offsetof(PhysConstraints, data[2].minAngle), CSPFT_FLOAT}, - {"c3_max_angle", offsetof(PhysConstraints, data[2].maxAngle), CSPFT_FLOAT}, - {"c3_yaw", offsetof(PhysConstraints, data[2].scale.y), CSPFT_FLOAT}, - {"c3_pitch", offsetof(PhysConstraints, data[2].scale.x), CSPFT_FLOAT}, - {"c4_type", offsetof(PhysConstraints, data[3].type), CFT_TYPE}, - {"c4_bone1_name", offsetof(PhysConstraints, data[3].target_bone1), CSPFT_STRING}, - {"c4_bone2_name", offsetof(PhysConstraints, data[3].target_bone2), CSPFT_STRING}, - {"c4_offsetX", offsetof(PhysConstraints, data[3].offset.x), CSPFT_FLOAT}, - {"c4_offsetY", offsetof(PhysConstraints, data[3].offset.y), CSPFT_FLOAT}, - {"c4_offsetZ", offsetof(PhysConstraints, data[3].offset.z), CSPFT_FLOAT}, - {"c4_timeout", offsetof(PhysConstraints, data[3].timeout), CSPFT_INT}, - {"c4_min_health", offsetof(PhysConstraints, data[3].min_health), CSPFT_INT}, - {"c4_max_health", offsetof(PhysConstraints, data[3].max_health), CSPFT_INT}, - {"c4_damp", offsetof(PhysConstraints, data[3].damp), CSPFT_FLOAT}, - {"c4_power", offsetof(PhysConstraints, data[3].power), CSPFT_FLOAT}, - {"c4_spin_scale", offsetof(PhysConstraints, data[3].spin_scale), CSPFT_FLOAT}, - {"c4_shakescalex", offsetof(PhysConstraints, data[3].scale.x), CSPFT_FLOAT}, - {"c4_shakescaley", offsetof(PhysConstraints, data[3].scale.y), CSPFT_FLOAT}, - {"c4_shakescalez", offsetof(PhysConstraints, data[3].scale.z), CSPFT_FLOAT}, - {"c4_min_angle", offsetof(PhysConstraints, data[3].minAngle), CSPFT_FLOAT}, - {"c4_max_angle", offsetof(PhysConstraints, data[3].maxAngle), CSPFT_FLOAT}, - {"c4_yaw", offsetof(PhysConstraints, data[3].scale.y), CSPFT_FLOAT}, - {"c4_pitch", offsetof(PhysConstraints, data[3].scale.x), CSPFT_FLOAT}, - }; +namespace T6 { +inline cspField_t phys_constraints_fields[]{ + {"c1_type", offsetof(PhysConstraints, data[0].type), CFT_TYPE }, + {"c1_bone1_name", offsetof(PhysConstraints, data[0].target_bone1), CSPFT_STRING}, + {"c1_bone2_name", offsetof(PhysConstraints, data[0].target_bone2), CSPFT_STRING}, + {"c1_offsetX", offsetof(PhysConstraints, data[0].offset.x), CSPFT_FLOAT }, + {"c1_offsetY", offsetof(PhysConstraints, data[0].offset.y), CSPFT_FLOAT }, + {"c1_offsetZ", offsetof(PhysConstraints, data[0].offset.z), CSPFT_FLOAT }, + {"c1_timeout", offsetof(PhysConstraints, data[0].timeout), CSPFT_INT }, + {"c1_min_health", offsetof(PhysConstraints, data[0].min_health), CSPFT_INT }, + {"c1_max_health", offsetof(PhysConstraints, data[0].max_health), CSPFT_INT }, + {"c1_damp", offsetof(PhysConstraints, data[0].damp), CSPFT_FLOAT }, + {"c1_power", offsetof(PhysConstraints, data[0].power), CSPFT_FLOAT }, + {"c1_spin_scale", offsetof(PhysConstraints, data[0].spin_scale), CSPFT_FLOAT }, + {"c1_shakescalex", offsetof(PhysConstraints, data[0].scale.x), CSPFT_FLOAT }, + {"c1_shakescaley", offsetof(PhysConstraints, data[0].scale.y), CSPFT_FLOAT }, + {"c1_shakescalez", offsetof(PhysConstraints, data[0].scale.z), CSPFT_FLOAT }, + {"c1_min_angle", offsetof(PhysConstraints, data[0].minAngle), CSPFT_FLOAT }, + {"c1_max_angle", offsetof(PhysConstraints, data[0].maxAngle), CSPFT_FLOAT }, + {"c1_yaw", offsetof(PhysConstraints, data[0].scale.y), CSPFT_FLOAT }, + {"c1_pitch", offsetof(PhysConstraints, data[0].scale.x), CSPFT_FLOAT }, + {"c2_type", offsetof(PhysConstraints, data[1].type), CFT_TYPE }, + {"c2_bone1_name", offsetof(PhysConstraints, data[1].target_bone1), CSPFT_STRING}, + {"c2_bone2_name", offsetof(PhysConstraints, data[1].target_bone2), CSPFT_STRING}, + {"c2_offsetX", offsetof(PhysConstraints, data[1].offset.x), CSPFT_FLOAT }, + {"c2_offsetY", offsetof(PhysConstraints, data[1].offset.y), CSPFT_FLOAT }, + {"c2_offsetZ", offsetof(PhysConstraints, data[1].offset.z), CSPFT_FLOAT }, + {"c2_timeout", offsetof(PhysConstraints, data[1].timeout), CSPFT_INT }, + {"c2_min_health", offsetof(PhysConstraints, data[1].min_health), CSPFT_INT }, + {"c2_max_health", offsetof(PhysConstraints, data[1].max_health), CSPFT_INT }, + {"c2_damp", offsetof(PhysConstraints, data[1].damp), CSPFT_FLOAT }, + {"c2_power", offsetof(PhysConstraints, data[1].power), CSPFT_FLOAT }, + {"c2_spin_scale", offsetof(PhysConstraints, data[1].spin_scale), CSPFT_FLOAT }, + {"c2_shakescalex", offsetof(PhysConstraints, data[1].scale.x), CSPFT_FLOAT }, + {"c2_shakescaley", offsetof(PhysConstraints, data[1].scale.y), CSPFT_FLOAT }, + {"c2_shakescalez", offsetof(PhysConstraints, data[1].scale.z), CSPFT_FLOAT }, + {"c2_min_angle", offsetof(PhysConstraints, data[1].minAngle), CSPFT_FLOAT }, + {"c2_max_angle", offsetof(PhysConstraints, data[1].maxAngle), CSPFT_FLOAT }, + {"c2_yaw", offsetof(PhysConstraints, data[1].scale.y), CSPFT_FLOAT }, + {"c2_pitch", offsetof(PhysConstraints, data[1].scale.x), CSPFT_FLOAT }, + {"c3_type", offsetof(PhysConstraints, data[2].type), CFT_TYPE }, + {"c3_bone1_name", offsetof(PhysConstraints, data[2].target_bone1), CSPFT_STRING}, + {"c3_bone2_name", offsetof(PhysConstraints, data[2].target_bone2), CSPFT_STRING}, + {"c3_offsetX", offsetof(PhysConstraints, data[2].offset.x), CSPFT_FLOAT }, + {"c3_offsetY", offsetof(PhysConstraints, data[2].offset.y), CSPFT_FLOAT }, + {"c3_offsetZ", offsetof(PhysConstraints, data[2].offset.z), CSPFT_FLOAT }, + {"c3_timeout", offsetof(PhysConstraints, data[2].timeout), CSPFT_INT }, + {"c3_min_health", offsetof(PhysConstraints, data[2].min_health), CSPFT_INT }, + {"c3_max_health", offsetof(PhysConstraints, data[2].max_health), CSPFT_INT }, + {"c3_damp", offsetof(PhysConstraints, data[2].damp), CSPFT_FLOAT }, + {"c3_power", offsetof(PhysConstraints, data[2].power), CSPFT_FLOAT }, + {"c3_spin_scale", offsetof(PhysConstraints, data[2].spin_scale), CSPFT_FLOAT }, + {"c3_shakescalex", offsetof(PhysConstraints, data[2].scale.x), CSPFT_FLOAT }, + {"c3_shakescaley", offsetof(PhysConstraints, data[2].scale.y), CSPFT_FLOAT }, + {"c3_shakescalez", offsetof(PhysConstraints, data[2].scale.z), CSPFT_FLOAT }, + {"c3_min_angle", offsetof(PhysConstraints, data[2].minAngle), CSPFT_FLOAT }, + {"c3_max_angle", offsetof(PhysConstraints, data[2].maxAngle), CSPFT_FLOAT }, + {"c3_yaw", offsetof(PhysConstraints, data[2].scale.y), CSPFT_FLOAT }, + {"c3_pitch", offsetof(PhysConstraints, data[2].scale.x), CSPFT_FLOAT }, + {"c4_type", offsetof(PhysConstraints, data[3].type), CFT_TYPE }, + {"c4_bone1_name", offsetof(PhysConstraints, data[3].target_bone1), CSPFT_STRING}, + {"c4_bone2_name", offsetof(PhysConstraints, data[3].target_bone2), CSPFT_STRING}, + {"c4_offsetX", offsetof(PhysConstraints, data[3].offset.x), CSPFT_FLOAT }, + {"c4_offsetY", offsetof(PhysConstraints, data[3].offset.y), CSPFT_FLOAT }, + {"c4_offsetZ", offsetof(PhysConstraints, data[3].offset.z), CSPFT_FLOAT }, + {"c4_timeout", offsetof(PhysConstraints, data[3].timeout), CSPFT_INT }, + {"c4_min_health", offsetof(PhysConstraints, data[3].min_health), CSPFT_INT }, + {"c4_max_health", offsetof(PhysConstraints, data[3].max_health), CSPFT_INT }, + {"c4_damp", offsetof(PhysConstraints, data[3].damp), CSPFT_FLOAT }, + {"c4_power", offsetof(PhysConstraints, data[3].power), CSPFT_FLOAT }, + {"c4_spin_scale", offsetof(PhysConstraints, data[3].spin_scale), CSPFT_FLOAT }, + {"c4_shakescalex", offsetof(PhysConstraints, data[3].scale.x), CSPFT_FLOAT }, + {"c4_shakescaley", offsetof(PhysConstraints, data[3].scale.y), CSPFT_FLOAT }, + {"c4_shakescalez", offsetof(PhysConstraints, data[3].scale.z), CSPFT_FLOAT }, + {"c4_min_angle", offsetof(PhysConstraints, data[3].minAngle), CSPFT_FLOAT }, + {"c4_max_angle", offsetof(PhysConstraints, data[3].maxAngle), CSPFT_FLOAT }, + {"c4_yaw", offsetof(PhysConstraints, data[3].scale.y), CSPFT_FLOAT }, + {"c4_pitch", offsetof(PhysConstraints, data[3].scale.x), CSPFT_FLOAT }, +}; } \ No newline at end of file diff --git a/src/ObjCommon/Game/T6/InfoString/PhysPresetFields.h b/src/ObjCommon/Game/T6/InfoString/PhysPresetFields.h index ffda5859f..b5d685a48 100644 --- a/src/ObjCommon/Game/T6/InfoString/PhysPresetFields.h +++ b/src/ObjCommon/Game/T6/InfoString/PhysPresetFields.h @@ -1,28 +1,26 @@ #pragma once #include "Game/T6/T6.h" -namespace T6 -{ - inline cspField_t phys_preset_fields[] - { - { "mass", offsetof(PhysPresetInfo, mass), CSPFT_FLOAT }, - { "bounce", offsetof(PhysPresetInfo, bounce), CSPFT_FLOAT }, - { "friction", offsetof(PhysPresetInfo, friction), CSPFT_FLOAT }, - { "isFrictionInfinity", offsetof(PhysPresetInfo, isFrictionInfinity), CSPFT_QBOOLEAN }, - { "bulletForceScale", offsetof(PhysPresetInfo, bulletForceScale), CSPFT_FLOAT }, - { "explosiveForceScale", offsetof(PhysPresetInfo, explosiveForceScale), CSPFT_FLOAT }, - { "piecesSpreadFraction", offsetof(PhysPresetInfo, piecesSpreadFraction), CSPFT_FLOAT }, - { "piecesUpwardVelocity", offsetof(PhysPresetInfo, piecesUpwardVelocity), CSPFT_FLOAT }, - { "canFloat", offsetof(PhysPresetInfo, canFloat), CSPFT_INT }, - { "gravityScale", offsetof(PhysPresetInfo, gravityScale), CSPFT_FLOAT }, - { "massOffsetX", offsetof(PhysPresetInfo, centerOfMassOffset.x), CSPFT_FLOAT }, - { "massOffsetY", offsetof(PhysPresetInfo, centerOfMassOffset.y), CSPFT_FLOAT }, - { "massOffsetZ", offsetof(PhysPresetInfo, centerOfMassOffset.z), CSPFT_FLOAT }, - { "buoyancyMinX", offsetof(PhysPresetInfo, buoyancyBoxMin.x), CSPFT_FLOAT }, - { "buoyancyMinY", offsetof(PhysPresetInfo, buoyancyBoxMin.y), CSPFT_FLOAT }, - { "buoyancyMinZ", offsetof(PhysPresetInfo, buoyancyBoxMin.z), CSPFT_FLOAT }, - { "buoyancyMaxX", offsetof(PhysPresetInfo, buoyancyBoxMax.x), CSPFT_FLOAT }, - { "buoyancyMaxY", offsetof(PhysPresetInfo, buoyancyBoxMax.y), CSPFT_FLOAT }, - { "buoyancyMaxZ", offsetof(PhysPresetInfo, buoyancyBoxMax.z), CSPFT_FLOAT }, - }; +namespace T6 { +inline cspField_t phys_preset_fields[]{ + {"mass", offsetof(PhysPresetInfo, mass), CSPFT_FLOAT }, + {"bounce", offsetof(PhysPresetInfo, bounce), CSPFT_FLOAT }, + {"friction", offsetof(PhysPresetInfo, friction), CSPFT_FLOAT }, + {"isFrictionInfinity", offsetof(PhysPresetInfo, isFrictionInfinity), CSPFT_QBOOLEAN}, + {"bulletForceScale", offsetof(PhysPresetInfo, bulletForceScale), CSPFT_FLOAT }, + {"explosiveForceScale", offsetof(PhysPresetInfo, explosiveForceScale), CSPFT_FLOAT }, + {"piecesSpreadFraction", offsetof(PhysPresetInfo, piecesSpreadFraction), CSPFT_FLOAT }, + {"piecesUpwardVelocity", offsetof(PhysPresetInfo, piecesUpwardVelocity), CSPFT_FLOAT }, + {"canFloat", offsetof(PhysPresetInfo, canFloat), CSPFT_INT }, + {"gravityScale", offsetof(PhysPresetInfo, gravityScale), CSPFT_FLOAT }, + {"massOffsetX", offsetof(PhysPresetInfo, centerOfMassOffset.x), CSPFT_FLOAT }, + {"massOffsetY", offsetof(PhysPresetInfo, centerOfMassOffset.y), CSPFT_FLOAT }, + {"massOffsetZ", offsetof(PhysPresetInfo, centerOfMassOffset.z), CSPFT_FLOAT }, + {"buoyancyMinX", offsetof(PhysPresetInfo, buoyancyBoxMin.x), CSPFT_FLOAT }, + {"buoyancyMinY", offsetof(PhysPresetInfo, buoyancyBoxMin.y), CSPFT_FLOAT }, + {"buoyancyMinZ", offsetof(PhysPresetInfo, buoyancyBoxMin.z), CSPFT_FLOAT }, + {"buoyancyMaxX", offsetof(PhysPresetInfo, buoyancyBoxMax.x), CSPFT_FLOAT }, + {"buoyancyMaxY", offsetof(PhysPresetInfo, buoyancyBoxMax.y), CSPFT_FLOAT }, + {"buoyancyMaxZ", offsetof(PhysPresetInfo, buoyancyBoxMax.z), CSPFT_FLOAT }, +}; } \ No newline at end of file diff --git a/src/ObjCommon/Game/T6/InfoString/TracerFields.h b/src/ObjCommon/Game/T6/InfoString/TracerFields.h index 5390e86c2..8658919cb 100644 --- a/src/ObjCommon/Game/T6/InfoString/TracerFields.h +++ b/src/ObjCommon/Game/T6/InfoString/TracerFields.h @@ -1,40 +1,38 @@ #pragma once #include "Game/T6/T6.h" -namespace T6 -{ - inline cspField_t tracer_fields[] - { - {"type", offsetof(TracerDef, type), TFT_TRACERTYPE}, - {"material", offsetof(TracerDef, material), CSPFT_MATERIAL}, - {"drawInterval", offsetof(TracerDef, drawInterval), CSPFT_INT}, - {"speed", offsetof(TracerDef, speed), CSPFT_FLOAT}, - {"beamLength", offsetof(TracerDef, beamLength), CSPFT_FLOAT}, - {"beamWidth", offsetof(TracerDef, beamWidth), CSPFT_FLOAT}, - {"screwRadius", offsetof(TracerDef, screwRadius), CSPFT_FLOAT}, - {"screwDist", offsetof(TracerDef, screwDist), CSPFT_FLOAT}, - {"fadeTime", offsetof(TracerDef, fadeTime), CSPFT_FLOAT}, - {"fadeScale", offsetof(TracerDef, fadeScale), CSPFT_FLOAT}, - {"texRepeatRate", offsetof(TracerDef, texRepeatRate), CSPFT_FLOAT}, - {"colorR0", offsetof(TracerDef, colors[0].r), CSPFT_FLOAT}, - {"colorG0", offsetof(TracerDef, colors[0].g), CSPFT_FLOAT}, - {"colorB0", offsetof(TracerDef, colors[0].b), CSPFT_FLOAT}, - {"colorA0", offsetof(TracerDef, colors[0].a), CSPFT_FLOAT}, - {"colorR1", offsetof(TracerDef, colors[1].r), CSPFT_FLOAT}, - {"colorG1", offsetof(TracerDef, colors[1].g), CSPFT_FLOAT}, - {"colorB1", offsetof(TracerDef, colors[1].b), CSPFT_FLOAT}, - {"colorA1", offsetof(TracerDef, colors[1].a), CSPFT_FLOAT}, - {"colorR2", offsetof(TracerDef, colors[2].r), CSPFT_FLOAT}, - {"colorG2", offsetof(TracerDef, colors[2].g), CSPFT_FLOAT}, - {"colorB2", offsetof(TracerDef, colors[2].b), CSPFT_FLOAT}, - {"colorA2", offsetof(TracerDef, colors[2].a), CSPFT_FLOAT}, - {"colorR3", offsetof(TracerDef, colors[3].r), CSPFT_FLOAT}, - {"colorG3", offsetof(TracerDef, colors[3].g), CSPFT_FLOAT}, - {"colorB3", offsetof(TracerDef, colors[3].b), CSPFT_FLOAT}, - {"colorA3", offsetof(TracerDef, colors[3].a), CSPFT_FLOAT}, - {"colorR4", offsetof(TracerDef, colors[4].r), CSPFT_FLOAT}, - {"colorG4", offsetof(TracerDef, colors[4].g), CSPFT_FLOAT}, - {"colorB4", offsetof(TracerDef, colors[4].b), CSPFT_FLOAT}, - {"colorA4", offsetof(TracerDef, colors[4].a), CSPFT_FLOAT} - }; +namespace T6 { +inline cspField_t tracer_fields[]{ + {"type", offsetof(TracerDef, type), TFT_TRACERTYPE}, + {"material", offsetof(TracerDef, material), CSPFT_MATERIAL}, + {"drawInterval", offsetof(TracerDef, drawInterval), CSPFT_INT }, + {"speed", offsetof(TracerDef, speed), CSPFT_FLOAT }, + {"beamLength", offsetof(TracerDef, beamLength), CSPFT_FLOAT }, + {"beamWidth", offsetof(TracerDef, beamWidth), CSPFT_FLOAT }, + {"screwRadius", offsetof(TracerDef, screwRadius), CSPFT_FLOAT }, + {"screwDist", offsetof(TracerDef, screwDist), CSPFT_FLOAT }, + {"fadeTime", offsetof(TracerDef, fadeTime), CSPFT_FLOAT }, + {"fadeScale", offsetof(TracerDef, fadeScale), CSPFT_FLOAT }, + {"texRepeatRate", offsetof(TracerDef, texRepeatRate), CSPFT_FLOAT }, + {"colorR0", offsetof(TracerDef, colors[0].r), CSPFT_FLOAT }, + {"colorG0", offsetof(TracerDef, colors[0].g), CSPFT_FLOAT }, + {"colorB0", offsetof(TracerDef, colors[0].b), CSPFT_FLOAT }, + {"colorA0", offsetof(TracerDef, colors[0].a), CSPFT_FLOAT }, + {"colorR1", offsetof(TracerDef, colors[1].r), CSPFT_FLOAT }, + {"colorG1", offsetof(TracerDef, colors[1].g), CSPFT_FLOAT }, + {"colorB1", offsetof(TracerDef, colors[1].b), CSPFT_FLOAT }, + {"colorA1", offsetof(TracerDef, colors[1].a), CSPFT_FLOAT }, + {"colorR2", offsetof(TracerDef, colors[2].r), CSPFT_FLOAT }, + {"colorG2", offsetof(TracerDef, colors[2].g), CSPFT_FLOAT }, + {"colorB2", offsetof(TracerDef, colors[2].b), CSPFT_FLOAT }, + {"colorA2", offsetof(TracerDef, colors[2].a), CSPFT_FLOAT }, + {"colorR3", offsetof(TracerDef, colors[3].r), CSPFT_FLOAT }, + {"colorG3", offsetof(TracerDef, colors[3].g), CSPFT_FLOAT }, + {"colorB3", offsetof(TracerDef, colors[3].b), CSPFT_FLOAT }, + {"colorA3", offsetof(TracerDef, colors[3].a), CSPFT_FLOAT }, + {"colorR4", offsetof(TracerDef, colors[4].r), CSPFT_FLOAT }, + {"colorG4", offsetof(TracerDef, colors[4].g), CSPFT_FLOAT }, + {"colorB4", offsetof(TracerDef, colors[4].b), CSPFT_FLOAT }, + {"colorA4", offsetof(TracerDef, colors[4].a), CSPFT_FLOAT } +}; } \ No newline at end of file diff --git a/src/ObjCommon/Game/T6/InfoString/VehicleFields.h b/src/ObjCommon/Game/T6/InfoString/VehicleFields.h index 86b83bd7e..500ae9191 100644 --- a/src/ObjCommon/Game/T6/InfoString/VehicleFields.h +++ b/src/ObjCommon/Game/T6/InfoString/VehicleFields.h @@ -1,565 +1,563 @@ #pragma once #include "Game/T6/T6.h" -namespace T6 -{ - inline cspField_t vehicle_fields[] - { - {"type", offsetof(VehicleDef, type), VFT_TYPE}, - {"remoteControl", offsetof(VehicleDef, remoteControl), CSPFT_QBOOLEAN}, - {"bulletDamage", offsetof(VehicleDef, bulletDamage), CSPFT_QBOOLEAN}, - {"armorPiercingDamage", offsetof(VehicleDef, armorPiercingDamage), CSPFT_QBOOLEAN}, - {"grenadeDamage", offsetof(VehicleDef, grenadeDamage), CSPFT_QBOOLEAN}, - {"projectileDamage", offsetof(VehicleDef, projectileDamage), CSPFT_QBOOLEAN}, - {"projectileSplashDamage", offsetof(VehicleDef, projectileSplashDamage), CSPFT_QBOOLEAN}, - {"heavyExplosiveDamage", offsetof(VehicleDef, heavyExplosiveDamage), CSPFT_QBOOLEAN}, - {"cameraMode", offsetof(VehicleDef, cameraMode), VFT_CAMERAMODE}, - {"autoRecenterOnAccel", offsetof(VehicleDef, autoRecenterOnAccel), CSPFT_QBOOLEAN}, - {"thirdPersonDriver", offsetof(VehicleDef, thirdPersonDriver), CSPFT_QBOOLEAN}, - {"thirdPersonUseVehicleRoll", offsetof(VehicleDef, thirdPersonUseVehicleRoll), CSPFT_QBOOLEAN}, - {"thirdPersonCameraPitchVehicleRelative", offsetof(VehicleDef, thirdPersonCameraPitchVehicleRelative), CSPFT_QBOOLEAN}, - {"thirdPersonCameraHeightWorldRelative", offsetof(VehicleDef, thirdPersonCameraHeightWorldRelative), CSPFT_QBOOLEAN}, - {"thirdPersonCameraHeightMin", offsetof(VehicleDef, thirdPersonCameraHeight[0]), CSPFT_FLOAT}, - {"thirdPersonCameraPitchMin", offsetof(VehicleDef, thirdPersonCameraPitch[0]), CSPFT_FLOAT}, - {"thirdPersonCameraRange", offsetof(VehicleDef, thirdPersonCameraRange), CSPFT_FLOAT}, - {"thirdPersonCameraHeight", offsetof(VehicleDef, thirdPersonCameraHeight[1]), CSPFT_FLOAT}, - {"thirdPersonCameraPitch", offsetof(VehicleDef, thirdPersonCameraPitch[1]), CSPFT_FLOAT}, - {"thirdPersonCameraMinPitchClamp", offsetof(VehicleDef, thirdPersonCameraMinPitchClamp), CSPFT_FLOAT}, - {"thirdPersonCameraMaxPitchClamp", offsetof(VehicleDef, thirdPersonCameraMaxPitchClamp), CSPFT_FLOAT}, - {"cameraAlwaysAutoCenter", offsetof(VehicleDef, cameraAlwaysAutoCenter), CSPFT_QBOOLEAN}, - {"cameraAutoCenterLerpRate", offsetof(VehicleDef, cameraAutoCenterLerpRate), CSPFT_FLOAT}, - {"cameraAutoCenterMaxLerpRate", offsetof(VehicleDef, cameraAutoCenterMaxLerpRate), CSPFT_FLOAT}, - {"thirdPersonCameraSpringDistance", offsetof(VehicleDef, thirdPersonCameraSpringDistance), CSPFT_FLOAT}, - {"thirdPersonCameraSpringTime", offsetof(VehicleDef, thirdPersonCameraSpringTime), CSPFT_FLOAT}, - {"thirdPersonCameraHandbrakeTurnRateInc", offsetof(VehicleDef, thirdPersonCameraHandbrakeTurnRateInc), CSPFT_FLOAT}, - {"cameraRollFraction", offsetof(VehicleDef, cameraRollFraction), CSPFT_FLOAT}, - {"cameraFOV", offsetof(VehicleDef, cameraFOV), CSPFT_FLOAT}, - {"viewInfluence", offsetof(VehicleDef, viewInfluence), CSPFT_FLOAT}, - {"tagPlayerOffsetX", offsetof(VehicleDef, tagPlayerOffset.x), CSPFT_FLOAT}, - {"tagPlayerOffsetY", offsetof(VehicleDef, tagPlayerOffset.y), CSPFT_FLOAT}, - {"tagPlayerOffsetZ", offsetof(VehicleDef, tagPlayerOffset.z), CSPFT_FLOAT}, - {"killcamCollision", offsetof(VehicleDef, killcamCollision), CSPFT_QBOOLEAN}, - {"killcamDist", offsetof(VehicleDef, killcamDist), CSPFT_FLOAT}, - {"killcamZDist", offsetof(VehicleDef, killcamZDist), CSPFT_FLOAT}, - {"killcamMinDist", offsetof(VehicleDef, killcamMinDist), CSPFT_FLOAT}, - {"killcamZTargetOffset", offsetof(VehicleDef, killcamZTargetOffset), CSPFT_FLOAT}, - {"killcamFOV", offsetof(VehicleDef, killcamFOV), CSPFT_FLOAT}, - {"killcamNearBlur", offsetof(VehicleDef, killcamNearBlur), CSPFT_FLOAT}, - {"killcamNearBlurStart", offsetof(VehicleDef, killcamNearBlurStart), CSPFT_FLOAT}, - {"killcamNearBlurEnd", offsetof(VehicleDef, killcamNearBlurEnd), CSPFT_FLOAT}, - {"killcamFarBlur", offsetof(VehicleDef, killcamFarBlur), CSPFT_FLOAT}, - {"killcamFarBlurStart", offsetof(VehicleDef, killcamFarBlurStart), CSPFT_FLOAT}, - {"killcamFarBlurEnd", offsetof(VehicleDef, killcamFarBlurEnd), CSPFT_FLOAT}, - {"isDrivable", offsetof(VehicleDef, isDrivable), CSPFT_QBOOLEAN}, - {"numberOfSeats", offsetof(VehicleDef, numberOfSeats), CSPFT_INT}, - {"numberOfGunners", offsetof(VehicleDef, numberOfGunners), CSPFT_INT}, - {"driverControlledGunPos", offsetof(VehicleDef, driverControlledGunPos), CSPFT_INT}, - {"seatSwitchOrder1", offsetof(VehicleDef, seatSwitchOrder[0]), CSPFT_INT}, - {"seatSwitchOrder2", offsetof(VehicleDef, seatSwitchOrder[1]), CSPFT_INT}, - {"seatSwitchOrder3", offsetof(VehicleDef, seatSwitchOrder[2]), CSPFT_INT}, - {"seatSwitchOrder4", offsetof(VehicleDef, seatSwitchOrder[3]), CSPFT_INT}, - {"seatSwitchOrder5", offsetof(VehicleDef, seatSwitchOrder[4]), CSPFT_INT}, - {"seatSwitchOrder6", offsetof(VehicleDef, seatSwitchOrder[5]), CSPFT_INT}, - {"seatSwitchOrder7", offsetof(VehicleDef, seatSwitchOrder[6]), CSPFT_INT}, - {"seatSwitchOrder8", offsetof(VehicleDef, seatSwitchOrder[7]), CSPFT_INT}, - {"seatSwitchOrder9", offsetof(VehicleDef, seatSwitchOrder[8]), CSPFT_INT}, - {"seatSwitchOrder10", offsetof(VehicleDef, seatSwitchOrder[9]), CSPFT_INT}, - {"seatSwitchOrder11", offsetof(VehicleDef, seatSwitchOrder[10]), CSPFT_INT}, - {"texureScrollScale", offsetof(VehicleDef, texScrollScale), CSPFT_FLOAT}, - {"wheelRotRate", offsetof(VehicleDef, wheelRotRate), CSPFT_FLOAT}, - {"extraWheelRotScale", offsetof(VehicleDef, extraWheelRotScale), CSPFT_FLOAT}, - {"wheelChildTakesSteerYaw", offsetof(VehicleDef, wheelChildTakesSteerYaw), CSPFT_QBOOLEAN}, - {"enterRadiusDriver", offsetof(VehicleDef, entryPointRadius[VEH_POS_DRIVER]), CSPFT_FLOAT}, - {"enterRadiusGunner1", offsetof(VehicleDef, entryPointRadius[VEH_POS_GUNNER_1]), CSPFT_FLOAT}, - {"enterRadiusGunner2", offsetof(VehicleDef, entryPointRadius[VEH_POS_GUNNER_2]), CSPFT_FLOAT}, - {"enterRadiusGunner3", offsetof(VehicleDef, entryPointRadius[VEH_POS_GUNNER_3]), CSPFT_FLOAT}, - {"enterRadiusGunner4", offsetof(VehicleDef, entryPointRadius[VEH_POS_GUNNER_4]), CSPFT_FLOAT}, - {"maxSpeed", offsetof(VehicleDef, maxSpeed), VFT_MPH_TO_INCHES_PER_SECOND}, - {"maxSpeedVertical", offsetof(VehicleDef, maxSpeedVertical), VFT_MPH_TO_INCHES_PER_SECOND}, - {"accel", offsetof(VehicleDef, accel), VFT_MPH_TO_INCHES_PER_SECOND}, - {"accelVertical", offsetof(VehicleDef, accelVertical), VFT_MPH_TO_INCHES_PER_SECOND}, - {"rotRate", offsetof(VehicleDef, rotRate), CSPFT_FLOAT}, - {"rotAccel", offsetof(VehicleDef, rotAccel), CSPFT_FLOAT}, - {"collisionDamage", offsetof(VehicleDef, collisionDamage), CSPFT_FLOAT}, - {"collisionSpeed", offsetof(VehicleDef, collisionSpeed), VFT_MPH_TO_INCHES_PER_SECOND}, - {"suspensionTravel", offsetof(VehicleDef, suspensionTravel), CSPFT_FLOAT}, - {"maxBodyPitch", offsetof(VehicleDef, maxBodyPitch), CSPFT_FLOAT}, - {"maxBodyRoll", offsetof(VehicleDef, maxBodyRoll), CSPFT_FLOAT}, - {"heliCollisionScalar", offsetof(VehicleDef, heliCollisionScalar), CSPFT_FLOAT}, - {"viewPitchOffset", offsetof(VehicleDef, viewPitchOffset), CSPFT_FLOAT}, - {"tiltFromAccelerationPitch", offsetof(VehicleDef, tiltFromAcceleration[0]), CSPFT_FLOAT}, - {"tiltFromAccelerationRoll", offsetof(VehicleDef, tiltFromAcceleration[1]), CSPFT_FLOAT}, - {"tiltFromDecelerationPitch", offsetof(VehicleDef, tiltFromDeceleration[0]), CSPFT_FLOAT}, - {"tiltFromDecelerationRoll", offsetof(VehicleDef, tiltFromDeceleration[1]), CSPFT_FLOAT}, - {"tiltFromVelocityPitch", offsetof(VehicleDef, tiltFromVelocity[0]), CSPFT_FLOAT}, - {"tiltFromVelocityRoll", offsetof(VehicleDef, tiltFromVelocity[1]), CSPFT_FLOAT}, - {"tiltSpeedPitch", offsetof(VehicleDef, tiltSpeed[0]), CSPFT_FLOAT}, - {"tiltSpeedRoll", offsetof(VehicleDef, tiltSpeed[1]), CSPFT_FLOAT}, - {"tracerOffsetForward", offsetof(VehicleDef, tracerOffset[0]), CSPFT_FLOAT}, - {"tracerOffsetUp", offsetof(VehicleDef, tracerOffset[1]), CSPFT_FLOAT}, - {"turretWeapon", offsetof(VehicleDef, turretWeapon), CSPFT_STRING}, - {"turretHorizSpanLeft", offsetof(VehicleDef, turretViewLimits.horizSpanLeft), CSPFT_FLOAT}, - {"turretHorizSpanRight", offsetof(VehicleDef, turretViewLimits.horizSpanRight), CSPFT_FLOAT}, - {"turretVertSpanUp", offsetof(VehicleDef, turretViewLimits.vertSpanUp), CSPFT_FLOAT}, - {"turretVertSpanDown", offsetof(VehicleDef, turretViewLimits.vertSpanDown), CSPFT_FLOAT}, - {"turretHorizResistLeft", offsetof(VehicleDef, turretViewLimits.horizResistLeft), CSPFT_FLOAT}, - {"turretHorizResistRight", offsetof(VehicleDef, turretViewLimits.horizResistRight), CSPFT_FLOAT}, - {"turretVertResistUp", offsetof(VehicleDef, turretViewLimits.vertResistUp), CSPFT_FLOAT}, - {"turretVertResistDown", offsetof(VehicleDef, turretViewLimits.vertResistDown), CSPFT_FLOAT}, - {"turretRotRate", offsetof(VehicleDef, turretRotRate), CSPFT_FLOAT}, - {"turretClampPlayerView", offsetof(VehicleDef, turretClampPlayerView), CSPFT_QBOOLEAN}, - {"turretLockTurretToPlayerView", offsetof(VehicleDef, turretLockTurretToPlayerView), CSPFT_QBOOLEAN}, - {"gunnerWeapon", offsetof(VehicleDef, gunnerWeapon[0]), CSPFT_STRING}, - {"gunnerWeapon1", offsetof(VehicleDef, gunnerWeapon[1]), CSPFT_STRING}, - {"gunnerWeapon2", offsetof(VehicleDef, gunnerWeapon[2]), CSPFT_STRING}, - {"gunnerWeapon3", offsetof(VehicleDef, gunnerWeapon[3]), CSPFT_STRING}, - {"gunnerRotRate", offsetof(VehicleDef, gunnerRotRate), CSPFT_FLOAT}, - {"passenger1HorizSpanLeft", offsetof(VehicleDef, passengerViewLimits[0].horizSpanLeft), CSPFT_FLOAT}, - {"passenger1HorizSpanRight", offsetof(VehicleDef, passengerViewLimits[0].horizSpanRight), CSPFT_FLOAT}, - {"passenger1VertSpanUp", offsetof(VehicleDef, passengerViewLimits[0].vertSpanUp), CSPFT_FLOAT}, - {"passenger1VertSpanDown", offsetof(VehicleDef, passengerViewLimits[0].vertSpanDown), CSPFT_FLOAT}, - {"passenger2HorizSpanLeft", offsetof(VehicleDef, passengerViewLimits[1].horizSpanLeft), CSPFT_FLOAT}, - {"passenger2HorizSpanRight", offsetof(VehicleDef, passengerViewLimits[1].horizSpanRight), CSPFT_FLOAT}, - {"passenger2VertSpanUp", offsetof(VehicleDef, passengerViewLimits[1].vertSpanUp), CSPFT_FLOAT}, - {"passenger2VertSpanDown", offsetof(VehicleDef, passengerViewLimits[1].vertSpanDown), CSPFT_FLOAT}, - {"passenger3HorizSpanLeft", offsetof(VehicleDef, passengerViewLimits[2].horizSpanLeft), CSPFT_FLOAT}, - {"passenger3HorizSpanRight", offsetof(VehicleDef, passengerViewLimits[2].horizSpanRight), CSPFT_FLOAT}, - {"passenger3VertSpanUp", offsetof(VehicleDef, passengerViewLimits[2].vertSpanUp), CSPFT_FLOAT}, - {"passenger3VertSpanDown", offsetof(VehicleDef, passengerViewLimits[2].vertSpanDown), CSPFT_FLOAT}, - {"passenger4HorizSpanLeft", offsetof(VehicleDef, passengerViewLimits[3].horizSpanLeft), CSPFT_FLOAT}, - {"passenger4HorizSpanRight", offsetof(VehicleDef, passengerViewLimits[3].horizSpanRight), CSPFT_FLOAT}, - {"passenger4VertSpanUp", offsetof(VehicleDef, passengerViewLimits[3].vertSpanUp), CSPFT_FLOAT}, - {"passenger4VertSpanDown", offsetof(VehicleDef, passengerViewLimits[3].vertSpanDown), CSPFT_FLOAT}, - {"passenger5HorizSpanLeft", offsetof(VehicleDef, passengerViewLimits[4].horizSpanLeft), CSPFT_FLOAT}, - {"passenger5HorizSpanRight", offsetof(VehicleDef, passengerViewLimits[4].horizSpanRight), CSPFT_FLOAT}, - {"passenger5VertSpanUp", offsetof(VehicleDef, passengerViewLimits[4].vertSpanUp), CSPFT_FLOAT}, - {"passenger5VertSpanDown", offsetof(VehicleDef, passengerViewLimits[4].vertSpanDown), CSPFT_FLOAT}, - {"passenger6HorizSpanLeft", offsetof(VehicleDef, passengerViewLimits[5].horizSpanLeft), CSPFT_FLOAT}, - {"passenger6HorizSpanRight", offsetof(VehicleDef, passengerViewLimits[5].horizSpanRight), CSPFT_FLOAT}, - {"passenger6VertSpanUp", offsetof(VehicleDef, passengerViewLimits[5].vertSpanUp), CSPFT_FLOAT}, - {"passenger6VertSpanDown", offsetof(VehicleDef, passengerViewLimits[5].vertSpanDown), CSPFT_FLOAT}, - {"turretSpinSnd", offsetof(VehicleDef, sndNames[VEH_TURRET_SPIN_SND]), CSPFT_STRING}, - {"turretStopSnd", offsetof(VehicleDef, sndNames[VEH_TURRET_STOP_SND]), CSPFT_STRING}, - {"wheelRoadNoiseSnd", offsetof(VehicleDef, sndMaterialNames[VEH_WHEEL_ROAD_NOISE]), CSPFT_STRING}, - {"wheelSlidingSnd", offsetof(VehicleDef, sndMaterialNames[VEH_WHEEL_SLIDING]), CSPFT_STRING}, - {"wheelPeelingOutSnd", offsetof(VehicleDef, sndMaterialNames[VEH_WHEEL_PEELING_OUT]), CSPFT_STRING}, - {"futzSnd", offsetof(VehicleDef, futzName), CSPFT_STRING}, - {"futzBlend", offsetof(VehicleDef, futzBlend), CSPFT_FLOAT}, - {"skidSpeedMin", offsetof(VehicleDef, skidSpeedMin), CSPFT_FLOAT}, - {"skidSpeedMax", offsetof(VehicleDef, skidSpeedMax), CSPFT_FLOAT}, - {"animType", offsetof(VehicleDef, animType), CSPFT_INT}, - {"animSet", offsetof(VehicleDef, animSet), CSPFT_STRING}, - {"scriptedAnimationEntry", offsetof(VehicleDef, scriptedAnimationEntry), CSPFT_QBOOLEAN}, - {"mantleAngleFront", offsetof(VehicleDef, mantleAngles[MANTLE_ANGLE_FRONT]), CSPFT_FLOAT}, - {"mantleAngleBack", offsetof(VehicleDef, mantleAngles[MANTLE_ANGLE_BACK]), CSPFT_FLOAT}, - {"mantleAngleLeft", offsetof(VehicleDef, mantleAngles[MANTLE_ANGLE_LEFT]), CSPFT_FLOAT}, - {"mantleAngleRight", offsetof(VehicleDef, mantleAngles[MANTLE_ANGLE_RIGHT]), CSPFT_FLOAT}, - {"driverHideTag1", offsetof(VehicleDef, driverHideTag), CSPFT_SCRIPT_STRING}, - {"extraWheelLeft1", offsetof(VehicleDef, extraWheelTags[FL_WHEEL]), CSPFT_SCRIPT_STRING}, - {"extraWheelRight1", offsetof(VehicleDef, extraWheelTags[FR_WHEEL]), CSPFT_SCRIPT_STRING}, - {"extraWheelLeft2", offsetof(VehicleDef, extraWheelTags[BL_WHEEL]), CSPFT_SCRIPT_STRING}, - {"extraWheelRight2", offsetof(VehicleDef, extraWheelTags[BR_WHEEL]), CSPFT_SCRIPT_STRING}, - {"mod0", offsetof(VehicleDef, attachmentModels[0]), CSPFT_XMODEL}, - {"tag0", offsetof(VehicleDef, attachmentTags[0]), CSPFT_SCRIPT_STRING}, - {"mod1", offsetof(VehicleDef, attachmentModels[1]), CSPFT_XMODEL}, - {"tag1", offsetof(VehicleDef, attachmentTags[1]), CSPFT_SCRIPT_STRING}, - {"mod2", offsetof(VehicleDef, attachmentModels[2]), CSPFT_XMODEL}, - {"tag2", offsetof(VehicleDef, attachmentTags[2]), CSPFT_SCRIPT_STRING}, - {"mod3", offsetof(VehicleDef, attachmentModels[3]), CSPFT_XMODEL}, - {"tag3", offsetof(VehicleDef, attachmentTags[3]), CSPFT_SCRIPT_STRING}, - {"dmod0", offsetof(VehicleDef, deathAttachmentModels[0]), CSPFT_XMODEL}, - {"dtag0", offsetof(VehicleDef, deathAttachmentTags[0]), CSPFT_SCRIPT_STRING}, - {"dmod1", offsetof(VehicleDef, deathAttachmentModels[1]), CSPFT_XMODEL}, - {"dtag1", offsetof(VehicleDef, deathAttachmentTags[1]), CSPFT_SCRIPT_STRING}, - {"dmod2", offsetof(VehicleDef, deathAttachmentModels[2]), CSPFT_XMODEL}, - {"dtag2", offsetof(VehicleDef, deathAttachmentTags[2]), CSPFT_SCRIPT_STRING}, - {"dmod3", offsetof(VehicleDef, deathAttachmentModels[3]), CSPFT_XMODEL}, - {"dtag3", offsetof(VehicleDef, deathAttachmentTags[3]), CSPFT_SCRIPT_STRING}, - {"worldModel", offsetof(VehicleDef, model), CSPFT_XMODEL}, - {"viewModel", offsetof(VehicleDef, viewModel), CSPFT_XMODEL}, - {"deathModel", offsetof(VehicleDef, deathModel), CSPFT_XMODEL}, - {"enemyModel", offsetof(VehicleDef, enemyModel), CSPFT_XMODEL}, - {"modelSwapDelay", offsetof(VehicleDef, modelSwapDelay), CSPFT_FLOAT}, - {"exhaustFx", offsetof(VehicleDef, exhaustFx), CSPFT_FX}, - {"oneExhaust", offsetof(VehicleDef, oneExhaust), CSPFT_QBOOLEAN}, - {"treadFxAsphalt", offsetof(VehicleDef, treadFx[SURF_TYPE_ASPHALT]), CSPFT_FX}, - {"treadFxBark", offsetof(VehicleDef, treadFx[SURF_TYPE_BARK]), CSPFT_FX}, - {"treadFxBrick", offsetof(VehicleDef, treadFx[SURF_TYPE_BRICK]), CSPFT_FX}, - {"treadFxCarpet", offsetof(VehicleDef, treadFx[SURF_TYPE_CARPET]), CSPFT_FX}, - {"treadFxCeramic", offsetof(VehicleDef, treadFx[SURF_TYPE_CERAMIC]), CSPFT_FX}, - {"treadFxCloth", offsetof(VehicleDef, treadFx[SURF_TYPE_CLOTH]), CSPFT_FX}, - {"treadFxConcrete", offsetof(VehicleDef, treadFx[SURF_TYPE_CONCRETE]), CSPFT_FX}, - {"treadFxCushion", offsetof(VehicleDef, treadFx[SURF_TYPE_CUSHION]), CSPFT_FX}, - {"treadFxDefault", offsetof(VehicleDef, treadFx[SURF_TYPE_DEFAULT]), CSPFT_FX}, - {"treadFxDirt", offsetof(VehicleDef, treadFx[SURF_TYPE_DIRT]), CSPFT_FX}, - {"treadFxFlesh", offsetof(VehicleDef, treadFx[SURF_TYPE_FLESH]), CSPFT_FX}, - {"treadFxFoliage", offsetof(VehicleDef, treadFx[SURF_TYPE_FOLIAGE]), CSPFT_FX}, - {"treadFxFruit", offsetof(VehicleDef, treadFx[SURF_TYPE_FRUIT]), CSPFT_FX}, - {"treadFxGlass", offsetof(VehicleDef, treadFx[SURF_TYPE_GLASS]), CSPFT_FX}, - {"treadFxGrass", offsetof(VehicleDef, treadFx[SURF_TYPE_GRASS]), CSPFT_FX}, - {"treadFxGravel", offsetof(VehicleDef, treadFx[SURF_TYPE_GRAVEL]), CSPFT_FX}, - {"treadFxIce", offsetof(VehicleDef, treadFx[SURF_TYPE_ICE]), CSPFT_FX}, - {"treadFxMetal", offsetof(VehicleDef, treadFx[SURF_TYPE_METAL]), CSPFT_FX}, - {"treadFxMud", offsetof(VehicleDef, treadFx[SURF_TYPE_MUD]), CSPFT_FX}, - {"treadFxPaintedMetal", offsetof(VehicleDef, treadFx[SURF_TYPE_PAINTED_METAL]), CSPFT_FX}, - {"treadFxPaper", offsetof(VehicleDef, treadFx[SURF_TYPE_PAPER]), CSPFT_FX}, - {"treadFxPlaster", offsetof(VehicleDef, treadFx[SURF_TYPE_PLASTER]), CSPFT_FX}, - {"treadFxPlastic", offsetof(VehicleDef, treadFx[SURF_TYPE_PLASTIC]), CSPFT_FX}, - {"treadFxRock", offsetof(VehicleDef, treadFx[SURF_TYPE_ROCK]), CSPFT_FX}, - {"treadFxRubber", offsetof(VehicleDef, treadFx[SURF_TYPE_RUBBER]), CSPFT_FX}, - {"treadFxSand", offsetof(VehicleDef, treadFx[SURF_TYPE_SAND]), CSPFT_FX}, - {"treadFxSnow", offsetof(VehicleDef, treadFx[SURF_TYPE_SNOW]), CSPFT_FX}, - {"treadFxWater", offsetof(VehicleDef, treadFx[SURF_TYPE_WATER]), CSPFT_FX}, - {"treadFxWood", offsetof(VehicleDef, treadFx[SURF_TYPE_WOOD]), CSPFT_FX}, - {"deathFxName", offsetof(VehicleDef, deathFx), CSPFT_FX}, - {"deathFxTag", offsetof(VehicleDef, deathFxTag), CSPFT_SCRIPT_STRING}, - {"deathFxSound", offsetof(VehicleDef, deathFxSound), CSPFT_STRING}, - {"lightFxName1", offsetof(VehicleDef, lightFx[0]), CSPFT_FX}, - {"lightFxTag1", offsetof(VehicleDef, lightFxTag[0]), CSPFT_SCRIPT_STRING}, - {"lightFxName2", offsetof(VehicleDef, lightFx[1]), CSPFT_FX}, - {"lightFxTag2", offsetof(VehicleDef, lightFxTag[1]), CSPFT_SCRIPT_STRING}, - {"lightFxName3", offsetof(VehicleDef, lightFx[2]), CSPFT_FX}, - {"lightFxTag3", offsetof(VehicleDef, lightFxTag[2]), CSPFT_SCRIPT_STRING}, - {"lightFxName4", offsetof(VehicleDef, lightFx[3]), CSPFT_FX}, - {"lightFxTag4", offsetof(VehicleDef, lightFxTag[3]), CSPFT_SCRIPT_STRING}, - {"FriendlyLightFxName", offsetof(VehicleDef, friendlyLightFx), CSPFT_FX}, - {"FriendlyLightFxTag", offsetof(VehicleDef, friendlyLightFxTag), CSPFT_SCRIPT_STRING}, - {"EnemyLightFxName", offsetof(VehicleDef, enemyLightFx), CSPFT_FX}, - {"EnemyLightFxTag", offsetof(VehicleDef, enemyLightFxTag), CSPFT_SCRIPT_STRING}, - {"radiusDamageMin", offsetof(VehicleDef, radiusDamageMin), CSPFT_FLOAT}, - {"radiusDamageMax", offsetof(VehicleDef, radiusDamageMax), CSPFT_FLOAT}, - {"radiusDamageRadius", offsetof(VehicleDef, radiusDamageRadius), CSPFT_FLOAT}, - {"shootShock", offsetof(VehicleDef, shootShock), CSPFT_STRING}, - {"shootRumble", offsetof(VehicleDef, shootRumble), CSPFT_STRING}, - {"deathQuakeScale", offsetof(VehicleDef, deathQuakeScale), CSPFT_FLOAT}, - {"deathQuakeDuration", offsetof(VehicleDef, deathQuakeDuration), CSPFT_FLOAT}, - {"deathQuakeRadius", offsetof(VehicleDef, deathQuakeRadius), CSPFT_FLOAT}, - {"rumbleType", offsetof(VehicleDef, rumbleType), CSPFT_STRING}, - {"rumbleScale", offsetof(VehicleDef, rumbleScale), CSPFT_FLOAT}, - {"rumbleDuration", offsetof(VehicleDef, rumbleDuration), CSPFT_FLOAT}, - {"rumbleRadius", offsetof(VehicleDef, rumbleRadius), CSPFT_FLOAT}, - {"rumbleBaseTime", offsetof(VehicleDef, rumbleBaseTime), CSPFT_FLOAT}, - {"rumbleAdditionalTime", offsetof(VehicleDef, rumbleAdditionalTime), CSPFT_FLOAT}, - {"healthDefault", offsetof(VehicleDef, healthDefault), CSPFT_INT}, - {"healthMin", offsetof(VehicleDef, healthMin), CSPFT_INT}, - {"healthMax", offsetof(VehicleDef, healthMax), CSPFT_INT}, - {"team", offsetof(VehicleDef, eTeam), VFT_TEAM}, - {"boostAccelMultiplier", offsetof(VehicleDef, boostAccelMultiplier), CSPFT_INT}, - {"boostDuration", offsetof(VehicleDef, boostDuration), CSPFT_FLOAT}, - {"boostSpeedIncrease", offsetof(VehicleDef, boostSpeedIncrease), CSPFT_FLOAT}, - {"addToCompass", offsetof(VehicleDef, addToCompass), CSPFT_QBOOLEAN}, - {"addToCompassEnemy", offsetof(VehicleDef, addToCompassEnemy), CSPFT_QBOOLEAN}, - {"compassIcon", offsetof(VehicleDef, compassIcon), CSPFT_STRING}, - {"gasButton", offsetof(VehicleDef, gasButtonName), CSPFT_STRING}, - {"reverseBrakeButton", offsetof(VehicleDef, reverseBrakeButtonName), CSPFT_STRING}, - {"handBrakeButton", offsetof(VehicleDef, handBrakeButtonName), CSPFT_STRING}, - {"attackButton", offsetof(VehicleDef, attackButtonName), CSPFT_STRING}, - {"attackSecondaryButton", offsetof(VehicleDef, attackSecondaryButtonName), CSPFT_STRING}, - {"moveUpButton", offsetof(VehicleDef, moveUpButtonName), CSPFT_STRING}, - {"moveDownButton", offsetof(VehicleDef, moveDownButtonName), CSPFT_STRING}, - {"switchSeatButton", offsetof(VehicleDef, switchSeatButtonName), CSPFT_STRING}, - {"boostButton", offsetof(VehicleDef, boostButtonName), CSPFT_STRING}, - {"steerGraph", offsetof(VehicleDef, steerGraphName), CSPFT_STRING}, - {"accelGraph", offsetof(VehicleDef, accelGraphName), CSPFT_STRING}, - {"isNitrous", offsetof(VehicleDef, isNitrous), CSPFT_QBOOLEAN}, - {"isFourWheelSteering", offsetof(VehicleDef, isFourWheelSteering), CSPFT_QBOOLEAN}, - {"useCollmap", offsetof(VehicleDef, useCollmap), CSPFT_QBOOLEAN}, - {"radius", offsetof(VehicleDef, radius), CSPFT_FLOAT}, - {"minHeight", offsetof(VehicleDef, minHeight), CSPFT_FLOAT}, - {"maxHeight", offsetof(VehicleDef, maxHeight), CSPFT_FLOAT}, - {"noDirectionalDamage", offsetof(VehicleDef, noDirectionalDamage), CSPFT_QBOOLEAN}, - {"max_fric_tilt_angle", offsetof(VehicleDef, max_fric_tilt_angle), CSPFT_FLOAT}, - {"max_fric_tilt", offsetof(VehicleDef, max_fric_tilt), CSPFT_FLOAT}, - {"fakeBodyStabilizer", offsetof(VehicleDef, fakeBodyStabilizer), CSPFT_QBOOLEAN}, - {"vehHelicopterBoundsRadius", offsetof(VehicleDef, vehHelicopterBoundsRadius), CSPFT_FLOAT}, - {"vehHelicopterDecelerationFwd", offsetof(VehicleDef, vehHelicopterDecelerationFwd), CSPFT_FLOAT}, - {"vehHelicopterDecelerationSide", offsetof(VehicleDef, vehHelicopterDecelerationSide), CSPFT_FLOAT}, - {"vehHelicopterDecelerationUp", offsetof(VehicleDef, vehHelicopterDecelerationUp), CSPFT_FLOAT}, - {"vehHelicopterTiltFromControllerAxes", offsetof(VehicleDef, vehHelicopterTiltFromControllerAxes), CSPFT_FLOAT}, - {"vehHelicopterTiltFromFwdAndYaw", offsetof(VehicleDef, vehHelicopterTiltFromFwdAndYaw), CSPFT_FLOAT}, - {"vehHelicopterTiltFromFwdAndYaw_VelAtMaxTilt", offsetof(VehicleDef, vehHelicopterTiltFromFwdAndYaw_VelAtMaxTilt), CSPFT_FLOAT}, - {"vehHelicopterTiltMomentum", offsetof(VehicleDef, vehHelicopterTiltMomentum), CSPFT_FLOAT}, - {"vehHelicopterQuadRotor", offsetof(VehicleDef, vehHelicopterQuadRotor), CSPFT_QBOOLEAN}, - {"vehHelicopterAccelTwardsView", offsetof(VehicleDef, vehHelicopterAccelTwardsView), CSPFT_QBOOLEAN}, - {"maxRotorArmMovementAngle", offsetof(VehicleDef, maxRotorArmMovementAngle), CSPFT_FLOAT}, - {"maxRotorArmRotationAngle", offsetof(VehicleDef, maxRotorArmRotationAngle), CSPFT_FLOAT}, - {"vehHelicopterMaintainHeight", offsetof(VehicleDef, vehHelicopterMaintainHeight), CSPFT_QBOOLEAN}, - {"vehHelicopterMaintainMaxHeight", offsetof(VehicleDef, vehHelicopterMaintainMaxHeight), CSPFT_QBOOLEAN}, - {"vehHelicopterMaintainHeightLimit", offsetof(VehicleDef, vehHelicopterMaintainHeightLimit), CSPFT_FLOAT}, - {"vehHelicopterMaintainHeightAccel", offsetof(VehicleDef, vehHelicopterMaintainHeightAccel), CSPFT_FLOAT}, - {"vehHelicopterMaintainHeightMinimum", offsetof(VehicleDef, vehHelicopterMaintainHeightMinimum), CSPFT_FLOAT}, - {"vehHelicopterMaintainHeightMaximum", offsetof(VehicleDef, vehHelicopterMaintainHeightMaximum), CSPFT_FLOAT}, - {"vehHelicopterMaintainCeilingMinimum", offsetof(VehicleDef, vehHelicopterMaintainCeilingMinimum), CSPFT_FLOAT}, - {"joltVehicle", offsetof(VehicleDef, joltVehicle), CSPFT_QBOOLEAN}, - {"joltVehicleDriver", offsetof(VehicleDef, joltVehicleDriver), CSPFT_QBOOLEAN}, - {"joltMaxTime", offsetof(VehicleDef, joltMaxTime), CSPFT_FLOAT}, - {"joltTime", offsetof(VehicleDef, joltTime), CSPFT_FLOAT}, - {"joltWaves", offsetof(VehicleDef, joltWaves), CSPFT_FLOAT}, - {"joltIntensity", offsetof(VehicleDef, joltIntensity), CSPFT_FLOAT}, - {"nitrous_max_speed", offsetof(VehicleDef, nitrousVehParams.m_speed_max), VFT_MPH_TO_INCHES_PER_SECOND}, - {"nitrous_accel", offsetof(VehicleDef, nitrousVehParams.m_accel_max), VFT_MPH_TO_INCHES_PER_SECOND}, - {"nitrous_auto_handbrake_min_speed", offsetof(VehicleDef, nitrousVehParams.m_auto_hand_brake_min_speed), VFT_MPH_TO_INCHES_PER_SECOND}, - {"nitrous_steer_angle_max", offsetof(VehicleDef, nitrousVehParams.m_steer_angle_max), CSPFT_FLOAT}, - {"nitrous_steer_angle_speed_scale", offsetof(VehicleDef, nitrousVehParams.m_steer_angle_speed_scale), CSPFT_FLOAT}, - {"nitrous_steer_speed", offsetof(VehicleDef, nitrousVehParams.m_steer_speed), CSPFT_FLOAT}, - {"nitrous_body_mass", offsetof(VehicleDef, nitrousVehParams.m_body_mass), VFT_POUNDS_TO_GAME_MASS}, - {"nitrous_wheel_radius", offsetof(VehicleDef, nitrousVehParams.m_wheel_radius), CSPFT_FLOAT}, - {"nitrous_susp_adj", offsetof(VehicleDef, nitrousVehParams.m_susp_adj), CSPFT_FLOAT}, - {"nitrous_susp_spring_k", offsetof(VehicleDef, nitrousVehParams.m_susp_spring_k), CSPFT_FLOAT}, - {"nitrous_susp_damp_k", offsetof(VehicleDef, nitrousVehParams.m_susp_damp_k), CSPFT_FLOAT}, - {"nitrous_susp_hard_limit", offsetof(VehicleDef, nitrousVehParams.m_susp_hard_limit), CSPFT_FLOAT}, - {"nitrous_susp_min_height", offsetof(VehicleDef, nitrousVehParams.m_susp_min_height), CSPFT_FLOAT}, - {"nitrous_tire_damp_hand", offsetof(VehicleDef, nitrousVehParams.m_tire_damp_hand), CSPFT_FLOAT}, - {"nitrous_tire_damp_brake", offsetof(VehicleDef, nitrousVehParams.m_tire_damp_brake), CSPFT_FLOAT}, - {"nitrous_tire_damp_coast", offsetof(VehicleDef, nitrousVehParams.m_tire_damp_coast), CSPFT_FLOAT}, - {"nitrous_tire_fric_brake", offsetof(VehicleDef, nitrousVehParams.m_tire_fric_brake), CSPFT_FLOAT}, - {"nitrous_tire_fric_hand_brake", offsetof(VehicleDef, nitrousVehParams.m_tire_fric_hand_brake), CSPFT_FLOAT}, - {"nitrous_tire_fric_fwd", offsetof(VehicleDef, nitrousVehParams.m_tire_fric_fwd), CSPFT_FLOAT}, - {"nitrous_tire_fric_side", offsetof(VehicleDef, nitrousVehParams.m_tire_fric_side), CSPFT_FLOAT}, - {"nitrous_roll_stability", offsetof(VehicleDef, nitrousVehParams.m_roll_stability), CSPFT_FLOAT}, - {"nitrous_pitch_stability", offsetof(VehicleDef, nitrousVehParams.m_pitch_stability), CSPFT_FLOAT}, - {"nitrous_roll_resistance", offsetof(VehicleDef, nitrousVehParams.m_pitch_roll_resistance), CSPFT_FLOAT}, - {"nitrous_yaw_resistance", offsetof(VehicleDef, nitrousVehParams.m_yaw_resistance), CSPFT_FLOAT}, - {"nitrous_upright_strength", offsetof(VehicleDef, nitrousVehParams.m_upright_strength), CSPFT_FLOAT}, - {"nitrous_tilt_fakey", offsetof(VehicleDef, nitrousVehParams.m_tilt_fakey), CSPFT_FLOAT}, - {"nitrous_traction_type", offsetof(VehicleDef, nitrousVehParams.m_traction_type), VFT_TRACTION_TYPE}, - {"nitrous_peel_out_max_speed", offsetof(VehicleDef, nitrousVehParams.m_peel_out_max_speed), CSPFT_FLOAT}, - {"nitrous_tire_fric_side_max", offsetof(VehicleDef, nitrousVehParams.m_tire_fric_side_max), CSPFT_FLOAT}, - {"nitrous_reverse_scale", offsetof(VehicleDef, nitrousVehParams.m_reverse_scale), CSPFT_FLOAT}, - {"nitrous_water_speed_max", offsetof(VehicleDef, nitrousVehParams.m_water_speed_max), VFT_MPH_TO_INCHES_PER_SECOND}, - {"nitrous_water_accel_max", offsetof(VehicleDef, nitrousVehParams.m_water_accel_max), CSPFT_FLOAT}, - {"nitrous_water_turn_accel", offsetof(VehicleDef, nitrousVehParams.m_water_turn_accel), CSPFT_FLOAT}, - {"nitrous_water_turn_speed_max", offsetof(VehicleDef, nitrousVehParams.m_water_turn_speed_max), CSPFT_FLOAT}, - {"nitrous_boat_ebrake_power", offsetof(VehicleDef, nitrousVehParams.m_water_ebrake_power), CSPFT_FLOAT}, - {"nitrous_bbox_min_x", offsetof(VehicleDef, nitrousVehParams.m_bbox_min.x), CSPFT_FLOAT}, - {"nitrous_bbox_min_y", offsetof(VehicleDef, nitrousVehParams.m_bbox_min.y), CSPFT_FLOAT}, - {"nitrous_bbox_min_z", offsetof(VehicleDef, nitrousVehParams.m_bbox_min.z), CSPFT_FLOAT}, - {"nitrous_bbox_max_x", offsetof(VehicleDef, nitrousVehParams.m_bbox_max.x), CSPFT_FLOAT}, - {"nitrous_bbox_max_y", offsetof(VehicleDef, nitrousVehParams.m_bbox_max.y), CSPFT_FLOAT}, - {"nitrous_bbox_max_z", offsetof(VehicleDef, nitrousVehParams.m_bbox_max.z), CSPFT_FLOAT}, - {"nitrous_mass_center_offset_x", offsetof(VehicleDef, nitrousVehParams.m_mass_center_offset.x), CSPFT_FLOAT}, - {"nitrous_mass_center_offset_y", offsetof(VehicleDef, nitrousVehParams.m_mass_center_offset.y), CSPFT_FLOAT}, - {"nitrous_mass_center_offset_z", offsetof(VehicleDef, nitrousVehParams.m_mass_center_offset.z), CSPFT_FLOAT}, - {"nitrous_buoyancybox_min_x", offsetof(VehicleDef, nitrousVehParams.m_buoyancybox_min.x), CSPFT_FLOAT}, - {"nitrous_buoyancybox_min_y", offsetof(VehicleDef, nitrousVehParams.m_buoyancybox_min.y), CSPFT_FLOAT}, - {"nitrous_buoyancybox_min_z", offsetof(VehicleDef, nitrousVehParams.m_buoyancybox_min.z), CSPFT_FLOAT}, - {"nitrous_buoyancybox_max_x", offsetof(VehicleDef, nitrousVehParams.m_buoyancybox_max.x), CSPFT_FLOAT}, - {"nitrous_buoyancybox_max_y", offsetof(VehicleDef, nitrousVehParams.m_buoyancybox_max.y), CSPFT_FLOAT}, - {"nitrous_buoyancybox_max_z", offsetof(VehicleDef, nitrousVehParams.m_buoyancybox_max.z), CSPFT_FLOAT}, - {"nitrous_boat_speed_rise", offsetof(VehicleDef, nitrousVehParams.m_boat_speed_rise), CSPFT_FLOAT}, - {"nitrous_boat_speed_tilt", offsetof(VehicleDef, nitrousVehParams.m_boat_speed_tilt), CSPFT_FLOAT}, - {"nitrous_boat_motor_offset_x", offsetof(VehicleDef, nitrousVehParams.m_boat_motor_offset.x), CSPFT_FLOAT}, - {"nitrous_boat_motor_offset_y", offsetof(VehicleDef, nitrousVehParams.m_boat_motor_offset.y), CSPFT_FLOAT}, - {"nitrous_boat_motor_offset_z", offsetof(VehicleDef, nitrousVehParams.m_boat_motor_offset.z), CSPFT_FLOAT}, - {"nitrous_boat_side_fric", offsetof(VehicleDef, nitrousVehParams.m_boat_side_fric_scale), CSPFT_FLOAT}, - {"nitrous_boat_forward_fric", offsetof(VehicleDef, nitrousVehParams.m_boat_forward_fric_scale), CSPFT_FLOAT}, - {"nitrous_boat_vertical_fric", offsetof(VehicleDef, nitrousVehParams.m_boat_vertical_fric_scale), CSPFT_FLOAT}, - {"nitrous_drive_on_walls", offsetof(VehicleDef, nitrousVehParams.m_drive_on_walls), CSPFT_BOOL}, - {"nitrous_linear_drag_scale", offsetof(VehicleDef, nitrousVehParams.m_linear_drag_scale), CSPFT_FLOAT}, - {"nitrous_angular_drag_scale", offsetof(VehicleDef, nitrousVehParams.m_angular_drag_scale), CSPFT_FLOAT}, - {"nitrous_jump_force", offsetof(VehicleDef, nitrousVehParams.m_jump_force), CSPFT_FLOAT}, - {"p_driveby_sound_radius", offsetof(VehicleDef, driveBySoundRadius[0]), CSPFT_FLOAT}, - {"s_driveby_sound_radius", offsetof(VehicleDef, driveBySoundRadius[1]), CSPFT_FLOAT}, - {"p_drive_by_sound_apex0", offsetof(VehicleDef, driveBySounds[0].apex), CSPFT_INT}, - {"p_drive_by_sound_name0", offsetof(VehicleDef, driveBySounds[0].name), CSPFT_STRING}, - {"p_drive_by_sound_apex1", offsetof(VehicleDef, driveBySounds[1].apex), CSPFT_INT}, - {"p_drive_by_sound_name1", offsetof(VehicleDef, driveBySounds[1].name), CSPFT_STRING}, - {"p_drive_by_sound_apex2", offsetof(VehicleDef, driveBySounds[2].apex), CSPFT_INT}, - {"p_drive_by_sound_name2", offsetof(VehicleDef, driveBySounds[2].name), CSPFT_STRING}, - {"p_drive_by_sound_apex3", offsetof(VehicleDef, driveBySounds[3].apex), CSPFT_INT}, - {"p_drive_by_sound_name3", offsetof(VehicleDef, driveBySounds[3].name), CSPFT_STRING}, - {"p_drive_by_sound_apex4", offsetof(VehicleDef, driveBySounds[4].apex), CSPFT_INT}, - {"p_drive_by_sound_name4", offsetof(VehicleDef, driveBySounds[4].name), CSPFT_STRING}, - {"p_drive_by_sound_apex5", offsetof(VehicleDef, driveBySounds[5].apex), CSPFT_INT}, - {"p_drive_by_sound_name5", offsetof(VehicleDef, driveBySounds[5].name), CSPFT_STRING}, - {"p_drive_by_sound_apex6", offsetof(VehicleDef, driveBySounds[6].apex), CSPFT_INT}, - {"p_drive_by_sound_name6", offsetof(VehicleDef, driveBySounds[6].name), CSPFT_STRING}, - {"p_drive_by_sound_apex7", offsetof(VehicleDef, driveBySounds[7].apex), CSPFT_INT}, - {"p_drive_by_sound_name7", offsetof(VehicleDef, driveBySounds[7].name), CSPFT_STRING}, - {"p_drive_by_sound_apex8", offsetof(VehicleDef, driveBySounds[8].apex), CSPFT_INT}, - {"p_drive_by_sound_name8", offsetof(VehicleDef, driveBySounds[8].name), CSPFT_STRING}, - {"p_drive_by_sound_apex9", offsetof(VehicleDef, driveBySounds[9].apex), CSPFT_INT}, - {"p_drive_by_sound_name9", offsetof(VehicleDef, driveBySounds[9].name), CSPFT_STRING}, - {"p_drive_by_sound_apex10", offsetof(VehicleDef, driveBySounds[10].apex), CSPFT_INT}, - {"p_drive_by_sound_name10", offsetof(VehicleDef, driveBySounds[10].name), CSPFT_STRING}, - {"p_drive_by_sound_apex11", offsetof(VehicleDef, driveBySounds[11].apex), CSPFT_INT}, - {"p_drive_by_sound_name11", offsetof(VehicleDef, driveBySounds[11].name), CSPFT_STRING}, - {"p_drive_by_sound_apex12", offsetof(VehicleDef, driveBySounds[12].apex), CSPFT_INT}, - {"p_drive_by_sound_name12", offsetof(VehicleDef, driveBySounds[12].name), CSPFT_STRING}, - {"p_drive_by_sound_apex13", offsetof(VehicleDef, driveBySounds[13].apex), CSPFT_INT}, - {"p_drive_by_sound_name13", offsetof(VehicleDef, driveBySounds[13].name), CSPFT_STRING}, - {"p_drive_by_sound_apex14", offsetof(VehicleDef, driveBySounds[14].apex), CSPFT_INT}, - {"p_drive_by_sound_name14", offsetof(VehicleDef, driveBySounds[14].name), CSPFT_STRING}, - {"p_drive_by_sound_apex15", offsetof(VehicleDef, driveBySounds[15].apex), CSPFT_INT}, - {"p_drive_by_sound_name15", offsetof(VehicleDef, driveBySounds[15].name), CSPFT_STRING}, - {"p_drive_by_sound_apex16", offsetof(VehicleDef, driveBySounds[16].apex), CSPFT_INT}, - {"p_drive_by_sound_name16", offsetof(VehicleDef, driveBySounds[16].name), CSPFT_STRING}, - {"p_drive_by_sound_apex17", offsetof(VehicleDef, driveBySounds[17].apex), CSPFT_INT}, - {"p_drive_by_sound_name17", offsetof(VehicleDef, driveBySounds[17].name), CSPFT_STRING}, - {"p_drive_by_sound_apex18", offsetof(VehicleDef, driveBySounds[18].apex), CSPFT_INT}, - {"p_drive_by_sound_name18", offsetof(VehicleDef, driveBySounds[18].name), CSPFT_STRING}, - {"p_drive_by_sound_apex19", offsetof(VehicleDef, driveBySounds[19].apex), CSPFT_INT}, - {"p_drive_by_sound_name19", offsetof(VehicleDef, driveBySounds[19].name), CSPFT_STRING}, - {"s_drive_by_sound_apex0", offsetof(VehicleDef, driveBySounds[20].apex), CSPFT_INT}, - {"s_drive_by_sound_name0", offsetof(VehicleDef, driveBySounds[20].name), CSPFT_STRING}, - {"s_drive_by_sound_apex1", offsetof(VehicleDef, driveBySounds[21].apex), CSPFT_INT}, - {"s_drive_by_sound_name1", offsetof(VehicleDef, driveBySounds[21].name), CSPFT_STRING}, - {"s_drive_by_sound_apex2", offsetof(VehicleDef, driveBySounds[22].apex), CSPFT_INT}, - {"s_drive_by_sound_name2", offsetof(VehicleDef, driveBySounds[22].name), CSPFT_STRING}, - {"s_drive_by_sound_apex3", offsetof(VehicleDef, driveBySounds[23].apex), CSPFT_INT}, - {"s_drive_by_sound_name3", offsetof(VehicleDef, driveBySounds[23].name), CSPFT_STRING}, - {"s_drive_by_sound_apex4", offsetof(VehicleDef, driveBySounds[24].apex), CSPFT_INT}, - {"s_drive_by_sound_name4", offsetof(VehicleDef, driveBySounds[24].name), CSPFT_STRING}, - {"s_drive_by_sound_apex5", offsetof(VehicleDef, driveBySounds[25].apex), CSPFT_INT}, - {"s_drive_by_sound_name5", offsetof(VehicleDef, driveBySounds[25].name), CSPFT_STRING}, - {"s_drive_by_sound_apex6", offsetof(VehicleDef, driveBySounds[26].apex), CSPFT_INT}, - {"s_drive_by_sound_name6", offsetof(VehicleDef, driveBySounds[26].name), CSPFT_STRING}, - {"s_drive_by_sound_apex7", offsetof(VehicleDef, driveBySounds[27].apex), CSPFT_INT}, - {"s_drive_by_sound_name7", offsetof(VehicleDef, driveBySounds[27].name), CSPFT_STRING}, - {"s_drive_by_sound_apex8", offsetof(VehicleDef, driveBySounds[28].apex), CSPFT_INT}, - {"s_drive_by_sound_name8", offsetof(VehicleDef, driveBySounds[28].name), CSPFT_STRING}, - {"s_drive_by_sound_apex9", offsetof(VehicleDef, driveBySounds[29].apex), CSPFT_INT}, - {"s_drive_by_sound_name9", offsetof(VehicleDef, driveBySounds[29].name), CSPFT_STRING}, - {"s_drive_by_sound_apex10", offsetof(VehicleDef, driveBySounds[30].apex), CSPFT_INT}, - {"s_drive_by_sound_name10", offsetof(VehicleDef, driveBySounds[30].name), CSPFT_STRING}, - {"s_drive_by_sound_apex11", offsetof(VehicleDef, driveBySounds[31].apex), CSPFT_INT}, - {"s_drive_by_sound_name11", offsetof(VehicleDef, driveBySounds[31].name), CSPFT_STRING}, - {"s_drive_by_sound_apex12", offsetof(VehicleDef, driveBySounds[32].apex), CSPFT_INT}, - {"s_drive_by_sound_name12", offsetof(VehicleDef, driveBySounds[32].name), CSPFT_STRING}, - {"s_drive_by_sound_apex13", offsetof(VehicleDef, driveBySounds[33].apex), CSPFT_INT}, - {"s_drive_by_sound_name13", offsetof(VehicleDef, driveBySounds[33].name), CSPFT_STRING}, - {"s_drive_by_sound_apex14", offsetof(VehicleDef, driveBySounds[34].apex), CSPFT_INT}, - {"s_drive_by_sound_name14", offsetof(VehicleDef, driveBySounds[34].name), CSPFT_STRING}, - {"s_drive_by_sound_apex15", offsetof(VehicleDef, driveBySounds[35].apex), CSPFT_INT}, - {"s_drive_by_sound_name15", offsetof(VehicleDef, driveBySounds[35].name), CSPFT_STRING}, - {"s_drive_by_sound_apex16", offsetof(VehicleDef, driveBySounds[36].apex), CSPFT_INT}, - {"s_drive_by_sound_name16", offsetof(VehicleDef, driveBySounds[36].name), CSPFT_STRING}, - {"s_drive_by_sound_apex17", offsetof(VehicleDef, driveBySounds[37].apex), CSPFT_INT}, - {"s_drive_by_sound_name17", offsetof(VehicleDef, driveBySounds[37].name), CSPFT_STRING}, - {"s_drive_by_sound_apex18", offsetof(VehicleDef, driveBySounds[38].apex), CSPFT_INT}, - {"s_drive_by_sound_name18", offsetof(VehicleDef, driveBySounds[38].name), CSPFT_STRING}, - {"s_drive_by_sound_apex19", offsetof(VehicleDef, driveBySounds[39].apex), CSPFT_INT}, - {"s_drive_by_sound_name19", offsetof(VehicleDef, driveBySounds[39].name), CSPFT_STRING}, - {"doFootSteps", offsetof(VehicleDef, doFootSteps), CSPFT_BOOL}, - {"isSentient", offsetof(VehicleDef, isSentient), CSPFT_BOOL}, - {"idleRpms", offsetof(VehicleDef, engine.idleRpms), CSPFT_FLOAT}, - {"maxRpms", offsetof(VehicleDef, engine.maxRpms), CSPFT_FLOAT}, - {"maxTorque", offsetof(VehicleDef, engine.maxTorque), CSPFT_FLOAT}, - {"brakingCoeff", offsetof(VehicleDef, engine.brakingCoeff), CSPFT_FLOAT}, - {"onLoadFadeInStart", offsetof(VehicleDef, engine.loadFadeParams.x), CSPFT_FLOAT}, - {"onLoadFadeInEnd", offsetof(VehicleDef, engine.loadFadeParams.y), CSPFT_FLOAT}, - {"offLoadFadeOutStart", offsetof(VehicleDef, engine.loadFadeParams.z), CSPFT_FLOAT}, - {"offLoadFadeOutEnd", offsetof(VehicleDef, engine.loadFadeParams.w), CSPFT_FLOAT}, - {"loadScale", offsetof(VehicleDef, engine.loadScale), CSPFT_FLOAT}, - {"loadSmooting", offsetof(VehicleDef, engine.loadSmoothing), CSPFT_FLOAT}, - {"throttleLag", offsetof(VehicleDef, engine.throttleLag), CSPFT_FLOAT}, - {"pitchScale", offsetof(VehicleDef, engine.pitchScale), CSPFT_FLOAT}, - {"on_engsnd_name0", offsetof(VehicleDef, engine.onload[0].name), CSPFT_STRING}, - {"on_engsnd_fade_in_start0", offsetof(VehicleDef, engine.onload[0].params[VEH_ENGINESND_FADE_IN_START]), CSPFT_FLOAT}, - {"on_engsnd_fade_in_end0", offsetof(VehicleDef, engine.onload[0].params[VEH_ENGINESND_FADE_IN_END]), CSPFT_FLOAT}, - {"on_engsnd_fade_out_start0", offsetof(VehicleDef, engine.onload[0].params[VEH_ENGINESND_FADE_OUT_START]), CSPFT_FLOAT}, - {"on_engsnd_fade_out_end0", offsetof(VehicleDef, engine.onload[0].params[VEH_ENGINESND_FADE_OUT_END]), CSPFT_FLOAT}, - {"on_engsnd_pitch_ref0", offsetof(VehicleDef, engine.onload[0].params[VEH_ENGINESND_PITCH_REF]), CSPFT_FLOAT}, - {"on_engsnd_name1", offsetof(VehicleDef, engine.onload[1].name), CSPFT_STRING}, - {"on_engsnd_fade_in_start1", offsetof(VehicleDef, engine.onload[1].params[VEH_ENGINESND_FADE_IN_START]), CSPFT_FLOAT}, - {"on_engsnd_fade_in_end1", offsetof(VehicleDef, engine.onload[1].params[VEH_ENGINESND_FADE_IN_END]), CSPFT_FLOAT}, - {"on_engsnd_fade_out_start1", offsetof(VehicleDef, engine.onload[1].params[VEH_ENGINESND_FADE_OUT_START]), CSPFT_FLOAT}, - {"on_engsnd_fade_out_end1", offsetof(VehicleDef, engine.onload[1].params[VEH_ENGINESND_FADE_OUT_END]), CSPFT_FLOAT}, - {"on_engsnd_pitch_ref1", offsetof(VehicleDef, engine.onload[1].params[VEH_ENGINESND_PITCH_REF]), CSPFT_FLOAT}, - {"on_engsnd_name2", offsetof(VehicleDef, engine.onload[2].name), CSPFT_STRING}, - {"on_engsnd_fade_in_start2", offsetof(VehicleDef, engine.onload[2].params[VEH_ENGINESND_FADE_IN_START]), CSPFT_FLOAT}, - {"on_engsnd_fade_in_end2", offsetof(VehicleDef, engine.onload[2].params[VEH_ENGINESND_FADE_IN_END]), CSPFT_FLOAT}, - {"on_engsnd_fade_out_start2", offsetof(VehicleDef, engine.onload[2].params[VEH_ENGINESND_FADE_OUT_START]), CSPFT_FLOAT}, - {"on_engsnd_fade_out_end2", offsetof(VehicleDef, engine.onload[2].params[VEH_ENGINESND_FADE_OUT_END]), CSPFT_FLOAT}, - {"on_engsnd_pitch_ref2", offsetof(VehicleDef, engine.onload[2].params[VEH_ENGINESND_PITCH_REF]), CSPFT_FLOAT}, - {"on_engsnd_name3", offsetof(VehicleDef, engine.onload[3].name), CSPFT_STRING}, - {"on_engsnd_fade_in_start3", offsetof(VehicleDef, engine.onload[3].params[VEH_ENGINESND_FADE_IN_START]), CSPFT_FLOAT}, - {"on_engsnd_fade_in_end3", offsetof(VehicleDef, engine.onload[3].params[VEH_ENGINESND_FADE_IN_END]), CSPFT_FLOAT}, - {"on_engsnd_fade_out_start3", offsetof(VehicleDef, engine.onload[3].params[VEH_ENGINESND_FADE_OUT_START]), CSPFT_FLOAT}, - {"on_engsnd_fade_out_end3", offsetof(VehicleDef, engine.onload[3].params[VEH_ENGINESND_FADE_OUT_END]), CSPFT_FLOAT}, - {"on_engsnd_pitch_ref3", offsetof(VehicleDef, engine.onload[3].params[VEH_ENGINESND_PITCH_REF]), CSPFT_FLOAT}, - {"on_engsnd_name4", offsetof(VehicleDef, engine.onload[4].name), CSPFT_STRING}, - {"on_engsnd_fade_in_start4", offsetof(VehicleDef, engine.onload[4].params[VEH_ENGINESND_FADE_IN_START]), CSPFT_FLOAT}, - {"on_engsnd_fade_in_end4", offsetof(VehicleDef, engine.onload[4].params[VEH_ENGINESND_FADE_IN_END]), CSPFT_FLOAT}, - {"on_engsnd_fade_out_start4", offsetof(VehicleDef, engine.onload[4].params[VEH_ENGINESND_FADE_OUT_START]), CSPFT_FLOAT}, - {"on_engsnd_fade_out_end4", offsetof(VehicleDef, engine.onload[4].params[VEH_ENGINESND_FADE_OUT_END]), CSPFT_FLOAT}, - {"on_engsnd_pitch_ref4", offsetof(VehicleDef, engine.onload[4].params[VEH_ENGINESND_PITCH_REF]), CSPFT_FLOAT}, - {"off_engsnd_name0", offsetof(VehicleDef, engine.offload[0].name), CSPFT_STRING}, - {"off_engsnd_fade_in_start0", offsetof(VehicleDef, engine.offload[0].params[VEH_ENGINESND_FADE_IN_START]), CSPFT_FLOAT}, - {"off_engsnd_fade_in_end0", offsetof(VehicleDef, engine.offload[0].params[VEH_ENGINESND_FADE_IN_END]), CSPFT_FLOAT}, - {"off_engsnd_fade_out_start0", offsetof(VehicleDef, engine.offload[0].params[VEH_ENGINESND_FADE_OUT_START]), CSPFT_FLOAT}, - {"off_engsnd_fade_out_end0", offsetof(VehicleDef, engine.offload[0].params[VEH_ENGINESND_FADE_OUT_END]), CSPFT_FLOAT}, - {"off_engsnd_pitch_ref0", offsetof(VehicleDef, engine.offload[0].params[VEH_ENGINESND_PITCH_REF]), CSPFT_FLOAT}, - {"off_engsnd_name1", offsetof(VehicleDef, engine.offload[1].name), CSPFT_STRING}, - {"off_engsnd_fade_in_start1", offsetof(VehicleDef, engine.offload[1].params[VEH_ENGINESND_FADE_IN_START]), CSPFT_FLOAT}, - {"off_engsnd_fade_in_end1", offsetof(VehicleDef, engine.offload[1].params[VEH_ENGINESND_FADE_IN_END]), CSPFT_FLOAT}, - {"off_engsnd_fade_out_start1", offsetof(VehicleDef, engine.offload[1].params[VEH_ENGINESND_FADE_OUT_START]), CSPFT_FLOAT}, - {"off_engsnd_fade_out_end1", offsetof(VehicleDef, engine.offload[1].params[VEH_ENGINESND_FADE_OUT_END]), CSPFT_FLOAT}, - {"off_engsnd_pitch_ref1", offsetof(VehicleDef, engine.offload[1].params[VEH_ENGINESND_PITCH_REF]), CSPFT_FLOAT}, - {"off_engsnd_name2", offsetof(VehicleDef, engine.offload[2].name), CSPFT_STRING}, - {"off_engsnd_fade_in_start2", offsetof(VehicleDef, engine.offload[2].params[VEH_ENGINESND_FADE_IN_START]), CSPFT_FLOAT}, - {"off_engsnd_fade_in_end2", offsetof(VehicleDef, engine.offload[2].params[VEH_ENGINESND_FADE_IN_END]), CSPFT_FLOAT}, - {"off_engsnd_fade_out_start2", offsetof(VehicleDef, engine.offload[2].params[VEH_ENGINESND_FADE_OUT_START]), CSPFT_FLOAT}, - {"off_engsnd_fade_out_end2", offsetof(VehicleDef, engine.offload[2].params[VEH_ENGINESND_FADE_OUT_END]), CSPFT_FLOAT}, - {"off_engsnd_pitch_ref2", offsetof(VehicleDef, engine.offload[2].params[VEH_ENGINESND_PITCH_REF]), CSPFT_FLOAT}, - {"off_engsnd_name3", offsetof(VehicleDef, engine.offload[3].name), CSPFT_STRING}, - {"off_engsnd_fade_in_start3", offsetof(VehicleDef, engine.offload[3].params[VEH_ENGINESND_FADE_IN_START]), CSPFT_FLOAT}, - {"off_engsnd_fade_in_end3", offsetof(VehicleDef, engine.offload[3].params[VEH_ENGINESND_FADE_IN_END]), CSPFT_FLOAT}, - {"off_engsnd_fade_out_start3", offsetof(VehicleDef, engine.offload[3].params[VEH_ENGINESND_FADE_OUT_START]), CSPFT_FLOAT}, - {"off_engsnd_fade_out_end3", offsetof(VehicleDef, engine.offload[3].params[VEH_ENGINESND_FADE_OUT_END]), CSPFT_FLOAT}, - {"off_engsnd_pitch_ref3", offsetof(VehicleDef, engine.offload[3].params[VEH_ENGINESND_PITCH_REF]), CSPFT_FLOAT}, - {"off_engsnd_name4", offsetof(VehicleDef, engine.offload[4].name), CSPFT_STRING}, - {"off_engsnd_fade_in_start4", offsetof(VehicleDef, engine.offload[4].params[VEH_ENGINESND_FADE_IN_START]), CSPFT_FLOAT}, - {"off_engsnd_fade_in_end4", offsetof(VehicleDef, engine.offload[4].params[VEH_ENGINESND_FADE_IN_END]), CSPFT_FLOAT}, - {"off_engsnd_fade_out_start4", offsetof(VehicleDef, engine.offload[4].params[VEH_ENGINESND_FADE_OUT_START]), CSPFT_FLOAT}, - {"off_engsnd_fade_out_end4", offsetof(VehicleDef, engine.offload[4].params[VEH_ENGINESND_FADE_OUT_END]), CSPFT_FLOAT}, - {"off_engsnd_pitch_ref4", offsetof(VehicleDef, engine.offload[4].params[VEH_ENGINESND_PITCH_REF]), CSPFT_FLOAT}, - {"numGears", offsetof(VehicleDef, engine.numGears), CSPFT_INT}, - {"loopLastGear", offsetof(VehicleDef, engine.loopLastGear), CSPFT_BOOL}, - {"gear_min_rpm0", offsetof(VehicleDef, engine.gears[0].minRPM), CSPFT_FLOAT}, - {"gear_max_rpm0", offsetof(VehicleDef, engine.gears[0].maxRPM), CSPFT_FLOAT}, - {"gear_ratio0", offsetof(VehicleDef, engine.gears[0].ratio), CSPFT_FLOAT}, - {"gear_min_rpm1", offsetof(VehicleDef, engine.gears[1].minRPM), CSPFT_FLOAT}, - {"gear_max_rpm1", offsetof(VehicleDef, engine.gears[1].maxRPM), CSPFT_FLOAT}, - {"gear_ratio1", offsetof(VehicleDef, engine.gears[1].ratio), CSPFT_FLOAT}, - {"gear_min_rpm2", offsetof(VehicleDef, engine.gears[2].minRPM), CSPFT_FLOAT}, - {"gear_max_rpm2", offsetof(VehicleDef, engine.gears[2].maxRPM), CSPFT_FLOAT}, - {"gear_ratio2", offsetof(VehicleDef, engine.gears[2].ratio), CSPFT_FLOAT}, - {"gear_min_rpm3", offsetof(VehicleDef, engine.gears[3].minRPM), CSPFT_FLOAT}, - {"gear_max_rpm3", offsetof(VehicleDef, engine.gears[3].maxRPM), CSPFT_FLOAT}, - {"gear_ratio3", offsetof(VehicleDef, engine.gears[3].ratio), CSPFT_FLOAT}, - {"gear_min_rpm4", offsetof(VehicleDef, engine.gears[4].minRPM), CSPFT_FLOAT}, - {"gear_max_rpm4", offsetof(VehicleDef, engine.gears[4].maxRPM), CSPFT_FLOAT}, - {"gear_ratio4", offsetof(VehicleDef, engine.gears[4].ratio), CSPFT_FLOAT}, - {"gear_min_rpm5", offsetof(VehicleDef, engine.gears[5].minRPM), CSPFT_FLOAT}, - {"gear_max_rpm5", offsetof(VehicleDef, engine.gears[5].maxRPM), CSPFT_FLOAT}, - {"gear_ratio5", offsetof(VehicleDef, engine.gears[5].ratio), CSPFT_FLOAT}, - {"gear_min_rpm6", offsetof(VehicleDef, engine.gears[6].minRPM), CSPFT_FLOAT}, - {"gear_max_rpm6", offsetof(VehicleDef, engine.gears[6].maxRPM), CSPFT_FLOAT}, - {"gear_ratio6", offsetof(VehicleDef, engine.gears[6].ratio), CSPFT_FLOAT}, - {"gear_min_rpm7", offsetof(VehicleDef, engine.gears[7].minRPM), CSPFT_FLOAT}, - {"gear_max_rpm7", offsetof(VehicleDef, engine.gears[7].maxRPM), CSPFT_FLOAT}, - {"gear_ratio7", offsetof(VehicleDef, engine.gears[7].ratio), CSPFT_FLOAT}, - {"gear_min_rpm8", offsetof(VehicleDef, engine.gears[8].minRPM), CSPFT_FLOAT}, - {"gear_max_rpm8", offsetof(VehicleDef, engine.gears[8].maxRPM), CSPFT_FLOAT}, - {"gear_ratio8", offsetof(VehicleDef, engine.gears[8].ratio), CSPFT_FLOAT}, - {"gear_min_rpm9", offsetof(VehicleDef, engine.gears[9].minRPM), CSPFT_FLOAT}, - {"gear_max_rpm9", offsetof(VehicleDef, engine.gears[9].maxRPM), CSPFT_FLOAT}, - {"gear_ratio9", offsetof(VehicleDef, engine.gears[9].ratio), CSPFT_FLOAT}, - {"csvInclude", offsetof(VehicleDef, csvInclude), CSPFT_STRING}, - {"antenna1SpringK", offsetof(VehicleDef, antenna[0].springK), CSPFT_FLOAT}, - {"antenna1Damp", offsetof(VehicleDef, antenna[0].damp), CSPFT_FLOAT}, - {"antenna1Length", offsetof(VehicleDef, antenna[0].length), CSPFT_FLOAT}, - {"antenna1Gravity", offsetof(VehicleDef, antenna[0].gravity), CSPFT_FLOAT}, - {"antenna2SpringK", offsetof(VehicleDef, antenna[1].springK), CSPFT_FLOAT}, - {"antenna2Damp", offsetof(VehicleDef, antenna[1].damp), CSPFT_FLOAT}, - {"antenna2Length", offsetof(VehicleDef, antenna[1].length), CSPFT_FLOAT}, - {"antenna2Gravity", offsetof(VehicleDef, antenna[1].gravity), CSPFT_FLOAT}, - {"customFloat0", offsetof(VehicleDef, customFloat0), CSPFT_FLOAT}, - {"customFloat1", offsetof(VehicleDef, customFloat1), CSPFT_FLOAT}, - {"customFloat2", offsetof(VehicleDef, customFloat2), CSPFT_FLOAT}, - {"customBool0", offsetof(VehicleDef, customBool0), CSPFT_BOOL}, - {"customBool1", offsetof(VehicleDef, customBool1), CSPFT_BOOL}, - {"customBool2", offsetof(VehicleDef, customBool2), CSPFT_BOOL}, - }; +namespace T6 { +inline cspField_t vehicle_fields[]{ + {"type", offsetof(VehicleDef, type), VFT_TYPE }, + {"remoteControl", offsetof(VehicleDef, remoteControl), CSPFT_QBOOLEAN }, + {"bulletDamage", offsetof(VehicleDef, bulletDamage), CSPFT_QBOOLEAN }, + {"armorPiercingDamage", offsetof(VehicleDef, armorPiercingDamage), CSPFT_QBOOLEAN }, + {"grenadeDamage", offsetof(VehicleDef, grenadeDamage), CSPFT_QBOOLEAN }, + {"projectileDamage", offsetof(VehicleDef, projectileDamage), CSPFT_QBOOLEAN }, + {"projectileSplashDamage", offsetof(VehicleDef, projectileSplashDamage), CSPFT_QBOOLEAN }, + {"heavyExplosiveDamage", offsetof(VehicleDef, heavyExplosiveDamage), CSPFT_QBOOLEAN }, + {"cameraMode", offsetof(VehicleDef, cameraMode), VFT_CAMERAMODE }, + {"autoRecenterOnAccel", offsetof(VehicleDef, autoRecenterOnAccel), CSPFT_QBOOLEAN }, + {"thirdPersonDriver", offsetof(VehicleDef, thirdPersonDriver), CSPFT_QBOOLEAN }, + {"thirdPersonUseVehicleRoll", offsetof(VehicleDef, thirdPersonUseVehicleRoll), CSPFT_QBOOLEAN }, + {"thirdPersonCameraPitchVehicleRelative", offsetof(VehicleDef, thirdPersonCameraPitchVehicleRelative), CSPFT_QBOOLEAN }, + {"thirdPersonCameraHeightWorldRelative", offsetof(VehicleDef, thirdPersonCameraHeightWorldRelative), CSPFT_QBOOLEAN }, + {"thirdPersonCameraHeightMin", offsetof(VehicleDef, thirdPersonCameraHeight[0]), CSPFT_FLOAT }, + {"thirdPersonCameraPitchMin", offsetof(VehicleDef, thirdPersonCameraPitch[0]), CSPFT_FLOAT }, + {"thirdPersonCameraRange", offsetof(VehicleDef, thirdPersonCameraRange), CSPFT_FLOAT }, + {"thirdPersonCameraHeight", offsetof(VehicleDef, thirdPersonCameraHeight[1]), CSPFT_FLOAT }, + {"thirdPersonCameraPitch", offsetof(VehicleDef, thirdPersonCameraPitch[1]), CSPFT_FLOAT }, + {"thirdPersonCameraMinPitchClamp", offsetof(VehicleDef, thirdPersonCameraMinPitchClamp), CSPFT_FLOAT }, + {"thirdPersonCameraMaxPitchClamp", offsetof(VehicleDef, thirdPersonCameraMaxPitchClamp), CSPFT_FLOAT }, + {"cameraAlwaysAutoCenter", offsetof(VehicleDef, cameraAlwaysAutoCenter), CSPFT_QBOOLEAN }, + {"cameraAutoCenterLerpRate", offsetof(VehicleDef, cameraAutoCenterLerpRate), CSPFT_FLOAT }, + {"cameraAutoCenterMaxLerpRate", offsetof(VehicleDef, cameraAutoCenterMaxLerpRate), CSPFT_FLOAT }, + {"thirdPersonCameraSpringDistance", offsetof(VehicleDef, thirdPersonCameraSpringDistance), CSPFT_FLOAT }, + {"thirdPersonCameraSpringTime", offsetof(VehicleDef, thirdPersonCameraSpringTime), CSPFT_FLOAT }, + {"thirdPersonCameraHandbrakeTurnRateInc", offsetof(VehicleDef, thirdPersonCameraHandbrakeTurnRateInc), CSPFT_FLOAT }, + {"cameraRollFraction", offsetof(VehicleDef, cameraRollFraction), CSPFT_FLOAT }, + {"cameraFOV", offsetof(VehicleDef, cameraFOV), CSPFT_FLOAT }, + {"viewInfluence", offsetof(VehicleDef, viewInfluence), CSPFT_FLOAT }, + {"tagPlayerOffsetX", offsetof(VehicleDef, tagPlayerOffset.x), CSPFT_FLOAT }, + {"tagPlayerOffsetY", offsetof(VehicleDef, tagPlayerOffset.y), CSPFT_FLOAT }, + {"tagPlayerOffsetZ", offsetof(VehicleDef, tagPlayerOffset.z), CSPFT_FLOAT }, + {"killcamCollision", offsetof(VehicleDef, killcamCollision), CSPFT_QBOOLEAN }, + {"killcamDist", offsetof(VehicleDef, killcamDist), CSPFT_FLOAT }, + {"killcamZDist", offsetof(VehicleDef, killcamZDist), CSPFT_FLOAT }, + {"killcamMinDist", offsetof(VehicleDef, killcamMinDist), CSPFT_FLOAT }, + {"killcamZTargetOffset", offsetof(VehicleDef, killcamZTargetOffset), CSPFT_FLOAT }, + {"killcamFOV", offsetof(VehicleDef, killcamFOV), CSPFT_FLOAT }, + {"killcamNearBlur", offsetof(VehicleDef, killcamNearBlur), CSPFT_FLOAT }, + {"killcamNearBlurStart", offsetof(VehicleDef, killcamNearBlurStart), CSPFT_FLOAT }, + {"killcamNearBlurEnd", offsetof(VehicleDef, killcamNearBlurEnd), CSPFT_FLOAT }, + {"killcamFarBlur", offsetof(VehicleDef, killcamFarBlur), CSPFT_FLOAT }, + {"killcamFarBlurStart", offsetof(VehicleDef, killcamFarBlurStart), CSPFT_FLOAT }, + {"killcamFarBlurEnd", offsetof(VehicleDef, killcamFarBlurEnd), CSPFT_FLOAT }, + {"isDrivable", offsetof(VehicleDef, isDrivable), CSPFT_QBOOLEAN }, + {"numberOfSeats", offsetof(VehicleDef, numberOfSeats), CSPFT_INT }, + {"numberOfGunners", offsetof(VehicleDef, numberOfGunners), CSPFT_INT }, + {"driverControlledGunPos", offsetof(VehicleDef, driverControlledGunPos), CSPFT_INT }, + {"seatSwitchOrder1", offsetof(VehicleDef, seatSwitchOrder[0]), CSPFT_INT }, + {"seatSwitchOrder2", offsetof(VehicleDef, seatSwitchOrder[1]), CSPFT_INT }, + {"seatSwitchOrder3", offsetof(VehicleDef, seatSwitchOrder[2]), CSPFT_INT }, + {"seatSwitchOrder4", offsetof(VehicleDef, seatSwitchOrder[3]), CSPFT_INT }, + {"seatSwitchOrder5", offsetof(VehicleDef, seatSwitchOrder[4]), CSPFT_INT }, + {"seatSwitchOrder6", offsetof(VehicleDef, seatSwitchOrder[5]), CSPFT_INT }, + {"seatSwitchOrder7", offsetof(VehicleDef, seatSwitchOrder[6]), CSPFT_INT }, + {"seatSwitchOrder8", offsetof(VehicleDef, seatSwitchOrder[7]), CSPFT_INT }, + {"seatSwitchOrder9", offsetof(VehicleDef, seatSwitchOrder[8]), CSPFT_INT }, + {"seatSwitchOrder10", offsetof(VehicleDef, seatSwitchOrder[9]), CSPFT_INT }, + {"seatSwitchOrder11", offsetof(VehicleDef, seatSwitchOrder[10]), CSPFT_INT }, + {"texureScrollScale", offsetof(VehicleDef, texScrollScale), CSPFT_FLOAT }, + {"wheelRotRate", offsetof(VehicleDef, wheelRotRate), CSPFT_FLOAT }, + {"extraWheelRotScale", offsetof(VehicleDef, extraWheelRotScale), CSPFT_FLOAT }, + {"wheelChildTakesSteerYaw", offsetof(VehicleDef, wheelChildTakesSteerYaw), CSPFT_QBOOLEAN }, + {"enterRadiusDriver", offsetof(VehicleDef, entryPointRadius[VEH_POS_DRIVER]), CSPFT_FLOAT }, + {"enterRadiusGunner1", offsetof(VehicleDef, entryPointRadius[VEH_POS_GUNNER_1]), CSPFT_FLOAT }, + {"enterRadiusGunner2", offsetof(VehicleDef, entryPointRadius[VEH_POS_GUNNER_2]), CSPFT_FLOAT }, + {"enterRadiusGunner3", offsetof(VehicleDef, entryPointRadius[VEH_POS_GUNNER_3]), CSPFT_FLOAT }, + {"enterRadiusGunner4", offsetof(VehicleDef, entryPointRadius[VEH_POS_GUNNER_4]), CSPFT_FLOAT }, + {"maxSpeed", offsetof(VehicleDef, maxSpeed), VFT_MPH_TO_INCHES_PER_SECOND}, + {"maxSpeedVertical", offsetof(VehicleDef, maxSpeedVertical), VFT_MPH_TO_INCHES_PER_SECOND}, + {"accel", offsetof(VehicleDef, accel), VFT_MPH_TO_INCHES_PER_SECOND}, + {"accelVertical", offsetof(VehicleDef, accelVertical), VFT_MPH_TO_INCHES_PER_SECOND}, + {"rotRate", offsetof(VehicleDef, rotRate), CSPFT_FLOAT }, + {"rotAccel", offsetof(VehicleDef, rotAccel), CSPFT_FLOAT }, + {"collisionDamage", offsetof(VehicleDef, collisionDamage), CSPFT_FLOAT }, + {"collisionSpeed", offsetof(VehicleDef, collisionSpeed), VFT_MPH_TO_INCHES_PER_SECOND}, + {"suspensionTravel", offsetof(VehicleDef, suspensionTravel), CSPFT_FLOAT }, + {"maxBodyPitch", offsetof(VehicleDef, maxBodyPitch), CSPFT_FLOAT }, + {"maxBodyRoll", offsetof(VehicleDef, maxBodyRoll), CSPFT_FLOAT }, + {"heliCollisionScalar", offsetof(VehicleDef, heliCollisionScalar), CSPFT_FLOAT }, + {"viewPitchOffset", offsetof(VehicleDef, viewPitchOffset), CSPFT_FLOAT }, + {"tiltFromAccelerationPitch", offsetof(VehicleDef, tiltFromAcceleration[0]), CSPFT_FLOAT }, + {"tiltFromAccelerationRoll", offsetof(VehicleDef, tiltFromAcceleration[1]), CSPFT_FLOAT }, + {"tiltFromDecelerationPitch", offsetof(VehicleDef, tiltFromDeceleration[0]), CSPFT_FLOAT }, + {"tiltFromDecelerationRoll", offsetof(VehicleDef, tiltFromDeceleration[1]), CSPFT_FLOAT }, + {"tiltFromVelocityPitch", offsetof(VehicleDef, tiltFromVelocity[0]), CSPFT_FLOAT }, + {"tiltFromVelocityRoll", offsetof(VehicleDef, tiltFromVelocity[1]), CSPFT_FLOAT }, + {"tiltSpeedPitch", offsetof(VehicleDef, tiltSpeed[0]), CSPFT_FLOAT }, + {"tiltSpeedRoll", offsetof(VehicleDef, tiltSpeed[1]), CSPFT_FLOAT }, + {"tracerOffsetForward", offsetof(VehicleDef, tracerOffset[0]), CSPFT_FLOAT }, + {"tracerOffsetUp", offsetof(VehicleDef, tracerOffset[1]), CSPFT_FLOAT }, + {"turretWeapon", offsetof(VehicleDef, turretWeapon), CSPFT_STRING }, + {"turretHorizSpanLeft", offsetof(VehicleDef, turretViewLimits.horizSpanLeft), CSPFT_FLOAT }, + {"turretHorizSpanRight", offsetof(VehicleDef, turretViewLimits.horizSpanRight), CSPFT_FLOAT }, + {"turretVertSpanUp", offsetof(VehicleDef, turretViewLimits.vertSpanUp), CSPFT_FLOAT }, + {"turretVertSpanDown", offsetof(VehicleDef, turretViewLimits.vertSpanDown), CSPFT_FLOAT }, + {"turretHorizResistLeft", offsetof(VehicleDef, turretViewLimits.horizResistLeft), CSPFT_FLOAT }, + {"turretHorizResistRight", offsetof(VehicleDef, turretViewLimits.horizResistRight), CSPFT_FLOAT }, + {"turretVertResistUp", offsetof(VehicleDef, turretViewLimits.vertResistUp), CSPFT_FLOAT }, + {"turretVertResistDown", offsetof(VehicleDef, turretViewLimits.vertResistDown), CSPFT_FLOAT }, + {"turretRotRate", offsetof(VehicleDef, turretRotRate), CSPFT_FLOAT }, + {"turretClampPlayerView", offsetof(VehicleDef, turretClampPlayerView), CSPFT_QBOOLEAN }, + {"turretLockTurretToPlayerView", offsetof(VehicleDef, turretLockTurretToPlayerView), CSPFT_QBOOLEAN }, + {"gunnerWeapon", offsetof(VehicleDef, gunnerWeapon[0]), CSPFT_STRING }, + {"gunnerWeapon1", offsetof(VehicleDef, gunnerWeapon[1]), CSPFT_STRING }, + {"gunnerWeapon2", offsetof(VehicleDef, gunnerWeapon[2]), CSPFT_STRING }, + {"gunnerWeapon3", offsetof(VehicleDef, gunnerWeapon[3]), CSPFT_STRING }, + {"gunnerRotRate", offsetof(VehicleDef, gunnerRotRate), CSPFT_FLOAT }, + {"passenger1HorizSpanLeft", offsetof(VehicleDef, passengerViewLimits[0].horizSpanLeft), CSPFT_FLOAT }, + {"passenger1HorizSpanRight", offsetof(VehicleDef, passengerViewLimits[0].horizSpanRight), CSPFT_FLOAT }, + {"passenger1VertSpanUp", offsetof(VehicleDef, passengerViewLimits[0].vertSpanUp), CSPFT_FLOAT }, + {"passenger1VertSpanDown", offsetof(VehicleDef, passengerViewLimits[0].vertSpanDown), CSPFT_FLOAT }, + {"passenger2HorizSpanLeft", offsetof(VehicleDef, passengerViewLimits[1].horizSpanLeft), CSPFT_FLOAT }, + {"passenger2HorizSpanRight", offsetof(VehicleDef, passengerViewLimits[1].horizSpanRight), CSPFT_FLOAT }, + {"passenger2VertSpanUp", offsetof(VehicleDef, passengerViewLimits[1].vertSpanUp), CSPFT_FLOAT }, + {"passenger2VertSpanDown", offsetof(VehicleDef, passengerViewLimits[1].vertSpanDown), CSPFT_FLOAT }, + {"passenger3HorizSpanLeft", offsetof(VehicleDef, passengerViewLimits[2].horizSpanLeft), CSPFT_FLOAT }, + {"passenger3HorizSpanRight", offsetof(VehicleDef, passengerViewLimits[2].horizSpanRight), CSPFT_FLOAT }, + {"passenger3VertSpanUp", offsetof(VehicleDef, passengerViewLimits[2].vertSpanUp), CSPFT_FLOAT }, + {"passenger3VertSpanDown", offsetof(VehicleDef, passengerViewLimits[2].vertSpanDown), CSPFT_FLOAT }, + {"passenger4HorizSpanLeft", offsetof(VehicleDef, passengerViewLimits[3].horizSpanLeft), CSPFT_FLOAT }, + {"passenger4HorizSpanRight", offsetof(VehicleDef, passengerViewLimits[3].horizSpanRight), CSPFT_FLOAT }, + {"passenger4VertSpanUp", offsetof(VehicleDef, passengerViewLimits[3].vertSpanUp), CSPFT_FLOAT }, + {"passenger4VertSpanDown", offsetof(VehicleDef, passengerViewLimits[3].vertSpanDown), CSPFT_FLOAT }, + {"passenger5HorizSpanLeft", offsetof(VehicleDef, passengerViewLimits[4].horizSpanLeft), CSPFT_FLOAT }, + {"passenger5HorizSpanRight", offsetof(VehicleDef, passengerViewLimits[4].horizSpanRight), CSPFT_FLOAT }, + {"passenger5VertSpanUp", offsetof(VehicleDef, passengerViewLimits[4].vertSpanUp), CSPFT_FLOAT }, + {"passenger5VertSpanDown", offsetof(VehicleDef, passengerViewLimits[4].vertSpanDown), CSPFT_FLOAT }, + {"passenger6HorizSpanLeft", offsetof(VehicleDef, passengerViewLimits[5].horizSpanLeft), CSPFT_FLOAT }, + {"passenger6HorizSpanRight", offsetof(VehicleDef, passengerViewLimits[5].horizSpanRight), CSPFT_FLOAT }, + {"passenger6VertSpanUp", offsetof(VehicleDef, passengerViewLimits[5].vertSpanUp), CSPFT_FLOAT }, + {"passenger6VertSpanDown", offsetof(VehicleDef, passengerViewLimits[5].vertSpanDown), CSPFT_FLOAT }, + {"turretSpinSnd", offsetof(VehicleDef, sndNames[VEH_TURRET_SPIN_SND]), CSPFT_STRING }, + {"turretStopSnd", offsetof(VehicleDef, sndNames[VEH_TURRET_STOP_SND]), CSPFT_STRING }, + {"wheelRoadNoiseSnd", offsetof(VehicleDef, sndMaterialNames[VEH_WHEEL_ROAD_NOISE]), CSPFT_STRING }, + {"wheelSlidingSnd", offsetof(VehicleDef, sndMaterialNames[VEH_WHEEL_SLIDING]), CSPFT_STRING }, + {"wheelPeelingOutSnd", offsetof(VehicleDef, sndMaterialNames[VEH_WHEEL_PEELING_OUT]), CSPFT_STRING }, + {"futzSnd", offsetof(VehicleDef, futzName), CSPFT_STRING }, + {"futzBlend", offsetof(VehicleDef, futzBlend), CSPFT_FLOAT }, + {"skidSpeedMin", offsetof(VehicleDef, skidSpeedMin), CSPFT_FLOAT }, + {"skidSpeedMax", offsetof(VehicleDef, skidSpeedMax), CSPFT_FLOAT }, + {"animType", offsetof(VehicleDef, animType), CSPFT_INT }, + {"animSet", offsetof(VehicleDef, animSet), CSPFT_STRING }, + {"scriptedAnimationEntry", offsetof(VehicleDef, scriptedAnimationEntry), CSPFT_QBOOLEAN }, + {"mantleAngleFront", offsetof(VehicleDef, mantleAngles[MANTLE_ANGLE_FRONT]), CSPFT_FLOAT }, + {"mantleAngleBack", offsetof(VehicleDef, mantleAngles[MANTLE_ANGLE_BACK]), CSPFT_FLOAT }, + {"mantleAngleLeft", offsetof(VehicleDef, mantleAngles[MANTLE_ANGLE_LEFT]), CSPFT_FLOAT }, + {"mantleAngleRight", offsetof(VehicleDef, mantleAngles[MANTLE_ANGLE_RIGHT]), CSPFT_FLOAT }, + {"driverHideTag1", offsetof(VehicleDef, driverHideTag), CSPFT_SCRIPT_STRING }, + {"extraWheelLeft1", offsetof(VehicleDef, extraWheelTags[FL_WHEEL]), CSPFT_SCRIPT_STRING }, + {"extraWheelRight1", offsetof(VehicleDef, extraWheelTags[FR_WHEEL]), CSPFT_SCRIPT_STRING }, + {"extraWheelLeft2", offsetof(VehicleDef, extraWheelTags[BL_WHEEL]), CSPFT_SCRIPT_STRING }, + {"extraWheelRight2", offsetof(VehicleDef, extraWheelTags[BR_WHEEL]), CSPFT_SCRIPT_STRING }, + {"mod0", offsetof(VehicleDef, attachmentModels[0]), CSPFT_XMODEL }, + {"tag0", offsetof(VehicleDef, attachmentTags[0]), CSPFT_SCRIPT_STRING }, + {"mod1", offsetof(VehicleDef, attachmentModels[1]), CSPFT_XMODEL }, + {"tag1", offsetof(VehicleDef, attachmentTags[1]), CSPFT_SCRIPT_STRING }, + {"mod2", offsetof(VehicleDef, attachmentModels[2]), CSPFT_XMODEL }, + {"tag2", offsetof(VehicleDef, attachmentTags[2]), CSPFT_SCRIPT_STRING }, + {"mod3", offsetof(VehicleDef, attachmentModels[3]), CSPFT_XMODEL }, + {"tag3", offsetof(VehicleDef, attachmentTags[3]), CSPFT_SCRIPT_STRING }, + {"dmod0", offsetof(VehicleDef, deathAttachmentModels[0]), CSPFT_XMODEL }, + {"dtag0", offsetof(VehicleDef, deathAttachmentTags[0]), CSPFT_SCRIPT_STRING }, + {"dmod1", offsetof(VehicleDef, deathAttachmentModels[1]), CSPFT_XMODEL }, + {"dtag1", offsetof(VehicleDef, deathAttachmentTags[1]), CSPFT_SCRIPT_STRING }, + {"dmod2", offsetof(VehicleDef, deathAttachmentModels[2]), CSPFT_XMODEL }, + {"dtag2", offsetof(VehicleDef, deathAttachmentTags[2]), CSPFT_SCRIPT_STRING }, + {"dmod3", offsetof(VehicleDef, deathAttachmentModels[3]), CSPFT_XMODEL }, + {"dtag3", offsetof(VehicleDef, deathAttachmentTags[3]), CSPFT_SCRIPT_STRING }, + {"worldModel", offsetof(VehicleDef, model), CSPFT_XMODEL }, + {"viewModel", offsetof(VehicleDef, viewModel), CSPFT_XMODEL }, + {"deathModel", offsetof(VehicleDef, deathModel), CSPFT_XMODEL }, + {"enemyModel", offsetof(VehicleDef, enemyModel), CSPFT_XMODEL }, + {"modelSwapDelay", offsetof(VehicleDef, modelSwapDelay), CSPFT_FLOAT }, + {"exhaustFx", offsetof(VehicleDef, exhaustFx), CSPFT_FX }, + {"oneExhaust", offsetof(VehicleDef, oneExhaust), CSPFT_QBOOLEAN }, + {"treadFxAsphalt", offsetof(VehicleDef, treadFx[SURF_TYPE_ASPHALT]), CSPFT_FX }, + {"treadFxBark", offsetof(VehicleDef, treadFx[SURF_TYPE_BARK]), CSPFT_FX }, + {"treadFxBrick", offsetof(VehicleDef, treadFx[SURF_TYPE_BRICK]), CSPFT_FX }, + {"treadFxCarpet", offsetof(VehicleDef, treadFx[SURF_TYPE_CARPET]), CSPFT_FX }, + {"treadFxCeramic", offsetof(VehicleDef, treadFx[SURF_TYPE_CERAMIC]), CSPFT_FX }, + {"treadFxCloth", offsetof(VehicleDef, treadFx[SURF_TYPE_CLOTH]), CSPFT_FX }, + {"treadFxConcrete", offsetof(VehicleDef, treadFx[SURF_TYPE_CONCRETE]), CSPFT_FX }, + {"treadFxCushion", offsetof(VehicleDef, treadFx[SURF_TYPE_CUSHION]), CSPFT_FX }, + {"treadFxDefault", offsetof(VehicleDef, treadFx[SURF_TYPE_DEFAULT]), CSPFT_FX }, + {"treadFxDirt", offsetof(VehicleDef, treadFx[SURF_TYPE_DIRT]), CSPFT_FX }, + {"treadFxFlesh", offsetof(VehicleDef, treadFx[SURF_TYPE_FLESH]), CSPFT_FX }, + {"treadFxFoliage", offsetof(VehicleDef, treadFx[SURF_TYPE_FOLIAGE]), CSPFT_FX }, + {"treadFxFruit", offsetof(VehicleDef, treadFx[SURF_TYPE_FRUIT]), CSPFT_FX }, + {"treadFxGlass", offsetof(VehicleDef, treadFx[SURF_TYPE_GLASS]), CSPFT_FX }, + {"treadFxGrass", offsetof(VehicleDef, treadFx[SURF_TYPE_GRASS]), CSPFT_FX }, + {"treadFxGravel", offsetof(VehicleDef, treadFx[SURF_TYPE_GRAVEL]), CSPFT_FX }, + {"treadFxIce", offsetof(VehicleDef, treadFx[SURF_TYPE_ICE]), CSPFT_FX }, + {"treadFxMetal", offsetof(VehicleDef, treadFx[SURF_TYPE_METAL]), CSPFT_FX }, + {"treadFxMud", offsetof(VehicleDef, treadFx[SURF_TYPE_MUD]), CSPFT_FX }, + {"treadFxPaintedMetal", offsetof(VehicleDef, treadFx[SURF_TYPE_PAINTED_METAL]), CSPFT_FX }, + {"treadFxPaper", offsetof(VehicleDef, treadFx[SURF_TYPE_PAPER]), CSPFT_FX }, + {"treadFxPlaster", offsetof(VehicleDef, treadFx[SURF_TYPE_PLASTER]), CSPFT_FX }, + {"treadFxPlastic", offsetof(VehicleDef, treadFx[SURF_TYPE_PLASTIC]), CSPFT_FX }, + {"treadFxRock", offsetof(VehicleDef, treadFx[SURF_TYPE_ROCK]), CSPFT_FX }, + {"treadFxRubber", offsetof(VehicleDef, treadFx[SURF_TYPE_RUBBER]), CSPFT_FX }, + {"treadFxSand", offsetof(VehicleDef, treadFx[SURF_TYPE_SAND]), CSPFT_FX }, + {"treadFxSnow", offsetof(VehicleDef, treadFx[SURF_TYPE_SNOW]), CSPFT_FX }, + {"treadFxWater", offsetof(VehicleDef, treadFx[SURF_TYPE_WATER]), CSPFT_FX }, + {"treadFxWood", offsetof(VehicleDef, treadFx[SURF_TYPE_WOOD]), CSPFT_FX }, + {"deathFxName", offsetof(VehicleDef, deathFx), CSPFT_FX }, + {"deathFxTag", offsetof(VehicleDef, deathFxTag), CSPFT_SCRIPT_STRING }, + {"deathFxSound", offsetof(VehicleDef, deathFxSound), CSPFT_STRING }, + {"lightFxName1", offsetof(VehicleDef, lightFx[0]), CSPFT_FX }, + {"lightFxTag1", offsetof(VehicleDef, lightFxTag[0]), CSPFT_SCRIPT_STRING }, + {"lightFxName2", offsetof(VehicleDef, lightFx[1]), CSPFT_FX }, + {"lightFxTag2", offsetof(VehicleDef, lightFxTag[1]), CSPFT_SCRIPT_STRING }, + {"lightFxName3", offsetof(VehicleDef, lightFx[2]), CSPFT_FX }, + {"lightFxTag3", offsetof(VehicleDef, lightFxTag[2]), CSPFT_SCRIPT_STRING }, + {"lightFxName4", offsetof(VehicleDef, lightFx[3]), CSPFT_FX }, + {"lightFxTag4", offsetof(VehicleDef, lightFxTag[3]), CSPFT_SCRIPT_STRING }, + {"FriendlyLightFxName", offsetof(VehicleDef, friendlyLightFx), CSPFT_FX }, + {"FriendlyLightFxTag", offsetof(VehicleDef, friendlyLightFxTag), CSPFT_SCRIPT_STRING }, + {"EnemyLightFxName", offsetof(VehicleDef, enemyLightFx), CSPFT_FX }, + {"EnemyLightFxTag", offsetof(VehicleDef, enemyLightFxTag), CSPFT_SCRIPT_STRING }, + {"radiusDamageMin", offsetof(VehicleDef, radiusDamageMin), CSPFT_FLOAT }, + {"radiusDamageMax", offsetof(VehicleDef, radiusDamageMax), CSPFT_FLOAT }, + {"radiusDamageRadius", offsetof(VehicleDef, radiusDamageRadius), CSPFT_FLOAT }, + {"shootShock", offsetof(VehicleDef, shootShock), CSPFT_STRING }, + {"shootRumble", offsetof(VehicleDef, shootRumble), CSPFT_STRING }, + {"deathQuakeScale", offsetof(VehicleDef, deathQuakeScale), CSPFT_FLOAT }, + {"deathQuakeDuration", offsetof(VehicleDef, deathQuakeDuration), CSPFT_FLOAT }, + {"deathQuakeRadius", offsetof(VehicleDef, deathQuakeRadius), CSPFT_FLOAT }, + {"rumbleType", offsetof(VehicleDef, rumbleType), CSPFT_STRING }, + {"rumbleScale", offsetof(VehicleDef, rumbleScale), CSPFT_FLOAT }, + {"rumbleDuration", offsetof(VehicleDef, rumbleDuration), CSPFT_FLOAT }, + {"rumbleRadius", offsetof(VehicleDef, rumbleRadius), CSPFT_FLOAT }, + {"rumbleBaseTime", offsetof(VehicleDef, rumbleBaseTime), CSPFT_FLOAT }, + {"rumbleAdditionalTime", offsetof(VehicleDef, rumbleAdditionalTime), CSPFT_FLOAT }, + {"healthDefault", offsetof(VehicleDef, healthDefault), CSPFT_INT }, + {"healthMin", offsetof(VehicleDef, healthMin), CSPFT_INT }, + {"healthMax", offsetof(VehicleDef, healthMax), CSPFT_INT }, + {"team", offsetof(VehicleDef, eTeam), VFT_TEAM }, + {"boostAccelMultiplier", offsetof(VehicleDef, boostAccelMultiplier), CSPFT_INT }, + {"boostDuration", offsetof(VehicleDef, boostDuration), CSPFT_FLOAT }, + {"boostSpeedIncrease", offsetof(VehicleDef, boostSpeedIncrease), CSPFT_FLOAT }, + {"addToCompass", offsetof(VehicleDef, addToCompass), CSPFT_QBOOLEAN }, + {"addToCompassEnemy", offsetof(VehicleDef, addToCompassEnemy), CSPFT_QBOOLEAN }, + {"compassIcon", offsetof(VehicleDef, compassIcon), CSPFT_STRING }, + {"gasButton", offsetof(VehicleDef, gasButtonName), CSPFT_STRING }, + {"reverseBrakeButton", offsetof(VehicleDef, reverseBrakeButtonName), CSPFT_STRING }, + {"handBrakeButton", offsetof(VehicleDef, handBrakeButtonName), CSPFT_STRING }, + {"attackButton", offsetof(VehicleDef, attackButtonName), CSPFT_STRING }, + {"attackSecondaryButton", offsetof(VehicleDef, attackSecondaryButtonName), CSPFT_STRING }, + {"moveUpButton", offsetof(VehicleDef, moveUpButtonName), CSPFT_STRING }, + {"moveDownButton", offsetof(VehicleDef, moveDownButtonName), CSPFT_STRING }, + {"switchSeatButton", offsetof(VehicleDef, switchSeatButtonName), CSPFT_STRING }, + {"boostButton", offsetof(VehicleDef, boostButtonName), CSPFT_STRING }, + {"steerGraph", offsetof(VehicleDef, steerGraphName), CSPFT_STRING }, + {"accelGraph", offsetof(VehicleDef, accelGraphName), CSPFT_STRING }, + {"isNitrous", offsetof(VehicleDef, isNitrous), CSPFT_QBOOLEAN }, + {"isFourWheelSteering", offsetof(VehicleDef, isFourWheelSteering), CSPFT_QBOOLEAN }, + {"useCollmap", offsetof(VehicleDef, useCollmap), CSPFT_QBOOLEAN }, + {"radius", offsetof(VehicleDef, radius), CSPFT_FLOAT }, + {"minHeight", offsetof(VehicleDef, minHeight), CSPFT_FLOAT }, + {"maxHeight", offsetof(VehicleDef, maxHeight), CSPFT_FLOAT }, + {"noDirectionalDamage", offsetof(VehicleDef, noDirectionalDamage), CSPFT_QBOOLEAN }, + {"max_fric_tilt_angle", offsetof(VehicleDef, max_fric_tilt_angle), CSPFT_FLOAT }, + {"max_fric_tilt", offsetof(VehicleDef, max_fric_tilt), CSPFT_FLOAT }, + {"fakeBodyStabilizer", offsetof(VehicleDef, fakeBodyStabilizer), CSPFT_QBOOLEAN }, + {"vehHelicopterBoundsRadius", offsetof(VehicleDef, vehHelicopterBoundsRadius), CSPFT_FLOAT }, + {"vehHelicopterDecelerationFwd", offsetof(VehicleDef, vehHelicopterDecelerationFwd), CSPFT_FLOAT }, + {"vehHelicopterDecelerationSide", offsetof(VehicleDef, vehHelicopterDecelerationSide), CSPFT_FLOAT }, + {"vehHelicopterDecelerationUp", offsetof(VehicleDef, vehHelicopterDecelerationUp), CSPFT_FLOAT }, + {"vehHelicopterTiltFromControllerAxes", offsetof(VehicleDef, vehHelicopterTiltFromControllerAxes), CSPFT_FLOAT }, + {"vehHelicopterTiltFromFwdAndYaw", offsetof(VehicleDef, vehHelicopterTiltFromFwdAndYaw), CSPFT_FLOAT }, + {"vehHelicopterTiltFromFwdAndYaw_VelAtMaxTilt", offsetof(VehicleDef, vehHelicopterTiltFromFwdAndYaw_VelAtMaxTilt), CSPFT_FLOAT }, + {"vehHelicopterTiltMomentum", offsetof(VehicleDef, vehHelicopterTiltMomentum), CSPFT_FLOAT }, + {"vehHelicopterQuadRotor", offsetof(VehicleDef, vehHelicopterQuadRotor), CSPFT_QBOOLEAN }, + {"vehHelicopterAccelTwardsView", offsetof(VehicleDef, vehHelicopterAccelTwardsView), CSPFT_QBOOLEAN }, + {"maxRotorArmMovementAngle", offsetof(VehicleDef, maxRotorArmMovementAngle), CSPFT_FLOAT }, + {"maxRotorArmRotationAngle", offsetof(VehicleDef, maxRotorArmRotationAngle), CSPFT_FLOAT }, + {"vehHelicopterMaintainHeight", offsetof(VehicleDef, vehHelicopterMaintainHeight), CSPFT_QBOOLEAN }, + {"vehHelicopterMaintainMaxHeight", offsetof(VehicleDef, vehHelicopterMaintainMaxHeight), CSPFT_QBOOLEAN }, + {"vehHelicopterMaintainHeightLimit", offsetof(VehicleDef, vehHelicopterMaintainHeightLimit), CSPFT_FLOAT }, + {"vehHelicopterMaintainHeightAccel", offsetof(VehicleDef, vehHelicopterMaintainHeightAccel), CSPFT_FLOAT }, + {"vehHelicopterMaintainHeightMinimum", offsetof(VehicleDef, vehHelicopterMaintainHeightMinimum), CSPFT_FLOAT }, + {"vehHelicopterMaintainHeightMaximum", offsetof(VehicleDef, vehHelicopterMaintainHeightMaximum), CSPFT_FLOAT }, + {"vehHelicopterMaintainCeilingMinimum", offsetof(VehicleDef, vehHelicopterMaintainCeilingMinimum), CSPFT_FLOAT }, + {"joltVehicle", offsetof(VehicleDef, joltVehicle), CSPFT_QBOOLEAN }, + {"joltVehicleDriver", offsetof(VehicleDef, joltVehicleDriver), CSPFT_QBOOLEAN }, + {"joltMaxTime", offsetof(VehicleDef, joltMaxTime), CSPFT_FLOAT }, + {"joltTime", offsetof(VehicleDef, joltTime), CSPFT_FLOAT }, + {"joltWaves", offsetof(VehicleDef, joltWaves), CSPFT_FLOAT }, + {"joltIntensity", offsetof(VehicleDef, joltIntensity), CSPFT_FLOAT }, + {"nitrous_max_speed", offsetof(VehicleDef, nitrousVehParams.m_speed_max), VFT_MPH_TO_INCHES_PER_SECOND}, + {"nitrous_accel", offsetof(VehicleDef, nitrousVehParams.m_accel_max), VFT_MPH_TO_INCHES_PER_SECOND}, + {"nitrous_auto_handbrake_min_speed", offsetof(VehicleDef, nitrousVehParams.m_auto_hand_brake_min_speed), VFT_MPH_TO_INCHES_PER_SECOND}, + {"nitrous_steer_angle_max", offsetof(VehicleDef, nitrousVehParams.m_steer_angle_max), CSPFT_FLOAT }, + {"nitrous_steer_angle_speed_scale", offsetof(VehicleDef, nitrousVehParams.m_steer_angle_speed_scale), CSPFT_FLOAT }, + {"nitrous_steer_speed", offsetof(VehicleDef, nitrousVehParams.m_steer_speed), CSPFT_FLOAT }, + {"nitrous_body_mass", offsetof(VehicleDef, nitrousVehParams.m_body_mass), VFT_POUNDS_TO_GAME_MASS }, + {"nitrous_wheel_radius", offsetof(VehicleDef, nitrousVehParams.m_wheel_radius), CSPFT_FLOAT }, + {"nitrous_susp_adj", offsetof(VehicleDef, nitrousVehParams.m_susp_adj), CSPFT_FLOAT }, + {"nitrous_susp_spring_k", offsetof(VehicleDef, nitrousVehParams.m_susp_spring_k), CSPFT_FLOAT }, + {"nitrous_susp_damp_k", offsetof(VehicleDef, nitrousVehParams.m_susp_damp_k), CSPFT_FLOAT }, + {"nitrous_susp_hard_limit", offsetof(VehicleDef, nitrousVehParams.m_susp_hard_limit), CSPFT_FLOAT }, + {"nitrous_susp_min_height", offsetof(VehicleDef, nitrousVehParams.m_susp_min_height), CSPFT_FLOAT }, + {"nitrous_tire_damp_hand", offsetof(VehicleDef, nitrousVehParams.m_tire_damp_hand), CSPFT_FLOAT }, + {"nitrous_tire_damp_brake", offsetof(VehicleDef, nitrousVehParams.m_tire_damp_brake), CSPFT_FLOAT }, + {"nitrous_tire_damp_coast", offsetof(VehicleDef, nitrousVehParams.m_tire_damp_coast), CSPFT_FLOAT }, + {"nitrous_tire_fric_brake", offsetof(VehicleDef, nitrousVehParams.m_tire_fric_brake), CSPFT_FLOAT }, + {"nitrous_tire_fric_hand_brake", offsetof(VehicleDef, nitrousVehParams.m_tire_fric_hand_brake), CSPFT_FLOAT }, + {"nitrous_tire_fric_fwd", offsetof(VehicleDef, nitrousVehParams.m_tire_fric_fwd), CSPFT_FLOAT }, + {"nitrous_tire_fric_side", offsetof(VehicleDef, nitrousVehParams.m_tire_fric_side), CSPFT_FLOAT }, + {"nitrous_roll_stability", offsetof(VehicleDef, nitrousVehParams.m_roll_stability), CSPFT_FLOAT }, + {"nitrous_pitch_stability", offsetof(VehicleDef, nitrousVehParams.m_pitch_stability), CSPFT_FLOAT }, + {"nitrous_roll_resistance", offsetof(VehicleDef, nitrousVehParams.m_pitch_roll_resistance), CSPFT_FLOAT }, + {"nitrous_yaw_resistance", offsetof(VehicleDef, nitrousVehParams.m_yaw_resistance), CSPFT_FLOAT }, + {"nitrous_upright_strength", offsetof(VehicleDef, nitrousVehParams.m_upright_strength), CSPFT_FLOAT }, + {"nitrous_tilt_fakey", offsetof(VehicleDef, nitrousVehParams.m_tilt_fakey), CSPFT_FLOAT }, + {"nitrous_traction_type", offsetof(VehicleDef, nitrousVehParams.m_traction_type), VFT_TRACTION_TYPE }, + {"nitrous_peel_out_max_speed", offsetof(VehicleDef, nitrousVehParams.m_peel_out_max_speed), CSPFT_FLOAT }, + {"nitrous_tire_fric_side_max", offsetof(VehicleDef, nitrousVehParams.m_tire_fric_side_max), CSPFT_FLOAT }, + {"nitrous_reverse_scale", offsetof(VehicleDef, nitrousVehParams.m_reverse_scale), CSPFT_FLOAT }, + {"nitrous_water_speed_max", offsetof(VehicleDef, nitrousVehParams.m_water_speed_max), VFT_MPH_TO_INCHES_PER_SECOND}, + {"nitrous_water_accel_max", offsetof(VehicleDef, nitrousVehParams.m_water_accel_max), CSPFT_FLOAT }, + {"nitrous_water_turn_accel", offsetof(VehicleDef, nitrousVehParams.m_water_turn_accel), CSPFT_FLOAT }, + {"nitrous_water_turn_speed_max", offsetof(VehicleDef, nitrousVehParams.m_water_turn_speed_max), CSPFT_FLOAT }, + {"nitrous_boat_ebrake_power", offsetof(VehicleDef, nitrousVehParams.m_water_ebrake_power), CSPFT_FLOAT }, + {"nitrous_bbox_min_x", offsetof(VehicleDef, nitrousVehParams.m_bbox_min.x), CSPFT_FLOAT }, + {"nitrous_bbox_min_y", offsetof(VehicleDef, nitrousVehParams.m_bbox_min.y), CSPFT_FLOAT }, + {"nitrous_bbox_min_z", offsetof(VehicleDef, nitrousVehParams.m_bbox_min.z), CSPFT_FLOAT }, + {"nitrous_bbox_max_x", offsetof(VehicleDef, nitrousVehParams.m_bbox_max.x), CSPFT_FLOAT }, + {"nitrous_bbox_max_y", offsetof(VehicleDef, nitrousVehParams.m_bbox_max.y), CSPFT_FLOAT }, + {"nitrous_bbox_max_z", offsetof(VehicleDef, nitrousVehParams.m_bbox_max.z), CSPFT_FLOAT }, + {"nitrous_mass_center_offset_x", offsetof(VehicleDef, nitrousVehParams.m_mass_center_offset.x), CSPFT_FLOAT }, + {"nitrous_mass_center_offset_y", offsetof(VehicleDef, nitrousVehParams.m_mass_center_offset.y), CSPFT_FLOAT }, + {"nitrous_mass_center_offset_z", offsetof(VehicleDef, nitrousVehParams.m_mass_center_offset.z), CSPFT_FLOAT }, + {"nitrous_buoyancybox_min_x", offsetof(VehicleDef, nitrousVehParams.m_buoyancybox_min.x), CSPFT_FLOAT }, + {"nitrous_buoyancybox_min_y", offsetof(VehicleDef, nitrousVehParams.m_buoyancybox_min.y), CSPFT_FLOAT }, + {"nitrous_buoyancybox_min_z", offsetof(VehicleDef, nitrousVehParams.m_buoyancybox_min.z), CSPFT_FLOAT }, + {"nitrous_buoyancybox_max_x", offsetof(VehicleDef, nitrousVehParams.m_buoyancybox_max.x), CSPFT_FLOAT }, + {"nitrous_buoyancybox_max_y", offsetof(VehicleDef, nitrousVehParams.m_buoyancybox_max.y), CSPFT_FLOAT }, + {"nitrous_buoyancybox_max_z", offsetof(VehicleDef, nitrousVehParams.m_buoyancybox_max.z), CSPFT_FLOAT }, + {"nitrous_boat_speed_rise", offsetof(VehicleDef, nitrousVehParams.m_boat_speed_rise), CSPFT_FLOAT }, + {"nitrous_boat_speed_tilt", offsetof(VehicleDef, nitrousVehParams.m_boat_speed_tilt), CSPFT_FLOAT }, + {"nitrous_boat_motor_offset_x", offsetof(VehicleDef, nitrousVehParams.m_boat_motor_offset.x), CSPFT_FLOAT }, + {"nitrous_boat_motor_offset_y", offsetof(VehicleDef, nitrousVehParams.m_boat_motor_offset.y), CSPFT_FLOAT }, + {"nitrous_boat_motor_offset_z", offsetof(VehicleDef, nitrousVehParams.m_boat_motor_offset.z), CSPFT_FLOAT }, + {"nitrous_boat_side_fric", offsetof(VehicleDef, nitrousVehParams.m_boat_side_fric_scale), CSPFT_FLOAT }, + {"nitrous_boat_forward_fric", offsetof(VehicleDef, nitrousVehParams.m_boat_forward_fric_scale), CSPFT_FLOAT }, + {"nitrous_boat_vertical_fric", offsetof(VehicleDef, nitrousVehParams.m_boat_vertical_fric_scale), CSPFT_FLOAT }, + {"nitrous_drive_on_walls", offsetof(VehicleDef, nitrousVehParams.m_drive_on_walls), CSPFT_BOOL }, + {"nitrous_linear_drag_scale", offsetof(VehicleDef, nitrousVehParams.m_linear_drag_scale), CSPFT_FLOAT }, + {"nitrous_angular_drag_scale", offsetof(VehicleDef, nitrousVehParams.m_angular_drag_scale), CSPFT_FLOAT }, + {"nitrous_jump_force", offsetof(VehicleDef, nitrousVehParams.m_jump_force), CSPFT_FLOAT }, + {"p_driveby_sound_radius", offsetof(VehicleDef, driveBySoundRadius[0]), CSPFT_FLOAT }, + {"s_driveby_sound_radius", offsetof(VehicleDef, driveBySoundRadius[1]), CSPFT_FLOAT }, + {"p_drive_by_sound_apex0", offsetof(VehicleDef, driveBySounds[0].apex), CSPFT_INT }, + {"p_drive_by_sound_name0", offsetof(VehicleDef, driveBySounds[0].name), CSPFT_STRING }, + {"p_drive_by_sound_apex1", offsetof(VehicleDef, driveBySounds[1].apex), CSPFT_INT }, + {"p_drive_by_sound_name1", offsetof(VehicleDef, driveBySounds[1].name), CSPFT_STRING }, + {"p_drive_by_sound_apex2", offsetof(VehicleDef, driveBySounds[2].apex), CSPFT_INT }, + {"p_drive_by_sound_name2", offsetof(VehicleDef, driveBySounds[2].name), CSPFT_STRING }, + {"p_drive_by_sound_apex3", offsetof(VehicleDef, driveBySounds[3].apex), CSPFT_INT }, + {"p_drive_by_sound_name3", offsetof(VehicleDef, driveBySounds[3].name), CSPFT_STRING }, + {"p_drive_by_sound_apex4", offsetof(VehicleDef, driveBySounds[4].apex), CSPFT_INT }, + {"p_drive_by_sound_name4", offsetof(VehicleDef, driveBySounds[4].name), CSPFT_STRING }, + {"p_drive_by_sound_apex5", offsetof(VehicleDef, driveBySounds[5].apex), CSPFT_INT }, + {"p_drive_by_sound_name5", offsetof(VehicleDef, driveBySounds[5].name), CSPFT_STRING }, + {"p_drive_by_sound_apex6", offsetof(VehicleDef, driveBySounds[6].apex), CSPFT_INT }, + {"p_drive_by_sound_name6", offsetof(VehicleDef, driveBySounds[6].name), CSPFT_STRING }, + {"p_drive_by_sound_apex7", offsetof(VehicleDef, driveBySounds[7].apex), CSPFT_INT }, + {"p_drive_by_sound_name7", offsetof(VehicleDef, driveBySounds[7].name), CSPFT_STRING }, + {"p_drive_by_sound_apex8", offsetof(VehicleDef, driveBySounds[8].apex), CSPFT_INT }, + {"p_drive_by_sound_name8", offsetof(VehicleDef, driveBySounds[8].name), CSPFT_STRING }, + {"p_drive_by_sound_apex9", offsetof(VehicleDef, driveBySounds[9].apex), CSPFT_INT }, + {"p_drive_by_sound_name9", offsetof(VehicleDef, driveBySounds[9].name), CSPFT_STRING }, + {"p_drive_by_sound_apex10", offsetof(VehicleDef, driveBySounds[10].apex), CSPFT_INT }, + {"p_drive_by_sound_name10", offsetof(VehicleDef, driveBySounds[10].name), CSPFT_STRING }, + {"p_drive_by_sound_apex11", offsetof(VehicleDef, driveBySounds[11].apex), CSPFT_INT }, + {"p_drive_by_sound_name11", offsetof(VehicleDef, driveBySounds[11].name), CSPFT_STRING }, + {"p_drive_by_sound_apex12", offsetof(VehicleDef, driveBySounds[12].apex), CSPFT_INT }, + {"p_drive_by_sound_name12", offsetof(VehicleDef, driveBySounds[12].name), CSPFT_STRING }, + {"p_drive_by_sound_apex13", offsetof(VehicleDef, driveBySounds[13].apex), CSPFT_INT }, + {"p_drive_by_sound_name13", offsetof(VehicleDef, driveBySounds[13].name), CSPFT_STRING }, + {"p_drive_by_sound_apex14", offsetof(VehicleDef, driveBySounds[14].apex), CSPFT_INT }, + {"p_drive_by_sound_name14", offsetof(VehicleDef, driveBySounds[14].name), CSPFT_STRING }, + {"p_drive_by_sound_apex15", offsetof(VehicleDef, driveBySounds[15].apex), CSPFT_INT }, + {"p_drive_by_sound_name15", offsetof(VehicleDef, driveBySounds[15].name), CSPFT_STRING }, + {"p_drive_by_sound_apex16", offsetof(VehicleDef, driveBySounds[16].apex), CSPFT_INT }, + {"p_drive_by_sound_name16", offsetof(VehicleDef, driveBySounds[16].name), CSPFT_STRING }, + {"p_drive_by_sound_apex17", offsetof(VehicleDef, driveBySounds[17].apex), CSPFT_INT }, + {"p_drive_by_sound_name17", offsetof(VehicleDef, driveBySounds[17].name), CSPFT_STRING }, + {"p_drive_by_sound_apex18", offsetof(VehicleDef, driveBySounds[18].apex), CSPFT_INT }, + {"p_drive_by_sound_name18", offsetof(VehicleDef, driveBySounds[18].name), CSPFT_STRING }, + {"p_drive_by_sound_apex19", offsetof(VehicleDef, driveBySounds[19].apex), CSPFT_INT }, + {"p_drive_by_sound_name19", offsetof(VehicleDef, driveBySounds[19].name), CSPFT_STRING }, + {"s_drive_by_sound_apex0", offsetof(VehicleDef, driveBySounds[20].apex), CSPFT_INT }, + {"s_drive_by_sound_name0", offsetof(VehicleDef, driveBySounds[20].name), CSPFT_STRING }, + {"s_drive_by_sound_apex1", offsetof(VehicleDef, driveBySounds[21].apex), CSPFT_INT }, + {"s_drive_by_sound_name1", offsetof(VehicleDef, driveBySounds[21].name), CSPFT_STRING }, + {"s_drive_by_sound_apex2", offsetof(VehicleDef, driveBySounds[22].apex), CSPFT_INT }, + {"s_drive_by_sound_name2", offsetof(VehicleDef, driveBySounds[22].name), CSPFT_STRING }, + {"s_drive_by_sound_apex3", offsetof(VehicleDef, driveBySounds[23].apex), CSPFT_INT }, + {"s_drive_by_sound_name3", offsetof(VehicleDef, driveBySounds[23].name), CSPFT_STRING }, + {"s_drive_by_sound_apex4", offsetof(VehicleDef, driveBySounds[24].apex), CSPFT_INT }, + {"s_drive_by_sound_name4", offsetof(VehicleDef, driveBySounds[24].name), CSPFT_STRING }, + {"s_drive_by_sound_apex5", offsetof(VehicleDef, driveBySounds[25].apex), CSPFT_INT }, + {"s_drive_by_sound_name5", offsetof(VehicleDef, driveBySounds[25].name), CSPFT_STRING }, + {"s_drive_by_sound_apex6", offsetof(VehicleDef, driveBySounds[26].apex), CSPFT_INT }, + {"s_drive_by_sound_name6", offsetof(VehicleDef, driveBySounds[26].name), CSPFT_STRING }, + {"s_drive_by_sound_apex7", offsetof(VehicleDef, driveBySounds[27].apex), CSPFT_INT }, + {"s_drive_by_sound_name7", offsetof(VehicleDef, driveBySounds[27].name), CSPFT_STRING }, + {"s_drive_by_sound_apex8", offsetof(VehicleDef, driveBySounds[28].apex), CSPFT_INT }, + {"s_drive_by_sound_name8", offsetof(VehicleDef, driveBySounds[28].name), CSPFT_STRING }, + {"s_drive_by_sound_apex9", offsetof(VehicleDef, driveBySounds[29].apex), CSPFT_INT }, + {"s_drive_by_sound_name9", offsetof(VehicleDef, driveBySounds[29].name), CSPFT_STRING }, + {"s_drive_by_sound_apex10", offsetof(VehicleDef, driveBySounds[30].apex), CSPFT_INT }, + {"s_drive_by_sound_name10", offsetof(VehicleDef, driveBySounds[30].name), CSPFT_STRING }, + {"s_drive_by_sound_apex11", offsetof(VehicleDef, driveBySounds[31].apex), CSPFT_INT }, + {"s_drive_by_sound_name11", offsetof(VehicleDef, driveBySounds[31].name), CSPFT_STRING }, + {"s_drive_by_sound_apex12", offsetof(VehicleDef, driveBySounds[32].apex), CSPFT_INT }, + {"s_drive_by_sound_name12", offsetof(VehicleDef, driveBySounds[32].name), CSPFT_STRING }, + {"s_drive_by_sound_apex13", offsetof(VehicleDef, driveBySounds[33].apex), CSPFT_INT }, + {"s_drive_by_sound_name13", offsetof(VehicleDef, driveBySounds[33].name), CSPFT_STRING }, + {"s_drive_by_sound_apex14", offsetof(VehicleDef, driveBySounds[34].apex), CSPFT_INT }, + {"s_drive_by_sound_name14", offsetof(VehicleDef, driveBySounds[34].name), CSPFT_STRING }, + {"s_drive_by_sound_apex15", offsetof(VehicleDef, driveBySounds[35].apex), CSPFT_INT }, + {"s_drive_by_sound_name15", offsetof(VehicleDef, driveBySounds[35].name), CSPFT_STRING }, + {"s_drive_by_sound_apex16", offsetof(VehicleDef, driveBySounds[36].apex), CSPFT_INT }, + {"s_drive_by_sound_name16", offsetof(VehicleDef, driveBySounds[36].name), CSPFT_STRING }, + {"s_drive_by_sound_apex17", offsetof(VehicleDef, driveBySounds[37].apex), CSPFT_INT }, + {"s_drive_by_sound_name17", offsetof(VehicleDef, driveBySounds[37].name), CSPFT_STRING }, + {"s_drive_by_sound_apex18", offsetof(VehicleDef, driveBySounds[38].apex), CSPFT_INT }, + {"s_drive_by_sound_name18", offsetof(VehicleDef, driveBySounds[38].name), CSPFT_STRING }, + {"s_drive_by_sound_apex19", offsetof(VehicleDef, driveBySounds[39].apex), CSPFT_INT }, + {"s_drive_by_sound_name19", offsetof(VehicleDef, driveBySounds[39].name), CSPFT_STRING }, + {"doFootSteps", offsetof(VehicleDef, doFootSteps), CSPFT_BOOL }, + {"isSentient", offsetof(VehicleDef, isSentient), CSPFT_BOOL }, + {"idleRpms", offsetof(VehicleDef, engine.idleRpms), CSPFT_FLOAT }, + {"maxRpms", offsetof(VehicleDef, engine.maxRpms), CSPFT_FLOAT }, + {"maxTorque", offsetof(VehicleDef, engine.maxTorque), CSPFT_FLOAT }, + {"brakingCoeff", offsetof(VehicleDef, engine.brakingCoeff), CSPFT_FLOAT }, + {"onLoadFadeInStart", offsetof(VehicleDef, engine.loadFadeParams.x), CSPFT_FLOAT }, + {"onLoadFadeInEnd", offsetof(VehicleDef, engine.loadFadeParams.y), CSPFT_FLOAT }, + {"offLoadFadeOutStart", offsetof(VehicleDef, engine.loadFadeParams.z), CSPFT_FLOAT }, + {"offLoadFadeOutEnd", offsetof(VehicleDef, engine.loadFadeParams.w), CSPFT_FLOAT }, + {"loadScale", offsetof(VehicleDef, engine.loadScale), CSPFT_FLOAT }, + {"loadSmooting", offsetof(VehicleDef, engine.loadSmoothing), CSPFT_FLOAT }, + {"throttleLag", offsetof(VehicleDef, engine.throttleLag), CSPFT_FLOAT }, + {"pitchScale", offsetof(VehicleDef, engine.pitchScale), CSPFT_FLOAT }, + {"on_engsnd_name0", offsetof(VehicleDef, engine.onload[0].name), CSPFT_STRING }, + {"on_engsnd_fade_in_start0", offsetof(VehicleDef, engine.onload[0].params[VEH_ENGINESND_FADE_IN_START]), CSPFT_FLOAT }, + {"on_engsnd_fade_in_end0", offsetof(VehicleDef, engine.onload[0].params[VEH_ENGINESND_FADE_IN_END]), CSPFT_FLOAT }, + {"on_engsnd_fade_out_start0", offsetof(VehicleDef, engine.onload[0].params[VEH_ENGINESND_FADE_OUT_START]), CSPFT_FLOAT }, + {"on_engsnd_fade_out_end0", offsetof(VehicleDef, engine.onload[0].params[VEH_ENGINESND_FADE_OUT_END]), CSPFT_FLOAT }, + {"on_engsnd_pitch_ref0", offsetof(VehicleDef, engine.onload[0].params[VEH_ENGINESND_PITCH_REF]), CSPFT_FLOAT }, + {"on_engsnd_name1", offsetof(VehicleDef, engine.onload[1].name), CSPFT_STRING }, + {"on_engsnd_fade_in_start1", offsetof(VehicleDef, engine.onload[1].params[VEH_ENGINESND_FADE_IN_START]), CSPFT_FLOAT }, + {"on_engsnd_fade_in_end1", offsetof(VehicleDef, engine.onload[1].params[VEH_ENGINESND_FADE_IN_END]), CSPFT_FLOAT }, + {"on_engsnd_fade_out_start1", offsetof(VehicleDef, engine.onload[1].params[VEH_ENGINESND_FADE_OUT_START]), CSPFT_FLOAT }, + {"on_engsnd_fade_out_end1", offsetof(VehicleDef, engine.onload[1].params[VEH_ENGINESND_FADE_OUT_END]), CSPFT_FLOAT }, + {"on_engsnd_pitch_ref1", offsetof(VehicleDef, engine.onload[1].params[VEH_ENGINESND_PITCH_REF]), CSPFT_FLOAT }, + {"on_engsnd_name2", offsetof(VehicleDef, engine.onload[2].name), CSPFT_STRING }, + {"on_engsnd_fade_in_start2", offsetof(VehicleDef, engine.onload[2].params[VEH_ENGINESND_FADE_IN_START]), CSPFT_FLOAT }, + {"on_engsnd_fade_in_end2", offsetof(VehicleDef, engine.onload[2].params[VEH_ENGINESND_FADE_IN_END]), CSPFT_FLOAT }, + {"on_engsnd_fade_out_start2", offsetof(VehicleDef, engine.onload[2].params[VEH_ENGINESND_FADE_OUT_START]), CSPFT_FLOAT }, + {"on_engsnd_fade_out_end2", offsetof(VehicleDef, engine.onload[2].params[VEH_ENGINESND_FADE_OUT_END]), CSPFT_FLOAT }, + {"on_engsnd_pitch_ref2", offsetof(VehicleDef, engine.onload[2].params[VEH_ENGINESND_PITCH_REF]), CSPFT_FLOAT }, + {"on_engsnd_name3", offsetof(VehicleDef, engine.onload[3].name), CSPFT_STRING }, + {"on_engsnd_fade_in_start3", offsetof(VehicleDef, engine.onload[3].params[VEH_ENGINESND_FADE_IN_START]), CSPFT_FLOAT }, + {"on_engsnd_fade_in_end3", offsetof(VehicleDef, engine.onload[3].params[VEH_ENGINESND_FADE_IN_END]), CSPFT_FLOAT }, + {"on_engsnd_fade_out_start3", offsetof(VehicleDef, engine.onload[3].params[VEH_ENGINESND_FADE_OUT_START]), CSPFT_FLOAT }, + {"on_engsnd_fade_out_end3", offsetof(VehicleDef, engine.onload[3].params[VEH_ENGINESND_FADE_OUT_END]), CSPFT_FLOAT }, + {"on_engsnd_pitch_ref3", offsetof(VehicleDef, engine.onload[3].params[VEH_ENGINESND_PITCH_REF]), CSPFT_FLOAT }, + {"on_engsnd_name4", offsetof(VehicleDef, engine.onload[4].name), CSPFT_STRING }, + {"on_engsnd_fade_in_start4", offsetof(VehicleDef, engine.onload[4].params[VEH_ENGINESND_FADE_IN_START]), CSPFT_FLOAT }, + {"on_engsnd_fade_in_end4", offsetof(VehicleDef, engine.onload[4].params[VEH_ENGINESND_FADE_IN_END]), CSPFT_FLOAT }, + {"on_engsnd_fade_out_start4", offsetof(VehicleDef, engine.onload[4].params[VEH_ENGINESND_FADE_OUT_START]), CSPFT_FLOAT }, + {"on_engsnd_fade_out_end4", offsetof(VehicleDef, engine.onload[4].params[VEH_ENGINESND_FADE_OUT_END]), CSPFT_FLOAT }, + {"on_engsnd_pitch_ref4", offsetof(VehicleDef, engine.onload[4].params[VEH_ENGINESND_PITCH_REF]), CSPFT_FLOAT }, + {"off_engsnd_name0", offsetof(VehicleDef, engine.offload[0].name), CSPFT_STRING }, + {"off_engsnd_fade_in_start0", offsetof(VehicleDef, engine.offload[0].params[VEH_ENGINESND_FADE_IN_START]), CSPFT_FLOAT }, + {"off_engsnd_fade_in_end0", offsetof(VehicleDef, engine.offload[0].params[VEH_ENGINESND_FADE_IN_END]), CSPFT_FLOAT }, + {"off_engsnd_fade_out_start0", offsetof(VehicleDef, engine.offload[0].params[VEH_ENGINESND_FADE_OUT_START]), CSPFT_FLOAT }, + {"off_engsnd_fade_out_end0", offsetof(VehicleDef, engine.offload[0].params[VEH_ENGINESND_FADE_OUT_END]), CSPFT_FLOAT }, + {"off_engsnd_pitch_ref0", offsetof(VehicleDef, engine.offload[0].params[VEH_ENGINESND_PITCH_REF]), CSPFT_FLOAT }, + {"off_engsnd_name1", offsetof(VehicleDef, engine.offload[1].name), CSPFT_STRING }, + {"off_engsnd_fade_in_start1", offsetof(VehicleDef, engine.offload[1].params[VEH_ENGINESND_FADE_IN_START]), CSPFT_FLOAT }, + {"off_engsnd_fade_in_end1", offsetof(VehicleDef, engine.offload[1].params[VEH_ENGINESND_FADE_IN_END]), CSPFT_FLOAT }, + {"off_engsnd_fade_out_start1", offsetof(VehicleDef, engine.offload[1].params[VEH_ENGINESND_FADE_OUT_START]), CSPFT_FLOAT }, + {"off_engsnd_fade_out_end1", offsetof(VehicleDef, engine.offload[1].params[VEH_ENGINESND_FADE_OUT_END]), CSPFT_FLOAT }, + {"off_engsnd_pitch_ref1", offsetof(VehicleDef, engine.offload[1].params[VEH_ENGINESND_PITCH_REF]), CSPFT_FLOAT }, + {"off_engsnd_name2", offsetof(VehicleDef, engine.offload[2].name), CSPFT_STRING }, + {"off_engsnd_fade_in_start2", offsetof(VehicleDef, engine.offload[2].params[VEH_ENGINESND_FADE_IN_START]), CSPFT_FLOAT }, + {"off_engsnd_fade_in_end2", offsetof(VehicleDef, engine.offload[2].params[VEH_ENGINESND_FADE_IN_END]), CSPFT_FLOAT }, + {"off_engsnd_fade_out_start2", offsetof(VehicleDef, engine.offload[2].params[VEH_ENGINESND_FADE_OUT_START]), CSPFT_FLOAT }, + {"off_engsnd_fade_out_end2", offsetof(VehicleDef, engine.offload[2].params[VEH_ENGINESND_FADE_OUT_END]), CSPFT_FLOAT }, + {"off_engsnd_pitch_ref2", offsetof(VehicleDef, engine.offload[2].params[VEH_ENGINESND_PITCH_REF]), CSPFT_FLOAT }, + {"off_engsnd_name3", offsetof(VehicleDef, engine.offload[3].name), CSPFT_STRING }, + {"off_engsnd_fade_in_start3", offsetof(VehicleDef, engine.offload[3].params[VEH_ENGINESND_FADE_IN_START]), CSPFT_FLOAT }, + {"off_engsnd_fade_in_end3", offsetof(VehicleDef, engine.offload[3].params[VEH_ENGINESND_FADE_IN_END]), CSPFT_FLOAT }, + {"off_engsnd_fade_out_start3", offsetof(VehicleDef, engine.offload[3].params[VEH_ENGINESND_FADE_OUT_START]), CSPFT_FLOAT }, + {"off_engsnd_fade_out_end3", offsetof(VehicleDef, engine.offload[3].params[VEH_ENGINESND_FADE_OUT_END]), CSPFT_FLOAT }, + {"off_engsnd_pitch_ref3", offsetof(VehicleDef, engine.offload[3].params[VEH_ENGINESND_PITCH_REF]), CSPFT_FLOAT }, + {"off_engsnd_name4", offsetof(VehicleDef, engine.offload[4].name), CSPFT_STRING }, + {"off_engsnd_fade_in_start4", offsetof(VehicleDef, engine.offload[4].params[VEH_ENGINESND_FADE_IN_START]), CSPFT_FLOAT }, + {"off_engsnd_fade_in_end4", offsetof(VehicleDef, engine.offload[4].params[VEH_ENGINESND_FADE_IN_END]), CSPFT_FLOAT }, + {"off_engsnd_fade_out_start4", offsetof(VehicleDef, engine.offload[4].params[VEH_ENGINESND_FADE_OUT_START]), CSPFT_FLOAT }, + {"off_engsnd_fade_out_end4", offsetof(VehicleDef, engine.offload[4].params[VEH_ENGINESND_FADE_OUT_END]), CSPFT_FLOAT }, + {"off_engsnd_pitch_ref4", offsetof(VehicleDef, engine.offload[4].params[VEH_ENGINESND_PITCH_REF]), CSPFT_FLOAT }, + {"numGears", offsetof(VehicleDef, engine.numGears), CSPFT_INT }, + {"loopLastGear", offsetof(VehicleDef, engine.loopLastGear), CSPFT_BOOL }, + {"gear_min_rpm0", offsetof(VehicleDef, engine.gears[0].minRPM), CSPFT_FLOAT }, + {"gear_max_rpm0", offsetof(VehicleDef, engine.gears[0].maxRPM), CSPFT_FLOAT }, + {"gear_ratio0", offsetof(VehicleDef, engine.gears[0].ratio), CSPFT_FLOAT }, + {"gear_min_rpm1", offsetof(VehicleDef, engine.gears[1].minRPM), CSPFT_FLOAT }, + {"gear_max_rpm1", offsetof(VehicleDef, engine.gears[1].maxRPM), CSPFT_FLOAT }, + {"gear_ratio1", offsetof(VehicleDef, engine.gears[1].ratio), CSPFT_FLOAT }, + {"gear_min_rpm2", offsetof(VehicleDef, engine.gears[2].minRPM), CSPFT_FLOAT }, + {"gear_max_rpm2", offsetof(VehicleDef, engine.gears[2].maxRPM), CSPFT_FLOAT }, + {"gear_ratio2", offsetof(VehicleDef, engine.gears[2].ratio), CSPFT_FLOAT }, + {"gear_min_rpm3", offsetof(VehicleDef, engine.gears[3].minRPM), CSPFT_FLOAT }, + {"gear_max_rpm3", offsetof(VehicleDef, engine.gears[3].maxRPM), CSPFT_FLOAT }, + {"gear_ratio3", offsetof(VehicleDef, engine.gears[3].ratio), CSPFT_FLOAT }, + {"gear_min_rpm4", offsetof(VehicleDef, engine.gears[4].minRPM), CSPFT_FLOAT }, + {"gear_max_rpm4", offsetof(VehicleDef, engine.gears[4].maxRPM), CSPFT_FLOAT }, + {"gear_ratio4", offsetof(VehicleDef, engine.gears[4].ratio), CSPFT_FLOAT }, + {"gear_min_rpm5", offsetof(VehicleDef, engine.gears[5].minRPM), CSPFT_FLOAT }, + {"gear_max_rpm5", offsetof(VehicleDef, engine.gears[5].maxRPM), CSPFT_FLOAT }, + {"gear_ratio5", offsetof(VehicleDef, engine.gears[5].ratio), CSPFT_FLOAT }, + {"gear_min_rpm6", offsetof(VehicleDef, engine.gears[6].minRPM), CSPFT_FLOAT }, + {"gear_max_rpm6", offsetof(VehicleDef, engine.gears[6].maxRPM), CSPFT_FLOAT }, + {"gear_ratio6", offsetof(VehicleDef, engine.gears[6].ratio), CSPFT_FLOAT }, + {"gear_min_rpm7", offsetof(VehicleDef, engine.gears[7].minRPM), CSPFT_FLOAT }, + {"gear_max_rpm7", offsetof(VehicleDef, engine.gears[7].maxRPM), CSPFT_FLOAT }, + {"gear_ratio7", offsetof(VehicleDef, engine.gears[7].ratio), CSPFT_FLOAT }, + {"gear_min_rpm8", offsetof(VehicleDef, engine.gears[8].minRPM), CSPFT_FLOAT }, + {"gear_max_rpm8", offsetof(VehicleDef, engine.gears[8].maxRPM), CSPFT_FLOAT }, + {"gear_ratio8", offsetof(VehicleDef, engine.gears[8].ratio), CSPFT_FLOAT }, + {"gear_min_rpm9", offsetof(VehicleDef, engine.gears[9].minRPM), CSPFT_FLOAT }, + {"gear_max_rpm9", offsetof(VehicleDef, engine.gears[9].maxRPM), CSPFT_FLOAT }, + {"gear_ratio9", offsetof(VehicleDef, engine.gears[9].ratio), CSPFT_FLOAT }, + {"csvInclude", offsetof(VehicleDef, csvInclude), CSPFT_STRING }, + {"antenna1SpringK", offsetof(VehicleDef, antenna[0].springK), CSPFT_FLOAT }, + {"antenna1Damp", offsetof(VehicleDef, antenna[0].damp), CSPFT_FLOAT }, + {"antenna1Length", offsetof(VehicleDef, antenna[0].length), CSPFT_FLOAT }, + {"antenna1Gravity", offsetof(VehicleDef, antenna[0].gravity), CSPFT_FLOAT }, + {"antenna2SpringK", offsetof(VehicleDef, antenna[1].springK), CSPFT_FLOAT }, + {"antenna2Damp", offsetof(VehicleDef, antenna[1].damp), CSPFT_FLOAT }, + {"antenna2Length", offsetof(VehicleDef, antenna[1].length), CSPFT_FLOAT }, + {"antenna2Gravity", offsetof(VehicleDef, antenna[1].gravity), CSPFT_FLOAT }, + {"customFloat0", offsetof(VehicleDef, customFloat0), CSPFT_FLOAT }, + {"customFloat1", offsetof(VehicleDef, customFloat1), CSPFT_FLOAT }, + {"customFloat2", offsetof(VehicleDef, customFloat2), CSPFT_FLOAT }, + {"customBool0", offsetof(VehicleDef, customBool0), CSPFT_BOOL }, + {"customBool1", offsetof(VehicleDef, customBool1), CSPFT_BOOL }, + {"customBool2", offsetof(VehicleDef, customBool2), CSPFT_BOOL }, +}; } \ No newline at end of file diff --git a/src/ObjCommon/Game/T6/InfoString/WeaponAttachmentFields.h b/src/ObjCommon/Game/T6/InfoString/WeaponAttachmentFields.h index 923774479..058c61733 100644 --- a/src/ObjCommon/Game/T6/InfoString/WeaponAttachmentFields.h +++ b/src/ObjCommon/Game/T6/InfoString/WeaponAttachmentFields.h @@ -1,85 +1,83 @@ #pragma once #include "Game/T6/T6.h" -namespace T6 -{ - inline cspField_t attachment_fields[] - { - {"displayName", offsetof(WeaponAttachment, szDisplayName), CSPFT_STRING}, - {"attachmentType", offsetof(WeaponAttachment, attachmentType), AFT_ATTACHMENTTYPE}, - {"penetrateType", offsetof(WeaponAttachment, penetrateType), AFT_PENETRATE_TYPE}, - {"firstRaisePriority", offsetof(WeaponAttachment, firstRaisePriority), CSPFT_INT}, - {"hipIdleAmount", offsetof(WeaponAttachment, fHipIdleAmount), CSPFT_FLOAT}, - {"fireType", offsetof(WeaponAttachment, fireType), AFT_FIRETYPE}, - {"damageRangeScale", offsetof(WeaponAttachment, fDamageRangeScale), CSPFT_FLOAT}, - {"adsZoomFov1", offsetof(WeaponAttachment, fAdsZoomFov1), CSPFT_FLOAT}, - {"adsZoomFov2", offsetof(WeaponAttachment, fAdsZoomFov2), CSPFT_FLOAT}, - {"adsZoomFov3", offsetof(WeaponAttachment, fAdsZoomFov3), CSPFT_FLOAT}, - {"adsZoomInFrac", offsetof(WeaponAttachment, fAdsZoomInFrac), CSPFT_FLOAT}, - {"adsZoomOutFrac", offsetof(WeaponAttachment, fAdsZoomOutFrac), CSPFT_FLOAT}, - {"adsTransInTimeScale", offsetof(WeaponAttachment, fAdsTransInTimeScale), CSPFT_FLOAT}, - {"adsTransOutTimeScale", offsetof(WeaponAttachment, fAdsTransOutTimeScale), CSPFT_FLOAT}, - {"adsRecoilReductionRate", offsetof(WeaponAttachment, fAdsRecoilReductionRate), CSPFT_FLOAT}, - {"adsRecoilReductionLimit", offsetof(WeaponAttachment, fAdsRecoilReductionLimit), CSPFT_FLOAT}, - {"adsViewKickCenterSpeedScale", offsetof(WeaponAttachment, fAdsViewKickCenterSpeedScale), CSPFT_FLOAT}, - {"adsIdleAmountScale", offsetof(WeaponAttachment, fAdsIdleAmountScale), CSPFT_FLOAT}, - {"swayOverride", offsetof(WeaponAttachment, swayOverride), CSPFT_BOOL}, - {"swayMaxAngle", offsetof(WeaponAttachment, swayMaxAngle), CSPFT_FLOAT}, - {"swayLerpSpeed", offsetof(WeaponAttachment, swayLerpSpeed), CSPFT_FLOAT}, - {"swayPitchScale", offsetof(WeaponAttachment, swayPitchScale), CSPFT_FLOAT}, - {"swayYawScale", offsetof(WeaponAttachment, swayYawScale), CSPFT_FLOAT}, - {"swayHorizScale", offsetof(WeaponAttachment, swayHorizScale), CSPFT_FLOAT}, - {"swayVertScale", offsetof(WeaponAttachment, swayVertScale), CSPFT_FLOAT}, - {"adsSwayOverride", offsetof(WeaponAttachment, adsSwayOverride), CSPFT_BOOL}, - {"adsSwayMaxAngle", offsetof(WeaponAttachment, adsSwayMaxAngle), CSPFT_FLOAT}, - {"adsSwayLerpSpeed", offsetof(WeaponAttachment, adsSwayLerpSpeed), CSPFT_FLOAT}, - {"adsSwayPitchScale", offsetof(WeaponAttachment, adsSwayPitchScale), CSPFT_FLOAT}, - {"adsSwayYawScale", offsetof(WeaponAttachment, adsSwayYawScale), CSPFT_FLOAT}, - {"adsSwayHorizScale", offsetof(WeaponAttachment, fAdsSwayHorizScale), CSPFT_FLOAT}, - {"adsSwayVertScale", offsetof(WeaponAttachment, fAdsSwayVertScale), CSPFT_FLOAT}, - {"adsMoveSpeedScale", offsetof(WeaponAttachment, adsMoveSpeedScale), CSPFT_FLOAT}, - {"hipSpreadMinScale", offsetof(WeaponAttachment, fHipSpreadMinScale), CSPFT_FLOAT}, - {"hipSpreadMaxScale", offsetof(WeaponAttachment, fHipSpreadMaxScale), CSPFT_FLOAT}, - {"strafeRotR", offsetof(WeaponAttachment, strafeRotR), CSPFT_FLOAT}, - {"standMoveF", offsetof(WeaponAttachment, standMoveF), CSPFT_FLOAT}, - {"standRotP", offsetof(WeaponAttachment, vStandRot.x), CSPFT_FLOAT}, - {"standRotY", offsetof(WeaponAttachment, vStandRot.y), CSPFT_FLOAT}, - {"standRotR", offsetof(WeaponAttachment, vStandRot.z), CSPFT_FLOAT}, - {"fireTimeScale", offsetof(WeaponAttachment, fFireTimeScale), CSPFT_FLOAT}, - {"reloadTimeScale", offsetof(WeaponAttachment, fReloadTimeScale), CSPFT_FLOAT}, - {"reloadEmptyTimeScale", offsetof(WeaponAttachment, fReloadEmptyTimeScale), CSPFT_FLOAT}, - {"reloadAddTimeScale", offsetof(WeaponAttachment, fReloadAddTimeScale), CSPFT_FLOAT}, - {"reloadQuickTimeScale", offsetof(WeaponAttachment, fReloadQuickTimeScale), CSPFT_FLOAT}, - {"reloadQuickEmptyTimeScale", offsetof(WeaponAttachment, fReloadQuickEmptyTimeScale), CSPFT_FLOAT}, - {"reloadQuickAddTimeScale", offsetof(WeaponAttachment, fReloadQuickAddTimeScale), CSPFT_FLOAT}, - {"perks1", offsetof(WeaponAttachment, perks[0]), CSPFT_UINT}, - {"perks0", offsetof(WeaponAttachment, perks[1]), CSPFT_UINT}, - {"altWeaponAdsOnly", offsetof(WeaponAttachment, bAltWeaponAdsOnly), CSPFT_BOOL}, - {"altWeaponDisableSwitching", offsetof(WeaponAttachment, bAltWeaponDisableSwitching), CSPFT_BOOL}, - {"altScopeADSTransInTime", offsetof(WeaponAttachment, altScopeADSTransInTime), CSPFT_FLOAT}, - {"altScopeADSTransOutTime", offsetof(WeaponAttachment, altScopeADSTransOutTime), CSPFT_FLOAT}, - {"silenced", offsetof(WeaponAttachment, bSilenced), CSPFT_BOOL}, - {"dualMag", offsetof(WeaponAttachment, bDualMag), CSPFT_BOOL}, - {"laserSight", offsetof(WeaponAttachment, laserSight), CSPFT_BOOL}, - {"infrared", offsetof(WeaponAttachment, bInfraRed), CSPFT_BOOL}, - {"useAsMelee", offsetof(WeaponAttachment, bUseAsMelee), CSPFT_BOOL}, - {"dualWield", offsetof(WeaponAttachment, bDualWield), CSPFT_BOOL}, - {"sharedAmmo", offsetof(WeaponAttachment, sharedAmmo), CSPFT_BOOL}, - {"mmsWeapon", offsetof(WeaponAttachment, mmsWeapon), CSPFT_BOOL}, - {"mmsInScope", offsetof(WeaponAttachment, mmsInScope), CSPFT_BOOL}, - {"mmsFOV", offsetof(WeaponAttachment, mmsFOV), CSPFT_FLOAT}, - {"mmsAspect", offsetof(WeaponAttachment, mmsAspect), CSPFT_FLOAT}, - {"mmsMaxDist", offsetof(WeaponAttachment, mmsMaxDist), CSPFT_FLOAT}, - {"clipSizeScale", offsetof(WeaponAttachment, clipSizeScale), CSPFT_FLOAT}, - {"clipSize", offsetof(WeaponAttachment, iClipSize), CSPFT_INT}, - {"stackFire", offsetof(WeaponAttachment, stackFire), CSPFT_FLOAT}, - {"stackFireSpread", offsetof(WeaponAttachment, stackFireSpread), CSPFT_FLOAT}, - {"stackFireAccuracyDecay", offsetof(WeaponAttachment, stackFireAccuracyDecay), CSPFT_FLOAT}, - {"customFloat0", offsetof(WeaponAttachment, customFloat0), CSPFT_FLOAT}, - {"customFloat1", offsetof(WeaponAttachment, customFloat1), CSPFT_FLOAT}, - {"customFloat2", offsetof(WeaponAttachment, customFloat2), CSPFT_FLOAT}, - {"customBool0", offsetof(WeaponAttachment, customBool0), CSPFT_BOOL}, - {"customBool1", offsetof(WeaponAttachment, customBool1), CSPFT_BOOL}, - {"customBool2", offsetof(WeaponAttachment, customBool2), CSPFT_BOOL}, - }; +namespace T6 { +inline cspField_t attachment_fields[]{ + {"displayName", offsetof(WeaponAttachment, szDisplayName), CSPFT_STRING }, + {"attachmentType", offsetof(WeaponAttachment, attachmentType), AFT_ATTACHMENTTYPE}, + {"penetrateType", offsetof(WeaponAttachment, penetrateType), AFT_PENETRATE_TYPE}, + {"firstRaisePriority", offsetof(WeaponAttachment, firstRaisePriority), CSPFT_INT }, + {"hipIdleAmount", offsetof(WeaponAttachment, fHipIdleAmount), CSPFT_FLOAT }, + {"fireType", offsetof(WeaponAttachment, fireType), AFT_FIRETYPE }, + {"damageRangeScale", offsetof(WeaponAttachment, fDamageRangeScale), CSPFT_FLOAT }, + {"adsZoomFov1", offsetof(WeaponAttachment, fAdsZoomFov1), CSPFT_FLOAT }, + {"adsZoomFov2", offsetof(WeaponAttachment, fAdsZoomFov2), CSPFT_FLOAT }, + {"adsZoomFov3", offsetof(WeaponAttachment, fAdsZoomFov3), CSPFT_FLOAT }, + {"adsZoomInFrac", offsetof(WeaponAttachment, fAdsZoomInFrac), CSPFT_FLOAT }, + {"adsZoomOutFrac", offsetof(WeaponAttachment, fAdsZoomOutFrac), CSPFT_FLOAT }, + {"adsTransInTimeScale", offsetof(WeaponAttachment, fAdsTransInTimeScale), CSPFT_FLOAT }, + {"adsTransOutTimeScale", offsetof(WeaponAttachment, fAdsTransOutTimeScale), CSPFT_FLOAT }, + {"adsRecoilReductionRate", offsetof(WeaponAttachment, fAdsRecoilReductionRate), CSPFT_FLOAT }, + {"adsRecoilReductionLimit", offsetof(WeaponAttachment, fAdsRecoilReductionLimit), CSPFT_FLOAT }, + {"adsViewKickCenterSpeedScale", offsetof(WeaponAttachment, fAdsViewKickCenterSpeedScale), CSPFT_FLOAT }, + {"adsIdleAmountScale", offsetof(WeaponAttachment, fAdsIdleAmountScale), CSPFT_FLOAT }, + {"swayOverride", offsetof(WeaponAttachment, swayOverride), CSPFT_BOOL }, + {"swayMaxAngle", offsetof(WeaponAttachment, swayMaxAngle), CSPFT_FLOAT }, + {"swayLerpSpeed", offsetof(WeaponAttachment, swayLerpSpeed), CSPFT_FLOAT }, + {"swayPitchScale", offsetof(WeaponAttachment, swayPitchScale), CSPFT_FLOAT }, + {"swayYawScale", offsetof(WeaponAttachment, swayYawScale), CSPFT_FLOAT }, + {"swayHorizScale", offsetof(WeaponAttachment, swayHorizScale), CSPFT_FLOAT }, + {"swayVertScale", offsetof(WeaponAttachment, swayVertScale), CSPFT_FLOAT }, + {"adsSwayOverride", offsetof(WeaponAttachment, adsSwayOverride), CSPFT_BOOL }, + {"adsSwayMaxAngle", offsetof(WeaponAttachment, adsSwayMaxAngle), CSPFT_FLOAT }, + {"adsSwayLerpSpeed", offsetof(WeaponAttachment, adsSwayLerpSpeed), CSPFT_FLOAT }, + {"adsSwayPitchScale", offsetof(WeaponAttachment, adsSwayPitchScale), CSPFT_FLOAT }, + {"adsSwayYawScale", offsetof(WeaponAttachment, adsSwayYawScale), CSPFT_FLOAT }, + {"adsSwayHorizScale", offsetof(WeaponAttachment, fAdsSwayHorizScale), CSPFT_FLOAT }, + {"adsSwayVertScale", offsetof(WeaponAttachment, fAdsSwayVertScale), CSPFT_FLOAT }, + {"adsMoveSpeedScale", offsetof(WeaponAttachment, adsMoveSpeedScale), CSPFT_FLOAT }, + {"hipSpreadMinScale", offsetof(WeaponAttachment, fHipSpreadMinScale), CSPFT_FLOAT }, + {"hipSpreadMaxScale", offsetof(WeaponAttachment, fHipSpreadMaxScale), CSPFT_FLOAT }, + {"strafeRotR", offsetof(WeaponAttachment, strafeRotR), CSPFT_FLOAT }, + {"standMoveF", offsetof(WeaponAttachment, standMoveF), CSPFT_FLOAT }, + {"standRotP", offsetof(WeaponAttachment, vStandRot.x), CSPFT_FLOAT }, + {"standRotY", offsetof(WeaponAttachment, vStandRot.y), CSPFT_FLOAT }, + {"standRotR", offsetof(WeaponAttachment, vStandRot.z), CSPFT_FLOAT }, + {"fireTimeScale", offsetof(WeaponAttachment, fFireTimeScale), CSPFT_FLOAT }, + {"reloadTimeScale", offsetof(WeaponAttachment, fReloadTimeScale), CSPFT_FLOAT }, + {"reloadEmptyTimeScale", offsetof(WeaponAttachment, fReloadEmptyTimeScale), CSPFT_FLOAT }, + {"reloadAddTimeScale", offsetof(WeaponAttachment, fReloadAddTimeScale), CSPFT_FLOAT }, + {"reloadQuickTimeScale", offsetof(WeaponAttachment, fReloadQuickTimeScale), CSPFT_FLOAT }, + {"reloadQuickEmptyTimeScale", offsetof(WeaponAttachment, fReloadQuickEmptyTimeScale), CSPFT_FLOAT }, + {"reloadQuickAddTimeScale", offsetof(WeaponAttachment, fReloadQuickAddTimeScale), CSPFT_FLOAT }, + {"perks1", offsetof(WeaponAttachment, perks[0]), CSPFT_UINT }, + {"perks0", offsetof(WeaponAttachment, perks[1]), CSPFT_UINT }, + {"altWeaponAdsOnly", offsetof(WeaponAttachment, bAltWeaponAdsOnly), CSPFT_BOOL }, + {"altWeaponDisableSwitching", offsetof(WeaponAttachment, bAltWeaponDisableSwitching), CSPFT_BOOL }, + {"altScopeADSTransInTime", offsetof(WeaponAttachment, altScopeADSTransInTime), CSPFT_FLOAT }, + {"altScopeADSTransOutTime", offsetof(WeaponAttachment, altScopeADSTransOutTime), CSPFT_FLOAT }, + {"silenced", offsetof(WeaponAttachment, bSilenced), CSPFT_BOOL }, + {"dualMag", offsetof(WeaponAttachment, bDualMag), CSPFT_BOOL }, + {"laserSight", offsetof(WeaponAttachment, laserSight), CSPFT_BOOL }, + {"infrared", offsetof(WeaponAttachment, bInfraRed), CSPFT_BOOL }, + {"useAsMelee", offsetof(WeaponAttachment, bUseAsMelee), CSPFT_BOOL }, + {"dualWield", offsetof(WeaponAttachment, bDualWield), CSPFT_BOOL }, + {"sharedAmmo", offsetof(WeaponAttachment, sharedAmmo), CSPFT_BOOL }, + {"mmsWeapon", offsetof(WeaponAttachment, mmsWeapon), CSPFT_BOOL }, + {"mmsInScope", offsetof(WeaponAttachment, mmsInScope), CSPFT_BOOL }, + {"mmsFOV", offsetof(WeaponAttachment, mmsFOV), CSPFT_FLOAT }, + {"mmsAspect", offsetof(WeaponAttachment, mmsAspect), CSPFT_FLOAT }, + {"mmsMaxDist", offsetof(WeaponAttachment, mmsMaxDist), CSPFT_FLOAT }, + {"clipSizeScale", offsetof(WeaponAttachment, clipSizeScale), CSPFT_FLOAT }, + {"clipSize", offsetof(WeaponAttachment, iClipSize), CSPFT_INT }, + {"stackFire", offsetof(WeaponAttachment, stackFire), CSPFT_FLOAT }, + {"stackFireSpread", offsetof(WeaponAttachment, stackFireSpread), CSPFT_FLOAT }, + {"stackFireAccuracyDecay", offsetof(WeaponAttachment, stackFireAccuracyDecay), CSPFT_FLOAT }, + {"customFloat0", offsetof(WeaponAttachment, customFloat0), CSPFT_FLOAT }, + {"customFloat1", offsetof(WeaponAttachment, customFloat1), CSPFT_FLOAT }, + {"customFloat2", offsetof(WeaponAttachment, customFloat2), CSPFT_FLOAT }, + {"customBool0", offsetof(WeaponAttachment, customBool0), CSPFT_BOOL }, + {"customBool1", offsetof(WeaponAttachment, customBool1), CSPFT_BOOL }, + {"customBool2", offsetof(WeaponAttachment, customBool2), CSPFT_BOOL }, +}; } \ No newline at end of file diff --git a/src/ObjCommon/Game/T6/InfoString/WeaponAttachmentUniqueFields.h b/src/ObjCommon/Game/T6/InfoString/WeaponAttachmentUniqueFields.h index 27dc77792..7f1c51a18 100644 --- a/src/ObjCommon/Game/T6/InfoString/WeaponAttachmentUniqueFields.h +++ b/src/ObjCommon/Game/T6/InfoString/WeaponAttachmentUniqueFields.h @@ -1,210 +1,208 @@ #pragma once #include "Game/T6/T6.h" -namespace T6 -{ - inline cspField_t attachment_unique_fields[] - { - {"attachmentType", offsetof(WeaponAttachmentUniqueFull, attachment.attachmentType), AUFT_ATTACHMENTTYPE}, - {"locNone", offsetof(WeaponAttachmentUniqueFull, locationDamageMultipliers[HITLOC_NONE]), CSPFT_FLOAT}, - {"locHelmet", offsetof(WeaponAttachmentUniqueFull, locationDamageMultipliers[HITLOC_HELMET]), CSPFT_FLOAT}, - {"locHead", offsetof(WeaponAttachmentUniqueFull, locationDamageMultipliers[HITLOC_HEAD]), CSPFT_FLOAT}, - {"locNeck", offsetof(WeaponAttachmentUniqueFull, locationDamageMultipliers[HITLOC_NECK]), CSPFT_FLOAT}, - {"locTorsoUpper", offsetof(WeaponAttachmentUniqueFull, locationDamageMultipliers[HITLOC_TORSO_UPR]), CSPFT_FLOAT}, - {"locTorsoMid", offsetof(WeaponAttachmentUniqueFull, locationDamageMultipliers[HITLOC_TORSO_MID]), CSPFT_FLOAT}, - {"locTorsoLower", offsetof(WeaponAttachmentUniqueFull, locationDamageMultipliers[HITLOC_TORSO_LWR]), CSPFT_FLOAT}, - {"locRightArmUpper", offsetof(WeaponAttachmentUniqueFull, locationDamageMultipliers[HITLOC_R_ARM_UPR]), CSPFT_FLOAT}, - {"locRightArmLower", offsetof(WeaponAttachmentUniqueFull, locationDamageMultipliers[HITLOC_R_ARM_LWR]), CSPFT_FLOAT}, - {"locRightHand", offsetof(WeaponAttachmentUniqueFull, locationDamageMultipliers[HITLOC_R_HAND]), CSPFT_FLOAT}, - {"locLeftArmUpper", offsetof(WeaponAttachmentUniqueFull, locationDamageMultipliers[HITLOC_L_ARM_UPR]), CSPFT_FLOAT}, - {"locLeftArmLower", offsetof(WeaponAttachmentUniqueFull, locationDamageMultipliers[HITLOC_L_ARM_LWR]), CSPFT_FLOAT}, - {"locLeftHand", offsetof(WeaponAttachmentUniqueFull, locationDamageMultipliers[HITLOC_L_HAND]), CSPFT_FLOAT}, - {"locRightLegUpper", offsetof(WeaponAttachmentUniqueFull, locationDamageMultipliers[HITLOC_R_LEG_UPR]), CSPFT_FLOAT}, - {"locRightLegLower", offsetof(WeaponAttachmentUniqueFull, locationDamageMultipliers[HITLOC_R_LEG_LWR]), CSPFT_FLOAT}, - {"locRightFoot", offsetof(WeaponAttachmentUniqueFull, locationDamageMultipliers[HITLOC_R_FOOT]), CSPFT_FLOAT}, - {"locLeftLegUpper", offsetof(WeaponAttachmentUniqueFull, locationDamageMultipliers[HITLOC_L_LEG_UPR]), CSPFT_FLOAT}, - {"locLeftLegLower", offsetof(WeaponAttachmentUniqueFull, locationDamageMultipliers[HITLOC_L_LEG_LWR]), CSPFT_FLOAT}, - {"locLeftFoot", offsetof(WeaponAttachmentUniqueFull, locationDamageMultipliers[HITLOC_L_FOOT]), CSPFT_FLOAT}, - {"locGun", offsetof(WeaponAttachmentUniqueFull, locationDamageMultipliers[HITLOC_GUN]), CSPFT_FLOAT}, - {"viewModel", offsetof(WeaponAttachmentUniqueFull, attachment.viewModel), CSPFT_XMODEL}, - {"viewModelAdditional", offsetof(WeaponAttachmentUniqueFull, attachment.viewModelAdditional), CSPFT_XMODEL}, - {"viewModelADS", offsetof(WeaponAttachmentUniqueFull, attachment.viewModelADS), CSPFT_XMODEL}, - {"worldModel", offsetof(WeaponAttachmentUniqueFull, attachment.worldModel), CSPFT_XMODEL}, - {"worldModelAdditional", offsetof(WeaponAttachmentUniqueFull, attachment.worldModelAdditional), CSPFT_XMODEL}, - {"viewModelTag", offsetof(WeaponAttachmentUniqueFull, attachment.viewModelTag), CSPFT_STRING}, - {"worldModelTag", offsetof(WeaponAttachmentUniqueFull, attachment.worldModelTag), CSPFT_STRING}, - {"viewModelOffsetX", offsetof(WeaponAttachmentUniqueFull, attachment.viewModelOffsets.x), CSPFT_FLOAT}, - {"viewModelOffsetY", offsetof(WeaponAttachmentUniqueFull, attachment.viewModelOffsets.y), CSPFT_FLOAT}, - {"viewModelOffsetZ", offsetof(WeaponAttachmentUniqueFull, attachment.viewModelOffsets.z), CSPFT_FLOAT}, - {"viewModelOffsetPitch", offsetof(WeaponAttachmentUniqueFull, attachment.viewModelRotations.x), CSPFT_FLOAT}, - {"viewModelOffsetYaw", offsetof(WeaponAttachmentUniqueFull, attachment.viewModelRotations.y), CSPFT_FLOAT}, - {"viewModelOffsetRoll", offsetof(WeaponAttachmentUniqueFull, attachment.viewModelRotations.z), CSPFT_FLOAT}, - {"worldModelOffsetX", offsetof(WeaponAttachmentUniqueFull, attachment.worldModelOffsets.x), CSPFT_FLOAT}, - {"worldModelOffsetY", offsetof(WeaponAttachmentUniqueFull, attachment.worldModelOffsets.y), CSPFT_FLOAT}, - {"worldModelOffsetZ", offsetof(WeaponAttachmentUniqueFull, attachment.worldModelOffsets.z), CSPFT_FLOAT}, - {"worldModelOffsetPitch", offsetof(WeaponAttachmentUniqueFull, attachment.worldModelRotations.x), CSPFT_FLOAT}, - {"worldModelOffsetYaw", offsetof(WeaponAttachmentUniqueFull, attachment.worldModelRotations.y), CSPFT_FLOAT}, - {"worldModelOffsetRoll", offsetof(WeaponAttachmentUniqueFull, attachment.worldModelRotations.z), CSPFT_FLOAT}, - {"viewModelAddOffsetX", offsetof(WeaponAttachmentUniqueFull, attachment.viewModelAddOffsets.x), CSPFT_FLOAT}, - {"viewModelAddOffsetY", offsetof(WeaponAttachmentUniqueFull, attachment.viewModelAddOffsets.y), CSPFT_FLOAT}, - {"viewModelAddOffsetZ", offsetof(WeaponAttachmentUniqueFull, attachment.viewModelAddOffsets.z), CSPFT_FLOAT}, - {"viewModelAddOffsetPitch", offsetof(WeaponAttachmentUniqueFull, attachment.viewModelAddRotations.x), CSPFT_FLOAT}, - {"viewModelAddOffsetYaw", offsetof(WeaponAttachmentUniqueFull, attachment.viewModelAddRotations.y), CSPFT_FLOAT}, - {"viewModelAddOffsetRoll", offsetof(WeaponAttachmentUniqueFull, attachment.viewModelAddRotations.z), CSPFT_FLOAT}, - {"worldModelAddOffsetX", offsetof(WeaponAttachmentUniqueFull, attachment.worldModelAddOffsets.x), CSPFT_FLOAT}, - {"worldModelAddOffsetY", offsetof(WeaponAttachmentUniqueFull, attachment.worldModelAddOffsets.y), CSPFT_FLOAT}, - {"worldModelAddOffsetZ", offsetof(WeaponAttachmentUniqueFull, attachment.worldModelAddOffsets.z), CSPFT_FLOAT}, - {"worldModelAddOffsetPitch", offsetof(WeaponAttachmentUniqueFull, attachment.worldModelAddRotations.x), CSPFT_FLOAT}, - {"worldModelAddOffsetYaw", offsetof(WeaponAttachmentUniqueFull, attachment.worldModelAddRotations.y), CSPFT_FLOAT}, - {"worldModelAddOffsetRoll", offsetof(WeaponAttachmentUniqueFull, attachment.worldModelAddRotations.z), CSPFT_FLOAT}, - {"hideTags", offsetof(WeaponAttachmentUniqueFull, hideTags), AUFT_HIDETAGS}, - {"camo", offsetof(WeaponAttachmentUniqueFull, attachment.weaponCamo), AUFT_CAMO}, - {"disableBaseWeaponAttachment", offsetof(WeaponAttachmentUniqueFull, attachment.disableBaseWeaponAttachment), CSPFT_BOOL}, - {"disableBaseWeaponClip", offsetof(WeaponAttachmentUniqueFull, attachment.disableBaseWeaponClip), CSPFT_BOOL}, - {"overrideBaseWeaponAttachmentOffsets", offsetof(WeaponAttachmentUniqueFull, attachment.overrideBaseWeaponAttachmentOffsets), CSPFT_BOOL}, - {"viewModelOffsetBaseAttachmentX", offsetof(WeaponAttachmentUniqueFull, attachment.viewModelOffsetBaseAttachment.x), CSPFT_FLOAT}, - {"viewModelOffsetBaseAttachmentY", offsetof(WeaponAttachmentUniqueFull, attachment.viewModelOffsetBaseAttachment.y), CSPFT_FLOAT}, - {"viewModelOffsetBaseAttachmentZ", offsetof(WeaponAttachmentUniqueFull, attachment.viewModelOffsetBaseAttachment.z), CSPFT_FLOAT}, - {"worldModelOffsetBaseAttachmentX", offsetof(WeaponAttachmentUniqueFull, attachment.worldModelOffsetBaseAttachment.x), CSPFT_FLOAT}, - {"worldModelOffsetBaseAttachmentY", offsetof(WeaponAttachmentUniqueFull, attachment.worldModelOffsetBaseAttachment.y), CSPFT_FLOAT}, - {"worldModelOffsetBaseAttachmentZ", offsetof(WeaponAttachmentUniqueFull, attachment.worldModelOffsetBaseAttachment.z), CSPFT_FLOAT}, - {"altWeapon", offsetof(WeaponAttachmentUniqueFull, attachment.szAltWeaponName), CSPFT_STRING}, - {"DualWieldWeapon", offsetof(WeaponAttachmentUniqueFull, attachment.szDualWieldWeaponName), CSPFT_STRING}, - {"adsOverlayShader", offsetof(WeaponAttachmentUniqueFull, attachment.overlayMaterial), CSPFT_MATERIAL_STREAM}, - {"adsOverlayShaderLowRes", offsetof(WeaponAttachmentUniqueFull, attachment.overlayMaterialLowRes), CSPFT_MATERIAL_STREAM}, - {"adsOverlayReticle", offsetof(WeaponAttachmentUniqueFull, attachment.overlayReticle), AUFT_OVERLAYRETICLE}, - {"firstRaiseTime", offsetof(WeaponAttachmentUniqueFull, attachment.iFirstRaiseTime), CSPFT_MILLISECONDS}, - {"altRaiseTime", offsetof(WeaponAttachmentUniqueFull, attachment.iAltRaiseTime), CSPFT_MILLISECONDS}, - {"altDropTime", offsetof(WeaponAttachmentUniqueFull, attachment.iAltDropTime), CSPFT_MILLISECONDS}, - {"reloadAmmoAdd", offsetof(WeaponAttachmentUniqueFull, attachment.iReloadAmmoAdd), CSPFT_INT}, - {"reloadStartAdd", offsetof(WeaponAttachmentUniqueFull, attachment.iReloadStartAdd), CSPFT_INT}, - {"segmentedReload", offsetof(WeaponAttachmentUniqueFull, attachment.bSegmentedReload), CSPFT_BOOL}, - {"idleAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_IDLE]), CSPFT_STRING}, - {"idleAnimLeft", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_IDLE_LEFT]), CSPFT_STRING}, - {"emptyIdleAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_EMPTY_IDLE]), CSPFT_STRING}, - {"emptyIdleAnimLeft", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_EMPTY_IDLE_LEFT]), CSPFT_STRING}, - {"fireIntroAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_FIRE_INTRO]), CSPFT_STRING}, - {"fireAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_FIRE]), CSPFT_STRING}, - {"fireAnimLeft", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_FIRE_LEFT]), CSPFT_STRING}, - {"holdFireAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_HOLD_FIRE]), CSPFT_STRING}, - {"lastShotAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_LASTSHOT]), CSPFT_STRING}, - {"lastShotAnimLeft", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_LASTSHOT_LEFT]), CSPFT_STRING}, - {"flourishAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_FINALSHOT]), CSPFT_STRING}, - {"flourishAnimLeft", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_FINALSHOT_LEFT]), CSPFT_STRING}, - {"detonateAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_DETONATE]), CSPFT_STRING}, - {"rechamberAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_RECHAMBER]), CSPFT_STRING}, - {"meleeAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_MELEE]), CSPFT_STRING}, - {"meleeAnimEmpty", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_MELEE_EMPTY]), CSPFT_STRING}, - {"meleeAnim1", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_MELEE1]), CSPFT_STRING}, - {"meleeAnim2", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_MELEE2]), CSPFT_STRING}, - {"meleeAnim3", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_MELEE3]), CSPFT_STRING}, - {"meleeChargeAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_MELEE_CHARGE]), CSPFT_STRING}, - {"meleeChargeAnimEmpty", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_MELEE_CHARGE_EMPTY]), CSPFT_STRING}, - {"reloadAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_RELOAD]), CSPFT_STRING}, - {"reloadAnimRight", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_RELOAD_RIGHT]), CSPFT_STRING}, - {"reloadAnimLeft", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_RELOAD_LEFT]), CSPFT_STRING}, - {"reloadEmptyAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_RELOAD_EMPTY]), CSPFT_STRING}, - {"reloadEmptyAnimLeft", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_RELOAD_EMPTY_LEFT]), CSPFT_STRING}, - {"reloadStartAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_RELOAD_START]), CSPFT_STRING}, - {"reloadEndAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_RELOAD_END]), CSPFT_STRING}, - {"reloadQuickAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_RELOAD_QUICK]), CSPFT_STRING}, - {"reloadQuickEmptyAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_RELOAD_QUICK_EMPTY]), CSPFT_STRING}, - {"raiseAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_RAISE]), CSPFT_STRING}, - {"dropAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_DROP]), CSPFT_STRING}, - {"firstRaiseAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_FIRST_RAISE]), CSPFT_STRING}, - {"altRaiseAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_ALT_RAISE]), CSPFT_STRING}, - {"altDropAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_ALT_DROP]), CSPFT_STRING}, - {"quickRaiseAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_QUICK_RAISE]), CSPFT_STRING}, - {"quickDropAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_QUICK_DROP]), CSPFT_STRING}, - {"emptyRaiseAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_EMPTY_RAISE]), CSPFT_STRING}, - {"emptyDropAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_EMPTY_DROP]), CSPFT_STRING}, - {"sprintInAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_SPRINT_IN]), CSPFT_STRING}, - {"sprintLoopAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_SPRINT_LOOP]), CSPFT_STRING}, - {"sprintOutAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_SPRINT_OUT]), CSPFT_STRING}, - {"sprintInEmptyAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_SPRINT_EMPTY_IN]), CSPFT_STRING}, - {"sprintLoopEmptyAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_SPRINT_EMPTY_LOOP]), CSPFT_STRING}, - {"sprintOutEmptyAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_SPRINT_EMPTY_OUT]), CSPFT_STRING}, - {"lowReadyInAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_LOWREADY_IN]), CSPFT_STRING}, - {"lowReadyLoopAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_LOWREADY_LOOP]), CSPFT_STRING}, - {"lowReadyOutAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_LOWREADY_OUT]), CSPFT_STRING}, - {"contFireInAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_CONT_FIRE_IN]), CSPFT_STRING}, - {"contFireLoopAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_CONT_FIRE_LOOP]), CSPFT_STRING}, - {"contFireOutAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_CONT_FIRE_OUT]), CSPFT_STRING}, - {"crawlInAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_CRAWL_IN]), CSPFT_STRING}, - {"crawlForwardAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_CRAWL_FORWARD]), CSPFT_STRING}, - {"crawlBackAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_CRAWL_BACK]), CSPFT_STRING}, - {"crawlRightAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_CRAWL_RIGHT]), CSPFT_STRING}, - {"crawlLeftAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_CRAWL_LEFT]), CSPFT_STRING}, - {"crawlOutAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_CRAWL_OUT]), CSPFT_STRING}, - {"crawlEmptyInAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_CRAWL_EMPTY_IN]), CSPFT_STRING}, - {"crawlEmptyForwardAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_CRAWL_EMPTY_FORWARD]), CSPFT_STRING}, - {"crawlEmptyBackAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_CRAWL_EMPTY_BACK]), CSPFT_STRING}, - {"crawlEmptyRightAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_CRAWL_EMPTY_RIGHT]), CSPFT_STRING}, - {"crawlEmptyLeftAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_CRAWL_EMPTY_LEFT]), CSPFT_STRING}, - {"crawlEmptyOutAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_CRAWL_EMPTY_OUT]), CSPFT_STRING}, - {"deployAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_DEPLOY]), CSPFT_STRING}, - {"breakdownAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_BREAKDOWN]), CSPFT_STRING}, - {"nightVisionWearAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_NIGHTVISION_WEAR]), CSPFT_STRING}, - {"nightVisionRemoveAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_NIGHTVISION_REMOVE]), CSPFT_STRING}, - {"adsFireAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_ADS_FIRE]), CSPFT_STRING}, - {"adsLastShotAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_ADS_LASTSHOT]), CSPFT_STRING}, - {"adsRechamberAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_ADS_RECHAMBER]), CSPFT_STRING}, - {"adsUpAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_ADS_UP]), CSPFT_STRING}, - {"adsDownAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_ADS_DOWN]), CSPFT_STRING}, - {"adsUpOtherScopeAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_ADS_UP_OTHER_SCOPE]), CSPFT_STRING}, - {"adsFireIntroAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_ADS_FIRE_INTRO]), CSPFT_STRING}, - {"dtp_in", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_DTP_IN]), CSPFT_STRING}, - {"dtp_loop", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_DTP_LOOP]), CSPFT_STRING}, - {"dtp_out", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_DTP_OUT]), CSPFT_STRING}, - {"dtp_empty_in", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_DTP_EMPTY_IN]), CSPFT_STRING}, - {"dtp_empty_loop", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_DTP_EMPTY_LOOP]), CSPFT_STRING}, - {"dtp_empty_out", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_DTP_EMPTY_OUT]), CSPFT_STRING}, - {"slide_in", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_SLIDE_IN]), CSPFT_STRING}, - {"mantleAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_MANTLE]), CSPFT_STRING}, - {"sprintCameraAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_CAMERA_SPRINT_LOOP]), CSPFT_STRING}, - {"dtpInCameraAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_CAMERA_DTP_IN]), CSPFT_STRING}, - {"dtpLoopCameraAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_CAMERA_DTP_LOOP]), CSPFT_STRING}, - {"dtpOutCameraAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_CAMERA_DTP_OUT]), CSPFT_STRING}, - {"mantleCameraAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_CAMERA_MANTLE]), CSPFT_STRING}, - {"fireSound", offsetof(WeaponAttachmentUniqueFull, attachment.fireSound), CSPFT_STRING}, - {"fireSoundPlayer", offsetof(WeaponAttachmentUniqueFull, attachment.fireSoundPlayer), CSPFT_STRING}, - {"loopFireSound", offsetof(WeaponAttachmentUniqueFull, attachment.fireLoopSound), CSPFT_STRING}, - {"loopFireSoundPlayer", offsetof(WeaponAttachmentUniqueFull, attachment.fireLoopSoundPlayer), CSPFT_STRING}, - {"loopFireEndSound", offsetof(WeaponAttachmentUniqueFull, attachment.fireLoopEndSound), CSPFT_STRING}, - {"loopFireEndSoundPlayer", offsetof(WeaponAttachmentUniqueFull, attachment.fireLoopEndSoundPlayer), CSPFT_STRING}, - {"startFireSound", offsetof(WeaponAttachmentUniqueFull, attachment.fireStartSound), CSPFT_STRING}, - {"stopFireSound", offsetof(WeaponAttachmentUniqueFull, attachment.fireStopSound), CSPFT_STRING}, - {"startFireSoundPlayer", offsetof(WeaponAttachmentUniqueFull, attachment.fireStartSoundPlayer), CSPFT_STRING}, - {"stopFireSoundPlayer", offsetof(WeaponAttachmentUniqueFull, attachment.fireStopSoundPlayer), CSPFT_STRING}, - {"lastShotSound", offsetof(WeaponAttachmentUniqueFull, attachment.fireLastSound), CSPFT_STRING}, - {"lastShotSoundPlayer", offsetof(WeaponAttachmentUniqueFull, attachment.fireLastSoundPlayer), CSPFT_STRING}, - {"killcamStartFireSound", offsetof(WeaponAttachmentUniqueFull, attachment.fireKillcamSound), CSPFT_STRING}, - {"killcamStartFireSoundPlayer", offsetof(WeaponAttachmentUniqueFull, attachment.fireKillcamSoundPlayer), CSPFT_STRING}, - {"viewFlashEffect", offsetof(WeaponAttachmentUniqueFull, attachment.viewFlashEffect), CSPFT_FX}, - {"worldFlashEffect", offsetof(WeaponAttachmentUniqueFull, attachment.worldFlashEffect), CSPFT_FX}, - {"tracerType", offsetof(WeaponAttachmentUniqueFull, attachment.tracerType), CSPFT_TRACER}, - {"enemyTracerType", offsetof(WeaponAttachmentUniqueFull, attachment.enemyTracerType), CSPFT_TRACER}, - {"adsDofStart", offsetof(WeaponAttachmentUniqueFull, attachment.adsDofStart), CSPFT_FLOAT}, - {"adsDofEnd", offsetof(WeaponAttachmentUniqueFull, attachment.adsDofEnd), CSPFT_FLOAT}, - {"overrideLeftHandIK", offsetof(WeaponAttachmentUniqueFull, attachment.bOverrideLeftHandIK), CSPFT_BOOL}, - {"overrideLeftHandProneIK", offsetof(WeaponAttachmentUniqueFull, attachment.bOverrideLeftHandProneIK), CSPFT_BOOL}, - {"ikLeftHandOffsetF", offsetof(WeaponAttachmentUniqueFull, attachment.ikLeftHandOffset.x), CSPFT_FLOAT}, - {"ikLeftHandOffsetR", offsetof(WeaponAttachmentUniqueFull, attachment.ikLeftHandOffset.y), CSPFT_FLOAT}, - {"ikLeftHandOffsetU", offsetof(WeaponAttachmentUniqueFull, attachment.ikLeftHandOffset.z), CSPFT_FLOAT}, - {"ikLeftHandRotationP", offsetof(WeaponAttachmentUniqueFull, attachment.ikLeftHandRotation.x), CSPFT_FLOAT}, - {"ikLeftHandRotationY", offsetof(WeaponAttachmentUniqueFull, attachment.ikLeftHandRotation.y), CSPFT_FLOAT}, - {"ikLeftHandRotationR", offsetof(WeaponAttachmentUniqueFull, attachment.ikLeftHandRotation.z), CSPFT_FLOAT}, - {"ikLeftHandProneOffsetF", offsetof(WeaponAttachmentUniqueFull, attachment.ikLeftHandProneOffset.x), CSPFT_FLOAT}, - {"ikLeftHandProneOffsetR", offsetof(WeaponAttachmentUniqueFull, attachment.ikLeftHandProneOffset.y), CSPFT_FLOAT}, - {"ikLeftHandProneOffsetU", offsetof(WeaponAttachmentUniqueFull, attachment.ikLeftHandProneOffset.z), CSPFT_FLOAT}, - {"ikLeftHandProneRotationP", offsetof(WeaponAttachmentUniqueFull, attachment.ikLeftHandProneRotation.x), CSPFT_FLOAT}, - {"ikLeftHandProneRotationY", offsetof(WeaponAttachmentUniqueFull, attachment.ikLeftHandProneRotation.y), CSPFT_FLOAT}, - {"ikLeftHandProneRotationR", offsetof(WeaponAttachmentUniqueFull, attachment.ikLeftHandProneRotation.z), CSPFT_FLOAT}, - {"customFloat0", offsetof(WeaponAttachmentUniqueFull, attachment.customFloat0), CSPFT_FLOAT}, - {"customFloat1", offsetof(WeaponAttachmentUniqueFull, attachment.customFloat1), CSPFT_FLOAT}, - {"customFloat2", offsetof(WeaponAttachmentUniqueFull, attachment.customFloat2), CSPFT_FLOAT}, - {"customBool0", offsetof(WeaponAttachmentUniqueFull, attachment.customBool0), CSPFT_BOOL}, - {"customBool1", offsetof(WeaponAttachmentUniqueFull, attachment.customBool1), CSPFT_BOOL}, - {"customBool2", offsetof(WeaponAttachmentUniqueFull, attachment.customBool2), CSPFT_BOOL} - }; +namespace T6 { +inline cspField_t attachment_unique_fields[]{ + {"attachmentType", offsetof(WeaponAttachmentUniqueFull, attachment.attachmentType), AUFT_ATTACHMENTTYPE }, + {"locNone", offsetof(WeaponAttachmentUniqueFull, locationDamageMultipliers[HITLOC_NONE]), CSPFT_FLOAT }, + {"locHelmet", offsetof(WeaponAttachmentUniqueFull, locationDamageMultipliers[HITLOC_HELMET]), CSPFT_FLOAT }, + {"locHead", offsetof(WeaponAttachmentUniqueFull, locationDamageMultipliers[HITLOC_HEAD]), CSPFT_FLOAT }, + {"locNeck", offsetof(WeaponAttachmentUniqueFull, locationDamageMultipliers[HITLOC_NECK]), CSPFT_FLOAT }, + {"locTorsoUpper", offsetof(WeaponAttachmentUniqueFull, locationDamageMultipliers[HITLOC_TORSO_UPR]), CSPFT_FLOAT }, + {"locTorsoMid", offsetof(WeaponAttachmentUniqueFull, locationDamageMultipliers[HITLOC_TORSO_MID]), CSPFT_FLOAT }, + {"locTorsoLower", offsetof(WeaponAttachmentUniqueFull, locationDamageMultipliers[HITLOC_TORSO_LWR]), CSPFT_FLOAT }, + {"locRightArmUpper", offsetof(WeaponAttachmentUniqueFull, locationDamageMultipliers[HITLOC_R_ARM_UPR]), CSPFT_FLOAT }, + {"locRightArmLower", offsetof(WeaponAttachmentUniqueFull, locationDamageMultipliers[HITLOC_R_ARM_LWR]), CSPFT_FLOAT }, + {"locRightHand", offsetof(WeaponAttachmentUniqueFull, locationDamageMultipliers[HITLOC_R_HAND]), CSPFT_FLOAT }, + {"locLeftArmUpper", offsetof(WeaponAttachmentUniqueFull, locationDamageMultipliers[HITLOC_L_ARM_UPR]), CSPFT_FLOAT }, + {"locLeftArmLower", offsetof(WeaponAttachmentUniqueFull, locationDamageMultipliers[HITLOC_L_ARM_LWR]), CSPFT_FLOAT }, + {"locLeftHand", offsetof(WeaponAttachmentUniqueFull, locationDamageMultipliers[HITLOC_L_HAND]), CSPFT_FLOAT }, + {"locRightLegUpper", offsetof(WeaponAttachmentUniqueFull, locationDamageMultipliers[HITLOC_R_LEG_UPR]), CSPFT_FLOAT }, + {"locRightLegLower", offsetof(WeaponAttachmentUniqueFull, locationDamageMultipliers[HITLOC_R_LEG_LWR]), CSPFT_FLOAT }, + {"locRightFoot", offsetof(WeaponAttachmentUniqueFull, locationDamageMultipliers[HITLOC_R_FOOT]), CSPFT_FLOAT }, + {"locLeftLegUpper", offsetof(WeaponAttachmentUniqueFull, locationDamageMultipliers[HITLOC_L_LEG_UPR]), CSPFT_FLOAT }, + {"locLeftLegLower", offsetof(WeaponAttachmentUniqueFull, locationDamageMultipliers[HITLOC_L_LEG_LWR]), CSPFT_FLOAT }, + {"locLeftFoot", offsetof(WeaponAttachmentUniqueFull, locationDamageMultipliers[HITLOC_L_FOOT]), CSPFT_FLOAT }, + {"locGun", offsetof(WeaponAttachmentUniqueFull, locationDamageMultipliers[HITLOC_GUN]), CSPFT_FLOAT }, + {"viewModel", offsetof(WeaponAttachmentUniqueFull, attachment.viewModel), CSPFT_XMODEL }, + {"viewModelAdditional", offsetof(WeaponAttachmentUniqueFull, attachment.viewModelAdditional), CSPFT_XMODEL }, + {"viewModelADS", offsetof(WeaponAttachmentUniqueFull, attachment.viewModelADS), CSPFT_XMODEL }, + {"worldModel", offsetof(WeaponAttachmentUniqueFull, attachment.worldModel), CSPFT_XMODEL }, + {"worldModelAdditional", offsetof(WeaponAttachmentUniqueFull, attachment.worldModelAdditional), CSPFT_XMODEL }, + {"viewModelTag", offsetof(WeaponAttachmentUniqueFull, attachment.viewModelTag), CSPFT_STRING }, + {"worldModelTag", offsetof(WeaponAttachmentUniqueFull, attachment.worldModelTag), CSPFT_STRING }, + {"viewModelOffsetX", offsetof(WeaponAttachmentUniqueFull, attachment.viewModelOffsets.x), CSPFT_FLOAT }, + {"viewModelOffsetY", offsetof(WeaponAttachmentUniqueFull, attachment.viewModelOffsets.y), CSPFT_FLOAT }, + {"viewModelOffsetZ", offsetof(WeaponAttachmentUniqueFull, attachment.viewModelOffsets.z), CSPFT_FLOAT }, + {"viewModelOffsetPitch", offsetof(WeaponAttachmentUniqueFull, attachment.viewModelRotations.x), CSPFT_FLOAT }, + {"viewModelOffsetYaw", offsetof(WeaponAttachmentUniqueFull, attachment.viewModelRotations.y), CSPFT_FLOAT }, + {"viewModelOffsetRoll", offsetof(WeaponAttachmentUniqueFull, attachment.viewModelRotations.z), CSPFT_FLOAT }, + {"worldModelOffsetX", offsetof(WeaponAttachmentUniqueFull, attachment.worldModelOffsets.x), CSPFT_FLOAT }, + {"worldModelOffsetY", offsetof(WeaponAttachmentUniqueFull, attachment.worldModelOffsets.y), CSPFT_FLOAT }, + {"worldModelOffsetZ", offsetof(WeaponAttachmentUniqueFull, attachment.worldModelOffsets.z), CSPFT_FLOAT }, + {"worldModelOffsetPitch", offsetof(WeaponAttachmentUniqueFull, attachment.worldModelRotations.x), CSPFT_FLOAT }, + {"worldModelOffsetYaw", offsetof(WeaponAttachmentUniqueFull, attachment.worldModelRotations.y), CSPFT_FLOAT }, + {"worldModelOffsetRoll", offsetof(WeaponAttachmentUniqueFull, attachment.worldModelRotations.z), CSPFT_FLOAT }, + {"viewModelAddOffsetX", offsetof(WeaponAttachmentUniqueFull, attachment.viewModelAddOffsets.x), CSPFT_FLOAT }, + {"viewModelAddOffsetY", offsetof(WeaponAttachmentUniqueFull, attachment.viewModelAddOffsets.y), CSPFT_FLOAT }, + {"viewModelAddOffsetZ", offsetof(WeaponAttachmentUniqueFull, attachment.viewModelAddOffsets.z), CSPFT_FLOAT }, + {"viewModelAddOffsetPitch", offsetof(WeaponAttachmentUniqueFull, attachment.viewModelAddRotations.x), CSPFT_FLOAT }, + {"viewModelAddOffsetYaw", offsetof(WeaponAttachmentUniqueFull, attachment.viewModelAddRotations.y), CSPFT_FLOAT }, + {"viewModelAddOffsetRoll", offsetof(WeaponAttachmentUniqueFull, attachment.viewModelAddRotations.z), CSPFT_FLOAT }, + {"worldModelAddOffsetX", offsetof(WeaponAttachmentUniqueFull, attachment.worldModelAddOffsets.x), CSPFT_FLOAT }, + {"worldModelAddOffsetY", offsetof(WeaponAttachmentUniqueFull, attachment.worldModelAddOffsets.y), CSPFT_FLOAT }, + {"worldModelAddOffsetZ", offsetof(WeaponAttachmentUniqueFull, attachment.worldModelAddOffsets.z), CSPFT_FLOAT }, + {"worldModelAddOffsetPitch", offsetof(WeaponAttachmentUniqueFull, attachment.worldModelAddRotations.x), CSPFT_FLOAT }, + {"worldModelAddOffsetYaw", offsetof(WeaponAttachmentUniqueFull, attachment.worldModelAddRotations.y), CSPFT_FLOAT }, + {"worldModelAddOffsetRoll", offsetof(WeaponAttachmentUniqueFull, attachment.worldModelAddRotations.z), CSPFT_FLOAT }, + {"hideTags", offsetof(WeaponAttachmentUniqueFull, hideTags), AUFT_HIDETAGS }, + {"camo", offsetof(WeaponAttachmentUniqueFull, attachment.weaponCamo), AUFT_CAMO }, + {"disableBaseWeaponAttachment", offsetof(WeaponAttachmentUniqueFull, attachment.disableBaseWeaponAttachment), CSPFT_BOOL }, + {"disableBaseWeaponClip", offsetof(WeaponAttachmentUniqueFull, attachment.disableBaseWeaponClip), CSPFT_BOOL }, + {"overrideBaseWeaponAttachmentOffsets", offsetof(WeaponAttachmentUniqueFull, attachment.overrideBaseWeaponAttachmentOffsets), CSPFT_BOOL }, + {"viewModelOffsetBaseAttachmentX", offsetof(WeaponAttachmentUniqueFull, attachment.viewModelOffsetBaseAttachment.x), CSPFT_FLOAT }, + {"viewModelOffsetBaseAttachmentY", offsetof(WeaponAttachmentUniqueFull, attachment.viewModelOffsetBaseAttachment.y), CSPFT_FLOAT }, + {"viewModelOffsetBaseAttachmentZ", offsetof(WeaponAttachmentUniqueFull, attachment.viewModelOffsetBaseAttachment.z), CSPFT_FLOAT }, + {"worldModelOffsetBaseAttachmentX", offsetof(WeaponAttachmentUniqueFull, attachment.worldModelOffsetBaseAttachment.x), CSPFT_FLOAT }, + {"worldModelOffsetBaseAttachmentY", offsetof(WeaponAttachmentUniqueFull, attachment.worldModelOffsetBaseAttachment.y), CSPFT_FLOAT }, + {"worldModelOffsetBaseAttachmentZ", offsetof(WeaponAttachmentUniqueFull, attachment.worldModelOffsetBaseAttachment.z), CSPFT_FLOAT }, + {"altWeapon", offsetof(WeaponAttachmentUniqueFull, attachment.szAltWeaponName), CSPFT_STRING }, + {"DualWieldWeapon", offsetof(WeaponAttachmentUniqueFull, attachment.szDualWieldWeaponName), CSPFT_STRING }, + {"adsOverlayShader", offsetof(WeaponAttachmentUniqueFull, attachment.overlayMaterial), CSPFT_MATERIAL_STREAM}, + {"adsOverlayShaderLowRes", offsetof(WeaponAttachmentUniqueFull, attachment.overlayMaterialLowRes), CSPFT_MATERIAL_STREAM}, + {"adsOverlayReticle", offsetof(WeaponAttachmentUniqueFull, attachment.overlayReticle), AUFT_OVERLAYRETICLE }, + {"firstRaiseTime", offsetof(WeaponAttachmentUniqueFull, attachment.iFirstRaiseTime), CSPFT_MILLISECONDS }, + {"altRaiseTime", offsetof(WeaponAttachmentUniqueFull, attachment.iAltRaiseTime), CSPFT_MILLISECONDS }, + {"altDropTime", offsetof(WeaponAttachmentUniqueFull, attachment.iAltDropTime), CSPFT_MILLISECONDS }, + {"reloadAmmoAdd", offsetof(WeaponAttachmentUniqueFull, attachment.iReloadAmmoAdd), CSPFT_INT }, + {"reloadStartAdd", offsetof(WeaponAttachmentUniqueFull, attachment.iReloadStartAdd), CSPFT_INT }, + {"segmentedReload", offsetof(WeaponAttachmentUniqueFull, attachment.bSegmentedReload), CSPFT_BOOL }, + {"idleAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_IDLE]), CSPFT_STRING }, + {"idleAnimLeft", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_IDLE_LEFT]), CSPFT_STRING }, + {"emptyIdleAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_EMPTY_IDLE]), CSPFT_STRING }, + {"emptyIdleAnimLeft", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_EMPTY_IDLE_LEFT]), CSPFT_STRING }, + {"fireIntroAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_FIRE_INTRO]), CSPFT_STRING }, + {"fireAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_FIRE]), CSPFT_STRING }, + {"fireAnimLeft", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_FIRE_LEFT]), CSPFT_STRING }, + {"holdFireAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_HOLD_FIRE]), CSPFT_STRING }, + {"lastShotAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_LASTSHOT]), CSPFT_STRING }, + {"lastShotAnimLeft", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_LASTSHOT_LEFT]), CSPFT_STRING }, + {"flourishAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_FINALSHOT]), CSPFT_STRING }, + {"flourishAnimLeft", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_FINALSHOT_LEFT]), CSPFT_STRING }, + {"detonateAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_DETONATE]), CSPFT_STRING }, + {"rechamberAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_RECHAMBER]), CSPFT_STRING }, + {"meleeAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_MELEE]), CSPFT_STRING }, + {"meleeAnimEmpty", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_MELEE_EMPTY]), CSPFT_STRING }, + {"meleeAnim1", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_MELEE1]), CSPFT_STRING }, + {"meleeAnim2", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_MELEE2]), CSPFT_STRING }, + {"meleeAnim3", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_MELEE3]), CSPFT_STRING }, + {"meleeChargeAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_MELEE_CHARGE]), CSPFT_STRING }, + {"meleeChargeAnimEmpty", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_MELEE_CHARGE_EMPTY]), CSPFT_STRING }, + {"reloadAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_RELOAD]), CSPFT_STRING }, + {"reloadAnimRight", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_RELOAD_RIGHT]), CSPFT_STRING }, + {"reloadAnimLeft", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_RELOAD_LEFT]), CSPFT_STRING }, + {"reloadEmptyAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_RELOAD_EMPTY]), CSPFT_STRING }, + {"reloadEmptyAnimLeft", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_RELOAD_EMPTY_LEFT]), CSPFT_STRING }, + {"reloadStartAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_RELOAD_START]), CSPFT_STRING }, + {"reloadEndAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_RELOAD_END]), CSPFT_STRING }, + {"reloadQuickAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_RELOAD_QUICK]), CSPFT_STRING }, + {"reloadQuickEmptyAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_RELOAD_QUICK_EMPTY]), CSPFT_STRING }, + {"raiseAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_RAISE]), CSPFT_STRING }, + {"dropAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_DROP]), CSPFT_STRING }, + {"firstRaiseAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_FIRST_RAISE]), CSPFT_STRING }, + {"altRaiseAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_ALT_RAISE]), CSPFT_STRING }, + {"altDropAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_ALT_DROP]), CSPFT_STRING }, + {"quickRaiseAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_QUICK_RAISE]), CSPFT_STRING }, + {"quickDropAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_QUICK_DROP]), CSPFT_STRING }, + {"emptyRaiseAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_EMPTY_RAISE]), CSPFT_STRING }, + {"emptyDropAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_EMPTY_DROP]), CSPFT_STRING }, + {"sprintInAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_SPRINT_IN]), CSPFT_STRING }, + {"sprintLoopAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_SPRINT_LOOP]), CSPFT_STRING }, + {"sprintOutAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_SPRINT_OUT]), CSPFT_STRING }, + {"sprintInEmptyAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_SPRINT_EMPTY_IN]), CSPFT_STRING }, + {"sprintLoopEmptyAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_SPRINT_EMPTY_LOOP]), CSPFT_STRING }, + {"sprintOutEmptyAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_SPRINT_EMPTY_OUT]), CSPFT_STRING }, + {"lowReadyInAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_LOWREADY_IN]), CSPFT_STRING }, + {"lowReadyLoopAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_LOWREADY_LOOP]), CSPFT_STRING }, + {"lowReadyOutAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_LOWREADY_OUT]), CSPFT_STRING }, + {"contFireInAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_CONT_FIRE_IN]), CSPFT_STRING }, + {"contFireLoopAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_CONT_FIRE_LOOP]), CSPFT_STRING }, + {"contFireOutAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_CONT_FIRE_OUT]), CSPFT_STRING }, + {"crawlInAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_CRAWL_IN]), CSPFT_STRING }, + {"crawlForwardAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_CRAWL_FORWARD]), CSPFT_STRING }, + {"crawlBackAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_CRAWL_BACK]), CSPFT_STRING }, + {"crawlRightAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_CRAWL_RIGHT]), CSPFT_STRING }, + {"crawlLeftAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_CRAWL_LEFT]), CSPFT_STRING }, + {"crawlOutAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_CRAWL_OUT]), CSPFT_STRING }, + {"crawlEmptyInAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_CRAWL_EMPTY_IN]), CSPFT_STRING }, + {"crawlEmptyForwardAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_CRAWL_EMPTY_FORWARD]), CSPFT_STRING }, + {"crawlEmptyBackAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_CRAWL_EMPTY_BACK]), CSPFT_STRING }, + {"crawlEmptyRightAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_CRAWL_EMPTY_RIGHT]), CSPFT_STRING }, + {"crawlEmptyLeftAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_CRAWL_EMPTY_LEFT]), CSPFT_STRING }, + {"crawlEmptyOutAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_CRAWL_EMPTY_OUT]), CSPFT_STRING }, + {"deployAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_DEPLOY]), CSPFT_STRING }, + {"breakdownAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_BREAKDOWN]), CSPFT_STRING }, + {"nightVisionWearAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_NIGHTVISION_WEAR]), CSPFT_STRING }, + {"nightVisionRemoveAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_NIGHTVISION_REMOVE]), CSPFT_STRING }, + {"adsFireAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_ADS_FIRE]), CSPFT_STRING }, + {"adsLastShotAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_ADS_LASTSHOT]), CSPFT_STRING }, + {"adsRechamberAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_ADS_RECHAMBER]), CSPFT_STRING }, + {"adsUpAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_ADS_UP]), CSPFT_STRING }, + {"adsDownAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_ADS_DOWN]), CSPFT_STRING }, + {"adsUpOtherScopeAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_ADS_UP_OTHER_SCOPE]), CSPFT_STRING }, + {"adsFireIntroAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_ADS_FIRE_INTRO]), CSPFT_STRING }, + {"dtp_in", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_DTP_IN]), CSPFT_STRING }, + {"dtp_loop", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_DTP_LOOP]), CSPFT_STRING }, + {"dtp_out", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_DTP_OUT]), CSPFT_STRING }, + {"dtp_empty_in", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_DTP_EMPTY_IN]), CSPFT_STRING }, + {"dtp_empty_loop", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_DTP_EMPTY_LOOP]), CSPFT_STRING }, + {"dtp_empty_out", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_DTP_EMPTY_OUT]), CSPFT_STRING }, + {"slide_in", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_SLIDE_IN]), CSPFT_STRING }, + {"mantleAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_MANTLE]), CSPFT_STRING }, + {"sprintCameraAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_CAMERA_SPRINT_LOOP]), CSPFT_STRING }, + {"dtpInCameraAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_CAMERA_DTP_IN]), CSPFT_STRING }, + {"dtpLoopCameraAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_CAMERA_DTP_LOOP]), CSPFT_STRING }, + {"dtpOutCameraAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_CAMERA_DTP_OUT]), CSPFT_STRING }, + {"mantleCameraAnim", offsetof(WeaponAttachmentUniqueFull, szXAnims[WEAP_ANIM_CAMERA_MANTLE]), CSPFT_STRING }, + {"fireSound", offsetof(WeaponAttachmentUniqueFull, attachment.fireSound), CSPFT_STRING }, + {"fireSoundPlayer", offsetof(WeaponAttachmentUniqueFull, attachment.fireSoundPlayer), CSPFT_STRING }, + {"loopFireSound", offsetof(WeaponAttachmentUniqueFull, attachment.fireLoopSound), CSPFT_STRING }, + {"loopFireSoundPlayer", offsetof(WeaponAttachmentUniqueFull, attachment.fireLoopSoundPlayer), CSPFT_STRING }, + {"loopFireEndSound", offsetof(WeaponAttachmentUniqueFull, attachment.fireLoopEndSound), CSPFT_STRING }, + {"loopFireEndSoundPlayer", offsetof(WeaponAttachmentUniqueFull, attachment.fireLoopEndSoundPlayer), CSPFT_STRING }, + {"startFireSound", offsetof(WeaponAttachmentUniqueFull, attachment.fireStartSound), CSPFT_STRING }, + {"stopFireSound", offsetof(WeaponAttachmentUniqueFull, attachment.fireStopSound), CSPFT_STRING }, + {"startFireSoundPlayer", offsetof(WeaponAttachmentUniqueFull, attachment.fireStartSoundPlayer), CSPFT_STRING }, + {"stopFireSoundPlayer", offsetof(WeaponAttachmentUniqueFull, attachment.fireStopSoundPlayer), CSPFT_STRING }, + {"lastShotSound", offsetof(WeaponAttachmentUniqueFull, attachment.fireLastSound), CSPFT_STRING }, + {"lastShotSoundPlayer", offsetof(WeaponAttachmentUniqueFull, attachment.fireLastSoundPlayer), CSPFT_STRING }, + {"killcamStartFireSound", offsetof(WeaponAttachmentUniqueFull, attachment.fireKillcamSound), CSPFT_STRING }, + {"killcamStartFireSoundPlayer", offsetof(WeaponAttachmentUniqueFull, attachment.fireKillcamSoundPlayer), CSPFT_STRING }, + {"viewFlashEffect", offsetof(WeaponAttachmentUniqueFull, attachment.viewFlashEffect), CSPFT_FX }, + {"worldFlashEffect", offsetof(WeaponAttachmentUniqueFull, attachment.worldFlashEffect), CSPFT_FX }, + {"tracerType", offsetof(WeaponAttachmentUniqueFull, attachment.tracerType), CSPFT_TRACER }, + {"enemyTracerType", offsetof(WeaponAttachmentUniqueFull, attachment.enemyTracerType), CSPFT_TRACER }, + {"adsDofStart", offsetof(WeaponAttachmentUniqueFull, attachment.adsDofStart), CSPFT_FLOAT }, + {"adsDofEnd", offsetof(WeaponAttachmentUniqueFull, attachment.adsDofEnd), CSPFT_FLOAT }, + {"overrideLeftHandIK", offsetof(WeaponAttachmentUniqueFull, attachment.bOverrideLeftHandIK), CSPFT_BOOL }, + {"overrideLeftHandProneIK", offsetof(WeaponAttachmentUniqueFull, attachment.bOverrideLeftHandProneIK), CSPFT_BOOL }, + {"ikLeftHandOffsetF", offsetof(WeaponAttachmentUniqueFull, attachment.ikLeftHandOffset.x), CSPFT_FLOAT }, + {"ikLeftHandOffsetR", offsetof(WeaponAttachmentUniqueFull, attachment.ikLeftHandOffset.y), CSPFT_FLOAT }, + {"ikLeftHandOffsetU", offsetof(WeaponAttachmentUniqueFull, attachment.ikLeftHandOffset.z), CSPFT_FLOAT }, + {"ikLeftHandRotationP", offsetof(WeaponAttachmentUniqueFull, attachment.ikLeftHandRotation.x), CSPFT_FLOAT }, + {"ikLeftHandRotationY", offsetof(WeaponAttachmentUniqueFull, attachment.ikLeftHandRotation.y), CSPFT_FLOAT }, + {"ikLeftHandRotationR", offsetof(WeaponAttachmentUniqueFull, attachment.ikLeftHandRotation.z), CSPFT_FLOAT }, + {"ikLeftHandProneOffsetF", offsetof(WeaponAttachmentUniqueFull, attachment.ikLeftHandProneOffset.x), CSPFT_FLOAT }, + {"ikLeftHandProneOffsetR", offsetof(WeaponAttachmentUniqueFull, attachment.ikLeftHandProneOffset.y), CSPFT_FLOAT }, + {"ikLeftHandProneOffsetU", offsetof(WeaponAttachmentUniqueFull, attachment.ikLeftHandProneOffset.z), CSPFT_FLOAT }, + {"ikLeftHandProneRotationP", offsetof(WeaponAttachmentUniqueFull, attachment.ikLeftHandProneRotation.x), CSPFT_FLOAT }, + {"ikLeftHandProneRotationY", offsetof(WeaponAttachmentUniqueFull, attachment.ikLeftHandProneRotation.y), CSPFT_FLOAT }, + {"ikLeftHandProneRotationR", offsetof(WeaponAttachmentUniqueFull, attachment.ikLeftHandProneRotation.z), CSPFT_FLOAT }, + {"customFloat0", offsetof(WeaponAttachmentUniqueFull, attachment.customFloat0), CSPFT_FLOAT }, + {"customFloat1", offsetof(WeaponAttachmentUniqueFull, attachment.customFloat1), CSPFT_FLOAT }, + {"customFloat2", offsetof(WeaponAttachmentUniqueFull, attachment.customFloat2), CSPFT_FLOAT }, + {"customBool0", offsetof(WeaponAttachmentUniqueFull, attachment.customBool0), CSPFT_BOOL }, + {"customBool1", offsetof(WeaponAttachmentUniqueFull, attachment.customBool1), CSPFT_BOOL }, + {"customBool2", offsetof(WeaponAttachmentUniqueFull, attachment.customBool2), CSPFT_BOOL } +}; } \ No newline at end of file diff --git a/src/ObjCommon/Game/T6/InfoString/WeaponFields.h b/src/ObjCommon/Game/T6/InfoString/WeaponFields.h index 4bff9ac37..bf5c508df 100644 --- a/src/ObjCommon/Game/T6/InfoString/WeaponFields.h +++ b/src/ObjCommon/Game/T6/InfoString/WeaponFields.h @@ -1,1037 +1,1035 @@ #pragma once #include "Game/T6/T6.h" -namespace T6 -{ - inline cspField_t weapon_fields[] - { - {"displayName", offsetof(WeaponFullDef, weapVariantDef.szDisplayName), CSPFT_STRING}, - {"AIOverlayDescription", offsetof(WeaponFullDef, weapDef.szOverlayName), CSPFT_STRING}, - {"modeName", offsetof(WeaponFullDef, weapDef.szModeName), CSPFT_STRING}, - {"playerAnimType", offsetof(WeaponFullDef, weapDef.playerAnimType), WFT_ANIMTYPE}, - {"gunModel", offsetof(WeaponFullDef, gunXModel[0]), CSPFT_XMODEL}, - {"gunModel2", offsetof(WeaponFullDef, gunXModel[1]), CSPFT_XMODEL}, - {"gunModel3", offsetof(WeaponFullDef, gunXModel[2]), CSPFT_XMODEL}, - {"gunModel4", offsetof(WeaponFullDef, gunXModel[3]), CSPFT_XMODEL}, - {"gunModel5", offsetof(WeaponFullDef, gunXModel[4]), CSPFT_XMODEL}, - {"gunModel6", offsetof(WeaponFullDef, gunXModel[5]), CSPFT_XMODEL}, - {"gunModel7", offsetof(WeaponFullDef, gunXModel[6]), CSPFT_XMODEL}, - {"gunModel8", offsetof(WeaponFullDef, gunXModel[7]), CSPFT_XMODEL}, - {"gunModel9", offsetof(WeaponFullDef, gunXModel[8]), CSPFT_XMODEL}, - {"gunModel10", offsetof(WeaponFullDef, gunXModel[9]), CSPFT_XMODEL}, - {"gunModel11", offsetof(WeaponFullDef, gunXModel[10]), CSPFT_XMODEL}, - {"gunModel12", offsetof(WeaponFullDef, gunXModel[11]), CSPFT_XMODEL}, - {"gunModel13", offsetof(WeaponFullDef, gunXModel[12]), CSPFT_XMODEL}, - {"gunModel14", offsetof(WeaponFullDef, gunXModel[13]), CSPFT_XMODEL}, - {"gunModel15", offsetof(WeaponFullDef, gunXModel[14]), CSPFT_XMODEL}, - {"gunModel16", offsetof(WeaponFullDef, gunXModel[15]), CSPFT_XMODEL}, - {"handModel", offsetof(WeaponFullDef, weapDef.handXModel), CSPFT_XMODEL}, - {"hideTags", offsetof(WeaponFullDef, hideTags), WFT_HIDETAGS}, - {"notetrackSoundMap", offsetof(WeaponFullDef, notetrackSoundMapKeys), WFT_NOTETRACKSOUNDMAP}, - {"idleAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_IDLE]), CSPFT_STRING}, - {"idleAnimLeft", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_IDLE_LEFT]), CSPFT_STRING}, - {"emptyIdleAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_EMPTY_IDLE]), CSPFT_STRING}, - {"emptyIdleAnimLeft", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_EMPTY_IDLE_LEFT]), CSPFT_STRING}, - {"fireIntroAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_FIRE_INTRO]), CSPFT_STRING}, - {"fireAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_FIRE]), CSPFT_STRING}, - {"fireAnimLeft", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_FIRE_LEFT]), CSPFT_STRING}, - {"holdFireAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_HOLD_FIRE]), CSPFT_STRING}, - {"lastShotAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_LASTSHOT]), CSPFT_STRING}, - {"lastShotAnimLeft", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_LASTSHOT_LEFT]), CSPFT_STRING}, - {"flourishAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_FINALSHOT]), CSPFT_STRING}, - {"flourishAnimLeft", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_FINALSHOT_LEFT]), CSPFT_STRING}, - {"detonateAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_DETONATE]), CSPFT_STRING}, - {"rechamberAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_RECHAMBER]), CSPFT_STRING}, - {"meleeAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_MELEE]), CSPFT_STRING}, - {"meleeAnimEmpty", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_MELEE_EMPTY]), CSPFT_STRING}, - {"meleeAnim1", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_MELEE1]), CSPFT_STRING}, - {"meleeAnim2", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_MELEE2]), CSPFT_STRING}, - {"meleeAnim3", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_MELEE3]), CSPFT_STRING}, - {"meleeChargeAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_MELEE_CHARGE]), CSPFT_STRING}, - {"meleeChargeAnimEmpty", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_MELEE_CHARGE_EMPTY]), CSPFT_STRING}, - {"reloadAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_RELOAD]), CSPFT_STRING}, - {"reloadAnimRight", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_RELOAD_RIGHT]), CSPFT_STRING}, - {"reloadAnimLeft", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_RELOAD_LEFT]), CSPFT_STRING}, - {"reloadEmptyAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_RELOAD_EMPTY]), CSPFT_STRING}, - {"reloadEmptyAnimLeft", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_RELOAD_EMPTY_LEFT]), CSPFT_STRING}, - {"reloadStartAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_RELOAD_START]), CSPFT_STRING}, - {"reloadEndAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_RELOAD_END]), CSPFT_STRING}, - {"reloadQuickAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_RELOAD_QUICK]), CSPFT_STRING}, - {"reloadQuickEmptyAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_RELOAD_QUICK_EMPTY]), CSPFT_STRING}, - {"raiseAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_RAISE]), CSPFT_STRING}, - {"dropAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_DROP]), CSPFT_STRING}, - {"firstRaiseAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_FIRST_RAISE]), CSPFT_STRING}, - {"altRaiseAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_ALT_RAISE]), CSPFT_STRING}, - {"altDropAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_ALT_DROP]), CSPFT_STRING}, - {"quickRaiseAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_QUICK_RAISE]), CSPFT_STRING}, - {"quickDropAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_QUICK_DROP]), CSPFT_STRING}, - {"emptyRaiseAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_EMPTY_RAISE]), CSPFT_STRING}, - {"emptyDropAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_EMPTY_DROP]), CSPFT_STRING}, - {"sprintInAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_SPRINT_IN]), CSPFT_STRING}, - {"sprintLoopAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_SPRINT_LOOP]), CSPFT_STRING}, - {"sprintOutAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_SPRINT_OUT]), CSPFT_STRING}, - {"sprintInEmptyAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_SPRINT_EMPTY_IN]), CSPFT_STRING}, - {"sprintLoopEmptyAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_SPRINT_EMPTY_LOOP]), CSPFT_STRING}, - {"sprintOutEmptyAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_SPRINT_EMPTY_OUT]), CSPFT_STRING}, - {"lowReadyInAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_LOWREADY_IN]), CSPFT_STRING}, - {"lowReadyLoopAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_LOWREADY_LOOP]), CSPFT_STRING}, - {"lowReadyOutAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_LOWREADY_OUT]), CSPFT_STRING}, - {"contFireInAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_CONT_FIRE_IN]), CSPFT_STRING}, - {"contFireLoopAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_CONT_FIRE_LOOP]), CSPFT_STRING}, - {"contFireOutAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_CONT_FIRE_OUT]), CSPFT_STRING}, - {"crawlInAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_CRAWL_IN]), CSPFT_STRING}, - {"crawlForwardAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_CRAWL_FORWARD]), CSPFT_STRING}, - {"crawlBackAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_CRAWL_BACK]), CSPFT_STRING}, - {"crawlRightAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_CRAWL_RIGHT]), CSPFT_STRING}, - {"crawlLeftAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_CRAWL_LEFT]), CSPFT_STRING}, - {"crawlOutAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_CRAWL_OUT]), CSPFT_STRING}, - {"crawlEmptyInAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_CRAWL_EMPTY_IN]), CSPFT_STRING}, - {"crawlEmptyForwardAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_CRAWL_EMPTY_FORWARD]), CSPFT_STRING}, - {"crawlEmptyBackAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_CRAWL_EMPTY_BACK]), CSPFT_STRING}, - {"crawlEmptyRightAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_CRAWL_EMPTY_RIGHT]), CSPFT_STRING}, - {"crawlEmptyLeftAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_CRAWL_EMPTY_LEFT]), CSPFT_STRING}, - {"crawlEmptyOutAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_CRAWL_EMPTY_OUT]), CSPFT_STRING}, - {"deployAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_DEPLOY]), CSPFT_STRING}, - {"nightVisionWearAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_NIGHTVISION_WEAR]), CSPFT_STRING}, - {"nightVisionRemoveAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_NIGHTVISION_REMOVE]), CSPFT_STRING}, - {"adsFireAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_ADS_FIRE]), CSPFT_STRING}, - {"adsLastShotAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_ADS_LASTSHOT]), CSPFT_STRING}, - {"adsRechamberAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_ADS_RECHAMBER]), CSPFT_STRING}, - {"adsUpAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_ADS_UP]), CSPFT_STRING}, - {"adsDownAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_ADS_DOWN]), CSPFT_STRING}, - {"adsUpOtherScopeAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_ADS_UP_OTHER_SCOPE]), CSPFT_STRING}, - {"adsFireIntroAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_ADS_FIRE_INTRO]), CSPFT_STRING}, - {"breakdownAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_BREAKDOWN]), CSPFT_STRING}, - {"dtp_in", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_DTP_IN]), CSPFT_STRING}, - {"dtp_loop", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_DTP_LOOP]), CSPFT_STRING}, - {"dtp_out", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_DTP_OUT]), CSPFT_STRING}, - {"dtp_empty_in", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_DTP_EMPTY_IN]), CSPFT_STRING}, - {"dtp_empty_loop", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_DTP_EMPTY_LOOP]), CSPFT_STRING}, - {"dtp_empty_out", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_DTP_EMPTY_OUT]), CSPFT_STRING}, - {"slide_in", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_SLIDE_IN]), CSPFT_STRING}, - {"mantleAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_MANTLE]), CSPFT_STRING}, - {"sprintCameraAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_CAMERA_SPRINT_LOOP]), CSPFT_STRING}, - {"dtpInCameraAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_CAMERA_DTP_IN]), CSPFT_STRING}, - {"dtpLoopCameraAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_CAMERA_DTP_LOOP]), CSPFT_STRING}, - {"dtpOutCameraAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_CAMERA_DTP_OUT]), CSPFT_STRING}, - {"mantleCameraAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_CAMERA_MANTLE]), CSPFT_STRING}, - {"script", offsetof(WeaponFullDef, weapDef.szScript), CSPFT_STRING}, - {"weaponType", offsetof(WeaponFullDef, weapDef.weapType), WFT_WEAPONTYPE}, - {"weaponClass", offsetof(WeaponFullDef, weapDef.weapClass), WFT_WEAPONCLASS}, - {"penetrateType", offsetof(WeaponFullDef, weapDef.penetrateTWeaponAttachmentype), WFT_PENETRATE_TYPE}, - {"impactType", offsetof(WeaponFullDef, weapDef.impactType), WFT_IMPACT_TYPE}, - {"inventoryType", offsetof(WeaponFullDef, weapDef.inventoryType), WFT_INVENTORYTYPE}, - {"fireType", offsetof(WeaponFullDef, weapDef.fireType), WFT_FIRETYPE}, - {"clipType", offsetof(WeaponFullDef, weapDef.clipType), WFT_CLIPTYPE}, - {"barrelType", offsetof(WeaponFullDef, weapDef.barrelType), WFT_BARRELTYPE}, - {"offhandClass", offsetof(WeaponFullDef, weapDef.offhandClass), WFT_OFFHAND_CLASS}, - {"offhandSlot", offsetof(WeaponFullDef, weapDef.offhandSlot), WFT_OFFHAND_SLOT}, - {"viewFlashEffect", offsetof(WeaponFullDef, weapDef.viewFlashEffect), CSPFT_FX}, - {"worldFlashEffect", offsetof(WeaponFullDef, weapDef.worldFlashEffect), CSPFT_FX}, - {"barrelCooldownEffect", offsetof(WeaponFullDef, weapDef.barrelCooldownEffect), CSPFT_FX}, - {"barrelCooldownMinCount", offsetof(WeaponFullDef, weapDef.barrelCooldownMinCount), CSPFT_INT}, - {"viewFlashOffsetF", offsetof(WeaponFullDef, weapDef.vViewFlashOffset.x), CSPFT_FLOAT}, - {"viewFlashOffsetR", offsetof(WeaponFullDef, weapDef.vViewFlashOffset.y), CSPFT_FLOAT}, - {"viewFlashOffsetU", offsetof(WeaponFullDef, weapDef.vViewFlashOffset.z), CSPFT_FLOAT}, - {"worldFlashOffsetF", offsetof(WeaponFullDef, weapDef.vWorldFlashOffset.x), CSPFT_FLOAT}, - {"worldFlashOffsetR", offsetof(WeaponFullDef, weapDef.vWorldFlashOffset.y), CSPFT_FLOAT}, - {"worldFlashOffsetU", offsetof(WeaponFullDef, weapDef.vWorldFlashOffset.z), CSPFT_FLOAT}, - {"pickupSound", offsetof(WeaponFullDef, weapDef.pickupSound), CSPFT_STRING}, - {"pickupSoundPlayer", offsetof(WeaponFullDef, weapDef.pickupSoundPlayer), CSPFT_STRING}, - {"ammoPickupSound", offsetof(WeaponFullDef, weapDef.ammoPickupSound), CSPFT_STRING}, - {"ammoPickupSoundPlayer", offsetof(WeaponFullDef, weapDef.ammoPickupSoundPlayer), CSPFT_STRING}, - {"projectileSound", offsetof(WeaponFullDef, weapDef.projectileSound), CSPFT_STRING}, - {"pullbackSound", offsetof(WeaponFullDef, weapDef.pullbackSound), CSPFT_STRING}, - {"pullbackSoundPlayer", offsetof(WeaponFullDef, weapDef.pullbackSoundPlayer), CSPFT_STRING}, - {"fireSound", offsetof(WeaponFullDef, weapDef.fireSound), CSPFT_STRING}, - {"crackSound", offsetof(WeaponFullDef, weapDef.crackSound), CSPFT_STRING}, - {"whizbySound", offsetof(WeaponFullDef, weapDef.whizbySound), CSPFT_STRING}, - {"fireSoundPlayer", offsetof(WeaponFullDef, weapDef.fireSoundPlayer), CSPFT_STRING}, - {"loopFireSound", offsetof(WeaponFullDef, weapDef.fireLoopSound), CSPFT_STRING}, - {"loopFireSoundPlayer", offsetof(WeaponFullDef, weapDef.fireLoopSoundPlayer), CSPFT_STRING}, - {"loopFireEndSound", offsetof(WeaponFullDef, weapDef.fireLoopEndSound), CSPFT_STRING}, - {"loopFireEndSoundPlayer", offsetof(WeaponFullDef, weapDef.fireLoopEndSoundPlayer), CSPFT_STRING}, - {"startFireSound", offsetof(WeaponFullDef, weapDef.fireStartSound), CSPFT_STRING}, - {"stopFireSound", offsetof(WeaponFullDef, weapDef.fireStopSound), CSPFT_STRING}, - {"killcamStartFireSound", offsetof(WeaponFullDef, weapDef.fireKillcamSound), CSPFT_STRING}, - {"startFireSoundPlayer", offsetof(WeaponFullDef, weapDef.fireStartSoundPlayer), CSPFT_STRING}, - {"stopFireSoundPlayer", offsetof(WeaponFullDef, weapDef.fireStopSoundPlayer), CSPFT_STRING}, - {"killcamStartFireSoundPlayer", offsetof(WeaponFullDef, weapDef.fireKillcamSoundPlayer), CSPFT_STRING}, - {"lastShotSound", offsetof(WeaponFullDef, weapDef.fireLastSound), CSPFT_STRING}, - {"lastShotSoundPlayer", offsetof(WeaponFullDef, weapDef.fireLastSoundPlayer), CSPFT_STRING}, - {"emptyFireSound", offsetof(WeaponFullDef, weapDef.emptyFireSound), CSPFT_STRING}, - {"emptyFireSoundPlayer", offsetof(WeaponFullDef, weapDef.emptyFireSoundPlayer), CSPFT_STRING}, - {"meleeSwipeSound", offsetof(WeaponFullDef, weapDef.meleeSwipeSound), CSPFT_STRING}, - {"meleeSwipeSoundPlayer", offsetof(WeaponFullDef, weapDef.meleeSwipeSoundPlayer), CSPFT_STRING}, - {"meleeHitSound", offsetof(WeaponFullDef, weapDef.meleeHitSound), CSPFT_STRING}, - {"meleeMissSound", offsetof(WeaponFullDef, weapDef.meleeMissSound), CSPFT_STRING}, - {"rechamberSound", offsetof(WeaponFullDef, weapDef.rechamberSound), CSPFT_STRING}, - {"rechamberSoundPlayer", offsetof(WeaponFullDef, weapDef.rechamberSoundPlayer), CSPFT_STRING}, - {"reloadSound", offsetof(WeaponFullDef, weapDef.reloadSound), CSPFT_STRING}, - {"reloadSoundPlayer", offsetof(WeaponFullDef, weapDef.reloadSoundPlayer), CSPFT_STRING}, - {"reloadEmptySound", offsetof(WeaponFullDef, weapDef.reloadEmptySound), CSPFT_STRING}, - {"reloadEmptySoundPlayer", offsetof(WeaponFullDef, weapDef.reloadEmptySoundPlayer), CSPFT_STRING}, - {"reloadStartSound", offsetof(WeaponFullDef, weapDef.reloadStartSound), CSPFT_STRING}, - {"reloadStartSoundPlayer", offsetof(WeaponFullDef, weapDef.reloadStartSoundPlayer), CSPFT_STRING}, - {"reloadEndSound", offsetof(WeaponFullDef, weapDef.reloadEndSound), CSPFT_STRING}, - {"reloadEndSoundPlayer", offsetof(WeaponFullDef, weapDef.reloadEndSoundPlayer), CSPFT_STRING}, - {"rotateLoopSound", offsetof(WeaponFullDef, weapDef.rotateLoopSound), CSPFT_STRING}, - {"rotateLoopSoundPlayer", offsetof(WeaponFullDef, weapDef.rotateLoopSoundPlayer), CSPFT_STRING}, - {"rotateStopSound", offsetof(WeaponFullDef, weapDef.rotateStopSound), CSPFT_STRING}, - {"rotateStopSoundPlayer", offsetof(WeaponFullDef, weapDef.rotateStopSoundPlayer), CSPFT_STRING}, - {"deploySound", offsetof(WeaponFullDef, weapDef.deploySound), CSPFT_STRING}, - {"deploySoundPlayer", offsetof(WeaponFullDef, weapDef.deploySoundPlayer), CSPFT_STRING}, - {"finishDeploySound", offsetof(WeaponFullDef, weapDef.finishDeploySound), CSPFT_STRING}, - {"finishDeploySoundPlayer", offsetof(WeaponFullDef, weapDef.finishDeploySoundPlayer), CSPFT_STRING}, - {"breakdownSound", offsetof(WeaponFullDef, weapDef.breakdownSound), CSPFT_STRING}, - {"breakdownSoundPlayer", offsetof(WeaponFullDef, weapDef.breakdownSoundPlayer), CSPFT_STRING}, - {"finishBreakdownSound", offsetof(WeaponFullDef, weapDef.finishBreakdownSound), CSPFT_STRING}, - {"finishBreakdownSoundPlayer", offsetof(WeaponFullDef, weapDef.finishBreakdownSoundPlayer), CSPFT_STRING}, - {"detonateSound", offsetof(WeaponFullDef, weapDef.detonateSound), CSPFT_STRING}, - {"detonateSoundPlayer", offsetof(WeaponFullDef, weapDef.detonateSoundPlayer), CSPFT_STRING}, - {"nightVisionWearSound", offsetof(WeaponFullDef, weapDef.nightVisionWearSound), CSPFT_STRING}, - {"nightVisionWearSoundPlayer", offsetof(WeaponFullDef, weapDef.nightVisionWearSoundPlayer), CSPFT_STRING}, - {"nightVisionRemoveSound", offsetof(WeaponFullDef, weapDef.nightVisionRemoveSound), CSPFT_STRING}, - {"nightVisionRemoveSoundPlayer", offsetof(WeaponFullDef, weapDef.nightVisionRemoveSoundPlayer), CSPFT_STRING}, - {"raiseSound", offsetof(WeaponFullDef, weapDef.raiseSound), CSPFT_STRING}, - {"raiseSoundPlayer", offsetof(WeaponFullDef, weapDef.raiseSoundPlayer), CSPFT_STRING}, - {"firstRaiseSound", offsetof(WeaponFullDef, weapDef.firstRaiseSound), CSPFT_STRING}, - {"firstRaiseSoundPlayer", offsetof(WeaponFullDef, weapDef.firstRaiseSoundPlayer), CSPFT_STRING}, - {"altSwitchSound", offsetof(WeaponFullDef, weapDef.altSwitchSound), CSPFT_STRING}, - {"altSwitchSoundPlayer", offsetof(WeaponFullDef, weapDef.altSwitchSoundPlayer), CSPFT_STRING}, - {"adsRaiseSoundPlayer", offsetof(WeaponFullDef, weapDef.adsRaiseSoundPlayer), CSPFT_STRING}, - {"adsLowerSoundPlayer", offsetof(WeaponFullDef, weapDef.adsLowerSoundPlayer), CSPFT_STRING}, - {"putawaySound", offsetof(WeaponFullDef, weapDef.putawaySound), CSPFT_STRING}, - {"putawaySoundPlayer", offsetof(WeaponFullDef, weapDef.putawaySoundPlayer), CSPFT_STRING}, - {"overheatSound", offsetof(WeaponFullDef, weapDef.overheatSound), CSPFT_STRING}, - {"overheatSoundPlayer", offsetof(WeaponFullDef, weapDef.overheatSoundPlayer), CSPFT_STRING}, - {"adsZoomSound", offsetof(WeaponFullDef, weapDef.adsZoomSound), CSPFT_STRING}, - {"shellCasing", offsetof(WeaponFullDef, weapDef.shellCasing), CSPFT_STRING}, - {"shellCasingPlayer", offsetof(WeaponFullDef, weapDef.shellCasingPlayer), CSPFT_STRING}, - {"bounceSound", offsetof(WeaponFullDef, weapDef.bounceSound), WFT_BOUNCE_SOUND}, - {"standMountedWeapdef", offsetof(WeaponFullDef, weapDef.standMountedWeapdef), CSPFT_STRING}, - {"crouchMountedWeapdef", offsetof(WeaponFullDef, weapDef.crouchMountedWeapdef), CSPFT_STRING}, - {"proneMountedWeapdef", offsetof(WeaponFullDef, weapDef.proneMountedWeapdef), CSPFT_STRING}, - {"viewShellEjectEffect", offsetof(WeaponFullDef, weapDef.viewShellEjectEffect), CSPFT_FX}, - {"worldShellEjectEffect", offsetof(WeaponFullDef, weapDef.worldShellEjectEffect), CSPFT_FX}, - {"viewLastShotEjectEffect", offsetof(WeaponFullDef, weapDef.viewLastShotEjectEffect), CSPFT_FX}, - {"worldLastShotEjectEffect", offsetof(WeaponFullDef, weapDef.worldLastShotEjectEffect), CSPFT_FX}, - {"viewShellEjectOffsetF", offsetof(WeaponFullDef, weapDef.vViewShellEjectOffset.x), CSPFT_FLOAT}, - {"viewShellEjectOffsetR", offsetof(WeaponFullDef, weapDef.vViewShellEjectOffset.y), CSPFT_FLOAT}, - {"viewShellEjectOffsetU", offsetof(WeaponFullDef, weapDef.vViewShellEjectOffset.z), CSPFT_FLOAT}, - {"worldShellEjectOffsetF", offsetof(WeaponFullDef, weapDef.vWorldShellEjectOffset.x), CSPFT_FLOAT}, - {"worldShellEjectOffsetR", offsetof(WeaponFullDef, weapDef.vWorldShellEjectOffset.y), CSPFT_FLOAT}, - {"worldShellEjectOffsetU", offsetof(WeaponFullDef, weapDef.vWorldShellEjectOffset.z), CSPFT_FLOAT}, - {"viewShellEjectRotationP", offsetof(WeaponFullDef, weapDef.vViewShellEjectRotation.x), CSPFT_FLOAT}, - {"viewShellEjectRotationY", offsetof(WeaponFullDef, weapDef.vViewShellEjectRotation.y), CSPFT_FLOAT}, - {"viewShellEjectRotationR", offsetof(WeaponFullDef, weapDef.vViewShellEjectRotation.z), CSPFT_FLOAT}, - {"worldShellEjectRotationP", offsetof(WeaponFullDef, weapDef.vWorldShellEjectRotation.x), CSPFT_FLOAT}, - {"worldShellEjectRotationY", offsetof(WeaponFullDef, weapDef.vWorldShellEjectRotation.y), CSPFT_FLOAT}, - {"worldShellEjectRotationR", offsetof(WeaponFullDef, weapDef.vWorldShellEjectRotation.z), CSPFT_FLOAT}, - {"reticleCenter", offsetof(WeaponFullDef, weapDef.reticleCenter), CSPFT_MATERIAL}, - {"reticleSide", offsetof(WeaponFullDef, weapDef.reticleSide), CSPFT_MATERIAL}, - {"reticleCenterSize", offsetof(WeaponFullDef, weapDef.iReticleCenterSize), CSPFT_INT}, - {"reticleSideSize", offsetof(WeaponFullDef, weapDef.iReticleSideSize), CSPFT_INT}, - {"reticleMinOfs", offsetof(WeaponFullDef, weapDef.iReticleMinOfs), CSPFT_INT}, - {"activeReticleType", offsetof(WeaponFullDef, weapDef.activeReticleType), WFT_ACTIVE_RETICLE_TYPE}, - {"standMoveF", offsetof(WeaponFullDef, weapDef.vStandMove.x), CSPFT_FLOAT}, - {"standMoveR", offsetof(WeaponFullDef, weapDef.vStandMove.y), CSPFT_FLOAT}, - {"standMoveU", offsetof(WeaponFullDef, weapDef.vStandMove.z), CSPFT_FLOAT}, - {"standRotP", offsetof(WeaponFullDef, weapDef.vStandRot.x), CSPFT_FLOAT}, - {"standRotY", offsetof(WeaponFullDef, weapDef.vStandRot.y), CSPFT_FLOAT}, - {"standRotR", offsetof(WeaponFullDef, weapDef.vStandRot.z), CSPFT_FLOAT}, - {"duckedOfsF", offsetof(WeaponFullDef, weapDef.vDuckedOfs.x), CSPFT_FLOAT}, - {"duckedOfsR", offsetof(WeaponFullDef, weapDef.vDuckedOfs.y), CSPFT_FLOAT}, - {"duckedOfsU", offsetof(WeaponFullDef, weapDef.vDuckedOfs.z), CSPFT_FLOAT}, - {"duckedMoveF", offsetof(WeaponFullDef, weapDef.vDuckedMove.x), CSPFT_FLOAT}, - {"duckedMoveR", offsetof(WeaponFullDef, weapDef.vDuckedMove.y), CSPFT_FLOAT}, - {"duckedMoveU", offsetof(WeaponFullDef, weapDef.vDuckedMove.z), CSPFT_FLOAT}, - {"duckedSprintOfsF", offsetof(WeaponFullDef, weapDef.vDuckedSprintOfs.x), CSPFT_FLOAT}, - {"duckedSprintOfsR", offsetof(WeaponFullDef, weapDef.vDuckedSprintOfs.y), CSPFT_FLOAT}, - {"duckedSprintOfsU", offsetof(WeaponFullDef, weapDef.vDuckedSprintOfs.z), CSPFT_FLOAT}, - {"duckedSprintRotP", offsetof(WeaponFullDef, weapDef.vDuckedSprintRot.x), CSPFT_FLOAT}, - {"duckedSprintRotY", offsetof(WeaponFullDef, weapDef.vDuckedSprintRot.y), CSPFT_FLOAT}, - {"duckedSprintRotR", offsetof(WeaponFullDef, weapDef.vDuckedSprintRot.z), CSPFT_FLOAT}, - {"duckedSprintBobH", offsetof(WeaponFullDef, weapDef.vDuckedSprintBob.x), CSPFT_FLOAT}, - {"duckedSprintBobV", offsetof(WeaponFullDef, weapDef.vDuckedSprintBob.y), CSPFT_FLOAT}, - {"duckedSprintScale", offsetof(WeaponFullDef, weapDef.fDuckedSprintCycleScale), CSPFT_FLOAT}, - {"sprintOfsF", offsetof(WeaponFullDef, weapDef.vSprintOfs.x), CSPFT_FLOAT}, - {"sprintOfsR", offsetof(WeaponFullDef, weapDef.vSprintOfs.y), CSPFT_FLOAT}, - {"sprintOfsU", offsetof(WeaponFullDef, weapDef.vSprintOfs.z), CSPFT_FLOAT}, - {"sprintRotP", offsetof(WeaponFullDef, weapDef.vSprintRot.x), CSPFT_FLOAT}, - {"sprintRotY", offsetof(WeaponFullDef, weapDef.vSprintRot.y), CSPFT_FLOAT}, - {"sprintRotR", offsetof(WeaponFullDef, weapDef.vSprintRot.z), CSPFT_FLOAT}, - {"sprintBobH", offsetof(WeaponFullDef, weapDef.vSprintBob.x), CSPFT_FLOAT}, - {"sprintBobV", offsetof(WeaponFullDef, weapDef.vSprintBob.y), CSPFT_FLOAT}, - {"sprintScale", offsetof(WeaponFullDef, weapDef.fSprintCycleScale), CSPFT_FLOAT}, - {"lowReadyOfsF", offsetof(WeaponFullDef, weapDef.vLowReadyOfs.x), CSPFT_FLOAT}, - {"lowReadyOfsR", offsetof(WeaponFullDef, weapDef.vLowReadyOfs.y), CSPFT_FLOAT}, - {"lowReadyOfsU", offsetof(WeaponFullDef, weapDef.vLowReadyOfs.z), CSPFT_FLOAT}, - {"lowReadyRotP", offsetof(WeaponFullDef, weapDef.vLowReadyRot.x), CSPFT_FLOAT}, - {"lowReadyRotY", offsetof(WeaponFullDef, weapDef.vLowReadyRot.y), CSPFT_FLOAT}, - {"lowReadyRotR", offsetof(WeaponFullDef, weapDef.vLowReadyRot.z), CSPFT_FLOAT}, - {"rideOfsF", offsetof(WeaponFullDef, weapDef.vRideOfs.x), CSPFT_FLOAT}, - {"rideOfsR", offsetof(WeaponFullDef, weapDef.vRideOfs.y), CSPFT_FLOAT}, - {"rideOfsU", offsetof(WeaponFullDef, weapDef.vRideOfs.z), CSPFT_FLOAT}, - {"rideRotP", offsetof(WeaponFullDef, weapDef.vRideRot.x), CSPFT_FLOAT}, - {"rideRotY", offsetof(WeaponFullDef, weapDef.vRideRot.y), CSPFT_FLOAT}, - {"rideRotR", offsetof(WeaponFullDef, weapDef.vRideRot.z), CSPFT_FLOAT}, - {"dtpOfsF", offsetof(WeaponFullDef, weapDef.vDtpOfs.x), CSPFT_FLOAT}, - {"dtpOfsR", offsetof(WeaponFullDef, weapDef.vDtpOfs.y), CSPFT_FLOAT}, - {"dtpOfsU", offsetof(WeaponFullDef, weapDef.vDtpOfs.z), CSPFT_FLOAT}, - {"dtpRotP", offsetof(WeaponFullDef, weapDef.vDtpRot.x), CSPFT_FLOAT}, - {"dtpRotY", offsetof(WeaponFullDef, weapDef.vDtpRot.y), CSPFT_FLOAT}, - {"dtpRotR", offsetof(WeaponFullDef, weapDef.vDtpRot.z), CSPFT_FLOAT}, - {"dtpBobH", offsetof(WeaponFullDef, weapDef.vDtpBob.x), CSPFT_FLOAT}, - {"dtpBobV", offsetof(WeaponFullDef, weapDef.vDtpBob.y), CSPFT_FLOAT}, - {"dtpScale", offsetof(WeaponFullDef, weapDef.fDtpCycleScale), CSPFT_FLOAT}, - {"mantleOfsF", offsetof(WeaponFullDef, weapDef.vMantleOfs.x), CSPFT_FLOAT}, - {"mantleOfsR", offsetof(WeaponFullDef, weapDef.vMantleOfs.y), CSPFT_FLOAT}, - {"mantleOfsU", offsetof(WeaponFullDef, weapDef.vMantleOfs.z), CSPFT_FLOAT}, - {"mantleRotP", offsetof(WeaponFullDef, weapDef.vMantleRot.x), CSPFT_FLOAT}, - {"mantleRotY", offsetof(WeaponFullDef, weapDef.vMantleRot.y), CSPFT_FLOAT}, - {"mantleRotR", offsetof(WeaponFullDef, weapDef.vMantleRot.z), CSPFT_FLOAT}, - {"slideOfsF", offsetof(WeaponFullDef, weapDef.vSlideOfs.x), CSPFT_FLOAT}, - {"slideOfsR", offsetof(WeaponFullDef, weapDef.vSlideOfs.y), CSPFT_FLOAT}, - {"slideOfsU", offsetof(WeaponFullDef, weapDef.vSlideOfs.z), CSPFT_FLOAT}, - {"slideRotP", offsetof(WeaponFullDef, weapDef.vSlideRot.x), CSPFT_FLOAT}, - {"slideRotY", offsetof(WeaponFullDef, weapDef.vSlideRot.y), CSPFT_FLOAT}, - {"slideRotR", offsetof(WeaponFullDef, weapDef.vSlideRot.z), CSPFT_FLOAT}, - {"duckedRotP", offsetof(WeaponFullDef, weapDef.vDuckedRot.x), CSPFT_FLOAT}, - {"duckedRotY", offsetof(WeaponFullDef, weapDef.vDuckedRot.y), CSPFT_FLOAT}, - {"duckedRotR", offsetof(WeaponFullDef, weapDef.vDuckedRot.z), CSPFT_FLOAT}, - {"proneOfsF", offsetof(WeaponFullDef, weapDef.vProneOfs.x), CSPFT_FLOAT}, - {"proneOfsR", offsetof(WeaponFullDef, weapDef.vProneOfs.y), CSPFT_FLOAT}, - {"proneOfsU", offsetof(WeaponFullDef, weapDef.vProneOfs.z), CSPFT_FLOAT}, - {"proneMoveF", offsetof(WeaponFullDef, weapDef.vProneMove.x), CSPFT_FLOAT}, - {"proneMoveR", offsetof(WeaponFullDef, weapDef.vProneMove.y), CSPFT_FLOAT}, - {"proneMoveU", offsetof(WeaponFullDef, weapDef.vProneMove.z), CSPFT_FLOAT}, - {"proneRotP", offsetof(WeaponFullDef, weapDef.vProneRot.x), CSPFT_FLOAT}, - {"proneRotY", offsetof(WeaponFullDef, weapDef.vProneRot.y), CSPFT_FLOAT}, - {"proneRotR", offsetof(WeaponFullDef, weapDef.vProneRot.z), CSPFT_FLOAT}, - {"strafeMoveF", offsetof(WeaponFullDef, weapDef.vStrafeMove.x), CSPFT_FLOAT}, - {"strafeMoveR", offsetof(WeaponFullDef, weapDef.vStrafeMove.y), CSPFT_FLOAT}, - {"strafeMoveU", offsetof(WeaponFullDef, weapDef.vStrafeMove.z), CSPFT_FLOAT}, - {"strafeRotP", offsetof(WeaponFullDef, weapDef.vStrafeRot.x), CSPFT_FLOAT}, - {"strafeRotY", offsetof(WeaponFullDef, weapDef.vStrafeRot.y), CSPFT_FLOAT}, - {"strafeRotR", offsetof(WeaponFullDef, weapDef.vStrafeRot.z), CSPFT_FLOAT}, - {"posMoveRate", offsetof(WeaponFullDef, weapDef.fPosMoveRate), CSPFT_FLOAT}, - {"posProneMoveRate", offsetof(WeaponFullDef, weapDef.fPosProneMoveRate), CSPFT_FLOAT}, - {"standMoveMinSpeed", offsetof(WeaponFullDef, weapDef.fStandMoveMinSpeed), CSPFT_FLOAT}, - {"duckedMoveMinSpeed", offsetof(WeaponFullDef, weapDef.fDuckedMoveMinSpeed), CSPFT_FLOAT}, - {"proneMoveMinSpeed", offsetof(WeaponFullDef, weapDef.fProneMoveMinSpeed), CSPFT_FLOAT}, - {"posRotRate", offsetof(WeaponFullDef, weapDef.fPosRotRate), CSPFT_FLOAT}, - {"posProneRotRate", offsetof(WeaponFullDef, weapDef.fPosProneRotRate), CSPFT_FLOAT}, - {"standRotMinSpeed", offsetof(WeaponFullDef, weapDef.fStandRotMinSpeed), CSPFT_FLOAT}, - {"duckedRotMinSpeed", offsetof(WeaponFullDef, weapDef.fDuckedRotMinSpeed), CSPFT_FLOAT}, - {"proneRotMinSpeed", offsetof(WeaponFullDef, weapDef.fProneRotMinSpeed), CSPFT_FLOAT}, - {"worldModel", offsetof(WeaponFullDef, worldModel[0]), CSPFT_XMODEL}, - {"worldModel2", offsetof(WeaponFullDef, worldModel[1]), CSPFT_XMODEL}, - {"worldModel3", offsetof(WeaponFullDef, worldModel[2]), CSPFT_XMODEL}, - {"worldModel4", offsetof(WeaponFullDef, worldModel[3]), CSPFT_XMODEL}, - {"worldModel5", offsetof(WeaponFullDef, worldModel[4]), CSPFT_XMODEL}, - {"worldModel6", offsetof(WeaponFullDef, worldModel[5]), CSPFT_XMODEL}, - {"worldModel7", offsetof(WeaponFullDef, worldModel[6]), CSPFT_XMODEL}, - {"worldModel8", offsetof(WeaponFullDef, worldModel[7]), CSPFT_XMODEL}, - {"worldModel9", offsetof(WeaponFullDef, worldModel[8]), CSPFT_XMODEL}, - {"worldModel10", offsetof(WeaponFullDef, worldModel[9]), CSPFT_XMODEL}, - {"worldModel11", offsetof(WeaponFullDef, worldModel[10]), CSPFT_XMODEL}, - {"worldModel12", offsetof(WeaponFullDef, worldModel[11]), CSPFT_XMODEL}, - {"worldModel13", offsetof(WeaponFullDef, worldModel[12]), CSPFT_XMODEL}, - {"worldModel14", offsetof(WeaponFullDef, worldModel[13]), CSPFT_XMODEL}, - {"worldModel15", offsetof(WeaponFullDef, worldModel[14]), CSPFT_XMODEL}, - {"worldModel16", offsetof(WeaponFullDef, worldModel[15]), CSPFT_XMODEL}, - {"attachViewModel1", offsetof(WeaponFullDef, attachViewModel[0]), CSPFT_XMODEL}, - {"attachViewModel2", offsetof(WeaponFullDef, attachViewModel[1]), CSPFT_XMODEL}, - {"attachViewModel3", offsetof(WeaponFullDef, attachViewModel[2]), CSPFT_XMODEL}, - {"attachViewModel4", offsetof(WeaponFullDef, attachViewModel[3]), CSPFT_XMODEL}, - {"attachViewModel5", offsetof(WeaponFullDef, attachViewModel[4]), CSPFT_XMODEL}, - {"attachViewModel6", offsetof(WeaponFullDef, attachViewModel[5]), CSPFT_XMODEL}, - {"attachViewModel7", offsetof(WeaponFullDef, attachViewModel[6]), CSPFT_XMODEL}, - {"attachViewModel8", offsetof(WeaponFullDef, attachViewModel[7]), CSPFT_XMODEL}, - {"attachWorldModel1", offsetof(WeaponFullDef, attachWorldModel[0]), CSPFT_XMODEL}, - {"attachWorldModel2", offsetof(WeaponFullDef, attachWorldModel[1]), CSPFT_XMODEL}, - {"attachWorldModel3", offsetof(WeaponFullDef, attachWorldModel[2]), CSPFT_XMODEL}, - {"attachWorldModel4", offsetof(WeaponFullDef, attachWorldModel[3]), CSPFT_XMODEL}, - {"attachWorldModel5", offsetof(WeaponFullDef, attachWorldModel[4]), CSPFT_XMODEL}, - {"attachWorldModel6", offsetof(WeaponFullDef, attachWorldModel[5]), CSPFT_XMODEL}, - {"attachWorldModel7", offsetof(WeaponFullDef, attachWorldModel[6]), CSPFT_XMODEL}, - {"attachWorldModel8", offsetof(WeaponFullDef, attachWorldModel[7]), CSPFT_XMODEL}, - {"attachViewModelTag1", offsetof(WeaponFullDef, attachViewModelTag[0]), CSPFT_STRING}, - {"attachViewModelTag2", offsetof(WeaponFullDef, attachViewModelTag[1]), CSPFT_STRING}, - {"attachViewModelTag3", offsetof(WeaponFullDef, attachViewModelTag[2]), CSPFT_STRING}, - {"attachViewModelTag4", offsetof(WeaponFullDef, attachViewModelTag[3]), CSPFT_STRING}, - {"attachViewModelTag5", offsetof(WeaponFullDef, attachViewModelTag[4]), CSPFT_STRING}, - {"attachViewModelTag6", offsetof(WeaponFullDef, attachViewModelTag[5]), CSPFT_STRING}, - {"attachViewModelTag7", offsetof(WeaponFullDef, attachViewModelTag[6]), CSPFT_STRING}, - {"attachViewModelTag8", offsetof(WeaponFullDef, attachViewModelTag[7]), CSPFT_STRING}, - {"attachWorldModelTag1", offsetof(WeaponFullDef, attachWorldModelTag[0]), CSPFT_STRING}, - {"attachWorldModelTag2", offsetof(WeaponFullDef, attachWorldModelTag[1]), CSPFT_STRING}, - {"attachWorldModelTag3", offsetof(WeaponFullDef, attachWorldModelTag[2]), CSPFT_STRING}, - {"attachWorldModelTag4", offsetof(WeaponFullDef, attachWorldModelTag[3]), CSPFT_STRING}, - {"attachWorldModelTag5", offsetof(WeaponFullDef, attachWorldModelTag[4]), CSPFT_STRING}, - {"attachWorldModelTag6", offsetof(WeaponFullDef, attachWorldModelTag[5]), CSPFT_STRING}, - {"attachWorldModelTag7", offsetof(WeaponFullDef, attachWorldModelTag[6]), CSPFT_STRING}, - {"attachWorldModelTag8", offsetof(WeaponFullDef, attachWorldModelTag[7]), CSPFT_STRING}, - {"attachViewModelOffsetX1", offsetof(WeaponFullDef, weapVariantDef.attachViewModelOffsets[0]), CSPFT_FLOAT}, - {"attachViewModelOffsetY1", offsetof(WeaponFullDef, weapVariantDef.attachViewModelOffsets[1]), CSPFT_FLOAT}, - {"attachViewModelOffsetZ1", offsetof(WeaponFullDef, weapVariantDef.attachViewModelOffsets[2]), CSPFT_FLOAT}, - {"attachViewModelOffsetX2", offsetof(WeaponFullDef, weapVariantDef.attachViewModelOffsets[3]), CSPFT_FLOAT}, - {"attachViewModelOffsetY2", offsetof(WeaponFullDef, weapVariantDef.attachViewModelOffsets[4]), CSPFT_FLOAT}, - {"attachViewModelOffsetZ2", offsetof(WeaponFullDef, weapVariantDef.attachViewModelOffsets[5]), CSPFT_FLOAT}, - {"attachViewModelOffsetX3", offsetof(WeaponFullDef, weapVariantDef.attachViewModelOffsets[6]), CSPFT_FLOAT}, - {"attachViewModelOffsetY3", offsetof(WeaponFullDef, weapVariantDef.attachViewModelOffsets[7]), CSPFT_FLOAT}, - {"attachViewModelOffsetZ3", offsetof(WeaponFullDef, weapVariantDef.attachViewModelOffsets[8]), CSPFT_FLOAT}, - {"attachViewModelOffsetX4", offsetof(WeaponFullDef, weapVariantDef.attachViewModelOffsets[9]), CSPFT_FLOAT}, - {"attachViewModelOffsetY4", offsetof(WeaponFullDef, weapVariantDef.attachViewModelOffsets[10]), CSPFT_FLOAT}, - {"attachViewModelOffsetZ4", offsetof(WeaponFullDef, weapVariantDef.attachViewModelOffsets[11]), CSPFT_FLOAT}, - {"attachViewModelOffsetX5", offsetof(WeaponFullDef, weapVariantDef.attachViewModelOffsets[12]), CSPFT_FLOAT}, - {"attachViewModelOffsetY5", offsetof(WeaponFullDef, weapVariantDef.attachViewModelOffsets[13]), CSPFT_FLOAT}, - {"attachViewModelOffsetZ5", offsetof(WeaponFullDef, weapVariantDef.attachViewModelOffsets[14]), CSPFT_FLOAT}, - {"attachViewModelOffsetX6", offsetof(WeaponFullDef, weapVariantDef.attachViewModelOffsets[15]), CSPFT_FLOAT}, - {"attachViewModelOffsetY6", offsetof(WeaponFullDef, weapVariantDef.attachViewModelOffsets[16]), CSPFT_FLOAT}, - {"attachViewModelOffsetZ6", offsetof(WeaponFullDef, weapVariantDef.attachViewModelOffsets[17]), CSPFT_FLOAT}, - {"attachViewModelOffsetX7", offsetof(WeaponFullDef, weapVariantDef.attachViewModelOffsets[18]), CSPFT_FLOAT}, - {"attachViewModelOffsetY7", offsetof(WeaponFullDef, weapVariantDef.attachViewModelOffsets[19]), CSPFT_FLOAT}, - {"attachViewModelOffsetZ7", offsetof(WeaponFullDef, weapVariantDef.attachViewModelOffsets[20]), CSPFT_FLOAT}, - {"attachViewModelOffsetX8", offsetof(WeaponFullDef, weapVariantDef.attachViewModelOffsets[21]), CSPFT_FLOAT}, - {"attachViewModelOffsetY8", offsetof(WeaponFullDef, weapVariantDef.attachViewModelOffsets[22]), CSPFT_FLOAT}, - {"attachViewModelOffsetZ8", offsetof(WeaponFullDef, weapVariantDef.attachViewModelOffsets[23]), CSPFT_FLOAT}, - {"attachWorldModelOffsetX1", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelOffsets[0]), CSPFT_FLOAT}, - {"attachWorldModelOffsetY1", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelOffsets[1]), CSPFT_FLOAT}, - {"attachWorldModelOffsetZ1", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelOffsets[2]), CSPFT_FLOAT}, - {"attachWorldModelOffsetX2", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelOffsets[3]), CSPFT_FLOAT}, - {"attachWorldModelOffsetY2", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelOffsets[4]), CSPFT_FLOAT}, - {"attachWorldModelOffsetZ2", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelOffsets[5]), CSPFT_FLOAT}, - {"attachWorldModelOffsetX3", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelOffsets[6]), CSPFT_FLOAT}, - {"attachWorldModelOffsetY3", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelOffsets[7]), CSPFT_FLOAT}, - {"attachWorldModelOffsetZ3", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelOffsets[8]), CSPFT_FLOAT}, - {"attachWorldModelOffsetX4", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelOffsets[9]), CSPFT_FLOAT}, - {"attachWorldModelOffsetY4", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelOffsets[10]), CSPFT_FLOAT}, - {"attachWorldModelOffsetZ4", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelOffsets[11]), CSPFT_FLOAT}, - {"attachWorldModelOffsetX5", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelOffsets[12]), CSPFT_FLOAT}, - {"attachWorldModelOffsetY5", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelOffsets[13]), CSPFT_FLOAT}, - {"attachWorldModelOffsetZ5", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelOffsets[14]), CSPFT_FLOAT}, - {"attachWorldModelOffsetX6", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelOffsets[15]), CSPFT_FLOAT}, - {"attachWorldModelOffsetY6", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelOffsets[16]), CSPFT_FLOAT}, - {"attachWorldModelOffsetZ6", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelOffsets[17]), CSPFT_FLOAT}, - {"attachWorldModelOffsetX7", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelOffsets[18]), CSPFT_FLOAT}, - {"attachWorldModelOffsetY7", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelOffsets[19]), CSPFT_FLOAT}, - {"attachWorldModelOffsetZ7", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelOffsets[20]), CSPFT_FLOAT}, - {"attachWorldModelOffsetX8", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelOffsets[21]), CSPFT_FLOAT}, - {"attachWorldModelOffsetY8", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelOffsets[22]), CSPFT_FLOAT}, - {"attachWorldModelOffsetZ8", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelOffsets[23]), CSPFT_FLOAT}, - {"attachViewModelOffsetPitch1", offsetof(WeaponFullDef, weapVariantDef.attachViewModelRotations[0]), CSPFT_FLOAT}, - {"attachViewModelOffsetYaw1", offsetof(WeaponFullDef, weapVariantDef.attachViewModelRotations[1]), CSPFT_FLOAT}, - {"attachViewModelOffsetRoll1", offsetof(WeaponFullDef, weapVariantDef.attachViewModelRotations[2]), CSPFT_FLOAT}, - {"attachViewModelOffsetPitch2", offsetof(WeaponFullDef, weapVariantDef.attachViewModelRotations[3]), CSPFT_FLOAT}, - {"attachViewModelOffsetYaw2", offsetof(WeaponFullDef, weapVariantDef.attachViewModelRotations[4]), CSPFT_FLOAT}, - {"attachViewModelOffsetRoll2", offsetof(WeaponFullDef, weapVariantDef.attachViewModelRotations[5]), CSPFT_FLOAT}, - {"attachViewModelOffsetPitch3", offsetof(WeaponFullDef, weapVariantDef.attachViewModelRotations[6]), CSPFT_FLOAT}, - {"attachViewModelOffsetYaw3", offsetof(WeaponFullDef, weapVariantDef.attachViewModelRotations[7]), CSPFT_FLOAT}, - {"attachViewModelOffsetRoll3", offsetof(WeaponFullDef, weapVariantDef.attachViewModelRotations[8]), CSPFT_FLOAT}, - {"attachViewModelOffsetPitch4", offsetof(WeaponFullDef, weapVariantDef.attachViewModelRotations[9]), CSPFT_FLOAT}, - {"attachViewModelOffsetYaw4", offsetof(WeaponFullDef, weapVariantDef.attachViewModelRotations[10]), CSPFT_FLOAT}, - {"attachViewModelOffsetRoll4", offsetof(WeaponFullDef, weapVariantDef.attachViewModelRotations[11]), CSPFT_FLOAT}, - {"attachViewModelOffsetPitch5", offsetof(WeaponFullDef, weapVariantDef.attachViewModelRotations[12]), CSPFT_FLOAT}, - {"attachViewModelOffsetYaw5", offsetof(WeaponFullDef, weapVariantDef.attachViewModelRotations[13]), CSPFT_FLOAT}, - {"attachViewModelOffsetRoll5", offsetof(WeaponFullDef, weapVariantDef.attachViewModelRotations[14]), CSPFT_FLOAT}, - {"attachViewModelOffsetPitch6", offsetof(WeaponFullDef, weapVariantDef.attachViewModelRotations[15]), CSPFT_FLOAT}, - {"attachViewModelOffsetYaw6", offsetof(WeaponFullDef, weapVariantDef.attachViewModelRotations[16]), CSPFT_FLOAT}, - {"attachViewModelOffsetRoll6", offsetof(WeaponFullDef, weapVariantDef.attachViewModelRotations[17]), CSPFT_FLOAT}, - {"attachViewModelOffsetPitch7", offsetof(WeaponFullDef, weapVariantDef.attachViewModelRotations[18]), CSPFT_FLOAT}, - {"attachViewModelOffsetYaw7", offsetof(WeaponFullDef, weapVariantDef.attachViewModelRotations[19]), CSPFT_FLOAT}, - {"attachViewModelOffsetRoll7", offsetof(WeaponFullDef, weapVariantDef.attachViewModelRotations[20]), CSPFT_FLOAT}, - {"attachViewModelOffsetPitch8", offsetof(WeaponFullDef, weapVariantDef.attachViewModelRotations[21]), CSPFT_FLOAT}, - {"attachViewModelOffsetYaw8", offsetof(WeaponFullDef, weapVariantDef.attachViewModelRotations[22]), CSPFT_FLOAT}, - {"attachViewModelOffsetRoll8", offsetof(WeaponFullDef, weapVariantDef.attachViewModelRotations[23]), CSPFT_FLOAT}, - {"attachWorldModelOffsetPitch1", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelRotations[0]), CSPFT_FLOAT}, - {"attachWorldModelOffsetYaw1", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelRotations[1]), CSPFT_FLOAT}, - {"attachWorldModelOffsetRoll1", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelRotations[2]), CSPFT_FLOAT}, - {"attachWorldModelOffsetPitch2", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelRotations[3]), CSPFT_FLOAT}, - {"attachWorldModelOffsetYaw2", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelRotations[4]), CSPFT_FLOAT}, - {"attachWorldModelOffsetRoll2", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelRotations[5]), CSPFT_FLOAT}, - {"attachWorldModelOffsetPitch3", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelRotations[6]), CSPFT_FLOAT}, - {"attachWorldModelOffsetYaw3", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelRotations[7]), CSPFT_FLOAT}, - {"attachWorldModelOffsetRoll3", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelRotations[8]), CSPFT_FLOAT}, - {"attachWorldModelOffsetPitch4", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelRotations[9]), CSPFT_FLOAT}, - {"attachWorldModelOffsetYaw4", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelRotations[10]), CSPFT_FLOAT}, - {"attachWorldModelOffsetRoll4", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelRotations[11]), CSPFT_FLOAT}, - {"attachWorldModelOffsetPitch5", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelRotations[12]), CSPFT_FLOAT}, - {"attachWorldModelOffsetYaw5", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelRotations[13]), CSPFT_FLOAT}, - {"attachWorldModelOffsetRoll5", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelRotations[14]), CSPFT_FLOAT}, - {"attachWorldModelOffsetPitch6", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelRotations[15]), CSPFT_FLOAT}, - {"attachWorldModelOffsetYaw6", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelRotations[16]), CSPFT_FLOAT}, - {"attachWorldModelOffsetRoll6", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelRotations[17]), CSPFT_FLOAT}, - {"attachWorldModelOffsetPitch7", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelRotations[18]), CSPFT_FLOAT}, - {"attachWorldModelOffsetYaw7", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelRotations[19]), CSPFT_FLOAT}, - {"attachWorldModelOffsetRoll7", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelRotations[20]), CSPFT_FLOAT}, - {"attachWorldModelOffsetPitch8", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelRotations[21]), CSPFT_FLOAT}, - {"attachWorldModelOffsetYaw8", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelRotations[22]), CSPFT_FLOAT}, - {"attachWorldModelOffsetRoll8", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelRotations[23]), CSPFT_FLOAT}, - {"ignoreAttachments", offsetof(WeaponFullDef, weapVariantDef.bIgnoreAttachments), CSPFT_BOOL}, - {"stowedModelOffsetsF", offsetof(WeaponFullDef, weapVariantDef.stowedModelOffsets.x), CSPFT_FLOAT}, - {"stowedModelOffsetsR", offsetof(WeaponFullDef, weapVariantDef.stowedModelOffsets.y), CSPFT_FLOAT}, - {"stowedModelOffsetsU", offsetof(WeaponFullDef, weapVariantDef.stowedModelOffsets.z), CSPFT_FLOAT}, - {"stowedModelOffsetsPitch", offsetof(WeaponFullDef, weapVariantDef.stowedModelRotations.x), CSPFT_FLOAT}, - {"stowedModelOffsetsYaw", offsetof(WeaponFullDef, weapVariantDef.stowedModelRotations.y), CSPFT_FLOAT}, - {"stowedModelOffsetsRoll", offsetof(WeaponFullDef, weapVariantDef.stowedModelRotations.z), CSPFT_FLOAT}, - {"worldClipModel", offsetof(WeaponFullDef, weapDef.worldClipModel), CSPFT_XMODEL}, - {"rocketModel", offsetof(WeaponFullDef, weapDef.rocketModel), CSPFT_XMODEL}, - {"mountedModel", offsetof(WeaponFullDef, weapDef.mountedModel), CSPFT_XMODEL}, - {"AdditionalMeleeModel", offsetof(WeaponFullDef, weapDef.additionalMeleeModel), CSPFT_XMODEL}, - {"fireTypeIcon", offsetof(WeaponFullDef, weapDef.fireTypeIcon), CSPFT_MATERIAL}, - {"hudIcon", offsetof(WeaponFullDef, weapDef.hudIcon), CSPFT_MATERIAL}, - {"hudIconRatio", offsetof(WeaponFullDef, weapDef.hudIconRatio), WFT_ICONRATIO_HUD}, - {"indicatorIcon", offsetof(WeaponFullDef, weapDef.indicatorIcon), CSPFT_MATERIAL}, - {"indicatorIconRatio", offsetof(WeaponFullDef, weapDef.indicatorIconRatio), WFT_ICONRATIO_INDICATOR}, - {"ammoCounterIcon", offsetof(WeaponFullDef, weapDef.ammoCounterIcon), CSPFT_MATERIAL}, - {"ammoCounterIconRatio", offsetof(WeaponFullDef, weapDef.ammoCounterIconRatio), WFT_ICONRATIO_AMMOCOUNTER}, - {"ammoCounterClip", offsetof(WeaponFullDef, weapDef.ammoCounterClip), WFT_AMMOCOUNTER_CLIPTYPE}, - {"startAmmo", offsetof(WeaponFullDef, weapDef.iStartAmmo), CSPFT_INT}, - {"ammoDisplayName", offsetof(WeaponFullDef, weapVariantDef.szAmmoDisplayName), CSPFT_STRING}, - {"ammoName", offsetof(WeaponFullDef, weapVariantDef.szAmmoName), CSPFT_STRING}, - {"clipName", offsetof(WeaponFullDef, weapVariantDef.szClipName), CSPFT_STRING}, - {"maxAmmo", offsetof(WeaponFullDef, weapDef.iMaxAmmo), CSPFT_INT}, - {"clipSize", offsetof(WeaponFullDef, weapVariantDef.iClipSize), CSPFT_INT}, - {"shotCount", offsetof(WeaponFullDef, weapDef.shotCount), CSPFT_INT}, - {"sharedAmmoCapName", offsetof(WeaponFullDef, weapDef.szSharedAmmoCapName), CSPFT_STRING}, - {"sharedAmmoCap", offsetof(WeaponFullDef, weapDef.iSharedAmmoCap), CSPFT_INT}, - {"unlimitedAmmo", offsetof(WeaponFullDef, weapDef.unlimitedAmmo), CSPFT_BOOL}, - {"ammoCountClipRelative", offsetof(WeaponFullDef, weapDef.ammoCountClipRelative), CSPFT_BOOL}, - {"sharedAmmo", offsetof(WeaponFullDef, weapDef.sharedAmmo), CSPFT_BOOL}, - {"jamFireTime", offsetof(WeaponFullDef, weapDef.iJamFireTime), CSPFT_MILLISECONDS}, - {"overheatWeapon", offsetof(WeaponFullDef, weapDef.overheatWeapon), CSPFT_INT}, - {"overheatRate", offsetof(WeaponFullDef, weapDef.overheatRate), CSPFT_FLOAT}, - {"cooldownRate", offsetof(WeaponFullDef, weapDef.cooldownRate), CSPFT_FLOAT}, - {"overheatEndVal", offsetof(WeaponFullDef, weapDef.overheatEndVal), CSPFT_FLOAT}, - {"coolWhileFiring", offsetof(WeaponFullDef, weapDef.coolWhileFiring), CSPFT_INT}, - {"fuelTankWeapon", offsetof(WeaponFullDef, weapDef.fuelTankWeapon), CSPFT_INT}, - {"tankLifeTime", offsetof(WeaponFullDef, weapDef.iTankLifeTime), CSPFT_MILLISECONDS}, - {"damage", offsetof(WeaponFullDef, weapDef.damage[0]), CSPFT_INT}, - {"minDamage", offsetof(WeaponFullDef, weapDef.damage[5]), CSPFT_INT}, - {"maxDamageRange", offsetof(WeaponFullDef, weapDef.damageRange[0]), CSPFT_FLOAT}, - {"minDamageRange", offsetof(WeaponFullDef, weapDef.damageRange[5]), CSPFT_FLOAT}, - {"damage2", offsetof(WeaponFullDef, weapDef.damage[1]), CSPFT_INT}, - {"damage3", offsetof(WeaponFullDef, weapDef.damage[2]), CSPFT_INT}, - {"damage4", offsetof(WeaponFullDef, weapDef.damage[3]), CSPFT_INT}, - {"damage5", offsetof(WeaponFullDef, weapDef.damage[4]), CSPFT_INT}, - {"damageRange2", offsetof(WeaponFullDef, weapDef.damageRange[1]), CSPFT_FLOAT}, - {"damageRange3", offsetof(WeaponFullDef, weapDef.damageRange[2]), CSPFT_FLOAT}, - {"damageRange4", offsetof(WeaponFullDef, weapDef.damageRange[3]), CSPFT_FLOAT}, - {"damageRange5", offsetof(WeaponFullDef, weapDef.damageRange[4]), CSPFT_FLOAT}, - {"damageDuration", offsetof(WeaponFullDef, weapDef.damageDuration), CSPFT_FLOAT}, - {"damageInterval", offsetof(WeaponFullDef, weapDef.damageInterval), CSPFT_FLOAT}, - {"playerDamage", offsetof(WeaponFullDef, weapDef.playerDamage), CSPFT_INT}, - {"meleeDamage", offsetof(WeaponFullDef, weapDef.iMeleeDamage), CSPFT_INT}, - {"minPlayerDamage", offsetof(WeaponFullDef, weapDef.minPlayerDamage), CSPFT_INT}, - {"destabilizationRateTime", offsetof(WeaponFullDef, weapDef.destabilizationRateTime), CSPFT_FLOAT}, - {"destabilizationCurvatureMax", offsetof(WeaponFullDef, weapDef.destabilizationCurvatureMax), CSPFT_FLOAT}, - {"destabilizeDistance", offsetof(WeaponFullDef, weapDef.destabilizeDistance), CSPFT_INT}, - {"fireDelay", offsetof(WeaponFullDef, weapDef.iFireDelay), CSPFT_MILLISECONDS}, - {"meleeDelay", offsetof(WeaponFullDef, weapDef.iMeleeDelay), CSPFT_MILLISECONDS}, - {"meleeChargeDelay", offsetof(WeaponFullDef, weapDef.meleeChargeDelay), CSPFT_MILLISECONDS}, - {"spinUpTime", offsetof(WeaponFullDef, weapDef.iSpinUpTime), CSPFT_MILLISECONDS}, - {"spinDownTime", offsetof(WeaponFullDef, weapDef.iSpinDownTime), CSPFT_MILLISECONDS}, - {"spinRate", offsetof(WeaponFullDef, weapDef.spinRate), CSPFT_FLOAT}, - {"spinLoopSound", offsetof(WeaponFullDef, weapDef.spinLoopSound), CSPFT_STRING}, - {"spinLoopSoundPlayer", offsetof(WeaponFullDef, weapDef.spinLoopSoundPlayer), CSPFT_STRING}, - {"startSpinSound", offsetof(WeaponFullDef, weapDef.startSpinSound), CSPFT_STRING}, - {"startSpinSoundPlayer", offsetof(WeaponFullDef, weapDef.startSpinSoundPlayer), CSPFT_STRING}, - {"stopSpinSound", offsetof(WeaponFullDef, weapDef.stopSpinSound), CSPFT_STRING}, - {"stopSpinSoundPlayer", offsetof(WeaponFullDef, weapDef.stopSpinSoundPlayer), CSPFT_STRING}, - {"applySpinPitch", offsetof(WeaponFullDef, weapDef.applySpinPitch), CSPFT_BOOL}, - {"introFireTime", offsetof(WeaponFullDef, weapDef.iIntroFireTime), CSPFT_MILLISECONDS}, - {"introFireLength", offsetof(WeaponFullDef, weapDef.iIntroFireLength), CSPFT_INT}, - {"fireTime", offsetof(WeaponFullDef, weapDef.iFireTime), CSPFT_MILLISECONDS}, - {"flourishTime", offsetof(WeaponFullDef, weapDef.iFlourishTime), CSPFT_MILLISECONDS}, - {"lastFireTime", offsetof(WeaponFullDef, weapDef.iLastFireTime), CSPFT_MILLISECONDS}, - {"rechamberTime", offsetof(WeaponFullDef, weapDef.iRechamberTime), CSPFT_MILLISECONDS}, - {"rechamberBoltTime", offsetof(WeaponFullDef, weapDef.iRechamberBoltTime), CSPFT_MILLISECONDS}, - {"holdFireTime", offsetof(WeaponFullDef, weapDef.iHoldFireTime), CSPFT_MILLISECONDS}, - {"burstFireDelay", offsetof(WeaponFullDef, weapDef.iBurstDelayTime), CSPFT_MILLISECONDS}, - {"detonateTime", offsetof(WeaponFullDef, weapDef.iDetonateTime), CSPFT_MILLISECONDS}, - {"detonateDelay", offsetof(WeaponFullDef, weapDef.iDetonateDelay), CSPFT_MILLISECONDS}, - {"meleeTime", offsetof(WeaponFullDef, weapDef.iMeleeTime), CSPFT_MILLISECONDS}, - {"meleeChargeTime", offsetof(WeaponFullDef, weapDef.meleeChargeTime), CSPFT_MILLISECONDS}, - {"reloadTime", offsetof(WeaponFullDef, weapVariantDef.iReloadTime), CSPFT_MILLISECONDS}, - {"reloadShowRocketTime", offsetof(WeaponFullDef, weapDef.reloadShowRocketTime), CSPFT_MILLISECONDS}, - {"reloadEmptyTime", offsetof(WeaponFullDef, weapVariantDef.iReloadEmptyTime), CSPFT_MILLISECONDS}, - {"reloadAddTime", offsetof(WeaponFullDef, weapDef.iReloadAddTime), CSPFT_MILLISECONDS}, - {"reloadEmptyAddTime", offsetof(WeaponFullDef, weapDef.iReloadEmptyAddTime), CSPFT_MILLISECONDS}, - {"reloadQuickAddTime", offsetof(WeaponFullDef, weapDef.iReloadQuickAddTime), CSPFT_MILLISECONDS}, - {"reloadQuickEmptyAddTime", offsetof(WeaponFullDef, weapDef.iReloadQuickEmptyAddTime), CSPFT_MILLISECONDS}, - {"reloadStartTime", offsetof(WeaponFullDef, weapDef.iReloadStartTime), CSPFT_MILLISECONDS}, - {"reloadStartAddTime", offsetof(WeaponFullDef, weapDef.iReloadStartAddTime), CSPFT_MILLISECONDS}, - {"reloadEndTime", offsetof(WeaponFullDef, weapDef.iReloadEndTime), CSPFT_MILLISECONDS}, - {"reloadQuickTime", offsetof(WeaponFullDef, weapVariantDef.iReloadQuickTime), CSPFT_MILLISECONDS}, - {"reloadQuickEmptyTime", offsetof(WeaponFullDef, weapVariantDef.iReloadQuickEmptyTime), CSPFT_MILLISECONDS}, - {"dropTime", offsetof(WeaponFullDef, weapDef.iDropTime), CSPFT_MILLISECONDS}, - {"raiseTime", offsetof(WeaponFullDef, weapDef.iRaiseTime), CSPFT_MILLISECONDS}, - {"altDropTime", offsetof(WeaponFullDef, weapDef.iAltDropTime), CSPFT_MILLISECONDS}, - {"altRaiseTime", offsetof(WeaponFullDef, weapVariantDef.iAltRaiseTime), CSPFT_MILLISECONDS}, - {"quickDropTime", offsetof(WeaponFullDef, weapDef.quickDropTime), CSPFT_MILLISECONDS}, - {"quickRaiseTime", offsetof(WeaponFullDef, weapDef.quickRaiseTime), CSPFT_MILLISECONDS}, - {"firstRaiseTime", offsetof(WeaponFullDef, weapDef.iFirstRaiseTime), CSPFT_MILLISECONDS}, - {"emptyRaiseTime", offsetof(WeaponFullDef, weapDef.iEmptyRaiseTime), CSPFT_MILLISECONDS}, - {"emptyDropTime", offsetof(WeaponFullDef, weapDef.iEmptyDropTime), CSPFT_MILLISECONDS}, - {"sprintInTime", offsetof(WeaponFullDef, weapDef.sprintInTime), CSPFT_MILLISECONDS}, - {"sprintLoopTime", offsetof(WeaponFullDef, weapDef.sprintLoopTime), CSPFT_MILLISECONDS}, - {"sprintOutTime", offsetof(WeaponFullDef, weapDef.sprintOutTime), CSPFT_MILLISECONDS}, - {"lowReadyInTime", offsetof(WeaponFullDef, weapDef.lowReadyInTime), CSPFT_MILLISECONDS}, - {"lowReadyLoopTime", offsetof(WeaponFullDef, weapDef.lowReadyLoopTime), CSPFT_MILLISECONDS}, - {"lowReadyOutTime", offsetof(WeaponFullDef, weapDef.lowReadyOutTime), CSPFT_MILLISECONDS}, - {"contFireInTime", offsetof(WeaponFullDef, weapDef.contFireInTime), CSPFT_MILLISECONDS}, - {"contFireLoopTime", offsetof(WeaponFullDef, weapDef.contFireLoopTime), CSPFT_MILLISECONDS}, - {"contFireOutTime", offsetof(WeaponFullDef, weapDef.contFireOutTime), CSPFT_MILLISECONDS}, - {"dtpInTime", offsetof(WeaponFullDef, weapDef.dtpInTime), CSPFT_MILLISECONDS}, - {"dtpLoopTime", offsetof(WeaponFullDef, weapDef.dtpLoopTime), CSPFT_MILLISECONDS}, - {"dtpOutTime", offsetof(WeaponFullDef, weapDef.dtpOutTime), CSPFT_MILLISECONDS}, - {"crawlInTime", offsetof(WeaponFullDef, weapDef.crawlInTime), CSPFT_MILLISECONDS}, - {"crawlForwardTime", offsetof(WeaponFullDef, weapDef.crawlForwardTime), CSPFT_MILLISECONDS}, - {"crawlBackTime", offsetof(WeaponFullDef, weapDef.crawlBackTime), CSPFT_MILLISECONDS}, - {"crawlRightTime", offsetof(WeaponFullDef, weapDef.crawlRightTime), CSPFT_MILLISECONDS}, - {"crawlLeftTime", offsetof(WeaponFullDef, weapDef.crawlLeftTime), CSPFT_MILLISECONDS}, - {"crawlOutFireTime", offsetof(WeaponFullDef, weapDef.crawlOutFireTime), CSPFT_MILLISECONDS}, - {"crawlOutTime", offsetof(WeaponFullDef, weapDef.crawlOutTime), CSPFT_MILLISECONDS}, - {"slideInTime", offsetof(WeaponFullDef, weapDef.slideInTime), CSPFT_MILLISECONDS}, - {"deployTime", offsetof(WeaponFullDef, weapDef.deployTime), CSPFT_MILLISECONDS}, - {"breakdownTime", offsetof(WeaponFullDef, weapDef.breakdownTime), CSPFT_MILLISECONDS}, - {"nightVisionWearTime", offsetof(WeaponFullDef, weapDef.nightVisionWearTime), CSPFT_MILLISECONDS}, - {"nightVisionWearTimeFadeOutEnd", offsetof(WeaponFullDef, weapDef.nightVisionWearTimeFadeOutEnd), CSPFT_MILLISECONDS}, - {"nightVisionWearTimePowerUp", offsetof(WeaponFullDef, weapDef.nightVisionWearTimePowerUp), CSPFT_MILLISECONDS}, - {"nightVisionRemoveTime", offsetof(WeaponFullDef, weapDef.nightVisionRemoveTime), CSPFT_MILLISECONDS}, - {"nightVisionRemoveTimePowerDown", offsetof(WeaponFullDef, weapDef.nightVisionRemoveTimePowerDown), CSPFT_MILLISECONDS}, - {"nightVisionRemoveTimeFadeInStart", offsetof(WeaponFullDef, weapDef.nightVisionRemoveTimeFadeInStart), CSPFT_MILLISECONDS}, - {"fuseTime", offsetof(WeaponFullDef, weapDef.fuseTime), CSPFT_MILLISECONDS}, - {"aifuseTime", offsetof(WeaponFullDef, weapDef.aiFuseTime), CSPFT_MILLISECONDS}, - {"lockOnRadius", offsetof(WeaponFullDef, weapDef.lockOnRadius), CSPFT_INT}, - {"lockOnSpeed", offsetof(WeaponFullDef, weapDef.lockOnSpeed), CSPFT_INT}, - {"requireLockonToFire", offsetof(WeaponFullDef, weapDef.requireLockonToFire), CSPFT_BOOL}, - {"noAdsWhenMagEmpty", offsetof(WeaponFullDef, weapDef.noAdsWhenMagEmpty), CSPFT_BOOL}, - {"avoidDropCleanup", offsetof(WeaponFullDef, weapDef.avoidDropCleanup), CSPFT_BOOL}, - {"stackFire", offsetof(WeaponFullDef, weapDef.stackFire), CSPFT_INT}, - {"stackFireSpread", offsetof(WeaponFullDef, weapDef.stackFireSpread), CSPFT_FLOAT}, - {"stackFireAccuracyDecay", offsetof(WeaponFullDef, weapDef.stackFireAccuracyDecay), CSPFT_FLOAT}, - {"stackSound", offsetof(WeaponFullDef, weapDef.stackSound), CSPFT_STRING}, - {"autoAimRange", offsetof(WeaponFullDef, weapDef.autoAimRange), CSPFT_FLOAT}, - {"aimAssistRange", offsetof(WeaponFullDef, weapDef.aimAssistRange), CSPFT_FLOAT}, - {"aimAssistRangeAds", offsetof(WeaponFullDef, weapVariantDef.fAimAssistRangeAds), CSPFT_FLOAT}, - {"mountableWeapon", offsetof(WeaponFullDef, weapDef.mountableWeapon), CSPFT_BOOL}, - {"aimPadding", offsetof(WeaponFullDef, weapDef.aimPadding), CSPFT_FLOAT}, - {"enemyCrosshairRange", offsetof(WeaponFullDef, weapDef.enemyCrosshairRange), CSPFT_FLOAT}, - {"crosshairColorChange", offsetof(WeaponFullDef, weapDef.crosshairColorChange), CSPFT_BOOL}, - {"moveSpeedScale", offsetof(WeaponFullDef, weapDef.moveSpeedScale), CSPFT_FLOAT}, - {"adsMoveSpeedScale", offsetof(WeaponFullDef, weapDef.adsMoveSpeedScale), CSPFT_FLOAT}, - {"sprintDurationScale", offsetof(WeaponFullDef, weapDef.sprintDurationScale), CSPFT_FLOAT}, - {"idleCrouchFactor", offsetof(WeaponFullDef, weapDef.fIdleCrouchFactor), CSPFT_FLOAT}, - {"idleProneFactor", offsetof(WeaponFullDef, weapDef.fIdleProneFactor), CSPFT_FLOAT}, - {"gunMaxPitch", offsetof(WeaponFullDef, weapDef.fGunMaxPitch), CSPFT_FLOAT}, - {"gunMaxYaw", offsetof(WeaponFullDef, weapDef.fGunMaxYaw), CSPFT_FLOAT}, - {"swayMaxAngle", offsetof(WeaponFullDef, weapDef.swayMaxAngle), CSPFT_FLOAT}, - {"swayLerpSpeed", offsetof(WeaponFullDef, weapDef.swayLerpSpeed), CSPFT_FLOAT}, - {"swayPitchScale", offsetof(WeaponFullDef, weapDef.swayPitchScale), CSPFT_FLOAT}, - {"swayYawScale", offsetof(WeaponFullDef, weapDef.swayYawScale), CSPFT_FLOAT}, - {"swayHorizScale", offsetof(WeaponFullDef, weapDef.swayHorizScale), CSPFT_FLOAT}, - {"swayVertScale", offsetof(WeaponFullDef, weapDef.swayVertScale), CSPFT_FLOAT}, - {"swayShellShockScale", offsetof(WeaponFullDef, weapDef.swayShellShockScale), CSPFT_FLOAT}, - {"adsSwayMaxAngle", offsetof(WeaponFullDef, weapDef.adsSwayMaxAngle), CSPFT_FLOAT}, - {"adsSwayLerpSpeed", offsetof(WeaponFullDef, weapDef.adsSwayLerpSpeed), CSPFT_FLOAT}, - {"adsSwayPitchScale", offsetof(WeaponFullDef, weapDef.adsSwayPitchScale), CSPFT_FLOAT}, - {"adsSwayYawScale", offsetof(WeaponFullDef, weapDef.adsSwayYawScale), CSPFT_FLOAT}, - {"adsSwayHorizScale", offsetof(WeaponFullDef, weapVariantDef.fAdsSwayHorizScale), CSPFT_FLOAT}, - {"adsSwayVertScale", offsetof(WeaponFullDef, weapVariantDef.fAdsSwayVertScale), CSPFT_FLOAT}, - {"meleeChargeRange", offsetof(WeaponFullDef, weapDef.meleeChargeRange), CSPFT_FLOAT}, - {"rifleBullet", offsetof(WeaponFullDef, weapDef.bRifleBullet), CSPFT_BOOL}, - {"armorPiercing", offsetof(WeaponFullDef, weapDef.armorPiercing), CSPFT_BOOL}, - {"boltAction", offsetof(WeaponFullDef, weapDef.bBoltAction), CSPFT_BOOL}, - {"shotsBeforeRechamber", offsetof(WeaponFullDef, weapDef.iShotsBeforeRechamber), CSPFT_INT}, - {"useAltTagFlash", offsetof(WeaponFullDef, weapDef.bUseAltTagFlash), CSPFT_BOOL}, - {"useAntiLagRewind", offsetof(WeaponFullDef, weapDef.bUseAntiLagRewind), CSPFT_BOOL}, - {"isCarriedKillstreakWeapon", offsetof(WeaponFullDef, weapDef.bIsCarriedKillstreakWeapon), CSPFT_BOOL}, - {"aimDownSight", offsetof(WeaponFullDef, weapDef.aimDownSight), CSPFT_BOOL}, - {"rechamberWhileAds", offsetof(WeaponFullDef, weapDef.bRechamberWhileAds), CSPFT_BOOL}, - {"reloadWhileAds", offsetof(WeaponFullDef, weapDef.bReloadWhileAds), CSPFT_BOOL}, - {"adsViewErrorMin", offsetof(WeaponFullDef, weapDef.adsViewErrorMin), CSPFT_FLOAT}, - {"adsViewErrorMax", offsetof(WeaponFullDef, weapDef.adsViewErrorMax), CSPFT_FLOAT}, - {"clipOnly", offsetof(WeaponFullDef, weapDef.bClipOnly), CSPFT_BOOL}, - {"canUseInVehicle", offsetof(WeaponFullDef, weapDef.bCanUseInVehicle), CSPFT_BOOL}, - {"noDropsOrRaises", offsetof(WeaponFullDef, weapDef.bNoDropsOrRaises), CSPFT_BOOL}, - {"cookOffHold", offsetof(WeaponFullDef, weapDef.bCookOffHold), CSPFT_BOOL}, - {"adsFire", offsetof(WeaponFullDef, weapDef.adsFireOnly), CSPFT_BOOL}, - {"cancelAutoHolsterWhenEmpty", offsetof(WeaponFullDef, weapDef.cancelAutoHolsterWhenEmpty), CSPFT_BOOL}, - {"suppressAmmoReserveDisplay", offsetof(WeaponFullDef, weapDef.suppressAmmoReserveDisplay), CSPFT_BOOL}, - {"laserSight", offsetof(WeaponFullDef, weapDef.laserSight), CSPFT_BOOL}, - {"laserSightDuringNightvision", offsetof(WeaponFullDef, weapDef.laserSightDuringNightvision), CSPFT_BOOL}, - {"bayonet", offsetof(WeaponFullDef, weapDef.bHasBayonet), CSPFT_BOOL}, - {"dualWield", offsetof(WeaponFullDef, weapDef.bDualWield), CSPFT_BOOL}, - {"hideThirdPerson", offsetof(WeaponFullDef, weapDef.bHideThirdPerson), CSPFT_BOOL}, - {"explodeOnGround", offsetof(WeaponFullDef, weapDef.bExplodeOnGround), CSPFT_BOOL}, - {"throwBack", offsetof(WeaponFullDef, weapDef.bThrowBack), CSPFT_BOOL}, - {"retrievable", offsetof(WeaponFullDef, weapDef.bRetrievable), CSPFT_BOOL}, - {"dieOnRespawn", offsetof(WeaponFullDef, weapDef.bDieOnRespawn), CSPFT_BOOL}, - {"noThirdPersonDropsOrRaises", offsetof(WeaponFullDef, weapDef.bNoThirdPersonDropsOrRaises), CSPFT_BOOL}, - {"continuousFire", offsetof(WeaponFullDef, weapDef.bContinuousFire), CSPFT_BOOL}, - {"useAsMelee", offsetof(WeaponFullDef, weapDef.bUseAsMelee), CSPFT_BOOL}, - {"antiQuickScope", offsetof(WeaponFullDef, weapVariantDef.bAntiQuickScope), CSPFT_BOOL}, - {"noPing", offsetof(WeaponFullDef, weapDef.bNoPing), CSPFT_BOOL}, - {"forceBounce", offsetof(WeaponFullDef, weapDef.bForceBounce), CSPFT_BOOL}, - {"useDroppedModelAsStowed", offsetof(WeaponFullDef, weapDef.bUseDroppedModelAsStowed), CSPFT_BOOL}, - {"noQuickDropWhenEmpty", offsetof(WeaponFullDef, weapDef.bNoQuickDropWhenEmpty), CSPFT_BOOL}, - {"keepCrosshairWhenADS", offsetof(WeaponFullDef, weapDef.bKeepCrosshairWhenADS), CSPFT_BOOL}, - {"useOnlyAltWeaoponHideTagsInAltMode", offsetof(WeaponFullDef, weapDef.bUseOnlyAltWeaoponHideTagsInAltMode), CSPFT_BOOL}, - {"altWeaponAdsOnly", offsetof(WeaponFullDef, weapDef.bAltWeaponAdsOnly), CSPFT_BOOL}, - {"altWeaponDisableSwitching", offsetof(WeaponFullDef, weapDef.bAltWeaponDisableSwitching), CSPFT_BOOL}, - {"killIcon", offsetof(WeaponFullDef, weapDef.killIcon), CSPFT_MATERIAL}, - {"killIconRatio", offsetof(WeaponFullDef, weapDef.killIconRatio), WFT_ICONRATIO_KILL}, - {"flipKillIcon", offsetof(WeaponFullDef, weapDef.flipKillIcon), CSPFT_BOOL}, - {"dpadIcon", offsetof(WeaponFullDef, weapVariantDef.dpadIcon), CSPFT_MATERIAL}, - {"dpadIconRatio", offsetof(WeaponFullDef, weapVariantDef.dpadIconRatio), WFT_ICONRATIO_DPAD}, - {"noAmmoOnDpadIcon", offsetof(WeaponFullDef, weapVariantDef.noAmmoOnDpadIcon), CSPFT_BOOL}, - {"noPartialReload", offsetof(WeaponFullDef, weapDef.bNoPartialReload), CSPFT_BOOL}, - {"segmentedReload", offsetof(WeaponFullDef, weapDef.bSegmentedReload), CSPFT_BOOL}, - {"noADSAutoReload", offsetof(WeaponFullDef, weapDef.bNoADSAutoReload), CSPFT_BOOL}, - {"reloadAmmoAdd", offsetof(WeaponFullDef, weapDef.iReloadAmmoAdd), CSPFT_INT}, - {"reloadStartAdd", offsetof(WeaponFullDef, weapDef.iReloadStartAdd), CSPFT_INT}, - {"attachmentUnique", offsetof(WeaponFullDef, weapVariantDef.szAttachmentUnique), CSPFT_STRING}, - {"altWeapon", offsetof(WeaponFullDef, weapVariantDef.szAltWeaponName), CSPFT_STRING}, - {"DualWieldWeapon", offsetof(WeaponFullDef, weapDef.szDualWieldWeaponName), CSPFT_STRING}, - {"grenadeWeapon", offsetof(WeaponFullDef, weapDef.szSpawnedGrenadeWeaponName), CSPFT_STRING}, - {"dropAmmoMin", offsetof(WeaponFullDef, weapDef.iDropAmmoMin), CSPFT_INT}, - {"dropAmmoMax", offsetof(WeaponFullDef, weapDef.iDropAmmoMax), CSPFT_INT}, - {"dropClipAmmoMin", offsetof(WeaponFullDef, weapDef.iDropClipAmmoMin), CSPFT_INT}, - {"dropClipAmmoMax", offsetof(WeaponFullDef, weapDef.iDropClipAmmoMax), CSPFT_INT}, - {"blocksProne", offsetof(WeaponFullDef, weapDef.blocksProne), CSPFT_BOOL}, - {"silenced", offsetof(WeaponFullDef, weapVariantDef.bSilenced), CSPFT_BOOL}, - {"dualMag", offsetof(WeaponFullDef, weapVariantDef.bDualMag), CSPFT_BOOL}, - {"infrared", offsetof(WeaponFullDef, weapVariantDef.bInfraRed), CSPFT_BOOL}, - {"tvguided", offsetof(WeaponFullDef, weapVariantDef.bTVGuided), CSPFT_BOOL}, - {"airburstWeapon", offsetof(WeaponFullDef, weapDef.bAirburstWeapon), CSPFT_BOOL}, - {"perks1", offsetof(WeaponFullDef, weapVariantDef.perks[0]), CSPFT_UINT}, - {"perks0", offsetof(WeaponFullDef, weapVariantDef.perks[1]), CSPFT_UINT}, - {"isRollingGrenade", offsetof(WeaponFullDef, weapDef.isRollingGrenade), CSPFT_QBOOLEAN}, - {"useBallisticPrediction", offsetof(WeaponFullDef, weapDef.useBallisticPrediction), CSPFT_QBOOLEAN}, - {"isValuable", offsetof(WeaponFullDef, weapDef.isValuable), CSPFT_QBOOLEAN}, - {"isTacticalInsertion", offsetof(WeaponFullDef, weapDef.isTacticalInsertion), CSPFT_QBOOLEAN}, - {"isReviveWeapon", offsetof(WeaponFullDef, weapDef.isReviveWeapon), CSPFT_BOOL}, - {"bUseRigidBodyOnVehicle", offsetof(WeaponFullDef, weapDef.bUseRigidBodyOnVehicle), CSPFT_BOOL}, - {"showIndicator", offsetof(WeaponFullDef, weapDef.bShowIndicator), CSPFT_BOOL}, - {"explosionRadius", offsetof(WeaponFullDef, weapDef.iExplosionRadius), CSPFT_INT}, - {"explosionRadiusMin", offsetof(WeaponFullDef, weapDef.iExplosionRadiusMin), CSPFT_INT}, - {"indicatorRadius", offsetof(WeaponFullDef, weapDef.iIndicatorRadius), CSPFT_INT}, - {"explosionInnerDamage", offsetof(WeaponFullDef, weapDef.iExplosionInnerDamage), CSPFT_INT}, - {"explosionOuterDamage", offsetof(WeaponFullDef, weapDef.iExplosionOuterDamage), CSPFT_INT}, - {"damageConeAngle", offsetof(WeaponFullDef, weapDef.damageConeAngle), CSPFT_FLOAT}, - {"projectileSpeed", offsetof(WeaponFullDef, weapDef.iProjectileSpeed), CSPFT_INT}, - {"projectileSpeedRelativeUp", offsetof(WeaponFullDef, weapDef.iProjectileSpeedRelativeUp), CSPFT_INT}, - {"projectileSpeedUp", offsetof(WeaponFullDef, weapDef.iProjectileSpeedUp), CSPFT_INT}, - {"projectileSpeedForward", offsetof(WeaponFullDef, weapDef.iProjectileSpeedForward), CSPFT_INT}, - {"projectileTakeParentVel", offsetof(WeaponFullDef, weapDef.fProjectileTakeParentVelocity), CSPFT_FLOAT}, - {"projectileActivateDist", offsetof(WeaponFullDef, weapDef.iProjectileActivateDist), CSPFT_INT}, - {"projectileLifetime", offsetof(WeaponFullDef, weapDef.projLifetime), CSPFT_FLOAT}, - {"timeToAccelerate", offsetof(WeaponFullDef, weapDef.timeToAccelerate), CSPFT_FLOAT}, - {"projectileCurvature", offsetof(WeaponFullDef, weapDef.projectileCurvature), CSPFT_FLOAT}, - {"projectileModel", offsetof(WeaponFullDef, weapDef.projectileModel), CSPFT_XMODEL}, - {"projExplosionType", offsetof(WeaponFullDef, weapDef.projExplosion), WFT_PROJ_EXPLOSION}, - {"projExplosionEffect", offsetof(WeaponFullDef, weapDef.projExplosionEffect), CSPFT_FX}, - {"projExplosionEffectForceNormalUp", offsetof(WeaponFullDef, weapDef.projExplosionEffectForceNormalUp), CSPFT_BOOL}, - {"projExplosionEffect2", offsetof(WeaponFullDef, weapDef.projExplosionEffect2), CSPFT_FX}, - {"projExplosionEffect2ForceNormalUp", offsetof(WeaponFullDef, weapDef.projExplosionEffect2ForceNormalUp), CSPFT_BOOL}, - {"projExplosionEffect3", offsetof(WeaponFullDef, weapDef.projExplosionEffect3), CSPFT_FX}, - {"projExplosionEffect3ForceNormalUp", offsetof(WeaponFullDef, weapDef.projExplosionEffect3ForceNormalUp), CSPFT_BOOL}, - {"projExplosionEffect4", offsetof(WeaponFullDef, weapDef.projExplosionEffect4), CSPFT_FX}, - {"projExplosionEffect4ForceNormalUp", offsetof(WeaponFullDef, weapDef.projExplosionEffect4ForceNormalUp), CSPFT_BOOL}, - {"projExplosionEffect5", offsetof(WeaponFullDef, weapDef.projExplosionEffect5), CSPFT_FX}, - {"projExplosionEffect5ForceNormalUp", offsetof(WeaponFullDef, weapDef.projExplosionEffect5ForceNormalUp), CSPFT_BOOL}, - {"projExplosionSound", offsetof(WeaponFullDef, weapDef.projExplosionSound), CSPFT_STRING}, - {"projDudEffect", offsetof(WeaponFullDef, weapDef.projDudEffect), CSPFT_FX}, - {"projDudSound", offsetof(WeaponFullDef, weapDef.projDudSound), CSPFT_STRING}, - {"projImpactExplode", offsetof(WeaponFullDef, weapDef.bProjImpactExplode), CSPFT_BOOL}, - {"sentientImpactExplode", offsetof(WeaponFullDef, weapDef.bProjSentientImpactExplode), CSPFT_BOOL}, - {"explodeWhenStationary", offsetof(WeaponFullDef, weapDef.bProjExplodeWhenStationary), CSPFT_BOOL}, - {"bulletImpactExplode", offsetof(WeaponFullDef, weapDef.bBulletImpactExplode), CSPFT_BOOL}, - {"mortarShellSound", offsetof(WeaponFullDef, weapDef.mortarShellSound), CSPFT_STRING}, - {"tankShellSound", offsetof(WeaponFullDef, weapDef.tankShellSound), CSPFT_STRING}, - {"stickiness", offsetof(WeaponFullDef, weapDef.stickiness), WFT_STICKINESS}, - {"rotateType", offsetof(WeaponFullDef, weapDef.rotateType), WFT_ROTATETYPE}, - {"hasDetonator", offsetof(WeaponFullDef, weapDef.hasDetonator), CSPFT_BOOL}, - {"plantable", offsetof(WeaponFullDef, weapDef.plantable), CSPFT_BOOL}, - {"timedDetonation", offsetof(WeaponFullDef, weapDef.timedDetonation), CSPFT_BOOL}, - {"noCrumpleMissile", offsetof(WeaponFullDef, weapDef.bNoCrumpleMissile), CSPFT_BOOL}, - {"rotate", offsetof(WeaponFullDef, weapDef.rotate), CSPFT_BOOL}, - {"keepRolling", offsetof(WeaponFullDef, weapDef.bKeepRolling), CSPFT_BOOL}, - {"holdButtonToThrow", offsetof(WeaponFullDef, weapDef.holdButtonToThrow), CSPFT_BOOL}, - {"offhandHoldIsCancelable", offsetof(WeaponFullDef, weapDef.offhandHoldIsCancelable), CSPFT_BOOL}, - {"freezeMovementWhenFiring", offsetof(WeaponFullDef, weapDef.freezeMovementWhenFiring), CSPFT_BOOL}, - {"lowAmmoWarningThreshold", offsetof(WeaponFullDef, weapDef.lowAmmoWarningThreshold), CSPFT_FLOAT}, - {"explosionTag", offsetof(WeaponFullDef, weapDef.explosionTag), WFT_EXPLOSION_TAG}, - {"bDisallowAtMatchStart", offsetof(WeaponFullDef, weapDef.bDisallowAtMatchStart), CSPFT_BOOL}, - {"isCameraSensor", offsetof(WeaponFullDef, weapDef.isCameraSensor), CSPFT_BOOL}, - {"isAcousticSensor", offsetof(WeaponFullDef, weapDef.isAcousticSensor), CSPFT_BOOL}, - {"isLaserSensor", offsetof(WeaponFullDef, weapDef.isLaserSensor), CSPFT_BOOL}, - {"isHoldUseGrenade", offsetof(WeaponFullDef, weapDef.isHoldUseGrenade), CSPFT_BOOL}, - {"parallelDefaultBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_DEFAULT]), CSPFT_FLOAT}, - {"parallelAsphaltBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_ASPHALT]), CSPFT_FLOAT}, - {"parallelBarkBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_BARK]), CSPFT_FLOAT}, - {"parallelBrickBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_BRICK]), CSPFT_FLOAT}, - {"parallelCarpetBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_CARPET]), CSPFT_FLOAT}, - {"parallelCeramicBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_CERAMIC]), CSPFT_FLOAT}, - {"parallelClothBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_CLOTH]), CSPFT_FLOAT}, - {"parallelConcreteBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_CONCRETE]), CSPFT_FLOAT}, - {"parallelCushionBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_CUSHION]), CSPFT_FLOAT}, - {"parallelDirtBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_DIRT]), CSPFT_FLOAT}, - {"parallelFleshBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_FLESH]), CSPFT_FLOAT}, - {"parallelFoliageBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_FOLIAGE]), CSPFT_FLOAT}, - {"parallelFruitBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_FRUIT]), CSPFT_FLOAT}, - {"parallelGlassBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_GLASS]), CSPFT_FLOAT}, - {"parallelGrassBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_GRASS]), CSPFT_FLOAT}, - {"parallelGravelBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_GRAVEL]), CSPFT_FLOAT}, - {"parallelIceBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_ICE]), CSPFT_FLOAT}, - {"parallelMetalBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_METAL]), CSPFT_FLOAT}, - {"parallelMudBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_MUD]), CSPFT_FLOAT}, - {"parallelPaintedMetalBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_PAINTED_METAL]), CSPFT_FLOAT}, - {"parallelPaperBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_PAPER]), CSPFT_FLOAT}, - {"parallelPlasterBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_PLASTER]), CSPFT_FLOAT}, - {"parallelPlasticBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_PLASTIC]), CSPFT_FLOAT}, - {"parallelRockBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_ROCK]), CSPFT_FLOAT}, - {"parallelRubberBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_RUBBER]), CSPFT_FLOAT}, - {"parallelSandBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_SAND]), CSPFT_FLOAT}, - {"parallelSnowBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_SNOW]), CSPFT_FLOAT}, - {"parallelWaterBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_WATER]), CSPFT_FLOAT}, - {"parallelWoodBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_WOOD]), CSPFT_FLOAT}, - {"parallelRiotShieldBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_RIOT_SHIELD]), CSPFT_FLOAT}, - {"perpendicularDefaultBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_DEFAULT]), CSPFT_FLOAT}, - {"perpendicularAsphaltBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_ASPHALT]), CSPFT_FLOAT}, - {"perpendicularBarkBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_BARK]), CSPFT_FLOAT}, - {"perpendicularBrickBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_BRICK]), CSPFT_FLOAT}, - {"perpendicularCarpetBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_CARPET]), CSPFT_FLOAT}, - {"perpendicularCeramicBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_CERAMIC]), CSPFT_FLOAT}, - {"perpendicularClothBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_CLOTH]), CSPFT_FLOAT}, - {"perpendicularConcreteBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_CONCRETE]), CSPFT_FLOAT}, - {"perpendicularCushionBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_CUSHION]), CSPFT_FLOAT}, - {"perpendicularDirtBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_DIRT]), CSPFT_FLOAT}, - {"perpendicularFleshBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_FLESH]), CSPFT_FLOAT}, - {"perpendicularFoliageBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_FOLIAGE]), CSPFT_FLOAT}, - {"perpendicularFruitBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_FRUIT]), CSPFT_FLOAT}, - {"perpendicularGlassBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_GLASS]), CSPFT_FLOAT}, - {"perpendicularGrassBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_GRASS]), CSPFT_FLOAT}, - {"perpendicularGravelBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_GRAVEL]), CSPFT_FLOAT}, - {"perpendicularIceBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_ICE]), CSPFT_FLOAT}, - {"perpendicularMetalBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_METAL]), CSPFT_FLOAT}, - {"perpendicularMudBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_MUD]), CSPFT_FLOAT}, - {"perpendicularPaintedMetalBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_PAINTED_METAL]), CSPFT_FLOAT}, - {"perpendicularPaperBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_PAPER]), CSPFT_FLOAT}, - {"perpendicularPlasterBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_PLASTER]), CSPFT_FLOAT}, - {"perpendicularPlasticBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_PLASTIC]), CSPFT_FLOAT}, - {"perpendicularRockBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_ROCK]), CSPFT_FLOAT}, - {"perpendicularRubberBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_RUBBER]), CSPFT_FLOAT}, - {"perpendicularSandBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_SAND]), CSPFT_FLOAT}, - {"perpendicularSnowBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_SNOW]), CSPFT_FLOAT}, - {"perpendicularWaterBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_WATER]), CSPFT_FLOAT}, - {"perpendicularWoodBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_WOOD]), CSPFT_FLOAT}, - {"perpendicularRiotShieldBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_RIOT_SHIELD]), CSPFT_FLOAT}, - {"projTrailEffect", offsetof(WeaponFullDef, weapDef.projTrailEffect), CSPFT_FX}, - {"projectileRed", offsetof(WeaponFullDef, weapDef.vProjectileColor.x), CSPFT_FLOAT}, - {"projectileGreen", offsetof(WeaponFullDef, weapDef.vProjectileColor.y), CSPFT_FLOAT}, - {"projectileBlue", offsetof(WeaponFullDef, weapDef.vProjectileColor.z), CSPFT_FLOAT}, - {"guidedMissileType", offsetof(WeaponFullDef, weapDef.guidedMissileType), WFT_GUIDED_MISSILE_TYPE}, - {"maxSteeringAccel", offsetof(WeaponFullDef, weapDef.maxSteeringAccel), CSPFT_FLOAT}, - {"projIgnitionDelay", offsetof(WeaponFullDef, weapDef.projIgnitionDelay), CSPFT_INT}, - {"projIgnitionEffect", offsetof(WeaponFullDef, weapDef.projIgnitionEffect), CSPFT_FX}, - {"projIgnitionSound", offsetof(WeaponFullDef, weapDef.projIgnitionSound), CSPFT_STRING}, - {"tagFx_preparationEffect", offsetof(WeaponFullDef, weapDef.tagFx_preparationEffect), CSPFT_FX}, - {"tagFlash_preparationEffect", offsetof(WeaponFullDef, weapDef.tagFlash_preparationEffect), CSPFT_FX}, - {"adsTransInTime", offsetof(WeaponFullDef, weapVariantDef.iAdsTransInTime), CSPFT_MILLISECONDS}, - {"adsTransOutTime", offsetof(WeaponFullDef, weapVariantDef.iAdsTransOutTime), CSPFT_MILLISECONDS}, - {"adsIdleAmount", offsetof(WeaponFullDef, weapDef.fAdsIdleAmount), CSPFT_FLOAT}, - {"adsIdleSpeed", offsetof(WeaponFullDef, weapDef.adsIdleSpeed), CSPFT_FLOAT}, - {"adsZoomFov1", offsetof(WeaponFullDef, weapVariantDef.fAdsZoomFov1), CSPFT_FLOAT}, - {"adsZoomFov2", offsetof(WeaponFullDef, weapVariantDef.fAdsZoomFov2), CSPFT_FLOAT}, - {"adsZoomFov3", offsetof(WeaponFullDef, weapVariantDef.fAdsZoomFov3), CSPFT_FLOAT}, - {"adsZoomInFrac", offsetof(WeaponFullDef, weapVariantDef.fAdsZoomInFrac), CSPFT_FLOAT}, - {"adsZoomOutFrac", offsetof(WeaponFullDef, weapVariantDef.fAdsZoomOutFrac), CSPFT_FLOAT}, - {"adsOverlayShader", offsetof(WeaponFullDef, weapVariantDef.overlayMaterial), CSPFT_MATERIAL_STREAM}, - {"adsOverlayShaderLowRes", offsetof(WeaponFullDef, weapVariantDef.overlayMaterialLowRes), CSPFT_MATERIAL_STREAM}, - {"adsOverlayReticle", offsetof(WeaponFullDef, weapDef.overlayReticle), WFT_OVERLAYRETICLE}, - {"adsOverlayInterface", offsetof(WeaponFullDef, weapDef.overlayInterface), WFT_OVERLAYINTERFACE}, - {"adsOverlayWidth", offsetof(WeaponFullDef, weapDef.overlayWidth), CSPFT_FLOAT}, - {"adsOverlayHeight", offsetof(WeaponFullDef, weapDef.overlayHeight), CSPFT_FLOAT}, - {"adsOverlayAlphaScale", offsetof(WeaponFullDef, weapVariantDef.fOverlayAlphaScale), CSPFT_FLOAT}, - {"adsBobFactor", offsetof(WeaponFullDef, weapDef.fAdsBobFactor), CSPFT_FLOAT}, - {"adsViewBobMult", offsetof(WeaponFullDef, weapDef.fAdsViewBobMult), CSPFT_FLOAT}, - {"holdBreathToSteady", offsetof(WeaponFullDef, weapDef.bHoldBreathToSteady), CSPFT_BOOL}, - {"adsAimPitch", offsetof(WeaponFullDef, weapDef.fAdsAimPitch), CSPFT_FLOAT}, - {"adsCrosshairInFrac", offsetof(WeaponFullDef, weapDef.fAdsCrosshairInFrac), CSPFT_FLOAT}, - {"adsCrosshairOutFrac", offsetof(WeaponFullDef, weapDef.fAdsCrosshairOutFrac), CSPFT_FLOAT}, - {"adsReloadTransTime", offsetof(WeaponFullDef, weapDef.iPositionReloadTransTime), CSPFT_MILLISECONDS}, - {"adsGunKickReducedKickBullets", offsetof(WeaponFullDef, weapDef.adsGunKickReducedKickBullets), CSPFT_INT}, - {"adsGunKickReducedKickPercent", offsetof(WeaponFullDef, weapDef.adsGunKickReducedKickPercent), CSPFT_FLOAT}, - {"adsGunKickPitchMin", offsetof(WeaponFullDef, weapDef.fAdsGunKickPitchMin), CSPFT_FLOAT}, - {"adsGunKickPitchMax", offsetof(WeaponFullDef, weapDef.fAdsGunKickPitchMax), CSPFT_FLOAT}, - {"adsGunKickYawMin", offsetof(WeaponFullDef, weapDef.fAdsGunKickYawMin), CSPFT_FLOAT}, - {"adsGunKickYawMax", offsetof(WeaponFullDef, weapDef.fAdsGunKickYawMax), CSPFT_FLOAT}, - {"adsGunKickAccel", offsetof(WeaponFullDef, weapDef.fAdsGunKickAccel), CSPFT_FLOAT}, - {"adsGunKickSpeedMax", offsetof(WeaponFullDef, weapDef.fAdsGunKickSpeedMax), CSPFT_FLOAT}, - {"adsGunKickSpeedDecay", offsetof(WeaponFullDef, weapDef.fAdsGunKickSpeedDecay), CSPFT_FLOAT}, - {"adsGunKickStaticDecay", offsetof(WeaponFullDef, weapDef.fAdsGunKickStaticDecay), CSPFT_FLOAT}, - {"adsViewKickPitchMin", offsetof(WeaponFullDef, weapDef.fAdsViewKickPitchMin), CSPFT_FLOAT}, - {"adsViewKickPitchMax", offsetof(WeaponFullDef, weapDef.fAdsViewKickPitchMax), CSPFT_FLOAT}, - {"adsViewKickMinMagnitude", offsetof(WeaponFullDef, weapDef.fAdsViewKickMinMagnitude), CSPFT_FLOAT}, - {"adsViewKickYawMin", offsetof(WeaponFullDef, weapDef.fAdsViewKickYawMin), CSPFT_FLOAT}, - {"adsViewKickYawMax", offsetof(WeaponFullDef, weapDef.fAdsViewKickYawMax), CSPFT_FLOAT}, - {"adsRecoilReductionRate", offsetof(WeaponFullDef, weapDef.fAdsRecoilReductionRate), CSPFT_FLOAT}, - {"adsRecoilReductionLimit", offsetof(WeaponFullDef, weapDef.fAdsRecoilReductionLimit), CSPFT_FLOAT}, - {"adsRecoilReturnRate", offsetof(WeaponFullDef, weapDef.fAdsRecoilReturnRate), CSPFT_FLOAT}, - {"adsViewKickCenterSpeed", offsetof(WeaponFullDef, weapVariantDef.fAdsViewKickCenterSpeed), CSPFT_FLOAT}, - {"adsViewKickCenterDuckedScale", offsetof(WeaponFullDef, weapDef.fAdsViewKickCenterDuckedScale), CSPFT_FLOAT}, - {"adsViewKickCenterProneScale", offsetof(WeaponFullDef, weapDef.fAdsViewKickCenterProneScale), CSPFT_FLOAT}, - {"adsSpread", offsetof(WeaponFullDef, weapDef.fAdsSpread), CSPFT_FLOAT}, - {"guidedMissileType", offsetof(WeaponFullDef, weapDef.guidedMissileType), WFT_GUIDED_MISSILE_TYPE}, - {"antiQuickScopeTime", offsetof(WeaponFullDef, weapDef.fAntiQuickScopeTime), CSPFT_FLOAT}, - {"antiQuickScopeScale", offsetof(WeaponFullDef, weapDef.fAntiQuickScopeScale), CSPFT_FLOAT}, - {"antiQuickScopeSpreadMultiplier", offsetof(WeaponFullDef, weapDef.fAntiQuickScopeSpreadMultiplier), CSPFT_FLOAT}, - {"antiQuickScopeSpreadMax", offsetof(WeaponFullDef, weapDef.fAntiQuickScopeSpreadMax), CSPFT_FLOAT}, - {"antiQuickScopeSwayFactor", offsetof(WeaponFullDef, weapDef.fAntiQuickScopeSwayFactor), CSPFT_FLOAT}, - {"hipSpreadStandMin", offsetof(WeaponFullDef, weapDef.fHipSpreadStandMin), CSPFT_FLOAT}, - {"hipSpreadDuckedMin", offsetof(WeaponFullDef, weapDef.fHipSpreadDuckedMin), CSPFT_FLOAT}, - {"hipSpreadProneMin", offsetof(WeaponFullDef, weapDef.fHipSpreadProneMin), CSPFT_FLOAT}, - {"hipSpreadMax", offsetof(WeaponFullDef, weapDef.hipSpreadStandMax), CSPFT_FLOAT}, - {"hipSpreadDuckedMax", offsetof(WeaponFullDef, weapDef.hipSpreadDuckedMax), CSPFT_FLOAT}, - {"hipSpreadProneMax", offsetof(WeaponFullDef, weapDef.hipSpreadProneMax), CSPFT_FLOAT}, - {"hipSpreadDecayRate", offsetof(WeaponFullDef, weapDef.fHipSpreadDecayRate), CSPFT_FLOAT}, - {"hipSpreadFireAdd", offsetof(WeaponFullDef, weapDef.fHipSpreadFireAdd), CSPFT_FLOAT}, - {"hipSpreadTurnAdd", offsetof(WeaponFullDef, weapDef.fHipSpreadTurnAdd), CSPFT_FLOAT}, - {"hipSpreadMoveAdd", offsetof(WeaponFullDef, weapDef.fHipSpreadMoveAdd), CSPFT_FLOAT}, - {"hipSpreadDuckedDecay", offsetof(WeaponFullDef, weapDef.fHipSpreadDuckedDecay), CSPFT_FLOAT}, - {"hipSpreadProneDecay", offsetof(WeaponFullDef, weapDef.fHipSpreadProneDecay), CSPFT_FLOAT}, - {"hipReticleSidePos", offsetof(WeaponFullDef, weapDef.fHipReticleSidePos), CSPFT_FLOAT}, - {"hipIdleAmount", offsetof(WeaponFullDef, weapDef.fHipIdleAmount), CSPFT_FLOAT}, - {"hipIdleSpeed", offsetof(WeaponFullDef, weapDef.hipIdleSpeed), CSPFT_FLOAT}, - {"hipGunKickReducedKickBullets", offsetof(WeaponFullDef, weapDef.hipGunKickReducedKickBullets), CSPFT_INT}, - {"hipGunKickReducedKickPercent", offsetof(WeaponFullDef, weapDef.hipGunKickReducedKickPercent), CSPFT_FLOAT}, - {"hipGunKickPitchMin", offsetof(WeaponFullDef, weapDef.fHipGunKickPitchMin), CSPFT_FLOAT}, - {"hipGunKickPitchMax", offsetof(WeaponFullDef, weapDef.fHipGunKickPitchMax), CSPFT_FLOAT}, - {"hipGunKickYawMin", offsetof(WeaponFullDef, weapDef.fHipGunKickYawMin), CSPFT_FLOAT}, - {"hipGunKickYawMax", offsetof(WeaponFullDef, weapDef.fHipGunKickYawMax), CSPFT_FLOAT}, - {"hipGunKickAccel", offsetof(WeaponFullDef, weapDef.fHipGunKickAccel), CSPFT_FLOAT}, - {"hipGunKickSpeedMax", offsetof(WeaponFullDef, weapDef.fHipGunKickSpeedMax), CSPFT_FLOAT}, - {"hipGunKickSpeedDecay", offsetof(WeaponFullDef, weapDef.fHipGunKickSpeedDecay), CSPFT_FLOAT}, - {"hipGunKickStaticDecay", offsetof(WeaponFullDef, weapDef.fHipGunKickStaticDecay), CSPFT_FLOAT}, - {"hipViewKickPitchMin", offsetof(WeaponFullDef, weapDef.fHipViewKickPitchMin), CSPFT_FLOAT}, - {"hipViewKickPitchMax", offsetof(WeaponFullDef, weapDef.fHipViewKickPitchMax), CSPFT_FLOAT}, - {"hipViewKickMinMagnitude", offsetof(WeaponFullDef, weapDef.fHipViewKickMinMagnitude), CSPFT_FLOAT}, - {"hipViewKickYawMin", offsetof(WeaponFullDef, weapDef.fHipViewKickYawMin), CSPFT_FLOAT}, - {"hipViewKickYawMax", offsetof(WeaponFullDef, weapDef.fHipViewKickYawMax), CSPFT_FLOAT}, - {"hipViewKickCenterSpeed", offsetof(WeaponFullDef, weapVariantDef.fHipViewKickCenterSpeed), CSPFT_FLOAT}, - {"leftArc", offsetof(WeaponFullDef, weapDef.leftArc), CSPFT_FLOAT}, - {"rightArc", offsetof(WeaponFullDef, weapDef.rightArc), CSPFT_FLOAT}, - {"topArc", offsetof(WeaponFullDef, weapDef.topArc), CSPFT_FLOAT}, - {"bottomArc", offsetof(WeaponFullDef, weapDef.bottomArc), CSPFT_FLOAT}, - {"accuracy", offsetof(WeaponFullDef, weapDef.accuracy), CSPFT_FLOAT}, - {"aiSpread", offsetof(WeaponFullDef, weapDef.aiSpread), CSPFT_FLOAT}, - {"playerSpread", offsetof(WeaponFullDef, weapDef.playerSpread), CSPFT_FLOAT}, - {"maxVertTurnSpeed", offsetof(WeaponFullDef, weapDef.maxTurnSpeed[0]), CSPFT_FLOAT}, - {"maxHorTurnSpeed", offsetof(WeaponFullDef, weapDef.maxTurnSpeed[1]), CSPFT_FLOAT}, - {"minVertTurnSpeed", offsetof(WeaponFullDef, weapDef.minTurnSpeed[0]), CSPFT_FLOAT}, - {"minHorTurnSpeed", offsetof(WeaponFullDef, weapDef.minTurnSpeed[1]), CSPFT_FLOAT}, - {"pitchConvergenceTime", offsetof(WeaponFullDef, weapDef.pitchConvergenceTime), CSPFT_FLOAT}, - {"yawConvergenceTime", offsetof(WeaponFullDef, weapDef.yawConvergenceTime), CSPFT_FLOAT}, - {"suppressionTime", offsetof(WeaponFullDef, weapDef.suppressTime), CSPFT_FLOAT}, - {"maxRange", offsetof(WeaponFullDef, weapDef.maxRange), CSPFT_FLOAT}, - {"animHorRotateInc", offsetof(WeaponFullDef, weapDef.fAnimHorRotateInc), CSPFT_FLOAT}, - {"playerPositionDist", offsetof(WeaponFullDef, weapDef.fPlayerPositionDist), CSPFT_FLOAT}, - {"stance", offsetof(WeaponFullDef, weapDef.stance), WFT_STANCE}, - {"useHintString", offsetof(WeaponFullDef, weapDef.szUseHintString), CSPFT_STRING}, - {"dropHintString", offsetof(WeaponFullDef, weapDef.dropHintString), CSPFT_STRING}, - {"horizViewJitter", offsetof(WeaponFullDef, weapDef.horizViewJitter), CSPFT_FLOAT}, - {"vertViewJitter", offsetof(WeaponFullDef, weapDef.vertViewJitter), CSPFT_FLOAT}, - {"cameraShakeScale", offsetof(WeaponFullDef, weapDef.cameraShakeScale), CSPFT_FLOAT}, - {"cameraShakeDuration", offsetof(WeaponFullDef, weapDef.cameraShakeDuration), CSPFT_INT}, - {"cameraShakeRadius", offsetof(WeaponFullDef, weapDef.cameraShakeRadius), CSPFT_INT}, - {"explosionCameraShakeScale", offsetof(WeaponFullDef, weapDef.explosionCameraShakeScale), CSPFT_FLOAT}, - {"explosionCameraShakeDuration", offsetof(WeaponFullDef, weapDef.explosionCameraShakeDuration), CSPFT_INT}, - {"explosionCameraShakeRadius", offsetof(WeaponFullDef, weapDef.explosionCameraShakeRadius), CSPFT_INT}, - {"fightDist", offsetof(WeaponFullDef, weapDef.fightDist), CSPFT_FLOAT}, - {"maxDist", offsetof(WeaponFullDef, weapDef.maxDist), CSPFT_FLOAT}, - {"aiVsAiAccuracyGraph", offsetof(WeaponFullDef, weapDef.accuracyGraphName0), CSPFT_STRING}, - {"aiVsPlayerAccuracyGraph", offsetof(WeaponFullDef, weapDef.accuracyGraphName1), CSPFT_STRING}, - {"locNone", offsetof(WeaponFullDef, locationDamageMultipliers[HITLOC_NONE]), CSPFT_FLOAT}, - {"locHelmet", offsetof(WeaponFullDef, locationDamageMultipliers[HITLOC_HELMET]), CSPFT_FLOAT}, - {"locHead", offsetof(WeaponFullDef, locationDamageMultipliers[HITLOC_HEAD]), CSPFT_FLOAT}, - {"locNeck", offsetof(WeaponFullDef, locationDamageMultipliers[HITLOC_NECK]), CSPFT_FLOAT}, - {"locTorsoUpper", offsetof(WeaponFullDef, locationDamageMultipliers[HITLOC_TORSO_UPR]), CSPFT_FLOAT}, - {"locTorsoMid", offsetof(WeaponFullDef, locationDamageMultipliers[HITLOC_TORSO_MID]), CSPFT_FLOAT}, - {"locTorsoLower", offsetof(WeaponFullDef, locationDamageMultipliers[HITLOC_TORSO_LWR]), CSPFT_FLOAT}, - {"locRightArmUpper", offsetof(WeaponFullDef, locationDamageMultipliers[HITLOC_R_ARM_UPR]), CSPFT_FLOAT}, - {"locRightArmLower", offsetof(WeaponFullDef, locationDamageMultipliers[HITLOC_R_ARM_LWR]), CSPFT_FLOAT}, - {"locRightHand", offsetof(WeaponFullDef, locationDamageMultipliers[HITLOC_R_HAND]), CSPFT_FLOAT}, - {"locLeftArmUpper", offsetof(WeaponFullDef, locationDamageMultipliers[HITLOC_L_ARM_UPR]), CSPFT_FLOAT}, - {"locLeftArmLower", offsetof(WeaponFullDef, locationDamageMultipliers[HITLOC_L_ARM_LWR]), CSPFT_FLOAT}, - {"locLeftHand", offsetof(WeaponFullDef, locationDamageMultipliers[HITLOC_L_HAND]), CSPFT_FLOAT}, - {"locRightLegUpper", offsetof(WeaponFullDef, locationDamageMultipliers[HITLOC_R_LEG_UPR]), CSPFT_FLOAT}, - {"locRightLegLower", offsetof(WeaponFullDef, locationDamageMultipliers[HITLOC_R_LEG_LWR]), CSPFT_FLOAT}, - {"locRightFoot", offsetof(WeaponFullDef, locationDamageMultipliers[HITLOC_R_FOOT]), CSPFT_FLOAT}, - {"locLeftLegUpper", offsetof(WeaponFullDef, locationDamageMultipliers[HITLOC_L_LEG_UPR]), CSPFT_FLOAT}, - {"locLeftLegLower", offsetof(WeaponFullDef, locationDamageMultipliers[HITLOC_L_LEG_LWR]), CSPFT_FLOAT}, - {"locLeftFoot", offsetof(WeaponFullDef, locationDamageMultipliers[HITLOC_L_FOOT]), CSPFT_FLOAT}, - {"locGun", offsetof(WeaponFullDef, locationDamageMultipliers[HITLOC_GUN]), CSPFT_FLOAT}, - {"fireRumble", offsetof(WeaponFullDef, weapDef.fireRumble), CSPFT_STRING}, - {"meleeImpactRumble", offsetof(WeaponFullDef, weapDef.meleeImpactRumble), CSPFT_STRING}, - {"reloadRumble", offsetof(WeaponFullDef, weapDef.reloadRumble), CSPFT_STRING}, - {"explosionRumble", offsetof(WeaponFullDef, weapDef.explosionRumble), CSPFT_STRING}, - {"tracerType", offsetof(WeaponFullDef, weapDef.tracerType), CSPFT_TRACER}, - {"enemyTracerType", offsetof(WeaponFullDef, weapDef.enemyTracerType), CSPFT_TRACER}, - {"adsDofStart", offsetof(WeaponFullDef, weapDef.adsDofStart), CSPFT_FLOAT}, - {"adsDofEnd", offsetof(WeaponFullDef, weapDef.adsDofEnd), CSPFT_FLOAT}, - {"scanSpeed", offsetof(WeaponFullDef, weapDef.scanSpeed), CSPFT_FLOAT}, - {"scanAccel", offsetof(WeaponFullDef, weapDef.scanAccel), CSPFT_FLOAT}, - {"scanPauseTime", offsetof(WeaponFullDef, weapDef.scanPauseTime), CSPFT_MILLISECONDS}, - {"flameTableFirstPerson", offsetof(WeaponFullDef, weapDef.flameTableFirstPerson), CSPFT_STRING}, - {"flameTableThirdPerson", offsetof(WeaponFullDef, weapDef.flameTableThirdPerson), CSPFT_STRING}, - {"mmsWeapon", offsetof(WeaponFullDef, weapVariantDef.mmsWeapon), CSPFT_BOOL}, - {"mmsInScope", offsetof(WeaponFullDef, weapVariantDef.mmsInScope), CSPFT_BOOL}, - {"mmsFOV", offsetof(WeaponFullDef, weapVariantDef.mmsFOV), CSPFT_FLOAT}, - {"mmsAspect", offsetof(WeaponFullDef, weapVariantDef.mmsAspect), CSPFT_FLOAT}, - {"mmsMaxDist", offsetof(WeaponFullDef, weapVariantDef.mmsMaxDist), CSPFT_FLOAT}, - {"ikLeftHandIdlePosF", offsetof(WeaponFullDef, weapVariantDef.ikLeftHandIdlePos.x), CSPFT_FLOAT}, - {"ikLeftHandIdlePosR", offsetof(WeaponFullDef, weapVariantDef.ikLeftHandIdlePos.y), CSPFT_FLOAT}, - {"ikLeftHandIdlePosU", offsetof(WeaponFullDef, weapVariantDef.ikLeftHandIdlePos.z), CSPFT_FLOAT}, - {"ikLeftHandOffsetF", offsetof(WeaponFullDef, weapVariantDef.ikLeftHandOffset.x), CSPFT_FLOAT}, - {"ikLeftHandOffsetR", offsetof(WeaponFullDef, weapVariantDef.ikLeftHandOffset.y), CSPFT_FLOAT}, - {"ikLeftHandOffsetU", offsetof(WeaponFullDef, weapVariantDef.ikLeftHandOffset.z), CSPFT_FLOAT}, - {"ikLeftHandRotationP", offsetof(WeaponFullDef, weapVariantDef.ikLeftHandRotation.x), CSPFT_FLOAT}, - {"ikLeftHandRotationY", offsetof(WeaponFullDef, weapVariantDef.ikLeftHandRotation.y), CSPFT_FLOAT}, - {"ikLeftHandRotationR", offsetof(WeaponFullDef, weapVariantDef.ikLeftHandRotation.z), CSPFT_FLOAT}, - {"usingLeftHandProneIK", offsetof(WeaponFullDef, weapVariantDef.bUsingLeftHandProneIK), CSPFT_BOOL}, - {"ikLeftHandProneOffsetF", offsetof(WeaponFullDef, weapVariantDef.ikLeftHandProneOffset.x), CSPFT_FLOAT}, - {"ikLeftHandProneOffsetR", offsetof(WeaponFullDef, weapVariantDef.ikLeftHandProneOffset.y), CSPFT_FLOAT}, - {"ikLeftHandProneOffsetU", offsetof(WeaponFullDef, weapVariantDef.ikLeftHandProneOffset.z), CSPFT_FLOAT}, - {"ikLeftHandProneRotationP", offsetof(WeaponFullDef, weapVariantDef.ikLeftHandProneRotation.x), CSPFT_FLOAT}, - {"ikLeftHandProneRotationY", offsetof(WeaponFullDef, weapVariantDef.ikLeftHandProneRotation.y), CSPFT_FLOAT}, - {"ikLeftHandProneRotationR", offsetof(WeaponFullDef, weapVariantDef.ikLeftHandProneRotation.z), CSPFT_FLOAT}, - {"ikLeftHandUiViewerOffsetF", offsetof(WeaponFullDef, weapVariantDef.ikLeftHandUiViewerOffset.x), CSPFT_FLOAT}, - {"ikLeftHandUiViewerOffsetR", offsetof(WeaponFullDef, weapVariantDef.ikLeftHandUiViewerOffset.y), CSPFT_FLOAT}, - {"ikLeftHandUiViewerOffsetU", offsetof(WeaponFullDef, weapVariantDef.ikLeftHandUiViewerOffset.z), CSPFT_FLOAT}, - {"ikLeftHandUiViewerRotationP", offsetof(WeaponFullDef, weapVariantDef.ikLeftHandUiViewerRotation.x), CSPFT_FLOAT}, - {"ikLeftHandUiViewerRotationY", offsetof(WeaponFullDef, weapVariantDef.ikLeftHandUiViewerRotation.y), CSPFT_FLOAT}, - {"ikLeftHandUiViewerRotationR", offsetof(WeaponFullDef, weapVariantDef.ikLeftHandUiViewerRotation.z), CSPFT_FLOAT}, - {"parentWeaponName", offsetof(WeaponFullDef, weapDef.parentWeaponName), CSPFT_STRING}, - {"doGibbing", offsetof(WeaponFullDef, weapDef.doGibbing), CSPFT_BOOL}, - {"maxGibDistance", offsetof(WeaponFullDef, weapDef.maxGibDistance), CSPFT_FLOAT}, - {"altScopeADSTransInTime", offsetof(WeaponFullDef, weapDef.altScopeADSTransInTime), CSPFT_FLOAT}, - {"altScopeADSTransOutTime", offsetof(WeaponFullDef, weapDef.altScopeADSTransOutTime), CSPFT_FLOAT}, - {"meleeSwipeEffect", offsetof(WeaponFullDef, weapDef.meleeSwipeEffect), CSPFT_FX}, - {"meleeImpactEffect", offsetof(WeaponFullDef, weapDef.meleeImpactEffect), CSPFT_FX}, - {"meleeImpactNoBloodEffect", offsetof(WeaponFullDef, weapDef.meleeImpactNoBloodEffect), CSPFT_FX}, - {"throwBackType", offsetof(WeaponFullDef, weapDef.throwBackType), CSPFT_STRING}, - {"camo", offsetof(WeaponFullDef, weapDef.weaponCamo), WFT_WEAPON_CAMO}, - {"customFloat0", offsetof(WeaponFullDef, weapDef.customFloat0), CSPFT_FLOAT}, - {"customFloat1", offsetof(WeaponFullDef, weapDef.customFloat1), CSPFT_FLOAT}, - {"customFloat2", offsetof(WeaponFullDef, weapDef.customFloat2), CSPFT_FLOAT}, - {"customBool0", offsetof(WeaponFullDef, weapDef.customBool0), CSPFT_BOOL}, - {"customBool1", offsetof(WeaponFullDef, weapDef.customBool1), CSPFT_BOOL}, - {"customBool2", offsetof(WeaponFullDef, weapDef.customBool2), CSPFT_BOOL}, - {"attachments", offsetof(WeaponFullDef, attachments), WFT_ATTACHMENTS}, - {"attachmentUniques", offsetof(WeaponFullDef, attachmentUniques), WFT_ATTACHMENT_UNIQUES} - }; +namespace T6 { +inline cspField_t weapon_fields[]{ + {"displayName", offsetof(WeaponFullDef, weapVariantDef.szDisplayName), CSPFT_STRING }, + {"AIOverlayDescription", offsetof(WeaponFullDef, weapDef.szOverlayName), CSPFT_STRING }, + {"modeName", offsetof(WeaponFullDef, weapDef.szModeName), CSPFT_STRING }, + {"playerAnimType", offsetof(WeaponFullDef, weapDef.playerAnimType), WFT_ANIMTYPE }, + {"gunModel", offsetof(WeaponFullDef, gunXModel[0]), CSPFT_XMODEL }, + {"gunModel2", offsetof(WeaponFullDef, gunXModel[1]), CSPFT_XMODEL }, + {"gunModel3", offsetof(WeaponFullDef, gunXModel[2]), CSPFT_XMODEL }, + {"gunModel4", offsetof(WeaponFullDef, gunXModel[3]), CSPFT_XMODEL }, + {"gunModel5", offsetof(WeaponFullDef, gunXModel[4]), CSPFT_XMODEL }, + {"gunModel6", offsetof(WeaponFullDef, gunXModel[5]), CSPFT_XMODEL }, + {"gunModel7", offsetof(WeaponFullDef, gunXModel[6]), CSPFT_XMODEL }, + {"gunModel8", offsetof(WeaponFullDef, gunXModel[7]), CSPFT_XMODEL }, + {"gunModel9", offsetof(WeaponFullDef, gunXModel[8]), CSPFT_XMODEL }, + {"gunModel10", offsetof(WeaponFullDef, gunXModel[9]), CSPFT_XMODEL }, + {"gunModel11", offsetof(WeaponFullDef, gunXModel[10]), CSPFT_XMODEL }, + {"gunModel12", offsetof(WeaponFullDef, gunXModel[11]), CSPFT_XMODEL }, + {"gunModel13", offsetof(WeaponFullDef, gunXModel[12]), CSPFT_XMODEL }, + {"gunModel14", offsetof(WeaponFullDef, gunXModel[13]), CSPFT_XMODEL }, + {"gunModel15", offsetof(WeaponFullDef, gunXModel[14]), CSPFT_XMODEL }, + {"gunModel16", offsetof(WeaponFullDef, gunXModel[15]), CSPFT_XMODEL }, + {"handModel", offsetof(WeaponFullDef, weapDef.handXModel), CSPFT_XMODEL }, + {"hideTags", offsetof(WeaponFullDef, hideTags), WFT_HIDETAGS }, + {"notetrackSoundMap", offsetof(WeaponFullDef, notetrackSoundMapKeys), WFT_NOTETRACKSOUNDMAP }, + {"idleAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_IDLE]), CSPFT_STRING }, + {"idleAnimLeft", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_IDLE_LEFT]), CSPFT_STRING }, + {"emptyIdleAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_EMPTY_IDLE]), CSPFT_STRING }, + {"emptyIdleAnimLeft", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_EMPTY_IDLE_LEFT]), CSPFT_STRING }, + {"fireIntroAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_FIRE_INTRO]), CSPFT_STRING }, + {"fireAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_FIRE]), CSPFT_STRING }, + {"fireAnimLeft", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_FIRE_LEFT]), CSPFT_STRING }, + {"holdFireAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_HOLD_FIRE]), CSPFT_STRING }, + {"lastShotAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_LASTSHOT]), CSPFT_STRING }, + {"lastShotAnimLeft", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_LASTSHOT_LEFT]), CSPFT_STRING }, + {"flourishAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_FINALSHOT]), CSPFT_STRING }, + {"flourishAnimLeft", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_FINALSHOT_LEFT]), CSPFT_STRING }, + {"detonateAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_DETONATE]), CSPFT_STRING }, + {"rechamberAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_RECHAMBER]), CSPFT_STRING }, + {"meleeAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_MELEE]), CSPFT_STRING }, + {"meleeAnimEmpty", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_MELEE_EMPTY]), CSPFT_STRING }, + {"meleeAnim1", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_MELEE1]), CSPFT_STRING }, + {"meleeAnim2", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_MELEE2]), CSPFT_STRING }, + {"meleeAnim3", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_MELEE3]), CSPFT_STRING }, + {"meleeChargeAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_MELEE_CHARGE]), CSPFT_STRING }, + {"meleeChargeAnimEmpty", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_MELEE_CHARGE_EMPTY]), CSPFT_STRING }, + {"reloadAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_RELOAD]), CSPFT_STRING }, + {"reloadAnimRight", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_RELOAD_RIGHT]), CSPFT_STRING }, + {"reloadAnimLeft", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_RELOAD_LEFT]), CSPFT_STRING }, + {"reloadEmptyAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_RELOAD_EMPTY]), CSPFT_STRING }, + {"reloadEmptyAnimLeft", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_RELOAD_EMPTY_LEFT]), CSPFT_STRING }, + {"reloadStartAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_RELOAD_START]), CSPFT_STRING }, + {"reloadEndAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_RELOAD_END]), CSPFT_STRING }, + {"reloadQuickAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_RELOAD_QUICK]), CSPFT_STRING }, + {"reloadQuickEmptyAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_RELOAD_QUICK_EMPTY]), CSPFT_STRING }, + {"raiseAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_RAISE]), CSPFT_STRING }, + {"dropAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_DROP]), CSPFT_STRING }, + {"firstRaiseAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_FIRST_RAISE]), CSPFT_STRING }, + {"altRaiseAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_ALT_RAISE]), CSPFT_STRING }, + {"altDropAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_ALT_DROP]), CSPFT_STRING }, + {"quickRaiseAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_QUICK_RAISE]), CSPFT_STRING }, + {"quickDropAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_QUICK_DROP]), CSPFT_STRING }, + {"emptyRaiseAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_EMPTY_RAISE]), CSPFT_STRING }, + {"emptyDropAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_EMPTY_DROP]), CSPFT_STRING }, + {"sprintInAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_SPRINT_IN]), CSPFT_STRING }, + {"sprintLoopAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_SPRINT_LOOP]), CSPFT_STRING }, + {"sprintOutAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_SPRINT_OUT]), CSPFT_STRING }, + {"sprintInEmptyAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_SPRINT_EMPTY_IN]), CSPFT_STRING }, + {"sprintLoopEmptyAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_SPRINT_EMPTY_LOOP]), CSPFT_STRING }, + {"sprintOutEmptyAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_SPRINT_EMPTY_OUT]), CSPFT_STRING }, + {"lowReadyInAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_LOWREADY_IN]), CSPFT_STRING }, + {"lowReadyLoopAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_LOWREADY_LOOP]), CSPFT_STRING }, + {"lowReadyOutAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_LOWREADY_OUT]), CSPFT_STRING }, + {"contFireInAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_CONT_FIRE_IN]), CSPFT_STRING }, + {"contFireLoopAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_CONT_FIRE_LOOP]), CSPFT_STRING }, + {"contFireOutAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_CONT_FIRE_OUT]), CSPFT_STRING }, + {"crawlInAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_CRAWL_IN]), CSPFT_STRING }, + {"crawlForwardAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_CRAWL_FORWARD]), CSPFT_STRING }, + {"crawlBackAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_CRAWL_BACK]), CSPFT_STRING }, + {"crawlRightAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_CRAWL_RIGHT]), CSPFT_STRING }, + {"crawlLeftAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_CRAWL_LEFT]), CSPFT_STRING }, + {"crawlOutAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_CRAWL_OUT]), CSPFT_STRING }, + {"crawlEmptyInAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_CRAWL_EMPTY_IN]), CSPFT_STRING }, + {"crawlEmptyForwardAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_CRAWL_EMPTY_FORWARD]), CSPFT_STRING }, + {"crawlEmptyBackAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_CRAWL_EMPTY_BACK]), CSPFT_STRING }, + {"crawlEmptyRightAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_CRAWL_EMPTY_RIGHT]), CSPFT_STRING }, + {"crawlEmptyLeftAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_CRAWL_EMPTY_LEFT]), CSPFT_STRING }, + {"crawlEmptyOutAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_CRAWL_EMPTY_OUT]), CSPFT_STRING }, + {"deployAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_DEPLOY]), CSPFT_STRING }, + {"nightVisionWearAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_NIGHTVISION_WEAR]), CSPFT_STRING }, + {"nightVisionRemoveAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_NIGHTVISION_REMOVE]), CSPFT_STRING }, + {"adsFireAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_ADS_FIRE]), CSPFT_STRING }, + {"adsLastShotAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_ADS_LASTSHOT]), CSPFT_STRING }, + {"adsRechamberAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_ADS_RECHAMBER]), CSPFT_STRING }, + {"adsUpAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_ADS_UP]), CSPFT_STRING }, + {"adsDownAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_ADS_DOWN]), CSPFT_STRING }, + {"adsUpOtherScopeAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_ADS_UP_OTHER_SCOPE]), CSPFT_STRING }, + {"adsFireIntroAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_ADS_FIRE_INTRO]), CSPFT_STRING }, + {"breakdownAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_BREAKDOWN]), CSPFT_STRING }, + {"dtp_in", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_DTP_IN]), CSPFT_STRING }, + {"dtp_loop", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_DTP_LOOP]), CSPFT_STRING }, + {"dtp_out", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_DTP_OUT]), CSPFT_STRING }, + {"dtp_empty_in", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_DTP_EMPTY_IN]), CSPFT_STRING }, + {"dtp_empty_loop", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_DTP_EMPTY_LOOP]), CSPFT_STRING }, + {"dtp_empty_out", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_DTP_EMPTY_OUT]), CSPFT_STRING }, + {"slide_in", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_SLIDE_IN]), CSPFT_STRING }, + {"mantleAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_MANTLE]), CSPFT_STRING }, + {"sprintCameraAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_CAMERA_SPRINT_LOOP]), CSPFT_STRING }, + {"dtpInCameraAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_CAMERA_DTP_IN]), CSPFT_STRING }, + {"dtpLoopCameraAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_CAMERA_DTP_LOOP]), CSPFT_STRING }, + {"dtpOutCameraAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_CAMERA_DTP_OUT]), CSPFT_STRING }, + {"mantleCameraAnim", offsetof(WeaponFullDef, szXAnims[WEAP_ANIM_CAMERA_MANTLE]), CSPFT_STRING }, + {"script", offsetof(WeaponFullDef, weapDef.szScript), CSPFT_STRING }, + {"weaponType", offsetof(WeaponFullDef, weapDef.weapType), WFT_WEAPONTYPE }, + {"weaponClass", offsetof(WeaponFullDef, weapDef.weapClass), WFT_WEAPONCLASS }, + {"penetrateType", offsetof(WeaponFullDef, weapDef.penetrateTWeaponAttachmentype), WFT_PENETRATE_TYPE }, + {"impactType", offsetof(WeaponFullDef, weapDef.impactType), WFT_IMPACT_TYPE }, + {"inventoryType", offsetof(WeaponFullDef, weapDef.inventoryType), WFT_INVENTORYTYPE }, + {"fireType", offsetof(WeaponFullDef, weapDef.fireType), WFT_FIRETYPE }, + {"clipType", offsetof(WeaponFullDef, weapDef.clipType), WFT_CLIPTYPE }, + {"barrelType", offsetof(WeaponFullDef, weapDef.barrelType), WFT_BARRELTYPE }, + {"offhandClass", offsetof(WeaponFullDef, weapDef.offhandClass), WFT_OFFHAND_CLASS }, + {"offhandSlot", offsetof(WeaponFullDef, weapDef.offhandSlot), WFT_OFFHAND_SLOT }, + {"viewFlashEffect", offsetof(WeaponFullDef, weapDef.viewFlashEffect), CSPFT_FX }, + {"worldFlashEffect", offsetof(WeaponFullDef, weapDef.worldFlashEffect), CSPFT_FX }, + {"barrelCooldownEffect", offsetof(WeaponFullDef, weapDef.barrelCooldownEffect), CSPFT_FX }, + {"barrelCooldownMinCount", offsetof(WeaponFullDef, weapDef.barrelCooldownMinCount), CSPFT_INT }, + {"viewFlashOffsetF", offsetof(WeaponFullDef, weapDef.vViewFlashOffset.x), CSPFT_FLOAT }, + {"viewFlashOffsetR", offsetof(WeaponFullDef, weapDef.vViewFlashOffset.y), CSPFT_FLOAT }, + {"viewFlashOffsetU", offsetof(WeaponFullDef, weapDef.vViewFlashOffset.z), CSPFT_FLOAT }, + {"worldFlashOffsetF", offsetof(WeaponFullDef, weapDef.vWorldFlashOffset.x), CSPFT_FLOAT }, + {"worldFlashOffsetR", offsetof(WeaponFullDef, weapDef.vWorldFlashOffset.y), CSPFT_FLOAT }, + {"worldFlashOffsetU", offsetof(WeaponFullDef, weapDef.vWorldFlashOffset.z), CSPFT_FLOAT }, + {"pickupSound", offsetof(WeaponFullDef, weapDef.pickupSound), CSPFT_STRING }, + {"pickupSoundPlayer", offsetof(WeaponFullDef, weapDef.pickupSoundPlayer), CSPFT_STRING }, + {"ammoPickupSound", offsetof(WeaponFullDef, weapDef.ammoPickupSound), CSPFT_STRING }, + {"ammoPickupSoundPlayer", offsetof(WeaponFullDef, weapDef.ammoPickupSoundPlayer), CSPFT_STRING }, + {"projectileSound", offsetof(WeaponFullDef, weapDef.projectileSound), CSPFT_STRING }, + {"pullbackSound", offsetof(WeaponFullDef, weapDef.pullbackSound), CSPFT_STRING }, + {"pullbackSoundPlayer", offsetof(WeaponFullDef, weapDef.pullbackSoundPlayer), CSPFT_STRING }, + {"fireSound", offsetof(WeaponFullDef, weapDef.fireSound), CSPFT_STRING }, + {"crackSound", offsetof(WeaponFullDef, weapDef.crackSound), CSPFT_STRING }, + {"whizbySound", offsetof(WeaponFullDef, weapDef.whizbySound), CSPFT_STRING }, + {"fireSoundPlayer", offsetof(WeaponFullDef, weapDef.fireSoundPlayer), CSPFT_STRING }, + {"loopFireSound", offsetof(WeaponFullDef, weapDef.fireLoopSound), CSPFT_STRING }, + {"loopFireSoundPlayer", offsetof(WeaponFullDef, weapDef.fireLoopSoundPlayer), CSPFT_STRING }, + {"loopFireEndSound", offsetof(WeaponFullDef, weapDef.fireLoopEndSound), CSPFT_STRING }, + {"loopFireEndSoundPlayer", offsetof(WeaponFullDef, weapDef.fireLoopEndSoundPlayer), CSPFT_STRING }, + {"startFireSound", offsetof(WeaponFullDef, weapDef.fireStartSound), CSPFT_STRING }, + {"stopFireSound", offsetof(WeaponFullDef, weapDef.fireStopSound), CSPFT_STRING }, + {"killcamStartFireSound", offsetof(WeaponFullDef, weapDef.fireKillcamSound), CSPFT_STRING }, + {"startFireSoundPlayer", offsetof(WeaponFullDef, weapDef.fireStartSoundPlayer), CSPFT_STRING }, + {"stopFireSoundPlayer", offsetof(WeaponFullDef, weapDef.fireStopSoundPlayer), CSPFT_STRING }, + {"killcamStartFireSoundPlayer", offsetof(WeaponFullDef, weapDef.fireKillcamSoundPlayer), CSPFT_STRING }, + {"lastShotSound", offsetof(WeaponFullDef, weapDef.fireLastSound), CSPFT_STRING }, + {"lastShotSoundPlayer", offsetof(WeaponFullDef, weapDef.fireLastSoundPlayer), CSPFT_STRING }, + {"emptyFireSound", offsetof(WeaponFullDef, weapDef.emptyFireSound), CSPFT_STRING }, + {"emptyFireSoundPlayer", offsetof(WeaponFullDef, weapDef.emptyFireSoundPlayer), CSPFT_STRING }, + {"meleeSwipeSound", offsetof(WeaponFullDef, weapDef.meleeSwipeSound), CSPFT_STRING }, + {"meleeSwipeSoundPlayer", offsetof(WeaponFullDef, weapDef.meleeSwipeSoundPlayer), CSPFT_STRING }, + {"meleeHitSound", offsetof(WeaponFullDef, weapDef.meleeHitSound), CSPFT_STRING }, + {"meleeMissSound", offsetof(WeaponFullDef, weapDef.meleeMissSound), CSPFT_STRING }, + {"rechamberSound", offsetof(WeaponFullDef, weapDef.rechamberSound), CSPFT_STRING }, + {"rechamberSoundPlayer", offsetof(WeaponFullDef, weapDef.rechamberSoundPlayer), CSPFT_STRING }, + {"reloadSound", offsetof(WeaponFullDef, weapDef.reloadSound), CSPFT_STRING }, + {"reloadSoundPlayer", offsetof(WeaponFullDef, weapDef.reloadSoundPlayer), CSPFT_STRING }, + {"reloadEmptySound", offsetof(WeaponFullDef, weapDef.reloadEmptySound), CSPFT_STRING }, + {"reloadEmptySoundPlayer", offsetof(WeaponFullDef, weapDef.reloadEmptySoundPlayer), CSPFT_STRING }, + {"reloadStartSound", offsetof(WeaponFullDef, weapDef.reloadStartSound), CSPFT_STRING }, + {"reloadStartSoundPlayer", offsetof(WeaponFullDef, weapDef.reloadStartSoundPlayer), CSPFT_STRING }, + {"reloadEndSound", offsetof(WeaponFullDef, weapDef.reloadEndSound), CSPFT_STRING }, + {"reloadEndSoundPlayer", offsetof(WeaponFullDef, weapDef.reloadEndSoundPlayer), CSPFT_STRING }, + {"rotateLoopSound", offsetof(WeaponFullDef, weapDef.rotateLoopSound), CSPFT_STRING }, + {"rotateLoopSoundPlayer", offsetof(WeaponFullDef, weapDef.rotateLoopSoundPlayer), CSPFT_STRING }, + {"rotateStopSound", offsetof(WeaponFullDef, weapDef.rotateStopSound), CSPFT_STRING }, + {"rotateStopSoundPlayer", offsetof(WeaponFullDef, weapDef.rotateStopSoundPlayer), CSPFT_STRING }, + {"deploySound", offsetof(WeaponFullDef, weapDef.deploySound), CSPFT_STRING }, + {"deploySoundPlayer", offsetof(WeaponFullDef, weapDef.deploySoundPlayer), CSPFT_STRING }, + {"finishDeploySound", offsetof(WeaponFullDef, weapDef.finishDeploySound), CSPFT_STRING }, + {"finishDeploySoundPlayer", offsetof(WeaponFullDef, weapDef.finishDeploySoundPlayer), CSPFT_STRING }, + {"breakdownSound", offsetof(WeaponFullDef, weapDef.breakdownSound), CSPFT_STRING }, + {"breakdownSoundPlayer", offsetof(WeaponFullDef, weapDef.breakdownSoundPlayer), CSPFT_STRING }, + {"finishBreakdownSound", offsetof(WeaponFullDef, weapDef.finishBreakdownSound), CSPFT_STRING }, + {"finishBreakdownSoundPlayer", offsetof(WeaponFullDef, weapDef.finishBreakdownSoundPlayer), CSPFT_STRING }, + {"detonateSound", offsetof(WeaponFullDef, weapDef.detonateSound), CSPFT_STRING }, + {"detonateSoundPlayer", offsetof(WeaponFullDef, weapDef.detonateSoundPlayer), CSPFT_STRING }, + {"nightVisionWearSound", offsetof(WeaponFullDef, weapDef.nightVisionWearSound), CSPFT_STRING }, + {"nightVisionWearSoundPlayer", offsetof(WeaponFullDef, weapDef.nightVisionWearSoundPlayer), CSPFT_STRING }, + {"nightVisionRemoveSound", offsetof(WeaponFullDef, weapDef.nightVisionRemoveSound), CSPFT_STRING }, + {"nightVisionRemoveSoundPlayer", offsetof(WeaponFullDef, weapDef.nightVisionRemoveSoundPlayer), CSPFT_STRING }, + {"raiseSound", offsetof(WeaponFullDef, weapDef.raiseSound), CSPFT_STRING }, + {"raiseSoundPlayer", offsetof(WeaponFullDef, weapDef.raiseSoundPlayer), CSPFT_STRING }, + {"firstRaiseSound", offsetof(WeaponFullDef, weapDef.firstRaiseSound), CSPFT_STRING }, + {"firstRaiseSoundPlayer", offsetof(WeaponFullDef, weapDef.firstRaiseSoundPlayer), CSPFT_STRING }, + {"altSwitchSound", offsetof(WeaponFullDef, weapDef.altSwitchSound), CSPFT_STRING }, + {"altSwitchSoundPlayer", offsetof(WeaponFullDef, weapDef.altSwitchSoundPlayer), CSPFT_STRING }, + {"adsRaiseSoundPlayer", offsetof(WeaponFullDef, weapDef.adsRaiseSoundPlayer), CSPFT_STRING }, + {"adsLowerSoundPlayer", offsetof(WeaponFullDef, weapDef.adsLowerSoundPlayer), CSPFT_STRING }, + {"putawaySound", offsetof(WeaponFullDef, weapDef.putawaySound), CSPFT_STRING }, + {"putawaySoundPlayer", offsetof(WeaponFullDef, weapDef.putawaySoundPlayer), CSPFT_STRING }, + {"overheatSound", offsetof(WeaponFullDef, weapDef.overheatSound), CSPFT_STRING }, + {"overheatSoundPlayer", offsetof(WeaponFullDef, weapDef.overheatSoundPlayer), CSPFT_STRING }, + {"adsZoomSound", offsetof(WeaponFullDef, weapDef.adsZoomSound), CSPFT_STRING }, + {"shellCasing", offsetof(WeaponFullDef, weapDef.shellCasing), CSPFT_STRING }, + {"shellCasingPlayer", offsetof(WeaponFullDef, weapDef.shellCasingPlayer), CSPFT_STRING }, + {"bounceSound", offsetof(WeaponFullDef, weapDef.bounceSound), WFT_BOUNCE_SOUND }, + {"standMountedWeapdef", offsetof(WeaponFullDef, weapDef.standMountedWeapdef), CSPFT_STRING }, + {"crouchMountedWeapdef", offsetof(WeaponFullDef, weapDef.crouchMountedWeapdef), CSPFT_STRING }, + {"proneMountedWeapdef", offsetof(WeaponFullDef, weapDef.proneMountedWeapdef), CSPFT_STRING }, + {"viewShellEjectEffect", offsetof(WeaponFullDef, weapDef.viewShellEjectEffect), CSPFT_FX }, + {"worldShellEjectEffect", offsetof(WeaponFullDef, weapDef.worldShellEjectEffect), CSPFT_FX }, + {"viewLastShotEjectEffect", offsetof(WeaponFullDef, weapDef.viewLastShotEjectEffect), CSPFT_FX }, + {"worldLastShotEjectEffect", offsetof(WeaponFullDef, weapDef.worldLastShotEjectEffect), CSPFT_FX }, + {"viewShellEjectOffsetF", offsetof(WeaponFullDef, weapDef.vViewShellEjectOffset.x), CSPFT_FLOAT }, + {"viewShellEjectOffsetR", offsetof(WeaponFullDef, weapDef.vViewShellEjectOffset.y), CSPFT_FLOAT }, + {"viewShellEjectOffsetU", offsetof(WeaponFullDef, weapDef.vViewShellEjectOffset.z), CSPFT_FLOAT }, + {"worldShellEjectOffsetF", offsetof(WeaponFullDef, weapDef.vWorldShellEjectOffset.x), CSPFT_FLOAT }, + {"worldShellEjectOffsetR", offsetof(WeaponFullDef, weapDef.vWorldShellEjectOffset.y), CSPFT_FLOAT }, + {"worldShellEjectOffsetU", offsetof(WeaponFullDef, weapDef.vWorldShellEjectOffset.z), CSPFT_FLOAT }, + {"viewShellEjectRotationP", offsetof(WeaponFullDef, weapDef.vViewShellEjectRotation.x), CSPFT_FLOAT }, + {"viewShellEjectRotationY", offsetof(WeaponFullDef, weapDef.vViewShellEjectRotation.y), CSPFT_FLOAT }, + {"viewShellEjectRotationR", offsetof(WeaponFullDef, weapDef.vViewShellEjectRotation.z), CSPFT_FLOAT }, + {"worldShellEjectRotationP", offsetof(WeaponFullDef, weapDef.vWorldShellEjectRotation.x), CSPFT_FLOAT }, + {"worldShellEjectRotationY", offsetof(WeaponFullDef, weapDef.vWorldShellEjectRotation.y), CSPFT_FLOAT }, + {"worldShellEjectRotationR", offsetof(WeaponFullDef, weapDef.vWorldShellEjectRotation.z), CSPFT_FLOAT }, + {"reticleCenter", offsetof(WeaponFullDef, weapDef.reticleCenter), CSPFT_MATERIAL }, + {"reticleSide", offsetof(WeaponFullDef, weapDef.reticleSide), CSPFT_MATERIAL }, + {"reticleCenterSize", offsetof(WeaponFullDef, weapDef.iReticleCenterSize), CSPFT_INT }, + {"reticleSideSize", offsetof(WeaponFullDef, weapDef.iReticleSideSize), CSPFT_INT }, + {"reticleMinOfs", offsetof(WeaponFullDef, weapDef.iReticleMinOfs), CSPFT_INT }, + {"activeReticleType", offsetof(WeaponFullDef, weapDef.activeReticleType), WFT_ACTIVE_RETICLE_TYPE }, + {"standMoveF", offsetof(WeaponFullDef, weapDef.vStandMove.x), CSPFT_FLOAT }, + {"standMoveR", offsetof(WeaponFullDef, weapDef.vStandMove.y), CSPFT_FLOAT }, + {"standMoveU", offsetof(WeaponFullDef, weapDef.vStandMove.z), CSPFT_FLOAT }, + {"standRotP", offsetof(WeaponFullDef, weapDef.vStandRot.x), CSPFT_FLOAT }, + {"standRotY", offsetof(WeaponFullDef, weapDef.vStandRot.y), CSPFT_FLOAT }, + {"standRotR", offsetof(WeaponFullDef, weapDef.vStandRot.z), CSPFT_FLOAT }, + {"duckedOfsF", offsetof(WeaponFullDef, weapDef.vDuckedOfs.x), CSPFT_FLOAT }, + {"duckedOfsR", offsetof(WeaponFullDef, weapDef.vDuckedOfs.y), CSPFT_FLOAT }, + {"duckedOfsU", offsetof(WeaponFullDef, weapDef.vDuckedOfs.z), CSPFT_FLOAT }, + {"duckedMoveF", offsetof(WeaponFullDef, weapDef.vDuckedMove.x), CSPFT_FLOAT }, + {"duckedMoveR", offsetof(WeaponFullDef, weapDef.vDuckedMove.y), CSPFT_FLOAT }, + {"duckedMoveU", offsetof(WeaponFullDef, weapDef.vDuckedMove.z), CSPFT_FLOAT }, + {"duckedSprintOfsF", offsetof(WeaponFullDef, weapDef.vDuckedSprintOfs.x), CSPFT_FLOAT }, + {"duckedSprintOfsR", offsetof(WeaponFullDef, weapDef.vDuckedSprintOfs.y), CSPFT_FLOAT }, + {"duckedSprintOfsU", offsetof(WeaponFullDef, weapDef.vDuckedSprintOfs.z), CSPFT_FLOAT }, + {"duckedSprintRotP", offsetof(WeaponFullDef, weapDef.vDuckedSprintRot.x), CSPFT_FLOAT }, + {"duckedSprintRotY", offsetof(WeaponFullDef, weapDef.vDuckedSprintRot.y), CSPFT_FLOAT }, + {"duckedSprintRotR", offsetof(WeaponFullDef, weapDef.vDuckedSprintRot.z), CSPFT_FLOAT }, + {"duckedSprintBobH", offsetof(WeaponFullDef, weapDef.vDuckedSprintBob.x), CSPFT_FLOAT }, + {"duckedSprintBobV", offsetof(WeaponFullDef, weapDef.vDuckedSprintBob.y), CSPFT_FLOAT }, + {"duckedSprintScale", offsetof(WeaponFullDef, weapDef.fDuckedSprintCycleScale), CSPFT_FLOAT }, + {"sprintOfsF", offsetof(WeaponFullDef, weapDef.vSprintOfs.x), CSPFT_FLOAT }, + {"sprintOfsR", offsetof(WeaponFullDef, weapDef.vSprintOfs.y), CSPFT_FLOAT }, + {"sprintOfsU", offsetof(WeaponFullDef, weapDef.vSprintOfs.z), CSPFT_FLOAT }, + {"sprintRotP", offsetof(WeaponFullDef, weapDef.vSprintRot.x), CSPFT_FLOAT }, + {"sprintRotY", offsetof(WeaponFullDef, weapDef.vSprintRot.y), CSPFT_FLOAT }, + {"sprintRotR", offsetof(WeaponFullDef, weapDef.vSprintRot.z), CSPFT_FLOAT }, + {"sprintBobH", offsetof(WeaponFullDef, weapDef.vSprintBob.x), CSPFT_FLOAT }, + {"sprintBobV", offsetof(WeaponFullDef, weapDef.vSprintBob.y), CSPFT_FLOAT }, + {"sprintScale", offsetof(WeaponFullDef, weapDef.fSprintCycleScale), CSPFT_FLOAT }, + {"lowReadyOfsF", offsetof(WeaponFullDef, weapDef.vLowReadyOfs.x), CSPFT_FLOAT }, + {"lowReadyOfsR", offsetof(WeaponFullDef, weapDef.vLowReadyOfs.y), CSPFT_FLOAT }, + {"lowReadyOfsU", offsetof(WeaponFullDef, weapDef.vLowReadyOfs.z), CSPFT_FLOAT }, + {"lowReadyRotP", offsetof(WeaponFullDef, weapDef.vLowReadyRot.x), CSPFT_FLOAT }, + {"lowReadyRotY", offsetof(WeaponFullDef, weapDef.vLowReadyRot.y), CSPFT_FLOAT }, + {"lowReadyRotR", offsetof(WeaponFullDef, weapDef.vLowReadyRot.z), CSPFT_FLOAT }, + {"rideOfsF", offsetof(WeaponFullDef, weapDef.vRideOfs.x), CSPFT_FLOAT }, + {"rideOfsR", offsetof(WeaponFullDef, weapDef.vRideOfs.y), CSPFT_FLOAT }, + {"rideOfsU", offsetof(WeaponFullDef, weapDef.vRideOfs.z), CSPFT_FLOAT }, + {"rideRotP", offsetof(WeaponFullDef, weapDef.vRideRot.x), CSPFT_FLOAT }, + {"rideRotY", offsetof(WeaponFullDef, weapDef.vRideRot.y), CSPFT_FLOAT }, + {"rideRotR", offsetof(WeaponFullDef, weapDef.vRideRot.z), CSPFT_FLOAT }, + {"dtpOfsF", offsetof(WeaponFullDef, weapDef.vDtpOfs.x), CSPFT_FLOAT }, + {"dtpOfsR", offsetof(WeaponFullDef, weapDef.vDtpOfs.y), CSPFT_FLOAT }, + {"dtpOfsU", offsetof(WeaponFullDef, weapDef.vDtpOfs.z), CSPFT_FLOAT }, + {"dtpRotP", offsetof(WeaponFullDef, weapDef.vDtpRot.x), CSPFT_FLOAT }, + {"dtpRotY", offsetof(WeaponFullDef, weapDef.vDtpRot.y), CSPFT_FLOAT }, + {"dtpRotR", offsetof(WeaponFullDef, weapDef.vDtpRot.z), CSPFT_FLOAT }, + {"dtpBobH", offsetof(WeaponFullDef, weapDef.vDtpBob.x), CSPFT_FLOAT }, + {"dtpBobV", offsetof(WeaponFullDef, weapDef.vDtpBob.y), CSPFT_FLOAT }, + {"dtpScale", offsetof(WeaponFullDef, weapDef.fDtpCycleScale), CSPFT_FLOAT }, + {"mantleOfsF", offsetof(WeaponFullDef, weapDef.vMantleOfs.x), CSPFT_FLOAT }, + {"mantleOfsR", offsetof(WeaponFullDef, weapDef.vMantleOfs.y), CSPFT_FLOAT }, + {"mantleOfsU", offsetof(WeaponFullDef, weapDef.vMantleOfs.z), CSPFT_FLOAT }, + {"mantleRotP", offsetof(WeaponFullDef, weapDef.vMantleRot.x), CSPFT_FLOAT }, + {"mantleRotY", offsetof(WeaponFullDef, weapDef.vMantleRot.y), CSPFT_FLOAT }, + {"mantleRotR", offsetof(WeaponFullDef, weapDef.vMantleRot.z), CSPFT_FLOAT }, + {"slideOfsF", offsetof(WeaponFullDef, weapDef.vSlideOfs.x), CSPFT_FLOAT }, + {"slideOfsR", offsetof(WeaponFullDef, weapDef.vSlideOfs.y), CSPFT_FLOAT }, + {"slideOfsU", offsetof(WeaponFullDef, weapDef.vSlideOfs.z), CSPFT_FLOAT }, + {"slideRotP", offsetof(WeaponFullDef, weapDef.vSlideRot.x), CSPFT_FLOAT }, + {"slideRotY", offsetof(WeaponFullDef, weapDef.vSlideRot.y), CSPFT_FLOAT }, + {"slideRotR", offsetof(WeaponFullDef, weapDef.vSlideRot.z), CSPFT_FLOAT }, + {"duckedRotP", offsetof(WeaponFullDef, weapDef.vDuckedRot.x), CSPFT_FLOAT }, + {"duckedRotY", offsetof(WeaponFullDef, weapDef.vDuckedRot.y), CSPFT_FLOAT }, + {"duckedRotR", offsetof(WeaponFullDef, weapDef.vDuckedRot.z), CSPFT_FLOAT }, + {"proneOfsF", offsetof(WeaponFullDef, weapDef.vProneOfs.x), CSPFT_FLOAT }, + {"proneOfsR", offsetof(WeaponFullDef, weapDef.vProneOfs.y), CSPFT_FLOAT }, + {"proneOfsU", offsetof(WeaponFullDef, weapDef.vProneOfs.z), CSPFT_FLOAT }, + {"proneMoveF", offsetof(WeaponFullDef, weapDef.vProneMove.x), CSPFT_FLOAT }, + {"proneMoveR", offsetof(WeaponFullDef, weapDef.vProneMove.y), CSPFT_FLOAT }, + {"proneMoveU", offsetof(WeaponFullDef, weapDef.vProneMove.z), CSPFT_FLOAT }, + {"proneRotP", offsetof(WeaponFullDef, weapDef.vProneRot.x), CSPFT_FLOAT }, + {"proneRotY", offsetof(WeaponFullDef, weapDef.vProneRot.y), CSPFT_FLOAT }, + {"proneRotR", offsetof(WeaponFullDef, weapDef.vProneRot.z), CSPFT_FLOAT }, + {"strafeMoveF", offsetof(WeaponFullDef, weapDef.vStrafeMove.x), CSPFT_FLOAT }, + {"strafeMoveR", offsetof(WeaponFullDef, weapDef.vStrafeMove.y), CSPFT_FLOAT }, + {"strafeMoveU", offsetof(WeaponFullDef, weapDef.vStrafeMove.z), CSPFT_FLOAT }, + {"strafeRotP", offsetof(WeaponFullDef, weapDef.vStrafeRot.x), CSPFT_FLOAT }, + {"strafeRotY", offsetof(WeaponFullDef, weapDef.vStrafeRot.y), CSPFT_FLOAT }, + {"strafeRotR", offsetof(WeaponFullDef, weapDef.vStrafeRot.z), CSPFT_FLOAT }, + {"posMoveRate", offsetof(WeaponFullDef, weapDef.fPosMoveRate), CSPFT_FLOAT }, + {"posProneMoveRate", offsetof(WeaponFullDef, weapDef.fPosProneMoveRate), CSPFT_FLOAT }, + {"standMoveMinSpeed", offsetof(WeaponFullDef, weapDef.fStandMoveMinSpeed), CSPFT_FLOAT }, + {"duckedMoveMinSpeed", offsetof(WeaponFullDef, weapDef.fDuckedMoveMinSpeed), CSPFT_FLOAT }, + {"proneMoveMinSpeed", offsetof(WeaponFullDef, weapDef.fProneMoveMinSpeed), CSPFT_FLOAT }, + {"posRotRate", offsetof(WeaponFullDef, weapDef.fPosRotRate), CSPFT_FLOAT }, + {"posProneRotRate", offsetof(WeaponFullDef, weapDef.fPosProneRotRate), CSPFT_FLOAT }, + {"standRotMinSpeed", offsetof(WeaponFullDef, weapDef.fStandRotMinSpeed), CSPFT_FLOAT }, + {"duckedRotMinSpeed", offsetof(WeaponFullDef, weapDef.fDuckedRotMinSpeed), CSPFT_FLOAT }, + {"proneRotMinSpeed", offsetof(WeaponFullDef, weapDef.fProneRotMinSpeed), CSPFT_FLOAT }, + {"worldModel", offsetof(WeaponFullDef, worldModel[0]), CSPFT_XMODEL }, + {"worldModel2", offsetof(WeaponFullDef, worldModel[1]), CSPFT_XMODEL }, + {"worldModel3", offsetof(WeaponFullDef, worldModel[2]), CSPFT_XMODEL }, + {"worldModel4", offsetof(WeaponFullDef, worldModel[3]), CSPFT_XMODEL }, + {"worldModel5", offsetof(WeaponFullDef, worldModel[4]), CSPFT_XMODEL }, + {"worldModel6", offsetof(WeaponFullDef, worldModel[5]), CSPFT_XMODEL }, + {"worldModel7", offsetof(WeaponFullDef, worldModel[6]), CSPFT_XMODEL }, + {"worldModel8", offsetof(WeaponFullDef, worldModel[7]), CSPFT_XMODEL }, + {"worldModel9", offsetof(WeaponFullDef, worldModel[8]), CSPFT_XMODEL }, + {"worldModel10", offsetof(WeaponFullDef, worldModel[9]), CSPFT_XMODEL }, + {"worldModel11", offsetof(WeaponFullDef, worldModel[10]), CSPFT_XMODEL }, + {"worldModel12", offsetof(WeaponFullDef, worldModel[11]), CSPFT_XMODEL }, + {"worldModel13", offsetof(WeaponFullDef, worldModel[12]), CSPFT_XMODEL }, + {"worldModel14", offsetof(WeaponFullDef, worldModel[13]), CSPFT_XMODEL }, + {"worldModel15", offsetof(WeaponFullDef, worldModel[14]), CSPFT_XMODEL }, + {"worldModel16", offsetof(WeaponFullDef, worldModel[15]), CSPFT_XMODEL }, + {"attachViewModel1", offsetof(WeaponFullDef, attachViewModel[0]), CSPFT_XMODEL }, + {"attachViewModel2", offsetof(WeaponFullDef, attachViewModel[1]), CSPFT_XMODEL }, + {"attachViewModel3", offsetof(WeaponFullDef, attachViewModel[2]), CSPFT_XMODEL }, + {"attachViewModel4", offsetof(WeaponFullDef, attachViewModel[3]), CSPFT_XMODEL }, + {"attachViewModel5", offsetof(WeaponFullDef, attachViewModel[4]), CSPFT_XMODEL }, + {"attachViewModel6", offsetof(WeaponFullDef, attachViewModel[5]), CSPFT_XMODEL }, + {"attachViewModel7", offsetof(WeaponFullDef, attachViewModel[6]), CSPFT_XMODEL }, + {"attachViewModel8", offsetof(WeaponFullDef, attachViewModel[7]), CSPFT_XMODEL }, + {"attachWorldModel1", offsetof(WeaponFullDef, attachWorldModel[0]), CSPFT_XMODEL }, + {"attachWorldModel2", offsetof(WeaponFullDef, attachWorldModel[1]), CSPFT_XMODEL }, + {"attachWorldModel3", offsetof(WeaponFullDef, attachWorldModel[2]), CSPFT_XMODEL }, + {"attachWorldModel4", offsetof(WeaponFullDef, attachWorldModel[3]), CSPFT_XMODEL }, + {"attachWorldModel5", offsetof(WeaponFullDef, attachWorldModel[4]), CSPFT_XMODEL }, + {"attachWorldModel6", offsetof(WeaponFullDef, attachWorldModel[5]), CSPFT_XMODEL }, + {"attachWorldModel7", offsetof(WeaponFullDef, attachWorldModel[6]), CSPFT_XMODEL }, + {"attachWorldModel8", offsetof(WeaponFullDef, attachWorldModel[7]), CSPFT_XMODEL }, + {"attachViewModelTag1", offsetof(WeaponFullDef, attachViewModelTag[0]), CSPFT_STRING }, + {"attachViewModelTag2", offsetof(WeaponFullDef, attachViewModelTag[1]), CSPFT_STRING }, + {"attachViewModelTag3", offsetof(WeaponFullDef, attachViewModelTag[2]), CSPFT_STRING }, + {"attachViewModelTag4", offsetof(WeaponFullDef, attachViewModelTag[3]), CSPFT_STRING }, + {"attachViewModelTag5", offsetof(WeaponFullDef, attachViewModelTag[4]), CSPFT_STRING }, + {"attachViewModelTag6", offsetof(WeaponFullDef, attachViewModelTag[5]), CSPFT_STRING }, + {"attachViewModelTag7", offsetof(WeaponFullDef, attachViewModelTag[6]), CSPFT_STRING }, + {"attachViewModelTag8", offsetof(WeaponFullDef, attachViewModelTag[7]), CSPFT_STRING }, + {"attachWorldModelTag1", offsetof(WeaponFullDef, attachWorldModelTag[0]), CSPFT_STRING }, + {"attachWorldModelTag2", offsetof(WeaponFullDef, attachWorldModelTag[1]), CSPFT_STRING }, + {"attachWorldModelTag3", offsetof(WeaponFullDef, attachWorldModelTag[2]), CSPFT_STRING }, + {"attachWorldModelTag4", offsetof(WeaponFullDef, attachWorldModelTag[3]), CSPFT_STRING }, + {"attachWorldModelTag5", offsetof(WeaponFullDef, attachWorldModelTag[4]), CSPFT_STRING }, + {"attachWorldModelTag6", offsetof(WeaponFullDef, attachWorldModelTag[5]), CSPFT_STRING }, + {"attachWorldModelTag7", offsetof(WeaponFullDef, attachWorldModelTag[6]), CSPFT_STRING }, + {"attachWorldModelTag8", offsetof(WeaponFullDef, attachWorldModelTag[7]), CSPFT_STRING }, + {"attachViewModelOffsetX1", offsetof(WeaponFullDef, weapVariantDef.attachViewModelOffsets[0]), CSPFT_FLOAT }, + {"attachViewModelOffsetY1", offsetof(WeaponFullDef, weapVariantDef.attachViewModelOffsets[1]), CSPFT_FLOAT }, + {"attachViewModelOffsetZ1", offsetof(WeaponFullDef, weapVariantDef.attachViewModelOffsets[2]), CSPFT_FLOAT }, + {"attachViewModelOffsetX2", offsetof(WeaponFullDef, weapVariantDef.attachViewModelOffsets[3]), CSPFT_FLOAT }, + {"attachViewModelOffsetY2", offsetof(WeaponFullDef, weapVariantDef.attachViewModelOffsets[4]), CSPFT_FLOAT }, + {"attachViewModelOffsetZ2", offsetof(WeaponFullDef, weapVariantDef.attachViewModelOffsets[5]), CSPFT_FLOAT }, + {"attachViewModelOffsetX3", offsetof(WeaponFullDef, weapVariantDef.attachViewModelOffsets[6]), CSPFT_FLOAT }, + {"attachViewModelOffsetY3", offsetof(WeaponFullDef, weapVariantDef.attachViewModelOffsets[7]), CSPFT_FLOAT }, + {"attachViewModelOffsetZ3", offsetof(WeaponFullDef, weapVariantDef.attachViewModelOffsets[8]), CSPFT_FLOAT }, + {"attachViewModelOffsetX4", offsetof(WeaponFullDef, weapVariantDef.attachViewModelOffsets[9]), CSPFT_FLOAT }, + {"attachViewModelOffsetY4", offsetof(WeaponFullDef, weapVariantDef.attachViewModelOffsets[10]), CSPFT_FLOAT }, + {"attachViewModelOffsetZ4", offsetof(WeaponFullDef, weapVariantDef.attachViewModelOffsets[11]), CSPFT_FLOAT }, + {"attachViewModelOffsetX5", offsetof(WeaponFullDef, weapVariantDef.attachViewModelOffsets[12]), CSPFT_FLOAT }, + {"attachViewModelOffsetY5", offsetof(WeaponFullDef, weapVariantDef.attachViewModelOffsets[13]), CSPFT_FLOAT }, + {"attachViewModelOffsetZ5", offsetof(WeaponFullDef, weapVariantDef.attachViewModelOffsets[14]), CSPFT_FLOAT }, + {"attachViewModelOffsetX6", offsetof(WeaponFullDef, weapVariantDef.attachViewModelOffsets[15]), CSPFT_FLOAT }, + {"attachViewModelOffsetY6", offsetof(WeaponFullDef, weapVariantDef.attachViewModelOffsets[16]), CSPFT_FLOAT }, + {"attachViewModelOffsetZ6", offsetof(WeaponFullDef, weapVariantDef.attachViewModelOffsets[17]), CSPFT_FLOAT }, + {"attachViewModelOffsetX7", offsetof(WeaponFullDef, weapVariantDef.attachViewModelOffsets[18]), CSPFT_FLOAT }, + {"attachViewModelOffsetY7", offsetof(WeaponFullDef, weapVariantDef.attachViewModelOffsets[19]), CSPFT_FLOAT }, + {"attachViewModelOffsetZ7", offsetof(WeaponFullDef, weapVariantDef.attachViewModelOffsets[20]), CSPFT_FLOAT }, + {"attachViewModelOffsetX8", offsetof(WeaponFullDef, weapVariantDef.attachViewModelOffsets[21]), CSPFT_FLOAT }, + {"attachViewModelOffsetY8", offsetof(WeaponFullDef, weapVariantDef.attachViewModelOffsets[22]), CSPFT_FLOAT }, + {"attachViewModelOffsetZ8", offsetof(WeaponFullDef, weapVariantDef.attachViewModelOffsets[23]), CSPFT_FLOAT }, + {"attachWorldModelOffsetX1", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelOffsets[0]), CSPFT_FLOAT }, + {"attachWorldModelOffsetY1", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelOffsets[1]), CSPFT_FLOAT }, + {"attachWorldModelOffsetZ1", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelOffsets[2]), CSPFT_FLOAT }, + {"attachWorldModelOffsetX2", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelOffsets[3]), CSPFT_FLOAT }, + {"attachWorldModelOffsetY2", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelOffsets[4]), CSPFT_FLOAT }, + {"attachWorldModelOffsetZ2", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelOffsets[5]), CSPFT_FLOAT }, + {"attachWorldModelOffsetX3", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelOffsets[6]), CSPFT_FLOAT }, + {"attachWorldModelOffsetY3", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelOffsets[7]), CSPFT_FLOAT }, + {"attachWorldModelOffsetZ3", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelOffsets[8]), CSPFT_FLOAT }, + {"attachWorldModelOffsetX4", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelOffsets[9]), CSPFT_FLOAT }, + {"attachWorldModelOffsetY4", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelOffsets[10]), CSPFT_FLOAT }, + {"attachWorldModelOffsetZ4", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelOffsets[11]), CSPFT_FLOAT }, + {"attachWorldModelOffsetX5", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelOffsets[12]), CSPFT_FLOAT }, + {"attachWorldModelOffsetY5", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelOffsets[13]), CSPFT_FLOAT }, + {"attachWorldModelOffsetZ5", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelOffsets[14]), CSPFT_FLOAT }, + {"attachWorldModelOffsetX6", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelOffsets[15]), CSPFT_FLOAT }, + {"attachWorldModelOffsetY6", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelOffsets[16]), CSPFT_FLOAT }, + {"attachWorldModelOffsetZ6", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelOffsets[17]), CSPFT_FLOAT }, + {"attachWorldModelOffsetX7", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelOffsets[18]), CSPFT_FLOAT }, + {"attachWorldModelOffsetY7", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelOffsets[19]), CSPFT_FLOAT }, + {"attachWorldModelOffsetZ7", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelOffsets[20]), CSPFT_FLOAT }, + {"attachWorldModelOffsetX8", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelOffsets[21]), CSPFT_FLOAT }, + {"attachWorldModelOffsetY8", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelOffsets[22]), CSPFT_FLOAT }, + {"attachWorldModelOffsetZ8", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelOffsets[23]), CSPFT_FLOAT }, + {"attachViewModelOffsetPitch1", offsetof(WeaponFullDef, weapVariantDef.attachViewModelRotations[0]), CSPFT_FLOAT }, + {"attachViewModelOffsetYaw1", offsetof(WeaponFullDef, weapVariantDef.attachViewModelRotations[1]), CSPFT_FLOAT }, + {"attachViewModelOffsetRoll1", offsetof(WeaponFullDef, weapVariantDef.attachViewModelRotations[2]), CSPFT_FLOAT }, + {"attachViewModelOffsetPitch2", offsetof(WeaponFullDef, weapVariantDef.attachViewModelRotations[3]), CSPFT_FLOAT }, + {"attachViewModelOffsetYaw2", offsetof(WeaponFullDef, weapVariantDef.attachViewModelRotations[4]), CSPFT_FLOAT }, + {"attachViewModelOffsetRoll2", offsetof(WeaponFullDef, weapVariantDef.attachViewModelRotations[5]), CSPFT_FLOAT }, + {"attachViewModelOffsetPitch3", offsetof(WeaponFullDef, weapVariantDef.attachViewModelRotations[6]), CSPFT_FLOAT }, + {"attachViewModelOffsetYaw3", offsetof(WeaponFullDef, weapVariantDef.attachViewModelRotations[7]), CSPFT_FLOAT }, + {"attachViewModelOffsetRoll3", offsetof(WeaponFullDef, weapVariantDef.attachViewModelRotations[8]), CSPFT_FLOAT }, + {"attachViewModelOffsetPitch4", offsetof(WeaponFullDef, weapVariantDef.attachViewModelRotations[9]), CSPFT_FLOAT }, + {"attachViewModelOffsetYaw4", offsetof(WeaponFullDef, weapVariantDef.attachViewModelRotations[10]), CSPFT_FLOAT }, + {"attachViewModelOffsetRoll4", offsetof(WeaponFullDef, weapVariantDef.attachViewModelRotations[11]), CSPFT_FLOAT }, + {"attachViewModelOffsetPitch5", offsetof(WeaponFullDef, weapVariantDef.attachViewModelRotations[12]), CSPFT_FLOAT }, + {"attachViewModelOffsetYaw5", offsetof(WeaponFullDef, weapVariantDef.attachViewModelRotations[13]), CSPFT_FLOAT }, + {"attachViewModelOffsetRoll5", offsetof(WeaponFullDef, weapVariantDef.attachViewModelRotations[14]), CSPFT_FLOAT }, + {"attachViewModelOffsetPitch6", offsetof(WeaponFullDef, weapVariantDef.attachViewModelRotations[15]), CSPFT_FLOAT }, + {"attachViewModelOffsetYaw6", offsetof(WeaponFullDef, weapVariantDef.attachViewModelRotations[16]), CSPFT_FLOAT }, + {"attachViewModelOffsetRoll6", offsetof(WeaponFullDef, weapVariantDef.attachViewModelRotations[17]), CSPFT_FLOAT }, + {"attachViewModelOffsetPitch7", offsetof(WeaponFullDef, weapVariantDef.attachViewModelRotations[18]), CSPFT_FLOAT }, + {"attachViewModelOffsetYaw7", offsetof(WeaponFullDef, weapVariantDef.attachViewModelRotations[19]), CSPFT_FLOAT }, + {"attachViewModelOffsetRoll7", offsetof(WeaponFullDef, weapVariantDef.attachViewModelRotations[20]), CSPFT_FLOAT }, + {"attachViewModelOffsetPitch8", offsetof(WeaponFullDef, weapVariantDef.attachViewModelRotations[21]), CSPFT_FLOAT }, + {"attachViewModelOffsetYaw8", offsetof(WeaponFullDef, weapVariantDef.attachViewModelRotations[22]), CSPFT_FLOAT }, + {"attachViewModelOffsetRoll8", offsetof(WeaponFullDef, weapVariantDef.attachViewModelRotations[23]), CSPFT_FLOAT }, + {"attachWorldModelOffsetPitch1", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelRotations[0]), CSPFT_FLOAT }, + {"attachWorldModelOffsetYaw1", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelRotations[1]), CSPFT_FLOAT }, + {"attachWorldModelOffsetRoll1", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelRotations[2]), CSPFT_FLOAT }, + {"attachWorldModelOffsetPitch2", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelRotations[3]), CSPFT_FLOAT }, + {"attachWorldModelOffsetYaw2", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelRotations[4]), CSPFT_FLOAT }, + {"attachWorldModelOffsetRoll2", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelRotations[5]), CSPFT_FLOAT }, + {"attachWorldModelOffsetPitch3", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelRotations[6]), CSPFT_FLOAT }, + {"attachWorldModelOffsetYaw3", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelRotations[7]), CSPFT_FLOAT }, + {"attachWorldModelOffsetRoll3", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelRotations[8]), CSPFT_FLOAT }, + {"attachWorldModelOffsetPitch4", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelRotations[9]), CSPFT_FLOAT }, + {"attachWorldModelOffsetYaw4", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelRotations[10]), CSPFT_FLOAT }, + {"attachWorldModelOffsetRoll4", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelRotations[11]), CSPFT_FLOAT }, + {"attachWorldModelOffsetPitch5", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelRotations[12]), CSPFT_FLOAT }, + {"attachWorldModelOffsetYaw5", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelRotations[13]), CSPFT_FLOAT }, + {"attachWorldModelOffsetRoll5", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelRotations[14]), CSPFT_FLOAT }, + {"attachWorldModelOffsetPitch6", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelRotations[15]), CSPFT_FLOAT }, + {"attachWorldModelOffsetYaw6", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelRotations[16]), CSPFT_FLOAT }, + {"attachWorldModelOffsetRoll6", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelRotations[17]), CSPFT_FLOAT }, + {"attachWorldModelOffsetPitch7", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelRotations[18]), CSPFT_FLOAT }, + {"attachWorldModelOffsetYaw7", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelRotations[19]), CSPFT_FLOAT }, + {"attachWorldModelOffsetRoll7", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelRotations[20]), CSPFT_FLOAT }, + {"attachWorldModelOffsetPitch8", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelRotations[21]), CSPFT_FLOAT }, + {"attachWorldModelOffsetYaw8", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelRotations[22]), CSPFT_FLOAT }, + {"attachWorldModelOffsetRoll8", offsetof(WeaponFullDef, weapVariantDef.attachWorldModelRotations[23]), CSPFT_FLOAT }, + {"ignoreAttachments", offsetof(WeaponFullDef, weapVariantDef.bIgnoreAttachments), CSPFT_BOOL }, + {"stowedModelOffsetsF", offsetof(WeaponFullDef, weapVariantDef.stowedModelOffsets.x), CSPFT_FLOAT }, + {"stowedModelOffsetsR", offsetof(WeaponFullDef, weapVariantDef.stowedModelOffsets.y), CSPFT_FLOAT }, + {"stowedModelOffsetsU", offsetof(WeaponFullDef, weapVariantDef.stowedModelOffsets.z), CSPFT_FLOAT }, + {"stowedModelOffsetsPitch", offsetof(WeaponFullDef, weapVariantDef.stowedModelRotations.x), CSPFT_FLOAT }, + {"stowedModelOffsetsYaw", offsetof(WeaponFullDef, weapVariantDef.stowedModelRotations.y), CSPFT_FLOAT }, + {"stowedModelOffsetsRoll", offsetof(WeaponFullDef, weapVariantDef.stowedModelRotations.z), CSPFT_FLOAT }, + {"worldClipModel", offsetof(WeaponFullDef, weapDef.worldClipModel), CSPFT_XMODEL }, + {"rocketModel", offsetof(WeaponFullDef, weapDef.rocketModel), CSPFT_XMODEL }, + {"mountedModel", offsetof(WeaponFullDef, weapDef.mountedModel), CSPFT_XMODEL }, + {"AdditionalMeleeModel", offsetof(WeaponFullDef, weapDef.additionalMeleeModel), CSPFT_XMODEL }, + {"fireTypeIcon", offsetof(WeaponFullDef, weapDef.fireTypeIcon), CSPFT_MATERIAL }, + {"hudIcon", offsetof(WeaponFullDef, weapDef.hudIcon), CSPFT_MATERIAL }, + {"hudIconRatio", offsetof(WeaponFullDef, weapDef.hudIconRatio), WFT_ICONRATIO_HUD }, + {"indicatorIcon", offsetof(WeaponFullDef, weapDef.indicatorIcon), CSPFT_MATERIAL }, + {"indicatorIconRatio", offsetof(WeaponFullDef, weapDef.indicatorIconRatio), WFT_ICONRATIO_INDICATOR }, + {"ammoCounterIcon", offsetof(WeaponFullDef, weapDef.ammoCounterIcon), CSPFT_MATERIAL }, + {"ammoCounterIconRatio", offsetof(WeaponFullDef, weapDef.ammoCounterIconRatio), WFT_ICONRATIO_AMMOCOUNTER}, + {"ammoCounterClip", offsetof(WeaponFullDef, weapDef.ammoCounterClip), WFT_AMMOCOUNTER_CLIPTYPE }, + {"startAmmo", offsetof(WeaponFullDef, weapDef.iStartAmmo), CSPFT_INT }, + {"ammoDisplayName", offsetof(WeaponFullDef, weapVariantDef.szAmmoDisplayName), CSPFT_STRING }, + {"ammoName", offsetof(WeaponFullDef, weapVariantDef.szAmmoName), CSPFT_STRING }, + {"clipName", offsetof(WeaponFullDef, weapVariantDef.szClipName), CSPFT_STRING }, + {"maxAmmo", offsetof(WeaponFullDef, weapDef.iMaxAmmo), CSPFT_INT }, + {"clipSize", offsetof(WeaponFullDef, weapVariantDef.iClipSize), CSPFT_INT }, + {"shotCount", offsetof(WeaponFullDef, weapDef.shotCount), CSPFT_INT }, + {"sharedAmmoCapName", offsetof(WeaponFullDef, weapDef.szSharedAmmoCapName), CSPFT_STRING }, + {"sharedAmmoCap", offsetof(WeaponFullDef, weapDef.iSharedAmmoCap), CSPFT_INT }, + {"unlimitedAmmo", offsetof(WeaponFullDef, weapDef.unlimitedAmmo), CSPFT_BOOL }, + {"ammoCountClipRelative", offsetof(WeaponFullDef, weapDef.ammoCountClipRelative), CSPFT_BOOL }, + {"sharedAmmo", offsetof(WeaponFullDef, weapDef.sharedAmmo), CSPFT_BOOL }, + {"jamFireTime", offsetof(WeaponFullDef, weapDef.iJamFireTime), CSPFT_MILLISECONDS }, + {"overheatWeapon", offsetof(WeaponFullDef, weapDef.overheatWeapon), CSPFT_INT }, + {"overheatRate", offsetof(WeaponFullDef, weapDef.overheatRate), CSPFT_FLOAT }, + {"cooldownRate", offsetof(WeaponFullDef, weapDef.cooldownRate), CSPFT_FLOAT }, + {"overheatEndVal", offsetof(WeaponFullDef, weapDef.overheatEndVal), CSPFT_FLOAT }, + {"coolWhileFiring", offsetof(WeaponFullDef, weapDef.coolWhileFiring), CSPFT_INT }, + {"fuelTankWeapon", offsetof(WeaponFullDef, weapDef.fuelTankWeapon), CSPFT_INT }, + {"tankLifeTime", offsetof(WeaponFullDef, weapDef.iTankLifeTime), CSPFT_MILLISECONDS }, + {"damage", offsetof(WeaponFullDef, weapDef.damage[0]), CSPFT_INT }, + {"minDamage", offsetof(WeaponFullDef, weapDef.damage[5]), CSPFT_INT }, + {"maxDamageRange", offsetof(WeaponFullDef, weapDef.damageRange[0]), CSPFT_FLOAT }, + {"minDamageRange", offsetof(WeaponFullDef, weapDef.damageRange[5]), CSPFT_FLOAT }, + {"damage2", offsetof(WeaponFullDef, weapDef.damage[1]), CSPFT_INT }, + {"damage3", offsetof(WeaponFullDef, weapDef.damage[2]), CSPFT_INT }, + {"damage4", offsetof(WeaponFullDef, weapDef.damage[3]), CSPFT_INT }, + {"damage5", offsetof(WeaponFullDef, weapDef.damage[4]), CSPFT_INT }, + {"damageRange2", offsetof(WeaponFullDef, weapDef.damageRange[1]), CSPFT_FLOAT }, + {"damageRange3", offsetof(WeaponFullDef, weapDef.damageRange[2]), CSPFT_FLOAT }, + {"damageRange4", offsetof(WeaponFullDef, weapDef.damageRange[3]), CSPFT_FLOAT }, + {"damageRange5", offsetof(WeaponFullDef, weapDef.damageRange[4]), CSPFT_FLOAT }, + {"damageDuration", offsetof(WeaponFullDef, weapDef.damageDuration), CSPFT_FLOAT }, + {"damageInterval", offsetof(WeaponFullDef, weapDef.damageInterval), CSPFT_FLOAT }, + {"playerDamage", offsetof(WeaponFullDef, weapDef.playerDamage), CSPFT_INT }, + {"meleeDamage", offsetof(WeaponFullDef, weapDef.iMeleeDamage), CSPFT_INT }, + {"minPlayerDamage", offsetof(WeaponFullDef, weapDef.minPlayerDamage), CSPFT_INT }, + {"destabilizationRateTime", offsetof(WeaponFullDef, weapDef.destabilizationRateTime), CSPFT_FLOAT }, + {"destabilizationCurvatureMax", offsetof(WeaponFullDef, weapDef.destabilizationCurvatureMax), CSPFT_FLOAT }, + {"destabilizeDistance", offsetof(WeaponFullDef, weapDef.destabilizeDistance), CSPFT_INT }, + {"fireDelay", offsetof(WeaponFullDef, weapDef.iFireDelay), CSPFT_MILLISECONDS }, + {"meleeDelay", offsetof(WeaponFullDef, weapDef.iMeleeDelay), CSPFT_MILLISECONDS }, + {"meleeChargeDelay", offsetof(WeaponFullDef, weapDef.meleeChargeDelay), CSPFT_MILLISECONDS }, + {"spinUpTime", offsetof(WeaponFullDef, weapDef.iSpinUpTime), CSPFT_MILLISECONDS }, + {"spinDownTime", offsetof(WeaponFullDef, weapDef.iSpinDownTime), CSPFT_MILLISECONDS }, + {"spinRate", offsetof(WeaponFullDef, weapDef.spinRate), CSPFT_FLOAT }, + {"spinLoopSound", offsetof(WeaponFullDef, weapDef.spinLoopSound), CSPFT_STRING }, + {"spinLoopSoundPlayer", offsetof(WeaponFullDef, weapDef.spinLoopSoundPlayer), CSPFT_STRING }, + {"startSpinSound", offsetof(WeaponFullDef, weapDef.startSpinSound), CSPFT_STRING }, + {"startSpinSoundPlayer", offsetof(WeaponFullDef, weapDef.startSpinSoundPlayer), CSPFT_STRING }, + {"stopSpinSound", offsetof(WeaponFullDef, weapDef.stopSpinSound), CSPFT_STRING }, + {"stopSpinSoundPlayer", offsetof(WeaponFullDef, weapDef.stopSpinSoundPlayer), CSPFT_STRING }, + {"applySpinPitch", offsetof(WeaponFullDef, weapDef.applySpinPitch), CSPFT_BOOL }, + {"introFireTime", offsetof(WeaponFullDef, weapDef.iIntroFireTime), CSPFT_MILLISECONDS }, + {"introFireLength", offsetof(WeaponFullDef, weapDef.iIntroFireLength), CSPFT_INT }, + {"fireTime", offsetof(WeaponFullDef, weapDef.iFireTime), CSPFT_MILLISECONDS }, + {"flourishTime", offsetof(WeaponFullDef, weapDef.iFlourishTime), CSPFT_MILLISECONDS }, + {"lastFireTime", offsetof(WeaponFullDef, weapDef.iLastFireTime), CSPFT_MILLISECONDS }, + {"rechamberTime", offsetof(WeaponFullDef, weapDef.iRechamberTime), CSPFT_MILLISECONDS }, + {"rechamberBoltTime", offsetof(WeaponFullDef, weapDef.iRechamberBoltTime), CSPFT_MILLISECONDS }, + {"holdFireTime", offsetof(WeaponFullDef, weapDef.iHoldFireTime), CSPFT_MILLISECONDS }, + {"burstFireDelay", offsetof(WeaponFullDef, weapDef.iBurstDelayTime), CSPFT_MILLISECONDS }, + {"detonateTime", offsetof(WeaponFullDef, weapDef.iDetonateTime), CSPFT_MILLISECONDS }, + {"detonateDelay", offsetof(WeaponFullDef, weapDef.iDetonateDelay), CSPFT_MILLISECONDS }, + {"meleeTime", offsetof(WeaponFullDef, weapDef.iMeleeTime), CSPFT_MILLISECONDS }, + {"meleeChargeTime", offsetof(WeaponFullDef, weapDef.meleeChargeTime), CSPFT_MILLISECONDS }, + {"reloadTime", offsetof(WeaponFullDef, weapVariantDef.iReloadTime), CSPFT_MILLISECONDS }, + {"reloadShowRocketTime", offsetof(WeaponFullDef, weapDef.reloadShowRocketTime), CSPFT_MILLISECONDS }, + {"reloadEmptyTime", offsetof(WeaponFullDef, weapVariantDef.iReloadEmptyTime), CSPFT_MILLISECONDS }, + {"reloadAddTime", offsetof(WeaponFullDef, weapDef.iReloadAddTime), CSPFT_MILLISECONDS }, + {"reloadEmptyAddTime", offsetof(WeaponFullDef, weapDef.iReloadEmptyAddTime), CSPFT_MILLISECONDS }, + {"reloadQuickAddTime", offsetof(WeaponFullDef, weapDef.iReloadQuickAddTime), CSPFT_MILLISECONDS }, + {"reloadQuickEmptyAddTime", offsetof(WeaponFullDef, weapDef.iReloadQuickEmptyAddTime), CSPFT_MILLISECONDS }, + {"reloadStartTime", offsetof(WeaponFullDef, weapDef.iReloadStartTime), CSPFT_MILLISECONDS }, + {"reloadStartAddTime", offsetof(WeaponFullDef, weapDef.iReloadStartAddTime), CSPFT_MILLISECONDS }, + {"reloadEndTime", offsetof(WeaponFullDef, weapDef.iReloadEndTime), CSPFT_MILLISECONDS }, + {"reloadQuickTime", offsetof(WeaponFullDef, weapVariantDef.iReloadQuickTime), CSPFT_MILLISECONDS }, + {"reloadQuickEmptyTime", offsetof(WeaponFullDef, weapVariantDef.iReloadQuickEmptyTime), CSPFT_MILLISECONDS }, + {"dropTime", offsetof(WeaponFullDef, weapDef.iDropTime), CSPFT_MILLISECONDS }, + {"raiseTime", offsetof(WeaponFullDef, weapDef.iRaiseTime), CSPFT_MILLISECONDS }, + {"altDropTime", offsetof(WeaponFullDef, weapDef.iAltDropTime), CSPFT_MILLISECONDS }, + {"altRaiseTime", offsetof(WeaponFullDef, weapVariantDef.iAltRaiseTime), CSPFT_MILLISECONDS }, + {"quickDropTime", offsetof(WeaponFullDef, weapDef.quickDropTime), CSPFT_MILLISECONDS }, + {"quickRaiseTime", offsetof(WeaponFullDef, weapDef.quickRaiseTime), CSPFT_MILLISECONDS }, + {"firstRaiseTime", offsetof(WeaponFullDef, weapDef.iFirstRaiseTime), CSPFT_MILLISECONDS }, + {"emptyRaiseTime", offsetof(WeaponFullDef, weapDef.iEmptyRaiseTime), CSPFT_MILLISECONDS }, + {"emptyDropTime", offsetof(WeaponFullDef, weapDef.iEmptyDropTime), CSPFT_MILLISECONDS }, + {"sprintInTime", offsetof(WeaponFullDef, weapDef.sprintInTime), CSPFT_MILLISECONDS }, + {"sprintLoopTime", offsetof(WeaponFullDef, weapDef.sprintLoopTime), CSPFT_MILLISECONDS }, + {"sprintOutTime", offsetof(WeaponFullDef, weapDef.sprintOutTime), CSPFT_MILLISECONDS }, + {"lowReadyInTime", offsetof(WeaponFullDef, weapDef.lowReadyInTime), CSPFT_MILLISECONDS }, + {"lowReadyLoopTime", offsetof(WeaponFullDef, weapDef.lowReadyLoopTime), CSPFT_MILLISECONDS }, + {"lowReadyOutTime", offsetof(WeaponFullDef, weapDef.lowReadyOutTime), CSPFT_MILLISECONDS }, + {"contFireInTime", offsetof(WeaponFullDef, weapDef.contFireInTime), CSPFT_MILLISECONDS }, + {"contFireLoopTime", offsetof(WeaponFullDef, weapDef.contFireLoopTime), CSPFT_MILLISECONDS }, + {"contFireOutTime", offsetof(WeaponFullDef, weapDef.contFireOutTime), CSPFT_MILLISECONDS }, + {"dtpInTime", offsetof(WeaponFullDef, weapDef.dtpInTime), CSPFT_MILLISECONDS }, + {"dtpLoopTime", offsetof(WeaponFullDef, weapDef.dtpLoopTime), CSPFT_MILLISECONDS }, + {"dtpOutTime", offsetof(WeaponFullDef, weapDef.dtpOutTime), CSPFT_MILLISECONDS }, + {"crawlInTime", offsetof(WeaponFullDef, weapDef.crawlInTime), CSPFT_MILLISECONDS }, + {"crawlForwardTime", offsetof(WeaponFullDef, weapDef.crawlForwardTime), CSPFT_MILLISECONDS }, + {"crawlBackTime", offsetof(WeaponFullDef, weapDef.crawlBackTime), CSPFT_MILLISECONDS }, + {"crawlRightTime", offsetof(WeaponFullDef, weapDef.crawlRightTime), CSPFT_MILLISECONDS }, + {"crawlLeftTime", offsetof(WeaponFullDef, weapDef.crawlLeftTime), CSPFT_MILLISECONDS }, + {"crawlOutFireTime", offsetof(WeaponFullDef, weapDef.crawlOutFireTime), CSPFT_MILLISECONDS }, + {"crawlOutTime", offsetof(WeaponFullDef, weapDef.crawlOutTime), CSPFT_MILLISECONDS }, + {"slideInTime", offsetof(WeaponFullDef, weapDef.slideInTime), CSPFT_MILLISECONDS }, + {"deployTime", offsetof(WeaponFullDef, weapDef.deployTime), CSPFT_MILLISECONDS }, + {"breakdownTime", offsetof(WeaponFullDef, weapDef.breakdownTime), CSPFT_MILLISECONDS }, + {"nightVisionWearTime", offsetof(WeaponFullDef, weapDef.nightVisionWearTime), CSPFT_MILLISECONDS }, + {"nightVisionWearTimeFadeOutEnd", offsetof(WeaponFullDef, weapDef.nightVisionWearTimeFadeOutEnd), CSPFT_MILLISECONDS }, + {"nightVisionWearTimePowerUp", offsetof(WeaponFullDef, weapDef.nightVisionWearTimePowerUp), CSPFT_MILLISECONDS }, + {"nightVisionRemoveTime", offsetof(WeaponFullDef, weapDef.nightVisionRemoveTime), CSPFT_MILLISECONDS }, + {"nightVisionRemoveTimePowerDown", offsetof(WeaponFullDef, weapDef.nightVisionRemoveTimePowerDown), CSPFT_MILLISECONDS }, + {"nightVisionRemoveTimeFadeInStart", offsetof(WeaponFullDef, weapDef.nightVisionRemoveTimeFadeInStart), CSPFT_MILLISECONDS }, + {"fuseTime", offsetof(WeaponFullDef, weapDef.fuseTime), CSPFT_MILLISECONDS }, + {"aifuseTime", offsetof(WeaponFullDef, weapDef.aiFuseTime), CSPFT_MILLISECONDS }, + {"lockOnRadius", offsetof(WeaponFullDef, weapDef.lockOnRadius), CSPFT_INT }, + {"lockOnSpeed", offsetof(WeaponFullDef, weapDef.lockOnSpeed), CSPFT_INT }, + {"requireLockonToFire", offsetof(WeaponFullDef, weapDef.requireLockonToFire), CSPFT_BOOL }, + {"noAdsWhenMagEmpty", offsetof(WeaponFullDef, weapDef.noAdsWhenMagEmpty), CSPFT_BOOL }, + {"avoidDropCleanup", offsetof(WeaponFullDef, weapDef.avoidDropCleanup), CSPFT_BOOL }, + {"stackFire", offsetof(WeaponFullDef, weapDef.stackFire), CSPFT_INT }, + {"stackFireSpread", offsetof(WeaponFullDef, weapDef.stackFireSpread), CSPFT_FLOAT }, + {"stackFireAccuracyDecay", offsetof(WeaponFullDef, weapDef.stackFireAccuracyDecay), CSPFT_FLOAT }, + {"stackSound", offsetof(WeaponFullDef, weapDef.stackSound), CSPFT_STRING }, + {"autoAimRange", offsetof(WeaponFullDef, weapDef.autoAimRange), CSPFT_FLOAT }, + {"aimAssistRange", offsetof(WeaponFullDef, weapDef.aimAssistRange), CSPFT_FLOAT }, + {"aimAssistRangeAds", offsetof(WeaponFullDef, weapVariantDef.fAimAssistRangeAds), CSPFT_FLOAT }, + {"mountableWeapon", offsetof(WeaponFullDef, weapDef.mountableWeapon), CSPFT_BOOL }, + {"aimPadding", offsetof(WeaponFullDef, weapDef.aimPadding), CSPFT_FLOAT }, + {"enemyCrosshairRange", offsetof(WeaponFullDef, weapDef.enemyCrosshairRange), CSPFT_FLOAT }, + {"crosshairColorChange", offsetof(WeaponFullDef, weapDef.crosshairColorChange), CSPFT_BOOL }, + {"moveSpeedScale", offsetof(WeaponFullDef, weapDef.moveSpeedScale), CSPFT_FLOAT }, + {"adsMoveSpeedScale", offsetof(WeaponFullDef, weapDef.adsMoveSpeedScale), CSPFT_FLOAT }, + {"sprintDurationScale", offsetof(WeaponFullDef, weapDef.sprintDurationScale), CSPFT_FLOAT }, + {"idleCrouchFactor", offsetof(WeaponFullDef, weapDef.fIdleCrouchFactor), CSPFT_FLOAT }, + {"idleProneFactor", offsetof(WeaponFullDef, weapDef.fIdleProneFactor), CSPFT_FLOAT }, + {"gunMaxPitch", offsetof(WeaponFullDef, weapDef.fGunMaxPitch), CSPFT_FLOAT }, + {"gunMaxYaw", offsetof(WeaponFullDef, weapDef.fGunMaxYaw), CSPFT_FLOAT }, + {"swayMaxAngle", offsetof(WeaponFullDef, weapDef.swayMaxAngle), CSPFT_FLOAT }, + {"swayLerpSpeed", offsetof(WeaponFullDef, weapDef.swayLerpSpeed), CSPFT_FLOAT }, + {"swayPitchScale", offsetof(WeaponFullDef, weapDef.swayPitchScale), CSPFT_FLOAT }, + {"swayYawScale", offsetof(WeaponFullDef, weapDef.swayYawScale), CSPFT_FLOAT }, + {"swayHorizScale", offsetof(WeaponFullDef, weapDef.swayHorizScale), CSPFT_FLOAT }, + {"swayVertScale", offsetof(WeaponFullDef, weapDef.swayVertScale), CSPFT_FLOAT }, + {"swayShellShockScale", offsetof(WeaponFullDef, weapDef.swayShellShockScale), CSPFT_FLOAT }, + {"adsSwayMaxAngle", offsetof(WeaponFullDef, weapDef.adsSwayMaxAngle), CSPFT_FLOAT }, + {"adsSwayLerpSpeed", offsetof(WeaponFullDef, weapDef.adsSwayLerpSpeed), CSPFT_FLOAT }, + {"adsSwayPitchScale", offsetof(WeaponFullDef, weapDef.adsSwayPitchScale), CSPFT_FLOAT }, + {"adsSwayYawScale", offsetof(WeaponFullDef, weapDef.adsSwayYawScale), CSPFT_FLOAT }, + {"adsSwayHorizScale", offsetof(WeaponFullDef, weapVariantDef.fAdsSwayHorizScale), CSPFT_FLOAT }, + {"adsSwayVertScale", offsetof(WeaponFullDef, weapVariantDef.fAdsSwayVertScale), CSPFT_FLOAT }, + {"meleeChargeRange", offsetof(WeaponFullDef, weapDef.meleeChargeRange), CSPFT_FLOAT }, + {"rifleBullet", offsetof(WeaponFullDef, weapDef.bRifleBullet), CSPFT_BOOL }, + {"armorPiercing", offsetof(WeaponFullDef, weapDef.armorPiercing), CSPFT_BOOL }, + {"boltAction", offsetof(WeaponFullDef, weapDef.bBoltAction), CSPFT_BOOL }, + {"shotsBeforeRechamber", offsetof(WeaponFullDef, weapDef.iShotsBeforeRechamber), CSPFT_INT }, + {"useAltTagFlash", offsetof(WeaponFullDef, weapDef.bUseAltTagFlash), CSPFT_BOOL }, + {"useAntiLagRewind", offsetof(WeaponFullDef, weapDef.bUseAntiLagRewind), CSPFT_BOOL }, + {"isCarriedKillstreakWeapon", offsetof(WeaponFullDef, weapDef.bIsCarriedKillstreakWeapon), CSPFT_BOOL }, + {"aimDownSight", offsetof(WeaponFullDef, weapDef.aimDownSight), CSPFT_BOOL }, + {"rechamberWhileAds", offsetof(WeaponFullDef, weapDef.bRechamberWhileAds), CSPFT_BOOL }, + {"reloadWhileAds", offsetof(WeaponFullDef, weapDef.bReloadWhileAds), CSPFT_BOOL }, + {"adsViewErrorMin", offsetof(WeaponFullDef, weapDef.adsViewErrorMin), CSPFT_FLOAT }, + {"adsViewErrorMax", offsetof(WeaponFullDef, weapDef.adsViewErrorMax), CSPFT_FLOAT }, + {"clipOnly", offsetof(WeaponFullDef, weapDef.bClipOnly), CSPFT_BOOL }, + {"canUseInVehicle", offsetof(WeaponFullDef, weapDef.bCanUseInVehicle), CSPFT_BOOL }, + {"noDropsOrRaises", offsetof(WeaponFullDef, weapDef.bNoDropsOrRaises), CSPFT_BOOL }, + {"cookOffHold", offsetof(WeaponFullDef, weapDef.bCookOffHold), CSPFT_BOOL }, + {"adsFire", offsetof(WeaponFullDef, weapDef.adsFireOnly), CSPFT_BOOL }, + {"cancelAutoHolsterWhenEmpty", offsetof(WeaponFullDef, weapDef.cancelAutoHolsterWhenEmpty), CSPFT_BOOL }, + {"suppressAmmoReserveDisplay", offsetof(WeaponFullDef, weapDef.suppressAmmoReserveDisplay), CSPFT_BOOL }, + {"laserSight", offsetof(WeaponFullDef, weapDef.laserSight), CSPFT_BOOL }, + {"laserSightDuringNightvision", offsetof(WeaponFullDef, weapDef.laserSightDuringNightvision), CSPFT_BOOL }, + {"bayonet", offsetof(WeaponFullDef, weapDef.bHasBayonet), CSPFT_BOOL }, + {"dualWield", offsetof(WeaponFullDef, weapDef.bDualWield), CSPFT_BOOL }, + {"hideThirdPerson", offsetof(WeaponFullDef, weapDef.bHideThirdPerson), CSPFT_BOOL }, + {"explodeOnGround", offsetof(WeaponFullDef, weapDef.bExplodeOnGround), CSPFT_BOOL }, + {"throwBack", offsetof(WeaponFullDef, weapDef.bThrowBack), CSPFT_BOOL }, + {"retrievable", offsetof(WeaponFullDef, weapDef.bRetrievable), CSPFT_BOOL }, + {"dieOnRespawn", offsetof(WeaponFullDef, weapDef.bDieOnRespawn), CSPFT_BOOL }, + {"noThirdPersonDropsOrRaises", offsetof(WeaponFullDef, weapDef.bNoThirdPersonDropsOrRaises), CSPFT_BOOL }, + {"continuousFire", offsetof(WeaponFullDef, weapDef.bContinuousFire), CSPFT_BOOL }, + {"useAsMelee", offsetof(WeaponFullDef, weapDef.bUseAsMelee), CSPFT_BOOL }, + {"antiQuickScope", offsetof(WeaponFullDef, weapVariantDef.bAntiQuickScope), CSPFT_BOOL }, + {"noPing", offsetof(WeaponFullDef, weapDef.bNoPing), CSPFT_BOOL }, + {"forceBounce", offsetof(WeaponFullDef, weapDef.bForceBounce), CSPFT_BOOL }, + {"useDroppedModelAsStowed", offsetof(WeaponFullDef, weapDef.bUseDroppedModelAsStowed), CSPFT_BOOL }, + {"noQuickDropWhenEmpty", offsetof(WeaponFullDef, weapDef.bNoQuickDropWhenEmpty), CSPFT_BOOL }, + {"keepCrosshairWhenADS", offsetof(WeaponFullDef, weapDef.bKeepCrosshairWhenADS), CSPFT_BOOL }, + {"useOnlyAltWeaoponHideTagsInAltMode", offsetof(WeaponFullDef, weapDef.bUseOnlyAltWeaoponHideTagsInAltMode), CSPFT_BOOL }, + {"altWeaponAdsOnly", offsetof(WeaponFullDef, weapDef.bAltWeaponAdsOnly), CSPFT_BOOL }, + {"altWeaponDisableSwitching", offsetof(WeaponFullDef, weapDef.bAltWeaponDisableSwitching), CSPFT_BOOL }, + {"killIcon", offsetof(WeaponFullDef, weapDef.killIcon), CSPFT_MATERIAL }, + {"killIconRatio", offsetof(WeaponFullDef, weapDef.killIconRatio), WFT_ICONRATIO_KILL }, + {"flipKillIcon", offsetof(WeaponFullDef, weapDef.flipKillIcon), CSPFT_BOOL }, + {"dpadIcon", offsetof(WeaponFullDef, weapVariantDef.dpadIcon), CSPFT_MATERIAL }, + {"dpadIconRatio", offsetof(WeaponFullDef, weapVariantDef.dpadIconRatio), WFT_ICONRATIO_DPAD }, + {"noAmmoOnDpadIcon", offsetof(WeaponFullDef, weapVariantDef.noAmmoOnDpadIcon), CSPFT_BOOL }, + {"noPartialReload", offsetof(WeaponFullDef, weapDef.bNoPartialReload), CSPFT_BOOL }, + {"segmentedReload", offsetof(WeaponFullDef, weapDef.bSegmentedReload), CSPFT_BOOL }, + {"noADSAutoReload", offsetof(WeaponFullDef, weapDef.bNoADSAutoReload), CSPFT_BOOL }, + {"reloadAmmoAdd", offsetof(WeaponFullDef, weapDef.iReloadAmmoAdd), CSPFT_INT }, + {"reloadStartAdd", offsetof(WeaponFullDef, weapDef.iReloadStartAdd), CSPFT_INT }, + {"attachmentUnique", offsetof(WeaponFullDef, weapVariantDef.szAttachmentUnique), CSPFT_STRING }, + {"altWeapon", offsetof(WeaponFullDef, weapVariantDef.szAltWeaponName), CSPFT_STRING }, + {"DualWieldWeapon", offsetof(WeaponFullDef, weapDef.szDualWieldWeaponName), CSPFT_STRING }, + {"grenadeWeapon", offsetof(WeaponFullDef, weapDef.szSpawnedGrenadeWeaponName), CSPFT_STRING }, + {"dropAmmoMin", offsetof(WeaponFullDef, weapDef.iDropAmmoMin), CSPFT_INT }, + {"dropAmmoMax", offsetof(WeaponFullDef, weapDef.iDropAmmoMax), CSPFT_INT }, + {"dropClipAmmoMin", offsetof(WeaponFullDef, weapDef.iDropClipAmmoMin), CSPFT_INT }, + {"dropClipAmmoMax", offsetof(WeaponFullDef, weapDef.iDropClipAmmoMax), CSPFT_INT }, + {"blocksProne", offsetof(WeaponFullDef, weapDef.blocksProne), CSPFT_BOOL }, + {"silenced", offsetof(WeaponFullDef, weapVariantDef.bSilenced), CSPFT_BOOL }, + {"dualMag", offsetof(WeaponFullDef, weapVariantDef.bDualMag), CSPFT_BOOL }, + {"infrared", offsetof(WeaponFullDef, weapVariantDef.bInfraRed), CSPFT_BOOL }, + {"tvguided", offsetof(WeaponFullDef, weapVariantDef.bTVGuided), CSPFT_BOOL }, + {"airburstWeapon", offsetof(WeaponFullDef, weapDef.bAirburstWeapon), CSPFT_BOOL }, + {"perks1", offsetof(WeaponFullDef, weapVariantDef.perks[0]), CSPFT_UINT }, + {"perks0", offsetof(WeaponFullDef, weapVariantDef.perks[1]), CSPFT_UINT }, + {"isRollingGrenade", offsetof(WeaponFullDef, weapDef.isRollingGrenade), CSPFT_QBOOLEAN }, + {"useBallisticPrediction", offsetof(WeaponFullDef, weapDef.useBallisticPrediction), CSPFT_QBOOLEAN }, + {"isValuable", offsetof(WeaponFullDef, weapDef.isValuable), CSPFT_QBOOLEAN }, + {"isTacticalInsertion", offsetof(WeaponFullDef, weapDef.isTacticalInsertion), CSPFT_QBOOLEAN }, + {"isReviveWeapon", offsetof(WeaponFullDef, weapDef.isReviveWeapon), CSPFT_BOOL }, + {"bUseRigidBodyOnVehicle", offsetof(WeaponFullDef, weapDef.bUseRigidBodyOnVehicle), CSPFT_BOOL }, + {"showIndicator", offsetof(WeaponFullDef, weapDef.bShowIndicator), CSPFT_BOOL }, + {"explosionRadius", offsetof(WeaponFullDef, weapDef.iExplosionRadius), CSPFT_INT }, + {"explosionRadiusMin", offsetof(WeaponFullDef, weapDef.iExplosionRadiusMin), CSPFT_INT }, + {"indicatorRadius", offsetof(WeaponFullDef, weapDef.iIndicatorRadius), CSPFT_INT }, + {"explosionInnerDamage", offsetof(WeaponFullDef, weapDef.iExplosionInnerDamage), CSPFT_INT }, + {"explosionOuterDamage", offsetof(WeaponFullDef, weapDef.iExplosionOuterDamage), CSPFT_INT }, + {"damageConeAngle", offsetof(WeaponFullDef, weapDef.damageConeAngle), CSPFT_FLOAT }, + {"projectileSpeed", offsetof(WeaponFullDef, weapDef.iProjectileSpeed), CSPFT_INT }, + {"projectileSpeedRelativeUp", offsetof(WeaponFullDef, weapDef.iProjectileSpeedRelativeUp), CSPFT_INT }, + {"projectileSpeedUp", offsetof(WeaponFullDef, weapDef.iProjectileSpeedUp), CSPFT_INT }, + {"projectileSpeedForward", offsetof(WeaponFullDef, weapDef.iProjectileSpeedForward), CSPFT_INT }, + {"projectileTakeParentVel", offsetof(WeaponFullDef, weapDef.fProjectileTakeParentVelocity), CSPFT_FLOAT }, + {"projectileActivateDist", offsetof(WeaponFullDef, weapDef.iProjectileActivateDist), CSPFT_INT }, + {"projectileLifetime", offsetof(WeaponFullDef, weapDef.projLifetime), CSPFT_FLOAT }, + {"timeToAccelerate", offsetof(WeaponFullDef, weapDef.timeToAccelerate), CSPFT_FLOAT }, + {"projectileCurvature", offsetof(WeaponFullDef, weapDef.projectileCurvature), CSPFT_FLOAT }, + {"projectileModel", offsetof(WeaponFullDef, weapDef.projectileModel), CSPFT_XMODEL }, + {"projExplosionType", offsetof(WeaponFullDef, weapDef.projExplosion), WFT_PROJ_EXPLOSION }, + {"projExplosionEffect", offsetof(WeaponFullDef, weapDef.projExplosionEffect), CSPFT_FX }, + {"projExplosionEffectForceNormalUp", offsetof(WeaponFullDef, weapDef.projExplosionEffectForceNormalUp), CSPFT_BOOL }, + {"projExplosionEffect2", offsetof(WeaponFullDef, weapDef.projExplosionEffect2), CSPFT_FX }, + {"projExplosionEffect2ForceNormalUp", offsetof(WeaponFullDef, weapDef.projExplosionEffect2ForceNormalUp), CSPFT_BOOL }, + {"projExplosionEffect3", offsetof(WeaponFullDef, weapDef.projExplosionEffect3), CSPFT_FX }, + {"projExplosionEffect3ForceNormalUp", offsetof(WeaponFullDef, weapDef.projExplosionEffect3ForceNormalUp), CSPFT_BOOL }, + {"projExplosionEffect4", offsetof(WeaponFullDef, weapDef.projExplosionEffect4), CSPFT_FX }, + {"projExplosionEffect4ForceNormalUp", offsetof(WeaponFullDef, weapDef.projExplosionEffect4ForceNormalUp), CSPFT_BOOL }, + {"projExplosionEffect5", offsetof(WeaponFullDef, weapDef.projExplosionEffect5), CSPFT_FX }, + {"projExplosionEffect5ForceNormalUp", offsetof(WeaponFullDef, weapDef.projExplosionEffect5ForceNormalUp), CSPFT_BOOL }, + {"projExplosionSound", offsetof(WeaponFullDef, weapDef.projExplosionSound), CSPFT_STRING }, + {"projDudEffect", offsetof(WeaponFullDef, weapDef.projDudEffect), CSPFT_FX }, + {"projDudSound", offsetof(WeaponFullDef, weapDef.projDudSound), CSPFT_STRING }, + {"projImpactExplode", offsetof(WeaponFullDef, weapDef.bProjImpactExplode), CSPFT_BOOL }, + {"sentientImpactExplode", offsetof(WeaponFullDef, weapDef.bProjSentientImpactExplode), CSPFT_BOOL }, + {"explodeWhenStationary", offsetof(WeaponFullDef, weapDef.bProjExplodeWhenStationary), CSPFT_BOOL }, + {"bulletImpactExplode", offsetof(WeaponFullDef, weapDef.bBulletImpactExplode), CSPFT_BOOL }, + {"mortarShellSound", offsetof(WeaponFullDef, weapDef.mortarShellSound), CSPFT_STRING }, + {"tankShellSound", offsetof(WeaponFullDef, weapDef.tankShellSound), CSPFT_STRING }, + {"stickiness", offsetof(WeaponFullDef, weapDef.stickiness), WFT_STICKINESS }, + {"rotateType", offsetof(WeaponFullDef, weapDef.rotateType), WFT_ROTATETYPE }, + {"hasDetonator", offsetof(WeaponFullDef, weapDef.hasDetonator), CSPFT_BOOL }, + {"plantable", offsetof(WeaponFullDef, weapDef.plantable), CSPFT_BOOL }, + {"timedDetonation", offsetof(WeaponFullDef, weapDef.timedDetonation), CSPFT_BOOL }, + {"noCrumpleMissile", offsetof(WeaponFullDef, weapDef.bNoCrumpleMissile), CSPFT_BOOL }, + {"rotate", offsetof(WeaponFullDef, weapDef.rotate), CSPFT_BOOL }, + {"keepRolling", offsetof(WeaponFullDef, weapDef.bKeepRolling), CSPFT_BOOL }, + {"holdButtonToThrow", offsetof(WeaponFullDef, weapDef.holdButtonToThrow), CSPFT_BOOL }, + {"offhandHoldIsCancelable", offsetof(WeaponFullDef, weapDef.offhandHoldIsCancelable), CSPFT_BOOL }, + {"freezeMovementWhenFiring", offsetof(WeaponFullDef, weapDef.freezeMovementWhenFiring), CSPFT_BOOL }, + {"lowAmmoWarningThreshold", offsetof(WeaponFullDef, weapDef.lowAmmoWarningThreshold), CSPFT_FLOAT }, + {"explosionTag", offsetof(WeaponFullDef, weapDef.explosionTag), WFT_EXPLOSION_TAG }, + {"bDisallowAtMatchStart", offsetof(WeaponFullDef, weapDef.bDisallowAtMatchStart), CSPFT_BOOL }, + {"isCameraSensor", offsetof(WeaponFullDef, weapDef.isCameraSensor), CSPFT_BOOL }, + {"isAcousticSensor", offsetof(WeaponFullDef, weapDef.isAcousticSensor), CSPFT_BOOL }, + {"isLaserSensor", offsetof(WeaponFullDef, weapDef.isLaserSensor), CSPFT_BOOL }, + {"isHoldUseGrenade", offsetof(WeaponFullDef, weapDef.isHoldUseGrenade), CSPFT_BOOL }, + {"parallelDefaultBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_DEFAULT]), CSPFT_FLOAT }, + {"parallelAsphaltBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_ASPHALT]), CSPFT_FLOAT }, + {"parallelBarkBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_BARK]), CSPFT_FLOAT }, + {"parallelBrickBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_BRICK]), CSPFT_FLOAT }, + {"parallelCarpetBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_CARPET]), CSPFT_FLOAT }, + {"parallelCeramicBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_CERAMIC]), CSPFT_FLOAT }, + {"parallelClothBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_CLOTH]), CSPFT_FLOAT }, + {"parallelConcreteBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_CONCRETE]), CSPFT_FLOAT }, + {"parallelCushionBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_CUSHION]), CSPFT_FLOAT }, + {"parallelDirtBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_DIRT]), CSPFT_FLOAT }, + {"parallelFleshBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_FLESH]), CSPFT_FLOAT }, + {"parallelFoliageBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_FOLIAGE]), CSPFT_FLOAT }, + {"parallelFruitBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_FRUIT]), CSPFT_FLOAT }, + {"parallelGlassBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_GLASS]), CSPFT_FLOAT }, + {"parallelGrassBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_GRASS]), CSPFT_FLOAT }, + {"parallelGravelBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_GRAVEL]), CSPFT_FLOAT }, + {"parallelIceBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_ICE]), CSPFT_FLOAT }, + {"parallelMetalBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_METAL]), CSPFT_FLOAT }, + {"parallelMudBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_MUD]), CSPFT_FLOAT }, + {"parallelPaintedMetalBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_PAINTED_METAL]), CSPFT_FLOAT }, + {"parallelPaperBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_PAPER]), CSPFT_FLOAT }, + {"parallelPlasterBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_PLASTER]), CSPFT_FLOAT }, + {"parallelPlasticBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_PLASTIC]), CSPFT_FLOAT }, + {"parallelRockBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_ROCK]), CSPFT_FLOAT }, + {"parallelRubberBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_RUBBER]), CSPFT_FLOAT }, + {"parallelSandBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_SAND]), CSPFT_FLOAT }, + {"parallelSnowBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_SNOW]), CSPFT_FLOAT }, + {"parallelWaterBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_WATER]), CSPFT_FLOAT }, + {"parallelWoodBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_WOOD]), CSPFT_FLOAT }, + {"parallelRiotShieldBounce", offsetof(WeaponFullDef, parallelBounce[SURF_TYPE_RIOT_SHIELD]), CSPFT_FLOAT }, + {"perpendicularDefaultBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_DEFAULT]), CSPFT_FLOAT }, + {"perpendicularAsphaltBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_ASPHALT]), CSPFT_FLOAT }, + {"perpendicularBarkBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_BARK]), CSPFT_FLOAT }, + {"perpendicularBrickBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_BRICK]), CSPFT_FLOAT }, + {"perpendicularCarpetBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_CARPET]), CSPFT_FLOAT }, + {"perpendicularCeramicBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_CERAMIC]), CSPFT_FLOAT }, + {"perpendicularClothBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_CLOTH]), CSPFT_FLOAT }, + {"perpendicularConcreteBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_CONCRETE]), CSPFT_FLOAT }, + {"perpendicularCushionBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_CUSHION]), CSPFT_FLOAT }, + {"perpendicularDirtBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_DIRT]), CSPFT_FLOAT }, + {"perpendicularFleshBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_FLESH]), CSPFT_FLOAT }, + {"perpendicularFoliageBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_FOLIAGE]), CSPFT_FLOAT }, + {"perpendicularFruitBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_FRUIT]), CSPFT_FLOAT }, + {"perpendicularGlassBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_GLASS]), CSPFT_FLOAT }, + {"perpendicularGrassBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_GRASS]), CSPFT_FLOAT }, + {"perpendicularGravelBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_GRAVEL]), CSPFT_FLOAT }, + {"perpendicularIceBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_ICE]), CSPFT_FLOAT }, + {"perpendicularMetalBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_METAL]), CSPFT_FLOAT }, + {"perpendicularMudBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_MUD]), CSPFT_FLOAT }, + {"perpendicularPaintedMetalBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_PAINTED_METAL]), CSPFT_FLOAT }, + {"perpendicularPaperBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_PAPER]), CSPFT_FLOAT }, + {"perpendicularPlasterBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_PLASTER]), CSPFT_FLOAT }, + {"perpendicularPlasticBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_PLASTIC]), CSPFT_FLOAT }, + {"perpendicularRockBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_ROCK]), CSPFT_FLOAT }, + {"perpendicularRubberBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_RUBBER]), CSPFT_FLOAT }, + {"perpendicularSandBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_SAND]), CSPFT_FLOAT }, + {"perpendicularSnowBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_SNOW]), CSPFT_FLOAT }, + {"perpendicularWaterBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_WATER]), CSPFT_FLOAT }, + {"perpendicularWoodBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_WOOD]), CSPFT_FLOAT }, + {"perpendicularRiotShieldBounce", offsetof(WeaponFullDef, perpendicularBounce[SURF_TYPE_RIOT_SHIELD]), CSPFT_FLOAT }, + {"projTrailEffect", offsetof(WeaponFullDef, weapDef.projTrailEffect), CSPFT_FX }, + {"projectileRed", offsetof(WeaponFullDef, weapDef.vProjectileColor.x), CSPFT_FLOAT }, + {"projectileGreen", offsetof(WeaponFullDef, weapDef.vProjectileColor.y), CSPFT_FLOAT }, + {"projectileBlue", offsetof(WeaponFullDef, weapDef.vProjectileColor.z), CSPFT_FLOAT }, + {"guidedMissileType", offsetof(WeaponFullDef, weapDef.guidedMissileType), WFT_GUIDED_MISSILE_TYPE }, + {"maxSteeringAccel", offsetof(WeaponFullDef, weapDef.maxSteeringAccel), CSPFT_FLOAT }, + {"projIgnitionDelay", offsetof(WeaponFullDef, weapDef.projIgnitionDelay), CSPFT_INT }, + {"projIgnitionEffect", offsetof(WeaponFullDef, weapDef.projIgnitionEffect), CSPFT_FX }, + {"projIgnitionSound", offsetof(WeaponFullDef, weapDef.projIgnitionSound), CSPFT_STRING }, + {"tagFx_preparationEffect", offsetof(WeaponFullDef, weapDef.tagFx_preparationEffect), CSPFT_FX }, + {"tagFlash_preparationEffect", offsetof(WeaponFullDef, weapDef.tagFlash_preparationEffect), CSPFT_FX }, + {"adsTransInTime", offsetof(WeaponFullDef, weapVariantDef.iAdsTransInTime), CSPFT_MILLISECONDS }, + {"adsTransOutTime", offsetof(WeaponFullDef, weapVariantDef.iAdsTransOutTime), CSPFT_MILLISECONDS }, + {"adsIdleAmount", offsetof(WeaponFullDef, weapDef.fAdsIdleAmount), CSPFT_FLOAT }, + {"adsIdleSpeed", offsetof(WeaponFullDef, weapDef.adsIdleSpeed), CSPFT_FLOAT }, + {"adsZoomFov1", offsetof(WeaponFullDef, weapVariantDef.fAdsZoomFov1), CSPFT_FLOAT }, + {"adsZoomFov2", offsetof(WeaponFullDef, weapVariantDef.fAdsZoomFov2), CSPFT_FLOAT }, + {"adsZoomFov3", offsetof(WeaponFullDef, weapVariantDef.fAdsZoomFov3), CSPFT_FLOAT }, + {"adsZoomInFrac", offsetof(WeaponFullDef, weapVariantDef.fAdsZoomInFrac), CSPFT_FLOAT }, + {"adsZoomOutFrac", offsetof(WeaponFullDef, weapVariantDef.fAdsZoomOutFrac), CSPFT_FLOAT }, + {"adsOverlayShader", offsetof(WeaponFullDef, weapVariantDef.overlayMaterial), CSPFT_MATERIAL_STREAM }, + {"adsOverlayShaderLowRes", offsetof(WeaponFullDef, weapVariantDef.overlayMaterialLowRes), CSPFT_MATERIAL_STREAM }, + {"adsOverlayReticle", offsetof(WeaponFullDef, weapDef.overlayReticle), WFT_OVERLAYRETICLE }, + {"adsOverlayInterface", offsetof(WeaponFullDef, weapDef.overlayInterface), WFT_OVERLAYINTERFACE }, + {"adsOverlayWidth", offsetof(WeaponFullDef, weapDef.overlayWidth), CSPFT_FLOAT }, + {"adsOverlayHeight", offsetof(WeaponFullDef, weapDef.overlayHeight), CSPFT_FLOAT }, + {"adsOverlayAlphaScale", offsetof(WeaponFullDef, weapVariantDef.fOverlayAlphaScale), CSPFT_FLOAT }, + {"adsBobFactor", offsetof(WeaponFullDef, weapDef.fAdsBobFactor), CSPFT_FLOAT }, + {"adsViewBobMult", offsetof(WeaponFullDef, weapDef.fAdsViewBobMult), CSPFT_FLOAT }, + {"holdBreathToSteady", offsetof(WeaponFullDef, weapDef.bHoldBreathToSteady), CSPFT_BOOL }, + {"adsAimPitch", offsetof(WeaponFullDef, weapDef.fAdsAimPitch), CSPFT_FLOAT }, + {"adsCrosshairInFrac", offsetof(WeaponFullDef, weapDef.fAdsCrosshairInFrac), CSPFT_FLOAT }, + {"adsCrosshairOutFrac", offsetof(WeaponFullDef, weapDef.fAdsCrosshairOutFrac), CSPFT_FLOAT }, + {"adsReloadTransTime", offsetof(WeaponFullDef, weapDef.iPositionReloadTransTime), CSPFT_MILLISECONDS }, + {"adsGunKickReducedKickBullets", offsetof(WeaponFullDef, weapDef.adsGunKickReducedKickBullets), CSPFT_INT }, + {"adsGunKickReducedKickPercent", offsetof(WeaponFullDef, weapDef.adsGunKickReducedKickPercent), CSPFT_FLOAT }, + {"adsGunKickPitchMin", offsetof(WeaponFullDef, weapDef.fAdsGunKickPitchMin), CSPFT_FLOAT }, + {"adsGunKickPitchMax", offsetof(WeaponFullDef, weapDef.fAdsGunKickPitchMax), CSPFT_FLOAT }, + {"adsGunKickYawMin", offsetof(WeaponFullDef, weapDef.fAdsGunKickYawMin), CSPFT_FLOAT }, + {"adsGunKickYawMax", offsetof(WeaponFullDef, weapDef.fAdsGunKickYawMax), CSPFT_FLOAT }, + {"adsGunKickAccel", offsetof(WeaponFullDef, weapDef.fAdsGunKickAccel), CSPFT_FLOAT }, + {"adsGunKickSpeedMax", offsetof(WeaponFullDef, weapDef.fAdsGunKickSpeedMax), CSPFT_FLOAT }, + {"adsGunKickSpeedDecay", offsetof(WeaponFullDef, weapDef.fAdsGunKickSpeedDecay), CSPFT_FLOAT }, + {"adsGunKickStaticDecay", offsetof(WeaponFullDef, weapDef.fAdsGunKickStaticDecay), CSPFT_FLOAT }, + {"adsViewKickPitchMin", offsetof(WeaponFullDef, weapDef.fAdsViewKickPitchMin), CSPFT_FLOAT }, + {"adsViewKickPitchMax", offsetof(WeaponFullDef, weapDef.fAdsViewKickPitchMax), CSPFT_FLOAT }, + {"adsViewKickMinMagnitude", offsetof(WeaponFullDef, weapDef.fAdsViewKickMinMagnitude), CSPFT_FLOAT }, + {"adsViewKickYawMin", offsetof(WeaponFullDef, weapDef.fAdsViewKickYawMin), CSPFT_FLOAT }, + {"adsViewKickYawMax", offsetof(WeaponFullDef, weapDef.fAdsViewKickYawMax), CSPFT_FLOAT }, + {"adsRecoilReductionRate", offsetof(WeaponFullDef, weapDef.fAdsRecoilReductionRate), CSPFT_FLOAT }, + {"adsRecoilReductionLimit", offsetof(WeaponFullDef, weapDef.fAdsRecoilReductionLimit), CSPFT_FLOAT }, + {"adsRecoilReturnRate", offsetof(WeaponFullDef, weapDef.fAdsRecoilReturnRate), CSPFT_FLOAT }, + {"adsViewKickCenterSpeed", offsetof(WeaponFullDef, weapVariantDef.fAdsViewKickCenterSpeed), CSPFT_FLOAT }, + {"adsViewKickCenterDuckedScale", offsetof(WeaponFullDef, weapDef.fAdsViewKickCenterDuckedScale), CSPFT_FLOAT }, + {"adsViewKickCenterProneScale", offsetof(WeaponFullDef, weapDef.fAdsViewKickCenterProneScale), CSPFT_FLOAT }, + {"adsSpread", offsetof(WeaponFullDef, weapDef.fAdsSpread), CSPFT_FLOAT }, + {"guidedMissileType", offsetof(WeaponFullDef, weapDef.guidedMissileType), WFT_GUIDED_MISSILE_TYPE }, + {"antiQuickScopeTime", offsetof(WeaponFullDef, weapDef.fAntiQuickScopeTime), CSPFT_FLOAT }, + {"antiQuickScopeScale", offsetof(WeaponFullDef, weapDef.fAntiQuickScopeScale), CSPFT_FLOAT }, + {"antiQuickScopeSpreadMultiplier", offsetof(WeaponFullDef, weapDef.fAntiQuickScopeSpreadMultiplier), CSPFT_FLOAT }, + {"antiQuickScopeSpreadMax", offsetof(WeaponFullDef, weapDef.fAntiQuickScopeSpreadMax), CSPFT_FLOAT }, + {"antiQuickScopeSwayFactor", offsetof(WeaponFullDef, weapDef.fAntiQuickScopeSwayFactor), CSPFT_FLOAT }, + {"hipSpreadStandMin", offsetof(WeaponFullDef, weapDef.fHipSpreadStandMin), CSPFT_FLOAT }, + {"hipSpreadDuckedMin", offsetof(WeaponFullDef, weapDef.fHipSpreadDuckedMin), CSPFT_FLOAT }, + {"hipSpreadProneMin", offsetof(WeaponFullDef, weapDef.fHipSpreadProneMin), CSPFT_FLOAT }, + {"hipSpreadMax", offsetof(WeaponFullDef, weapDef.hipSpreadStandMax), CSPFT_FLOAT }, + {"hipSpreadDuckedMax", offsetof(WeaponFullDef, weapDef.hipSpreadDuckedMax), CSPFT_FLOAT }, + {"hipSpreadProneMax", offsetof(WeaponFullDef, weapDef.hipSpreadProneMax), CSPFT_FLOAT }, + {"hipSpreadDecayRate", offsetof(WeaponFullDef, weapDef.fHipSpreadDecayRate), CSPFT_FLOAT }, + {"hipSpreadFireAdd", offsetof(WeaponFullDef, weapDef.fHipSpreadFireAdd), CSPFT_FLOAT }, + {"hipSpreadTurnAdd", offsetof(WeaponFullDef, weapDef.fHipSpreadTurnAdd), CSPFT_FLOAT }, + {"hipSpreadMoveAdd", offsetof(WeaponFullDef, weapDef.fHipSpreadMoveAdd), CSPFT_FLOAT }, + {"hipSpreadDuckedDecay", offsetof(WeaponFullDef, weapDef.fHipSpreadDuckedDecay), CSPFT_FLOAT }, + {"hipSpreadProneDecay", offsetof(WeaponFullDef, weapDef.fHipSpreadProneDecay), CSPFT_FLOAT }, + {"hipReticleSidePos", offsetof(WeaponFullDef, weapDef.fHipReticleSidePos), CSPFT_FLOAT }, + {"hipIdleAmount", offsetof(WeaponFullDef, weapDef.fHipIdleAmount), CSPFT_FLOAT }, + {"hipIdleSpeed", offsetof(WeaponFullDef, weapDef.hipIdleSpeed), CSPFT_FLOAT }, + {"hipGunKickReducedKickBullets", offsetof(WeaponFullDef, weapDef.hipGunKickReducedKickBullets), CSPFT_INT }, + {"hipGunKickReducedKickPercent", offsetof(WeaponFullDef, weapDef.hipGunKickReducedKickPercent), CSPFT_FLOAT }, + {"hipGunKickPitchMin", offsetof(WeaponFullDef, weapDef.fHipGunKickPitchMin), CSPFT_FLOAT }, + {"hipGunKickPitchMax", offsetof(WeaponFullDef, weapDef.fHipGunKickPitchMax), CSPFT_FLOAT }, + {"hipGunKickYawMin", offsetof(WeaponFullDef, weapDef.fHipGunKickYawMin), CSPFT_FLOAT }, + {"hipGunKickYawMax", offsetof(WeaponFullDef, weapDef.fHipGunKickYawMax), CSPFT_FLOAT }, + {"hipGunKickAccel", offsetof(WeaponFullDef, weapDef.fHipGunKickAccel), CSPFT_FLOAT }, + {"hipGunKickSpeedMax", offsetof(WeaponFullDef, weapDef.fHipGunKickSpeedMax), CSPFT_FLOAT }, + {"hipGunKickSpeedDecay", offsetof(WeaponFullDef, weapDef.fHipGunKickSpeedDecay), CSPFT_FLOAT }, + {"hipGunKickStaticDecay", offsetof(WeaponFullDef, weapDef.fHipGunKickStaticDecay), CSPFT_FLOAT }, + {"hipViewKickPitchMin", offsetof(WeaponFullDef, weapDef.fHipViewKickPitchMin), CSPFT_FLOAT }, + {"hipViewKickPitchMax", offsetof(WeaponFullDef, weapDef.fHipViewKickPitchMax), CSPFT_FLOAT }, + {"hipViewKickMinMagnitude", offsetof(WeaponFullDef, weapDef.fHipViewKickMinMagnitude), CSPFT_FLOAT }, + {"hipViewKickYawMin", offsetof(WeaponFullDef, weapDef.fHipViewKickYawMin), CSPFT_FLOAT }, + {"hipViewKickYawMax", offsetof(WeaponFullDef, weapDef.fHipViewKickYawMax), CSPFT_FLOAT }, + {"hipViewKickCenterSpeed", offsetof(WeaponFullDef, weapVariantDef.fHipViewKickCenterSpeed), CSPFT_FLOAT }, + {"leftArc", offsetof(WeaponFullDef, weapDef.leftArc), CSPFT_FLOAT }, + {"rightArc", offsetof(WeaponFullDef, weapDef.rightArc), CSPFT_FLOAT }, + {"topArc", offsetof(WeaponFullDef, weapDef.topArc), CSPFT_FLOAT }, + {"bottomArc", offsetof(WeaponFullDef, weapDef.bottomArc), CSPFT_FLOAT }, + {"accuracy", offsetof(WeaponFullDef, weapDef.accuracy), CSPFT_FLOAT }, + {"aiSpread", offsetof(WeaponFullDef, weapDef.aiSpread), CSPFT_FLOAT }, + {"playerSpread", offsetof(WeaponFullDef, weapDef.playerSpread), CSPFT_FLOAT }, + {"maxVertTurnSpeed", offsetof(WeaponFullDef, weapDef.maxTurnSpeed[0]), CSPFT_FLOAT }, + {"maxHorTurnSpeed", offsetof(WeaponFullDef, weapDef.maxTurnSpeed[1]), CSPFT_FLOAT }, + {"minVertTurnSpeed", offsetof(WeaponFullDef, weapDef.minTurnSpeed[0]), CSPFT_FLOAT }, + {"minHorTurnSpeed", offsetof(WeaponFullDef, weapDef.minTurnSpeed[1]), CSPFT_FLOAT }, + {"pitchConvergenceTime", offsetof(WeaponFullDef, weapDef.pitchConvergenceTime), CSPFT_FLOAT }, + {"yawConvergenceTime", offsetof(WeaponFullDef, weapDef.yawConvergenceTime), CSPFT_FLOAT }, + {"suppressionTime", offsetof(WeaponFullDef, weapDef.suppressTime), CSPFT_FLOAT }, + {"maxRange", offsetof(WeaponFullDef, weapDef.maxRange), CSPFT_FLOAT }, + {"animHorRotateInc", offsetof(WeaponFullDef, weapDef.fAnimHorRotateInc), CSPFT_FLOAT }, + {"playerPositionDist", offsetof(WeaponFullDef, weapDef.fPlayerPositionDist), CSPFT_FLOAT }, + {"stance", offsetof(WeaponFullDef, weapDef.stance), WFT_STANCE }, + {"useHintString", offsetof(WeaponFullDef, weapDef.szUseHintString), CSPFT_STRING }, + {"dropHintString", offsetof(WeaponFullDef, weapDef.dropHintString), CSPFT_STRING }, + {"horizViewJitter", offsetof(WeaponFullDef, weapDef.horizViewJitter), CSPFT_FLOAT }, + {"vertViewJitter", offsetof(WeaponFullDef, weapDef.vertViewJitter), CSPFT_FLOAT }, + {"cameraShakeScale", offsetof(WeaponFullDef, weapDef.cameraShakeScale), CSPFT_FLOAT }, + {"cameraShakeDuration", offsetof(WeaponFullDef, weapDef.cameraShakeDuration), CSPFT_INT }, + {"cameraShakeRadius", offsetof(WeaponFullDef, weapDef.cameraShakeRadius), CSPFT_INT }, + {"explosionCameraShakeScale", offsetof(WeaponFullDef, weapDef.explosionCameraShakeScale), CSPFT_FLOAT }, + {"explosionCameraShakeDuration", offsetof(WeaponFullDef, weapDef.explosionCameraShakeDuration), CSPFT_INT }, + {"explosionCameraShakeRadius", offsetof(WeaponFullDef, weapDef.explosionCameraShakeRadius), CSPFT_INT }, + {"fightDist", offsetof(WeaponFullDef, weapDef.fightDist), CSPFT_FLOAT }, + {"maxDist", offsetof(WeaponFullDef, weapDef.maxDist), CSPFT_FLOAT }, + {"aiVsAiAccuracyGraph", offsetof(WeaponFullDef, weapDef.accuracyGraphName0), CSPFT_STRING }, + {"aiVsPlayerAccuracyGraph", offsetof(WeaponFullDef, weapDef.accuracyGraphName1), CSPFT_STRING }, + {"locNone", offsetof(WeaponFullDef, locationDamageMultipliers[HITLOC_NONE]), CSPFT_FLOAT }, + {"locHelmet", offsetof(WeaponFullDef, locationDamageMultipliers[HITLOC_HELMET]), CSPFT_FLOAT }, + {"locHead", offsetof(WeaponFullDef, locationDamageMultipliers[HITLOC_HEAD]), CSPFT_FLOAT }, + {"locNeck", offsetof(WeaponFullDef, locationDamageMultipliers[HITLOC_NECK]), CSPFT_FLOAT }, + {"locTorsoUpper", offsetof(WeaponFullDef, locationDamageMultipliers[HITLOC_TORSO_UPR]), CSPFT_FLOAT }, + {"locTorsoMid", offsetof(WeaponFullDef, locationDamageMultipliers[HITLOC_TORSO_MID]), CSPFT_FLOAT }, + {"locTorsoLower", offsetof(WeaponFullDef, locationDamageMultipliers[HITLOC_TORSO_LWR]), CSPFT_FLOAT }, + {"locRightArmUpper", offsetof(WeaponFullDef, locationDamageMultipliers[HITLOC_R_ARM_UPR]), CSPFT_FLOAT }, + {"locRightArmLower", offsetof(WeaponFullDef, locationDamageMultipliers[HITLOC_R_ARM_LWR]), CSPFT_FLOAT }, + {"locRightHand", offsetof(WeaponFullDef, locationDamageMultipliers[HITLOC_R_HAND]), CSPFT_FLOAT }, + {"locLeftArmUpper", offsetof(WeaponFullDef, locationDamageMultipliers[HITLOC_L_ARM_UPR]), CSPFT_FLOAT }, + {"locLeftArmLower", offsetof(WeaponFullDef, locationDamageMultipliers[HITLOC_L_ARM_LWR]), CSPFT_FLOAT }, + {"locLeftHand", offsetof(WeaponFullDef, locationDamageMultipliers[HITLOC_L_HAND]), CSPFT_FLOAT }, + {"locRightLegUpper", offsetof(WeaponFullDef, locationDamageMultipliers[HITLOC_R_LEG_UPR]), CSPFT_FLOAT }, + {"locRightLegLower", offsetof(WeaponFullDef, locationDamageMultipliers[HITLOC_R_LEG_LWR]), CSPFT_FLOAT }, + {"locRightFoot", offsetof(WeaponFullDef, locationDamageMultipliers[HITLOC_R_FOOT]), CSPFT_FLOAT }, + {"locLeftLegUpper", offsetof(WeaponFullDef, locationDamageMultipliers[HITLOC_L_LEG_UPR]), CSPFT_FLOAT }, + {"locLeftLegLower", offsetof(WeaponFullDef, locationDamageMultipliers[HITLOC_L_LEG_LWR]), CSPFT_FLOAT }, + {"locLeftFoot", offsetof(WeaponFullDef, locationDamageMultipliers[HITLOC_L_FOOT]), CSPFT_FLOAT }, + {"locGun", offsetof(WeaponFullDef, locationDamageMultipliers[HITLOC_GUN]), CSPFT_FLOAT }, + {"fireRumble", offsetof(WeaponFullDef, weapDef.fireRumble), CSPFT_STRING }, + {"meleeImpactRumble", offsetof(WeaponFullDef, weapDef.meleeImpactRumble), CSPFT_STRING }, + {"reloadRumble", offsetof(WeaponFullDef, weapDef.reloadRumble), CSPFT_STRING }, + {"explosionRumble", offsetof(WeaponFullDef, weapDef.explosionRumble), CSPFT_STRING }, + {"tracerType", offsetof(WeaponFullDef, weapDef.tracerType), CSPFT_TRACER }, + {"enemyTracerType", offsetof(WeaponFullDef, weapDef.enemyTracerType), CSPFT_TRACER }, + {"adsDofStart", offsetof(WeaponFullDef, weapDef.adsDofStart), CSPFT_FLOAT }, + {"adsDofEnd", offsetof(WeaponFullDef, weapDef.adsDofEnd), CSPFT_FLOAT }, + {"scanSpeed", offsetof(WeaponFullDef, weapDef.scanSpeed), CSPFT_FLOAT }, + {"scanAccel", offsetof(WeaponFullDef, weapDef.scanAccel), CSPFT_FLOAT }, + {"scanPauseTime", offsetof(WeaponFullDef, weapDef.scanPauseTime), CSPFT_MILLISECONDS }, + {"flameTableFirstPerson", offsetof(WeaponFullDef, weapDef.flameTableFirstPerson), CSPFT_STRING }, + {"flameTableThirdPerson", offsetof(WeaponFullDef, weapDef.flameTableThirdPerson), CSPFT_STRING }, + {"mmsWeapon", offsetof(WeaponFullDef, weapVariantDef.mmsWeapon), CSPFT_BOOL }, + {"mmsInScope", offsetof(WeaponFullDef, weapVariantDef.mmsInScope), CSPFT_BOOL }, + {"mmsFOV", offsetof(WeaponFullDef, weapVariantDef.mmsFOV), CSPFT_FLOAT }, + {"mmsAspect", offsetof(WeaponFullDef, weapVariantDef.mmsAspect), CSPFT_FLOAT }, + {"mmsMaxDist", offsetof(WeaponFullDef, weapVariantDef.mmsMaxDist), CSPFT_FLOAT }, + {"ikLeftHandIdlePosF", offsetof(WeaponFullDef, weapVariantDef.ikLeftHandIdlePos.x), CSPFT_FLOAT }, + {"ikLeftHandIdlePosR", offsetof(WeaponFullDef, weapVariantDef.ikLeftHandIdlePos.y), CSPFT_FLOAT }, + {"ikLeftHandIdlePosU", offsetof(WeaponFullDef, weapVariantDef.ikLeftHandIdlePos.z), CSPFT_FLOAT }, + {"ikLeftHandOffsetF", offsetof(WeaponFullDef, weapVariantDef.ikLeftHandOffset.x), CSPFT_FLOAT }, + {"ikLeftHandOffsetR", offsetof(WeaponFullDef, weapVariantDef.ikLeftHandOffset.y), CSPFT_FLOAT }, + {"ikLeftHandOffsetU", offsetof(WeaponFullDef, weapVariantDef.ikLeftHandOffset.z), CSPFT_FLOAT }, + {"ikLeftHandRotationP", offsetof(WeaponFullDef, weapVariantDef.ikLeftHandRotation.x), CSPFT_FLOAT }, + {"ikLeftHandRotationY", offsetof(WeaponFullDef, weapVariantDef.ikLeftHandRotation.y), CSPFT_FLOAT }, + {"ikLeftHandRotationR", offsetof(WeaponFullDef, weapVariantDef.ikLeftHandRotation.z), CSPFT_FLOAT }, + {"usingLeftHandProneIK", offsetof(WeaponFullDef, weapVariantDef.bUsingLeftHandProneIK), CSPFT_BOOL }, + {"ikLeftHandProneOffsetF", offsetof(WeaponFullDef, weapVariantDef.ikLeftHandProneOffset.x), CSPFT_FLOAT }, + {"ikLeftHandProneOffsetR", offsetof(WeaponFullDef, weapVariantDef.ikLeftHandProneOffset.y), CSPFT_FLOAT }, + {"ikLeftHandProneOffsetU", offsetof(WeaponFullDef, weapVariantDef.ikLeftHandProneOffset.z), CSPFT_FLOAT }, + {"ikLeftHandProneRotationP", offsetof(WeaponFullDef, weapVariantDef.ikLeftHandProneRotation.x), CSPFT_FLOAT }, + {"ikLeftHandProneRotationY", offsetof(WeaponFullDef, weapVariantDef.ikLeftHandProneRotation.y), CSPFT_FLOAT }, + {"ikLeftHandProneRotationR", offsetof(WeaponFullDef, weapVariantDef.ikLeftHandProneRotation.z), CSPFT_FLOAT }, + {"ikLeftHandUiViewerOffsetF", offsetof(WeaponFullDef, weapVariantDef.ikLeftHandUiViewerOffset.x), CSPFT_FLOAT }, + {"ikLeftHandUiViewerOffsetR", offsetof(WeaponFullDef, weapVariantDef.ikLeftHandUiViewerOffset.y), CSPFT_FLOAT }, + {"ikLeftHandUiViewerOffsetU", offsetof(WeaponFullDef, weapVariantDef.ikLeftHandUiViewerOffset.z), CSPFT_FLOAT }, + {"ikLeftHandUiViewerRotationP", offsetof(WeaponFullDef, weapVariantDef.ikLeftHandUiViewerRotation.x), CSPFT_FLOAT }, + {"ikLeftHandUiViewerRotationY", offsetof(WeaponFullDef, weapVariantDef.ikLeftHandUiViewerRotation.y), CSPFT_FLOAT }, + {"ikLeftHandUiViewerRotationR", offsetof(WeaponFullDef, weapVariantDef.ikLeftHandUiViewerRotation.z), CSPFT_FLOAT }, + {"parentWeaponName", offsetof(WeaponFullDef, weapDef.parentWeaponName), CSPFT_STRING }, + {"doGibbing", offsetof(WeaponFullDef, weapDef.doGibbing), CSPFT_BOOL }, + {"maxGibDistance", offsetof(WeaponFullDef, weapDef.maxGibDistance), CSPFT_FLOAT }, + {"altScopeADSTransInTime", offsetof(WeaponFullDef, weapDef.altScopeADSTransInTime), CSPFT_FLOAT }, + {"altScopeADSTransOutTime", offsetof(WeaponFullDef, weapDef.altScopeADSTransOutTime), CSPFT_FLOAT }, + {"meleeSwipeEffect", offsetof(WeaponFullDef, weapDef.meleeSwipeEffect), CSPFT_FX }, + {"meleeImpactEffect", offsetof(WeaponFullDef, weapDef.meleeImpactEffect), CSPFT_FX }, + {"meleeImpactNoBloodEffect", offsetof(WeaponFullDef, weapDef.meleeImpactNoBloodEffect), CSPFT_FX }, + {"throwBackType", offsetof(WeaponFullDef, weapDef.throwBackType), CSPFT_STRING }, + {"camo", offsetof(WeaponFullDef, weapDef.weaponCamo), WFT_WEAPON_CAMO }, + {"customFloat0", offsetof(WeaponFullDef, weapDef.customFloat0), CSPFT_FLOAT }, + {"customFloat1", offsetof(WeaponFullDef, weapDef.customFloat1), CSPFT_FLOAT }, + {"customFloat2", offsetof(WeaponFullDef, weapDef.customFloat2), CSPFT_FLOAT }, + {"customBool0", offsetof(WeaponFullDef, weapDef.customBool0), CSPFT_BOOL }, + {"customBool1", offsetof(WeaponFullDef, weapDef.customBool1), CSPFT_BOOL }, + {"customBool2", offsetof(WeaponFullDef, weapDef.customBool2), CSPFT_BOOL }, + {"attachments", offsetof(WeaponFullDef, attachments), WFT_ATTACHMENTS }, + {"attachmentUniques", offsetof(WeaponFullDef, attachmentUniques), WFT_ATTACHMENT_UNIQUES } +}; } \ No newline at end of file diff --git a/src/ObjCommon/Game/T6/InfoString/ZBarrierFields.h b/src/ObjCommon/Game/T6/InfoString/ZBarrierFields.h index 2d7e3d8f7..1a6d4bcf2 100644 --- a/src/ObjCommon/Game/T6/InfoString/ZBarrierFields.h +++ b/src/ObjCommon/Game/T6/InfoString/ZBarrierFields.h @@ -1,154 +1,152 @@ #pragma once #include "Game/T6/T6.h" -namespace T6 -{ - inline cspField_t zbarrier_fields[] - { - {"delayBetweenGeneralRepSounds", offsetof(ZBarrierDef, delayBetweenRepSoundsDuration), CSPFT_FLOAT}, - {"earthquakeMaxDuration", offsetof(ZBarrierDef, earthquakeMaxDuration), CSPFT_FLOAT}, - {"earthquakeMaxScale", offsetof(ZBarrierDef, earthquakeMaxScale), CSPFT_FLOAT}, - {"earthquakeMinDuration", offsetof(ZBarrierDef, earthquakeMinDuration), CSPFT_FLOAT}, - {"earthquakeMinScale", offsetof(ZBarrierDef, earthquakeMinScale), CSPFT_FLOAT}, - {"earthquakeOnRepair", offsetof(ZBarrierDef, earthquakeOnRepair), CSPFT_UINT}, - {"earthquakeRadius", offsetof(ZBarrierDef, earthquakeRadius), CSPFT_FLOAT}, - {"generalRepairSound0", offsetof(ZBarrierDef, generalRepairSound1), CSPFT_SOUND_ALIAS_ID}, - {"generalRepairSound1", offsetof(ZBarrierDef, generalRepairSound2), CSPFT_SOUND_ALIAS_ID}, - {"upgradedGeneralRepairSound0", offsetof(ZBarrierDef, upgradedGeneralRepairSound1), CSPFT_SOUND_ALIAS_ID}, - {"upgradedGeneralRepairSound1", offsetof(ZBarrierDef, upgradedGeneralRepairSound2), CSPFT_SOUND_ALIAS_ID}, - {"useDelayBetweenGeneralRepSounds", offsetof(ZBarrierDef, delayBetweenRepSounds), CSPFT_UINT}, - {"taunts", offsetof(ZBarrierDef, taunts), CSPFT_UINT}, - {"reachThroughAttacks", offsetof(ZBarrierDef, reachThroughAttacks), CSPFT_UINT}, - {"zombieTauntAnimState", offsetof(ZBarrierDef, zombieTauntAnimState), CSPFT_SCRIPT_STRING}, - {"zombieReachThroughAnimState", offsetof(ZBarrierDef, zombieReachThroughAnimState), CSPFT_SCRIPT_STRING}, - {"numAttackSlots", offsetof(ZBarrierDef, numAttackSlots), CSPFT_UINT}, - {"attackSpotHorzOffset", offsetof(ZBarrierDef, attackSpotHorzOffset), CSPFT_FLOAT}, - {"autoHideOpenPieces", offsetof(ZBarrierDef, autoHideOpenPieces), CSPFT_UINT}, - {"alternateBoardModel1", offsetof(ZBarrierDef, boards[0].pAlternateBoardModel), CSPFT_XMODEL}, - {"boardAnim1", offsetof(ZBarrierDef, boards[0].pBoardAnim), CSPFT_STRING}, - {"boardModel1", offsetof(ZBarrierDef, boards[0].pBoardModel), CSPFT_XMODEL}, - {"boardRepairSound1", offsetof(ZBarrierDef, boards[0].boardRepairSound), CSPFT_SOUND_ALIAS_ID}, - {"boardRepairHoverSound1", offsetof(ZBarrierDef, boards[0].boardRepairHoverSound), CSPFT_SOUND_ALIAS_ID}, - {"OffsetRepairFxX10", offsetof(ZBarrierDef, boards[0].repairEffect1Offset.x), CSPFT_FLOAT}, - {"OffsetRepairFxX11", offsetof(ZBarrierDef, boards[0].repairEffect2Offset.x), CSPFT_FLOAT}, - {"OffsetRepairFxY10", offsetof(ZBarrierDef, boards[0].repairEffect1Offset.y), CSPFT_FLOAT}, - {"OffsetRepairFxY11", offsetof(ZBarrierDef, boards[0].repairEffect2Offset.y), CSPFT_FLOAT}, - {"OffsetRepairFxZ10", offsetof(ZBarrierDef, boards[0].repairEffect1Offset.z), CSPFT_FLOAT}, - {"OffsetRepairFxZ11", offsetof(ZBarrierDef, boards[0].repairEffect2Offset.z), CSPFT_FLOAT}, - {"pauseAndRepeatBoardRepairSound1", offsetof(ZBarrierDef, boards[0].pauseAndRepeatRepSound), CSPFT_UINT}, - {"pauseBetweenRepSoundsMax1", offsetof(ZBarrierDef, boards[0].maxPause), CSPFT_FLOAT}, - {"pauseBetweenRepSoundsMin1", offsetof(ZBarrierDef, boards[0].minPause), CSPFT_FLOAT}, - {"proBoardNumRepsToTear1", offsetof(ZBarrierDef, boards[0].numRepsToPullProBoard), CSPFT_UINT}, - {"repairFx10", offsetof(ZBarrierDef, boards[0].repairEffect1), CSPFT_FX}, - {"repairFx11", offsetof(ZBarrierDef, boards[0].repairEffect2), CSPFT_FX}, - {"tearAnim1", offsetof(ZBarrierDef, boards[0].pTearAnim), CSPFT_STRING}, - {"upgradedBoardModel1", offsetof(ZBarrierDef, boards[0].pUpgradedBoardModel), CSPFT_XMODEL}, - {"zombieBoardTearAnimState1", offsetof(ZBarrierDef, boards[0].zombieBoardTearStateName), CSPFT_SCRIPT_STRING}, - {"zombieBoardTearAnimSubState1", offsetof(ZBarrierDef, boards[0].zombieBoardTearSubStateName), CSPFT_SCRIPT_STRING}, - {"alternateBoardModel2", offsetof(ZBarrierDef, boards[1].pAlternateBoardModel), CSPFT_XMODEL}, - {"boardAnim2", offsetof(ZBarrierDef, boards[1].pBoardAnim), CSPFT_STRING}, - {"boardModel2", offsetof(ZBarrierDef, boards[1].pBoardModel), CSPFT_XMODEL}, - {"boardRepairSound2", offsetof(ZBarrierDef, boards[1].boardRepairSound), CSPFT_SOUND_ALIAS_ID}, - {"boardRepairHoverSound2", offsetof(ZBarrierDef, boards[1].boardRepairHoverSound), CSPFT_SOUND_ALIAS_ID}, - {"OffsetRepairFxX20", offsetof(ZBarrierDef, boards[1].repairEffect1Offset.x), CSPFT_FLOAT}, - {"OffsetRepairFxX21", offsetof(ZBarrierDef, boards[1].repairEffect2Offset.x), CSPFT_FLOAT}, - {"OffsetRepairFxY20", offsetof(ZBarrierDef, boards[1].repairEffect1Offset.y), CSPFT_FLOAT}, - {"OffsetRepairFxY21", offsetof(ZBarrierDef, boards[1].repairEffect2Offset.y), CSPFT_FLOAT}, - {"OffsetRepairFxZ20", offsetof(ZBarrierDef, boards[1].repairEffect1Offset.z), CSPFT_FLOAT}, - {"OffsetRepairFxZ21", offsetof(ZBarrierDef, boards[1].repairEffect2Offset.z), CSPFT_FLOAT}, - {"pauseAndRepeatBoardRepairSound2", offsetof(ZBarrierDef, boards[1].pauseAndRepeatRepSound), CSPFT_UINT}, - {"pauseBetweenRepSoundsMax2", offsetof(ZBarrierDef, boards[1].maxPause), CSPFT_FLOAT}, - {"pauseBetweenRepSoundsMin2", offsetof(ZBarrierDef, boards[1].minPause), CSPFT_FLOAT}, - {"proBoardNumRepsToTear2", offsetof(ZBarrierDef, boards[1].numRepsToPullProBoard), CSPFT_UINT}, - {"repairFx20", offsetof(ZBarrierDef, boards[1].repairEffect1), CSPFT_FX}, - {"repairFx21", offsetof(ZBarrierDef, boards[1].repairEffect2), CSPFT_FX}, - {"tearAnim2", offsetof(ZBarrierDef, boards[1].pTearAnim), CSPFT_STRING}, - {"upgradedBoardModel2", offsetof(ZBarrierDef, boards[1].pUpgradedBoardModel), CSPFT_XMODEL}, - {"zombieBoardTearAnimState2", offsetof(ZBarrierDef, boards[1].zombieBoardTearStateName), CSPFT_SCRIPT_STRING}, - {"zombieBoardTearAnimSubState2", offsetof(ZBarrierDef, boards[1].zombieBoardTearSubStateName), CSPFT_SCRIPT_STRING}, - {"alternateBoardModel3", offsetof(ZBarrierDef, boards[2].pAlternateBoardModel), CSPFT_XMODEL}, - {"boardAnim3", offsetof(ZBarrierDef, boards[2].pBoardAnim), CSPFT_STRING}, - {"boardModel3", offsetof(ZBarrierDef, boards[2].pBoardModel), CSPFT_XMODEL}, - {"boardRepairSound3", offsetof(ZBarrierDef, boards[2].boardRepairSound), CSPFT_SOUND_ALIAS_ID}, - {"boardRepairHoverSound3", offsetof(ZBarrierDef, boards[2].boardRepairHoverSound), CSPFT_SOUND_ALIAS_ID}, - {"OffsetRepairFxX30", offsetof(ZBarrierDef, boards[2].repairEffect1Offset.x), CSPFT_FLOAT}, - {"OffsetRepairFxX31", offsetof(ZBarrierDef, boards[2].repairEffect2Offset.x), CSPFT_FLOAT}, - {"OffsetRepairFxY30", offsetof(ZBarrierDef, boards[2].repairEffect1Offset.y), CSPFT_FLOAT}, - {"OffsetRepairFxY31", offsetof(ZBarrierDef, boards[2].repairEffect2Offset.y), CSPFT_FLOAT}, - {"OffsetRepairFxZ30", offsetof(ZBarrierDef, boards[2].repairEffect1Offset.z), CSPFT_FLOAT}, - {"OffsetRepairFxZ31", offsetof(ZBarrierDef, boards[2].repairEffect2Offset.z), CSPFT_FLOAT}, - {"pauseAndRepeatBoardRepairSound3", offsetof(ZBarrierDef, boards[2].pauseAndRepeatRepSound), CSPFT_UINT}, - {"pauseBetweenRepSoundsMax3", offsetof(ZBarrierDef, boards[2].maxPause), CSPFT_FLOAT}, - {"pauseBetweenRepSoundsMin3", offsetof(ZBarrierDef, boards[2].minPause), CSPFT_FLOAT}, - {"proBoardNumRepsToTear3", offsetof(ZBarrierDef, boards[2].numRepsToPullProBoard), CSPFT_UINT}, - {"repairFx30", offsetof(ZBarrierDef, boards[2].repairEffect1), CSPFT_FX}, - {"repairFx31", offsetof(ZBarrierDef, boards[2].repairEffect2), CSPFT_FX}, - {"tearAnim3", offsetof(ZBarrierDef, boards[2].pTearAnim), CSPFT_STRING}, - {"upgradedBoardModel3", offsetof(ZBarrierDef, boards[2].pUpgradedBoardModel), CSPFT_XMODEL}, - {"zombieBoardTearAnimState3", offsetof(ZBarrierDef, boards[2].zombieBoardTearStateName), CSPFT_SCRIPT_STRING}, - {"zombieBoardTearAnimSubState3", offsetof(ZBarrierDef, boards[2].zombieBoardTearSubStateName), CSPFT_SCRIPT_STRING}, - {"alternateBoardModel4", offsetof(ZBarrierDef, boards[3].pAlternateBoardModel), CSPFT_XMODEL}, - {"boardAnim4", offsetof(ZBarrierDef, boards[3].pBoardAnim), CSPFT_STRING}, - {"boardModel4", offsetof(ZBarrierDef, boards[3].pBoardModel), CSPFT_XMODEL}, - {"boardRepairSound4", offsetof(ZBarrierDef, boards[3].boardRepairSound), CSPFT_SOUND_ALIAS_ID}, - {"boardRepairHoverSound4", offsetof(ZBarrierDef, boards[3].boardRepairHoverSound), CSPFT_SOUND_ALIAS_ID}, - {"OffsetRepairFxX40", offsetof(ZBarrierDef, boards[3].repairEffect1Offset.x), CSPFT_FLOAT}, - {"OffsetRepairFxX41", offsetof(ZBarrierDef, boards[3].repairEffect2Offset.x), CSPFT_FLOAT}, - {"OffsetRepairFxY40", offsetof(ZBarrierDef, boards[3].repairEffect1Offset.y), CSPFT_FLOAT}, - {"OffsetRepairFxY41", offsetof(ZBarrierDef, boards[3].repairEffect2Offset.y), CSPFT_FLOAT}, - {"OffsetRepairFxZ40", offsetof(ZBarrierDef, boards[3].repairEffect1Offset.z), CSPFT_FLOAT}, - {"OffsetRepairFxZ41", offsetof(ZBarrierDef, boards[3].repairEffect2Offset.z), CSPFT_FLOAT}, - {"pauseAndRepeatBoardRepairSound4", offsetof(ZBarrierDef, boards[3].pauseAndRepeatRepSound), CSPFT_UINT}, - {"pauseBetweenRepSoundsMax4", offsetof(ZBarrierDef, boards[3].maxPause), CSPFT_FLOAT}, - {"pauseBetweenRepSoundsMin4", offsetof(ZBarrierDef, boards[3].minPause), CSPFT_FLOAT}, - {"proBoardNumRepsToTear4", offsetof(ZBarrierDef, boards[3].numRepsToPullProBoard), CSPFT_UINT}, - {"repairFx40", offsetof(ZBarrierDef, boards[3].repairEffect1), CSPFT_FX}, - {"repairFx41", offsetof(ZBarrierDef, boards[3].repairEffect2), CSPFT_FX}, - {"tearAnim4", offsetof(ZBarrierDef, boards[3].pTearAnim), CSPFT_STRING}, - {"upgradedBoardModel4", offsetof(ZBarrierDef, boards[3].pUpgradedBoardModel), CSPFT_XMODEL}, - {"zombieBoardTearAnimState4", offsetof(ZBarrierDef, boards[3].zombieBoardTearStateName), CSPFT_SCRIPT_STRING}, - {"zombieBoardTearAnimSubState4", offsetof(ZBarrierDef, boards[3].zombieBoardTearSubStateName), CSPFT_SCRIPT_STRING}, - {"alternateBoardModel5", offsetof(ZBarrierDef, boards[4].pAlternateBoardModel), CSPFT_XMODEL}, - {"boardAnim5", offsetof(ZBarrierDef, boards[4].pBoardAnim), CSPFT_STRING}, - {"boardModel5", offsetof(ZBarrierDef, boards[4].pBoardModel), CSPFT_XMODEL}, - {"boardRepairSound5", offsetof(ZBarrierDef, boards[4].boardRepairSound), CSPFT_SOUND_ALIAS_ID}, - {"boardRepairHoverSound5", offsetof(ZBarrierDef, boards[4].boardRepairHoverSound), CSPFT_SOUND_ALIAS_ID}, - {"OffsetRepairFxX50", offsetof(ZBarrierDef, boards[4].repairEffect1Offset.x), CSPFT_FLOAT}, - {"OffsetRepairFxX51", offsetof(ZBarrierDef, boards[4].repairEffect2Offset.x), CSPFT_FLOAT}, - {"OffsetRepairFxY50", offsetof(ZBarrierDef, boards[4].repairEffect1Offset.y), CSPFT_FLOAT}, - {"OffsetRepairFxY51", offsetof(ZBarrierDef, boards[4].repairEffect2Offset.y), CSPFT_FLOAT}, - {"OffsetRepairFxZ50", offsetof(ZBarrierDef, boards[4].repairEffect1Offset.z), CSPFT_FLOAT}, - {"OffsetRepairFxZ51", offsetof(ZBarrierDef, boards[4].repairEffect2Offset.z), CSPFT_FLOAT}, - {"pauseAndRepeatBoardRepairSound5", offsetof(ZBarrierDef, boards[4].pauseAndRepeatRepSound), CSPFT_UINT}, - {"pauseBetweenRepSoundsMax5", offsetof(ZBarrierDef, boards[4].maxPause), CSPFT_FLOAT}, - {"pauseBetweenRepSoundsMin5", offsetof(ZBarrierDef, boards[4].minPause), CSPFT_FLOAT}, - {"proBoardNumRepsToTear5", offsetof(ZBarrierDef, boards[4].numRepsToPullProBoard), CSPFT_UINT}, - {"repairFx50", offsetof(ZBarrierDef, boards[4].repairEffect1), CSPFT_FX}, - {"repairFx51", offsetof(ZBarrierDef, boards[4].repairEffect2), CSPFT_FX}, - {"tearAnim5", offsetof(ZBarrierDef, boards[4].pTearAnim), CSPFT_STRING}, - {"upgradedBoardModel5", offsetof(ZBarrierDef, boards[4].pUpgradedBoardModel), CSPFT_XMODEL}, - {"zombieBoardTearAnimState5", offsetof(ZBarrierDef, boards[4].zombieBoardTearStateName), CSPFT_SCRIPT_STRING}, - {"zombieBoardTearAnimSubState5", offsetof(ZBarrierDef, boards[4].zombieBoardTearSubStateName), CSPFT_SCRIPT_STRING}, - {"alternateBoardModel6", offsetof(ZBarrierDef, boards[5].pAlternateBoardModel), CSPFT_XMODEL}, - {"boardAnim6", offsetof(ZBarrierDef, boards[5].pBoardAnim), CSPFT_STRING}, - {"boardModel6", offsetof(ZBarrierDef, boards[5].pBoardModel), CSPFT_XMODEL}, - {"boardRepairSound6", offsetof(ZBarrierDef, boards[5].boardRepairSound), CSPFT_SOUND_ALIAS_ID}, - {"boardRepairHoverSound6", offsetof(ZBarrierDef, boards[5].boardRepairHoverSound), CSPFT_SOUND_ALIAS_ID}, - {"OffsetRepairFxX60", offsetof(ZBarrierDef, boards[5].repairEffect1Offset.x), CSPFT_FLOAT}, - {"OffsetRepairFxX61", offsetof(ZBarrierDef, boards[5].repairEffect2Offset.x), CSPFT_FLOAT}, - {"OffsetRepairFxY60", offsetof(ZBarrierDef, boards[5].repairEffect1Offset.y), CSPFT_FLOAT}, - {"OffsetRepairFxY61", offsetof(ZBarrierDef, boards[5].repairEffect2Offset.y), CSPFT_FLOAT}, - {"OffsetRepairFxZ60", offsetof(ZBarrierDef, boards[5].repairEffect1Offset.z), CSPFT_FLOAT}, - {"OffsetRepairFxZ61", offsetof(ZBarrierDef, boards[5].repairEffect2Offset.z), CSPFT_FLOAT}, - {"pauseAndRepeatBoardRepairSound6", offsetof(ZBarrierDef, boards[5].pauseAndRepeatRepSound), CSPFT_UINT}, - {"pauseBetweenRepSoundsMax6", offsetof(ZBarrierDef, boards[5].maxPause), CSPFT_FLOAT}, - {"pauseBetweenRepSoundsMin6", offsetof(ZBarrierDef, boards[5].minPause), CSPFT_FLOAT}, - {"proBoardNumRepsToTear6", offsetof(ZBarrierDef, boards[5].numRepsToPullProBoard), CSPFT_UINT}, - {"repairFx60", offsetof(ZBarrierDef, boards[5].repairEffect1), CSPFT_FX}, - {"repairFx61", offsetof(ZBarrierDef, boards[5].repairEffect2), CSPFT_FX}, - {"tearAnim6", offsetof(ZBarrierDef, boards[5].pTearAnim), CSPFT_STRING}, - {"upgradedBoardModel6", offsetof(ZBarrierDef, boards[5].pUpgradedBoardModel), CSPFT_XMODEL}, - {"zombieBoardTearAnimState6", offsetof(ZBarrierDef, boards[5].zombieBoardTearStateName), CSPFT_SCRIPT_STRING}, - {"zombieBoardTearAnimSubState6", offsetof(ZBarrierDef, boards[5].zombieBoardTearSubStateName), CSPFT_SCRIPT_STRING}, - }; +namespace T6 { +inline cspField_t zbarrier_fields[]{ + {"delayBetweenGeneralRepSounds", offsetof(ZBarrierDef, delayBetweenRepSoundsDuration), CSPFT_FLOAT }, + {"earthquakeMaxDuration", offsetof(ZBarrierDef, earthquakeMaxDuration), CSPFT_FLOAT }, + {"earthquakeMaxScale", offsetof(ZBarrierDef, earthquakeMaxScale), CSPFT_FLOAT }, + {"earthquakeMinDuration", offsetof(ZBarrierDef, earthquakeMinDuration), CSPFT_FLOAT }, + {"earthquakeMinScale", offsetof(ZBarrierDef, earthquakeMinScale), CSPFT_FLOAT }, + {"earthquakeOnRepair", offsetof(ZBarrierDef, earthquakeOnRepair), CSPFT_UINT }, + {"earthquakeRadius", offsetof(ZBarrierDef, earthquakeRadius), CSPFT_FLOAT }, + {"generalRepairSound0", offsetof(ZBarrierDef, generalRepairSound1), CSPFT_SOUND_ALIAS_ID}, + {"generalRepairSound1", offsetof(ZBarrierDef, generalRepairSound2), CSPFT_SOUND_ALIAS_ID}, + {"upgradedGeneralRepairSound0", offsetof(ZBarrierDef, upgradedGeneralRepairSound1), CSPFT_SOUND_ALIAS_ID}, + {"upgradedGeneralRepairSound1", offsetof(ZBarrierDef, upgradedGeneralRepairSound2), CSPFT_SOUND_ALIAS_ID}, + {"useDelayBetweenGeneralRepSounds", offsetof(ZBarrierDef, delayBetweenRepSounds), CSPFT_UINT }, + {"taunts", offsetof(ZBarrierDef, taunts), CSPFT_UINT }, + {"reachThroughAttacks", offsetof(ZBarrierDef, reachThroughAttacks), CSPFT_UINT }, + {"zombieTauntAnimState", offsetof(ZBarrierDef, zombieTauntAnimState), CSPFT_SCRIPT_STRING }, + {"zombieReachThroughAnimState", offsetof(ZBarrierDef, zombieReachThroughAnimState), CSPFT_SCRIPT_STRING }, + {"numAttackSlots", offsetof(ZBarrierDef, numAttackSlots), CSPFT_UINT }, + {"attackSpotHorzOffset", offsetof(ZBarrierDef, attackSpotHorzOffset), CSPFT_FLOAT }, + {"autoHideOpenPieces", offsetof(ZBarrierDef, autoHideOpenPieces), CSPFT_UINT }, + {"alternateBoardModel1", offsetof(ZBarrierDef, boards[0].pAlternateBoardModel), CSPFT_XMODEL }, + {"boardAnim1", offsetof(ZBarrierDef, boards[0].pBoardAnim), CSPFT_STRING }, + {"boardModel1", offsetof(ZBarrierDef, boards[0].pBoardModel), CSPFT_XMODEL }, + {"boardRepairSound1", offsetof(ZBarrierDef, boards[0].boardRepairSound), CSPFT_SOUND_ALIAS_ID}, + {"boardRepairHoverSound1", offsetof(ZBarrierDef, boards[0].boardRepairHoverSound), CSPFT_SOUND_ALIAS_ID}, + {"OffsetRepairFxX10", offsetof(ZBarrierDef, boards[0].repairEffect1Offset.x), CSPFT_FLOAT }, + {"OffsetRepairFxX11", offsetof(ZBarrierDef, boards[0].repairEffect2Offset.x), CSPFT_FLOAT }, + {"OffsetRepairFxY10", offsetof(ZBarrierDef, boards[0].repairEffect1Offset.y), CSPFT_FLOAT }, + {"OffsetRepairFxY11", offsetof(ZBarrierDef, boards[0].repairEffect2Offset.y), CSPFT_FLOAT }, + {"OffsetRepairFxZ10", offsetof(ZBarrierDef, boards[0].repairEffect1Offset.z), CSPFT_FLOAT }, + {"OffsetRepairFxZ11", offsetof(ZBarrierDef, boards[0].repairEffect2Offset.z), CSPFT_FLOAT }, + {"pauseAndRepeatBoardRepairSound1", offsetof(ZBarrierDef, boards[0].pauseAndRepeatRepSound), CSPFT_UINT }, + {"pauseBetweenRepSoundsMax1", offsetof(ZBarrierDef, boards[0].maxPause), CSPFT_FLOAT }, + {"pauseBetweenRepSoundsMin1", offsetof(ZBarrierDef, boards[0].minPause), CSPFT_FLOAT }, + {"proBoardNumRepsToTear1", offsetof(ZBarrierDef, boards[0].numRepsToPullProBoard), CSPFT_UINT }, + {"repairFx10", offsetof(ZBarrierDef, boards[0].repairEffect1), CSPFT_FX }, + {"repairFx11", offsetof(ZBarrierDef, boards[0].repairEffect2), CSPFT_FX }, + {"tearAnim1", offsetof(ZBarrierDef, boards[0].pTearAnim), CSPFT_STRING }, + {"upgradedBoardModel1", offsetof(ZBarrierDef, boards[0].pUpgradedBoardModel), CSPFT_XMODEL }, + {"zombieBoardTearAnimState1", offsetof(ZBarrierDef, boards[0].zombieBoardTearStateName), CSPFT_SCRIPT_STRING }, + {"zombieBoardTearAnimSubState1", offsetof(ZBarrierDef, boards[0].zombieBoardTearSubStateName), CSPFT_SCRIPT_STRING }, + {"alternateBoardModel2", offsetof(ZBarrierDef, boards[1].pAlternateBoardModel), CSPFT_XMODEL }, + {"boardAnim2", offsetof(ZBarrierDef, boards[1].pBoardAnim), CSPFT_STRING }, + {"boardModel2", offsetof(ZBarrierDef, boards[1].pBoardModel), CSPFT_XMODEL }, + {"boardRepairSound2", offsetof(ZBarrierDef, boards[1].boardRepairSound), CSPFT_SOUND_ALIAS_ID}, + {"boardRepairHoverSound2", offsetof(ZBarrierDef, boards[1].boardRepairHoverSound), CSPFT_SOUND_ALIAS_ID}, + {"OffsetRepairFxX20", offsetof(ZBarrierDef, boards[1].repairEffect1Offset.x), CSPFT_FLOAT }, + {"OffsetRepairFxX21", offsetof(ZBarrierDef, boards[1].repairEffect2Offset.x), CSPFT_FLOAT }, + {"OffsetRepairFxY20", offsetof(ZBarrierDef, boards[1].repairEffect1Offset.y), CSPFT_FLOAT }, + {"OffsetRepairFxY21", offsetof(ZBarrierDef, boards[1].repairEffect2Offset.y), CSPFT_FLOAT }, + {"OffsetRepairFxZ20", offsetof(ZBarrierDef, boards[1].repairEffect1Offset.z), CSPFT_FLOAT }, + {"OffsetRepairFxZ21", offsetof(ZBarrierDef, boards[1].repairEffect2Offset.z), CSPFT_FLOAT }, + {"pauseAndRepeatBoardRepairSound2", offsetof(ZBarrierDef, boards[1].pauseAndRepeatRepSound), CSPFT_UINT }, + {"pauseBetweenRepSoundsMax2", offsetof(ZBarrierDef, boards[1].maxPause), CSPFT_FLOAT }, + {"pauseBetweenRepSoundsMin2", offsetof(ZBarrierDef, boards[1].minPause), CSPFT_FLOAT }, + {"proBoardNumRepsToTear2", offsetof(ZBarrierDef, boards[1].numRepsToPullProBoard), CSPFT_UINT }, + {"repairFx20", offsetof(ZBarrierDef, boards[1].repairEffect1), CSPFT_FX }, + {"repairFx21", offsetof(ZBarrierDef, boards[1].repairEffect2), CSPFT_FX }, + {"tearAnim2", offsetof(ZBarrierDef, boards[1].pTearAnim), CSPFT_STRING }, + {"upgradedBoardModel2", offsetof(ZBarrierDef, boards[1].pUpgradedBoardModel), CSPFT_XMODEL }, + {"zombieBoardTearAnimState2", offsetof(ZBarrierDef, boards[1].zombieBoardTearStateName), CSPFT_SCRIPT_STRING }, + {"zombieBoardTearAnimSubState2", offsetof(ZBarrierDef, boards[1].zombieBoardTearSubStateName), CSPFT_SCRIPT_STRING }, + {"alternateBoardModel3", offsetof(ZBarrierDef, boards[2].pAlternateBoardModel), CSPFT_XMODEL }, + {"boardAnim3", offsetof(ZBarrierDef, boards[2].pBoardAnim), CSPFT_STRING }, + {"boardModel3", offsetof(ZBarrierDef, boards[2].pBoardModel), CSPFT_XMODEL }, + {"boardRepairSound3", offsetof(ZBarrierDef, boards[2].boardRepairSound), CSPFT_SOUND_ALIAS_ID}, + {"boardRepairHoverSound3", offsetof(ZBarrierDef, boards[2].boardRepairHoverSound), CSPFT_SOUND_ALIAS_ID}, + {"OffsetRepairFxX30", offsetof(ZBarrierDef, boards[2].repairEffect1Offset.x), CSPFT_FLOAT }, + {"OffsetRepairFxX31", offsetof(ZBarrierDef, boards[2].repairEffect2Offset.x), CSPFT_FLOAT }, + {"OffsetRepairFxY30", offsetof(ZBarrierDef, boards[2].repairEffect1Offset.y), CSPFT_FLOAT }, + {"OffsetRepairFxY31", offsetof(ZBarrierDef, boards[2].repairEffect2Offset.y), CSPFT_FLOAT }, + {"OffsetRepairFxZ30", offsetof(ZBarrierDef, boards[2].repairEffect1Offset.z), CSPFT_FLOAT }, + {"OffsetRepairFxZ31", offsetof(ZBarrierDef, boards[2].repairEffect2Offset.z), CSPFT_FLOAT }, + {"pauseAndRepeatBoardRepairSound3", offsetof(ZBarrierDef, boards[2].pauseAndRepeatRepSound), CSPFT_UINT }, + {"pauseBetweenRepSoundsMax3", offsetof(ZBarrierDef, boards[2].maxPause), CSPFT_FLOAT }, + {"pauseBetweenRepSoundsMin3", offsetof(ZBarrierDef, boards[2].minPause), CSPFT_FLOAT }, + {"proBoardNumRepsToTear3", offsetof(ZBarrierDef, boards[2].numRepsToPullProBoard), CSPFT_UINT }, + {"repairFx30", offsetof(ZBarrierDef, boards[2].repairEffect1), CSPFT_FX }, + {"repairFx31", offsetof(ZBarrierDef, boards[2].repairEffect2), CSPFT_FX }, + {"tearAnim3", offsetof(ZBarrierDef, boards[2].pTearAnim), CSPFT_STRING }, + {"upgradedBoardModel3", offsetof(ZBarrierDef, boards[2].pUpgradedBoardModel), CSPFT_XMODEL }, + {"zombieBoardTearAnimState3", offsetof(ZBarrierDef, boards[2].zombieBoardTearStateName), CSPFT_SCRIPT_STRING }, + {"zombieBoardTearAnimSubState3", offsetof(ZBarrierDef, boards[2].zombieBoardTearSubStateName), CSPFT_SCRIPT_STRING }, + {"alternateBoardModel4", offsetof(ZBarrierDef, boards[3].pAlternateBoardModel), CSPFT_XMODEL }, + {"boardAnim4", offsetof(ZBarrierDef, boards[3].pBoardAnim), CSPFT_STRING }, + {"boardModel4", offsetof(ZBarrierDef, boards[3].pBoardModel), CSPFT_XMODEL }, + {"boardRepairSound4", offsetof(ZBarrierDef, boards[3].boardRepairSound), CSPFT_SOUND_ALIAS_ID}, + {"boardRepairHoverSound4", offsetof(ZBarrierDef, boards[3].boardRepairHoverSound), CSPFT_SOUND_ALIAS_ID}, + {"OffsetRepairFxX40", offsetof(ZBarrierDef, boards[3].repairEffect1Offset.x), CSPFT_FLOAT }, + {"OffsetRepairFxX41", offsetof(ZBarrierDef, boards[3].repairEffect2Offset.x), CSPFT_FLOAT }, + {"OffsetRepairFxY40", offsetof(ZBarrierDef, boards[3].repairEffect1Offset.y), CSPFT_FLOAT }, + {"OffsetRepairFxY41", offsetof(ZBarrierDef, boards[3].repairEffect2Offset.y), CSPFT_FLOAT }, + {"OffsetRepairFxZ40", offsetof(ZBarrierDef, boards[3].repairEffect1Offset.z), CSPFT_FLOAT }, + {"OffsetRepairFxZ41", offsetof(ZBarrierDef, boards[3].repairEffect2Offset.z), CSPFT_FLOAT }, + {"pauseAndRepeatBoardRepairSound4", offsetof(ZBarrierDef, boards[3].pauseAndRepeatRepSound), CSPFT_UINT }, + {"pauseBetweenRepSoundsMax4", offsetof(ZBarrierDef, boards[3].maxPause), CSPFT_FLOAT }, + {"pauseBetweenRepSoundsMin4", offsetof(ZBarrierDef, boards[3].minPause), CSPFT_FLOAT }, + {"proBoardNumRepsToTear4", offsetof(ZBarrierDef, boards[3].numRepsToPullProBoard), CSPFT_UINT }, + {"repairFx40", offsetof(ZBarrierDef, boards[3].repairEffect1), CSPFT_FX }, + {"repairFx41", offsetof(ZBarrierDef, boards[3].repairEffect2), CSPFT_FX }, + {"tearAnim4", offsetof(ZBarrierDef, boards[3].pTearAnim), CSPFT_STRING }, + {"upgradedBoardModel4", offsetof(ZBarrierDef, boards[3].pUpgradedBoardModel), CSPFT_XMODEL }, + {"zombieBoardTearAnimState4", offsetof(ZBarrierDef, boards[3].zombieBoardTearStateName), CSPFT_SCRIPT_STRING }, + {"zombieBoardTearAnimSubState4", offsetof(ZBarrierDef, boards[3].zombieBoardTearSubStateName), CSPFT_SCRIPT_STRING }, + {"alternateBoardModel5", offsetof(ZBarrierDef, boards[4].pAlternateBoardModel), CSPFT_XMODEL }, + {"boardAnim5", offsetof(ZBarrierDef, boards[4].pBoardAnim), CSPFT_STRING }, + {"boardModel5", offsetof(ZBarrierDef, boards[4].pBoardModel), CSPFT_XMODEL }, + {"boardRepairSound5", offsetof(ZBarrierDef, boards[4].boardRepairSound), CSPFT_SOUND_ALIAS_ID}, + {"boardRepairHoverSound5", offsetof(ZBarrierDef, boards[4].boardRepairHoverSound), CSPFT_SOUND_ALIAS_ID}, + {"OffsetRepairFxX50", offsetof(ZBarrierDef, boards[4].repairEffect1Offset.x), CSPFT_FLOAT }, + {"OffsetRepairFxX51", offsetof(ZBarrierDef, boards[4].repairEffect2Offset.x), CSPFT_FLOAT }, + {"OffsetRepairFxY50", offsetof(ZBarrierDef, boards[4].repairEffect1Offset.y), CSPFT_FLOAT }, + {"OffsetRepairFxY51", offsetof(ZBarrierDef, boards[4].repairEffect2Offset.y), CSPFT_FLOAT }, + {"OffsetRepairFxZ50", offsetof(ZBarrierDef, boards[4].repairEffect1Offset.z), CSPFT_FLOAT }, + {"OffsetRepairFxZ51", offsetof(ZBarrierDef, boards[4].repairEffect2Offset.z), CSPFT_FLOAT }, + {"pauseAndRepeatBoardRepairSound5", offsetof(ZBarrierDef, boards[4].pauseAndRepeatRepSound), CSPFT_UINT }, + {"pauseBetweenRepSoundsMax5", offsetof(ZBarrierDef, boards[4].maxPause), CSPFT_FLOAT }, + {"pauseBetweenRepSoundsMin5", offsetof(ZBarrierDef, boards[4].minPause), CSPFT_FLOAT }, + {"proBoardNumRepsToTear5", offsetof(ZBarrierDef, boards[4].numRepsToPullProBoard), CSPFT_UINT }, + {"repairFx50", offsetof(ZBarrierDef, boards[4].repairEffect1), CSPFT_FX }, + {"repairFx51", offsetof(ZBarrierDef, boards[4].repairEffect2), CSPFT_FX }, + {"tearAnim5", offsetof(ZBarrierDef, boards[4].pTearAnim), CSPFT_STRING }, + {"upgradedBoardModel5", offsetof(ZBarrierDef, boards[4].pUpgradedBoardModel), CSPFT_XMODEL }, + {"zombieBoardTearAnimState5", offsetof(ZBarrierDef, boards[4].zombieBoardTearStateName), CSPFT_SCRIPT_STRING }, + {"zombieBoardTearAnimSubState5", offsetof(ZBarrierDef, boards[4].zombieBoardTearSubStateName), CSPFT_SCRIPT_STRING }, + {"alternateBoardModel6", offsetof(ZBarrierDef, boards[5].pAlternateBoardModel), CSPFT_XMODEL }, + {"boardAnim6", offsetof(ZBarrierDef, boards[5].pBoardAnim), CSPFT_STRING }, + {"boardModel6", offsetof(ZBarrierDef, boards[5].pBoardModel), CSPFT_XMODEL }, + {"boardRepairSound6", offsetof(ZBarrierDef, boards[5].boardRepairSound), CSPFT_SOUND_ALIAS_ID}, + {"boardRepairHoverSound6", offsetof(ZBarrierDef, boards[5].boardRepairHoverSound), CSPFT_SOUND_ALIAS_ID}, + {"OffsetRepairFxX60", offsetof(ZBarrierDef, boards[5].repairEffect1Offset.x), CSPFT_FLOAT }, + {"OffsetRepairFxX61", offsetof(ZBarrierDef, boards[5].repairEffect2Offset.x), CSPFT_FLOAT }, + {"OffsetRepairFxY60", offsetof(ZBarrierDef, boards[5].repairEffect1Offset.y), CSPFT_FLOAT }, + {"OffsetRepairFxY61", offsetof(ZBarrierDef, boards[5].repairEffect2Offset.y), CSPFT_FLOAT }, + {"OffsetRepairFxZ60", offsetof(ZBarrierDef, boards[5].repairEffect1Offset.z), CSPFT_FLOAT }, + {"OffsetRepairFxZ61", offsetof(ZBarrierDef, boards[5].repairEffect2Offset.z), CSPFT_FLOAT }, + {"pauseAndRepeatBoardRepairSound6", offsetof(ZBarrierDef, boards[5].pauseAndRepeatRepSound), CSPFT_UINT }, + {"pauseBetweenRepSoundsMax6", offsetof(ZBarrierDef, boards[5].maxPause), CSPFT_FLOAT }, + {"pauseBetweenRepSoundsMin6", offsetof(ZBarrierDef, boards[5].minPause), CSPFT_FLOAT }, + {"proBoardNumRepsToTear6", offsetof(ZBarrierDef, boards[5].numRepsToPullProBoard), CSPFT_UINT }, + {"repairFx60", offsetof(ZBarrierDef, boards[5].repairEffect1), CSPFT_FX }, + {"repairFx61", offsetof(ZBarrierDef, boards[5].repairEffect2), CSPFT_FX }, + {"tearAnim6", offsetof(ZBarrierDef, boards[5].pTearAnim), CSPFT_STRING }, + {"upgradedBoardModel6", offsetof(ZBarrierDef, boards[5].pUpgradedBoardModel), CSPFT_XMODEL }, + {"zombieBoardTearAnimState6", offsetof(ZBarrierDef, boards[5].zombieBoardTearStateName), CSPFT_SCRIPT_STRING }, + {"zombieBoardTearAnimSubState6", offsetof(ZBarrierDef, boards[5].zombieBoardTearSubStateName), CSPFT_SCRIPT_STRING }, +}; } \ No newline at end of file diff --git a/src/ObjCommon/Game/T6/ObjConstantsT6.h b/src/ObjCommon/Game/T6/ObjConstantsT6.h index a39de7af3..25ef5db73 100644 --- a/src/ObjCommon/Game/T6/ObjConstantsT6.h +++ b/src/ObjCommon/Game/T6/ObjConstantsT6.h @@ -1,28 +1,26 @@ #pragma once -namespace T6 -{ - class ObjConstants - { - ObjConstants() = default; +namespace T6 { +class ObjConstants { + ObjConstants() = default; - public: - static constexpr const char* INFO_STRING_PREFIX_PHYS_CONSTRAINTS = "PHYSCONSTRAINTS"; - static constexpr const char* INFO_STRING_PREFIX_PHYS_PRESET = "PHYSIC"; - static constexpr const char* INFO_STRING_PREFIX_TRACER = "TRACER"; - static constexpr const char* INFO_STRING_PREFIX_VEHICLE = "VEHICLEFILE"; - static constexpr const char* INFO_STRING_PREFIX_WEAPON = "WEAPONFILE"; - static constexpr const char* INFO_STRING_PREFIX_WEAPON_ATTACHMENT = "ATTACHMENTFILE"; - static constexpr const char* INFO_STRING_PREFIX_WEAPON_ATTACHMENT_UNIQUE = "ATTACHMENTUNIQUEFILE"; - static constexpr const char* INFO_STRING_PREFIX_ZBARRIER = "ZBARRIER"; +public: + static constexpr const char *INFO_STRING_PREFIX_PHYS_CONSTRAINTS = "PHYSCONSTRAINTS"; + static constexpr const char *INFO_STRING_PREFIX_PHYS_PRESET = "PHYSIC"; + static constexpr const char *INFO_STRING_PREFIX_TRACER = "TRACER"; + static constexpr const char *INFO_STRING_PREFIX_VEHICLE = "VEHICLEFILE"; + static constexpr const char *INFO_STRING_PREFIX_WEAPON = "WEAPONFILE"; + static constexpr const char *INFO_STRING_PREFIX_WEAPON_ATTACHMENT = "ATTACHMENTFILE"; + static constexpr const char *INFO_STRING_PREFIX_WEAPON_ATTACHMENT_UNIQUE = "ATTACHMENTUNIQUEFILE"; + static constexpr const char *INFO_STRING_PREFIX_ZBARRIER = "ZBARRIER"; - static constexpr const char* GDF_FILENAME_PHYS_CONSTRAINTS = "physconstraints.gdf"; - static constexpr const char* GDF_FILENAME_PHYS_PRESET = "physpreset.gdf"; - static constexpr const char* GDF_FILENAME_TRACER = "tracer.gdf"; - static constexpr const char* GDF_FILENAME_VEHICLE = "vehicle.gdf"; - static constexpr const char* GDF_FILENAME_WEAPON = "weapon.gdf"; - static constexpr const char* GDF_FILENAME_WEAPON_ATTACHMENT = "attachment.gdf"; - static constexpr const char* GDF_FILENAME_WEAPON_ATTACHMENT_UNIQUE = "attachmentunique.gdf"; - static constexpr const char* GDF_FILENAME_ZBARRIER = "zbarrier.gdf"; - }; -} \ No newline at end of file + static constexpr const char *GDF_FILENAME_PHYS_CONSTRAINTS = "physconstraints.gdf"; + static constexpr const char *GDF_FILENAME_PHYS_PRESET = "physpreset.gdf"; + static constexpr const char *GDF_FILENAME_TRACER = "tracer.gdf"; + static constexpr const char *GDF_FILENAME_VEHICLE = "vehicle.gdf"; + static constexpr const char *GDF_FILENAME_WEAPON = "weapon.gdf"; + static constexpr const char *GDF_FILENAME_WEAPON_ATTACHMENT = "attachment.gdf"; + static constexpr const char *GDF_FILENAME_WEAPON_ATTACHMENT_UNIQUE = "attachmentunique.gdf"; + static constexpr const char *GDF_FILENAME_ZBARRIER = "zbarrier.gdf"; +}; +} // namespace T6 \ No newline at end of file diff --git a/src/ObjCommon/InfoString/InfoString.cpp b/src/ObjCommon/InfoString/InfoString.cpp index 489fbc206..ddc60d3e9 100644 --- a/src/ObjCommon/InfoString/InfoString.cpp +++ b/src/ObjCommon/InfoString/InfoString.cpp @@ -1,234 +1,194 @@ #include "InfoString.h" -#include #include +#include #include const std::string InfoString::EMPTY_VALUE; -bool InfoString::HasKey(const std::string& key) const -{ - return m_values.find(key) != m_values.end(); -} +bool InfoString::HasKey(const std::string &key) const { return m_values.find(key) != m_values.end(); } -const std::string& InfoString::GetValueForKey(const std::string& key) const -{ - const auto& value = m_values.find(key); +const std::string &InfoString::GetValueForKey(const std::string &key) const { + const auto &value = m_values.find(key); - if (value == m_values.end()) - return EMPTY_VALUE; + if (value == m_values.end()) + return EMPTY_VALUE; - return value->second; + return value->second; } -const std::string& InfoString::GetValueForKey(const std::string& key, bool* foundValue) const -{ - const auto& value = m_values.find(key); - - if (value == m_values.end()) - { - if (foundValue) - *foundValue = false; - return EMPTY_VALUE; - } +const std::string &InfoString::GetValueForKey(const std::string &key, bool *foundValue) const { + const auto &value = m_values.find(key); + if (value == m_values.end()) { if (foundValue) - *foundValue = true; - return value->second; + *foundValue = false; + return EMPTY_VALUE; + } + + if (foundValue) + *foundValue = true; + return value->second; } -void InfoString::SetValueForKey(const std::string& key, std::string value) -{ - if (!HasKey(key)) - m_keys_by_insertion.push_back(key); +void InfoString::SetValueForKey(const std::string &key, std::string value) { + if (!HasKey(key)) + m_keys_by_insertion.push_back(key); - m_values[key] = std::move(value); + m_values[key] = std::move(value); } -void InfoString::RemoveKey(const std::string& key) -{ - const auto& value = m_values.find(key); +void InfoString::RemoveKey(const std::string &key) { + const auto &value = m_values.find(key); - if (value != m_values.end()) - m_values.erase(value); + if (value != m_values.end()) + m_values.erase(value); } -std::string InfoString::ToString() const -{ - std::stringstream ss; - bool first = true; +std::string InfoString::ToString() const { + std::stringstream ss; + bool first = true; - for (const auto& key : m_keys_by_insertion) - { - const auto value = m_values.find(key); - if (!first) - ss << '\\'; - else - first = false; + for (const auto &key : m_keys_by_insertion) { + const auto value = m_values.find(key); + if (!first) + ss << '\\'; + else + first = false; - ss << key << '\\' << value->second; - } + ss << key << '\\' << value->second; + } - return ss.str(); + return ss.str(); } -std::string InfoString::ToString(const std::string& prefix) const -{ - std::stringstream ss; - ss << prefix; +std::string InfoString::ToString(const std::string &prefix) const { + std::stringstream ss; + ss << prefix; - for (const auto& key : m_keys_by_insertion) - { - const auto value = m_values.find(key); - ss << '\\' << key << '\\' << value->second; - } + for (const auto &key : m_keys_by_insertion) { + const auto value = m_values.find(key); + ss << '\\' << key << '\\' << value->second; + } - return ss.str(); + return ss.str(); } -void InfoString::ToGdtProperties(const std::string& prefix, GdtEntry& gdtEntry) const -{ - for (const auto& key : m_keys_by_insertion) - { - const auto value = m_values.find(key); - gdtEntry.m_properties[key] = value->second; - } +void InfoString::ToGdtProperties(const std::string &prefix, GdtEntry &gdtEntry) const { + for (const auto &key : m_keys_by_insertion) { + const auto value = m_values.find(key); + gdtEntry.m_properties[key] = value->second; + } - gdtEntry.m_properties[GDT_PREFIX_FIELD] = prefix; + gdtEntry.m_properties[GDT_PREFIX_FIELD] = prefix; } -class InfoStringInputStream -{ - std::istream& m_stream; - int m_last_separator; +class InfoStringInputStream { + std::istream &m_stream; + int m_last_separator; public: - explicit InfoStringInputStream(std::istream& stream) - : m_stream(stream), - m_last_separator(EOF) - { - } + explicit InfoStringInputStream(std::istream &stream) : m_stream(stream), m_last_separator(EOF) {} - bool NextField(std::string& value) - { - std::ostringstream str; - - auto c = m_stream.get(); - if (c == EOF) - { - if(m_last_separator != EOF) - { - m_last_separator = EOF; - value = std::string(); - return true; - } - - return false; - } - - while (c != EOF && c != '\\') - { - str << static_cast(c); - c = m_stream.get(); - } - - m_last_separator = c; - value = str.str(); + bool NextField(std::string &value) { + std::ostringstream str; + + auto c = m_stream.get(); + if (c == EOF) { + if (m_last_separator != EOF) { + m_last_separator = EOF; + value = std::string(); return true; + } + + return false; } -}; -bool InfoString::FromStream(std::istream& stream) -{ - InfoStringInputStream infoStream(stream); - - std::string key; - while (infoStream.NextField(key)) - { - std::string value; - if (!infoStream.NextField(value)) - return false; - - const auto existingEntry = m_values.find(key); - if (existingEntry == m_values.end()) - { - m_keys_by_insertion.push_back(key); - m_values.emplace(std::make_pair(key, value)); - } - else - { - existingEntry->second = value; - } + while (c != EOF && c != '\\') { + str << static_cast(c); + c = m_stream.get(); } + m_last_separator = c; + value = str.str(); return true; + } +}; + +bool InfoString::FromStream(std::istream &stream) { + InfoStringInputStream infoStream(stream); + + std::string key; + while (infoStream.NextField(key)) { + std::string value; + if (!infoStream.NextField(value)) + return false; + + const auto existingEntry = m_values.find(key); + if (existingEntry == m_values.end()) { + m_keys_by_insertion.push_back(key); + m_values.emplace(std::make_pair(key, value)); + } else { + existingEntry->second = value; + } + } + + return true; } -bool InfoString::FromStream(const std::string& prefix, std::istream& stream) -{ - InfoStringInputStream infoStream(stream); - - std::string readPrefix; - if (!infoStream.NextField(readPrefix)) - return false; - - if (prefix != readPrefix) - return false; - - std::string key; - while (infoStream.NextField(key)) - { - std::string value; - if (!infoStream.NextField(value)) - return false; - - const auto existingEntry = m_values.find(key); - if (existingEntry == m_values.end()) - { - m_keys_by_insertion.push_back(key); - m_values.emplace(std::make_pair(key, value)); - } - else - { - existingEntry->second = value; - } +bool InfoString::FromStream(const std::string &prefix, std::istream &stream) { + InfoStringInputStream infoStream(stream); + + std::string readPrefix; + if (!infoStream.NextField(readPrefix)) + return false; + + if (prefix != readPrefix) + return false; + + std::string key; + while (infoStream.NextField(key)) { + std::string value; + if (!infoStream.NextField(value)) + return false; + + const auto existingEntry = m_values.find(key); + if (existingEntry == m_values.end()) { + m_keys_by_insertion.push_back(key); + m_values.emplace(std::make_pair(key, value)); + } else { + existingEntry->second = value; } + } - return true; + return true; } -bool InfoString::FromGdtProperties(const GdtEntry& gdtEntry) -{ - std::stack entryStack; - - { - const auto* currentEntry = &gdtEntry; - while (currentEntry) - { - entryStack.push(currentEntry); - currentEntry = currentEntry->m_parent; - } +bool InfoString::FromGdtProperties(const GdtEntry &gdtEntry) { + std::stack entryStack; + + { + const auto *currentEntry = &gdtEntry; + while (currentEntry) { + entryStack.push(currentEntry); + currentEntry = currentEntry->m_parent; } + } - while(!entryStack.empty()) - { - const auto* currentEntry = entryStack.top(); - entryStack.pop(); - - for (const auto& [key, value] : currentEntry->m_properties) - { - auto existingEntry = m_values.find(key); - if(existingEntry == m_values.end()) - { - m_keys_by_insertion.push_back(key); - m_values.emplace(std::make_pair(key, value)); - } - else - { - existingEntry->second = value; - } - } + while (!entryStack.empty()) { + const auto *currentEntry = entryStack.top(); + entryStack.pop(); + + for (const auto &[key, value] : currentEntry->m_properties) { + auto existingEntry = m_values.find(key); + if (existingEntry == m_values.end()) { + m_keys_by_insertion.push_back(key); + m_values.emplace(std::make_pair(key, value)); + } else { + existingEntry->second = value; + } } + } - return true; + return true; } diff --git a/src/ObjCommon/InfoString/InfoString.h b/src/ObjCommon/InfoString/InfoString.h index 096a30885..01bf1f68e 100644 --- a/src/ObjCommon/InfoString/InfoString.h +++ b/src/ObjCommon/InfoString/InfoString.h @@ -1,32 +1,31 @@ #pragma once #include -#include #include +#include #include -#include "Utils/ClassUtils.h" #include "Obj/Gdt/GdtEntry.h" +#include "Utils/ClassUtils.h" -class InfoString -{ - static constexpr const char* GDT_PREFIX_FIELD = "configstringFileType"; +class InfoString { + static constexpr const char *GDT_PREFIX_FIELD = "configstringFileType"; - static const std::string EMPTY_VALUE; - std::unordered_map m_values; - std::vector m_keys_by_insertion; + static const std::string EMPTY_VALUE; + std::unordered_map m_values; + std::vector m_keys_by_insertion; public: - _NODISCARD bool HasKey(const std::string& key) const; - _NODISCARD const std::string& GetValueForKey(const std::string& key) const; - const std::string& GetValueForKey(const std::string& key, bool* foundValue) const; - void SetValueForKey(const std::string& key, std::string value); - void RemoveKey(const std::string& key); + _NODISCARD bool HasKey(const std::string &key) const; + _NODISCARD const std::string &GetValueForKey(const std::string &key) const; + const std::string &GetValueForKey(const std::string &key, bool *foundValue) const; + void SetValueForKey(const std::string &key, std::string value); + void RemoveKey(const std::string &key); - _NODISCARD std::string ToString() const; - _NODISCARD std::string ToString(const std::string& prefix) const; - void ToGdtProperties(const std::string& prefix, GdtEntry& gdtEntry) const; + _NODISCARD std::string ToString() const; + _NODISCARD std::string ToString(const std::string &prefix) const; + void ToGdtProperties(const std::string &prefix, GdtEntry &gdtEntry) const; - bool FromStream(std::istream& stream); - bool FromStream(const std::string& prefix, std::istream& stream); - bool FromGdtProperties(const GdtEntry& gdtEntry); + bool FromStream(std::istream &stream); + bool FromStream(const std::string &prefix, std::istream &stream); + bool FromGdtProperties(const GdtEntry &gdtEntry); }; \ No newline at end of file diff --git a/src/ObjCommon/Localize/LocalizeCommon.cpp b/src/ObjCommon/Localize/LocalizeCommon.cpp index 025cbc93f..9e705fe4e 100644 --- a/src/ObjCommon/Localize/LocalizeCommon.cpp +++ b/src/ObjCommon/Localize/LocalizeCommon.cpp @@ -1,69 +1,67 @@ #include "LocalizeCommon.h" -std::string LocalizeCommon::GetNameOfLanguage(GameLanguage language) -{ - switch (language) - { - case GameLanguage::LANGUAGE_NONE: - case GameLanguage::LANGUAGE_ENGLISH: - default: - return "english"; +std::string LocalizeCommon::GetNameOfLanguage(GameLanguage language) { + switch (language) { + case GameLanguage::LANGUAGE_NONE: + case GameLanguage::LANGUAGE_ENGLISH: + default: + return "english"; - case GameLanguage::LANGUAGE_FRENCH: - return "french"; + case GameLanguage::LANGUAGE_FRENCH: + return "french"; - case GameLanguage::LANGUAGE_GERMAN: - return "german"; + case GameLanguage::LANGUAGE_GERMAN: + return "german"; - case GameLanguage::LANGUAGE_ITALIAN: - return "italian"; + case GameLanguage::LANGUAGE_ITALIAN: + return "italian"; - case GameLanguage::LANGUAGE_SPANISH: - return "spanish"; + case GameLanguage::LANGUAGE_SPANISH: + return "spanish"; - case GameLanguage::LANGUAGE_BRITISH: - return "british"; + case GameLanguage::LANGUAGE_BRITISH: + return "british"; - case GameLanguage::LANGUAGE_RUSSIAN: - return "russian"; + case GameLanguage::LANGUAGE_RUSSIAN: + return "russian"; - case GameLanguage::LANGUAGE_POLISH: - return "polish"; + case GameLanguage::LANGUAGE_POLISH: + return "polish"; - case GameLanguage::LANGUAGE_KOREAN: - return "korean"; + case GameLanguage::LANGUAGE_KOREAN: + return "korean"; - case GameLanguage::LANGUAGE_JAPANESE: - return "japanese"; + case GameLanguage::LANGUAGE_JAPANESE: + return "japanese"; - case GameLanguage::LANGUAGE_CZECH: - return "czech"; + case GameLanguage::LANGUAGE_CZECH: + return "czech"; - case GameLanguage::LANGUAGE_FRENCH_CAN: - return "frenchcan"; + case GameLanguage::LANGUAGE_FRENCH_CAN: + return "frenchcan"; - case GameLanguage::LANGUAGE_AUSTRIAN: - return "austrian"; + case GameLanguage::LANGUAGE_AUSTRIAN: + return "austrian"; - case GameLanguage::LANGUAGE_PORTUGUESE: - return "portuguese"; + case GameLanguage::LANGUAGE_PORTUGUESE: + return "portuguese"; - case GameLanguage::LANGUAGE_MEXICAN_SPANISH: - return "mexicanspanish"; + case GameLanguage::LANGUAGE_MEXICAN_SPANISH: + return "mexicanspanish"; - case GameLanguage::LANGUAGE_FULL_JAPANESE: - return "fulljapanese"; + case GameLanguage::LANGUAGE_FULL_JAPANESE: + return "fulljapanese"; - case GameLanguage::LANGUAGE_TAIWANESE: - return "taiwanese"; + case GameLanguage::LANGUAGE_TAIWANESE: + return "taiwanese"; - case GameLanguage::LANGUAGE_CHINESE: - return "chinese"; + case GameLanguage::LANGUAGE_CHINESE: + return "chinese"; - case GameLanguage::LANGUAGE_THAI: - return "thai"; + case GameLanguage::LANGUAGE_THAI: + return "thai"; - case GameLanguage::LANGUAGE_LEET: - return "leet"; - } + case GameLanguage::LANGUAGE_LEET: + return "leet"; + } } diff --git a/src/ObjCommon/Localize/LocalizeCommon.h b/src/ObjCommon/Localize/LocalizeCommon.h index d5ee88fda..ba8c33914 100644 --- a/src/ObjCommon/Localize/LocalizeCommon.h +++ b/src/ObjCommon/Localize/LocalizeCommon.h @@ -4,8 +4,7 @@ #include "Game/GameLanguage.h" -class LocalizeCommon -{ +class LocalizeCommon { public: - static std::string GetNameOfLanguage(GameLanguage language); + static std::string GetNameOfLanguage(GameLanguage language); }; diff --git a/src/ObjCommon/Localize/LocalizeFile.cpp b/src/ObjCommon/Localize/LocalizeFile.cpp index 4617d5d04..92395ad06 100644 --- a/src/ObjCommon/Localize/LocalizeFile.cpp +++ b/src/ObjCommon/Localize/LocalizeFile.cpp @@ -1,10 +1,5 @@ #include "LocalizeFile.h" -LocalizeFileEntry::LocalizeFileEntry() -= default; +LocalizeFileEntry::LocalizeFileEntry() = default; -LocalizeFileEntry::LocalizeFileEntry(std::string key, std::string value) - : m_key(std::move(key)), - m_value(std::move(value)) -{ -} +LocalizeFileEntry::LocalizeFileEntry(std::string key, std::string value) : m_key(std::move(key)), m_value(std::move(value)) {} diff --git a/src/ObjCommon/Localize/LocalizeFile.h b/src/ObjCommon/Localize/LocalizeFile.h index 73ac2dad9..3b6065c8f 100644 --- a/src/ObjCommon/Localize/LocalizeFile.h +++ b/src/ObjCommon/Localize/LocalizeFile.h @@ -1,12 +1,11 @@ #pragma once #include -class LocalizeFileEntry -{ +class LocalizeFileEntry { public: - std::string m_key; - std::string m_value; + std::string m_key; + std::string m_value; - LocalizeFileEntry(); - LocalizeFileEntry(std::string key, std::string value); + LocalizeFileEntry(); + LocalizeFileEntry(std::string key, std::string value); }; diff --git a/src/ObjCommon/Model/Obj/ObjCommon.cpp b/src/ObjCommon/Model/Obj/ObjCommon.cpp index f6ec8b39b..b446fff81 100644 --- a/src/ObjCommon/Model/Obj/ObjCommon.cpp +++ b/src/ObjCommon/Model/Obj/ObjCommon.cpp @@ -4,52 +4,34 @@ #include #include -bool operator==(const ObjVertex& lhs, const ObjVertex& rhs) -{ - return std::fabs(lhs.coordinates[0] - rhs.coordinates[0]) < std::numeric_limits::epsilon() - && std::fabs(lhs.coordinates[1] - rhs.coordinates[1]) < std::numeric_limits::epsilon() - && std::fabs(lhs.coordinates[2] - rhs.coordinates[2]) < std::numeric_limits::epsilon(); +bool operator==(const ObjVertex &lhs, const ObjVertex &rhs) { + return std::fabs(lhs.coordinates[0] - rhs.coordinates[0]) < std::numeric_limits::epsilon() && + std::fabs(lhs.coordinates[1] - rhs.coordinates[1]) < std::numeric_limits::epsilon() && + std::fabs(lhs.coordinates[2] - rhs.coordinates[2]) < std::numeric_limits::epsilon(); } -bool operator!=(const ObjVertex& lhs, const ObjVertex& rhs) -{ - return !(lhs == rhs); -} +bool operator!=(const ObjVertex &lhs, const ObjVertex &rhs) { return !(lhs == rhs); } -bool operator<(const ObjVertex& lhs, const ObjVertex& rhs) -{ - return std::tie(lhs.coordinates[0], lhs.coordinates[1], lhs.coordinates[2]) < std::tie(rhs.coordinates[0], rhs.coordinates[1], rhs.coordinates[2]); +bool operator<(const ObjVertex &lhs, const ObjVertex &rhs) { + return std::tie(lhs.coordinates[0], lhs.coordinates[1], lhs.coordinates[2]) < std::tie(rhs.coordinates[0], rhs.coordinates[1], rhs.coordinates[2]); } -bool operator==(const ObjNormal& lhs, const ObjNormal& rhs) -{ - return std::fabs(lhs.normal[0] - rhs.normal[0]) < std::numeric_limits::epsilon() - && std::fabs(lhs.normal[1] - rhs.normal[1]) < std::numeric_limits::epsilon() - && std::fabs(lhs.normal[2] - rhs.normal[2]) < std::numeric_limits::epsilon(); +bool operator==(const ObjNormal &lhs, const ObjNormal &rhs) { + return std::fabs(lhs.normal[0] - rhs.normal[0]) < std::numeric_limits::epsilon() && + std::fabs(lhs.normal[1] - rhs.normal[1]) < std::numeric_limits::epsilon() && + std::fabs(lhs.normal[2] - rhs.normal[2]) < std::numeric_limits::epsilon(); } -bool operator!=(const ObjNormal& lhs, const ObjNormal& rhs) -{ - return !(lhs == rhs); -} +bool operator!=(const ObjNormal &lhs, const ObjNormal &rhs) { return !(lhs == rhs); } -bool operator<(const ObjNormal& lhs, const ObjNormal& rhs) -{ - return std::tie(lhs.normal[0], lhs.normal[1], lhs.normal[2]) < std::tie(rhs.normal[0], rhs.normal[1], rhs.normal[2]); +bool operator<(const ObjNormal &lhs, const ObjNormal &rhs) { + return std::tie(lhs.normal[0], lhs.normal[1], lhs.normal[2]) < std::tie(rhs.normal[0], rhs.normal[1], rhs.normal[2]); } -bool operator==(const ObjUv& lhs, const ObjUv& rhs) -{ - return std::fabs(lhs.uv[0] - rhs.uv[0]) < std::numeric_limits::epsilon() - && std::fabs(lhs.uv[1] - rhs.uv[1]) < std::numeric_limits::epsilon(); +bool operator==(const ObjUv &lhs, const ObjUv &rhs) { + return std::fabs(lhs.uv[0] - rhs.uv[0]) < std::numeric_limits::epsilon() && std::fabs(lhs.uv[1] - rhs.uv[1]) < std::numeric_limits::epsilon(); } -bool operator!=(const ObjUv& lhs, const ObjUv& rhs) -{ - return !(lhs == rhs); -} +bool operator!=(const ObjUv &lhs, const ObjUv &rhs) { return !(lhs == rhs); } -bool operator<(const ObjUv& lhs, const ObjUv& rhs) -{ - return std::tie(lhs.uv[0], lhs.uv[1]) < std::tie(rhs.uv[0], rhs.uv[1]); -} +bool operator<(const ObjUv &lhs, const ObjUv &rhs) { return std::tie(lhs.uv[0], lhs.uv[1]) < std::tie(rhs.uv[0], rhs.uv[1]); } diff --git a/src/ObjCommon/Model/Obj/ObjCommon.h b/src/ObjCommon/Model/Obj/ObjCommon.h index 911b9e9e3..77ec2c53c 100644 --- a/src/ObjCommon/Model/Obj/ObjCommon.h +++ b/src/ObjCommon/Model/Obj/ObjCommon.h @@ -2,50 +2,44 @@ #include -struct ObjObject -{ - std::string name; - int materialIndex; +struct ObjObject { + std::string name; + int materialIndex; }; -struct ObjVertex -{ - float coordinates[3]; +struct ObjVertex { + float coordinates[3]; - friend bool operator==(const ObjVertex& lhs, const ObjVertex& rhs); - friend bool operator!=(const ObjVertex& lhs, const ObjVertex& rhs); - friend bool operator<(const ObjVertex& lhs, const ObjVertex& rhs); + friend bool operator==(const ObjVertex &lhs, const ObjVertex &rhs); + friend bool operator!=(const ObjVertex &lhs, const ObjVertex &rhs); + friend bool operator<(const ObjVertex &lhs, const ObjVertex &rhs); }; -struct ObjNormal -{ - float normal[3]; +struct ObjNormal { + float normal[3]; - friend bool operator==(const ObjNormal& lhs, const ObjNormal& rhs); - friend bool operator!=(const ObjNormal& lhs, const ObjNormal& rhs); - friend bool operator<(const ObjNormal& lhs, const ObjNormal& rhs); + friend bool operator==(const ObjNormal &lhs, const ObjNormal &rhs); + friend bool operator!=(const ObjNormal &lhs, const ObjNormal &rhs); + friend bool operator<(const ObjNormal &lhs, const ObjNormal &rhs); }; -struct ObjUv -{ - float uv[2]; +struct ObjUv { + float uv[2]; - friend bool operator==(const ObjUv& lhs, const ObjUv& rhs); - friend bool operator!=(const ObjUv& lhs, const ObjUv& rhs); - friend bool operator<(const ObjUv& lhs, const ObjUv& rhs); + friend bool operator==(const ObjUv &lhs, const ObjUv &rhs); + friend bool operator!=(const ObjUv &lhs, const ObjUv &rhs); + friend bool operator<(const ObjUv &lhs, const ObjUv &rhs); }; -struct ObjFace -{ - int vertexIndex[3]; - int normalIndex[3]; - int uvIndex[3]; +struct ObjFace { + int vertexIndex[3]; + int normalIndex[3]; + int uvIndex[3]; }; -struct MtlMaterial -{ - std::string materialName; - std::string colorMapName; - std::string normalMapName; - std::string specularMapName; +struct MtlMaterial { + std::string materialName; + std::string colorMapName; + std::string normalMapName; + std::string specularMapName; }; \ No newline at end of file diff --git a/src/ObjCommon/Model/XModel/XModelCommon.cpp b/src/ObjCommon/Model/XModel/XModelCommon.cpp index 4e0c68443..4c67a8d20 100644 --- a/src/ObjCommon/Model/XModel/XModelCommon.cpp +++ b/src/ObjCommon/Model/XModel/XModelCommon.cpp @@ -4,98 +4,89 @@ #include #include -void XModelMaterial::ApplyDefaults() -{ - // Phong = Color, Bump, Spec, CosinePower - // Blinn = Color, Bump, Spec, Eccentricity - // Lambert = Color, Bump - materialTypeName = "Phong"; - color[0] = 0; - color[1] = 0; - color[2] = 0; - color[3] = 1; - transparency[0] = 0; - transparency[1] = 0; - transparency[2] = 0; - transparency[3] = 1; - ambientColor[0] = 0; - ambientColor[1] = 0; - ambientColor[2] = 0; - ambientColor[3] = 1; - incandescence[0] = 0; - incandescence[1] = 0; - incandescence[2] = 0; - incandescence[3] = 1; - coeffs[0] = 0.8f; - coeffs[1] = 0; - glow.x = 0; - glow.y = 0; - refractive.x = 6; - refractive.y = 1; - specularColor[0] = -1; - specularColor[1] = -1; - specularColor[2] = -1; - specularColor[3] = 1; - reflectiveColor[0] = -1; - reflectiveColor[1] = -1; - reflectiveColor[2] = -1; - reflectiveColor[3] = 1; - reflective.x = -1; - reflective.y = -1; - blinn[0] = -1; - blinn[1] = -1; - phong = -1; +void XModelMaterial::ApplyDefaults() { + // Phong = Color, Bump, Spec, CosinePower + // Blinn = Color, Bump, Spec, Eccentricity + // Lambert = Color, Bump + materialTypeName = "Phong"; + color[0] = 0; + color[1] = 0; + color[2] = 0; + color[3] = 1; + transparency[0] = 0; + transparency[1] = 0; + transparency[2] = 0; + transparency[3] = 1; + ambientColor[0] = 0; + ambientColor[1] = 0; + ambientColor[2] = 0; + ambientColor[3] = 1; + incandescence[0] = 0; + incandescence[1] = 0; + incandescence[2] = 0; + incandescence[3] = 1; + coeffs[0] = 0.8f; + coeffs[1] = 0; + glow.x = 0; + glow.y = 0; + refractive.x = 6; + refractive.y = 1; + specularColor[0] = -1; + specularColor[1] = -1; + specularColor[2] = -1; + specularColor[3] = 1; + reflectiveColor[0] = -1; + reflectiveColor[1] = -1; + reflectiveColor[2] = -1; + reflectiveColor[3] = 1; + reflective.x = -1; + reflective.y = -1; + blinn[0] = -1; + blinn[1] = -1; + phong = -1; } -bool operator==(const VertexMergerPos& lhs, const VertexMergerPos& rhs) -{ - const auto coordinatesMatch = std::fabs(lhs.x - rhs.x) < std::numeric_limits::epsilon() - && std::fabs(lhs.y - rhs.y) < std::numeric_limits::epsilon() - && std::fabs(lhs.z - rhs.z) < std::numeric_limits::epsilon(); +bool operator==(const VertexMergerPos &lhs, const VertexMergerPos &rhs) { + const auto coordinatesMatch = std::fabs(lhs.x - rhs.x) < std::numeric_limits::epsilon() && + std::fabs(lhs.y - rhs.y) < std::numeric_limits::epsilon() && + std::fabs(lhs.z - rhs.z) < std::numeric_limits::epsilon(); - if (!coordinatesMatch || lhs.weightCount != rhs.weightCount) - return false; + if (!coordinatesMatch || lhs.weightCount != rhs.weightCount) + return false; - for (auto weightIndex = 0u; weightIndex < lhs.weightCount; weightIndex++) - { - if (lhs.weights[weightIndex].boneIndex != rhs.weights[weightIndex].boneIndex - || std::fabs(lhs.weights[weightIndex].weight - rhs.weights[weightIndex].weight) >= std::numeric_limits::epsilon()) - { - return false; - } + for (auto weightIndex = 0u; weightIndex < lhs.weightCount; weightIndex++) { + if (lhs.weights[weightIndex].boneIndex != rhs.weights[weightIndex].boneIndex || + std::fabs(lhs.weights[weightIndex].weight - rhs.weights[weightIndex].weight) >= std::numeric_limits::epsilon()) { + return false; } + } - return true; + return true; } -bool operator!=(const VertexMergerPos& lhs, VertexMergerPos& rhs) -{ - return !(lhs == rhs); -} +bool operator!=(const VertexMergerPos &lhs, VertexMergerPos &rhs) { return !(lhs == rhs); } -bool operator<(const VertexMergerPos& lhs, const VertexMergerPos& rhs) -{ - const auto t0 = std::tie(lhs.x, lhs.y, lhs.z, rhs.weightCount); - const auto t1 = std::tie(rhs.x, rhs.y, rhs.z, rhs.weightCount); - if (t0 < t1) - return true; +bool operator<(const VertexMergerPos &lhs, const VertexMergerPos &rhs) { + const auto t0 = std::tie(lhs.x, lhs.y, lhs.z, rhs.weightCount); + const auto t1 = std::tie(rhs.x, rhs.y, rhs.z, rhs.weightCount); + if (t0 < t1) + return true; - if (!(t0 == t1)) - return false; + if (!(t0 == t1)) + return false; - for (auto weightIndex = 0u; weightIndex < lhs.weightCount; weightIndex++) - { - const auto& lhsWeight = lhs.weights[weightIndex]; - const auto& rhsWeight = rhs.weights[weightIndex]; + for (auto weightIndex = 0u; weightIndex < lhs.weightCount; weightIndex++) { + const auto &lhsWeight = lhs.weights[weightIndex]; + const auto &rhsWeight = rhs.weights[weightIndex]; - const auto t2 = std::tie(lhsWeight.boneIndex, lhsWeight.weight); - const auto t3 = std::tie(rhsWeight.boneIndex, rhsWeight.weight); - if (t2 < t3) - return true; + const auto t2 = std::tie(lhsWeight.boneIndex, lhsWeight.weight); + const auto t3 = std::tie(rhsWeight.boneIndex, rhsWeight.weight); + if (t2 < t3) + return true; - if (!(t2 == t3)) - return false; - } + if (!(t2 == t3)) + return false; + } - return false; + return false; } diff --git a/src/ObjCommon/Model/XModel/XModelCommon.h b/src/ObjCommon/Model/XModel/XModelCommon.h index 158a69db0..3627e1854 100644 --- a/src/ObjCommon/Model/XModel/XModelCommon.h +++ b/src/ObjCommon/Model/XModel/XModelCommon.h @@ -1,103 +1,92 @@ #pragma once -#include #include +#include -#include "Utils/DistinctMapper.h" #include "Math/Quaternion.h" +#include "Utils/DistinctMapper.h" -struct XModelObject -{ - std::string name; +struct XModelObject { + std::string name; }; -struct XModelBone -{ - std::string name; - int parentIndex; - float scale[3]; - float globalOffset[3]; - float localOffset[3]; - Quaternion32 globalRotation; - Quaternion32 localRotation; +struct XModelBone { + std::string name; + int parentIndex; + float scale[3]; + float globalOffset[3]; + float localOffset[3]; + Quaternion32 globalRotation; + Quaternion32 localRotation; }; -struct XModelBoneWeight -{ - int boneIndex; - float weight; +struct XModelBoneWeight { + int boneIndex; + float weight; }; -struct XModelVertexBoneWeightCollection -{ - std::unique_ptr weights; - size_t totalWeightCount; +struct XModelVertexBoneWeightCollection { + std::unique_ptr weights; + size_t totalWeightCount; }; -struct XModelVertexBoneWeights -{ - const XModelBoneWeight* weights; - size_t weightCount; +struct XModelVertexBoneWeights { + const XModelBoneWeight *weights; + size_t weightCount; }; -struct XModelVertex -{ - float coordinates[3]; - float normal[3]; - float color[4]; - float uv[2]; +struct XModelVertex { + float coordinates[3]; + float normal[3]; + float color[4]; + float uv[2]; }; -struct XModelFace -{ - int vertexIndex[3]; - int objectIndex; - int materialIndex; +struct XModelFace { + int vertexIndex[3]; + int objectIndex; + int materialIndex; }; -struct XModelMaterial -{ - std::string name; - std::string materialTypeName; - float color[4]; - float transparency[4]; - float ambientColor[4]; - float incandescence[4]; - float coeffs[2]; - struct { - float x; - int y; - } glow; - struct - { - int x; - float y; - } refractive; - float specularColor[4]; - float reflectiveColor[4]; - struct - { - int x; - float y; - } reflective; - float blinn[2]; - float phong; - std::string colorMapName; +struct XModelMaterial { + std::string name; + std::string materialTypeName; + float color[4]; + float transparency[4]; + float ambientColor[4]; + float incandescence[4]; + float coeffs[2]; + struct { + float x; + int y; + } glow; + struct { + int x; + float y; + } refractive; + float specularColor[4]; + float reflectiveColor[4]; + struct { + int x; + float y; + } reflective; + float blinn[2]; + float phong; + std::string colorMapName; - void ApplyDefaults(); + void ApplyDefaults(); }; -struct VertexMergerPos -{ - float x; - float y; - float z; - const XModelBoneWeight* weights; - size_t weightCount; +struct VertexMergerPos { + float x; + float y; + float z; + const XModelBoneWeight *weights; + size_t weightCount; - friend bool operator==(const VertexMergerPos& lhs, const VertexMergerPos& rhs); - friend bool operator!=(const VertexMergerPos& lhs, const VertexMergerPos& rhs); - friend bool operator<(const VertexMergerPos& lhs, const VertexMergerPos& rhs); + friend bool operator==(const VertexMergerPos &lhs, const VertexMergerPos &rhs); + friend bool operator!=(const VertexMergerPos &lhs, const VertexMergerPos &rhs); + friend bool operator<(const VertexMergerPos &lhs, const VertexMergerPos &rhs); }; typedef DistinctMapper VertexMerger; \ No newline at end of file diff --git a/src/ObjCommon/Obj/Gdt/Gdt.cpp b/src/ObjCommon/Obj/Gdt/Gdt.cpp index 081ea81e7..78b222f39 100644 --- a/src/ObjCommon/Obj/Gdt/Gdt.cpp +++ b/src/ObjCommon/Obj/Gdt/Gdt.cpp @@ -1,9 +1,5 @@ #include "Gdt.h" -Gdt::Gdt() -= default; +Gdt::Gdt() = default; -Gdt::Gdt(GdtVersion version) - : m_version(std::move(version)) -{ -} +Gdt::Gdt(GdtVersion version) : m_version(std::move(version)) {} diff --git a/src/ObjCommon/Obj/Gdt/Gdt.h b/src/ObjCommon/Obj/Gdt/Gdt.h index da8800890..2c6cfcbd0 100644 --- a/src/ObjCommon/Obj/Gdt/Gdt.h +++ b/src/ObjCommon/Obj/Gdt/Gdt.h @@ -6,12 +6,11 @@ #include "GdtEntry.h" #include "GdtVersion.h" -class Gdt -{ +class Gdt { public: - GdtVersion m_version; - std::vector> m_entries; + GdtVersion m_version; + std::vector> m_entries; - Gdt(); - explicit Gdt(GdtVersion version); + Gdt(); + explicit Gdt(GdtVersion version); }; diff --git a/src/ObjCommon/Obj/Gdt/GdtEntry.cpp b/src/ObjCommon/Obj/Gdt/GdtEntry.cpp index 9d2d28221..74b700891 100644 --- a/src/ObjCommon/Obj/Gdt/GdtEntry.cpp +++ b/src/ObjCommon/Obj/Gdt/GdtEntry.cpp @@ -1,19 +1,7 @@ #include "GdtEntry.h" -GdtEntry::GdtEntry() - : m_parent(nullptr) -{ -} +GdtEntry::GdtEntry() : m_parent(nullptr) {} -GdtEntry::GdtEntry(std::string name, std::string gdfName) - : m_name(std::move(name)), - m_gdf_name(std::move(gdfName)), - m_parent(nullptr) -{ -} +GdtEntry::GdtEntry(std::string name, std::string gdfName) : m_name(std::move(name)), m_gdf_name(std::move(gdfName)), m_parent(nullptr) {} -GdtEntry::GdtEntry(std::string name, GdtEntry* parent) - : m_name(std::move(name)), - m_parent(parent) -{ -} +GdtEntry::GdtEntry(std::string name, GdtEntry *parent) : m_name(std::move(name)), m_parent(parent) {} diff --git a/src/ObjCommon/Obj/Gdt/GdtEntry.h b/src/ObjCommon/Obj/Gdt/GdtEntry.h index 5463b5f5f..6a4214b62 100644 --- a/src/ObjCommon/Obj/Gdt/GdtEntry.h +++ b/src/ObjCommon/Obj/Gdt/GdtEntry.h @@ -3,15 +3,14 @@ #include #include -class GdtEntry -{ +class GdtEntry { public: - std::string m_name; - std::string m_gdf_name; - GdtEntry* m_parent; - std::map m_properties; + std::string m_name; + std::string m_gdf_name; + GdtEntry *m_parent; + std::map m_properties; - GdtEntry(); - GdtEntry(std::string name, std::string gdfName); - GdtEntry(std::string name, GdtEntry* parent); + GdtEntry(); + GdtEntry(std::string name, std::string gdfName); + GdtEntry(std::string name, GdtEntry *parent); }; diff --git a/src/ObjCommon/Obj/Gdt/GdtStream.cpp b/src/ObjCommon/Obj/Gdt/GdtStream.cpp index 4355c3473..49874c507 100644 --- a/src/ObjCommon/Obj/Gdt/GdtStream.cpp +++ b/src/ObjCommon/Obj/Gdt/GdtStream.cpp @@ -3,398 +3,318 @@ #include #include -class GdtConst -{ +class GdtConst { public: - static constexpr const char* VERSION_ENTRY_NAME = "version"; - static constexpr const char* VERSION_ENTRY_GDF = "version.gdf"; - static constexpr const char* VERSION_KEY_GAME = "game"; - static constexpr const char* VERSION_KEY_VERSION = "version"; + static constexpr const char *VERSION_ENTRY_NAME = "version"; + static constexpr const char *VERSION_ENTRY_GDF = "version.gdf"; + static constexpr const char *VERSION_KEY_GAME = "game"; + static constexpr const char *VERSION_KEY_VERSION = "version"; }; -void GdtReader::PrintError(const std::string& message) const -{ - std::cout << "GDT Error at line " << m_line << ": " << message << "\n"; -} +void GdtReader::PrintError(const std::string &message) const { std::cout << "GDT Error at line " << m_line << ": " << message << "\n"; } -int GdtReader::PeekChar() -{ - if (m_peeked) - return m_char; +int GdtReader::PeekChar() { + if (m_peeked) + return m_char; - int c; - do - { - c = m_stream.get(); - } - while (isspace(c)); + int c; + do { + c = m_stream.get(); + } while (isspace(c)); - m_peeked = true; - m_char = c; - return c; + m_peeked = true; + m_char = c; + return c; } -int GdtReader::NextChar() -{ - if (m_peeked) - { - m_peeked = false; - return m_char; - } +int GdtReader::NextChar() { + if (m_peeked) { + m_peeked = false; + return m_char; + } - int c; - do - { - c = m_stream.get(); - } - while (isspace(c)); + int c; + do { + c = m_stream.get(); + } while (isspace(c)); - return c; + return c; } -bool GdtReader::ReadStringContent(std::string& str) -{ - std::ostringstream ss; - - if (NextChar() != '"') - { - PrintError("Expected string opening tag"); - return false; - } +bool GdtReader::ReadStringContent(std::string &str) { + std::ostringstream ss; - auto c = m_stream.get(); - auto escaped = false; - while ((escaped || c != '"' && c != '\n') && c != EOF) - { - if (escaped) - { - switch (c) - { - case '\n': - case 'n': - ss << '\n'; - break; - - case 'r': - ss << '\r'; - break; - - default: - ss << static_cast(c); - break; - } - escaped = false; - } - else if(c == '\\') - { - escaped = true; - } - else - { - ss << static_cast(c); - } - c = m_stream.get(); + if (NextChar() != '"') { + PrintError("Expected string opening tag"); + return false; + } + + auto c = m_stream.get(); + auto escaped = false; + while ((escaped || c != '"' && c != '\n') && c != EOF) { + if (escaped) { + switch (c) { + case '\n': + case 'n': + ss << '\n'; + break; + + case 'r': + ss << '\r'; + break; + + default: + ss << static_cast(c); + break; + } + escaped = false; + } else if (c == '\\') { + escaped = true; + } else { + ss << static_cast(c); } + c = m_stream.get(); + } - if (c == '"') - { - str = ss.str(); - return true; - } + if (c == '"') { + str = ss.str(); + return true; + } - return false; + return false; } -GdtEntry* GdtReader::GetEntryByName(const Gdt& gdt, const std::string& name) -{ - for (const auto& entry : gdt.m_entries) - { - if (entry->m_name == name) - return entry.get(); - } +GdtEntry *GdtReader::GetEntryByName(const Gdt &gdt, const std::string &name) { + for (const auto &entry : gdt.m_entries) { + if (entry->m_name == name) + return entry.get(); + } - return nullptr; + return nullptr; } -bool GdtReader::ReadProperties(GdtEntry& entry) -{ - while (PeekChar() == '"') - { - std::string propertyKey; - std::string propertyValue; - - if (!ReadStringContent(propertyKey)) - return false; +bool GdtReader::ReadProperties(GdtEntry &entry) { + while (PeekChar() == '"') { + std::string propertyKey; + std::string propertyValue; - if (PeekChar() != '"' || !ReadStringContent(propertyValue)) - { - PrintError("Expected value string"); - return false; - } + if (!ReadStringContent(propertyKey)) + return false; - entry.m_properties.emplace(std::move(propertyKey), std::move(propertyValue)); + if (PeekChar() != '"' || !ReadStringContent(propertyValue)) { + PrintError("Expected value string"); + return false; } + entry.m_properties.emplace(std::move(propertyKey), std::move(propertyValue)); + } - if (NextChar() != '}') - { - PrintError("Expected closing tags"); - return false; - } + if (NextChar() != '}') { + PrintError("Expected closing tags"); + return false; + } - return true; + return true; } -bool GdtReader::AddEntry(Gdt& gdt, GdtEntry& entry) const -{ - if (entry.m_name == GdtConst::VERSION_ENTRY_NAME - && entry.m_gdf_name == GdtConst::VERSION_ENTRY_GDF) - { - auto foundEntry = entry.m_properties.find(GdtConst::VERSION_KEY_GAME); - if (foundEntry == entry.m_properties.end()) - { - PrintError("Version does not feature game property"); - return false; - } - gdt.m_version.m_game = foundEntry->second; - - foundEntry = entry.m_properties.find(GdtConst::VERSION_KEY_VERSION); - if (foundEntry == entry.m_properties.end()) - { - PrintError("Version does not feature version property"); - return false; - } - gdt.m_version.m_version = strtol(foundEntry->second.c_str(), nullptr, 0); +bool GdtReader::AddEntry(Gdt &gdt, GdtEntry &entry) const { + if (entry.m_name == GdtConst::VERSION_ENTRY_NAME && entry.m_gdf_name == GdtConst::VERSION_ENTRY_GDF) { + auto foundEntry = entry.m_properties.find(GdtConst::VERSION_KEY_GAME); + if (foundEntry == entry.m_properties.end()) { + PrintError("Version does not feature game property"); + return false; } - else - { - gdt.m_entries.emplace_back(std::make_unique(std::move(entry))); + gdt.m_version.m_game = foundEntry->second; + + foundEntry = entry.m_properties.find(GdtConst::VERSION_KEY_VERSION); + if (foundEntry == entry.m_properties.end()) { + PrintError("Version does not feature version property"); + return false; } + gdt.m_version.m_version = strtol(foundEntry->second.c_str(), nullptr, 0); + } else { + gdt.m_entries.emplace_back(std::make_unique(std::move(entry))); + } - return true; + return true; } -GdtReader::GdtReader(std::istream& stream) - : m_stream(stream), - m_char(0), - m_peeked(false), - m_line(0) -{ -} +GdtReader::GdtReader(std::istream &stream) : m_stream(stream), m_char(0), m_peeked(false), m_line(0) {} + +bool GdtReader::Read(Gdt &gdt) { + if (NextChar() != '{') { + PrintError("Expected opening tag"); + return false; + } + + while (PeekChar() == '"') { + GdtEntry entry; + + if (!ReadStringContent(entry.m_name)) { + PrintError("Failed to read string"); + return false; + } -bool GdtReader::Read(Gdt& gdt) -{ - if (NextChar() != '{') - { - PrintError("Expected opening tag"); + if (PeekChar() == '(') { + NextChar(); + if (!ReadStringContent(entry.m_gdf_name)) { + PrintError("Expected gdf name string"); return false; + } + if (NextChar() != ')') { + PrintError("Expected closing parenthesis"); + return false; + } + } else if (PeekChar() == '[') { + NextChar(); + std::string parentName; + if (!ReadStringContent(parentName)) { + PrintError("Expected parent name string"); + return false; + } + if (NextChar() != ']') { + PrintError("Expected closing square brackets"); + return false; + } + entry.m_parent = GetEntryByName(gdt, parentName); + if (entry.m_parent == nullptr) { + PrintError("Could not find parent with name"); + return false; + } + auto *currentParentEntry = entry.m_parent; + while (currentParentEntry->m_parent) + currentParentEntry = currentParentEntry->m_parent; + entry.m_gdf_name = currentParentEntry->m_gdf_name; + } else { + PrintError("Expected gdf or parent opening"); + return false; } - while (PeekChar() == '"') - { - GdtEntry entry; - - if (!ReadStringContent(entry.m_name)) - { - PrintError("Failed to read string"); - return false; - } - - if (PeekChar() == '(') - { - NextChar(); - if (!ReadStringContent(entry.m_gdf_name)) - { - PrintError("Expected gdf name string"); - return false; - } - if (NextChar() != ')') - { - PrintError("Expected closing parenthesis"); - return false; - } - } - else if (PeekChar() == '[') - { - NextChar(); - std::string parentName; - if (!ReadStringContent(parentName)) - { - PrintError("Expected parent name string"); - return false; - } - if (NextChar() != ']') - { - PrintError("Expected closing square brackets"); - return false; - } - entry.m_parent = GetEntryByName(gdt, parentName); - if (entry.m_parent == nullptr) - { - PrintError("Could not find parent with name"); - return false; - } - auto* currentParentEntry = entry.m_parent; - while (currentParentEntry->m_parent) - currentParentEntry = currentParentEntry->m_parent; - entry.m_gdf_name = currentParentEntry->m_gdf_name; - } - else - { - PrintError("Expected gdf or parent opening"); - return false; - } - - if (NextChar() != '{') - { - PrintError("Expected opening tag for entries"); - return false; - } - - if (!ReadProperties(entry)) - return false; - - if (!AddEntry(gdt, entry)) - return false; + if (NextChar() != '{') { + PrintError("Expected opening tag for entries"); + return false; } + if (!ReadProperties(entry)) + return false; - if (NextChar() != '}') - { - PrintError("Expected closing tags"); - return false; - } + if (!AddEntry(gdt, entry)) + return false; + } - return true; -} + if (NextChar() != '}') { + PrintError("Expected closing tags"); + return false; + } -GdtOutputStream::GdtOutputStream(std::ostream& stream) - : m_stream(stream), - m_open(false), - m_intendation_level(0) -{ + return true; } -void GdtOutputStream::BeginStream() -{ - if (!m_open) - { - m_stream << "{\n"; - m_intendation_level++; - m_open = true; - } +GdtOutputStream::GdtOutputStream(std::ostream &stream) : m_stream(stream), m_open(false), m_intendation_level(0) {} + +void GdtOutputStream::BeginStream() { + if (!m_open) { + m_stream << "{\n"; + m_intendation_level++; + m_open = true; + } } -void GdtOutputStream::DoIntendation() const -{ - for (auto i = 0u; i < m_intendation_level; i++) - m_stream << "\t"; +void GdtOutputStream::DoIntendation() const { + for (auto i = 0u; i < m_intendation_level; i++) + m_stream << "\t"; } -void GdtOutputStream::WriteVersion(const GdtVersion& gdtVersion) -{ - GdtEntry versionEntry; - versionEntry.m_name = GdtConst::VERSION_ENTRY_NAME; - versionEntry.m_gdf_name = GdtConst::VERSION_ENTRY_GDF; - versionEntry.m_properties[GdtConst::VERSION_KEY_GAME] = gdtVersion.m_game; - versionEntry.m_properties[GdtConst::VERSION_KEY_VERSION] = std::to_string(gdtVersion.m_version); +void GdtOutputStream::WriteVersion(const GdtVersion &gdtVersion) { + GdtEntry versionEntry; + versionEntry.m_name = GdtConst::VERSION_ENTRY_NAME; + versionEntry.m_gdf_name = GdtConst::VERSION_ENTRY_GDF; + versionEntry.m_properties[GdtConst::VERSION_KEY_GAME] = gdtVersion.m_game; + versionEntry.m_properties[GdtConst::VERSION_KEY_VERSION] = std::to_string(gdtVersion.m_version); - WriteEntry(versionEntry); + WriteEntry(versionEntry); } -void GdtOutputStream::WriteEscaped(const std::string& str) const -{ - auto wroteBefore = false; - for(auto i = 0u; i < str.size(); i++) - { - auto needsEscape = false; - auto c = str[i]; - switch(c) - { - case '\r': - needsEscape = true; - c = 'r'; - break; - - case '\n': - needsEscape = true; - c = 'n'; - break; - - case '\\': - needsEscape = true; - break; - - default: - break; - } - - if(needsEscape) - { - if(!wroteBefore) - { - wroteBefore = true; - m_stream << std::string(str, 0, i); - } - - m_stream << '\\' << c; - } - else if(wroteBefore) - { - m_stream << c; - } +void GdtOutputStream::WriteEscaped(const std::string &str) const { + auto wroteBefore = false; + for (auto i = 0u; i < str.size(); i++) { + auto needsEscape = false; + auto c = str[i]; + switch (c) { + case '\r': + needsEscape = true; + c = 'r'; + break; + + case '\n': + needsEscape = true; + c = 'n'; + break; + + case '\\': + needsEscape = true; + break; + + default: + break; } - if(!wroteBefore) - { - m_stream << str; + if (needsEscape) { + if (!wroteBefore) { + wroteBefore = true; + m_stream << std::string(str, 0, i); + } + + m_stream << '\\' << c; + } else if (wroteBefore) { + m_stream << c; } -} + } -void GdtOutputStream::WriteEntry(const GdtEntry& entry) -{ - DoIntendation(); - m_stream << "\"" << entry.m_name << "\" "; - if (entry.m_parent) - m_stream << "[ \"" << entry.m_parent->m_name << "\" ]\n"; - else - m_stream << "( \"" << entry.m_gdf_name << "\" )\n"; - DoIntendation(); - m_stream << "{\n"; + if (!wroteBefore) { + m_stream << str; + } +} - m_intendation_level++; +void GdtOutputStream::WriteEntry(const GdtEntry &entry) { + DoIntendation(); + m_stream << "\"" << entry.m_name << "\" "; + if (entry.m_parent) + m_stream << "[ \"" << entry.m_parent->m_name << "\" ]\n"; + else + m_stream << "( \"" << entry.m_gdf_name << "\" )\n"; + DoIntendation(); + m_stream << "{\n"; - for (const auto& [propertyKey, propertyValue] : entry.m_properties) - { - DoIntendation(); - m_stream << "\"" << propertyKey << "\" \""; - WriteEscaped(propertyValue); - m_stream << "\"\n"; - } + m_intendation_level++; - m_intendation_level--; + for (const auto &[propertyKey, propertyValue] : entry.m_properties) { DoIntendation(); - m_stream << "}\n"; + m_stream << "\"" << propertyKey << "\" \""; + WriteEscaped(propertyValue); + m_stream << "\"\n"; + } + + m_intendation_level--; + DoIntendation(); + m_stream << "}\n"; } -void GdtOutputStream::EndStream() -{ - if (m_open) - { - m_intendation_level--; - m_stream << "}"; - m_open = false; - } +void GdtOutputStream::EndStream() { + if (m_open) { + m_intendation_level--; + m_stream << "}"; + m_open = false; + } } -void GdtOutputStream::WriteGdt(const Gdt& gdt, std::ostream& stream) -{ - GdtOutputStream out(stream); - out.BeginStream(); - out.WriteVersion(gdt.m_version); +void GdtOutputStream::WriteGdt(const Gdt &gdt, std::ostream &stream) { + GdtOutputStream out(stream); + out.BeginStream(); + out.WriteVersion(gdt.m_version); - for (const auto& entry : gdt.m_entries) - out.WriteEntry(*entry); + for (const auto &entry : gdt.m_entries) + out.WriteEntry(*entry); - out.EndStream(); + out.EndStream(); } diff --git a/src/ObjCommon/Obj/Gdt/GdtStream.h b/src/ObjCommon/Obj/Gdt/GdtStream.h index 3eb046813..d4d713000 100644 --- a/src/ObjCommon/Obj/Gdt/GdtStream.h +++ b/src/ObjCommon/Obj/Gdt/GdtStream.h @@ -3,42 +3,40 @@ #include "Gdt.h" -class GdtReader -{ - std::istream& m_stream; - char m_char; - bool m_peeked; - int m_line; - - static GdtEntry* GetEntryByName(const Gdt& gdt, const std::string& name); - void PrintError(const std::string& message) const; - int PeekChar(); - int NextChar(); - bool ReadStringContent(std::string& str); - bool ReadProperties(GdtEntry& entry); - bool AddEntry(Gdt& gdt, GdtEntry& entry) const; +class GdtReader { + std::istream &m_stream; + char m_char; + bool m_peeked; + int m_line; + + static GdtEntry *GetEntryByName(const Gdt &gdt, const std::string &name); + void PrintError(const std::string &message) const; + int PeekChar(); + int NextChar(); + bool ReadStringContent(std::string &str); + bool ReadProperties(GdtEntry &entry); + bool AddEntry(Gdt &gdt, GdtEntry &entry) const; public: - explicit GdtReader(std::istream& stream); - bool Read(Gdt& gdt); + explicit GdtReader(std::istream &stream); + bool Read(Gdt &gdt); }; -class GdtOutputStream -{ - std::ostream& m_stream; - bool m_open; - unsigned m_intendation_level; +class GdtOutputStream { + std::ostream &m_stream; + bool m_open; + unsigned m_intendation_level; - void DoIntendation() const; + void DoIntendation() const; public: - explicit GdtOutputStream(std::ostream& stream); + explicit GdtOutputStream(std::ostream &stream); - void BeginStream(); - void WriteVersion(const GdtVersion& gdtVersion); - void WriteEscaped(const std::string& str) const; - void WriteEntry(const GdtEntry& entry); - void EndStream(); + void BeginStream(); + void WriteVersion(const GdtVersion &gdtVersion); + void WriteEscaped(const std::string &str) const; + void WriteEntry(const GdtEntry &entry); + void EndStream(); - static void WriteGdt(const Gdt& gdt, std::ostream& stream); + static void WriteGdt(const Gdt &gdt, std::ostream &stream); }; diff --git a/src/ObjCommon/Obj/Gdt/GdtVersion.cpp b/src/ObjCommon/Obj/Gdt/GdtVersion.cpp index 42143c609..1e68b30a5 100644 --- a/src/ObjCommon/Obj/Gdt/GdtVersion.cpp +++ b/src/ObjCommon/Obj/Gdt/GdtVersion.cpp @@ -1,12 +1,5 @@ #include "GdtVersion.h" -GdtVersion::GdtVersion() - : m_version(0) -{ -} +GdtVersion::GdtVersion() : m_version(0) {} -GdtVersion::GdtVersion(std::string game, const int version) - : m_game(std::move(game)), - m_version(version) -{ -} +GdtVersion::GdtVersion(std::string game, const int version) : m_game(std::move(game)), m_version(version) {} diff --git a/src/ObjCommon/Obj/Gdt/GdtVersion.h b/src/ObjCommon/Obj/Gdt/GdtVersion.h index 02adf3fea..b06639d0a 100644 --- a/src/ObjCommon/Obj/Gdt/GdtVersion.h +++ b/src/ObjCommon/Obj/Gdt/GdtVersion.h @@ -2,12 +2,11 @@ #include -class GdtVersion -{ +class GdtVersion { public: - std::string m_game; - int m_version; + std::string m_game; + int m_version; - GdtVersion(); - GdtVersion(std::string game, int version); + GdtVersion(); + GdtVersion(std::string game, int version); }; \ No newline at end of file diff --git a/src/ObjCommon/ObjContainer/IObjContainer.h b/src/ObjCommon/ObjContainer/IObjContainer.h index 1c4aa6a53..93894f804 100644 --- a/src/ObjCommon/ObjContainer/IObjContainer.h +++ b/src/ObjCommon/ObjContainer/IObjContainer.h @@ -2,10 +2,9 @@ #include -class IObjContainer -{ +class IObjContainer { public: - virtual ~IObjContainer() = default; + virtual ~IObjContainer() = default; - virtual std::string GetName() = 0; + virtual std::string GetName() = 0; }; \ No newline at end of file diff --git a/src/ObjCommon/ObjContainer/IPak/IPakTypes.h b/src/ObjCommon/ObjContainer/IPak/IPakTypes.h index ee259f1da..37bbe7d93 100644 --- a/src/ObjCommon/ObjContainer/IPak/IPakTypes.h +++ b/src/ObjCommon/ObjContainer/IPak/IPakTypes.h @@ -4,63 +4,52 @@ typedef uint32_t IPakHash; -namespace ipak_consts -{ - static constexpr size_t IPAK_CHUNK_SIZE = 0x8000; - static constexpr size_t IPAK_CHUNK_COUNT_PER_READ = 0x8; -} - -struct IPakHeader -{ - uint32_t magic; - uint32_t version; - uint32_t size; - uint32_t sectionCount; +namespace ipak_consts { +static constexpr size_t IPAK_CHUNK_SIZE = 0x8000; +static constexpr size_t IPAK_CHUNK_COUNT_PER_READ = 0x8; +} // namespace ipak_consts + +struct IPakHeader { + uint32_t magic; + uint32_t version; + uint32_t size; + uint32_t sectionCount; }; -struct IPakSection -{ - uint32_t type; - uint32_t offset; - uint32_t size; - uint32_t itemCount; +struct IPakSection { + uint32_t type; + uint32_t offset; + uint32_t size; + uint32_t itemCount; }; -union IPakIndexEntryKey -{ - struct - { - IPakHash dataHash; - IPakHash nameHash; - }; - uint64_t combinedKey; +union IPakIndexEntryKey { + struct { + IPakHash dataHash; + IPakHash nameHash; + }; + uint64_t combinedKey; }; -struct IPakIndexEntry -{ - IPakIndexEntryKey key; - uint32_t offset; - uint32_t size; +struct IPakIndexEntry { + IPakIndexEntryKey key; + uint32_t offset; + uint32_t size; }; -struct IPakDataBlockHeader -{ - union - { - uint32_t countAndOffset; - struct - { - uint32_t offset : 24; - uint32_t count : 8; - }; - }; - union - { - uint32_t commands[31]; - struct - { - uint32_t size : 24; - uint32_t compressed : 8; - }_commands[31]; - }; +struct IPakDataBlockHeader { + union { + uint32_t countAndOffset; + struct { + uint32_t offset : 24; + uint32_t count : 8; + }; + }; + union { + uint32_t commands[31]; + struct { + uint32_t size : 24; + uint32_t compressed : 8; + } _commands[31]; + }; }; \ No newline at end of file diff --git a/src/ObjCommon/ObjContainer/ObjContainerReferenceable.cpp b/src/ObjCommon/ObjContainer/ObjContainerReferenceable.cpp index 9592c62e3..8a6d3eeec 100644 --- a/src/ObjCommon/ObjContainer/ObjContainerReferenceable.cpp +++ b/src/ObjCommon/ObjContainer/ObjContainerReferenceable.cpp @@ -1,16 +1,7 @@ #include "ObjContainerReferenceable.h" -void ObjContainerReferenceable::AddReference(void* referencer) -{ - m_references.insert(referencer); -} +void ObjContainerReferenceable::AddReference(void *referencer) { m_references.insert(referencer); } -bool ObjContainerReferenceable::RemoveReference(void* referencer) -{ - return m_references.erase(referencer) > 0; -} +bool ObjContainerReferenceable::RemoveReference(void *referencer) { return m_references.erase(referencer) > 0; } -bool ObjContainerReferenceable::IsReferenced() const -{ - return !m_references.empty(); -} +bool ObjContainerReferenceable::IsReferenced() const { return !m_references.empty(); } diff --git a/src/ObjCommon/ObjContainer/ObjContainerReferenceable.h b/src/ObjCommon/ObjContainer/ObjContainerReferenceable.h index 2d51165f3..987e0c4b8 100644 --- a/src/ObjCommon/ObjContainer/ObjContainerReferenceable.h +++ b/src/ObjCommon/ObjContainer/ObjContainerReferenceable.h @@ -4,12 +4,11 @@ #include -class ObjContainerReferenceable : public IObjContainer -{ - std::set m_references; +class ObjContainerReferenceable : public IObjContainer { + std::set m_references; public: - void AddReference(void* referencer); - bool RemoveReference(void* referencer); - bool IsReferenced() const; + void AddReference(void *referencer); + bool RemoveReference(void *referencer); + bool IsReferenced() const; }; diff --git a/src/ObjCommon/Shader/D3D9ShaderAnalyser.cpp b/src/ObjCommon/Shader/D3D9ShaderAnalyser.cpp index 67f6498c9..0ff749612 100644 --- a/src/ObjCommon/Shader/D3D9ShaderAnalyser.cpp +++ b/src/ObjCommon/Shader/D3D9ShaderAnalyser.cpp @@ -7,241 +7,220 @@ using namespace d3d9; -namespace d3d9 -{ - // https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/d3d9types/ne-d3d9types-_d3dshader_instruction_opcode_type - static constexpr uint32_t OPCODE_COMMENT = 0xFFFE; - static constexpr uint32_t OPCODE_END = 0xFFFF; - - static constexpr uint32_t OPCODE_MASK = 0x0000FFFF; - - static constexpr uint32_t COMMENT_SIZE_MASK = 0xFFFF0000; - static constexpr uint32_t COMMENT_SIZE_SHIFT = 16; - - // https://docs.microsoft.com/en-us/windows/win32/direct3d9/d3dxshader-constanttable - struct ConstantTable - { - uint32_t Size; - uint32_t Creator; - uint32_t Version; - uint32_t Constants; - uint32_t ConstantInfo; - uint32_t Flags; - uint32_t Target; - }; - - // https://docs.microsoft.com/en-us/windows/win32/direct3d9/d3dxshader-constantinfo - struct ConstantInfo - { - uint32_t Name; - uint16_t RegisterSet; - uint16_t RegisterIndex; - uint16_t RegisterCount; - uint16_t Reserved; - uint32_t TypeInfo; - uint32_t DefaultValue; - }; - - // https://docs.microsoft.com/en-us/windows/win32/direct3d9/d3dxshader-typeinfo - struct TypeInfo - { - uint16_t Class; - uint16_t Type; - uint16_t Rows; - uint16_t Columns; - uint16_t Elements; - uint16_t StructMembers; - uint32_t StructMemberInfo; - }; - - // https://docs.microsoft.com/en-us/windows/win32/direct3d9/d3dxshader-structmemberinfo - struct StructMemberInfo - { - uint32_t Name; - uint32_t TypeInfo; - }; - - bool PopulateVersionInfo(ShaderInfo& shaderInfo, const uint32_t* shaderByteCode, const size_t shaderByteCodeSize) - { - if (shaderByteCodeSize < sizeof(uint32_t)) - return false; - - const auto version = *shaderByteCode; - shaderInfo.m_version_minor = version & 0xFF; - shaderInfo.m_version_major = (version & 0xFF00) >> 8; - - switch ((version & 0xFFFF0000) >> 16) - { - case 0x4658: // FX - case 0x5458: // TX - case 0x7ffe: // ? - case 0x7fff: // ? - shaderInfo.m_type = ShaderType::UNKNOWN; // Valid according to wine - return true; - case 0xfffe: - shaderInfo.m_type = ShaderType::VERTEX_SHADER; - return true; - case 0xffff: - shaderInfo.m_type = ShaderType::PIXEL_SHADER; - return true; - default: - break; - } +namespace d3d9 { +// https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/d3d9types/ne-d3d9types-_d3dshader_instruction_opcode_type +static constexpr uint32_t OPCODE_COMMENT = 0xFFFE; +static constexpr uint32_t OPCODE_END = 0xFFFF; + +static constexpr uint32_t OPCODE_MASK = 0x0000FFFF; + +static constexpr uint32_t COMMENT_SIZE_MASK = 0xFFFF0000; +static constexpr uint32_t COMMENT_SIZE_SHIFT = 16; + +// https://docs.microsoft.com/en-us/windows/win32/direct3d9/d3dxshader-constanttable +struct ConstantTable { + uint32_t Size; + uint32_t Creator; + uint32_t Version; + uint32_t Constants; + uint32_t ConstantInfo; + uint32_t Flags; + uint32_t Target; +}; + +// https://docs.microsoft.com/en-us/windows/win32/direct3d9/d3dxshader-constantinfo +struct ConstantInfo { + uint32_t Name; + uint16_t RegisterSet; + uint16_t RegisterIndex; + uint16_t RegisterCount; + uint16_t Reserved; + uint32_t TypeInfo; + uint32_t DefaultValue; +}; + +// https://docs.microsoft.com/en-us/windows/win32/direct3d9/d3dxshader-typeinfo +struct TypeInfo { + uint16_t Class; + uint16_t Type; + uint16_t Rows; + uint16_t Columns; + uint16_t Elements; + uint16_t StructMembers; + uint32_t StructMemberInfo; +}; + +// https://docs.microsoft.com/en-us/windows/win32/direct3d9/d3dxshader-structmemberinfo +struct StructMemberInfo { + uint32_t Name; + uint32_t TypeInfo; +}; + +bool PopulateVersionInfo(ShaderInfo &shaderInfo, const uint32_t *shaderByteCode, const size_t shaderByteCodeSize) { + if (shaderByteCodeSize < sizeof(uint32_t)) + return false; + + const auto version = *shaderByteCode; + shaderInfo.m_version_minor = version & 0xFF; + shaderInfo.m_version_major = (version & 0xFF00) >> 8; + + switch ((version & 0xFFFF0000) >> 16) { + case 0x4658: // FX + case 0x5458: // TX + case 0x7ffe: // ? + case 0x7fff: // ? + shaderInfo.m_type = ShaderType::UNKNOWN; // Valid according to wine + return true; + case 0xfffe: + shaderInfo.m_type = ShaderType::VERTEX_SHADER; + return true; + case 0xffff: + shaderInfo.m_type = ShaderType::PIXEL_SHADER; + return true; + default: + break; + } + + return false; +} +bool FindComment(const uint32_t *shaderByteCode, const size_t shaderByteCodeSize, const uint32_t magic, const char *&commentStart, size_t &commentSize) { + const uint32_t *currentPos = shaderByteCode + 1; + size_t currentOffset = sizeof(uint32_t); + while (*currentPos != OPCODE_END && (currentOffset + sizeof(uint32_t) - 1) < shaderByteCodeSize) { + const auto currentValue = *currentPos; + if ((currentValue & OPCODE_MASK) == OPCODE_COMMENT) { + assert(currentOffset + sizeof(uint32_t) < shaderByteCodeSize); + if (currentOffset + sizeof(uint32_t) >= shaderByteCodeSize) return false; - } - bool FindComment(const uint32_t* shaderByteCode, const size_t shaderByteCodeSize, const uint32_t magic, const char*& commentStart, size_t& commentSize) - { - const uint32_t* currentPos = shaderByteCode + 1; - size_t currentOffset = sizeof(uint32_t); - while (*currentPos != OPCODE_END && (currentOffset + sizeof(uint32_t) - 1) < shaderByteCodeSize) - { - const auto currentValue = *currentPos; - if ((currentValue & OPCODE_MASK) == OPCODE_COMMENT) - { - assert(currentOffset + sizeof(uint32_t) < shaderByteCodeSize); - if (currentOffset + sizeof(uint32_t) >= shaderByteCodeSize) - return false; - - const auto currentCommentSize = (currentValue & COMMENT_SIZE_MASK) >> COMMENT_SIZE_SHIFT; - - if (currentPos[1] == magic) - { - commentStart = reinterpret_cast(currentPos + 2); - commentSize = (currentCommentSize - 1) * sizeof(uint32_t); - return currentOffset + sizeof(uint32_t) * (currentCommentSize + 1) <= shaderByteCodeSize; - } - - currentPos += currentCommentSize; - currentOffset += currentCommentSize * sizeof(uint32_t); - } - - currentPos++; - currentOffset += sizeof(uint32_t); - assert((currentOffset + sizeof(uint32_t) - 1) < shaderByteCodeSize); - } + const auto currentCommentSize = (currentValue & COMMENT_SIZE_MASK) >> COMMENT_SIZE_SHIFT; - return false; - } + if (currentPos[1] == magic) { + commentStart = reinterpret_cast(currentPos + 2); + commentSize = (currentCommentSize - 1) * sizeof(uint32_t); + return currentOffset + sizeof(uint32_t) * (currentCommentSize + 1) <= shaderByteCodeSize; + } - bool StringFitsInComment(const char* str, const char* commentStart, const size_t commentSize) - { - const auto strLen = strnlen(str, commentSize - (str - commentStart)); - return str[strLen] == '\0'; + currentPos += currentCommentSize; + currentOffset += currentCommentSize * sizeof(uint32_t); } - bool PopulateShaderConstantFromConstantInfo(ShaderConstant& shaderConstant, const char* commentStart, const size_t commentSize, const ConstantInfo& constantInfo) - { - if (constantInfo.Name) - { - const auto* constantName = commentStart + constantInfo.Name; - if (!StringFitsInComment(constantName, commentStart, commentSize)) - return false; - shaderConstant.m_name = std::string(constantName); - } - - shaderConstant.m_register_set = static_cast(constantInfo.RegisterSet); - if (shaderConstant.m_register_set >= RegisterSet::MAX) - return false; - - shaderConstant.m_register_index = constantInfo.RegisterIndex; - shaderConstant.m_register_count = constantInfo.RegisterCount; - - if(constantInfo.TypeInfo) - { - assert(commentStart + constantInfo.TypeInfo + sizeof(TypeInfo) <= commentStart + commentSize); - if (commentStart + constantInfo.TypeInfo + sizeof(TypeInfo) > commentStart + commentSize) - return false; - - const auto* typeInfo = reinterpret_cast(commentStart + constantInfo.TypeInfo); - - shaderConstant.m_class = static_cast(typeInfo->Class); - if (shaderConstant.m_class >= ParameterClass::MAX) - return false; - - shaderConstant.m_type = static_cast(typeInfo->Type); - if (shaderConstant.m_type >= ParameterType::MAX) - return false; - - shaderConstant.m_type_rows = typeInfo->Rows; - shaderConstant.m_type_columns = typeInfo->Columns; - shaderConstant.m_type_elements = typeInfo->Elements; - } - - return true; - } + currentPos++; + currentOffset += sizeof(uint32_t); + assert((currentOffset + sizeof(uint32_t) - 1) < shaderByteCodeSize); + } - bool PopulateShaderInfoFromConstantTable(ShaderInfo& shaderInfo, const char* commentStart, const size_t commentSize, const ConstantTable& constantTable) - { - if (constantTable.Size != sizeof(ConstantTable)) - return false; - - if (constantTable.Creator) - { - const auto* creatorName = commentStart + constantTable.Creator; - if (!StringFitsInComment(creatorName, commentStart, commentSize)) - return false; - shaderInfo.m_creator = std::string(creatorName); - } - - if (constantTable.Target) - { - const auto* targetName = commentStart + constantTable.Target; - if (!StringFitsInComment(targetName, commentStart, commentSize)) - return false; - shaderInfo.m_target = std::string(targetName); - } - - if (constantTable.Constants > 0 && constantTable.ConstantInfo) - { - assert(commentStart + constantTable.ConstantInfo + sizeof(ConstantInfo) * constantTable.Constants <= commentStart + commentSize); - if (commentStart + constantTable.ConstantInfo + sizeof(ConstantInfo) * constantTable.Constants > commentStart + commentSize) - return false; - - const auto* constantInfos = reinterpret_cast(commentStart + constantTable.ConstantInfo); - for (auto constantInfoIndex = 0u; constantInfoIndex < constantTable.Constants; constantInfoIndex++) - { - ShaderConstant constant; - if (!PopulateShaderConstantFromConstantInfo(constant, commentStart, commentSize, constantInfos[constantInfoIndex])) - return false; - shaderInfo.m_constants.emplace_back(std::move(constant)); - } - } - - return true; - } + return false; +} + +bool StringFitsInComment(const char *str, const char *commentStart, const size_t commentSize) { + const auto strLen = strnlen(str, commentSize - (str - commentStart)); + return str[strLen] == '\0'; +} + +bool PopulateShaderConstantFromConstantInfo(ShaderConstant &shaderConstant, const char *commentStart, const size_t commentSize, + const ConstantInfo &constantInfo) { + if (constantInfo.Name) { + const auto *constantName = commentStart + constantInfo.Name; + if (!StringFitsInComment(constantName, commentStart, commentSize)) + return false; + shaderConstant.m_name = std::string(constantName); + } + + shaderConstant.m_register_set = static_cast(constantInfo.RegisterSet); + if (shaderConstant.m_register_set >= RegisterSet::MAX) + return false; + + shaderConstant.m_register_index = constantInfo.RegisterIndex; + shaderConstant.m_register_count = constantInfo.RegisterCount; - bool PopulateShaderInfoFromShaderByteCode(ShaderInfo& shaderInfo, const uint32_t* shaderByteCode, const size_t shaderByteCodeSize) - { - if (!PopulateVersionInfo(shaderInfo, shaderByteCode, shaderByteCodeSize)) - return false; + if (constantInfo.TypeInfo) { + assert(commentStart + constantInfo.TypeInfo + sizeof(TypeInfo) <= commentStart + commentSize); + if (commentStart + constantInfo.TypeInfo + sizeof(TypeInfo) > commentStart + commentSize) + return false; - const char* constantTableComment; - size_t constantTableCommentSize; - if (!FindComment(shaderByteCode, shaderByteCodeSize, FileUtils::MakeMagic32('C', 'T', 'A', 'B'), constantTableComment, constantTableCommentSize)) - return false; + const auto *typeInfo = reinterpret_cast(commentStart + constantInfo.TypeInfo); - if (constantTableCommentSize < sizeof(ConstantTable)) - return false; + shaderConstant.m_class = static_cast(typeInfo->Class); + if (shaderConstant.m_class >= ParameterClass::MAX) + return false; - const auto* constantTable = reinterpret_cast(constantTableComment); - if (!PopulateShaderInfoFromConstantTable(shaderInfo, constantTableComment, constantTableCommentSize, *constantTable)) - return false; + shaderConstant.m_type = static_cast(typeInfo->Type); + if (shaderConstant.m_type >= ParameterType::MAX) + return false; - return true; + shaderConstant.m_type_rows = typeInfo->Rows; + shaderConstant.m_type_columns = typeInfo->Columns; + shaderConstant.m_type_elements = typeInfo->Elements; + } + + return true; +} + +bool PopulateShaderInfoFromConstantTable(ShaderInfo &shaderInfo, const char *commentStart, const size_t commentSize, const ConstantTable &constantTable) { + if (constantTable.Size != sizeof(ConstantTable)) + return false; + + if (constantTable.Creator) { + const auto *creatorName = commentStart + constantTable.Creator; + if (!StringFitsInComment(creatorName, commentStart, commentSize)) + return false; + shaderInfo.m_creator = std::string(creatorName); + } + + if (constantTable.Target) { + const auto *targetName = commentStart + constantTable.Target; + if (!StringFitsInComment(targetName, commentStart, commentSize)) + return false; + shaderInfo.m_target = std::string(targetName); + } + + if (constantTable.Constants > 0 && constantTable.ConstantInfo) { + assert(commentStart + constantTable.ConstantInfo + sizeof(ConstantInfo) * constantTable.Constants <= commentStart + commentSize); + if (commentStart + constantTable.ConstantInfo + sizeof(ConstantInfo) * constantTable.Constants > commentStart + commentSize) + return false; + + const auto *constantInfos = reinterpret_cast(commentStart + constantTable.ConstantInfo); + for (auto constantInfoIndex = 0u; constantInfoIndex < constantTable.Constants; constantInfoIndex++) { + ShaderConstant constant; + if (!PopulateShaderConstantFromConstantInfo(constant, commentStart, commentSize, constantInfos[constantInfoIndex])) + return false; + shaderInfo.m_constants.emplace_back(std::move(constant)); } + } + + return true; +} + +bool PopulateShaderInfoFromShaderByteCode(ShaderInfo &shaderInfo, const uint32_t *shaderByteCode, const size_t shaderByteCodeSize) { + if (!PopulateVersionInfo(shaderInfo, shaderByteCode, shaderByteCodeSize)) + return false; + + const char *constantTableComment; + size_t constantTableCommentSize; + if (!FindComment(shaderByteCode, shaderByteCodeSize, FileUtils::MakeMagic32('C', 'T', 'A', 'B'), constantTableComment, constantTableCommentSize)) + return false; + + if (constantTableCommentSize < sizeof(ConstantTable)) + return false; + + const auto *constantTable = reinterpret_cast(constantTableComment); + if (!PopulateShaderInfoFromConstantTable(shaderInfo, constantTableComment, constantTableCommentSize, *constantTable)) + return false; + + return true; } +} // namespace d3d9 -std::unique_ptr ShaderAnalyser::GetShaderInfo(const uint32_t* shaderByteCode, const size_t shaderByteCodeSize) -{ - if (shaderByteCode == nullptr || shaderByteCodeSize == 0) - return nullptr; +std::unique_ptr ShaderAnalyser::GetShaderInfo(const uint32_t *shaderByteCode, const size_t shaderByteCodeSize) { + if (shaderByteCode == nullptr || shaderByteCodeSize == 0) + return nullptr; - auto shaderInfo = std::make_unique(); + auto shaderInfo = std::make_unique(); - if (!PopulateShaderInfoFromShaderByteCode(*shaderInfo, shaderByteCode, shaderByteCodeSize)) - return nullptr; + if (!PopulateShaderInfoFromShaderByteCode(*shaderInfo, shaderByteCode, shaderByteCodeSize)) + return nullptr; - return shaderInfo; + return shaderInfo; } diff --git a/src/ObjCommon/Shader/D3D9ShaderAnalyser.h b/src/ObjCommon/Shader/D3D9ShaderAnalyser.h index 7e02ebd24..5ae8ae274 100644 --- a/src/ObjCommon/Shader/D3D9ShaderAnalyser.h +++ b/src/ObjCommon/Shader/D3D9ShaderAnalyser.h @@ -4,97 +4,85 @@ #include #include -namespace d3d9 -{ - enum class ShaderType - { - UNKNOWN, - PIXEL_SHADER, - VERTEX_SHADER - }; +namespace d3d9 { +enum class ShaderType { UNKNOWN, PIXEL_SHADER, VERTEX_SHADER }; - // https://docs.microsoft.com/en-us/windows/win32/direct3d9/d3dxregister-set - enum class RegisterSet - { - BOOL, - INT_4, - FLOAT_4, - SAMPLER, +// https://docs.microsoft.com/en-us/windows/win32/direct3d9/d3dxregister-set +enum class RegisterSet { + BOOL, + INT_4, + FLOAT_4, + SAMPLER, - // This entry only exist to mark the size of the enum and is not an actual valid value - MAX - }; + // This entry only exist to mark the size of the enum and is not an actual valid value + MAX +}; - // https://docs.microsoft.com/en-us/windows/win32/direct3d9/d3dxparameter-class - enum class ParameterClass - { - SCALAR, - VECTOR, - MATRIX_ROWS, - MATRIX_COLUMNS, - OBJECT, - STRUCT, +// https://docs.microsoft.com/en-us/windows/win32/direct3d9/d3dxparameter-class +enum class ParameterClass { + SCALAR, + VECTOR, + MATRIX_ROWS, + MATRIX_COLUMNS, + OBJECT, + STRUCT, - // This entry only exist to mark the size of the enum and is not an actual valid value - MAX - }; + // This entry only exist to mark the size of the enum and is not an actual valid value + MAX +}; - // https://docs.microsoft.com/en-us/windows/win32/direct3d9/d3dxparameter-type - enum class ParameterType - { - VOID, - BOOL, - INT, - FLOAT, - STRING, - TEXTURE, - TEXTURE_1D, - TEXTURE_2D, - TEXTURE_3D, - TEXTURE_CUBE, - SAMPLER, - SAMPLER_1D, - SAMPLER_2D, - SAMPLER_3D, - SAMPLER_CUBE, - PIXEL_SHADER, - VERTEX_SHADER, - PIXEL_FRAGMENT, - VERTEX_FRAGMENT, - UNSUPPORTED, +// https://docs.microsoft.com/en-us/windows/win32/direct3d9/d3dxparameter-type +enum class ParameterType { + VOID, + BOOL, + INT, + FLOAT, + STRING, + TEXTURE, + TEXTURE_1D, + TEXTURE_2D, + TEXTURE_3D, + TEXTURE_CUBE, + SAMPLER, + SAMPLER_1D, + SAMPLER_2D, + SAMPLER_3D, + SAMPLER_CUBE, + PIXEL_SHADER, + VERTEX_SHADER, + PIXEL_FRAGMENT, + VERTEX_FRAGMENT, + UNSUPPORTED, - // This entry only exist to mark the size of the enum and is not an actual valid value - MAX - }; + // This entry only exist to mark the size of the enum and is not an actual valid value + MAX +}; - class ShaderConstant - { - public: - std::string m_name; - RegisterSet m_register_set{}; - unsigned m_register_index = 0; - unsigned m_register_count = 0; - ParameterClass m_class{}; - ParameterType m_type{}; - unsigned m_type_rows = 0; - unsigned m_type_columns = 0; - unsigned m_type_elements = 0; - }; +class ShaderConstant { +public: + std::string m_name; + RegisterSet m_register_set{}; + unsigned m_register_index = 0; + unsigned m_register_count = 0; + ParameterClass m_class{}; + ParameterType m_type{}; + unsigned m_type_rows = 0; + unsigned m_type_columns = 0; + unsigned m_type_elements = 0; +}; - class ShaderInfo - { - public: - ShaderType m_type = ShaderType::UNKNOWN; - unsigned m_version_major = 0; - unsigned m_version_minor = 0; - std::string m_creator; - std::string m_target; - std::vector m_constants; - }; +class ShaderInfo { +public: + ShaderType m_type = ShaderType::UNKNOWN; + unsigned m_version_major = 0; + unsigned m_version_minor = 0; + std::string m_creator; + std::string m_target; + std::vector m_constants; +}; - class ShaderAnalyser - { - public: - static std::unique_ptr GetShaderInfo(const uint32_t* shaderByteCode, size_t shaderByteCodeSize); - }; -} \ No newline at end of file +class ShaderAnalyser { +public: + static std::unique_ptr GetShaderInfo(const uint32_t *shaderByteCode, size_t shaderByteCodeSize); +}; +} // namespace d3d9 \ No newline at end of file diff --git a/src/ObjCommon/Sound/WavTypes.h b/src/ObjCommon/Sound/WavTypes.h index e5cd145d4..444106430 100644 --- a/src/ObjCommon/Sound/WavTypes.h +++ b/src/ObjCommon/Sound/WavTypes.h @@ -8,23 +8,18 @@ constexpr uint32_t WAV_CHUNK_ID_RIFF = FileUtils::MakeMagic32('R', 'I', 'F', 'F' constexpr uint32_t WAV_CHUNK_ID_FMT = FileUtils::MakeMagic32('f', 'm', 't', ' '); constexpr uint32_t WAV_CHUNK_ID_DATA = FileUtils::MakeMagic32('d', 'a', 't', 'a'); -struct WavChunkHeader -{ - uint32_t chunkID; - uint32_t chunkSize; +struct WavChunkHeader { + uint32_t chunkID; + uint32_t chunkSize; }; -enum class WavFormat : int16_t -{ - PCM = 1 -}; +enum class WavFormat : int16_t { PCM = 1 }; -struct WavFormatChunkPcm -{ - WavFormat wFormatTag; - uint16_t nChannels; - uint32_t nSamplesPerSec; - uint32_t nAvgBytesPerSec; - uint16_t nBlockAlign; - uint16_t wBitsPerSample; +struct WavFormatChunkPcm { + WavFormat wFormatTag; + uint16_t nChannels; + uint32_t nSamplesPerSec; + uint32_t nAvgBytesPerSec; + uint16_t nBlockAlign; + uint16_t wBitsPerSample; }; \ No newline at end of file diff --git a/src/ObjCommon/StructuredDataDef/CommonStructuredDataDef.cpp b/src/ObjCommon/StructuredDataDef/CommonStructuredDataDef.cpp index 5aad0732f..ab95e963d 100644 --- a/src/ObjCommon/StructuredDataDef/CommonStructuredDataDef.cpp +++ b/src/ObjCommon/StructuredDataDef/CommonStructuredDataDef.cpp @@ -1,24 +1,15 @@ #include "CommonStructuredDataDef.h" -CommonStructuredDataDef::CommonStructuredDataDef() - : CommonStructuredDataDef(0) -{ -} +CommonStructuredDataDef::CommonStructuredDataDef() : CommonStructuredDataDef(0) {} -CommonStructuredDataDef::CommonStructuredDataDef(const int version) - : m_version(version), - m_checksum(0u), - m_size_in_byte(0u) -{ -} +CommonStructuredDataDef::CommonStructuredDataDef(const int version) : m_version(version), m_checksum(0u), m_size_in_byte(0u) {} -uint32_t CommonStructuredDataDef::CalculateChecksum() const -{ - auto checksum = 0u; - for (const auto& _enum : m_enums) - checksum = _enum->CalculateChecksum(checksum); - for (const auto& _struct : m_structs) - checksum = _struct->CalculateChecksum(*this, checksum); +uint32_t CommonStructuredDataDef::CalculateChecksum() const { + auto checksum = 0u; + for (const auto &_enum : m_enums) + checksum = _enum->CalculateChecksum(checksum); + for (const auto &_struct : m_structs) + checksum = _struct->CalculateChecksum(*this, checksum); - return checksum; + return checksum; } diff --git a/src/ObjCommon/StructuredDataDef/CommonStructuredDataDef.h b/src/ObjCommon/StructuredDataDef/CommonStructuredDataDef.h index ff16ef805..19f99a85f 100644 --- a/src/ObjCommon/StructuredDataDef/CommonStructuredDataDef.h +++ b/src/ObjCommon/StructuredDataDef/CommonStructuredDataDef.h @@ -3,25 +3,24 @@ #include #include -#include "Utils/ClassUtils.h" #include "CommonStructuredDataEnum.h" #include "CommonStructuredDataStruct.h" +#include "Utils/ClassUtils.h" -class CommonStructuredDataDef -{ +class CommonStructuredDataDef { public: - std::vector> m_enums; - std::vector> m_structs; - std::vector m_indexed_arrays; - std::vector m_enumed_arrays; + std::vector> m_enums; + std::vector> m_structs; + std::vector m_indexed_arrays; + std::vector m_enumed_arrays; - int m_version; - size_t m_checksum; - CommonStructuredDataType m_root_type; - size_t m_size_in_byte; + int m_version; + size_t m_checksum; + CommonStructuredDataType m_root_type; + size_t m_size_in_byte; - CommonStructuredDataDef(); - explicit CommonStructuredDataDef(int version); + CommonStructuredDataDef(); + explicit CommonStructuredDataDef(int version); - _NODISCARD uint32_t CalculateChecksum() const; + _NODISCARD uint32_t CalculateChecksum() const; }; diff --git a/src/ObjCommon/StructuredDataDef/CommonStructuredDataEnum.cpp b/src/ObjCommon/StructuredDataDef/CommonStructuredDataEnum.cpp index 1eaee34f3..2b440546c 100644 --- a/src/ObjCommon/StructuredDataDef/CommonStructuredDataEnum.cpp +++ b/src/ObjCommon/StructuredDataDef/CommonStructuredDataEnum.cpp @@ -5,71 +5,43 @@ #include "Utils/Endianness.h" -CommonStructuredDataEnumEntry::CommonStructuredDataEnumEntry() - : m_value(0u) -{ -} +CommonStructuredDataEnumEntry::CommonStructuredDataEnumEntry() : m_value(0u) {} -CommonStructuredDataEnumEntry::CommonStructuredDataEnumEntry(std::string name, const size_t value) - : m_name(std::move(name)), - m_value(value) -{ -} +CommonStructuredDataEnumEntry::CommonStructuredDataEnumEntry(std::string name, const size_t value) : m_name(std::move(name)), m_value(value) {} -CommonStructuredDataEnum::CommonStructuredDataEnum() - : m_reserved_entry_count(-1) -{ -} +CommonStructuredDataEnum::CommonStructuredDataEnum() : m_reserved_entry_count(-1) {} -CommonStructuredDataEnum::CommonStructuredDataEnum(std::string name) - : m_name(std::move(name)), - m_reserved_entry_count(-1) -{ -} +CommonStructuredDataEnum::CommonStructuredDataEnum(std::string name) : m_name(std::move(name)), m_reserved_entry_count(-1) {} CommonStructuredDataEnum::CommonStructuredDataEnum(std::string name, const int reservedEntryCount) - : m_name(std::move(name)), - m_reserved_entry_count(reservedEntryCount) -{ -} + : m_name(std::move(name)), m_reserved_entry_count(reservedEntryCount) {} -size_t CommonStructuredDataEnum::ElementCount() const -{ - return m_reserved_entry_count > 0 ? static_cast(m_reserved_entry_count) : m_entries.size(); -} +size_t CommonStructuredDataEnum::ElementCount() const { return m_reserved_entry_count > 0 ? static_cast(m_reserved_entry_count) : m_entries.size(); } -uint32_t CommonStructuredDataEnum::CalculateChecksum(const uint32_t initialValue) const -{ - auto checksum = initialValue; +uint32_t CommonStructuredDataEnum::CalculateChecksum(const uint32_t initialValue) const { + auto checksum = initialValue; - checksum = crc32(checksum, reinterpret_cast(m_name.c_str()), m_name.size() + 1); + checksum = crc32(checksum, reinterpret_cast(m_name.c_str()), m_name.size() + 1); - const auto littleEndianElementCount = endianness::ToLittleEndian(ElementCount()); - checksum = crc32(checksum, reinterpret_cast(&littleEndianElementCount), sizeof(littleEndianElementCount)); + const auto littleEndianElementCount = endianness::ToLittleEndian(ElementCount()); + checksum = crc32(checksum, reinterpret_cast(&littleEndianElementCount), sizeof(littleEndianElementCount)); - for (const auto& entry : m_entries) - { - checksum = crc32(checksum, reinterpret_cast(entry.m_name.c_str()), entry.m_name.size() + 1); + for (const auto &entry : m_entries) { + checksum = crc32(checksum, reinterpret_cast(entry.m_name.c_str()), entry.m_name.size() + 1); - const auto littleEndianValue = endianness::ToLittleEndian(entry.m_value); - checksum = crc32(checksum, reinterpret_cast(&littleEndianValue), sizeof(littleEndianValue)); - } + const auto littleEndianValue = endianness::ToLittleEndian(entry.m_value); + checksum = crc32(checksum, reinterpret_cast(&littleEndianValue), sizeof(littleEndianValue)); + } - return checksum; + return checksum; } -void CommonStructuredDataEnum::SortEntriesByOffset() -{ - std::sort(m_entries.begin(), m_entries.end(), [](const CommonStructuredDataEnumEntry& e1, const CommonStructuredDataEnumEntry& e2) - { - return e1.m_value < e2.m_value; - }); +void CommonStructuredDataEnum::SortEntriesByOffset() { + std::sort(m_entries.begin(), m_entries.end(), + [](const CommonStructuredDataEnumEntry &e1, const CommonStructuredDataEnumEntry &e2) { return e1.m_value < e2.m_value; }); } -void CommonStructuredDataEnum::SortEntriesByName() -{ - std::sort(m_entries.begin(), m_entries.end(), [](const CommonStructuredDataEnumEntry& e1, const CommonStructuredDataEnumEntry& e2) - { - return e1.m_name < e2.m_name; - }); +void CommonStructuredDataEnum::SortEntriesByName() { + std::sort(m_entries.begin(), m_entries.end(), + [](const CommonStructuredDataEnumEntry &e1, const CommonStructuredDataEnumEntry &e2) { return e1.m_name < e2.m_name; }); } diff --git a/src/ObjCommon/StructuredDataDef/CommonStructuredDataEnum.h b/src/ObjCommon/StructuredDataDef/CommonStructuredDataEnum.h index 86b1fd697..31fe8fe1e 100644 --- a/src/ObjCommon/StructuredDataDef/CommonStructuredDataEnum.h +++ b/src/ObjCommon/StructuredDataDef/CommonStructuredDataEnum.h @@ -6,28 +6,26 @@ #include "Utils/ClassUtils.h" -struct CommonStructuredDataEnumEntry -{ - std::string m_name; - size_t m_value; +struct CommonStructuredDataEnumEntry { + std::string m_name; + size_t m_value; - CommonStructuredDataEnumEntry(); - CommonStructuredDataEnumEntry(std::string name, size_t value); + CommonStructuredDataEnumEntry(); + CommonStructuredDataEnumEntry(std::string name, size_t value); }; -struct CommonStructuredDataEnum -{ - std::string m_name; - int m_reserved_entry_count; - std::vector m_entries; +struct CommonStructuredDataEnum { + std::string m_name; + int m_reserved_entry_count; + std::vector m_entries; - CommonStructuredDataEnum(); - explicit CommonStructuredDataEnum(std::string name); - CommonStructuredDataEnum(std::string name, int reservedEntryCount); + CommonStructuredDataEnum(); + explicit CommonStructuredDataEnum(std::string name); + CommonStructuredDataEnum(std::string name, int reservedEntryCount); - _NODISCARD size_t ElementCount() const; - _NODISCARD uint32_t CalculateChecksum(uint32_t initialValue) const; + _NODISCARD size_t ElementCount() const; + _NODISCARD uint32_t CalculateChecksum(uint32_t initialValue) const; - void SortEntriesByOffset(); - void SortEntriesByName(); + void SortEntriesByOffset(); + void SortEntriesByName(); }; diff --git a/src/ObjCommon/StructuredDataDef/CommonStructuredDataStruct.cpp b/src/ObjCommon/StructuredDataDef/CommonStructuredDataStruct.cpp index 5e0e32d61..264cb7178 100644 --- a/src/ObjCommon/StructuredDataDef/CommonStructuredDataStruct.cpp +++ b/src/ObjCommon/StructuredDataDef/CommonStructuredDataStruct.cpp @@ -6,128 +6,90 @@ #include "CommonStructuredDataDef.h" #include "Utils/Endianness.h" -CommonStructuredDataStructProperty::CommonStructuredDataStructProperty() - : m_offset_in_bits(0u) -{ -} +CommonStructuredDataStructProperty::CommonStructuredDataStructProperty() : m_offset_in_bits(0u) {} -CommonStructuredDataStructProperty::CommonStructuredDataStructProperty(std::string name) - : m_name(std::move(name)), - m_offset_in_bits(0u) -{ -} +CommonStructuredDataStructProperty::CommonStructuredDataStructProperty(std::string name) : m_name(std::move(name)), m_offset_in_bits(0u) {} CommonStructuredDataStructProperty::CommonStructuredDataStructProperty(std::string name, const CommonStructuredDataType type, const size_t offsetInBits) - : m_name(std::move(name)), - m_type(type), - m_offset_in_bits(offsetInBits) -{ -} - -CommonStructuredDataStruct::CommonStructuredDataStruct() - : m_bit_offset(0u), - m_size_in_byte(0u) -{ -} - -CommonStructuredDataStruct::CommonStructuredDataStruct(std::string name) - : m_name(std::move(name)), - m_bit_offset(0u), - m_size_in_byte(0u) -{ -} - -uint32_t CommonStructuredDataStruct::CalculateChecksum(const CommonStructuredDataDef& def, const uint32_t initialValue) const -{ - auto checksum = initialValue; - - checksum = crc32(checksum, reinterpret_cast(m_name.c_str()), m_name.size() + 1); - for (const auto& property : m_properties) - { - checksum = crc32(checksum, reinterpret_cast(property.m_name.c_str()), property.m_name.size() + 1); - - const auto littleEndianOffset = endianness::ToLittleEndian(property.m_offset_in_bits); - checksum = crc32(checksum, reinterpret_cast(&littleEndianOffset), sizeof(littleEndianOffset)); - - auto currentType = property.m_type; - while (currentType.m_category != CommonStructuredDataTypeCategory::UNKNOWN) - { - const auto categoryByte = static_cast(currentType.m_category); - checksum = crc32(checksum, &categoryByte, sizeof(categoryByte)); - - switch (currentType.m_category) - { - case CommonStructuredDataTypeCategory::STRING: - { - const auto littleEndianStringLength = endianness::ToLittleEndian(currentType.m_info.string_length); - checksum = crc32(checksum, reinterpret_cast(&littleEndianStringLength), sizeof(littleEndianStringLength)); - currentType = CommonStructuredDataType(CommonStructuredDataTypeCategory::UNKNOWN); - } - break; - case CommonStructuredDataTypeCategory::ENUM: - if (currentType.m_info.type_index < def.m_enums.size()) - { - const auto& _enum = *def.m_enums[currentType.m_info.type_index]; - checksum = crc32(checksum, reinterpret_cast(_enum.m_name.c_str()), _enum.m_name.size() + 1); - currentType = CommonStructuredDataType(CommonStructuredDataTypeCategory::UNKNOWN); - } - break; - case CommonStructuredDataTypeCategory::STRUCT: - if (currentType.m_info.type_index < def.m_structs.size()) - { - const auto& _struct = *def.m_structs[currentType.m_info.type_index]; - checksum = crc32(checksum, reinterpret_cast(_struct.m_name.c_str()), _struct.m_name.size() + 1); - currentType = CommonStructuredDataType(CommonStructuredDataTypeCategory::UNKNOWN); - } - break; - case CommonStructuredDataTypeCategory::INDEXED_ARRAY: - if (currentType.m_info.type_index < def.m_indexed_arrays.size()) - { - const auto& indexedArray = def.m_indexed_arrays[currentType.m_info.type_index]; - const auto littleEndianElementCount = endianness::ToLittleEndian(indexedArray.m_element_count); - checksum = crc32(checksum, reinterpret_cast(&littleEndianElementCount), sizeof(littleEndianElementCount)); - currentType = indexedArray.m_array_type; - } - else - currentType = CommonStructuredDataType(CommonStructuredDataTypeCategory::UNKNOWN); - break; - case CommonStructuredDataTypeCategory::ENUM_ARRAY: - if (currentType.m_info.type_index < def.m_enumed_arrays.size()) - { - const auto& enumedArray = def.m_enumed_arrays[currentType.m_info.type_index]; - - if (enumedArray.m_enum_index < def.m_enums.size()) - { - const auto& _enum = *def.m_enums[enumedArray.m_enum_index]; - checksum = crc32(checksum, reinterpret_cast(_enum.m_name.c_str()), _enum.m_name.size() + 1); - } - currentType = enumedArray.m_array_type; - } - else - currentType = CommonStructuredDataType(CommonStructuredDataTypeCategory::UNKNOWN); - break; - default: - currentType = CommonStructuredDataType(CommonStructuredDataTypeCategory::UNKNOWN); - break; - } + : m_name(std::move(name)), m_type(type), m_offset_in_bits(offsetInBits) {} + +CommonStructuredDataStruct::CommonStructuredDataStruct() : m_bit_offset(0u), m_size_in_byte(0u) {} + +CommonStructuredDataStruct::CommonStructuredDataStruct(std::string name) : m_name(std::move(name)), m_bit_offset(0u), m_size_in_byte(0u) {} + +uint32_t CommonStructuredDataStruct::CalculateChecksum(const CommonStructuredDataDef &def, const uint32_t initialValue) const { + auto checksum = initialValue; + + checksum = crc32(checksum, reinterpret_cast(m_name.c_str()), m_name.size() + 1); + for (const auto &property : m_properties) { + checksum = crc32(checksum, reinterpret_cast(property.m_name.c_str()), property.m_name.size() + 1); + + const auto littleEndianOffset = endianness::ToLittleEndian(property.m_offset_in_bits); + checksum = crc32(checksum, reinterpret_cast(&littleEndianOffset), sizeof(littleEndianOffset)); + + auto currentType = property.m_type; + while (currentType.m_category != CommonStructuredDataTypeCategory::UNKNOWN) { + const auto categoryByte = static_cast(currentType.m_category); + checksum = crc32(checksum, &categoryByte, sizeof(categoryByte)); + + switch (currentType.m_category) { + case CommonStructuredDataTypeCategory::STRING: { + const auto littleEndianStringLength = endianness::ToLittleEndian(currentType.m_info.string_length); + checksum = crc32(checksum, reinterpret_cast(&littleEndianStringLength), sizeof(littleEndianStringLength)); + currentType = CommonStructuredDataType(CommonStructuredDataTypeCategory::UNKNOWN); + } break; + case CommonStructuredDataTypeCategory::ENUM: + if (currentType.m_info.type_index < def.m_enums.size()) { + const auto &_enum = *def.m_enums[currentType.m_info.type_index]; + checksum = crc32(checksum, reinterpret_cast(_enum.m_name.c_str()), _enum.m_name.size() + 1); + currentType = CommonStructuredDataType(CommonStructuredDataTypeCategory::UNKNOWN); + } + break; + case CommonStructuredDataTypeCategory::STRUCT: + if (currentType.m_info.type_index < def.m_structs.size()) { + const auto &_struct = *def.m_structs[currentType.m_info.type_index]; + checksum = crc32(checksum, reinterpret_cast(_struct.m_name.c_str()), _struct.m_name.size() + 1); + currentType = CommonStructuredDataType(CommonStructuredDataTypeCategory::UNKNOWN); } + break; + case CommonStructuredDataTypeCategory::INDEXED_ARRAY: + if (currentType.m_info.type_index < def.m_indexed_arrays.size()) { + const auto &indexedArray = def.m_indexed_arrays[currentType.m_info.type_index]; + const auto littleEndianElementCount = endianness::ToLittleEndian(indexedArray.m_element_count); + checksum = crc32(checksum, reinterpret_cast(&littleEndianElementCount), sizeof(littleEndianElementCount)); + currentType = indexedArray.m_array_type; + } else + currentType = CommonStructuredDataType(CommonStructuredDataTypeCategory::UNKNOWN); + break; + case CommonStructuredDataTypeCategory::ENUM_ARRAY: + if (currentType.m_info.type_index < def.m_enumed_arrays.size()) { + const auto &enumedArray = def.m_enumed_arrays[currentType.m_info.type_index]; + + if (enumedArray.m_enum_index < def.m_enums.size()) { + const auto &_enum = *def.m_enums[enumedArray.m_enum_index]; + checksum = crc32(checksum, reinterpret_cast(_enum.m_name.c_str()), _enum.m_name.size() + 1); + } + currentType = enumedArray.m_array_type; + } else + currentType = CommonStructuredDataType(CommonStructuredDataTypeCategory::UNKNOWN); + break; + default: + currentType = CommonStructuredDataType(CommonStructuredDataTypeCategory::UNKNOWN); + break; + } } + } - return checksum; + return checksum; } -void CommonStructuredDataStruct::SortPropertiesByOffset() -{ - std::sort(m_properties.begin(), m_properties.end(), [](const CommonStructuredDataStructProperty& e1, const CommonStructuredDataStructProperty& e2) - { - return e1.m_offset_in_bits < e2.m_offset_in_bits; - }); +void CommonStructuredDataStruct::SortPropertiesByOffset() { + std::sort(m_properties.begin(), m_properties.end(), [](const CommonStructuredDataStructProperty &e1, const CommonStructuredDataStructProperty &e2) { + return e1.m_offset_in_bits < e2.m_offset_in_bits; + }); } -void CommonStructuredDataStruct::SortPropertiesByName() -{ - std::sort(m_properties.begin(), m_properties.end(), [](const CommonStructuredDataStructProperty& e1, const CommonStructuredDataStructProperty& e2) - { - return e1.m_name < e2.m_name; - }); +void CommonStructuredDataStruct::SortPropertiesByName() { + std::sort(m_properties.begin(), m_properties.end(), + [](const CommonStructuredDataStructProperty &e1, const CommonStructuredDataStructProperty &e2) { return e1.m_name < e2.m_name; }); } diff --git a/src/ObjCommon/StructuredDataDef/CommonStructuredDataStruct.h b/src/ObjCommon/StructuredDataDef/CommonStructuredDataStruct.h index 3dbf02a6d..764b9b62e 100644 --- a/src/ObjCommon/StructuredDataDef/CommonStructuredDataStruct.h +++ b/src/ObjCommon/StructuredDataDef/CommonStructuredDataStruct.h @@ -3,33 +3,31 @@ #include #include -#include "Utils/ClassUtils.h" #include "CommonStructuredDataTypes.h" +#include "Utils/ClassUtils.h" -struct CommonStructuredDataStructProperty -{ - std::string m_name; - CommonStructuredDataType m_type; - size_t m_offset_in_bits; +struct CommonStructuredDataStructProperty { + std::string m_name; + CommonStructuredDataType m_type; + size_t m_offset_in_bits; - CommonStructuredDataStructProperty(); - explicit CommonStructuredDataStructProperty(std::string name); - CommonStructuredDataStructProperty(std::string name, CommonStructuredDataType type, size_t offsetInBits); + CommonStructuredDataStructProperty(); + explicit CommonStructuredDataStructProperty(std::string name); + CommonStructuredDataStructProperty(std::string name, CommonStructuredDataType type, size_t offsetInBits); }; class CommonStructuredDataDef; -struct CommonStructuredDataStruct -{ - std::string m_name; - std::vector m_properties; - size_t m_bit_offset; - size_t m_size_in_byte; +struct CommonStructuredDataStruct { + std::string m_name; + std::vector m_properties; + size_t m_bit_offset; + size_t m_size_in_byte; - CommonStructuredDataStruct(); - explicit CommonStructuredDataStruct(std::string name); + CommonStructuredDataStruct(); + explicit CommonStructuredDataStruct(std::string name); - _NODISCARD uint32_t CalculateChecksum(const CommonStructuredDataDef& def, uint32_t initialValue) const; + _NODISCARD uint32_t CalculateChecksum(const CommonStructuredDataDef &def, uint32_t initialValue) const; - void SortPropertiesByOffset(); - void SortPropertiesByName(); + void SortPropertiesByOffset(); + void SortPropertiesByName(); }; diff --git a/src/ObjCommon/StructuredDataDef/CommonStructuredDataTypes.cpp b/src/ObjCommon/StructuredDataDef/CommonStructuredDataTypes.cpp index 276d51752..2a46130bf 100644 --- a/src/ObjCommon/StructuredDataDef/CommonStructuredDataTypes.cpp +++ b/src/ObjCommon/StructuredDataDef/CommonStructuredDataTypes.cpp @@ -5,183 +5,114 @@ #include "CommonStructuredDataDef.h" #include "Utils/Alignment.h" -CommonStructuredDataType::CommonStructuredDataType() - : m_category(CommonStructuredDataTypeCategory::UNKNOWN), - m_info({0}) -{ -} +CommonStructuredDataType::CommonStructuredDataType() : m_category(CommonStructuredDataTypeCategory::UNKNOWN), m_info({0}) {} -CommonStructuredDataType::CommonStructuredDataType(const CommonStructuredDataTypeCategory category) - : m_category(category), - m_info({0}) -{ -} +CommonStructuredDataType::CommonStructuredDataType(const CommonStructuredDataTypeCategory category) : m_category(category), m_info({0}) {} CommonStructuredDataType::CommonStructuredDataType(const CommonStructuredDataTypeCategory category, const size_t extraInfo) - : m_category(category), - m_info({extraInfo}) -{ -} - -size_t CommonStructuredDataType::GetAlignmentInBits() const -{ - return m_category == CommonStructuredDataTypeCategory::BOOL ? 0u : 8u; -} - -size_t CommonStructuredDataType::GetSizeInBits(const CommonStructuredDataDef& def) const -{ - switch (m_category) - { - case CommonStructuredDataTypeCategory::INT: - case CommonStructuredDataTypeCategory::FLOAT: - return 32u; - case CommonStructuredDataTypeCategory::BYTE: - return 8u; - case CommonStructuredDataTypeCategory::BOOL: - return 1u; - case CommonStructuredDataTypeCategory::ENUM: - case CommonStructuredDataTypeCategory::SHORT: - return 16u; - case CommonStructuredDataTypeCategory::STRING: - return m_info.string_length * 8; - case CommonStructuredDataTypeCategory::STRUCT: - if (m_info.type_index >= def.m_structs.size()) - { - assert(false); - return 0u; - } - return def.m_structs[m_info.type_index]->m_size_in_byte * 8u; - case CommonStructuredDataTypeCategory::INDEXED_ARRAY: - { - if (m_info.type_index >= def.m_indexed_arrays.size()) - { - assert(false); - return 0u; - } - const auto& indexedArray = def.m_indexed_arrays[m_info.type_index]; - return utils::Align(indexedArray.m_element_size_in_bits * indexedArray.m_element_count, 8u); - } - case CommonStructuredDataTypeCategory::ENUM_ARRAY: - { - if (m_info.type_index >= def.m_enumed_arrays.size()) - { - assert(false); - return 0u; - } - const auto& enumedArray = def.m_enumed_arrays[m_info.type_index]; - return utils::Align(enumedArray.m_element_size_in_bits * enumedArray.m_element_count, 8u); + : m_category(category), m_info({extraInfo}) {} + +size_t CommonStructuredDataType::GetAlignmentInBits() const { return m_category == CommonStructuredDataTypeCategory::BOOL ? 0u : 8u; } + +size_t CommonStructuredDataType::GetSizeInBits(const CommonStructuredDataDef &def) const { + switch (m_category) { + case CommonStructuredDataTypeCategory::INT: + case CommonStructuredDataTypeCategory::FLOAT: + return 32u; + case CommonStructuredDataTypeCategory::BYTE: + return 8u; + case CommonStructuredDataTypeCategory::BOOL: + return 1u; + case CommonStructuredDataTypeCategory::ENUM: + case CommonStructuredDataTypeCategory::SHORT: + return 16u; + case CommonStructuredDataTypeCategory::STRING: + return m_info.string_length * 8; + case CommonStructuredDataTypeCategory::STRUCT: + if (m_info.type_index >= def.m_structs.size()) { + assert(false); + return 0u; } - - case CommonStructuredDataTypeCategory::UNKNOWN: - default: - assert(false); - return 0u; + return def.m_structs[m_info.type_index]->m_size_in_byte * 8u; + case CommonStructuredDataTypeCategory::INDEXED_ARRAY: { + if (m_info.type_index >= def.m_indexed_arrays.size()) { + assert(false); + return 0u; } -} + const auto &indexedArray = def.m_indexed_arrays[m_info.type_index]; + return utils::Align(indexedArray.m_element_size_in_bits * indexedArray.m_element_count, 8u); + } + case CommonStructuredDataTypeCategory::ENUM_ARRAY: { + if (m_info.type_index >= def.m_enumed_arrays.size()) { + assert(false); + return 0u; + } + const auto &enumedArray = def.m_enumed_arrays[m_info.type_index]; + return utils::Align(enumedArray.m_element_size_in_bits * enumedArray.m_element_count, 8u); + } -bool operator<(const CommonStructuredDataType& lhs, const CommonStructuredDataType& rhs) -{ - if (lhs.m_category < rhs.m_category) - return true; - if (rhs.m_category < lhs.m_category) - return false; - return lhs.m_info.type_index < rhs.m_info.type_index; + case CommonStructuredDataTypeCategory::UNKNOWN: + default: + assert(false); + return 0u; + } } -bool operator<=(const CommonStructuredDataType& lhs, const CommonStructuredDataType& rhs) -{ - return !(rhs < lhs); +bool operator<(const CommonStructuredDataType &lhs, const CommonStructuredDataType &rhs) { + if (lhs.m_category < rhs.m_category) + return true; + if (rhs.m_category < lhs.m_category) + return false; + return lhs.m_info.type_index < rhs.m_info.type_index; } -bool operator>(const CommonStructuredDataType& lhs, const CommonStructuredDataType& rhs) -{ - return rhs < lhs; -} +bool operator<=(const CommonStructuredDataType &lhs, const CommonStructuredDataType &rhs) { return !(rhs < lhs); } -bool operator>=(const CommonStructuredDataType& lhs, const CommonStructuredDataType& rhs) -{ - return !(lhs < rhs); -} +bool operator>(const CommonStructuredDataType &lhs, const CommonStructuredDataType &rhs) { return rhs < lhs; } -CommonStructuredDataIndexedArray::CommonStructuredDataIndexedArray() - : CommonStructuredDataIndexedArray({}, 0u) -{ -} +bool operator>=(const CommonStructuredDataType &lhs, const CommonStructuredDataType &rhs) { return !(lhs < rhs); } + +CommonStructuredDataIndexedArray::CommonStructuredDataIndexedArray() : CommonStructuredDataIndexedArray({}, 0u) {} CommonStructuredDataIndexedArray::CommonStructuredDataIndexedArray(const CommonStructuredDataType type, const size_t elementCount) - : CommonStructuredDataIndexedArray(type, elementCount, 0u) -{ -} + : CommonStructuredDataIndexedArray(type, elementCount, 0u) {} CommonStructuredDataIndexedArray::CommonStructuredDataIndexedArray(const CommonStructuredDataType type, const size_t elementCount, const size_t elementSize) - : m_array_type(type), - m_element_count(elementCount), - m_element_size_in_bits(elementSize) -{ -} + : m_array_type(type), m_element_count(elementCount), m_element_size_in_bits(elementSize) {} -bool operator<(const CommonStructuredDataIndexedArray& lhs, const CommonStructuredDataIndexedArray& rhs) -{ - if (lhs.m_array_type < rhs.m_array_type) - return true; - if (rhs.m_array_type < lhs.m_array_type) - return false; - return lhs.m_element_count < rhs.m_element_count; +bool operator<(const CommonStructuredDataIndexedArray &lhs, const CommonStructuredDataIndexedArray &rhs) { + if (lhs.m_array_type < rhs.m_array_type) + return true; + if (rhs.m_array_type < lhs.m_array_type) + return false; + return lhs.m_element_count < rhs.m_element_count; } -bool operator<=(const CommonStructuredDataIndexedArray& lhs, const CommonStructuredDataIndexedArray& rhs) -{ - return !(rhs < lhs); -} +bool operator<=(const CommonStructuredDataIndexedArray &lhs, const CommonStructuredDataIndexedArray &rhs) { return !(rhs < lhs); } -bool operator>(const CommonStructuredDataIndexedArray& lhs, const CommonStructuredDataIndexedArray& rhs) -{ - return rhs < lhs; -} +bool operator>(const CommonStructuredDataIndexedArray &lhs, const CommonStructuredDataIndexedArray &rhs) { return rhs < lhs; } -bool operator>=(const CommonStructuredDataIndexedArray& lhs, const CommonStructuredDataIndexedArray& rhs) -{ - return !(lhs < rhs); -} +bool operator>=(const CommonStructuredDataIndexedArray &lhs, const CommonStructuredDataIndexedArray &rhs) { return !(lhs < rhs); } -CommonStructuredDataEnumedArray::CommonStructuredDataEnumedArray() - : CommonStructuredDataEnumedArray({}, 0u, 0u) -{ -} +CommonStructuredDataEnumedArray::CommonStructuredDataEnumedArray() : CommonStructuredDataEnumedArray({}, 0u, 0u) {} CommonStructuredDataEnumedArray::CommonStructuredDataEnumedArray(const CommonStructuredDataType type, const size_t enumIndex, const size_t elementCount) - : CommonStructuredDataEnumedArray(type, enumIndex, elementCount, 0u) -{ -} + : CommonStructuredDataEnumedArray(type, enumIndex, elementCount, 0u) {} -CommonStructuredDataEnumedArray::CommonStructuredDataEnumedArray(const CommonStructuredDataType type, const size_t enumIndex, const size_t elementCount, const size_t elementSizeInBits) - : m_array_type(type), - m_enum_index(enumIndex), - m_element_count(elementCount), - m_element_size_in_bits(elementSizeInBits) -{ -} +CommonStructuredDataEnumedArray::CommonStructuredDataEnumedArray(const CommonStructuredDataType type, const size_t enumIndex, const size_t elementCount, + const size_t elementSizeInBits) + : m_array_type(type), m_enum_index(enumIndex), m_element_count(elementCount), m_element_size_in_bits(elementSizeInBits) {} -bool operator<(const CommonStructuredDataEnumedArray& lhs, const CommonStructuredDataEnumedArray& rhs) -{ - if (lhs.m_array_type < rhs.m_array_type) - return true; - if (rhs.m_array_type < lhs.m_array_type) - return false; - return lhs.m_enum_index < rhs.m_enum_index; +bool operator<(const CommonStructuredDataEnumedArray &lhs, const CommonStructuredDataEnumedArray &rhs) { + if (lhs.m_array_type < rhs.m_array_type) + return true; + if (rhs.m_array_type < lhs.m_array_type) + return false; + return lhs.m_enum_index < rhs.m_enum_index; } -bool operator<=(const CommonStructuredDataEnumedArray& lhs, const CommonStructuredDataEnumedArray& rhs) -{ - return !(rhs < lhs); -} +bool operator<=(const CommonStructuredDataEnumedArray &lhs, const CommonStructuredDataEnumedArray &rhs) { return !(rhs < lhs); } -bool operator>(const CommonStructuredDataEnumedArray& lhs, const CommonStructuredDataEnumedArray& rhs) -{ - return rhs < lhs; -} +bool operator>(const CommonStructuredDataEnumedArray &lhs, const CommonStructuredDataEnumedArray &rhs) { return rhs < lhs; } -bool operator>=(const CommonStructuredDataEnumedArray& lhs, const CommonStructuredDataEnumedArray& rhs) -{ - return !(lhs < rhs); -} +bool operator>=(const CommonStructuredDataEnumedArray &lhs, const CommonStructuredDataEnumedArray &rhs) { return !(lhs < rhs); } diff --git a/src/ObjCommon/StructuredDataDef/CommonStructuredDataTypes.h b/src/ObjCommon/StructuredDataDef/CommonStructuredDataTypes.h index 9352b0e4b..19a47be60 100644 --- a/src/ObjCommon/StructuredDataDef/CommonStructuredDataTypes.h +++ b/src/ObjCommon/StructuredDataDef/CommonStructuredDataTypes.h @@ -4,75 +4,58 @@ #include "Utils/ClassUtils.h" -enum class CommonStructuredDataTypeCategory -{ - UNKNOWN, - INT, - BYTE, - BOOL, - FLOAT, - SHORT, - STRING, - ENUM, - STRUCT, - INDEXED_ARRAY, - ENUM_ARRAY -}; +enum class CommonStructuredDataTypeCategory { UNKNOWN, INT, BYTE, BOOL, FLOAT, SHORT, STRING, ENUM, STRUCT, INDEXED_ARRAY, ENUM_ARRAY }; -union CommonStructuredDataTypeExtraInfo -{ - size_t string_length; - size_t type_index; +union CommonStructuredDataTypeExtraInfo { + size_t string_length; + size_t type_index; }; class CommonStructuredDataDef; -struct CommonStructuredDataType -{ - CommonStructuredDataTypeCategory m_category; - CommonStructuredDataTypeExtraInfo m_info; +struct CommonStructuredDataType { + CommonStructuredDataTypeCategory m_category; + CommonStructuredDataTypeExtraInfo m_info; - CommonStructuredDataType(); - explicit CommonStructuredDataType(CommonStructuredDataTypeCategory category); - CommonStructuredDataType(CommonStructuredDataTypeCategory category, size_t extraInfo); + CommonStructuredDataType(); + explicit CommonStructuredDataType(CommonStructuredDataTypeCategory category); + CommonStructuredDataType(CommonStructuredDataTypeCategory category, size_t extraInfo); - _NODISCARD size_t GetAlignmentInBits() const; - _NODISCARD size_t GetSizeInBits(const CommonStructuredDataDef& def) const; + _NODISCARD size_t GetAlignmentInBits() const; + _NODISCARD size_t GetSizeInBits(const CommonStructuredDataDef &def) const; - friend bool operator<(const CommonStructuredDataType& lhs, const CommonStructuredDataType& rhs); - friend bool operator<=(const CommonStructuredDataType& lhs, const CommonStructuredDataType& rhs); - friend bool operator>(const CommonStructuredDataType& lhs, const CommonStructuredDataType& rhs); - friend bool operator>=(const CommonStructuredDataType& lhs, const CommonStructuredDataType& rhs); + friend bool operator<(const CommonStructuredDataType &lhs, const CommonStructuredDataType &rhs); + friend bool operator<=(const CommonStructuredDataType &lhs, const CommonStructuredDataType &rhs); + friend bool operator>(const CommonStructuredDataType &lhs, const CommonStructuredDataType &rhs); + friend bool operator>=(const CommonStructuredDataType &lhs, const CommonStructuredDataType &rhs); }; -struct CommonStructuredDataIndexedArray -{ - CommonStructuredDataType m_array_type; - size_t m_element_count; - size_t m_element_size_in_bits; +struct CommonStructuredDataIndexedArray { + CommonStructuredDataType m_array_type; + size_t m_element_count; + size_t m_element_size_in_bits; - CommonStructuredDataIndexedArray(); - CommonStructuredDataIndexedArray(CommonStructuredDataType type, size_t elementCount); - CommonStructuredDataIndexedArray(CommonStructuredDataType type, size_t elementCount, size_t elementSize); + CommonStructuredDataIndexedArray(); + CommonStructuredDataIndexedArray(CommonStructuredDataType type, size_t elementCount); + CommonStructuredDataIndexedArray(CommonStructuredDataType type, size_t elementCount, size_t elementSize); - friend bool operator<(const CommonStructuredDataIndexedArray& lhs, const CommonStructuredDataIndexedArray& rhs); - friend bool operator<=(const CommonStructuredDataIndexedArray& lhs, const CommonStructuredDataIndexedArray& rhs); - friend bool operator>(const CommonStructuredDataIndexedArray& lhs, const CommonStructuredDataIndexedArray& rhs); - friend bool operator>=(const CommonStructuredDataIndexedArray& lhs, const CommonStructuredDataIndexedArray& rhs); + friend bool operator<(const CommonStructuredDataIndexedArray &lhs, const CommonStructuredDataIndexedArray &rhs); + friend bool operator<=(const CommonStructuredDataIndexedArray &lhs, const CommonStructuredDataIndexedArray &rhs); + friend bool operator>(const CommonStructuredDataIndexedArray &lhs, const CommonStructuredDataIndexedArray &rhs); + friend bool operator>=(const CommonStructuredDataIndexedArray &lhs, const CommonStructuredDataIndexedArray &rhs); }; -struct CommonStructuredDataEnumedArray -{ - CommonStructuredDataType m_array_type; - size_t m_enum_index; - size_t m_element_count; - size_t m_element_size_in_bits; +struct CommonStructuredDataEnumedArray { + CommonStructuredDataType m_array_type; + size_t m_enum_index; + size_t m_element_count; + size_t m_element_size_in_bits; - CommonStructuredDataEnumedArray(); - CommonStructuredDataEnumedArray(CommonStructuredDataType type, size_t enumIndex, size_t elementCount); - CommonStructuredDataEnumedArray(CommonStructuredDataType type, size_t enumIndex, size_t elementCount, size_t elementSizeInBits); + CommonStructuredDataEnumedArray(); + CommonStructuredDataEnumedArray(CommonStructuredDataType type, size_t enumIndex, size_t elementCount); + CommonStructuredDataEnumedArray(CommonStructuredDataType type, size_t enumIndex, size_t elementCount, size_t elementSizeInBits); - friend bool operator<(const CommonStructuredDataEnumedArray& lhs, const CommonStructuredDataEnumedArray& rhs); - friend bool operator<=(const CommonStructuredDataEnumedArray& lhs, const CommonStructuredDataEnumedArray& rhs); - friend bool operator>(const CommonStructuredDataEnumedArray& lhs, const CommonStructuredDataEnumedArray& rhs); - friend bool operator>=(const CommonStructuredDataEnumedArray& lhs, const CommonStructuredDataEnumedArray& rhs); + friend bool operator<(const CommonStructuredDataEnumedArray &lhs, const CommonStructuredDataEnumedArray &rhs); + friend bool operator<=(const CommonStructuredDataEnumedArray &lhs, const CommonStructuredDataEnumedArray &rhs); + friend bool operator>(const CommonStructuredDataEnumedArray &lhs, const CommonStructuredDataEnumedArray &rhs); + friend bool operator>=(const CommonStructuredDataEnumedArray &lhs, const CommonStructuredDataEnumedArray &rhs); }; diff --git a/src/ObjCommon/Utils/DistinctMapper.h b/src/ObjCommon/Utils/DistinctMapper.h index c34b1370e..2e468aa97 100644 --- a/src/ObjCommon/Utils/DistinctMapper.h +++ b/src/ObjCommon/Utils/DistinctMapper.h @@ -5,86 +5,63 @@ #include "Utils/ClassUtils.h" -template -class DistinctMapper -{ +template class DistinctMapper { public: - DistinctMapper() - : m_input_entry_index(0), - m_distinct_entry_index(0) - { + DistinctMapper() : m_input_entry_index(0), m_distinct_entry_index(0) {} + + explicit DistinctMapper(const size_t totalInputCount) : m_input_entry_index(0), m_distinct_entry_index(0) { + m_distinct_position_by_input_position.reserve(totalInputCount); + } + + bool Add(T inputValue) { + const auto mapEntry = m_distinct_position_by_value_map.find(inputValue); + if (mapEntry == m_distinct_position_by_value_map.end()) { + m_distinct_position_by_input_position.push_back(m_distinct_entry_index); + m_input_position_by_distinct_position.push_back(m_input_entry_index); + m_distinct_values.push_back(inputValue); + m_distinct_position_by_value_map.emplace(std::make_pair(std::move(inputValue), m_distinct_entry_index)); + m_distinct_entry_index++; + m_input_entry_index++; + return true; } - explicit DistinctMapper(const size_t totalInputCount) - : m_input_entry_index(0), - m_distinct_entry_index(0) - { - m_distinct_position_by_input_position.reserve(totalInputCount); - } + m_distinct_position_by_input_position.push_back(mapEntry->second); + m_input_entry_index++; + return false; + } - bool Add(T inputValue) - { - const auto mapEntry = m_distinct_position_by_value_map.find(inputValue); - if (mapEntry == m_distinct_position_by_value_map.end()) - { - m_distinct_position_by_input_position.push_back(m_distinct_entry_index); - m_input_position_by_distinct_position.push_back(m_input_entry_index); - m_distinct_values.push_back(inputValue); - m_distinct_position_by_value_map.emplace(std::make_pair(std::move(inputValue), m_distinct_entry_index)); - m_distinct_entry_index++; - m_input_entry_index++; - return true; - } - - m_distinct_position_by_input_position.push_back(mapEntry->second); - m_input_entry_index++; - return false; - } + _NODISCARD size_t GetDistinctPositionByInputPosition(const size_t inputPosition) const { + if (inputPosition >= m_distinct_position_by_input_position.size()) + return 0; - _NODISCARD size_t GetDistinctPositionByInputPosition(const size_t inputPosition) const - { - if (inputPosition >= m_distinct_position_by_input_position.size()) - return 0; + return m_distinct_position_by_input_position[inputPosition]; + } - return m_distinct_position_by_input_position[inputPosition]; - } + _NODISCARD T GetDistinctValueByInputPosition(const size_t inputPosition) const { + if (inputPosition >= m_distinct_values.size()) + return T{}; - _NODISCARD T GetDistinctValueByInputPosition(const size_t inputPosition) const - { - if (inputPosition >= m_distinct_values.size()) - return T{}; + return m_distinct_values[inputPosition]; + } - return m_distinct_values[inputPosition]; - } + _NODISCARD size_t GetInputPositionByDistinctPosition(const size_t distinctPosition) const { + if (distinctPosition >= m_input_position_by_distinct_position.size()) + return 0; - _NODISCARD size_t GetInputPositionByDistinctPosition(const size_t distinctPosition) const - { - if (distinctPosition >= m_input_position_by_distinct_position.size()) - return 0; + return m_input_position_by_distinct_position[distinctPosition]; + } - return m_input_position_by_distinct_position[distinctPosition]; - } + _NODISCARD const std::vector &GetDistinctValues() const { return m_distinct_values; } - _NODISCARD const std::vector& GetDistinctValues() const - { - return m_distinct_values; - } - - _NODISCARD size_t GetInputValueCount() const - { - return m_input_entry_index; - } + _NODISCARD size_t GetInputValueCount() const { return m_input_entry_index; } - _NODISCARD size_t GetDistinctValueCount() const - { - return m_distinct_entry_index; - } + _NODISCARD size_t GetDistinctValueCount() const { return m_distinct_entry_index; } private: - size_t m_input_entry_index; - size_t m_distinct_entry_index; - std::map m_distinct_position_by_value_map; - std::vector m_distinct_position_by_input_position; - std::vector m_input_position_by_distinct_position; - std::vector m_distinct_values; + size_t m_input_entry_index; + size_t m_distinct_entry_index; + std::map m_distinct_position_by_value_map; + std::vector m_distinct_position_by_input_position; + std::vector m_input_position_by_distinct_position; + std::vector m_distinct_values; }; diff --git a/src/ObjCommon/Utils/FileToZlibWrapper.cpp b/src/ObjCommon/Utils/FileToZlibWrapper.cpp index 60bf8525a..2dfdd8a51 100644 --- a/src/ObjCommon/Utils/FileToZlibWrapper.cpp +++ b/src/ObjCommon/Utils/FileToZlibWrapper.cpp @@ -3,168 +3,128 @@ #include #include -voidpf Wrapper_Zlib_FileOpen(voidpf opaque, const char*, int) -{ - return opaque; -} +voidpf Wrapper_Zlib_FileOpen(voidpf opaque, const char *, int) { return opaque; } -template -uLong Wrapper_Zlib_FileRead(voidpf opaque, voidpf stream, void* buf, const uLong size) -{ - auto* file = static_cast(stream); +template uLong Wrapper_Zlib_FileRead(voidpf opaque, voidpf stream, void *buf, const uLong size) { + auto *file = static_cast(stream); - file->read(static_cast(buf), size); + file->read(static_cast(buf), size); - return static_cast(file->gcount()); + return static_cast(file->gcount()); } -uLong Wrapper_Zlib_NoFileRead(voidpf opaque, voidpf stream, void* buf, const uLong size) -{ - return 0; -} +uLong Wrapper_Zlib_NoFileRead(voidpf opaque, voidpf stream, void *buf, const uLong size) { return 0; } -template -uLong Wrapper_Zlib_FileWrite(voidpf opaque, voidpf stream, const void* buf, const uLong size) -{ - auto* file = static_cast(stream); - file->write(static_cast(buf), size); - return size; +template uLong Wrapper_Zlib_FileWrite(voidpf opaque, voidpf stream, const void *buf, const uLong size) { + auto *file = static_cast(stream); + file->write(static_cast(buf), size); + return size; } -uLong Wrapper_Zlib_NoFileWrite(voidpf opaque, voidpf stream, const void* buf, const uLong size) -{ - return 0; -} +uLong Wrapper_Zlib_NoFileWrite(voidpf opaque, voidpf stream, const void *buf, const uLong size) { return 0; } + +template long Wrapper_Zlib_FileTellRead(voidpf opaque, voidpf stream) { + auto *file = static_cast(stream); -template -long Wrapper_Zlib_FileTellRead(voidpf opaque, voidpf stream) -{ - auto* file = static_cast(stream); - - return static_cast(file->tellg()); + return static_cast(file->tellg()); } -template -long Wrapper_Zlib_FileTellWrite(voidpf opaque, voidpf stream) -{ - auto* file = static_cast(stream); - - return static_cast(file->tellp()); +template long Wrapper_Zlib_FileTellWrite(voidpf opaque, voidpf stream) { + auto *file = static_cast(stream); + + return static_cast(file->tellp()); } -template -long Wrapper_Zlib_FileSeekRead(voidpf opaque, voidpf stream, const uLong offset, const int origin) -{ - auto* file = static_cast(stream); +template long Wrapper_Zlib_FileSeekRead(voidpf opaque, voidpf stream, const uLong offset, const int origin) { + auto *file = static_cast(stream); - switch (origin) - { - case ZLIB_FILEFUNC_SEEK_CUR: - file->seekg(offset, std::ios_base::cur); - break; + switch (origin) { + case ZLIB_FILEFUNC_SEEK_CUR: + file->seekg(offset, std::ios_base::cur); + break; - case ZLIB_FILEFUNC_SEEK_END: - file->seekg(offset, std::ios_base::end); - break; + case ZLIB_FILEFUNC_SEEK_END: + file->seekg(offset, std::ios_base::end); + break; - case ZLIB_FILEFUNC_SEEK_SET: - file->seekg(offset, std::ios_base::beg); - break; + case ZLIB_FILEFUNC_SEEK_SET: + file->seekg(offset, std::ios_base::beg); + break; - default: - return -1; - } + default: + return -1; + } - return 0; + return 0; } -template -long Wrapper_Zlib_FileSeekWrite(voidpf opaque, voidpf stream, const uLong offset, const int origin) -{ - auto* file = static_cast(stream); - - switch (origin) - { - case ZLIB_FILEFUNC_SEEK_CUR: - file->seekp(offset, std::ios_base::cur); - break; +template long Wrapper_Zlib_FileSeekWrite(voidpf opaque, voidpf stream, const uLong offset, const int origin) { + auto *file = static_cast(stream); - case ZLIB_FILEFUNC_SEEK_END: - file->seekp(offset, std::ios_base::end); - break; + switch (origin) { + case ZLIB_FILEFUNC_SEEK_CUR: + file->seekp(offset, std::ios_base::cur); + break; - case ZLIB_FILEFUNC_SEEK_SET: - file->seekp(offset, std::ios_base::beg); - break; + case ZLIB_FILEFUNC_SEEK_END: + file->seekp(offset, std::ios_base::end); + break; - default: - return -1; - } + case ZLIB_FILEFUNC_SEEK_SET: + file->seekp(offset, std::ios_base::beg); + break; - return 0; -} + default: + return -1; + } -template -int Wrapper_Zlib_FileClose(voidpf opaque, voidpf stream) -{ - return 0; - // auto* file = static_cast(stream); - // - // if (file->is_open()) - // { - // file->close(); - // return 0; - // } - // - // return -1; + return 0; } -int Wrapper_Zlib_FileError(voidpf opaque, voidpf stream) -{ - return 0; +template int Wrapper_Zlib_FileClose(voidpf opaque, voidpf stream) { + return 0; + // auto* file = static_cast(stream); + // + // if (file->is_open()) + // { + // file->close(); + // return 0; + // } + // + // return -1; } -zlib_filefunc_def FileToZlibWrapper::CreateFunctions32ForFile(std::iostream* stream) -{ - return zlib_filefunc_def_s - { - Wrapper_Zlib_FileOpen, - Wrapper_Zlib_FileRead, - Wrapper_Zlib_FileWrite, - Wrapper_Zlib_FileTellRead, - Wrapper_Zlib_FileSeekRead, - Wrapper_Zlib_FileClose, - Wrapper_Zlib_FileError, - stream - }; +int Wrapper_Zlib_FileError(voidpf opaque, voidpf stream) { return 0; } + +zlib_filefunc_def FileToZlibWrapper::CreateFunctions32ForFile(std::iostream *stream) { + return zlib_filefunc_def_s{Wrapper_Zlib_FileOpen, + Wrapper_Zlib_FileRead, + Wrapper_Zlib_FileWrite, + Wrapper_Zlib_FileTellRead, + Wrapper_Zlib_FileSeekRead, + Wrapper_Zlib_FileClose, + Wrapper_Zlib_FileError, + stream}; } -zlib_filefunc_def FileToZlibWrapper::CreateFunctions32ForFile(std::istream* stream) -{ - return zlib_filefunc_def_s - { - Wrapper_Zlib_FileOpen, - Wrapper_Zlib_FileRead, - Wrapper_Zlib_NoFileWrite, - Wrapper_Zlib_FileTellRead, - Wrapper_Zlib_FileSeekRead, - Wrapper_Zlib_FileClose, - Wrapper_Zlib_FileError, - stream - }; +zlib_filefunc_def FileToZlibWrapper::CreateFunctions32ForFile(std::istream *stream) { + return zlib_filefunc_def_s{Wrapper_Zlib_FileOpen, + Wrapper_Zlib_FileRead, + Wrapper_Zlib_NoFileWrite, + Wrapper_Zlib_FileTellRead, + Wrapper_Zlib_FileSeekRead, + Wrapper_Zlib_FileClose, + Wrapper_Zlib_FileError, + stream}; } -zlib_filefunc_def FileToZlibWrapper::CreateFunctions32ForFile(std::ostream* stream) -{ - return zlib_filefunc_def_s - { - Wrapper_Zlib_FileOpen, - Wrapper_Zlib_NoFileRead, - Wrapper_Zlib_FileWrite, - Wrapper_Zlib_FileTellWrite, - Wrapper_Zlib_FileSeekWrite, - Wrapper_Zlib_FileClose, - Wrapper_Zlib_FileError, - stream - }; +zlib_filefunc_def FileToZlibWrapper::CreateFunctions32ForFile(std::ostream *stream) { + return zlib_filefunc_def_s{Wrapper_Zlib_FileOpen, + Wrapper_Zlib_NoFileRead, + Wrapper_Zlib_FileWrite, + Wrapper_Zlib_FileTellWrite, + Wrapper_Zlib_FileSeekWrite, + Wrapper_Zlib_FileClose, + Wrapper_Zlib_FileError, + stream}; } diff --git a/src/ObjCommon/Utils/FileToZlibWrapper.h b/src/ObjCommon/Utils/FileToZlibWrapper.h index b5fc4251d..2bd0c1875 100644 --- a/src/ObjCommon/Utils/FileToZlibWrapper.h +++ b/src/ObjCommon/Utils/FileToZlibWrapper.h @@ -7,10 +7,9 @@ #include "ObjStream.h" -class FileToZlibWrapper -{ +class FileToZlibWrapper { public: - static zlib_filefunc_def CreateFunctions32ForFile(std::iostream* stream); - static zlib_filefunc_def CreateFunctions32ForFile(std::istream* stream); - static zlib_filefunc_def CreateFunctions32ForFile(std::ostream* stream); + static zlib_filefunc_def CreateFunctions32ForFile(std::iostream *stream); + static zlib_filefunc_def CreateFunctions32ForFile(std::istream *stream); + static zlib_filefunc_def CreateFunctions32ForFile(std::ostream *stream); }; diff --git a/src/ObjCommon/Utils/ObjStream.h b/src/ObjCommon/Utils/ObjStream.h index acb672aba..50d84d791 100644 --- a/src/ObjCommon/Utils/ObjStream.h +++ b/src/ObjCommon/Utils/ObjStream.h @@ -3,217 +3,151 @@ #pragma once #include -#include #include #include +#include #include "Utils/ClassUtils.h" -template -class basic_objbuf : public std::basic_streambuf -{ +template class basic_objbuf : public std::basic_streambuf { public: - _NODISCARD virtual bool is_open() const = 0; - virtual bool close() = 0; + _NODISCARD virtual bool is_open() const = 0; + virtual bool close() = 0; }; -template -class basic_objstream : public std::basic_iostream -{ +template class basic_objstream : public std::basic_iostream { public: - using mybase = std::basic_iostream; - using myob = basic_objbuf; - using myios = std::basic_ios; - - explicit basic_objstream(std::unique_ptr objbuf) - : std::basic_iostream(objbuf.get()), - m_ob(std::move(objbuf)) - { - assert(m_ob); - } + using mybase = std::basic_iostream; + using myob = basic_objbuf; + using myios = std::basic_ios; - explicit basic_objstream(basic_objstream&& right) noexcept - : std::basic_iostream(right), - m_ob(std::move(right.m_ob)) - { - assert(m_ob != nullptr); - } + explicit basic_objstream(std::unique_ptr objbuf) : std::basic_iostream(objbuf.get()), m_ob(std::move(objbuf)) { assert(m_ob); } - basic_objstream(const basic_objstream& other) = delete; - basic_objstream& operator=(const basic_objstream& other) = delete; + explicit basic_objstream(basic_objstream &&right) noexcept : std::basic_iostream(right), m_ob(std::move(right.m_ob)) { + assert(m_ob != nullptr); + } - ~basic_objstream() override - { - if(m_ob) - m_ob->close(); - } + basic_objstream(const basic_objstream &other) = delete; + basic_objstream &operator=(const basic_objstream &other) = delete; - void swap(basic_objstream& right) noexcept - { - if (this != std::addressof(right)) - { - mybase::swap(right); - m_ob = std::move(right.m_ob); - } - } + ~basic_objstream() override { + if (m_ob) + m_ob->close(); + } - basic_objstream& operator=(basic_objstream&& other) noexcept - { - swap(other); - return *this; + void swap(basic_objstream &right) noexcept { + if (this != std::addressof(right)) { + mybase::swap(right); + m_ob = std::move(right.m_ob); } + } - // ReSharper disable once CppHidingFunction - _NODISCARD myob* rdbuf() const - { - return const_cast(m_ob.get()); - } + basic_objstream &operator=(basic_objstream &&other) noexcept { + swap(other); + return *this; + } - _NODISCARD bool is_open() const - { - return m_ob->is_open(); - } + // ReSharper disable once CppHidingFunction + _NODISCARD myob *rdbuf() const { return const_cast(m_ob.get()); } + + _NODISCARD bool is_open() const { return m_ob->is_open(); } - void close() - { - if (!m_ob->close()) - { - myios::setstate(std::ios_base::failbit); - } + void close() { + if (!m_ob->close()) { + myios::setstate(std::ios_base::failbit); } + } protected: - std::unique_ptr m_ob; + std::unique_ptr m_ob; }; -template -class basic_iobjstream : public std::basic_istream -{ +template class basic_iobjstream : public std::basic_istream { public: - using mybase = std::basic_istream; - using myob = basic_objbuf; - using myios = std::basic_ios; - - explicit basic_iobjstream(std::unique_ptr objbuf) - : std::basic_istream(objbuf.get()), - m_ob(std::move(objbuf)) - { - assert(m_ob); - } + using mybase = std::basic_istream; + using myob = basic_objbuf; + using myios = std::basic_ios; - explicit basic_iobjstream(basic_iobjstream&& right) noexcept - : std::basic_istream(right), - m_ob(std::move(right.m_ob)) - { - assert(m_ob != nullptr); - } + explicit basic_iobjstream(std::unique_ptr objbuf) : std::basic_istream(objbuf.get()), m_ob(std::move(objbuf)) { assert(m_ob); } - basic_iobjstream(const basic_iobjstream& other) = delete; - basic_iobjstream& operator=(const basic_iobjstream& other) = delete; + explicit basic_iobjstream(basic_iobjstream &&right) noexcept : std::basic_istream(right), m_ob(std::move(right.m_ob)) { + assert(m_ob != nullptr); + } - ~basic_iobjstream() override = default; + basic_iobjstream(const basic_iobjstream &other) = delete; + basic_iobjstream &operator=(const basic_iobjstream &other) = delete; - void swap(basic_iobjstream& right) noexcept - { - if (this != std::addressof(right)) - { - mybase::swap(right); - m_ob = std::move(right.m_ob); - } - } + ~basic_iobjstream() override = default; - basic_iobjstream& operator=(basic_iobjstream&& other) noexcept - { - swap(other); - return *this; + void swap(basic_iobjstream &right) noexcept { + if (this != std::addressof(right)) { + mybase::swap(right); + m_ob = std::move(right.m_ob); } + } - // ReSharper disable once CppHidingFunction - _NODISCARD myob* rdbuf() const - { - return const_cast(m_ob.get()); - } + basic_iobjstream &operator=(basic_iobjstream &&other) noexcept { + swap(other); + return *this; + } - _NODISCARD bool is_open() const - { - return m_ob->is_open(); - } + // ReSharper disable once CppHidingFunction + _NODISCARD myob *rdbuf() const { return const_cast(m_ob.get()); } - void close() - { - if (!m_ob->close()) - { - myios::setstate(std::ios_base::failbit); - } + _NODISCARD bool is_open() const { return m_ob->is_open(); } + + void close() { + if (!m_ob->close()) { + myios::setstate(std::ios_base::failbit); } + } protected: - std::unique_ptr m_ob; + std::unique_ptr m_ob; }; -template -class basic_oobjstream : public std::basic_ostream -{ +template class basic_oobjstream : public std::basic_ostream { public: - using mybase = std::basic_ostream; - using myob = basic_objbuf; - using myios = std::basic_ios; - - explicit basic_oobjstream(std::unique_ptr objbuf) - : std::basic_ostream(objbuf.get()), - m_ob(std::move(objbuf)) - { - assert(m_ob); - } + using mybase = std::basic_ostream; + using myob = basic_objbuf; + using myios = std::basic_ios; - explicit basic_oobjstream(basic_oobjstream&& right) noexcept - : std::basic_ostream(right), - m_ob(std::move(right.m_ob)) - { - assert(m_ob != nullptr); - } + explicit basic_oobjstream(std::unique_ptr objbuf) : std::basic_ostream(objbuf.get()), m_ob(std::move(objbuf)) { assert(m_ob); } - ~basic_oobjstream() override = default; + explicit basic_oobjstream(basic_oobjstream &&right) noexcept : std::basic_ostream(right), m_ob(std::move(right.m_ob)) { + assert(m_ob != nullptr); + } - basic_oobjstream(const basic_oobjstream& other) = delete; - basic_oobjstream& operator=(const basic_oobjstream& other) = delete; + ~basic_oobjstream() override = default; - void swap(basic_oobjstream& right) noexcept - { - if (this != std::addressof(right)) - { - mybase::swap(right); - m_ob = std::move(right.m_ob); - } - } + basic_oobjstream(const basic_oobjstream &other) = delete; + basic_oobjstream &operator=(const basic_oobjstream &other) = delete; - basic_oobjstream& operator=(basic_oobjstream&& other) noexcept - { - swap(other); - return *this; - } - - // ReSharper disable once CppHidingFunction - _NODISCARD myob* rdbuf() const - { - return const_cast(m_ob.get()); + void swap(basic_oobjstream &right) noexcept { + if (this != std::addressof(right)) { + mybase::swap(right); + m_ob = std::move(right.m_ob); } + } - _NODISCARD bool is_open() const - { - return m_ob->is_open(); - } + basic_oobjstream &operator=(basic_oobjstream &&other) noexcept { + swap(other); + return *this; + } + + // ReSharper disable once CppHidingFunction + _NODISCARD myob *rdbuf() const { return const_cast(m_ob.get()); } + + _NODISCARD bool is_open() const { return m_ob->is_open(); } - void close() - { - if (!m_ob->close()) - { - myios::setstate(std::ios_base::failbit); - } + void close() { + if (!m_ob->close()) { + myios::setstate(std::ios_base::failbit); } + } protected: - std::unique_ptr m_ob; + std::unique_ptr m_ob; }; using objbuf = basic_objbuf>; diff --git a/src/ObjLoading/AssetLoading/AbstractGdtEntryReader.cpp b/src/ObjLoading/AssetLoading/AbstractGdtEntryReader.cpp index 01eba76af..fae6283c6 100644 --- a/src/ObjLoading/AssetLoading/AbstractGdtEntryReader.cpp +++ b/src/ObjLoading/AssetLoading/AbstractGdtEntryReader.cpp @@ -2,143 +2,121 @@ #include -GdtReadingException::GdtReadingException(std::string message) - : m_message(std::move(message)) -{ -} +GdtReadingException::GdtReadingException(std::string message) : m_message(std::move(message)) {} -const char* GdtReadingException::what() const noexcept -{ - return m_message.c_str(); -} +const char *GdtReadingException::what() const noexcept { return m_message.c_str(); } -AbstractGdtEntryReader::AbstractGdtEntryReader(const GdtEntry& entry) - : m_entry(entry) -{ -} +AbstractGdtEntryReader::AbstractGdtEntryReader(const GdtEntry &entry) : m_entry(entry) {} -std::string AbstractGdtEntryReader::ReadStringProperty(const std::string& propertyName, std::string defaultValue) const -{ - const auto foundProperty = m_entry.m_properties.find(propertyName); - if (foundProperty == m_entry.m_properties.end()) - return defaultValue; +std::string AbstractGdtEntryReader::ReadStringProperty(const std::string &propertyName, std::string defaultValue) const { + const auto foundProperty = m_entry.m_properties.find(propertyName); + if (foundProperty == m_entry.m_properties.end()) + return defaultValue; - return foundProperty->second; + return foundProperty->second; } -bool AbstractGdtEntryReader::ReadBoolProperty(const std::string& propertyName, const bool defaultValue) const -{ - const auto foundProperty = m_entry.m_properties.find(propertyName); - if (foundProperty == m_entry.m_properties.end()) - return defaultValue; - - char* endPtr = nullptr; - const auto result = std::strtol(foundProperty->second.c_str(), &endPtr, 10); - if (endPtr != &foundProperty->second[foundProperty->second.size()]) - { - std::ostringstream ss; - ss << "\"" << foundProperty->second << "\" is not a valid boolean value"; - throw GdtReadingException(ss.str()); - } - - return result != 0; +bool AbstractGdtEntryReader::ReadBoolProperty(const std::string &propertyName, const bool defaultValue) const { + const auto foundProperty = m_entry.m_properties.find(propertyName); + if (foundProperty == m_entry.m_properties.end()) + return defaultValue; + + char *endPtr = nullptr; + const auto result = std::strtol(foundProperty->second.c_str(), &endPtr, 10); + if (endPtr != &foundProperty->second[foundProperty->second.size()]) { + std::ostringstream ss; + ss << "\"" << foundProperty->second << "\" is not a valid boolean value"; + throw GdtReadingException(ss.str()); + } + + return result != 0; } -int AbstractGdtEntryReader::ReadIntegerProperty(const std::string& propertyName, const int defaultValue) const -{ - const auto foundProperty = m_entry.m_properties.find(propertyName); - if (foundProperty == m_entry.m_properties.end()) - return defaultValue; - - char* endPtr = nullptr; - const auto result = std::strtol(foundProperty->second.c_str(), &endPtr, 10); - if (endPtr != &foundProperty->second[foundProperty->second.size()]) - { - std::ostringstream ss; - ss << "\"" << foundProperty->second << "\" is not a valid integer value"; - throw GdtReadingException(ss.str()); - } - - return result; +int AbstractGdtEntryReader::ReadIntegerProperty(const std::string &propertyName, const int defaultValue) const { + const auto foundProperty = m_entry.m_properties.find(propertyName); + if (foundProperty == m_entry.m_properties.end()) + return defaultValue; + + char *endPtr = nullptr; + const auto result = std::strtol(foundProperty->second.c_str(), &endPtr, 10); + if (endPtr != &foundProperty->second[foundProperty->second.size()]) { + std::ostringstream ss; + ss << "\"" << foundProperty->second << "\" is not a valid integer value"; + throw GdtReadingException(ss.str()); + } + + return result; } -float AbstractGdtEntryReader::ReadFloatProperty(const std::string& propertyName, const float defaultValue) const -{ - const auto foundProperty = m_entry.m_properties.find(propertyName); - if (foundProperty == m_entry.m_properties.end()) - return defaultValue; - - char* endPtr = nullptr; - const auto result = std::strtof(foundProperty->second.c_str(), &endPtr); - if (endPtr != &foundProperty->second[foundProperty->second.size()]) - { - std::ostringstream ss; - ss << "\"" << foundProperty->second << "\" is not a valid float value"; - throw GdtReadingException(ss.str()); - } - - return result; +float AbstractGdtEntryReader::ReadFloatProperty(const std::string &propertyName, const float defaultValue) const { + const auto foundProperty = m_entry.m_properties.find(propertyName); + if (foundProperty == m_entry.m_properties.end()) + return defaultValue; + + char *endPtr = nullptr; + const auto result = std::strtof(foundProperty->second.c_str(), &endPtr); + if (endPtr != &foundProperty->second[foundProperty->second.size()]) { + std::ostringstream ss; + ss << "\"" << foundProperty->second << "\" is not a valid float value"; + throw GdtReadingException(ss.str()); + } + + return result; } -Vector2f AbstractGdtEntryReader::ReadVec2Property(const std::string& propertyName, const Vector2f defaultValue) const -{ - const auto foundProperty = m_entry.m_properties.find(propertyName); - if (foundProperty == m_entry.m_properties.end()) - return defaultValue; +Vector2f AbstractGdtEntryReader::ReadVec2Property(const std::string &propertyName, const Vector2f defaultValue) const { + const auto foundProperty = m_entry.m_properties.find(propertyName); + if (foundProperty == m_entry.m_properties.end()) + return defaultValue; - std::istringstream iss(foundProperty->second); - Vector2f result; + std::istringstream iss(foundProperty->second); + Vector2f result; - iss >> result(0) >> result(1); + iss >> result(0) >> result(1); - if (iss.fail()) - { - std::ostringstream oss; - oss << "\"" << foundProperty->second << "\" is not a valid vec2 value"; - throw GdtReadingException(oss.str()); - } + if (iss.fail()) { + std::ostringstream oss; + oss << "\"" << foundProperty->second << "\" is not a valid vec2 value"; + throw GdtReadingException(oss.str()); + } - return result; + return result; } -Vector3f AbstractGdtEntryReader::ReadVec3Property(const std::string& propertyName, const Vector3f defaultValue) const -{ - const auto foundProperty = m_entry.m_properties.find(propertyName); - if (foundProperty == m_entry.m_properties.end()) - return defaultValue; +Vector3f AbstractGdtEntryReader::ReadVec3Property(const std::string &propertyName, const Vector3f defaultValue) const { + const auto foundProperty = m_entry.m_properties.find(propertyName); + if (foundProperty == m_entry.m_properties.end()) + return defaultValue; - std::istringstream iss(foundProperty->second); - Vector3f result; + std::istringstream iss(foundProperty->second); + Vector3f result; - iss >> result(0) >> result(1) >> result(2); + iss >> result(0) >> result(1) >> result(2); - if (iss.fail()) - { - std::ostringstream oss; - oss << "\"" << foundProperty->second << "\" is not a valid vec3 value"; - throw GdtReadingException(oss.str()); - } + if (iss.fail()) { + std::ostringstream oss; + oss << "\"" << foundProperty->second << "\" is not a valid vec3 value"; + throw GdtReadingException(oss.str()); + } - return result; + return result; } -Vector4f AbstractGdtEntryReader::ReadVec4Property(const std::string& propertyName, const Vector4f defaultValue) const -{ - const auto foundProperty = m_entry.m_properties.find(propertyName); - if (foundProperty == m_entry.m_properties.end()) - return defaultValue; +Vector4f AbstractGdtEntryReader::ReadVec4Property(const std::string &propertyName, const Vector4f defaultValue) const { + const auto foundProperty = m_entry.m_properties.find(propertyName); + if (foundProperty == m_entry.m_properties.end()) + return defaultValue; - std::istringstream iss(foundProperty->second); - Vector4f result; + std::istringstream iss(foundProperty->second); + Vector4f result; - iss >> result(0) >> result(1) >> result(2) >> result(3); + iss >> result(0) >> result(1) >> result(2) >> result(3); - if (iss.fail()) - { - std::ostringstream oss; - oss << "\"" << foundProperty->second << "\" is not a valid vec4 value"; - throw GdtReadingException(oss.str()); - } + if (iss.fail()) { + std::ostringstream oss; + oss << "\"" << foundProperty->second << "\" is not a valid vec4 value"; + throw GdtReadingException(oss.str()); + } - return result; + return result; } diff --git a/src/ObjLoading/AssetLoading/AbstractGdtEntryReader.h b/src/ObjLoading/AssetLoading/AbstractGdtEntryReader.h index df45dcf70..3101371d7 100644 --- a/src/ObjLoading/AssetLoading/AbstractGdtEntryReader.h +++ b/src/ObjLoading/AssetLoading/AbstractGdtEntryReader.h @@ -3,31 +3,29 @@ #include #include "Math/Vector.h" -#include "Utils/ClassUtils.h" #include "Obj/Gdt/GdtEntry.h" +#include "Utils/ClassUtils.h" -class GdtReadingException : public std::exception -{ +class GdtReadingException : public std::exception { public: - explicit GdtReadingException(std::string message); - _NODISCARD const char* what() const noexcept override; + explicit GdtReadingException(std::string message); + _NODISCARD const char *what() const noexcept override; private: - std::string m_message; + std::string m_message; }; -class AbstractGdtEntryReader -{ +class AbstractGdtEntryReader { protected: - explicit AbstractGdtEntryReader(const GdtEntry& entry); + explicit AbstractGdtEntryReader(const GdtEntry &entry); - _NODISCARD std::string ReadStringProperty(const std::string& propertyName, std::string defaultValue = std::string()) const; - _NODISCARD bool ReadBoolProperty(const std::string& propertyName, bool defaultValue = false) const; - _NODISCARD int ReadIntegerProperty(const std::string& propertyName, int defaultValue = 0) const; - _NODISCARD float ReadFloatProperty(const std::string& propertyName, float defaultValue = 0.0f) const; - _NODISCARD Vector2f ReadVec2Property(const std::string& propertyName, Vector2f defaultValue = {}) const; - _NODISCARD Vector3f ReadVec3Property(const std::string& propertyName, Vector3f defaultValue = {}) const; - _NODISCARD Vector4f ReadVec4Property(const std::string& propertyName, Vector4f defaultValue = {}) const; + _NODISCARD std::string ReadStringProperty(const std::string &propertyName, std::string defaultValue = std::string()) const; + _NODISCARD bool ReadBoolProperty(const std::string &propertyName, bool defaultValue = false) const; + _NODISCARD int ReadIntegerProperty(const std::string &propertyName, int defaultValue = 0) const; + _NODISCARD float ReadFloatProperty(const std::string &propertyName, float defaultValue = 0.0f) const; + _NODISCARD Vector2f ReadVec2Property(const std::string &propertyName, Vector2f defaultValue = {}) const; + _NODISCARD Vector3f ReadVec3Property(const std::string &propertyName, Vector3f defaultValue = {}) const; + _NODISCARD Vector4f ReadVec4Property(const std::string &propertyName, Vector4f defaultValue = {}) const; - const GdtEntry& m_entry; + const GdtEntry &m_entry; }; diff --git a/src/ObjLoading/AssetLoading/AssetLoadingContext.cpp b/src/ObjLoading/AssetLoading/AssetLoadingContext.cpp index 76a0f72e3..f2a2d530a 100644 --- a/src/ObjLoading/AssetLoading/AssetLoadingContext.cpp +++ b/src/ObjLoading/AssetLoading/AssetLoadingContext.cpp @@ -1,50 +1,40 @@ #include "AssetLoadingContext.h" -AssetLoadingContext::AssetLoadingContext(Zone* zone, ISearchPath* rawSearchPath, std::vector gdtFiles) - : m_zone(zone), - m_raw_search_path(rawSearchPath), - m_gdt_files(std::move(gdtFiles)) -{ - BuildGdtEntryCache(); +AssetLoadingContext::AssetLoadingContext(Zone *zone, ISearchPath *rawSearchPath, std::vector gdtFiles) + : m_zone(zone), m_raw_search_path(rawSearchPath), m_gdt_files(std::move(gdtFiles)) { + BuildGdtEntryCache(); } -void AssetLoadingContext::BuildGdtEntryCache() -{ - for (auto* gdt : m_gdt_files) - { - for (const auto& entry : gdt->m_entries) - { - auto gdfMapEntry = m_entries_by_gdf_and_by_name.find(entry->m_gdf_name); - if (gdfMapEntry == m_entries_by_gdf_and_by_name.end()) - { - std::unordered_map entryMap; - entryMap.emplace(std::make_pair(entry->m_name, entry.get())); - m_entries_by_gdf_and_by_name.emplace(std::make_pair(entry->m_gdf_name, std::move(entryMap))); - } - else - { - auto entryMapEntry = gdfMapEntry->second.find(entry->m_name); - - if (entryMapEntry == gdfMapEntry->second.end()) - gdfMapEntry->second.emplace(std::make_pair(entry->m_name, entry.get())); - else - entryMapEntry->second = entry.get(); - } - } +void AssetLoadingContext::BuildGdtEntryCache() { + for (auto *gdt : m_gdt_files) { + for (const auto &entry : gdt->m_entries) { + auto gdfMapEntry = m_entries_by_gdf_and_by_name.find(entry->m_gdf_name); + if (gdfMapEntry == m_entries_by_gdf_and_by_name.end()) { + std::unordered_map entryMap; + entryMap.emplace(std::make_pair(entry->m_name, entry.get())); + m_entries_by_gdf_and_by_name.emplace(std::make_pair(entry->m_gdf_name, std::move(entryMap))); + } else { + auto entryMapEntry = gdfMapEntry->second.find(entry->m_name); + + if (entryMapEntry == gdfMapEntry->second.end()) + gdfMapEntry->second.emplace(std::make_pair(entry->m_name, entry.get())); + else + entryMapEntry->second = entry.get(); + } } + } } -GdtEntry* AssetLoadingContext::GetGdtEntryByGdfAndName(const std::string& gdfName, const std::string& entryName) -{ - const auto foundGdtMap = m_entries_by_gdf_and_by_name.find(gdfName); +GdtEntry *AssetLoadingContext::GetGdtEntryByGdfAndName(const std::string &gdfName, const std::string &entryName) { + const auto foundGdtMap = m_entries_by_gdf_and_by_name.find(gdfName); - if (foundGdtMap == m_entries_by_gdf_and_by_name.end()) - return nullptr; + if (foundGdtMap == m_entries_by_gdf_and_by_name.end()) + return nullptr; - const auto foundGdtEntry = foundGdtMap->second.find(entryName); + const auto foundGdtEntry = foundGdtMap->second.find(entryName); - if (foundGdtEntry == foundGdtMap->second.end()) - return nullptr; + if (foundGdtEntry == foundGdtMap->second.end()) + return nullptr; - return foundGdtEntry->second; + return foundGdtEntry->second; } diff --git a/src/ObjLoading/AssetLoading/AssetLoadingContext.h b/src/ObjLoading/AssetLoading/AssetLoadingContext.h index aeb9377dd..5d1f8c0e4 100644 --- a/src/ObjLoading/AssetLoading/AssetLoadingContext.h +++ b/src/ObjLoading/AssetLoading/AssetLoadingContext.h @@ -1,8 +1,8 @@ #pragma once -#include -#include #include +#include +#include #include "IGdtQueryable.h" #include "IZoneAssetLoaderState.h" @@ -10,36 +10,33 @@ #include "SearchPath/ISearchPath.h" #include "Zone/Zone.h" -class AssetLoadingContext final : public IGdtQueryable -{ - std::unordered_map> m_entries_by_gdf_and_by_name; - std::unordered_map> m_zone_asset_loader_states; +class AssetLoadingContext final : public IGdtQueryable { + std::unordered_map> m_entries_by_gdf_and_by_name; + std::unordered_map> m_zone_asset_loader_states; - void BuildGdtEntryCache(); + void BuildGdtEntryCache(); public: - Zone* const m_zone; - ISearchPath* const m_raw_search_path; - const std::vector m_gdt_files; - std::unordered_map m_ignored_asset_map; - - AssetLoadingContext(Zone* zone, ISearchPath* rawSearchPath, std::vector gdtFiles); - GdtEntry* GetGdtEntryByGdfAndName(const std::string& gdfName, const std::string& entryName) override; - - template - T* GetZoneAssetLoaderState() - { - static_assert(std::is_base_of_v, "T must inherit IZoneAssetLoaderState"); - // T must also have a public default constructor - - const auto foundEntry = m_zone_asset_loader_states.find(typeid(T)); - if(foundEntry != m_zone_asset_loader_states.end()) - return dynamic_cast(foundEntry->second.get()); - - auto newState = std::make_unique(); - newState->SetZone(m_zone); - auto* newStatePtr = newState.get(); - m_zone_asset_loader_states.emplace(std::make_pair>(typeid(T), std::move(newState))); - return newStatePtr; - } + Zone *const m_zone; + ISearchPath *const m_raw_search_path; + const std::vector m_gdt_files; + std::unordered_map m_ignored_asset_map; + + AssetLoadingContext(Zone *zone, ISearchPath *rawSearchPath, std::vector gdtFiles); + GdtEntry *GetGdtEntryByGdfAndName(const std::string &gdfName, const std::string &entryName) override; + + template T *GetZoneAssetLoaderState() { + static_assert(std::is_base_of_v, "T must inherit IZoneAssetLoaderState"); + // T must also have a public default constructor + + const auto foundEntry = m_zone_asset_loader_states.find(typeid(T)); + if (foundEntry != m_zone_asset_loader_states.end()) + return dynamic_cast(foundEntry->second.get()); + + auto newState = std::make_unique(); + newState->SetZone(m_zone); + auto *newStatePtr = newState.get(); + m_zone_asset_loader_states.emplace(std::make_pair>(typeid(T), std::move(newState))); + return newStatePtr; + } }; diff --git a/src/ObjLoading/AssetLoading/AssetLoadingManager.cpp b/src/ObjLoading/AssetLoading/AssetLoadingManager.cpp index bc34497bb..b4f2587a4 100644 --- a/src/ObjLoading/AssetLoading/AssetLoadingManager.cpp +++ b/src/ObjLoading/AssetLoading/AssetLoadingManager.cpp @@ -1,136 +1,121 @@ #include "AssetLoadingManager.h" #include -AssetLoadingManager::AssetLoadingManager(const std::map>& assetLoadersByType, AssetLoadingContext& context): - m_asset_loaders_by_type(assetLoadersByType), - m_context(context), - m_last_dependency_loaded(nullptr) -{ -} +AssetLoadingManager::AssetLoadingManager(const std::map> &assetLoadersByType, AssetLoadingContext &context) + : m_asset_loaders_by_type(assetLoadersByType), m_context(context), m_last_dependency_loaded(nullptr) {} -bool AssetLoadingManager::LoadAssetFromLoader(const asset_type_t assetType, const std::string& assetName) -{ - return LoadDependency(assetType, assetName) != nullptr; +bool AssetLoadingManager::LoadAssetFromLoader(const asset_type_t assetType, const std::string &assetName) { + return LoadDependency(assetType, assetName) != nullptr; } -AssetLoadingContext* AssetLoadingManager::GetAssetLoadingContext() const -{ - return &m_context; -} +AssetLoadingContext *AssetLoadingManager::GetAssetLoadingContext() const { return &m_context; } -XAssetInfoGeneric* AssetLoadingManager::AddAsset(const asset_type_t assetType, const std::string& assetName, void* asset, std::vector dependencies, std::vector usedScriptStrings, - Zone* zone) -{ - m_last_dependency_loaded = m_context.m_zone->m_pools->AddAsset(assetType, assetName, asset, std::move(dependencies), std::move(usedScriptStrings), zone); - if (m_last_dependency_loaded == nullptr) - std::cout << "Failed to add asset of type \"" << m_context.m_zone->m_pools->GetAssetTypeName(assetType) << "\" to pool: \"" << assetName << "\"" << std::endl; - return m_last_dependency_loaded; +XAssetInfoGeneric *AssetLoadingManager::AddAsset(const asset_type_t assetType, const std::string &assetName, void *asset, + std::vector dependencies, std::vector usedScriptStrings, Zone *zone) { + m_last_dependency_loaded = m_context.m_zone->m_pools->AddAsset(assetType, assetName, asset, std::move(dependencies), std::move(usedScriptStrings), zone); + if (m_last_dependency_loaded == nullptr) + std::cout << "Failed to add asset of type \"" << m_context.m_zone->m_pools->GetAssetTypeName(assetType) << "\" to pool: \"" << assetName << "\"" + << std::endl; + return m_last_dependency_loaded; } -XAssetInfoGeneric* AssetLoadingManager::AddAsset(const asset_type_t assetType, const std::string& assetName, void* asset, std::vector dependencies, std::vector usedScriptStrings) -{ - m_last_dependency_loaded = m_context.m_zone->m_pools->AddAsset(assetType, assetName, asset, std::move(dependencies), std::move(usedScriptStrings)); - if (m_last_dependency_loaded == nullptr) - std::cout << "Failed to add asset of type \"" << m_context.m_zone->m_pools->GetAssetTypeName(assetType) << "\" to pool: \"" << assetName << "\"" << std::endl; - return m_last_dependency_loaded; +XAssetInfoGeneric *AssetLoadingManager::AddAsset(const asset_type_t assetType, const std::string &assetName, void *asset, + std::vector dependencies, std::vector usedScriptStrings) { + m_last_dependency_loaded = m_context.m_zone->m_pools->AddAsset(assetType, assetName, asset, std::move(dependencies), std::move(usedScriptStrings)); + if (m_last_dependency_loaded == nullptr) + std::cout << "Failed to add asset of type \"" << m_context.m_zone->m_pools->GetAssetTypeName(assetType) << "\" to pool: \"" << assetName << "\"" + << std::endl; + return m_last_dependency_loaded; } -XAssetInfoGeneric* AssetLoadingManager::LoadIgnoredDependency(const asset_type_t assetType, const std::string& assetName, IAssetLoader* loader) -{ - auto* alreadyLoadedAsset = m_context.m_zone->m_pools->GetAsset(assetType, assetName); - if (alreadyLoadedAsset) - return alreadyLoadedAsset; - - auto* linkAsset = loader->CreateEmptyAsset(assetName, m_context.m_zone->GetMemory()); - if (linkAsset) - { - AddAsset(assetType, assetName, linkAsset, std::vector(), std::vector()); - auto* lastDependency = m_last_dependency_loaded; - m_last_dependency_loaded = nullptr; - return lastDependency; - } - - auto* existingAsset = loader->LoadFromGlobalAssetPools(assetName); - if (existingAsset) - { - std::vector dependencies; - AddAsset(existingAsset->m_type, existingAsset->m_name, existingAsset->m_ptr, std::vector(), std::vector(), existingAsset->m_zone); - auto* lastDependency = m_last_dependency_loaded; - m_last_dependency_loaded = nullptr; - return lastDependency; - } - - std::cout << "Failed to create empty asset for type \"" << m_context.m_zone->m_pools->GetAssetTypeName(assetType) << "\"" << std::endl; - return nullptr; +XAssetInfoGeneric *AssetLoadingManager::LoadIgnoredDependency(const asset_type_t assetType, const std::string &assetName, IAssetLoader *loader) { + auto *alreadyLoadedAsset = m_context.m_zone->m_pools->GetAsset(assetType, assetName); + if (alreadyLoadedAsset) + return alreadyLoadedAsset; + + auto *linkAsset = loader->CreateEmptyAsset(assetName, m_context.m_zone->GetMemory()); + if (linkAsset) { + AddAsset(assetType, assetName, linkAsset, std::vector(), std::vector()); + auto *lastDependency = m_last_dependency_loaded; + m_last_dependency_loaded = nullptr; + return lastDependency; + } + + auto *existingAsset = loader->LoadFromGlobalAssetPools(assetName); + if (existingAsset) { + std::vector dependencies; + AddAsset(existingAsset->m_type, existingAsset->m_name, existingAsset->m_ptr, std::vector(), std::vector(), + existingAsset->m_zone); + auto *lastDependency = m_last_dependency_loaded; + m_last_dependency_loaded = nullptr; + return lastDependency; + } + + std::cout << "Failed to create empty asset for type \"" << m_context.m_zone->m_pools->GetAssetTypeName(assetType) << "\"" << std::endl; + return nullptr; } -XAssetInfoGeneric* AssetLoadingManager::LoadAssetDependency(const asset_type_t assetType, const std::string& assetName, IAssetLoader* loader) -{ - if (loader->CanLoadFromGdt() && !m_context.m_gdt_files.empty() && loader->LoadFromGdt(assetName, &m_context, m_context.m_zone->GetMemory(), this, m_context.m_zone)) - { - auto* lastDependency = m_last_dependency_loaded; - m_last_dependency_loaded = nullptr; - return lastDependency; +XAssetInfoGeneric *AssetLoadingManager::LoadAssetDependency(const asset_type_t assetType, const std::string &assetName, IAssetLoader *loader) { + if (loader->CanLoadFromGdt() && !m_context.m_gdt_files.empty() && + loader->LoadFromGdt(assetName, &m_context, m_context.m_zone->GetMemory(), this, m_context.m_zone)) { + auto *lastDependency = m_last_dependency_loaded; + m_last_dependency_loaded = nullptr; + return lastDependency; + } + + if (loader->CanLoadFromRaw() && loader->LoadFromRaw(assetName, m_context.m_raw_search_path, m_context.m_zone->GetMemory(), this, m_context.m_zone)) { + auto *lastDependency = m_last_dependency_loaded; + m_last_dependency_loaded = nullptr; + return lastDependency; + } + + auto *existingAsset = loader->LoadFromGlobalAssetPools(assetName); + if (!existingAsset && !assetName.empty() && assetName[0] != ',') + existingAsset = loader->LoadFromGlobalAssetPools(',' + assetName); + + if (existingAsset) { + std::vector dependencies; + for (const auto *dependency : existingAsset->m_dependencies) { + auto *newDependency = LoadDependency(dependency->m_type, dependency->m_name); + if (newDependency) + dependencies.push_back(newDependency); + else + return nullptr; } - if (loader->CanLoadFromRaw() && loader->LoadFromRaw(assetName, m_context.m_raw_search_path, m_context.m_zone->GetMemory(), this, m_context.m_zone)) - { - auto* lastDependency = m_last_dependency_loaded; - m_last_dependency_loaded = nullptr; - return lastDependency; - } + // Make sure any used script string is available in the created zone + // The replacement of the scr_string_t values will be done upon writing + for (const auto scrString : existingAsset->m_used_script_strings) + m_context.m_zone->m_script_strings.AddOrGetScriptString(existingAsset->m_zone->m_script_strings.CValue(scrString)); - auto* existingAsset = loader->LoadFromGlobalAssetPools(assetName); - if (!existingAsset && !assetName.empty() && assetName[0] != ',') - existingAsset = loader->LoadFromGlobalAssetPools(',' + assetName); - - if (existingAsset) - { - std::vector dependencies; - for (const auto* dependency : existingAsset->m_dependencies) - { - auto* newDependency = LoadDependency(dependency->m_type, dependency->m_name); - if (newDependency) - dependencies.push_back(newDependency); - else - return nullptr; - } - - // Make sure any used script string is available in the created zone - // The replacement of the scr_string_t values will be done upon writing - for(const auto scrString : existingAsset->m_used_script_strings) - m_context.m_zone->m_script_strings.AddOrGetScriptString(existingAsset->m_zone->m_script_strings.CValue(scrString)); - - AddAsset(existingAsset->m_type, existingAsset->m_name, existingAsset->m_ptr, std::move(dependencies), existingAsset->m_used_script_strings, existingAsset->m_zone); - auto* lastDependency = m_last_dependency_loaded; - m_last_dependency_loaded = nullptr; - return lastDependency; - } + AddAsset(existingAsset->m_type, existingAsset->m_name, existingAsset->m_ptr, std::move(dependencies), existingAsset->m_used_script_strings, + existingAsset->m_zone); + auto *lastDependency = m_last_dependency_loaded; + m_last_dependency_loaded = nullptr; + return lastDependency; + } - std::cout << "Failed to load asset of type \"" << m_context.m_zone->m_pools->GetAssetTypeName(assetType) << "\": \"" << assetName << "\"" << std::endl; - return nullptr; + std::cout << "Failed to load asset of type \"" << m_context.m_zone->m_pools->GetAssetTypeName(assetType) << "\": \"" << assetName << "\"" << std::endl; + return nullptr; } -XAssetInfoGeneric* AssetLoadingManager::LoadDependency(const asset_type_t assetType, const std::string& assetName) -{ - auto* alreadyLoadedAsset = m_context.m_zone->m_pools->GetAsset(assetType, assetName); - if (alreadyLoadedAsset) - return alreadyLoadedAsset; +XAssetInfoGeneric *AssetLoadingManager::LoadDependency(const asset_type_t assetType, const std::string &assetName) { + auto *alreadyLoadedAsset = m_context.m_zone->m_pools->GetAsset(assetType, assetName); + if (alreadyLoadedAsset) + return alreadyLoadedAsset; - const auto loader = m_asset_loaders_by_type.find(assetType); - if (loader != m_asset_loaders_by_type.end()) - { - const auto ignoreEntry = m_context.m_ignored_asset_map.find(assetName); - if (ignoreEntry != m_context.m_ignored_asset_map.end() && ignoreEntry->second == assetType) - { - const auto linkAssetName = ',' + assetName; + const auto loader = m_asset_loaders_by_type.find(assetType); + if (loader != m_asset_loaders_by_type.end()) { + const auto ignoreEntry = m_context.m_ignored_asset_map.find(assetName); + if (ignoreEntry != m_context.m_ignored_asset_map.end() && ignoreEntry->second == assetType) { + const auto linkAssetName = ',' + assetName; - return LoadIgnoredDependency(assetType, linkAssetName, loader->second.get()); - } - - return LoadAssetDependency(assetType, assetName, loader->second.get()); + return LoadIgnoredDependency(assetType, linkAssetName, loader->second.get()); } - std::cout << "Failed to find loader for asset type \"" << m_context.m_zone->m_pools->GetAssetTypeName(assetType) << "\"" << std::endl; - return nullptr; + return LoadAssetDependency(assetType, assetName, loader->second.get()); + } + + std::cout << "Failed to find loader for asset type \"" << m_context.m_zone->m_pools->GetAssetTypeName(assetType) << "\"" << std::endl; + return nullptr; } diff --git a/src/ObjLoading/AssetLoading/AssetLoadingManager.h b/src/ObjLoading/AssetLoading/AssetLoadingManager.h index 62a3007d3..37f85a576 100644 --- a/src/ObjLoading/AssetLoading/AssetLoadingManager.h +++ b/src/ObjLoading/AssetLoading/AssetLoadingManager.h @@ -5,24 +5,25 @@ #include "IAssetLoader.h" #include "IAssetLoadingManager.h" -class AssetLoadingManager final : public IAssetLoadingManager -{ - const std::map>& m_asset_loaders_by_type; - AssetLoadingContext& m_context; - XAssetInfoGeneric* m_last_dependency_loaded; +class AssetLoadingManager final : public IAssetLoadingManager { + const std::map> &m_asset_loaders_by_type; + AssetLoadingContext &m_context; + XAssetInfoGeneric *m_last_dependency_loaded; - XAssetInfoGeneric* LoadIgnoredDependency(asset_type_t assetType, const std::string& assetName, IAssetLoader* loader); - XAssetInfoGeneric* LoadAssetDependency(asset_type_t assetType, const std::string& assetName, IAssetLoader* loader); + XAssetInfoGeneric *LoadIgnoredDependency(asset_type_t assetType, const std::string &assetName, IAssetLoader *loader); + XAssetInfoGeneric *LoadAssetDependency(asset_type_t assetType, const std::string &assetName, IAssetLoader *loader); - XAssetInfoGeneric* AddAsset(asset_type_t assetType, const std::string& assetName, void* asset, std::vector dependencies, std::vector usedScriptStrings, Zone* zone); + XAssetInfoGeneric *AddAsset(asset_type_t assetType, const std::string &assetName, void *asset, std::vector dependencies, + std::vector usedScriptStrings, Zone *zone); public: - AssetLoadingManager(const std::map>& assetLoadersByType, AssetLoadingContext& context); + AssetLoadingManager(const std::map> &assetLoadersByType, AssetLoadingContext &context); - bool LoadAssetFromLoader(asset_type_t assetType, const std::string& assetName); + bool LoadAssetFromLoader(asset_type_t assetType, const std::string &assetName); - _NODISCARD AssetLoadingContext* GetAssetLoadingContext() const override; + _NODISCARD AssetLoadingContext *GetAssetLoadingContext() const override; - XAssetInfoGeneric* AddAsset(asset_type_t assetType, const std::string& assetName, void* asset, std::vector dependencies, std::vector usedScriptStrings) override; - XAssetInfoGeneric* LoadDependency(asset_type_t assetType, const std::string& assetName) override; + XAssetInfoGeneric *AddAsset(asset_type_t assetType, const std::string &assetName, void *asset, std::vector dependencies, + std::vector usedScriptStrings) override; + XAssetInfoGeneric *LoadDependency(asset_type_t assetType, const std::string &assetName) override; }; diff --git a/src/ObjLoading/AssetLoading/BasicAssetLoader.h b/src/ObjLoading/AssetLoading/BasicAssetLoader.h index 0f74428da..cc201431f 100644 --- a/src/ObjLoading/AssetLoading/BasicAssetLoader.h +++ b/src/ObjLoading/AssetLoading/BasicAssetLoader.h @@ -2,22 +2,12 @@ #include "IAssetLoader.h" #include "Pool/GlobalAssetPool.h" -template -class BasicAssetLoaderWithoutType : public IAssetLoader -{ +template class BasicAssetLoaderWithoutType : public IAssetLoader { public: - _NODISCARD XAssetInfoGeneric* LoadFromGlobalAssetPools(const std::string& assetName) const override - { - return GlobalAssetPool::GetAssetByName(assetName); - } + _NODISCARD XAssetInfoGeneric *LoadFromGlobalAssetPools(const std::string &assetName) const override { return GlobalAssetPool::GetAssetByName(assetName); } }; -template -class BasicAssetLoader : public BasicAssetLoaderWithoutType -{ +template class BasicAssetLoader : public BasicAssetLoaderWithoutType { public: - _NODISCARD asset_type_t GetHandlingAssetType() const override - { - return AssetType; - } + _NODISCARD asset_type_t GetHandlingAssetType() const override { return AssetType; } }; diff --git a/src/ObjLoading/AssetLoading/IAssetLoader.h b/src/ObjLoading/AssetLoading/IAssetLoader.h index 7ecde3246..ea16c19fb 100644 --- a/src/ObjLoading/AssetLoading/IAssetLoader.h +++ b/src/ObjLoading/AssetLoading/IAssetLoader.h @@ -1,53 +1,42 @@ #pragma once #include -#include "Utils/ClassUtils.h" -#include "SearchPath/ISearchPath.h" #include "IAssetLoadingManager.h" #include "IGdtQueryable.h" +#include "SearchPath/ISearchPath.h" +#include "Utils/ClassUtils.h" #include "Zone/ZoneTypes.h" -class IAssetLoader -{ +class IAssetLoader { public: - IAssetLoader() = default; - virtual ~IAssetLoader() = default; - IAssetLoader(const IAssetLoader& other) = default; - IAssetLoader(IAssetLoader&& other) noexcept = default; - IAssetLoader& operator=(const IAssetLoader& other) = default; - IAssetLoader& operator=(IAssetLoader&& other) noexcept = default; - - _NODISCARD virtual asset_type_t GetHandlingAssetType() const = 0; - _NODISCARD virtual XAssetInfoGeneric* LoadFromGlobalAssetPools(const std::string& assetName) const = 0; - - _NODISCARD virtual void* CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) - { - // TODO: Make this pure virtual - return nullptr; - } - - _NODISCARD virtual bool CanLoadFromGdt() const - { - return false; - } - - _NODISCARD virtual bool CanLoadFromRaw() const - { - return false; - } - - virtual bool LoadFromGdt(const std::string& assetName, IGdtQueryable* gdtQueryable, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const - { - return false; - } - - virtual bool LoadFromRaw(const std::string& assetName, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const - { - return false; - } - - virtual void FinalizeAssetsForZone(AssetLoadingContext* context) const - { - // Do nothing by default - } + IAssetLoader() = default; + virtual ~IAssetLoader() = default; + IAssetLoader(const IAssetLoader &other) = default; + IAssetLoader(IAssetLoader &&other) noexcept = default; + IAssetLoader &operator=(const IAssetLoader &other) = default; + IAssetLoader &operator=(IAssetLoader &&other) noexcept = default; + + _NODISCARD virtual asset_type_t GetHandlingAssetType() const = 0; + _NODISCARD virtual XAssetInfoGeneric *LoadFromGlobalAssetPools(const std::string &assetName) const = 0; + + _NODISCARD virtual void *CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) { + // TODO: Make this pure virtual + return nullptr; + } + + _NODISCARD virtual bool CanLoadFromGdt() const { return false; } + + _NODISCARD virtual bool CanLoadFromRaw() const { return false; } + + virtual bool LoadFromGdt(const std::string &assetName, IGdtQueryable *gdtQueryable, MemoryManager *memory, IAssetLoadingManager *manager, Zone *zone) const { + return false; + } + + virtual bool LoadFromRaw(const std::string &assetName, ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager, Zone *zone) const { + return false; + } + + virtual void FinalizeAssetsForZone(AssetLoadingContext *context) const { + // Do nothing by default + } }; diff --git a/src/ObjLoading/AssetLoading/IAssetLoadingManager.h b/src/ObjLoading/AssetLoading/IAssetLoadingManager.h index e92aa9207..dca033590 100644 --- a/src/ObjLoading/AssetLoading/IAssetLoadingManager.h +++ b/src/ObjLoading/AssetLoading/IAssetLoadingManager.h @@ -3,25 +3,24 @@ #include "AssetLoadingContext.h" #include "Pool/XAssetInfo.h" -#include "Zone/ZoneTypes.h" #include "Utils/ClassUtils.h" +#include "Zone/ZoneTypes.h" -class IAssetLoadingManager -{ +class IAssetLoadingManager { public: - IAssetLoadingManager() = default; - virtual ~IAssetLoadingManager() = default; - IAssetLoadingManager(const IAssetLoadingManager& other) = default; - IAssetLoadingManager(IAssetLoadingManager&& other) noexcept = default; - IAssetLoadingManager& operator=(const IAssetLoadingManager& other) = default; - IAssetLoadingManager& operator=(IAssetLoadingManager&& other) noexcept = default; + IAssetLoadingManager() = default; + virtual ~IAssetLoadingManager() = default; + IAssetLoadingManager(const IAssetLoadingManager &other) = default; + IAssetLoadingManager(IAssetLoadingManager &&other) noexcept = default; + IAssetLoadingManager &operator=(const IAssetLoadingManager &other) = default; + IAssetLoadingManager &operator=(IAssetLoadingManager &&other) noexcept = default; - _NODISCARD virtual AssetLoadingContext* GetAssetLoadingContext() const = 0; + _NODISCARD virtual AssetLoadingContext *GetAssetLoadingContext() const = 0; - virtual XAssetInfoGeneric* AddAsset(asset_type_t assetType, const std::string& assetName, void* asset, std::vector dependencies, std::vector usedScriptStrings) = 0; - XAssetInfoGeneric* AddAsset(const asset_type_t assetType, const std::string& assetName, void* asset) - { - return AddAsset(assetType, assetName, asset, std::vector(), std::vector()); - } - virtual XAssetInfoGeneric* LoadDependency(asset_type_t assetType, const std::string& assetName) = 0; + virtual XAssetInfoGeneric *AddAsset(asset_type_t assetType, const std::string &assetName, void *asset, std::vector dependencies, + std::vector usedScriptStrings) = 0; + XAssetInfoGeneric *AddAsset(const asset_type_t assetType, const std::string &assetName, void *asset) { + return AddAsset(assetType, assetName, asset, std::vector(), std::vector()); + } + virtual XAssetInfoGeneric *LoadDependency(asset_type_t assetType, const std::string &assetName) = 0; }; diff --git a/src/ObjLoading/AssetLoading/IGdtQueryable.h b/src/ObjLoading/AssetLoading/IGdtQueryable.h index 79ff4ff8d..650695765 100644 --- a/src/ObjLoading/AssetLoading/IGdtQueryable.h +++ b/src/ObjLoading/AssetLoading/IGdtQueryable.h @@ -3,15 +3,14 @@ #include "Obj/Gdt/GdtEntry.h" -class IGdtQueryable -{ +class IGdtQueryable { public: - IGdtQueryable() = default; - virtual ~IGdtQueryable() = default; - IGdtQueryable(const IGdtQueryable& other) = default; - IGdtQueryable(IGdtQueryable&& other) noexcept = default; - IGdtQueryable& operator=(const IGdtQueryable& other) = default; - IGdtQueryable& operator=(IGdtQueryable&& other) noexcept = default; + IGdtQueryable() = default; + virtual ~IGdtQueryable() = default; + IGdtQueryable(const IGdtQueryable &other) = default; + IGdtQueryable(IGdtQueryable &&other) noexcept = default; + IGdtQueryable &operator=(const IGdtQueryable &other) = default; + IGdtQueryable &operator=(IGdtQueryable &&other) noexcept = default; - virtual GdtEntry* GetGdtEntryByGdfAndName(const std::string& gdfName, const std::string& entryName) = 0; + virtual GdtEntry *GetGdtEntryByGdfAndName(const std::string &gdfName, const std::string &entryName) = 0; }; diff --git a/src/ObjLoading/AssetLoading/IZoneAssetLoaderState.h b/src/ObjLoading/AssetLoading/IZoneAssetLoaderState.h index a17ccd515..4ec6bf1d1 100644 --- a/src/ObjLoading/AssetLoading/IZoneAssetLoaderState.h +++ b/src/ObjLoading/AssetLoading/IZoneAssetLoaderState.h @@ -1,20 +1,18 @@ #pragma once #include "Zone/Zone.h" -class IZoneAssetLoaderState -{ +class IZoneAssetLoaderState { protected: - IZoneAssetLoaderState() = default; + IZoneAssetLoaderState() = default; public: - virtual ~IZoneAssetLoaderState() = default; - IZoneAssetLoaderState(const IZoneAssetLoaderState& other) = default; - IZoneAssetLoaderState(IZoneAssetLoaderState&& other) noexcept = default; - IZoneAssetLoaderState& operator=(const IZoneAssetLoaderState& other) = default; - IZoneAssetLoaderState& operator=(IZoneAssetLoaderState&& other) noexcept = default; + virtual ~IZoneAssetLoaderState() = default; + IZoneAssetLoaderState(const IZoneAssetLoaderState &other) = default; + IZoneAssetLoaderState(IZoneAssetLoaderState &&other) noexcept = default; + IZoneAssetLoaderState &operator=(const IZoneAssetLoaderState &other) = default; + IZoneAssetLoaderState &operator=(IZoneAssetLoaderState &&other) noexcept = default; - virtual void SetZone(Zone* zone) - { - // Do nothing by default - } + virtual void SetZone(Zone *zone) { + // Do nothing by default + } }; diff --git a/src/ObjLoading/AssetLoading/SndCurve/SndCurveReader.cpp b/src/ObjLoading/AssetLoading/SndCurve/SndCurveReader.cpp index 5649a25ef..6e2170d97 100644 --- a/src/ObjLoading/AssetLoading/SndCurve/SndCurveReader.cpp +++ b/src/ObjLoading/AssetLoading/SndCurve/SndCurveReader.cpp @@ -2,212 +2,152 @@ #include "Parsing/Impl/AbstractParser.h" #include "Parsing/Impl/ParserSingleInputStream.h" +#include "Parsing/Simple/Matcher/SimpleMatcherFactory.h" #include "Parsing/Simple/SimpleLexer.h" #include "Parsing/Simple/SimpleParserValue.h" -#include "Parsing/Simple/Matcher/SimpleMatcherFactory.h" -enum class SndCurveParserStatus -{ - EXPECT_MAGIC, - EXPECT_KNOT_COUNT, - KNOTS -}; +enum class SndCurveParserStatus { EXPECT_MAGIC, EXPECT_KNOT_COUNT, KNOTS }; -class SndCurveParserState -{ +class SndCurveParserState { public: - SndCurveParserStatus m_status; - size_t m_knot_count; - SndCurveReader::Result m_result; - - SndCurveParserState() - : m_status(SndCurveParserStatus::EXPECT_MAGIC), - m_knot_count(0u) - { - } + SndCurveParserStatus m_status; + size_t m_knot_count; + SndCurveReader::Result m_result; + + SndCurveParserState() : m_status(SndCurveParserStatus::EXPECT_MAGIC), m_knot_count(0u) {} }; using snd_sequence_t = AbstractSequence; -class SndCurveMagicSequence final : public snd_sequence_t -{ +class SndCurveMagicSequence final : public snd_sequence_t { public: - SndCurveMagicSequence() - { - const SimpleMatcherFactory create(this); - AddMatchers({ - create.Keyword("SNDCURVE") - }); - } + SndCurveMagicSequence() { + const SimpleMatcherFactory create(this); + AddMatchers({create.Keyword("SNDCURVE")}); + } protected: - void ProcessMatch(SndCurveParserState* state, SequenceResult& result) const override - { - state->m_status = SndCurveParserStatus::EXPECT_KNOT_COUNT; - } + void ProcessMatch(SndCurveParserState *state, SequenceResult &result) const override { + state->m_status = SndCurveParserStatus::EXPECT_KNOT_COUNT; + } }; -class SndCurveKnotCountSequence final : public snd_sequence_t -{ - static constexpr auto CAPTURE_KNOT_COUNT = 1; +class SndCurveKnotCountSequence final : public snd_sequence_t { + static constexpr auto CAPTURE_KNOT_COUNT = 1; public: - SndCurveKnotCountSequence() - { - const SimpleMatcherFactory create(this); - AddMatchers({ - create.Integer().Capture(CAPTURE_KNOT_COUNT) - }); - } + SndCurveKnotCountSequence() { + const SimpleMatcherFactory create(this); + AddMatchers({create.Integer().Capture(CAPTURE_KNOT_COUNT)}); + } protected: - void ProcessMatch(SndCurveParserState* state, SequenceResult& result) const override - { - state->m_status = SndCurveParserStatus::KNOTS; + void ProcessMatch(SndCurveParserState *state, SequenceResult &result) const override { + state->m_status = SndCurveParserStatus::KNOTS; - const auto& knotCountToken = result.NextCapture(CAPTURE_KNOT_COUNT); - if (knotCountToken.IntegerValue() < 0) - throw ParsingException(knotCountToken.GetPos(), "Negative knot count is invalid"); + const auto &knotCountToken = result.NextCapture(CAPTURE_KNOT_COUNT); + if (knotCountToken.IntegerValue() < 0) + throw ParsingException(knotCountToken.GetPos(), "Negative knot count is invalid"); - state->m_knot_count = static_cast(knotCountToken.IntegerValue()); - state->m_result.m_knots.reserve(state->m_knot_count); - } + state->m_knot_count = static_cast(knotCountToken.IntegerValue()); + state->m_result.m_knots.reserve(state->m_knot_count); + } }; -class SndCurveKnotSequence final : public snd_sequence_t -{ - static constexpr auto CAPTURE_X = 1; - static constexpr auto CAPTURE_Y = 2; +class SndCurveKnotSequence final : public snd_sequence_t { + static constexpr auto CAPTURE_X = 1; + static constexpr auto CAPTURE_Y = 2; public: - SndCurveKnotSequence() - { - const SimpleMatcherFactory create(this); - AddMatchers({ - create.Or({ - create.FloatingPoint(), - create.Integer() - }).Capture(CAPTURE_X), - - create.Or({ - create.FloatingPoint(), - create.Integer() - }).Capture(CAPTURE_Y), - }); - } + SndCurveKnotSequence() { + const SimpleMatcherFactory create(this); + AddMatchers({ + create.Or({create.FloatingPoint(), create.Integer()}).Capture(CAPTURE_X), + + create.Or({create.FloatingPoint(), create.Integer()}).Capture(CAPTURE_Y), + }); + } private: - static double GetValue(const SimpleParserValue& token) - { - if (token.m_type == SimpleParserValueType::INTEGER) - return static_cast(token.IntegerValue()); + static double GetValue(const SimpleParserValue &token) { + if (token.m_type == SimpleParserValueType::INTEGER) + return static_cast(token.IntegerValue()); - return token.FloatingPointValue(); - } + return token.FloatingPointValue(); + } protected: - void ProcessMatch(SndCurveParserState* state, SequenceResult& result) const override - { - const auto& xToken = result.NextCapture(CAPTURE_X); - const auto& yToken = result.NextCapture(CAPTURE_Y); + void ProcessMatch(SndCurveParserState *state, SequenceResult &result) const override { + const auto &xToken = result.NextCapture(CAPTURE_X); + const auto &yToken = result.NextCapture(CAPTURE_Y); - if (state->m_result.m_knots.size() >= state->m_knot_count) - throw ParsingException(xToken.GetPos(), "Too many knots"); + if (state->m_result.m_knots.size() >= state->m_knot_count) + throw ParsingException(xToken.GetPos(), "Too many knots"); - const auto xValue = GetValue(xToken); - const auto yValue = GetValue(yToken); + const auto xValue = GetValue(xToken); + const auto yValue = GetValue(yToken); - state->m_result.m_knots.push_back(SndCurveReader::Result::Knot{xValue, yValue}); - } + state->m_result.m_knots.push_back(SndCurveReader::Result::Knot{xValue, yValue}); + } }; -class SndCurveParser final : public AbstractParser -{ +class SndCurveParser final : public AbstractParser { public: - explicit SndCurveParser(ILexer* lexer) - : AbstractParser(lexer, std::make_unique()) - { - } + explicit SndCurveParser(ILexer *lexer) + : AbstractParser(lexer, std::make_unique()) {} protected: - const std::vector& GetTestsForState() override - { - switch (m_state->m_status) - { - case SndCurveParserStatus::EXPECT_MAGIC: - { - static std::vector expectMagicSequences - { - new SndCurveMagicSequence() - }; - return expectMagicSequences; - } - - case SndCurveParserStatus::EXPECT_KNOT_COUNT: - { - static std::vector expectKnotCountSequences - { - new SndCurveKnotCountSequence() - }; - return expectKnotCountSequences; - } - - case SndCurveParserStatus::KNOTS: - { - static std::vector knotsSequences - { - new SndCurveKnotSequence() - }; - return knotsSequences; - } - } - - assert(false); - throw std::runtime_error("Invalid parsing status"); + const std::vector &GetTestsForState() override { + switch (m_state->m_status) { + case SndCurveParserStatus::EXPECT_MAGIC: { + static std::vector expectMagicSequences{new SndCurveMagicSequence()}; + return expectMagicSequences; } -public: - _NODISCARD SndCurveReader::Result& GetResult() const - { - return m_state->m_result; + case SndCurveParserStatus::EXPECT_KNOT_COUNT: { + static std::vector expectKnotCountSequences{new SndCurveKnotCountSequence()}; + return expectKnotCountSequences; } - _NODISCARD bool HasExpectedKnotCount() const - { - return m_state->m_knot_count == m_state->m_result.m_knots.size(); + case SndCurveParserStatus::KNOTS: { + static std::vector knotsSequences{new SndCurveKnotSequence()}; + return knotsSequences; } + } + + assert(false); + throw std::runtime_error("Invalid parsing status"); + } + +public: + _NODISCARD SndCurveReader::Result &GetResult() const { return m_state->m_result; } + + _NODISCARD bool HasExpectedKnotCount() const { return m_state->m_knot_count == m_state->m_result.m_knots.size(); } }; -SndCurveReader::SndCurveReader(std::istream& stream, const std::string& filename) - : m_stream(stream), - m_filename(filename) -{ -} +SndCurveReader::SndCurveReader(std::istream &stream, const std::string &filename) : m_stream(stream), m_filename(filename) {} -std::unique_ptr SndCurveReader::Read() const -{ - ParserSingleInputStream parserStream(m_stream, m_filename); +std::unique_ptr SndCurveReader::Read() const { + ParserSingleInputStream parserStream(m_stream, m_filename); - SimpleLexer::Config lexerConfig; - lexerConfig.m_emit_new_line_tokens = false; - lexerConfig.m_read_strings = false; - lexerConfig.m_read_integer_numbers = true; - lexerConfig.m_read_floating_point_numbers = true; + SimpleLexer::Config lexerConfig; + lexerConfig.m_emit_new_line_tokens = false; + lexerConfig.m_read_strings = false; + lexerConfig.m_read_integer_numbers = true; + lexerConfig.m_read_floating_point_numbers = true; - SimpleLexer lexer(&parserStream, std::move(lexerConfig)); - SndCurveParser parser(&lexer); + SimpleLexer lexer(&parserStream, std::move(lexerConfig)); + SndCurveParser parser(&lexer); - if (!parser.Parse()) - { - std::cerr << "Failed to parse SndCurve \"" << m_filename << "\"\n"; - return nullptr; - } + if (!parser.Parse()) { + std::cerr << "Failed to parse SndCurve \"" << m_filename << "\"\n"; + return nullptr; + } - if(!parser.HasExpectedKnotCount()) - { - std::cerr << "Failed to load SndCurve: Actual knot count differs from expected: \"" << m_filename << "\"\n"; - return nullptr; - } + if (!parser.HasExpectedKnotCount()) { + std::cerr << "Failed to load SndCurve: Actual knot count differs from expected: \"" << m_filename << "\"\n"; + return nullptr; + } - return std::make_unique(std::move(parser.GetResult())); + return std::make_unique(std::move(parser.GetResult())); } diff --git a/src/ObjLoading/AssetLoading/SndCurve/SndCurveReader.h b/src/ObjLoading/AssetLoading/SndCurve/SndCurveReader.h index 58ecec889..3eb200296 100644 --- a/src/ObjLoading/AssetLoading/SndCurve/SndCurveReader.h +++ b/src/ObjLoading/AssetLoading/SndCurve/SndCurveReader.h @@ -1,32 +1,29 @@ #pragma once #include -#include #include +#include #include "Utils/ClassUtils.h" -class SndCurveReader -{ +class SndCurveReader { public: - class Result - { - public: - struct Knot - { - double m_x; - double m_y; - }; - - std::vector m_knots; + class Result { + public: + struct Knot { + double m_x; + double m_y; }; + std::vector m_knots; + }; + private: - std::istream& m_stream; - const std::string& m_filename; + std::istream &m_stream; + const std::string &m_filename; public: - SndCurveReader(std::istream& stream, const std::string& filename); + SndCurveReader(std::istream &stream, const std::string &filename); - _NODISCARD std::unique_ptr Read() const; + _NODISCARD std::unique_ptr Read() const; }; diff --git a/src/ObjLoading/Game/IW3/AssetLoaders/AssetLoaderGfxImage.cpp b/src/ObjLoading/Game/IW3/AssetLoaders/AssetLoaderGfxImage.cpp index afe24bdea..e4f39ebfd 100644 --- a/src/ObjLoading/Game/IW3/AssetLoaders/AssetLoaderGfxImage.cpp +++ b/src/ObjLoading/Game/IW3/AssetLoaders/AssetLoaderGfxImage.cpp @@ -5,128 +5,118 @@ #include "Game/IW3/IW3.h" #include "Image/DdsLoader.h" -#include "Pool/GlobalAssetPool.h" #include "Image/IwiTypes.h" +#include "Pool/GlobalAssetPool.h" using namespace IW3; -void* AssetLoaderGfxImage::CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) -{ - auto* image = memory->Create(); - memset(image, 0, sizeof(GfxImage)); - image->name = memory->Dup(assetName.c_str()); - return image; +void *AssetLoaderGfxImage::CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) { + auto *image = memory->Create(); + memset(image, 0, sizeof(GfxImage)); + image->name = memory->Dup(assetName.c_str()); + return image; } -bool AssetLoaderGfxImage::CanLoadFromRaw() const -{ - return true; -} - -bool AssetLoaderGfxImage::LoadFromRaw(const std::string& assetName, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const -{ - // Do not load any GfxImages from raw for now that are not loaded - // TODO: Load iwis and add streaming info to asset - if (assetName.empty() || assetName[0] != '*') - return false; - - std::string safeAssetName = assetName; - for (auto& c : safeAssetName) - { - switch (c) - { - case '*': - c = '_'; - break; - - default: - break; - } - } +bool AssetLoaderGfxImage::CanLoadFromRaw() const { return true; } - const auto file = searchPath->Open("images/" + safeAssetName + ".dds"); - if (!file.IsOpen()) - return false; +bool AssetLoaderGfxImage::LoadFromRaw(const std::string &assetName, ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager, + Zone *zone) const { + // Do not load any GfxImages from raw for now that are not loaded + // TODO: Load iwis and add streaming info to asset + if (assetName.empty() || assetName[0] != '*') + return false; - const DdsLoader ddsLoader(zone->GetMemory()); - auto* texture = ddsLoader.LoadDds(*file.m_stream); - - if (texture == nullptr) - { - std::cout << "Failed to load dds file for image asset \"" << assetName << "\"" << std::endl; - return false; - } - - auto* image = memory->Create(); - image->name = memory->Dup(assetName.c_str()); - image->picmip.platform[0] = 0; - image->picmip.platform[1] = 0; - image->noPicmip = !texture->HasMipMaps(); - image->semantic = TS_FUNCTION; - image->track = 0; - image->cardMemory.platform[0] = 0; - image->cardMemory.platform[1] = 0; - image->width = static_cast(texture->GetWidth()); - image->height = static_cast(texture->GetHeight()); - image->depth = static_cast(texture->GetDepth()); - image->category = IMG_CATEGORY_AUTO_GENERATED; - image->delayLoadPixels = false; - - switch (texture->GetTextureType()) - { - case TextureType::T_2D: - image->mapType = MAPTYPE_2D; - break; - - case TextureType::T_3D: - image->mapType = MAPTYPE_3D; - break; - - case TextureType::T_CUBE: - image->mapType = MAPTYPE_CUBE; - break; + std::string safeAssetName = assetName; + for (auto &c : safeAssetName) { + switch (c) { + case '*': + c = '_'; + break; default: - image->mapType = MAPTYPE_NONE; - break; + break; } - - const auto mipCount = texture->HasMipMaps() ? texture->GetMipMapCount() : 1; - const auto faceCount = texture->GetFaceCount(); - - size_t dataSize = 0; - for (auto mipLevel = 0; mipLevel < mipCount; mipLevel++) - dataSize += texture->GetSizeOfMipLevel(mipLevel) * faceCount; - - auto* loadDef = static_cast(zone->GetMemory()->Alloc(offsetof(GfxImageLoadDef, data) + dataSize)); - image->texture.loadDef = loadDef; - loadDef->levelCount = static_cast(mipCount); - loadDef->flags = 0; - if (!texture->HasMipMaps()) - loadDef->flags |= iwi6::IMG_FLAG_NOMIPMAPS; - if (texture->GetTextureType() == TextureType::T_CUBE) - loadDef->flags |= iwi6::IMG_FLAG_CUBEMAP; - if (texture->GetTextureType() == TextureType::T_3D) - loadDef->flags |= iwi6::IMG_FLAG_VOLMAP; - loadDef->dimensions[0] = image->width; - loadDef->dimensions[1] = image->height; - loadDef->dimensions[2] = image->depth; - loadDef->format = static_cast(texture->GetFormat()->GetD3DFormat()); - loadDef->resourceSize = dataSize; - - char* currentDataBuffer = loadDef->data; - for (auto mipLevel = 0; mipLevel < mipCount; mipLevel++) - { - const auto mipSize = texture->GetSizeOfMipLevel(mipLevel); - - for (auto face = 0; face < faceCount; face++) - { - memcpy(currentDataBuffer, texture->GetBufferForMipLevel(mipLevel, face), mipSize); - currentDataBuffer += mipSize; - } + } + + const auto file = searchPath->Open("images/" + safeAssetName + ".dds"); + if (!file.IsOpen()) + return false; + + const DdsLoader ddsLoader(zone->GetMemory()); + auto *texture = ddsLoader.LoadDds(*file.m_stream); + + if (texture == nullptr) { + std::cout << "Failed to load dds file for image asset \"" << assetName << "\"" << std::endl; + return false; + } + + auto *image = memory->Create(); + image->name = memory->Dup(assetName.c_str()); + image->picmip.platform[0] = 0; + image->picmip.platform[1] = 0; + image->noPicmip = !texture->HasMipMaps(); + image->semantic = TS_FUNCTION; + image->track = 0; + image->cardMemory.platform[0] = 0; + image->cardMemory.platform[1] = 0; + image->width = static_cast(texture->GetWidth()); + image->height = static_cast(texture->GetHeight()); + image->depth = static_cast(texture->GetDepth()); + image->category = IMG_CATEGORY_AUTO_GENERATED; + image->delayLoadPixels = false; + + switch (texture->GetTextureType()) { + case TextureType::T_2D: + image->mapType = MAPTYPE_2D; + break; + + case TextureType::T_3D: + image->mapType = MAPTYPE_3D; + break; + + case TextureType::T_CUBE: + image->mapType = MAPTYPE_CUBE; + break; + + default: + image->mapType = MAPTYPE_NONE; + break; + } + + const auto mipCount = texture->HasMipMaps() ? texture->GetMipMapCount() : 1; + const auto faceCount = texture->GetFaceCount(); + + size_t dataSize = 0; + for (auto mipLevel = 0; mipLevel < mipCount; mipLevel++) + dataSize += texture->GetSizeOfMipLevel(mipLevel) * faceCount; + + auto *loadDef = static_cast(zone->GetMemory()->Alloc(offsetof(GfxImageLoadDef, data) + dataSize)); + image->texture.loadDef = loadDef; + loadDef->levelCount = static_cast(mipCount); + loadDef->flags = 0; + if (!texture->HasMipMaps()) + loadDef->flags |= iwi6::IMG_FLAG_NOMIPMAPS; + if (texture->GetTextureType() == TextureType::T_CUBE) + loadDef->flags |= iwi6::IMG_FLAG_CUBEMAP; + if (texture->GetTextureType() == TextureType::T_3D) + loadDef->flags |= iwi6::IMG_FLAG_VOLMAP; + loadDef->dimensions[0] = image->width; + loadDef->dimensions[1] = image->height; + loadDef->dimensions[2] = image->depth; + loadDef->format = static_cast(texture->GetFormat()->GetD3DFormat()); + loadDef->resourceSize = dataSize; + + char *currentDataBuffer = loadDef->data; + for (auto mipLevel = 0; mipLevel < mipCount; mipLevel++) { + const auto mipSize = texture->GetSizeOfMipLevel(mipLevel); + + for (auto face = 0; face < faceCount; face++) { + memcpy(currentDataBuffer, texture->GetBufferForMipLevel(mipLevel, face), mipSize); + currentDataBuffer += mipSize; } + } - manager->AddAsset(ASSET_TYPE_IMAGE, assetName, image); + manager->AddAsset(ASSET_TYPE_IMAGE, assetName, image); - return true; + return true; } diff --git a/src/ObjLoading/Game/IW3/AssetLoaders/AssetLoaderGfxImage.h b/src/ObjLoading/Game/IW3/AssetLoaders/AssetLoaderGfxImage.h index c9541a61a..e5cbc94df 100644 --- a/src/ObjLoading/Game/IW3/AssetLoaders/AssetLoaderGfxImage.h +++ b/src/ObjLoading/Game/IW3/AssetLoaders/AssetLoaderGfxImage.h @@ -1,16 +1,14 @@ #pragma once -#include "Game/IW3/IW3.h" #include "AssetLoading/BasicAssetLoader.h" #include "AssetLoading/IAssetLoadingManager.h" +#include "Game/IW3/IW3.h" #include "SearchPath/ISearchPath.h" -namespace IW3 -{ - class AssetLoaderGfxImage final : public BasicAssetLoader - { - public: - _NODISCARD void* CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) override; - _NODISCARD bool CanLoadFromRaw() const override; - bool LoadFromRaw(const std::string& assetName, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const override; - }; -} +namespace IW3 { +class AssetLoaderGfxImage final : public BasicAssetLoader { +public: + _NODISCARD void *CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) override; + _NODISCARD bool CanLoadFromRaw() const override; + bool LoadFromRaw(const std::string &assetName, ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager, Zone *zone) const override; +}; +} // namespace IW3 diff --git a/src/ObjLoading/Game/IW3/AssetLoaders/AssetLoaderRawFile.cpp b/src/ObjLoading/Game/IW3/AssetLoaders/AssetLoaderRawFile.cpp index 259c00eb1..b802298a2 100644 --- a/src/ObjLoading/Game/IW3/AssetLoaders/AssetLoaderRawFile.cpp +++ b/src/ObjLoading/Game/IW3/AssetLoaders/AssetLoaderRawFile.cpp @@ -7,37 +7,33 @@ using namespace IW3; -void* AssetLoaderRawFile::CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) -{ - auto* rawFile = memory->Create(); - memset(rawFile, 0, sizeof(RawFile)); - rawFile->name = memory->Dup(assetName.c_str()); - return rawFile; +void *AssetLoaderRawFile::CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) { + auto *rawFile = memory->Create(); + memset(rawFile, 0, sizeof(RawFile)); + rawFile->name = memory->Dup(assetName.c_str()); + return rawFile; } -bool AssetLoaderRawFile::CanLoadFromRaw() const -{ - return true; -} +bool AssetLoaderRawFile::CanLoadFromRaw() const { return true; } -bool AssetLoaderRawFile::LoadFromRaw(const std::string& assetName, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const -{ - const auto file = searchPath->Open(assetName); - if (!file.IsOpen()) - return false; +bool AssetLoaderRawFile::LoadFromRaw(const std::string &assetName, ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager, + Zone *zone) const { + const auto file = searchPath->Open(assetName); + if (!file.IsOpen()) + return false; - auto* rawFile = memory->Create(); - rawFile->name = memory->Dup(assetName.c_str()); - rawFile->len = static_cast(file.m_length); + auto *rawFile = memory->Create(); + rawFile->name = memory->Dup(assetName.c_str()); + rawFile->len = static_cast(file.m_length); - auto* fileBuffer = static_cast(memory->Alloc(static_cast(file.m_length + 1))); - file.m_stream->read(fileBuffer, file.m_length); - if (file.m_stream->gcount() != file.m_length) - return false; - fileBuffer[rawFile->len] = '\0'; + auto *fileBuffer = static_cast(memory->Alloc(static_cast(file.m_length + 1))); + file.m_stream->read(fileBuffer, file.m_length); + if (file.m_stream->gcount() != file.m_length) + return false; + fileBuffer[rawFile->len] = '\0'; - rawFile->buffer = fileBuffer; - manager->AddAsset(ASSET_TYPE_RAWFILE, assetName, rawFile); + rawFile->buffer = fileBuffer; + manager->AddAsset(ASSET_TYPE_RAWFILE, assetName, rawFile); - return true; + return true; } diff --git a/src/ObjLoading/Game/IW3/AssetLoaders/AssetLoaderRawFile.h b/src/ObjLoading/Game/IW3/AssetLoaders/AssetLoaderRawFile.h index 290fa77c0..5a66e178e 100644 --- a/src/ObjLoading/Game/IW3/AssetLoaders/AssetLoaderRawFile.h +++ b/src/ObjLoading/Game/IW3/AssetLoaders/AssetLoaderRawFile.h @@ -1,16 +1,14 @@ #pragma once -#include "Game/IW3/IW3.h" #include "AssetLoading/BasicAssetLoader.h" #include "AssetLoading/IAssetLoadingManager.h" +#include "Game/IW3/IW3.h" #include "SearchPath/ISearchPath.h" -namespace IW3 -{ - class AssetLoaderRawFile final : public BasicAssetLoader - { - public: - _NODISCARD void* CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) override; - _NODISCARD bool CanLoadFromRaw() const override; - bool LoadFromRaw(const std::string& assetName, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const override; - }; -} +namespace IW3 { +class AssetLoaderRawFile final : public BasicAssetLoader { +public: + _NODISCARD void *CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) override; + _NODISCARD bool CanLoadFromRaw() const override; + bool LoadFromRaw(const std::string &assetName, ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager, Zone *zone) const override; +}; +} // namespace IW3 diff --git a/src/ObjLoading/Game/IW3/ObjLoaderIW3.cpp b/src/ObjLoading/Game/IW3/ObjLoaderIW3.cpp index 8320b26e0..d51b47a4d 100644 --- a/src/ObjLoading/Game/IW3/ObjLoaderIW3.cpp +++ b/src/ObjLoading/Game/IW3/ObjLoaderIW3.cpp @@ -1,186 +1,154 @@ #include "ObjLoaderIW3.h" -#include "Game/IW3/GameIW3.h" -#include "Game/IW3/GameAssetPoolIW3.h" -#include "ObjContainer/IPak/IPak.h" -#include "ObjLoading.h" #include "AssetLoaders/AssetLoaderGfxImage.h" #include "AssetLoaders/AssetLoaderRawFile.h" #include "AssetLoading/AssetLoadingManager.h" +#include "Game/IW3/GameAssetPoolIW3.h" +#include "Game/IW3/GameIW3.h" #include "Image/Dx9TextureLoader.h" -#include "Image/Texture.h" #include "Image/IwiLoader.h" #include "Image/IwiTypes.h" +#include "Image/Texture.h" +#include "ObjContainer/IPak/IPak.h" +#include "ObjLoading.h" using namespace IW3; -ObjLoader::ObjLoader() -{ -#define REGISTER_ASSET_LOADER(t) {auto l = std::make_unique(); m_asset_loaders_by_type[l->GetHandlingAssetType()] = std::move(l);} +ObjLoader::ObjLoader() { +#define REGISTER_ASSET_LOADER(t) \ + { \ + auto l = std::make_unique(); \ + m_asset_loaders_by_type[l->GetHandlingAssetType()] = std::move(l); \ + } #define BASIC_LOADER(assetType, assetClass) BasicAssetLoader - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_PHYSPRESET, PhysPreset)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_XANIMPARTS, XAnimParts)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_XMODEL, XModel)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_MATERIAL, Material)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_TECHNIQUE_SET, MaterialTechniqueSet)) - REGISTER_ASSET_LOADER(AssetLoaderGfxImage) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_SOUND, snd_alias_list_t)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_SOUND_CURVE, SndCurve)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_LOADED_SOUND, LoadedSound)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_CLIPMAP, clipMap_t)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_CLIPMAP_PVS, clipMap_t)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_COMWORLD, ComWorld)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_GAMEWORLD_SP, GameWorldSp)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_GAMEWORLD_MP, GameWorldMp)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_MAP_ENTS, MapEnts)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_GFXWORLD, GfxWorld)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_LIGHT_DEF, GfxLightDef)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_FONT, Font_s)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_MENULIST, MenuList)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_MENU, menuDef_t)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_LOCALIZE_ENTRY, LocalizeEntry)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_WEAPON, WeaponDef)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_SNDDRIVER_GLOBALS, SndDriverGlobals)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_FX, FxEffectDef)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_IMPACT_FX, FxImpactTable)) - REGISTER_ASSET_LOADER(AssetLoaderRawFile) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_STRINGTABLE, StringTable)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_PHYSPRESET, PhysPreset)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_XANIMPARTS, XAnimParts)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_XMODEL, XModel)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_MATERIAL, Material)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_TECHNIQUE_SET, MaterialTechniqueSet)) + REGISTER_ASSET_LOADER(AssetLoaderGfxImage) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_SOUND, snd_alias_list_t)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_SOUND_CURVE, SndCurve)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_LOADED_SOUND, LoadedSound)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_CLIPMAP, clipMap_t)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_CLIPMAP_PVS, clipMap_t)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_COMWORLD, ComWorld)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_GAMEWORLD_SP, GameWorldSp)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_GAMEWORLD_MP, GameWorldMp)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_MAP_ENTS, MapEnts)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_GFXWORLD, GfxWorld)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_LIGHT_DEF, GfxLightDef)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_FONT, Font_s)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_MENULIST, MenuList)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_MENU, menuDef_t)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_LOCALIZE_ENTRY, LocalizeEntry)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_WEAPON, WeaponDef)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_SNDDRIVER_GLOBALS, SndDriverGlobals)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_FX, FxEffectDef)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_IMPACT_FX, FxImpactTable)) + REGISTER_ASSET_LOADER(AssetLoaderRawFile) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_STRINGTABLE, StringTable)) #undef BASIC_LOADER #undef REGISTER_ASSET_LOADER } -bool ObjLoader::SupportsZone(Zone* zone) const -{ - return zone->m_game == &g_GameIW3; -} +bool ObjLoader::SupportsZone(Zone *zone) const { return zone->m_game == &g_GameIW3; } -bool ObjLoader::IsMpZone(Zone* zone) -{ - return zone->m_name.compare(0, 3, "mp_") == 0 - || zone->m_name.compare(zone->m_name.length() - 3, 3, "_mp") == 0; -} +bool ObjLoader::IsMpZone(Zone *zone) { return zone->m_name.compare(0, 3, "mp_") == 0 || zone->m_name.compare(zone->m_name.length() - 3, 3, "_mp") == 0; } -bool ObjLoader::IsZmZone(Zone* zone) -{ - return zone->m_name.compare(0, 3, "zm_") == 0 - || zone->m_name.compare(zone->m_name.length() - 3, 3, "_zm") == 0; -} +bool ObjLoader::IsZmZone(Zone *zone) { return zone->m_name.compare(0, 3, "zm_") == 0 || zone->m_name.compare(zone->m_name.length() - 3, 3, "_zm") == 0; } -void ObjLoader::LoadReferencedContainersForZone(ISearchPath* searchPath, Zone* zone) const -{ -} +void ObjLoader::LoadReferencedContainersForZone(ISearchPath *searchPath, Zone *zone) const {} -void ObjLoader::UnloadContainersOfZone(Zone* zone) const -{ -} +void ObjLoader::UnloadContainersOfZone(Zone *zone) const {} -void ObjLoader::LoadImageFromLoadDef(GfxImage* image, Zone* zone) -{ - const auto* loadDef = image->texture.loadDef; - Dx9TextureLoader textureLoader(zone->GetMemory()); +void ObjLoader::LoadImageFromLoadDef(GfxImage *image, Zone *zone) { + const auto *loadDef = image->texture.loadDef; + Dx9TextureLoader textureLoader(zone->GetMemory()); - textureLoader.Width(loadDef->dimensions[0]).Height(loadDef->dimensions[1]).Depth(loadDef->dimensions[2]); + textureLoader.Width(loadDef->dimensions[0]).Height(loadDef->dimensions[1]).Depth(loadDef->dimensions[2]); - if (loadDef->flags & iwi6::IMG_FLAG_VOLMAP) - textureLoader.Type(TextureType::T_3D); - else if (loadDef->flags & iwi6::IMG_FLAG_CUBEMAP) - textureLoader.Type(TextureType::T_CUBE); - else - textureLoader.Type(TextureType::T_2D); + if (loadDef->flags & iwi6::IMG_FLAG_VOLMAP) + textureLoader.Type(TextureType::T_3D); + else if (loadDef->flags & iwi6::IMG_FLAG_CUBEMAP) + textureLoader.Type(TextureType::T_CUBE); + else + textureLoader.Type(TextureType::T_2D); - textureLoader.Format(static_cast(loadDef->format)); - textureLoader.HasMipMaps(!(loadDef->flags & iwi6::IMG_FLAG_NOMIPMAPS)); - Texture* loadedTexture = textureLoader.LoadTexture(image->texture.loadDef->data); + textureLoader.Format(static_cast(loadDef->format)); + textureLoader.HasMipMaps(!(loadDef->flags & iwi6::IMG_FLAG_NOMIPMAPS)); + Texture *loadedTexture = textureLoader.LoadTexture(image->texture.loadDef->data); - if (loadedTexture != nullptr) - { - image->texture.texture = loadedTexture; - image->cardMemory.platform[0] = 0; + if (loadedTexture != nullptr) { + image->texture.texture = loadedTexture; + image->cardMemory.platform[0] = 0; - const auto textureMipCount = loadedTexture->GetMipMapCount(); - for (auto mipLevel = 0; mipLevel < textureMipCount; mipLevel++) - image->cardMemory.platform[0] += static_cast(loadedTexture->GetSizeOfMipLevel(mipLevel) * loadedTexture->GetFaceCount()); - } + const auto textureMipCount = loadedTexture->GetMipMapCount(); + for (auto mipLevel = 0; mipLevel < textureMipCount; mipLevel++) + image->cardMemory.platform[0] += static_cast(loadedTexture->GetSizeOfMipLevel(mipLevel) * loadedTexture->GetFaceCount()); + } } -void ObjLoader::LoadImageFromIwi(GfxImage* image, ISearchPath* searchPath, Zone* zone) -{ - Texture* loadedTexture = nullptr; - IwiLoader loader(zone->GetMemory()); +void ObjLoader::LoadImageFromIwi(GfxImage *image, ISearchPath *searchPath, Zone *zone) { + Texture *loadedTexture = nullptr; + IwiLoader loader(zone->GetMemory()); - const auto imageFileName = "images/" + std::string(image->name) + ".iwi"; + const auto imageFileName = "images/" + std::string(image->name) + ".iwi"; - { - const auto filePathImage = searchPath->Open(imageFileName); - if (filePathImage.IsOpen()) - { - loadedTexture = loader.LoadIwi(*filePathImage.m_stream); - } + { + const auto filePathImage = searchPath->Open(imageFileName); + if (filePathImage.IsOpen()) { + loadedTexture = loader.LoadIwi(*filePathImage.m_stream); } + } + + if (loadedTexture != nullptr) { + image->texture.texture = loadedTexture; + image->cardMemory.platform[0] = 0; + + const auto textureMipCount = loadedTexture->GetMipMapCount(); + for (auto mipLevel = 0; mipLevel < textureMipCount; mipLevel++) + image->cardMemory.platform[0] += static_cast(loadedTexture->GetSizeOfMipLevel(mipLevel) * loadedTexture->GetFaceCount()); + } else { + printf("Could not find data for image \"%s\"\n", image->name); + } +} - if (loadedTexture != nullptr) - { - image->texture.texture = loadedTexture; - image->cardMemory.platform[0] = 0; +void ObjLoader::LoadImageData(ISearchPath *searchPath, Zone *zone) { + auto *assetPool = dynamic_cast(zone->m_pools.get()); - const auto textureMipCount = loadedTexture->GetMipMapCount(); - for (auto mipLevel = 0; mipLevel < textureMipCount; mipLevel++) - image->cardMemory.platform[0] += static_cast(loadedTexture->GetSizeOfMipLevel(mipLevel) * loadedTexture->GetFaceCount()); - } - else - { - printf("Could not find data for image \"%s\"\n", image->name); - } -} + if (assetPool && assetPool->m_image != nullptr) { + for (auto *imageEntry : *assetPool->m_image) { + auto *image = imageEntry->Asset(); + + if (image->cardMemory.platform[0] > 0) { + continue; + } -void ObjLoader::LoadImageData(ISearchPath* searchPath, Zone* zone) -{ - auto* assetPool = dynamic_cast(zone->m_pools.get()); - - if (assetPool && assetPool->m_image != nullptr) - { - for (auto* imageEntry : *assetPool->m_image) - { - auto* image = imageEntry->Asset(); - - if (image->cardMemory.platform[0] > 0) - { - continue; - } - - // Do not load linked assets - if (image->name && image->name[0] == ',') - { - continue; - } - - if (image->texture.loadDef && image->texture.loadDef->resourceSize > 0) - { - LoadImageFromLoadDef(image, zone); - } - else - { - LoadImageFromIwi(image, searchPath, zone); - } - } + // Do not load linked assets + if (image->name && image->name[0] == ',') { + continue; + } + + if (image->texture.loadDef && image->texture.loadDef->resourceSize > 0) { + LoadImageFromLoadDef(image, zone); + } else { + LoadImageFromIwi(image, searchPath, zone); + } } + } } -void ObjLoader::LoadObjDataForZone(ISearchPath* searchPath, Zone* zone) const -{ - LoadImageData(searchPath, zone); -} +void ObjLoader::LoadObjDataForZone(ISearchPath *searchPath, Zone *zone) const { LoadImageData(searchPath, zone); } -bool ObjLoader::LoadAssetForZone(AssetLoadingContext* context, const asset_type_t assetType, const std::string& assetName) const -{ - AssetLoadingManager assetLoadingManager(m_asset_loaders_by_type, *context); - return assetLoadingManager.LoadAssetFromLoader(assetType, assetName); +bool ObjLoader::LoadAssetForZone(AssetLoadingContext *context, const asset_type_t assetType, const std::string &assetName) const { + AssetLoadingManager assetLoadingManager(m_asset_loaders_by_type, *context); + return assetLoadingManager.LoadAssetFromLoader(assetType, assetName); } -void ObjLoader::FinalizeAssetsForZone(AssetLoadingContext* context) const -{ - for (const auto& [type, loader] : m_asset_loaders_by_type) - loader->FinalizeAssetsForZone(context); +void ObjLoader::FinalizeAssetsForZone(AssetLoadingContext *context) const { + for (const auto &[type, loader] : m_asset_loaders_by_type) + loader->FinalizeAssetsForZone(context); } \ No newline at end of file diff --git a/src/ObjLoading/Game/IW3/ObjLoaderIW3.h b/src/ObjLoading/Game/IW3/ObjLoaderIW3.h index 1e65e614f..d45f6e7dd 100644 --- a/src/ObjLoading/Game/IW3/ObjLoaderIW3.h +++ b/src/ObjLoading/Game/IW3/ObjLoaderIW3.h @@ -3,35 +3,33 @@ #include #include -#include "IObjLoader.h" #include "AssetLoading/IAssetLoader.h" -#include "SearchPath/ISearchPath.h" #include "Game/IW3/IW3.h" +#include "IObjLoader.h" +#include "SearchPath/ISearchPath.h" -namespace IW3 -{ - class ObjLoader final : public IObjLoader - { - std::map> m_asset_loaders_by_type; +namespace IW3 { +class ObjLoader final : public IObjLoader { + std::map> m_asset_loaders_by_type; - static void LoadImageFromIwi(GfxImage* image, ISearchPath* searchPath, Zone* zone); - static void LoadImageFromLoadDef(GfxImage* image, Zone* zone); - static void LoadImageData(ISearchPath* searchPath, Zone* zone); + static void LoadImageFromIwi(GfxImage *image, ISearchPath *searchPath, Zone *zone); + static void LoadImageFromLoadDef(GfxImage *image, Zone *zone); + static void LoadImageData(ISearchPath *searchPath, Zone *zone); - static bool IsMpZone(Zone* zone); - static bool IsZmZone(Zone* zone); + static bool IsMpZone(Zone *zone); + static bool IsZmZone(Zone *zone); - public: - ObjLoader(); +public: + ObjLoader(); - bool SupportsZone(Zone* zone) const override; + bool SupportsZone(Zone *zone) const override; - void LoadReferencedContainersForZone(ISearchPath* searchPath, Zone* zone) const override; - void UnloadContainersOfZone(Zone* zone) const override; + void LoadReferencedContainersForZone(ISearchPath *searchPath, Zone *zone) const override; + void UnloadContainersOfZone(Zone *zone) const override; - void LoadObjDataForZone(ISearchPath* searchPath, Zone* zone) const override; + void LoadObjDataForZone(ISearchPath *searchPath, Zone *zone) const override; - bool LoadAssetForZone(AssetLoadingContext* context, asset_type_t assetType, const std::string& assetName) const override; - void FinalizeAssetsForZone(AssetLoadingContext* context) const override; - }; -} + bool LoadAssetForZone(AssetLoadingContext *context, asset_type_t assetType, const std::string &assetName) const override; + void FinalizeAssetsForZone(AssetLoadingContext *context) const override; +}; +} // namespace IW3 diff --git a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderAddonMapEnts.cpp b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderAddonMapEnts.cpp index 6c0c2ea65..2776a2591 100644 --- a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderAddonMapEnts.cpp +++ b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderAddonMapEnts.cpp @@ -2,16 +2,15 @@ #include -#include "ObjLoading.h" #include "Game/IW4/IW4.h" +#include "ObjLoading.h" #include "Pool/GlobalAssetPool.h" using namespace IW4; -void* AssetLoaderAddonMapEnts::CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) -{ - auto* addonMapEnts = memory->Create(); - memset(addonMapEnts, 0, sizeof(AddonMapEnts)); - addonMapEnts->name = memory->Dup(assetName.c_str()); - return addonMapEnts; +void *AssetLoaderAddonMapEnts::CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) { + auto *addonMapEnts = memory->Create(); + memset(addonMapEnts, 0, sizeof(AddonMapEnts)); + addonMapEnts->name = memory->Dup(assetName.c_str()); + return addonMapEnts; } diff --git a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderAddonMapEnts.h b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderAddonMapEnts.h index 20c1be55d..90acf1156 100644 --- a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderAddonMapEnts.h +++ b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderAddonMapEnts.h @@ -1,14 +1,12 @@ #pragma once -#include "Game/IW4/IW4.h" #include "AssetLoading/BasicAssetLoader.h" +#include "Game/IW4/IW4.h" #include "SearchPath/ISearchPath.h" -namespace IW4 -{ - class AssetLoaderAddonMapEnts final : public BasicAssetLoader - { - public: - _NODISCARD void* CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) override; - }; -} +namespace IW4 { +class AssetLoaderAddonMapEnts final : public BasicAssetLoader { +public: + _NODISCARD void *CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) override; +}; +} // namespace IW4 diff --git a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderClipMap.cpp b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderClipMap.cpp index 84730867f..0bf7b8dc6 100644 --- a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderClipMap.cpp +++ b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderClipMap.cpp @@ -2,26 +2,19 @@ #include -#include "ObjLoading.h" #include "Game/IW4/IW4.h" +#include "ObjLoading.h" #include "Pool/GlobalAssetPool.h" using namespace IW4; -void* AssetLoaderClipMap::CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) -{ - auto* clipMap = memory->Create(); - memset(clipMap, 0, sizeof(clipMap_t)); - clipMap->name = memory->Dup(assetName.c_str()); - return clipMap; +void *AssetLoaderClipMap::CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) { + auto *clipMap = memory->Create(); + memset(clipMap, 0, sizeof(clipMap_t)); + clipMap->name = memory->Dup(assetName.c_str()); + return clipMap; } -asset_type_t AssetLoaderClipMapSp::GetHandlingAssetType() const -{ - return ASSET_TYPE_CLIPMAP_SP; -} +asset_type_t AssetLoaderClipMapSp::GetHandlingAssetType() const { return ASSET_TYPE_CLIPMAP_SP; } -asset_type_t AssetLoaderClipMapMp::GetHandlingAssetType() const -{ - return ASSET_TYPE_CLIPMAP_MP; -} +asset_type_t AssetLoaderClipMapMp::GetHandlingAssetType() const { return ASSET_TYPE_CLIPMAP_MP; } diff --git a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderClipMap.h b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderClipMap.h index 4e730971f..a49e277a5 100644 --- a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderClipMap.h +++ b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderClipMap.h @@ -1,25 +1,21 @@ #pragma once -#include "Game/IW4/IW4.h" #include "AssetLoading/BasicAssetLoader.h" +#include "Game/IW4/IW4.h" #include "SearchPath/ISearchPath.h" -namespace IW4 -{ - class AssetLoaderClipMap : public BasicAssetLoaderWithoutType - { - _NODISCARD void* CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) override; - }; +namespace IW4 { +class AssetLoaderClipMap : public BasicAssetLoaderWithoutType { + _NODISCARD void *CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) override; +}; - class AssetLoaderClipMapSp final : public AssetLoaderClipMap - { - public: - _NODISCARD asset_type_t GetHandlingAssetType() const override; - }; +class AssetLoaderClipMapSp final : public AssetLoaderClipMap { +public: + _NODISCARD asset_type_t GetHandlingAssetType() const override; +}; - class AssetLoaderClipMapMp final : public AssetLoaderClipMap - { - public: - _NODISCARD asset_type_t GetHandlingAssetType() const override; - }; -} +class AssetLoaderClipMapMp final : public AssetLoaderClipMap { +public: + _NODISCARD asset_type_t GetHandlingAssetType() const override; +}; +} // namespace IW4 diff --git a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderComWorld.cpp b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderComWorld.cpp index 931b72e46..28073d3c9 100644 --- a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderComWorld.cpp +++ b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderComWorld.cpp @@ -2,16 +2,15 @@ #include -#include "ObjLoading.h" #include "Game/IW4/IW4.h" +#include "ObjLoading.h" #include "Pool/GlobalAssetPool.h" using namespace IW4; -void* AssetLoaderComWorld::CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) -{ - auto* comWorld = memory->Create(); - memset(comWorld, 0, sizeof(ComWorld)); - comWorld->name = memory->Dup(assetName.c_str()); - return comWorld; +void *AssetLoaderComWorld::CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) { + auto *comWorld = memory->Create(); + memset(comWorld, 0, sizeof(ComWorld)); + comWorld->name = memory->Dup(assetName.c_str()); + return comWorld; } diff --git a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderComWorld.h b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderComWorld.h index 3490a46a6..c64e5727f 100644 --- a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderComWorld.h +++ b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderComWorld.h @@ -1,14 +1,12 @@ #pragma once -#include "Game/IW4/IW4.h" #include "AssetLoading/BasicAssetLoader.h" +#include "Game/IW4/IW4.h" #include "SearchPath/ISearchPath.h" -namespace IW4 -{ - class AssetLoaderComWorld final : public BasicAssetLoader - { - public: - _NODISCARD void* CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) override; - }; -} +namespace IW4 { +class AssetLoaderComWorld final : public BasicAssetLoader { +public: + _NODISCARD void *CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) override; +}; +} // namespace IW4 diff --git a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderFont.cpp b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderFont.cpp index 8accee5dc..892cbc011 100644 --- a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderFont.cpp +++ b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderFont.cpp @@ -2,16 +2,15 @@ #include -#include "ObjLoading.h" #include "Game/IW4/IW4.h" +#include "ObjLoading.h" #include "Pool/GlobalAssetPool.h" using namespace IW4; -void* AssetLoaderFont::CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) -{ - auto* font = memory->Create(); - memset(font, 0, sizeof(Font_s)); - font->fontName = memory->Dup(assetName.c_str()); - return font; +void *AssetLoaderFont::CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) { + auto *font = memory->Create(); + memset(font, 0, sizeof(Font_s)); + font->fontName = memory->Dup(assetName.c_str()); + return font; } diff --git a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderFont.h b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderFont.h index 4ed08beea..e07db8dcc 100644 --- a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderFont.h +++ b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderFont.h @@ -1,14 +1,12 @@ #pragma once -#include "Game/IW4/IW4.h" #include "AssetLoading/BasicAssetLoader.h" +#include "Game/IW4/IW4.h" #include "SearchPath/ISearchPath.h" -namespace IW4 -{ - class AssetLoaderFont final : public BasicAssetLoader - { - public: - _NODISCARD void* CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) override; - }; -} +namespace IW4 { +class AssetLoaderFont final : public BasicAssetLoader { +public: + _NODISCARD void *CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) override; +}; +} // namespace IW4 diff --git a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderFx.cpp b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderFx.cpp index 5c12e978a..4213b6186 100644 --- a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderFx.cpp +++ b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderFx.cpp @@ -2,16 +2,15 @@ #include -#include "ObjLoading.h" #include "Game/IW4/IW4.h" +#include "ObjLoading.h" #include "Pool/GlobalAssetPool.h" using namespace IW4; -void* AssetLoaderFx::CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) -{ - auto* fx = memory->Create(); - memset(fx, 0, sizeof(FxEffectDef)); - fx->name = memory->Dup(assetName.c_str()); - return fx; +void *AssetLoaderFx::CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) { + auto *fx = memory->Create(); + memset(fx, 0, sizeof(FxEffectDef)); + fx->name = memory->Dup(assetName.c_str()); + return fx; } diff --git a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderFx.h b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderFx.h index b76aa0eb3..663c4bce1 100644 --- a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderFx.h +++ b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderFx.h @@ -1,14 +1,12 @@ #pragma once -#include "Game/IW4/IW4.h" #include "AssetLoading/BasicAssetLoader.h" +#include "Game/IW4/IW4.h" #include "SearchPath/ISearchPath.h" -namespace IW4 -{ - class AssetLoaderFx final : public BasicAssetLoader - { - public: - _NODISCARD void* CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) override; - }; -} +namespace IW4 { +class AssetLoaderFx final : public BasicAssetLoader { +public: + _NODISCARD void *CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) override; +}; +} // namespace IW4 diff --git a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderFxImpactTable.cpp b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderFxImpactTable.cpp index 59b282e5f..41147e396 100644 --- a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderFxImpactTable.cpp +++ b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderFxImpactTable.cpp @@ -2,16 +2,15 @@ #include -#include "ObjLoading.h" #include "Game/IW4/IW4.h" +#include "ObjLoading.h" #include "Pool/GlobalAssetPool.h" using namespace IW4; -void* AssetLoaderFxImpactTable::CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) -{ - auto* fxImpactTable = memory->Create(); - memset(fxImpactTable, 0, sizeof(FxImpactTable)); - fxImpactTable->name = memory->Dup(assetName.c_str()); - return fxImpactTable; +void *AssetLoaderFxImpactTable::CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) { + auto *fxImpactTable = memory->Create(); + memset(fxImpactTable, 0, sizeof(FxImpactTable)); + fxImpactTable->name = memory->Dup(assetName.c_str()); + return fxImpactTable; } diff --git a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderFxImpactTable.h b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderFxImpactTable.h index 5ab9bb86b..55bab82cd 100644 --- a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderFxImpactTable.h +++ b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderFxImpactTable.h @@ -1,14 +1,12 @@ #pragma once -#include "Game/IW4/IW4.h" #include "AssetLoading/BasicAssetLoader.h" +#include "Game/IW4/IW4.h" #include "SearchPath/ISearchPath.h" -namespace IW4 -{ - class AssetLoaderFxImpactTable final : public BasicAssetLoader - { - public: - _NODISCARD void* CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) override; - }; -} +namespace IW4 { +class AssetLoaderFxImpactTable final : public BasicAssetLoader { +public: + _NODISCARD void *CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) override; +}; +} // namespace IW4 diff --git a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderFxWorld.cpp b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderFxWorld.cpp index 945a84cc7..a8ca31f2a 100644 --- a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderFxWorld.cpp +++ b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderFxWorld.cpp @@ -2,16 +2,15 @@ #include -#include "ObjLoading.h" #include "Game/IW4/IW4.h" +#include "ObjLoading.h" #include "Pool/GlobalAssetPool.h" using namespace IW4; -void* AssetLoaderFxWorld::CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) -{ - auto* fxWorld = memory->Create(); - memset(fxWorld, 0, sizeof(FxWorld)); - fxWorld->name = memory->Dup(assetName.c_str()); - return fxWorld; +void *AssetLoaderFxWorld::CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) { + auto *fxWorld = memory->Create(); + memset(fxWorld, 0, sizeof(FxWorld)); + fxWorld->name = memory->Dup(assetName.c_str()); + return fxWorld; } diff --git a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderFxWorld.h b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderFxWorld.h index e914e7419..4952b6f1b 100644 --- a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderFxWorld.h +++ b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderFxWorld.h @@ -1,14 +1,12 @@ #pragma once -#include "Game/IW4/IW4.h" #include "AssetLoading/BasicAssetLoader.h" +#include "Game/IW4/IW4.h" #include "SearchPath/ISearchPath.h" -namespace IW4 -{ - class AssetLoaderFxWorld final : public BasicAssetLoader - { - public: - _NODISCARD void* CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) override; - }; -} +namespace IW4 { +class AssetLoaderFxWorld final : public BasicAssetLoader { +public: + _NODISCARD void *CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) override; +}; +} // namespace IW4 diff --git a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderGameWorldMp.cpp b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderGameWorldMp.cpp index b2100227b..72277e0f3 100644 --- a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderGameWorldMp.cpp +++ b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderGameWorldMp.cpp @@ -2,16 +2,15 @@ #include -#include "ObjLoading.h" #include "Game/IW4/IW4.h" +#include "ObjLoading.h" #include "Pool/GlobalAssetPool.h" using namespace IW4; -void* AssetLoaderGameWorldMp::CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) -{ - auto* gameWorld = memory->Create(); - memset(gameWorld, 0, sizeof(GameWorldMp)); - gameWorld->name = memory->Dup(assetName.c_str()); - return gameWorld; +void *AssetLoaderGameWorldMp::CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) { + auto *gameWorld = memory->Create(); + memset(gameWorld, 0, sizeof(GameWorldMp)); + gameWorld->name = memory->Dup(assetName.c_str()); + return gameWorld; } diff --git a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderGameWorldMp.h b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderGameWorldMp.h index 3fafb2253..a997febea 100644 --- a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderGameWorldMp.h +++ b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderGameWorldMp.h @@ -1,14 +1,12 @@ #pragma once -#include "Game/IW4/IW4.h" #include "AssetLoading/BasicAssetLoader.h" +#include "Game/IW4/IW4.h" #include "SearchPath/ISearchPath.h" -namespace IW4 -{ - class AssetLoaderGameWorldMp final : public BasicAssetLoader - { - public: - _NODISCARD void* CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) override; - }; -} +namespace IW4 { +class AssetLoaderGameWorldMp final : public BasicAssetLoader { +public: + _NODISCARD void *CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) override; +}; +} // namespace IW4 diff --git a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderGameWorldSp.cpp b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderGameWorldSp.cpp index 82788b635..4bb6572a8 100644 --- a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderGameWorldSp.cpp +++ b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderGameWorldSp.cpp @@ -2,16 +2,15 @@ #include -#include "ObjLoading.h" #include "Game/IW4/IW4.h" +#include "ObjLoading.h" #include "Pool/GlobalAssetPool.h" using namespace IW4; -void* AssetLoaderGameWorldSp::CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) -{ - auto* gameWorld = memory->Create(); - memset(gameWorld, 0, sizeof(GameWorldSp)); - gameWorld->name = memory->Dup(assetName.c_str()); - return gameWorld; +void *AssetLoaderGameWorldSp::CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) { + auto *gameWorld = memory->Create(); + memset(gameWorld, 0, sizeof(GameWorldSp)); + gameWorld->name = memory->Dup(assetName.c_str()); + return gameWorld; } diff --git a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderGameWorldSp.h b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderGameWorldSp.h index e0d03d16d..f44f63820 100644 --- a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderGameWorldSp.h +++ b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderGameWorldSp.h @@ -1,14 +1,12 @@ #pragma once -#include "Game/IW4/IW4.h" #include "AssetLoading/BasicAssetLoader.h" +#include "Game/IW4/IW4.h" #include "SearchPath/ISearchPath.h" -namespace IW4 -{ - class AssetLoaderGameWorldSp final : public BasicAssetLoader - { - public: - _NODISCARD void* CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) override; - }; -} +namespace IW4 { +class AssetLoaderGameWorldSp final : public BasicAssetLoader { +public: + _NODISCARD void *CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) override; +}; +} // namespace IW4 diff --git a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderGfxImage.cpp b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderGfxImage.cpp index 86d1ac258..8fa6546b9 100644 --- a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderGfxImage.cpp +++ b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderGfxImage.cpp @@ -2,16 +2,15 @@ #include -#include "ObjLoading.h" #include "Game/IW4/IW4.h" +#include "ObjLoading.h" #include "Pool/GlobalAssetPool.h" using namespace IW4; -void* AssetLoaderGfxImage::CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) -{ - auto* image = memory->Create(); - memset(image, 0, sizeof(GfxImage)); - image->name = memory->Dup(assetName.c_str()); - return image; +void *AssetLoaderGfxImage::CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) { + auto *image = memory->Create(); + memset(image, 0, sizeof(GfxImage)); + image->name = memory->Dup(assetName.c_str()); + return image; } diff --git a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderGfxImage.h b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderGfxImage.h index 911fe22d5..d6f7c0a64 100644 --- a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderGfxImage.h +++ b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderGfxImage.h @@ -1,14 +1,12 @@ #pragma once -#include "Game/IW4/IW4.h" #include "AssetLoading/BasicAssetLoader.h" +#include "Game/IW4/IW4.h" #include "SearchPath/ISearchPath.h" -namespace IW4 -{ - class AssetLoaderGfxImage final : public BasicAssetLoader - { - public: - _NODISCARD void* CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) override; - }; -} +namespace IW4 { +class AssetLoaderGfxImage final : public BasicAssetLoader { +public: + _NODISCARD void *CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) override; +}; +} // namespace IW4 diff --git a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderGfxLightDef.cpp b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderGfxLightDef.cpp index aedfd2d90..2a881ec8c 100644 --- a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderGfxLightDef.cpp +++ b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderGfxLightDef.cpp @@ -4,68 +4,62 @@ #include #include -#include "ObjLoading.h" #include "Game/IW4/IW4.h" +#include "ObjLoading.h" #include "Pool/GlobalAssetPool.h" using namespace IW4; -std::string AssetLoaderGfxLightDef::GetAssetFilename(const std::string& assetName) -{ - std::ostringstream ss; +std::string AssetLoaderGfxLightDef::GetAssetFilename(const std::string &assetName) { + std::ostringstream ss; - ss << "lights/" << assetName; + ss << "lights/" << assetName; - return ss.str(); + return ss.str(); } -void* AssetLoaderGfxLightDef::CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) -{ - auto* lightDef = memory->Create(); - memset(lightDef, 0, sizeof(GfxLightDef)); - lightDef->name = memory->Dup(assetName.c_str()); - return lightDef; +void *AssetLoaderGfxLightDef::CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) { + auto *lightDef = memory->Create(); + memset(lightDef, 0, sizeof(GfxLightDef)); + lightDef->name = memory->Dup(assetName.c_str()); + return lightDef; } -bool AssetLoaderGfxLightDef::CanLoadFromRaw() const -{ - return true; -} +bool AssetLoaderGfxLightDef::CanLoadFromRaw() const { return true; } -bool AssetLoaderGfxLightDef::LoadFromRaw(const std::string& assetName, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const -{ - const auto filename = GetAssetFilename(assetName); - const auto file = searchPath->Open(filename); - if (!file.IsOpen()) - return false; +bool AssetLoaderGfxLightDef::LoadFromRaw(const std::string &assetName, ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager, + Zone *zone) const { + const auto filename = GetAssetFilename(assetName); + const auto file = searchPath->Open(filename); + if (!file.IsOpen()) + return false; - const auto imageNameSize = file.m_length - sizeof(char) - sizeof(char); - if (imageNameSize < 0 || imageNameSize > MAX_IMAGE_NAME_SIZE) - return false; + const auto imageNameSize = file.m_length - sizeof(char) - sizeof(char); + if (imageNameSize < 0 || imageNameSize > MAX_IMAGE_NAME_SIZE) + return false; - std::string imageName(static_cast(imageNameSize), '\0'); + std::string imageName(static_cast(imageNameSize), '\0'); - int8_t samplerState; - int8_t lmapLookupStart; - file.m_stream->read(reinterpret_cast(&samplerState), sizeof(int8_t)); - file.m_stream->read(&imageName[0], static_cast(imageNameSize)); - file.m_stream->read(reinterpret_cast(&lmapLookupStart), sizeof(int8_t)); + int8_t samplerState; + int8_t lmapLookupStart; + file.m_stream->read(reinterpret_cast(&samplerState), sizeof(int8_t)); + file.m_stream->read(&imageName[0], static_cast(imageNameSize)); + file.m_stream->read(reinterpret_cast(&lmapLookupStart), sizeof(int8_t)); - auto* imageDependency = reinterpret_cast*>(manager->LoadDependency(ASSET_TYPE_IMAGE, imageName)); + auto *imageDependency = reinterpret_cast *>(manager->LoadDependency(ASSET_TYPE_IMAGE, imageName)); - if(!imageDependency) - { - std::cerr << "Could not load GfxLightDef \"" << assetName << "\" due to missing image \"" << imageName << "\"\n"; - return false; - } + if (!imageDependency) { + std::cerr << "Could not load GfxLightDef \"" << assetName << "\" due to missing image \"" << imageName << "\"\n"; + return false; + } - auto* lightDef = memory->Create(); - lightDef->name = memory->Dup(assetName.c_str()); - lightDef->attenuation.samplerState = samplerState; - lightDef->attenuation.image = imageDependency->Asset(); - lightDef->lmapLookupStart = static_cast(static_cast(lmapLookupStart)); + auto *lightDef = memory->Create(); + lightDef->name = memory->Dup(assetName.c_str()); + lightDef->attenuation.samplerState = samplerState; + lightDef->attenuation.image = imageDependency->Asset(); + lightDef->lmapLookupStart = static_cast(static_cast(lmapLookupStart)); - manager->AddAsset(ASSET_TYPE_LIGHT_DEF, assetName, lightDef); + manager->AddAsset(ASSET_TYPE_LIGHT_DEF, assetName, lightDef); - return true; + return true; } diff --git a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderGfxLightDef.h b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderGfxLightDef.h index e593fc3e7..af54f042b 100644 --- a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderGfxLightDef.h +++ b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderGfxLightDef.h @@ -1,20 +1,18 @@ #pragma once -#include "Game/IW4/IW4.h" #include "AssetLoading/BasicAssetLoader.h" +#include "Game/IW4/IW4.h" #include "SearchPath/ISearchPath.h" -namespace IW4 -{ - class AssetLoaderGfxLightDef final : public BasicAssetLoader - { - static constexpr auto MAX_IMAGE_NAME_SIZE = 0x800; +namespace IW4 { +class AssetLoaderGfxLightDef final : public BasicAssetLoader { + static constexpr auto MAX_IMAGE_NAME_SIZE = 0x800; - static std::string GetAssetFilename(const std::string& assetName); + static std::string GetAssetFilename(const std::string &assetName); - public: - _NODISCARD void* CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) override; - _NODISCARD bool CanLoadFromRaw() const override; - bool LoadFromRaw(const std::string& assetName, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const override; - }; -} +public: + _NODISCARD void *CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) override; + _NODISCARD bool CanLoadFromRaw() const override; + bool LoadFromRaw(const std::string &assetName, ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager, Zone *zone) const override; +}; +} // namespace IW4 diff --git a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderGfxWorld.cpp b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderGfxWorld.cpp index 8676b1d7e..846068edb 100644 --- a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderGfxWorld.cpp +++ b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderGfxWorld.cpp @@ -2,16 +2,15 @@ #include -#include "ObjLoading.h" #include "Game/IW4/IW4.h" +#include "ObjLoading.h" #include "Pool/GlobalAssetPool.h" using namespace IW4; -void* AssetLoaderGfxWorld::CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) -{ - auto* gfxWorld = memory->Create(); - memset(gfxWorld, 0, sizeof(GfxWorld)); - gfxWorld->name = memory->Dup(assetName.c_str()); - return gfxWorld; +void *AssetLoaderGfxWorld::CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) { + auto *gfxWorld = memory->Create(); + memset(gfxWorld, 0, sizeof(GfxWorld)); + gfxWorld->name = memory->Dup(assetName.c_str()); + return gfxWorld; } diff --git a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderGfxWorld.h b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderGfxWorld.h index ae6ec95f7..96908d667 100644 --- a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderGfxWorld.h +++ b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderGfxWorld.h @@ -1,14 +1,12 @@ #pragma once -#include "Game/IW4/IW4.h" #include "AssetLoading/BasicAssetLoader.h" +#include "Game/IW4/IW4.h" #include "SearchPath/ISearchPath.h" -namespace IW4 -{ - class AssetLoaderGfxWorld final : public BasicAssetLoader - { - public: - _NODISCARD void* CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) override; - }; -} +namespace IW4 { +class AssetLoaderGfxWorld final : public BasicAssetLoader { +public: + _NODISCARD void *CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) override; +}; +} // namespace IW4 diff --git a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderLeaderboard.cpp b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderLeaderboard.cpp index 49e965be6..979a1b7dc 100644 --- a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderLeaderboard.cpp +++ b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderLeaderboard.cpp @@ -2,16 +2,15 @@ #include -#include "ObjLoading.h" #include "Game/IW4/IW4.h" +#include "ObjLoading.h" #include "Pool/GlobalAssetPool.h" using namespace IW4; -void* AssetLoaderLeaderboard::CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) -{ - auto* leaderboard = memory->Create(); - memset(leaderboard, 0, sizeof(LeaderboardDef)); - leaderboard->name = memory->Dup(assetName.c_str()); - return leaderboard; +void *AssetLoaderLeaderboard::CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) { + auto *leaderboard = memory->Create(); + memset(leaderboard, 0, sizeof(LeaderboardDef)); + leaderboard->name = memory->Dup(assetName.c_str()); + return leaderboard; } diff --git a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderLeaderboard.h b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderLeaderboard.h index f10497e4f..a44594f4e 100644 --- a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderLeaderboard.h +++ b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderLeaderboard.h @@ -1,14 +1,12 @@ #pragma once -#include "Game/IW4/IW4.h" #include "AssetLoading/BasicAssetLoader.h" +#include "Game/IW4/IW4.h" #include "SearchPath/ISearchPath.h" -namespace IW4 -{ - class AssetLoaderLeaderboard final : public BasicAssetLoader - { - public: - _NODISCARD void* CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) override; - }; -} +namespace IW4 { +class AssetLoaderLeaderboard final : public BasicAssetLoader { +public: + _NODISCARD void *CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) override; +}; +} // namespace IW4 diff --git a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderLoadedSound.cpp b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderLoadedSound.cpp index e0d509478..4f09becbc 100644 --- a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderLoadedSound.cpp +++ b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderLoadedSound.cpp @@ -2,16 +2,15 @@ #include -#include "ObjLoading.h" #include "Game/IW4/IW4.h" +#include "ObjLoading.h" #include "Pool/GlobalAssetPool.h" using namespace IW4; -void* AssetLoaderLoadedSound::CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) -{ - auto* loadedSound = memory->Create(); - memset(loadedSound, 0, sizeof(LoadedSound)); - loadedSound->name = memory->Dup(assetName.c_str()); - return loadedSound; +void *AssetLoaderLoadedSound::CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) { + auto *loadedSound = memory->Create(); + memset(loadedSound, 0, sizeof(LoadedSound)); + loadedSound->name = memory->Dup(assetName.c_str()); + return loadedSound; } diff --git a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderLoadedSound.h b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderLoadedSound.h index 14a0e2bd1..3f4d6ce4b 100644 --- a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderLoadedSound.h +++ b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderLoadedSound.h @@ -1,14 +1,12 @@ #pragma once -#include "Game/IW4/IW4.h" #include "AssetLoading/BasicAssetLoader.h" +#include "Game/IW4/IW4.h" #include "SearchPath/ISearchPath.h" -namespace IW4 -{ - class AssetLoaderLoadedSound final : public BasicAssetLoader - { - public: - _NODISCARD void* CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) override; - }; -} +namespace IW4 { +class AssetLoaderLoadedSound final : public BasicAssetLoader { +public: + _NODISCARD void *CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) override; +}; +} // namespace IW4 diff --git a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderLocalizeEntry.cpp b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderLocalizeEntry.cpp index fee16bf76..80ee297e8 100644 --- a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderLocalizeEntry.cpp +++ b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderLocalizeEntry.cpp @@ -7,45 +7,35 @@ using namespace IW4; -XAssetInfoGeneric* AssetLoaderLocalizeEntry::LoadFromGlobalAssetPools(const std::string& assetName) const -{ - return nullptr; -} +XAssetInfoGeneric *AssetLoaderLocalizeEntry::LoadFromGlobalAssetPools(const std::string &assetName) const { return nullptr; } -void* AssetLoaderLocalizeEntry::CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) -{ - return nullptr; -} +void *AssetLoaderLocalizeEntry::CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) { return nullptr; } -bool AssetLoaderLocalizeEntry::CanLoadFromRaw() const -{ - return true; -} +bool AssetLoaderLocalizeEntry::CanLoadFromRaw() const { return true; } -bool AssetLoaderLocalizeEntry::LoadFromRaw(const std::string& assetName, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const -{ - std::string fileName; - { - std::ostringstream str; - str << LocalizeCommon::GetNameOfLanguage(zone->m_language) << "/localizedstrings/" << assetName << ".str"; - fileName = str.str(); - } +bool AssetLoaderLocalizeEntry::LoadFromRaw(const std::string &assetName, ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager, + Zone *zone) const { + std::string fileName; + { + std::ostringstream str; + str << LocalizeCommon::GetNameOfLanguage(zone->m_language) << "/localizedstrings/" << assetName << ".str"; + fileName = str.str(); + } - const auto file = searchPath->Open(fileName); - if (!file.IsOpen()) - return false; + const auto file = searchPath->Open(fileName); + if (!file.IsOpen()) + return false; - LocalizeFileReader reader(*file.m_stream, assetName, zone->m_language); - const auto localizeEntries = reader.ReadLocalizeFile(); + LocalizeFileReader reader(*file.m_stream, assetName, zone->m_language); + const auto localizeEntries = reader.ReadLocalizeFile(); - for (const auto& entry : localizeEntries) - { - auto* localizeEntry = memory->Create(); - localizeEntry->name = memory->Dup(entry.m_key.c_str()); - localizeEntry->value = memory->Dup(entry.m_value.c_str()); + for (const auto &entry : localizeEntries) { + auto *localizeEntry = memory->Create(); + localizeEntry->name = memory->Dup(entry.m_key.c_str()); + localizeEntry->value = memory->Dup(entry.m_value.c_str()); - manager->AddAsset(ASSET_TYPE_LOCALIZE_ENTRY, entry.m_key, localizeEntry); - } + manager->AddAsset(ASSET_TYPE_LOCALIZE_ENTRY, entry.m_key, localizeEntry); + } - return true; + return true; } diff --git a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderLocalizeEntry.h b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderLocalizeEntry.h index 55f8c35a9..18e8c25f6 100644 --- a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderLocalizeEntry.h +++ b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderLocalizeEntry.h @@ -1,17 +1,15 @@ #pragma once -#include "Game/IW4/IW4.h" #include "AssetLoading/BasicAssetLoader.h" #include "AssetLoading/IAssetLoadingManager.h" +#include "Game/IW4/IW4.h" #include "SearchPath/ISearchPath.h" -namespace IW4 -{ - class AssetLoaderLocalizeEntry final : public BasicAssetLoader - { - public: - _NODISCARD XAssetInfoGeneric* LoadFromGlobalAssetPools(const std::string& assetName) const override; - _NODISCARD void* CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) override; - _NODISCARD bool CanLoadFromRaw() const override; - bool LoadFromRaw(const std::string& assetName, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const override; - }; -} +namespace IW4 { +class AssetLoaderLocalizeEntry final : public BasicAssetLoader { +public: + _NODISCARD XAssetInfoGeneric *LoadFromGlobalAssetPools(const std::string &assetName) const override; + _NODISCARD void *CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) override; + _NODISCARD bool CanLoadFromRaw() const override; + bool LoadFromRaw(const std::string &assetName, ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager, Zone *zone) const override; +}; +} // namespace IW4 diff --git a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderMapEnts.cpp b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderMapEnts.cpp index 627e66b2f..f0f719c55 100644 --- a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderMapEnts.cpp +++ b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderMapEnts.cpp @@ -2,16 +2,15 @@ #include -#include "ObjLoading.h" #include "Game/IW4/IW4.h" +#include "ObjLoading.h" #include "Pool/GlobalAssetPool.h" using namespace IW4; -void* AssetLoaderMapEnts::CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) -{ - auto* mapEnts = memory->Create(); - memset(mapEnts, 0, sizeof(MapEnts)); - mapEnts->name = memory->Dup(assetName.c_str()); - return mapEnts; +void *AssetLoaderMapEnts::CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) { + auto *mapEnts = memory->Create(); + memset(mapEnts, 0, sizeof(MapEnts)); + mapEnts->name = memory->Dup(assetName.c_str()); + return mapEnts; } diff --git a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderMapEnts.h b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderMapEnts.h index 28adc57c3..4a5cff582 100644 --- a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderMapEnts.h +++ b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderMapEnts.h @@ -1,14 +1,12 @@ #pragma once -#include "Game/IW4/IW4.h" #include "AssetLoading/BasicAssetLoader.h" +#include "Game/IW4/IW4.h" #include "SearchPath/ISearchPath.h" -namespace IW4 -{ - class AssetLoaderMapEnts final : public BasicAssetLoader - { - public: - _NODISCARD void* CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) override; - }; -} +namespace IW4 { +class AssetLoaderMapEnts final : public BasicAssetLoader { +public: + _NODISCARD void *CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) override; +}; +} // namespace IW4 diff --git a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderMaterial.cpp b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderMaterial.cpp index a17e7ef70..26f489e7f 100644 --- a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderMaterial.cpp +++ b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderMaterial.cpp @@ -1,12 +1,11 @@ #include "AssetLoaderMaterial.h" -#include #include +#include #include #include #include "AssetLoaderTechniqueSet.h" -#include "ObjLoading.h" #include "AssetLoading/AbstractGdtEntryReader.h" #include "Game/IW4/CommonIW4.h" #include "Game/IW4/IW4.h" @@ -14,6 +13,7 @@ #include "Game/IW4/ObjConstantsIW4.h" #include "Game/IW4/TechsetConstantsIW4.h" #include "Math/Vector.h" +#include "ObjLoading.h" #include "Pool/GlobalAssetPool.h" #include "StateMap/StateMapFromTechniqueExtractor.h" #include "StateMap/StateMapHandler.h" @@ -21,1352 +21,1134 @@ using namespace IW4; -namespace IW4 -{ - class SkipMaterialException final : public std::exception - { - }; - - class MaterialGdtLoader : AbstractGdtEntryReader - { - public: - MaterialGdtLoader(const GdtEntry& entry, MemoryManager* memory, ISearchPath* searchPath, IAssetLoadingManager* manager) - : AbstractGdtEntryReader(entry), - m_memory(memory), - m_search_path(searchPath), - m_manager(manager), - m_state_map_cache(manager->GetAssetLoadingContext()->GetZoneAssetLoaderState()), - m_material(nullptr), - m_base_state_bits{} - { - } - - bool Load() - { - m_material = m_memory->Create(); - memset(m_material, 0, sizeof(Material)); - - m_material->info.name = m_memory->Dup(m_entry.m_name.c_str()); - material_template(); - - FinalizeMaterial(); - return true; - } - - _NODISCARD Material* GetMaterial() const - { - return m_material; - } - - _NODISCARD std::vector GetDependencies() - { - return std::move(m_dependencies); - } - - private: - void material_template() - { - const auto materialType = ReadStringProperty("materialType"); - - if (materialType == GDT_MATERIAL_TYPE_MODEL_PHONG - || materialType == GDT_MATERIAL_TYPE_WORLD_PHONG - || materialType == GDT_MATERIAL_TYPE_IMPACT_MARK) - { - mtl_phong_template(); - } - else if (materialType == GDT_MATERIAL_TYPE_MODEL_AMBIENT) - { - mtl_ambient_template(); - } - else if (materialType == GDT_MATERIAL_TYPE_2D) - { - mtl_2d_template(); - } - else if (materialType == GDT_MATERIAL_TYPE_MODEL_UNLIT - || materialType == GDT_MATERIAL_TYPE_WORLD_UNLIT) - { - mtl_unlit_template(); - } - else if (materialType == GDT_MATERIAL_TYPE_UNLIT) - { - mtl_unlit_deprecated_template(); - } - else if (materialType == GDT_MATERIAL_TYPE_EFFECT) - { - mtl_effect_template(); - } - else if (materialType == GDT_MATERIAL_TYPE_DISTORTION) - { - mtl_distortion_template(); - } - else if (materialType == GDT_MATERIAL_TYPE_PARTICLE_CLOUD) - { - mtl_particlecloud_template(); - } - else if (materialType == GDT_MATERIAL_TYPE_TOOLS) - { - mtl_tools_template(); - } - else if (materialType == GDT_MATERIAL_TYPE_SKY) - { - mtl_sky_template(); - } - else if (materialType == GDT_MATERIAL_TYPE_WATER) - { - mtl_water_template(); - } - else if (materialType == GDT_MATERIAL_TYPE_OBJECTIVE) - { - mtl_objective_template(); - } - else if (materialType == GDT_MATERIAL_TYPE_CUSTOM) - { - custom_template(); - } - else - { - std::ostringstream ss; - ss << "Unknown material type: \"" << materialType << "\""; - throw GdtReadingException(ss.str()); - } - } - - void mtl_phong_template() - { - // TODO - throw SkipMaterialException(); - } - - void mtl_ambient_template() - { - // TODO - throw SkipMaterialException(); - } - - void mtl_2d_template() - { - commonsetup_template(); - - SetTechniqueSet("2d"); - - const auto colorMapName = ReadStringProperty("colorMap"); - const auto tileColor = ReadEnumProperty("tileColor", GdtTileModeNames, std::extent_v); - const auto filterColor = ReadEnumProperty("filterColor", GdtSamplerFilterNames, std::extent_v); - - if (!colorMapName.empty()) - AddMapTexture("colorMap", tileColor, filterColor, TS_2D, colorMapName); - else - throw GdtReadingException("ColorMap may not be blank in 2d materials"); - } - - void mtl_unlit_template() - { - // TODO - throw SkipMaterialException(); - } - - void mtl_unlit_deprecated_template() - { - // TODO - throw SkipMaterialException(); - } - - void mtl_effect_template() - { - // TODO - throw SkipMaterialException(); - - commonsetup_template(); - unitlitcommon_template(); - } - - void mtl_distortion_template() - { - commonsetup_template(); - - const auto uvAnim = ReadBoolProperty("uvAnim"); - if (uvAnim) - SetTechniqueSet("distortion_scale_ua_zfeather"); - else - SetTechniqueSet("distortion_scale_zfeather"); - - const auto colorMapName = ReadStringProperty("colorMap"); - const auto tileColor = ReadEnumProperty("tileColor", GdtTileModeNames, std::extent_v); - const auto filterColor = ReadEnumProperty("filterColor", GdtSamplerFilterNames, std::extent_v); - - if (!colorMapName.empty()) - AddMapTexture("colorMap", tileColor, filterColor, TS_COLOR_MAP, colorMapName); - else - throw GdtReadingException("ColorMap may not be blank in tools materials"); - - const auto distortionScaleX = ReadFloatProperty("distortionScaleX"); - const auto distortionScaleY = ReadFloatProperty("distortionScaleY"); - AddConstant("distortionScale", Vector4f(distortionScaleX, distortionScaleY, 0, 0)); - - if (uvAnim) - { - const auto uvScrollX = ReadFloatProperty("uvScrollX"); - const auto uvScrollY = ReadFloatProperty("uvScrollY"); - const auto uvScrollRotate = ReadFloatProperty("uvScrollRotate"); - AddConstant("uvAnimParms", Vector4f(uvScrollX, uvScrollY, uvScrollRotate, 0)); - } - } - - void mtl_particlecloud_template() - { - refblend_template(); - sort_template(); - clamp_template(); - - SetTextureAtlas(1, 1); - // tessSize(0) - - // hasEditorMaterial - // allocLightmap - - statebits_template(); - - std::string outdoorSuffix; - const auto outdoorOnly = ReadBoolProperty("outdoorOnly"); - if (outdoorOnly) - outdoorSuffix = "_outdoor"; - - std::string addSuffix; - const auto blendFunc = ReadStringProperty("blendFunc"); - if (blendFunc == GDT_BLEND_FUNC_ADD || blendFunc == GDT_BLEND_FUNC_SCREEN_ADD) - addSuffix = "_add"; - - std::string spotSuffix; - const auto useSpotLight = ReadBoolProperty("useSpotLight"); - if (useSpotLight) - spotSuffix = "_spot"; - - if (outdoorOnly && useSpotLight) - throw GdtReadingException("Outdoor and spot aren't supported on particle cloud materials"); +namespace IW4 { +class SkipMaterialException final : public std::exception {}; - std::ostringstream ss; - ss << "particle_cloud" << outdoorSuffix << addSuffix << spotSuffix; - SetTechniqueSet(ss.str()); +class MaterialGdtLoader : AbstractGdtEntryReader { +public: + MaterialGdtLoader(const GdtEntry &entry, MemoryManager *memory, ISearchPath *searchPath, IAssetLoadingManager *manager) + : AbstractGdtEntryReader(entry), m_memory(memory), m_search_path(searchPath), m_manager(manager), + m_state_map_cache(manager->GetAssetLoadingContext()->GetZoneAssetLoaderState()), m_material(nullptr), + m_base_state_bits{} {} - const auto colorMapName = ReadStringProperty("colorMap"); - const auto tileColor = ReadEnumProperty("tileColor", GdtTileModeNames, std::extent_v); - const auto filterColor = ReadEnumProperty("filterColor", GdtSamplerFilterNames, std::extent_v); + bool Load() { + m_material = m_memory->Create(); + memset(m_material, 0, sizeof(Material)); - if (!colorMapName.empty()) - AddMapTexture("colorMap", tileColor, filterColor, TS_COLOR_MAP, colorMapName); - else - throw GdtReadingException("ColorMap may not be blank in particle cloud materials"); + m_material->info.name = m_memory->Dup(m_entry.m_name.c_str()); + material_template(); - std::cout << "Using particlecloud for \"" << m_material->info.name << "\"\n"; - } - - void mtl_tools_template() - { - commonsetup_template(); - - SetTechniqueSet("tools"); - - AddMapTexture("normalMap", TileMode_e::NO_TILE, GdtFilter_e::NOMIP_NEAREST, TS_NORMAL_MAP, "$identitynormalmap"); - - const auto colorMapName = ReadStringProperty("colorMap"); - const auto tileColor = ReadEnumProperty("tileColor", GdtTileModeNames, std::extent_v); - const auto filterColor = ReadEnumProperty("filterColor", GdtSamplerFilterNames, std::extent_v); - - if (!colorMapName.empty()) - AddMapTexture("colorMap", tileColor, filterColor, TS_COLOR_MAP, colorMapName); - else - throw GdtReadingException("ColorMap may not be blank in tools materials"); - - const auto colorTint = ReadVec4Property("colorTint", {1.0f, 1.0f, 1.0f, 1.0f}); - AddConstant("colorTint", colorTint); - } - - void mtl_sky_template() - { - // TODO - throw SkipMaterialException(); - } - - void mtl_water_template() - { - // TODO - throw SkipMaterialException(); - } - - void mtl_objective_template() - { - // TODO - throw SkipMaterialException(); - } - - void custom_template() - { - const auto customTemplate = ReadStringProperty("customTemplate"); - - if (customTemplate == GDT_CUSTOM_MATERIAL_TYPE_CUSTOM) - { - mtl_custom_template(); - } - else if (customTemplate == GDT_CUSTOM_MATERIAL_TYPE_PHONG_FLAG) - { - mtl_phong_flag_template(); - } - else if (customTemplate == GDT_CUSTOM_MATERIAL_TYPE_GRAIN_OVERLAY) - { - mtl_grain_overlay_template(); - } - else if (customTemplate == GDT_CUSTOM_MATERIAL_TYPE_EFFECT_EYE_OFFSET) - { - mtl_effect_eyeoffset_template(); - } - else if (customTemplate == GDT_CUSTOM_MATERIAL_TYPE_REFLEXSIGHT) - { - mtl_reflexsight_template(); - } - else if (customTemplate == GDT_CUSTOM_MATERIAL_TYPE_SHADOWCLEAR) - { - mtl_shadowclear_template(); - } - else if (customTemplate == GDT_CUSTOM_MATERIAL_TYPE_SHADOWOVERLAY) - { - mtl_shadowoverlay_template(); - } - else if (customTemplate == GDT_CUSTOM_MATERIAL_TYPE_SPLATTER) - { - mtl_splatter_template(); - } - else - { - std::ostringstream ss; - ss << "Unknown custom template: \"" << customTemplate << "\""; - throw GdtReadingException(ss.str()); - } - } - - void mtl_custom_template() - { - // TODO - throw SkipMaterialException(); - } - - void mtl_phong_flag_template() - { - // TODO - throw SkipMaterialException(); - } - - void mtl_grain_overlay_template() - { - // TODO - throw SkipMaterialException(); - } - - void mtl_effect_eyeoffset_template() - { - // TODO - throw SkipMaterialException(); - } - - void mtl_reflexsight_template() - { - // TODO - throw SkipMaterialException(); - } - - void mtl_shadowclear_template() - { - // TODO - throw SkipMaterialException(); - } - - void mtl_shadowoverlay_template() - { - // TODO - throw SkipMaterialException(); - } - - void mtl_splatter_template() - { - // TODO - throw SkipMaterialException(); - } - - void unitlitcommon_template() - { - const auto outdoorOnly = ReadBoolProperty("outdoorOnly"); - const auto blendFunc = ReadStringProperty("blendFunc"); - - std::string distFalloffSuffix; - const auto distFalloff = ReadBoolProperty("distFalloff"); - if (distFalloff) - { - const auto hdrPortal = ReadBoolProperty("hdrPortal"); - if (!hdrPortal) - throw GdtReadingException("Cannot have distance falloff active without hdrPortal."); - - if (blendFunc == GDT_BLEND_FUNC_MULTIPLY) - throw GdtReadingException("Distance falloff does not currently support Multiply."); - - if (outdoorOnly) - throw GdtReadingException("Distance falloff does not currently support outdoor-only types."); - - distFalloffSuffix = "_falloff"; - } - - std::string godFalloffSuffix; - const auto falloff = ReadBoolProperty("falloff"); - if (falloff) - { - if (blendFunc == GDT_BLEND_FUNC_MULTIPLY) - throw GdtReadingException("Falloff does not currently support Multiply."); - - if (outdoorOnly) - throw GdtReadingException("Falloff does not currently support outdoor-only types."); - - godFalloffSuffix = "_falloff"; - } - - std::string noFogSuffix; - const auto noFog = ReadBoolProperty("noFog"); - if (noFog) - noFogSuffix = "_nofog"; - - std::string spotSuffix; - const auto useSpotLight = ReadBoolProperty("useSpotLight"); - if (useSpotLight) - spotSuffix = "_spot"; - - std::string eyeOffsetSuffix; - const auto eyeOffsetDepth = ReadFloatProperty("eyeOffsetDepth"); - if (std::fpclassify(eyeOffsetDepth) != FP_ZERO) - eyeOffsetSuffix = "_eyeoffset"; - - const auto materialType = ReadStringProperty("materialType"); - const auto zFeather = ReadBoolProperty("zFeather"); - - if (materialType == GDT_MATERIAL_TYPE_EFFECT && zFeather) - { - if (blendFunc == GDT_BLEND_FUNC_MULTIPLY) - throw GdtReadingException("zFeather does not support multiply."); - - std::string addSuffix; - if (blendFunc == GDT_BLEND_FUNC_ADD || blendFunc == GDT_BLEND_FUNC_SCREEN_ADD) - addSuffix = "_add"; - - if (outdoorOnly) - { - std::ostringstream ss; - ss << "effect_zfeather_outdoor" << addSuffix << noFogSuffix << spotSuffix << eyeOffsetSuffix; - SetTechniqueSet(ss.str()); - } - else - { - std::ostringstream ss; - ss << "effect_zfeather" << distFalloffSuffix << godFalloffSuffix << addSuffix << noFogSuffix << spotSuffix << eyeOffsetSuffix; - SetTechniqueSet(ss.str()); - } - } - else - { - std::string baseTechName = materialType == GDT_MATERIAL_TYPE_EFFECT ? "effect" : "unlit"; - - if (blendFunc == GDT_BLEND_FUNC_MULTIPLY) - { - std::ostringstream ss; - ss << baseTechName << "_multiply" << noFogSuffix << spotSuffix << eyeOffsetSuffix; - SetTechniqueSet(ss.str()); - } - else - { - std::string addSuffix; - if (blendFunc == GDT_BLEND_FUNC_ADD || blendFunc == GDT_BLEND_FUNC_SCREEN_ADD) - addSuffix = "_add"; - - std::ostringstream ss; - ss << baseTechName << distFalloffSuffix << godFalloffSuffix << addSuffix << noFogSuffix << spotSuffix << eyeOffsetSuffix; - SetTechniqueSet(ss.str()); - } - } - - const auto colorMapName = ReadStringProperty("colorMap"); - const auto tileColor = ReadEnumProperty("tileColor", GdtTileModeNames, std::extent_v); - const auto filterColor = ReadEnumProperty("filterColor", GdtSamplerFilterNames, std::extent_v); - - if (!colorMapName.empty()) - AddMapTexture("colorMap", tileColor, filterColor, TS_COLOR_MAP, colorMapName); - else - throw GdtReadingException("ColorMap may not be blank in effect/unlit materials"); - - if (falloff || distFalloff) - { - // TODO - } - - if (zFeather) - { - const auto zFeatherDepth = ReadFloatProperty("zFeatherDepth"); - if (std::fpclassify(zFeatherDepth) == FP_ZERO) - throw GdtReadingException("zFeatherDepth may not be zero"); - AddConstant("featherParms", Vector4f(1.0f / zFeatherDepth, zFeatherDepth, 0, 0)); - } - - if (std::fpclassify(eyeOffsetDepth) != FP_ZERO) - AddConstant("eyeOffsetParms", Vector4f(eyeOffsetDepth, 0, 0, 0)); - - const auto colorTint = ReadVec4Property("colorTint", {1.0f, 1.0f, 1.0f, 1.0f}); - AddConstant("colorTint", colorTint); - } - - void commonsetup_template() - { - refblend_template(); - sort_template(); - clamp_template(); + FinalizeMaterial(); + return true; + } + + _NODISCARD Material *GetMaterial() const { return m_material; } + + _NODISCARD std::vector GetDependencies() { return std::move(m_dependencies); } + +private: + void material_template() { + const auto materialType = ReadStringProperty("materialType"); + + if (materialType == GDT_MATERIAL_TYPE_MODEL_PHONG || materialType == GDT_MATERIAL_TYPE_WORLD_PHONG || materialType == GDT_MATERIAL_TYPE_IMPACT_MARK) { + mtl_phong_template(); + } else if (materialType == GDT_MATERIAL_TYPE_MODEL_AMBIENT) { + mtl_ambient_template(); + } else if (materialType == GDT_MATERIAL_TYPE_2D) { + mtl_2d_template(); + } else if (materialType == GDT_MATERIAL_TYPE_MODEL_UNLIT || materialType == GDT_MATERIAL_TYPE_WORLD_UNLIT) { + mtl_unlit_template(); + } else if (materialType == GDT_MATERIAL_TYPE_UNLIT) { + mtl_unlit_deprecated_template(); + } else if (materialType == GDT_MATERIAL_TYPE_EFFECT) { + mtl_effect_template(); + } else if (materialType == GDT_MATERIAL_TYPE_DISTORTION) { + mtl_distortion_template(); + } else if (materialType == GDT_MATERIAL_TYPE_PARTICLE_CLOUD) { + mtl_particlecloud_template(); + } else if (materialType == GDT_MATERIAL_TYPE_TOOLS) { + mtl_tools_template(); + } else if (materialType == GDT_MATERIAL_TYPE_SKY) { + mtl_sky_template(); + } else if (materialType == GDT_MATERIAL_TYPE_WATER) { + mtl_water_template(); + } else if (materialType == GDT_MATERIAL_TYPE_OBJECTIVE) { + mtl_objective_template(); + } else if (materialType == GDT_MATERIAL_TYPE_CUSTOM) { + custom_template(); + } else { + std::ostringstream ss; + ss << "Unknown material type: \"" << materialType << "\""; + throw GdtReadingException(ss.str()); + } + } + + void mtl_phong_template() { + // TODO + throw SkipMaterialException(); + } + + void mtl_ambient_template() { + // TODO + throw SkipMaterialException(); + } + + void mtl_2d_template() { + commonsetup_template(); + + SetTechniqueSet("2d"); + + const auto colorMapName = ReadStringProperty("colorMap"); + const auto tileColor = ReadEnumProperty("tileColor", GdtTileModeNames, std::extent_v); + const auto filterColor = ReadEnumProperty("filterColor", GdtSamplerFilterNames, std::extent_v); + + if (!colorMapName.empty()) + AddMapTexture("colorMap", tileColor, filterColor, TS_2D, colorMapName); + else + throw GdtReadingException("ColorMap may not be blank in 2d materials"); + } + + void mtl_unlit_template() { + // TODO + throw SkipMaterialException(); + } + + void mtl_unlit_deprecated_template() { + // TODO + throw SkipMaterialException(); + } + + void mtl_effect_template() { + // TODO + throw SkipMaterialException(); + + commonsetup_template(); + unitlitcommon_template(); + } + + void mtl_distortion_template() { + commonsetup_template(); + + const auto uvAnim = ReadBoolProperty("uvAnim"); + if (uvAnim) + SetTechniqueSet("distortion_scale_ua_zfeather"); + else + SetTechniqueSet("distortion_scale_zfeather"); + + const auto colorMapName = ReadStringProperty("colorMap"); + const auto tileColor = ReadEnumProperty("tileColor", GdtTileModeNames, std::extent_v); + const auto filterColor = ReadEnumProperty("filterColor", GdtSamplerFilterNames, std::extent_v); + + if (!colorMapName.empty()) + AddMapTexture("colorMap", tileColor, filterColor, TS_COLOR_MAP, colorMapName); + else + throw GdtReadingException("ColorMap may not be blank in tools materials"); + + const auto distortionScaleX = ReadFloatProperty("distortionScaleX"); + const auto distortionScaleY = ReadFloatProperty("distortionScaleY"); + AddConstant("distortionScale", Vector4f(distortionScaleX, distortionScaleY, 0, 0)); + + if (uvAnim) { + const auto uvScrollX = ReadFloatProperty("uvScrollX"); + const auto uvScrollY = ReadFloatProperty("uvScrollY"); + const auto uvScrollRotate = ReadFloatProperty("uvScrollRotate"); + AddConstant("uvAnimParms", Vector4f(uvScrollX, uvScrollY, uvScrollRotate, 0)); + } + } + + void mtl_particlecloud_template() { + refblend_template(); + sort_template(); + clamp_template(); + + SetTextureAtlas(1, 1); + // tessSize(0) + + // hasEditorMaterial + // allocLightmap + + statebits_template(); + + std::string outdoorSuffix; + const auto outdoorOnly = ReadBoolProperty("outdoorOnly"); + if (outdoorOnly) + outdoorSuffix = "_outdoor"; + + std::string addSuffix; + const auto blendFunc = ReadStringProperty("blendFunc"); + if (blendFunc == GDT_BLEND_FUNC_ADD || blendFunc == GDT_BLEND_FUNC_SCREEN_ADD) + addSuffix = "_add"; + + std::string spotSuffix; + const auto useSpotLight = ReadBoolProperty("useSpotLight"); + if (useSpotLight) + spotSuffix = "_spot"; + + if (outdoorOnly && useSpotLight) + throw GdtReadingException("Outdoor and spot aren't supported on particle cloud materials"); + + std::ostringstream ss; + ss << "particle_cloud" << outdoorSuffix << addSuffix << spotSuffix; + SetTechniqueSet(ss.str()); + + const auto colorMapName = ReadStringProperty("colorMap"); + const auto tileColor = ReadEnumProperty("tileColor", GdtTileModeNames, std::extent_v); + const auto filterColor = ReadEnumProperty("filterColor", GdtSamplerFilterNames, std::extent_v); + + if (!colorMapName.empty()) + AddMapTexture("colorMap", tileColor, filterColor, TS_COLOR_MAP, colorMapName); + else + throw GdtReadingException("ColorMap may not be blank in particle cloud materials"); + + std::cout << "Using particlecloud for \"" << m_material->info.name << "\"\n"; + } + + void mtl_tools_template() { + commonsetup_template(); + + SetTechniqueSet("tools"); + + AddMapTexture("normalMap", TileMode_e::NO_TILE, GdtFilter_e::NOMIP_NEAREST, TS_NORMAL_MAP, "$identitynormalmap"); + + const auto colorMapName = ReadStringProperty("colorMap"); + const auto tileColor = ReadEnumProperty("tileColor", GdtTileModeNames, std::extent_v); + const auto filterColor = ReadEnumProperty("filterColor", GdtSamplerFilterNames, std::extent_v); + + if (!colorMapName.empty()) + AddMapTexture("colorMap", tileColor, filterColor, TS_COLOR_MAP, colorMapName); + else + throw GdtReadingException("ColorMap may not be blank in tools materials"); + + const auto colorTint = ReadVec4Property("colorTint", {1.0f, 1.0f, 1.0f, 1.0f}); + AddConstant("colorTint", colorTint); + } + + void mtl_sky_template() { + // TODO + throw SkipMaterialException(); + } + + void mtl_water_template() { + // TODO + throw SkipMaterialException(); + } + + void mtl_objective_template() { + // TODO + throw SkipMaterialException(); + } + + void custom_template() { + const auto customTemplate = ReadStringProperty("customTemplate"); + + if (customTemplate == GDT_CUSTOM_MATERIAL_TYPE_CUSTOM) { + mtl_custom_template(); + } else if (customTemplate == GDT_CUSTOM_MATERIAL_TYPE_PHONG_FLAG) { + mtl_phong_flag_template(); + } else if (customTemplate == GDT_CUSTOM_MATERIAL_TYPE_GRAIN_OVERLAY) { + mtl_grain_overlay_template(); + } else if (customTemplate == GDT_CUSTOM_MATERIAL_TYPE_EFFECT_EYE_OFFSET) { + mtl_effect_eyeoffset_template(); + } else if (customTemplate == GDT_CUSTOM_MATERIAL_TYPE_REFLEXSIGHT) { + mtl_reflexsight_template(); + } else if (customTemplate == GDT_CUSTOM_MATERIAL_TYPE_SHADOWCLEAR) { + mtl_shadowclear_template(); + } else if (customTemplate == GDT_CUSTOM_MATERIAL_TYPE_SHADOWOVERLAY) { + mtl_shadowoverlay_template(); + } else if (customTemplate == GDT_CUSTOM_MATERIAL_TYPE_SPLATTER) { + mtl_splatter_template(); + } else { + std::ostringstream ss; + ss << "Unknown custom template: \"" << customTemplate << "\""; + throw GdtReadingException(ss.str()); + } + } + + void mtl_custom_template() { + // TODO + throw SkipMaterialException(); + } + + void mtl_phong_flag_template() { + // TODO + throw SkipMaterialException(); + } + + void mtl_grain_overlay_template() { + // TODO + throw SkipMaterialException(); + } + + void mtl_effect_eyeoffset_template() { + // TODO + throw SkipMaterialException(); + } + + void mtl_reflexsight_template() { + // TODO + throw SkipMaterialException(); + } + + void mtl_shadowclear_template() { + // TODO + throw SkipMaterialException(); + } + + void mtl_shadowoverlay_template() { + // TODO + throw SkipMaterialException(); + } + + void mtl_splatter_template() { + // TODO + throw SkipMaterialException(); + } + + void unitlitcommon_template() { + const auto outdoorOnly = ReadBoolProperty("outdoorOnly"); + const auto blendFunc = ReadStringProperty("blendFunc"); + + std::string distFalloffSuffix; + const auto distFalloff = ReadBoolProperty("distFalloff"); + if (distFalloff) { + const auto hdrPortal = ReadBoolProperty("hdrPortal"); + if (!hdrPortal) + throw GdtReadingException("Cannot have distance falloff active without hdrPortal."); + + if (blendFunc == GDT_BLEND_FUNC_MULTIPLY) + throw GdtReadingException("Distance falloff does not currently support Multiply."); + + if (outdoorOnly) + throw GdtReadingException("Distance falloff does not currently support outdoor-only types."); + + distFalloffSuffix = "_falloff"; + } - // tessSize + std::string godFalloffSuffix; + const auto falloff = ReadBoolProperty("falloff"); + if (falloff) { + if (blendFunc == GDT_BLEND_FUNC_MULTIPLY) + throw GdtReadingException("Falloff does not currently support Multiply."); - textureAtlas_template(); + if (outdoorOnly) + throw GdtReadingException("Falloff does not currently support outdoor-only types."); - // hasEditorMaterial + godFalloffSuffix = "_falloff"; + } - // allocLightmap + std::string noFogSuffix; + const auto noFog = ReadBoolProperty("noFog"); + if (noFog) + noFogSuffix = "_nofog"; + + std::string spotSuffix; + const auto useSpotLight = ReadBoolProperty("useSpotLight"); + if (useSpotLight) + spotSuffix = "_spot"; + + std::string eyeOffsetSuffix; + const auto eyeOffsetDepth = ReadFloatProperty("eyeOffsetDepth"); + if (std::fpclassify(eyeOffsetDepth) != FP_ZERO) + eyeOffsetSuffix = "_eyeoffset"; + + const auto materialType = ReadStringProperty("materialType"); + const auto zFeather = ReadBoolProperty("zFeather"); + + if (materialType == GDT_MATERIAL_TYPE_EFFECT && zFeather) { + if (blendFunc == GDT_BLEND_FUNC_MULTIPLY) + throw GdtReadingException("zFeather does not support multiply."); + + std::string addSuffix; + if (blendFunc == GDT_BLEND_FUNC_ADD || blendFunc == GDT_BLEND_FUNC_SCREEN_ADD) + addSuffix = "_add"; + + if (outdoorOnly) { + std::ostringstream ss; + ss << "effect_zfeather_outdoor" << addSuffix << noFogSuffix << spotSuffix << eyeOffsetSuffix; + SetTechniqueSet(ss.str()); + } else { + std::ostringstream ss; + ss << "effect_zfeather" << distFalloffSuffix << godFalloffSuffix << addSuffix << noFogSuffix << spotSuffix << eyeOffsetSuffix; + SetTechniqueSet(ss.str()); + } + } else { + std::string baseTechName = materialType == GDT_MATERIAL_TYPE_EFFECT ? "effect" : "unlit"; + + if (blendFunc == GDT_BLEND_FUNC_MULTIPLY) { + std::ostringstream ss; + ss << baseTechName << "_multiply" << noFogSuffix << spotSuffix << eyeOffsetSuffix; + SetTechniqueSet(ss.str()); + } else { + std::string addSuffix; + if (blendFunc == GDT_BLEND_FUNC_ADD || blendFunc == GDT_BLEND_FUNC_SCREEN_ADD) + addSuffix = "_add"; + + std::ostringstream ss; + ss << baseTechName << distFalloffSuffix << godFalloffSuffix << addSuffix << noFogSuffix << spotSuffix << eyeOffsetSuffix; + SetTechniqueSet(ss.str()); + } + } - statebits_template(); - } + const auto colorMapName = ReadStringProperty("colorMap"); + const auto tileColor = ReadEnumProperty("tileColor", GdtTileModeNames, std::extent_v); + const auto filterColor = ReadEnumProperty("filterColor", GdtSamplerFilterNames, std::extent_v); - void refblend_template() - { - const auto blendFunc = ReadStringProperty("blendFunc"); - } + if (!colorMapName.empty()) + AddMapTexture("colorMap", tileColor, filterColor, TS_COLOR_MAP, colorMapName); + else + throw GdtReadingException("ColorMap may not be blank in effect/unlit materials"); - void sort_template() - { - const auto sort = ReadStringProperty("sort"); - const auto materialType = ReadStringProperty("materialType"); - const auto polygonOffset = ReadStringProperty("polygonOffset"); - const auto blendFunc = ReadStringProperty("blendFunc"); - - std::string sortKey; - if (sort.empty() || sort == GDT_SORTKEY_DEFAULT) - { - if (materialType == GDT_MATERIAL_TYPE_DISTORTION) - sortKey = GDT_SORTKEY_DISTORTION; - else if (polygonOffset == "Static Decal") - sortKey = GDT_SORTKEY_DECAL_STATIC; - else if (polygonOffset == "Weapon Impact") - sortKey = GDT_SORTKEY_DECAL_WEAPON_IMPACT; - else if (materialType == GDT_MATERIAL_TYPE_EFFECT) - sortKey = GDT_SORTKEY_EFFECT_AUTO_SORT; - else if (materialType == GDT_MATERIAL_TYPE_OBJECTIVE - || blendFunc == "Blend" || blendFunc == "Add" || blendFunc == "Screen Add") - sortKey = GDT_SORTKEY_BLEND_ADDITIVE; - // else if (blendFunc == "Multiply") // TODO - // sortKey = GDT_SORTKEY_MULTIPLICATIVE; - else if (materialType == GDT_MATERIAL_TYPE_SKY) - sortKey = GDT_SORTKEY_SKY; - else if (materialType == GDT_MATERIAL_TYPE_MODEL_AMBIENT) - sortKey = GDT_SORTKEY_OPAQUE_AMBIENT; - else - sortKey = GDT_SORTKEY_OPAQUE; - } - else - sortKey = sort; - - bool foundSortKey = false; - for (auto sortKeyIndex = 0u; sortKeyIndex < SORTKEY_MAX; sortKeyIndex++) - { - if (SortKeyNames[sortKeyIndex] && sortKey == SortKeyNames[sortKeyIndex]) - { - SetSort(static_cast(sortKeyIndex)); - foundSortKey = true; - break; - } - } - - if (!foundSortKey) - { - char* endPtr; - const auto sortKeyNum = strtoul(sortKey.c_str(), &endPtr, 10); - - if (endPtr != &sortKey[sortKey.size()]) - { - std::ostringstream ss; - ss << "Invalid sort value: \"" << sortKey << "\""; - throw GdtReadingException(ss.str()); - } - - SetSort(static_cast(sortKeyNum)); - } - } + if (falloff || distFalloff) { + // TODO + } - void clamp_template() - { - } + if (zFeather) { + const auto zFeatherDepth = ReadFloatProperty("zFeatherDepth"); + if (std::fpclassify(zFeatherDepth) == FP_ZERO) + throw GdtReadingException("zFeatherDepth may not be zero"); + AddConstant("featherParms", Vector4f(1.0f / zFeatherDepth, zFeatherDepth, 0, 0)); + } - void textureAtlas_template() - { - const auto rowCount = ReadIntegerProperty("textureAtlasRowCount", 1); - const auto columnCount = ReadIntegerProperty("textureAtlasColumnCount", 1); + if (std::fpclassify(eyeOffsetDepth) != FP_ZERO) + AddConstant("eyeOffsetParms", Vector4f(eyeOffsetDepth, 0, 0, 0)); + + const auto colorTint = ReadVec4Property("colorTint", {1.0f, 1.0f, 1.0f, 1.0f}); + AddConstant("colorTint", colorTint); + } + + void commonsetup_template() { + refblend_template(); + sort_template(); + clamp_template(); + + // tessSize + + textureAtlas_template(); + + // hasEditorMaterial + + // allocLightmap + + statebits_template(); + } + + void refblend_template() { const auto blendFunc = ReadStringProperty("blendFunc"); } + + void sort_template() { + const auto sort = ReadStringProperty("sort"); + const auto materialType = ReadStringProperty("materialType"); + const auto polygonOffset = ReadStringProperty("polygonOffset"); + const auto blendFunc = ReadStringProperty("blendFunc"); + + std::string sortKey; + if (sort.empty() || sort == GDT_SORTKEY_DEFAULT) { + if (materialType == GDT_MATERIAL_TYPE_DISTORTION) + sortKey = GDT_SORTKEY_DISTORTION; + else if (polygonOffset == "Static Decal") + sortKey = GDT_SORTKEY_DECAL_STATIC; + else if (polygonOffset == "Weapon Impact") + sortKey = GDT_SORTKEY_DECAL_WEAPON_IMPACT; + else if (materialType == GDT_MATERIAL_TYPE_EFFECT) + sortKey = GDT_SORTKEY_EFFECT_AUTO_SORT; + else if (materialType == GDT_MATERIAL_TYPE_OBJECTIVE || blendFunc == "Blend" || blendFunc == "Add" || blendFunc == "Screen Add") + sortKey = GDT_SORTKEY_BLEND_ADDITIVE; + // else if (blendFunc == "Multiply") // TODO + // sortKey = GDT_SORTKEY_MULTIPLICATIVE; + else if (materialType == GDT_MATERIAL_TYPE_SKY) + sortKey = GDT_SORTKEY_SKY; + else if (materialType == GDT_MATERIAL_TYPE_MODEL_AMBIENT) + sortKey = GDT_SORTKEY_OPAQUE_AMBIENT; + else + sortKey = GDT_SORTKEY_OPAQUE; + } else + sortKey = sort; + + bool foundSortKey = false; + for (auto sortKeyIndex = 0u; sortKeyIndex < SORTKEY_MAX; sortKeyIndex++) { + if (SortKeyNames[sortKeyIndex] && sortKey == SortKeyNames[sortKeyIndex]) { + SetSort(static_cast(sortKeyIndex)); + foundSortKey = true; + break; + } + } - SetTextureAtlas(static_cast(rowCount), static_cast(columnCount)); - } + if (!foundSortKey) { + char *endPtr; + const auto sortKeyNum = strtoul(sortKey.c_str(), &endPtr, 10); - void statebits_template() - { - alphatest_template(); - blendfunc_template(); - colorwrite_template(); - cullface_template(); - depthtest_template(); - depthwrite_template(); - gammawrite_template(); - polygonoffset_template(); - stencil_template(); - } + if (endPtr != &sortKey[sortKey.size()]) { + std::ostringstream ss; + ss << "Invalid sort value: \"" << sortKey << "\""; + throw GdtReadingException(ss.str()); + } - void alphatest_template() - { - const auto alphaTest = ReadStringProperty("alphaTest"); - - if (alphaTest == GDT_ALPHA_TEST_ALWAYS) - SetAlphaTest(AlphaTest_e::ALWAYS); - else if (alphaTest == GDT_ALPHA_TEST_GE128) - SetAlphaTest(AlphaTest_e::GE128); - else if (alphaTest == GDT_ALPHA_TEST_GT0) // TODO: This is not available for IW3 - SetAlphaTest(AlphaTest_e::GT0); - else - { - std::ostringstream ss; - ss << "Invalid alphatest value: \"" << alphaTest << "\""; - throw GdtReadingException(ss.str()); - } - } + SetSort(static_cast(sortKeyNum)); + } + } + + void clamp_template() {} + + void textureAtlas_template() { + const auto rowCount = ReadIntegerProperty("textureAtlasRowCount", 1); + const auto columnCount = ReadIntegerProperty("textureAtlasColumnCount", 1); + + SetTextureAtlas(static_cast(rowCount), static_cast(columnCount)); + } + + void statebits_template() { + alphatest_template(); + blendfunc_template(); + colorwrite_template(); + cullface_template(); + depthtest_template(); + depthwrite_template(); + gammawrite_template(); + polygonoffset_template(); + stencil_template(); + } + + void alphatest_template() { + const auto alphaTest = ReadStringProperty("alphaTest"); + + if (alphaTest == GDT_ALPHA_TEST_ALWAYS) + SetAlphaTest(AlphaTest_e::ALWAYS); + else if (alphaTest == GDT_ALPHA_TEST_GE128) + SetAlphaTest(AlphaTest_e::GE128); + else if (alphaTest == GDT_ALPHA_TEST_GT0) // TODO: This is not available for IW3 + SetAlphaTest(AlphaTest_e::GT0); + else { + std::ostringstream ss; + ss << "Invalid alphatest value: \"" << alphaTest << "\""; + throw GdtReadingException(ss.str()); + } + } + + void blendfunc_template() { + const auto blendFunc = ReadStringProperty("blendFunc"); + + if (blendFunc == GDT_BLEND_FUNC_ADD) { + SetBlendFunc(BlendOp_e::ADD, CustomBlendFunc_e::ONE, CustomBlendFunc_e::ONE); + SetSeparateAlphaBlendFunc(BlendOp_e::DISABLE, CustomBlendFunc_e::ONE, CustomBlendFunc_e::ZERO); + } else if (blendFunc == GDT_BLEND_FUNC_BLEND) { + SetBlendFunc(BlendOp_e::ADD, CustomBlendFunc_e::SRC_ALPHA, CustomBlendFunc_e::INV_SRC_ALPHA); + SetSeparateAlphaBlendFunc(BlendOp_e::DISABLE, CustomBlendFunc_e::ONE, CustomBlendFunc_e::ZERO); + } else if (blendFunc == GDT_BLEND_FUNC_MULTIPLY) { + SetBlendFunc(BlendOp_e::ADD, CustomBlendFunc_e::ZERO, CustomBlendFunc_e::SRC_COLOR); + SetSeparateAlphaBlendFunc(BlendOp_e::DISABLE, CustomBlendFunc_e::ONE, CustomBlendFunc_e::ZERO); + } else if (blendFunc == GDT_BLEND_FUNC_REPLACE) { + SetBlendFunc(BlendOp_e::DISABLE, CustomBlendFunc_e::ONE, CustomBlendFunc_e::ZERO); + SetSeparateAlphaBlendFunc(BlendOp_e::DISABLE, CustomBlendFunc_e::ONE, CustomBlendFunc_e::ZERO); + } else if (blendFunc == GDT_BLEND_FUNC_SCREEN_ADD) { + SetBlendFunc(BlendOp_e::ADD, CustomBlendFunc_e::INV_DST_COLOR, CustomBlendFunc_e::ONE); + SetSeparateAlphaBlendFunc(BlendOp_e::DISABLE, CustomBlendFunc_e::ONE, CustomBlendFunc_e::ZERO); + } else if (blendFunc == GDT_BLEND_FUNC_CUSTOM) { + const auto customBlendOpRgb = ReadEnumProperty("customBlendOpRgb", GdtBlendOpNames, std::extent_v); + const auto srcCustomBlendFunc = + ReadEnumProperty("srcCustomBlendFunc", GdtCustomBlendFuncNames, std::extent_v); + const auto destCustomBlendFunc = + ReadEnumProperty("destCustomBlendFunc", GdtCustomBlendFuncNames, std::extent_v); + const auto customBlendOpAlpha = ReadEnumProperty("customBlendOpAlpha", GdtBlendOpNames, std::extent_v); + const auto srcCustomBlendFuncAlpha = + ReadEnumProperty("srcCustomBlendFuncAlpha", GdtCustomBlendFuncNames, std::extent_v); + const auto destCustomBlendFuncAlpha = + ReadEnumProperty("destCustomBlendFuncAlpha", GdtCustomBlendFuncNames, std::extent_v); + + SetBlendFunc(customBlendOpRgb, srcCustomBlendFunc, destCustomBlendFunc); + SetSeparateAlphaBlendFunc(customBlendOpAlpha, srcCustomBlendFuncAlpha, destCustomBlendFuncAlpha); + } else { + std::ostringstream ss; + ss << "Invalid blendfunc value: \"" << blendFunc << "\""; + throw GdtReadingException(ss.str()); + } + } + + void colorwrite_template() { + const auto colorWriteRed = + ReadEnumProperty("colorWriteRed", GdtStateBitsEnabledStatusNames, std::extent_v); + const auto colorWriteGreen = + ReadEnumProperty("colorWriteGreen", GdtStateBitsEnabledStatusNames, std::extent_v); + const auto colorWriteBlue = + ReadEnumProperty("colorWriteBlue", GdtStateBitsEnabledStatusNames, std::extent_v); + const auto colorWriteAlpha = + ReadEnumProperty("colorWriteAlpha", GdtStateBitsEnabledStatusNames, std::extent_v); + + SetColorWrite(colorWriteRed, colorWriteGreen, colorWriteBlue, colorWriteAlpha); + } + + void cullface_template() { + const auto cullFace = ReadEnumProperty("cullFace", GdtCullFaceNames, std::extent_v); + + SetCullFace(cullFace); + } + + void depthtest_template() { + const auto depthTest = ReadEnumProperty("depthTest", GdtDepthTestNames, std::extent_v); + + SetDepthTest(depthTest); + } + + void depthwrite_template() { + const auto depthWrite = + ReadEnumProperty("depthWrite", GdtStateBitsOnOffStatusNames, std::extent_v); + const auto blendFunc = ReadStringProperty("blendFunc"); + + if (depthWrite == StateBitsEnabledStatus_e::ENABLED) + SetDepthWrite(true); + else if (depthWrite == StateBitsEnabledStatus_e::DISABLED) + SetDepthWrite(false); + else if (blendFunc == GDT_BLEND_FUNC_ADD) + SetDepthWrite(false); + else if (blendFunc == GDT_BLEND_FUNC_BLEND) + SetDepthWrite(false); + else if (blendFunc == GDT_BLEND_FUNC_MULTIPLY) + SetDepthWrite(false); + else if (blendFunc == GDT_BLEND_FUNC_REPLACE) + SetDepthWrite(true); + else if (blendFunc == GDT_BLEND_FUNC_SCREEN_ADD) + SetDepthWrite(false); + else if (blendFunc == GDT_BLEND_FUNC_CUSTOM) + SetDepthWrite(false); + else { + std::ostringstream ss; + ss << "Invalid depthWrite blendFunc value: \"" << blendFunc << "\""; + throw GdtReadingException(ss.str()); + } + } - void blendfunc_template() - { - const auto blendFunc = ReadStringProperty("blendFunc"); - - if (blendFunc == GDT_BLEND_FUNC_ADD) - { - SetBlendFunc(BlendOp_e::ADD, CustomBlendFunc_e::ONE, CustomBlendFunc_e::ONE); - SetSeparateAlphaBlendFunc(BlendOp_e::DISABLE, CustomBlendFunc_e::ONE, CustomBlendFunc_e::ZERO); - } - else if (blendFunc == GDT_BLEND_FUNC_BLEND) - { - SetBlendFunc(BlendOp_e::ADD, CustomBlendFunc_e::SRC_ALPHA, CustomBlendFunc_e::INV_SRC_ALPHA); - SetSeparateAlphaBlendFunc(BlendOp_e::DISABLE, CustomBlendFunc_e::ONE, CustomBlendFunc_e::ZERO); - } - else if (blendFunc == GDT_BLEND_FUNC_MULTIPLY) - { - SetBlendFunc(BlendOp_e::ADD, CustomBlendFunc_e::ZERO, CustomBlendFunc_e::SRC_COLOR); - SetSeparateAlphaBlendFunc(BlendOp_e::DISABLE, CustomBlendFunc_e::ONE, CustomBlendFunc_e::ZERO); - } - else if (blendFunc == GDT_BLEND_FUNC_REPLACE) - { - SetBlendFunc(BlendOp_e::DISABLE, CustomBlendFunc_e::ONE, CustomBlendFunc_e::ZERO); - SetSeparateAlphaBlendFunc(BlendOp_e::DISABLE, CustomBlendFunc_e::ONE, CustomBlendFunc_e::ZERO); - } - else if (blendFunc == GDT_BLEND_FUNC_SCREEN_ADD) - { - SetBlendFunc(BlendOp_e::ADD, CustomBlendFunc_e::INV_DST_COLOR, CustomBlendFunc_e::ONE); - SetSeparateAlphaBlendFunc(BlendOp_e::DISABLE, CustomBlendFunc_e::ONE, CustomBlendFunc_e::ZERO); - } - else if (blendFunc == GDT_BLEND_FUNC_CUSTOM) - { - const auto customBlendOpRgb = ReadEnumProperty("customBlendOpRgb", GdtBlendOpNames, std::extent_v); - const auto srcCustomBlendFunc = ReadEnumProperty("srcCustomBlendFunc", GdtCustomBlendFuncNames, std::extent_v); - const auto destCustomBlendFunc = ReadEnumProperty("destCustomBlendFunc", GdtCustomBlendFuncNames, std::extent_v); - const auto customBlendOpAlpha = ReadEnumProperty("customBlendOpAlpha", GdtBlendOpNames, std::extent_v); - const auto srcCustomBlendFuncAlpha = ReadEnumProperty("srcCustomBlendFuncAlpha", GdtCustomBlendFuncNames, std::extent_v); - const auto destCustomBlendFuncAlpha = ReadEnumProperty("destCustomBlendFuncAlpha", GdtCustomBlendFuncNames, std::extent_v); - - SetBlendFunc(customBlendOpRgb, srcCustomBlendFunc, destCustomBlendFunc); - SetSeparateAlphaBlendFunc(customBlendOpAlpha, srcCustomBlendFuncAlpha, destCustomBlendFuncAlpha); - } - else - { - std::ostringstream ss; - ss << "Invalid blendfunc value: \"" << blendFunc << "\""; - throw GdtReadingException(ss.str()); - } - } + void gammawrite_template() { + const auto gammaWrite = + ReadEnumProperty("gammaWrite", GdtStateBitsOnOffStatusNames, std::extent_v); - void colorwrite_template() - { - const auto colorWriteRed = ReadEnumProperty("colorWriteRed", GdtStateBitsEnabledStatusNames, std::extent_v); - const auto colorWriteGreen = ReadEnumProperty("colorWriteGreen", GdtStateBitsEnabledStatusNames, std::extent_v); - const auto colorWriteBlue = ReadEnumProperty("colorWriteBlue", GdtStateBitsEnabledStatusNames, std::extent_v); - const auto colorWriteAlpha = ReadEnumProperty("colorWriteAlpha", GdtStateBitsEnabledStatusNames, std::extent_v); + if (gammaWrite == StateBitsEnabledStatus_e::UNKNOWN) { + std::ostringstream ss; + ss << "Invalid gammaWrite blendFunc value: \"\""; + throw GdtReadingException(ss.str()); + } - SetColorWrite(colorWriteRed, colorWriteGreen, colorWriteBlue, colorWriteAlpha); - } + SetGammaWrite(gammaWrite == StateBitsEnabledStatus_e::ENABLED); + } - void cullface_template() - { - const auto cullFace = ReadEnumProperty("cullFace", GdtCullFaceNames, std::extent_v); + void polygonoffset_template() { + const auto polygonOffset = ReadEnumProperty("polygonOffset", GdtPolygonOffsetNames, std::extent_v); - SetCullFace(cullFace); - } + SetPolygonOffset(polygonOffset); + } - void depthtest_template() - { - const auto depthTest = ReadEnumProperty("depthTest", GdtDepthTestNames, std::extent_v); + void stencil_template() { + const auto stencilMode = ReadEnumProperty("stencil", GdtStencilModeNames, std::extent_v); - SetDepthTest(depthTest); - } + if (stencilMode == StencilMode_e::DISABLED) { + DisableStencil(StencilIndex::FRONT); + DisableStencil(StencilIndex::BACK); + } else { + if (stencilMode == StencilMode_e::TWO_SIDED) { + const auto stencilBackFunc = ReadEnumProperty("stencilFunc2", GdtStencilFuncNames, std::extent_v); + const auto stencilBackOpFail = ReadEnumProperty("stencilOpFail2", GdtStencilOpNames, std::extent_v); + const auto stencilBackOpZFail = ReadEnumProperty("stencilOpZFail2", GdtStencilOpNames, std::extent_v); + const auto stencilBackOpPass = ReadEnumProperty("stencilOpPass2", GdtStencilOpNames, std::extent_v); - void depthwrite_template() - { - const auto depthWrite = ReadEnumProperty("depthWrite", GdtStateBitsOnOffStatusNames, std::extent_v); - const auto blendFunc = ReadStringProperty("blendFunc"); - - if (depthWrite == StateBitsEnabledStatus_e::ENABLED) - SetDepthWrite(true); - else if (depthWrite == StateBitsEnabledStatus_e::DISABLED) - SetDepthWrite(false); - else if (blendFunc == GDT_BLEND_FUNC_ADD) - SetDepthWrite(false); - else if (blendFunc == GDT_BLEND_FUNC_BLEND) - SetDepthWrite(false); - else if (blendFunc == GDT_BLEND_FUNC_MULTIPLY) - SetDepthWrite(false); - else if (blendFunc == GDT_BLEND_FUNC_REPLACE) - SetDepthWrite(true); - else if (blendFunc == GDT_BLEND_FUNC_SCREEN_ADD) - SetDepthWrite(false); - else if (blendFunc == GDT_BLEND_FUNC_CUSTOM) - SetDepthWrite(false); - else - { - std::ostringstream ss; - ss << "Invalid depthWrite blendFunc value: \"" << blendFunc << "\""; - throw GdtReadingException(ss.str()); - } - } + EnableStencil(StencilIndex::BACK, stencilBackFunc, stencilBackOpFail, stencilBackOpZFail, stencilBackOpPass); + } - void gammawrite_template() - { - const auto gammaWrite = ReadEnumProperty("gammaWrite", GdtStateBitsOnOffStatusNames, std::extent_v); + const auto stencilFrontFunc = ReadEnumProperty("stencilFunc1", GdtStencilFuncNames, std::extent_v); + const auto stencilFrontOpFail = ReadEnumProperty("stencilOpFail1", GdtStencilOpNames, std::extent_v); + const auto stencilFrontOpZFail = ReadEnumProperty("stencilOpZFail1", GdtStencilOpNames, std::extent_v); + const auto stencilFrontOpPass = ReadEnumProperty("stencilOpPass1", GdtStencilOpNames, std::extent_v); - if (gammaWrite == StateBitsEnabledStatus_e::UNKNOWN) - { - std::ostringstream ss; - ss << "Invalid gammaWrite blendFunc value: \"\""; - throw GdtReadingException(ss.str()); - } + EnableStencil(StencilIndex::FRONT, stencilFrontFunc, stencilFrontOpFail, stencilFrontOpZFail, stencilFrontOpPass); + } + } - SetGammaWrite(gammaWrite == StateBitsEnabledStatus_e::ENABLED); - } + void SetTechniqueSet(const std::string &techsetName) { + auto *techset = reinterpret_cast *>(m_manager->LoadDependency(ASSET_TYPE_TECHNIQUE_SET, techsetName)); - void polygonoffset_template() - { - const auto polygonOffset = ReadEnumProperty("polygonOffset", GdtPolygonOffsetNames, std::extent_v); + if (techset == nullptr) { + std::ostringstream ss; + ss << "Could not load techset: \"" << techsetName << "\""; + throw GdtReadingException(ss.str()); + } - SetPolygonOffset(polygonOffset); - } + m_dependencies.push_back(techset); + m_material->techniqueSet = techset->Asset(); - void stencil_template() - { - const auto stencilMode = ReadEnumProperty("stencil", GdtStencilModeNames, std::extent_v); - - if (stencilMode == StencilMode_e::DISABLED) - { - DisableStencil(StencilIndex::FRONT); - DisableStencil(StencilIndex::BACK); - } - else - { - if (stencilMode == StencilMode_e::TWO_SIDED) - { - const auto stencilBackFunc = ReadEnumProperty("stencilFunc2", GdtStencilFuncNames, std::extent_v); - const auto stencilBackOpFail = ReadEnumProperty("stencilOpFail2", GdtStencilOpNames, std::extent_v); - const auto stencilBackOpZFail = ReadEnumProperty("stencilOpZFail2", GdtStencilOpNames, std::extent_v); - const auto stencilBackOpPass = ReadEnumProperty("stencilOpPass2", GdtStencilOpNames, std::extent_v); - - EnableStencil(StencilIndex::BACK, stencilBackFunc, stencilBackOpFail, stencilBackOpZFail, stencilBackOpPass); - } - - const auto stencilFrontFunc = ReadEnumProperty("stencilFunc1", GdtStencilFuncNames, std::extent_v); - const auto stencilFrontOpFail = ReadEnumProperty("stencilOpFail1", GdtStencilOpNames, std::extent_v); - const auto stencilFrontOpZFail = ReadEnumProperty("stencilOpZFail1", GdtStencilOpNames, std::extent_v); - const auto stencilFrontOpPass = ReadEnumProperty("stencilOpPass1", GdtStencilOpNames, std::extent_v); - - EnableStencil(StencilIndex::FRONT, stencilFrontFunc, stencilFrontOpFail, stencilFrontOpZFail, stencilFrontOpPass); - } - } + auto *loadingContext = m_manager->GetAssetLoadingContext(); + auto *searchPath = loadingContext->m_raw_search_path; + auto *definitionCache = loadingContext->GetZoneAssetLoaderState(); - void SetTechniqueSet(const std::string& techsetName) - { - auto* techset = reinterpret_cast*>(m_manager->LoadDependency(ASSET_TYPE_TECHNIQUE_SET, techsetName)); - - if (techset == nullptr) - { - std::ostringstream ss; - ss << "Could not load techset: \"" << techsetName << "\""; - throw GdtReadingException(ss.str()); - } - - m_dependencies.push_back(techset); - m_material->techniqueSet = techset->Asset(); - - auto* loadingContext = m_manager->GetAssetLoadingContext(); - auto* searchPath = loadingContext->m_raw_search_path; - auto* definitionCache = loadingContext->GetZoneAssetLoaderState(); - - const auto* techsetDefinition = AssetLoaderTechniqueSet::LoadTechsetDefinition(techsetName, searchPath, definitionCache); - if (techsetDefinition == nullptr) - { - std::ostringstream ss; - ss << "Could not find techset definition for: \"" << techsetName << "\""; - throw GdtReadingException(ss.str()); - } - - SetTechniqueSetStateBits(techsetDefinition); - SetTechniqueSetCameraRegion(techsetDefinition); - } + const auto *techsetDefinition = AssetLoaderTechniqueSet::LoadTechsetDefinition(techsetName, searchPath, definitionCache); + if (techsetDefinition == nullptr) { + std::ostringstream ss; + ss << "Could not find techset definition for: \"" << techsetName << "\""; + throw GdtReadingException(ss.str()); + } - void SetTechniqueSetStateBits(const techset::TechsetDefinition* techsetDefinition) - { - for (auto i = 0; i < TECHNIQUE_COUNT; i++) - { - std::string techniqueName; - if (techsetDefinition->GetTechniqueByIndex(i, techniqueName)) - { - const auto stateBitsForTechnique = GetStateBitsForTechnique(techniqueName); - const auto foundStateBits = std::find_if(m_state_bits.begin(), m_state_bits.end(), - [stateBitsForTechnique](const GfxStateBits& s1) - { - return s1.loadBits[0] == stateBitsForTechnique.loadBits[0] && s1.loadBits[1] == stateBitsForTechnique.loadBits[1]; - }); - - if (foundStateBits != m_state_bits.end()) - { - m_material->stateBitsEntry[i] = static_cast(foundStateBits - m_state_bits.begin()); - } - else - { - m_material->stateBitsEntry[i] = static_cast(m_state_bits.size()); - m_state_bits.push_back(stateBitsForTechnique); - } - } - else - { - m_material->stateBitsEntry[i] = std::numeric_limits::max(); - } - } - } + SetTechniqueSetStateBits(techsetDefinition); + SetTechniqueSetCameraRegion(techsetDefinition); + } + + void SetTechniqueSetStateBits(const techset::TechsetDefinition *techsetDefinition) { + for (auto i = 0; i < TECHNIQUE_COUNT; i++) { + std::string techniqueName; + if (techsetDefinition->GetTechniqueByIndex(i, techniqueName)) { + const auto stateBitsForTechnique = GetStateBitsForTechnique(techniqueName); + const auto foundStateBits = std::find_if(m_state_bits.begin(), m_state_bits.end(), [stateBitsForTechnique](const GfxStateBits &s1) { + return s1.loadBits[0] == stateBitsForTechnique.loadBits[0] && s1.loadBits[1] == stateBitsForTechnique.loadBits[1]; + }); + + if (foundStateBits != m_state_bits.end()) { + m_material->stateBitsEntry[i] = static_cast(foundStateBits - m_state_bits.begin()); + } else { + m_material->stateBitsEntry[i] = static_cast(m_state_bits.size()); + m_state_bits.push_back(stateBitsForTechnique); + } + } else { + m_material->stateBitsEntry[i] = std::numeric_limits::max(); + } + } + } + + GfxStateBits GetStateBitsForTechnique(const std::string &techniqueName) { + const auto *stateMap = GetStateMapForTechnique(techniqueName); + if (!stateMap) + return m_base_state_bits; + + const auto preCalculatedStateBits = m_state_bits_per_state_map.find(stateMap); + if (preCalculatedStateBits != m_state_bits_per_state_map.end()) + return preCalculatedStateBits->second; + + const auto stateBits = CalculateStateBitsWithStateMap(stateMap); + m_state_bits_per_state_map.emplace(stateMap, stateBits); + + return stateBits; + } + + _NODISCARD const state_map::StateMapDefinition *GetStateMapForTechnique(const std::string &techniqueName) const { + const auto *preloadedStateMap = m_state_map_cache->GetStateMapForTechnique(techniqueName); + if (preloadedStateMap) + return preloadedStateMap; + + const auto techniqueFileName = AssetLoaderTechniqueSet::GetTechniqueFileName(techniqueName); + const auto file = m_search_path->Open(techniqueFileName); + if (!file.IsOpen()) + return nullptr; + + state_map::StateMapFromTechniqueExtractor extractor; + const techset::TechniqueFileReader reader(*file.m_stream, techniqueFileName, &extractor); + if (!reader.ReadTechniqueDefinition()) { + m_state_map_cache->SetTechniqueUsesStateMap(techniqueName, nullptr); + return nullptr; + } - GfxStateBits GetStateBitsForTechnique(const std::string& techniqueName) - { - const auto* stateMap = GetStateMapForTechnique(techniqueName); - if (!stateMap) - return m_base_state_bits; + const auto stateMapName = extractor.RetrieveStateMap(); + const auto *loadedStateMap = AssetLoaderTechniqueSet::LoadStateMapDefinition(stateMapName, m_search_path, m_state_map_cache); + m_state_map_cache->SetTechniqueUsesStateMap(techniqueName, loadedStateMap); + + return loadedStateMap; + } + + GfxStateBits CalculateStateBitsWithStateMap(const state_map::StateMapDefinition *stateMap) const { + const state_map::StateMapHandler stateMapHandler(stateMapLayout, *stateMap); + + GfxStateBits outBits{}; + stateMapHandler.ApplyStateMap(m_base_state_bits.loadBits, outBits.loadBits); + + return outBits; + } + + void SetTechniqueSetCameraRegion(const techset::TechsetDefinition *techsetDefinition) const { + std::string tempName; + if (techsetDefinition->GetTechniqueByIndex(TECHNIQUE_LIT, tempName)) { + if (m_material->info.sortKey >= SORTKEY_TRANS_START) + m_material->cameraRegion = CAMERA_REGION_LIT_TRANS; + else + m_material->cameraRegion = CAMERA_REGION_LIT_OPAQUE; + } else if (techsetDefinition->GetTechniqueByIndex(TECHNIQUE_EMISSIVE, tempName)) { + m_material->cameraRegion = CAMERA_REGION_EMISSIVE; + } else { + m_material->cameraRegion = CAMERA_REGION_NONE; + } + } + + void AddMapTexture(const std::string &typeName, const TileMode_e tileMode, GdtFilter_e filterMode, const TextureSemantic semantic, + const std::string &textureName) { + MaterialTextureDef textureDef{}; + textureDef.nameHash = Common::R_HashString(typeName.c_str()); + textureDef.nameStart = typeName[0]; + textureDef.nameEnd = typeName[typeName.size() - 1]; + textureDef.samplerState = 0; + textureDef.semantic = static_cast(semantic); + + switch (tileMode) { + case TileMode_e::TILE_BOTH: + textureDef.samplerState |= SAMPLER_CLAMP_U | SAMPLER_CLAMP_V | SAMPLER_CLAMP_W; + break; + case TileMode_e::TILE_HORIZONTAL: + textureDef.samplerState |= SAMPLER_CLAMP_V; + break; + case TileMode_e::TILE_VERTICAL: + textureDef.samplerState |= SAMPLER_CLAMP_U; + break; + case TileMode_e::UNKNOWN: + case TileMode_e::NO_TILE: + break; + default: + assert(false); + break; + } - const auto preCalculatedStateBits = m_state_bits_per_state_map.find(stateMap); - if (preCalculatedStateBits != m_state_bits_per_state_map.end()) - return preCalculatedStateBits->second; + switch (filterMode) { + case GdtFilter_e::MIP_2X_BILINEAR: + textureDef.samplerState |= SAMPLER_FILTER_ANISO2X | SAMPLER_MIPMAP_NEAREST; + break; + case GdtFilter_e::MIP_2X_TRILINEAR: + textureDef.samplerState |= SAMPLER_FILTER_ANISO2X | SAMPLER_MIPMAP_LINEAR; + break; + case GdtFilter_e::MIP_4X_BILINEAR: + textureDef.samplerState |= SAMPLER_FILTER_ANISO4X | SAMPLER_MIPMAP_NEAREST; + break; + case GdtFilter_e::MIP_4X_TRILINEAR: + textureDef.samplerState |= SAMPLER_FILTER_ANISO4X | SAMPLER_MIPMAP_LINEAR; + break; + case GdtFilter_e::NOMIP_NEAREST: + textureDef.samplerState |= SAMPLER_FILTER_NEAREST | SAMPLER_MIPMAP_DISABLED; + break; + case GdtFilter_e::NOMIP_BILINEAR: + textureDef.samplerState |= SAMPLER_FILTER_LINEAR | SAMPLER_MIPMAP_DISABLED; + break; + default: + assert(false); + break; + } - const auto stateBits = CalculateStateBitsWithStateMap(stateMap); - m_state_bits_per_state_map.emplace(stateMap, stateBits); + auto *image = reinterpret_cast *>(m_manager->LoadDependency(ASSET_TYPE_IMAGE, textureName)); - return stateBits; - } + if (image == nullptr) { + std::ostringstream ss; + ss << "Could not load image: \"" << textureName << "\""; + throw GdtReadingException(ss.str()); + } - _NODISCARD const state_map::StateMapDefinition* GetStateMapForTechnique(const std::string& techniqueName) const - { - const auto* preloadedStateMap = m_state_map_cache->GetStateMapForTechnique(techniqueName); - if (preloadedStateMap) - return preloadedStateMap; - - const auto techniqueFileName = AssetLoaderTechniqueSet::GetTechniqueFileName(techniqueName); - const auto file = m_search_path->Open(techniqueFileName); - if (!file.IsOpen()) - return nullptr; - - state_map::StateMapFromTechniqueExtractor extractor; - const techset::TechniqueFileReader reader(*file.m_stream, techniqueFileName, &extractor); - if (!reader.ReadTechniqueDefinition()) - { - m_state_map_cache->SetTechniqueUsesStateMap(techniqueName, nullptr); - return nullptr; - } - - const auto stateMapName = extractor.RetrieveStateMap(); - const auto* loadedStateMap = AssetLoaderTechniqueSet::LoadStateMapDefinition(stateMapName, m_search_path, m_state_map_cache); - m_state_map_cache->SetTechniqueUsesStateMap(techniqueName, loadedStateMap); - - return loadedStateMap; - } + m_dependencies.push_back(image); + textureDef.u.image = image->Asset(); + + m_textures.push_back(textureDef); + } + + void AddConstant(const std::string &constantName, Vector4f literalData) { + MaterialConstantDef constantDef{}; + constantDef.literal[0] = literalData(0); + constantDef.literal[1] = literalData(1); + constantDef.literal[2] = literalData(2); + constantDef.literal[3] = literalData(3); + strncpy(constantDef.name, constantName.c_str(), std::extent_v); + constantDef.nameHash = Common::R_HashString(constantName.c_str()); + + m_constants.push_back(constantDef); + } + + void SetSort(const unsigned char sort) const { m_material->info.sortKey = sort; } + + void SetTextureAtlas(const unsigned char rowCount, const unsigned char columnCount) const { + m_material->info.textureAtlasRowCount = rowCount; + m_material->info.textureAtlasColumnCount = columnCount; + } + + void SetAlphaTest(const AlphaTest_e alphaTest) { + switch (alphaTest) { + case AlphaTest_e::ALWAYS: + m_base_state_bits.loadBits[0] |= GFXS0_ATEST_DISABLE; + break; + + case AlphaTest_e::GT0: + m_base_state_bits.loadBits[0] |= GFXS0_ATEST_GT_0; + break; + + case AlphaTest_e::LT128: + m_base_state_bits.loadBits[0] |= GFXS0_ATEST_LT_128; + break; + + case AlphaTest_e::GE128: + m_base_state_bits.loadBits[0] |= GFXS0_ATEST_GE_128; + break; + + case AlphaTest_e::UNKNOWN: + default: + std::ostringstream ss; + ss << "Unknown alphatest value: \"" << static_cast(alphaTest) << "\""; + throw GdtReadingException(ss.str()); + } + } - GfxStateBits CalculateStateBitsWithStateMap(const state_map::StateMapDefinition* stateMap) const - { - const state_map::StateMapHandler stateMapHandler(stateMapLayout, *stateMap); + void SetBlendFunc(BlendOp_e blendOp, CustomBlendFunc_e srcFunc, CustomBlendFunc_e destFunc) { + if (blendOp == BlendOp_e::UNKNOWN || srcFunc == CustomBlendFunc_e::UNKNOWN || destFunc == CustomBlendFunc_e::UNKNOWN) { + std::ostringstream ss; + ss << "Unknown SeparateAlphaBlendFunc values: \"\""; + throw GdtReadingException(ss.str()); + } - GfxStateBits outBits{}; - stateMapHandler.ApplyStateMap(m_base_state_bits.loadBits, outBits.loadBits); + m_base_state_bits.loadBits[0] &= ~GFXS0_BLENDOP_RGB_MASK; + m_base_state_bits.loadBits[0] |= ((static_cast(blendOp) - 1) << GFXS0_BLENDOP_RGB_SHIFT) & GFXS0_BLENDOP_RGB_MASK; - return outBits; - } + m_base_state_bits.loadBits[0] &= ~GFXS0_SRCBLEND_RGB_MASK; + m_base_state_bits.loadBits[0] |= ((static_cast(srcFunc) - 1) << GFXS0_SRCBLEND_RGB_SHIFT) & GFXS0_SRCBLEND_RGB_MASK; - void SetTechniqueSetCameraRegion(const techset::TechsetDefinition* techsetDefinition) const - { - std::string tempName; - if (techsetDefinition->GetTechniqueByIndex(TECHNIQUE_LIT, tempName)) - { - if (m_material->info.sortKey >= SORTKEY_TRANS_START) - m_material->cameraRegion = CAMERA_REGION_LIT_TRANS; - else - m_material->cameraRegion = CAMERA_REGION_LIT_OPAQUE; - } - else if (techsetDefinition->GetTechniqueByIndex(TECHNIQUE_EMISSIVE, tempName)) - { - m_material->cameraRegion = CAMERA_REGION_EMISSIVE; - } - else - { - m_material->cameraRegion = CAMERA_REGION_NONE; - } - } + m_base_state_bits.loadBits[0] &= ~GFXS0_DSTBLEND_RGB_MASK; + m_base_state_bits.loadBits[0] |= ((static_cast(destFunc) - 1) << GFXS0_DSTBLEND_RGB_SHIFT) & GFXS0_DSTBLEND_RGB_MASK; + } - void AddMapTexture(const std::string& typeName, const TileMode_e tileMode, GdtFilter_e filterMode, const TextureSemantic semantic, const std::string& textureName) - { - MaterialTextureDef textureDef{}; - textureDef.nameHash = Common::R_HashString(typeName.c_str()); - textureDef.nameStart = typeName[0]; - textureDef.nameEnd = typeName[typeName.size() - 1]; - textureDef.samplerState = 0; - textureDef.semantic = static_cast(semantic); - - switch (tileMode) - { - case TileMode_e::TILE_BOTH: - textureDef.samplerState |= SAMPLER_CLAMP_U | SAMPLER_CLAMP_V | SAMPLER_CLAMP_W; - break; - case TileMode_e::TILE_HORIZONTAL: - textureDef.samplerState |= SAMPLER_CLAMP_V; - break; - case TileMode_e::TILE_VERTICAL: - textureDef.samplerState |= SAMPLER_CLAMP_U; - break; - case TileMode_e::UNKNOWN: - case TileMode_e::NO_TILE: - break; - default: - assert(false); - break; - } - - switch (filterMode) - { - case GdtFilter_e::MIP_2X_BILINEAR: - textureDef.samplerState |= SAMPLER_FILTER_ANISO2X | SAMPLER_MIPMAP_NEAREST; - break; - case GdtFilter_e::MIP_2X_TRILINEAR: - textureDef.samplerState |= SAMPLER_FILTER_ANISO2X | SAMPLER_MIPMAP_LINEAR; - break; - case GdtFilter_e::MIP_4X_BILINEAR: - textureDef.samplerState |= SAMPLER_FILTER_ANISO4X | SAMPLER_MIPMAP_NEAREST; - break; - case GdtFilter_e::MIP_4X_TRILINEAR: - textureDef.samplerState |= SAMPLER_FILTER_ANISO4X | SAMPLER_MIPMAP_LINEAR; - break; - case GdtFilter_e::NOMIP_NEAREST: - textureDef.samplerState |= SAMPLER_FILTER_NEAREST | SAMPLER_MIPMAP_DISABLED; - break; - case GdtFilter_e::NOMIP_BILINEAR: - textureDef.samplerState |= SAMPLER_FILTER_LINEAR | SAMPLER_MIPMAP_DISABLED; - break; - default: - assert(false); - break; - } - - auto* image = reinterpret_cast*>(m_manager->LoadDependency(ASSET_TYPE_IMAGE, textureName)); - - if (image == nullptr) - { - std::ostringstream ss; - ss << "Could not load image: \"" << textureName << "\""; - throw GdtReadingException(ss.str()); - } - - m_dependencies.push_back(image); - textureDef.u.image = image->Asset(); - - m_textures.push_back(textureDef); - } + void SetSeparateAlphaBlendFunc(BlendOp_e blendOp, CustomBlendFunc_e srcFunc, CustomBlendFunc_e destFunc) { + if (blendOp == BlendOp_e::UNKNOWN || srcFunc == CustomBlendFunc_e::UNKNOWN || destFunc == CustomBlendFunc_e::UNKNOWN) { + std::ostringstream ss; + ss << "Unknown SeparateAlphaBlendFunc values: \"\""; + throw GdtReadingException(ss.str()); + } - void AddConstant(const std::string& constantName, Vector4f literalData) - { - MaterialConstantDef constantDef{}; - constantDef.literal[0] = literalData(0); - constantDef.literal[1] = literalData(1); - constantDef.literal[2] = literalData(2); - constantDef.literal[3] = literalData(3); - strncpy(constantDef.name, constantName.c_str(), std::extent_v); - constantDef.nameHash = Common::R_HashString(constantName.c_str()); - - m_constants.push_back(constantDef); - } + m_base_state_bits.loadBits[0] &= ~GFXS0_BLENDOP_ALPHA_MASK; + m_base_state_bits.loadBits[0] |= ((static_cast(blendOp) - 1) << GFXS0_BLENDOP_ALPHA_SHIFT) & GFXS0_BLENDOP_ALPHA_MASK; - void SetSort(const unsigned char sort) const - { - m_material->info.sortKey = sort; - } + m_base_state_bits.loadBits[0] &= ~GFXS0_SRCBLEND_ALPHA_MASK; + m_base_state_bits.loadBits[0] |= ((static_cast(srcFunc) - 1) << GFXS0_SRCBLEND_ALPHA_SHIFT) & GFXS0_SRCBLEND_ALPHA_MASK; - void SetTextureAtlas(const unsigned char rowCount, const unsigned char columnCount) const - { - m_material->info.textureAtlasRowCount = rowCount; - m_material->info.textureAtlasColumnCount = columnCount; - } + m_base_state_bits.loadBits[0] &= ~GFXS0_DSTBLEND_ALPHA_MASK; + m_base_state_bits.loadBits[0] |= ((static_cast(destFunc) - 1) << GFXS0_DSTBLEND_ALPHA_SHIFT) & GFXS0_DSTBLEND_ALPHA_MASK; + } - void SetAlphaTest(const AlphaTest_e alphaTest) - { - switch (alphaTest) - { - case AlphaTest_e::ALWAYS: - m_base_state_bits.loadBits[0] |= GFXS0_ATEST_DISABLE; - break; - - case AlphaTest_e::GT0: - m_base_state_bits.loadBits[0] |= GFXS0_ATEST_GT_0; - break; - - case AlphaTest_e::LT128: - m_base_state_bits.loadBits[0] |= GFXS0_ATEST_LT_128; - break; - - case AlphaTest_e::GE128: - m_base_state_bits.loadBits[0] |= GFXS0_ATEST_GE_128; - break; - - case AlphaTest_e::UNKNOWN: - default: - std::ostringstream ss; - ss << "Unknown alphatest value: \"" << static_cast(alphaTest) << "\""; - throw GdtReadingException(ss.str()); - } - } + void SetColorWrite(const StateBitsEnabledStatus_e colorWriteRed, const StateBitsEnabledStatus_e colorWriteGreen, + const StateBitsEnabledStatus_e colorWriteBlue, const StateBitsEnabledStatus_e colorWriteAlpha) { + if (colorWriteRed == StateBitsEnabledStatus_e::UNKNOWN || colorWriteGreen == StateBitsEnabledStatus_e::UNKNOWN || + colorWriteBlue == StateBitsEnabledStatus_e::UNKNOWN || colorWriteAlpha == StateBitsEnabledStatus_e::UNKNOWN) { + std::ostringstream ss; + ss << "Unknown ColorWrite values: \"\""; + throw GdtReadingException(ss.str()); + } - void SetBlendFunc(BlendOp_e blendOp, CustomBlendFunc_e srcFunc, CustomBlendFunc_e destFunc) - { - if (blendOp == BlendOp_e::UNKNOWN || srcFunc == CustomBlendFunc_e::UNKNOWN || destFunc == CustomBlendFunc_e::UNKNOWN) - { - std::ostringstream ss; - ss << "Unknown SeparateAlphaBlendFunc values: \"\""; - throw GdtReadingException(ss.str()); - } + if (colorWriteRed != colorWriteGreen || colorWriteRed != colorWriteBlue) { + std::ostringstream ss; + ss << "Invalid ColorWrite values: values for rgb must match"; + throw GdtReadingException(ss.str()); + } - m_base_state_bits.loadBits[0] &= ~GFXS0_BLENDOP_RGB_MASK; - m_base_state_bits.loadBits[0] |= ((static_cast(blendOp) - 1) << GFXS0_BLENDOP_RGB_SHIFT) & GFXS0_BLENDOP_RGB_MASK; + m_base_state_bits.loadBits[0] &= ~GFXS0_COLORWRITE_MASK; + if (colorWriteRed == StateBitsEnabledStatus_e::ENABLED) + m_base_state_bits.loadBits[0] |= GFXS0_COLORWRITE_RGB; + if (colorWriteAlpha == StateBitsEnabledStatus_e::ENABLED) + m_base_state_bits.loadBits[0] |= GFXS0_COLORWRITE_ALPHA; + } + + void SetCullFace(const CullFace_e cullFace) { + if (cullFace == CullFace_e::UNKNOWN) { + std::ostringstream ss; + ss << "Unknown cullFace values: \"\""; + throw GdtReadingException(ss.str()); + } - m_base_state_bits.loadBits[0] &= ~GFXS0_SRCBLEND_RGB_MASK; - m_base_state_bits.loadBits[0] |= ((static_cast(srcFunc) - 1) << GFXS0_SRCBLEND_RGB_SHIFT) & GFXS0_SRCBLEND_RGB_MASK; + m_base_state_bits.loadBits[0] &= ~GFXS0_CULL_MASK; - m_base_state_bits.loadBits[0] &= ~GFXS0_DSTBLEND_RGB_MASK; - m_base_state_bits.loadBits[0] |= ((static_cast(destFunc) - 1) << GFXS0_DSTBLEND_RGB_SHIFT) & GFXS0_DSTBLEND_RGB_MASK; - } + if (cullFace == CullFace_e::FRONT) { + m_base_state_bits.loadBits[0] |= GFXS0_CULL_FRONT; + } else if (cullFace == CullFace_e::BACK) { + m_base_state_bits.loadBits[0] |= GFXS0_CULL_BACK; + } else { + assert(cullFace == CullFace_e::NONE); + m_base_state_bits.loadBits[0] |= GFXS0_CULL_NONE; + } + } - void SetSeparateAlphaBlendFunc(BlendOp_e blendOp, CustomBlendFunc_e srcFunc, CustomBlendFunc_e destFunc) - { - if (blendOp == BlendOp_e::UNKNOWN || srcFunc == CustomBlendFunc_e::UNKNOWN || destFunc == CustomBlendFunc_e::UNKNOWN) - { - std::ostringstream ss; - ss << "Unknown SeparateAlphaBlendFunc values: \"\""; - throw GdtReadingException(ss.str()); - } + void SetDepthTest(const DepthTest_e depthTest) { + m_base_state_bits.loadBits[1] &= GFXS1_DEPTHTEST_MASK; - m_base_state_bits.loadBits[0] &= ~GFXS0_BLENDOP_ALPHA_MASK; - m_base_state_bits.loadBits[0] |= ((static_cast(blendOp) - 1) << GFXS0_BLENDOP_ALPHA_SHIFT) & GFXS0_BLENDOP_ALPHA_MASK; + switch (depthTest) { + case DepthTest_e::LESS_EQUAL: + m_base_state_bits.loadBits[1] |= GFXS1_DEPTHTEST_LESSEQUAL; + break; - m_base_state_bits.loadBits[0] &= ~GFXS0_SRCBLEND_ALPHA_MASK; - m_base_state_bits.loadBits[0] |= ((static_cast(srcFunc) - 1) << GFXS0_SRCBLEND_ALPHA_SHIFT) & GFXS0_SRCBLEND_ALPHA_MASK; + case DepthTest_e::LESS: + m_base_state_bits.loadBits[1] |= GFXS1_DEPTHTEST_LESS; + break; - m_base_state_bits.loadBits[0] &= ~GFXS0_DSTBLEND_ALPHA_MASK; - m_base_state_bits.loadBits[0] |= ((static_cast(destFunc) - 1) << GFXS0_DSTBLEND_ALPHA_SHIFT) & GFXS0_DSTBLEND_ALPHA_MASK; - } + case DepthTest_e::EQUAL: + m_base_state_bits.loadBits[1] |= GFXS1_DEPTHTEST_EQUAL; + break; - void SetColorWrite(const StateBitsEnabledStatus_e colorWriteRed, const StateBitsEnabledStatus_e colorWriteGreen, const StateBitsEnabledStatus_e colorWriteBlue, - const StateBitsEnabledStatus_e colorWriteAlpha) - { - if (colorWriteRed == StateBitsEnabledStatus_e::UNKNOWN || colorWriteGreen == StateBitsEnabledStatus_e::UNKNOWN - || colorWriteBlue == StateBitsEnabledStatus_e::UNKNOWN || colorWriteAlpha == StateBitsEnabledStatus_e::UNKNOWN) - { - std::ostringstream ss; - ss << "Unknown ColorWrite values: \"\""; - throw GdtReadingException(ss.str()); - } - - if (colorWriteRed != colorWriteGreen || colorWriteRed != colorWriteBlue) - { - std::ostringstream ss; - ss << "Invalid ColorWrite values: values for rgb must match"; - throw GdtReadingException(ss.str()); - } - - m_base_state_bits.loadBits[0] &= ~GFXS0_COLORWRITE_MASK; - if (colorWriteRed == StateBitsEnabledStatus_e::ENABLED) - m_base_state_bits.loadBits[0] |= GFXS0_COLORWRITE_RGB; - if (colorWriteAlpha == StateBitsEnabledStatus_e::ENABLED) - m_base_state_bits.loadBits[0] |= GFXS0_COLORWRITE_ALPHA; - } + case DepthTest_e::ALWAYS: + m_base_state_bits.loadBits[1] |= GFXS1_DEPTHTEST_ALWAYS; + break; - void SetCullFace(const CullFace_e cullFace) - { - if (cullFace == CullFace_e::UNKNOWN) - { - std::ostringstream ss; - ss << "Unknown cullFace values: \"\""; - throw GdtReadingException(ss.str()); - } - - m_base_state_bits.loadBits[0] &= ~GFXS0_CULL_MASK; - - if (cullFace == CullFace_e::FRONT) - { - m_base_state_bits.loadBits[0] |= GFXS0_CULL_FRONT; - } - else if (cullFace == CullFace_e::BACK) - { - m_base_state_bits.loadBits[0] |= GFXS0_CULL_BACK; - } - else - { - assert(cullFace == CullFace_e::NONE); - m_base_state_bits.loadBits[0] |= GFXS0_CULL_NONE; - } - } + case DepthTest_e::DISABLE: + m_base_state_bits.loadBits[1] |= GFXS1_DEPTHTEST_DISABLE; + break; - void SetDepthTest(const DepthTest_e depthTest) - { - m_base_state_bits.loadBits[1] &= GFXS1_DEPTHTEST_MASK; - - switch (depthTest) - { - case DepthTest_e::LESS_EQUAL: - m_base_state_bits.loadBits[1] |= GFXS1_DEPTHTEST_LESSEQUAL; - break; - - case DepthTest_e::LESS: - m_base_state_bits.loadBits[1] |= GFXS1_DEPTHTEST_LESS; - break; - - case DepthTest_e::EQUAL: - m_base_state_bits.loadBits[1] |= GFXS1_DEPTHTEST_EQUAL; - break; - - case DepthTest_e::ALWAYS: - m_base_state_bits.loadBits[1] |= GFXS1_DEPTHTEST_ALWAYS; - break; - - case DepthTest_e::DISABLE: - m_base_state_bits.loadBits[1] |= GFXS1_DEPTHTEST_DISABLE; - break; - - case DepthTest_e::UNKNOWN: - default: - std::ostringstream ss; - ss << "Unknown depthTest values: \"\""; - throw GdtReadingException(ss.str()); - } - } + case DepthTest_e::UNKNOWN: + default: + std::ostringstream ss; + ss << "Unknown depthTest values: \"\""; + throw GdtReadingException(ss.str()); + } + } - void SetDepthWrite(const bool depthWrite) - { - m_base_state_bits.loadBits[1] &= ~GFXS1_DEPTHWRITE; + void SetDepthWrite(const bool depthWrite) { + m_base_state_bits.loadBits[1] &= ~GFXS1_DEPTHWRITE; - if (depthWrite) - m_base_state_bits.loadBits[1] |= GFXS1_DEPTHWRITE; - } + if (depthWrite) + m_base_state_bits.loadBits[1] |= GFXS1_DEPTHWRITE; + } - void SetGammaWrite(const bool gammaWrite) - { - m_base_state_bits.loadBits[0] &= ~GFXS0_GAMMAWRITE; + void SetGammaWrite(const bool gammaWrite) { + m_base_state_bits.loadBits[0] &= ~GFXS0_GAMMAWRITE; - if (gammaWrite) - m_base_state_bits.loadBits[0] |= GFXS0_GAMMAWRITE; - } + if (gammaWrite) + m_base_state_bits.loadBits[0] |= GFXS0_GAMMAWRITE; + } - void SetPolygonOffset(const PolygonOffset_e polygonOffset) - { - if (polygonOffset == PolygonOffset_e::UNKNOWN) - { - std::ostringstream ss; - ss << "Unknown polygonOffset values: \"\""; - throw GdtReadingException(ss.str()); - } - - m_base_state_bits.loadBits[1] &= ~GFXS1_POLYGON_OFFSET_MASK; - m_base_state_bits.loadBits[1] |= ((static_cast(polygonOffset) - 1) << GFXS1_POLYGON_OFFSET_SHIFT) & GFXS1_POLYGON_OFFSET_MASK; - } + void SetPolygonOffset(const PolygonOffset_e polygonOffset) { + if (polygonOffset == PolygonOffset_e::UNKNOWN) { + std::ostringstream ss; + ss << "Unknown polygonOffset values: \"\""; + throw GdtReadingException(ss.str()); + } - static void GetStencilMasksForIndex(const StencilIndex stencil, unsigned& enabledMask, unsigned& funcShift, unsigned& funcMask, unsigned& opFailShift, unsigned& opFailMask, - unsigned& opZFailShift, unsigned& opZFailMask, unsigned& opPassShift, unsigned& opPassMask) - { - if (stencil == StencilIndex::FRONT) - { - enabledMask = GFXS1_STENCIL_FRONT_ENABLE; - funcShift = GFXS1_STENCIL_FRONT_FUNC_SHIFT; - funcMask = GFXS1_STENCIL_FRONT_FUNC_MASK; - opFailShift = GFXS1_STENCIL_FRONT_FAIL_SHIFT; - opFailMask = GFXS1_STENCIL_FRONT_FAIL_MASK; - opZFailShift = GFXS1_STENCIL_FRONT_ZFAIL_SHIFT; - opZFailMask = GFXS1_STENCIL_FRONT_ZFAIL_MASK; - opPassShift = GFXS1_STENCIL_FRONT_PASS_SHIFT; - opPassMask = GFXS1_STENCIL_FRONT_PASS_MASK; - } - else - { - assert(stencil == StencilIndex::BACK); - - enabledMask = GFXS1_STENCIL_BACK_ENABLE; - funcShift = GFXS1_STENCIL_BACK_FUNC_SHIFT; - funcMask = GFXS1_STENCIL_BACK_FUNC_MASK; - opFailShift = GFXS1_STENCIL_BACK_FAIL_SHIFT; - opFailMask = GFXS1_STENCIL_BACK_FAIL_MASK; - opZFailShift = GFXS1_STENCIL_BACK_ZFAIL_SHIFT; - opZFailMask = GFXS1_STENCIL_BACK_ZFAIL_MASK; - opPassShift = GFXS1_STENCIL_BACK_PASS_SHIFT; - opPassMask = GFXS1_STENCIL_BACK_PASS_MASK; - } - } + m_base_state_bits.loadBits[1] &= ~GFXS1_POLYGON_OFFSET_MASK; + m_base_state_bits.loadBits[1] |= ((static_cast(polygonOffset) - 1) << GFXS1_POLYGON_OFFSET_SHIFT) & GFXS1_POLYGON_OFFSET_MASK; + } + + static void GetStencilMasksForIndex(const StencilIndex stencil, unsigned &enabledMask, unsigned &funcShift, unsigned &funcMask, unsigned &opFailShift, + unsigned &opFailMask, unsigned &opZFailShift, unsigned &opZFailMask, unsigned &opPassShift, unsigned &opPassMask) { + if (stencil == StencilIndex::FRONT) { + enabledMask = GFXS1_STENCIL_FRONT_ENABLE; + funcShift = GFXS1_STENCIL_FRONT_FUNC_SHIFT; + funcMask = GFXS1_STENCIL_FRONT_FUNC_MASK; + opFailShift = GFXS1_STENCIL_FRONT_FAIL_SHIFT; + opFailMask = GFXS1_STENCIL_FRONT_FAIL_MASK; + opZFailShift = GFXS1_STENCIL_FRONT_ZFAIL_SHIFT; + opZFailMask = GFXS1_STENCIL_FRONT_ZFAIL_MASK; + opPassShift = GFXS1_STENCIL_FRONT_PASS_SHIFT; + opPassMask = GFXS1_STENCIL_FRONT_PASS_MASK; + } else { + assert(stencil == StencilIndex::BACK); + + enabledMask = GFXS1_STENCIL_BACK_ENABLE; + funcShift = GFXS1_STENCIL_BACK_FUNC_SHIFT; + funcMask = GFXS1_STENCIL_BACK_FUNC_MASK; + opFailShift = GFXS1_STENCIL_BACK_FAIL_SHIFT; + opFailMask = GFXS1_STENCIL_BACK_FAIL_MASK; + opZFailShift = GFXS1_STENCIL_BACK_ZFAIL_SHIFT; + opZFailMask = GFXS1_STENCIL_BACK_ZFAIL_MASK; + opPassShift = GFXS1_STENCIL_BACK_PASS_SHIFT; + opPassMask = GFXS1_STENCIL_BACK_PASS_MASK; + } + } - void DisableStencil(const StencilIndex stencil) - { - unsigned enabledMask, funcShift, funcMask, opFailShift, opFailMask, opZFailShift, opZFailMask, opPassShift, opPassMask; - GetStencilMasksForIndex(stencil, enabledMask, funcShift, funcMask, opFailShift, opFailMask, opZFailShift, opZFailMask, opPassShift, opPassMask); + void DisableStencil(const StencilIndex stencil) { + unsigned enabledMask, funcShift, funcMask, opFailShift, opFailMask, opZFailShift, opZFailMask, opPassShift, opPassMask; + GetStencilMasksForIndex(stencil, enabledMask, funcShift, funcMask, opFailShift, opFailMask, opZFailShift, opZFailMask, opPassShift, opPassMask); - m_base_state_bits.loadBits[1] &= ~(enabledMask | funcMask | opFailMask | opZFailMask | opPassMask); - } + m_base_state_bits.loadBits[1] &= ~(enabledMask | funcMask | opFailMask | opZFailMask | opPassMask); + } - void EnableStencil(const StencilIndex stencil, StencilFunc_e stencilFunc, StencilOp_e stencilOpFail, StencilOp_e stencilOpZFail, StencilOp_e stencilOpPass) - { - unsigned enabledMask, funcShift, funcMask, opFailShift, opFailMask, opZFailShift, opZFailMask, opPassShift, opPassMask; - GetStencilMasksForIndex(stencil, enabledMask, funcShift, funcMask, opFailShift, opFailMask, opZFailShift, opZFailMask, opPassShift, opPassMask); + void EnableStencil(const StencilIndex stencil, StencilFunc_e stencilFunc, StencilOp_e stencilOpFail, StencilOp_e stencilOpZFail, StencilOp_e stencilOpPass) { + unsigned enabledMask, funcShift, funcMask, opFailShift, opFailMask, opZFailShift, opZFailMask, opPassShift, opPassMask; + GetStencilMasksForIndex(stencil, enabledMask, funcShift, funcMask, opFailShift, opFailMask, opZFailShift, opZFailMask, opPassShift, opPassMask); - m_base_state_bits.loadBits[1] |= enabledMask; + m_base_state_bits.loadBits[1] |= enabledMask; - m_base_state_bits.loadBits[1] &= ~funcMask; - m_base_state_bits.loadBits[1] |= ((static_cast(stencilFunc) - 1) << funcShift) & funcMask; + m_base_state_bits.loadBits[1] &= ~funcMask; + m_base_state_bits.loadBits[1] |= ((static_cast(stencilFunc) - 1) << funcShift) & funcMask; - m_base_state_bits.loadBits[1] &= ~opFailMask; - m_base_state_bits.loadBits[1] |= ((static_cast(stencilOpFail) - 1) << opFailShift) & opFailMask; + m_base_state_bits.loadBits[1] &= ~opFailMask; + m_base_state_bits.loadBits[1] |= ((static_cast(stencilOpFail) - 1) << opFailShift) & opFailMask; - m_base_state_bits.loadBits[1] &= ~opZFailMask; - m_base_state_bits.loadBits[1] |= ((static_cast(stencilOpZFail) - 1) << opZFailShift) & opZFailMask; + m_base_state_bits.loadBits[1] &= ~opZFailMask; + m_base_state_bits.loadBits[1] |= ((static_cast(stencilOpZFail) - 1) << opZFailShift) & opZFailMask; - m_base_state_bits.loadBits[1] &= ~opPassMask; - m_base_state_bits.loadBits[1] |= ((static_cast(stencilOpPass) - 1) << opPassShift) & opPassMask; - } + m_base_state_bits.loadBits[1] &= ~opPassMask; + m_base_state_bits.loadBits[1] |= ((static_cast(stencilOpPass) - 1) << opPassShift) & opPassMask; + } - void FinalizeMaterial() const - { - if (!m_textures.empty()) - { - m_material->textureTable = static_cast(m_memory->Alloc(sizeof(MaterialTextureDef) * m_textures.size())); - m_material->textureCount = static_cast(m_textures.size()); - memcpy(m_material->textureTable, m_textures.data(), sizeof(MaterialTextureDef) * m_textures.size()); - } - else - { - m_material->textureTable = nullptr; - m_material->textureCount = 0u; - } - - if (!m_constants.empty()) - { - m_material->constantTable = static_cast(m_memory->Alloc(sizeof(MaterialConstantDef) * m_constants.size())); - m_material->constantCount = static_cast(m_constants.size()); - memcpy(m_material->constantTable, m_constants.data(), sizeof(MaterialConstantDef) * m_constants.size()); - } - else - { - m_material->constantTable = nullptr; - m_material->constantCount = 0u; - } - - if (!m_state_bits.empty()) - { - m_material->stateBitsTable = static_cast(m_memory->Alloc(sizeof(GfxStateBits) * m_state_bits.size())); - m_material->stateBitsCount = static_cast(m_state_bits.size()); - memcpy(m_material->stateBitsTable, m_state_bits.data(), sizeof(GfxStateBits) * m_state_bits.size()); - } - else - { - m_material->stateBitsTable = nullptr; - m_material->stateBitsCount = 0u; - } - } + void FinalizeMaterial() const { + if (!m_textures.empty()) { + m_material->textureTable = static_cast(m_memory->Alloc(sizeof(MaterialTextureDef) * m_textures.size())); + m_material->textureCount = static_cast(m_textures.size()); + memcpy(m_material->textureTable, m_textures.data(), sizeof(MaterialTextureDef) * m_textures.size()); + } else { + m_material->textureTable = nullptr; + m_material->textureCount = 0u; + } - static size_t GetIndexForString(const std::string& propertyName, const std::string& value, const char** validValuesArray, const size_t validValuesArraySize) - { - for (auto i = 0u; i < validValuesArraySize; i++) - { - if (validValuesArray[i] == value) - return i; - } - - std::ostringstream ss; - ss << "Unknown " << propertyName << " value: \"" << value << "\""; - throw GdtReadingException(ss.str()); - } + if (!m_constants.empty()) { + m_material->constantTable = static_cast(m_memory->Alloc(sizeof(MaterialConstantDef) * m_constants.size())); + m_material->constantCount = static_cast(m_constants.size()); + memcpy(m_material->constantTable, m_constants.data(), sizeof(MaterialConstantDef) * m_constants.size()); + } else { + m_material->constantTable = nullptr; + m_material->constantCount = 0u; + } - template - T ReadEnumProperty(const std::string& propertyName, const char** validValuesArray, const size_t validValuesArraySize) const - { - return static_cast(GetIndexForString(propertyName, ReadStringProperty(propertyName), validValuesArray, validValuesArraySize)); - } + if (!m_state_bits.empty()) { + m_material->stateBitsTable = static_cast(m_memory->Alloc(sizeof(GfxStateBits) * m_state_bits.size())); + m_material->stateBitsCount = static_cast(m_state_bits.size()); + memcpy(m_material->stateBitsTable, m_state_bits.data(), sizeof(GfxStateBits) * m_state_bits.size()); + } else { + m_material->stateBitsTable = nullptr; + m_material->stateBitsCount = 0u; + } + } - MemoryManager* m_memory; - ISearchPath* m_search_path; - IAssetLoadingManager* m_manager; - techset::TechniqueStateMapCache* m_state_map_cache; - std::unordered_map m_state_bits_per_state_map; - std::vector m_dependencies; - - Material* m_material; - GfxStateBits m_base_state_bits; - std::vector m_state_bits; - std::vector m_textures; - std::vector m_constants; - }; -} + static size_t GetIndexForString(const std::string &propertyName, const std::string &value, const char **validValuesArray, const size_t validValuesArraySize) { + for (auto i = 0u; i < validValuesArraySize; i++) { + if (validValuesArray[i] == value) + return i; + } -void* AssetLoaderMaterial::CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) -{ - auto* material = memory->Create(); - memset(material, 0, sizeof(Material)); - material->info.name = memory->Dup(assetName.c_str()); - return material; + std::ostringstream ss; + ss << "Unknown " << propertyName << " value: \"" << value << "\""; + throw GdtReadingException(ss.str()); + } + + template T ReadEnumProperty(const std::string &propertyName, const char **validValuesArray, const size_t validValuesArraySize) const { + return static_cast(GetIndexForString(propertyName, ReadStringProperty(propertyName), validValuesArray, validValuesArraySize)); + } + + MemoryManager *m_memory; + ISearchPath *m_search_path; + IAssetLoadingManager *m_manager; + techset::TechniqueStateMapCache *m_state_map_cache; + std::unordered_map m_state_bits_per_state_map; + std::vector m_dependencies; + + Material *m_material; + GfxStateBits m_base_state_bits; + std::vector m_state_bits; + std::vector m_textures; + std::vector m_constants; +}; +} // namespace IW4 + +void *AssetLoaderMaterial::CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) { + auto *material = memory->Create(); + memset(material, 0, sizeof(Material)); + material->info.name = memory->Dup(assetName.c_str()); + return material; } -bool AssetLoaderMaterial::CanLoadFromGdt() const -{ - return true; -} +bool AssetLoaderMaterial::CanLoadFromGdt() const { return true; } -bool AssetLoaderMaterial::LoadFromGdt(const std::string& assetName, IGdtQueryable* gdtQueryable, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const -{ - const auto* entry = gdtQueryable->GetGdtEntryByGdfAndName(ObjConstants::GDF_FILENAME_MATERIAL, assetName); - if (!entry) - return false; +bool AssetLoaderMaterial::LoadFromGdt(const std::string &assetName, IGdtQueryable *gdtQueryable, MemoryManager *memory, IAssetLoadingManager *manager, + Zone *zone) const { + const auto *entry = gdtQueryable->GetGdtEntryByGdfAndName(ObjConstants::GDF_FILENAME_MATERIAL, assetName); + if (!entry) + return false; - MaterialGdtLoader loader(*entry, memory, manager->GetAssetLoadingContext()->m_raw_search_path, manager); + MaterialGdtLoader loader(*entry, memory, manager->GetAssetLoadingContext()->m_raw_search_path, manager); - try - { - if (loader.Load()) - manager->AddAsset(ASSET_TYPE_MATERIAL, assetName, loader.GetMaterial(), loader.GetDependencies(), std::vector()); - } - catch (const SkipMaterialException&) - { - return false; - } - catch (const GdtReadingException& e) - { - std::cerr << "Error while trying to load material from gdt: " << e.what() << " @ GdtEntry \"" << entry->m_name << "\"\n"; - return false; - } + try { + if (loader.Load()) + manager->AddAsset(ASSET_TYPE_MATERIAL, assetName, loader.GetMaterial(), loader.GetDependencies(), std::vector()); + } catch (const SkipMaterialException &) { + return false; + } catch (const GdtReadingException &e) { + std::cerr << "Error while trying to load material from gdt: " << e.what() << " @ GdtEntry \"" << entry->m_name << "\"\n"; + return false; + } - return true; + return true; } diff --git a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderMaterial.h b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderMaterial.h index 26c363332..6580ef981 100644 --- a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderMaterial.h +++ b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderMaterial.h @@ -1,16 +1,14 @@ #pragma once -#include "Game/IW4/IW4.h" #include "AssetLoading/BasicAssetLoader.h" +#include "Game/IW4/IW4.h" #include "SearchPath/ISearchPath.h" -namespace IW4 -{ - class AssetLoaderMaterial final : public BasicAssetLoader - { - public: - _NODISCARD void* CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) override; - _NODISCARD bool CanLoadFromGdt() const override; - bool LoadFromGdt(const std::string& assetName, IGdtQueryable* gdtQueryable, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const override; - }; -} +namespace IW4 { +class AssetLoaderMaterial final : public BasicAssetLoader { +public: + _NODISCARD void *CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) override; + _NODISCARD bool CanLoadFromGdt() const override; + bool LoadFromGdt(const std::string &assetName, IGdtQueryable *gdtQueryable, MemoryManager *memory, IAssetLoadingManager *manager, Zone *zone) const override; +}; +} // namespace IW4 diff --git a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderMenuDef.cpp b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderMenuDef.cpp index a3dfabbf4..f71994175 100644 --- a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderMenuDef.cpp +++ b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderMenuDef.cpp @@ -2,16 +2,15 @@ #include -#include "ObjLoading.h" #include "Game/IW4/IW4.h" +#include "ObjLoading.h" #include "Pool/GlobalAssetPool.h" using namespace IW4; -void* AssetLoaderMenuDef::CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) -{ - auto* menu = memory->Create(); - memset(menu, 0, sizeof(menuDef_t)); - menu->window.name = memory->Dup(assetName.c_str()); - return menu; +void *AssetLoaderMenuDef::CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) { + auto *menu = memory->Create(); + memset(menu, 0, sizeof(menuDef_t)); + menu->window.name = memory->Dup(assetName.c_str()); + return menu; } diff --git a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderMenuDef.h b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderMenuDef.h index 1c264b991..99c76af4c 100644 --- a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderMenuDef.h +++ b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderMenuDef.h @@ -1,14 +1,12 @@ #pragma once -#include "Game/IW4/IW4.h" #include "AssetLoading/BasicAssetLoader.h" +#include "Game/IW4/IW4.h" #include "SearchPath/ISearchPath.h" -namespace IW4 -{ - class AssetLoaderMenuDef final : public BasicAssetLoader - { - public: - _NODISCARD void* CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) override; - }; -} +namespace IW4 { +class AssetLoaderMenuDef final : public BasicAssetLoader { +public: + _NODISCARD void *CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) override; +}; +} // namespace IW4 diff --git a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderMenuList.cpp b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderMenuList.cpp index 16fa7bad5..501ea7de2 100644 --- a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderMenuList.cpp +++ b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderMenuList.cpp @@ -3,205 +3,184 @@ #include #include -#include "ObjLoading.h" #include "Game/IW4/IW4.h" #include "Game/IW4/Menu/MenuConversionZoneStateIW4.h" #include "Game/IW4/Menu/MenuConverterIW4.h" +#include "ObjLoading.h" #include "Parsing/Menu/MenuFileReader.h" #include "Pool/GlobalAssetPool.h" using namespace IW4; -namespace IW4 -{ - class MenuLoader - { - public: - static bool ProcessParsedResults(const std::string& fileName, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager, menu::ParsingResult* parsingResult, - menu::MenuAssetZoneState* zoneState, MenuConversionZoneState* conversionState, std::vector& menus, - std::vector& menuListDependencies) - { - const auto menuCount = parsingResult->m_menus.size(); - const auto functionCount = parsingResult->m_functions.size(); - const auto menuLoadCount = parsingResult->m_menus_to_load.size(); - auto totalItemCount = 0u; - for (const auto& menu : parsingResult->m_menus) - totalItemCount += menu->m_items.size(); - - std::cout << "Successfully read menu file \"" << fileName << "\" (" << menuLoadCount << " loads, " << menuCount << " menus, " << functionCount << " functions, " << totalItemCount << - " items)\n"; - - // Add all functions to the zone state to make them available for all menus to be converted - for (auto& function : parsingResult->m_functions) - zoneState->AddFunction(std::move(function)); - - // Prepare a list of all menus of this file - std::vector*> allMenusOfFile; - allMenusOfFile.reserve(parsingResult->m_menus.size()); - - // Convert all menus and add them as assets - for (auto& menu : parsingResult->m_menus) - { - MenuConverter converter(ObjLoading::Configuration.MenuNoOptimization, searchPath, memory, manager); - auto* menuAsset = converter.ConvertMenu(*menu); - if (menuAsset == nullptr) - { - std::cout << "Failed to convert menu file \"" << menu->m_name << "\"\n"; - return false; - } - - menus.push_back(menuAsset); - auto* menuAssetInfo = manager->AddAsset(ASSET_TYPE_MENU, menu->m_name, menuAsset, std::move(converter.GetDependencies()), std::vector()); - - if (menuAssetInfo) - { - allMenusOfFile.push_back(reinterpret_cast*>(menuAssetInfo)); - menuListDependencies.push_back(menuAssetInfo); - } - - zoneState->AddMenu(std::move(menu)); - } - - // Register this file with all loaded menus - conversionState->AddLoadedFile(fileName, std::move(allMenusOfFile)); - - return true; - } - - static MenuList* CreateMenuListAsset(const std::string& assetName, MemoryManager* memory, const std::vector& menus) - { - auto* menuListAsset = memory->Create(); - menuListAsset->name = memory->Dup(assetName.c_str()); - menuListAsset->menuCount = static_cast(menus.size()); - - if (menuListAsset->menuCount > 0) - { - menuListAsset->menus = static_cast(memory->Alloc(sizeof(uintptr_t) * menuListAsset->menuCount)); - for (auto i = 0; i < menuListAsset->menuCount; i++) - menuListAsset->menus[i] = menus[i]; - } - else - menuListAsset->menus = nullptr; - - return menuListAsset; - } - - static std::unique_ptr ParseMenuFile(const std::string& menuFileName, ISearchPath* searchPath, const menu::MenuAssetZoneState* zoneState) - { - const auto file = searchPath->Open(menuFileName); - if (!file.IsOpen()) - return nullptr; - - menu::MenuFileReader reader(*file.m_stream, menuFileName, menu::FeatureLevel::IW4, [searchPath](const std::string& filename, const std::string& sourceFile) -> std::unique_ptr - { - auto foundFileToInclude = searchPath->Open(filename); - if (!foundFileToInclude.IsOpen() || !foundFileToInclude.m_stream) - return nullptr; - - return std::move(foundFileToInclude.m_stream); - }); - - reader.IncludeZoneState(zoneState); - reader.SetPermissiveMode(ObjLoading::Configuration.MenuPermissiveParsing); - - return reader.ReadMenuFile(); - } - }; -} +namespace IW4 { +class MenuLoader { +public: + static bool ProcessParsedResults(const std::string &fileName, ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager, + menu::ParsingResult *parsingResult, menu::MenuAssetZoneState *zoneState, MenuConversionZoneState *conversionState, + std::vector &menus, std::vector &menuListDependencies) { + const auto menuCount = parsingResult->m_menus.size(); + const auto functionCount = parsingResult->m_functions.size(); + const auto menuLoadCount = parsingResult->m_menus_to_load.size(); + auto totalItemCount = 0u; + for (const auto &menu : parsingResult->m_menus) + totalItemCount += menu->m_items.size(); + + std::cout << "Successfully read menu file \"" << fileName << "\" (" << menuLoadCount << " loads, " << menuCount << " menus, " << functionCount + << " functions, " << totalItemCount << " items)\n"; + + // Add all functions to the zone state to make them available for all menus to be converted + for (auto &function : parsingResult->m_functions) + zoneState->AddFunction(std::move(function)); + + // Prepare a list of all menus of this file + std::vector *> allMenusOfFile; + allMenusOfFile.reserve(parsingResult->m_menus.size()); + + // Convert all menus and add them as assets + for (auto &menu : parsingResult->m_menus) { + MenuConverter converter(ObjLoading::Configuration.MenuNoOptimization, searchPath, memory, manager); + auto *menuAsset = converter.ConvertMenu(*menu); + if (menuAsset == nullptr) { + std::cout << "Failed to convert menu file \"" << menu->m_name << "\"\n"; + return false; + } -void* AssetLoaderMenuList::CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) -{ - auto* menuList = memory->Create(); - memset(menuList, 0, sizeof(MenuList)); - menuList->name = memory->Dup(assetName.c_str()); - return menuList; -} + menus.push_back(menuAsset); + auto *menuAssetInfo = manager->AddAsset(ASSET_TYPE_MENU, menu->m_name, menuAsset, std::move(converter.GetDependencies()), std::vector()); -bool AssetLoaderMenuList::CanLoadFromRaw() const -{ - return true; -} + if (menuAssetInfo) { + allMenusOfFile.push_back(reinterpret_cast *>(menuAssetInfo)); + menuListDependencies.push_back(menuAssetInfo); + } -bool BuildMenuFileQueue(std::deque& menuLoadQueue, const std::string& menuListAssetName, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager, menu::MenuAssetZoneState* zoneState, - MenuConversionZoneState* conversionState, std::vector& menus, std::vector& menuListDependencies) -{ - const auto alreadyLoadedMenuListFileMenus = conversionState->m_menus_by_filename.find(menuListAssetName); - - if (alreadyLoadedMenuListFileMenus == conversionState->m_menus_by_filename.end()) - { - const auto menuListResult = MenuLoader::ParseMenuFile(menuListAssetName, searchPath, zoneState); - if (menuListResult) - { - MenuLoader::ProcessParsedResults(menuListAssetName, searchPath, memory, manager, menuListResult.get(), zoneState, conversionState, menus, menuListDependencies); - - for (const auto& menuToLoad : menuListResult->m_menus_to_load) - menuLoadQueue.push_back(menuToLoad); - - zoneState->AddMenusToLoad(menuListAssetName, std::move(menuListResult->m_menus_to_load)); - } - else - return false; + zoneState->AddMenu(std::move(menu)); } + // Register this file with all loaded menus + conversionState->AddLoadedFile(fileName, std::move(allMenusOfFile)); + return true; + } + + static MenuList *CreateMenuListAsset(const std::string &assetName, MemoryManager *memory, const std::vector &menus) { + auto *menuListAsset = memory->Create(); + menuListAsset->name = memory->Dup(assetName.c_str()); + menuListAsset->menuCount = static_cast(menus.size()); + + if (menuListAsset->menuCount > 0) { + menuListAsset->menus = static_cast(memory->Alloc(sizeof(uintptr_t) * menuListAsset->menuCount)); + for (auto i = 0; i < menuListAsset->menuCount; i++) + menuListAsset->menus[i] = menus[i]; + } else + menuListAsset->menus = nullptr; + + return menuListAsset; + } + + static std::unique_ptr ParseMenuFile(const std::string &menuFileName, ISearchPath *searchPath, + const menu::MenuAssetZoneState *zoneState) { + const auto file = searchPath->Open(menuFileName); + if (!file.IsOpen()) + return nullptr; + + menu::MenuFileReader reader(*file.m_stream, menuFileName, menu::FeatureLevel::IW4, + [searchPath](const std::string &filename, const std::string &sourceFile) -> std::unique_ptr { + auto foundFileToInclude = searchPath->Open(filename); + if (!foundFileToInclude.IsOpen() || !foundFileToInclude.m_stream) + return nullptr; + + return std::move(foundFileToInclude.m_stream); + }); + + reader.IncludeZoneState(zoneState); + reader.SetPermissiveMode(ObjLoading::Configuration.MenuPermissiveParsing); + + return reader.ReadMenuFile(); + } +}; +} // namespace IW4 + +void *AssetLoaderMenuList::CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) { + auto *menuList = memory->Create(); + memset(menuList, 0, sizeof(MenuList)); + menuList->name = memory->Dup(assetName.c_str()); + return menuList; } -void LoadMenuFileFromQueue(const std::string& menuFilePath, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager, menu::MenuAssetZoneState* zoneState, - MenuConversionZoneState* conversionState, std::vector& menus, std::vector& menuListDependencies) -{ - const auto alreadyLoadedMenuFile = conversionState->m_menus_by_filename.find(menuFilePath); - if (alreadyLoadedMenuFile != conversionState->m_menus_by_filename.end()) - { - std::cout << "Already loaded \"" << menuFilePath << "\", skipping\n"; - for (auto* menu : alreadyLoadedMenuFile->second) - { - menus.push_back(menu->Asset()); - menuListDependencies.push_back(menu); - } - return; - } +bool AssetLoaderMenuList::CanLoadFromRaw() const { return true; } - const auto menuFileResult = MenuLoader::ParseMenuFile(menuFilePath, searchPath, zoneState); - if (menuFileResult) - { - MenuLoader::ProcessParsedResults(menuFilePath, searchPath, memory, manager, menuFileResult.get(), zoneState, conversionState, menus, menuListDependencies); - if (!menuFileResult->m_menus_to_load.empty()) - std::cout << "WARNING: Menu file has menus to load even though it is not a menu list, ignoring: \"" << menuFilePath << "\"\n"; +bool BuildMenuFileQueue(std::deque &menuLoadQueue, const std::string &menuListAssetName, ISearchPath *searchPath, MemoryManager *memory, + IAssetLoadingManager *manager, menu::MenuAssetZoneState *zoneState, MenuConversionZoneState *conversionState, + std::vector &menus, std::vector &menuListDependencies) { + const auto alreadyLoadedMenuListFileMenus = conversionState->m_menus_by_filename.find(menuListAssetName); + + if (alreadyLoadedMenuListFileMenus == conversionState->m_menus_by_filename.end()) { + const auto menuListResult = MenuLoader::ParseMenuFile(menuListAssetName, searchPath, zoneState); + if (menuListResult) { + MenuLoader::ProcessParsedResults(menuListAssetName, searchPath, memory, manager, menuListResult.get(), zoneState, conversionState, menus, + menuListDependencies); + + for (const auto &menuToLoad : menuListResult->m_menus_to_load) + menuLoadQueue.push_back(menuToLoad); + + zoneState->AddMenusToLoad(menuListAssetName, std::move(menuListResult->m_menus_to_load)); + } else + return false; + } + + return true; +} + +void LoadMenuFileFromQueue(const std::string &menuFilePath, ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager, + menu::MenuAssetZoneState *zoneState, MenuConversionZoneState *conversionState, std::vector &menus, + std::vector &menuListDependencies) { + const auto alreadyLoadedMenuFile = conversionState->m_menus_by_filename.find(menuFilePath); + if (alreadyLoadedMenuFile != conversionState->m_menus_by_filename.end()) { + std::cout << "Already loaded \"" << menuFilePath << "\", skipping\n"; + for (auto *menu : alreadyLoadedMenuFile->second) { + menus.push_back(menu->Asset()); + menuListDependencies.push_back(menu); } - else - std::cerr << "Could not read menu file \"" << menuFilePath << "\"\n"; + return; + } + + const auto menuFileResult = MenuLoader::ParseMenuFile(menuFilePath, searchPath, zoneState); + if (menuFileResult) { + MenuLoader::ProcessParsedResults(menuFilePath, searchPath, memory, manager, menuFileResult.get(), zoneState, conversionState, menus, menuListDependencies); + if (!menuFileResult->m_menus_to_load.empty()) + std::cout << "WARNING: Menu file has menus to load even though it is not a menu list, ignoring: \"" << menuFilePath << "\"\n"; + } else + std::cerr << "Could not read menu file \"" << menuFilePath << "\"\n"; } -bool AssetLoaderMenuList::LoadFromRaw(const std::string& assetName, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const -{ - std::vector menus; - std::vector menuListDependencies; +bool AssetLoaderMenuList::LoadFromRaw(const std::string &assetName, ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager, + Zone *zone) const { + std::vector menus; + std::vector menuListDependencies; - auto* zoneState = manager->GetAssetLoadingContext()->GetZoneAssetLoaderState(); - auto* conversionState = manager->GetAssetLoadingContext()->GetZoneAssetLoaderState(); + auto *zoneState = manager->GetAssetLoadingContext()->GetZoneAssetLoaderState(); + auto *conversionState = manager->GetAssetLoadingContext()->GetZoneAssetLoaderState(); - std::deque menuLoadQueue; - if (!BuildMenuFileQueue(menuLoadQueue, assetName, searchPath, memory, manager, zoneState, conversionState, menus, menuListDependencies)) - return false; + std::deque menuLoadQueue; + if (!BuildMenuFileQueue(menuLoadQueue, assetName, searchPath, memory, manager, zoneState, conversionState, menus, menuListDependencies)) + return false; - while(!menuLoadQueue.empty()) - { - const auto& menuFileToLoad = menuLoadQueue.front(); + while (!menuLoadQueue.empty()) { + const auto &menuFileToLoad = menuLoadQueue.front(); - LoadMenuFileFromQueue(menuFileToLoad, searchPath, memory, manager, zoneState, conversionState, menus, menuListDependencies); + LoadMenuFileFromQueue(menuFileToLoad, searchPath, memory, manager, zoneState, conversionState, menus, menuListDependencies); - menuLoadQueue.pop_front(); - } + menuLoadQueue.pop_front(); + } - auto* menuListAsset = MenuLoader::CreateMenuListAsset(assetName, memory, menus); + auto *menuListAsset = MenuLoader::CreateMenuListAsset(assetName, memory, menus); - if (menuListAsset) - manager->AddAsset(ASSET_TYPE_MENULIST, assetName, menuListAsset, menuListDependencies, std::vector()); + if (menuListAsset) + manager->AddAsset(ASSET_TYPE_MENULIST, assetName, menuListAsset, menuListDependencies, std::vector()); - return true; + return true; } -void AssetLoaderMenuList::FinalizeAssetsForZone(AssetLoadingContext* context) const -{ - context->GetZoneAssetLoaderState()->FinalizeSupportingData(); +void AssetLoaderMenuList::FinalizeAssetsForZone(AssetLoadingContext *context) const { + context->GetZoneAssetLoaderState()->FinalizeSupportingData(); } diff --git a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderMenuList.h b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderMenuList.h index d7d0209cd..0ad846688 100644 --- a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderMenuList.h +++ b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderMenuList.h @@ -1,18 +1,16 @@ #pragma once -#include "Game/IW4/IW4.h" #include "AssetLoading/BasicAssetLoader.h" #include "AssetLoading/IAssetLoadingManager.h" +#include "Game/IW4/IW4.h" #include "SearchPath/ISearchPath.h" -namespace IW4 -{ - class AssetLoaderMenuList final : public BasicAssetLoader - { - public: - _NODISCARD void* CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) override; - _NODISCARD bool CanLoadFromRaw() const override; - bool LoadFromRaw(const std::string& assetName, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const override; - void FinalizeAssetsForZone(AssetLoadingContext* context) const override; - }; -} +namespace IW4 { +class AssetLoaderMenuList final : public BasicAssetLoader { +public: + _NODISCARD void *CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) override; + _NODISCARD bool CanLoadFromRaw() const override; + bool LoadFromRaw(const std::string &assetName, ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager, Zone *zone) const override; + void FinalizeAssetsForZone(AssetLoadingContext *context) const override; +}; +} // namespace IW4 diff --git a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderPhysCollmap.cpp b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderPhysCollmap.cpp index c838edbf3..cd8491022 100644 --- a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderPhysCollmap.cpp +++ b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderPhysCollmap.cpp @@ -2,16 +2,15 @@ #include -#include "ObjLoading.h" #include "Game/IW4/IW4.h" +#include "ObjLoading.h" #include "Pool/GlobalAssetPool.h" using namespace IW4; -void* AssetLoaderPhysCollmap::CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) -{ - auto* collmap = memory->Create(); - memset(collmap, 0, sizeof(PhysCollmap)); - collmap->name = memory->Dup(assetName.c_str()); - return collmap; +void *AssetLoaderPhysCollmap::CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) { + auto *collmap = memory->Create(); + memset(collmap, 0, sizeof(PhysCollmap)); + collmap->name = memory->Dup(assetName.c_str()); + return collmap; } diff --git a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderPhysCollmap.h b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderPhysCollmap.h index 3464be721..bd898a49c 100644 --- a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderPhysCollmap.h +++ b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderPhysCollmap.h @@ -1,14 +1,12 @@ #pragma once -#include "Game/IW4/IW4.h" #include "AssetLoading/BasicAssetLoader.h" +#include "Game/IW4/IW4.h" #include "SearchPath/ISearchPath.h" -namespace IW4 -{ - class AssetLoaderPhysCollmap final : public BasicAssetLoader - { - public: - _NODISCARD void* CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) override; - }; -} +namespace IW4 { +class AssetLoaderPhysCollmap final : public BasicAssetLoader { +public: + _NODISCARD void *CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) override; +}; +} // namespace IW4 diff --git a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderPhysPreset.cpp b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderPhysPreset.cpp index 39c41fd40..6360bc43e 100644 --- a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderPhysPreset.cpp +++ b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderPhysPreset.cpp @@ -4,123 +4,107 @@ #include #include -#include "ObjLoading.h" #include "Game/IW4/IW4.h" -#include "Game/IW4/ObjConstantsIW4.h" #include "Game/IW4/InfoString/InfoStringToStructConverter.h" #include "Game/IW4/InfoString/PhysPresetFields.h" +#include "Game/IW4/ObjConstantsIW4.h" +#include "ObjLoading.h" #include "Pool/GlobalAssetPool.h" using namespace IW4; -namespace IW4 -{ - class InfoStringToPhysPresetConverter final : public InfoStringToStructConverter - { - protected: - bool ConvertExtensionField(const cspField_t& field, const std::string& value) override - { - assert(false); - return false; - } - - public: - InfoStringToPhysPresetConverter(const InfoString& infoString, PhysPresetInfo* physPreset, ZoneScriptStrings& zoneScriptStrings, MemoryManager* memory, IAssetLoadingManager* manager, - const cspField_t* fields, const size_t fieldCount) - : InfoStringToStructConverter(infoString, physPreset, zoneScriptStrings, memory, manager, fields, fieldCount) - { - } - }; +namespace IW4 { +class InfoStringToPhysPresetConverter final : public InfoStringToStructConverter { +protected: + bool ConvertExtensionField(const cspField_t &field, const std::string &value) override { + assert(false); + return false; + } + +public: + InfoStringToPhysPresetConverter(const InfoString &infoString, PhysPresetInfo *physPreset, ZoneScriptStrings &zoneScriptStrings, MemoryManager *memory, + IAssetLoadingManager *manager, const cspField_t *fields, const size_t fieldCount) + : InfoStringToStructConverter(infoString, physPreset, zoneScriptStrings, memory, manager, fields, fieldCount) {} +}; +} // namespace IW4 + +void AssetLoaderPhysPreset::CopyFromPhysPresetInfo(const PhysPresetInfo *physPresetInfo, PhysPreset *physPreset) { + physPreset->mass = std::clamp(physPresetInfo->mass, 1.0f, 2000.0f) * 0.001f; + physPreset->bounce = physPresetInfo->bounce; + + if (physPresetInfo->isFrictionInfinity != 0) + physPreset->friction = std::numeric_limits::infinity(); + else + physPreset->friction = physPresetInfo->friction; + + physPreset->bulletForceScale = physPresetInfo->bulletForceScale; + physPreset->explosiveForceScale = physPresetInfo->explosiveForceScale; + physPreset->sndAliasPrefix = physPresetInfo->sndAliasPrefix; + physPreset->piecesSpreadFraction = physPresetInfo->piecesSpreadFraction; + physPreset->piecesUpwardVelocity = physPresetInfo->piecesUpwardVelocity; + physPreset->tempDefaultToCylinder = physPresetInfo->tempDefaultToCylinder != 0; + physPreset->perSurfaceSndAlias = physPresetInfo->perSurfaceSndAlias != 0; } -void AssetLoaderPhysPreset::CopyFromPhysPresetInfo(const PhysPresetInfo* physPresetInfo, PhysPreset* physPreset) -{ - physPreset->mass = std::clamp(physPresetInfo->mass, 1.0f, 2000.0f) * 0.001f; - physPreset->bounce = physPresetInfo->bounce; - - if (physPresetInfo->isFrictionInfinity != 0) - physPreset->friction = std::numeric_limits::infinity(); - else - physPreset->friction = physPresetInfo->friction; - - physPreset->bulletForceScale = physPresetInfo->bulletForceScale; - physPreset->explosiveForceScale = physPresetInfo->explosiveForceScale; - physPreset->sndAliasPrefix = physPresetInfo->sndAliasPrefix; - physPreset->piecesSpreadFraction = physPresetInfo->piecesSpreadFraction; - physPreset->piecesUpwardVelocity = physPresetInfo->piecesUpwardVelocity; - physPreset->tempDefaultToCylinder = physPresetInfo->tempDefaultToCylinder != 0; - physPreset->perSurfaceSndAlias = physPresetInfo->perSurfaceSndAlias != 0; -} - -bool AssetLoaderPhysPreset::LoadFromInfoString(const InfoString& infoString, const std::string& assetName, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) -{ - const auto presetInfo = std::make_unique(); - memset(presetInfo.get(), 0, sizeof(PhysPresetInfo)); - InfoStringToPhysPresetConverter converter(infoString, presetInfo.get(), zone->m_script_strings, memory, manager, phys_preset_fields, std::extent::value); - if (!converter.Convert()) - { - std::cout << "Failed to parse phys preset: \"" << assetName << "\"" << std::endl; - return true; - } +bool AssetLoaderPhysPreset::LoadFromInfoString(const InfoString &infoString, const std::string &assetName, MemoryManager *memory, IAssetLoadingManager *manager, + Zone *zone) { + const auto presetInfo = std::make_unique(); + memset(presetInfo.get(), 0, sizeof(PhysPresetInfo)); + InfoStringToPhysPresetConverter converter(infoString, presetInfo.get(), zone->m_script_strings, memory, manager, phys_preset_fields, + std::extent::value); + if (!converter.Convert()) { + std::cout << "Failed to parse phys preset: \"" << assetName << "\"" << std::endl; + return true; + } - auto* physPreset = memory->Create(); + auto *physPreset = memory->Create(); - CopyFromPhysPresetInfo(presetInfo.get(), physPreset); - physPreset->name = memory->Dup(assetName.c_str()); + CopyFromPhysPresetInfo(presetInfo.get(), physPreset); + physPreset->name = memory->Dup(assetName.c_str()); - manager->AddAsset(ASSET_TYPE_PHYSPRESET, assetName, physPreset, converter.GetDependencies(), converter.GetUsedScriptStrings()); + manager->AddAsset(ASSET_TYPE_PHYSPRESET, assetName, physPreset, converter.GetDependencies(), converter.GetUsedScriptStrings()); - return true; + return true; } -void* AssetLoaderPhysPreset::CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) -{ - auto* physPreset = memory->Create(); - memset(physPreset, 0, sizeof(PhysPreset)); - physPreset->name = memory->Dup(assetName.c_str()); - return physPreset; +void *AssetLoaderPhysPreset::CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) { + auto *physPreset = memory->Create(); + memset(physPreset, 0, sizeof(PhysPreset)); + physPreset->name = memory->Dup(assetName.c_str()); + return physPreset; } -bool AssetLoaderPhysPreset::CanLoadFromGdt() const -{ - return true; -} +bool AssetLoaderPhysPreset::CanLoadFromGdt() const { return true; } -bool AssetLoaderPhysPreset::LoadFromGdt(const std::string& assetName, IGdtQueryable* gdtQueryable, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const -{ - auto* gdtEntry = gdtQueryable->GetGdtEntryByGdfAndName(ObjConstants::GDF_FILENAME_PHYS_PRESET, assetName); - if (gdtEntry == nullptr) - return false; +bool AssetLoaderPhysPreset::LoadFromGdt(const std::string &assetName, IGdtQueryable *gdtQueryable, MemoryManager *memory, IAssetLoadingManager *manager, + Zone *zone) const { + auto *gdtEntry = gdtQueryable->GetGdtEntryByGdfAndName(ObjConstants::GDF_FILENAME_PHYS_PRESET, assetName); + if (gdtEntry == nullptr) + return false; - InfoString infoString; - if (!infoString.FromGdtProperties(*gdtEntry)) - { - std::cout << "Failed to read phys preset gdt entry: \"" << assetName << "\"" << std::endl; - return true; - } + InfoString infoString; + if (!infoString.FromGdtProperties(*gdtEntry)) { + std::cout << "Failed to read phys preset gdt entry: \"" << assetName << "\"" << std::endl; + return true; + } - return LoadFromInfoString(infoString, assetName, memory, manager, zone); + return LoadFromInfoString(infoString, assetName, memory, manager, zone); } -bool AssetLoaderPhysPreset::CanLoadFromRaw() const -{ +bool AssetLoaderPhysPreset::CanLoadFromRaw() const { return true; } + +bool AssetLoaderPhysPreset::LoadFromRaw(const std::string &assetName, ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager, + Zone *zone) const { + const auto fileName = "physic/" + assetName; + const auto file = searchPath->Open(fileName); + if (!file.IsOpen()) + return false; + + InfoString infoString; + if (!infoString.FromStream(ObjConstants::INFO_STRING_PREFIX_PHYS_PRESET, *file.m_stream)) { + std::cout << "Failed to read phys preset raw file: \"" << fileName << "\"" << std::endl; return true; -} + } -bool AssetLoaderPhysPreset::LoadFromRaw(const std::string& assetName, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const -{ - const auto fileName = "physic/" + assetName; - const auto file = searchPath->Open(fileName); - if (!file.IsOpen()) - return false; - - InfoString infoString; - if (!infoString.FromStream(ObjConstants::INFO_STRING_PREFIX_PHYS_PRESET, *file.m_stream)) - { - std::cout << "Failed to read phys preset raw file: \"" << fileName << "\"" << std::endl; - return true; - } - - return LoadFromInfoString(infoString, assetName, memory, manager, zone); + return LoadFromInfoString(infoString, assetName, memory, manager, zone); } - diff --git a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderPhysPreset.h b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderPhysPreset.h index ec73fb700..39604c32a 100644 --- a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderPhysPreset.h +++ b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderPhysPreset.h @@ -1,23 +1,21 @@ #pragma once -#include "Game/IW4/IW4.h" #include "AssetLoading/BasicAssetLoader.h" +#include "Game/IW4/IW4.h" #include "InfoString/InfoString.h" #include "SearchPath/ISearchPath.h" -namespace IW4 -{ - class AssetLoaderPhysPreset final : public BasicAssetLoader - { - static void CopyFromPhysPresetInfo(const PhysPresetInfo* physPresetInfo, PhysPreset* physPreset); +namespace IW4 { +class AssetLoaderPhysPreset final : public BasicAssetLoader { + static void CopyFromPhysPresetInfo(const PhysPresetInfo *physPresetInfo, PhysPreset *physPreset); - static bool LoadFromInfoString(const InfoString& infoString, const std::string& assetName, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone); + static bool LoadFromInfoString(const InfoString &infoString, const std::string &assetName, MemoryManager *memory, IAssetLoadingManager *manager, Zone *zone); - public: - _NODISCARD void* CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) override; - _NODISCARD bool CanLoadFromGdt() const override; - bool LoadFromGdt(const std::string& assetName, IGdtQueryable* gdtQueryable, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const override; - _NODISCARD bool CanLoadFromRaw() const override; - bool LoadFromRaw(const std::string& assetName, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const override; - }; -} +public: + _NODISCARD void *CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) override; + _NODISCARD bool CanLoadFromGdt() const override; + bool LoadFromGdt(const std::string &assetName, IGdtQueryable *gdtQueryable, MemoryManager *memory, IAssetLoadingManager *manager, Zone *zone) const override; + _NODISCARD bool CanLoadFromRaw() const override; + bool LoadFromRaw(const std::string &assetName, ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager, Zone *zone) const override; +}; +} // namespace IW4 diff --git a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderPixelShader.cpp b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderPixelShader.cpp index df5e5128d..6f1a1e622 100644 --- a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderPixelShader.cpp +++ b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderPixelShader.cpp @@ -5,58 +5,52 @@ #include #include -#include "ObjLoading.h" #include "Game/IW4/IW4.h" +#include "ObjLoading.h" #include "Pool/GlobalAssetPool.h" using namespace IW4; -void* AssetLoaderPixelShader::CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) -{ - auto* pixelShader = memory->Create(); - memset(pixelShader, 0, sizeof(MaterialPixelShader)); - pixelShader->name = memory->Dup(assetName.c_str()); - return pixelShader; +void *AssetLoaderPixelShader::CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) { + auto *pixelShader = memory->Create(); + memset(pixelShader, 0, sizeof(MaterialPixelShader)); + pixelShader->name = memory->Dup(assetName.c_str()); + return pixelShader; } -bool AssetLoaderPixelShader::CanLoadFromRaw() const -{ - return true; -} +bool AssetLoaderPixelShader::CanLoadFromRaw() const { return true; } -std::string AssetLoaderPixelShader::GetFileNameForAsset(const std::string& assetName) -{ - std::ostringstream ss; - ss << "shader_bin/ps_" << assetName << ".cso"; - return ss.str(); +std::string AssetLoaderPixelShader::GetFileNameForAsset(const std::string &assetName) { + std::ostringstream ss; + ss << "shader_bin/ps_" << assetName << ".cso"; + return ss.str(); } -bool AssetLoaderPixelShader::LoadFromRaw(const std::string& assetName, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const -{ - const auto fileName = GetFileNameForAsset(assetName); - const auto file = searchPath->Open(fileName); - if (!file.IsOpen()) - return false; - - if(file.m_length % sizeof(uint32_t) != 0) - { - std::cerr << "Invalid pixel shader \"" << assetName << "\": Size must be dividable by " << sizeof(uint32_t) << "\n"; - return false; - } - - auto* pixelShader = memory->Create(); - pixelShader->name = memory->Dup(assetName.c_str()); - pixelShader->prog.loadDef.programSize = static_cast(static_cast(file.m_length) / sizeof(uint32_t)); - pixelShader->prog.loadDef.loadForRenderer = 0; - pixelShader->prog.ps = nullptr; - - auto* fileBuffer = static_cast(memory->Alloc(pixelShader->prog.loadDef.programSize * sizeof(uint32_t))); - file.m_stream->read(fileBuffer, static_cast(pixelShader->prog.loadDef.programSize) * sizeof(uint32_t)); - if (file.m_stream->gcount() != file.m_length) - return false; - - pixelShader->prog.loadDef.program = reinterpret_cast(fileBuffer); - manager->AddAsset(ASSET_TYPE_PIXELSHADER, assetName, pixelShader); - - return true; +bool AssetLoaderPixelShader::LoadFromRaw(const std::string &assetName, ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager, + Zone *zone) const { + const auto fileName = GetFileNameForAsset(assetName); + const auto file = searchPath->Open(fileName); + if (!file.IsOpen()) + return false; + + if (file.m_length % sizeof(uint32_t) != 0) { + std::cerr << "Invalid pixel shader \"" << assetName << "\": Size must be dividable by " << sizeof(uint32_t) << "\n"; + return false; + } + + auto *pixelShader = memory->Create(); + pixelShader->name = memory->Dup(assetName.c_str()); + pixelShader->prog.loadDef.programSize = static_cast(static_cast(file.m_length) / sizeof(uint32_t)); + pixelShader->prog.loadDef.loadForRenderer = 0; + pixelShader->prog.ps = nullptr; + + auto *fileBuffer = static_cast(memory->Alloc(pixelShader->prog.loadDef.programSize * sizeof(uint32_t))); + file.m_stream->read(fileBuffer, static_cast(pixelShader->prog.loadDef.programSize) * sizeof(uint32_t)); + if (file.m_stream->gcount() != file.m_length) + return false; + + pixelShader->prog.loadDef.program = reinterpret_cast(fileBuffer); + manager->AddAsset(ASSET_TYPE_PIXELSHADER, assetName, pixelShader); + + return true; } diff --git a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderPixelShader.h b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderPixelShader.h index 4a96e825e..1817c25ff 100644 --- a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderPixelShader.h +++ b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderPixelShader.h @@ -2,19 +2,17 @@ #include -#include "Game/IW4/IW4.h" #include "AssetLoading/BasicAssetLoader.h" +#include "Game/IW4/IW4.h" #include "SearchPath/ISearchPath.h" -namespace IW4 -{ - class AssetLoaderPixelShader final : public BasicAssetLoader - { - public: - _NODISCARD static std::string GetFileNameForAsset(const std::string& assetName); +namespace IW4 { +class AssetLoaderPixelShader final : public BasicAssetLoader { +public: + _NODISCARD static std::string GetFileNameForAsset(const std::string &assetName); - _NODISCARD void* CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) override; - _NODISCARD bool CanLoadFromRaw() const override; - bool LoadFromRaw(const std::string& assetName, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const override; - }; -} + _NODISCARD void *CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) override; + _NODISCARD bool CanLoadFromRaw() const override; + bool LoadFromRaw(const std::string &assetName, ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager, Zone *zone) const override; +}; +} // namespace IW4 diff --git a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderRawFile.cpp b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderRawFile.cpp index aaea2db6e..c10bccffd 100644 --- a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderRawFile.cpp +++ b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderRawFile.cpp @@ -7,37 +7,33 @@ using namespace IW4; -void* AssetLoaderRawFile::CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) -{ - auto* rawFile = memory->Create(); - memset(rawFile, 0, sizeof(RawFile)); - rawFile->name = memory->Dup(assetName.c_str()); - return rawFile; +void *AssetLoaderRawFile::CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) { + auto *rawFile = memory->Create(); + memset(rawFile, 0, sizeof(RawFile)); + rawFile->name = memory->Dup(assetName.c_str()); + return rawFile; } -bool AssetLoaderRawFile::CanLoadFromRaw() const -{ - return true; -} +bool AssetLoaderRawFile::CanLoadFromRaw() const { return true; } -bool AssetLoaderRawFile::LoadFromRaw(const std::string& assetName, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const -{ - const auto file = searchPath->Open(assetName); - if (!file.IsOpen()) - return false; +bool AssetLoaderRawFile::LoadFromRaw(const std::string &assetName, ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager, + Zone *zone) const { + const auto file = searchPath->Open(assetName); + if (!file.IsOpen()) + return false; - auto* rawFile = memory->Create(); - rawFile->name = memory->Dup(assetName.c_str()); - rawFile->len = static_cast(file.m_length); + auto *rawFile = memory->Create(); + rawFile->name = memory->Dup(assetName.c_str()); + rawFile->len = static_cast(file.m_length); - auto* fileBuffer = static_cast(memory->Alloc(static_cast(file.m_length + 1))); - file.m_stream->read(fileBuffer, file.m_length); - if (file.m_stream->gcount() != file.m_length) - return false; - fileBuffer[rawFile->len] = '\0'; + auto *fileBuffer = static_cast(memory->Alloc(static_cast(file.m_length + 1))); + file.m_stream->read(fileBuffer, file.m_length); + if (file.m_stream->gcount() != file.m_length) + return false; + fileBuffer[rawFile->len] = '\0'; - rawFile->data.buffer = fileBuffer; - manager->AddAsset(ASSET_TYPE_RAWFILE, assetName, rawFile); + rawFile->data.buffer = fileBuffer; + manager->AddAsset(ASSET_TYPE_RAWFILE, assetName, rawFile); - return true; + return true; } diff --git a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderRawFile.h b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderRawFile.h index 3e5ac6d0d..ad9ea111c 100644 --- a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderRawFile.h +++ b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderRawFile.h @@ -1,16 +1,14 @@ #pragma once -#include "Game/IW4/IW4.h" #include "AssetLoading/BasicAssetLoader.h" #include "AssetLoading/IAssetLoadingManager.h" +#include "Game/IW4/IW4.h" #include "SearchPath/ISearchPath.h" -namespace IW4 -{ - class AssetLoaderRawFile final : public BasicAssetLoader - { - public: - _NODISCARD void* CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) override; - _NODISCARD bool CanLoadFromRaw() const override; - bool LoadFromRaw(const std::string& assetName, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const override; - }; -} +namespace IW4 { +class AssetLoaderRawFile final : public BasicAssetLoader { +public: + _NODISCARD void *CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) override; + _NODISCARD bool CanLoadFromRaw() const override; + bool LoadFromRaw(const std::string &assetName, ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager, Zone *zone) const override; +}; +} // namespace IW4 diff --git a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderSndCurve.cpp b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderSndCurve.cpp index e26108409..8285d4458 100644 --- a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderSndCurve.cpp +++ b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderSndCurve.cpp @@ -4,75 +4,65 @@ #include #include -#include "ObjLoading.h" #include "AssetLoading/SndCurve/SndCurveReader.h" #include "Game/IW4/IW4.h" +#include "ObjLoading.h" #include "Pool/GlobalAssetPool.h" using namespace IW4; -std::string AssetLoaderSndCurve::GetAssetFilename(const std::string& assetName) -{ - std::ostringstream ss; +std::string AssetLoaderSndCurve::GetAssetFilename(const std::string &assetName) { + std::ostringstream ss; - ss << "soundaliases/" << assetName << ".vfcurve"; + ss << "soundaliases/" << assetName << ".vfcurve"; - return ss.str(); + return ss.str(); } -void* AssetLoaderSndCurve::CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) -{ - auto* sndCurve = memory->Create(); - memset(sndCurve, 0, sizeof(SndCurve)); - sndCurve->filename = memory->Dup(assetName.c_str()); - return sndCurve; +void *AssetLoaderSndCurve::CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) { + auto *sndCurve = memory->Create(); + memset(sndCurve, 0, sizeof(SndCurve)); + sndCurve->filename = memory->Dup(assetName.c_str()); + return sndCurve; } -bool AssetLoaderSndCurve::CanLoadFromRaw() const -{ - return true; -} +bool AssetLoaderSndCurve::CanLoadFromRaw() const { return true; } -bool AssetLoaderSndCurve::LoadFromRaw(const std::string& assetName, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const -{ - const auto filename = GetAssetFilename(assetName); - const auto file = searchPath->Open(filename); - if (!file.IsOpen()) - return false; +bool AssetLoaderSndCurve::LoadFromRaw(const std::string &assetName, ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager, + Zone *zone) const { + const auto filename = GetAssetFilename(assetName); + const auto file = searchPath->Open(filename); + if (!file.IsOpen()) + return false; - const SndCurveReader reader(*file.m_stream, filename); + const SndCurveReader reader(*file.m_stream, filename); - const auto sndCurveData = reader.Read(); + const auto sndCurveData = reader.Read(); - if (!sndCurveData) - return false; + if (!sndCurveData) + return false; - if(sndCurveData->m_knots.size() > std::extent_v) - { - std::cerr << "Failed to load SndCurve \"" << assetName << "\": Too many knots (" << sndCurveData->m_knots.size() << ")\n"; - return false; - } + if (sndCurveData->m_knots.size() > std::extent_v) { + std::cerr << "Failed to load SndCurve \"" << assetName << "\": Too many knots (" << sndCurveData->m_knots.size() << ")\n"; + return false; + } + + auto *sndCurve = memory->Create(); + sndCurve->filename = memory->Dup(assetName.c_str()); + sndCurve->knotCount = static_cast(sndCurveData->m_knots.size()); - auto* sndCurve = memory->Create(); - sndCurve->filename = memory->Dup(assetName.c_str()); - sndCurve->knotCount = static_cast(sndCurveData->m_knots.size()); - - for(auto i = 0u; i < std::extent_v; i++) - { - if(i < sndCurveData->m_knots.size()) - { - const auto& [x, y] = sndCurveData->m_knots[i]; - sndCurve->knots[i][0] = static_cast(x); - sndCurve->knots[i][1] = static_cast(y); - } - else - { - sndCurve->knots[i][0] = 0; - sndCurve->knots[i][1] = 0; - } + for (auto i = 0u; i < std::extent_v; i++) { + if (i < sndCurveData->m_knots.size()) { + const auto &[x, y] = sndCurveData->m_knots[i]; + sndCurve->knots[i][0] = static_cast(x); + sndCurve->knots[i][1] = static_cast(y); + } else { + sndCurve->knots[i][0] = 0; + sndCurve->knots[i][1] = 0; } + } - manager->AddAsset(ASSET_TYPE_SOUND_CURVE, assetName, sndCurve); + manager->AddAsset(ASSET_TYPE_SOUND_CURVE, assetName, sndCurve); - return true; + return true; } diff --git a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderSndCurve.h b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderSndCurve.h index 4a55f9ca2..32146cd30 100644 --- a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderSndCurve.h +++ b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderSndCurve.h @@ -1,18 +1,16 @@ #pragma once -#include "Game/IW4/IW4.h" #include "AssetLoading/BasicAssetLoader.h" +#include "Game/IW4/IW4.h" #include "SearchPath/ISearchPath.h" -namespace IW4 -{ - class AssetLoaderSndCurve final : public BasicAssetLoader - { - static std::string GetAssetFilename(const std::string& assetName); +namespace IW4 { +class AssetLoaderSndCurve final : public BasicAssetLoader { + static std::string GetAssetFilename(const std::string &assetName); - public: - _NODISCARD void* CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) override; - _NODISCARD bool CanLoadFromRaw() const override; - bool LoadFromRaw(const std::string& assetName, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const override; - }; -} +public: + _NODISCARD void *CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) override; + _NODISCARD bool CanLoadFromRaw() const override; + bool LoadFromRaw(const std::string &assetName, ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager, Zone *zone) const override; +}; +} // namespace IW4 diff --git a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderSoundAliasList.cpp b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderSoundAliasList.cpp index 7ec9e48c1..16c68d21d 100644 --- a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderSoundAliasList.cpp +++ b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderSoundAliasList.cpp @@ -2,16 +2,15 @@ #include -#include "ObjLoading.h" #include "Game/IW4/IW4.h" +#include "ObjLoading.h" #include "Pool/GlobalAssetPool.h" using namespace IW4; -void* AssetLoaderSoundAliasList::CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) -{ - auto* sndAliasList = memory->Create(); - memset(sndAliasList, 0, sizeof(snd_alias_list_t)); - sndAliasList->aliasName = memory->Dup(assetName.c_str()); - return sndAliasList; +void *AssetLoaderSoundAliasList::CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) { + auto *sndAliasList = memory->Create(); + memset(sndAliasList, 0, sizeof(snd_alias_list_t)); + sndAliasList->aliasName = memory->Dup(assetName.c_str()); + return sndAliasList; } diff --git a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderSoundAliasList.h b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderSoundAliasList.h index 42b2d6bf7..d83ae63ba 100644 --- a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderSoundAliasList.h +++ b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderSoundAliasList.h @@ -1,14 +1,12 @@ #pragma once -#include "Game/IW4/IW4.h" #include "AssetLoading/BasicAssetLoader.h" +#include "Game/IW4/IW4.h" #include "SearchPath/ISearchPath.h" -namespace IW4 -{ - class AssetLoaderSoundAliasList final : public BasicAssetLoader - { - public: - _NODISCARD void* CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) override; - }; -} +namespace IW4 { +class AssetLoaderSoundAliasList final : public BasicAssetLoader { +public: + _NODISCARD void *CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) override; +}; +} // namespace IW4 diff --git a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderStringTable.cpp b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderStringTable.cpp index 2b5b4b17a..d7159ee47 100644 --- a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderStringTable.cpp +++ b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderStringTable.cpp @@ -2,78 +2,68 @@ #include -#include "ObjLoading.h" #include "Csv/CsvStream.h" #include "Game/IW4/CommonIW4.h" #include "Game/IW4/IW4.h" +#include "ObjLoading.h" #include "Pool/GlobalAssetPool.h" using namespace IW4; -void* AssetLoaderStringTable::CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) -{ - auto* stringTable = memory->Create(); - memset(stringTable, 0, sizeof(StringTable)); - stringTable->name = memory->Dup(assetName.c_str()); - return stringTable; +void *AssetLoaderStringTable::CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) { + auto *stringTable = memory->Create(); + memset(stringTable, 0, sizeof(StringTable)); + stringTable->name = memory->Dup(assetName.c_str()); + return stringTable; } -bool AssetLoaderStringTable::CanLoadFromRaw() const -{ - return true; -} +bool AssetLoaderStringTable::CanLoadFromRaw() const { return true; } -bool AssetLoaderStringTable::LoadFromRaw(const std::string& assetName, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const -{ - const auto file = searchPath->Open(assetName); - if (!file.IsOpen()) - return false; +bool AssetLoaderStringTable::LoadFromRaw(const std::string &assetName, ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager, + Zone *zone) const { + const auto file = searchPath->Open(assetName); + if (!file.IsOpen()) + return false; - auto* stringTable = memory->Create(); - stringTable->name = memory->Dup(assetName.c_str()); + auto *stringTable = memory->Create(); + stringTable->name = memory->Dup(assetName.c_str()); - std::vector> csvLines; - std::vector currentLine; - auto maxCols = 0u; - const CsvInputStream csv(*file.m_stream); + std::vector> csvLines; + std::vector currentLine; + auto maxCols = 0u; + const CsvInputStream csv(*file.m_stream); - while (csv.NextRow(currentLine)) - { - if (currentLine.size() > maxCols) - maxCols = currentLine.size(); - csvLines.emplace_back(std::move(currentLine)); - currentLine = std::vector(); - } + while (csv.NextRow(currentLine)) { + if (currentLine.size() > maxCols) + maxCols = currentLine.size(); + csvLines.emplace_back(std::move(currentLine)); + currentLine = std::vector(); + } - stringTable->columnCount = static_cast(maxCols); - stringTable->rowCount = static_cast(csvLines.size()); - const auto cellCount = static_cast(stringTable->rowCount) * static_cast(stringTable->columnCount); + stringTable->columnCount = static_cast(maxCols); + stringTable->rowCount = static_cast(csvLines.size()); + const auto cellCount = static_cast(stringTable->rowCount) * static_cast(stringTable->columnCount); - if (cellCount) - { - stringTable->values = static_cast(memory->Alloc(sizeof(StringTableCell) * cellCount)); + if (cellCount) { + stringTable->values = static_cast(memory->Alloc(sizeof(StringTableCell) * cellCount)); - for (auto row = 0u; row < csvLines.size(); row++) - { - const auto& rowValues = csvLines[row]; - for (auto col = 0u; col < maxCols; col++) - { - auto& cell = stringTable->values[row * maxCols + col]; - if (col >= rowValues.size() || rowValues[col].empty()) - cell.string = ""; - else - cell.string = memory->Dup(rowValues[col].c_str()); + for (auto row = 0u; row < csvLines.size(); row++) { + const auto &rowValues = csvLines[row]; + for (auto col = 0u; col < maxCols; col++) { + auto &cell = stringTable->values[row * maxCols + col]; + if (col >= rowValues.size() || rowValues[col].empty()) + cell.string = ""; + else + cell.string = memory->Dup(rowValues[col].c_str()); - cell.hash = Common::StringTable_HashString(cell.string); - } - } - } - else - { - stringTable->values = nullptr; + cell.hash = Common::StringTable_HashString(cell.string); + } } + } else { + stringTable->values = nullptr; + } - manager->AddAsset(ASSET_TYPE_STRINGTABLE, assetName, stringTable); + manager->AddAsset(ASSET_TYPE_STRINGTABLE, assetName, stringTable); - return true; + return true; } diff --git a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderStringTable.h b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderStringTable.h index 79fee191d..dc8062a80 100644 --- a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderStringTable.h +++ b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderStringTable.h @@ -1,16 +1,14 @@ #pragma once -#include "Game/IW4/IW4.h" #include "AssetLoading/BasicAssetLoader.h" +#include "Game/IW4/IW4.h" #include "SearchPath/ISearchPath.h" -namespace IW4 -{ - class AssetLoaderStringTable final : public BasicAssetLoader - { - public: - _NODISCARD void* CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) override; - _NODISCARD bool CanLoadFromRaw() const override; - bool LoadFromRaw(const std::string& assetName, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const override; - }; -} +namespace IW4 { +class AssetLoaderStringTable final : public BasicAssetLoader { +public: + _NODISCARD void *CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) override; + _NODISCARD bool CanLoadFromRaw() const override; + bool LoadFromRaw(const std::string &assetName, ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager, Zone *zone) const override; +}; +} // namespace IW4 diff --git a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderStructuredDataDefSet.cpp b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderStructuredDataDefSet.cpp index aae3fc269..889c55d94 100644 --- a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderStructuredDataDefSet.cpp +++ b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderStructuredDataDefSet.cpp @@ -2,210 +2,186 @@ #include -#include "ObjLoading.h" #include "Game/IW4/IW4.h" -#include "StructuredDataDef/StructuredDataDefReader.h" +#include "ObjLoading.h" #include "Pool/GlobalAssetPool.h" +#include "StructuredDataDef/StructuredDataDefReader.h" #include "Utils/Alignment.h" using namespace IW4; -void* AssetLoaderStructuredDataDefSet::CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) -{ - auto* structuredDataDefSet = memory->Create(); - memset(structuredDataDefSet, 0, sizeof(StructuredDataDefSet)); - structuredDataDefSet->name = memory->Dup(assetName.c_str()); - return structuredDataDefSet; -} - -bool AssetLoaderStructuredDataDefSet::CanLoadFromRaw() const -{ - return true; +void *AssetLoaderStructuredDataDefSet::CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) { + auto *structuredDataDefSet = memory->Create(); + memset(structuredDataDefSet, 0, sizeof(StructuredDataDefSet)); + structuredDataDefSet->name = memory->Dup(assetName.c_str()); + return structuredDataDefSet; } -StructuredDataType AssetLoaderStructuredDataDefSet::ConvertType(CommonStructuredDataType inputType) -{ - switch (inputType.m_category) - { - case CommonStructuredDataTypeCategory::INT: - return {DATA_INT, {0}}; - case CommonStructuredDataTypeCategory::BYTE: - return {DATA_BYTE, {0}}; - case CommonStructuredDataTypeCategory::BOOL: - return {DATA_BOOL, {0}}; - case CommonStructuredDataTypeCategory::FLOAT: - return {DATA_FLOAT, {0}}; - case CommonStructuredDataTypeCategory::SHORT: - return {DATA_SHORT, {0}}; - case CommonStructuredDataTypeCategory::STRING: - return {DATA_STRING, {inputType.m_info.string_length}}; - case CommonStructuredDataTypeCategory::ENUM: - return {DATA_ENUM, {inputType.m_info.type_index}}; - case CommonStructuredDataTypeCategory::STRUCT: - return {DATA_STRUCT, {inputType.m_info.type_index}}; - case CommonStructuredDataTypeCategory::INDEXED_ARRAY: - return {DATA_INDEXED_ARRAY, {inputType.m_info.type_index}}; - case CommonStructuredDataTypeCategory::ENUM_ARRAY: - return {DATA_ENUM_ARRAY, {inputType.m_info.type_index}}; - case CommonStructuredDataTypeCategory::UNKNOWN: - default: - assert(false); - return {DATA_INT, {0}}; - } +bool AssetLoaderStructuredDataDefSet::CanLoadFromRaw() const { return true; } + +StructuredDataType AssetLoaderStructuredDataDefSet::ConvertType(CommonStructuredDataType inputType) { + switch (inputType.m_category) { + case CommonStructuredDataTypeCategory::INT: + return {DATA_INT, {0}}; + case CommonStructuredDataTypeCategory::BYTE: + return {DATA_BYTE, {0}}; + case CommonStructuredDataTypeCategory::BOOL: + return {DATA_BOOL, {0}}; + case CommonStructuredDataTypeCategory::FLOAT: + return {DATA_FLOAT, {0}}; + case CommonStructuredDataTypeCategory::SHORT: + return {DATA_SHORT, {0}}; + case CommonStructuredDataTypeCategory::STRING: + return {DATA_STRING, {inputType.m_info.string_length}}; + case CommonStructuredDataTypeCategory::ENUM: + return {DATA_ENUM, {inputType.m_info.type_index}}; + case CommonStructuredDataTypeCategory::STRUCT: + return {DATA_STRUCT, {inputType.m_info.type_index}}; + case CommonStructuredDataTypeCategory::INDEXED_ARRAY: + return {DATA_INDEXED_ARRAY, {inputType.m_info.type_index}}; + case CommonStructuredDataTypeCategory::ENUM_ARRAY: + return {DATA_ENUM_ARRAY, {inputType.m_info.type_index}}; + case CommonStructuredDataTypeCategory::UNKNOWN: + default: + assert(false); + return {DATA_INT, {0}}; + } } -void AssetLoaderStructuredDataDefSet::ConvertEnum(StructuredDataEnum* outputEnum, CommonStructuredDataEnum* inputEnum, MemoryManager* memory) -{ - outputEnum->entryCount = static_cast(inputEnum->m_entries.size()); - if (inputEnum->m_reserved_entry_count <= 0) - outputEnum->reservedEntryCount = outputEnum->entryCount; - else - outputEnum->reservedEntryCount = inputEnum->m_reserved_entry_count; - - inputEnum->SortEntriesByName(); - if (!inputEnum->m_entries.empty()) - { - outputEnum->entries = static_cast(memory->Alloc(sizeof(StructuredDataEnumEntry) * inputEnum->m_entries.size())); - for (auto entryIndex = 0u; entryIndex < inputEnum->m_entries.size(); entryIndex++) - { - auto& outputEntry = outputEnum->entries[entryIndex]; - const auto& inputEntry = inputEnum->m_entries[entryIndex]; - - outputEntry.string = memory->Dup(inputEntry.m_name.c_str()); - outputEntry.index = static_cast(inputEntry.m_value); - } +void AssetLoaderStructuredDataDefSet::ConvertEnum(StructuredDataEnum *outputEnum, CommonStructuredDataEnum *inputEnum, MemoryManager *memory) { + outputEnum->entryCount = static_cast(inputEnum->m_entries.size()); + if (inputEnum->m_reserved_entry_count <= 0) + outputEnum->reservedEntryCount = outputEnum->entryCount; + else + outputEnum->reservedEntryCount = inputEnum->m_reserved_entry_count; + + inputEnum->SortEntriesByName(); + if (!inputEnum->m_entries.empty()) { + outputEnum->entries = static_cast(memory->Alloc(sizeof(StructuredDataEnumEntry) * inputEnum->m_entries.size())); + for (auto entryIndex = 0u; entryIndex < inputEnum->m_entries.size(); entryIndex++) { + auto &outputEntry = outputEnum->entries[entryIndex]; + const auto &inputEntry = inputEnum->m_entries[entryIndex]; + + outputEntry.string = memory->Dup(inputEntry.m_name.c_str()); + outputEntry.index = static_cast(inputEntry.m_value); } - else - outputEnum->entries = nullptr; + } else + outputEnum->entries = nullptr; } -void AssetLoaderStructuredDataDefSet::ConvertStruct(StructuredDataStruct* outputStruct, CommonStructuredDataStruct* inputStruct, MemoryManager* memory) -{ - outputStruct->size = static_cast(inputStruct->m_size_in_byte); - outputStruct->bitOffset = inputStruct->m_bit_offset; - - outputStruct->propertyCount = static_cast(inputStruct->m_properties.size()); - inputStruct->SortPropertiesByName(); - if (!inputStruct->m_properties.empty()) - { - outputStruct->properties = static_cast(memory->Alloc(sizeof(StructuredDataStructProperty) * inputStruct->m_properties.size())); - for (auto propertyIndex = 0u; propertyIndex < inputStruct->m_properties.size(); propertyIndex++) - { - auto& outputProperty = outputStruct->properties[propertyIndex]; - const auto& inputProperty = inputStruct->m_properties[propertyIndex]; - - outputProperty.name = memory->Dup(inputProperty.m_name.c_str()); - outputProperty.type = ConvertType(inputProperty.m_type); - - if (outputProperty.type.type != DATA_BOOL) - { - assert(inputProperty.m_offset_in_bits % 8 == 0); - outputProperty.offset = inputProperty.m_offset_in_bits / 8; - } - else - outputProperty.offset = inputProperty.m_offset_in_bits; - } +void AssetLoaderStructuredDataDefSet::ConvertStruct(StructuredDataStruct *outputStruct, CommonStructuredDataStruct *inputStruct, MemoryManager *memory) { + outputStruct->size = static_cast(inputStruct->m_size_in_byte); + outputStruct->bitOffset = inputStruct->m_bit_offset; + + outputStruct->propertyCount = static_cast(inputStruct->m_properties.size()); + inputStruct->SortPropertiesByName(); + if (!inputStruct->m_properties.empty()) { + outputStruct->properties = + static_cast(memory->Alloc(sizeof(StructuredDataStructProperty) * inputStruct->m_properties.size())); + for (auto propertyIndex = 0u; propertyIndex < inputStruct->m_properties.size(); propertyIndex++) { + auto &outputProperty = outputStruct->properties[propertyIndex]; + const auto &inputProperty = inputStruct->m_properties[propertyIndex]; + + outputProperty.name = memory->Dup(inputProperty.m_name.c_str()); + outputProperty.type = ConvertType(inputProperty.m_type); + + if (outputProperty.type.type != DATA_BOOL) { + assert(inputProperty.m_offset_in_bits % 8 == 0); + outputProperty.offset = inputProperty.m_offset_in_bits / 8; + } else + outputProperty.offset = inputProperty.m_offset_in_bits; } - else - outputStruct->properties = nullptr; + } else + outputStruct->properties = nullptr; } -void AssetLoaderStructuredDataDefSet::ConvertIndexedArray(StructuredDataIndexedArray* outputIndexedArray, const CommonStructuredDataIndexedArray* inputIndexedArray, MemoryManager* memory) -{ - outputIndexedArray->arraySize = static_cast(inputIndexedArray->m_element_count); - outputIndexedArray->elementType = ConvertType(inputIndexedArray->m_array_type); - outputIndexedArray->elementSize = utils::Align(inputIndexedArray->m_element_size_in_bits, 8u) / 8u; +void AssetLoaderStructuredDataDefSet::ConvertIndexedArray(StructuredDataIndexedArray *outputIndexedArray, + const CommonStructuredDataIndexedArray *inputIndexedArray, MemoryManager *memory) { + outputIndexedArray->arraySize = static_cast(inputIndexedArray->m_element_count); + outputIndexedArray->elementType = ConvertType(inputIndexedArray->m_array_type); + outputIndexedArray->elementSize = utils::Align(inputIndexedArray->m_element_size_in_bits, 8u) / 8u; } -void AssetLoaderStructuredDataDefSet::ConvertEnumedArray(StructuredDataEnumedArray* outputEnumedArray, const CommonStructuredDataEnumedArray* inputEnumedArray, MemoryManager* memory) -{ - outputEnumedArray->enumIndex = static_cast(inputEnumedArray->m_enum_index); - outputEnumedArray->elementType = ConvertType(inputEnumedArray->m_array_type); - outputEnumedArray->elementSize = utils::Align(inputEnumedArray->m_element_size_in_bits, 8u) / 8u; +void AssetLoaderStructuredDataDefSet::ConvertEnumedArray(StructuredDataEnumedArray *outputEnumedArray, const CommonStructuredDataEnumedArray *inputEnumedArray, + MemoryManager *memory) { + outputEnumedArray->enumIndex = static_cast(inputEnumedArray->m_enum_index); + outputEnumedArray->elementType = ConvertType(inputEnumedArray->m_array_type); + outputEnumedArray->elementSize = utils::Align(inputEnumedArray->m_element_size_in_bits, 8u) / 8u; } -void AssetLoaderStructuredDataDefSet::ConvertDef(StructuredDataDef* outputDef, const CommonStructuredDataDef* inputDef, MemoryManager* memory) -{ - outputDef->version = inputDef->m_version; - outputDef->formatChecksum = inputDef->m_checksum; - - outputDef->enumCount = static_cast(inputDef->m_enums.size()); - if (!inputDef->m_enums.empty()) - { - outputDef->enums = static_cast(memory->Alloc(sizeof(StructuredDataEnum) * inputDef->m_enums.size())); - for (auto enumIndex = 0u; enumIndex < inputDef->m_enums.size(); enumIndex++) - ConvertEnum(&outputDef->enums[enumIndex], inputDef->m_enums[enumIndex].get(), memory); - } - else - outputDef->enums = nullptr; - - outputDef->structCount = static_cast(inputDef->m_structs.size()); - if (!inputDef->m_structs.empty()) - { - outputDef->structs = static_cast(memory->Alloc(sizeof(StructuredDataStruct) * inputDef->m_structs.size())); - for (auto structIndex = 0u; structIndex < inputDef->m_structs.size(); structIndex++) - ConvertStruct(&outputDef->structs[structIndex], inputDef->m_structs[structIndex].get(), memory); - } - else - outputDef->structs = nullptr; - - outputDef->indexedArrayCount = static_cast(inputDef->m_indexed_arrays.size()); - if (!inputDef->m_indexed_arrays.empty()) - { - outputDef->indexedArrays = static_cast(memory->Alloc(sizeof(StructuredDataIndexedArray) * inputDef->m_indexed_arrays.size())); - for (auto indexedArrayIndex = 0u; indexedArrayIndex < inputDef->m_indexed_arrays.size(); indexedArrayIndex++) - ConvertIndexedArray(&outputDef->indexedArrays[indexedArrayIndex], &inputDef->m_indexed_arrays[indexedArrayIndex], memory); - } - else - outputDef->indexedArrays = nullptr; - - outputDef->enumedArrayCount = static_cast(inputDef->m_enumed_arrays.size()); - if (!inputDef->m_enumed_arrays.empty()) - { - outputDef->enumedArrays = static_cast(memory->Alloc(sizeof(StructuredDataEnumedArray) * inputDef->m_enumed_arrays.size())); - for (auto enumedArrayIndex = 0u; enumedArrayIndex < inputDef->m_enumed_arrays.size(); enumedArrayIndex++) - ConvertEnumedArray(&outputDef->enumedArrays[enumedArrayIndex], &inputDef->m_enumed_arrays[enumedArrayIndex], memory); - } - else - outputDef->enumedArrays = nullptr; - - outputDef->rootType = ConvertType(inputDef->m_root_type); - outputDef->size = inputDef->m_size_in_byte; +void AssetLoaderStructuredDataDefSet::ConvertDef(StructuredDataDef *outputDef, const CommonStructuredDataDef *inputDef, MemoryManager *memory) { + outputDef->version = inputDef->m_version; + outputDef->formatChecksum = inputDef->m_checksum; + + outputDef->enumCount = static_cast(inputDef->m_enums.size()); + if (!inputDef->m_enums.empty()) { + outputDef->enums = static_cast(memory->Alloc(sizeof(StructuredDataEnum) * inputDef->m_enums.size())); + for (auto enumIndex = 0u; enumIndex < inputDef->m_enums.size(); enumIndex++) + ConvertEnum(&outputDef->enums[enumIndex], inputDef->m_enums[enumIndex].get(), memory); + } else + outputDef->enums = nullptr; + + outputDef->structCount = static_cast(inputDef->m_structs.size()); + if (!inputDef->m_structs.empty()) { + outputDef->structs = static_cast(memory->Alloc(sizeof(StructuredDataStruct) * inputDef->m_structs.size())); + for (auto structIndex = 0u; structIndex < inputDef->m_structs.size(); structIndex++) + ConvertStruct(&outputDef->structs[structIndex], inputDef->m_structs[structIndex].get(), memory); + } else + outputDef->structs = nullptr; + + outputDef->indexedArrayCount = static_cast(inputDef->m_indexed_arrays.size()); + if (!inputDef->m_indexed_arrays.empty()) { + outputDef->indexedArrays = static_cast(memory->Alloc(sizeof(StructuredDataIndexedArray) * inputDef->m_indexed_arrays.size())); + for (auto indexedArrayIndex = 0u; indexedArrayIndex < inputDef->m_indexed_arrays.size(); indexedArrayIndex++) + ConvertIndexedArray(&outputDef->indexedArrays[indexedArrayIndex], &inputDef->m_indexed_arrays[indexedArrayIndex], memory); + } else + outputDef->indexedArrays = nullptr; + + outputDef->enumedArrayCount = static_cast(inputDef->m_enumed_arrays.size()); + if (!inputDef->m_enumed_arrays.empty()) { + outputDef->enumedArrays = static_cast(memory->Alloc(sizeof(StructuredDataEnumedArray) * inputDef->m_enumed_arrays.size())); + for (auto enumedArrayIndex = 0u; enumedArrayIndex < inputDef->m_enumed_arrays.size(); enumedArrayIndex++) + ConvertEnumedArray(&outputDef->enumedArrays[enumedArrayIndex], &inputDef->m_enumed_arrays[enumedArrayIndex], memory); + } else + outputDef->enumedArrays = nullptr; + + outputDef->rootType = ConvertType(inputDef->m_root_type); + outputDef->size = inputDef->m_size_in_byte; } -StructuredDataDefSet* AssetLoaderStructuredDataDefSet::ConvertSet(const std::string& assetName, const std::vector>& defs, MemoryManager* memory) -{ - auto* set = memory->Create(); - set->name = memory->Dup(assetName.c_str()); - set->defCount = defs.size(); - set->defs = static_cast(memory->Alloc(sizeof(StructuredDataDef) * defs.size())); +StructuredDataDefSet *AssetLoaderStructuredDataDefSet::ConvertSet(const std::string &assetName, + const std::vector> &defs, MemoryManager *memory) { + auto *set = memory->Create(); + set->name = memory->Dup(assetName.c_str()); + set->defCount = defs.size(); + set->defs = static_cast(memory->Alloc(sizeof(StructuredDataDef) * defs.size())); - for (auto defIndex = 0u; defIndex < defs.size(); defIndex++) - ConvertDef(&set->defs[defIndex], defs[defIndex].get(), memory); + for (auto defIndex = 0u; defIndex < defs.size(); defIndex++) + ConvertDef(&set->defs[defIndex], defs[defIndex].get(), memory); - return set; + return set; } -bool AssetLoaderStructuredDataDefSet::LoadFromRaw(const std::string& assetName, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const -{ - const auto file = searchPath->Open(assetName); - if (!file.IsOpen()) - return false; +bool AssetLoaderStructuredDataDefSet::LoadFromRaw(const std::string &assetName, ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager, + Zone *zone) const { + const auto file = searchPath->Open(assetName); + if (!file.IsOpen()) + return false; - StructuredDataDefReader reader(*file.m_stream, assetName, [searchPath](const std::string& filename, const std::string& sourceFile) -> std::unique_ptr - { - auto foundFileToInclude = searchPath->Open(filename); - if (!foundFileToInclude.IsOpen() || !foundFileToInclude.m_stream) - return nullptr; + StructuredDataDefReader reader(*file.m_stream, assetName, + [searchPath](const std::string &filename, const std::string &sourceFile) -> std::unique_ptr { + auto foundFileToInclude = searchPath->Open(filename); + if (!foundFileToInclude.IsOpen() || !foundFileToInclude.m_stream) + return nullptr; - return std::move(foundFileToInclude.m_stream); - }); + return std::move(foundFileToInclude.m_stream); + }); - bool readingDefsSuccessful; - const auto defs = reader.ReadStructureDataDefs(readingDefsSuccessful); + bool readingDefsSuccessful; + const auto defs = reader.ReadStructureDataDefs(readingDefsSuccessful); - if (readingDefsSuccessful) - manager->AddAsset(ASSET_TYPE_STRUCTURED_DATA_DEF, assetName, ConvertSet(assetName, defs, memory)); + if (readingDefsSuccessful) + manager->AddAsset(ASSET_TYPE_STRUCTURED_DATA_DEF, assetName, ConvertSet(assetName, defs, memory)); - return true; + return true; } diff --git a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderStructuredDataDefSet.h b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderStructuredDataDefSet.h index 9a72d9d4f..6b0508a2e 100644 --- a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderStructuredDataDefSet.h +++ b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderStructuredDataDefSet.h @@ -1,24 +1,24 @@ #pragma once -#include "Game/IW4/IW4.h" #include "AssetLoading/BasicAssetLoader.h" -#include "StructuredDataDef/CommonStructuredDataDef.h" +#include "Game/IW4/IW4.h" #include "SearchPath/ISearchPath.h" +#include "StructuredDataDef/CommonStructuredDataDef.h" -namespace IW4 -{ - class AssetLoaderStructuredDataDefSet final : public BasicAssetLoader - { - public: - _NODISCARD void* CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) override; - _NODISCARD bool CanLoadFromRaw() const override; - static StructuredDataType ConvertType(CommonStructuredDataType inputType); - static void ConvertEnum(StructuredDataEnum* outputEnum, CommonStructuredDataEnum* inputEnum, MemoryManager* memory); - static void ConvertStruct(StructuredDataStruct* outputStruct, CommonStructuredDataStruct* inputStruct, MemoryManager* memory); - static void ConvertIndexedArray(StructuredDataIndexedArray* outputIndexedArray, const CommonStructuredDataIndexedArray* inputIndexedArray, MemoryManager* memory); - static void ConvertEnumedArray(StructuredDataEnumedArray* outputEnumedArray, const CommonStructuredDataEnumedArray* inputEnumedArray, MemoryManager* memory); - static void ConvertDef(StructuredDataDef* outputDef, const CommonStructuredDataDef* inputDef, MemoryManager* memory); - static StructuredDataDefSet* ConvertSet(const std::string& assetName, const std::vector>& defs, MemoryManager* memory); - bool LoadFromRaw(const std::string& assetName, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const override; - }; -} +namespace IW4 { +class AssetLoaderStructuredDataDefSet final : public BasicAssetLoader { +public: + _NODISCARD void *CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) override; + _NODISCARD bool CanLoadFromRaw() const override; + static StructuredDataType ConvertType(CommonStructuredDataType inputType); + static void ConvertEnum(StructuredDataEnum *outputEnum, CommonStructuredDataEnum *inputEnum, MemoryManager *memory); + static void ConvertStruct(StructuredDataStruct *outputStruct, CommonStructuredDataStruct *inputStruct, MemoryManager *memory); + static void ConvertIndexedArray(StructuredDataIndexedArray *outputIndexedArray, const CommonStructuredDataIndexedArray *inputIndexedArray, + MemoryManager *memory); + static void ConvertEnumedArray(StructuredDataEnumedArray *outputEnumedArray, const CommonStructuredDataEnumedArray *inputEnumedArray, MemoryManager *memory); + static void ConvertDef(StructuredDataDef *outputDef, const CommonStructuredDataDef *inputDef, MemoryManager *memory); + static StructuredDataDefSet *ConvertSet(const std::string &assetName, const std::vector> &defs, + MemoryManager *memory); + bool LoadFromRaw(const std::string &assetName, ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager, Zone *zone) const override; +}; +} // namespace IW4 diff --git a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderTechniqueSet.cpp b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderTechniqueSet.cpp index 74cb73844..7980ba83f 100644 --- a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderTechniqueSet.cpp +++ b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderTechniqueSet.cpp @@ -3,1350 +3,1176 @@ #include #include #include -#include #include #include +#include #include "AssetLoaderPixelShader.h" #include "AssetLoaderVertexShader.h" -#include "Utils/ClassUtils.h" -#include "ObjLoading.h" #include "Game/IW4/IW4.h" #include "Game/IW4/TechsetConstantsIW4.h" +#include "ObjLoading.h" #include "Pool/GlobalAssetPool.h" -#include "Techset/TechniqueFileReader.h" -#include "Techset/TechsetFileReader.h" #include "Shader/D3D9ShaderAnalyser.h" #include "StateMap/StateMapReader.h" +#include "Techset/TechniqueFileReader.h" #include "Techset/TechniqueStateMapCache.h" #include "Techset/TechsetDefinitionCache.h" +#include "Techset/TechsetFileReader.h" #include "Utils/Alignment.h" +#include "Utils/ClassUtils.h" using namespace IW4; using namespace std::string_literals; -namespace IW4 -{ - class LoadedTechnique - { - public: - MaterialTechnique* m_technique; - std::vector m_dependencies; - - LoadedTechnique(MaterialTechnique* technique, std::vector dependencies) - : m_technique(technique), - m_dependencies(std::move(dependencies)) - { - } - }; +namespace IW4 { +class LoadedTechnique { +public: + MaterialTechnique *m_technique; + std::vector m_dependencies; + + LoadedTechnique(MaterialTechnique *technique, std::vector dependencies) + : m_technique(technique), m_dependencies(std::move(dependencies)) {} +}; + +class TechniqueZoneLoadingState final : public IZoneAssetLoaderState { +public: + typedef const float (*literal_t)[4]; + +private: + std::unordered_map> m_loaded_techniques; + std::map m_allocated_literals; + +public: + _NODISCARD const LoadedTechnique *FindLoadedTechnique(const std::string &techniqueName) const { + const auto loadedTechnique = m_loaded_techniques.find(techniqueName); + if (loadedTechnique != m_loaded_techniques.end()) + return loadedTechnique->second.get(); + + return nullptr; + } + + const LoadedTechnique *AddLoadedTechnique(std::string techniqueName, MaterialTechnique *technique, std::vector dependencies) { + return m_loaded_techniques.emplace(std::make_pair(std::move(techniqueName), std::make_unique(technique, std::move(dependencies)))) + .first->second.get(); + } + + literal_t GetAllocatedLiteral(MemoryManager *memory, techset::ShaderArgumentLiteralSource source) { + const auto &existingEntry = m_allocated_literals.find(source); + + if (existingEntry != m_allocated_literals.end()) + return existingEntry->second; + + auto *newLiteral = static_cast(memory->Alloc(sizeof(float) * 4u)); + (*newLiteral)[0] = source.m_value[0]; + (*newLiteral)[1] = source.m_value[1]; + (*newLiteral)[2] = source.m_value[2]; + (*newLiteral)[3] = source.m_value[3]; + m_allocated_literals.emplace(std::make_pair(source, newLiteral)); + + return newLiteral; + } +}; + +class ShaderInfoFromFileSystemCacheState final : public IZoneAssetLoaderState { + std::unordered_map> m_cached_shader_info; + +public: + _NODISCARD const d3d9::ShaderInfo *LoadShaderInfoFromDisk(ISearchPath *searchPath, const std::string &fileName) { + const auto cachedShaderInfo = m_cached_shader_info.find(fileName); + if (cachedShaderInfo != m_cached_shader_info.end()) + return cachedShaderInfo->second.get(); + + const auto file = searchPath->Open(fileName); + if (!file.IsOpen()) + return nullptr; - class TechniqueZoneLoadingState final : public IZoneAssetLoaderState - { - public: - typedef const float (*literal_t)[4]; + const auto shaderSize = static_cast(file.m_length); - private: - std::unordered_map> m_loaded_techniques; - std::map m_allocated_literals; + if (shaderSize % sizeof(uint32_t) != 0) { + std::cerr << "Invalid shader \"" << fileName << "\": Size must be dividable by " << sizeof(uint32_t) << "\n"; + return nullptr; + } - public: - _NODISCARD const LoadedTechnique* FindLoadedTechnique(const std::string& techniqueName) const - { - const auto loadedTechnique = m_loaded_techniques.find(techniqueName); - if (loadedTechnique != m_loaded_techniques.end()) - return loadedTechnique->second.get(); + const auto shaderData = std::make_unique(shaderSize); + file.m_stream->read(shaderData.get(), shaderSize); + + auto shaderInfo = d3d9::ShaderAnalyser::GetShaderInfo(reinterpret_cast(shaderData.get()), shaderSize); + if (!shaderInfo) + return nullptr; + + const auto *result = shaderInfo.get(); + m_cached_shader_info.emplace(std::make_pair(fileName, std::move(shaderInfo))); + return result; + } +}; + +class TechniqueCreator final : public techset::ITechniqueDefinitionAcceptor { + const std::string &m_technique_name; + ISearchPath *const m_search_path; + MemoryManager *const m_memory; + IAssetLoadingManager *const m_manager; + TechniqueZoneLoadingState *const m_zone_state; + techset::TechniqueStateMapCache *const m_state_map_cache; + ShaderInfoFromFileSystemCacheState *const m_shader_info_cache; + +public: + class PassShaderArgument { + public: + MaterialShaderArgument m_arg; + MaterialUpdateFrequency m_update_frequency; + + static MaterialUpdateFrequency GetUpdateFrequencyForArg(MaterialShaderArgument arg) { + switch (arg.type) { + case MTL_ARG_CODE_VERTEX_CONST: + case MTL_ARG_CODE_PIXEL_CONST: + if (arg.u.codeConst.index >= std::extent_v) { + assert(false); + return MTL_UPDATE_RARELY; + } + return s_codeConstUpdateFreq[arg.u.codeConst.index]; - return nullptr; + case MTL_ARG_CODE_PIXEL_SAMPLER: + if (arg.u.codeSampler >= std::extent_v) { + assert(false); + return MTL_UPDATE_RARELY; } + return s_codeSamplerUpdateFreq[arg.u.codeSampler]; + + case MTL_ARG_MATERIAL_VERTEX_CONST: + case MTL_ARG_MATERIAL_PIXEL_SAMPLER: + case MTL_ARG_MATERIAL_PIXEL_CONST: + case MTL_ARG_LITERAL_VERTEX_CONST: + case MTL_ARG_LITERAL_PIXEL_CONST: + default: + return MTL_UPDATE_RARELY; + } + } + + explicit PassShaderArgument(const MaterialShaderArgument arg) : m_arg(arg), m_update_frequency(GetUpdateFrequencyForArg(arg)) {} + }; + + struct Pass { + XAssetInfo *m_vertex_shader; + const d3d9::ShaderInfo *m_vertex_shader_info; + std::unique_ptr m_vertex_shader_info_unq; + std::vector m_vertex_shader_argument_handled_offset; + std::vector m_handled_vertex_shader_arguments; + + XAssetInfo *m_pixel_shader; + const d3d9::ShaderInfo *m_pixel_shader_info; + std::unique_ptr m_pixel_shader_info_unq; + std::vector m_pixel_shader_argument_handled_offset; + std::vector m_handled_pixel_shader_arguments; + + MaterialVertexDeclaration m_vertex_decl; + XAssetInfo *m_vertex_decl_asset; + std::vector m_arguments; + + Pass() + : m_vertex_shader(nullptr), m_vertex_shader_info(nullptr), m_pixel_shader(nullptr), m_pixel_shader_info(nullptr), m_vertex_decl{}, + m_vertex_decl_asset(nullptr) {} + }; + + std::vector m_passes; + std::vector m_dependencies; + + TechniqueCreator(const std::string &techniqueName, ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager, + TechniqueZoneLoadingState *zoneState, ShaderInfoFromFileSystemCacheState *shaderInfoCache, techset::TechniqueStateMapCache *stateMapCache) + : m_technique_name(techniqueName), m_search_path(searchPath), m_memory(memory), m_manager(manager), m_zone_state(zoneState), + m_state_map_cache(stateMapCache), m_shader_info_cache(shaderInfoCache) {} + + void AcceptNextPass() override { m_passes.emplace_back(); } + + static size_t RegisterCountPerElement(const d3d9::ShaderConstant &constant) { + const auto valuesPerRegister = constant.m_register_set == d3d9::RegisterSet::BOOL || constant.m_register_set == d3d9::RegisterSet::SAMPLER ? 1u : 4u; + return utils::Align(constant.m_type_columns * constant.m_type_rows, valuesPerRegister) / valuesPerRegister; + } + + static bool IsSamplerArgument(const d3d9::ShaderConstant &constant) { + return constant.m_type == d3d9::ParameterType::SAMPLER || constant.m_type == d3d9::ParameterType::SAMPLER_1D || + constant.m_type == d3d9::ParameterType::SAMPLER_2D || constant.m_type == d3d9::ParameterType::SAMPLER_3D || + constant.m_type == d3d9::ParameterType::SAMPLER_CUBE; + } + + bool AutoCreateShaderArgument(const techset::ShaderSelector shaderType, const d3d9::ShaderConstant &shaderArgument, const size_t elementOffset, + const size_t registerOffset) { + assert(!m_passes.empty()); + auto &pass = m_passes.at(m_passes.size() - 1); + + const auto isSamplerArgument = IsSamplerArgument(shaderArgument); + if (shaderType == techset::ShaderSelector::VERTEX_SHADER && isSamplerArgument) + return false; + + MaterialShaderArgument argument{}; + argument.dest = static_cast(shaderArgument.m_register_index + registerOffset); + + unsigned arrayCount; + const std::vector accessors({shaderArgument.m_name}); + if (isSamplerArgument) { + const CodeSamplerSource *samplerSource = FindCodeSamplerSource(accessors, s_codeSamplers); + if (!samplerSource) + samplerSource = FindCodeSamplerSource(accessors, s_defaultCodeSamplers); + + if (!samplerSource) + return false; + + argument.type = MTL_ARG_CODE_PIXEL_SAMPLER; + argument.u.codeSampler = samplerSource->source + elementOffset; + + arrayCount = static_cast(samplerSource->arrayCount); + } else { + const CodeConstantSource *constantSource = FindCodeConstantSource(accessors, s_codeConsts); + if (!constantSource) + constantSource = FindCodeConstantSource(accessors, s_defaultCodeConsts); + + if (!constantSource) + return false; + + argument.type = shaderType == techset::ShaderSelector::VERTEX_SHADER ? MTL_ARG_CODE_VERTEX_CONST : MTL_ARG_CODE_PIXEL_CONST; + argument.u.codeConst.index = static_cast(constantSource->source + elementOffset); + argument.u.codeConst.firstRow = 0u; + argument.u.codeConst.rowCount = static_cast(shaderArgument.m_type_rows); + + arrayCount = static_cast(constantSource->arrayCount); + } + + if (elementOffset >= std::max(arrayCount, 1u)) + return false; - const LoadedTechnique* AddLoadedTechnique(std::string techniqueName, MaterialTechnique* technique, std::vector dependencies) - { - return m_loaded_techniques.emplace(std::make_pair(std::move(techniqueName), std::make_unique(technique, std::move(dependencies)))).first->second.get(); + pass.m_arguments.emplace_back(argument); + return true; + } + + bool AutoCreateVertexShaderArguments(std::string &errorMessage) { + assert(!m_passes.empty()); + const auto &pass = m_passes.at(m_passes.size() - 1); + + for (auto i = 0u; i < pass.m_vertex_shader_argument_handled_offset.size(); i++) { + const auto &argument = pass.m_vertex_shader_info->m_constants[i]; + const auto argumentHandledIndex = pass.m_vertex_shader_argument_handled_offset[i]; + const auto argumentRegistersPerElement = argument.m_type_elements > 1u ? RegisterCountPerElement(argument) : argument.m_register_count; + + auto elementIndex = 0u; + for (auto registerIndex = 0u; registerIndex < argument.m_register_count; registerIndex += argumentRegistersPerElement) { + if (!pass.m_handled_vertex_shader_arguments[argumentHandledIndex + elementIndex]) { + if (!AutoCreateShaderArgument(techset::ShaderSelector::VERTEX_SHADER, argument, elementIndex, registerIndex)) { + std::ostringstream ss; + ss << "Unassigned vertex shader \"" << pass.m_vertex_shader->m_name << "\" arg: " << argument.m_name; + + if (argument.m_type_elements > 1) + ss << '[' << elementIndex << ']'; + + errorMessage = ss.str(); + return false; + } } - literal_t GetAllocatedLiteral(MemoryManager* memory, techset::ShaderArgumentLiteralSource source) - { - const auto& existingEntry = m_allocated_literals.find(source); + elementIndex++; + } + } - if (existingEntry != m_allocated_literals.end()) - return existingEntry->second; + return true; + } - auto* newLiteral = static_cast(memory->Alloc(sizeof(float) * 4u)); - (*newLiteral)[0] = source.m_value[0]; - (*newLiteral)[1] = source.m_value[1]; - (*newLiteral)[2] = source.m_value[2]; - (*newLiteral)[3] = source.m_value[3]; - m_allocated_literals.emplace(std::make_pair(source, newLiteral)); + bool AutoCreatePixelShaderArguments(std::string &errorMessage) { + assert(!m_passes.empty()); + const auto &pass = m_passes.at(m_passes.size() - 1); - return newLiteral; + for (auto i = 0u; i < pass.m_pixel_shader_argument_handled_offset.size(); i++) { + const auto &argument = pass.m_pixel_shader_info->m_constants[i]; + const auto argumentHandledIndex = pass.m_pixel_shader_argument_handled_offset[i]; + const auto argumentRegistersPerElement = argument.m_type_elements > 1u ? RegisterCountPerElement(argument) : argument.m_register_count; + + auto elementIndex = 0u; + for (auto registerIndex = 0u; registerIndex < argument.m_register_count; registerIndex += argumentRegistersPerElement) { + if (!pass.m_handled_pixel_shader_arguments[argumentHandledIndex + elementIndex]) { + if (!AutoCreateShaderArgument(techset::ShaderSelector::PIXEL_SHADER, argument, elementIndex, registerIndex)) { + std::ostringstream ss; + ss << "Unassigned pixel shader \"" << pass.m_pixel_shader->m_name << "\" arg: " << argument.m_name; + + if (argument.m_type_elements > 1) + ss << '[' << elementIndex << ']'; + + errorMessage = ss.str(); + return false; + } } - }; - class ShaderInfoFromFileSystemCacheState final : public IZoneAssetLoaderState - { - std::unordered_map> m_cached_shader_info; + elementIndex++; + } + } - public: - _NODISCARD const d3d9::ShaderInfo* LoadShaderInfoFromDisk(ISearchPath* searchPath, const std::string& fileName) - { - const auto cachedShaderInfo = m_cached_shader_info.find(fileName); - if (cachedShaderInfo != m_cached_shader_info.end()) - return cachedShaderInfo->second.get(); + return true; + } - const auto file = searchPath->Open(fileName); - if (!file.IsOpen()) - return nullptr; + void AllocateVertexDecl() { + assert(!m_passes.empty()); + auto &pass = m_passes.at(m_passes.size() - 1); - const auto shaderSize = static_cast(file.m_length); + std::sort(std::begin(pass.m_vertex_decl.routing.data), std::begin(pass.m_vertex_decl.routing.data) + pass.m_vertex_decl.streamCount, + [](const MaterialStreamRouting &r1, const MaterialStreamRouting &r2) { return r1.source < r2.source; }); - if (shaderSize % sizeof(uint32_t) != 0) - { - std::cerr << "Invalid shader \"" << fileName << "\": Size must be dividable by " << sizeof(uint32_t) << "\n"; - return nullptr; - } + std::ostringstream ss; + for (auto i = 0u; i < pass.m_vertex_decl.streamCount; i++) { + const auto &stream = pass.m_vertex_decl.routing.data[i]; + assert(stream.source < std::extent_v); + assert(stream.dest < std::extent_v); - const auto shaderData = std::make_unique(shaderSize); - file.m_stream->read(shaderData.get(), shaderSize); + ss << materialStreamSourceAbbreviation[stream.source] << materialStreamDestinationAbbreviation[stream.dest]; + } - auto shaderInfo = d3d9::ShaderAnalyser::GetShaderInfo(reinterpret_cast(shaderData.get()), shaderSize); - if (!shaderInfo) - return nullptr; + pass.m_vertex_decl_asset = reinterpret_cast *>(m_manager->LoadDependency(ASSET_TYPE_VERTEXDECL, ss.str())); + } - const auto* result = shaderInfo.get(); - m_cached_shader_info.emplace(std::make_pair(fileName, std::move(shaderInfo))); - return result; - } - }; - - class TechniqueCreator final : public techset::ITechniqueDefinitionAcceptor - { - const std::string& m_technique_name; - ISearchPath* const m_search_path; - MemoryManager* const m_memory; - IAssetLoadingManager* const m_manager; - TechniqueZoneLoadingState* const m_zone_state; - techset::TechniqueStateMapCache* const m_state_map_cache; - ShaderInfoFromFileSystemCacheState* const m_shader_info_cache; - - public: - class PassShaderArgument - { - public: - MaterialShaderArgument m_arg; - MaterialUpdateFrequency m_update_frequency; - - static MaterialUpdateFrequency GetUpdateFrequencyForArg(MaterialShaderArgument arg) - { - switch (arg.type) - { - case MTL_ARG_CODE_VERTEX_CONST: - case MTL_ARG_CODE_PIXEL_CONST: - if (arg.u.codeConst.index >= std::extent_v) - { - assert(false); - return MTL_UPDATE_RARELY; - } - return s_codeConstUpdateFreq[arg.u.codeConst.index]; - - case MTL_ARG_CODE_PIXEL_SAMPLER: - if (arg.u.codeSampler >= std::extent_v) - { - assert(false); - return MTL_UPDATE_RARELY; - } - return s_codeSamplerUpdateFreq[arg.u.codeSampler]; - - case MTL_ARG_MATERIAL_VERTEX_CONST: - case MTL_ARG_MATERIAL_PIXEL_SAMPLER: - case MTL_ARG_MATERIAL_PIXEL_CONST: - case MTL_ARG_LITERAL_VERTEX_CONST: - case MTL_ARG_LITERAL_PIXEL_CONST: - default: - return MTL_UPDATE_RARELY; - } - } - - explicit PassShaderArgument(const MaterialShaderArgument arg) - : m_arg(arg), - m_update_frequency(GetUpdateFrequencyForArg(arg)) - { - } - }; - - struct Pass - { - XAssetInfo* m_vertex_shader; - const d3d9::ShaderInfo* m_vertex_shader_info; - std::unique_ptr m_vertex_shader_info_unq; - std::vector m_vertex_shader_argument_handled_offset; - std::vector m_handled_vertex_shader_arguments; - - XAssetInfo* m_pixel_shader; - const d3d9::ShaderInfo* m_pixel_shader_info; - std::unique_ptr m_pixel_shader_info_unq; - std::vector m_pixel_shader_argument_handled_offset; - std::vector m_handled_pixel_shader_arguments; - - MaterialVertexDeclaration m_vertex_decl; - XAssetInfo* m_vertex_decl_asset; - std::vector m_arguments; - - Pass() - : m_vertex_shader(nullptr), - m_vertex_shader_info(nullptr), - m_pixel_shader(nullptr), - m_pixel_shader_info(nullptr), - m_vertex_decl{}, - m_vertex_decl_asset(nullptr) - { - } - }; - - std::vector m_passes; - std::vector m_dependencies; - - TechniqueCreator(const std::string& techniqueName, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager, TechniqueZoneLoadingState* zoneState, - ShaderInfoFromFileSystemCacheState* shaderInfoCache, - techset::TechniqueStateMapCache* stateMapCache) - : m_technique_name(techniqueName), - m_search_path(searchPath), - m_memory(memory), - m_manager(manager), - m_zone_state(zoneState), - m_state_map_cache(stateMapCache), - m_shader_info_cache(shaderInfoCache) - { - } + bool AcceptEndPass(std::string &errorMessage) override { + assert(!m_passes.empty()); + auto &pass = m_passes.at(m_passes.size() - 1); - void AcceptNextPass() override - { - m_passes.emplace_back(); - } + if (!AutoCreateVertexShaderArguments(errorMessage) || !AutoCreatePixelShaderArguments(errorMessage)) + return false; - static size_t RegisterCountPerElement(const d3d9::ShaderConstant& constant) - { - const auto valuesPerRegister = constant.m_register_set == d3d9::RegisterSet::BOOL || constant.m_register_set == d3d9::RegisterSet::SAMPLER ? 1u : 4u; - return utils::Align(constant.m_type_columns * constant.m_type_rows, valuesPerRegister) / valuesPerRegister; - } + // Sort args by their update frequency + std::sort(pass.m_arguments.begin(), pass.m_arguments.end(), [](const PassShaderArgument &arg1, const PassShaderArgument &arg2) { + if (arg1.m_update_frequency != arg2.m_update_frequency) + return arg1.m_update_frequency < arg2.m_update_frequency; - static bool IsSamplerArgument(const d3d9::ShaderConstant& constant) - { - return constant.m_type == d3d9::ParameterType::SAMPLER - || constant.m_type == d3d9::ParameterType::SAMPLER_1D - || constant.m_type == d3d9::ParameterType::SAMPLER_2D - || constant.m_type == d3d9::ParameterType::SAMPLER_3D - || constant.m_type == d3d9::ParameterType::SAMPLER_CUBE; - } + if (arg1.m_arg.type != arg2.m_arg.type) + return arg1.m_arg.type < arg2.m_arg.type; - bool AutoCreateShaderArgument(const techset::ShaderSelector shaderType, const d3d9::ShaderConstant& shaderArgument, const size_t elementOffset, const size_t registerOffset) - { - assert(!m_passes.empty()); - auto& pass = m_passes.at(m_passes.size() - 1); + if (arg1.m_arg.type == MTL_ARG_MATERIAL_VERTEX_CONST || arg1.m_arg.type == MTL_ARG_MATERIAL_PIXEL_CONST || + arg1.m_arg.type == MTL_ARG_MATERIAL_PIXEL_SAMPLER) + return arg1.m_arg.u.codeSampler < arg2.m_arg.u.codeSampler; - const auto isSamplerArgument = IsSamplerArgument(shaderArgument); - if (shaderType == techset::ShaderSelector::VERTEX_SHADER && isSamplerArgument) - return false; + return arg1.m_arg.dest < arg2.m_arg.dest; + }); - MaterialShaderArgument argument{}; - argument.dest = static_cast(shaderArgument.m_register_index + registerOffset); + AllocateVertexDecl(); - unsigned arrayCount; - const std::vector accessors({shaderArgument.m_name}); - if (isSamplerArgument) - { - const CodeSamplerSource* samplerSource = FindCodeSamplerSource(accessors, s_codeSamplers); - if (!samplerSource) - samplerSource = FindCodeSamplerSource(accessors, s_defaultCodeSamplers); + return true; + } - if (!samplerSource) - return false; + bool AcceptStateMap(const std::string &stateMapName, std::string &errorMessage) override { + const auto *stateMap = AssetLoaderTechniqueSet::LoadStateMapDefinition(stateMapName, m_search_path, m_state_map_cache); - argument.type = MTL_ARG_CODE_PIXEL_SAMPLER; - argument.u.codeSampler = samplerSource->source + elementOffset; + if (!stateMap) { + std::ostringstream ss; + ss << "Failed to load specified state map \"" << stateMapName << "\""; + errorMessage = ss.str(); + return false; + } - arrayCount = static_cast(samplerSource->arrayCount); - } - else - { - const CodeConstantSource* constantSource = FindCodeConstantSource(accessors, s_codeConsts); - if (!constantSource) - constantSource = FindCodeConstantSource(accessors, s_defaultCodeConsts); + m_state_map_cache->SetTechniqueUsesStateMap(m_technique_name, stateMap); + return true; + } + + static void InitializeArgumentState(const d3d9::ShaderInfo &shaderInfo, std::vector &argumentHandledOffsetVector, + std::vector &argumentHandledVector) { + auto vertexShaderArgumentSlotCount = 0u; + auto argIndex = 0u; + argumentHandledOffsetVector.resize(shaderInfo.m_constants.size()); + for (const auto &arg : shaderInfo.m_constants) { + argumentHandledOffsetVector[argIndex++] = vertexShaderArgumentSlotCount; + + if (arg.m_type_elements > 1) + vertexShaderArgumentSlotCount += arg.m_register_count / RegisterCountPerElement(arg); + else + vertexShaderArgumentSlotCount++; + } + argumentHandledVector.resize(vertexShaderArgumentSlotCount); + } + + bool AcceptVertexShader(const std::string &vertexShaderName, std::string &errorMessage) override { + auto *vertexShaderDependency = m_manager->LoadDependency(ASSET_TYPE_VERTEXSHADER, vertexShaderName); + if (vertexShaderDependency == nullptr) { + std::ostringstream ss; + ss << "Failed to load specified shader \"" << vertexShaderName << "\""; + errorMessage = ss.str(); + return false; + } - if (!constantSource) - return false; + assert(!m_passes.empty()); + auto &pass = m_passes.at(m_passes.size() - 1); + pass.m_vertex_shader = reinterpret_cast *>(vertexShaderDependency); - argument.type = shaderType == techset::ShaderSelector::VERTEX_SHADER ? MTL_ARG_CODE_VERTEX_CONST : MTL_ARG_CODE_PIXEL_CONST; - argument.u.codeConst.index = static_cast(constantSource->source + elementOffset); - argument.u.codeConst.firstRow = 0u; - argument.u.codeConst.rowCount = static_cast(shaderArgument.m_type_rows); + if (pass.m_vertex_shader->Asset()->name && pass.m_vertex_shader->Asset()->name[0] == ',') { + pass.m_vertex_shader_info = m_shader_info_cache->LoadShaderInfoFromDisk(m_search_path, AssetLoaderVertexShader::GetFileNameForAsset(vertexShaderName)); + } else { + const auto &shaderLoadDef = pass.m_vertex_shader->Asset()->prog.loadDef; + pass.m_vertex_shader_info_unq = d3d9::ShaderAnalyser::GetShaderInfo(shaderLoadDef.program, shaderLoadDef.programSize * sizeof(uint32_t)); + pass.m_vertex_shader_info = pass.m_vertex_shader_info_unq.get(); + } - arrayCount = static_cast(constantSource->arrayCount); - } + if (!pass.m_vertex_shader_info) { + std::ostringstream ss; + ss << "No shader info for shader \"" << vertexShaderName << "\""; + errorMessage = ss.str(); + return false; + } - if (elementOffset >= std::max(arrayCount, 1u)) - return false; + InitializeArgumentState(*pass.m_vertex_shader_info, pass.m_vertex_shader_argument_handled_offset, pass.m_handled_vertex_shader_arguments); - pass.m_arguments.emplace_back(argument); - return true; - } + return true; + } + + bool AcceptPixelShader(const std::string &pixelShaderName, std::string &errorMessage) override { + auto *pixelShaderDependency = m_manager->LoadDependency(ASSET_TYPE_PIXELSHADER, pixelShaderName); + if (pixelShaderDependency == nullptr) { + std::ostringstream ss; + ss << "Failed to load specified shader \"" << pixelShaderName << "\""; + errorMessage = ss.str(); + return false; + } - bool AutoCreateVertexShaderArguments(std::string& errorMessage) - { - assert(!m_passes.empty()); - const auto& pass = m_passes.at(m_passes.size() - 1); - - for (auto i = 0u; i < pass.m_vertex_shader_argument_handled_offset.size(); i++) - { - const auto& argument = pass.m_vertex_shader_info->m_constants[i]; - const auto argumentHandledIndex = pass.m_vertex_shader_argument_handled_offset[i]; - const auto argumentRegistersPerElement = argument.m_type_elements > 1u ? RegisterCountPerElement(argument) : argument.m_register_count; - - auto elementIndex = 0u; - for (auto registerIndex = 0u; registerIndex < argument.m_register_count; registerIndex += argumentRegistersPerElement) - { - if (!pass.m_handled_vertex_shader_arguments[argumentHandledIndex + elementIndex]) - { - if (!AutoCreateShaderArgument(techset::ShaderSelector::VERTEX_SHADER, argument, elementIndex, registerIndex)) - { - std::ostringstream ss; - ss << "Unassigned vertex shader \"" << pass.m_vertex_shader->m_name << "\" arg: " << argument.m_name; - - if (argument.m_type_elements > 1) - ss << '[' << elementIndex << ']'; - - errorMessage = ss.str(); - return false; - } - } - - elementIndex++; - } - } - - return true; - } + assert(!m_passes.empty()); + auto &pass = m_passes.at(m_passes.size() - 1); + pass.m_pixel_shader = reinterpret_cast *>(pixelShaderDependency); - bool AutoCreatePixelShaderArguments(std::string& errorMessage) - { - assert(!m_passes.empty()); - const auto& pass = m_passes.at(m_passes.size() - 1); - - for (auto i = 0u; i < pass.m_pixel_shader_argument_handled_offset.size(); i++) - { - const auto& argument = pass.m_pixel_shader_info->m_constants[i]; - const auto argumentHandledIndex = pass.m_pixel_shader_argument_handled_offset[i]; - const auto argumentRegistersPerElement = argument.m_type_elements > 1u ? RegisterCountPerElement(argument) : argument.m_register_count; - - auto elementIndex = 0u; - for (auto registerIndex = 0u; registerIndex < argument.m_register_count; registerIndex += argumentRegistersPerElement) - { - if (!pass.m_handled_pixel_shader_arguments[argumentHandledIndex + elementIndex]) - { - if (!AutoCreateShaderArgument(techset::ShaderSelector::PIXEL_SHADER, argument, elementIndex, registerIndex)) - { - std::ostringstream ss; - ss << "Unassigned pixel shader \"" << pass.m_pixel_shader->m_name << "\" arg: " << argument.m_name; - - if (argument.m_type_elements > 1) - ss << '[' << elementIndex << ']'; - - errorMessage = ss.str(); - return false; - } - } - - elementIndex++; - } - } - - return true; - } + if (pass.m_pixel_shader->Asset()->name && pass.m_pixel_shader->Asset()->name[0] == ',') { + pass.m_pixel_shader_info = m_shader_info_cache->LoadShaderInfoFromDisk(m_search_path, AssetLoaderPixelShader::GetFileNameForAsset(pixelShaderName)); + } else { + const auto &shaderLoadDef = pass.m_pixel_shader->Asset()->prog.loadDef; + pass.m_pixel_shader_info_unq = d3d9::ShaderAnalyser::GetShaderInfo(shaderLoadDef.program, shaderLoadDef.programSize * sizeof(uint32_t)); + pass.m_pixel_shader_info = pass.m_pixel_shader_info_unq.get(); + } - void AllocateVertexDecl() - { - assert(!m_passes.empty()); - auto& pass = m_passes.at(m_passes.size() - 1); + if (!pass.m_pixel_shader_info) { + std::ostringstream ss; + ss << "No shader info for shader \"" << pixelShaderName << "\""; + errorMessage = ss.str(); + return false; + } - std::sort(std::begin(pass.m_vertex_decl.routing.data), std::begin(pass.m_vertex_decl.routing.data) + pass.m_vertex_decl.streamCount, - [](const MaterialStreamRouting& r1, const MaterialStreamRouting& r2) - { - return r1.source < r2.source; - }); + InitializeArgumentState(*pass.m_pixel_shader_info, pass.m_pixel_shader_argument_handled_offset, pass.m_handled_pixel_shader_arguments); - std::ostringstream ss; - for (auto i = 0u; i < pass.m_vertex_decl.streamCount; i++) - { - const auto& stream = pass.m_vertex_decl.routing.data[i]; - assert(stream.source < std::extent_v); - assert(stream.dest < std::extent_v); + return true; + } - ss << materialStreamSourceAbbreviation[stream.source] << materialStreamDestinationAbbreviation[stream.dest]; - } + static const CodeConstantSource *FindCodeConstantSource(const std::vector &accessors, const CodeConstantSource *sourceTable) { + const CodeConstantSource *foundSource = nullptr; + const CodeConstantSource *currentTable = sourceTable; + for (const auto &accessor : accessors) { + if (currentTable == nullptr) + return nullptr; - pass.m_vertex_decl_asset = reinterpret_cast*>(m_manager->LoadDependency(ASSET_TYPE_VERTEXDECL, ss.str())); - } + while (true) { + if (currentTable->name == nullptr) + return nullptr; - bool AcceptEndPass(std::string& errorMessage) override - { - assert(!m_passes.empty()); - auto& pass = m_passes.at(m_passes.size() - 1); + if (accessor == currentTable->name) + break; - if (!AutoCreateVertexShaderArguments(errorMessage) || !AutoCreatePixelShaderArguments(errorMessage)) - return false; + currentTable++; + } - // Sort args by their update frequency - std::sort(pass.m_arguments.begin(), pass.m_arguments.end(), [](const PassShaderArgument& arg1, const PassShaderArgument& arg2) - { - if (arg1.m_update_frequency != arg2.m_update_frequency) - return arg1.m_update_frequency < arg2.m_update_frequency; + foundSource = currentTable; + currentTable = currentTable->subtable; + } - if (arg1.m_arg.type != arg2.m_arg.type) - return arg1.m_arg.type < arg2.m_arg.type; + return foundSource; + } - if (arg1.m_arg.type == MTL_ARG_MATERIAL_VERTEX_CONST || arg1.m_arg.type == MTL_ARG_MATERIAL_PIXEL_CONST || arg1.m_arg.type == MTL_ARG_MATERIAL_PIXEL_SAMPLER) - return arg1.m_arg.u.codeSampler < arg2.m_arg.u.codeSampler; + static const CodeSamplerSource *FindCodeSamplerSource(const std::vector &accessors, const CodeSamplerSource *sourceTable) { + const CodeSamplerSource *foundSource = nullptr; + const CodeSamplerSource *currentTable = sourceTable; + for (const auto &accessor : accessors) { + if (currentTable == nullptr) + return nullptr; - return arg1.m_arg.dest < arg2.m_arg.dest; - }); + while (true) { + if (currentTable->name == nullptr) + return nullptr; - AllocateVertexDecl(); + if (accessor == currentTable->name) + break; - return true; - } + currentTable++; + } - bool AcceptStateMap(const std::string& stateMapName, std::string& errorMessage) override - { - const auto* stateMap = AssetLoaderTechniqueSet::LoadStateMapDefinition(stateMapName, m_search_path, m_state_map_cache); + foundSource = currentTable; + currentTable = currentTable->subtable; + } - if (!stateMap) - { - std::ostringstream ss; - ss << "Failed to load specified state map \"" << stateMapName << "\""; - errorMessage = ss.str(); - return false; - } + return foundSource; + } - m_state_map_cache->SetTechniqueUsesStateMap(m_technique_name, stateMap); - return true; - } + bool FindShaderArgument(const d3d9::ShaderInfo &shaderInfo, const techset::ShaderArgument &argument, size_t &constantIndex, size_t ®isterOffset, + std::string &errorMessage) const { + const auto matchingShaderConstant = std::find_if(shaderInfo.m_constants.begin(), shaderInfo.m_constants.end(), + [argument](const d3d9::ShaderConstant &constant) { return constant.m_name == argument.m_argument_name; }); - static void InitializeArgumentState(const d3d9::ShaderInfo& shaderInfo, std::vector& argumentHandledOffsetVector, std::vector& argumentHandledVector) - { - auto vertexShaderArgumentSlotCount = 0u; - auto argIndex = 0u; - argumentHandledOffsetVector.resize(shaderInfo.m_constants.size()); - for (const auto& arg : shaderInfo.m_constants) - { - argumentHandledOffsetVector[argIndex++] = vertexShaderArgumentSlotCount; - - if (arg.m_type_elements > 1) - vertexShaderArgumentSlotCount += arg.m_register_count / RegisterCountPerElement(arg); - else - vertexShaderArgumentSlotCount++; - } - argumentHandledVector.resize(vertexShaderArgumentSlotCount); - } + if (matchingShaderConstant == shaderInfo.m_constants.end()) { + errorMessage = "Could not find argument in shader"; + return false; + } - bool AcceptVertexShader(const std::string& vertexShaderName, std::string& errorMessage) override - { - auto* vertexShaderDependency = m_manager->LoadDependency(ASSET_TYPE_VERTEXSHADER, vertexShaderName); - if (vertexShaderDependency == nullptr) - { - std::ostringstream ss; - ss << "Failed to load specified shader \"" << vertexShaderName << "\""; - errorMessage = ss.str(); - return false; - } - - assert(!m_passes.empty()); - auto& pass = m_passes.at(m_passes.size() - 1); - pass.m_vertex_shader = reinterpret_cast*>(vertexShaderDependency); - - if (pass.m_vertex_shader->Asset()->name && pass.m_vertex_shader->Asset()->name[0] == ',') - { - pass.m_vertex_shader_info = m_shader_info_cache->LoadShaderInfoFromDisk(m_search_path, AssetLoaderVertexShader::GetFileNameForAsset(vertexShaderName)); - } - else - { - const auto& shaderLoadDef = pass.m_vertex_shader->Asset()->prog.loadDef; - pass.m_vertex_shader_info_unq = d3d9::ShaderAnalyser::GetShaderInfo(shaderLoadDef.program, shaderLoadDef.programSize * sizeof(uint32_t)); - pass.m_vertex_shader_info = pass.m_vertex_shader_info_unq.get(); - } - - if (!pass.m_vertex_shader_info) - { - std::ostringstream ss; - ss << "No shader info for shader \"" << vertexShaderName << "\""; - errorMessage = ss.str(); - return false; - } - - InitializeArgumentState(*pass.m_vertex_shader_info, pass.m_vertex_shader_argument_handled_offset, pass.m_handled_vertex_shader_arguments); - - return true; - } + if (argument.m_argument_index_specified) { + if (matchingShaderConstant->m_type_elements <= 1) { + errorMessage = "Argument does not have more than one element"; + return false; + } + + const auto registersPerElement = RegisterCountPerElement(*matchingShaderConstant); + if (argument.m_argument_index >= matchingShaderConstant->m_register_count / registersPerElement) { + errorMessage = "Argument index out of bounds"; + return false; + } + + registerOffset = argument.m_argument_index * registersPerElement; + } else if (matchingShaderConstant->m_type_elements > 1) { + errorMessage = "Argument has more than one element and needs to be accessed with an index"; + return false; + } else { + registerOffset = 0u; + } - bool AcceptPixelShader(const std::string& pixelShaderName, std::string& errorMessage) override - { - auto* pixelShaderDependency = m_manager->LoadDependency(ASSET_TYPE_PIXELSHADER, pixelShaderName); - if (pixelShaderDependency == nullptr) - { - std::ostringstream ss; - ss << "Failed to load specified shader \"" << pixelShaderName << "\""; - errorMessage = ss.str(); - return false; - } - - assert(!m_passes.empty()); - auto& pass = m_passes.at(m_passes.size() - 1); - pass.m_pixel_shader = reinterpret_cast*>(pixelShaderDependency); - - if (pass.m_pixel_shader->Asset()->name && pass.m_pixel_shader->Asset()->name[0] == ',') - { - pass.m_pixel_shader_info = m_shader_info_cache->LoadShaderInfoFromDisk(m_search_path, AssetLoaderPixelShader::GetFileNameForAsset(pixelShaderName)); - } - else - { - const auto& shaderLoadDef = pass.m_pixel_shader->Asset()->prog.loadDef; - pass.m_pixel_shader_info_unq = d3d9::ShaderAnalyser::GetShaderInfo(shaderLoadDef.program, shaderLoadDef.programSize * sizeof(uint32_t)); - pass.m_pixel_shader_info = pass.m_pixel_shader_info_unq.get(); - } - - if (!pass.m_pixel_shader_info) - { - std::ostringstream ss; - ss << "No shader info for shader \"" << pixelShaderName << "\""; - errorMessage = ss.str(); - return false; - } - - InitializeArgumentState(*pass.m_pixel_shader_info, pass.m_pixel_shader_argument_handled_offset, pass.m_handled_pixel_shader_arguments); - - return true; - } + constantIndex = static_cast(matchingShaderConstant - shaderInfo.m_constants.begin()); + return true; + } + + static bool SetArgumentCodeConst(MaterialShaderArgument &argument, const techset::ShaderArgumentCodeSource &source, + const d3d9::ShaderConstant &shaderConstant, const unsigned sourceIndex, const unsigned arrayCount, + std::string &errorMessage) { + if (arrayCount > 0u) { + if (!source.m_index_accessor_specified) { + errorMessage = "Code constant must have array index specified"; + return false; + } + + if (source.m_index_accessor >= arrayCount) { + errorMessage = "Code constant array index out of bounds"; + return false; + } + + argument.u.codeConst.index = static_cast(sourceIndex + source.m_index_accessor); + } else if (source.m_index_accessor_specified) { + errorMessage = "Code constant cannot have array index specified"; + return false; + } else { + argument.u.codeConst.index = static_cast(sourceIndex); + } + argument.u.codeConst.firstRow = 0u; + argument.u.codeConst.rowCount = static_cast(shaderConstant.m_type_rows); - static const CodeConstantSource* FindCodeConstantSource(const std::vector& accessors, const CodeConstantSource* sourceTable) - { - const CodeConstantSource* foundSource = nullptr; - const CodeConstantSource* currentTable = sourceTable; - for (const auto& accessor : accessors) - { - if (currentTable == nullptr) - return nullptr; + return true; + } + + static bool SetArgumentCodeSampler(MaterialShaderArgument &argument, const techset::ShaderArgumentCodeSource &source, + const d3d9::ShaderConstant &shaderConstant, const unsigned sourceIndex, const unsigned arrayCount, + std::string &errorMessage) { + if (arrayCount > 0u) { + if (!source.m_index_accessor_specified) { + errorMessage = "Code constant must have array index specified"; + return false; + } + + if (source.m_index_accessor >= arrayCount) { + errorMessage = "Code constant array index out of bounds"; + return false; + } + + argument.u.codeSampler = sourceIndex + source.m_index_accessor; + } else if (source.m_index_accessor_specified) { + errorMessage = "Code constant cannot have array index specified"; + return false; + } else { + argument.u.codeSampler = sourceIndex; + } - while (true) - { - if (currentTable->name == nullptr) - return nullptr; + return true; + } - if (accessor == currentTable->name) - break; + bool AcceptVertexShaderConstantArgument(const techset::ShaderArgument &shaderArgument, const techset::ShaderArgumentCodeSource &source, + std::string &errorMessage) { + assert(!m_passes.empty()); + auto &pass = m_passes.at(m_passes.size() - 1); - currentTable++; - } + if (!pass.m_vertex_shader_info) { + errorMessage = "Shader not specified"; + return false; + } - foundSource = currentTable; - currentTable = currentTable->subtable; - } + size_t shaderConstantIndex = 0u; + size_t registerOffset = 0u; + if (!FindShaderArgument(*pass.m_vertex_shader_info, shaderArgument, shaderConstantIndex, registerOffset, errorMessage)) + return false; + + const auto elementOffset = shaderArgument.m_argument_index_specified ? shaderArgument.m_argument_index : 0u; + const auto &shaderConstant = pass.m_vertex_shader_info->m_constants[shaderConstantIndex]; + const auto argumentIsSampler = IsSamplerArgument(shaderConstant); + if (argumentIsSampler) { + errorMessage = "Vertex shader argument expected sampler but got constant"; + return false; + } - return foundSource; - } + MaterialShaderArgument argument{}; + argument.type = MTL_ARG_CODE_VERTEX_CONST; + argument.dest = static_cast(shaderConstant.m_register_index + registerOffset); - static const CodeSamplerSource* FindCodeSamplerSource(const std::vector& accessors, const CodeSamplerSource* sourceTable) - { - const CodeSamplerSource* foundSource = nullptr; - const CodeSamplerSource* currentTable = sourceTable; - for (const auto& accessor : accessors) - { - if (currentTable == nullptr) - return nullptr; + const CodeConstantSource *constantSource = FindCodeConstantSource(source.m_accessors, s_codeConsts); + if (!constantSource) + constantSource = FindCodeConstantSource(source.m_accessors, s_defaultCodeConsts); - while (true) - { - if (currentTable->name == nullptr) - return nullptr; + if (!constantSource) { + errorMessage = "Unknown code constant"; + return false; + } - if (accessor == currentTable->name) - break; + if (!SetArgumentCodeConst(argument, source, shaderConstant, constantSource->source, constantSource->arrayCount, errorMessage)) + return false; - currentTable++; - } + pass.m_arguments.emplace_back(argument); + pass.m_handled_vertex_shader_arguments[pass.m_vertex_shader_argument_handled_offset[shaderConstantIndex] + elementOffset] = true; - foundSource = currentTable; - currentTable = currentTable->subtable; - } + return true; + } - return foundSource; - } + bool AcceptPixelShaderCodeArgument(const techset::ShaderArgument &shaderArgument, const techset::ShaderArgumentCodeSource &source, std::string &errorMessage, + const bool isSampler) { + assert(!m_passes.empty()); + auto &pass = m_passes.at(m_passes.size() - 1); - bool FindShaderArgument(const d3d9::ShaderInfo& shaderInfo, const techset::ShaderArgument& argument, size_t& constantIndex, size_t& registerOffset, std::string& errorMessage) const - { - const auto matchingShaderConstant = std::find_if(shaderInfo.m_constants.begin(), shaderInfo.m_constants.end(), [argument](const d3d9::ShaderConstant& constant) - { - return constant.m_name == argument.m_argument_name; - }); - - if (matchingShaderConstant == shaderInfo.m_constants.end()) - { - errorMessage = "Could not find argument in shader"; - return false; - } - - if (argument.m_argument_index_specified) - { - if (matchingShaderConstant->m_type_elements <= 1) - { - errorMessage = "Argument does not have more than one element"; - return false; - } - - const auto registersPerElement = RegisterCountPerElement(*matchingShaderConstant); - if (argument.m_argument_index >= matchingShaderConstant->m_register_count / registersPerElement) - { - errorMessage = "Argument index out of bounds"; - return false; - } - - registerOffset = argument.m_argument_index * registersPerElement; - } - else if (matchingShaderConstant->m_type_elements > 1) - { - errorMessage = "Argument has more than one element and needs to be accessed with an index"; - return false; - } - else - { - registerOffset = 0u; - } - - constantIndex = static_cast(matchingShaderConstant - shaderInfo.m_constants.begin()); - return true; - } + if (!pass.m_pixel_shader_info) { + errorMessage = "Shader not specified"; + return false; + } - static bool SetArgumentCodeConst(MaterialShaderArgument& argument, const techset::ShaderArgumentCodeSource& source, const d3d9::ShaderConstant& shaderConstant, const unsigned sourceIndex, - const unsigned arrayCount, std::string& errorMessage) - { - if (arrayCount > 0u) - { - if (!source.m_index_accessor_specified) - { - errorMessage = "Code constant must have array index specified"; - return false; - } - - if (source.m_index_accessor >= arrayCount) - { - errorMessage = "Code constant array index out of bounds"; - return false; - } - - argument.u.codeConst.index = static_cast(sourceIndex + source.m_index_accessor); - } - else if (source.m_index_accessor_specified) - { - errorMessage = "Code constant cannot have array index specified"; - return false; - } - else - { - argument.u.codeConst.index = static_cast(sourceIndex); - } - argument.u.codeConst.firstRow = 0u; - argument.u.codeConst.rowCount = static_cast(shaderConstant.m_type_rows); - - return true; - } + size_t shaderConstantIndex = 0u; + size_t registerOffset = 0u; + if (!FindShaderArgument(*pass.m_pixel_shader_info, shaderArgument, shaderConstantIndex, registerOffset, errorMessage)) + return false; + + const auto elementOffset = shaderArgument.m_argument_index_specified ? shaderArgument.m_argument_index : 0u; + const auto &shaderConstant = pass.m_pixel_shader_info->m_constants[shaderConstantIndex]; + const auto argumentIsSampler = IsSamplerArgument(shaderConstant); + if (argumentIsSampler && !isSampler) { + errorMessage = "Pixel shader argument expects sampler but got constant"; + return false; + } else if (!argumentIsSampler && isSampler) { + errorMessage = "Pixel shader argument expects constant but got sampler"; + return false; + } - static bool SetArgumentCodeSampler(MaterialShaderArgument& argument, const techset::ShaderArgumentCodeSource& source, const d3d9::ShaderConstant& shaderConstant, const unsigned sourceIndex, - const unsigned arrayCount, std::string& errorMessage) - { - if (arrayCount > 0u) - { - if (!source.m_index_accessor_specified) - { - errorMessage = "Code constant must have array index specified"; - return false; - } - - if (source.m_index_accessor >= arrayCount) - { - errorMessage = "Code constant array index out of bounds"; - return false; - } - - argument.u.codeSampler = sourceIndex + source.m_index_accessor; - } - else if (source.m_index_accessor_specified) - { - errorMessage = "Code constant cannot have array index specified"; - return false; - } - else - { - argument.u.codeSampler = sourceIndex; - } - - return true; - } + MaterialShaderArgument argument{}; + argument.type = isSampler ? MTL_ARG_CODE_PIXEL_SAMPLER : MTL_ARG_CODE_PIXEL_CONST; + argument.dest = static_cast(shaderConstant.m_register_index + registerOffset); + + unsigned sourceIndex, arrayCount; + if (isSampler) { + const CodeSamplerSource *samplerSource = FindCodeSamplerSource(source.m_accessors, s_codeSamplers); + if (!samplerSource) + samplerSource = FindCodeSamplerSource(source.m_accessors, s_defaultCodeSamplers); + + if (!samplerSource) { + errorMessage = "Unknown code sampler"; + return false; + } + + sourceIndex = static_cast(samplerSource->source); + arrayCount = static_cast(samplerSource->arrayCount); + + if (!SetArgumentCodeSampler(argument, source, shaderConstant, sourceIndex, arrayCount, errorMessage)) + return false; + } else { + const CodeConstantSource *constantSource = FindCodeConstantSource(source.m_accessors, s_codeConsts); + if (!constantSource) + constantSource = FindCodeConstantSource(source.m_accessors, s_defaultCodeConsts); + + if (!constantSource) { + errorMessage = "Unknown code constant"; + return false; + } + + sourceIndex = static_cast(constantSource->source); + arrayCount = static_cast(constantSource->arrayCount); + + if (!SetArgumentCodeConst(argument, source, shaderConstant, sourceIndex, arrayCount, errorMessage)) + return false; + } - bool AcceptVertexShaderConstantArgument(const techset::ShaderArgument& shaderArgument, const techset::ShaderArgumentCodeSource& source, std::string& errorMessage) - { - assert(!m_passes.empty()); - auto& pass = m_passes.at(m_passes.size() - 1); - - if (!pass.m_vertex_shader_info) - { - errorMessage = "Shader not specified"; - return false; - } - - size_t shaderConstantIndex = 0u; - size_t registerOffset = 0u; - if (!FindShaderArgument(*pass.m_vertex_shader_info, shaderArgument, shaderConstantIndex, registerOffset, errorMessage)) - return false; - - const auto elementOffset = shaderArgument.m_argument_index_specified ? shaderArgument.m_argument_index : 0u; - const auto& shaderConstant = pass.m_vertex_shader_info->m_constants[shaderConstantIndex]; - const auto argumentIsSampler = IsSamplerArgument(shaderConstant); - if (argumentIsSampler) - { - errorMessage = "Vertex shader argument expected sampler but got constant"; - return false; - } - - MaterialShaderArgument argument{}; - argument.type = MTL_ARG_CODE_VERTEX_CONST; - argument.dest = static_cast(shaderConstant.m_register_index + registerOffset); - - const CodeConstantSource* constantSource = FindCodeConstantSource(source.m_accessors, s_codeConsts); - if (!constantSource) - constantSource = FindCodeConstantSource(source.m_accessors, s_defaultCodeConsts); - - if (!constantSource) - { - errorMessage = "Unknown code constant"; - return false; - } - - if (!SetArgumentCodeConst(argument, source, shaderConstant, constantSource->source, constantSource->arrayCount, errorMessage)) - return false; - - pass.m_arguments.emplace_back(argument); - pass.m_handled_vertex_shader_arguments[pass.m_vertex_shader_argument_handled_offset[shaderConstantIndex] + elementOffset] = true; - - return true; - } + pass.m_arguments.emplace_back(argument); + pass.m_handled_pixel_shader_arguments[pass.m_pixel_shader_argument_handled_offset[shaderConstantIndex] + elementOffset] = true; - bool AcceptPixelShaderCodeArgument(const techset::ShaderArgument& shaderArgument, const techset::ShaderArgumentCodeSource& source, std::string& errorMessage, const bool isSampler) - { - assert(!m_passes.empty()); - auto& pass = m_passes.at(m_passes.size() - 1); - - if (!pass.m_pixel_shader_info) - { - errorMessage = "Shader not specified"; - return false; - } - - size_t shaderConstantIndex = 0u; - size_t registerOffset = 0u; - if (!FindShaderArgument(*pass.m_pixel_shader_info, shaderArgument, shaderConstantIndex, registerOffset, errorMessage)) - return false; - - const auto elementOffset = shaderArgument.m_argument_index_specified ? shaderArgument.m_argument_index : 0u; - const auto& shaderConstant = pass.m_pixel_shader_info->m_constants[shaderConstantIndex]; - const auto argumentIsSampler = IsSamplerArgument(shaderConstant); - if (argumentIsSampler && !isSampler) - { - errorMessage = "Pixel shader argument expects sampler but got constant"; - return false; - } - else if (!argumentIsSampler && isSampler) - { - errorMessage = "Pixel shader argument expects constant but got sampler"; - return false; - } - - MaterialShaderArgument argument{}; - argument.type = isSampler ? MTL_ARG_CODE_PIXEL_SAMPLER : MTL_ARG_CODE_PIXEL_CONST; - argument.dest = static_cast(shaderConstant.m_register_index + registerOffset); - - unsigned sourceIndex, arrayCount; - if (isSampler) - { - const CodeSamplerSource* samplerSource = FindCodeSamplerSource(source.m_accessors, s_codeSamplers); - if (!samplerSource) - samplerSource = FindCodeSamplerSource(source.m_accessors, s_defaultCodeSamplers); - - if (!samplerSource) - { - errorMessage = "Unknown code sampler"; - return false; - } - - sourceIndex = static_cast(samplerSource->source); - arrayCount = static_cast(samplerSource->arrayCount); - - if (!SetArgumentCodeSampler(argument, source, shaderConstant, sourceIndex, arrayCount, errorMessage)) - return false; - } - else - { - const CodeConstantSource* constantSource = FindCodeConstantSource(source.m_accessors, s_codeConsts); - if (!constantSource) - constantSource = FindCodeConstantSource(source.m_accessors, s_defaultCodeConsts); - - if (!constantSource) - { - errorMessage = "Unknown code constant"; - return false; - } - - sourceIndex = static_cast(constantSource->source); - arrayCount = static_cast(constantSource->arrayCount); - - if (!SetArgumentCodeConst(argument, source, shaderConstant, sourceIndex, arrayCount, errorMessage)) - return false; - } - - - pass.m_arguments.emplace_back(argument); - pass.m_handled_pixel_shader_arguments[pass.m_pixel_shader_argument_handled_offset[shaderConstantIndex] + elementOffset] = true; - - return true; - } + return true; + } + + bool AcceptShaderConstantArgument(const techset::ShaderSelector shader, const techset::ShaderArgument shaderArgument, + const techset::ShaderArgumentCodeSource source, std::string &errorMessage) override { + if (shader == techset::ShaderSelector::VERTEX_SHADER) + return AcceptVertexShaderConstantArgument(shaderArgument, source, errorMessage); + + assert(shader == techset::ShaderSelector::PIXEL_SHADER); + return AcceptPixelShaderCodeArgument(shaderArgument, source, errorMessage, false); + } + + bool AcceptShaderSamplerArgument(const techset::ShaderSelector shader, const techset::ShaderArgument shaderArgument, + const techset::ShaderArgumentCodeSource source, std::string &errorMessage) override { + if (shader == techset::ShaderSelector::VERTEX_SHADER) { + errorMessage = "Vertex sampler are unsupported"; + return false; + } - bool AcceptShaderConstantArgument(const techset::ShaderSelector shader, const techset::ShaderArgument shaderArgument, const techset::ShaderArgumentCodeSource source, - std::string& errorMessage) override - { - if (shader == techset::ShaderSelector::VERTEX_SHADER) - return AcceptVertexShaderConstantArgument(shaderArgument, source, errorMessage); + assert(shader == techset::ShaderSelector::PIXEL_SHADER); + return AcceptPixelShaderCodeArgument(shaderArgument, source, errorMessage, true); + } + + bool AcceptShaderLiteralArgument(const techset::ShaderSelector shader, techset::ShaderArgument shaderArgument, techset::ShaderArgumentLiteralSource source, + std::string &errorMessage) override { + assert(!m_passes.empty()); + auto &pass = m_passes.at(m_passes.size() - 1); + + MaterialShaderArgument argument{}; + const d3d9::ShaderInfo *shaderInfo; + + if (shader == techset::ShaderSelector::VERTEX_SHADER) { + argument.type = MTL_ARG_LITERAL_VERTEX_CONST; + shaderInfo = pass.m_vertex_shader_info; + } else { + assert(shader == techset::ShaderSelector::PIXEL_SHADER); + argument.type = MTL_ARG_LITERAL_PIXEL_CONST; + shaderInfo = pass.m_pixel_shader_info; + } - assert(shader == techset::ShaderSelector::PIXEL_SHADER); - return AcceptPixelShaderCodeArgument(shaderArgument, source, errorMessage, false); - } + if (!shaderInfo) { + errorMessage = "Shader not specified"; + return false; + } - bool AcceptShaderSamplerArgument(const techset::ShaderSelector shader, const techset::ShaderArgument shaderArgument, const techset::ShaderArgumentCodeSource source, - std::string& errorMessage) override - { - if (shader == techset::ShaderSelector::VERTEX_SHADER) - { - errorMessage = "Vertex sampler are unsupported"; - return false; - } - - assert(shader == techset::ShaderSelector::PIXEL_SHADER); - return AcceptPixelShaderCodeArgument(shaderArgument, source, errorMessage, true); - } + size_t shaderConstantIndex = 0u; + size_t registerOffset = 0u; + if (!FindShaderArgument(*shaderInfo, shaderArgument, shaderConstantIndex, registerOffset, errorMessage)) + return false; + + const auto elementOffset = shaderArgument.m_argument_index_specified ? shaderArgument.m_argument_index : 0u; + const auto &shaderConstant = shaderInfo->m_constants[shaderConstantIndex]; + const auto argumentIsSampler = IsSamplerArgument(shaderConstant); + if (argumentIsSampler) { + if (shader == techset::ShaderSelector::VERTEX_SHADER) + errorMessage = "Vertex shader argument expects sampler but got constant"; + else + errorMessage = "Pixel shader argument expects sampler but got constant"; + + return false; + } - bool AcceptShaderLiteralArgument(const techset::ShaderSelector shader, techset::ShaderArgument shaderArgument, techset::ShaderArgumentLiteralSource source, std::string& errorMessage) override - { - assert(!m_passes.empty()); - auto& pass = m_passes.at(m_passes.size() - 1); - - MaterialShaderArgument argument{}; - const d3d9::ShaderInfo* shaderInfo; - - if (shader == techset::ShaderSelector::VERTEX_SHADER) - { - argument.type = MTL_ARG_LITERAL_VERTEX_CONST; - shaderInfo = pass.m_vertex_shader_info; - } - else - { - assert(shader == techset::ShaderSelector::PIXEL_SHADER); - argument.type = MTL_ARG_LITERAL_PIXEL_CONST; - shaderInfo = pass.m_pixel_shader_info; - } - - if (!shaderInfo) - { - errorMessage = "Shader not specified"; - return false; - } - - size_t shaderConstantIndex = 0u; - size_t registerOffset = 0u; - if (!FindShaderArgument(*shaderInfo, shaderArgument, shaderConstantIndex, registerOffset, errorMessage)) - return false; - - const auto elementOffset = shaderArgument.m_argument_index_specified ? shaderArgument.m_argument_index : 0u; - const auto& shaderConstant = shaderInfo->m_constants[shaderConstantIndex]; - const auto argumentIsSampler = IsSamplerArgument(shaderConstant); - if (argumentIsSampler) - { - if (shader == techset::ShaderSelector::VERTEX_SHADER) - errorMessage = "Vertex shader argument expects sampler but got constant"; - else - errorMessage = "Pixel shader argument expects sampler but got constant"; - - return false; - } - - argument.dest = static_cast(shaderConstant.m_register_index + registerOffset); - argument.u.literalConst = m_zone_state->GetAllocatedLiteral(m_memory, source); - pass.m_arguments.emplace_back(argument); - - if (shader == techset::ShaderSelector::VERTEX_SHADER) - pass.m_handled_vertex_shader_arguments[pass.m_vertex_shader_argument_handled_offset[shaderConstantIndex] + elementOffset] = true; - else - pass.m_handled_pixel_shader_arguments[pass.m_pixel_shader_argument_handled_offset[shaderConstantIndex] + elementOffset] = true; - - return true; - } + argument.dest = static_cast(shaderConstant.m_register_index + registerOffset); + argument.u.literalConst = m_zone_state->GetAllocatedLiteral(m_memory, source); + pass.m_arguments.emplace_back(argument); - bool AcceptShaderMaterialArgument(const techset::ShaderSelector shader, techset::ShaderArgument shaderArgument, const techset::ShaderArgumentMaterialSource source, - std::string& errorMessage) override - { - assert(!m_passes.empty()); - auto& pass = m_passes.at(m_passes.size() - 1); - - MaterialShaderArgument argument{}; - const d3d9::ShaderInfo* shaderInfo; - - if (shader == techset::ShaderSelector::VERTEX_SHADER) - { - shaderInfo = pass.m_vertex_shader_info; - } - else - { - assert(shader == techset::ShaderSelector::PIXEL_SHADER); - shaderInfo = pass.m_pixel_shader_info; - } - - if (!shaderInfo) - { - errorMessage = "Shader not specified"; - return false; - } - - size_t shaderConstantIndex = 0u; - size_t registerOffset = 0u; - if (!FindShaderArgument(*shaderInfo, shaderArgument, shaderConstantIndex, registerOffset, errorMessage)) - return false; - - const auto elementOffset = shaderArgument.m_argument_index_specified ? shaderArgument.m_argument_index : 0u; - const auto& shaderConstant = shaderInfo->m_constants[shaderConstantIndex]; - const auto argumentIsSampler = IsSamplerArgument(shaderConstant); - if (shader == techset::ShaderSelector::VERTEX_SHADER) - { - if (argumentIsSampler) - { - errorMessage = "Vertex sampler are unsupported"; - return false; - } - argument.type = MTL_ARG_MATERIAL_VERTEX_CONST; - } - else - { - assert(shader == techset::ShaderSelector::PIXEL_SHADER); - argument.type = !argumentIsSampler ? MTL_ARG_MATERIAL_PIXEL_CONST : MTL_ARG_MATERIAL_PIXEL_SAMPLER; - } - - if (source.m_is_hash) - argument.u.nameHash = static_cast(source.m_hash); - else - argument.u.nameHash = Common::R_HashString(source.m_name.c_str(), 0u); - - argument.dest = static_cast(shaderConstant.m_register_index + registerOffset); - pass.m_arguments.emplace_back(argument); - - if (shader == techset::ShaderSelector::VERTEX_SHADER) - pass.m_handled_vertex_shader_arguments[pass.m_vertex_shader_argument_handled_offset[shaderConstantIndex] + elementOffset] = true; - else - pass.m_handled_pixel_shader_arguments[pass.m_pixel_shader_argument_handled_offset[shaderConstantIndex] + elementOffset] = true; - - return true; - } + if (shader == techset::ShaderSelector::VERTEX_SHADER) + pass.m_handled_vertex_shader_arguments[pass.m_vertex_shader_argument_handled_offset[shaderConstantIndex] + elementOffset] = true; + else + pass.m_handled_pixel_shader_arguments[pass.m_pixel_shader_argument_handled_offset[shaderConstantIndex] + elementOffset] = true; - bool AcceptVertexStreamRouting(const std::string& destination, const std::string& source, std::string& errorMessage) override - { - assert(!m_passes.empty()); - auto& pass = m_passes.at(m_passes.size() - 1); - - const auto streamIndex = static_cast(pass.m_vertex_decl.streamCount); - if (pass.m_vertex_decl.streamCount >= std::extent_v) - { - errorMessage = "Too many stream routings"; - return false; - } - - const auto foundDestination = std::find(std::begin(materialStreamDestinationNames), std::end(materialStreamDestinationNames), destination); - if (foundDestination == std::end(materialStreamDestinationNames)) - { - errorMessage = "Unknown stream destination"; - return false; - } - - const auto foundSource = std::find(std::begin(materialStreamSourceNames), std::end(materialStreamSourceNames), source); - if (foundSource == std::end(materialStreamSourceNames)) - { - errorMessage = "Unknown stream source"; - return false; - } - - const auto destinationIndex = static_cast(foundDestination - std::begin(materialStreamDestinationNames)); - const auto sourceIndex = static_cast(foundSource - std::begin(materialStreamSourceNames)); - - pass.m_vertex_decl.routing.data[streamIndex].dest = destinationIndex; - pass.m_vertex_decl.routing.data[streamIndex].source = sourceIndex; - - pass.m_vertex_decl.hasOptionalSource = pass.m_vertex_decl.hasOptionalSource || sourceIndex >= STREAM_SRC_OPTIONAL_BEGIN; - - pass.m_vertex_decl.streamCount++; - return true; - } - }; - - class TechniqueLoader - { - ISearchPath* m_search_path; - MemoryManager* m_memory; - IAssetLoadingManager* m_manager; - TechniqueZoneLoadingState* m_zone_state; - ShaderInfoFromFileSystemCacheState* m_shader_info_cache; - techset::TechniqueStateMapCache* m_state_map_cache; - - static void UpdateTechniqueFlags(MaterialTechnique& technique) - { - // This is stupid but that's what the game does for zprepass for sure - // The other ones might be handled by the game in the same fashion because there is not recognizable pattern that connects the shaders with the same flags - static std::unordered_map flagsByTechniqueName({ - {"zprepass", TECHNIQUE_FLAG_4 | TECHNIQUE_FLAG_200}, - {"build_floatz", TECHNIQUE_FLAG_8}, - {"build_shadowmap_depth", TECHNIQUE_FLAG_10 | TECHNIQUE_FLAG_200}, - {"build_shadowmap_model", TECHNIQUE_FLAG_10 | TECHNIQUE_FLAG_200}, - {"distortion_scale_ua_zfeather", TECHNIQUE_FLAG_100}, - {"distortion_scale_zfeather", TECHNIQUE_FLAG_100}, - {"distortion_scale_zfeather_dtex", TECHNIQUE_FLAG_100}, - {"alternate_scene_overlay", TECHNIQUE_FLAG_200}, - {"blur_apply", TECHNIQUE_FLAG_200}, - {"build_floatz", TECHNIQUE_FLAG_200}, - {"build_floatz_clear", TECHNIQUE_FLAG_200}, - {"build_floatz_dtex", TECHNIQUE_FLAG_200}, - {"build_floatz_ua", TECHNIQUE_FLAG_200}, - {"build_floatz_ua_dtex", TECHNIQUE_FLAG_200}, - {"build_shadowmap_depth_nc", TECHNIQUE_FLAG_200}, - {"build_shadowmap_depth_ua", TECHNIQUE_FLAG_200}, - {"build_shadowmap_model_dtex", TECHNIQUE_FLAG_200}, - {"build_shadowmap_model_nc_dtex", TECHNIQUE_FLAG_200}, - {"build_shadowmap_model_ua", TECHNIQUE_FLAG_200}, - {"cinematic", TECHNIQUE_FLAG_200}, - {"cinematic_3d", TECHNIQUE_FLAG_200}, - {"cinematic_dtex_3d", TECHNIQUE_FLAG_200}, - {"dof_near_coc", TECHNIQUE_FLAG_200}, - {"floatz", TECHNIQUE_FLAG_200}, - {"floatzdisplay", TECHNIQUE_FLAG_200}, - {"particle_blend", TECHNIQUE_FLAG_200}, - {"particle_zdownsample", TECHNIQUE_FLAG_200}, - {"passthru_alpha", TECHNIQUE_FLAG_200}, - {"postfx", TECHNIQUE_FLAG_200}, - {"postfx_mblur", TECHNIQUE_FLAG_200}, - {"processed_floatz", TECHNIQUE_FLAG_200}, - {"ps3_aadownsample", TECHNIQUE_FLAG_200}, - {"shell_shock", TECHNIQUE_FLAG_200}, - {"shell_shock_flashed", TECHNIQUE_FLAG_200}, - {"small_blur", TECHNIQUE_FLAG_200}, - {"stencildisplay", TECHNIQUE_FLAG_200}, - {"stencilshadow", TECHNIQUE_FLAG_200}, - {"wireframe_solid", TECHNIQUE_FLAG_200}, - {"wireframe_solid_atest_dtex", TECHNIQUE_FLAG_200}, - {"wireframe_solid_dtex", TECHNIQUE_FLAG_200}, - {"wireframe_solid_nc", TECHNIQUE_FLAG_200}, - {"wireframe_solid_nc_dtex", TECHNIQUE_FLAG_200}, - {"wireframe_solid_ua", TECHNIQUE_FLAG_200}, - {"wireframe_solid_ua_dtex", TECHNIQUE_FLAG_200} - }); - - const auto flagsForName = flagsByTechniqueName.find(technique.name); - if (flagsForName != flagsByTechniqueName.end()) - { - technique.flags |= flagsForName->second; - } - - for (auto i = 0u; i < technique.passCount; i++) - { - const auto& pass = technique.passArray[i]; - if (pass.vertexDecl && pass.vertexDecl->hasOptionalSource) - { - technique.flags |= TECHNIQUE_FLAG_20; - break; - } - } - } + return true; + } - static void UpdateTechniqueFlagsForArgument(uint16_t& techniqueFlags, const TechniqueCreator::PassShaderArgument& arg) - { - if (arg.m_arg.type == MTL_ARG_CODE_PIXEL_SAMPLER) - { - switch (arg.m_arg.u.codeSampler) - { - case TEXTURE_SRC_CODE_RESOLVED_POST_SUN: - techniqueFlags |= TECHNIQUE_FLAG_1; - break; - case TEXTURE_SRC_CODE_RESOLVED_SCENE: - techniqueFlags |= TECHNIQUE_FLAG_2; - break; - case TEXTURE_SRC_CODE_FLOATZ: - case TEXTURE_SRC_CODE_PROCESSED_FLOATZ: - case TEXTURE_SRC_CODE_RAW_FLOATZ: - if ((techniqueFlags & TECHNIQUE_FLAG_100) == 0) - techniqueFlags |= TECHNIQUE_FLAG_80; - break; - default: - break; - } - } - else if (arg.m_arg.type == MTL_ARG_CODE_VERTEX_CONST || arg.m_arg.type == MTL_ARG_CODE_PIXEL_CONST) - { - switch (arg.m_arg.u.codeConst.index) - { - case CONST_SRC_CODE_LIGHT_SPOTDIR: - case CONST_SRC_CODE_LIGHT_SPOTFACTORS: - techniqueFlags |= TECHNIQUE_FLAG_40; - break; - default: - break; - } - } - } + bool AcceptShaderMaterialArgument(const techset::ShaderSelector shader, techset::ShaderArgument shaderArgument, + const techset::ShaderArgumentMaterialSource source, std::string &errorMessage) override { + assert(!m_passes.empty()); + auto &pass = m_passes.at(m_passes.size() - 1); - void ConvertPass(MaterialTechnique& technique, MaterialPass& out, const TechniqueCreator::Pass& in, std::vector& dependencies) const - { - out.customSamplerFlags = 0u; - out.vertexShader = in.m_vertex_shader->Asset(); - out.pixelShader = in.m_pixel_shader->Asset(); - out.vertexDecl = in.m_vertex_decl_asset->Asset(); - - const auto argDataSize = sizeof(MaterialShaderArgument) * in.m_arguments.size(); - out.args = static_cast(m_memory->Alloc(argDataSize)); - - size_t perObjArgCount = 0u; - size_t perPrimArgCount = 0u; - size_t stableArgCount = 0u; - size_t argIndex = 0u; - for (const auto& arg : in.m_arguments) - { - UpdateTechniqueFlagsForArgument(technique.flags, arg); - switch (arg.m_update_frequency) - { - case MTL_UPDATE_PER_PRIM: - perPrimArgCount++; - break; - case MTL_UPDATE_PER_OBJECT: - perObjArgCount++; - break; - case MTL_UPDATE_RARELY: - stableArgCount++; - break; - case MTL_UPDATE_CUSTOM: - { - assert(arg.m_arg.type == MTL_ARG_CODE_PIXEL_SAMPLER); - if (arg.m_arg.type == MTL_ARG_CODE_PIXEL_SAMPLER) - { - const auto customSampler = std::find(std::begin(g_customSamplerSrc), std::end(g_customSamplerSrc), arg.m_arg.u.codeSampler); - assert(customSampler != std::end(g_customSamplerSrc)); - if (customSampler != std::end(g_customSamplerSrc)) - { - const auto customSamplerIndex = customSampler - std::begin(g_customSamplerSrc); - out.customSamplerFlags |= 1 << customSamplerIndex; - } - } - } - continue; - default: - assert(false); - continue; - } - - out.args[argIndex++] = arg.m_arg; - } - - out.perObjArgCount = static_cast(perObjArgCount); - out.perPrimArgCount = static_cast(perPrimArgCount); - out.stableArgCount = static_cast(stableArgCount); - - if (in.m_vertex_shader) - dependencies.push_back(in.m_vertex_shader); - if (in.m_pixel_shader) - dependencies.push_back(in.m_pixel_shader); - if (in.m_vertex_decl_asset) - dependencies.push_back(in.m_vertex_decl_asset); - } + MaterialShaderArgument argument{}; + const d3d9::ShaderInfo *shaderInfo; - MaterialTechnique* ConvertTechnique(const std::string& techniqueName, const std::vector& passes, std::vector& dependencies) const - { - assert(!passes.empty()); - const auto techniqueSize = sizeof(MaterialTechnique) + (passes.size() - 1u) * sizeof(MaterialPass); - auto* technique = static_cast(m_memory->Alloc(techniqueSize)); - memset(technique, 0, techniqueSize); - technique->name = m_memory->Dup(techniqueName.c_str()); - technique->passCount = static_cast(passes.size()); + if (shader == techset::ShaderSelector::VERTEX_SHADER) { + shaderInfo = pass.m_vertex_shader_info; + } else { + assert(shader == techset::ShaderSelector::PIXEL_SHADER); + shaderInfo = pass.m_pixel_shader_info; + } - UpdateTechniqueFlags(*technique); + if (!shaderInfo) { + errorMessage = "Shader not specified"; + return false; + } - for (auto i = 0u; i < passes.size(); i++) - ConvertPass(*technique, technique->passArray[i], passes.at(i), dependencies); + size_t shaderConstantIndex = 0u; + size_t registerOffset = 0u; + if (!FindShaderArgument(*shaderInfo, shaderArgument, shaderConstantIndex, registerOffset, errorMessage)) + return false; + + const auto elementOffset = shaderArgument.m_argument_index_specified ? shaderArgument.m_argument_index : 0u; + const auto &shaderConstant = shaderInfo->m_constants[shaderConstantIndex]; + const auto argumentIsSampler = IsSamplerArgument(shaderConstant); + if (shader == techset::ShaderSelector::VERTEX_SHADER) { + if (argumentIsSampler) { + errorMessage = "Vertex sampler are unsupported"; + return false; + } + argument.type = MTL_ARG_MATERIAL_VERTEX_CONST; + } else { + assert(shader == techset::ShaderSelector::PIXEL_SHADER); + argument.type = !argumentIsSampler ? MTL_ARG_MATERIAL_PIXEL_CONST : MTL_ARG_MATERIAL_PIXEL_SAMPLER; + } - return technique; - } + if (source.m_is_hash) + argument.u.nameHash = static_cast(source.m_hash); + else + argument.u.nameHash = Common::R_HashString(source.m_name.c_str(), 0u); - MaterialTechnique* LoadTechniqueFromRaw(const std::string& techniqueName, std::vector& dependencies) const - { - const auto techniqueFileName = AssetLoaderTechniqueSet::GetTechniqueFileName(techniqueName); - const auto file = m_search_path->Open(techniqueFileName); - if (!file.IsOpen()) - return nullptr; + argument.dest = static_cast(shaderConstant.m_register_index + registerOffset); + pass.m_arguments.emplace_back(argument); - TechniqueCreator creator(techniqueName, m_search_path, m_memory, m_manager, m_zone_state, m_shader_info_cache, m_state_map_cache); - const techset::TechniqueFileReader reader(*file.m_stream, techniqueFileName, &creator); - if (!reader.ReadTechniqueDefinition()) - return nullptr; + if (shader == techset::ShaderSelector::VERTEX_SHADER) + pass.m_handled_vertex_shader_arguments[pass.m_vertex_shader_argument_handled_offset[shaderConstantIndex] + elementOffset] = true; + else + pass.m_handled_pixel_shader_arguments[pass.m_pixel_shader_argument_handled_offset[shaderConstantIndex] + elementOffset] = true; - return ConvertTechnique(techniqueName, creator.m_passes, dependencies); - } + return true; + } - public: - TechniqueLoader(ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager) - : m_search_path(searchPath), - m_memory(memory), - m_manager(manager), - m_zone_state(manager->GetAssetLoadingContext()->GetZoneAssetLoaderState()), - m_shader_info_cache(manager->GetAssetLoadingContext()->GetZoneAssetLoaderState()), - m_state_map_cache(manager->GetAssetLoadingContext()->GetZoneAssetLoaderState()) - { - } + bool AcceptVertexStreamRouting(const std::string &destination, const std::string &source, std::string &errorMessage) override { + assert(!m_passes.empty()); + auto &pass = m_passes.at(m_passes.size() - 1); + + const auto streamIndex = static_cast(pass.m_vertex_decl.streamCount); + if (pass.m_vertex_decl.streamCount >= std::extent_v) { + errorMessage = "Too many stream routings"; + return false; + } + + const auto foundDestination = std::find(std::begin(materialStreamDestinationNames), std::end(materialStreamDestinationNames), destination); + if (foundDestination == std::end(materialStreamDestinationNames)) { + errorMessage = "Unknown stream destination"; + return false; + } + + const auto foundSource = std::find(std::begin(materialStreamSourceNames), std::end(materialStreamSourceNames), source); + if (foundSource == std::end(materialStreamSourceNames)) { + errorMessage = "Unknown stream source"; + return false; + } - _NODISCARD const LoadedTechnique* LoadMaterialTechnique(const std::string& techniqueName) const - { - auto* technique = m_zone_state->FindLoadedTechnique(techniqueName); - if (technique) - return technique; + const auto destinationIndex = static_cast(foundDestination - std::begin(materialStreamDestinationNames)); + const auto sourceIndex = static_cast(foundSource - std::begin(materialStreamSourceNames)); - std::vector dependencies; - auto* techniqueFromRaw = LoadTechniqueFromRaw(techniqueName, dependencies); - if (techniqueFromRaw == nullptr) - return nullptr; + pass.m_vertex_decl.routing.data[streamIndex].dest = destinationIndex; + pass.m_vertex_decl.routing.data[streamIndex].source = sourceIndex; - return m_zone_state->AddLoadedTechnique(techniqueName, techniqueFromRaw, dependencies); + pass.m_vertex_decl.hasOptionalSource = pass.m_vertex_decl.hasOptionalSource || sourceIndex >= STREAM_SRC_OPTIONAL_BEGIN; + + pass.m_vertex_decl.streamCount++; + return true; + } +}; + +class TechniqueLoader { + ISearchPath *m_search_path; + MemoryManager *m_memory; + IAssetLoadingManager *m_manager; + TechniqueZoneLoadingState *m_zone_state; + ShaderInfoFromFileSystemCacheState *m_shader_info_cache; + techset::TechniqueStateMapCache *m_state_map_cache; + + static void UpdateTechniqueFlags(MaterialTechnique &technique) { + // This is stupid but that's what the game does for zprepass for sure + // The other ones might be handled by the game in the same fashion because there is not recognizable pattern that connects the shaders with the same flags + static std::unordered_map flagsByTechniqueName({ + {"zprepass", TECHNIQUE_FLAG_4 | TECHNIQUE_FLAG_200 }, + {"build_floatz", TECHNIQUE_FLAG_8 }, + {"build_shadowmap_depth", TECHNIQUE_FLAG_10 | TECHNIQUE_FLAG_200}, + {"build_shadowmap_model", TECHNIQUE_FLAG_10 | TECHNIQUE_FLAG_200}, + {"distortion_scale_ua_zfeather", TECHNIQUE_FLAG_100 }, + {"distortion_scale_zfeather", TECHNIQUE_FLAG_100 }, + {"distortion_scale_zfeather_dtex", TECHNIQUE_FLAG_100 }, + {"alternate_scene_overlay", TECHNIQUE_FLAG_200 }, + {"blur_apply", TECHNIQUE_FLAG_200 }, + {"build_floatz", TECHNIQUE_FLAG_200 }, + {"build_floatz_clear", TECHNIQUE_FLAG_200 }, + {"build_floatz_dtex", TECHNIQUE_FLAG_200 }, + {"build_floatz_ua", TECHNIQUE_FLAG_200 }, + {"build_floatz_ua_dtex", TECHNIQUE_FLAG_200 }, + {"build_shadowmap_depth_nc", TECHNIQUE_FLAG_200 }, + {"build_shadowmap_depth_ua", TECHNIQUE_FLAG_200 }, + {"build_shadowmap_model_dtex", TECHNIQUE_FLAG_200 }, + {"build_shadowmap_model_nc_dtex", TECHNIQUE_FLAG_200 }, + {"build_shadowmap_model_ua", TECHNIQUE_FLAG_200 }, + {"cinematic", TECHNIQUE_FLAG_200 }, + {"cinematic_3d", TECHNIQUE_FLAG_200 }, + {"cinematic_dtex_3d", TECHNIQUE_FLAG_200 }, + {"dof_near_coc", TECHNIQUE_FLAG_200 }, + {"floatz", TECHNIQUE_FLAG_200 }, + {"floatzdisplay", TECHNIQUE_FLAG_200 }, + {"particle_blend", TECHNIQUE_FLAG_200 }, + {"particle_zdownsample", TECHNIQUE_FLAG_200 }, + {"passthru_alpha", TECHNIQUE_FLAG_200 }, + {"postfx", TECHNIQUE_FLAG_200 }, + {"postfx_mblur", TECHNIQUE_FLAG_200 }, + {"processed_floatz", TECHNIQUE_FLAG_200 }, + {"ps3_aadownsample", TECHNIQUE_FLAG_200 }, + {"shell_shock", TECHNIQUE_FLAG_200 }, + {"shell_shock_flashed", TECHNIQUE_FLAG_200 }, + {"small_blur", TECHNIQUE_FLAG_200 }, + {"stencildisplay", TECHNIQUE_FLAG_200 }, + {"stencilshadow", TECHNIQUE_FLAG_200 }, + {"wireframe_solid", TECHNIQUE_FLAG_200 }, + {"wireframe_solid_atest_dtex", TECHNIQUE_FLAG_200 }, + {"wireframe_solid_dtex", TECHNIQUE_FLAG_200 }, + {"wireframe_solid_nc", TECHNIQUE_FLAG_200 }, + {"wireframe_solid_nc_dtex", TECHNIQUE_FLAG_200 }, + {"wireframe_solid_ua", TECHNIQUE_FLAG_200 }, + {"wireframe_solid_ua_dtex", TECHNIQUE_FLAG_200 } + }); + + const auto flagsForName = flagsByTechniqueName.find(technique.name); + if (flagsForName != flagsByTechniqueName.end()) { + technique.flags |= flagsForName->second; + } + + for (auto i = 0u; i < technique.passCount; i++) { + const auto &pass = technique.passArray[i]; + if (pass.vertexDecl && pass.vertexDecl->hasOptionalSource) { + technique.flags |= TECHNIQUE_FLAG_20; + break; + } + } + } + + static void UpdateTechniqueFlagsForArgument(uint16_t &techniqueFlags, const TechniqueCreator::PassShaderArgument &arg) { + if (arg.m_arg.type == MTL_ARG_CODE_PIXEL_SAMPLER) { + switch (arg.m_arg.u.codeSampler) { + case TEXTURE_SRC_CODE_RESOLVED_POST_SUN: + techniqueFlags |= TECHNIQUE_FLAG_1; + break; + case TEXTURE_SRC_CODE_RESOLVED_SCENE: + techniqueFlags |= TECHNIQUE_FLAG_2; + break; + case TEXTURE_SRC_CODE_FLOATZ: + case TEXTURE_SRC_CODE_PROCESSED_FLOATZ: + case TEXTURE_SRC_CODE_RAW_FLOATZ: + if ((techniqueFlags & TECHNIQUE_FLAG_100) == 0) + techniqueFlags |= TECHNIQUE_FLAG_80; + break; + default: + break; + } + } else if (arg.m_arg.type == MTL_ARG_CODE_VERTEX_CONST || arg.m_arg.type == MTL_ARG_CODE_PIXEL_CONST) { + switch (arg.m_arg.u.codeConst.index) { + case CONST_SRC_CODE_LIGHT_SPOTDIR: + case CONST_SRC_CODE_LIGHT_SPOTFACTORS: + techniqueFlags |= TECHNIQUE_FLAG_40; + break; + default: + break; + } + } + } + + void ConvertPass(MaterialTechnique &technique, MaterialPass &out, const TechniqueCreator::Pass &in, std::vector &dependencies) const { + out.customSamplerFlags = 0u; + out.vertexShader = in.m_vertex_shader->Asset(); + out.pixelShader = in.m_pixel_shader->Asset(); + out.vertexDecl = in.m_vertex_decl_asset->Asset(); + + const auto argDataSize = sizeof(MaterialShaderArgument) * in.m_arguments.size(); + out.args = static_cast(m_memory->Alloc(argDataSize)); + + size_t perObjArgCount = 0u; + size_t perPrimArgCount = 0u; + size_t stableArgCount = 0u; + size_t argIndex = 0u; + for (const auto &arg : in.m_arguments) { + UpdateTechniqueFlagsForArgument(technique.flags, arg); + switch (arg.m_update_frequency) { + case MTL_UPDATE_PER_PRIM: + perPrimArgCount++; + break; + case MTL_UPDATE_PER_OBJECT: + perObjArgCount++; + break; + case MTL_UPDATE_RARELY: + stableArgCount++; + break; + case MTL_UPDATE_CUSTOM: { + assert(arg.m_arg.type == MTL_ARG_CODE_PIXEL_SAMPLER); + if (arg.m_arg.type == MTL_ARG_CODE_PIXEL_SAMPLER) { + const auto customSampler = std::find(std::begin(g_customSamplerSrc), std::end(g_customSamplerSrc), arg.m_arg.u.codeSampler); + assert(customSampler != std::end(g_customSamplerSrc)); + if (customSampler != std::end(g_customSamplerSrc)) { + const auto customSamplerIndex = customSampler - std::begin(g_customSamplerSrc); + out.customSamplerFlags |= 1 << customSamplerIndex; + } } - }; -} + } + continue; + default: + assert(false); + continue; + } + + out.args[argIndex++] = arg.m_arg; + } -void* AssetLoaderTechniqueSet::CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) -{ - auto* techset = memory->Create(); - memset(techset, 0, sizeof(MaterialTechniqueSet)); - techset->name = memory->Dup(assetName.c_str()); - return techset; + out.perObjArgCount = static_cast(perObjArgCount); + out.perPrimArgCount = static_cast(perPrimArgCount); + out.stableArgCount = static_cast(stableArgCount); + + if (in.m_vertex_shader) + dependencies.push_back(in.m_vertex_shader); + if (in.m_pixel_shader) + dependencies.push_back(in.m_pixel_shader); + if (in.m_vertex_decl_asset) + dependencies.push_back(in.m_vertex_decl_asset); + } + + MaterialTechnique *ConvertTechnique(const std::string &techniqueName, const std::vector &passes, + std::vector &dependencies) const { + assert(!passes.empty()); + const auto techniqueSize = sizeof(MaterialTechnique) + (passes.size() - 1u) * sizeof(MaterialPass); + auto *technique = static_cast(m_memory->Alloc(techniqueSize)); + memset(technique, 0, techniqueSize); + technique->name = m_memory->Dup(techniqueName.c_str()); + technique->passCount = static_cast(passes.size()); + + UpdateTechniqueFlags(*technique); + + for (auto i = 0u; i < passes.size(); i++) + ConvertPass(*technique, technique->passArray[i], passes.at(i), dependencies); + + return technique; + } + + MaterialTechnique *LoadTechniqueFromRaw(const std::string &techniqueName, std::vector &dependencies) const { + const auto techniqueFileName = AssetLoaderTechniqueSet::GetTechniqueFileName(techniqueName); + const auto file = m_search_path->Open(techniqueFileName); + if (!file.IsOpen()) + return nullptr; + + TechniqueCreator creator(techniqueName, m_search_path, m_memory, m_manager, m_zone_state, m_shader_info_cache, m_state_map_cache); + const techset::TechniqueFileReader reader(*file.m_stream, techniqueFileName, &creator); + if (!reader.ReadTechniqueDefinition()) + return nullptr; + + return ConvertTechnique(techniqueName, creator.m_passes, dependencies); + } + +public: + TechniqueLoader(ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager) + : m_search_path(searchPath), m_memory(memory), m_manager(manager), + m_zone_state(manager->GetAssetLoadingContext()->GetZoneAssetLoaderState()), + m_shader_info_cache(manager->GetAssetLoadingContext()->GetZoneAssetLoaderState()), + m_state_map_cache(manager->GetAssetLoadingContext()->GetZoneAssetLoaderState()) {} + + _NODISCARD const LoadedTechnique *LoadMaterialTechnique(const std::string &techniqueName) const { + auto *technique = m_zone_state->FindLoadedTechnique(techniqueName); + if (technique) + return technique; + + std::vector dependencies; + auto *techniqueFromRaw = LoadTechniqueFromRaw(techniqueName, dependencies); + if (techniqueFromRaw == nullptr) + return nullptr; + + return m_zone_state->AddLoadedTechnique(techniqueName, techniqueFromRaw, dependencies); + } +}; +} // namespace IW4 + +void *AssetLoaderTechniqueSet::CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) { + auto *techset = memory->Create(); + memset(techset, 0, sizeof(MaterialTechniqueSet)); + techset->name = memory->Dup(assetName.c_str()); + return techset; } -std::string AssetLoaderTechniqueSet::GetTechsetFileName(const std::string& techsetAssetName) -{ - std::ostringstream ss; - ss << "techsets/" << techsetAssetName << ".techset"; - return ss.str(); +std::string AssetLoaderTechniqueSet::GetTechsetFileName(const std::string &techsetAssetName) { + std::ostringstream ss; + ss << "techsets/" << techsetAssetName << ".techset"; + return ss.str(); } -std::string AssetLoaderTechniqueSet::GetTechniqueFileName(const std::string& techniqueName) -{ - std::ostringstream ss; - ss << "techniques/" << techniqueName << ".tech"; - return ss.str(); +std::string AssetLoaderTechniqueSet::GetTechniqueFileName(const std::string &techniqueName) { + std::ostringstream ss; + ss << "techniques/" << techniqueName << ".tech"; + return ss.str(); } -std::string AssetLoaderTechniqueSet::GetStateMapFileName(const std::string& stateMapName) -{ - std::ostringstream ss; - ss << "statemaps/" << stateMapName << ".sm"; - return ss.str(); +std::string AssetLoaderTechniqueSet::GetStateMapFileName(const std::string &stateMapName) { + std::ostringstream ss; + ss << "statemaps/" << stateMapName << ".sm"; + return ss.str(); } -bool AssetLoaderTechniqueSet::CreateTechsetFromDefinition(const std::string& assetName, const techset::TechsetDefinition& definition, ISearchPath* searchPath, MemoryManager* memory, - IAssetLoadingManager* manager) -{ - auto* techset = memory->Create(); - memset(techset, 0, sizeof(MaterialTechniqueSet)); - techset->name = memory->Dup(assetName.c_str()); - - const TechniqueLoader techniqueLoader(searchPath, memory, manager); - std::set dependencies; - for (auto i = 0u; i < std::extent_v; i++) - { - std::string techniqueName; - if (definition.GetTechniqueByIndex(i, techniqueName)) - { - auto* technique = techniqueLoader.LoadMaterialTechnique(techniqueName); - - if (!technique) - return false; - - for (auto* techniqueDependency : technique->m_dependencies) - dependencies.emplace(techniqueDependency); - - techset->techniques[i] = technique->m_technique; - } +bool AssetLoaderTechniqueSet::CreateTechsetFromDefinition(const std::string &assetName, const techset::TechsetDefinition &definition, ISearchPath *searchPath, + MemoryManager *memory, IAssetLoadingManager *manager) { + auto *techset = memory->Create(); + memset(techset, 0, sizeof(MaterialTechniqueSet)); + techset->name = memory->Dup(assetName.c_str()); + + const TechniqueLoader techniqueLoader(searchPath, memory, manager); + std::set dependencies; + for (auto i = 0u; i < std::extent_v; i++) { + std::string techniqueName; + if (definition.GetTechniqueByIndex(i, techniqueName)) { + auto *technique = techniqueLoader.LoadMaterialTechnique(techniqueName); + + if (!technique) + return false; + + for (auto *techniqueDependency : technique->m_dependencies) + dependencies.emplace(techniqueDependency); + + techset->techniques[i] = technique->m_technique; } + } - manager->AddAsset(ASSET_TYPE_TECHNIQUE_SET, assetName, techset, std::vector(dependencies.begin(), dependencies.end()), std::vector()); + manager->AddAsset(ASSET_TYPE_TECHNIQUE_SET, assetName, techset, std::vector(dependencies.begin(), dependencies.end()), std::vector()); - return true; + return true; } -techset::TechsetDefinition* AssetLoaderTechniqueSet::LoadTechsetDefinition(const std::string& assetName, ISearchPath* searchPath, techset::TechsetDefinitionCache* definitionCache) -{ - auto* cachedTechsetDefinition = definitionCache->GetCachedTechsetDefinition(assetName); - if (cachedTechsetDefinition) - return cachedTechsetDefinition; +techset::TechsetDefinition *AssetLoaderTechniqueSet::LoadTechsetDefinition(const std::string &assetName, ISearchPath *searchPath, + techset::TechsetDefinitionCache *definitionCache) { + auto *cachedTechsetDefinition = definitionCache->GetCachedTechsetDefinition(assetName); + if (cachedTechsetDefinition) + return cachedTechsetDefinition; - const auto techsetFileName = GetTechsetFileName(assetName); - const auto file = searchPath->Open(techsetFileName); - if (!file.IsOpen()) - return nullptr; + const auto techsetFileName = GetTechsetFileName(assetName); + const auto file = searchPath->Open(techsetFileName); + if (!file.IsOpen()) + return nullptr; - const techset::TechsetFileReader reader(*file.m_stream, techsetFileName, techniqueTypeNames, std::extent_v); - auto techsetDefinition = reader.ReadTechsetDefinition(); - auto* techsetDefinitionPtr = techsetDefinition.get(); + const techset::TechsetFileReader reader(*file.m_stream, techsetFileName, techniqueTypeNames, std::extent_v); + auto techsetDefinition = reader.ReadTechsetDefinition(); + auto *techsetDefinitionPtr = techsetDefinition.get(); - definitionCache->AddTechsetDefinitionToCache(assetName, std::move(techsetDefinition)); + definitionCache->AddTechsetDefinitionToCache(assetName, std::move(techsetDefinition)); - return techsetDefinitionPtr; + return techsetDefinitionPtr; } -const state_map::StateMapDefinition* AssetLoaderTechniqueSet::LoadStateMapDefinition(const std::string& stateMapName, ISearchPath* searchPath, techset::TechniqueStateMapCache* stateMapCache) -{ - auto* cachedStateMap = stateMapCache->GetCachedStateMap(stateMapName); - if (cachedStateMap) - return cachedStateMap; +const state_map::StateMapDefinition *AssetLoaderTechniqueSet::LoadStateMapDefinition(const std::string &stateMapName, ISearchPath *searchPath, + techset::TechniqueStateMapCache *stateMapCache) { + auto *cachedStateMap = stateMapCache->GetCachedStateMap(stateMapName); + if (cachedStateMap) + return cachedStateMap; - const auto stateMapFileName = GetStateMapFileName(stateMapName); - const auto file = searchPath->Open(stateMapFileName); - if (!file.IsOpen()) - return nullptr; + const auto stateMapFileName = GetStateMapFileName(stateMapName); + const auto file = searchPath->Open(stateMapFileName); + if (!file.IsOpen()) + return nullptr; - const state_map::StateMapReader reader(*file.m_stream, stateMapFileName, stateMapName, stateMapLayout); - auto stateMapDefinition = reader.ReadStateMapDefinition(); - if (!stateMapDefinition) - return nullptr; + const state_map::StateMapReader reader(*file.m_stream, stateMapFileName, stateMapName, stateMapLayout); + auto stateMapDefinition = reader.ReadStateMapDefinition(); + if (!stateMapDefinition) + return nullptr; - const auto* stateMapDefinitionPtr = stateMapDefinition.get(); + const auto *stateMapDefinitionPtr = stateMapDefinition.get(); - stateMapCache->AddStateMapToCache(std::move(stateMapDefinition)); + stateMapCache->AddStateMapToCache(std::move(stateMapDefinition)); - return stateMapDefinitionPtr; + return stateMapDefinitionPtr; } -bool AssetLoaderTechniqueSet::CanLoadFromRaw() const -{ - return true; -} +bool AssetLoaderTechniqueSet::CanLoadFromRaw() const { return true; } -bool AssetLoaderTechniqueSet::LoadFromRaw(const std::string& assetName, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const -{ - auto* definitionCache = manager->GetAssetLoadingContext()->GetZoneAssetLoaderState(); - const auto* techsetDefinition = LoadTechsetDefinition(assetName, searchPath, definitionCache); - if (techsetDefinition) - return CreateTechsetFromDefinition(assetName, *techsetDefinition, searchPath, memory, manager); +bool AssetLoaderTechniqueSet::LoadFromRaw(const std::string &assetName, ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager, + Zone *zone) const { + auto *definitionCache = manager->GetAssetLoadingContext()->GetZoneAssetLoaderState(); + const auto *techsetDefinition = LoadTechsetDefinition(assetName, searchPath, definitionCache); + if (techsetDefinition) + return CreateTechsetFromDefinition(assetName, *techsetDefinition, searchPath, memory, manager); - return false; + return false; } diff --git a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderTechniqueSet.h b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderTechniqueSet.h index fe33e504c..34be4de49 100644 --- a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderTechniqueSet.h +++ b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderTechniqueSet.h @@ -1,30 +1,30 @@ #pragma once -#include "Game/IW4/IW4.h" #include "AssetLoading/BasicAssetLoader.h" +#include "Game/IW4/IW4.h" #include "SearchPath/ISearchPath.h" #include "StateMap/StateMapDefinition.h" #include "Techset/TechniqueStateMapCache.h" #include "Techset/TechsetDefinition.h" #include "Techset/TechsetDefinitionCache.h" -namespace IW4 -{ - class AssetLoaderTechniqueSet final : public BasicAssetLoader - { - static bool CreateTechsetFromDefinition(const std::string& assetName, const techset::TechsetDefinition& definition, ISearchPath* searchPath, MemoryManager* memory, - IAssetLoadingManager* manager); +namespace IW4 { +class AssetLoaderTechniqueSet final : public BasicAssetLoader { + static bool CreateTechsetFromDefinition(const std::string &assetName, const techset::TechsetDefinition &definition, ISearchPath *searchPath, + MemoryManager *memory, IAssetLoadingManager *manager); - public: - static std::string GetTechsetFileName(const std::string& techsetAssetName); - static std::string GetTechniqueFileName(const std::string& techniqueName); - static std::string GetStateMapFileName(const std::string& stateMapName); +public: + static std::string GetTechsetFileName(const std::string &techsetAssetName); + static std::string GetTechniqueFileName(const std::string &techniqueName); + static std::string GetStateMapFileName(const std::string &stateMapName); - static techset::TechsetDefinition* LoadTechsetDefinition(const std::string& assetName, ISearchPath* searchPath, techset::TechsetDefinitionCache* definitionCache); - static const state_map::StateMapDefinition* LoadStateMapDefinition(const std::string& stateMapName, ISearchPath* searchPath, techset::TechniqueStateMapCache* stateMapCache); + static techset::TechsetDefinition *LoadTechsetDefinition(const std::string &assetName, ISearchPath *searchPath, + techset::TechsetDefinitionCache *definitionCache); + static const state_map::StateMapDefinition *LoadStateMapDefinition(const std::string &stateMapName, ISearchPath *searchPath, + techset::TechniqueStateMapCache *stateMapCache); - _NODISCARD void* CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) override; - _NODISCARD bool CanLoadFromRaw() const override; - bool LoadFromRaw(const std::string& assetName, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const override; - }; -} + _NODISCARD void *CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) override; + _NODISCARD bool CanLoadFromRaw() const override; + bool LoadFromRaw(const std::string &assetName, ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager, Zone *zone) const override; +}; +} // namespace IW4 diff --git a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderTracer.cpp b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderTracer.cpp index f7ca05b6c..462760a6c 100644 --- a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderTracer.cpp +++ b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderTracer.cpp @@ -2,16 +2,15 @@ #include -#include "ObjLoading.h" #include "Game/IW4/IW4.h" +#include "ObjLoading.h" #include "Pool/GlobalAssetPool.h" using namespace IW4; -void* AssetLoaderTracer::CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) -{ - auto* tracer = memory->Create(); - memset(tracer, 0, sizeof(TracerDef)); - tracer->name = memory->Dup(assetName.c_str()); - return tracer; +void *AssetLoaderTracer::CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) { + auto *tracer = memory->Create(); + memset(tracer, 0, sizeof(TracerDef)); + tracer->name = memory->Dup(assetName.c_str()); + return tracer; } diff --git a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderTracer.h b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderTracer.h index 44e855e1d..fca8d4c6a 100644 --- a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderTracer.h +++ b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderTracer.h @@ -1,14 +1,12 @@ #pragma once -#include "Game/IW4/IW4.h" #include "AssetLoading/BasicAssetLoader.h" +#include "Game/IW4/IW4.h" #include "SearchPath/ISearchPath.h" -namespace IW4 -{ - class AssetLoaderTracer final : public BasicAssetLoader - { - public: - _NODISCARD void* CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) override; - }; -} +namespace IW4 { +class AssetLoaderTracer final : public BasicAssetLoader { +public: + _NODISCARD void *CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) override; +}; +} // namespace IW4 diff --git a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderVehicle.cpp b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderVehicle.cpp index 55e12a1fa..de0ee143f 100644 --- a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderVehicle.cpp +++ b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderVehicle.cpp @@ -2,16 +2,15 @@ #include -#include "ObjLoading.h" #include "Game/IW4/IW4.h" +#include "ObjLoading.h" #include "Pool/GlobalAssetPool.h" using namespace IW4; -void* AssetLoaderVehicle::CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) -{ - auto* vehicle = memory->Create(); - memset(vehicle, 0, sizeof(VehicleDef)); - vehicle->name = memory->Dup(assetName.c_str()); - return vehicle; +void *AssetLoaderVehicle::CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) { + auto *vehicle = memory->Create(); + memset(vehicle, 0, sizeof(VehicleDef)); + vehicle->name = memory->Dup(assetName.c_str()); + return vehicle; } diff --git a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderVehicle.h b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderVehicle.h index 26ef3e371..1c56a874e 100644 --- a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderVehicle.h +++ b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderVehicle.h @@ -1,14 +1,12 @@ #pragma once -#include "Game/IW4/IW4.h" #include "AssetLoading/BasicAssetLoader.h" +#include "Game/IW4/IW4.h" #include "SearchPath/ISearchPath.h" -namespace IW4 -{ - class AssetLoaderVehicle final : public BasicAssetLoader - { - public: - _NODISCARD void* CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) override; - }; -} +namespace IW4 { +class AssetLoaderVehicle final : public BasicAssetLoader { +public: + _NODISCARD void *CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) override; +}; +} // namespace IW4 diff --git a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderVertexDecl.cpp b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderVertexDecl.cpp index e2b0ae122..11235cb8b 100644 --- a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderVertexDecl.cpp +++ b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderVertexDecl.cpp @@ -3,93 +3,82 @@ #include #include -#include "ObjLoading.h" #include "Game/IW4/IW4.h" #include "Game/IW4/TechsetConstantsIW4.h" +#include "ObjLoading.h" #include "Pool/GlobalAssetPool.h" using namespace IW4; -void* AssetLoaderVertexDecl::CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) -{ - auto* vertexDecl = memory->Create(); - memset(vertexDecl, 0, sizeof(MaterialVertexDeclaration)); - vertexDecl->name = memory->Dup(assetName.c_str()); - return vertexDecl; +void *AssetLoaderVertexDecl::CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) { + auto *vertexDecl = memory->Create(); + memset(vertexDecl, 0, sizeof(MaterialVertexDeclaration)); + vertexDecl->name = memory->Dup(assetName.c_str()); + return vertexDecl; } -bool AssetLoaderVertexDecl::CanLoadFromRaw() const -{ - return true; +bool AssetLoaderVertexDecl::CanLoadFromRaw() const { return true; } + +bool AssetLoaderVertexDecl::NextAbbreviation(const std::string &assetName, std::string &abbreviation, size_t &offset) { + if (offset >= assetName.size()) + return false; + + if (offset + 1 < assetName.size() && isdigit(assetName[offset + 1])) { + abbreviation = std::string(assetName, offset, 2); + offset += 2; + } else { + abbreviation = std::string(assetName, offset, 1); + offset += 1; + } + + return true; } -bool AssetLoaderVertexDecl::NextAbbreviation(const std::string& assetName, std::string& abbreviation, size_t& offset) -{ - if (offset >= assetName.size()) - return false; +bool AssetLoaderVertexDecl::LoadFromRaw(const std::string &assetName, ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager, + Zone *zone) const { + MaterialVertexDeclaration decl{}; - if (offset + 1 < assetName.size() && isdigit(assetName[offset + 1])) - { - abbreviation = std::string(assetName, offset, 2); - offset += 2; + size_t currentOffset = 0u; + std::string sourceAbbreviation; + while (NextAbbreviation(assetName, sourceAbbreviation, currentOffset)) { + if (decl.streamCount >= std::extent_v) { + std::cout << "Failed to add vertex decl stream. Too many abbreviations: " << assetName << "\n"; + return false; } - else - { - abbreviation = std::string(assetName, offset, 1); - offset += 1; + + std::string destinationAbbreviation; + if (!NextAbbreviation(assetName, destinationAbbreviation, currentOffset)) { + std::cout << "Failed to detect vertex decl destination abbreviation: " << assetName << "\n"; + return false; } - return true; -} + const auto foundSourceAbbreviation = + std::find(std::begin(materialStreamSourceAbbreviation), std::end(materialStreamSourceAbbreviation), sourceAbbreviation); + if (foundSourceAbbreviation == std::end(materialStreamSourceAbbreviation)) { + std::cout << "Unknown vertex decl source abbreviation: " << sourceAbbreviation << "\n"; + return false; + } -bool AssetLoaderVertexDecl::LoadFromRaw(const std::string& assetName, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const -{ - MaterialVertexDeclaration decl{}; - - size_t currentOffset = 0u; - std::string sourceAbbreviation; - while (NextAbbreviation(assetName, sourceAbbreviation, currentOffset)) - { - if(decl.streamCount >= std::extent_v) - { - std::cout << "Failed to add vertex decl stream. Too many abbreviations: " << assetName << "\n"; - return false; - } - - std::string destinationAbbreviation; - if (!NextAbbreviation(assetName, destinationAbbreviation, currentOffset)) - { - std::cout << "Failed to detect vertex decl destination abbreviation: " << assetName << "\n"; - return false; - } - - const auto foundSourceAbbreviation = std::find(std::begin(materialStreamSourceAbbreviation), std::end(materialStreamSourceAbbreviation), sourceAbbreviation); - if (foundSourceAbbreviation == std::end(materialStreamSourceAbbreviation)) - { - std::cout << "Unknown vertex decl source abbreviation: " << sourceAbbreviation << "\n"; - return false; - } - - const auto foundDestinationAbbreviation = std::find(std::begin(materialStreamDestinationAbbreviation), std::end(materialStreamDestinationAbbreviation), destinationAbbreviation); - if (foundDestinationAbbreviation == std::end(materialStreamDestinationAbbreviation)) - { - std::cout << "Unknown vertex decl destination abbreviation: " << destinationAbbreviation << "\n"; - return false; - } - - const auto sourceIndex = static_cast(foundSourceAbbreviation - std::begin(materialStreamSourceAbbreviation)); - const auto destinationIndex = static_cast(foundDestinationAbbreviation - std::begin(materialStreamDestinationAbbreviation)); - - decl.routing.data[decl.streamCount].source = sourceIndex; - decl.routing.data[decl.streamCount].dest = destinationIndex; - decl.hasOptionalSource = decl.hasOptionalSource || sourceIndex >= STREAM_SRC_OPTIONAL_BEGIN; - decl.streamCount++; + const auto foundDestinationAbbreviation = + std::find(std::begin(materialStreamDestinationAbbreviation), std::end(materialStreamDestinationAbbreviation), destinationAbbreviation); + if (foundDestinationAbbreviation == std::end(materialStreamDestinationAbbreviation)) { + std::cout << "Unknown vertex decl destination abbreviation: " << destinationAbbreviation << "\n"; + return false; } - decl.name = memory->Dup(assetName.c_str()); + const auto sourceIndex = static_cast(foundSourceAbbreviation - std::begin(materialStreamSourceAbbreviation)); + const auto destinationIndex = static_cast(foundDestinationAbbreviation - std::begin(materialStreamDestinationAbbreviation)); + + decl.routing.data[decl.streamCount].source = sourceIndex; + decl.routing.data[decl.streamCount].dest = destinationIndex; + decl.hasOptionalSource = decl.hasOptionalSource || sourceIndex >= STREAM_SRC_OPTIONAL_BEGIN; + decl.streamCount++; + } + + decl.name = memory->Dup(assetName.c_str()); - auto* allocatedDecl = memory->Create(decl); + auto *allocatedDecl = memory->Create(decl); - manager->AddAsset(ASSET_TYPE_VERTEXDECL, assetName, allocatedDecl); - return true; + manager->AddAsset(ASSET_TYPE_VERTEXDECL, assetName, allocatedDecl); + return true; } diff --git a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderVertexDecl.h b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderVertexDecl.h index 196c52952..b8569a9e8 100644 --- a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderVertexDecl.h +++ b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderVertexDecl.h @@ -1,19 +1,17 @@ #pragma once -#include "Game/IW4/IW4.h" #include "AssetLoading/BasicAssetLoader.h" +#include "Game/IW4/IW4.h" #include "SearchPath/ISearchPath.h" -namespace IW4 -{ - class AssetLoaderVertexDecl final : public BasicAssetLoader - { - static bool NextAbbreviation(const std::string& assetName, std::string& abbreviation, size_t& offset); +namespace IW4 { +class AssetLoaderVertexDecl final : public BasicAssetLoader { + static bool NextAbbreviation(const std::string &assetName, std::string &abbreviation, size_t &offset); - public: - _NODISCARD void* CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) override; +public: + _NODISCARD void *CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) override; - _NODISCARD bool CanLoadFromRaw() const override; - bool LoadFromRaw(const std::string& assetName, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const override; - }; -} + _NODISCARD bool CanLoadFromRaw() const override; + bool LoadFromRaw(const std::string &assetName, ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager, Zone *zone) const override; +}; +} // namespace IW4 diff --git a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderVertexShader.cpp b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderVertexShader.cpp index c619bbd6b..be0ccf5d0 100644 --- a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderVertexShader.cpp +++ b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderVertexShader.cpp @@ -5,58 +5,52 @@ #include #include -#include "ObjLoading.h" #include "Game/IW4/IW4.h" +#include "ObjLoading.h" #include "Pool/GlobalAssetPool.h" using namespace IW4; -void* AssetLoaderVertexShader::CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) -{ - auto* vertexShader = memory->Create(); - memset(vertexShader, 0, sizeof(MaterialVertexShader)); - vertexShader->name = memory->Dup(assetName.c_str()); - return vertexShader; +void *AssetLoaderVertexShader::CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) { + auto *vertexShader = memory->Create(); + memset(vertexShader, 0, sizeof(MaterialVertexShader)); + vertexShader->name = memory->Dup(assetName.c_str()); + return vertexShader; } -bool AssetLoaderVertexShader::CanLoadFromRaw() const -{ - return true; -} +bool AssetLoaderVertexShader::CanLoadFromRaw() const { return true; } -std::string AssetLoaderVertexShader::GetFileNameForAsset(const std::string& assetName) -{ - std::ostringstream ss; - ss << "shader_bin/vs_" << assetName << ".cso"; - return ss.str(); +std::string AssetLoaderVertexShader::GetFileNameForAsset(const std::string &assetName) { + std::ostringstream ss; + ss << "shader_bin/vs_" << assetName << ".cso"; + return ss.str(); } -bool AssetLoaderVertexShader::LoadFromRaw(const std::string& assetName, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const -{ - const auto fileName = GetFileNameForAsset(assetName); - const auto file = searchPath->Open(fileName); - if (!file.IsOpen()) - return false; - - if (file.m_length % sizeof(uint32_t) != 0) - { - std::cerr << "Invalid vertex shader \"" << assetName << "\": Size must be dividable by " << sizeof(uint32_t) << "\n"; - return false; - } - - auto* vertexShader = memory->Create(); - vertexShader->name = memory->Dup(assetName.c_str()); - vertexShader->prog.loadDef.programSize = static_cast(static_cast(file.m_length) / sizeof(uint32_t)); - vertexShader->prog.loadDef.loadForRenderer = 0; - vertexShader->prog.vs = nullptr; - - auto* fileBuffer = static_cast(memory->Alloc(vertexShader->prog.loadDef.programSize * sizeof(uint32_t))); - file.m_stream->read(fileBuffer, static_cast(vertexShader->prog.loadDef.programSize) * sizeof(uint32_t)); - if (file.m_stream->gcount() != file.m_length) - return false; - - vertexShader->prog.loadDef.program = reinterpret_cast(fileBuffer); - manager->AddAsset(ASSET_TYPE_VERTEXSHADER, assetName, vertexShader); - - return true; +bool AssetLoaderVertexShader::LoadFromRaw(const std::string &assetName, ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager, + Zone *zone) const { + const auto fileName = GetFileNameForAsset(assetName); + const auto file = searchPath->Open(fileName); + if (!file.IsOpen()) + return false; + + if (file.m_length % sizeof(uint32_t) != 0) { + std::cerr << "Invalid vertex shader \"" << assetName << "\": Size must be dividable by " << sizeof(uint32_t) << "\n"; + return false; + } + + auto *vertexShader = memory->Create(); + vertexShader->name = memory->Dup(assetName.c_str()); + vertexShader->prog.loadDef.programSize = static_cast(static_cast(file.m_length) / sizeof(uint32_t)); + vertexShader->prog.loadDef.loadForRenderer = 0; + vertexShader->prog.vs = nullptr; + + auto *fileBuffer = static_cast(memory->Alloc(vertexShader->prog.loadDef.programSize * sizeof(uint32_t))); + file.m_stream->read(fileBuffer, static_cast(vertexShader->prog.loadDef.programSize) * sizeof(uint32_t)); + if (file.m_stream->gcount() != file.m_length) + return false; + + vertexShader->prog.loadDef.program = reinterpret_cast(fileBuffer); + manager->AddAsset(ASSET_TYPE_VERTEXSHADER, assetName, vertexShader); + + return true; } diff --git a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderVertexShader.h b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderVertexShader.h index b2eab7e89..a5454c2d5 100644 --- a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderVertexShader.h +++ b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderVertexShader.h @@ -1,18 +1,16 @@ #pragma once -#include "Game/IW4/IW4.h" #include "AssetLoading/BasicAssetLoader.h" +#include "Game/IW4/IW4.h" #include "SearchPath/ISearchPath.h" -namespace IW4 -{ - class AssetLoaderVertexShader final : public BasicAssetLoader - { - public: - _NODISCARD static std::string GetFileNameForAsset(const std::string& assetName); +namespace IW4 { +class AssetLoaderVertexShader final : public BasicAssetLoader { +public: + _NODISCARD static std::string GetFileNameForAsset(const std::string &assetName); - _NODISCARD void* CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) override; - _NODISCARD bool CanLoadFromRaw() const override; - bool LoadFromRaw(const std::string& assetName, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const override; - }; -} + _NODISCARD void *CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) override; + _NODISCARD bool CanLoadFromRaw() const override; + bool LoadFromRaw(const std::string &assetName, ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager, Zone *zone) const override; +}; +} // namespace IW4 diff --git a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderWeapon.cpp b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderWeapon.cpp index dec4e5b6c..4584bc257 100644 --- a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderWeapon.cpp +++ b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderWeapon.cpp @@ -2,16 +2,15 @@ #include -#include "ObjLoading.h" #include "Game/IW4/IW4.h" +#include "ObjLoading.h" #include "Pool/GlobalAssetPool.h" using namespace IW4; -void* AssetLoaderWeapon::CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) -{ - auto* weapon = memory->Create(); - memset(weapon, 0, sizeof(WeaponCompleteDef)); - weapon->szInternalName = memory->Dup(assetName.c_str()); - return weapon; +void *AssetLoaderWeapon::CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) { + auto *weapon = memory->Create(); + memset(weapon, 0, sizeof(WeaponCompleteDef)); + weapon->szInternalName = memory->Dup(assetName.c_str()); + return weapon; } diff --git a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderWeapon.h b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderWeapon.h index 6640e9467..4683e53f9 100644 --- a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderWeapon.h +++ b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderWeapon.h @@ -1,14 +1,12 @@ #pragma once -#include "Game/IW4/IW4.h" #include "AssetLoading/BasicAssetLoader.h" +#include "Game/IW4/IW4.h" #include "SearchPath/ISearchPath.h" -namespace IW4 -{ - class AssetLoaderWeapon final : public BasicAssetLoader - { - public: - _NODISCARD void* CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) override; - }; -} +namespace IW4 { +class AssetLoaderWeapon final : public BasicAssetLoader { +public: + _NODISCARD void *CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) override; +}; +} // namespace IW4 diff --git a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderXAnim.cpp b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderXAnim.cpp index bb1a275b6..356edfd23 100644 --- a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderXAnim.cpp +++ b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderXAnim.cpp @@ -2,16 +2,15 @@ #include -#include "ObjLoading.h" #include "Game/IW4/IW4.h" +#include "ObjLoading.h" #include "Pool/GlobalAssetPool.h" using namespace IW4; -void* AssetLoaderXAnim::CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) -{ - auto* anim = memory->Create(); - memset(anim, 0, sizeof(XAnimParts)); - anim->name = memory->Dup(assetName.c_str()); - return anim; +void *AssetLoaderXAnim::CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) { + auto *anim = memory->Create(); + memset(anim, 0, sizeof(XAnimParts)); + anim->name = memory->Dup(assetName.c_str()); + return anim; } diff --git a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderXAnim.h b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderXAnim.h index a3d98d3f5..d9dc13bd1 100644 --- a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderXAnim.h +++ b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderXAnim.h @@ -1,14 +1,12 @@ #pragma once -#include "Game/IW4/IW4.h" #include "AssetLoading/BasicAssetLoader.h" +#include "Game/IW4/IW4.h" #include "SearchPath/ISearchPath.h" -namespace IW4 -{ - class AssetLoaderXAnim final : public BasicAssetLoader - { - public: - _NODISCARD void* CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) override; - }; -} +namespace IW4 { +class AssetLoaderXAnim final : public BasicAssetLoader { +public: + _NODISCARD void *CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) override; +}; +} // namespace IW4 diff --git a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderXModel.cpp b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderXModel.cpp index c8f43cfa3..2fbfb15ad 100644 --- a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderXModel.cpp +++ b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderXModel.cpp @@ -2,16 +2,15 @@ #include -#include "ObjLoading.h" #include "Game/IW4/IW4.h" +#include "ObjLoading.h" #include "Pool/GlobalAssetPool.h" using namespace IW4; -void* AssetLoaderXModel::CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) -{ - auto* model = memory->Create(); - memset(model, 0, sizeof(XModel)); - model->name = memory->Dup(assetName.c_str()); - return model; +void *AssetLoaderXModel::CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) { + auto *model = memory->Create(); + memset(model, 0, sizeof(XModel)); + model->name = memory->Dup(assetName.c_str()); + return model; } diff --git a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderXModel.h b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderXModel.h index b5e79d129..69d6478f8 100644 --- a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderXModel.h +++ b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderXModel.h @@ -1,14 +1,12 @@ #pragma once -#include "Game/IW4/IW4.h" #include "AssetLoading/BasicAssetLoader.h" +#include "Game/IW4/IW4.h" #include "SearchPath/ISearchPath.h" -namespace IW4 -{ - class AssetLoaderXModel final : public BasicAssetLoader - { - public: - _NODISCARD void* CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) override; - }; -} +namespace IW4 { +class AssetLoaderXModel final : public BasicAssetLoader { +public: + _NODISCARD void *CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) override; +}; +} // namespace IW4 diff --git a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderXModelSurfs.cpp b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderXModelSurfs.cpp index ba8caa7bb..ee7d365b0 100644 --- a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderXModelSurfs.cpp +++ b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderXModelSurfs.cpp @@ -2,16 +2,15 @@ #include -#include "ObjLoading.h" #include "Game/IW4/IW4.h" +#include "ObjLoading.h" #include "Pool/GlobalAssetPool.h" using namespace IW4; -void* AssetLoaderXModelSurfs::CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) -{ - auto* modelSurfs = memory->Create(); - memset(modelSurfs, 0, sizeof(XModelSurfs)); - modelSurfs->name = memory->Dup(assetName.c_str()); - return modelSurfs; +void *AssetLoaderXModelSurfs::CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) { + auto *modelSurfs = memory->Create(); + memset(modelSurfs, 0, sizeof(XModelSurfs)); + modelSurfs->name = memory->Dup(assetName.c_str()); + return modelSurfs; } diff --git a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderXModelSurfs.h b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderXModelSurfs.h index f9326ee77..a19ac2a29 100644 --- a/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderXModelSurfs.h +++ b/src/ObjLoading/Game/IW4/AssetLoaders/AssetLoaderXModelSurfs.h @@ -1,14 +1,12 @@ #pragma once -#include "Game/IW4/IW4.h" #include "AssetLoading/BasicAssetLoader.h" +#include "Game/IW4/IW4.h" #include "SearchPath/ISearchPath.h" -namespace IW4 -{ - class AssetLoaderXModelSurfs final : public BasicAssetLoader - { - public: - _NODISCARD void* CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) override; - }; -} +namespace IW4 { +class AssetLoaderXModelSurfs final : public BasicAssetLoader { +public: + _NODISCARD void *CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) override; +}; +} // namespace IW4 diff --git a/src/ObjLoading/Game/IW4/InfoString/InfoStringToStructConverter.cpp b/src/ObjLoading/Game/IW4/InfoString/InfoStringToStructConverter.cpp index df9b5dd27..1d8fda9ae 100644 --- a/src/ObjLoading/Game/IW4/InfoString/InfoStringToStructConverter.cpp +++ b/src/ObjLoading/Game/IW4/InfoString/InfoStringToStructConverter.cpp @@ -5,223 +5,192 @@ using namespace IW4; -InfoStringToStructConverter::InfoStringToStructConverter(const InfoString& infoString, void* structure, ZoneScriptStrings& zoneScriptStrings, MemoryManager* memory, IAssetLoadingManager* manager, - const cspField_t* fields, const size_t fieldCount) - : InfoStringToStructConverterBase(infoString, structure, zoneScriptStrings, memory), - m_loading_manager(manager), - m_fields(fields), - m_field_count(fieldCount) -{ -} +InfoStringToStructConverter::InfoStringToStructConverter(const InfoString &infoString, void *structure, ZoneScriptStrings &zoneScriptStrings, + MemoryManager *memory, IAssetLoadingManager *manager, const cspField_t *fields, + const size_t fieldCount) + : InfoStringToStructConverterBase(infoString, structure, zoneScriptStrings, memory), m_loading_manager(manager), m_fields(fields), + m_field_count(fieldCount) {} + +bool InfoStringToStructConverter::ConvertBaseField(const cspField_t &field, const std::string &value) { + switch (static_cast(field.iFieldType)) { + case CSPFT_STRING: + return ConvertString(value, field.iOffset); -bool InfoStringToStructConverter::ConvertBaseField(const cspField_t& field, const std::string& value) -{ - switch (static_cast(field.iFieldType)) - { - case CSPFT_STRING: - return ConvertString(value, field.iOffset); + case CSPFT_STRING_MAX_STRING_CHARS: + return ConvertStringBuffer(value, field.iOffset, 1024); - case CSPFT_STRING_MAX_STRING_CHARS: - return ConvertStringBuffer(value, field.iOffset, 1024); + case CSPFT_STRING_MAX_QPATH: + return ConvertStringBuffer(value, field.iOffset, 64); - case CSPFT_STRING_MAX_QPATH: - return ConvertStringBuffer(value, field.iOffset, 64); + case CSPFT_STRING_MAX_OSPATH: + return ConvertStringBuffer(value, field.iOffset, 256); - case CSPFT_STRING_MAX_OSPATH: - return ConvertStringBuffer(value, field.iOffset, 256); + case CSPFT_INT: + return ConvertInt(value, field.iOffset); - case CSPFT_INT: - return ConvertInt(value, field.iOffset); + case CSPFT_BOOL: + return ConvertBool(value, field.iOffset); - case CSPFT_BOOL: - return ConvertBool(value, field.iOffset); + case CSPFT_QBOOLEAN: + return ConvertQBoolean(value, field.iOffset); - case CSPFT_QBOOLEAN: - return ConvertQBoolean(value, field.iOffset); + case CSPFT_FLOAT: + return ConvertFloat(value, field.iOffset); - case CSPFT_FLOAT: - return ConvertFloat(value, field.iOffset); - - case CSPFT_MILLISECONDS: - return ConvertMilliseconds(value, field.iOffset); - - case CSPFT_FX: - { - if (value.empty()) - { - *reinterpret_cast(reinterpret_cast(m_structure) + field.iOffset) = nullptr; - return true; - } - - auto* fx = m_loading_manager->LoadDependency(ASSET_TYPE_FX, value); - - if (fx == nullptr) - { - std::cout << "Failed to load fx asset \"" << value << "\"" << std::endl; - return false; - } - - m_dependencies.emplace(fx); - *reinterpret_cast(reinterpret_cast(m_structure) + field.iOffset) = fx->m_ptr; - - return true; - } - - case CSPFT_XMODEL: - { - if (value.empty()) - { - *reinterpret_cast(reinterpret_cast(m_structure) + field.iOffset) = nullptr; - return true; - } - - auto* xmodel = m_loading_manager->LoadDependency(ASSET_TYPE_XMODEL, value); - - if (xmodel == nullptr) - { - std::cout << "Failed to load xmodel asset \"" << value << "\"" << std::endl; - return false; - } - - m_dependencies.emplace(xmodel); - *reinterpret_cast(reinterpret_cast(m_structure) + field.iOffset) = xmodel->m_ptr; - - return true; - } - - case CSPFT_MATERIAL: - { - if (value.empty()) - { - *reinterpret_cast(reinterpret_cast(m_structure) + field.iOffset) = nullptr; - return true; - } - - auto* material = m_loading_manager->LoadDependency(ASSET_TYPE_MATERIAL, value); - - if (material == nullptr) - { - std::cout << "Failed to load material asset \"" << value << "\"" << std::endl; - return false; - } - - m_dependencies.emplace(material); - *reinterpret_cast(reinterpret_cast(m_structure) + field.iOffset) = material->m_ptr; - - return true; - } - - case CSPFT_TRACER: - { - if (value.empty()) - { - *reinterpret_cast(reinterpret_cast(m_structure) + field.iOffset) = nullptr; - return true; - } - - auto* tracer = m_loading_manager->LoadDependency(ASSET_TYPE_TRACER, value); - - if (tracer == nullptr) - { - std::cout << "Failed to load tracer asset \"" << value << "\"" << std::endl; - return false; - } - - m_dependencies.emplace(tracer); - *reinterpret_cast(reinterpret_cast(m_structure) + field.iOffset) = tracer->m_ptr; - - return true; - } - - case CSPFT_MPH_TO_INCHES_PER_SEC: - { - char* endPtr; - *reinterpret_cast(reinterpret_cast(m_structure) + field.iOffset) = strtof(value.c_str(), &endPtr) * 17.6f; - - if (endPtr != &value[value.size()]) - { - std::cout << "Failed to parse value \"" << value << "\" as mph" << std::endl; - return false; - } - - return true; - } - - case CSPFT_PHYS_COLLMAP: - { - if (value.empty()) - { - *reinterpret_cast(reinterpret_cast(m_structure) + field.iOffset) = nullptr; - return true; - } - - auto* collmap = m_loading_manager->LoadDependency(ASSET_TYPE_PHYSCOLLMAP, value); - - if (collmap == nullptr) - { - std::cout << "Failed to load collmap asset \"" << value << "\"" << std::endl; - return false; - } - - m_dependencies.emplace(collmap); - *reinterpret_cast(reinterpret_cast(m_structure) + field.iOffset) = collmap->m_ptr; - - return true; - } - - case CSPFT_SOUND: - { - if (value.empty()) - { - *reinterpret_cast(reinterpret_cast(m_structure) + field.iOffset) = nullptr; - return true; - } - - auto* sound = m_loading_manager->LoadDependency(ASSET_TYPE_SOUND, value); - - if (sound == nullptr) - { - std::cout << "Failed to load sound asset \"" << value << "\"" << std::endl; - return false; - } - - m_dependencies.emplace(sound); - *reinterpret_cast(reinterpret_cast(m_structure) + field.iOffset) = sound->m_ptr; - - return true; - } - - case CSPFT_NUM_BASE_FIELD_TYPES: - default: - assert(false); - return false; + case CSPFT_MILLISECONDS: + return ConvertMilliseconds(value, field.iOffset); + + case CSPFT_FX: { + if (value.empty()) { + *reinterpret_cast(reinterpret_cast(m_structure) + field.iOffset) = nullptr; + return true; + } + + auto *fx = m_loading_manager->LoadDependency(ASSET_TYPE_FX, value); + + if (fx == nullptr) { + std::cout << "Failed to load fx asset \"" << value << "\"" << std::endl; + return false; + } + + m_dependencies.emplace(fx); + *reinterpret_cast(reinterpret_cast(m_structure) + field.iOffset) = fx->m_ptr; + + return true; + } + + case CSPFT_XMODEL: { + if (value.empty()) { + *reinterpret_cast(reinterpret_cast(m_structure) + field.iOffset) = nullptr; + return true; + } + + auto *xmodel = m_loading_manager->LoadDependency(ASSET_TYPE_XMODEL, value); + + if (xmodel == nullptr) { + std::cout << "Failed to load xmodel asset \"" << value << "\"" << std::endl; + return false; + } + + m_dependencies.emplace(xmodel); + *reinterpret_cast(reinterpret_cast(m_structure) + field.iOffset) = xmodel->m_ptr; + + return true; + } + + case CSPFT_MATERIAL: { + if (value.empty()) { + *reinterpret_cast(reinterpret_cast(m_structure) + field.iOffset) = nullptr; + return true; + } + + auto *material = m_loading_manager->LoadDependency(ASSET_TYPE_MATERIAL, value); + + if (material == nullptr) { + std::cout << "Failed to load material asset \"" << value << "\"" << std::endl; + return false; + } + + m_dependencies.emplace(material); + *reinterpret_cast(reinterpret_cast(m_structure) + field.iOffset) = material->m_ptr; + + return true; + } + + case CSPFT_TRACER: { + if (value.empty()) { + *reinterpret_cast(reinterpret_cast(m_structure) + field.iOffset) = nullptr; + return true; } -} -bool InfoStringToStructConverter::Convert() -{ - for (auto fieldIndex = 0u; fieldIndex < m_field_count; fieldIndex++) - { - const auto& field = m_fields[fieldIndex]; - assert(field.iFieldType >= 0); - - auto foundValue = false; - const auto& value = m_info_string.GetValueForKey(std::string(field.szName), &foundValue); - - if (foundValue) - { - if (field.iFieldType < CSPFT_NUM_BASE_FIELD_TYPES) - { - if (!ConvertBaseField(field, value)) - return false; - } - else - { - if (!ConvertExtensionField(field, value)) - return false; - } - } + auto *tracer = m_loading_manager->LoadDependency(ASSET_TYPE_TRACER, value); + + if (tracer == nullptr) { + std::cout << "Failed to load tracer asset \"" << value << "\"" << std::endl; + return false; + } + + m_dependencies.emplace(tracer); + *reinterpret_cast(reinterpret_cast(m_structure) + field.iOffset) = tracer->m_ptr; + + return true; + } + + case CSPFT_MPH_TO_INCHES_PER_SEC: { + char *endPtr; + *reinterpret_cast(reinterpret_cast(m_structure) + field.iOffset) = strtof(value.c_str(), &endPtr) * 17.6f; + + if (endPtr != &value[value.size()]) { + std::cout << "Failed to parse value \"" << value << "\" as mph" << std::endl; + return false; + } + + return true; + } + + case CSPFT_PHYS_COLLMAP: { + if (value.empty()) { + *reinterpret_cast(reinterpret_cast(m_structure) + field.iOffset) = nullptr; + return true; + } + + auto *collmap = m_loading_manager->LoadDependency(ASSET_TYPE_PHYSCOLLMAP, value); + + if (collmap == nullptr) { + std::cout << "Failed to load collmap asset \"" << value << "\"" << std::endl; + return false; } + m_dependencies.emplace(collmap); + *reinterpret_cast(reinterpret_cast(m_structure) + field.iOffset) = collmap->m_ptr; + + return true; + } + + case CSPFT_SOUND: { + if (value.empty()) { + *reinterpret_cast(reinterpret_cast(m_structure) + field.iOffset) = nullptr; + return true; + } + + auto *sound = m_loading_manager->LoadDependency(ASSET_TYPE_SOUND, value); + + if (sound == nullptr) { + std::cout << "Failed to load sound asset \"" << value << "\"" << std::endl; + return false; + } + + m_dependencies.emplace(sound); + *reinterpret_cast(reinterpret_cast(m_structure) + field.iOffset) = sound->m_ptr; + return true; + } + + case CSPFT_NUM_BASE_FIELD_TYPES: + default: + assert(false); + return false; + } +} + +bool InfoStringToStructConverter::Convert() { + for (auto fieldIndex = 0u; fieldIndex < m_field_count; fieldIndex++) { + const auto &field = m_fields[fieldIndex]; + assert(field.iFieldType >= 0); + + auto foundValue = false; + const auto &value = m_info_string.GetValueForKey(std::string(field.szName), &foundValue); + + if (foundValue) { + if (field.iFieldType < CSPFT_NUM_BASE_FIELD_TYPES) { + if (!ConvertBaseField(field, value)) + return false; + } else { + if (!ConvertExtensionField(field, value)) + return false; + } + } + } + + return true; } diff --git a/src/ObjLoading/Game/IW4/InfoString/InfoStringToStructConverter.h b/src/ObjLoading/Game/IW4/InfoString/InfoStringToStructConverter.h index 672af897b..1eb63d1c3 100644 --- a/src/ObjLoading/Game/IW4/InfoString/InfoStringToStructConverter.h +++ b/src/ObjLoading/Game/IW4/InfoString/InfoStringToStructConverter.h @@ -1,23 +1,21 @@ #pragma once #include "AssetLoading/IAssetLoadingManager.h" -#include "InfoString/InfoStringToStructConverterBase.h" #include "Game/IW4/IW4.h" +#include "InfoString/InfoStringToStructConverterBase.h" -namespace IW4 -{ - class InfoStringToStructConverter : public InfoStringToStructConverterBase - { - protected: - IAssetLoadingManager* m_loading_manager; - const cspField_t* m_fields; - size_t m_field_count; +namespace IW4 { +class InfoStringToStructConverter : public InfoStringToStructConverterBase { +protected: + IAssetLoadingManager *m_loading_manager; + const cspField_t *m_fields; + size_t m_field_count; - virtual bool ConvertExtensionField(const cspField_t& field, const std::string& value) = 0; - bool ConvertBaseField(const cspField_t& field, const std::string& value); + virtual bool ConvertExtensionField(const cspField_t &field, const std::string &value) = 0; + bool ConvertBaseField(const cspField_t &field, const std::string &value); - public: - InfoStringToStructConverter(const InfoString& infoString, void* structure, ZoneScriptStrings& zoneScriptStrings, MemoryManager* memory, IAssetLoadingManager* manager, const cspField_t* fields, - size_t fieldCount); - bool Convert() override; - }; -} \ No newline at end of file +public: + InfoStringToStructConverter(const InfoString &infoString, void *structure, ZoneScriptStrings &zoneScriptStrings, MemoryManager *memory, + IAssetLoadingManager *manager, const cspField_t *fields, size_t fieldCount); + bool Convert() override; +}; +} // namespace IW4 \ No newline at end of file diff --git a/src/ObjLoading/Game/IW4/Menu/MenuConversionZoneStateIW4.cpp b/src/ObjLoading/Game/IW4/Menu/MenuConversionZoneStateIW4.cpp index 3868e3f04..97c9ce481 100644 --- a/src/ObjLoading/Game/IW4/Menu/MenuConversionZoneStateIW4.cpp +++ b/src/ObjLoading/Game/IW4/Menu/MenuConversionZoneStateIW4.cpp @@ -4,118 +4,101 @@ using namespace IW4; -MenuConversionZoneState::MenuConversionZoneState() - : m_zone(nullptr), - m_supporting_data(nullptr) -{ -} +MenuConversionZoneState::MenuConversionZoneState() : m_zone(nullptr), m_supporting_data(nullptr) {} -void MenuConversionZoneState::SetZone(Zone* zone) -{ - auto* memory = zone->GetMemory(); +void MenuConversionZoneState::SetZone(Zone *zone) { + auto *memory = zone->GetMemory(); - m_zone = zone; - m_supporting_data = memory->Create(); - memset(m_supporting_data, 0, sizeof(ExpressionSupportingData)); + m_zone = zone; + m_supporting_data = memory->Create(); + memset(m_supporting_data, 0, sizeof(ExpressionSupportingData)); } -Statement_s* MenuConversionZoneState::FindFunction(const std::string& functionName) -{ - const auto foundFunction = m_function_by_name.find(functionName); +Statement_s *MenuConversionZoneState::FindFunction(const std::string &functionName) { + const auto foundFunction = m_function_by_name.find(functionName); - if (foundFunction != m_function_by_name.end()) - return foundFunction->second; + if (foundFunction != m_function_by_name.end()) + return foundFunction->second; - return nullptr; + return nullptr; } -Statement_s* MenuConversionZoneState::AddFunction(const std::string& functionName, Statement_s* function) -{ - m_functions.push_back(function); - m_function_by_name.emplace(std::make_pair(functionName, function)); +Statement_s *MenuConversionZoneState::AddFunction(const std::string &functionName, Statement_s *function) { + m_functions.push_back(function); + m_function_by_name.emplace(std::make_pair(functionName, function)); - return function; + return function; } -size_t MenuConversionZoneState::AddStaticDvar(const std::string& dvarName) -{ - const auto foundDvar = m_dvars_by_name.find(dvarName); +size_t MenuConversionZoneState::AddStaticDvar(const std::string &dvarName) { + const auto foundDvar = m_dvars_by_name.find(dvarName); - if (foundDvar != m_dvars_by_name.end()) - return foundDvar->second; + if (foundDvar != m_dvars_by_name.end()) + return foundDvar->second; - auto* memory = m_zone->GetMemory(); - auto* staticDvar = static_cast(memory->Alloc(sizeof(StaticDvar))); + auto *memory = m_zone->GetMemory(); + auto *staticDvar = static_cast(memory->Alloc(sizeof(StaticDvar))); - staticDvar->dvarName = memory->Dup(dvarName.c_str()); - staticDvar->dvar = nullptr; + staticDvar->dvarName = memory->Dup(dvarName.c_str()); + staticDvar->dvar = nullptr; - const auto staticDvarIndex = m_static_dvars.size(); - m_static_dvars.push_back(staticDvar); - m_dvars_by_name.emplace(std::make_pair(dvarName, staticDvarIndex)); + const auto staticDvarIndex = m_static_dvars.size(); + m_static_dvars.push_back(staticDvar); + m_dvars_by_name.emplace(std::make_pair(dvarName, staticDvarIndex)); - return staticDvarIndex; + return staticDvarIndex; } -const char* MenuConversionZoneState::AddString(const std::string& str) -{ - const auto foundString = m_strings_by_value.find(str); +const char *MenuConversionZoneState::AddString(const std::string &str) { + const auto foundString = m_strings_by_value.find(str); - if (foundString != m_strings_by_value.end()) - return foundString->second; + if (foundString != m_strings_by_value.end()) + return foundString->second; - auto* memory = m_zone->GetMemory(); - const auto* strDuped = memory->Dup(str.c_str()); + auto *memory = m_zone->GetMemory(); + const auto *strDuped = memory->Dup(str.c_str()); - m_strings.push_back(strDuped); - m_strings_by_value.emplace(std::make_pair(str, strDuped)); + m_strings.push_back(strDuped); + m_strings_by_value.emplace(std::make_pair(str, strDuped)); - return strDuped; + return strDuped; } -void MenuConversionZoneState::AddLoadedFile(std::string loadedFileName, std::vector*> menusOfFile) -{ - m_menus_by_filename.emplace(std::make_pair(std::move(loadedFileName), std::move(menusOfFile))); +void MenuConversionZoneState::AddLoadedFile(std::string loadedFileName, std::vector *> menusOfFile) { + m_menus_by_filename.emplace(std::make_pair(std::move(loadedFileName), std::move(menusOfFile))); } -void MenuConversionZoneState::FinalizeSupportingData() const -{ - auto* memory = m_zone->GetMemory(); - - m_supporting_data->uifunctions.totalFunctions = static_cast(m_functions.size()); - m_supporting_data->staticDvarList.numStaticDvars = static_cast(m_static_dvars.size()); - m_supporting_data->uiStrings.totalStrings = static_cast(m_strings.size()); - - if (m_supporting_data->uifunctions.functions) - memory->Free(m_supporting_data->uifunctions.functions); - - if (m_supporting_data->staticDvarList.staticDvars) - memory->Free(m_supporting_data->staticDvarList.staticDvars); - - if (m_supporting_data->uiStrings.strings) - memory->Free(m_supporting_data->uiStrings.strings); - - if (!m_functions.empty()) - { - m_supporting_data->uifunctions.functions = static_cast(memory->Alloc(sizeof(void*) * m_functions.size())); - memcpy(m_supporting_data->uifunctions.functions, &m_functions[0], sizeof(void*) * m_functions.size()); - } - else - m_supporting_data->uifunctions.functions = nullptr; - - if (!m_static_dvars.empty()) - { - m_supporting_data->staticDvarList.staticDvars = static_cast(memory->Alloc(sizeof(void*) * m_static_dvars.size())); - memcpy(m_supporting_data->staticDvarList.staticDvars, &m_static_dvars[0], sizeof(void*) * m_static_dvars.size()); - } - else - m_supporting_data->staticDvarList.staticDvars = nullptr; - - if (!m_strings.empty()) - { - m_supporting_data->uiStrings.strings = static_cast(memory->Alloc(sizeof(void*) * m_strings.size())); - memcpy(m_supporting_data->uiStrings.strings, &m_strings[0], sizeof(void*) * m_strings.size()); - } - else - m_supporting_data->uiStrings.strings = nullptr; +void MenuConversionZoneState::FinalizeSupportingData() const { + auto *memory = m_zone->GetMemory(); + + m_supporting_data->uifunctions.totalFunctions = static_cast(m_functions.size()); + m_supporting_data->staticDvarList.numStaticDvars = static_cast(m_static_dvars.size()); + m_supporting_data->uiStrings.totalStrings = static_cast(m_strings.size()); + + if (m_supporting_data->uifunctions.functions) + memory->Free(m_supporting_data->uifunctions.functions); + + if (m_supporting_data->staticDvarList.staticDvars) + memory->Free(m_supporting_data->staticDvarList.staticDvars); + + if (m_supporting_data->uiStrings.strings) + memory->Free(m_supporting_data->uiStrings.strings); + + if (!m_functions.empty()) { + m_supporting_data->uifunctions.functions = static_cast(memory->Alloc(sizeof(void *) * m_functions.size())); + memcpy(m_supporting_data->uifunctions.functions, &m_functions[0], sizeof(void *) * m_functions.size()); + } else + m_supporting_data->uifunctions.functions = nullptr; + + if (!m_static_dvars.empty()) { + m_supporting_data->staticDvarList.staticDvars = static_cast(memory->Alloc(sizeof(void *) * m_static_dvars.size())); + memcpy(m_supporting_data->staticDvarList.staticDvars, &m_static_dvars[0], sizeof(void *) * m_static_dvars.size()); + } else + m_supporting_data->staticDvarList.staticDvars = nullptr; + + if (!m_strings.empty()) { + m_supporting_data->uiStrings.strings = static_cast(memory->Alloc(sizeof(void *) * m_strings.size())); + memcpy(m_supporting_data->uiStrings.strings, &m_strings[0], sizeof(void *) * m_strings.size()); + } else + m_supporting_data->uiStrings.strings = nullptr; } diff --git a/src/ObjLoading/Game/IW4/Menu/MenuConversionZoneStateIW4.h b/src/ObjLoading/Game/IW4/Menu/MenuConversionZoneStateIW4.h index bb4a5da9c..45b5828e6 100644 --- a/src/ObjLoading/Game/IW4/Menu/MenuConversionZoneStateIW4.h +++ b/src/ObjLoading/Game/IW4/Menu/MenuConversionZoneStateIW4.h @@ -5,35 +5,33 @@ #include "AssetLoading/IZoneAssetLoaderState.h" #include "Game/IW4/IW4.h" -namespace IW4 -{ - class MenuConversionZoneState final : public IZoneAssetLoaderState - { - Zone* m_zone; - std::vector m_functions; - std::map m_function_by_name; +namespace IW4 { +class MenuConversionZoneState final : public IZoneAssetLoaderState { + Zone *m_zone; + std::vector m_functions; + std::map m_function_by_name; - std::vector m_static_dvars; - std::map m_dvars_by_name; + std::vector m_static_dvars; + std::map m_dvars_by_name; - std::vector m_strings; - std::map m_strings_by_value; + std::vector m_strings; + std::map m_strings_by_value; - public: - std::map*>> m_menus_by_filename; - ExpressionSupportingData* m_supporting_data; +public: + std::map *>> m_menus_by_filename; + ExpressionSupportingData *m_supporting_data; - MenuConversionZoneState(); - void SetZone(Zone* zone) override; + MenuConversionZoneState(); + void SetZone(Zone *zone) override; - Statement_s* FindFunction(const std::string& functionName); + Statement_s *FindFunction(const std::string &functionName); - Statement_s* AddFunction(const std::string& functionName, Statement_s* function); - size_t AddStaticDvar(const std::string& dvarName); - const char* AddString(const std::string& str); + Statement_s *AddFunction(const std::string &functionName, Statement_s *function); + size_t AddStaticDvar(const std::string &dvarName); + const char *AddString(const std::string &str); - void AddLoadedFile(std::string loadedFileName, std::vector*> menusOfFile); + void AddLoadedFile(std::string loadedFileName, std::vector *> menusOfFile); - void FinalizeSupportingData() const; - }; -} + void FinalizeSupportingData() const; +}; +} // namespace IW4 diff --git a/src/ObjLoading/Game/IW4/Menu/MenuConverterIW4.cpp b/src/ObjLoading/Game/IW4/Menu/MenuConverterIW4.cpp index 24f90347f..7b8e47061 100644 --- a/src/ObjLoading/Game/IW4/Menu/MenuConverterIW4.cpp +++ b/src/ObjLoading/Game/IW4/Menu/MenuConverterIW4.cpp @@ -4,1141 +4,1019 @@ #include #include -#include "MenuConversionZoneStateIW4.h" -#include "Utils/ClassUtils.h" #include "Menu/AbstractMenuConverter.h" -#include "Parsing/Menu/MenuAssetZoneState.h" +#include "MenuConversionZoneStateIW4.h" #include "Parsing/Menu/Domain/EventHandler/CommonEventHandlerCondition.h" #include "Parsing/Menu/Domain/EventHandler/CommonEventHandlerScript.h" #include "Parsing/Menu/Domain/EventHandler/CommonEventHandlerSetLocalVar.h" #include "Parsing/Menu/Domain/Expression/CommonExpressionBaseFunctionCall.h" #include "Parsing/Menu/Domain/Expression/CommonExpressionCustomFunctionCall.h" +#include "Parsing/Menu/MenuAssetZoneState.h" #include "Parsing/Simple/Expression/SimpleExpressionBinaryOperation.h" #include "Parsing/Simple/Expression/SimpleExpressionConditionalOperator.h" #include "Parsing/Simple/Expression/SimpleExpressionUnaryOperation.h" +#include "Utils/ClassUtils.h" using namespace IW4; using namespace menu; -namespace IW4 -{ - class MenuConverterImpl : public AbstractMenuConverter - { - MenuConversionZoneState* m_conversion_zone_state; - MenuAssetZoneState* m_parsing_zone_state; - - _NODISCARD static rectDef_s ConvertRectDef(const CommonRect& rect) - { - return rectDef_s{ - static_cast(rect.x), - static_cast(rect.y), - static_cast(rect.w), - static_cast(rect.h), - static_cast(rect.horizontalAlign), - static_cast(rect.verticalAlign) - }; - } - - _NODISCARD static rectDef_s ConvertRectDefRelativeTo(const CommonRect& rect, const CommonRect& rectRelativeTo) - { - return rectDef_s{ - static_cast(rectRelativeTo.x + rect.x), - static_cast(rectRelativeTo.y + rect.y), - static_cast(rect.w), - static_cast(rect.h), - static_cast(rect.horizontalAlign), - static_cast(rect.verticalAlign) - }; - } - - static void ConvertColor(float (&output)[4], const CommonColor& input) - { - output[0] = static_cast(input.r); - output[1] = static_cast(input.g); - output[2] = static_cast(input.b); - output[3] = static_cast(input.a); - } - - static void ApplyFlag(int& flags, const bool shouldApply, const int flagValue) - { - if (!shouldApply) - return; - - flags |= flagValue; - } - - static int ConvertItemType(const int input) - { - return input; - } - - static int ConvertTextFont(const int input) - { - return input; - } - - _NODISCARD Material* ConvertMaterial(const std::string& materialName, const CommonMenuDef* menu, const CommonItemDef* item = nullptr) const - { - if (materialName.empty()) - return nullptr; - - auto* materialDependency = m_manager->LoadDependency(ASSET_TYPE_MATERIAL, materialName); - if (!materialDependency) - throw MenuConversionException("Failed to load material \"" + materialName + "\"", menu, item); - - return static_cast(materialDependency->m_ptr); - } - - _NODISCARD snd_alias_list_t* ConvertSound(const std::string& soundName, const CommonMenuDef* menu, const CommonItemDef* item = nullptr) const - { - if (soundName.empty()) - return nullptr; - - auto* soundDependency = m_manager->LoadDependency(ASSET_TYPE_SOUND, soundName); - if (!soundDependency) - throw MenuConversionException("Failed to load sound \"" + soundName + "\"", menu, item); - - return static_cast(soundDependency->m_ptr); - } - - bool HandleStaticDvarFunctionCall(Statement_s* gameStatement, std::vector& entries, const CommonExpressionBaseFunctionCall* functionCall, const int targetFunctionIndex) const - { - if (functionCall->m_args.size() != 1) - return false; - - const auto* dvarNameExpression = functionCall->m_args[0].get(); - if (!dvarNameExpression->IsStatic()) - return false; - - const auto staticDvarNameExpressionValue = dvarNameExpression->EvaluateStatic(); - if (staticDvarNameExpressionValue.m_type != SimpleExpressionValue::Type::STRING) - return false; - - expressionEntry functionEntry{}; - functionEntry.type = EET_OPERATOR; - functionEntry.data.op = targetFunctionIndex; - entries.emplace_back(functionEntry); - - expressionEntry staticDvarIndexEntry{}; - staticDvarIndexEntry.type = EET_OPERAND; - staticDvarIndexEntry.data.operand.dataType = VAL_INT; - staticDvarIndexEntry.data.operand.internals.intVal = static_cast(m_conversion_zone_state->AddStaticDvar(*staticDvarNameExpressionValue.m_string_value)); - entries.emplace_back(staticDvarIndexEntry); - - expressionEntry parenRight{}; - parenRight.type = EET_OPERATOR; - parenRight.data.op = OP_RIGHTPAREN; - entries.emplace_back(parenRight); - - gameStatement->supportingData = m_conversion_zone_state->m_supporting_data; - - return true; - } - - bool HandleSpecialBaseFunctionCall(Statement_s* gameStatement, std::vector& entries, const CommonExpressionBaseFunctionCall* functionCall, const CommonMenuDef* menu, - const CommonItemDef* item) const - { - switch (functionCall->m_function_index) - { - case EXP_FUNC_DVAR_INT: - return HandleStaticDvarFunctionCall(gameStatement, entries, functionCall, EXP_FUNC_STATIC_DVAR_INT); - case EXP_FUNC_DVAR_BOOL: - return HandleStaticDvarFunctionCall(gameStatement, entries, functionCall, EXP_FUNC_STATIC_DVAR_BOOL); - case EXP_FUNC_DVAR_FLOAT: - return HandleStaticDvarFunctionCall(gameStatement, entries, functionCall, EXP_FUNC_STATIC_DVAR_FLOAT); - case EXP_FUNC_DVAR_STRING: - return HandleStaticDvarFunctionCall(gameStatement, entries, functionCall, EXP_FUNC_STATIC_DVAR_STRING); - default: - break; - } - - return false; - } - - void ConvertExpressionEntryBaseFunctionCall(Statement_s* gameStatement, std::vector& entries, const CommonExpressionBaseFunctionCall* functionCall, const CommonMenuDef* menu, - const CommonItemDef* item) const - { - if (!HandleSpecialBaseFunctionCall(gameStatement, entries, functionCall, menu, item)) - { - expressionEntry functionEntry{}; - functionEntry.type = EET_OPERATOR; - functionEntry.data.op = static_cast(functionCall->m_function_index); - entries.emplace_back(functionEntry); - - auto firstArg = true; - for (const auto& arg : functionCall->m_args) - { - if (!firstArg) - { - expressionEntry argSeparator{}; - argSeparator.type = EET_OPERATOR; - argSeparator.data.op = OP_COMMA; - entries.emplace_back(argSeparator); - } - else - firstArg = false; - - ConvertExpressionEntry(gameStatement, entries, arg.get(), menu, item); - } - - expressionEntry parenRight{}; - parenRight.type = EET_OPERATOR; - parenRight.data.op = OP_RIGHTPAREN; - entries.emplace_back(parenRight); - } - } - - void ConvertExpressionEntryCustomFunctionCall(Statement_s* gameStatement, std::vector& entries, const CommonExpressionCustomFunctionCall* functionCall, - const CommonMenuDef* menu, - const CommonItemDef* item) const - { - Statement_s* functionStatement = m_conversion_zone_state->FindFunction(functionCall->m_function_name); - - if (functionStatement == nullptr) - { - // Function was not converted yet: Convert it now - const auto foundCommonFunction = m_parsing_zone_state->m_functions_by_name.find(functionCall->m_function_name); - - if (foundCommonFunction == m_parsing_zone_state->m_functions_by_name.end()) - throw MenuConversionException("Failed to find definition for custom function \"" + functionCall->m_function_name + "\"", menu, item); - - functionStatement = ConvertExpression(foundCommonFunction->second->m_value.get(), menu, item); - functionStatement = m_conversion_zone_state->AddFunction(foundCommonFunction->second->m_name, functionStatement); - } - - expressionEntry functionEntry{}; - functionEntry.type = EET_OPERAND; - functionEntry.data.operand.dataType = VAL_FUNCTION; - functionEntry.data.operand.internals.function = functionStatement; - entries.emplace_back(functionEntry); - - // Statement uses custom function so it needs supporting data - gameStatement->supportingData = m_conversion_zone_state->m_supporting_data; - } - - constexpr static expressionOperatorType_e UNARY_OPERATION_MAPPING[static_cast(SimpleUnaryOperationId::COUNT)] - { - OP_NOT, - OP_BITWISENOT, - OP_SUBTRACT - }; - - bool IsOperation(const ISimpleExpression* expression) const - { - if (!m_disable_optimizations && expression->IsStatic()) - return false; - - return dynamic_cast(expression) || dynamic_cast(expression); - } - - void ConvertExpressionEntryUnaryOperation(Statement_s* gameStatement, std::vector& entries, const SimpleExpressionUnaryOperation* unaryOperation, const CommonMenuDef* menu, - const CommonItemDef* item) const - { - assert(static_cast(unaryOperation->m_operation_type->m_id) < static_cast(SimpleUnaryOperationId::COUNT)); - expressionEntry operation{}; - operation.type = EET_OPERATOR; - operation.data.op = UNARY_OPERATION_MAPPING[static_cast(unaryOperation->m_operation_type->m_id)]; - entries.emplace_back(operation); - - if (IsOperation(unaryOperation->m_operand.get())) - { - expressionEntry parenLeft{}; - parenLeft.type = EET_OPERATOR; - parenLeft.data.op = OP_LEFTPAREN; - entries.emplace_back(parenLeft); - - ConvertExpressionEntry(gameStatement, entries, unaryOperation->m_operand.get(), menu, item); - - expressionEntry parenRight{}; - parenRight.type = EET_OPERATOR; - parenRight.data.op = OP_RIGHTPAREN; - entries.emplace_back(parenRight); - } - else - ConvertExpressionEntry(gameStatement, entries, unaryOperation->m_operand.get(), menu, item); - } - - constexpr static expressionOperatorType_e BINARY_OPERATION_MAPPING[static_cast(SimpleBinaryOperationId::COUNT)] - { - OP_ADD, - OP_SUBTRACT, - OP_MULTIPLY, - OP_DIVIDE, - OP_MODULUS, - OP_BITWISEAND, - OP_BITWISEOR, - OP_BITSHIFTLEFT, - OP_BITSHIFTRIGHT, - OP_GREATERTHAN, - OP_GREATERTHANEQUALTO, - OP_LESSTHAN, - OP_LESSTHANEQUALTO, - OP_EQUALS, - OP_NOTEQUAL, - OP_AND, - OP_OR - }; - - void ConvertExpressionEntryBinaryOperation(Statement_s* gameStatement, std::vector& entries, const SimpleExpressionBinaryOperation* binaryOperation, const CommonMenuDef* menu, - const CommonItemDef* item) const - { - // Game needs all nested operations to have parenthesis - if (IsOperation(binaryOperation->m_operand1.get())) - { - expressionEntry parenLeft{}; - parenLeft.type = EET_OPERATOR; - parenLeft.data.op = OP_LEFTPAREN; - entries.emplace_back(parenLeft); - - ConvertExpressionEntry(gameStatement, entries, binaryOperation->m_operand1.get(), menu, item); - - expressionEntry parenRight{}; - parenRight.type = EET_OPERATOR; - parenRight.data.op = OP_RIGHTPAREN; - entries.emplace_back(parenRight); - } - else - ConvertExpressionEntry(gameStatement, entries, binaryOperation->m_operand1.get(), menu, item); - - assert(static_cast(binaryOperation->m_operation_type->m_id) < static_cast(SimpleBinaryOperationId::COUNT)); - expressionEntry operation{}; - operation.type = EET_OPERATOR; - operation.data.op = BINARY_OPERATION_MAPPING[static_cast(binaryOperation->m_operation_type->m_id)]; - entries.emplace_back(operation); - - // Game needs all nested operations to have parenthesis - if (IsOperation(binaryOperation->m_operand2.get())) - { - expressionEntry parenLeft{}; - parenLeft.type = EET_OPERATOR; - parenLeft.data.op = OP_LEFTPAREN; - entries.emplace_back(parenLeft); - - ConvertExpressionEntry(gameStatement, entries, binaryOperation->m_operand2.get(), menu, item); - - expressionEntry parenRight{}; - parenRight.type = EET_OPERATOR; - parenRight.data.op = OP_RIGHTPAREN; - entries.emplace_back(parenRight); - } - else - ConvertExpressionEntry(gameStatement, entries, binaryOperation->m_operand2.get(), menu, item); - } - - void ConvertExpressionEntryExpressionValue(std::vector& entries, const SimpleExpressionValue* expressionValue) const - { - expressionEntry entry{}; - entry.type = EET_OPERAND; - - if (expressionValue->m_type == SimpleExpressionValue::Type::INT) - { - entry.data.operand.dataType = VAL_INT; - entry.data.operand.internals.intVal = expressionValue->m_int_value; - } - else if (expressionValue->m_type == SimpleExpressionValue::Type::DOUBLE) - { - entry.data.operand.dataType = VAL_FLOAT; - entry.data.operand.internals.floatVal = static_cast(expressionValue->m_double_value); - } - else if (expressionValue->m_type == SimpleExpressionValue::Type::STRING) - { - entry.data.operand.dataType = VAL_STRING; - entry.data.operand.internals.stringVal.string = m_conversion_zone_state->AddString(*expressionValue->m_string_value); - } - - entries.emplace_back(entry); - } - - void ConvertExpressionEntry(Statement_s* gameStatement, std::vector& entries, const ISimpleExpression* expression, const CommonMenuDef* menu, const CommonItemDef* item) const - { - if (!m_disable_optimizations && expression->IsStatic()) - { - const auto expressionStaticValue = expression->EvaluateStatic(); - ConvertExpressionEntryExpressionValue(entries, &expressionStaticValue); - } - else if (const auto* expressionValue = dynamic_cast(expression)) - { - ConvertExpressionEntryExpressionValue(entries, expressionValue); - } - else if (const auto* binaryOperation = dynamic_cast(expression)) - { - ConvertExpressionEntryBinaryOperation(gameStatement, entries, binaryOperation, menu, item); - } - else if (const auto* unaryOperation = dynamic_cast(expression)) - { - ConvertExpressionEntryUnaryOperation(gameStatement, entries, unaryOperation, menu, item); - } - else if (const auto* baseFunctionCall = dynamic_cast(expression)) - { - ConvertExpressionEntryBaseFunctionCall(gameStatement, entries, baseFunctionCall, menu, item); - } - else if (const auto* customFunctionCall = dynamic_cast(expression)) - { - ConvertExpressionEntryCustomFunctionCall(gameStatement, entries, customFunctionCall, menu, item); - } - else if (dynamic_cast(expression)) - { - throw MenuConversionException("Cannot use conditional expression in menu expressions", menu, item); - } - else - { - assert(false); - throw MenuConversionException("Unknown expression entry type in menu expressions", menu, item); - } - } - - _NODISCARD Statement_s* ConvertExpression(const ISimpleExpression* expression, const CommonMenuDef* menu, const CommonItemDef* item = nullptr) const - { - if (!expression) - return nullptr; +namespace IW4 { +class MenuConverterImpl : public AbstractMenuConverter { + MenuConversionZoneState *m_conversion_zone_state; + MenuAssetZoneState *m_parsing_zone_state; + + _NODISCARD static rectDef_s ConvertRectDef(const CommonRect &rect) { + return rectDef_s{static_cast(rect.x), + static_cast(rect.y), + static_cast(rect.w), + static_cast(rect.h), + static_cast(rect.horizontalAlign), + static_cast(rect.verticalAlign)}; + } + + _NODISCARD static rectDef_s ConvertRectDefRelativeTo(const CommonRect &rect, const CommonRect &rectRelativeTo) { + return rectDef_s{ + static_cast(rectRelativeTo.x + rect.x), static_cast(rectRelativeTo.y + rect.y), static_cast(rect.w), static_cast(rect.h), + static_cast(rect.horizontalAlign), static_cast(rect.verticalAlign)}; + } + + static void ConvertColor(float (&output)[4], const CommonColor &input) { + output[0] = static_cast(input.r); + output[1] = static_cast(input.g); + output[2] = static_cast(input.b); + output[3] = static_cast(input.a); + } + + static void ApplyFlag(int &flags, const bool shouldApply, const int flagValue) { + if (!shouldApply) + return; + + flags |= flagValue; + } + + static int ConvertItemType(const int input) { return input; } + + static int ConvertTextFont(const int input) { return input; } + + _NODISCARD Material *ConvertMaterial(const std::string &materialName, const CommonMenuDef *menu, const CommonItemDef *item = nullptr) const { + if (materialName.empty()) + return nullptr; + + auto *materialDependency = m_manager->LoadDependency(ASSET_TYPE_MATERIAL, materialName); + if (!materialDependency) + throw MenuConversionException("Failed to load material \"" + materialName + "\"", menu, item); + + return static_cast(materialDependency->m_ptr); + } + + _NODISCARD snd_alias_list_t *ConvertSound(const std::string &soundName, const CommonMenuDef *menu, const CommonItemDef *item = nullptr) const { + if (soundName.empty()) + return nullptr; + + auto *soundDependency = m_manager->LoadDependency(ASSET_TYPE_SOUND, soundName); + if (!soundDependency) + throw MenuConversionException("Failed to load sound \"" + soundName + "\"", menu, item); + + return static_cast(soundDependency->m_ptr); + } + + bool HandleStaticDvarFunctionCall(Statement_s *gameStatement, std::vector &entries, const CommonExpressionBaseFunctionCall *functionCall, + const int targetFunctionIndex) const { + if (functionCall->m_args.size() != 1) + return false; + + const auto *dvarNameExpression = functionCall->m_args[0].get(); + if (!dvarNameExpression->IsStatic()) + return false; + + const auto staticDvarNameExpressionValue = dvarNameExpression->EvaluateStatic(); + if (staticDvarNameExpressionValue.m_type != SimpleExpressionValue::Type::STRING) + return false; + + expressionEntry functionEntry{}; + functionEntry.type = EET_OPERATOR; + functionEntry.data.op = targetFunctionIndex; + entries.emplace_back(functionEntry); + + expressionEntry staticDvarIndexEntry{}; + staticDvarIndexEntry.type = EET_OPERAND; + staticDvarIndexEntry.data.operand.dataType = VAL_INT; + staticDvarIndexEntry.data.operand.internals.intVal = + static_cast(m_conversion_zone_state->AddStaticDvar(*staticDvarNameExpressionValue.m_string_value)); + entries.emplace_back(staticDvarIndexEntry); + + expressionEntry parenRight{}; + parenRight.type = EET_OPERATOR; + parenRight.data.op = OP_RIGHTPAREN; + entries.emplace_back(parenRight); + + gameStatement->supportingData = m_conversion_zone_state->m_supporting_data; + + return true; + } + + bool HandleSpecialBaseFunctionCall(Statement_s *gameStatement, std::vector &entries, const CommonExpressionBaseFunctionCall *functionCall, + const CommonMenuDef *menu, const CommonItemDef *item) const { + switch (functionCall->m_function_index) { + case EXP_FUNC_DVAR_INT: + return HandleStaticDvarFunctionCall(gameStatement, entries, functionCall, EXP_FUNC_STATIC_DVAR_INT); + case EXP_FUNC_DVAR_BOOL: + return HandleStaticDvarFunctionCall(gameStatement, entries, functionCall, EXP_FUNC_STATIC_DVAR_BOOL); + case EXP_FUNC_DVAR_FLOAT: + return HandleStaticDvarFunctionCall(gameStatement, entries, functionCall, EXP_FUNC_STATIC_DVAR_FLOAT); + case EXP_FUNC_DVAR_STRING: + return HandleStaticDvarFunctionCall(gameStatement, entries, functionCall, EXP_FUNC_STATIC_DVAR_STRING); + default: + break; + } - auto* statement = m_memory->Create(); - statement->lastResult = Operand{}; - statement->lastExecuteTime = 0; - statement->supportingData = nullptr; // Supporting data is set upon using it + return false; + } + + void ConvertExpressionEntryBaseFunctionCall(Statement_s *gameStatement, std::vector &entries, + const CommonExpressionBaseFunctionCall *functionCall, const CommonMenuDef *menu, + const CommonItemDef *item) const { + if (!HandleSpecialBaseFunctionCall(gameStatement, entries, functionCall, menu, item)) { + expressionEntry functionEntry{}; + functionEntry.type = EET_OPERATOR; + functionEntry.data.op = static_cast(functionCall->m_function_index); + entries.emplace_back(functionEntry); + + auto firstArg = true; + for (const auto &arg : functionCall->m_args) { + if (!firstArg) { + expressionEntry argSeparator{}; + argSeparator.type = EET_OPERATOR; + argSeparator.data.op = OP_COMMA; + entries.emplace_back(argSeparator); + } else + firstArg = false; + + ConvertExpressionEntry(gameStatement, entries, arg.get(), menu, item); + } + + expressionEntry parenRight{}; + parenRight.type = EET_OPERATOR; + parenRight.data.op = OP_RIGHTPAREN; + entries.emplace_back(parenRight); + } + } - std::vector expressionEntries; - ConvertExpressionEntry(statement, expressionEntries, expression, menu, item); + void ConvertExpressionEntryCustomFunctionCall(Statement_s *gameStatement, std::vector &entries, + const CommonExpressionCustomFunctionCall *functionCall, const CommonMenuDef *menu, + const CommonItemDef *item) const { + Statement_s *functionStatement = m_conversion_zone_state->FindFunction(functionCall->m_function_name); - auto* outputExpressionEntries = static_cast(m_memory->Alloc(sizeof(expressionEntry) * expressionEntries.size())); - memcpy(outputExpressionEntries, expressionEntries.data(), sizeof(expressionEntry) * expressionEntries.size()); + if (functionStatement == nullptr) { + // Function was not converted yet: Convert it now + const auto foundCommonFunction = m_parsing_zone_state->m_functions_by_name.find(functionCall->m_function_name); - statement->entries = outputExpressionEntries; - statement->numEntries = static_cast(expressionEntries.size()); + if (foundCommonFunction == m_parsing_zone_state->m_functions_by_name.end()) + throw MenuConversionException("Failed to find definition for custom function \"" + functionCall->m_function_name + "\"", menu, item); - return statement; - } + functionStatement = ConvertExpression(foundCommonFunction->second->m_value.get(), menu, item); + functionStatement = m_conversion_zone_state->AddFunction(foundCommonFunction->second->m_name, functionStatement); + } - _NODISCARD Statement_s* ConvertOrApplyStatement(float& staticValue, const ISimpleExpression* expression, const CommonMenuDef* menu, const CommonItemDef* item = nullptr) const - { - if (m_disable_optimizations) - return ConvertExpression(expression, menu, item); - - if (!expression) - return nullptr; - - if (expression->IsStatic()) - { - const auto value = expression->EvaluateStatic(); - switch (value.m_type) - { - case SimpleExpressionValue::Type::DOUBLE: - staticValue = static_cast(value.m_double_value); - break; - case SimpleExpressionValue::Type::INT: - staticValue = static_cast(value.m_int_value); - break; - case SimpleExpressionValue::Type::STRING: - throw MenuConversionException("Cannot convert string expression value to floating point", menu, item); - } - return nullptr; - } - - return ConvertExpression(expression, menu, item); - } + expressionEntry functionEntry{}; + functionEntry.type = EET_OPERAND; + functionEntry.data.operand.dataType = VAL_FUNCTION; + functionEntry.data.operand.internals.function = functionStatement; + entries.emplace_back(functionEntry); + + // Statement uses custom function so it needs supporting data + gameStatement->supportingData = m_conversion_zone_state->m_supporting_data; + } + + constexpr static expressionOperatorType_e UNARY_OPERATION_MAPPING[static_cast(SimpleUnaryOperationId::COUNT)]{OP_NOT, OP_BITWISENOT, OP_SUBTRACT}; + + bool IsOperation(const ISimpleExpression *expression) const { + if (!m_disable_optimizations && expression->IsStatic()) + return false; + + return dynamic_cast(expression) || dynamic_cast(expression); + } + + void ConvertExpressionEntryUnaryOperation(Statement_s *gameStatement, std::vector &entries, + const SimpleExpressionUnaryOperation *unaryOperation, const CommonMenuDef *menu, const CommonItemDef *item) const { + assert(static_cast(unaryOperation->m_operation_type->m_id) < static_cast(SimpleUnaryOperationId::COUNT)); + expressionEntry operation{}; + operation.type = EET_OPERATOR; + operation.data.op = UNARY_OPERATION_MAPPING[static_cast(unaryOperation->m_operation_type->m_id)]; + entries.emplace_back(operation); + + if (IsOperation(unaryOperation->m_operand.get())) { + expressionEntry parenLeft{}; + parenLeft.type = EET_OPERATOR; + parenLeft.data.op = OP_LEFTPAREN; + entries.emplace_back(parenLeft); + + ConvertExpressionEntry(gameStatement, entries, unaryOperation->m_operand.get(), menu, item); + + expressionEntry parenRight{}; + parenRight.type = EET_OPERATOR; + parenRight.data.op = OP_RIGHTPAREN; + entries.emplace_back(parenRight); + } else + ConvertExpressionEntry(gameStatement, entries, unaryOperation->m_operand.get(), menu, item); + } + + constexpr static expressionOperatorType_e BINARY_OPERATION_MAPPING[static_cast(SimpleBinaryOperationId::COUNT)]{OP_ADD, + OP_SUBTRACT, + OP_MULTIPLY, + OP_DIVIDE, + OP_MODULUS, + OP_BITWISEAND, + OP_BITWISEOR, + OP_BITSHIFTLEFT, + OP_BITSHIFTRIGHT, + OP_GREATERTHAN, + OP_GREATERTHANEQUALTO, + OP_LESSTHAN, + OP_LESSTHANEQUALTO, + OP_EQUALS, + OP_NOTEQUAL, + OP_AND, + OP_OR}; + + void ConvertExpressionEntryBinaryOperation(Statement_s *gameStatement, std::vector &entries, + const SimpleExpressionBinaryOperation *binaryOperation, const CommonMenuDef *menu, + const CommonItemDef *item) const { + // Game needs all nested operations to have parenthesis + if (IsOperation(binaryOperation->m_operand1.get())) { + expressionEntry parenLeft{}; + parenLeft.type = EET_OPERATOR; + parenLeft.data.op = OP_LEFTPAREN; + entries.emplace_back(parenLeft); + + ConvertExpressionEntry(gameStatement, entries, binaryOperation->m_operand1.get(), menu, item); + + expressionEntry parenRight{}; + parenRight.type = EET_OPERATOR; + parenRight.data.op = OP_RIGHTPAREN; + entries.emplace_back(parenRight); + } else + ConvertExpressionEntry(gameStatement, entries, binaryOperation->m_operand1.get(), menu, item); + + assert(static_cast(binaryOperation->m_operation_type->m_id) < static_cast(SimpleBinaryOperationId::COUNT)); + expressionEntry operation{}; + operation.type = EET_OPERATOR; + operation.data.op = BINARY_OPERATION_MAPPING[static_cast(binaryOperation->m_operation_type->m_id)]; + entries.emplace_back(operation); + + // Game needs all nested operations to have parenthesis + if (IsOperation(binaryOperation->m_operand2.get())) { + expressionEntry parenLeft{}; + parenLeft.type = EET_OPERATOR; + parenLeft.data.op = OP_LEFTPAREN; + entries.emplace_back(parenLeft); + + ConvertExpressionEntry(gameStatement, entries, binaryOperation->m_operand2.get(), menu, item); + + expressionEntry parenRight{}; + parenRight.type = EET_OPERATOR; + parenRight.data.op = OP_RIGHTPAREN; + entries.emplace_back(parenRight); + } else + ConvertExpressionEntry(gameStatement, entries, binaryOperation->m_operand2.get(), menu, item); + } + + void ConvertExpressionEntryExpressionValue(std::vector &entries, const SimpleExpressionValue *expressionValue) const { + expressionEntry entry{}; + entry.type = EET_OPERAND; + + if (expressionValue->m_type == SimpleExpressionValue::Type::INT) { + entry.data.operand.dataType = VAL_INT; + entry.data.operand.internals.intVal = expressionValue->m_int_value; + } else if (expressionValue->m_type == SimpleExpressionValue::Type::DOUBLE) { + entry.data.operand.dataType = VAL_FLOAT; + entry.data.operand.internals.floatVal = static_cast(expressionValue->m_double_value); + } else if (expressionValue->m_type == SimpleExpressionValue::Type::STRING) { + entry.data.operand.dataType = VAL_STRING; + entry.data.operand.internals.stringVal.string = m_conversion_zone_state->AddString(*expressionValue->m_string_value); + } - _NODISCARD Statement_s* ConvertOrApplyStatement(const char*& staticValue, const ISimpleExpression* expression, const CommonMenuDef* menu, const CommonItemDef* item = nullptr) const - { - if (m_disable_optimizations) - return ConvertExpression(expression, menu, item); - - if (!expression) - return nullptr; - - if (expression->IsStatic()) - { - const auto value = expression->EvaluateStatic(); - switch (value.m_type) - { - case SimpleExpressionValue::Type::STRING: - staticValue = m_memory->Dup(value.m_string_value->c_str()); - break; - - case SimpleExpressionValue::Type::DOUBLE: - case SimpleExpressionValue::Type::INT: - throw MenuConversionException("Cannot convert numeric expression value to string", menu, item); - } - return nullptr; - } - - return ConvertExpression(expression, menu, item); - } + entries.emplace_back(entry); + } + + void ConvertExpressionEntry(Statement_s *gameStatement, std::vector &entries, const ISimpleExpression *expression, const CommonMenuDef *menu, + const CommonItemDef *item) const { + if (!m_disable_optimizations && expression->IsStatic()) { + const auto expressionStaticValue = expression->EvaluateStatic(); + ConvertExpressionEntryExpressionValue(entries, &expressionStaticValue); + } else if (const auto *expressionValue = dynamic_cast(expression)) { + ConvertExpressionEntryExpressionValue(entries, expressionValue); + } else if (const auto *binaryOperation = dynamic_cast(expression)) { + ConvertExpressionEntryBinaryOperation(gameStatement, entries, binaryOperation, menu, item); + } else if (const auto *unaryOperation = dynamic_cast(expression)) { + ConvertExpressionEntryUnaryOperation(gameStatement, entries, unaryOperation, menu, item); + } else if (const auto *baseFunctionCall = dynamic_cast(expression)) { + ConvertExpressionEntryBaseFunctionCall(gameStatement, entries, baseFunctionCall, menu, item); + } else if (const auto *customFunctionCall = dynamic_cast(expression)) { + ConvertExpressionEntryCustomFunctionCall(gameStatement, entries, customFunctionCall, menu, item); + } else if (dynamic_cast(expression)) { + throw MenuConversionException("Cannot use conditional expression in menu expressions", menu, item); + } else { + assert(false); + throw MenuConversionException("Unknown expression entry type in menu expressions", menu, item); + } + } + + _NODISCARD Statement_s *ConvertExpression(const ISimpleExpression *expression, const CommonMenuDef *menu, const CommonItemDef *item = nullptr) const { + if (!expression) + return nullptr; + + auto *statement = m_memory->Create(); + statement->lastResult = Operand{}; + statement->lastExecuteTime = 0; + statement->supportingData = nullptr; // Supporting data is set upon using it + + std::vector expressionEntries; + ConvertExpressionEntry(statement, expressionEntries, expression, menu, item); + + auto *outputExpressionEntries = static_cast(m_memory->Alloc(sizeof(expressionEntry) * expressionEntries.size())); + memcpy(outputExpressionEntries, expressionEntries.data(), sizeof(expressionEntry) * expressionEntries.size()); + + statement->entries = outputExpressionEntries; + statement->numEntries = static_cast(expressionEntries.size()); + + return statement; + } + + _NODISCARD Statement_s *ConvertOrApplyStatement(float &staticValue, const ISimpleExpression *expression, const CommonMenuDef *menu, + const CommonItemDef *item = nullptr) const { + if (m_disable_optimizations) + return ConvertExpression(expression, menu, item); + + if (!expression) + return nullptr; + + if (expression->IsStatic()) { + const auto value = expression->EvaluateStatic(); + switch (value.m_type) { + case SimpleExpressionValue::Type::DOUBLE: + staticValue = static_cast(value.m_double_value); + break; + case SimpleExpressionValue::Type::INT: + staticValue = static_cast(value.m_int_value); + break; + case SimpleExpressionValue::Type::STRING: + throw MenuConversionException("Cannot convert string expression value to floating point", menu, item); + } + return nullptr; + } - _NODISCARD Statement_s* ConvertOrApplyStatement(Material*& staticValue, const ISimpleExpression* expression, const CommonMenuDef* menu, const CommonItemDef* item = nullptr) const - { - if (m_disable_optimizations) - return ConvertExpression(expression, menu, item); - - if (!expression) - return nullptr; - - if (expression->IsStatic()) - { - const auto value = expression->EvaluateStatic(); - switch (value.m_type) - { - case SimpleExpressionValue::Type::STRING: - staticValue = ConvertMaterial(*value.m_string_value, menu, item); - break; - - case SimpleExpressionValue::Type::DOUBLE: - case SimpleExpressionValue::Type::INT: - throw MenuConversionException("Cannot convert numeric expression value to string", menu, item); - } - return nullptr; - } - - return ConvertExpression(expression, menu, item); - } + return ConvertExpression(expression, menu, item); + } + + _NODISCARD Statement_s *ConvertOrApplyStatement(const char *&staticValue, const ISimpleExpression *expression, const CommonMenuDef *menu, + const CommonItemDef *item = nullptr) const { + if (m_disable_optimizations) + return ConvertExpression(expression, menu, item); + + if (!expression) + return nullptr; + + if (expression->IsStatic()) { + const auto value = expression->EvaluateStatic(); + switch (value.m_type) { + case SimpleExpressionValue::Type::STRING: + staticValue = m_memory->Dup(value.m_string_value->c_str()); + break; + + case SimpleExpressionValue::Type::DOUBLE: + case SimpleExpressionValue::Type::INT: + throw MenuConversionException("Cannot convert numeric expression value to string", menu, item); + } + return nullptr; + } - _NODISCARD Statement_s* ConvertVisibleExpression(windowDef_t* window, const ISimpleExpression* expression, const CommonMenuDef* commonMenu, const CommonItemDef* commonItem = nullptr) const - { - if (expression == nullptr) - return nullptr; - - bool isStatic; - bool isTruthy; - if (m_disable_optimizations) - { - const auto* staticValue = dynamic_cast(expression); - isStatic = staticValue != nullptr; - isTruthy = isStatic && (staticValue->m_type == SimpleExpressionValue::Type::INT || staticValue->m_type == SimpleExpressionValue::Type::DOUBLE) && staticValue->IsTruthy(); - } - else - { - isStatic = expression->IsStatic(); - isTruthy = isStatic && expression->EvaluateStatic().IsTruthy(); - } - - if (isStatic) - { - if (isTruthy) - window->dynamicFlags[0] |= WINDOW_FLAG_VISIBLE; - return nullptr; - } - - window->dynamicFlags[0] |= WINDOW_FLAG_VISIBLE; - return ConvertExpression(expression, commonMenu, commonItem); - } + return ConvertExpression(expression, menu, item); + } + + _NODISCARD Statement_s *ConvertOrApplyStatement(Material *&staticValue, const ISimpleExpression *expression, const CommonMenuDef *menu, + const CommonItemDef *item = nullptr) const { + if (m_disable_optimizations) + return ConvertExpression(expression, menu, item); + + if (!expression) + return nullptr; + + if (expression->IsStatic()) { + const auto value = expression->EvaluateStatic(); + switch (value.m_type) { + case SimpleExpressionValue::Type::STRING: + staticValue = ConvertMaterial(*value.m_string_value, menu, item); + break; + + case SimpleExpressionValue::Type::DOUBLE: + case SimpleExpressionValue::Type::INT: + throw MenuConversionException("Cannot convert numeric expression value to string", menu, item); + } + return nullptr; + } - _NODISCARD static EventType SetLocalVarTypeToEventType(const SetLocalVarType setLocalVarType) - { - switch (setLocalVarType) - { - case SetLocalVarType::BOOL: - return EVENT_SET_LOCAL_VAR_BOOL; - case SetLocalVarType::STRING: - return EVENT_SET_LOCAL_VAR_STRING; - case SetLocalVarType::FLOAT: - return EVENT_SET_LOCAL_VAR_FLOAT; - case SetLocalVarType::INT: - return EVENT_SET_LOCAL_VAR_INT; - default: - case SetLocalVarType::UNKNOWN: - assert(false); - return EVENT_SET_LOCAL_VAR_INT; - } - } + return ConvertExpression(expression, menu, item); + } + + _NODISCARD Statement_s *ConvertVisibleExpression(windowDef_t *window, const ISimpleExpression *expression, const CommonMenuDef *commonMenu, + const CommonItemDef *commonItem = nullptr) const { + if (expression == nullptr) + return nullptr; + + bool isStatic; + bool isTruthy; + if (m_disable_optimizations) { + const auto *staticValue = dynamic_cast(expression); + isStatic = staticValue != nullptr; + isTruthy = isStatic && (staticValue->m_type == SimpleExpressionValue::Type::INT || staticValue->m_type == SimpleExpressionValue::Type::DOUBLE) && + staticValue->IsTruthy(); + } else { + isStatic = expression->IsStatic(); + isTruthy = isStatic && expression->EvaluateStatic().IsTruthy(); + } - void ConvertEventHandlerSetLocalVar(std::vector& elements, const CommonEventHandlerSetLocalVar* setLocalVar, const CommonMenuDef* menu, const CommonItemDef* item) const - { - assert(setLocalVar); - if (!setLocalVar) - return; + if (isStatic) { + if (isTruthy) + window->dynamicFlags[0] |= WINDOW_FLAG_VISIBLE; + return nullptr; + } - auto* outputHandler = static_cast(m_memory->Alloc(sizeof(MenuEventHandler) + sizeof(SetLocalVarData))); - auto* outputSetLocalVar = reinterpret_cast(reinterpret_cast(outputHandler) + sizeof(MenuEventHandler)); + window->dynamicFlags[0] |= WINDOW_FLAG_VISIBLE; + return ConvertExpression(expression, commonMenu, commonItem); + } + + _NODISCARD static EventType SetLocalVarTypeToEventType(const SetLocalVarType setLocalVarType) { + switch (setLocalVarType) { + case SetLocalVarType::BOOL: + return EVENT_SET_LOCAL_VAR_BOOL; + case SetLocalVarType::STRING: + return EVENT_SET_LOCAL_VAR_STRING; + case SetLocalVarType::FLOAT: + return EVENT_SET_LOCAL_VAR_FLOAT; + case SetLocalVarType::INT: + return EVENT_SET_LOCAL_VAR_INT; + default: + case SetLocalVarType::UNKNOWN: + assert(false); + return EVENT_SET_LOCAL_VAR_INT; + } + } - outputHandler->eventType = SetLocalVarTypeToEventType(setLocalVar->m_type); - outputHandler->eventData.setLocalVarData = outputSetLocalVar; + void ConvertEventHandlerSetLocalVar(std::vector &elements, const CommonEventHandlerSetLocalVar *setLocalVar, const CommonMenuDef *menu, + const CommonItemDef *item) const { + assert(setLocalVar); + if (!setLocalVar) + return; - outputSetLocalVar->localVarName = m_memory->Dup(setLocalVar->m_var_name.c_str()); - outputSetLocalVar->expression = ConvertExpression(setLocalVar->m_value.get(), menu, item); + auto *outputHandler = static_cast(m_memory->Alloc(sizeof(MenuEventHandler) + sizeof(SetLocalVarData))); + auto *outputSetLocalVar = reinterpret_cast(reinterpret_cast(outputHandler) + sizeof(MenuEventHandler)); - elements.push_back(outputHandler); - } + outputHandler->eventType = SetLocalVarTypeToEventType(setLocalVar->m_type); + outputHandler->eventData.setLocalVarData = outputSetLocalVar; - void ConvertEventHandlerScript(std::vector& elements, const CommonEventHandlerScript* script) const - { - assert(script); - if (!script) - return; + outputSetLocalVar->localVarName = m_memory->Dup(setLocalVar->m_var_name.c_str()); + outputSetLocalVar->expression = ConvertExpression(setLocalVar->m_value.get(), menu, item); - auto* outputHandler = m_memory->Create(); - outputHandler->eventType = EVENT_UNCONDITIONAL; - outputHandler->eventData.unconditionalScript = m_memory->Dup(script->m_script.c_str()); + elements.push_back(outputHandler); + } - elements.push_back(outputHandler); - } + void ConvertEventHandlerScript(std::vector &elements, const CommonEventHandlerScript *script) const { + assert(script); + if (!script) + return; - void ConvertEventHandlerCondition(std::vector& elements, const CommonEventHandlerCondition* condition, const CommonMenuDef* menu, - const CommonItemDef* item) const - { - assert(condition); - if (!condition || !condition->m_condition) - return; - - if(!m_disable_optimizations && condition->m_condition->IsStatic()) - { - const auto staticValueIsTruthy = condition->m_condition->EvaluateStatic().IsTruthy(); - - if(staticValueIsTruthy) - ConvertEventHandlerElements(elements, condition->m_condition_elements.get(), menu, item); - else if(condition->m_else_elements) - ConvertEventHandlerElements(elements, condition->m_else_elements.get(), menu, item); - } - else - { - auto* outputHandler = static_cast(m_memory->Alloc(sizeof(MenuEventHandler) + sizeof(ConditionalScript))); - auto* outputCondition = reinterpret_cast(reinterpret_cast(outputHandler) + sizeof(MenuEventHandler)); - - outputHandler->eventType = EVENT_IF; - outputHandler->eventData.conditionalScript = outputCondition; - - outputCondition->eventExpression = ConvertExpression(condition->m_condition.get(), menu, item); - outputCondition->eventHandlerSet = ConvertEventHandlerSet(condition->m_condition_elements.get(), menu, item); - - elements.push_back(outputHandler); - - if (condition->m_else_elements) - { - auto* outputElseHandler = m_memory->Create(); - outputElseHandler->eventType = EVENT_ELSE; - outputElseHandler->eventData.elseScript = ConvertEventHandlerSet(condition->m_else_elements.get(), menu, item); - - elements.push_back(outputElseHandler); - } - } - } + auto *outputHandler = m_memory->Create(); + outputHandler->eventType = EVENT_UNCONDITIONAL; + outputHandler->eventData.unconditionalScript = m_memory->Dup(script->m_script.c_str()); - void ConvertEventHandler(std::vector& elements, const ICommonEventHandlerElement* eventHandler, const CommonMenuDef* menu, - const CommonItemDef* item) const - { - assert(eventHandler); - if (!eventHandler) - return; - - switch (eventHandler->GetType()) - { - case CommonEventHandlerElementType::CONDITION: - ConvertEventHandlerCondition(elements, dynamic_cast(eventHandler), menu, item); - break; - - case CommonEventHandlerElementType::SCRIPT: - ConvertEventHandlerScript(elements, dynamic_cast(eventHandler)); - break; - - case CommonEventHandlerElementType::SET_LOCAL_VAR: - ConvertEventHandlerSetLocalVar(elements, dynamic_cast(eventHandler), menu, item); - break; - } - } + elements.push_back(outputHandler); + } - void ConvertEventHandlerElements(std::vector& elements, const CommonEventHandlerSet* eventHandlerSet, const CommonMenuDef* menu, const CommonItemDef* item) const - { - for (const auto& element : eventHandlerSet->m_elements) - ConvertEventHandler(elements, element.get(), menu, item); - } + void ConvertEventHandlerCondition(std::vector &elements, const CommonEventHandlerCondition *condition, const CommonMenuDef *menu, + const CommonItemDef *item) const { + assert(condition); + if (!condition || !condition->m_condition) + return; - _NODISCARD MenuEventHandlerSet* ConvertEventHandlerSet(const CommonEventHandlerSet* eventHandlerSet, const CommonMenuDef* menu, const CommonItemDef* item = nullptr) const - { - if (!eventHandlerSet) - return nullptr; + if (!m_disable_optimizations && condition->m_condition->IsStatic()) { + const auto staticValueIsTruthy = condition->m_condition->EvaluateStatic().IsTruthy(); - std::vector elements; - ConvertEventHandlerElements(elements, eventHandlerSet, menu, item); + if (staticValueIsTruthy) + ConvertEventHandlerElements(elements, condition->m_condition_elements.get(), menu, item); + else if (condition->m_else_elements) + ConvertEventHandlerElements(elements, condition->m_else_elements.get(), menu, item); + } else { + auto *outputHandler = static_cast(m_memory->Alloc(sizeof(MenuEventHandler) + sizeof(ConditionalScript))); + auto *outputCondition = reinterpret_cast(reinterpret_cast(outputHandler) + sizeof(MenuEventHandler)); - if (elements.empty()) - return nullptr; + outputHandler->eventType = EVENT_IF; + outputHandler->eventData.conditionalScript = outputCondition; - auto* outputSet = static_cast(m_memory->Alloc(sizeof(MenuEventHandlerSet) + sizeof(void*) * elements.size())); - auto* outputElements = reinterpret_cast(reinterpret_cast(outputSet) + sizeof(MenuEventHandlerSet)); - memcpy(outputElements, &elements[0], sizeof(void*) * elements.size()); + outputCondition->eventExpression = ConvertExpression(condition->m_condition.get(), menu, item); + outputCondition->eventHandlerSet = ConvertEventHandlerSet(condition->m_condition_elements.get(), menu, item); - outputSet->eventHandlerCount = static_cast(elements.size()); - outputSet->eventHandlers = outputElements; + elements.push_back(outputHandler); - return outputSet; - } + if (condition->m_else_elements) { + auto *outputElseHandler = m_memory->Create(); + outputElseHandler->eventType = EVENT_ELSE; + outputElseHandler->eventData.elseScript = ConvertEventHandlerSet(condition->m_else_elements.get(), menu, item); - _NODISCARD ItemKeyHandler* ConvertKeyHandler(const std::multimap>& keyHandlers, const CommonMenuDef* menu, const CommonItemDef* item = nullptr) const - { - if (keyHandlers.empty()) - return nullptr; - - const auto keyHandlerCount = keyHandlers.size(); - auto* output = static_cast(m_memory->Alloc(sizeof(ItemKeyHandler) * keyHandlerCount)); - auto currentKeyHandler = keyHandlers.cbegin(); - for (auto i = 0u; i < keyHandlerCount; i++) - { - output[i].key = currentKeyHandler->first; - output[i].action = ConvertEventHandlerSet(currentKeyHandler->second.get(), menu, item); - - if (i + 1 < keyHandlerCount) - output[i].next = &output[i + 1]; - else - output[i].next = nullptr; - ++currentKeyHandler; - } - - return output; - } + elements.push_back(outputElseHandler); + } + } + } + + void ConvertEventHandler(std::vector &elements, const ICommonEventHandlerElement *eventHandler, const CommonMenuDef *menu, + const CommonItemDef *item) const { + assert(eventHandler); + if (!eventHandler) + return; + + switch (eventHandler->GetType()) { + case CommonEventHandlerElementType::CONDITION: + ConvertEventHandlerCondition(elements, dynamic_cast(eventHandler), menu, item); + break; + + case CommonEventHandlerElementType::SCRIPT: + ConvertEventHandlerScript(elements, dynamic_cast(eventHandler)); + break; + + case CommonEventHandlerElementType::SET_LOCAL_VAR: + ConvertEventHandlerSetLocalVar(elements, dynamic_cast(eventHandler), menu, item); + break; + } + } + + void ConvertEventHandlerElements(std::vector &elements, const CommonEventHandlerSet *eventHandlerSet, const CommonMenuDef *menu, + const CommonItemDef *item) const { + for (const auto &element : eventHandlerSet->m_elements) + ConvertEventHandler(elements, element.get(), menu, item); + } + + _NODISCARD MenuEventHandlerSet *ConvertEventHandlerSet(const CommonEventHandlerSet *eventHandlerSet, const CommonMenuDef *menu, + const CommonItemDef *item = nullptr) const { + if (!eventHandlerSet) + return nullptr; + + std::vector elements; + ConvertEventHandlerElements(elements, eventHandlerSet, menu, item); + + if (elements.empty()) + return nullptr; + + auto *outputSet = static_cast(m_memory->Alloc(sizeof(MenuEventHandlerSet) + sizeof(void *) * elements.size())); + auto *outputElements = reinterpret_cast(reinterpret_cast(outputSet) + sizeof(MenuEventHandlerSet)); + memcpy(outputElements, &elements[0], sizeof(void *) * elements.size()); + + outputSet->eventHandlerCount = static_cast(elements.size()); + outputSet->eventHandlers = outputElements; + + return outputSet; + } + + _NODISCARD ItemKeyHandler *ConvertKeyHandler(const std::multimap> &keyHandlers, const CommonMenuDef *menu, + const CommonItemDef *item = nullptr) const { + if (keyHandlers.empty()) + return nullptr; + + const auto keyHandlerCount = keyHandlers.size(); + auto *output = static_cast(m_memory->Alloc(sizeof(ItemKeyHandler) * keyHandlerCount)); + auto currentKeyHandler = keyHandlers.cbegin(); + for (auto i = 0u; i < keyHandlerCount; i++) { + output[i].key = currentKeyHandler->first; + output[i].action = ConvertEventHandlerSet(currentKeyHandler->second.get(), menu, item); + + if (i + 1 < keyHandlerCount) + output[i].next = &output[i + 1]; + else + output[i].next = nullptr; + ++currentKeyHandler; + } - ItemFloatExpression* ConvertFloatExpressions(const CommonItemDef* commonItem, itemDef_s* item, const CommonMenuDef* parentMenu, int& floatExpressionCount) const - { - struct FloatExpressionLocation - { - ISimpleExpression* m_expression; - bool m_expression_is_static; - ItemFloatExpressionTarget m_target; - float* m_static_value; - unsigned m_static_value_array_size; - unsigned m_dynamic_flags_to_set; - }; - FloatExpressionLocation locations[] - { - {commonItem->m_rect_x_exp.get(), false, ITEM_FLOATEXP_TGT_RECT_X, &item->window.rectClient.x, 1, 0}, - {commonItem->m_rect_y_exp.get(), false, ITEM_FLOATEXP_TGT_RECT_Y, &item->window.rectClient.y, 1, 0}, - {commonItem->m_rect_w_exp.get(), false, ITEM_FLOATEXP_TGT_RECT_W, &item->window.rectClient.w, 1, 0}, - {commonItem->m_rect_h_exp.get(), false, ITEM_FLOATEXP_TGT_RECT_H, &item->window.rectClient.h, 1, 0}, - {commonItem->m_forecolor_expressions.m_r_exp.get(), false, ITEM_FLOATEXP_TGT_FORECOLOR_R, &item->window.foreColor[0], 1, WINDOW_FLAG_NON_DEFAULT_FORECOLOR}, - {commonItem->m_forecolor_expressions.m_g_exp.get(), false, ITEM_FLOATEXP_TGT_FORECOLOR_G, &item->window.foreColor[1], 1, WINDOW_FLAG_NON_DEFAULT_FORECOLOR}, - {commonItem->m_forecolor_expressions.m_b_exp.get(), false, ITEM_FLOATEXP_TGT_FORECOLOR_B, &item->window.foreColor[2], 1, WINDOW_FLAG_NON_DEFAULT_FORECOLOR}, - {commonItem->m_forecolor_expressions.m_a_exp.get(), false, ITEM_FLOATEXP_TGT_FORECOLOR_A, &item->window.foreColor[3], 1, WINDOW_FLAG_NON_DEFAULT_FORECOLOR}, - {commonItem->m_forecolor_expressions.m_rgb_exp.get(), false, ITEM_FLOATEXP_TGT_FORECOLOR_RGB, &item->window.foreColor[0], 3, WINDOW_FLAG_NON_DEFAULT_FORECOLOR}, - {commonItem->m_glowcolor_expressions.m_r_exp.get(), false, ITEM_FLOATEXP_TGT_GLOWCOLOR_R, &item->glowColor[0], 1, 0}, - {commonItem->m_glowcolor_expressions.m_g_exp.get(), false, ITEM_FLOATEXP_TGT_GLOWCOLOR_G, &item->glowColor[1], 1, 0}, - {commonItem->m_glowcolor_expressions.m_b_exp.get(), false, ITEM_FLOATEXP_TGT_GLOWCOLOR_B, &item->glowColor[2], 1, 0}, - {commonItem->m_glowcolor_expressions.m_a_exp.get(), false, ITEM_FLOATEXP_TGT_GLOWCOLOR_A, &item->glowColor[3], 1, 0}, - {commonItem->m_glowcolor_expressions.m_rgb_exp.get(), false, ITEM_FLOATEXP_TGT_GLOWCOLOR_RGB, &item->glowColor[0], 3, 0}, - {commonItem->m_backcolor_expressions.m_r_exp.get(), false, ITEM_FLOATEXP_TGT_BACKCOLOR_R, &item->window.backColor[0], 1, 0}, - {commonItem->m_backcolor_expressions.m_g_exp.get(), false, ITEM_FLOATEXP_TGT_BACKCOLOR_G, &item->window.backColor[1], 1, 0}, - {commonItem->m_backcolor_expressions.m_b_exp.get(), false, ITEM_FLOATEXP_TGT_BACKCOLOR_B, &item->window.backColor[2], 1, 0}, - {commonItem->m_backcolor_expressions.m_a_exp.get(), false, ITEM_FLOATEXP_TGT_BACKCOLOR_A, &item->window.backColor[3], 1, 0}, - {commonItem->m_backcolor_expressions.m_rgb_exp.get(), false, ITEM_FLOATEXP_TGT_BACKCOLOR_RGB, &item->window.backColor[0], 3, 0}, - }; - - floatExpressionCount = 0; - for (auto& [expression, expressionIsStatic, target, staticValue, staticValueArraySize, dynamicFlagsToSet] : locations) - { - expressionIsStatic = !m_disable_optimizations && staticValue != nullptr && expression && expression->IsStatic(); - - if (expressionIsStatic) - { - const auto evaluatedValue = expression->EvaluateStatic(); - - if (evaluatedValue.m_type == SimpleExpressionValue::Type::INT) - { - item->window.dynamicFlags[0] |= dynamicFlagsToSet; - - auto* staticValuePtr = staticValue; - for(auto i = 0u; i < staticValueArraySize; i++) - { - *staticValuePtr = static_cast(evaluatedValue.m_int_value); - staticValuePtr++; - } - continue; - } - if (evaluatedValue.m_type == SimpleExpressionValue::Type::DOUBLE) - { - item->window.dynamicFlags[0] |= dynamicFlagsToSet; - auto* staticValuePtr = staticValue; - for (auto i = 0u; i < staticValueArraySize; i++) - { - *staticValue = static_cast(evaluatedValue.m_double_value); - staticValuePtr++; - } - continue; - } - - // Do not consider this a mistake since the games menus do this by mistake and it should be able to compile them anyway - // But the game should also not know what to do with this i guess - expressionIsStatic = false; - } - - if (expression) - floatExpressionCount++; - } - - if (floatExpressionCount <= 0) - return nullptr; - - auto* floatExpressions = static_cast(m_memory->Alloc(sizeof(ItemFloatExpression) * floatExpressionCount)); - auto floatExpressionIndex = 0; - for (const auto& [expression, expressionIsStatic, target, staticValue, staticValueArraySize, dynamicFlagsToSet] : locations) - { - if (!expression || expressionIsStatic) - continue; - - assert(floatExpressionIndex < floatExpressionCount && floatExpressionIndex >= 0); - floatExpressions[floatExpressionIndex].target = target; - floatExpressions[floatExpressionIndex].expression = ConvertExpression(expression, parentMenu, commonItem); - item->window.dynamicFlags[0] |= dynamicFlagsToSet; - floatExpressionIndex++; - } - - return floatExpressions; - } + return output; + } + + ItemFloatExpression *ConvertFloatExpressions(const CommonItemDef *commonItem, itemDef_s *item, const CommonMenuDef *parentMenu, + int &floatExpressionCount) const { + struct FloatExpressionLocation { + ISimpleExpression *m_expression; + bool m_expression_is_static; + ItemFloatExpressionTarget m_target; + float *m_static_value; + unsigned m_static_value_array_size; + unsigned m_dynamic_flags_to_set; + }; + FloatExpressionLocation locations[]{ + {commonItem->m_rect_x_exp.get(), false, ITEM_FLOATEXP_TGT_RECT_X, &item->window.rectClient.x, 1, 0}, + {commonItem->m_rect_y_exp.get(), false, ITEM_FLOATEXP_TGT_RECT_Y, &item->window.rectClient.y, 1, 0}, + {commonItem->m_rect_w_exp.get(), false, ITEM_FLOATEXP_TGT_RECT_W, &item->window.rectClient.w, 1, 0}, + {commonItem->m_rect_h_exp.get(), false, ITEM_FLOATEXP_TGT_RECT_H, &item->window.rectClient.h, 1, 0}, + {commonItem->m_forecolor_expressions.m_r_exp.get(), false, ITEM_FLOATEXP_TGT_FORECOLOR_R, &item->window.foreColor[0], 1, + WINDOW_FLAG_NON_DEFAULT_FORECOLOR }, + {commonItem->m_forecolor_expressions.m_g_exp.get(), false, ITEM_FLOATEXP_TGT_FORECOLOR_G, &item->window.foreColor[1], 1, + WINDOW_FLAG_NON_DEFAULT_FORECOLOR }, + {commonItem->m_forecolor_expressions.m_b_exp.get(), false, ITEM_FLOATEXP_TGT_FORECOLOR_B, &item->window.foreColor[2], 1, + WINDOW_FLAG_NON_DEFAULT_FORECOLOR }, + {commonItem->m_forecolor_expressions.m_a_exp.get(), false, ITEM_FLOATEXP_TGT_FORECOLOR_A, &item->window.foreColor[3], 1, + WINDOW_FLAG_NON_DEFAULT_FORECOLOR }, + {commonItem->m_forecolor_expressions.m_rgb_exp.get(), false, ITEM_FLOATEXP_TGT_FORECOLOR_RGB, &item->window.foreColor[0], 3, + WINDOW_FLAG_NON_DEFAULT_FORECOLOR }, + {commonItem->m_glowcolor_expressions.m_r_exp.get(), false, ITEM_FLOATEXP_TGT_GLOWCOLOR_R, &item->glowColor[0], 1, 0}, + {commonItem->m_glowcolor_expressions.m_g_exp.get(), false, ITEM_FLOATEXP_TGT_GLOWCOLOR_G, &item->glowColor[1], 1, 0}, + {commonItem->m_glowcolor_expressions.m_b_exp.get(), false, ITEM_FLOATEXP_TGT_GLOWCOLOR_B, &item->glowColor[2], 1, 0}, + {commonItem->m_glowcolor_expressions.m_a_exp.get(), false, ITEM_FLOATEXP_TGT_GLOWCOLOR_A, &item->glowColor[3], 1, 0}, + {commonItem->m_glowcolor_expressions.m_rgb_exp.get(), false, ITEM_FLOATEXP_TGT_GLOWCOLOR_RGB, &item->glowColor[0], 3, 0}, + {commonItem->m_backcolor_expressions.m_r_exp.get(), false, ITEM_FLOATEXP_TGT_BACKCOLOR_R, &item->window.backColor[0], 1, 0}, + {commonItem->m_backcolor_expressions.m_g_exp.get(), false, ITEM_FLOATEXP_TGT_BACKCOLOR_G, &item->window.backColor[1], 1, 0}, + {commonItem->m_backcolor_expressions.m_b_exp.get(), false, ITEM_FLOATEXP_TGT_BACKCOLOR_B, &item->window.backColor[2], 1, 0}, + {commonItem->m_backcolor_expressions.m_a_exp.get(), false, ITEM_FLOATEXP_TGT_BACKCOLOR_A, &item->window.backColor[3], 1, 0}, + {commonItem->m_backcolor_expressions.m_rgb_exp.get(), false, ITEM_FLOATEXP_TGT_BACKCOLOR_RGB, &item->window.backColor[0], 3, 0}, + }; - _NODISCARD const char* CreateEnableDvarString(const std::vector& stringElements) const - { - std::ostringstream ss; + floatExpressionCount = 0; + for (auto &[expression, expressionIsStatic, target, staticValue, staticValueArraySize, dynamicFlagsToSet] : locations) { + expressionIsStatic = !m_disable_optimizations && staticValue != nullptr && expression && expression->IsStatic(); - for (const auto& element : stringElements) - { - ss << "\"" << element << "\" "; - } + if (expressionIsStatic) { + const auto evaluatedValue = expression->EvaluateStatic(); - return m_memory->Dup(ss.str().c_str()); - } + if (evaluatedValue.m_type == SimpleExpressionValue::Type::INT) { + item->window.dynamicFlags[0] |= dynamicFlagsToSet; - _NODISCARD const char* ConvertEnableDvar(const CommonItemDef& commonItem, int& dvarFlags) const - { - dvarFlags = 0; - - if (!commonItem.m_enable_dvar.empty()) - { - dvarFlags |= ITEM_DVAR_FLAG_ENABLE; - return CreateEnableDvarString(commonItem.m_enable_dvar); - } - - if (!commonItem.m_disable_dvar.empty()) - { - dvarFlags |= ITEM_DVAR_FLAG_DISABLE; - return CreateEnableDvarString(commonItem.m_disable_dvar); - } - - if (!commonItem.m_show_dvar.empty()) - { - dvarFlags |= ITEM_DVAR_FLAG_SHOW; - return CreateEnableDvarString(commonItem.m_show_dvar); - } - - if (!commonItem.m_hide_dvar.empty()) - { - dvarFlags |= ITEM_DVAR_FLAG_HIDE; - return CreateEnableDvarString(commonItem.m_hide_dvar); - } - - if (!commonItem.m_focus_dvar.empty()) - { - dvarFlags |= ITEM_DVAR_FLAG_FOCUS; - return CreateEnableDvarString(commonItem.m_focus_dvar); - } - - return nullptr; + auto *staticValuePtr = staticValue; + for (auto i = 0u; i < staticValueArraySize; i++) { + *staticValuePtr = static_cast(evaluatedValue.m_int_value); + staticValuePtr++; + } + continue; } - - _NODISCARD listBoxDef_s* ConvertListBoxFeatures(itemDef_s* item, CommonItemFeaturesListBox* commonListBox, const CommonMenuDef& parentMenu, const CommonItemDef& commonItem) const - { - if (commonListBox == nullptr) - return nullptr; - - auto* listBox = static_cast(m_memory->Alloc(sizeof(listBoxDef_s))); - memset(listBox, 0, sizeof(listBoxDef_s)); - - listBox->notselectable = commonListBox->m_not_selectable ? 1 : 0; - listBox->noScrollBars = commonListBox->m_no_scrollbars ? 1 : 0; - listBox->usePaging = commonListBox->m_use_paging ? 1 : 0; - listBox->elementWidth = static_cast(commonListBox->m_element_width); - listBox->elementHeight = static_cast(commonListBox->m_element_height); - item->special = static_cast(commonListBox->m_feeder); - listBox->elementStyle = commonListBox->m_element_style; - listBox->onDoubleClick = ConvertEventHandlerSet(commonListBox->m_on_double_click.get(), &parentMenu, &commonItem); - ConvertColor(listBox->selectBorder, commonListBox->m_select_border); - listBox->selectIcon = ConvertMaterial(commonListBox->m_select_icon, &parentMenu, &commonItem); - - listBox->numColumns = static_cast(std::min(std::extent_v, commonListBox->m_columns.size())); - for (auto i = 0; i < listBox->numColumns; i++) - { - auto& col = listBox->columnInfo[i]; - const auto& commonCol = commonListBox->m_columns[i]; - - col.pos = commonCol.m_x_pos; - col.width = commonCol.m_width; - col.maxChars = commonCol.m_max_chars; - col.alignment = commonCol.m_alignment; - } - - return listBox; + if (evaluatedValue.m_type == SimpleExpressionValue::Type::DOUBLE) { + item->window.dynamicFlags[0] |= dynamicFlagsToSet; + auto *staticValuePtr = staticValue; + for (auto i = 0u; i < staticValueArraySize; i++) { + *staticValue = static_cast(evaluatedValue.m_double_value); + staticValuePtr++; + } + continue; } - _NODISCARD editFieldDef_s* ConvertEditFieldFeatures(itemDef_s* item, CommonItemFeaturesEditField* commonEditField, const CommonMenuDef& parentMenu, const CommonItemDef& commonItem) const - { - if (commonEditField == nullptr) - return nullptr; + // Do not consider this a mistake since the games menus do this by mistake and it should be able to compile them anyway + // But the game should also not know what to do with this i guess + expressionIsStatic = false; + } - auto* editField = static_cast(m_memory->Alloc(sizeof(editFieldDef_s))); - memset(editField, 0, sizeof(editFieldDef_s)); - - editField->defVal = static_cast(commonEditField->m_def_val); - editField->minVal = static_cast(commonEditField->m_min_val); - editField->maxVal = static_cast(commonEditField->m_max_val); - item->localVar = ConvertString(commonEditField->m_local_var); - editField->maxChars = commonEditField->m_max_chars; - editField->maxCharsGotoNext = commonEditField->m_max_chars_goto_next ? 1 : 0; - editField->maxPaintChars = commonEditField->m_max_paint_chars; + if (expression) + floatExpressionCount++; + } - return editField; - } + if (floatExpressionCount <= 0) + return nullptr; - _NODISCARD multiDef_s* ConvertMultiValueFeatures(itemDef_s* item, CommonItemFeaturesMultiValue* commonMultiValue, const CommonMenuDef& parentMenu, const CommonItemDef& commonItem) const - { - if (commonMultiValue == nullptr) - return nullptr; - - auto* multiValue = static_cast(m_memory->Alloc(sizeof(multiDef_s))); - memset(multiValue, 0, sizeof(multiDef_s)); - - multiValue->count = static_cast(std::min(std::extent_v, commonMultiValue->m_step_names.size())); - multiValue->strDef = !commonMultiValue->m_string_values.empty() ? 1 : 0; - - for (auto i = 0; i < multiValue->count; i++) - { - multiValue->dvarList[i] = ConvertString(commonMultiValue->m_step_names[i]); - - if (multiValue->strDef) - { - if (commonMultiValue->m_string_values.size() > static_cast(i)) - multiValue->dvarStr[i] = ConvertString(commonMultiValue->m_string_values[i]); - } - else - { - if (commonMultiValue->m_double_values.size() > static_cast(i)) - multiValue->dvarValue[i] = static_cast(commonMultiValue->m_double_values[i]); - } - } - - return multiValue; - } + auto *floatExpressions = static_cast(m_memory->Alloc(sizeof(ItemFloatExpression) * floatExpressionCount)); + auto floatExpressionIndex = 0; + for (const auto &[expression, expressionIsStatic, target, staticValue, staticValueArraySize, dynamicFlagsToSet] : locations) { + if (!expression || expressionIsStatic) + continue; - _NODISCARD newsTickerDef_s* ConvertNewsTickerFeatures(itemDef_s* item, CommonItemFeaturesNewsTicker* commonNewsTicker, const CommonMenuDef& parentMenu, const CommonItemDef& commonItem) const - { - if (commonNewsTicker == nullptr) - return nullptr; + assert(floatExpressionIndex < floatExpressionCount && floatExpressionIndex >= 0); + floatExpressions[floatExpressionIndex].target = target; + floatExpressions[floatExpressionIndex].expression = ConvertExpression(expression, parentMenu, commonItem); + item->window.dynamicFlags[0] |= dynamicFlagsToSet; + floatExpressionIndex++; + } - auto* newsTicker = static_cast(m_memory->Alloc(sizeof(newsTickerDef_s))); - memset(newsTicker, 0, sizeof(newsTickerDef_s)); + return floatExpressions; + } - newsTicker->spacing = commonNewsTicker->m_spacing; - newsTicker->speed = commonNewsTicker->m_speed; - newsTicker->feedId = commonNewsTicker->m_news_feed_id; + _NODISCARD const char *CreateEnableDvarString(const std::vector &stringElements) const { + std::ostringstream ss; - return newsTicker; - } - - _NODISCARD itemDef_s* ConvertItem(const CommonMenuDef& parentMenu, const CommonItemDef& commonItem) const - { - auto* item = m_memory->Create(); - memset(item, 0, sizeof(itemDef_s)); - - item->window.name = ConvertString(commonItem.m_name); - item->text = ConvertString(commonItem.m_text); - ApplyFlag(item->itemFlags, commonItem.m_text_save_game, ITEM_FLAG_SAVE_GAME_INFO); - ApplyFlag(item->itemFlags, commonItem.m_text_cinematic_subtitle, ITEM_FLAG_CINEMATIC_SUBTITLE); - item->window.group = ConvertString(commonItem.m_group); - item->window.rectClient = ConvertRectDef(commonItem.m_rect); - item->window.rect = ConvertRectDefRelativeTo(commonItem.m_rect, parentMenu.m_rect); - item->window.style = commonItem.m_style; - ApplyFlag(item->window.staticFlags, commonItem.m_decoration, WINDOW_FLAG_DECORATION); - ApplyFlag(item->window.staticFlags, commonItem.m_auto_wrapped, WINDOW_FLAG_AUTO_WRAPPED); - ApplyFlag(item->window.staticFlags, commonItem.m_horizontal_scroll, WINDOW_FLAG_HORIZONTAL_SCROLL); - item->type = ConvertItemType(commonItem.m_type); - item->dataType = item->type; - item->window.border = commonItem.m_border; - item->window.borderSize = static_cast(commonItem.m_border_size); - item->visibleExp = ConvertVisibleExpression(&item->window, commonItem.m_visible_expression.get(), &parentMenu, &commonItem); - item->disabledExp = ConvertExpression(commonItem.m_disabled_expression.get(), &parentMenu, &commonItem); - item->window.ownerDraw = commonItem.m_owner_draw; - item->window.ownerDrawFlags = commonItem.m_owner_draw_flags; - item->alignment = commonItem.m_align; - item->textAlignMode = commonItem.m_text_align; - item->textalignx = static_cast(commonItem.m_text_align_x); - item->textaligny = static_cast(commonItem.m_text_align_y); - item->textscale = static_cast(commonItem.m_text_scale); - item->textStyle = commonItem.m_text_style; - item->fontEnum = ConvertTextFont(commonItem.m_text_font); - ConvertColor(item->window.backColor, commonItem.m_back_color); - - ConvertColor(item->window.foreColor, commonItem.m_fore_color); - if (!commonItem.m_fore_color.Equals(CommonColor(1.0, 1.0, 1.0, 1.0))) - item->window.dynamicFlags[0] |= WINDOW_FLAG_NON_DEFAULT_FORECOLOR; - - ConvertColor(item->window.borderColor, commonItem.m_border_color); - ConvertColor(item->window.outlineColor, commonItem.m_outline_color); - ConvertColor(item->window.disableColor, commonItem.m_disable_color); - ConvertColor(item->glowColor, commonItem.m_glow_color); - item->window.background = ConvertMaterial(commonItem.m_background, &parentMenu, &commonItem); - item->onFocus = ConvertEventHandlerSet(commonItem.m_on_focus.get(), &parentMenu, &commonItem); - item->leaveFocus = ConvertEventHandlerSet(commonItem.m_on_leave_focus.get(), &parentMenu, &commonItem); - item->mouseEnter = ConvertEventHandlerSet(commonItem.m_on_mouse_enter.get(), &parentMenu, &commonItem); - item->mouseExit = ConvertEventHandlerSet(commonItem.m_on_mouse_exit.get(), &parentMenu, &commonItem); - item->mouseEnterText = ConvertEventHandlerSet(commonItem.m_on_mouse_enter_text.get(), &parentMenu, &commonItem); - item->mouseExitText = ConvertEventHandlerSet(commonItem.m_on_mouse_exit_text.get(), &parentMenu, &commonItem); - item->action = ConvertEventHandlerSet(commonItem.m_on_action.get(), &parentMenu, &commonItem); - item->accept = ConvertEventHandlerSet(commonItem.m_on_accept.get(), &parentMenu, &commonItem); - item->focusSound = ConvertSound(commonItem.m_focus_sound, &parentMenu, &commonItem); - item->dvarTest = ConvertString(commonItem.m_dvar_test); - item->enableDvar = ConvertEnableDvar(commonItem, item->dvarFlags); - item->onKey = ConvertKeyHandler(commonItem.m_key_handlers, &parentMenu, &commonItem); - item->textExp = ConvertOrApplyStatement(item->text, commonItem.m_text_expression.get(), &parentMenu, &commonItem); - item->materialExp = ConvertOrApplyStatement(item->window.background, commonItem.m_material_expression.get(), &parentMenu, &commonItem); - item->disabledExp = ConvertExpression(commonItem.m_disabled_expression.get(), &parentMenu, &commonItem); - item->floatExpressions = ConvertFloatExpressions(&commonItem, item, &parentMenu, item->floatExpressionCount); - item->gameMsgWindowIndex = commonItem.m_game_message_window_index; - item->gameMsgWindowMode = commonItem.m_game_message_window_mode; - item->fxLetterTime = commonItem.m_fx_letter_time; - item->fxDecayStartTime = commonItem.m_fx_decay_start_time; - item->fxDecayDuration = commonItem.m_fx_decay_duration; - item->dvar = ConvertString(commonItem.m_dvar); - - switch (commonItem.m_feature_type) - { - case CommonItemFeatureType::LISTBOX: - item->typeData.listBox = ConvertListBoxFeatures(item, commonItem.m_list_box_features.get(), parentMenu, commonItem); - break; - - case CommonItemFeatureType::EDIT_FIELD: - item->typeData.editField = ConvertEditFieldFeatures(item, commonItem.m_edit_field_features.get(), parentMenu, commonItem); - break; - - case CommonItemFeatureType::MULTI_VALUE: - item->typeData.multi = ConvertMultiValueFeatures(item, commonItem.m_multi_value_features.get(), parentMenu, commonItem); - break; - - case CommonItemFeatureType::ENUM_DVAR: - item->typeData.enumDvarName = ConvertString(commonItem.m_enum_dvar_name); - break; - - case CommonItemFeatureType::NEWS_TICKER: - item->typeData.ticker = ConvertNewsTickerFeatures(item, commonItem.m_news_ticker_features.get(), parentMenu, commonItem); - break; - - case CommonItemFeatureType::NONE: - default: - if(item->type == ITEM_TYPE_TEXT_SCROLL) - { - item->typeData.scroll = static_cast(m_memory->Alloc(sizeof(textScrollDef_s))); - memset(item->typeData.scroll, 0, sizeof(textScrollDef_s)); - } - break; - } - - return item; - } + for (const auto &element : stringElements) { + ss << "\"" << element << "\" "; + } - itemDef_s** ConvertMenuItems(const CommonMenuDef& commonMenu, int& itemCount) const - { - if (commonMenu.m_items.empty()) - { - itemCount = 0; - return nullptr; - } + return m_memory->Dup(ss.str().c_str()); + } - auto* items = static_cast(m_memory->Alloc(sizeof(void*) * commonMenu.m_items.size())); - memset(items, 0, sizeof(void*) * commonMenu.m_items.size()); + _NODISCARD const char *ConvertEnableDvar(const CommonItemDef &commonItem, int &dvarFlags) const { + dvarFlags = 0; - for (auto i = 0u; i < commonMenu.m_items.size(); i++) - items[i] = ConvertItem(commonMenu, *commonMenu.m_items[i]); + if (!commonItem.m_enable_dvar.empty()) { + dvarFlags |= ITEM_DVAR_FLAG_ENABLE; + return CreateEnableDvarString(commonItem.m_enable_dvar); + } - itemCount = static_cast(commonMenu.m_items.size()); + if (!commonItem.m_disable_dvar.empty()) { + dvarFlags |= ITEM_DVAR_FLAG_DISABLE; + return CreateEnableDvarString(commonItem.m_disable_dvar); + } - return items; - } + if (!commonItem.m_show_dvar.empty()) { + dvarFlags |= ITEM_DVAR_FLAG_SHOW; + return CreateEnableDvarString(commonItem.m_show_dvar); + } - public: - MenuConverterImpl(const bool disableOptimizations, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager) - : AbstractMenuConverter(disableOptimizations, searchPath, memory, manager), - m_conversion_zone_state(manager->GetAssetLoadingContext()->GetZoneAssetLoaderState()), - m_parsing_zone_state(manager->GetAssetLoadingContext()->GetZoneAssetLoaderState()) - { - assert(m_conversion_zone_state); - assert(m_parsing_zone_state); - } + if (!commonItem.m_hide_dvar.empty()) { + dvarFlags |= ITEM_DVAR_FLAG_HIDE; + return CreateEnableDvarString(commonItem.m_hide_dvar); + } - _NODISCARD menuDef_t* ConvertMenu(const CommonMenuDef& commonMenu) const - { - auto* menu = m_memory->Create(); - memset(menu, 0, sizeof(menuDef_t)); - - menu->window.name = m_memory->Dup(commonMenu.m_name.c_str()); - menu->fullScreen = commonMenu.m_full_screen; - ApplyFlag(menu->window.staticFlags, commonMenu.m_screen_space, WINDOW_FLAG_SCREEN_SPACE); - ApplyFlag(menu->window.staticFlags, commonMenu.m_decoration, WINDOW_FLAG_DECORATION); - menu->window.rect = ConvertRectDef(commonMenu.m_rect); - menu->window.style = commonMenu.m_style; - menu->window.border = commonMenu.m_border; - menu->window.borderSize = static_cast(commonMenu.m_border_size); - ConvertColor(menu->window.backColor, commonMenu.m_back_color); - ConvertColor(menu->window.foreColor, commonMenu.m_fore_color); - ConvertColor(menu->window.borderColor, commonMenu.m_border_color); - ConvertColor(menu->focusColor, commonMenu.m_focus_color); - menu->window.background = ConvertMaterial(commonMenu.m_background, &commonMenu); - menu->window.ownerDraw = commonMenu.m_owner_draw; - menu->window.ownerDrawFlags = commonMenu.m_owner_draw_flags; - ApplyFlag(menu->window.staticFlags, commonMenu.m_out_of_bounds_click, WINDOW_FLAG_OUT_OF_BOUNDS_CLICK); - menu->soundName = ConvertString(commonMenu.m_sound_loop); - ApplyFlag(menu->window.staticFlags, commonMenu.m_popup, WINDOW_FLAG_POPUP); - menu->fadeClamp = static_cast(commonMenu.m_fade_clamp); - menu->fadeCycle = commonMenu.m_fade_cycle; - menu->fadeAmount = static_cast(commonMenu.m_fade_amount); - menu->fadeInAmount = static_cast(commonMenu.m_fade_in_amount); - menu->blurRadius = static_cast(commonMenu.m_blur_radius); - ApplyFlag(menu->window.staticFlags, commonMenu.m_legacy_split_screen_scale, WINDOW_FLAG_LEGACY_SPLIT_SCREEN_SCALE); - ApplyFlag(menu->window.staticFlags, commonMenu.m_hidden_during_scope, WINDOW_FLAG_HIDDEN_DURING_SCOPE); - ApplyFlag(menu->window.staticFlags, commonMenu.m_hidden_during_flashbang, WINDOW_FLAG_HIDDEN_DURING_FLASH_BANG); - ApplyFlag(menu->window.staticFlags, commonMenu.m_hidden_during_ui, WINDOW_FLAG_HIDDEN_DURING_UI); - menu->allowedBinding = ConvertString(commonMenu.m_allowed_binding); - ApplyFlag(menu->window.staticFlags, commonMenu.m_text_only_focus, WINDOW_FLAG_TEXT_ONLY_FOCUS); - menu->visibleExp = ConvertVisibleExpression(&menu->window, commonMenu.m_visible_expression.get(), &commonMenu); - menu->rectXExp = ConvertOrApplyStatement(menu->window.rect.x, commonMenu.m_rect_x_exp.get(), &commonMenu); - menu->rectYExp = ConvertOrApplyStatement(menu->window.rect.y, commonMenu.m_rect_y_exp.get(), &commonMenu); - menu->rectWExp = ConvertOrApplyStatement(menu->window.rect.w, commonMenu.m_rect_w_exp.get(), &commonMenu); - menu->rectHExp = ConvertOrApplyStatement(menu->window.rect.h, commonMenu.m_rect_h_exp.get(), &commonMenu); - menu->openSoundExp = ConvertExpression(commonMenu.m_open_sound_exp.get(), &commonMenu); - menu->closeSoundExp = ConvertExpression(commonMenu.m_close_sound_exp.get(), &commonMenu); - menu->onOpen = ConvertEventHandlerSet(commonMenu.m_on_open.get(), &commonMenu); - menu->onClose = ConvertEventHandlerSet(commonMenu.m_on_close.get(), &commonMenu); - menu->onCloseRequest = ConvertEventHandlerSet(commonMenu.m_on_request_close.get(), &commonMenu); - menu->onESC = ConvertEventHandlerSet(commonMenu.m_on_esc.get(), &commonMenu); - menu->onKey = ConvertKeyHandler(commonMenu.m_key_handlers, &commonMenu); - menu->items = ConvertMenuItems(commonMenu, menu->itemCount); - menu->expressionData = m_conversion_zone_state->m_supporting_data; - - return menu; - } + if (!commonItem.m_focus_dvar.empty()) { + dvarFlags |= ITEM_DVAR_FLAG_FOCUS; + return CreateEnableDvarString(commonItem.m_focus_dvar); + } - std::vector m_dependencies; - }; -} + return nullptr; + } + + _NODISCARD listBoxDef_s *ConvertListBoxFeatures(itemDef_s *item, CommonItemFeaturesListBox *commonListBox, const CommonMenuDef &parentMenu, + const CommonItemDef &commonItem) const { + if (commonListBox == nullptr) + return nullptr; + + auto *listBox = static_cast(m_memory->Alloc(sizeof(listBoxDef_s))); + memset(listBox, 0, sizeof(listBoxDef_s)); + + listBox->notselectable = commonListBox->m_not_selectable ? 1 : 0; + listBox->noScrollBars = commonListBox->m_no_scrollbars ? 1 : 0; + listBox->usePaging = commonListBox->m_use_paging ? 1 : 0; + listBox->elementWidth = static_cast(commonListBox->m_element_width); + listBox->elementHeight = static_cast(commonListBox->m_element_height); + item->special = static_cast(commonListBox->m_feeder); + listBox->elementStyle = commonListBox->m_element_style; + listBox->onDoubleClick = ConvertEventHandlerSet(commonListBox->m_on_double_click.get(), &parentMenu, &commonItem); + ConvertColor(listBox->selectBorder, commonListBox->m_select_border); + listBox->selectIcon = ConvertMaterial(commonListBox->m_select_icon, &parentMenu, &commonItem); + + listBox->numColumns = static_cast(std::min(std::extent_v, commonListBox->m_columns.size())); + for (auto i = 0; i < listBox->numColumns; i++) { + auto &col = listBox->columnInfo[i]; + const auto &commonCol = commonListBox->m_columns[i]; + + col.pos = commonCol.m_x_pos; + col.width = commonCol.m_width; + col.maxChars = commonCol.m_max_chars; + col.alignment = commonCol.m_alignment; + } -MenuConverter::MenuConverter(const bool disableOptimizations, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager) - : m_disable_optimizations(disableOptimizations), - m_search_path(searchPath), - m_memory(memory), - m_manager(manager) -{ -} + return listBox; + } + + _NODISCARD editFieldDef_s *ConvertEditFieldFeatures(itemDef_s *item, CommonItemFeaturesEditField *commonEditField, const CommonMenuDef &parentMenu, + const CommonItemDef &commonItem) const { + if (commonEditField == nullptr) + return nullptr; + + auto *editField = static_cast(m_memory->Alloc(sizeof(editFieldDef_s))); + memset(editField, 0, sizeof(editFieldDef_s)); + + editField->defVal = static_cast(commonEditField->m_def_val); + editField->minVal = static_cast(commonEditField->m_min_val); + editField->maxVal = static_cast(commonEditField->m_max_val); + item->localVar = ConvertString(commonEditField->m_local_var); + editField->maxChars = commonEditField->m_max_chars; + editField->maxCharsGotoNext = commonEditField->m_max_chars_goto_next ? 1 : 0; + editField->maxPaintChars = commonEditField->m_max_paint_chars; + + return editField; + } + + _NODISCARD multiDef_s *ConvertMultiValueFeatures(itemDef_s *item, CommonItemFeaturesMultiValue *commonMultiValue, const CommonMenuDef &parentMenu, + const CommonItemDef &commonItem) const { + if (commonMultiValue == nullptr) + return nullptr; + + auto *multiValue = static_cast(m_memory->Alloc(sizeof(multiDef_s))); + memset(multiValue, 0, sizeof(multiDef_s)); + + multiValue->count = static_cast(std::min(std::extent_v, commonMultiValue->m_step_names.size())); + multiValue->strDef = !commonMultiValue->m_string_values.empty() ? 1 : 0; + + for (auto i = 0; i < multiValue->count; i++) { + multiValue->dvarList[i] = ConvertString(commonMultiValue->m_step_names[i]); + + if (multiValue->strDef) { + if (commonMultiValue->m_string_values.size() > static_cast(i)) + multiValue->dvarStr[i] = ConvertString(commonMultiValue->m_string_values[i]); + } else { + if (commonMultiValue->m_double_values.size() > static_cast(i)) + multiValue->dvarValue[i] = static_cast(commonMultiValue->m_double_values[i]); + } + } -std::vector& MenuConverter::GetDependencies() -{ - return m_dependencies; -} + return multiValue; + } + + _NODISCARD newsTickerDef_s *ConvertNewsTickerFeatures(itemDef_s *item, CommonItemFeaturesNewsTicker *commonNewsTicker, const CommonMenuDef &parentMenu, + const CommonItemDef &commonItem) const { + if (commonNewsTicker == nullptr) + return nullptr; + + auto *newsTicker = static_cast(m_memory->Alloc(sizeof(newsTickerDef_s))); + memset(newsTicker, 0, sizeof(newsTickerDef_s)); + + newsTicker->spacing = commonNewsTicker->m_spacing; + newsTicker->speed = commonNewsTicker->m_speed; + newsTicker->feedId = commonNewsTicker->m_news_feed_id; + + return newsTicker; + } + + _NODISCARD itemDef_s *ConvertItem(const CommonMenuDef &parentMenu, const CommonItemDef &commonItem) const { + auto *item = m_memory->Create(); + memset(item, 0, sizeof(itemDef_s)); + + item->window.name = ConvertString(commonItem.m_name); + item->text = ConvertString(commonItem.m_text); + ApplyFlag(item->itemFlags, commonItem.m_text_save_game, ITEM_FLAG_SAVE_GAME_INFO); + ApplyFlag(item->itemFlags, commonItem.m_text_cinematic_subtitle, ITEM_FLAG_CINEMATIC_SUBTITLE); + item->window.group = ConvertString(commonItem.m_group); + item->window.rectClient = ConvertRectDef(commonItem.m_rect); + item->window.rect = ConvertRectDefRelativeTo(commonItem.m_rect, parentMenu.m_rect); + item->window.style = commonItem.m_style; + ApplyFlag(item->window.staticFlags, commonItem.m_decoration, WINDOW_FLAG_DECORATION); + ApplyFlag(item->window.staticFlags, commonItem.m_auto_wrapped, WINDOW_FLAG_AUTO_WRAPPED); + ApplyFlag(item->window.staticFlags, commonItem.m_horizontal_scroll, WINDOW_FLAG_HORIZONTAL_SCROLL); + item->type = ConvertItemType(commonItem.m_type); + item->dataType = item->type; + item->window.border = commonItem.m_border; + item->window.borderSize = static_cast(commonItem.m_border_size); + item->visibleExp = ConvertVisibleExpression(&item->window, commonItem.m_visible_expression.get(), &parentMenu, &commonItem); + item->disabledExp = ConvertExpression(commonItem.m_disabled_expression.get(), &parentMenu, &commonItem); + item->window.ownerDraw = commonItem.m_owner_draw; + item->window.ownerDrawFlags = commonItem.m_owner_draw_flags; + item->alignment = commonItem.m_align; + item->textAlignMode = commonItem.m_text_align; + item->textalignx = static_cast(commonItem.m_text_align_x); + item->textaligny = static_cast(commonItem.m_text_align_y); + item->textscale = static_cast(commonItem.m_text_scale); + item->textStyle = commonItem.m_text_style; + item->fontEnum = ConvertTextFont(commonItem.m_text_font); + ConvertColor(item->window.backColor, commonItem.m_back_color); + + ConvertColor(item->window.foreColor, commonItem.m_fore_color); + if (!commonItem.m_fore_color.Equals(CommonColor(1.0, 1.0, 1.0, 1.0))) + item->window.dynamicFlags[0] |= WINDOW_FLAG_NON_DEFAULT_FORECOLOR; + + ConvertColor(item->window.borderColor, commonItem.m_border_color); + ConvertColor(item->window.outlineColor, commonItem.m_outline_color); + ConvertColor(item->window.disableColor, commonItem.m_disable_color); + ConvertColor(item->glowColor, commonItem.m_glow_color); + item->window.background = ConvertMaterial(commonItem.m_background, &parentMenu, &commonItem); + item->onFocus = ConvertEventHandlerSet(commonItem.m_on_focus.get(), &parentMenu, &commonItem); + item->leaveFocus = ConvertEventHandlerSet(commonItem.m_on_leave_focus.get(), &parentMenu, &commonItem); + item->mouseEnter = ConvertEventHandlerSet(commonItem.m_on_mouse_enter.get(), &parentMenu, &commonItem); + item->mouseExit = ConvertEventHandlerSet(commonItem.m_on_mouse_exit.get(), &parentMenu, &commonItem); + item->mouseEnterText = ConvertEventHandlerSet(commonItem.m_on_mouse_enter_text.get(), &parentMenu, &commonItem); + item->mouseExitText = ConvertEventHandlerSet(commonItem.m_on_mouse_exit_text.get(), &parentMenu, &commonItem); + item->action = ConvertEventHandlerSet(commonItem.m_on_action.get(), &parentMenu, &commonItem); + item->accept = ConvertEventHandlerSet(commonItem.m_on_accept.get(), &parentMenu, &commonItem); + item->focusSound = ConvertSound(commonItem.m_focus_sound, &parentMenu, &commonItem); + item->dvarTest = ConvertString(commonItem.m_dvar_test); + item->enableDvar = ConvertEnableDvar(commonItem, item->dvarFlags); + item->onKey = ConvertKeyHandler(commonItem.m_key_handlers, &parentMenu, &commonItem); + item->textExp = ConvertOrApplyStatement(item->text, commonItem.m_text_expression.get(), &parentMenu, &commonItem); + item->materialExp = ConvertOrApplyStatement(item->window.background, commonItem.m_material_expression.get(), &parentMenu, &commonItem); + item->disabledExp = ConvertExpression(commonItem.m_disabled_expression.get(), &parentMenu, &commonItem); + item->floatExpressions = ConvertFloatExpressions(&commonItem, item, &parentMenu, item->floatExpressionCount); + item->gameMsgWindowIndex = commonItem.m_game_message_window_index; + item->gameMsgWindowMode = commonItem.m_game_message_window_mode; + item->fxLetterTime = commonItem.m_fx_letter_time; + item->fxDecayStartTime = commonItem.m_fx_decay_start_time; + item->fxDecayDuration = commonItem.m_fx_decay_duration; + item->dvar = ConvertString(commonItem.m_dvar); + + switch (commonItem.m_feature_type) { + case CommonItemFeatureType::LISTBOX: + item->typeData.listBox = ConvertListBoxFeatures(item, commonItem.m_list_box_features.get(), parentMenu, commonItem); + break; + + case CommonItemFeatureType::EDIT_FIELD: + item->typeData.editField = ConvertEditFieldFeatures(item, commonItem.m_edit_field_features.get(), parentMenu, commonItem); + break; + + case CommonItemFeatureType::MULTI_VALUE: + item->typeData.multi = ConvertMultiValueFeatures(item, commonItem.m_multi_value_features.get(), parentMenu, commonItem); + break; + + case CommonItemFeatureType::ENUM_DVAR: + item->typeData.enumDvarName = ConvertString(commonItem.m_enum_dvar_name); + break; + + case CommonItemFeatureType::NEWS_TICKER: + item->typeData.ticker = ConvertNewsTickerFeatures(item, commonItem.m_news_ticker_features.get(), parentMenu, commonItem); + break; + + case CommonItemFeatureType::NONE: + default: + if (item->type == ITEM_TYPE_TEXT_SCROLL) { + item->typeData.scroll = static_cast(m_memory->Alloc(sizeof(textScrollDef_s))); + memset(item->typeData.scroll, 0, sizeof(textScrollDef_s)); + } + break; + } -menuDef_t* MenuConverter::ConvertMenu(const CommonMenuDef& commonMenu) -{ - MenuConverterImpl impl(m_disable_optimizations, m_search_path, m_memory, m_manager); + return item; + } - try - { - auto* result = impl.ConvertMenu(commonMenu); - m_dependencies = std::move(impl.m_dependencies); - return result; - } - catch (const MenuConversionException& e) - { - MenuConverterImpl::PrintConversionExceptionDetails(e); + itemDef_s **ConvertMenuItems(const CommonMenuDef &commonMenu, int &itemCount) const { + if (commonMenu.m_items.empty()) { + itemCount = 0; + return nullptr; } - return nullptr; + auto *items = static_cast(m_memory->Alloc(sizeof(void *) * commonMenu.m_items.size())); + memset(items, 0, sizeof(void *) * commonMenu.m_items.size()); + + for (auto i = 0u; i < commonMenu.m_items.size(); i++) + items[i] = ConvertItem(commonMenu, *commonMenu.m_items[i]); + + itemCount = static_cast(commonMenu.m_items.size()); + + return items; + } + +public: + MenuConverterImpl(const bool disableOptimizations, ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager) + : AbstractMenuConverter(disableOptimizations, searchPath, memory, manager), + m_conversion_zone_state(manager->GetAssetLoadingContext()->GetZoneAssetLoaderState()), + m_parsing_zone_state(manager->GetAssetLoadingContext()->GetZoneAssetLoaderState()) { + assert(m_conversion_zone_state); + assert(m_parsing_zone_state); + } + + _NODISCARD menuDef_t *ConvertMenu(const CommonMenuDef &commonMenu) const { + auto *menu = m_memory->Create(); + memset(menu, 0, sizeof(menuDef_t)); + + menu->window.name = m_memory->Dup(commonMenu.m_name.c_str()); + menu->fullScreen = commonMenu.m_full_screen; + ApplyFlag(menu->window.staticFlags, commonMenu.m_screen_space, WINDOW_FLAG_SCREEN_SPACE); + ApplyFlag(menu->window.staticFlags, commonMenu.m_decoration, WINDOW_FLAG_DECORATION); + menu->window.rect = ConvertRectDef(commonMenu.m_rect); + menu->window.style = commonMenu.m_style; + menu->window.border = commonMenu.m_border; + menu->window.borderSize = static_cast(commonMenu.m_border_size); + ConvertColor(menu->window.backColor, commonMenu.m_back_color); + ConvertColor(menu->window.foreColor, commonMenu.m_fore_color); + ConvertColor(menu->window.borderColor, commonMenu.m_border_color); + ConvertColor(menu->focusColor, commonMenu.m_focus_color); + menu->window.background = ConvertMaterial(commonMenu.m_background, &commonMenu); + menu->window.ownerDraw = commonMenu.m_owner_draw; + menu->window.ownerDrawFlags = commonMenu.m_owner_draw_flags; + ApplyFlag(menu->window.staticFlags, commonMenu.m_out_of_bounds_click, WINDOW_FLAG_OUT_OF_BOUNDS_CLICK); + menu->soundName = ConvertString(commonMenu.m_sound_loop); + ApplyFlag(menu->window.staticFlags, commonMenu.m_popup, WINDOW_FLAG_POPUP); + menu->fadeClamp = static_cast(commonMenu.m_fade_clamp); + menu->fadeCycle = commonMenu.m_fade_cycle; + menu->fadeAmount = static_cast(commonMenu.m_fade_amount); + menu->fadeInAmount = static_cast(commonMenu.m_fade_in_amount); + menu->blurRadius = static_cast(commonMenu.m_blur_radius); + ApplyFlag(menu->window.staticFlags, commonMenu.m_legacy_split_screen_scale, WINDOW_FLAG_LEGACY_SPLIT_SCREEN_SCALE); + ApplyFlag(menu->window.staticFlags, commonMenu.m_hidden_during_scope, WINDOW_FLAG_HIDDEN_DURING_SCOPE); + ApplyFlag(menu->window.staticFlags, commonMenu.m_hidden_during_flashbang, WINDOW_FLAG_HIDDEN_DURING_FLASH_BANG); + ApplyFlag(menu->window.staticFlags, commonMenu.m_hidden_during_ui, WINDOW_FLAG_HIDDEN_DURING_UI); + menu->allowedBinding = ConvertString(commonMenu.m_allowed_binding); + ApplyFlag(menu->window.staticFlags, commonMenu.m_text_only_focus, WINDOW_FLAG_TEXT_ONLY_FOCUS); + menu->visibleExp = ConvertVisibleExpression(&menu->window, commonMenu.m_visible_expression.get(), &commonMenu); + menu->rectXExp = ConvertOrApplyStatement(menu->window.rect.x, commonMenu.m_rect_x_exp.get(), &commonMenu); + menu->rectYExp = ConvertOrApplyStatement(menu->window.rect.y, commonMenu.m_rect_y_exp.get(), &commonMenu); + menu->rectWExp = ConvertOrApplyStatement(menu->window.rect.w, commonMenu.m_rect_w_exp.get(), &commonMenu); + menu->rectHExp = ConvertOrApplyStatement(menu->window.rect.h, commonMenu.m_rect_h_exp.get(), &commonMenu); + menu->openSoundExp = ConvertExpression(commonMenu.m_open_sound_exp.get(), &commonMenu); + menu->closeSoundExp = ConvertExpression(commonMenu.m_close_sound_exp.get(), &commonMenu); + menu->onOpen = ConvertEventHandlerSet(commonMenu.m_on_open.get(), &commonMenu); + menu->onClose = ConvertEventHandlerSet(commonMenu.m_on_close.get(), &commonMenu); + menu->onCloseRequest = ConvertEventHandlerSet(commonMenu.m_on_request_close.get(), &commonMenu); + menu->onESC = ConvertEventHandlerSet(commonMenu.m_on_esc.get(), &commonMenu); + menu->onKey = ConvertKeyHandler(commonMenu.m_key_handlers, &commonMenu); + menu->items = ConvertMenuItems(commonMenu, menu->itemCount); + menu->expressionData = m_conversion_zone_state->m_supporting_data; + + return menu; + } + + std::vector m_dependencies; +}; +} // namespace IW4 + +MenuConverter::MenuConverter(const bool disableOptimizations, ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager) + : m_disable_optimizations(disableOptimizations), m_search_path(searchPath), m_memory(memory), m_manager(manager) {} + +std::vector &MenuConverter::GetDependencies() { return m_dependencies; } + +menuDef_t *MenuConverter::ConvertMenu(const CommonMenuDef &commonMenu) { + MenuConverterImpl impl(m_disable_optimizations, m_search_path, m_memory, m_manager); + + try { + auto *result = impl.ConvertMenu(commonMenu); + m_dependencies = std::move(impl.m_dependencies); + return result; + } catch (const MenuConversionException &e) { + MenuConverterImpl::PrintConversionExceptionDetails(e); + } + + return nullptr; } diff --git a/src/ObjLoading/Game/IW4/Menu/MenuConverterIW4.h b/src/ObjLoading/Game/IW4/Menu/MenuConverterIW4.h index 9dbdcb803..bd5395ebd 100644 --- a/src/ObjLoading/Game/IW4/Menu/MenuConverterIW4.h +++ b/src/ObjLoading/Game/IW4/Menu/MenuConverterIW4.h @@ -1,26 +1,24 @@ #pragma once -#include "Utils/ClassUtils.h" #include "AssetLoading/IAssetLoadingManager.h" #include "Game/IW4/IW4.h" #include "Parsing/Menu/Domain/CommonMenuDef.h" -#include "Utils/MemoryManager.h" #include "SearchPath/ISearchPath.h" +#include "Utils/ClassUtils.h" +#include "Utils/MemoryManager.h" -namespace IW4 -{ - class MenuConverter - { - bool m_disable_optimizations; - ISearchPath* m_search_path; - MemoryManager* m_memory; - IAssetLoadingManager* m_manager; - std::vector m_dependencies; +namespace IW4 { +class MenuConverter { + bool m_disable_optimizations; + ISearchPath *m_search_path; + MemoryManager *m_memory; + IAssetLoadingManager *m_manager; + std::vector m_dependencies; - public: - MenuConverter(bool disableOptimizations, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager); +public: + MenuConverter(bool disableOptimizations, ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager); - std::vector& GetDependencies(); - _NODISCARD menuDef_t* ConvertMenu(const menu::CommonMenuDef& commonMenu); - }; -} + std::vector &GetDependencies(); + _NODISCARD menuDef_t *ConvertMenu(const menu::CommonMenuDef &commonMenu); +}; +} // namespace IW4 diff --git a/src/ObjLoading/Game/IW4/ObjLoaderIW4.cpp b/src/ObjLoading/Game/IW4/ObjLoaderIW4.cpp index 6bb437936..588007831 100644 --- a/src/ObjLoading/Game/IW4/ObjLoaderIW4.cpp +++ b/src/ObjLoading/Game/IW4/ObjLoaderIW4.cpp @@ -1,9 +1,5 @@ #include "ObjLoaderIW4.h" -#include "Game/IW4/GameIW4.h" -#include "Game/IW4/GameAssetPoolIW4.h" -#include "ObjContainer/IPak/IPak.h" -#include "ObjLoading.h" #include "AssetLoaders/AssetLoaderAddonMapEnts.h" #include "AssetLoaders/AssetLoaderClipMap.h" #include "AssetLoaders/AssetLoaderComWorld.h" @@ -41,188 +37,160 @@ #include "AssetLoaders/AssetLoaderXModel.h" #include "AssetLoaders/AssetLoaderXModelSurfs.h" #include "AssetLoading/AssetLoadingManager.h" +#include "Game/IW4/GameAssetPoolIW4.h" +#include "Game/IW4/GameIW4.h" #include "Image/Dx9TextureLoader.h" -#include "Image/Texture.h" #include "Image/IwiLoader.h" #include "Image/IwiTypes.h" +#include "Image/Texture.h" +#include "ObjContainer/IPak/IPak.h" +#include "ObjLoading.h" using namespace IW4; -ObjLoader::ObjLoader() -{ -#define REGISTER_ASSET_LOADER(t) {auto l = std::make_unique(); m_asset_loaders_by_type[l->GetHandlingAssetType()] = std::move(l);} - - REGISTER_ASSET_LOADER(AssetLoaderPhysPreset) - REGISTER_ASSET_LOADER(AssetLoaderPhysCollmap) - REGISTER_ASSET_LOADER(AssetLoaderXAnim) - REGISTER_ASSET_LOADER(AssetLoaderXModelSurfs) - REGISTER_ASSET_LOADER(AssetLoaderXModel) - REGISTER_ASSET_LOADER(AssetLoaderMaterial) - REGISTER_ASSET_LOADER(AssetLoaderPixelShader) - REGISTER_ASSET_LOADER(AssetLoaderVertexShader) - REGISTER_ASSET_LOADER(AssetLoaderVertexDecl) - REGISTER_ASSET_LOADER(AssetLoaderTechniqueSet) - REGISTER_ASSET_LOADER(AssetLoaderGfxImage) - REGISTER_ASSET_LOADER(AssetLoaderSoundAliasList) - REGISTER_ASSET_LOADER(AssetLoaderSndCurve) - REGISTER_ASSET_LOADER(AssetLoaderLoadedSound) - REGISTER_ASSET_LOADER(AssetLoaderClipMapSp) - REGISTER_ASSET_LOADER(AssetLoaderClipMapMp) - REGISTER_ASSET_LOADER(AssetLoaderComWorld) - REGISTER_ASSET_LOADER(AssetLoaderGameWorldSp) - REGISTER_ASSET_LOADER(AssetLoaderGameWorldMp) - REGISTER_ASSET_LOADER(AssetLoaderMapEnts) - REGISTER_ASSET_LOADER(AssetLoaderFxWorld) - REGISTER_ASSET_LOADER(AssetLoaderGfxWorld) - REGISTER_ASSET_LOADER(AssetLoaderGfxLightDef) - REGISTER_ASSET_LOADER(AssetLoaderFont) - REGISTER_ASSET_LOADER(AssetLoaderMenuList) - REGISTER_ASSET_LOADER(AssetLoaderMenuDef) - REGISTER_ASSET_LOADER(AssetLoaderLocalizeEntry) - REGISTER_ASSET_LOADER(AssetLoaderWeapon) - REGISTER_ASSET_LOADER(AssetLoaderFx) - REGISTER_ASSET_LOADER(AssetLoaderFxImpactTable) - REGISTER_ASSET_LOADER(AssetLoaderRawFile) - REGISTER_ASSET_LOADER(AssetLoaderStringTable) - REGISTER_ASSET_LOADER(AssetLoaderLeaderboard) - REGISTER_ASSET_LOADER(AssetLoaderStructuredDataDefSet) - REGISTER_ASSET_LOADER(AssetLoaderTracer) - REGISTER_ASSET_LOADER(AssetLoaderVehicle) - REGISTER_ASSET_LOADER(AssetLoaderAddonMapEnts) - +ObjLoader::ObjLoader() { +#define REGISTER_ASSET_LOADER(t) \ + { \ + auto l = std::make_unique(); \ + m_asset_loaders_by_type[l->GetHandlingAssetType()] = std::move(l); \ + } + + REGISTER_ASSET_LOADER(AssetLoaderPhysPreset) + REGISTER_ASSET_LOADER(AssetLoaderPhysCollmap) + REGISTER_ASSET_LOADER(AssetLoaderXAnim) + REGISTER_ASSET_LOADER(AssetLoaderXModelSurfs) + REGISTER_ASSET_LOADER(AssetLoaderXModel) + REGISTER_ASSET_LOADER(AssetLoaderMaterial) + REGISTER_ASSET_LOADER(AssetLoaderPixelShader) + REGISTER_ASSET_LOADER(AssetLoaderVertexShader) + REGISTER_ASSET_LOADER(AssetLoaderVertexDecl) + REGISTER_ASSET_LOADER(AssetLoaderTechniqueSet) + REGISTER_ASSET_LOADER(AssetLoaderGfxImage) + REGISTER_ASSET_LOADER(AssetLoaderSoundAliasList) + REGISTER_ASSET_LOADER(AssetLoaderSndCurve) + REGISTER_ASSET_LOADER(AssetLoaderLoadedSound) + REGISTER_ASSET_LOADER(AssetLoaderClipMapSp) + REGISTER_ASSET_LOADER(AssetLoaderClipMapMp) + REGISTER_ASSET_LOADER(AssetLoaderComWorld) + REGISTER_ASSET_LOADER(AssetLoaderGameWorldSp) + REGISTER_ASSET_LOADER(AssetLoaderGameWorldMp) + REGISTER_ASSET_LOADER(AssetLoaderMapEnts) + REGISTER_ASSET_LOADER(AssetLoaderFxWorld) + REGISTER_ASSET_LOADER(AssetLoaderGfxWorld) + REGISTER_ASSET_LOADER(AssetLoaderGfxLightDef) + REGISTER_ASSET_LOADER(AssetLoaderFont) + REGISTER_ASSET_LOADER(AssetLoaderMenuList) + REGISTER_ASSET_LOADER(AssetLoaderMenuDef) + REGISTER_ASSET_LOADER(AssetLoaderLocalizeEntry) + REGISTER_ASSET_LOADER(AssetLoaderWeapon) + REGISTER_ASSET_LOADER(AssetLoaderFx) + REGISTER_ASSET_LOADER(AssetLoaderFxImpactTable) + REGISTER_ASSET_LOADER(AssetLoaderRawFile) + REGISTER_ASSET_LOADER(AssetLoaderStringTable) + REGISTER_ASSET_LOADER(AssetLoaderLeaderboard) + REGISTER_ASSET_LOADER(AssetLoaderStructuredDataDefSet) + REGISTER_ASSET_LOADER(AssetLoaderTracer) + REGISTER_ASSET_LOADER(AssetLoaderVehicle) + REGISTER_ASSET_LOADER(AssetLoaderAddonMapEnts) + #undef REGISTER_ASSET_LOADER } -bool ObjLoader::SupportsZone(Zone* zone) const -{ - return zone->m_game == &g_GameIW4; -} +bool ObjLoader::SupportsZone(Zone *zone) const { return zone->m_game == &g_GameIW4; } -bool ObjLoader::IsMpZone(Zone* zone) -{ - return zone->m_name.compare(0, 3, "mp_") == 0 - || zone->m_name.compare(zone->m_name.length() - 3, 3, "_mp") == 0; -} +bool ObjLoader::IsMpZone(Zone *zone) { return zone->m_name.compare(0, 3, "mp_") == 0 || zone->m_name.compare(zone->m_name.length() - 3, 3, "_mp") == 0; } -bool ObjLoader::IsZmZone(Zone* zone) -{ - return zone->m_name.compare(0, 3, "zm_") == 0 - || zone->m_name.compare(zone->m_name.length() - 3, 3, "_zm") == 0; -} +bool ObjLoader::IsZmZone(Zone *zone) { return zone->m_name.compare(0, 3, "zm_") == 0 || zone->m_name.compare(zone->m_name.length() - 3, 3, "_zm") == 0; } -void ObjLoader::LoadReferencedContainersForZone(ISearchPath* searchPath, Zone* zone) const -{ -} +void ObjLoader::LoadReferencedContainersForZone(ISearchPath *searchPath, Zone *zone) const {} -void ObjLoader::UnloadContainersOfZone(Zone* zone) const -{ -} +void ObjLoader::UnloadContainersOfZone(Zone *zone) const {} -void ObjLoader::LoadImageFromLoadDef(GfxImage* image, Zone* zone) -{ - const auto* loadDef = image->texture.loadDef; - Dx9TextureLoader textureLoader(zone->GetMemory()); +void ObjLoader::LoadImageFromLoadDef(GfxImage *image, Zone *zone) { + const auto *loadDef = image->texture.loadDef; + Dx9TextureLoader textureLoader(zone->GetMemory()); - textureLoader.Width(image->width).Height(image->height).Depth(image->depth); + textureLoader.Width(image->width).Height(image->height).Depth(image->depth); - if ((loadDef->flags & iwi8::IMG_FLAG_MAPTYPE_MASK) == iwi8::IMG_FLAG_MAPTYPE_3D) - textureLoader.Type(TextureType::T_3D); - else if ((loadDef->flags & iwi8::IMG_FLAG_MAPTYPE_MASK) == iwi8::IMG_FLAG_MAPTYPE_CUBE) - textureLoader.Type(TextureType::T_CUBE); - else - textureLoader.Type(TextureType::T_2D); + if ((loadDef->flags & iwi8::IMG_FLAG_MAPTYPE_MASK) == iwi8::IMG_FLAG_MAPTYPE_3D) + textureLoader.Type(TextureType::T_3D); + else if ((loadDef->flags & iwi8::IMG_FLAG_MAPTYPE_MASK) == iwi8::IMG_FLAG_MAPTYPE_CUBE) + textureLoader.Type(TextureType::T_CUBE); + else + textureLoader.Type(TextureType::T_2D); - textureLoader.Format(static_cast(loadDef->format)); - textureLoader.HasMipMaps(!(loadDef->flags & iwi8::IMG_FLAG_NOMIPMAPS)); - Texture* loadedTexture = textureLoader.LoadTexture(image->texture.loadDef->data); + textureLoader.Format(static_cast(loadDef->format)); + textureLoader.HasMipMaps(!(loadDef->flags & iwi8::IMG_FLAG_NOMIPMAPS)); + Texture *loadedTexture = textureLoader.LoadTexture(image->texture.loadDef->data); - if (loadedTexture != nullptr) - { - image->texture.texture = loadedTexture; - image->cardMemory.platform[0] = 0; + if (loadedTexture != nullptr) { + image->texture.texture = loadedTexture; + image->cardMemory.platform[0] = 0; - const auto textureMipCount = loadedTexture->GetMipMapCount(); - for (auto mipLevel = 0; mipLevel < textureMipCount; mipLevel++) - image->cardMemory.platform[0] += static_cast(loadedTexture->GetSizeOfMipLevel(mipLevel) * loadedTexture->GetFaceCount()); - } + const auto textureMipCount = loadedTexture->GetMipMapCount(); + for (auto mipLevel = 0; mipLevel < textureMipCount; mipLevel++) + image->cardMemory.platform[0] += static_cast(loadedTexture->GetSizeOfMipLevel(mipLevel) * loadedTexture->GetFaceCount()); + } } -void ObjLoader::LoadImageFromIwi(GfxImage* image, ISearchPath* searchPath, Zone* zone) -{ - Texture* loadedTexture = nullptr; - IwiLoader loader(zone->GetMemory()); +void ObjLoader::LoadImageFromIwi(GfxImage *image, ISearchPath *searchPath, Zone *zone) { + Texture *loadedTexture = nullptr; + IwiLoader loader(zone->GetMemory()); - const auto imageFileName = "images/" + std::string(image->name) + ".iwi"; + const auto imageFileName = "images/" + std::string(image->name) + ".iwi"; - { - const auto filePathImage = searchPath->Open(imageFileName); - if (filePathImage.IsOpen()) - { - loadedTexture = loader.LoadIwi(*filePathImage.m_stream); - } + { + const auto filePathImage = searchPath->Open(imageFileName); + if (filePathImage.IsOpen()) { + loadedTexture = loader.LoadIwi(*filePathImage.m_stream); } + } + + if (loadedTexture != nullptr) { + image->texture.texture = loadedTexture; + image->cardMemory.platform[0] = 0; + + const auto textureMipCount = loadedTexture->GetMipMapCount(); + for (auto mipLevel = 0; mipLevel < textureMipCount; mipLevel++) + image->cardMemory.platform[0] += static_cast(loadedTexture->GetSizeOfMipLevel(mipLevel) * loadedTexture->GetFaceCount()); + } else { + printf("Could not find data for image \"%s\"\n", image->name); + } +} - if (loadedTexture != nullptr) - { - image->texture.texture = loadedTexture; - image->cardMemory.platform[0] = 0; +void ObjLoader::LoadImageData(ISearchPath *searchPath, Zone *zone) { + auto *assetPool = dynamic_cast(zone->m_pools.get()); - const auto textureMipCount = loadedTexture->GetMipMapCount(); - for (auto mipLevel = 0; mipLevel < textureMipCount; mipLevel++) - image->cardMemory.platform[0] += static_cast(loadedTexture->GetSizeOfMipLevel(mipLevel) * loadedTexture->GetFaceCount()); - } - else - { - printf("Could not find data for image \"%s\"\n", image->name); - } -} + if (assetPool && assetPool->m_image != nullptr) { + for (auto *imageEntry : *assetPool->m_image) { + auto *image = imageEntry->Asset(); -void ObjLoader::LoadImageData(ISearchPath* searchPath, Zone* zone) -{ - auto* assetPool = dynamic_cast(zone->m_pools.get()); - - if (assetPool && assetPool->m_image != nullptr) - { - for (auto* imageEntry : *assetPool->m_image) - { - auto* image = imageEntry->Asset(); - - if (image->cardMemory.platform[0] > 0) - { - continue; - } - - // Do not load linked assets - if (image->name && image->name[0] == ',') - { - continue; - } - - if (image->texture.loadDef && image->texture.loadDef->resourceSize > 0) - { - LoadImageFromLoadDef(image, zone); - } - else - { - LoadImageFromIwi(image, searchPath, zone); - } - } + if (image->cardMemory.platform[0] > 0) { + continue; + } + + // Do not load linked assets + if (image->name && image->name[0] == ',') { + continue; + } + + if (image->texture.loadDef && image->texture.loadDef->resourceSize > 0) { + LoadImageFromLoadDef(image, zone); + } else { + LoadImageFromIwi(image, searchPath, zone); + } } + } } -void ObjLoader::LoadObjDataForZone(ISearchPath* searchPath, Zone* zone) const -{ - LoadImageData(searchPath, zone); -} +void ObjLoader::LoadObjDataForZone(ISearchPath *searchPath, Zone *zone) const { LoadImageData(searchPath, zone); } -bool ObjLoader::LoadAssetForZone(AssetLoadingContext* context, asset_type_t assetType, const std::string& assetName) const -{ - AssetLoadingManager assetLoadingManager(m_asset_loaders_by_type, *context); - return assetLoadingManager.LoadAssetFromLoader(assetType, assetName); +bool ObjLoader::LoadAssetForZone(AssetLoadingContext *context, asset_type_t assetType, const std::string &assetName) const { + AssetLoadingManager assetLoadingManager(m_asset_loaders_by_type, *context); + return assetLoadingManager.LoadAssetFromLoader(assetType, assetName); } -void ObjLoader::FinalizeAssetsForZone(AssetLoadingContext* context) const -{ - for (const auto& [type, loader] : m_asset_loaders_by_type) - loader->FinalizeAssetsForZone(context); +void ObjLoader::FinalizeAssetsForZone(AssetLoadingContext *context) const { + for (const auto &[type, loader] : m_asset_loaders_by_type) + loader->FinalizeAssetsForZone(context); } diff --git a/src/ObjLoading/Game/IW4/ObjLoaderIW4.h b/src/ObjLoading/Game/IW4/ObjLoaderIW4.h index 5a24078a7..354b33147 100644 --- a/src/ObjLoading/Game/IW4/ObjLoaderIW4.h +++ b/src/ObjLoading/Game/IW4/ObjLoaderIW4.h @@ -3,35 +3,33 @@ #include #include -#include "IObjLoader.h" #include "AssetLoading/IAssetLoader.h" -#include "SearchPath/ISearchPath.h" #include "Game/IW4/IW4.h" +#include "IObjLoader.h" +#include "SearchPath/ISearchPath.h" -namespace IW4 -{ - class ObjLoader final : public IObjLoader - { - std::map> m_asset_loaders_by_type; +namespace IW4 { +class ObjLoader final : public IObjLoader { + std::map> m_asset_loaders_by_type; - static void LoadImageFromIwi(GfxImage* image, ISearchPath* searchPath, Zone* zone); - static void LoadImageFromLoadDef(GfxImage* image, Zone* zone); - static void LoadImageData(ISearchPath* searchPath, Zone* zone); + static void LoadImageFromIwi(GfxImage *image, ISearchPath *searchPath, Zone *zone); + static void LoadImageFromLoadDef(GfxImage *image, Zone *zone); + static void LoadImageData(ISearchPath *searchPath, Zone *zone); - static bool IsMpZone(Zone* zone); - static bool IsZmZone(Zone* zone); + static bool IsMpZone(Zone *zone); + static bool IsZmZone(Zone *zone); - public: - ObjLoader(); +public: + ObjLoader(); - bool SupportsZone(Zone* zone) const override; + bool SupportsZone(Zone *zone) const override; - void LoadReferencedContainersForZone(ISearchPath* searchPath, Zone* zone) const override; - void UnloadContainersOfZone(Zone* zone) const override; + void LoadReferencedContainersForZone(ISearchPath *searchPath, Zone *zone) const override; + void UnloadContainersOfZone(Zone *zone) const override; - void LoadObjDataForZone(ISearchPath* searchPath, Zone* zone) const override; + void LoadObjDataForZone(ISearchPath *searchPath, Zone *zone) const override; - bool LoadAssetForZone(AssetLoadingContext* context, asset_type_t assetType, const std::string& assetName) const override; - void FinalizeAssetsForZone(AssetLoadingContext* context) const override; - }; -} + bool LoadAssetForZone(AssetLoadingContext *context, asset_type_t assetType, const std::string &assetName) const override; + void FinalizeAssetsForZone(AssetLoadingContext *context) const override; +}; +} // namespace IW4 diff --git a/src/ObjLoading/Game/IW5/AssetLoaders/AssetLoaderLocalizeEntry.cpp b/src/ObjLoading/Game/IW5/AssetLoaders/AssetLoaderLocalizeEntry.cpp index f5eb59783..603ee49bb 100644 --- a/src/ObjLoading/Game/IW5/AssetLoaders/AssetLoaderLocalizeEntry.cpp +++ b/src/ObjLoading/Game/IW5/AssetLoaders/AssetLoaderLocalizeEntry.cpp @@ -7,45 +7,35 @@ using namespace IW5; -XAssetInfoGeneric* AssetLoaderLocalizeEntry::LoadFromGlobalAssetPools(const std::string& assetName) const -{ - return nullptr; -} +XAssetInfoGeneric *AssetLoaderLocalizeEntry::LoadFromGlobalAssetPools(const std::string &assetName) const { return nullptr; } -void* AssetLoaderLocalizeEntry::CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) -{ - return nullptr; -} +void *AssetLoaderLocalizeEntry::CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) { return nullptr; } -bool AssetLoaderLocalizeEntry::CanLoadFromRaw() const -{ - return true; -} +bool AssetLoaderLocalizeEntry::CanLoadFromRaw() const { return true; } -bool AssetLoaderLocalizeEntry::LoadFromRaw(const std::string& assetName, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const -{ - std::string fileName; - { - std::ostringstream str; - str << LocalizeCommon::GetNameOfLanguage(zone->m_language) << "/localizedstrings/" << assetName << ".str"; - fileName = str.str(); - } +bool AssetLoaderLocalizeEntry::LoadFromRaw(const std::string &assetName, ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager, + Zone *zone) const { + std::string fileName; + { + std::ostringstream str; + str << LocalizeCommon::GetNameOfLanguage(zone->m_language) << "/localizedstrings/" << assetName << ".str"; + fileName = str.str(); + } - const auto file = searchPath->Open(fileName); - if (!file.IsOpen()) - return false; + const auto file = searchPath->Open(fileName); + if (!file.IsOpen()) + return false; - LocalizeFileReader reader(*file.m_stream, assetName, zone->m_language); - const auto localizeEntries = reader.ReadLocalizeFile(); + LocalizeFileReader reader(*file.m_stream, assetName, zone->m_language); + const auto localizeEntries = reader.ReadLocalizeFile(); - for (const auto& entry : localizeEntries) - { - auto* localizeEntry = memory->Create(); - localizeEntry->name = memory->Dup(entry.m_key.c_str()); - localizeEntry->value = memory->Dup(entry.m_value.c_str()); + for (const auto &entry : localizeEntries) { + auto *localizeEntry = memory->Create(); + localizeEntry->name = memory->Dup(entry.m_key.c_str()); + localizeEntry->value = memory->Dup(entry.m_value.c_str()); - manager->AddAsset(ASSET_TYPE_LOCALIZE_ENTRY, entry.m_key, localizeEntry); - } + manager->AddAsset(ASSET_TYPE_LOCALIZE_ENTRY, entry.m_key, localizeEntry); + } - return true; + return true; } diff --git a/src/ObjLoading/Game/IW5/AssetLoaders/AssetLoaderLocalizeEntry.h b/src/ObjLoading/Game/IW5/AssetLoaders/AssetLoaderLocalizeEntry.h index 8d4c21c4a..db5e289d5 100644 --- a/src/ObjLoading/Game/IW5/AssetLoaders/AssetLoaderLocalizeEntry.h +++ b/src/ObjLoading/Game/IW5/AssetLoaders/AssetLoaderLocalizeEntry.h @@ -1,17 +1,15 @@ #pragma once -#include "Game/IW5/IW5.h" #include "AssetLoading/BasicAssetLoader.h" #include "AssetLoading/IAssetLoadingManager.h" +#include "Game/IW5/IW5.h" #include "SearchPath/ISearchPath.h" -namespace IW5 -{ - class AssetLoaderLocalizeEntry final : public BasicAssetLoader - { - public: - _NODISCARD XAssetInfoGeneric* LoadFromGlobalAssetPools(const std::string& assetName) const override; - _NODISCARD void* CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) override; - _NODISCARD bool CanLoadFromRaw() const override; - bool LoadFromRaw(const std::string& assetName, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const override; - }; -} +namespace IW5 { +class AssetLoaderLocalizeEntry final : public BasicAssetLoader { +public: + _NODISCARD XAssetInfoGeneric *LoadFromGlobalAssetPools(const std::string &assetName) const override; + _NODISCARD void *CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) override; + _NODISCARD bool CanLoadFromRaw() const override; + bool LoadFromRaw(const std::string &assetName, ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager, Zone *zone) const override; +}; +} // namespace IW5 diff --git a/src/ObjLoading/Game/IW5/AssetLoaders/AssetLoaderMaterial.cpp b/src/ObjLoading/Game/IW5/AssetLoaders/AssetLoaderMaterial.cpp index 8bd593202..ebfccb866 100644 --- a/src/ObjLoading/Game/IW5/AssetLoaders/AssetLoaderMaterial.cpp +++ b/src/ObjLoading/Game/IW5/AssetLoaders/AssetLoaderMaterial.cpp @@ -2,17 +2,16 @@ #include -#include "ObjLoading.h" #include "Game/IW5/IW5.h" +#include "ObjLoading.h" #include "Pool/GlobalAssetPool.h" using namespace IW5; -void* AssetLoaderMaterial::CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) -{ - auto* material = memory->Create(); - memset(material, 0, sizeof(Material)); - material->info.name = memory->Dup(assetName.c_str()); +void *AssetLoaderMaterial::CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) { + auto *material = memory->Create(); + memset(material, 0, sizeof(Material)); + material->info.name = memory->Dup(assetName.c_str()); - return material; + return material; } diff --git a/src/ObjLoading/Game/IW5/AssetLoaders/AssetLoaderMaterial.h b/src/ObjLoading/Game/IW5/AssetLoaders/AssetLoaderMaterial.h index d283e74e8..264a4d490 100644 --- a/src/ObjLoading/Game/IW5/AssetLoaders/AssetLoaderMaterial.h +++ b/src/ObjLoading/Game/IW5/AssetLoaders/AssetLoaderMaterial.h @@ -1,14 +1,12 @@ #pragma once -#include "Game/IW5/IW5.h" #include "AssetLoading/BasicAssetLoader.h" +#include "Game/IW5/IW5.h" #include "SearchPath/ISearchPath.h" -namespace IW5 -{ - class AssetLoaderMaterial final : public BasicAssetLoader - { - public: - _NODISCARD void* CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) override; - }; -} +namespace IW5 { +class AssetLoaderMaterial final : public BasicAssetLoader { +public: + _NODISCARD void *CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) override; +}; +} // namespace IW5 diff --git a/src/ObjLoading/Game/IW5/AssetLoaders/AssetLoaderMenuDef.cpp b/src/ObjLoading/Game/IW5/AssetLoaders/AssetLoaderMenuDef.cpp index d72739a78..2d1e5d040 100644 --- a/src/ObjLoading/Game/IW5/AssetLoaders/AssetLoaderMenuDef.cpp +++ b/src/ObjLoading/Game/IW5/AssetLoaders/AssetLoaderMenuDef.cpp @@ -2,16 +2,15 @@ #include -#include "ObjLoading.h" #include "Game/IW5/IW5.h" +#include "ObjLoading.h" #include "Pool/GlobalAssetPool.h" using namespace IW5; -void* AssetLoaderMenuDef::CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) -{ - auto* menu = memory->Create(); - memset(menu, 0, sizeof(menuDef_t)); - menu->window.name = memory->Dup(assetName.c_str()); - return menu; +void *AssetLoaderMenuDef::CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) { + auto *menu = memory->Create(); + memset(menu, 0, sizeof(menuDef_t)); + menu->window.name = memory->Dup(assetName.c_str()); + return menu; } diff --git a/src/ObjLoading/Game/IW5/AssetLoaders/AssetLoaderMenuDef.h b/src/ObjLoading/Game/IW5/AssetLoaders/AssetLoaderMenuDef.h index 8bf0bf906..3c4703786 100644 --- a/src/ObjLoading/Game/IW5/AssetLoaders/AssetLoaderMenuDef.h +++ b/src/ObjLoading/Game/IW5/AssetLoaders/AssetLoaderMenuDef.h @@ -1,14 +1,12 @@ #pragma once -#include "Game/IW5/IW5.h" #include "AssetLoading/BasicAssetLoader.h" +#include "Game/IW5/IW5.h" #include "SearchPath/ISearchPath.h" -namespace IW5 -{ - class AssetLoaderMenuDef final : public BasicAssetLoader - { - public: - _NODISCARD void* CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) override; - }; -} +namespace IW5 { +class AssetLoaderMenuDef final : public BasicAssetLoader { +public: + _NODISCARD void *CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) override; +}; +} // namespace IW5 diff --git a/src/ObjLoading/Game/IW5/AssetLoaders/AssetLoaderMenuList.cpp b/src/ObjLoading/Game/IW5/AssetLoaders/AssetLoaderMenuList.cpp index 10a75ace0..3bd304044 100644 --- a/src/ObjLoading/Game/IW5/AssetLoaders/AssetLoaderMenuList.cpp +++ b/src/ObjLoading/Game/IW5/AssetLoaders/AssetLoaderMenuList.cpp @@ -3,205 +3,184 @@ #include #include -#include "ObjLoading.h" #include "Game/IW5/IW5.h" #include "Game/IW5/Menu/MenuConversionZoneStateIW5.h" #include "Game/IW5/Menu/MenuConverterIW5.h" +#include "ObjLoading.h" #include "Parsing/Menu/MenuFileReader.h" #include "Pool/GlobalAssetPool.h" using namespace IW5; -namespace IW5 -{ - class MenuLoader - { - public: - static bool ProcessParsedResults(const std::string& fileName, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager, menu::ParsingResult* parsingResult, - menu::MenuAssetZoneState* zoneState, MenuConversionZoneState* conversionState, std::vector& menus, - std::vector& menuListDependencies) - { - const auto menuCount = parsingResult->m_menus.size(); - const auto functionCount = parsingResult->m_functions.size(); - const auto menuLoadCount = parsingResult->m_menus_to_load.size(); - auto totalItemCount = 0u; - for (const auto& menu : parsingResult->m_menus) - totalItemCount += menu->m_items.size(); - - std::cout << "Successfully read menu file \"" << fileName << "\" (" << menuLoadCount << " loads, " << menuCount << " menus, " << functionCount << " functions, " << totalItemCount << - " items)\n"; - - // Add all functions to the zone state to make them available for all menus to be converted - for (auto& function : parsingResult->m_functions) - zoneState->AddFunction(std::move(function)); - - // Prepare a list of all menus of this file - std::vector*> allMenusOfFile; - allMenusOfFile.reserve(parsingResult->m_menus.size()); - - // Convert all menus and add them as assets - for (auto& menu : parsingResult->m_menus) - { - MenuConverter converter(ObjLoading::Configuration.MenuNoOptimization, searchPath, memory, manager); - auto* menuAsset = converter.ConvertMenu(*menu); - if (menuAsset == nullptr) - { - std::cout << "Failed to convert menu file \"" << menu->m_name << "\"\n"; - return false; - } - - menus.push_back(menuAsset); - auto* menuAssetInfo = manager->AddAsset(ASSET_TYPE_MENU, menu->m_name, menuAsset, std::move(converter.GetDependencies()), std::vector()); - - if (menuAssetInfo) - { - allMenusOfFile.push_back(reinterpret_cast*>(menuAssetInfo)); - menuListDependencies.push_back(menuAssetInfo); - } - - zoneState->AddMenu(std::move(menu)); - } - - // Register this file with all loaded menus - conversionState->AddLoadedFile(fileName, std::move(allMenusOfFile)); - - return true; - } - - static MenuList* CreateMenuListAsset(const std::string& assetName, MemoryManager* memory, const std::vector& menus) - { - auto* menuListAsset = memory->Create(); - menuListAsset->name = memory->Dup(assetName.c_str()); - menuListAsset->menuCount = static_cast(menus.size()); - - if (menuListAsset->menuCount > 0) - { - menuListAsset->menus = static_cast(memory->Alloc(sizeof(uintptr_t) * menuListAsset->menuCount)); - for (auto i = 0; i < menuListAsset->menuCount; i++) - menuListAsset->menus[i] = menus[i]; - } - else - menuListAsset->menus = nullptr; - - return menuListAsset; - } - - static std::unique_ptr ParseMenuFile(const std::string& menuFileName, ISearchPath* searchPath, const menu::MenuAssetZoneState* zoneState) - { - const auto file = searchPath->Open(menuFileName); - if (!file.IsOpen()) - return nullptr; - - menu::MenuFileReader reader(*file.m_stream, menuFileName, menu::FeatureLevel::IW5, [searchPath](const std::string& filename, const std::string& sourceFile) -> std::unique_ptr - { - auto foundFileToInclude = searchPath->Open(filename); - if (!foundFileToInclude.IsOpen() || !foundFileToInclude.m_stream) - return nullptr; - - return std::move(foundFileToInclude.m_stream); - }); - - reader.IncludeZoneState(zoneState); - reader.SetPermissiveMode(ObjLoading::Configuration.MenuPermissiveParsing); - - return reader.ReadMenuFile(); - } - }; -} +namespace IW5 { +class MenuLoader { +public: + static bool ProcessParsedResults(const std::string &fileName, ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager, + menu::ParsingResult *parsingResult, menu::MenuAssetZoneState *zoneState, MenuConversionZoneState *conversionState, + std::vector &menus, std::vector &menuListDependencies) { + const auto menuCount = parsingResult->m_menus.size(); + const auto functionCount = parsingResult->m_functions.size(); + const auto menuLoadCount = parsingResult->m_menus_to_load.size(); + auto totalItemCount = 0u; + for (const auto &menu : parsingResult->m_menus) + totalItemCount += menu->m_items.size(); + + std::cout << "Successfully read menu file \"" << fileName << "\" (" << menuLoadCount << " loads, " << menuCount << " menus, " << functionCount + << " functions, " << totalItemCount << " items)\n"; + + // Add all functions to the zone state to make them available for all menus to be converted + for (auto &function : parsingResult->m_functions) + zoneState->AddFunction(std::move(function)); + + // Prepare a list of all menus of this file + std::vector *> allMenusOfFile; + allMenusOfFile.reserve(parsingResult->m_menus.size()); + + // Convert all menus and add them as assets + for (auto &menu : parsingResult->m_menus) { + MenuConverter converter(ObjLoading::Configuration.MenuNoOptimization, searchPath, memory, manager); + auto *menuAsset = converter.ConvertMenu(*menu); + if (menuAsset == nullptr) { + std::cout << "Failed to convert menu file \"" << menu->m_name << "\"\n"; + return false; + } -void* AssetLoaderMenuList::CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) -{ - auto* menuList = memory->Create(); - memset(menuList, 0, sizeof(MenuList)); - menuList->name = memory->Dup(assetName.c_str()); - return menuList; -} + menus.push_back(menuAsset); + auto *menuAssetInfo = manager->AddAsset(ASSET_TYPE_MENU, menu->m_name, menuAsset, std::move(converter.GetDependencies()), std::vector()); -bool AssetLoaderMenuList::CanLoadFromRaw() const -{ - return true; -} + if (menuAssetInfo) { + allMenusOfFile.push_back(reinterpret_cast *>(menuAssetInfo)); + menuListDependencies.push_back(menuAssetInfo); + } -bool BuildMenuFileQueue(std::deque& menuLoadQueue, const std::string& menuListAssetName, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager, menu::MenuAssetZoneState* zoneState, - MenuConversionZoneState* conversionState, std::vector& menus, std::vector& menuListDependencies) -{ - const auto alreadyLoadedMenuListFileMenus = conversionState->m_menus_by_filename.find(menuListAssetName); - - if (alreadyLoadedMenuListFileMenus == conversionState->m_menus_by_filename.end()) - { - const auto menuListResult = MenuLoader::ParseMenuFile(menuListAssetName, searchPath, zoneState); - if (menuListResult) - { - MenuLoader::ProcessParsedResults(menuListAssetName, searchPath, memory, manager, menuListResult.get(), zoneState, conversionState, menus, menuListDependencies); - - for (const auto& menuToLoad : menuListResult->m_menus_to_load) - menuLoadQueue.push_back(menuToLoad); - - zoneState->AddMenusToLoad(menuListAssetName, std::move(menuListResult->m_menus_to_load)); - } - else - return false; + zoneState->AddMenu(std::move(menu)); } + // Register this file with all loaded menus + conversionState->AddLoadedFile(fileName, std::move(allMenusOfFile)); + return true; + } + + static MenuList *CreateMenuListAsset(const std::string &assetName, MemoryManager *memory, const std::vector &menus) { + auto *menuListAsset = memory->Create(); + menuListAsset->name = memory->Dup(assetName.c_str()); + menuListAsset->menuCount = static_cast(menus.size()); + + if (menuListAsset->menuCount > 0) { + menuListAsset->menus = static_cast(memory->Alloc(sizeof(uintptr_t) * menuListAsset->menuCount)); + for (auto i = 0; i < menuListAsset->menuCount; i++) + menuListAsset->menus[i] = menus[i]; + } else + menuListAsset->menus = nullptr; + + return menuListAsset; + } + + static std::unique_ptr ParseMenuFile(const std::string &menuFileName, ISearchPath *searchPath, + const menu::MenuAssetZoneState *zoneState) { + const auto file = searchPath->Open(menuFileName); + if (!file.IsOpen()) + return nullptr; + + menu::MenuFileReader reader(*file.m_stream, menuFileName, menu::FeatureLevel::IW5, + [searchPath](const std::string &filename, const std::string &sourceFile) -> std::unique_ptr { + auto foundFileToInclude = searchPath->Open(filename); + if (!foundFileToInclude.IsOpen() || !foundFileToInclude.m_stream) + return nullptr; + + return std::move(foundFileToInclude.m_stream); + }); + + reader.IncludeZoneState(zoneState); + reader.SetPermissiveMode(ObjLoading::Configuration.MenuPermissiveParsing); + + return reader.ReadMenuFile(); + } +}; +} // namespace IW5 + +void *AssetLoaderMenuList::CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) { + auto *menuList = memory->Create(); + memset(menuList, 0, sizeof(MenuList)); + menuList->name = memory->Dup(assetName.c_str()); + return menuList; } -void LoadMenuFileFromQueue(const std::string& menuFilePath, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager, menu::MenuAssetZoneState* zoneState, - MenuConversionZoneState* conversionState, std::vector& menus, std::vector& menuListDependencies) -{ - const auto alreadyLoadedMenuFile = conversionState->m_menus_by_filename.find(menuFilePath); - if (alreadyLoadedMenuFile != conversionState->m_menus_by_filename.end()) - { - std::cout << "Already loaded \"" << menuFilePath << "\", skipping\n"; - for (auto* menu : alreadyLoadedMenuFile->second) - { - menus.push_back(menu->Asset()); - menuListDependencies.push_back(menu); - } - return; - } +bool AssetLoaderMenuList::CanLoadFromRaw() const { return true; } - const auto menuFileResult = MenuLoader::ParseMenuFile(menuFilePath, searchPath, zoneState); - if (menuFileResult) - { - MenuLoader::ProcessParsedResults(menuFilePath, searchPath, memory, manager, menuFileResult.get(), zoneState, conversionState, menus, menuListDependencies); - if (!menuFileResult->m_menus_to_load.empty()) - std::cout << "WARNING: Menu file has menus to load even though it is not a menu list, ignoring: \"" << menuFilePath << "\"\n"; +bool BuildMenuFileQueue(std::deque &menuLoadQueue, const std::string &menuListAssetName, ISearchPath *searchPath, MemoryManager *memory, + IAssetLoadingManager *manager, menu::MenuAssetZoneState *zoneState, MenuConversionZoneState *conversionState, + std::vector &menus, std::vector &menuListDependencies) { + const auto alreadyLoadedMenuListFileMenus = conversionState->m_menus_by_filename.find(menuListAssetName); + + if (alreadyLoadedMenuListFileMenus == conversionState->m_menus_by_filename.end()) { + const auto menuListResult = MenuLoader::ParseMenuFile(menuListAssetName, searchPath, zoneState); + if (menuListResult) { + MenuLoader::ProcessParsedResults(menuListAssetName, searchPath, memory, manager, menuListResult.get(), zoneState, conversionState, menus, + menuListDependencies); + + for (const auto &menuToLoad : menuListResult->m_menus_to_load) + menuLoadQueue.push_back(menuToLoad); + + zoneState->AddMenusToLoad(menuListAssetName, std::move(menuListResult->m_menus_to_load)); + } else + return false; + } + + return true; +} + +void LoadMenuFileFromQueue(const std::string &menuFilePath, ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager, + menu::MenuAssetZoneState *zoneState, MenuConversionZoneState *conversionState, std::vector &menus, + std::vector &menuListDependencies) { + const auto alreadyLoadedMenuFile = conversionState->m_menus_by_filename.find(menuFilePath); + if (alreadyLoadedMenuFile != conversionState->m_menus_by_filename.end()) { + std::cout << "Already loaded \"" << menuFilePath << "\", skipping\n"; + for (auto *menu : alreadyLoadedMenuFile->second) { + menus.push_back(menu->Asset()); + menuListDependencies.push_back(menu); } - else - std::cerr << "Could not read menu file \"" << menuFilePath << "\"\n"; + return; + } + + const auto menuFileResult = MenuLoader::ParseMenuFile(menuFilePath, searchPath, zoneState); + if (menuFileResult) { + MenuLoader::ProcessParsedResults(menuFilePath, searchPath, memory, manager, menuFileResult.get(), zoneState, conversionState, menus, menuListDependencies); + if (!menuFileResult->m_menus_to_load.empty()) + std::cout << "WARNING: Menu file has menus to load even though it is not a menu list, ignoring: \"" << menuFilePath << "\"\n"; + } else + std::cerr << "Could not read menu file \"" << menuFilePath << "\"\n"; } -bool AssetLoaderMenuList::LoadFromRaw(const std::string& assetName, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const -{ - std::vector menus; - std::vector menuListDependencies; +bool AssetLoaderMenuList::LoadFromRaw(const std::string &assetName, ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager, + Zone *zone) const { + std::vector menus; + std::vector menuListDependencies; - auto* zoneState = manager->GetAssetLoadingContext()->GetZoneAssetLoaderState(); - auto* conversionState = manager->GetAssetLoadingContext()->GetZoneAssetLoaderState(); + auto *zoneState = manager->GetAssetLoadingContext()->GetZoneAssetLoaderState(); + auto *conversionState = manager->GetAssetLoadingContext()->GetZoneAssetLoaderState(); - std::deque menuLoadQueue; - if (!BuildMenuFileQueue(menuLoadQueue, assetName, searchPath, memory, manager, zoneState, conversionState, menus, menuListDependencies)) - return false; + std::deque menuLoadQueue; + if (!BuildMenuFileQueue(menuLoadQueue, assetName, searchPath, memory, manager, zoneState, conversionState, menus, menuListDependencies)) + return false; - while(!menuLoadQueue.empty()) - { - const auto& menuFileToLoad = menuLoadQueue.front(); + while (!menuLoadQueue.empty()) { + const auto &menuFileToLoad = menuLoadQueue.front(); - LoadMenuFileFromQueue(menuFileToLoad, searchPath, memory, manager, zoneState, conversionState, menus, menuListDependencies); + LoadMenuFileFromQueue(menuFileToLoad, searchPath, memory, manager, zoneState, conversionState, menus, menuListDependencies); - menuLoadQueue.pop_front(); - } + menuLoadQueue.pop_front(); + } - auto* menuListAsset = MenuLoader::CreateMenuListAsset(assetName, memory, menus); + auto *menuListAsset = MenuLoader::CreateMenuListAsset(assetName, memory, menus); - if (menuListAsset) - manager->AddAsset(ASSET_TYPE_MENULIST, assetName, menuListAsset, menuListDependencies, std::vector()); + if (menuListAsset) + manager->AddAsset(ASSET_TYPE_MENULIST, assetName, menuListAsset, menuListDependencies, std::vector()); - return true; + return true; } -void AssetLoaderMenuList::FinalizeAssetsForZone(AssetLoadingContext* context) const -{ - context->GetZoneAssetLoaderState()->FinalizeSupportingData(); +void AssetLoaderMenuList::FinalizeAssetsForZone(AssetLoadingContext *context) const { + context->GetZoneAssetLoaderState()->FinalizeSupportingData(); } diff --git a/src/ObjLoading/Game/IW5/AssetLoaders/AssetLoaderMenuList.h b/src/ObjLoading/Game/IW5/AssetLoaders/AssetLoaderMenuList.h index 3aa870410..63eaee75e 100644 --- a/src/ObjLoading/Game/IW5/AssetLoaders/AssetLoaderMenuList.h +++ b/src/ObjLoading/Game/IW5/AssetLoaders/AssetLoaderMenuList.h @@ -1,18 +1,16 @@ #pragma once -#include "Game/IW5/IW5.h" #include "AssetLoading/BasicAssetLoader.h" #include "AssetLoading/IAssetLoadingManager.h" +#include "Game/IW5/IW5.h" #include "SearchPath/ISearchPath.h" -namespace IW5 -{ - class AssetLoaderMenuList final : public BasicAssetLoader - { - public: - _NODISCARD void* CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) override; - _NODISCARD bool CanLoadFromRaw() const override; - bool LoadFromRaw(const std::string& assetName, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const override; - void FinalizeAssetsForZone(AssetLoadingContext* context) const override; - }; -} +namespace IW5 { +class AssetLoaderMenuList final : public BasicAssetLoader { +public: + _NODISCARD void *CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) override; + _NODISCARD bool CanLoadFromRaw() const override; + bool LoadFromRaw(const std::string &assetName, ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager, Zone *zone) const override; + void FinalizeAssetsForZone(AssetLoadingContext *context) const override; +}; +} // namespace IW5 diff --git a/src/ObjLoading/Game/IW5/AssetLoaders/AssetLoaderRawFile.cpp b/src/ObjLoading/Game/IW5/AssetLoaders/AssetLoaderRawFile.cpp index 41912d7a2..bbb591297 100644 --- a/src/ObjLoading/Game/IW5/AssetLoaders/AssetLoaderRawFile.cpp +++ b/src/ObjLoading/Game/IW5/AssetLoaders/AssetLoaderRawFile.cpp @@ -10,68 +10,62 @@ using namespace IW5; -void* AssetLoaderRawFile::CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) -{ - auto* rawFile = memory->Create(); - memset(rawFile, 0, sizeof(RawFile)); - rawFile->name = memory->Dup(assetName.c_str()); - return rawFile; +void *AssetLoaderRawFile::CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) { + auto *rawFile = memory->Create(); + memset(rawFile, 0, sizeof(RawFile)); + rawFile->name = memory->Dup(assetName.c_str()); + return rawFile; } -bool AssetLoaderRawFile::CanLoadFromRaw() const -{ - return true; -} +bool AssetLoaderRawFile::CanLoadFromRaw() const { return true; } -bool AssetLoaderRawFile::LoadFromRaw(const std::string& assetName, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const -{ - const auto file = searchPath->Open(assetName); - if (!file.IsOpen()) - return false; +bool AssetLoaderRawFile::LoadFromRaw(const std::string &assetName, ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager, + Zone *zone) const { + const auto file = searchPath->Open(assetName); + if (!file.IsOpen()) + return false; - const auto uncompressedBuffer = std::make_unique(static_cast(file.m_length)); - file.m_stream->read(uncompressedBuffer.get(), file.m_length); - if (file.m_stream->gcount() != file.m_length) - return false; + const auto uncompressedBuffer = std::make_unique(static_cast(file.m_length)); + file.m_stream->read(uncompressedBuffer.get(), file.m_length); + if (file.m_stream->gcount() != file.m_length) + return false; - const auto compressionBufferSize = static_cast(file.m_length + COMPRESSED_BUFFER_SIZE_PADDING); - auto* compressedBuffer = static_cast(memory->Alloc(compressionBufferSize)); + const auto compressionBufferSize = static_cast(file.m_length + COMPRESSED_BUFFER_SIZE_PADDING); + auto *compressedBuffer = static_cast(memory->Alloc(compressionBufferSize)); - z_stream_s zs{}; + z_stream_s zs{}; - zs.zalloc = Z_NULL; - zs.zfree = Z_NULL; - zs.opaque = Z_NULL; - zs.avail_in = static_cast(file.m_length); - zs.avail_out = compressionBufferSize; - zs.next_in = reinterpret_cast(uncompressedBuffer.get()); - zs.next_out = reinterpret_cast(compressedBuffer); + zs.zalloc = Z_NULL; + zs.zfree = Z_NULL; + zs.opaque = Z_NULL; + zs.avail_in = static_cast(file.m_length); + zs.avail_out = compressionBufferSize; + zs.next_in = reinterpret_cast(uncompressedBuffer.get()); + zs.next_out = reinterpret_cast(compressedBuffer); - int ret = deflateInit(&zs, Z_DEFAULT_COMPRESSION); + int ret = deflateInit(&zs, Z_DEFAULT_COMPRESSION); - if (ret != Z_OK) - { - throw std::runtime_error("Initializing deflate failed"); - } + if (ret != Z_OK) { + throw std::runtime_error("Initializing deflate failed"); + } - ret = deflate(&zs, Z_FINISH); + ret = deflate(&zs, Z_FINISH); - if (ret != Z_STREAM_END) - { - std::cout << "Deflate failed for loading rawfile \"" << assetName << "\"" << std::endl; - deflateEnd(&zs); - return false; - } + if (ret != Z_STREAM_END) { + std::cout << "Deflate failed for loading rawfile \"" << assetName << "\"" << std::endl; + deflateEnd(&zs); + return false; + } - const auto compressedSize = compressionBufferSize - zs.avail_out; + const auto compressedSize = compressionBufferSize - zs.avail_out; - auto* rawFile = memory->Create(); - rawFile->name = memory->Dup(assetName.c_str()); - rawFile->compressedLen = static_cast(compressedSize); - rawFile->len = static_cast(file.m_length); - rawFile->buffer = static_cast(compressedBuffer); + auto *rawFile = memory->Create(); + rawFile->name = memory->Dup(assetName.c_str()); + rawFile->compressedLen = static_cast(compressedSize); + rawFile->len = static_cast(file.m_length); + rawFile->buffer = static_cast(compressedBuffer); - manager->AddAsset(ASSET_TYPE_RAWFILE, assetName, rawFile); + manager->AddAsset(ASSET_TYPE_RAWFILE, assetName, rawFile); - return true; + return true; } diff --git a/src/ObjLoading/Game/IW5/AssetLoaders/AssetLoaderRawFile.h b/src/ObjLoading/Game/IW5/AssetLoaders/AssetLoaderRawFile.h index da6fe90a0..5c0653b98 100644 --- a/src/ObjLoading/Game/IW5/AssetLoaders/AssetLoaderRawFile.h +++ b/src/ObjLoading/Game/IW5/AssetLoaders/AssetLoaderRawFile.h @@ -1,18 +1,16 @@ #pragma once -#include "Game/IW5/IW5.h" #include "AssetLoading/BasicAssetLoader.h" #include "AssetLoading/IAssetLoadingManager.h" +#include "Game/IW5/IW5.h" #include "SearchPath/ISearchPath.h" -namespace IW5 -{ - class AssetLoaderRawFile final : public BasicAssetLoader - { - static constexpr size_t COMPRESSED_BUFFER_SIZE_PADDING = 64; +namespace IW5 { +class AssetLoaderRawFile final : public BasicAssetLoader { + static constexpr size_t COMPRESSED_BUFFER_SIZE_PADDING = 64; - public: - _NODISCARD void* CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) override; - _NODISCARD bool CanLoadFromRaw() const override; - bool LoadFromRaw(const std::string& assetName, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const override; - }; -} +public: + _NODISCARD void *CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) override; + _NODISCARD bool CanLoadFromRaw() const override; + bool LoadFromRaw(const std::string &assetName, ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager, Zone *zone) const override; +}; +} // namespace IW5 diff --git a/src/ObjLoading/Game/IW5/AssetLoaders/AssetLoaderStringTable.cpp b/src/ObjLoading/Game/IW5/AssetLoaders/AssetLoaderStringTable.cpp index 95171e8fd..8f8367083 100644 --- a/src/ObjLoading/Game/IW5/AssetLoaders/AssetLoaderStringTable.cpp +++ b/src/ObjLoading/Game/IW5/AssetLoaders/AssetLoaderStringTable.cpp @@ -2,78 +2,68 @@ #include -#include "ObjLoading.h" #include "Csv/CsvStream.h" #include "Game/IW5/CommonIW5.h" #include "Game/IW5/IW5.h" +#include "ObjLoading.h" #include "Pool/GlobalAssetPool.h" using namespace IW5; -void* AssetLoaderStringTable::CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) -{ - auto* stringTable = memory->Create(); - memset(stringTable, 0, sizeof(StringTable)); - stringTable->name = memory->Dup(assetName.c_str()); - return stringTable; +void *AssetLoaderStringTable::CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) { + auto *stringTable = memory->Create(); + memset(stringTable, 0, sizeof(StringTable)); + stringTable->name = memory->Dup(assetName.c_str()); + return stringTable; } -bool AssetLoaderStringTable::CanLoadFromRaw() const -{ - return true; -} +bool AssetLoaderStringTable::CanLoadFromRaw() const { return true; } -bool AssetLoaderStringTable::LoadFromRaw(const std::string& assetName, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const -{ - const auto file = searchPath->Open(assetName); - if (!file.IsOpen()) - return false; +bool AssetLoaderStringTable::LoadFromRaw(const std::string &assetName, ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager, + Zone *zone) const { + const auto file = searchPath->Open(assetName); + if (!file.IsOpen()) + return false; - auto* stringTable = memory->Create(); - stringTable->name = memory->Dup(assetName.c_str()); + auto *stringTable = memory->Create(); + stringTable->name = memory->Dup(assetName.c_str()); - std::vector> csvLines; - std::vector currentLine; - auto maxCols = 0u; - const CsvInputStream csv(*file.m_stream); + std::vector> csvLines; + std::vector currentLine; + auto maxCols = 0u; + const CsvInputStream csv(*file.m_stream); - while (csv.NextRow(currentLine)) - { - if (currentLine.size() > maxCols) - maxCols = currentLine.size(); - csvLines.emplace_back(std::move(currentLine)); - currentLine = std::vector(); - } + while (csv.NextRow(currentLine)) { + if (currentLine.size() > maxCols) + maxCols = currentLine.size(); + csvLines.emplace_back(std::move(currentLine)); + currentLine = std::vector(); + } - stringTable->columnCount = static_cast(maxCols); - stringTable->rowCount = static_cast(csvLines.size()); - const auto cellCount = static_cast(stringTable->rowCount) * static_cast(stringTable->columnCount); + stringTable->columnCount = static_cast(maxCols); + stringTable->rowCount = static_cast(csvLines.size()); + const auto cellCount = static_cast(stringTable->rowCount) * static_cast(stringTable->columnCount); - if (cellCount) - { - stringTable->values = static_cast(memory->Alloc(sizeof(StringTableCell) * cellCount)); + if (cellCount) { + stringTable->values = static_cast(memory->Alloc(sizeof(StringTableCell) * cellCount)); - for (auto row = 0u; row < csvLines.size(); row++) - { - const auto& rowValues = csvLines[row]; - for (auto col = 0u; col < maxCols; col++) - { - auto& cell = stringTable->values[row * maxCols + col]; - if (col >= rowValues.size() || rowValues[col].empty()) - cell.string = ""; - else - cell.string = memory->Dup(rowValues[col].c_str()); + for (auto row = 0u; row < csvLines.size(); row++) { + const auto &rowValues = csvLines[row]; + for (auto col = 0u; col < maxCols; col++) { + auto &cell = stringTable->values[row * maxCols + col]; + if (col >= rowValues.size() || rowValues[col].empty()) + cell.string = ""; + else + cell.string = memory->Dup(rowValues[col].c_str()); - cell.hash = Common::StringTable_HashString(cell.string); - } - } - } - else - { - stringTable->values = nullptr; + cell.hash = Common::StringTable_HashString(cell.string); + } } + } else { + stringTable->values = nullptr; + } - manager->AddAsset(ASSET_TYPE_STRINGTABLE, assetName, stringTable); + manager->AddAsset(ASSET_TYPE_STRINGTABLE, assetName, stringTable); - return true; + return true; } diff --git a/src/ObjLoading/Game/IW5/AssetLoaders/AssetLoaderStringTable.h b/src/ObjLoading/Game/IW5/AssetLoaders/AssetLoaderStringTable.h index 428d03f3f..15bb1bba0 100644 --- a/src/ObjLoading/Game/IW5/AssetLoaders/AssetLoaderStringTable.h +++ b/src/ObjLoading/Game/IW5/AssetLoaders/AssetLoaderStringTable.h @@ -1,16 +1,14 @@ #pragma once -#include "Game/IW5/IW5.h" #include "AssetLoading/BasicAssetLoader.h" +#include "Game/IW5/IW5.h" #include "SearchPath/ISearchPath.h" -namespace IW5 -{ - class AssetLoaderStringTable final : public BasicAssetLoader - { - public: - _NODISCARD void* CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) override; - _NODISCARD bool CanLoadFromRaw() const override; - bool LoadFromRaw(const std::string& assetName, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const override; - }; -} +namespace IW5 { +class AssetLoaderStringTable final : public BasicAssetLoader { +public: + _NODISCARD void *CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) override; + _NODISCARD bool CanLoadFromRaw() const override; + bool LoadFromRaw(const std::string &assetName, ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager, Zone *zone) const override; +}; +} // namespace IW5 diff --git a/src/ObjLoading/Game/IW5/InfoString/InfoStringToStructConverter.cpp b/src/ObjLoading/Game/IW5/InfoString/InfoStringToStructConverter.cpp index 3233a77ee..b68d2bc9f 100644 --- a/src/ObjLoading/Game/IW5/InfoString/InfoStringToStructConverter.cpp +++ b/src/ObjLoading/Game/IW5/InfoString/InfoStringToStructConverter.cpp @@ -1,4 +1,3 @@ #include "InfoStringToStructConverter.h" using namespace IW5; - diff --git a/src/ObjLoading/Game/IW5/InfoString/InfoStringToStructConverter.h b/src/ObjLoading/Game/IW5/InfoString/InfoStringToStructConverter.h index d9e957bb8..57c9dae50 100644 --- a/src/ObjLoading/Game/IW5/InfoString/InfoStringToStructConverter.h +++ b/src/ObjLoading/Game/IW5/InfoString/InfoStringToStructConverter.h @@ -1,25 +1,23 @@ #pragma once #include "AssetLoading/IAssetLoadingManager.h" -#include "InfoString/InfoStringToStructConverterBase.h" #include "Game/IW5/IW5.h" +#include "InfoString/InfoStringToStructConverterBase.h" -namespace IW5 -{ - class InfoStringToStructConverter : public InfoStringToStructConverterBase - { - protected: - IAssetLoadingManager* m_loading_manager; - const cspField_t* m_fields; - size_t m_field_count; +namespace IW5 { +class InfoStringToStructConverter : public InfoStringToStructConverterBase { +protected: + IAssetLoadingManager *m_loading_manager; + const cspField_t *m_fields; + size_t m_field_count; - static bool GetHashValue(const std::string& value, unsigned int& hash); + static bool GetHashValue(const std::string &value, unsigned int &hash); - virtual bool ConvertExtensionField(const cspField_t& field, const std::string& value) = 0; - bool ConvertBaseField(const cspField_t& field, const std::string& value); + virtual bool ConvertExtensionField(const cspField_t &field, const std::string &value) = 0; + bool ConvertBaseField(const cspField_t &field, const std::string &value); - public: - InfoStringToStructConverter(const InfoString& infoString, void* structure, ZoneScriptStrings& zoneScriptStrings, MemoryManager* memory, IAssetLoadingManager* manager, const cspField_t* fields, - size_t fieldCount); - bool Convert() override; - }; -} \ No newline at end of file +public: + InfoStringToStructConverter(const InfoString &infoString, void *structure, ZoneScriptStrings &zoneScriptStrings, MemoryManager *memory, + IAssetLoadingManager *manager, const cspField_t *fields, size_t fieldCount); + bool Convert() override; +}; +} // namespace IW5 \ No newline at end of file diff --git a/src/ObjLoading/Game/IW5/Menu/MenuConversionZoneStateIW5.cpp b/src/ObjLoading/Game/IW5/Menu/MenuConversionZoneStateIW5.cpp index 11d2614b1..37a47c9ef 100644 --- a/src/ObjLoading/Game/IW5/Menu/MenuConversionZoneStateIW5.cpp +++ b/src/ObjLoading/Game/IW5/Menu/MenuConversionZoneStateIW5.cpp @@ -4,118 +4,101 @@ using namespace IW5; -MenuConversionZoneState::MenuConversionZoneState() - : m_zone(nullptr), - m_supporting_data(nullptr) -{ -} +MenuConversionZoneState::MenuConversionZoneState() : m_zone(nullptr), m_supporting_data(nullptr) {} -void MenuConversionZoneState::SetZone(Zone* zone) -{ - auto* memory = zone->GetMemory(); +void MenuConversionZoneState::SetZone(Zone *zone) { + auto *memory = zone->GetMemory(); - m_zone = zone; - m_supporting_data = memory->Create(); - memset(m_supporting_data, 0, sizeof(ExpressionSupportingData)); + m_zone = zone; + m_supporting_data = memory->Create(); + memset(m_supporting_data, 0, sizeof(ExpressionSupportingData)); } -Statement_s* MenuConversionZoneState::FindFunction(const std::string& functionName) -{ - const auto foundFunction = m_function_by_name.find(functionName); +Statement_s *MenuConversionZoneState::FindFunction(const std::string &functionName) { + const auto foundFunction = m_function_by_name.find(functionName); - if (foundFunction != m_function_by_name.end()) - return foundFunction->second; + if (foundFunction != m_function_by_name.end()) + return foundFunction->second; - return nullptr; + return nullptr; } -Statement_s* MenuConversionZoneState::AddFunction(const std::string& functionName, Statement_s* function) -{ - m_functions.push_back(function); - m_function_by_name.emplace(std::make_pair(functionName, function)); +Statement_s *MenuConversionZoneState::AddFunction(const std::string &functionName, Statement_s *function) { + m_functions.push_back(function); + m_function_by_name.emplace(std::make_pair(functionName, function)); - return function; + return function; } -size_t MenuConversionZoneState::AddStaticDvar(const std::string& dvarName) -{ - const auto foundDvar = m_dvars_by_name.find(dvarName); +size_t MenuConversionZoneState::AddStaticDvar(const std::string &dvarName) { + const auto foundDvar = m_dvars_by_name.find(dvarName); - if (foundDvar != m_dvars_by_name.end()) - return foundDvar->second; + if (foundDvar != m_dvars_by_name.end()) + return foundDvar->second; - auto* memory = m_zone->GetMemory(); - auto* staticDvar = static_cast(memory->Alloc(sizeof(StaticDvar))); + auto *memory = m_zone->GetMemory(); + auto *staticDvar = static_cast(memory->Alloc(sizeof(StaticDvar))); - staticDvar->dvarName = memory->Dup(dvarName.c_str()); - staticDvar->dvar = nullptr; + staticDvar->dvarName = memory->Dup(dvarName.c_str()); + staticDvar->dvar = nullptr; - const auto staticDvarIndex = m_static_dvars.size(); - m_static_dvars.push_back(staticDvar); - m_dvars_by_name.emplace(std::make_pair(dvarName, staticDvarIndex)); + const auto staticDvarIndex = m_static_dvars.size(); + m_static_dvars.push_back(staticDvar); + m_dvars_by_name.emplace(std::make_pair(dvarName, staticDvarIndex)); - return staticDvarIndex; + return staticDvarIndex; } -const char* MenuConversionZoneState::AddString(const std::string& str) -{ - const auto foundString = m_strings_by_value.find(str); +const char *MenuConversionZoneState::AddString(const std::string &str) { + const auto foundString = m_strings_by_value.find(str); - if (foundString != m_strings_by_value.end()) - return foundString->second; + if (foundString != m_strings_by_value.end()) + return foundString->second; - auto* memory = m_zone->GetMemory(); - const auto* strDuped = memory->Dup(str.c_str()); + auto *memory = m_zone->GetMemory(); + const auto *strDuped = memory->Dup(str.c_str()); - m_strings.push_back(strDuped); - m_strings_by_value.emplace(std::make_pair(str, strDuped)); + m_strings.push_back(strDuped); + m_strings_by_value.emplace(std::make_pair(str, strDuped)); - return strDuped; + return strDuped; } -void MenuConversionZoneState::AddLoadedFile(std::string loadedFileName, std::vector*> menusOfFile) -{ - m_menus_by_filename.emplace(std::make_pair(std::move(loadedFileName), std::move(menusOfFile))); +void MenuConversionZoneState::AddLoadedFile(std::string loadedFileName, std::vector *> menusOfFile) { + m_menus_by_filename.emplace(std::make_pair(std::move(loadedFileName), std::move(menusOfFile))); } -void MenuConversionZoneState::FinalizeSupportingData() const -{ - auto* memory = m_zone->GetMemory(); - - m_supporting_data->uifunctions.totalFunctions = static_cast(m_functions.size()); - m_supporting_data->staticDvarList.numStaticDvars = static_cast(m_static_dvars.size()); - m_supporting_data->uiStrings.totalStrings = static_cast(m_strings.size()); - - if (m_supporting_data->uifunctions.functions) - memory->Free(m_supporting_data->uifunctions.functions); - - if (m_supporting_data->staticDvarList.staticDvars) - memory->Free(m_supporting_data->staticDvarList.staticDvars); - - if (m_supporting_data->uiStrings.strings) - memory->Free(m_supporting_data->uiStrings.strings); - - if (!m_functions.empty()) - { - m_supporting_data->uifunctions.functions = static_cast(memory->Alloc(sizeof(void*) * m_functions.size())); - memcpy(m_supporting_data->uifunctions.functions, &m_functions[0], sizeof(void*) * m_functions.size()); - } - else - m_supporting_data->uifunctions.functions = nullptr; - - if (!m_static_dvars.empty()) - { - m_supporting_data->staticDvarList.staticDvars = static_cast(memory->Alloc(sizeof(void*) * m_static_dvars.size())); - memcpy(m_supporting_data->staticDvarList.staticDvars, &m_static_dvars[0], sizeof(void*) * m_static_dvars.size()); - } - else - m_supporting_data->staticDvarList.staticDvars = nullptr; - - if (!m_strings.empty()) - { - m_supporting_data->uiStrings.strings = static_cast(memory->Alloc(sizeof(void*) * m_strings.size())); - memcpy(m_supporting_data->uiStrings.strings, &m_strings[0], sizeof(void*) * m_strings.size()); - } - else - m_supporting_data->uiStrings.strings = nullptr; +void MenuConversionZoneState::FinalizeSupportingData() const { + auto *memory = m_zone->GetMemory(); + + m_supporting_data->uifunctions.totalFunctions = static_cast(m_functions.size()); + m_supporting_data->staticDvarList.numStaticDvars = static_cast(m_static_dvars.size()); + m_supporting_data->uiStrings.totalStrings = static_cast(m_strings.size()); + + if (m_supporting_data->uifunctions.functions) + memory->Free(m_supporting_data->uifunctions.functions); + + if (m_supporting_data->staticDvarList.staticDvars) + memory->Free(m_supporting_data->staticDvarList.staticDvars); + + if (m_supporting_data->uiStrings.strings) + memory->Free(m_supporting_data->uiStrings.strings); + + if (!m_functions.empty()) { + m_supporting_data->uifunctions.functions = static_cast(memory->Alloc(sizeof(void *) * m_functions.size())); + memcpy(m_supporting_data->uifunctions.functions, &m_functions[0], sizeof(void *) * m_functions.size()); + } else + m_supporting_data->uifunctions.functions = nullptr; + + if (!m_static_dvars.empty()) { + m_supporting_data->staticDvarList.staticDvars = static_cast(memory->Alloc(sizeof(void *) * m_static_dvars.size())); + memcpy(m_supporting_data->staticDvarList.staticDvars, &m_static_dvars[0], sizeof(void *) * m_static_dvars.size()); + } else + m_supporting_data->staticDvarList.staticDvars = nullptr; + + if (!m_strings.empty()) { + m_supporting_data->uiStrings.strings = static_cast(memory->Alloc(sizeof(void *) * m_strings.size())); + memcpy(m_supporting_data->uiStrings.strings, &m_strings[0], sizeof(void *) * m_strings.size()); + } else + m_supporting_data->uiStrings.strings = nullptr; } diff --git a/src/ObjLoading/Game/IW5/Menu/MenuConversionZoneStateIW5.h b/src/ObjLoading/Game/IW5/Menu/MenuConversionZoneStateIW5.h index 890c1dc63..5d30ea60e 100644 --- a/src/ObjLoading/Game/IW5/Menu/MenuConversionZoneStateIW5.h +++ b/src/ObjLoading/Game/IW5/Menu/MenuConversionZoneStateIW5.h @@ -5,35 +5,33 @@ #include "AssetLoading/IZoneAssetLoaderState.h" #include "Game/IW5/IW5.h" -namespace IW5 -{ - class MenuConversionZoneState final : public IZoneAssetLoaderState - { - Zone* m_zone; - std::vector m_functions; - std::map m_function_by_name; +namespace IW5 { +class MenuConversionZoneState final : public IZoneAssetLoaderState { + Zone *m_zone; + std::vector m_functions; + std::map m_function_by_name; - std::vector m_static_dvars; - std::map m_dvars_by_name; + std::vector m_static_dvars; + std::map m_dvars_by_name; - std::vector m_strings; - std::map m_strings_by_value; + std::vector m_strings; + std::map m_strings_by_value; - public: - std::map*>> m_menus_by_filename; - ExpressionSupportingData* m_supporting_data; +public: + std::map *>> m_menus_by_filename; + ExpressionSupportingData *m_supporting_data; - MenuConversionZoneState(); - void SetZone(Zone* zone) override; + MenuConversionZoneState(); + void SetZone(Zone *zone) override; - Statement_s* FindFunction(const std::string& functionName); + Statement_s *FindFunction(const std::string &functionName); - Statement_s* AddFunction(const std::string& functionName, Statement_s* function); - size_t AddStaticDvar(const std::string& dvarName); - const char* AddString(const std::string& str); + Statement_s *AddFunction(const std::string &functionName, Statement_s *function); + size_t AddStaticDvar(const std::string &dvarName); + const char *AddString(const std::string &str); - void AddLoadedFile(std::string loadedFileName, std::vector*> menusOfFile); + void AddLoadedFile(std::string loadedFileName, std::vector *> menusOfFile); - void FinalizeSupportingData() const; - }; -} + void FinalizeSupportingData() const; +}; +} // namespace IW5 diff --git a/src/ObjLoading/Game/IW5/Menu/MenuConverterIW5.cpp b/src/ObjLoading/Game/IW5/Menu/MenuConverterIW5.cpp index 1cde69a07..a34280c11 100644 --- a/src/ObjLoading/Game/IW5/Menu/MenuConverterIW5.cpp +++ b/src/ObjLoading/Game/IW5/Menu/MenuConverterIW5.cpp @@ -4,1151 +4,1028 @@ #include #include -#include "MenuConversionZoneStateIW5.h" -#include "Utils/ClassUtils.h" #include "Menu/AbstractMenuConverter.h" -#include "Parsing/Menu/MenuAssetZoneState.h" +#include "MenuConversionZoneStateIW5.h" #include "Parsing/Menu/Domain/EventHandler/CommonEventHandlerCondition.h" #include "Parsing/Menu/Domain/EventHandler/CommonEventHandlerScript.h" #include "Parsing/Menu/Domain/EventHandler/CommonEventHandlerSetLocalVar.h" #include "Parsing/Menu/Domain/Expression/CommonExpressionBaseFunctionCall.h" #include "Parsing/Menu/Domain/Expression/CommonExpressionCustomFunctionCall.h" +#include "Parsing/Menu/MenuAssetZoneState.h" #include "Parsing/Simple/Expression/SimpleExpressionBinaryOperation.h" #include "Parsing/Simple/Expression/SimpleExpressionConditionalOperator.h" #include "Parsing/Simple/Expression/SimpleExpressionUnaryOperation.h" +#include "Utils/ClassUtils.h" using namespace IW5; using namespace menu; -namespace IW5 -{ - class MenuConverterImpl : public AbstractMenuConverter - { - MenuConversionZoneState* m_conversion_zone_state; - MenuAssetZoneState* m_parsing_zone_state; - - _NODISCARD static rectDef_s ConvertRectDef(const CommonRect& rect) - { - return rectDef_s{ - static_cast(rect.x), - static_cast(rect.y), - static_cast(rect.w), - static_cast(rect.h), - static_cast(rect.horizontalAlign), - static_cast(rect.verticalAlign) - }; - } - - _NODISCARD static rectDef_s ConvertRectDefRelativeTo(const CommonRect& rect, const CommonRect& rectRelativeTo) - { - return rectDef_s{ - static_cast(rectRelativeTo.x + rect.x), - static_cast(rectRelativeTo.y + rect.y), - static_cast(rect.w), - static_cast(rect.h), - static_cast(rect.horizontalAlign), - static_cast(rect.verticalAlign) - }; - } - - static void ConvertColor(float (&output)[4], const CommonColor& input) - { - output[0] = static_cast(input.r); - output[1] = static_cast(input.g); - output[2] = static_cast(input.b); - output[3] = static_cast(input.a); - } - - static void ApplyFlag(int& flags, const bool shouldApply, const int flagValue) - { - if (!shouldApply) - return; - - flags |= flagValue; - } - - static int ConvertItemType(const int input) - { - return input; - } - - static int ConvertTextFont(const int input) - { - return input; - } - - _NODISCARD Material* ConvertMaterial(const std::string& materialName, const CommonMenuDef* menu, const CommonItemDef* item = nullptr) const - { - if (materialName.empty()) - return nullptr; - - auto* materialDependency = m_manager->LoadDependency(ASSET_TYPE_MATERIAL, materialName); - if (!materialDependency) - throw MenuConversionException("Failed to load material \"" + materialName + "\"", menu, item); - - return static_cast(materialDependency->m_ptr); - } - - _NODISCARD snd_alias_list_t* ConvertSound(const std::string& soundName, const CommonMenuDef* menu, const CommonItemDef* item = nullptr) const - { - if (soundName.empty()) - return nullptr; - - auto* soundDependency = m_manager->LoadDependency(ASSET_TYPE_SOUND, soundName); - if (!soundDependency) - throw MenuConversionException("Failed to load sound \"" + soundName + "\"", menu, item); - - return static_cast(soundDependency->m_ptr); - } - - bool HandleStaticDvarFunctionCall(Statement_s* gameStatement, std::vector& entries, const CommonExpressionBaseFunctionCall* functionCall, const int targetFunctionIndex) const - { - if (functionCall->m_args.size() != 1) - return false; - - const auto* dvarNameExpression = functionCall->m_args[0].get(); - if (!dvarNameExpression->IsStatic()) - return false; - - const auto staticDvarNameExpressionValue = dvarNameExpression->EvaluateStatic(); - if (staticDvarNameExpressionValue.m_type != SimpleExpressionValue::Type::STRING) - return false; - - expressionEntry functionEntry{}; - functionEntry.type = EET_OPERATOR; - functionEntry.data.op = targetFunctionIndex; - entries.emplace_back(functionEntry); - - expressionEntry staticDvarIndexEntry{}; - staticDvarIndexEntry.type = EET_OPERAND; - staticDvarIndexEntry.data.operand.dataType = VAL_INT; - staticDvarIndexEntry.data.operand.internals.intVal = static_cast(m_conversion_zone_state->AddStaticDvar(*staticDvarNameExpressionValue.m_string_value)); - entries.emplace_back(staticDvarIndexEntry); - - expressionEntry parenRight{}; - parenRight.type = EET_OPERATOR; - parenRight.data.op = OP_RIGHTPAREN; - entries.emplace_back(parenRight); - - gameStatement->supportingData = m_conversion_zone_state->m_supporting_data; - - return true; - } - - bool HandleSpecialBaseFunctionCall(Statement_s* gameStatement, std::vector& entries, const CommonExpressionBaseFunctionCall* functionCall, const CommonMenuDef* menu, - const CommonItemDef* item) const - { - switch (functionCall->m_function_index) - { - case EXP_FUNC_DVAR_INT: - return HandleStaticDvarFunctionCall(gameStatement, entries, functionCall, EXP_FUNC_STATIC_DVAR_INT); - case EXP_FUNC_DVAR_BOOL: - return HandleStaticDvarFunctionCall(gameStatement, entries, functionCall, EXP_FUNC_STATIC_DVAR_BOOL); - case EXP_FUNC_DVAR_FLOAT: - return HandleStaticDvarFunctionCall(gameStatement, entries, functionCall, EXP_FUNC_STATIC_DVAR_FLOAT); - case EXP_FUNC_DVAR_STRING: - return HandleStaticDvarFunctionCall(gameStatement, entries, functionCall, EXP_FUNC_STATIC_DVAR_STRING); - default: - break; - } - - return false; - } - - void ConvertExpressionEntryBaseFunctionCall(Statement_s* gameStatement, std::vector& entries, const CommonExpressionBaseFunctionCall* functionCall, const CommonMenuDef* menu, - const CommonItemDef* item) const - { - if (!HandleSpecialBaseFunctionCall(gameStatement, entries, functionCall, menu, item)) - { - expressionEntry functionEntry{}; - functionEntry.type = EET_OPERATOR; - functionEntry.data.op = static_cast(functionCall->m_function_index); - entries.emplace_back(functionEntry); - - auto firstArg = true; - for (const auto& arg : functionCall->m_args) - { - if (!firstArg) - { - expressionEntry argSeparator{}; - argSeparator.type = EET_OPERATOR; - argSeparator.data.op = OP_COMMA; - entries.emplace_back(argSeparator); - } - else - firstArg = false; - - ConvertExpressionEntry(gameStatement, entries, arg.get(), menu, item); - } - - expressionEntry parenRight{}; - parenRight.type = EET_OPERATOR; - parenRight.data.op = OP_RIGHTPAREN; - entries.emplace_back(parenRight); - } - } - - void ConvertExpressionEntryCustomFunctionCall(Statement_s* gameStatement, std::vector& entries, const CommonExpressionCustomFunctionCall* functionCall, - const CommonMenuDef* menu, - const CommonItemDef* item) const - { - Statement_s* functionStatement = m_conversion_zone_state->FindFunction(functionCall->m_function_name); - - if (functionStatement == nullptr) - { - // Function was not converted yet: Convert it now - const auto foundCommonFunction = m_parsing_zone_state->m_functions_by_name.find(functionCall->m_function_name); - - if (foundCommonFunction == m_parsing_zone_state->m_functions_by_name.end()) - throw MenuConversionException("Failed to find definition for custom function \"" + functionCall->m_function_name + "\"", menu, item); - - functionStatement = ConvertExpression(foundCommonFunction->second->m_value.get(), menu, item); - functionStatement = m_conversion_zone_state->AddFunction(foundCommonFunction->second->m_name, functionStatement); - } - - expressionEntry functionEntry{}; - functionEntry.type = EET_OPERAND; - functionEntry.data.operand.dataType = VAL_FUNCTION; - functionEntry.data.operand.internals.function = functionStatement; - entries.emplace_back(functionEntry); - - // Statement uses custom function so it needs supporting data - gameStatement->supportingData = m_conversion_zone_state->m_supporting_data; - } - - constexpr static expressionOperatorType_e UNARY_OPERATION_MAPPING[static_cast(SimpleUnaryOperationId::COUNT)] - { - OP_NOT, - OP_BITWISENOT, - OP_SUBTRACT - }; - - bool IsOperation(const ISimpleExpression* expression) const - { - if (!m_disable_optimizations && expression->IsStatic()) - return false; - - return dynamic_cast(expression) || dynamic_cast(expression); - } - - void ConvertExpressionEntryUnaryOperation(Statement_s* gameStatement, std::vector& entries, const SimpleExpressionUnaryOperation* unaryOperation, const CommonMenuDef* menu, - const CommonItemDef* item) const - { - assert(static_cast(unaryOperation->m_operation_type->m_id) < static_cast(SimpleUnaryOperationId::COUNT)); - expressionEntry operation{}; - operation.type = EET_OPERATOR; - operation.data.op = UNARY_OPERATION_MAPPING[static_cast(unaryOperation->m_operation_type->m_id)]; - entries.emplace_back(operation); - - if (IsOperation(unaryOperation->m_operand.get())) - { - expressionEntry parenLeft{}; - parenLeft.type = EET_OPERATOR; - parenLeft.data.op = OP_LEFTPAREN; - entries.emplace_back(parenLeft); - - ConvertExpressionEntry(gameStatement, entries, unaryOperation->m_operand.get(), menu, item); - - expressionEntry parenRight{}; - parenRight.type = EET_OPERATOR; - parenRight.data.op = OP_RIGHTPAREN; - entries.emplace_back(parenRight); - } - else - ConvertExpressionEntry(gameStatement, entries, unaryOperation->m_operand.get(), menu, item); - } - - constexpr static expressionOperatorType_e BINARY_OPERATION_MAPPING[static_cast(SimpleBinaryOperationId::COUNT)] - { - OP_ADD, - OP_SUBTRACT, - OP_MULTIPLY, - OP_DIVIDE, - OP_MODULUS, - OP_BITWISEAND, - OP_BITWISEOR, - OP_BITSHIFTLEFT, - OP_BITSHIFTRIGHT, - OP_GREATERTHAN, - OP_GREATERTHANEQUALTO, - OP_LESSTHAN, - OP_LESSTHANEQUALTO, - OP_EQUALS, - OP_NOTEQUAL, - OP_AND, - OP_OR - }; - - void ConvertExpressionEntryBinaryOperation(Statement_s* gameStatement, std::vector& entries, const SimpleExpressionBinaryOperation* binaryOperation, const CommonMenuDef* menu, - const CommonItemDef* item) const - { - // Game needs all nested operations to have parenthesis - if (IsOperation(binaryOperation->m_operand1.get())) - { - expressionEntry parenLeft{}; - parenLeft.type = EET_OPERATOR; - parenLeft.data.op = OP_LEFTPAREN; - entries.emplace_back(parenLeft); - - ConvertExpressionEntry(gameStatement, entries, binaryOperation->m_operand1.get(), menu, item); - - expressionEntry parenRight{}; - parenRight.type = EET_OPERATOR; - parenRight.data.op = OP_RIGHTPAREN; - entries.emplace_back(parenRight); - } - else - ConvertExpressionEntry(gameStatement, entries, binaryOperation->m_operand1.get(), menu, item); - - assert(static_cast(binaryOperation->m_operation_type->m_id) < static_cast(SimpleBinaryOperationId::COUNT)); - expressionEntry operation{}; - operation.type = EET_OPERATOR; - operation.data.op = BINARY_OPERATION_MAPPING[static_cast(binaryOperation->m_operation_type->m_id)]; - entries.emplace_back(operation); - - // Game needs all nested operations to have parenthesis - if (IsOperation(binaryOperation->m_operand2.get())) - { - expressionEntry parenLeft{}; - parenLeft.type = EET_OPERATOR; - parenLeft.data.op = OP_LEFTPAREN; - entries.emplace_back(parenLeft); - - ConvertExpressionEntry(gameStatement, entries, binaryOperation->m_operand2.get(), menu, item); - - expressionEntry parenRight{}; - parenRight.type = EET_OPERATOR; - parenRight.data.op = OP_RIGHTPAREN; - entries.emplace_back(parenRight); - } - else - ConvertExpressionEntry(gameStatement, entries, binaryOperation->m_operand2.get(), menu, item); - } - - void ConvertExpressionEntryExpressionValue(std::vector& entries, const SimpleExpressionValue* expressionValue) const - { - expressionEntry entry{}; - entry.type = EET_OPERAND; - - if (expressionValue->m_type == SimpleExpressionValue::Type::INT) - { - entry.data.operand.dataType = VAL_INT; - entry.data.operand.internals.intVal = expressionValue->m_int_value; - } - else if (expressionValue->m_type == SimpleExpressionValue::Type::DOUBLE) - { - entry.data.operand.dataType = VAL_FLOAT; - entry.data.operand.internals.floatVal = static_cast(expressionValue->m_double_value); - } - else if (expressionValue->m_type == SimpleExpressionValue::Type::STRING) - { - entry.data.operand.dataType = VAL_STRING; - entry.data.operand.internals.stringVal.string = m_conversion_zone_state->AddString(*expressionValue->m_string_value); - } - - entries.emplace_back(entry); - } - - void ConvertExpressionEntry(Statement_s* gameStatement, std::vector& entries, const ISimpleExpression* expression, const CommonMenuDef* menu, const CommonItemDef* item) const - { - if (!m_disable_optimizations && expression->IsStatic()) - { - const auto expressionStaticValue = expression->EvaluateStatic(); - ConvertExpressionEntryExpressionValue(entries, &expressionStaticValue); - } - else if (const auto* expressionValue = dynamic_cast(expression)) - { - ConvertExpressionEntryExpressionValue(entries, expressionValue); - } - else if (const auto* binaryOperation = dynamic_cast(expression)) - { - ConvertExpressionEntryBinaryOperation(gameStatement, entries, binaryOperation, menu, item); - } - else if (const auto* unaryOperation = dynamic_cast(expression)) - { - ConvertExpressionEntryUnaryOperation(gameStatement, entries, unaryOperation, menu, item); - } - else if (const auto* baseFunctionCall = dynamic_cast(expression)) - { - ConvertExpressionEntryBaseFunctionCall(gameStatement, entries, baseFunctionCall, menu, item); - } - else if (const auto* customFunctionCall = dynamic_cast(expression)) - { - ConvertExpressionEntryCustomFunctionCall(gameStatement, entries, customFunctionCall, menu, item); - } - else if (dynamic_cast(expression)) - { - throw MenuConversionException("Cannot use conditional expression in menu expressions", menu, item); - } - else - { - assert(false); - throw MenuConversionException("Unknown expression entry type in menu expressions", menu, item); - } - } - - _NODISCARD Statement_s* ConvertExpression(const ISimpleExpression* expression, const CommonMenuDef* menu, const CommonItemDef* item = nullptr) const - { - if (!expression) - return nullptr; +namespace IW5 { +class MenuConverterImpl : public AbstractMenuConverter { + MenuConversionZoneState *m_conversion_zone_state; + MenuAssetZoneState *m_parsing_zone_state; + + _NODISCARD static rectDef_s ConvertRectDef(const CommonRect &rect) { + return rectDef_s{static_cast(rect.x), + static_cast(rect.y), + static_cast(rect.w), + static_cast(rect.h), + static_cast(rect.horizontalAlign), + static_cast(rect.verticalAlign)}; + } + + _NODISCARD static rectDef_s ConvertRectDefRelativeTo(const CommonRect &rect, const CommonRect &rectRelativeTo) { + return rectDef_s{ + static_cast(rectRelativeTo.x + rect.x), static_cast(rectRelativeTo.y + rect.y), static_cast(rect.w), static_cast(rect.h), + static_cast(rect.horizontalAlign), static_cast(rect.verticalAlign)}; + } + + static void ConvertColor(float (&output)[4], const CommonColor &input) { + output[0] = static_cast(input.r); + output[1] = static_cast(input.g); + output[2] = static_cast(input.b); + output[3] = static_cast(input.a); + } + + static void ApplyFlag(int &flags, const bool shouldApply, const int flagValue) { + if (!shouldApply) + return; + + flags |= flagValue; + } + + static int ConvertItemType(const int input) { return input; } + + static int ConvertTextFont(const int input) { return input; } + + _NODISCARD Material *ConvertMaterial(const std::string &materialName, const CommonMenuDef *menu, const CommonItemDef *item = nullptr) const { + if (materialName.empty()) + return nullptr; + + auto *materialDependency = m_manager->LoadDependency(ASSET_TYPE_MATERIAL, materialName); + if (!materialDependency) + throw MenuConversionException("Failed to load material \"" + materialName + "\"", menu, item); + + return static_cast(materialDependency->m_ptr); + } + + _NODISCARD snd_alias_list_t *ConvertSound(const std::string &soundName, const CommonMenuDef *menu, const CommonItemDef *item = nullptr) const { + if (soundName.empty()) + return nullptr; + + auto *soundDependency = m_manager->LoadDependency(ASSET_TYPE_SOUND, soundName); + if (!soundDependency) + throw MenuConversionException("Failed to load sound \"" + soundName + "\"", menu, item); + + return static_cast(soundDependency->m_ptr); + } + + bool HandleStaticDvarFunctionCall(Statement_s *gameStatement, std::vector &entries, const CommonExpressionBaseFunctionCall *functionCall, + const int targetFunctionIndex) const { + if (functionCall->m_args.size() != 1) + return false; + + const auto *dvarNameExpression = functionCall->m_args[0].get(); + if (!dvarNameExpression->IsStatic()) + return false; + + const auto staticDvarNameExpressionValue = dvarNameExpression->EvaluateStatic(); + if (staticDvarNameExpressionValue.m_type != SimpleExpressionValue::Type::STRING) + return false; + + expressionEntry functionEntry{}; + functionEntry.type = EET_OPERATOR; + functionEntry.data.op = targetFunctionIndex; + entries.emplace_back(functionEntry); + + expressionEntry staticDvarIndexEntry{}; + staticDvarIndexEntry.type = EET_OPERAND; + staticDvarIndexEntry.data.operand.dataType = VAL_INT; + staticDvarIndexEntry.data.operand.internals.intVal = + static_cast(m_conversion_zone_state->AddStaticDvar(*staticDvarNameExpressionValue.m_string_value)); + entries.emplace_back(staticDvarIndexEntry); + + expressionEntry parenRight{}; + parenRight.type = EET_OPERATOR; + parenRight.data.op = OP_RIGHTPAREN; + entries.emplace_back(parenRight); + + gameStatement->supportingData = m_conversion_zone_state->m_supporting_data; + + return true; + } + + bool HandleSpecialBaseFunctionCall(Statement_s *gameStatement, std::vector &entries, const CommonExpressionBaseFunctionCall *functionCall, + const CommonMenuDef *menu, const CommonItemDef *item) const { + switch (functionCall->m_function_index) { + case EXP_FUNC_DVAR_INT: + return HandleStaticDvarFunctionCall(gameStatement, entries, functionCall, EXP_FUNC_STATIC_DVAR_INT); + case EXP_FUNC_DVAR_BOOL: + return HandleStaticDvarFunctionCall(gameStatement, entries, functionCall, EXP_FUNC_STATIC_DVAR_BOOL); + case EXP_FUNC_DVAR_FLOAT: + return HandleStaticDvarFunctionCall(gameStatement, entries, functionCall, EXP_FUNC_STATIC_DVAR_FLOAT); + case EXP_FUNC_DVAR_STRING: + return HandleStaticDvarFunctionCall(gameStatement, entries, functionCall, EXP_FUNC_STATIC_DVAR_STRING); + default: + break; + } - auto* statement = m_memory->Create(); - for (auto& result : statement->persistentState.lastResult) - result = Operand{}; - for (auto& lastExecutionTime : statement->persistentState.lastExecuteTime) - lastExecutionTime = 0; - statement->supportingData = nullptr; // Supporting data is set upon using it + return false; + } + + void ConvertExpressionEntryBaseFunctionCall(Statement_s *gameStatement, std::vector &entries, + const CommonExpressionBaseFunctionCall *functionCall, const CommonMenuDef *menu, + const CommonItemDef *item) const { + if (!HandleSpecialBaseFunctionCall(gameStatement, entries, functionCall, menu, item)) { + expressionEntry functionEntry{}; + functionEntry.type = EET_OPERATOR; + functionEntry.data.op = static_cast(functionCall->m_function_index); + entries.emplace_back(functionEntry); + + auto firstArg = true; + for (const auto &arg : functionCall->m_args) { + if (!firstArg) { + expressionEntry argSeparator{}; + argSeparator.type = EET_OPERATOR; + argSeparator.data.op = OP_COMMA; + entries.emplace_back(argSeparator); + } else + firstArg = false; + + ConvertExpressionEntry(gameStatement, entries, arg.get(), menu, item); + } + + expressionEntry parenRight{}; + parenRight.type = EET_OPERATOR; + parenRight.data.op = OP_RIGHTPAREN; + entries.emplace_back(parenRight); + } + } - std::vector expressionEntries; - ConvertExpressionEntry(statement, expressionEntries, expression, menu, item); + void ConvertExpressionEntryCustomFunctionCall(Statement_s *gameStatement, std::vector &entries, + const CommonExpressionCustomFunctionCall *functionCall, const CommonMenuDef *menu, + const CommonItemDef *item) const { + Statement_s *functionStatement = m_conversion_zone_state->FindFunction(functionCall->m_function_name); - auto* outputExpressionEntries = static_cast(m_memory->Alloc(sizeof(expressionEntry) * expressionEntries.size())); - memcpy(outputExpressionEntries, expressionEntries.data(), sizeof(expressionEntry) * expressionEntries.size()); + if (functionStatement == nullptr) { + // Function was not converted yet: Convert it now + const auto foundCommonFunction = m_parsing_zone_state->m_functions_by_name.find(functionCall->m_function_name); - statement->entries = outputExpressionEntries; - statement->numEntries = static_cast(expressionEntries.size()); + if (foundCommonFunction == m_parsing_zone_state->m_functions_by_name.end()) + throw MenuConversionException("Failed to find definition for custom function \"" + functionCall->m_function_name + "\"", menu, item); - return statement; - } + functionStatement = ConvertExpression(foundCommonFunction->second->m_value.get(), menu, item); + functionStatement = m_conversion_zone_state->AddFunction(foundCommonFunction->second->m_name, functionStatement); + } - _NODISCARD Statement_s* ConvertOrApplyStatement(float& staticValue, const ISimpleExpression* expression, const CommonMenuDef* menu, const CommonItemDef* item = nullptr) const - { - if (m_disable_optimizations) - return ConvertExpression(expression, menu, item); - - if (!expression) - return nullptr; - - if (expression->IsStatic()) - { - const auto value = expression->EvaluateStatic(); - switch (value.m_type) - { - case SimpleExpressionValue::Type::DOUBLE: - staticValue = static_cast(value.m_double_value); - break; - case SimpleExpressionValue::Type::INT: - staticValue = static_cast(value.m_int_value); - break; - case SimpleExpressionValue::Type::STRING: - throw MenuConversionException("Cannot convert string expression value to floating point", menu, item); - } - return nullptr; - } - - return ConvertExpression(expression, menu, item); - } + expressionEntry functionEntry{}; + functionEntry.type = EET_OPERAND; + functionEntry.data.operand.dataType = VAL_FUNCTION; + functionEntry.data.operand.internals.function = functionStatement; + entries.emplace_back(functionEntry); + + // Statement uses custom function so it needs supporting data + gameStatement->supportingData = m_conversion_zone_state->m_supporting_data; + } + + constexpr static expressionOperatorType_e UNARY_OPERATION_MAPPING[static_cast(SimpleUnaryOperationId::COUNT)]{OP_NOT, OP_BITWISENOT, OP_SUBTRACT}; + + bool IsOperation(const ISimpleExpression *expression) const { + if (!m_disable_optimizations && expression->IsStatic()) + return false; + + return dynamic_cast(expression) || dynamic_cast(expression); + } + + void ConvertExpressionEntryUnaryOperation(Statement_s *gameStatement, std::vector &entries, + const SimpleExpressionUnaryOperation *unaryOperation, const CommonMenuDef *menu, const CommonItemDef *item) const { + assert(static_cast(unaryOperation->m_operation_type->m_id) < static_cast(SimpleUnaryOperationId::COUNT)); + expressionEntry operation{}; + operation.type = EET_OPERATOR; + operation.data.op = UNARY_OPERATION_MAPPING[static_cast(unaryOperation->m_operation_type->m_id)]; + entries.emplace_back(operation); + + if (IsOperation(unaryOperation->m_operand.get())) { + expressionEntry parenLeft{}; + parenLeft.type = EET_OPERATOR; + parenLeft.data.op = OP_LEFTPAREN; + entries.emplace_back(parenLeft); + + ConvertExpressionEntry(gameStatement, entries, unaryOperation->m_operand.get(), menu, item); + + expressionEntry parenRight{}; + parenRight.type = EET_OPERATOR; + parenRight.data.op = OP_RIGHTPAREN; + entries.emplace_back(parenRight); + } else + ConvertExpressionEntry(gameStatement, entries, unaryOperation->m_operand.get(), menu, item); + } + + constexpr static expressionOperatorType_e BINARY_OPERATION_MAPPING[static_cast(SimpleBinaryOperationId::COUNT)]{OP_ADD, + OP_SUBTRACT, + OP_MULTIPLY, + OP_DIVIDE, + OP_MODULUS, + OP_BITWISEAND, + OP_BITWISEOR, + OP_BITSHIFTLEFT, + OP_BITSHIFTRIGHT, + OP_GREATERTHAN, + OP_GREATERTHANEQUALTO, + OP_LESSTHAN, + OP_LESSTHANEQUALTO, + OP_EQUALS, + OP_NOTEQUAL, + OP_AND, + OP_OR}; + + void ConvertExpressionEntryBinaryOperation(Statement_s *gameStatement, std::vector &entries, + const SimpleExpressionBinaryOperation *binaryOperation, const CommonMenuDef *menu, + const CommonItemDef *item) const { + // Game needs all nested operations to have parenthesis + if (IsOperation(binaryOperation->m_operand1.get())) { + expressionEntry parenLeft{}; + parenLeft.type = EET_OPERATOR; + parenLeft.data.op = OP_LEFTPAREN; + entries.emplace_back(parenLeft); + + ConvertExpressionEntry(gameStatement, entries, binaryOperation->m_operand1.get(), menu, item); + + expressionEntry parenRight{}; + parenRight.type = EET_OPERATOR; + parenRight.data.op = OP_RIGHTPAREN; + entries.emplace_back(parenRight); + } else + ConvertExpressionEntry(gameStatement, entries, binaryOperation->m_operand1.get(), menu, item); + + assert(static_cast(binaryOperation->m_operation_type->m_id) < static_cast(SimpleBinaryOperationId::COUNT)); + expressionEntry operation{}; + operation.type = EET_OPERATOR; + operation.data.op = BINARY_OPERATION_MAPPING[static_cast(binaryOperation->m_operation_type->m_id)]; + entries.emplace_back(operation); + + // Game needs all nested operations to have parenthesis + if (IsOperation(binaryOperation->m_operand2.get())) { + expressionEntry parenLeft{}; + parenLeft.type = EET_OPERATOR; + parenLeft.data.op = OP_LEFTPAREN; + entries.emplace_back(parenLeft); + + ConvertExpressionEntry(gameStatement, entries, binaryOperation->m_operand2.get(), menu, item); + + expressionEntry parenRight{}; + parenRight.type = EET_OPERATOR; + parenRight.data.op = OP_RIGHTPAREN; + entries.emplace_back(parenRight); + } else + ConvertExpressionEntry(gameStatement, entries, binaryOperation->m_operand2.get(), menu, item); + } + + void ConvertExpressionEntryExpressionValue(std::vector &entries, const SimpleExpressionValue *expressionValue) const { + expressionEntry entry{}; + entry.type = EET_OPERAND; + + if (expressionValue->m_type == SimpleExpressionValue::Type::INT) { + entry.data.operand.dataType = VAL_INT; + entry.data.operand.internals.intVal = expressionValue->m_int_value; + } else if (expressionValue->m_type == SimpleExpressionValue::Type::DOUBLE) { + entry.data.operand.dataType = VAL_FLOAT; + entry.data.operand.internals.floatVal = static_cast(expressionValue->m_double_value); + } else if (expressionValue->m_type == SimpleExpressionValue::Type::STRING) { + entry.data.operand.dataType = VAL_STRING; + entry.data.operand.internals.stringVal.string = m_conversion_zone_state->AddString(*expressionValue->m_string_value); + } - _NODISCARD Statement_s* ConvertOrApplyStatement(const char*& staticValue, const ISimpleExpression* expression, const CommonMenuDef* menu, const CommonItemDef* item = nullptr) const - { - if (m_disable_optimizations) - return ConvertExpression(expression, menu, item); - - if (!expression) - return nullptr; - - if (expression->IsStatic()) - { - const auto value = expression->EvaluateStatic(); - switch (value.m_type) - { - case SimpleExpressionValue::Type::STRING: - staticValue = m_memory->Dup(value.m_string_value->c_str()); - break; - - case SimpleExpressionValue::Type::DOUBLE: - case SimpleExpressionValue::Type::INT: - throw MenuConversionException("Cannot convert numeric expression value to string", menu, item); - } - return nullptr; - } - - return ConvertExpression(expression, menu, item); - } + entries.emplace_back(entry); + } + + void ConvertExpressionEntry(Statement_s *gameStatement, std::vector &entries, const ISimpleExpression *expression, const CommonMenuDef *menu, + const CommonItemDef *item) const { + if (!m_disable_optimizations && expression->IsStatic()) { + const auto expressionStaticValue = expression->EvaluateStatic(); + ConvertExpressionEntryExpressionValue(entries, &expressionStaticValue); + } else if (const auto *expressionValue = dynamic_cast(expression)) { + ConvertExpressionEntryExpressionValue(entries, expressionValue); + } else if (const auto *binaryOperation = dynamic_cast(expression)) { + ConvertExpressionEntryBinaryOperation(gameStatement, entries, binaryOperation, menu, item); + } else if (const auto *unaryOperation = dynamic_cast(expression)) { + ConvertExpressionEntryUnaryOperation(gameStatement, entries, unaryOperation, menu, item); + } else if (const auto *baseFunctionCall = dynamic_cast(expression)) { + ConvertExpressionEntryBaseFunctionCall(gameStatement, entries, baseFunctionCall, menu, item); + } else if (const auto *customFunctionCall = dynamic_cast(expression)) { + ConvertExpressionEntryCustomFunctionCall(gameStatement, entries, customFunctionCall, menu, item); + } else if (dynamic_cast(expression)) { + throw MenuConversionException("Cannot use conditional expression in menu expressions", menu, item); + } else { + assert(false); + throw MenuConversionException("Unknown expression entry type in menu expressions", menu, item); + } + } + + _NODISCARD Statement_s *ConvertExpression(const ISimpleExpression *expression, const CommonMenuDef *menu, const CommonItemDef *item = nullptr) const { + if (!expression) + return nullptr; + + auto *statement = m_memory->Create(); + for (auto &result : statement->persistentState.lastResult) + result = Operand{}; + for (auto &lastExecutionTime : statement->persistentState.lastExecuteTime) + lastExecutionTime = 0; + statement->supportingData = nullptr; // Supporting data is set upon using it + + std::vector expressionEntries; + ConvertExpressionEntry(statement, expressionEntries, expression, menu, item); + + auto *outputExpressionEntries = static_cast(m_memory->Alloc(sizeof(expressionEntry) * expressionEntries.size())); + memcpy(outputExpressionEntries, expressionEntries.data(), sizeof(expressionEntry) * expressionEntries.size()); + + statement->entries = outputExpressionEntries; + statement->numEntries = static_cast(expressionEntries.size()); + + return statement; + } + + _NODISCARD Statement_s *ConvertOrApplyStatement(float &staticValue, const ISimpleExpression *expression, const CommonMenuDef *menu, + const CommonItemDef *item = nullptr) const { + if (m_disable_optimizations) + return ConvertExpression(expression, menu, item); + + if (!expression) + return nullptr; + + if (expression->IsStatic()) { + const auto value = expression->EvaluateStatic(); + switch (value.m_type) { + case SimpleExpressionValue::Type::DOUBLE: + staticValue = static_cast(value.m_double_value); + break; + case SimpleExpressionValue::Type::INT: + staticValue = static_cast(value.m_int_value); + break; + case SimpleExpressionValue::Type::STRING: + throw MenuConversionException("Cannot convert string expression value to floating point", menu, item); + } + return nullptr; + } - _NODISCARD Statement_s* ConvertOrApplyStatement(Material*& staticValue, const ISimpleExpression* expression, const CommonMenuDef* menu, const CommonItemDef* item = nullptr) const - { - if (m_disable_optimizations) - return ConvertExpression(expression, menu, item); - - if (!expression) - return nullptr; - - if (expression->IsStatic()) - { - const auto value = expression->EvaluateStatic(); - switch (value.m_type) - { - case SimpleExpressionValue::Type::STRING: - staticValue = ConvertMaterial(*value.m_string_value, menu, item); - break; - - case SimpleExpressionValue::Type::DOUBLE: - case SimpleExpressionValue::Type::INT: - throw MenuConversionException("Cannot convert numeric expression value to string", menu, item); - } - return nullptr; - } - - return ConvertExpression(expression, menu, item); - } + return ConvertExpression(expression, menu, item); + } + + _NODISCARD Statement_s *ConvertOrApplyStatement(const char *&staticValue, const ISimpleExpression *expression, const CommonMenuDef *menu, + const CommonItemDef *item = nullptr) const { + if (m_disable_optimizations) + return ConvertExpression(expression, menu, item); + + if (!expression) + return nullptr; + + if (expression->IsStatic()) { + const auto value = expression->EvaluateStatic(); + switch (value.m_type) { + case SimpleExpressionValue::Type::STRING: + staticValue = m_memory->Dup(value.m_string_value->c_str()); + break; + + case SimpleExpressionValue::Type::DOUBLE: + case SimpleExpressionValue::Type::INT: + throw MenuConversionException("Cannot convert numeric expression value to string", menu, item); + } + return nullptr; + } - _NODISCARD Statement_s* ConvertVisibleExpression(windowDef_t* window, const ISimpleExpression* expression, const CommonMenuDef* commonMenu, const CommonItemDef* commonItem = nullptr) const - { - if (expression == nullptr) - return nullptr; - - bool isStatic; - bool isTruthy; - if (m_disable_optimizations) - { - const auto* staticValue = dynamic_cast(expression); - isStatic = staticValue != nullptr; - isTruthy = isStatic && (staticValue->m_type == SimpleExpressionValue::Type::INT || staticValue->m_type == SimpleExpressionValue::Type::DOUBLE) && staticValue->IsTruthy(); - } - else - { - isStatic = expression->IsStatic(); - isTruthy = isStatic && expression->EvaluateStatic().IsTruthy(); - } - - if (isStatic) - { - if (isTruthy) - window->dynamicFlags[0] |= WINDOW_FLAG_VISIBLE; - return nullptr; - } - - window->dynamicFlags[0] |= WINDOW_FLAG_VISIBLE; - return ConvertExpression(expression, commonMenu, commonItem); - } + return ConvertExpression(expression, menu, item); + } + + _NODISCARD Statement_s *ConvertOrApplyStatement(Material *&staticValue, const ISimpleExpression *expression, const CommonMenuDef *menu, + const CommonItemDef *item = nullptr) const { + if (m_disable_optimizations) + return ConvertExpression(expression, menu, item); + + if (!expression) + return nullptr; + + if (expression->IsStatic()) { + const auto value = expression->EvaluateStatic(); + switch (value.m_type) { + case SimpleExpressionValue::Type::STRING: + staticValue = ConvertMaterial(*value.m_string_value, menu, item); + break; + + case SimpleExpressionValue::Type::DOUBLE: + case SimpleExpressionValue::Type::INT: + throw MenuConversionException("Cannot convert numeric expression value to string", menu, item); + } + return nullptr; + } - _NODISCARD static EventType SetLocalVarTypeToEventType(const SetLocalVarType setLocalVarType) - { - switch (setLocalVarType) - { - case SetLocalVarType::BOOL: - return EVENT_SET_LOCAL_VAR_BOOL; - case SetLocalVarType::STRING: - return EVENT_SET_LOCAL_VAR_STRING; - case SetLocalVarType::FLOAT: - return EVENT_SET_LOCAL_VAR_FLOAT; - case SetLocalVarType::INT: - return EVENT_SET_LOCAL_VAR_INT; - default: - case SetLocalVarType::UNKNOWN: - assert(false); - return EVENT_SET_LOCAL_VAR_INT; - } - } + return ConvertExpression(expression, menu, item); + } + + _NODISCARD Statement_s *ConvertVisibleExpression(windowDef_t *window, const ISimpleExpression *expression, const CommonMenuDef *commonMenu, + const CommonItemDef *commonItem = nullptr) const { + if (expression == nullptr) + return nullptr; + + bool isStatic; + bool isTruthy; + if (m_disable_optimizations) { + const auto *staticValue = dynamic_cast(expression); + isStatic = staticValue != nullptr; + isTruthy = isStatic && (staticValue->m_type == SimpleExpressionValue::Type::INT || staticValue->m_type == SimpleExpressionValue::Type::DOUBLE) && + staticValue->IsTruthy(); + } else { + isStatic = expression->IsStatic(); + isTruthy = isStatic && expression->EvaluateStatic().IsTruthy(); + } - void ConvertEventHandlerSetLocalVar(std::vector& elements, const CommonEventHandlerSetLocalVar* setLocalVar, const CommonMenuDef* menu, const CommonItemDef* item) const - { - assert(setLocalVar); - if (!setLocalVar) - return; + if (isStatic) { + if (isTruthy) + window->dynamicFlags[0] |= WINDOW_FLAG_VISIBLE; + return nullptr; + } - auto* outputHandler = static_cast(m_memory->Alloc(sizeof(MenuEventHandler) + sizeof(SetLocalVarData))); - auto* outputSetLocalVar = reinterpret_cast(reinterpret_cast(outputHandler) + sizeof(MenuEventHandler)); + window->dynamicFlags[0] |= WINDOW_FLAG_VISIBLE; + return ConvertExpression(expression, commonMenu, commonItem); + } + + _NODISCARD static EventType SetLocalVarTypeToEventType(const SetLocalVarType setLocalVarType) { + switch (setLocalVarType) { + case SetLocalVarType::BOOL: + return EVENT_SET_LOCAL_VAR_BOOL; + case SetLocalVarType::STRING: + return EVENT_SET_LOCAL_VAR_STRING; + case SetLocalVarType::FLOAT: + return EVENT_SET_LOCAL_VAR_FLOAT; + case SetLocalVarType::INT: + return EVENT_SET_LOCAL_VAR_INT; + default: + case SetLocalVarType::UNKNOWN: + assert(false); + return EVENT_SET_LOCAL_VAR_INT; + } + } - outputHandler->eventType = SetLocalVarTypeToEventType(setLocalVar->m_type); - outputHandler->eventData.setLocalVarData = outputSetLocalVar; + void ConvertEventHandlerSetLocalVar(std::vector &elements, const CommonEventHandlerSetLocalVar *setLocalVar, const CommonMenuDef *menu, + const CommonItemDef *item) const { + assert(setLocalVar); + if (!setLocalVar) + return; - outputSetLocalVar->localVarName = m_memory->Dup(setLocalVar->m_var_name.c_str()); - outputSetLocalVar->expression = ConvertExpression(setLocalVar->m_value.get(), menu, item); + auto *outputHandler = static_cast(m_memory->Alloc(sizeof(MenuEventHandler) + sizeof(SetLocalVarData))); + auto *outputSetLocalVar = reinterpret_cast(reinterpret_cast(outputHandler) + sizeof(MenuEventHandler)); - elements.push_back(outputHandler); - } + outputHandler->eventType = SetLocalVarTypeToEventType(setLocalVar->m_type); + outputHandler->eventData.setLocalVarData = outputSetLocalVar; - void ConvertEventHandlerScript(std::vector& elements, const CommonEventHandlerScript* script) const - { - assert(script); - if (!script) - return; + outputSetLocalVar->localVarName = m_memory->Dup(setLocalVar->m_var_name.c_str()); + outputSetLocalVar->expression = ConvertExpression(setLocalVar->m_value.get(), menu, item); - auto* outputHandler = m_memory->Create(); - outputHandler->eventType = EVENT_UNCONDITIONAL; - outputHandler->eventData.unconditionalScript = m_memory->Dup(script->m_script.c_str()); + elements.push_back(outputHandler); + } - elements.push_back(outputHandler); - } + void ConvertEventHandlerScript(std::vector &elements, const CommonEventHandlerScript *script) const { + assert(script); + if (!script) + return; - void ConvertEventHandlerCondition(std::vector& elements, const CommonEventHandlerCondition* condition, const CommonMenuDef* menu, - const CommonItemDef* item) const - { - assert(condition); - if (!condition || !condition->m_condition) - return; - - if (!m_disable_optimizations && condition->m_condition->IsStatic()) - { - const auto staticValueIsTruthy = condition->m_condition->EvaluateStatic().IsTruthy(); - - if (staticValueIsTruthy) - ConvertEventHandlerElements(elements, condition->m_condition_elements.get(), menu, item); - else if (condition->m_else_elements) - ConvertEventHandlerElements(elements, condition->m_else_elements.get(), menu, item); - } - else - { - auto* outputHandler = static_cast(m_memory->Alloc(sizeof(MenuEventHandler) + sizeof(ConditionalScript))); - auto* outputCondition = reinterpret_cast(reinterpret_cast(outputHandler) + sizeof(MenuEventHandler)); - - outputHandler->eventType = EVENT_IF; - outputHandler->eventData.conditionalScript = outputCondition; - - outputCondition->eventExpression = ConvertExpression(condition->m_condition.get(), menu, item); - outputCondition->eventHandlerSet = ConvertEventHandlerSet(condition->m_condition_elements.get(), menu, item); - - elements.push_back(outputHandler); - - if (condition->m_else_elements) - { - auto* outputElseHandler = m_memory->Create(); - outputElseHandler->eventType = EVENT_ELSE; - outputElseHandler->eventData.elseScript = ConvertEventHandlerSet(condition->m_else_elements.get(), menu, item); - - elements.push_back(outputElseHandler); - } - } - } + auto *outputHandler = m_memory->Create(); + outputHandler->eventType = EVENT_UNCONDITIONAL; + outputHandler->eventData.unconditionalScript = m_memory->Dup(script->m_script.c_str()); - void ConvertEventHandler(std::vector& elements, const ICommonEventHandlerElement* eventHandler, const CommonMenuDef* menu, - const CommonItemDef* item) const - { - assert(eventHandler); - if (!eventHandler) - return; - - switch (eventHandler->GetType()) - { - case CommonEventHandlerElementType::CONDITION: - ConvertEventHandlerCondition(elements, dynamic_cast(eventHandler), menu, item); - break; - - case CommonEventHandlerElementType::SCRIPT: - ConvertEventHandlerScript(elements, dynamic_cast(eventHandler)); - break; - - case CommonEventHandlerElementType::SET_LOCAL_VAR: - ConvertEventHandlerSetLocalVar(elements, dynamic_cast(eventHandler), menu, item); - break; - } - } + elements.push_back(outputHandler); + } - void ConvertEventHandlerElements(std::vector& elements, const CommonEventHandlerSet* eventHandlerSet, const CommonMenuDef* menu, const CommonItemDef* item) const - { - for (const auto& element : eventHandlerSet->m_elements) - ConvertEventHandler(elements, element.get(), menu, item); - } + void ConvertEventHandlerCondition(std::vector &elements, const CommonEventHandlerCondition *condition, const CommonMenuDef *menu, + const CommonItemDef *item) const { + assert(condition); + if (!condition || !condition->m_condition) + return; - _NODISCARD MenuEventHandlerSet* ConvertEventHandlerSet(const CommonEventHandlerSet* eventHandlerSet, const CommonMenuDef* menu, const CommonItemDef* item = nullptr) const - { - if (!eventHandlerSet) - return nullptr; + if (!m_disable_optimizations && condition->m_condition->IsStatic()) { + const auto staticValueIsTruthy = condition->m_condition->EvaluateStatic().IsTruthy(); - std::vector elements; - ConvertEventHandlerElements(elements, eventHandlerSet, menu, item); + if (staticValueIsTruthy) + ConvertEventHandlerElements(elements, condition->m_condition_elements.get(), menu, item); + else if (condition->m_else_elements) + ConvertEventHandlerElements(elements, condition->m_else_elements.get(), menu, item); + } else { + auto *outputHandler = static_cast(m_memory->Alloc(sizeof(MenuEventHandler) + sizeof(ConditionalScript))); + auto *outputCondition = reinterpret_cast(reinterpret_cast(outputHandler) + sizeof(MenuEventHandler)); - if (elements.empty()) - return nullptr; + outputHandler->eventType = EVENT_IF; + outputHandler->eventData.conditionalScript = outputCondition; - auto* outputSet = static_cast(m_memory->Alloc(sizeof(MenuEventHandlerSet) + sizeof(void*) * elements.size())); - auto* outputElements = reinterpret_cast(reinterpret_cast(outputSet) + sizeof(MenuEventHandlerSet)); - memcpy(outputElements, &elements[0], sizeof(void*) * elements.size()); + outputCondition->eventExpression = ConvertExpression(condition->m_condition.get(), menu, item); + outputCondition->eventHandlerSet = ConvertEventHandlerSet(condition->m_condition_elements.get(), menu, item); - outputSet->eventHandlerCount = static_cast(elements.size()); - outputSet->eventHandlers = outputElements; + elements.push_back(outputHandler); - return outputSet; - } + if (condition->m_else_elements) { + auto *outputElseHandler = m_memory->Create(); + outputElseHandler->eventType = EVENT_ELSE; + outputElseHandler->eventData.elseScript = ConvertEventHandlerSet(condition->m_else_elements.get(), menu, item); - _NODISCARD ItemKeyHandler* ConvertKeyHandler(const std::multimap>& keyHandlers, const CommonMenuDef* menu, - const CommonItemDef* item = nullptr) const - { - if (keyHandlers.empty()) - return nullptr; - - const auto keyHandlerCount = keyHandlers.size(); - auto* output = static_cast(m_memory->Alloc(sizeof(ItemKeyHandler) * keyHandlerCount)); - auto currentKeyHandler = keyHandlers.cbegin(); - for (auto i = 0u; i < keyHandlerCount; i++) - { - output[i].key = currentKeyHandler->first; - output[i].action = ConvertEventHandlerSet(currentKeyHandler->second.get(), menu, item); - - if (i + 1 < keyHandlerCount) - output[i].next = &output[i + 1]; - else - output[i].next = nullptr; - ++currentKeyHandler; - } - - return output; - } + elements.push_back(outputElseHandler); + } + } + } + + void ConvertEventHandler(std::vector &elements, const ICommonEventHandlerElement *eventHandler, const CommonMenuDef *menu, + const CommonItemDef *item) const { + assert(eventHandler); + if (!eventHandler) + return; + + switch (eventHandler->GetType()) { + case CommonEventHandlerElementType::CONDITION: + ConvertEventHandlerCondition(elements, dynamic_cast(eventHandler), menu, item); + break; + + case CommonEventHandlerElementType::SCRIPT: + ConvertEventHandlerScript(elements, dynamic_cast(eventHandler)); + break; + + case CommonEventHandlerElementType::SET_LOCAL_VAR: + ConvertEventHandlerSetLocalVar(elements, dynamic_cast(eventHandler), menu, item); + break; + } + } + + void ConvertEventHandlerElements(std::vector &elements, const CommonEventHandlerSet *eventHandlerSet, const CommonMenuDef *menu, + const CommonItemDef *item) const { + for (const auto &element : eventHandlerSet->m_elements) + ConvertEventHandler(elements, element.get(), menu, item); + } + + _NODISCARD MenuEventHandlerSet *ConvertEventHandlerSet(const CommonEventHandlerSet *eventHandlerSet, const CommonMenuDef *menu, + const CommonItemDef *item = nullptr) const { + if (!eventHandlerSet) + return nullptr; + + std::vector elements; + ConvertEventHandlerElements(elements, eventHandlerSet, menu, item); + + if (elements.empty()) + return nullptr; + + auto *outputSet = static_cast(m_memory->Alloc(sizeof(MenuEventHandlerSet) + sizeof(void *) * elements.size())); + auto *outputElements = reinterpret_cast(reinterpret_cast(outputSet) + sizeof(MenuEventHandlerSet)); + memcpy(outputElements, &elements[0], sizeof(void *) * elements.size()); + + outputSet->eventHandlerCount = static_cast(elements.size()); + outputSet->eventHandlers = outputElements; + + return outputSet; + } + + _NODISCARD ItemKeyHandler *ConvertKeyHandler(const std::multimap> &keyHandlers, const CommonMenuDef *menu, + const CommonItemDef *item = nullptr) const { + if (keyHandlers.empty()) + return nullptr; + + const auto keyHandlerCount = keyHandlers.size(); + auto *output = static_cast(m_memory->Alloc(sizeof(ItemKeyHandler) * keyHandlerCount)); + auto currentKeyHandler = keyHandlers.cbegin(); + for (auto i = 0u; i < keyHandlerCount; i++) { + output[i].key = currentKeyHandler->first; + output[i].action = ConvertEventHandlerSet(currentKeyHandler->second.get(), menu, item); + + if (i + 1 < keyHandlerCount) + output[i].next = &output[i + 1]; + else + output[i].next = nullptr; + ++currentKeyHandler; + } - ItemFloatExpression* ConvertFloatExpressions(const CommonItemDef* commonItem, itemDef_s* item, const CommonMenuDef* parentMenu, int& floatExpressionCount) const - { - struct FloatExpressionLocation - { - ISimpleExpression* m_expression; - bool m_expression_is_static; - ItemFloatExpressionTarget m_target; - float* m_static_value; - unsigned m_static_value_array_size; - unsigned m_dynamic_flags_to_set; - }; - FloatExpressionLocation locations[] - { - {commonItem->m_rect_x_exp.get(), false, ITEM_FLOATEXP_TGT_RECT_X, &item->window.rectClient.x, 1, 0}, - {commonItem->m_rect_y_exp.get(), false, ITEM_FLOATEXP_TGT_RECT_Y, &item->window.rectClient.y, 1, 0}, - {commonItem->m_rect_w_exp.get(), false, ITEM_FLOATEXP_TGT_RECT_W, &item->window.rectClient.w, 1, 0}, - {commonItem->m_rect_h_exp.get(), false, ITEM_FLOATEXP_TGT_RECT_H, &item->window.rectClient.h, 1, 0}, - {commonItem->m_forecolor_expressions.m_r_exp.get(), false, ITEM_FLOATEXP_TGT_FORECOLOR_R, &item->window.foreColor[0], 1, WINDOW_FLAG_NON_DEFAULT_FORECOLOR}, - {commonItem->m_forecolor_expressions.m_g_exp.get(), false, ITEM_FLOATEXP_TGT_FORECOLOR_G, &item->window.foreColor[1], 1, WINDOW_FLAG_NON_DEFAULT_FORECOLOR}, - {commonItem->m_forecolor_expressions.m_b_exp.get(), false, ITEM_FLOATEXP_TGT_FORECOLOR_B, &item->window.foreColor[2], 1, WINDOW_FLAG_NON_DEFAULT_FORECOLOR}, - {commonItem->m_forecolor_expressions.m_a_exp.get(), false, ITEM_FLOATEXP_TGT_FORECOLOR_A, &item->window.foreColor[3], 1, WINDOW_FLAG_NON_DEFAULT_FORECOLOR}, - {commonItem->m_forecolor_expressions.m_rgb_exp.get(), false, ITEM_FLOATEXP_TGT_FORECOLOR_RGB, &item->window.foreColor[0], 3, WINDOW_FLAG_NON_DEFAULT_FORECOLOR}, - {commonItem->m_glowcolor_expressions.m_r_exp.get(), false, ITEM_FLOATEXP_TGT_GLOWCOLOR_R, &item->glowColor[0], 1, 0}, - {commonItem->m_glowcolor_expressions.m_g_exp.get(), false, ITEM_FLOATEXP_TGT_GLOWCOLOR_G, &item->glowColor[1], 1, 0}, - {commonItem->m_glowcolor_expressions.m_b_exp.get(), false, ITEM_FLOATEXP_TGT_GLOWCOLOR_B, &item->glowColor[2], 1, 0}, - {commonItem->m_glowcolor_expressions.m_a_exp.get(), false, ITEM_FLOATEXP_TGT_GLOWCOLOR_A, &item->glowColor[3], 1, 0}, - {commonItem->m_glowcolor_expressions.m_rgb_exp.get(), false, ITEM_FLOATEXP_TGT_GLOWCOLOR_RGB, &item->glowColor[0], 3, 0}, - {commonItem->m_backcolor_expressions.m_r_exp.get(), false, ITEM_FLOATEXP_TGT_BACKCOLOR_R, &item->window.backColor[0], 1, 0}, - {commonItem->m_backcolor_expressions.m_g_exp.get(), false, ITEM_FLOATEXP_TGT_BACKCOLOR_G, &item->window.backColor[1], 1, 0}, - {commonItem->m_backcolor_expressions.m_b_exp.get(), false, ITEM_FLOATEXP_TGT_BACKCOLOR_B, &item->window.backColor[2], 1, 0}, - {commonItem->m_backcolor_expressions.m_a_exp.get(), false, ITEM_FLOATEXP_TGT_BACKCOLOR_A, &item->window.backColor[3], 1, 0}, - {commonItem->m_backcolor_expressions.m_rgb_exp.get(), false, ITEM_FLOATEXP_TGT_BACKCOLOR_RGB, &item->window.backColor[0], 3, 0}, - }; - - floatExpressionCount = 0; - for (auto& [expression, expressionIsStatic, target, staticValue, staticValueArraySize, dynamicFlagsToSet] : locations) - { - expressionIsStatic = !m_disable_optimizations && staticValue != nullptr && expression && expression->IsStatic(); - - if (expressionIsStatic) - { - const auto evaluatedValue = expression->EvaluateStatic(); - - if (evaluatedValue.m_type == SimpleExpressionValue::Type::INT) - { - item->window.dynamicFlags[0] |= dynamicFlagsToSet; - - auto* staticValuePtr = staticValue; - for (auto i = 0u; i < staticValueArraySize; i++) - { - *staticValuePtr = static_cast(evaluatedValue.m_int_value); - staticValuePtr++; - } - continue; - } - if (evaluatedValue.m_type == SimpleExpressionValue::Type::DOUBLE) - { - item->window.dynamicFlags[0] |= dynamicFlagsToSet; - auto* staticValuePtr = staticValue; - for (auto i = 0u; i < staticValueArraySize; i++) - { - *staticValue = static_cast(evaluatedValue.m_double_value); - staticValuePtr++; - } - continue; - } - - // Do not consider this a mistake since the games menus do this by mistake and it should be able to compile them anyway - // But the game should also not know what to do with this i guess - expressionIsStatic = false; - } - - if (expression) - floatExpressionCount++; - } - - if (floatExpressionCount <= 0) - return nullptr; - - auto* floatExpressions = static_cast(m_memory->Alloc(sizeof(ItemFloatExpression) * floatExpressionCount)); - auto floatExpressionIndex = 0; - for (const auto& [expression, expressionIsStatic, target, staticValue, staticValueArraySize, dynamicFlagsToSet] : locations) - { - if (!expression || expressionIsStatic) - continue; - - assert(floatExpressionIndex < floatExpressionCount && floatExpressionIndex >= 0); - floatExpressions[floatExpressionIndex].target = target; - floatExpressions[floatExpressionIndex].expression = ConvertExpression(expression, parentMenu, commonItem); - item->window.dynamicFlags[0] |= dynamicFlagsToSet; - floatExpressionIndex++; - } - - return floatExpressions; - } + return output; + } + + ItemFloatExpression *ConvertFloatExpressions(const CommonItemDef *commonItem, itemDef_s *item, const CommonMenuDef *parentMenu, + int &floatExpressionCount) const { + struct FloatExpressionLocation { + ISimpleExpression *m_expression; + bool m_expression_is_static; + ItemFloatExpressionTarget m_target; + float *m_static_value; + unsigned m_static_value_array_size; + unsigned m_dynamic_flags_to_set; + }; + FloatExpressionLocation locations[]{ + {commonItem->m_rect_x_exp.get(), false, ITEM_FLOATEXP_TGT_RECT_X, &item->window.rectClient.x, 1, 0}, + {commonItem->m_rect_y_exp.get(), false, ITEM_FLOATEXP_TGT_RECT_Y, &item->window.rectClient.y, 1, 0}, + {commonItem->m_rect_w_exp.get(), false, ITEM_FLOATEXP_TGT_RECT_W, &item->window.rectClient.w, 1, 0}, + {commonItem->m_rect_h_exp.get(), false, ITEM_FLOATEXP_TGT_RECT_H, &item->window.rectClient.h, 1, 0}, + {commonItem->m_forecolor_expressions.m_r_exp.get(), false, ITEM_FLOATEXP_TGT_FORECOLOR_R, &item->window.foreColor[0], 1, + WINDOW_FLAG_NON_DEFAULT_FORECOLOR }, + {commonItem->m_forecolor_expressions.m_g_exp.get(), false, ITEM_FLOATEXP_TGT_FORECOLOR_G, &item->window.foreColor[1], 1, + WINDOW_FLAG_NON_DEFAULT_FORECOLOR }, + {commonItem->m_forecolor_expressions.m_b_exp.get(), false, ITEM_FLOATEXP_TGT_FORECOLOR_B, &item->window.foreColor[2], 1, + WINDOW_FLAG_NON_DEFAULT_FORECOLOR }, + {commonItem->m_forecolor_expressions.m_a_exp.get(), false, ITEM_FLOATEXP_TGT_FORECOLOR_A, &item->window.foreColor[3], 1, + WINDOW_FLAG_NON_DEFAULT_FORECOLOR }, + {commonItem->m_forecolor_expressions.m_rgb_exp.get(), false, ITEM_FLOATEXP_TGT_FORECOLOR_RGB, &item->window.foreColor[0], 3, + WINDOW_FLAG_NON_DEFAULT_FORECOLOR }, + {commonItem->m_glowcolor_expressions.m_r_exp.get(), false, ITEM_FLOATEXP_TGT_GLOWCOLOR_R, &item->glowColor[0], 1, 0}, + {commonItem->m_glowcolor_expressions.m_g_exp.get(), false, ITEM_FLOATEXP_TGT_GLOWCOLOR_G, &item->glowColor[1], 1, 0}, + {commonItem->m_glowcolor_expressions.m_b_exp.get(), false, ITEM_FLOATEXP_TGT_GLOWCOLOR_B, &item->glowColor[2], 1, 0}, + {commonItem->m_glowcolor_expressions.m_a_exp.get(), false, ITEM_FLOATEXP_TGT_GLOWCOLOR_A, &item->glowColor[3], 1, 0}, + {commonItem->m_glowcolor_expressions.m_rgb_exp.get(), false, ITEM_FLOATEXP_TGT_GLOWCOLOR_RGB, &item->glowColor[0], 3, 0}, + {commonItem->m_backcolor_expressions.m_r_exp.get(), false, ITEM_FLOATEXP_TGT_BACKCOLOR_R, &item->window.backColor[0], 1, 0}, + {commonItem->m_backcolor_expressions.m_g_exp.get(), false, ITEM_FLOATEXP_TGT_BACKCOLOR_G, &item->window.backColor[1], 1, 0}, + {commonItem->m_backcolor_expressions.m_b_exp.get(), false, ITEM_FLOATEXP_TGT_BACKCOLOR_B, &item->window.backColor[2], 1, 0}, + {commonItem->m_backcolor_expressions.m_a_exp.get(), false, ITEM_FLOATEXP_TGT_BACKCOLOR_A, &item->window.backColor[3], 1, 0}, + {commonItem->m_backcolor_expressions.m_rgb_exp.get(), false, ITEM_FLOATEXP_TGT_BACKCOLOR_RGB, &item->window.backColor[0], 3, 0}, + }; - _NODISCARD const char* CreateEnableDvarString(const std::vector& stringElements) const - { - std::ostringstream ss; + floatExpressionCount = 0; + for (auto &[expression, expressionIsStatic, target, staticValue, staticValueArraySize, dynamicFlagsToSet] : locations) { + expressionIsStatic = !m_disable_optimizations && staticValue != nullptr && expression && expression->IsStatic(); - for (const auto& element : stringElements) - { - ss << "\"" << element << "\" "; - } + if (expressionIsStatic) { + const auto evaluatedValue = expression->EvaluateStatic(); - return m_memory->Dup(ss.str().c_str()); - } + if (evaluatedValue.m_type == SimpleExpressionValue::Type::INT) { + item->window.dynamicFlags[0] |= dynamicFlagsToSet; - _NODISCARD const char* ConvertEnableDvar(const CommonItemDef& commonItem, int& dvarFlags) const - { - dvarFlags = 0; - - if (!commonItem.m_enable_dvar.empty()) - { - dvarFlags |= ITEM_DVAR_FLAG_ENABLE; - return CreateEnableDvarString(commonItem.m_enable_dvar); - } - - if (!commonItem.m_disable_dvar.empty()) - { - dvarFlags |= ITEM_DVAR_FLAG_DISABLE; - return CreateEnableDvarString(commonItem.m_disable_dvar); - } - - if (!commonItem.m_show_dvar.empty()) - { - dvarFlags |= ITEM_DVAR_FLAG_SHOW; - return CreateEnableDvarString(commonItem.m_show_dvar); - } - - if (!commonItem.m_hide_dvar.empty()) - { - dvarFlags |= ITEM_DVAR_FLAG_HIDE; - return CreateEnableDvarString(commonItem.m_hide_dvar); - } - - if (!commonItem.m_focus_dvar.empty()) - { - dvarFlags |= ITEM_DVAR_FLAG_FOCUS; - return CreateEnableDvarString(commonItem.m_focus_dvar); - } - - return nullptr; + auto *staticValuePtr = staticValue; + for (auto i = 0u; i < staticValueArraySize; i++) { + *staticValuePtr = static_cast(evaluatedValue.m_int_value); + staticValuePtr++; + } + continue; } - - _NODISCARD listBoxDef_s* ConvertListBoxFeatures(itemDef_s* item, CommonItemFeaturesListBox* commonListBox, const CommonMenuDef& parentMenu, const CommonItemDef& commonItem) const - { - if (commonListBox == nullptr) - return nullptr; - - auto* listBox = static_cast(m_memory->Alloc(sizeof(listBoxDef_s))); - memset(listBox, 0, sizeof(listBoxDef_s)); - - listBox->notselectable = commonListBox->m_not_selectable ? 1 : 0; - listBox->noScrollBars = commonListBox->m_no_scrollbars ? 1 : 0; - listBox->usePaging = commonListBox->m_use_paging ? 1 : 0; - listBox->elementWidth = static_cast(commonListBox->m_element_width); - listBox->elementHeight = static_cast(commonListBox->m_element_height); - item->special = static_cast(commonListBox->m_feeder); - listBox->elementStyle = commonListBox->m_element_style; - listBox->onDoubleClick = ConvertEventHandlerSet(commonListBox->m_on_double_click.get(), &parentMenu, &commonItem); - ConvertColor(listBox->selectBorder, commonListBox->m_select_border); - listBox->selectIcon = ConvertMaterial(commonListBox->m_select_icon, &parentMenu, &commonItem); - listBox->elementHeightExp = ConvertOrApplyStatement(listBox->elementHeight, commonListBox->m_element_height_expression.get(), &parentMenu, &commonItem); - - listBox->numColumns = static_cast(std::min(std::extent_v, commonListBox->m_columns.size())); - for (auto i = 0; i < listBox->numColumns; i++) - { - auto& col = listBox->columnInfo[i]; - const auto& commonCol = commonListBox->m_columns[i]; - - col.xpos = commonCol.m_x_pos; - col.ypos = commonCol.m_y_pos; - col.width = commonCol.m_width; - col.maxChars = commonCol.m_max_chars; - col.alignment = commonCol.m_alignment; - } - - return listBox; + if (evaluatedValue.m_type == SimpleExpressionValue::Type::DOUBLE) { + item->window.dynamicFlags[0] |= dynamicFlagsToSet; + auto *staticValuePtr = staticValue; + for (auto i = 0u; i < staticValueArraySize; i++) { + *staticValue = static_cast(evaluatedValue.m_double_value); + staticValuePtr++; + } + continue; } - _NODISCARD editFieldDef_s* ConvertEditFieldFeatures(itemDef_s* item, CommonItemFeaturesEditField* commonEditField, const CommonMenuDef& parentMenu, const CommonItemDef& commonItem) const - { - if (commonEditField == nullptr) - return nullptr; + // Do not consider this a mistake since the games menus do this by mistake and it should be able to compile them anyway + // But the game should also not know what to do with this i guess + expressionIsStatic = false; + } - auto* editField = static_cast(m_memory->Alloc(sizeof(editFieldDef_s))); - memset(editField, 0, sizeof(editFieldDef_s)); - - editField->stepVal = static_cast(commonEditField->m_def_val); - editField->minVal = static_cast(commonEditField->m_min_val); - editField->maxVal = static_cast(commonEditField->m_max_val); - item->localVar = ConvertString(commonEditField->m_local_var); - editField->maxChars = commonEditField->m_max_chars; - editField->maxCharsGotoNext = commonEditField->m_max_chars_goto_next ? 1 : 0; - editField->maxPaintChars = commonEditField->m_max_paint_chars; + if (expression) + floatExpressionCount++; + } - return editField; - } + if (floatExpressionCount <= 0) + return nullptr; - _NODISCARD multiDef_s* ConvertMultiValueFeatures(itemDef_s* item, CommonItemFeaturesMultiValue* commonMultiValue, const CommonMenuDef& parentMenu, const CommonItemDef& commonItem) const - { - if (commonMultiValue == nullptr) - return nullptr; - - auto* multiValue = static_cast(m_memory->Alloc(sizeof(multiDef_s))); - memset(multiValue, 0, sizeof(multiDef_s)); - - multiValue->count = static_cast(std::min(std::extent_v, commonMultiValue->m_step_names.size())); - multiValue->strDef = !commonMultiValue->m_string_values.empty() ? 1 : 0; - - for (auto i = 0; i < multiValue->count; i++) - { - multiValue->dvarList[i] = ConvertString(commonMultiValue->m_step_names[i]); - - if (multiValue->strDef) - { - if (commonMultiValue->m_string_values.size() > static_cast(i)) - multiValue->dvarStr[i] = ConvertString(commonMultiValue->m_string_values[i]); - } - else - { - if (commonMultiValue->m_double_values.size() > static_cast(i)) - multiValue->dvarValue[i] = static_cast(commonMultiValue->m_double_values[i]); - } - } - - return multiValue; - } + auto *floatExpressions = static_cast(m_memory->Alloc(sizeof(ItemFloatExpression) * floatExpressionCount)); + auto floatExpressionIndex = 0; + for (const auto &[expression, expressionIsStatic, target, staticValue, staticValueArraySize, dynamicFlagsToSet] : locations) { + if (!expression || expressionIsStatic) + continue; - _NODISCARD newsTickerDef_s* ConvertNewsTickerFeatures(itemDef_s* item, CommonItemFeaturesNewsTicker* commonNewsTicker, const CommonMenuDef& parentMenu, const CommonItemDef& commonItem) const - { - if (commonNewsTicker == nullptr) - return nullptr; + assert(floatExpressionIndex < floatExpressionCount && floatExpressionIndex >= 0); + floatExpressions[floatExpressionIndex].target = target; + floatExpressions[floatExpressionIndex].expression = ConvertExpression(expression, parentMenu, commonItem); + item->window.dynamicFlags[0] |= dynamicFlagsToSet; + floatExpressionIndex++; + } - auto* newsTicker = static_cast(m_memory->Alloc(sizeof(newsTickerDef_s))); - memset(newsTicker, 0, sizeof(newsTickerDef_s)); + return floatExpressions; + } - newsTicker->spacing = commonNewsTicker->m_spacing; - newsTicker->speed = commonNewsTicker->m_speed; - newsTicker->feedId = commonNewsTicker->m_news_feed_id; + _NODISCARD const char *CreateEnableDvarString(const std::vector &stringElements) const { + std::ostringstream ss; - return newsTicker; - } - - _NODISCARD itemDef_s* ConvertItem(const CommonMenuDef& parentMenu, const CommonItemDef& commonItem) const - { - auto* item = m_memory->Create(); - memset(item, 0, sizeof(itemDef_s)); - - item->window.name = ConvertString(commonItem.m_name); - item->text = ConvertString(commonItem.m_text); - ApplyFlag(item->itemFlags, commonItem.m_text_save_game, ITEM_FLAG_SAVE_GAME_INFO); - ApplyFlag(item->itemFlags, commonItem.m_text_cinematic_subtitle, ITEM_FLAG_CINEMATIC_SUBTITLE); - item->window.group = ConvertString(commonItem.m_group); - item->window.rectClient = ConvertRectDef(commonItem.m_rect); - item->window.rect = ConvertRectDefRelativeTo(commonItem.m_rect, parentMenu.m_rect); - item->window.style = commonItem.m_style; - ApplyFlag(item->window.staticFlags, commonItem.m_decoration, WINDOW_FLAG_DECORATION); - ApplyFlag(item->window.staticFlags, commonItem.m_auto_wrapped, WINDOW_FLAG_AUTO_WRAPPED); - ApplyFlag(item->window.staticFlags, commonItem.m_horizontal_scroll, WINDOW_FLAG_HORIZONTAL_SCROLL); - item->type = ConvertItemType(commonItem.m_type); - item->dataType = item->type; - item->window.border = commonItem.m_border; - item->window.borderSize = static_cast(commonItem.m_border_size); - item->visibleExp = ConvertVisibleExpression(&item->window, commonItem.m_visible_expression.get(), &parentMenu, &commonItem); - item->disabledExp = ConvertExpression(commonItem.m_disabled_expression.get(), &parentMenu, &commonItem); - item->window.ownerDraw = commonItem.m_owner_draw; - item->window.ownerDrawFlags = commonItem.m_owner_draw_flags; - item->alignment = commonItem.m_align; - item->textAlignMode = commonItem.m_text_align; - item->textalignx = static_cast(commonItem.m_text_align_x); - item->textaligny = static_cast(commonItem.m_text_align_y); - item->textscale = static_cast(commonItem.m_text_scale); - item->textStyle = commonItem.m_text_style; - item->fontEnum = ConvertTextFont(commonItem.m_text_font); - ConvertColor(item->window.backColor, commonItem.m_back_color); - - ConvertColor(item->window.foreColor, commonItem.m_fore_color); - if (!commonItem.m_fore_color.Equals(CommonColor(1.0, 1.0, 1.0, 1.0))) - item->window.dynamicFlags[0] |= WINDOW_FLAG_NON_DEFAULT_FORECOLOR; - - ConvertColor(item->window.borderColor, commonItem.m_border_color); - ConvertColor(item->window.outlineColor, commonItem.m_outline_color); - ConvertColor(item->window.disableColor, commonItem.m_disable_color); - ConvertColor(item->glowColor, commonItem.m_glow_color); - item->window.background = ConvertMaterial(commonItem.m_background, &parentMenu, &commonItem); - item->onFocus = ConvertEventHandlerSet(commonItem.m_on_focus.get(), &parentMenu, &commonItem); - item->hasFocus = ConvertEventHandlerSet(commonItem.m_has_focus.get(), &parentMenu, &commonItem); - item->leaveFocus = ConvertEventHandlerSet(commonItem.m_on_leave_focus.get(), &parentMenu, &commonItem); - item->mouseEnter = ConvertEventHandlerSet(commonItem.m_on_mouse_enter.get(), &parentMenu, &commonItem); - item->mouseExit = ConvertEventHandlerSet(commonItem.m_on_mouse_exit.get(), &parentMenu, &commonItem); - item->mouseEnterText = ConvertEventHandlerSet(commonItem.m_on_mouse_enter_text.get(), &parentMenu, &commonItem); - item->mouseExitText = ConvertEventHandlerSet(commonItem.m_on_mouse_exit_text.get(), &parentMenu, &commonItem); - item->action = ConvertEventHandlerSet(commonItem.m_on_action.get(), &parentMenu, &commonItem); - item->accept = ConvertEventHandlerSet(commonItem.m_on_accept.get(), &parentMenu, &commonItem); - item->focusSound = ConvertSound(commonItem.m_focus_sound, &parentMenu, &commonItem); - item->dvarTest = ConvertString(commonItem.m_dvar_test); - item->enableDvar = ConvertEnableDvar(commonItem, item->dvarFlags); - item->onKey = ConvertKeyHandler(commonItem.m_key_handlers, &parentMenu, &commonItem); - item->textExp = ConvertOrApplyStatement(item->text, commonItem.m_text_expression.get(), &parentMenu, &commonItem); - item->textAlignYExp = ConvertOrApplyStatement(item->textaligny, commonItem.m_text_align_y_expression.get(), &parentMenu, &commonItem); - item->materialExp = ConvertOrApplyStatement(item->window.background, commonItem.m_material_expression.get(), &parentMenu, &commonItem); - item->disabledExp = ConvertExpression(commonItem.m_disabled_expression.get(), &parentMenu, &commonItem); - item->floatExpressions = ConvertFloatExpressions(&commonItem, item, &parentMenu, item->floatExpressionCount); - item->gameMsgWindowIndex = commonItem.m_game_message_window_index; - item->gameMsgWindowMode = commonItem.m_game_message_window_mode; - item->fxLetterTime = commonItem.m_fx_letter_time; - item->fxDecayStartTime = commonItem.m_fx_decay_start_time; - item->fxDecayDuration = commonItem.m_fx_decay_duration; - item->dvar = ConvertString(commonItem.m_dvar); - - switch (commonItem.m_feature_type) - { - case CommonItemFeatureType::LISTBOX: - item->typeData.listBox = ConvertListBoxFeatures(item, commonItem.m_list_box_features.get(), parentMenu, commonItem); - break; - - case CommonItemFeatureType::EDIT_FIELD: - item->typeData.editField = ConvertEditFieldFeatures(item, commonItem.m_edit_field_features.get(), parentMenu, commonItem); - break; - - case CommonItemFeatureType::MULTI_VALUE: - item->typeData.multi = ConvertMultiValueFeatures(item, commonItem.m_multi_value_features.get(), parentMenu, commonItem); - break; - - case CommonItemFeatureType::ENUM_DVAR: - item->typeData.enumDvarName = ConvertString(commonItem.m_enum_dvar_name); - break; - - case CommonItemFeatureType::NEWS_TICKER: - item->typeData.ticker = ConvertNewsTickerFeatures(item, commonItem.m_news_ticker_features.get(), parentMenu, commonItem); - break; - - case CommonItemFeatureType::NONE: - default: - if (item->type == ITEM_TYPE_TEXT_SCROLL) - { - item->typeData.scroll = static_cast(m_memory->Alloc(sizeof(textScrollDef_s))); - memset(item->typeData.scroll, 0, sizeof(textScrollDef_s)); - } - break; - } - - return item; - } + for (const auto &element : stringElements) { + ss << "\"" << element << "\" "; + } - itemDef_s** ConvertMenuItems(const CommonMenuDef& commonMenu, int& itemCount) const - { - if (commonMenu.m_items.empty()) - { - itemCount = 0; - return nullptr; - } + return m_memory->Dup(ss.str().c_str()); + } - auto* items = static_cast(m_memory->Alloc(sizeof(void*) * commonMenu.m_items.size())); - memset(items, 0, sizeof(void*) * commonMenu.m_items.size()); + _NODISCARD const char *ConvertEnableDvar(const CommonItemDef &commonItem, int &dvarFlags) const { + dvarFlags = 0; - for (auto i = 0u; i < commonMenu.m_items.size(); i++) - items[i] = ConvertItem(commonMenu, *commonMenu.m_items[i]); + if (!commonItem.m_enable_dvar.empty()) { + dvarFlags |= ITEM_DVAR_FLAG_ENABLE; + return CreateEnableDvarString(commonItem.m_enable_dvar); + } - itemCount = static_cast(commonMenu.m_items.size()); + if (!commonItem.m_disable_dvar.empty()) { + dvarFlags |= ITEM_DVAR_FLAG_DISABLE; + return CreateEnableDvarString(commonItem.m_disable_dvar); + } - return items; - } + if (!commonItem.m_show_dvar.empty()) { + dvarFlags |= ITEM_DVAR_FLAG_SHOW; + return CreateEnableDvarString(commonItem.m_show_dvar); + } - public: - MenuConverterImpl(const bool disableOptimizations, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager) - : AbstractMenuConverter(disableOptimizations, searchPath, memory, manager), - m_conversion_zone_state(manager->GetAssetLoadingContext()->GetZoneAssetLoaderState()), - m_parsing_zone_state(manager->GetAssetLoadingContext()->GetZoneAssetLoaderState()) - { - assert(m_conversion_zone_state); - assert(m_parsing_zone_state); - } + if (!commonItem.m_hide_dvar.empty()) { + dvarFlags |= ITEM_DVAR_FLAG_HIDE; + return CreateEnableDvarString(commonItem.m_hide_dvar); + } - _NODISCARD menuDef_t* ConvertMenu(const CommonMenuDef& commonMenu) const - { - auto* menu = m_memory->Create(); - auto* menuData = m_memory->Create(); - memset(menu, 0, sizeof(menuDef_t)); - - menu->data = menuData; - menu->window.name = m_memory->Dup(commonMenu.m_name.c_str()); - menuData->fullScreen = commonMenu.m_full_screen; - ApplyFlag(menu->window.staticFlags, commonMenu.m_screen_space, WINDOW_FLAG_SCREEN_SPACE); - ApplyFlag(menu->window.staticFlags, commonMenu.m_decoration, WINDOW_FLAG_DECORATION); - menu->window.rect = ConvertRectDef(commonMenu.m_rect); - menu->window.style = commonMenu.m_style; - menu->window.border = commonMenu.m_border; - menu->window.borderSize = static_cast(commonMenu.m_border_size); - ConvertColor(menu->window.backColor, commonMenu.m_back_color); - ConvertColor(menu->window.foreColor, commonMenu.m_fore_color); - ConvertColor(menu->window.borderColor, commonMenu.m_border_color); - ConvertColor(menuData->focusColor, commonMenu.m_focus_color); - menu->window.background = ConvertMaterial(commonMenu.m_background, &commonMenu); - menu->window.ownerDraw = commonMenu.m_owner_draw; - menu->window.ownerDrawFlags = commonMenu.m_owner_draw_flags; - ApplyFlag(menu->window.staticFlags, commonMenu.m_out_of_bounds_click, WINDOW_FLAG_OUT_OF_BOUNDS_CLICK); - menuData->soundName = ConvertString(commonMenu.m_sound_loop); - ApplyFlag(menu->window.staticFlags, commonMenu.m_popup, WINDOW_FLAG_POPUP); - menuData->fadeClamp = static_cast(commonMenu.m_fade_clamp); - menuData->fadeCycle = commonMenu.m_fade_cycle; - menuData->fadeAmount = static_cast(commonMenu.m_fade_amount); - menuData->fadeInAmount = static_cast(commonMenu.m_fade_in_amount); - menuData->blurRadius = static_cast(commonMenu.m_blur_radius); - ApplyFlag(menu->window.staticFlags, commonMenu.m_legacy_split_screen_scale, WINDOW_FLAG_LEGACY_SPLIT_SCREEN_SCALE); - ApplyFlag(menu->window.staticFlags, commonMenu.m_hidden_during_scope, WINDOW_FLAG_HIDDEN_DURING_SCOPE); - ApplyFlag(menu->window.staticFlags, commonMenu.m_hidden_during_flashbang, WINDOW_FLAG_HIDDEN_DURING_FLASH_BANG); - ApplyFlag(menu->window.staticFlags, commonMenu.m_hidden_during_ui, WINDOW_FLAG_HIDDEN_DURING_UI); - menuData->allowedBinding = ConvertString(commonMenu.m_allowed_binding); - ApplyFlag(menu->window.staticFlags, commonMenu.m_text_only_focus, WINDOW_FLAG_TEXT_ONLY_FOCUS); - menuData->visibleExp = ConvertVisibleExpression(&menu->window, commonMenu.m_visible_expression.get(), &commonMenu); - menuData->rectXExp = ConvertOrApplyStatement(menu->window.rect.x, commonMenu.m_rect_x_exp.get(), &commonMenu); - menuData->rectYExp = ConvertOrApplyStatement(menu->window.rect.y, commonMenu.m_rect_y_exp.get(), &commonMenu); - menuData->rectWExp = ConvertOrApplyStatement(menu->window.rect.w, commonMenu.m_rect_w_exp.get(), &commonMenu); - menuData->rectHExp = ConvertOrApplyStatement(menu->window.rect.h, commonMenu.m_rect_h_exp.get(), &commonMenu); - menuData->openSoundExp = ConvertExpression(commonMenu.m_open_sound_exp.get(), &commonMenu); - menuData->closeSoundExp = ConvertExpression(commonMenu.m_close_sound_exp.get(), &commonMenu); - menuData->onOpen = ConvertEventHandlerSet(commonMenu.m_on_open.get(), &commonMenu); - menuData->onClose = ConvertEventHandlerSet(commonMenu.m_on_close.get(), &commonMenu); - menuData->onCloseRequest = ConvertEventHandlerSet(commonMenu.m_on_request_close.get(), &commonMenu); - menuData->onESC = ConvertEventHandlerSet(commonMenu.m_on_esc.get(), &commonMenu); - menuData->onFocusDueToClose = ConvertEventHandlerSet(commonMenu.m_on_focus_due_to_close.get(), &commonMenu); - menuData->onKey = ConvertKeyHandler(commonMenu.m_key_handlers, &commonMenu); - menu->items = ConvertMenuItems(commonMenu, menu->itemCount); - menuData->expressionData = m_conversion_zone_state->m_supporting_data; - - return menu; - } + if (!commonItem.m_focus_dvar.empty()) { + dvarFlags |= ITEM_DVAR_FLAG_FOCUS; + return CreateEnableDvarString(commonItem.m_focus_dvar); + } - std::vector m_dependencies; - }; -} + return nullptr; + } + + _NODISCARD listBoxDef_s *ConvertListBoxFeatures(itemDef_s *item, CommonItemFeaturesListBox *commonListBox, const CommonMenuDef &parentMenu, + const CommonItemDef &commonItem) const { + if (commonListBox == nullptr) + return nullptr; + + auto *listBox = static_cast(m_memory->Alloc(sizeof(listBoxDef_s))); + memset(listBox, 0, sizeof(listBoxDef_s)); + + listBox->notselectable = commonListBox->m_not_selectable ? 1 : 0; + listBox->noScrollBars = commonListBox->m_no_scrollbars ? 1 : 0; + listBox->usePaging = commonListBox->m_use_paging ? 1 : 0; + listBox->elementWidth = static_cast(commonListBox->m_element_width); + listBox->elementHeight = static_cast(commonListBox->m_element_height); + item->special = static_cast(commonListBox->m_feeder); + listBox->elementStyle = commonListBox->m_element_style; + listBox->onDoubleClick = ConvertEventHandlerSet(commonListBox->m_on_double_click.get(), &parentMenu, &commonItem); + ConvertColor(listBox->selectBorder, commonListBox->m_select_border); + listBox->selectIcon = ConvertMaterial(commonListBox->m_select_icon, &parentMenu, &commonItem); + listBox->elementHeightExp = ConvertOrApplyStatement(listBox->elementHeight, commonListBox->m_element_height_expression.get(), &parentMenu, &commonItem); + + listBox->numColumns = static_cast(std::min(std::extent_v, commonListBox->m_columns.size())); + for (auto i = 0; i < listBox->numColumns; i++) { + auto &col = listBox->columnInfo[i]; + const auto &commonCol = commonListBox->m_columns[i]; + + col.xpos = commonCol.m_x_pos; + col.ypos = commonCol.m_y_pos; + col.width = commonCol.m_width; + col.maxChars = commonCol.m_max_chars; + col.alignment = commonCol.m_alignment; + } -MenuConverter::MenuConverter(const bool disableOptimizations, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager) - : m_disable_optimizations(disableOptimizations), - m_search_path(searchPath), - m_memory(memory), - m_manager(manager) -{ -} + return listBox; + } + + _NODISCARD editFieldDef_s *ConvertEditFieldFeatures(itemDef_s *item, CommonItemFeaturesEditField *commonEditField, const CommonMenuDef &parentMenu, + const CommonItemDef &commonItem) const { + if (commonEditField == nullptr) + return nullptr; + + auto *editField = static_cast(m_memory->Alloc(sizeof(editFieldDef_s))); + memset(editField, 0, sizeof(editFieldDef_s)); + + editField->stepVal = static_cast(commonEditField->m_def_val); + editField->minVal = static_cast(commonEditField->m_min_val); + editField->maxVal = static_cast(commonEditField->m_max_val); + item->localVar = ConvertString(commonEditField->m_local_var); + editField->maxChars = commonEditField->m_max_chars; + editField->maxCharsGotoNext = commonEditField->m_max_chars_goto_next ? 1 : 0; + editField->maxPaintChars = commonEditField->m_max_paint_chars; + + return editField; + } + + _NODISCARD multiDef_s *ConvertMultiValueFeatures(itemDef_s *item, CommonItemFeaturesMultiValue *commonMultiValue, const CommonMenuDef &parentMenu, + const CommonItemDef &commonItem) const { + if (commonMultiValue == nullptr) + return nullptr; + + auto *multiValue = static_cast(m_memory->Alloc(sizeof(multiDef_s))); + memset(multiValue, 0, sizeof(multiDef_s)); + + multiValue->count = static_cast(std::min(std::extent_v, commonMultiValue->m_step_names.size())); + multiValue->strDef = !commonMultiValue->m_string_values.empty() ? 1 : 0; + + for (auto i = 0; i < multiValue->count; i++) { + multiValue->dvarList[i] = ConvertString(commonMultiValue->m_step_names[i]); + + if (multiValue->strDef) { + if (commonMultiValue->m_string_values.size() > static_cast(i)) + multiValue->dvarStr[i] = ConvertString(commonMultiValue->m_string_values[i]); + } else { + if (commonMultiValue->m_double_values.size() > static_cast(i)) + multiValue->dvarValue[i] = static_cast(commonMultiValue->m_double_values[i]); + } + } -std::vector& MenuConverter::GetDependencies() -{ - return m_dependencies; -} + return multiValue; + } + + _NODISCARD newsTickerDef_s *ConvertNewsTickerFeatures(itemDef_s *item, CommonItemFeaturesNewsTicker *commonNewsTicker, const CommonMenuDef &parentMenu, + const CommonItemDef &commonItem) const { + if (commonNewsTicker == nullptr) + return nullptr; + + auto *newsTicker = static_cast(m_memory->Alloc(sizeof(newsTickerDef_s))); + memset(newsTicker, 0, sizeof(newsTickerDef_s)); + + newsTicker->spacing = commonNewsTicker->m_spacing; + newsTicker->speed = commonNewsTicker->m_speed; + newsTicker->feedId = commonNewsTicker->m_news_feed_id; + + return newsTicker; + } + + _NODISCARD itemDef_s *ConvertItem(const CommonMenuDef &parentMenu, const CommonItemDef &commonItem) const { + auto *item = m_memory->Create(); + memset(item, 0, sizeof(itemDef_s)); + + item->window.name = ConvertString(commonItem.m_name); + item->text = ConvertString(commonItem.m_text); + ApplyFlag(item->itemFlags, commonItem.m_text_save_game, ITEM_FLAG_SAVE_GAME_INFO); + ApplyFlag(item->itemFlags, commonItem.m_text_cinematic_subtitle, ITEM_FLAG_CINEMATIC_SUBTITLE); + item->window.group = ConvertString(commonItem.m_group); + item->window.rectClient = ConvertRectDef(commonItem.m_rect); + item->window.rect = ConvertRectDefRelativeTo(commonItem.m_rect, parentMenu.m_rect); + item->window.style = commonItem.m_style; + ApplyFlag(item->window.staticFlags, commonItem.m_decoration, WINDOW_FLAG_DECORATION); + ApplyFlag(item->window.staticFlags, commonItem.m_auto_wrapped, WINDOW_FLAG_AUTO_WRAPPED); + ApplyFlag(item->window.staticFlags, commonItem.m_horizontal_scroll, WINDOW_FLAG_HORIZONTAL_SCROLL); + item->type = ConvertItemType(commonItem.m_type); + item->dataType = item->type; + item->window.border = commonItem.m_border; + item->window.borderSize = static_cast(commonItem.m_border_size); + item->visibleExp = ConvertVisibleExpression(&item->window, commonItem.m_visible_expression.get(), &parentMenu, &commonItem); + item->disabledExp = ConvertExpression(commonItem.m_disabled_expression.get(), &parentMenu, &commonItem); + item->window.ownerDraw = commonItem.m_owner_draw; + item->window.ownerDrawFlags = commonItem.m_owner_draw_flags; + item->alignment = commonItem.m_align; + item->textAlignMode = commonItem.m_text_align; + item->textalignx = static_cast(commonItem.m_text_align_x); + item->textaligny = static_cast(commonItem.m_text_align_y); + item->textscale = static_cast(commonItem.m_text_scale); + item->textStyle = commonItem.m_text_style; + item->fontEnum = ConvertTextFont(commonItem.m_text_font); + ConvertColor(item->window.backColor, commonItem.m_back_color); + + ConvertColor(item->window.foreColor, commonItem.m_fore_color); + if (!commonItem.m_fore_color.Equals(CommonColor(1.0, 1.0, 1.0, 1.0))) + item->window.dynamicFlags[0] |= WINDOW_FLAG_NON_DEFAULT_FORECOLOR; + + ConvertColor(item->window.borderColor, commonItem.m_border_color); + ConvertColor(item->window.outlineColor, commonItem.m_outline_color); + ConvertColor(item->window.disableColor, commonItem.m_disable_color); + ConvertColor(item->glowColor, commonItem.m_glow_color); + item->window.background = ConvertMaterial(commonItem.m_background, &parentMenu, &commonItem); + item->onFocus = ConvertEventHandlerSet(commonItem.m_on_focus.get(), &parentMenu, &commonItem); + item->hasFocus = ConvertEventHandlerSet(commonItem.m_has_focus.get(), &parentMenu, &commonItem); + item->leaveFocus = ConvertEventHandlerSet(commonItem.m_on_leave_focus.get(), &parentMenu, &commonItem); + item->mouseEnter = ConvertEventHandlerSet(commonItem.m_on_mouse_enter.get(), &parentMenu, &commonItem); + item->mouseExit = ConvertEventHandlerSet(commonItem.m_on_mouse_exit.get(), &parentMenu, &commonItem); + item->mouseEnterText = ConvertEventHandlerSet(commonItem.m_on_mouse_enter_text.get(), &parentMenu, &commonItem); + item->mouseExitText = ConvertEventHandlerSet(commonItem.m_on_mouse_exit_text.get(), &parentMenu, &commonItem); + item->action = ConvertEventHandlerSet(commonItem.m_on_action.get(), &parentMenu, &commonItem); + item->accept = ConvertEventHandlerSet(commonItem.m_on_accept.get(), &parentMenu, &commonItem); + item->focusSound = ConvertSound(commonItem.m_focus_sound, &parentMenu, &commonItem); + item->dvarTest = ConvertString(commonItem.m_dvar_test); + item->enableDvar = ConvertEnableDvar(commonItem, item->dvarFlags); + item->onKey = ConvertKeyHandler(commonItem.m_key_handlers, &parentMenu, &commonItem); + item->textExp = ConvertOrApplyStatement(item->text, commonItem.m_text_expression.get(), &parentMenu, &commonItem); + item->textAlignYExp = ConvertOrApplyStatement(item->textaligny, commonItem.m_text_align_y_expression.get(), &parentMenu, &commonItem); + item->materialExp = ConvertOrApplyStatement(item->window.background, commonItem.m_material_expression.get(), &parentMenu, &commonItem); + item->disabledExp = ConvertExpression(commonItem.m_disabled_expression.get(), &parentMenu, &commonItem); + item->floatExpressions = ConvertFloatExpressions(&commonItem, item, &parentMenu, item->floatExpressionCount); + item->gameMsgWindowIndex = commonItem.m_game_message_window_index; + item->gameMsgWindowMode = commonItem.m_game_message_window_mode; + item->fxLetterTime = commonItem.m_fx_letter_time; + item->fxDecayStartTime = commonItem.m_fx_decay_start_time; + item->fxDecayDuration = commonItem.m_fx_decay_duration; + item->dvar = ConvertString(commonItem.m_dvar); + + switch (commonItem.m_feature_type) { + case CommonItemFeatureType::LISTBOX: + item->typeData.listBox = ConvertListBoxFeatures(item, commonItem.m_list_box_features.get(), parentMenu, commonItem); + break; + + case CommonItemFeatureType::EDIT_FIELD: + item->typeData.editField = ConvertEditFieldFeatures(item, commonItem.m_edit_field_features.get(), parentMenu, commonItem); + break; + + case CommonItemFeatureType::MULTI_VALUE: + item->typeData.multi = ConvertMultiValueFeatures(item, commonItem.m_multi_value_features.get(), parentMenu, commonItem); + break; + + case CommonItemFeatureType::ENUM_DVAR: + item->typeData.enumDvarName = ConvertString(commonItem.m_enum_dvar_name); + break; + + case CommonItemFeatureType::NEWS_TICKER: + item->typeData.ticker = ConvertNewsTickerFeatures(item, commonItem.m_news_ticker_features.get(), parentMenu, commonItem); + break; + + case CommonItemFeatureType::NONE: + default: + if (item->type == ITEM_TYPE_TEXT_SCROLL) { + item->typeData.scroll = static_cast(m_memory->Alloc(sizeof(textScrollDef_s))); + memset(item->typeData.scroll, 0, sizeof(textScrollDef_s)); + } + break; + } -menuDef_t* MenuConverter::ConvertMenu(const CommonMenuDef& commonMenu) -{ - MenuConverterImpl impl(m_disable_optimizations, m_search_path, m_memory, m_manager); + return item; + } - try - { - auto* result = impl.ConvertMenu(commonMenu); - m_dependencies = std::move(impl.m_dependencies); - return result; - } - catch (const MenuConversionException& e) - { - MenuConverterImpl::PrintConversionExceptionDetails(e); + itemDef_s **ConvertMenuItems(const CommonMenuDef &commonMenu, int &itemCount) const { + if (commonMenu.m_items.empty()) { + itemCount = 0; + return nullptr; } - return nullptr; + auto *items = static_cast(m_memory->Alloc(sizeof(void *) * commonMenu.m_items.size())); + memset(items, 0, sizeof(void *) * commonMenu.m_items.size()); + + for (auto i = 0u; i < commonMenu.m_items.size(); i++) + items[i] = ConvertItem(commonMenu, *commonMenu.m_items[i]); + + itemCount = static_cast(commonMenu.m_items.size()); + + return items; + } + +public: + MenuConverterImpl(const bool disableOptimizations, ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager) + : AbstractMenuConverter(disableOptimizations, searchPath, memory, manager), + m_conversion_zone_state(manager->GetAssetLoadingContext()->GetZoneAssetLoaderState()), + m_parsing_zone_state(manager->GetAssetLoadingContext()->GetZoneAssetLoaderState()) { + assert(m_conversion_zone_state); + assert(m_parsing_zone_state); + } + + _NODISCARD menuDef_t *ConvertMenu(const CommonMenuDef &commonMenu) const { + auto *menu = m_memory->Create(); + auto *menuData = m_memory->Create(); + memset(menu, 0, sizeof(menuDef_t)); + + menu->data = menuData; + menu->window.name = m_memory->Dup(commonMenu.m_name.c_str()); + menuData->fullScreen = commonMenu.m_full_screen; + ApplyFlag(menu->window.staticFlags, commonMenu.m_screen_space, WINDOW_FLAG_SCREEN_SPACE); + ApplyFlag(menu->window.staticFlags, commonMenu.m_decoration, WINDOW_FLAG_DECORATION); + menu->window.rect = ConvertRectDef(commonMenu.m_rect); + menu->window.style = commonMenu.m_style; + menu->window.border = commonMenu.m_border; + menu->window.borderSize = static_cast(commonMenu.m_border_size); + ConvertColor(menu->window.backColor, commonMenu.m_back_color); + ConvertColor(menu->window.foreColor, commonMenu.m_fore_color); + ConvertColor(menu->window.borderColor, commonMenu.m_border_color); + ConvertColor(menuData->focusColor, commonMenu.m_focus_color); + menu->window.background = ConvertMaterial(commonMenu.m_background, &commonMenu); + menu->window.ownerDraw = commonMenu.m_owner_draw; + menu->window.ownerDrawFlags = commonMenu.m_owner_draw_flags; + ApplyFlag(menu->window.staticFlags, commonMenu.m_out_of_bounds_click, WINDOW_FLAG_OUT_OF_BOUNDS_CLICK); + menuData->soundName = ConvertString(commonMenu.m_sound_loop); + ApplyFlag(menu->window.staticFlags, commonMenu.m_popup, WINDOW_FLAG_POPUP); + menuData->fadeClamp = static_cast(commonMenu.m_fade_clamp); + menuData->fadeCycle = commonMenu.m_fade_cycle; + menuData->fadeAmount = static_cast(commonMenu.m_fade_amount); + menuData->fadeInAmount = static_cast(commonMenu.m_fade_in_amount); + menuData->blurRadius = static_cast(commonMenu.m_blur_radius); + ApplyFlag(menu->window.staticFlags, commonMenu.m_legacy_split_screen_scale, WINDOW_FLAG_LEGACY_SPLIT_SCREEN_SCALE); + ApplyFlag(menu->window.staticFlags, commonMenu.m_hidden_during_scope, WINDOW_FLAG_HIDDEN_DURING_SCOPE); + ApplyFlag(menu->window.staticFlags, commonMenu.m_hidden_during_flashbang, WINDOW_FLAG_HIDDEN_DURING_FLASH_BANG); + ApplyFlag(menu->window.staticFlags, commonMenu.m_hidden_during_ui, WINDOW_FLAG_HIDDEN_DURING_UI); + menuData->allowedBinding = ConvertString(commonMenu.m_allowed_binding); + ApplyFlag(menu->window.staticFlags, commonMenu.m_text_only_focus, WINDOW_FLAG_TEXT_ONLY_FOCUS); + menuData->visibleExp = ConvertVisibleExpression(&menu->window, commonMenu.m_visible_expression.get(), &commonMenu); + menuData->rectXExp = ConvertOrApplyStatement(menu->window.rect.x, commonMenu.m_rect_x_exp.get(), &commonMenu); + menuData->rectYExp = ConvertOrApplyStatement(menu->window.rect.y, commonMenu.m_rect_y_exp.get(), &commonMenu); + menuData->rectWExp = ConvertOrApplyStatement(menu->window.rect.w, commonMenu.m_rect_w_exp.get(), &commonMenu); + menuData->rectHExp = ConvertOrApplyStatement(menu->window.rect.h, commonMenu.m_rect_h_exp.get(), &commonMenu); + menuData->openSoundExp = ConvertExpression(commonMenu.m_open_sound_exp.get(), &commonMenu); + menuData->closeSoundExp = ConvertExpression(commonMenu.m_close_sound_exp.get(), &commonMenu); + menuData->onOpen = ConvertEventHandlerSet(commonMenu.m_on_open.get(), &commonMenu); + menuData->onClose = ConvertEventHandlerSet(commonMenu.m_on_close.get(), &commonMenu); + menuData->onCloseRequest = ConvertEventHandlerSet(commonMenu.m_on_request_close.get(), &commonMenu); + menuData->onESC = ConvertEventHandlerSet(commonMenu.m_on_esc.get(), &commonMenu); + menuData->onFocusDueToClose = ConvertEventHandlerSet(commonMenu.m_on_focus_due_to_close.get(), &commonMenu); + menuData->onKey = ConvertKeyHandler(commonMenu.m_key_handlers, &commonMenu); + menu->items = ConvertMenuItems(commonMenu, menu->itemCount); + menuData->expressionData = m_conversion_zone_state->m_supporting_data; + + return menu; + } + + std::vector m_dependencies; +}; +} // namespace IW5 + +MenuConverter::MenuConverter(const bool disableOptimizations, ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager) + : m_disable_optimizations(disableOptimizations), m_search_path(searchPath), m_memory(memory), m_manager(manager) {} + +std::vector &MenuConverter::GetDependencies() { return m_dependencies; } + +menuDef_t *MenuConverter::ConvertMenu(const CommonMenuDef &commonMenu) { + MenuConverterImpl impl(m_disable_optimizations, m_search_path, m_memory, m_manager); + + try { + auto *result = impl.ConvertMenu(commonMenu); + m_dependencies = std::move(impl.m_dependencies); + return result; + } catch (const MenuConversionException &e) { + MenuConverterImpl::PrintConversionExceptionDetails(e); + } + + return nullptr; } diff --git a/src/ObjLoading/Game/IW5/Menu/MenuConverterIW5.h b/src/ObjLoading/Game/IW5/Menu/MenuConverterIW5.h index 3570ba790..fdf53cda4 100644 --- a/src/ObjLoading/Game/IW5/Menu/MenuConverterIW5.h +++ b/src/ObjLoading/Game/IW5/Menu/MenuConverterIW5.h @@ -1,26 +1,24 @@ #pragma once -#include "Utils/ClassUtils.h" #include "AssetLoading/IAssetLoadingManager.h" #include "Game/IW5/IW5.h" #include "Parsing/Menu/Domain/CommonMenuDef.h" -#include "Utils/MemoryManager.h" #include "SearchPath/ISearchPath.h" +#include "Utils/ClassUtils.h" +#include "Utils/MemoryManager.h" -namespace IW5 -{ - class MenuConverter - { - bool m_disable_optimizations; - ISearchPath* m_search_path; - MemoryManager* m_memory; - IAssetLoadingManager* m_manager; - std::vector m_dependencies; +namespace IW5 { +class MenuConverter { + bool m_disable_optimizations; + ISearchPath *m_search_path; + MemoryManager *m_memory; + IAssetLoadingManager *m_manager; + std::vector m_dependencies; - public: - MenuConverter(bool disableOptimizations, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager); +public: + MenuConverter(bool disableOptimizations, ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager); - std::vector& GetDependencies(); - _NODISCARD menuDef_t* ConvertMenu(const menu::CommonMenuDef& commonMenu); - }; -} + std::vector &GetDependencies(); + _NODISCARD menuDef_t *ConvertMenu(const menu::CommonMenuDef &commonMenu); +}; +} // namespace IW5 diff --git a/src/ObjLoading/Game/IW5/ObjLoaderIW5.cpp b/src/ObjLoading/Game/IW5/ObjLoaderIW5.cpp index 9766e9845..403c3f8b5 100644 --- a/src/ObjLoading/Game/IW5/ObjLoaderIW5.cpp +++ b/src/ObjLoading/Game/IW5/ObjLoaderIW5.cpp @@ -1,9 +1,5 @@ #include "ObjLoaderIW5.h" -#include "Game/IW5/GameIW5.h" -#include "Game/IW5/GameAssetPoolIW5.h" -#include "ObjContainer/IPak/IPak.h" -#include "ObjLoading.h" #include "AssetLoaders/AssetLoaderLocalizeEntry.h" #include "AssetLoaders/AssetLoaderMaterial.h" #include "AssetLoaders/AssetLoaderMenuDef.h" @@ -11,193 +7,165 @@ #include "AssetLoaders/AssetLoaderRawFile.h" #include "AssetLoaders/AssetLoaderStringTable.h" #include "AssetLoading/AssetLoadingManager.h" +#include "Game/IW5/GameAssetPoolIW5.h" +#include "Game/IW5/GameIW5.h" #include "Image/Dx9TextureLoader.h" -#include "Image/Texture.h" #include "Image/IwiLoader.h" #include "Image/IwiTypes.h" +#include "Image/Texture.h" +#include "ObjContainer/IPak/IPak.h" +#include "ObjLoading.h" using namespace IW5; -ObjLoader::ObjLoader() -{ -#define REGISTER_ASSET_LOADER(t) {auto l = std::make_unique(); m_asset_loaders_by_type[l->GetHandlingAssetType()] = std::move(l);} +ObjLoader::ObjLoader() { +#define REGISTER_ASSET_LOADER(t) \ + { \ + auto l = std::make_unique(); \ + m_asset_loaders_by_type[l->GetHandlingAssetType()] = std::move(l); \ + } #define BASIC_LOADER(assetType, assetClass) BasicAssetLoader - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_PHYSPRESET, PhysPreset)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_PHYSCOLLMAP, PhysCollmap)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_XANIMPARTS, XAnimParts)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_XMODEL_SURFS, XModelSurfs)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_XMODEL, XModel)) - REGISTER_ASSET_LOADER(AssetLoaderMaterial) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_PIXELSHADER, MaterialPixelShader)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_VERTEXSHADER, MaterialVertexShader)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_VERTEXDECL, MaterialVertexDeclaration)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_TECHNIQUE_SET, MaterialTechniqueSet)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_IMAGE, GfxImage)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_SOUND, snd_alias_list_t)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_SOUND_CURVE, SndCurve)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_LOADED_SOUND, LoadedSound)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_CLIPMAP, clipMap_t)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_COMWORLD, ComWorld)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_GLASSWORLD, GlassWorld)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_PATHDATA, PathData)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_VEHICLE_TRACK, VehicleTrack)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_MAP_ENTS, MapEnts)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_FXWORLD, FxWorld)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_GFXWORLD, GfxWorld)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_LIGHT_DEF, GfxLightDef)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_FONT, Font_s)) - REGISTER_ASSET_LOADER(AssetLoaderMenuList) - REGISTER_ASSET_LOADER(AssetLoaderMenuDef) - REGISTER_ASSET_LOADER(AssetLoaderLocalizeEntry) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_ATTACHMENT, WeaponAttachment)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_WEAPON, WeaponCompleteDef)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_FX, FxEffectDef)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_IMPACT_FX, FxImpactTable)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_SURFACE_FX, SurfaceFxTable)) - REGISTER_ASSET_LOADER(AssetLoaderRawFile) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_SCRIPTFILE, ScriptFile)) - REGISTER_ASSET_LOADER(AssetLoaderStringTable) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_LEADERBOARD, LeaderboardDef)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_STRUCTURED_DATA_DEF, StructuredDataDefSet)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_TRACER, TracerDef)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_VEHICLE, VehicleDef)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_ADDON_MAP_ENTS, AddonMapEnts)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_PHYSPRESET, PhysPreset)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_PHYSCOLLMAP, PhysCollmap)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_XANIMPARTS, XAnimParts)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_XMODEL_SURFS, XModelSurfs)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_XMODEL, XModel)) + REGISTER_ASSET_LOADER(AssetLoaderMaterial) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_PIXELSHADER, MaterialPixelShader)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_VERTEXSHADER, MaterialVertexShader)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_VERTEXDECL, MaterialVertexDeclaration)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_TECHNIQUE_SET, MaterialTechniqueSet)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_IMAGE, GfxImage)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_SOUND, snd_alias_list_t)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_SOUND_CURVE, SndCurve)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_LOADED_SOUND, LoadedSound)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_CLIPMAP, clipMap_t)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_COMWORLD, ComWorld)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_GLASSWORLD, GlassWorld)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_PATHDATA, PathData)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_VEHICLE_TRACK, VehicleTrack)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_MAP_ENTS, MapEnts)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_FXWORLD, FxWorld)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_GFXWORLD, GfxWorld)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_LIGHT_DEF, GfxLightDef)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_FONT, Font_s)) + REGISTER_ASSET_LOADER(AssetLoaderMenuList) + REGISTER_ASSET_LOADER(AssetLoaderMenuDef) + REGISTER_ASSET_LOADER(AssetLoaderLocalizeEntry) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_ATTACHMENT, WeaponAttachment)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_WEAPON, WeaponCompleteDef)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_FX, FxEffectDef)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_IMPACT_FX, FxImpactTable)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_SURFACE_FX, SurfaceFxTable)) + REGISTER_ASSET_LOADER(AssetLoaderRawFile) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_SCRIPTFILE, ScriptFile)) + REGISTER_ASSET_LOADER(AssetLoaderStringTable) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_LEADERBOARD, LeaderboardDef)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_STRUCTURED_DATA_DEF, StructuredDataDefSet)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_TRACER, TracerDef)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_VEHICLE, VehicleDef)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_ADDON_MAP_ENTS, AddonMapEnts)) #undef BASIC_LOADER #undef REGISTER_ASSET_LOADER } -bool ObjLoader::SupportsZone(Zone* zone) const -{ - return zone->m_game == &g_GameIW5; -} +bool ObjLoader::SupportsZone(Zone *zone) const { return zone->m_game == &g_GameIW5; } -bool ObjLoader::IsMpZone(Zone* zone) -{ - return zone->m_name.compare(0, 3, "mp_") == 0 - || zone->m_name.compare(zone->m_name.length() - 3, 3, "_mp") == 0; -} +bool ObjLoader::IsMpZone(Zone *zone) { return zone->m_name.compare(0, 3, "mp_") == 0 || zone->m_name.compare(zone->m_name.length() - 3, 3, "_mp") == 0; } -bool ObjLoader::IsZmZone(Zone* zone) -{ - return zone->m_name.compare(0, 3, "zm_") == 0 - || zone->m_name.compare(zone->m_name.length() - 3, 3, "_zm") == 0; -} +bool ObjLoader::IsZmZone(Zone *zone) { return zone->m_name.compare(0, 3, "zm_") == 0 || zone->m_name.compare(zone->m_name.length() - 3, 3, "_zm") == 0; } -void ObjLoader::LoadReferencedContainersForZone(ISearchPath* searchPath, Zone* zone) const -{ -} +void ObjLoader::LoadReferencedContainersForZone(ISearchPath *searchPath, Zone *zone) const {} -void ObjLoader::UnloadContainersOfZone(Zone* zone) const -{ -} +void ObjLoader::UnloadContainersOfZone(Zone *zone) const {} -void ObjLoader::LoadImageFromLoadDef(GfxImage* image, Zone* zone) -{ - const auto* loadDef = image->texture.loadDef; - Dx9TextureLoader textureLoader(zone->GetMemory()); +void ObjLoader::LoadImageFromLoadDef(GfxImage *image, Zone *zone) { + const auto *loadDef = image->texture.loadDef; + Dx9TextureLoader textureLoader(zone->GetMemory()); - textureLoader.Width(image->width).Height(image->height).Depth(image->depth); + textureLoader.Width(image->width).Height(image->height).Depth(image->depth); - if ((loadDef->flags & iwi8::IMG_FLAG_MAPTYPE_MASK) == iwi8::IMG_FLAG_MAPTYPE_3D) - textureLoader.Type(TextureType::T_3D); - else if ((loadDef->flags & iwi8::IMG_FLAG_MAPTYPE_MASK) == iwi8::IMG_FLAG_MAPTYPE_CUBE) - textureLoader.Type(TextureType::T_CUBE); - else - textureLoader.Type(TextureType::T_2D); + if ((loadDef->flags & iwi8::IMG_FLAG_MAPTYPE_MASK) == iwi8::IMG_FLAG_MAPTYPE_3D) + textureLoader.Type(TextureType::T_3D); + else if ((loadDef->flags & iwi8::IMG_FLAG_MAPTYPE_MASK) == iwi8::IMG_FLAG_MAPTYPE_CUBE) + textureLoader.Type(TextureType::T_CUBE); + else + textureLoader.Type(TextureType::T_2D); - textureLoader.Format(static_cast(loadDef->format)); - textureLoader.HasMipMaps(!(loadDef->flags & iwi8::IMG_FLAG_NOMIPMAPS)); - Texture* loadedTexture = textureLoader.LoadTexture(image->texture.loadDef->data); + textureLoader.Format(static_cast(loadDef->format)); + textureLoader.HasMipMaps(!(loadDef->flags & iwi8::IMG_FLAG_NOMIPMAPS)); + Texture *loadedTexture = textureLoader.LoadTexture(image->texture.loadDef->data); - if (loadedTexture != nullptr) - { - image->texture.texture = loadedTexture; - image->cardMemory.platform[0] = 0; + if (loadedTexture != nullptr) { + image->texture.texture = loadedTexture; + image->cardMemory.platform[0] = 0; - const auto textureMipCount = loadedTexture->GetMipMapCount(); - for (auto mipLevel = 0; mipLevel < textureMipCount; mipLevel++) - image->cardMemory.platform[0] += static_cast(loadedTexture->GetSizeOfMipLevel(mipLevel) * loadedTexture->GetFaceCount()); - } + const auto textureMipCount = loadedTexture->GetMipMapCount(); + for (auto mipLevel = 0; mipLevel < textureMipCount; mipLevel++) + image->cardMemory.platform[0] += static_cast(loadedTexture->GetSizeOfMipLevel(mipLevel) * loadedTexture->GetFaceCount()); + } } -void ObjLoader::LoadImageFromIwi(GfxImage* image, ISearchPath* searchPath, Zone* zone) -{ - Texture* loadedTexture = nullptr; - IwiLoader loader(zone->GetMemory()); +void ObjLoader::LoadImageFromIwi(GfxImage *image, ISearchPath *searchPath, Zone *zone) { + Texture *loadedTexture = nullptr; + IwiLoader loader(zone->GetMemory()); - const auto imageFileName = "images/" + std::string(image->name) + ".iwi"; + const auto imageFileName = "images/" + std::string(image->name) + ".iwi"; - { - const auto filePathImage = searchPath->Open(imageFileName); - if (filePathImage.IsOpen()) - { - loadedTexture = loader.LoadIwi(*filePathImage.m_stream); - } + { + const auto filePathImage = searchPath->Open(imageFileName); + if (filePathImage.IsOpen()) { + loadedTexture = loader.LoadIwi(*filePathImage.m_stream); } + } + + if (loadedTexture != nullptr) { + image->texture.texture = loadedTexture; + image->cardMemory.platform[0] = 0; + + const auto textureMipCount = loadedTexture->GetMipMapCount(); + for (auto mipLevel = 0; mipLevel < textureMipCount; mipLevel++) + image->cardMemory.platform[0] += static_cast(loadedTexture->GetSizeOfMipLevel(mipLevel) * loadedTexture->GetFaceCount()); + } else { + printf("Could not find data for image \"%s\"\n", image->name); + } +} - if (loadedTexture != nullptr) - { - image->texture.texture = loadedTexture; - image->cardMemory.platform[0] = 0; +void ObjLoader::LoadImageData(ISearchPath *searchPath, Zone *zone) { + auto *assetPool = dynamic_cast(zone->m_pools.get()); - const auto textureMipCount = loadedTexture->GetMipMapCount(); - for (auto mipLevel = 0; mipLevel < textureMipCount; mipLevel++) - image->cardMemory.platform[0] += static_cast(loadedTexture->GetSizeOfMipLevel(mipLevel) * loadedTexture->GetFaceCount()); - } - else - { - printf("Could not find data for image \"%s\"\n", image->name); - } -} + if (assetPool && assetPool->m_image != nullptr) { + for (auto *imageEntry : *assetPool->m_image) { + auto *image = imageEntry->Asset(); + + if (image->cardMemory.platform[0] > 0) { + continue; + } -void ObjLoader::LoadImageData(ISearchPath* searchPath, Zone* zone) -{ - auto* assetPool = dynamic_cast(zone->m_pools.get()); - - if (assetPool && assetPool->m_image != nullptr) - { - for (auto* imageEntry : *assetPool->m_image) - { - auto* image = imageEntry->Asset(); - - if (image->cardMemory.platform[0] > 0) - { - continue; - } - - // Do not load linked assets - if (image->name && image->name[0] == ',') - { - continue; - } - - if (image->texture.loadDef && image->texture.loadDef->resourceSize > 0) - { - LoadImageFromLoadDef(image, zone); - } - else - { - LoadImageFromIwi(image, searchPath, zone); - } - } + // Do not load linked assets + if (image->name && image->name[0] == ',') { + continue; + } + + if (image->texture.loadDef && image->texture.loadDef->resourceSize > 0) { + LoadImageFromLoadDef(image, zone); + } else { + LoadImageFromIwi(image, searchPath, zone); + } } + } } -void ObjLoader::LoadObjDataForZone(ISearchPath* searchPath, Zone* zone) const -{ - LoadImageData(searchPath, zone); -} +void ObjLoader::LoadObjDataForZone(ISearchPath *searchPath, Zone *zone) const { LoadImageData(searchPath, zone); } -bool ObjLoader::LoadAssetForZone(AssetLoadingContext* context, asset_type_t assetType, const std::string& assetName) const -{ - AssetLoadingManager assetLoadingManager(m_asset_loaders_by_type, *context); - return assetLoadingManager.LoadAssetFromLoader(assetType, assetName); +bool ObjLoader::LoadAssetForZone(AssetLoadingContext *context, asset_type_t assetType, const std::string &assetName) const { + AssetLoadingManager assetLoadingManager(m_asset_loaders_by_type, *context); + return assetLoadingManager.LoadAssetFromLoader(assetType, assetName); } -void ObjLoader::FinalizeAssetsForZone(AssetLoadingContext* context) const -{ - for (const auto& [type, loader] : m_asset_loaders_by_type) - loader->FinalizeAssetsForZone(context); +void ObjLoader::FinalizeAssetsForZone(AssetLoadingContext *context) const { + for (const auto &[type, loader] : m_asset_loaders_by_type) + loader->FinalizeAssetsForZone(context); } diff --git a/src/ObjLoading/Game/IW5/ObjLoaderIW5.h b/src/ObjLoading/Game/IW5/ObjLoaderIW5.h index 680e5454a..8d0d82e68 100644 --- a/src/ObjLoading/Game/IW5/ObjLoaderIW5.h +++ b/src/ObjLoading/Game/IW5/ObjLoaderIW5.h @@ -3,35 +3,33 @@ #include #include -#include "IObjLoader.h" #include "AssetLoading/IAssetLoader.h" -#include "SearchPath/ISearchPath.h" #include "Game/IW5/IW5.h" +#include "IObjLoader.h" +#include "SearchPath/ISearchPath.h" -namespace IW5 -{ - class ObjLoader final : public IObjLoader - { - std::map> m_asset_loaders_by_type; +namespace IW5 { +class ObjLoader final : public IObjLoader { + std::map> m_asset_loaders_by_type; - static void LoadImageFromIwi(GfxImage* image, ISearchPath* searchPath, Zone* zone); - static void LoadImageFromLoadDef(GfxImage* image, Zone* zone); - static void LoadImageData(ISearchPath* searchPath, Zone* zone); + static void LoadImageFromIwi(GfxImage *image, ISearchPath *searchPath, Zone *zone); + static void LoadImageFromLoadDef(GfxImage *image, Zone *zone); + static void LoadImageData(ISearchPath *searchPath, Zone *zone); - static bool IsMpZone(Zone* zone); - static bool IsZmZone(Zone* zone); + static bool IsMpZone(Zone *zone); + static bool IsZmZone(Zone *zone); - public: - ObjLoader(); +public: + ObjLoader(); - bool SupportsZone(Zone* zone) const override; + bool SupportsZone(Zone *zone) const override; - void LoadReferencedContainersForZone(ISearchPath* searchPath, Zone* zone) const override; - void UnloadContainersOfZone(Zone* zone) const override; + void LoadReferencedContainersForZone(ISearchPath *searchPath, Zone *zone) const override; + void UnloadContainersOfZone(Zone *zone) const override; - void LoadObjDataForZone(ISearchPath* searchPath, Zone* zone) const override; + void LoadObjDataForZone(ISearchPath *searchPath, Zone *zone) const override; - bool LoadAssetForZone(AssetLoadingContext* context, asset_type_t assetType, const std::string& assetName) const override; - void FinalizeAssetsForZone(AssetLoadingContext* context) const override; - }; -} + bool LoadAssetForZone(AssetLoadingContext *context, asset_type_t assetType, const std::string &assetName) const override; + void FinalizeAssetsForZone(AssetLoadingContext *context) const override; +}; +} // namespace IW5 diff --git a/src/ObjLoading/Game/T5/AssetLoaders/AssetLoaderLocalizeEntry.cpp b/src/ObjLoading/Game/T5/AssetLoaders/AssetLoaderLocalizeEntry.cpp index 1884c4325..498aa4aca 100644 --- a/src/ObjLoading/Game/T5/AssetLoaders/AssetLoaderLocalizeEntry.cpp +++ b/src/ObjLoading/Game/T5/AssetLoaders/AssetLoaderLocalizeEntry.cpp @@ -7,45 +7,35 @@ using namespace T5; -XAssetInfoGeneric* AssetLoaderLocalizeEntry::LoadFromGlobalAssetPools(const std::string& assetName) const -{ - return nullptr; -} +XAssetInfoGeneric *AssetLoaderLocalizeEntry::LoadFromGlobalAssetPools(const std::string &assetName) const { return nullptr; } -void* AssetLoaderLocalizeEntry::CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) -{ - return nullptr; -} +void *AssetLoaderLocalizeEntry::CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) { return nullptr; } -bool AssetLoaderLocalizeEntry::CanLoadFromRaw() const -{ - return true; -} +bool AssetLoaderLocalizeEntry::CanLoadFromRaw() const { return true; } -bool AssetLoaderLocalizeEntry::LoadFromRaw(const std::string& assetName, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const -{ - std::string fileName; - { - std::ostringstream str; - str << LocalizeCommon::GetNameOfLanguage(zone->m_language) << "/localizedstrings/" << assetName << ".str"; - fileName = str.str(); - } +bool AssetLoaderLocalizeEntry::LoadFromRaw(const std::string &assetName, ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager, + Zone *zone) const { + std::string fileName; + { + std::ostringstream str; + str << LocalizeCommon::GetNameOfLanguage(zone->m_language) << "/localizedstrings/" << assetName << ".str"; + fileName = str.str(); + } - const auto file = searchPath->Open(fileName); - if (!file.IsOpen()) - return false; + const auto file = searchPath->Open(fileName); + if (!file.IsOpen()) + return false; - LocalizeFileReader reader(*file.m_stream, assetName, zone->m_language); - const auto localizeEntries = reader.ReadLocalizeFile(); + LocalizeFileReader reader(*file.m_stream, assetName, zone->m_language); + const auto localizeEntries = reader.ReadLocalizeFile(); - for (const auto& entry : localizeEntries) - { - auto* localizeEntry = memory->Create(); - localizeEntry->name = memory->Dup(entry.m_key.c_str()); - localizeEntry->value = memory->Dup(entry.m_value.c_str()); + for (const auto &entry : localizeEntries) { + auto *localizeEntry = memory->Create(); + localizeEntry->name = memory->Dup(entry.m_key.c_str()); + localizeEntry->value = memory->Dup(entry.m_value.c_str()); - manager->AddAsset(ASSET_TYPE_LOCALIZE_ENTRY, entry.m_key, localizeEntry); - } + manager->AddAsset(ASSET_TYPE_LOCALIZE_ENTRY, entry.m_key, localizeEntry); + } - return true; + return true; } diff --git a/src/ObjLoading/Game/T5/AssetLoaders/AssetLoaderLocalizeEntry.h b/src/ObjLoading/Game/T5/AssetLoaders/AssetLoaderLocalizeEntry.h index 65a2854f8..487c339d4 100644 --- a/src/ObjLoading/Game/T5/AssetLoaders/AssetLoaderLocalizeEntry.h +++ b/src/ObjLoading/Game/T5/AssetLoaders/AssetLoaderLocalizeEntry.h @@ -1,17 +1,15 @@ #pragma once -#include "Game/T5/T5.h" #include "AssetLoading/BasicAssetLoader.h" #include "AssetLoading/IAssetLoadingManager.h" +#include "Game/T5/T5.h" #include "SearchPath/ISearchPath.h" -namespace T5 -{ - class AssetLoaderLocalizeEntry final : public BasicAssetLoader - { - public: - _NODISCARD XAssetInfoGeneric* LoadFromGlobalAssetPools(const std::string& assetName) const override; - _NODISCARD void* CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) override; - _NODISCARD bool CanLoadFromRaw() const override; - bool LoadFromRaw(const std::string& assetName, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const override; - }; -} +namespace T5 { +class AssetLoaderLocalizeEntry final : public BasicAssetLoader { +public: + _NODISCARD XAssetInfoGeneric *LoadFromGlobalAssetPools(const std::string &assetName) const override; + _NODISCARD void *CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) override; + _NODISCARD bool CanLoadFromRaw() const override; + bool LoadFromRaw(const std::string &assetName, ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager, Zone *zone) const override; +}; +} // namespace T5 diff --git a/src/ObjLoading/Game/T5/AssetLoaders/AssetLoaderRawFile.cpp b/src/ObjLoading/Game/T5/AssetLoaders/AssetLoaderRawFile.cpp index 07ab8458d..b08c93193 100644 --- a/src/ObjLoading/Game/T5/AssetLoaders/AssetLoaderRawFile.cpp +++ b/src/ObjLoading/Game/T5/AssetLoaders/AssetLoaderRawFile.cpp @@ -12,100 +12,94 @@ using namespace T5; namespace fs = std::filesystem; -void* AssetLoaderRawFile::CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) -{ - auto* rawFile = memory->Create(); - memset(rawFile, 0, sizeof(RawFile)); - rawFile->name = memory->Dup(assetName.c_str()); - return rawFile; +void *AssetLoaderRawFile::CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) { + auto *rawFile = memory->Create(); + memset(rawFile, 0, sizeof(RawFile)); + rawFile->name = memory->Dup(assetName.c_str()); + return rawFile; } -bool AssetLoaderRawFile::CanLoadFromRaw() const -{ - return true; -} +bool AssetLoaderRawFile::CanLoadFromRaw() const { return true; } -bool AssetLoaderRawFile::LoadGsc(const SearchPathOpenFile& file, const std::string& assetName, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager) -{ - const auto uncompressedBuffer = std::make_unique(static_cast(file.m_length + 1)); - file.m_stream->read(uncompressedBuffer.get(), file.m_length); - if (file.m_stream->gcount() != file.m_length) - return false; - uncompressedBuffer[static_cast(file.m_length)] = '\0'; +bool AssetLoaderRawFile::LoadGsc(const SearchPathOpenFile &file, const std::string &assetName, ISearchPath *searchPath, MemoryManager *memory, + IAssetLoadingManager *manager) { + const auto uncompressedBuffer = std::make_unique(static_cast(file.m_length + 1)); + file.m_stream->read(uncompressedBuffer.get(), file.m_length); + if (file.m_stream->gcount() != file.m_length) + return false; + uncompressedBuffer[static_cast(file.m_length)] = '\0'; - const auto compressionBufferSize = static_cast(file.m_length + 1 + sizeof(uint32_t) + sizeof(uint32_t) + COMPRESSED_BUFFER_SIZE_PADDING); - auto* compressedBuffer = static_cast(memory->Alloc(compressionBufferSize)); + const auto compressionBufferSize = static_cast(file.m_length + 1 + sizeof(uint32_t) + sizeof(uint32_t) + COMPRESSED_BUFFER_SIZE_PADDING); + auto *compressedBuffer = static_cast(memory->Alloc(compressionBufferSize)); - z_stream_s zs{}; + z_stream_s zs{}; - zs.zalloc = Z_NULL; - zs.zfree = Z_NULL; - zs.opaque = Z_NULL; - zs.avail_in = static_cast(file.m_length + 1); - zs.avail_out = compressionBufferSize; - zs.next_in = reinterpret_cast(uncompressedBuffer.get()); - zs.next_out = reinterpret_cast(&compressedBuffer[sizeof(uint32_t) + sizeof(uint32_t)]); + zs.zalloc = Z_NULL; + zs.zfree = Z_NULL; + zs.opaque = Z_NULL; + zs.avail_in = static_cast(file.m_length + 1); + zs.avail_out = compressionBufferSize; + zs.next_in = reinterpret_cast(uncompressedBuffer.get()); + zs.next_out = reinterpret_cast(&compressedBuffer[sizeof(uint32_t) + sizeof(uint32_t)]); - int ret = deflateInit(&zs, Z_DEFAULT_COMPRESSION); + int ret = deflateInit(&zs, Z_DEFAULT_COMPRESSION); - if (ret != Z_OK) - { - throw std::runtime_error("Initializing deflate failed"); - } + if (ret != Z_OK) { + throw std::runtime_error("Initializing deflate failed"); + } - ret = deflate(&zs, Z_FINISH); + ret = deflate(&zs, Z_FINISH); - if (ret != Z_STREAM_END) - { - std::cout << "Deflate failed for loading gsc file \"" << assetName << "\"" << std::endl; - deflateEnd(&zs); - return false; - } + if (ret != Z_STREAM_END) { + std::cout << "Deflate failed for loading gsc file \"" << assetName << "\"" << std::endl; + deflateEnd(&zs); + return false; + } - const auto compressedSize = compressionBufferSize - zs.avail_out; + const auto compressedSize = compressionBufferSize - zs.avail_out; - reinterpret_cast(compressedBuffer)[0] = static_cast(file.m_length + 1); // outLen - reinterpret_cast(compressedBuffer)[1] = compressedSize; // inLen + reinterpret_cast(compressedBuffer)[0] = static_cast(file.m_length + 1); // outLen + reinterpret_cast(compressedBuffer)[1] = compressedSize; // inLen - auto* rawFile = memory->Create(); - rawFile->name = memory->Dup(assetName.c_str()); - rawFile->len = static_cast(compressedSize + sizeof(uint32_t) + sizeof(uint32_t)); - rawFile->buffer = static_cast(compressedBuffer); + auto *rawFile = memory->Create(); + rawFile->name = memory->Dup(assetName.c_str()); + rawFile->len = static_cast(compressedSize + sizeof(uint32_t) + sizeof(uint32_t)); + rawFile->buffer = static_cast(compressedBuffer); - manager->AddAsset(ASSET_TYPE_RAWFILE, assetName, rawFile); + manager->AddAsset(ASSET_TYPE_RAWFILE, assetName, rawFile); - return true; + return true; } -bool AssetLoaderRawFile::LoadDefault(const SearchPathOpenFile& file, const std::string& assetName, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager) -{ - auto* rawFile = memory->Create(); - rawFile->name = memory->Dup(assetName.c_str()); - rawFile->len = static_cast(file.m_length); +bool AssetLoaderRawFile::LoadDefault(const SearchPathOpenFile &file, const std::string &assetName, ISearchPath *searchPath, MemoryManager *memory, + IAssetLoadingManager *manager) { + auto *rawFile = memory->Create(); + rawFile->name = memory->Dup(assetName.c_str()); + rawFile->len = static_cast(file.m_length); - auto* fileBuffer = static_cast(memory->Alloc(static_cast(file.m_length + 1))); - file.m_stream->read(fileBuffer, file.m_length); - if (file.m_stream->gcount() != file.m_length) - return false; - fileBuffer[rawFile->len] = '\0'; + auto *fileBuffer = static_cast(memory->Alloc(static_cast(file.m_length + 1))); + file.m_stream->read(fileBuffer, file.m_length); + if (file.m_stream->gcount() != file.m_length) + return false; + fileBuffer[rawFile->len] = '\0'; - rawFile->buffer = fileBuffer; - manager->AddAsset(ASSET_TYPE_RAWFILE, assetName, rawFile); + rawFile->buffer = fileBuffer; + manager->AddAsset(ASSET_TYPE_RAWFILE, assetName, rawFile); - return true; + return true; } -bool AssetLoaderRawFile::LoadFromRaw(const std::string& assetName, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const -{ - const auto file = searchPath->Open(assetName); - if (!file.IsOpen()) - return false; +bool AssetLoaderRawFile::LoadFromRaw(const std::string &assetName, ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager, + Zone *zone) const { + const auto file = searchPath->Open(assetName); + if (!file.IsOpen()) + return false; - const fs::path rawFilePath(assetName); - const auto extension = rawFilePath.extension().string(); + const fs::path rawFilePath(assetName); + const auto extension = rawFilePath.extension().string(); - if(extension == ".gsc" ||extension == ".csc") - return LoadGsc(file, assetName, searchPath, memory, manager); + if (extension == ".gsc" || extension == ".csc") + return LoadGsc(file, assetName, searchPath, memory, manager); - return LoadDefault(file, assetName, searchPath, memory, manager); + return LoadDefault(file, assetName, searchPath, memory, manager); } diff --git a/src/ObjLoading/Game/T5/AssetLoaders/AssetLoaderRawFile.h b/src/ObjLoading/Game/T5/AssetLoaders/AssetLoaderRawFile.h index 5a32e7a16..4524370bb 100644 --- a/src/ObjLoading/Game/T5/AssetLoaders/AssetLoaderRawFile.h +++ b/src/ObjLoading/Game/T5/AssetLoaders/AssetLoaderRawFile.h @@ -1,21 +1,21 @@ #pragma once -#include "Game/T5/T5.h" #include "AssetLoading/BasicAssetLoader.h" #include "AssetLoading/IAssetLoadingManager.h" +#include "Game/T5/T5.h" #include "SearchPath/ISearchPath.h" -namespace T5 -{ - class AssetLoaderRawFile final : public BasicAssetLoader - { - static constexpr size_t COMPRESSED_BUFFER_SIZE_PADDING = 64; +namespace T5 { +class AssetLoaderRawFile final : public BasicAssetLoader { + static constexpr size_t COMPRESSED_BUFFER_SIZE_PADDING = 64; - static bool LoadGsc(const SearchPathOpenFile& file, const std::string& assetName, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager); - static bool LoadDefault(const SearchPathOpenFile& file, const std::string& assetName, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager); + static bool LoadGsc(const SearchPathOpenFile &file, const std::string &assetName, ISearchPath *searchPath, MemoryManager *memory, + IAssetLoadingManager *manager); + static bool LoadDefault(const SearchPathOpenFile &file, const std::string &assetName, ISearchPath *searchPath, MemoryManager *memory, + IAssetLoadingManager *manager); - public: - _NODISCARD void* CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) override; - _NODISCARD bool CanLoadFromRaw() const override; - bool LoadFromRaw(const std::string& assetName, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const override; - }; -} +public: + _NODISCARD void *CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) override; + _NODISCARD bool CanLoadFromRaw() const override; + bool LoadFromRaw(const std::string &assetName, ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager, Zone *zone) const override; +}; +} // namespace T5 diff --git a/src/ObjLoading/Game/T5/AssetLoaders/AssetLoaderStringTable.cpp b/src/ObjLoading/Game/T5/AssetLoaders/AssetLoaderStringTable.cpp index 986ce669b..fcf3af573 100644 --- a/src/ObjLoading/Game/T5/AssetLoaders/AssetLoaderStringTable.cpp +++ b/src/ObjLoading/Game/T5/AssetLoaders/AssetLoaderStringTable.cpp @@ -9,85 +9,74 @@ using namespace T5; -void* AssetLoaderStringTable::CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) -{ - auto* stringTable = memory->Create(); - memset(stringTable, 0, sizeof(StringTable)); - stringTable->name = memory->Dup(assetName.c_str()); - return stringTable; +void *AssetLoaderStringTable::CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) { + auto *stringTable = memory->Create(); + memset(stringTable, 0, sizeof(StringTable)); + stringTable->name = memory->Dup(assetName.c_str()); + return stringTable; } -bool AssetLoaderStringTable::CanLoadFromRaw() const -{ - return true; -} - -bool AssetLoaderStringTable::LoadFromRaw(const std::string& assetName, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const -{ - const auto file = searchPath->Open(assetName); - if (!file.IsOpen()) - return false; - - auto* stringTable = memory->Create(); - stringTable->name = memory->Dup(assetName.c_str()); - - std::vector> csvLines; - std::vector currentLine; - auto maxCols = 0u; - const CsvInputStream csv(*file.m_stream); - - while (csv.NextRow(currentLine)) - { - if (currentLine.size() > maxCols) - maxCols = currentLine.size(); - csvLines.emplace_back(std::move(currentLine)); - currentLine = std::vector(); +bool AssetLoaderStringTable::CanLoadFromRaw() const { return true; } + +bool AssetLoaderStringTable::LoadFromRaw(const std::string &assetName, ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager, + Zone *zone) const { + const auto file = searchPath->Open(assetName); + if (!file.IsOpen()) + return false; + + auto *stringTable = memory->Create(); + stringTable->name = memory->Dup(assetName.c_str()); + + std::vector> csvLines; + std::vector currentLine; + auto maxCols = 0u; + const CsvInputStream csv(*file.m_stream); + + while (csv.NextRow(currentLine)) { + if (currentLine.size() > maxCols) + maxCols = currentLine.size(); + csvLines.emplace_back(std::move(currentLine)); + currentLine = std::vector(); + } + + stringTable->columnCount = static_cast(maxCols); + stringTable->rowCount = static_cast(csvLines.size()); + const auto cellCount = static_cast(stringTable->rowCount) * static_cast(stringTable->columnCount); + + if (cellCount) { + stringTable->values = static_cast(memory->Alloc(sizeof(StringTableCell) * cellCount)); + stringTable->cellIndex = static_cast(memory->Alloc(sizeof(int16_t) * cellCount)); + + for (auto c = 0u; c < cellCount; c++) + stringTable->cellIndex[c] = static_cast(c); + + for (auto row = 0u; row < csvLines.size(); row++) { + const auto &rowValues = csvLines[row]; + for (auto col = 0u; col < maxCols; col++) { + auto &cell = stringTable->values[row * maxCols + col]; + if (col >= rowValues.size() || rowValues[col].empty()) + cell.string = ""; + else + cell.string = memory->Dup(rowValues[col].c_str()); + + cell.hash = Common::Com_HashString(cell.string); + } } - stringTable->columnCount = static_cast(maxCols); - stringTable->rowCount = static_cast(csvLines.size()); - const auto cellCount = static_cast(stringTable->rowCount) * static_cast(stringTable->columnCount); - - if (cellCount) - { - stringTable->values = static_cast(memory->Alloc(sizeof(StringTableCell) * cellCount)); - stringTable->cellIndex = static_cast(memory->Alloc(sizeof(int16_t) * cellCount)); - - for (auto c = 0u; c < cellCount; c++) - stringTable->cellIndex[c] = static_cast(c); - - for (auto row = 0u; row < csvLines.size(); row++) - { - const auto& rowValues = csvLines[row]; - for (auto col = 0u; col < maxCols; col++) - { - auto& cell = stringTable->values[row * maxCols + col]; - if (col >= rowValues.size() || rowValues[col].empty()) - cell.string = ""; - else - cell.string = memory->Dup(rowValues[col].c_str()); - - cell.hash = Common::Com_HashString(cell.string); - } - } - - - std::sort(&stringTable->cellIndex[0], &stringTable->cellIndex[cellCount - 1], [stringTable, maxCols](const int16_t a, const int16_t b) - { - auto compareResult = stringTable->values[a].hash - stringTable->values[b].hash; - if (compareResult == 0) - compareResult = a % maxCols - b % maxCols; - return compareResult < 0; - }); - } + std::sort(&stringTable->cellIndex[0], &stringTable->cellIndex[cellCount - 1], [stringTable, maxCols](const int16_t a, const int16_t b) { + auto compareResult = stringTable->values[a].hash - stringTable->values[b].hash; + if (compareResult == 0) + compareResult = a % maxCols - b % maxCols; + return compareResult < 0; + }); + } - else - { - stringTable->values = nullptr; - stringTable->cellIndex = nullptr; - } + else { + stringTable->values = nullptr; + stringTable->cellIndex = nullptr; + } - manager->AddAsset(ASSET_TYPE_STRINGTABLE, assetName, stringTable); + manager->AddAsset(ASSET_TYPE_STRINGTABLE, assetName, stringTable); - return true; + return true; } diff --git a/src/ObjLoading/Game/T5/AssetLoaders/AssetLoaderStringTable.h b/src/ObjLoading/Game/T5/AssetLoaders/AssetLoaderStringTable.h index e80a82be1..f696c937e 100644 --- a/src/ObjLoading/Game/T5/AssetLoaders/AssetLoaderStringTable.h +++ b/src/ObjLoading/Game/T5/AssetLoaders/AssetLoaderStringTable.h @@ -1,16 +1,14 @@ #pragma once -#include "Game/T5/T5.h" #include "AssetLoading/BasicAssetLoader.h" #include "AssetLoading/IAssetLoadingManager.h" +#include "Game/T5/T5.h" #include "SearchPath/ISearchPath.h" -namespace T5 -{ - class AssetLoaderStringTable final : public BasicAssetLoader - { - public: - _NODISCARD void* CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) override; - _NODISCARD bool CanLoadFromRaw() const override; - bool LoadFromRaw(const std::string& assetName, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const override; - }; -} +namespace T5 { +class AssetLoaderStringTable final : public BasicAssetLoader { +public: + _NODISCARD void *CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) override; + _NODISCARD bool CanLoadFromRaw() const override; + bool LoadFromRaw(const std::string &assetName, ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager, Zone *zone) const override; +}; +} // namespace T5 diff --git a/src/ObjLoading/Game/T5/ObjLoaderT5.cpp b/src/ObjLoading/Game/T5/ObjLoaderT5.cpp index 562710a8a..14ddb07f5 100644 --- a/src/ObjLoading/Game/T5/ObjLoaderT5.cpp +++ b/src/ObjLoading/Game/T5/ObjLoaderT5.cpp @@ -1,193 +1,161 @@ #include "ObjLoaderT5.h" -#include "Game/T5/GameT5.h" -#include "Game/T5/GameAssetPoolT5.h" -#include "ObjContainer/IPak/IPak.h" -#include "ObjLoading.h" #include "AssetLoaders/AssetLoaderLocalizeEntry.h" #include "AssetLoaders/AssetLoaderRawFile.h" #include "AssetLoaders/AssetLoaderStringTable.h" #include "AssetLoading/AssetLoadingManager.h" +#include "Game/T5/GameAssetPoolT5.h" +#include "Game/T5/GameT5.h" #include "Image/Dx9TextureLoader.h" -#include "Image/Texture.h" #include "Image/IwiLoader.h" #include "Image/IwiTypes.h" +#include "Image/Texture.h" +#include "ObjContainer/IPak/IPak.h" +#include "ObjLoading.h" using namespace T5; -ObjLoader::ObjLoader() -{ -#define REGISTER_ASSET_LOADER(t) {auto l = std::make_unique(); m_asset_loaders_by_type[l->GetHandlingAssetType()] = std::move(l);} +ObjLoader::ObjLoader() { +#define REGISTER_ASSET_LOADER(t) \ + { \ + auto l = std::make_unique(); \ + m_asset_loaders_by_type[l->GetHandlingAssetType()] = std::move(l); \ + } #define BASIC_LOADER(assetType, assetClass) BasicAssetLoader - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_PHYSPRESET, PhysPreset)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_PHYSCONSTRAINTS, PhysConstraints)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_DESTRUCTIBLEDEF, DestructibleDef)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_XANIMPARTS, XAnimParts)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_XMODEL, XModel)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_MATERIAL, Material)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_TECHNIQUE_SET, MaterialTechniqueSet)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_IMAGE, GfxImage)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_SOUND, SndBank)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_SOUND_PATCH, SndPatch)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_CLIPMAP, clipMap_t)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_CLIPMAP_PVS, clipMap_t)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_COMWORLD, ComWorld)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_GAMEWORLD_SP, GameWorldSp)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_GAMEWORLD_MP, GameWorldMp)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_MAP_ENTS, MapEnts)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_GFXWORLD, GfxWorld)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_LIGHT_DEF, GfxLightDef)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_FONT, Font_s)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_MENULIST, MenuList)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_MENU, menuDef_t)) - REGISTER_ASSET_LOADER(AssetLoaderLocalizeEntry) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_WEAPON, WeaponVariantDef)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_SNDDRIVER_GLOBALS, SndDriverGlobals)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_FX, FxEffectDef)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_IMPACT_FX, FxImpactTable)) - REGISTER_ASSET_LOADER(AssetLoaderRawFile) - REGISTER_ASSET_LOADER(AssetLoaderStringTable) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_PACK_INDEX, PackIndex)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_XGLOBALS, XGlobals)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_DDL, ddlRoot_t)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_GLASSES, Glasses)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_EMBLEMSET, EmblemSet)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_PHYSPRESET, PhysPreset)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_PHYSCONSTRAINTS, PhysConstraints)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_DESTRUCTIBLEDEF, DestructibleDef)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_XANIMPARTS, XAnimParts)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_XMODEL, XModel)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_MATERIAL, Material)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_TECHNIQUE_SET, MaterialTechniqueSet)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_IMAGE, GfxImage)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_SOUND, SndBank)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_SOUND_PATCH, SndPatch)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_CLIPMAP, clipMap_t)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_CLIPMAP_PVS, clipMap_t)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_COMWORLD, ComWorld)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_GAMEWORLD_SP, GameWorldSp)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_GAMEWORLD_MP, GameWorldMp)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_MAP_ENTS, MapEnts)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_GFXWORLD, GfxWorld)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_LIGHT_DEF, GfxLightDef)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_FONT, Font_s)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_MENULIST, MenuList)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_MENU, menuDef_t)) + REGISTER_ASSET_LOADER(AssetLoaderLocalizeEntry) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_WEAPON, WeaponVariantDef)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_SNDDRIVER_GLOBALS, SndDriverGlobals)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_FX, FxEffectDef)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_IMPACT_FX, FxImpactTable)) + REGISTER_ASSET_LOADER(AssetLoaderRawFile) + REGISTER_ASSET_LOADER(AssetLoaderStringTable) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_PACK_INDEX, PackIndex)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_XGLOBALS, XGlobals)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_DDL, ddlRoot_t)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_GLASSES, Glasses)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_EMBLEMSET, EmblemSet)) #undef BASIC_LOADER #undef REGISTER_ASSET_LOADER } -bool ObjLoader::SupportsZone(Zone* zone) const -{ - return zone->m_game == &g_GameT5; -} +bool ObjLoader::SupportsZone(Zone *zone) const { return zone->m_game == &g_GameT5; } -bool ObjLoader::IsMpZone(Zone* zone) -{ - return zone->m_name.compare(0, 3, "mp_") == 0 - || zone->m_name.compare(zone->m_name.length() - 3, 3, "_mp") == 0; -} +bool ObjLoader::IsMpZone(Zone *zone) { return zone->m_name.compare(0, 3, "mp_") == 0 || zone->m_name.compare(zone->m_name.length() - 3, 3, "_mp") == 0; } -bool ObjLoader::IsZmZone(Zone* zone) -{ - return zone->m_name.compare(0, 3, "zm_") == 0 - || zone->m_name.compare(zone->m_name.length() - 3, 3, "_zm") == 0; -} +bool ObjLoader::IsZmZone(Zone *zone) { return zone->m_name.compare(0, 3, "zm_") == 0 || zone->m_name.compare(zone->m_name.length() - 3, 3, "_zm") == 0; } -void ObjLoader::LoadReferencedContainersForZone(ISearchPath* searchPath, Zone* zone) const -{ -} +void ObjLoader::LoadReferencedContainersForZone(ISearchPath *searchPath, Zone *zone) const {} -void ObjLoader::UnloadContainersOfZone(Zone* zone) const -{ -} +void ObjLoader::UnloadContainersOfZone(Zone *zone) const {} -void ObjLoader::LoadImageFromLoadDef(GfxImage* image, Zone* zone) -{ - const auto* loadDef = image->texture.loadDef; - Dx9TextureLoader textureLoader(zone->GetMemory()); +void ObjLoader::LoadImageFromLoadDef(GfxImage *image, Zone *zone) { + const auto *loadDef = image->texture.loadDef; + Dx9TextureLoader textureLoader(zone->GetMemory()); - textureLoader.Width(image->width).Height(image->height).Depth(image->depth); + textureLoader.Width(image->width).Height(image->height).Depth(image->depth); - if (loadDef->flags & iwi13::IMG_FLAG_VOLMAP) - textureLoader.Type(TextureType::T_3D); - else if (loadDef->flags & iwi13::IMG_FLAG_CUBEMAP) - textureLoader.Type(TextureType::T_CUBE); - else - textureLoader.Type(TextureType::T_2D); + if (loadDef->flags & iwi13::IMG_FLAG_VOLMAP) + textureLoader.Type(TextureType::T_3D); + else if (loadDef->flags & iwi13::IMG_FLAG_CUBEMAP) + textureLoader.Type(TextureType::T_CUBE); + else + textureLoader.Type(TextureType::T_2D); - textureLoader.Format(static_cast(loadDef->format)); - textureLoader.HasMipMaps(!(loadDef->flags & iwi13::IMG_FLAG_NOMIPMAPS)); - Texture* loadedTexture = textureLoader.LoadTexture(image->texture.loadDef->data); + textureLoader.Format(static_cast(loadDef->format)); + textureLoader.HasMipMaps(!(loadDef->flags & iwi13::IMG_FLAG_NOMIPMAPS)); + Texture *loadedTexture = textureLoader.LoadTexture(image->texture.loadDef->data); - if (loadedTexture != nullptr) - { - image->texture.texture = loadedTexture; - image->loadedSize = 0; + if (loadedTexture != nullptr) { + image->texture.texture = loadedTexture; + image->loadedSize = 0; - const auto textureMipCount = loadedTexture->GetMipMapCount(); - for (auto mipLevel = 0; mipLevel < textureMipCount; mipLevel++) - image->loadedSize += static_cast(loadedTexture->GetSizeOfMipLevel(mipLevel) * loadedTexture->GetFaceCount()); - } + const auto textureMipCount = loadedTexture->GetMipMapCount(); + for (auto mipLevel = 0; mipLevel < textureMipCount; mipLevel++) + image->loadedSize += static_cast(loadedTexture->GetSizeOfMipLevel(mipLevel) * loadedTexture->GetFaceCount()); + } } -void ObjLoader::LoadImageFromIwi(GfxImage* image, ISearchPath* searchPath, Zone* zone) -{ - Texture* loadedTexture = nullptr; - IwiLoader loader(zone->GetMemory()); +void ObjLoader::LoadImageFromIwi(GfxImage *image, ISearchPath *searchPath, Zone *zone) { + Texture *loadedTexture = nullptr; + IwiLoader loader(zone->GetMemory()); - const auto imageFileName = "images/" + std::string(image->name) + ".iwi"; + const auto imageFileName = "images/" + std::string(image->name) + ".iwi"; - { - const auto filePathImage = searchPath->Open(imageFileName); - if (filePathImage.IsOpen()) - { - loadedTexture = loader.LoadIwi(*filePathImage.m_stream); - } + { + const auto filePathImage = searchPath->Open(imageFileName); + if (filePathImage.IsOpen()) { + loadedTexture = loader.LoadIwi(*filePathImage.m_stream); } + } + + if (loadedTexture != nullptr) { + image->texture.texture = loadedTexture; + image->loadedSize = 0; + + const auto textureMipCount = loadedTexture->GetMipMapCount(); + for (auto mipLevel = 0; mipLevel < textureMipCount; mipLevel++) + image->loadedSize += static_cast(loadedTexture->GetSizeOfMipLevel(mipLevel) * loadedTexture->GetFaceCount()); + } else { + printf("Could not find data for image \"%s\"\n", image->name); + } +} - if (loadedTexture != nullptr) - { - image->texture.texture = loadedTexture; - image->loadedSize = 0; +void ObjLoader::LoadImageData(ISearchPath *searchPath, Zone *zone) { + auto *assetPool = dynamic_cast(zone->m_pools.get()); - const auto textureMipCount = loadedTexture->GetMipMapCount(); - for (auto mipLevel = 0; mipLevel < textureMipCount; mipLevel++) - image->loadedSize += static_cast(loadedTexture->GetSizeOfMipLevel(mipLevel) * loadedTexture->GetFaceCount()); - } - else - { - printf("Could not find data for image \"%s\"\n", image->name); - } -} + if (assetPool && assetPool->m_image != nullptr) { + for (auto *imageEntry : *assetPool->m_image) { + auto *image = imageEntry->Asset(); + + if (image->loadedSize > 0) { + continue; + } -void ObjLoader::LoadImageData(ISearchPath* searchPath, Zone* zone) -{ - auto* assetPool = dynamic_cast(zone->m_pools.get()); - - if (assetPool && assetPool->m_image != nullptr) - { - for (auto* imageEntry : *assetPool->m_image) - { - auto* image = imageEntry->Asset(); - - if (image->loadedSize > 0) - { - continue; - } - - // Do not load linked assets - if (image->name && image->name[0] == ',') - { - continue; - } - - if (image->texture.loadDef && image->texture.loadDef->resourceSize > 0) - { - LoadImageFromLoadDef(image, zone); - } - else - { - LoadImageFromIwi(image, searchPath, zone); - } - } + // Do not load linked assets + if (image->name && image->name[0] == ',') { + continue; + } + + if (image->texture.loadDef && image->texture.loadDef->resourceSize > 0) { + LoadImageFromLoadDef(image, zone); + } else { + LoadImageFromIwi(image, searchPath, zone); + } } + } } -void ObjLoader::LoadObjDataForZone(ISearchPath* searchPath, Zone* zone) const -{ - LoadImageData(searchPath, zone); -} +void ObjLoader::LoadObjDataForZone(ISearchPath *searchPath, Zone *zone) const { LoadImageData(searchPath, zone); } -bool ObjLoader::LoadAssetForZone(AssetLoadingContext* context, asset_type_t assetType, const std::string& assetName) const -{ - AssetLoadingManager assetLoadingManager(m_asset_loaders_by_type, *context); - return assetLoadingManager.LoadAssetFromLoader(assetType, assetName); +bool ObjLoader::LoadAssetForZone(AssetLoadingContext *context, asset_type_t assetType, const std::string &assetName) const { + AssetLoadingManager assetLoadingManager(m_asset_loaders_by_type, *context); + return assetLoadingManager.LoadAssetFromLoader(assetType, assetName); } -void ObjLoader::FinalizeAssetsForZone(AssetLoadingContext* context) const -{ - for (const auto& [type, loader] : m_asset_loaders_by_type) - loader->FinalizeAssetsForZone(context); +void ObjLoader::FinalizeAssetsForZone(AssetLoadingContext *context) const { + for (const auto &[type, loader] : m_asset_loaders_by_type) + loader->FinalizeAssetsForZone(context); } \ No newline at end of file diff --git a/src/ObjLoading/Game/T5/ObjLoaderT5.h b/src/ObjLoading/Game/T5/ObjLoaderT5.h index c7377dde9..a6c9bf32b 100644 --- a/src/ObjLoading/Game/T5/ObjLoaderT5.h +++ b/src/ObjLoading/Game/T5/ObjLoaderT5.h @@ -3,35 +3,33 @@ #include #include -#include "IObjLoader.h" #include "AssetLoading/IAssetLoader.h" -#include "SearchPath/ISearchPath.h" #include "Game/T5/T5.h" +#include "IObjLoader.h" +#include "SearchPath/ISearchPath.h" -namespace T5 -{ - class ObjLoader final : public IObjLoader - { - std::map> m_asset_loaders_by_type; +namespace T5 { +class ObjLoader final : public IObjLoader { + std::map> m_asset_loaders_by_type; - static void LoadImageFromIwi(GfxImage* image, ISearchPath* searchPath, Zone* zone); - static void LoadImageFromLoadDef(GfxImage* image, Zone* zone); - static void LoadImageData(ISearchPath* searchPath, Zone* zone); + static void LoadImageFromIwi(GfxImage *image, ISearchPath *searchPath, Zone *zone); + static void LoadImageFromLoadDef(GfxImage *image, Zone *zone); + static void LoadImageData(ISearchPath *searchPath, Zone *zone); - static bool IsMpZone(Zone* zone); - static bool IsZmZone(Zone* zone); + static bool IsMpZone(Zone *zone); + static bool IsZmZone(Zone *zone); - public: - ObjLoader(); +public: + ObjLoader(); - bool SupportsZone(Zone* zone) const override; + bool SupportsZone(Zone *zone) const override; - void LoadReferencedContainersForZone(ISearchPath* searchPath, Zone* zone) const override; - void UnloadContainersOfZone(Zone* zone) const override; + void LoadReferencedContainersForZone(ISearchPath *searchPath, Zone *zone) const override; + void UnloadContainersOfZone(Zone *zone) const override; - void LoadObjDataForZone(ISearchPath* searchPath, Zone* zone) const override; + void LoadObjDataForZone(ISearchPath *searchPath, Zone *zone) const override; - bool LoadAssetForZone(AssetLoadingContext* context, asset_type_t assetType, const std::string& assetName) const override; - void FinalizeAssetsForZone(AssetLoadingContext* context) const override; - }; -} + bool LoadAssetForZone(AssetLoadingContext *context, asset_type_t assetType, const std::string &assetName) const override; + void FinalizeAssetsForZone(AssetLoadingContext *context) const override; +}; +} // namespace T5 diff --git a/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderFontIcon.cpp b/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderFontIcon.cpp index ae0682fa0..f68a13b58 100644 --- a/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderFontIcon.cpp +++ b/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderFontIcon.cpp @@ -11,251 +11,201 @@ using namespace T6; -void* AssetLoaderFontIcon::CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) -{ - auto* fontIcon = memory->Create(); - memset(fontIcon, 0, sizeof(FontIcon)); - fontIcon->name = memory->Dup(assetName.c_str()); - return fontIcon; +void *AssetLoaderFontIcon::CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) { + auto *fontIcon = memory->Create(); + memset(fontIcon, 0, sizeof(FontIcon)); + fontIcon->name = memory->Dup(assetName.c_str()); + return fontIcon; } -bool AssetLoaderFontIcon::CanLoadFromRaw() const -{ - return true; -} +bool AssetLoaderFontIcon::CanLoadFromRaw() const { return true; } -std::string AssetLoaderFontIcon::ErrorPrefix(const std::string& assetName, const unsigned rowIndex) -{ - std::ostringstream str; - str << "FontIcon \"" << assetName << "\" Row " << rowIndex << ": "; - return str.str(); +std::string AssetLoaderFontIcon::ErrorPrefix(const std::string &assetName, const unsigned rowIndex) { + std::ostringstream str; + str << "FontIcon \"" << assetName << "\" Row " << rowIndex << ": "; + return str.str(); } -void AssetLoaderFontIcon::PreprocessRow(std::vector& row) -{ - for (auto& cell : row) - { - for (auto c : cell) - { - if (isspace(c)) - continue; - if (c == '#') - cell = ""; - break; - } +void AssetLoaderFontIcon::PreprocessRow(std::vector &row) { + for (auto &cell : row) { + for (auto c : cell) { + if (isspace(c)) + continue; + if (c == '#') + cell = ""; + break; } + } } -bool AssetLoaderFontIcon::RowIsEmpty(const std::vector& row) -{ - return std::all_of(row.begin(), row.end(), [](const std::string& cell) - { - return cell.empty(); - }); +bool AssetLoaderFontIcon::RowIsEmpty(const std::vector &row) { + return std::all_of(row.begin(), row.end(), [](const std::string &cell) { return cell.empty(); }); } -bool AssetLoaderFontIcon::ParseInt(int& value, const std::string& str) -{ - char* endPtr; - value = strtol(str.c_str(), &endPtr, 0); - if (endPtr != &str[str.size()]) - return false; - return true; +bool AssetLoaderFontIcon::ParseInt(int &value, const std::string &str) { + char *endPtr; + value = strtol(str.c_str(), &endPtr, 0); + if (endPtr != &str[str.size()]) + return false; + return true; } -bool AssetLoaderFontIcon::ParseFloat(float& value, const std::string& str) -{ - char* endPtr; - value = strtof(str.c_str(), &endPtr); - if (endPtr != &str[str.size()]) - return false; - return true; +bool AssetLoaderFontIcon::ParseFloat(float &value, const std::string &str) { + char *endPtr; + value = strtof(str.c_str(), &endPtr); + if (endPtr != &str[str.size()]) + return false; + return true; } -bool AssetLoaderFontIcon::ParseHashStr(int& value, const std::string& str) -{ - if (!str.empty() && str[0] == '@' && str.size() > 1) - { - char* endPtr; - value = strtol(&str[1], &endPtr, 16); +bool AssetLoaderFontIcon::ParseHashStr(int &value, const std::string &str) { + if (!str.empty() && str[0] == '@' && str.size() > 1) { + char *endPtr; + value = strtol(&str[1], &endPtr, 16); - if (endPtr != &str[str.size()]) - return false; - } - else - { - value = Common::Com_HashString(str.c_str()); - } + if (endPtr != &str[str.size()]) + return false; + } else { + value = Common::Com_HashString(str.c_str()); + } - return true; + return true; } -bool AssetLoaderFontIcon::ReadIconRow(const std::vector& row, FontIconEntry& icon, const std::string& assetName, const unsigned rowIndex, MemoryManager* memory, - IAssetLoadingManager* manager, std::vector& dependencies) -{ - if (row.size() < COL_COUNT_ICON) - { - std::cout << ErrorPrefix(assetName, rowIndex) << "Column count lower than min column count for entries (" << COL_COUNT_ICON << ")" << std::endl; - return false; - } +bool AssetLoaderFontIcon::ReadIconRow(const std::vector &row, FontIconEntry &icon, const std::string &assetName, const unsigned rowIndex, + MemoryManager *memory, IAssetLoadingManager *manager, std::vector &dependencies) { + if (row.size() < COL_COUNT_ICON) { + std::cout << ErrorPrefix(assetName, rowIndex) << "Column count lower than min column count for entries (" << COL_COUNT_ICON << ")" << std::endl; + return false; + } + + if (!ParseInt(icon.fontIconSize, row[ROW_ICON_SIZE])) { + std::cout << ErrorPrefix(assetName, rowIndex) << "Failed to parse size" << std::endl; + return false; + } + + if (!ParseFloat(icon.xScale, row[ROW_ICON_XSCALE]) || !ParseFloat(icon.yScale, row[ROW_ICON_YSCALE])) { + std::cout << ErrorPrefix(assetName, rowIndex) << "Failed to parse scale" << std::endl; + return false; + } + + auto *materialDependency = manager->LoadDependency(ASSET_TYPE_MATERIAL, row[ROW_ICON_MATERIAL]); + if (materialDependency == nullptr) { + std::cout << ErrorPrefix(assetName, rowIndex) << "Failed to load material \"" << row[ROW_ICON_MATERIAL] << "\"" << std::endl; + return false; + } + + icon.fontIconMaterialHandle = static_cast(materialDependency->m_ptr); + icon.fontIconName.string = memory->Dup(row[ROW_ICON_NAME].c_str()); + icon.fontIconName.hash = Common::Com_HashString(icon.fontIconName.string); + + return true; +} - if (!ParseInt(icon.fontIconSize, row[ROW_ICON_SIZE])) - { - std::cout << ErrorPrefix(assetName, rowIndex) << "Failed to parse size" << std::endl; - return false; - } +bool AssetLoaderFontIcon::ReadAliasRow(const std::vector &row, FontIconAlias &alias, const std::string &assetName, const unsigned rowIndex, + MemoryManager *memory, IAssetLoadingManager *manager) { + if (row.size() < COL_COUNT_ALIAS) { + std::cout << ErrorPrefix(assetName, rowIndex) << "Column count lower than min column count for aliases (" << COL_COUNT_ALIAS << ")" << std::endl; + return false; + } - if (!ParseFloat(icon.xScale, row[ROW_ICON_XSCALE]) - || !ParseFloat(icon.yScale, row[ROW_ICON_YSCALE])) - { - std::cout << ErrorPrefix(assetName, rowIndex) << "Failed to parse scale" << std::endl; - return false; - } + if (!ParseHashStr(alias.aliasHash, row[ROW_ALIAS_NAME])) { + std::cout << ErrorPrefix(assetName, rowIndex) << "Failed to parse alias \"" << row[ROW_ALIAS_NAME] << "\"" << std::endl; + return false; + } - auto* materialDependency = manager->LoadDependency(ASSET_TYPE_MATERIAL, row[ROW_ICON_MATERIAL]); - if (materialDependency == nullptr) - { - std::cout << ErrorPrefix(assetName, rowIndex) << "Failed to load material \"" << row[ROW_ICON_MATERIAL] << "\"" << std::endl; - return false; - } + if (!ParseHashStr(alias.buttonHash, row[ROW_ALIAS_BUTTON])) { + std::cout << ErrorPrefix(assetName, rowIndex) << "Failed to parse button \"" << row[ROW_ALIAS_BUTTON] << "\"" << std::endl; + return false; + } - icon.fontIconMaterialHandle = static_cast(materialDependency->m_ptr); - icon.fontIconName.string = memory->Dup(row[ROW_ICON_NAME].c_str()); - icon.fontIconName.hash = Common::Com_HashString(icon.fontIconName.string); - - return true; + return true; } -bool AssetLoaderFontIcon::ReadAliasRow(const std::vector& row, FontIconAlias& alias, const std::string& assetName, const unsigned rowIndex, MemoryManager* memory, - IAssetLoadingManager* manager) -{ - if (row.size() < COL_COUNT_ALIAS) - { - std::cout << ErrorPrefix(assetName, rowIndex) << "Column count lower than min column count for aliases (" << COL_COUNT_ALIAS << ")" << std::endl; - return false; +bool AssetLoaderFontIcon::LoadFromRaw(const std::string &assetName, ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager, + Zone *zone) const { + const auto file = searchPath->Open(assetName); + if (!file.IsOpen()) + return false; + + auto *fontIcon = memory->Create(); + fontIcon->name = memory->Dup(assetName.c_str()); + + const CsvInputStream csv(*file.m_stream); + std::vector dependencies; + std::vector currentRow; + std::vector entries; + std::vector aliases; + auto currentRowIndex = 0u; + + while (csv.NextRow(currentRow)) { + currentRowIndex++; + PreprocessRow(currentRow); + + if (RowIsEmpty(currentRow)) + continue; + + if (currentRow.size() < COL_COUNT_MIN) { + std::cout << ErrorPrefix(assetName, currentRowIndex) << "Column count lower than min column count (" << COL_COUNT_MIN << ")" << std::endl; + return true; } - if (!ParseHashStr(alias.aliasHash, row[ROW_ALIAS_NAME])) - { - std::cout << ErrorPrefix(assetName, rowIndex) << "Failed to parse alias \"" << row[ROW_ALIAS_NAME] << "\"" << std::endl; - return false; + int index; + if (!ParseInt(index, currentRow[ROW_INDEX]) || index < 0) { + std::cout << ErrorPrefix(assetName, currentRowIndex) << "Failed to parse index" << std::endl; + return true; } - if (!ParseHashStr(alias.buttonHash, row[ROW_ALIAS_BUTTON])) - { - std::cout << ErrorPrefix(assetName, rowIndex) << "Failed to parse button \"" << row[ROW_ALIAS_BUTTON] << "\"" << std::endl; - return false; + if (currentRow[ROW_TYPE] == VALUE_TYPE_ICON) { + FontIconEntry icon{}; + if (!ReadIconRow(currentRow, icon, assetName, currentRowIndex, memory, manager, dependencies)) + return true; + + if (static_cast(index) == entries.size()) { + entries.push_back(icon); + } else if (static_cast(index) > entries.size()) { + entries.reserve(index + 1); + entries[index] = icon; + } else { + entries[index] = icon; + } + } else if (currentRow[ROW_TYPE] == VALUE_TYPE_ALIAS) { + FontIconAlias alias{}; + if (!ReadAliasRow(currentRow, alias, assetName, currentRowIndex, memory, manager)) + return true; + + if (static_cast(index) == aliases.size()) { + aliases.push_back(alias); + } else if (static_cast(index) > aliases.size()) { + aliases.reserve(index + 1); + aliases[index] = alias; + } else { + aliases[index] = alias; + } + } else { + std::cout << ErrorPrefix(assetName, currentRowIndex) << "Unknown row type \"" << currentRow[ROW_TYPE] << "\"" << std::endl; + return true; } + } - return true; -} + fontIcon->numEntries = entries.size(); + fontIcon->numAliasEntries = aliases.size(); -bool AssetLoaderFontIcon::LoadFromRaw(const std::string& assetName, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const -{ - const auto file = searchPath->Open(assetName); - if (!file.IsOpen()) - return false; - - auto* fontIcon = memory->Create(); - fontIcon->name = memory->Dup(assetName.c_str()); - - const CsvInputStream csv(*file.m_stream); - std::vector dependencies; - std::vector currentRow; - std::vector entries; - std::vector aliases; - auto currentRowIndex = 0u; - - while (csv.NextRow(currentRow)) - { - currentRowIndex++; - PreprocessRow(currentRow); - - if (RowIsEmpty(currentRow)) - continue; - - if (currentRow.size() < COL_COUNT_MIN) - { - std::cout << ErrorPrefix(assetName, currentRowIndex) << "Column count lower than min column count (" << COL_COUNT_MIN << ")" << std::endl; - return true; - } - - int index; - if (!ParseInt(index, currentRow[ROW_INDEX]) || index < 0) - { - std::cout << ErrorPrefix(assetName, currentRowIndex) << "Failed to parse index" << std::endl; - return true; - } - - if (currentRow[ROW_TYPE] == VALUE_TYPE_ICON) - { - FontIconEntry icon{}; - if (!ReadIconRow(currentRow, icon, assetName, currentRowIndex, memory, manager, dependencies)) - return true; - - if (static_cast(index) == entries.size()) - { - entries.push_back(icon); - } - else if (static_cast(index) > entries.size()) - { - entries.reserve(index + 1); - entries[index] = icon; - } - else - { - entries[index] = icon; - } - } - else if (currentRow[ROW_TYPE] == VALUE_TYPE_ALIAS) - { - FontIconAlias alias{}; - if (!ReadAliasRow(currentRow, alias, assetName, currentRowIndex, memory, manager)) - return true; - - if (static_cast(index) == aliases.size()) - { - aliases.push_back(alias); - } - else if (static_cast(index) > aliases.size()) - { - aliases.reserve(index + 1); - aliases[index] = alias; - } - else - { - aliases[index] = alias; - } - } - else - { - std::cout << ErrorPrefix(assetName, currentRowIndex) << "Unknown row type \"" << currentRow[ROW_TYPE] << "\"" << std::endl; - return true; - } - } + if (fontIcon->numEntries > 0) { + fontIcon->fontIconEntry = static_cast(memory->Alloc(sizeof(FontIconEntry) * fontIcon->numEntries)); + for (auto i = 0u; i < entries.size(); i++) + fontIcon->fontIconEntry[i] = entries[i]; + } else + fontIcon->fontIconEntry = nullptr; - fontIcon->numEntries = entries.size(); - fontIcon->numAliasEntries = aliases.size(); + if (fontIcon->numAliasEntries > 0) { + fontIcon->fontIconAlias = static_cast(memory->Alloc(sizeof(FontIconAlias) * fontIcon->numAliasEntries)); + for (auto i = 0u; i < aliases.size(); i++) + fontIcon->fontIconAlias[i] = aliases[i]; + } else + fontIcon->fontIconAlias = nullptr; - if (fontIcon->numEntries > 0) - { - fontIcon->fontIconEntry = static_cast(memory->Alloc(sizeof(FontIconEntry) * fontIcon->numEntries)); - for (auto i = 0u; i < entries.size(); i++) - fontIcon->fontIconEntry[i] = entries[i]; - } - else - fontIcon->fontIconEntry = nullptr; - - if (fontIcon->numAliasEntries > 0) - { - fontIcon->fontIconAlias = static_cast(memory->Alloc(sizeof(FontIconAlias) * fontIcon->numAliasEntries)); - for (auto i = 0u; i < aliases.size(); i++) - fontIcon->fontIconAlias[i] = aliases[i]; - } - else - fontIcon->fontIconAlias = nullptr; - - manager->AddAsset(ASSET_TYPE_FONTICON, assetName, fontIcon); + manager->AddAsset(ASSET_TYPE_FONTICON, assetName, fontIcon); - return true; + return true; } diff --git a/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderFontIcon.h b/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderFontIcon.h index 0ec8f0005..3734169bd 100644 --- a/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderFontIcon.h +++ b/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderFontIcon.h @@ -1,52 +1,51 @@ #pragma once #include -#include #include +#include -#include "Game/T6/T6.h" #include "AssetLoading/BasicAssetLoader.h" #include "AssetLoading/IAssetLoadingManager.h" +#include "Game/T6/T6.h" #include "SearchPath/ISearchPath.h" -namespace T6 -{ - class AssetLoaderFontIcon final : public BasicAssetLoader - { - static constexpr unsigned ROW_INDEX = 0; - static constexpr unsigned ROW_TYPE = 1; - - static constexpr unsigned ROW_ICON_NAME = 2; - static constexpr unsigned ROW_ICON_MATERIAL = 3; - static constexpr unsigned ROW_ICON_SIZE = 4; - static constexpr unsigned ROW_ICON_XSCALE = 5; - static constexpr unsigned ROW_ICON_YSCALE = 6; - - static constexpr unsigned ROW_ALIAS_NAME = 2; - static constexpr unsigned ROW_ALIAS_BUTTON = 3; - - static constexpr const char* VALUE_TYPE_ICON = "icon"; - static constexpr const char* VALUE_TYPE_ALIAS = "alias"; - - static constexpr unsigned COL_COUNT_ICON = 7; - static constexpr unsigned COL_COUNT_ALIAS = 4; - static constexpr unsigned COL_COUNT_MIN = std::min(COL_COUNT_ICON, COL_COUNT_ALIAS); - - static std::string ErrorPrefix(const std::string& assetName, unsigned rowIndex); - static void PreprocessRow(std::vector& row); - static bool RowIsEmpty(const std::vector& row); - - static bool ParseInt(int& value, const std::string& str); - static bool ParseFloat(float& value, const std::string& str); - static bool ParseHashStr(int& value, const std::string& str); - - static bool ReadIconRow(const std::vector& row, FontIconEntry& icon, const std::string& assetName, unsigned rowIndex, MemoryManager* memory, IAssetLoadingManager* manager, - std::vector& dependencies); - static bool ReadAliasRow(const std::vector& row, FontIconAlias& alias, const std::string& assetName, unsigned rowIndex, MemoryManager* memory, IAssetLoadingManager* manager); - - public: - _NODISCARD void* CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) override; - _NODISCARD bool CanLoadFromRaw() const override; - bool LoadFromRaw(const std::string& assetName, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const override; - }; -} +namespace T6 { +class AssetLoaderFontIcon final : public BasicAssetLoader { + static constexpr unsigned ROW_INDEX = 0; + static constexpr unsigned ROW_TYPE = 1; + + static constexpr unsigned ROW_ICON_NAME = 2; + static constexpr unsigned ROW_ICON_MATERIAL = 3; + static constexpr unsigned ROW_ICON_SIZE = 4; + static constexpr unsigned ROW_ICON_XSCALE = 5; + static constexpr unsigned ROW_ICON_YSCALE = 6; + + static constexpr unsigned ROW_ALIAS_NAME = 2; + static constexpr unsigned ROW_ALIAS_BUTTON = 3; + + static constexpr const char *VALUE_TYPE_ICON = "icon"; + static constexpr const char *VALUE_TYPE_ALIAS = "alias"; + + static constexpr unsigned COL_COUNT_ICON = 7; + static constexpr unsigned COL_COUNT_ALIAS = 4; + static constexpr unsigned COL_COUNT_MIN = std::min(COL_COUNT_ICON, COL_COUNT_ALIAS); + + static std::string ErrorPrefix(const std::string &assetName, unsigned rowIndex); + static void PreprocessRow(std::vector &row); + static bool RowIsEmpty(const std::vector &row); + + static bool ParseInt(int &value, const std::string &str); + static bool ParseFloat(float &value, const std::string &str); + static bool ParseHashStr(int &value, const std::string &str); + + static bool ReadIconRow(const std::vector &row, FontIconEntry &icon, const std::string &assetName, unsigned rowIndex, MemoryManager *memory, + IAssetLoadingManager *manager, std::vector &dependencies); + static bool ReadAliasRow(const std::vector &row, FontIconAlias &alias, const std::string &assetName, unsigned rowIndex, MemoryManager *memory, + IAssetLoadingManager *manager); + +public: + _NODISCARD void *CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) override; + _NODISCARD bool CanLoadFromRaw() const override; + bool LoadFromRaw(const std::string &assetName, ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager, Zone *zone) const override; +}; +} // namespace T6 diff --git a/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderLocalizeEntry.cpp b/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderLocalizeEntry.cpp index cd838610a..2e1850ecf 100644 --- a/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderLocalizeEntry.cpp +++ b/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderLocalizeEntry.cpp @@ -2,51 +2,40 @@ #include - #include "Localize/LocalizeCommon.h" #include "Parsing/LocalizeFile/LocalizeFileReader.h" using namespace T6; -XAssetInfoGeneric* AssetLoaderLocalizeEntry::LoadFromGlobalAssetPools(const std::string& assetName) const -{ - return nullptr; -} +XAssetInfoGeneric *AssetLoaderLocalizeEntry::LoadFromGlobalAssetPools(const std::string &assetName) const { return nullptr; } -void* AssetLoaderLocalizeEntry::CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) -{ - return nullptr; -} +void *AssetLoaderLocalizeEntry::CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) { return nullptr; } -bool AssetLoaderLocalizeEntry::CanLoadFromRaw() const -{ - return true; -} +bool AssetLoaderLocalizeEntry::CanLoadFromRaw() const { return true; } -bool AssetLoaderLocalizeEntry::LoadFromRaw(const std::string& assetName, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const -{ - std::string fileName; - { - std::ostringstream str; - str << LocalizeCommon::GetNameOfLanguage(zone->m_language) << "/localizedstrings/" << assetName << ".str"; - fileName = str.str(); - } +bool AssetLoaderLocalizeEntry::LoadFromRaw(const std::string &assetName, ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager, + Zone *zone) const { + std::string fileName; + { + std::ostringstream str; + str << LocalizeCommon::GetNameOfLanguage(zone->m_language) << "/localizedstrings/" << assetName << ".str"; + fileName = str.str(); + } - const auto file = searchPath->Open(fileName); - if (!file.IsOpen()) - return false; + const auto file = searchPath->Open(fileName); + if (!file.IsOpen()) + return false; - LocalizeFileReader reader(*file.m_stream, assetName, zone->m_language); - const auto localizeEntries = reader.ReadLocalizeFile(); + LocalizeFileReader reader(*file.m_stream, assetName, zone->m_language); + const auto localizeEntries = reader.ReadLocalizeFile(); - for(const auto& entry : localizeEntries) - { - auto* localizeEntry = memory->Create(); - localizeEntry->name = memory->Dup(entry.m_key.c_str()); - localizeEntry->value = memory->Dup(entry.m_value.c_str()); + for (const auto &entry : localizeEntries) { + auto *localizeEntry = memory->Create(); + localizeEntry->name = memory->Dup(entry.m_key.c_str()); + localizeEntry->value = memory->Dup(entry.m_value.c_str()); - manager->AddAsset(ASSET_TYPE_LOCALIZE_ENTRY, entry.m_key, localizeEntry); - } + manager->AddAsset(ASSET_TYPE_LOCALIZE_ENTRY, entry.m_key, localizeEntry); + } - return true; + return true; } diff --git a/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderLocalizeEntry.h b/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderLocalizeEntry.h index a20112018..d458f2c08 100644 --- a/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderLocalizeEntry.h +++ b/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderLocalizeEntry.h @@ -1,17 +1,15 @@ #pragma once -#include "Game/T6/T6.h" #include "AssetLoading/BasicAssetLoader.h" #include "AssetLoading/IAssetLoadingManager.h" +#include "Game/T6/T6.h" #include "SearchPath/ISearchPath.h" -namespace T6 -{ - class AssetLoaderLocalizeEntry final : public BasicAssetLoader - { - public: - _NODISCARD XAssetInfoGeneric* LoadFromGlobalAssetPools(const std::string& assetName) const override; - _NODISCARD void* CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) override; - _NODISCARD bool CanLoadFromRaw() const override; - bool LoadFromRaw(const std::string& assetName, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const override; - }; -} +namespace T6 { +class AssetLoaderLocalizeEntry final : public BasicAssetLoader { +public: + _NODISCARD XAssetInfoGeneric *LoadFromGlobalAssetPools(const std::string &assetName) const override; + _NODISCARD void *CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) override; + _NODISCARD bool CanLoadFromRaw() const override; + bool LoadFromRaw(const std::string &assetName, ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager, Zone *zone) const override; +}; +} // namespace T6 diff --git a/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderPhysConstraints.cpp b/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderPhysConstraints.cpp index 6af31c517..2f5a0608a 100644 --- a/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderPhysConstraints.cpp +++ b/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderPhysConstraints.cpp @@ -1,145 +1,126 @@ #include "AssetLoaderPhysConstraints.h" +#include #include #include -#include -#include "Game/T6/ObjConstantsT6.h" -#include "Game/T6/T6.h" #include "Game/T6/InfoString/EnumStrings.h" #include "Game/T6/InfoString/InfoStringToStructConverter.h" #include "Game/T6/InfoString/PhysConstraintsFields.h" +#include "Game/T6/ObjConstantsT6.h" +#include "Game/T6/T6.h" #include "InfoString/InfoString.h" using namespace T6; -namespace T6 -{ - class InfoStringToPhysConstraintsConverter final : public InfoStringToStructConverter - { - protected: - bool ConvertExtensionField(const cspField_t& field, const std::string& value) override - { - switch (static_cast(field.iFieldType)) - { - case CFT_TYPE: - return ConvertEnumInt(value, field.iOffset, s_constraintTypeNames, std::extent::value); - - default: - assert(false); - return false; - } - } - - public: - InfoStringToPhysConstraintsConverter(const InfoString& infoString, PhysConstraints* physConstraints, ZoneScriptStrings& zoneScriptStrings, MemoryManager* memory, IAssetLoadingManager* manager, - const cspField_t* fields, const size_t fieldCount) - : InfoStringToStructConverter(infoString, physConstraints, zoneScriptStrings, memory, manager, fields, fieldCount) - { - } - }; -} - -void AssetLoaderPhysConstraints::CalculatePhysConstraintsFields(PhysConstraints* physConstraints, Zone* zone) -{ - for(auto& constraint : physConstraints->data) - { - constraint.targetname = zone->m_script_strings.AddOrGetScriptString(""); - constraint.target_ent1 = zone->m_script_strings.AddOrGetScriptString(""); - constraint.target_ent2 = zone->m_script_strings.AddOrGetScriptString(""); - constraint.attach_point_type1 = ATTACH_POINT_BONE; - constraint.attach_point_type2 = ATTACH_POINT_BONE; - constraint.target_bone1 = ""; - constraint.target_bone2 = ""; +namespace T6 { +class InfoStringToPhysConstraintsConverter final : public InfoStringToStructConverter { +protected: + bool ConvertExtensionField(const cspField_t &field, const std::string &value) override { + switch (static_cast(field.iFieldType)) { + case CFT_TYPE: + return ConvertEnumInt(value, field.iOffset, s_constraintTypeNames, std::extent::value); + + default: + assert(false); + return false; } - - // count - { - auto foundEnd = false; - for (auto i = 0u; i < std::extent::value; i++) - { - if (physConstraints->data[i].type == CONSTRAINT_NONE) - { - foundEnd = true; - physConstraints->count = i; - break; - } - } - - if (!foundEnd) - physConstraints->count = std::extent::value; + } + +public: + InfoStringToPhysConstraintsConverter(const InfoString &infoString, PhysConstraints *physConstraints, ZoneScriptStrings &zoneScriptStrings, + MemoryManager *memory, IAssetLoadingManager *manager, const cspField_t *fields, const size_t fieldCount) + : InfoStringToStructConverter(infoString, physConstraints, zoneScriptStrings, memory, manager, fields, fieldCount) {} +}; +} // namespace T6 + +void AssetLoaderPhysConstraints::CalculatePhysConstraintsFields(PhysConstraints *physConstraints, Zone *zone) { + for (auto &constraint : physConstraints->data) { + constraint.targetname = zone->m_script_strings.AddOrGetScriptString(""); + constraint.target_ent1 = zone->m_script_strings.AddOrGetScriptString(""); + constraint.target_ent2 = zone->m_script_strings.AddOrGetScriptString(""); + constraint.attach_point_type1 = ATTACH_POINT_BONE; + constraint.attach_point_type2 = ATTACH_POINT_BONE; + constraint.target_bone1 = ""; + constraint.target_bone2 = ""; + } + + // count + { + auto foundEnd = false; + for (auto i = 0u; i < std::extent::value; i++) { + if (physConstraints->data[i].type == CONSTRAINT_NONE) { + foundEnd = true; + physConstraints->count = i; + break; + } } + + if (!foundEnd) + physConstraints->count = std::extent::value; + } } -bool AssetLoaderPhysConstraints::LoadFromInfoString(const InfoString& infoString, const std::string& assetName, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) -{ - auto* physConstraints = memory->Create(); - memset(physConstraints, 0, sizeof(PhysConstraints)); +bool AssetLoaderPhysConstraints::LoadFromInfoString(const InfoString &infoString, const std::string &assetName, MemoryManager *memory, + IAssetLoadingManager *manager, Zone *zone) { + auto *physConstraints = memory->Create(); + memset(physConstraints, 0, sizeof(PhysConstraints)); - InfoStringToPhysConstraintsConverter converter(infoString, physConstraints, zone->m_script_strings, memory, manager, phys_constraints_fields, std::extent::value); - if (!converter.Convert()) - { - std::cout << "Failed to parse phys constraints: \"" << assetName << "\"" << std::endl; - return true; - } + InfoStringToPhysConstraintsConverter converter(infoString, physConstraints, zone->m_script_strings, memory, manager, phys_constraints_fields, + std::extent::value); + if (!converter.Convert()) { + std::cout << "Failed to parse phys constraints: \"" << assetName << "\"" << std::endl; + return true; + } - CalculatePhysConstraintsFields(physConstraints, zone); - physConstraints->name = memory->Dup(assetName.c_str()); + CalculatePhysConstraintsFields(physConstraints, zone); + physConstraints->name = memory->Dup(assetName.c_str()); - auto scrStrings = converter.GetUsedScriptStrings(); - scrStrings.push_back(zone->m_script_strings.AddOrGetScriptString("")); - manager->AddAsset(ASSET_TYPE_PHYSCONSTRAINTS, assetName, physConstraints, converter.GetDependencies(), scrStrings); + auto scrStrings = converter.GetUsedScriptStrings(); + scrStrings.push_back(zone->m_script_strings.AddOrGetScriptString("")); + manager->AddAsset(ASSET_TYPE_PHYSCONSTRAINTS, assetName, physConstraints, converter.GetDependencies(), scrStrings); - return true; + return true; } -void* AssetLoaderPhysConstraints::CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) -{ - auto* physConstraints = memory->Create(); - memset(physConstraints, 0, sizeof(PhysConstraints)); - physConstraints->name = memory->Dup(assetName.c_str()); - return physConstraints; +void *AssetLoaderPhysConstraints::CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) { + auto *physConstraints = memory->Create(); + memset(physConstraints, 0, sizeof(PhysConstraints)); + physConstraints->name = memory->Dup(assetName.c_str()); + return physConstraints; } -bool AssetLoaderPhysConstraints::CanLoadFromGdt() const -{ +bool AssetLoaderPhysConstraints::CanLoadFromGdt() const { return true; } + +bool AssetLoaderPhysConstraints::LoadFromGdt(const std::string &assetName, IGdtQueryable *gdtQueryable, MemoryManager *memory, IAssetLoadingManager *manager, + Zone *zone) const { + auto *gdtEntry = gdtQueryable->GetGdtEntryByGdfAndName(ObjConstants::GDF_FILENAME_PHYS_CONSTRAINTS, assetName); + if (gdtEntry == nullptr) + return false; + + InfoString infoString; + if (!infoString.FromGdtProperties(*gdtEntry)) { + std::cout << "Failed to read phys constraints gdt entry: \"" << assetName << "\"" << std::endl; return true; + } + + return LoadFromInfoString(infoString, assetName, memory, manager, zone); } -bool AssetLoaderPhysConstraints::LoadFromGdt(const std::string& assetName, IGdtQueryable* gdtQueryable, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const -{ - auto* gdtEntry = gdtQueryable->GetGdtEntryByGdfAndName(ObjConstants::GDF_FILENAME_PHYS_CONSTRAINTS, assetName); - if (gdtEntry == nullptr) - return false; - - InfoString infoString; - if (!infoString.FromGdtProperties(*gdtEntry)) - { - std::cout << "Failed to read phys constraints gdt entry: \"" << assetName << "\"" << std::endl; - return true; - } +bool AssetLoaderPhysConstraints::CanLoadFromRaw() const { return true; } - return LoadFromInfoString(infoString, assetName, memory, manager, zone); -} +bool AssetLoaderPhysConstraints::LoadFromRaw(const std::string &assetName, ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager, + Zone *zone) const { + const auto fileName = "physconstraints/" + assetName; + const auto file = searchPath->Open(fileName); + if (!file.IsOpen()) + return false; -bool AssetLoaderPhysConstraints::CanLoadFromRaw() const -{ + InfoString infoString; + if (!infoString.FromStream(ObjConstants::INFO_STRING_PREFIX_PHYS_CONSTRAINTS, *file.m_stream)) { + std::cout << "Failed to read phys constraints raw file: \"" << fileName << "\"" << std::endl; return true; -} - -bool AssetLoaderPhysConstraints::LoadFromRaw(const std::string& assetName, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const -{ - const auto fileName = "physconstraints/" + assetName; - const auto file = searchPath->Open(fileName); - if (!file.IsOpen()) - return false; - - InfoString infoString; - if (!infoString.FromStream(ObjConstants::INFO_STRING_PREFIX_PHYS_CONSTRAINTS, *file.m_stream)) - { - std::cout << "Failed to read phys constraints raw file: \"" << fileName << "\"" << std::endl; - return true; - } + } - return LoadFromInfoString(infoString, assetName, memory, manager, zone); + return LoadFromInfoString(infoString, assetName, memory, manager, zone); } diff --git a/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderPhysConstraints.h b/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderPhysConstraints.h index 8c5176d4f..6f3eb5c2f 100644 --- a/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderPhysConstraints.h +++ b/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderPhysConstraints.h @@ -1,23 +1,21 @@ #pragma once -#include "Game/T6/T6.h" #include "AssetLoading/BasicAssetLoader.h" #include "AssetLoading/IAssetLoadingManager.h" +#include "Game/T6/T6.h" #include "InfoString/InfoString.h" #include "SearchPath/ISearchPath.h" -namespace T6 -{ - class AssetLoaderPhysConstraints final : public BasicAssetLoader - { - static void CalculatePhysConstraintsFields(PhysConstraints* physConstraints, Zone* zone); +namespace T6 { +class AssetLoaderPhysConstraints final : public BasicAssetLoader { + static void CalculatePhysConstraintsFields(PhysConstraints *physConstraints, Zone *zone); - static bool LoadFromInfoString(const InfoString& infoString, const std::string& assetName, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone); + static bool LoadFromInfoString(const InfoString &infoString, const std::string &assetName, MemoryManager *memory, IAssetLoadingManager *manager, Zone *zone); - public: - _NODISCARD void* CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) override; - _NODISCARD bool CanLoadFromGdt() const override; - bool LoadFromGdt(const std::string& assetName, IGdtQueryable* gdtQueryable, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const override; - _NODISCARD bool CanLoadFromRaw() const override; - bool LoadFromRaw(const std::string& assetName, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const override; - }; -} +public: + _NODISCARD void *CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) override; + _NODISCARD bool CanLoadFromGdt() const override; + bool LoadFromGdt(const std::string &assetName, IGdtQueryable *gdtQueryable, MemoryManager *memory, IAssetLoadingManager *manager, Zone *zone) const override; + _NODISCARD bool CanLoadFromRaw() const override; + bool LoadFromRaw(const std::string &assetName, ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager, Zone *zone) const override; +}; +} // namespace T6 diff --git a/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderPhysPreset.cpp b/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderPhysPreset.cpp index 26aae9762..ab6d38177 100644 --- a/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderPhysPreset.cpp +++ b/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderPhysPreset.cpp @@ -1,128 +1,113 @@ #include "AssetLoaderPhysPreset.h" #include +#include #include #include -#include #include -#include "Game/T6/ObjConstantsT6.h" -#include "Game/T6/T6.h" #include "Game/T6/InfoString/InfoStringToStructConverter.h" #include "Game/T6/InfoString/PhysPresetFields.h" +#include "Game/T6/ObjConstantsT6.h" +#include "Game/T6/T6.h" #include "InfoString/InfoString.h" using namespace T6; -namespace T6 -{ - class InfoStringToPhysPresetConverter final : public InfoStringToStructConverter - { - protected: - bool ConvertExtensionField(const cspField_t& field, const std::string& value) override - { - assert(false); - return false; - } - - public: - InfoStringToPhysPresetConverter(const InfoString& infoString, PhysPresetInfo* physPreset, ZoneScriptStrings& zoneScriptStrings, MemoryManager* memory, IAssetLoadingManager* manager, - const cspField_t* fields, const size_t fieldCount) - : InfoStringToStructConverter(infoString, physPreset, zoneScriptStrings, memory, manager, fields, fieldCount) - { - } - }; -} - -void AssetLoaderPhysPreset::CopyFromPhysPresetInfo(const PhysPresetInfo* physPresetInfo, PhysPreset* physPreset) -{ - physPreset->mass = std::clamp(physPresetInfo->mass, 1.0f, 2000.0f) * 0.001f; - physPreset->bounce = physPresetInfo->bounce; - - if (physPresetInfo->isFrictionInfinity != 0) - physPreset->friction = std::numeric_limits::infinity(); - else - physPreset->friction = physPresetInfo->friction; - - physPreset->bulletForceScale = physPresetInfo->bulletForceScale; - physPreset->explosiveForceScale = physPresetInfo->explosiveForceScale; - physPreset->piecesSpreadFraction = physPresetInfo->piecesSpreadFraction; - physPreset->piecesUpwardVelocity = physPresetInfo->piecesUpwardVelocity; - physPreset->canFloat = physPresetInfo->canFloat; - physPreset->gravityScale = std::clamp(physPresetInfo->gravityScale, 0.01f, 10.0f); - physPreset->centerOfMassOffset = physPresetInfo->centerOfMassOffset; - physPreset->buoyancyBoxMin = physPresetInfo->buoyancyBoxMin; - physPreset->buoyancyBoxMax = physPresetInfo->buoyancyBoxMax; +namespace T6 { +class InfoStringToPhysPresetConverter final : public InfoStringToStructConverter { +protected: + bool ConvertExtensionField(const cspField_t &field, const std::string &value) override { + assert(false); + return false; + } + +public: + InfoStringToPhysPresetConverter(const InfoString &infoString, PhysPresetInfo *physPreset, ZoneScriptStrings &zoneScriptStrings, MemoryManager *memory, + IAssetLoadingManager *manager, const cspField_t *fields, const size_t fieldCount) + : InfoStringToStructConverter(infoString, physPreset, zoneScriptStrings, memory, manager, fields, fieldCount) {} +}; +} // namespace T6 + +void AssetLoaderPhysPreset::CopyFromPhysPresetInfo(const PhysPresetInfo *physPresetInfo, PhysPreset *physPreset) { + physPreset->mass = std::clamp(physPresetInfo->mass, 1.0f, 2000.0f) * 0.001f; + physPreset->bounce = physPresetInfo->bounce; + + if (physPresetInfo->isFrictionInfinity != 0) + physPreset->friction = std::numeric_limits::infinity(); + else + physPreset->friction = physPresetInfo->friction; + + physPreset->bulletForceScale = physPresetInfo->bulletForceScale; + physPreset->explosiveForceScale = physPresetInfo->explosiveForceScale; + physPreset->piecesSpreadFraction = physPresetInfo->piecesSpreadFraction; + physPreset->piecesUpwardVelocity = physPresetInfo->piecesUpwardVelocity; + physPreset->canFloat = physPresetInfo->canFloat; + physPreset->gravityScale = std::clamp(physPresetInfo->gravityScale, 0.01f, 10.0f); + physPreset->centerOfMassOffset = physPresetInfo->centerOfMassOffset; + physPreset->buoyancyBoxMin = physPresetInfo->buoyancyBoxMin; + physPreset->buoyancyBoxMax = physPresetInfo->buoyancyBoxMax; } -bool AssetLoaderPhysPreset::LoadFromInfoString(const InfoString& infoString, const std::string& assetName, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) -{ - const auto presetInfo = std::make_unique(); - memset(presetInfo.get(), 0, sizeof(PhysPresetInfo)); - InfoStringToPhysPresetConverter converter(infoString, presetInfo.get(), zone->m_script_strings, memory, manager, phys_preset_fields, std::extent::value); - if (!converter.Convert()) - { - std::cout << "Failed to parse phys preset: \"" << assetName << "\"" << std::endl; - return true; - } +bool AssetLoaderPhysPreset::LoadFromInfoString(const InfoString &infoString, const std::string &assetName, MemoryManager *memory, IAssetLoadingManager *manager, + Zone *zone) { + const auto presetInfo = std::make_unique(); + memset(presetInfo.get(), 0, sizeof(PhysPresetInfo)); + InfoStringToPhysPresetConverter converter(infoString, presetInfo.get(), zone->m_script_strings, memory, manager, phys_preset_fields, + std::extent::value); + if (!converter.Convert()) { + std::cout << "Failed to parse phys preset: \"" << assetName << "\"" << std::endl; + return true; + } - auto* physPreset = memory->Create(); + auto *physPreset = memory->Create(); - CopyFromPhysPresetInfo(presetInfo.get(), physPreset); - physPreset->name = memory->Dup(assetName.c_str()); + CopyFromPhysPresetInfo(presetInfo.get(), physPreset); + physPreset->name = memory->Dup(assetName.c_str()); - manager->AddAsset(ASSET_TYPE_PHYSPRESET, assetName, physPreset, converter.GetDependencies(), converter.GetUsedScriptStrings()); + manager->AddAsset(ASSET_TYPE_PHYSPRESET, assetName, physPreset, converter.GetDependencies(), converter.GetUsedScriptStrings()); - return true; + return true; } -void* AssetLoaderPhysPreset::CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) -{ - auto* physPreset = memory->Create(); - memset(physPreset, 0, sizeof(PhysPreset)); - physPreset->name = memory->Dup(assetName.c_str()); - return physPreset; +void *AssetLoaderPhysPreset::CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) { + auto *physPreset = memory->Create(); + memset(physPreset, 0, sizeof(PhysPreset)); + physPreset->name = memory->Dup(assetName.c_str()); + return physPreset; } -bool AssetLoaderPhysPreset::CanLoadFromGdt() const -{ - return true; -} +bool AssetLoaderPhysPreset::CanLoadFromGdt() const { return true; } -bool AssetLoaderPhysPreset::LoadFromGdt(const std::string& assetName, IGdtQueryable* gdtQueryable, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const -{ - auto* gdtEntry = gdtQueryable->GetGdtEntryByGdfAndName(ObjConstants::GDF_FILENAME_PHYS_PRESET, assetName); - if (gdtEntry == nullptr) - return false; +bool AssetLoaderPhysPreset::LoadFromGdt(const std::string &assetName, IGdtQueryable *gdtQueryable, MemoryManager *memory, IAssetLoadingManager *manager, + Zone *zone) const { + auto *gdtEntry = gdtQueryable->GetGdtEntryByGdfAndName(ObjConstants::GDF_FILENAME_PHYS_PRESET, assetName); + if (gdtEntry == nullptr) + return false; - InfoString infoString; - if (!infoString.FromGdtProperties(*gdtEntry)) - { - std::cout << "Failed to read phys preset gdt entry: \"" << assetName << "\"" << std::endl; - return true; - } + InfoString infoString; + if (!infoString.FromGdtProperties(*gdtEntry)) { + std::cout << "Failed to read phys preset gdt entry: \"" << assetName << "\"" << std::endl; + return true; + } - return LoadFromInfoString(infoString, assetName, memory, manager, zone); + return LoadFromInfoString(infoString, assetName, memory, manager, zone); } -bool AssetLoaderPhysPreset::CanLoadFromRaw() const -{ +bool AssetLoaderPhysPreset::CanLoadFromRaw() const { return true; } + +bool AssetLoaderPhysPreset::LoadFromRaw(const std::string &assetName, ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager, + Zone *zone) const { + const auto fileName = "physic/" + assetName; + const auto file = searchPath->Open(fileName); + if (!file.IsOpen()) + return false; + + InfoString infoString; + if (!infoString.FromStream(ObjConstants::INFO_STRING_PREFIX_PHYS_PRESET, *file.m_stream)) { + std::cout << "Failed to read phys preset raw file: \"" << fileName << "\"" << std::endl; return true; -} + } -bool AssetLoaderPhysPreset::LoadFromRaw(const std::string& assetName, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const -{ - const auto fileName = "physic/" + assetName; - const auto file = searchPath->Open(fileName); - if (!file.IsOpen()) - return false; - - InfoString infoString; - if (!infoString.FromStream(ObjConstants::INFO_STRING_PREFIX_PHYS_PRESET, *file.m_stream)) - { - std::cout << "Failed to read phys preset raw file: \"" << fileName << "\"" << std::endl; - return true; - } - - return LoadFromInfoString(infoString, assetName, memory, manager, zone); + return LoadFromInfoString(infoString, assetName, memory, manager, zone); } diff --git a/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderPhysPreset.h b/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderPhysPreset.h index 79bcb672e..92e904556 100644 --- a/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderPhysPreset.h +++ b/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderPhysPreset.h @@ -1,23 +1,21 @@ #pragma once -#include "Game/T6/T6.h" #include "AssetLoading/BasicAssetLoader.h" #include "AssetLoading/IAssetLoadingManager.h" +#include "Game/T6/T6.h" #include "InfoString/InfoString.h" #include "SearchPath/ISearchPath.h" -namespace T6 -{ - class AssetLoaderPhysPreset final : public BasicAssetLoader - { - static void CopyFromPhysPresetInfo(const PhysPresetInfo* physPresetInfo, PhysPreset* physPreset); +namespace T6 { +class AssetLoaderPhysPreset final : public BasicAssetLoader { + static void CopyFromPhysPresetInfo(const PhysPresetInfo *physPresetInfo, PhysPreset *physPreset); - static bool LoadFromInfoString(const InfoString& infoString, const std::string& assetName, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone); + static bool LoadFromInfoString(const InfoString &infoString, const std::string &assetName, MemoryManager *memory, IAssetLoadingManager *manager, Zone *zone); - public: - _NODISCARD void* CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) override; - _NODISCARD bool CanLoadFromGdt() const override; - bool LoadFromGdt(const std::string& assetName, IGdtQueryable* gdtQueryable, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const override; - _NODISCARD bool CanLoadFromRaw() const override; - bool LoadFromRaw(const std::string& assetName, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const override; - }; -} +public: + _NODISCARD void *CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) override; + _NODISCARD bool CanLoadFromGdt() const override; + bool LoadFromGdt(const std::string &assetName, IGdtQueryable *gdtQueryable, MemoryManager *memory, IAssetLoadingManager *manager, Zone *zone) const override; + _NODISCARD bool CanLoadFromRaw() const override; + bool LoadFromRaw(const std::string &assetName, ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager, Zone *zone) const override; +}; +} // namespace T6 diff --git a/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderQdb.cpp b/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderQdb.cpp index 5508d459b..7b36bd797 100644 --- a/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderQdb.cpp +++ b/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderQdb.cpp @@ -7,37 +7,33 @@ using namespace T6; -void* AssetLoaderQdb::CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) -{ - auto* qdb = memory->Create(); - memset(qdb, 0, sizeof(Qdb)); - qdb->name = memory->Dup(assetName.c_str()); - return qdb; +void *AssetLoaderQdb::CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) { + auto *qdb = memory->Create(); + memset(qdb, 0, sizeof(Qdb)); + qdb->name = memory->Dup(assetName.c_str()); + return qdb; } -bool AssetLoaderQdb::CanLoadFromRaw() const -{ - return true; -} +bool AssetLoaderQdb::CanLoadFromRaw() const { return true; } -bool AssetLoaderQdb::LoadFromRaw(const std::string& assetName, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const -{ - const auto file = searchPath->Open(assetName); - if (!file.IsOpen()) - return false; +bool AssetLoaderQdb::LoadFromRaw(const std::string &assetName, ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager, + Zone *zone) const { + const auto file = searchPath->Open(assetName); + if (!file.IsOpen()) + return false; - auto* qdb = memory->Create(); - qdb->name = memory->Dup(assetName.c_str()); - qdb->len = static_cast(file.m_length); + auto *qdb = memory->Create(); + qdb->name = memory->Dup(assetName.c_str()); + qdb->len = static_cast(file.m_length); - auto* fileBuffer = static_cast(memory->Alloc(static_cast(file.m_length + 1))); - file.m_stream->read(fileBuffer, file.m_length); - if (file.m_stream->gcount() != file.m_length) - return false; - fileBuffer[qdb->len] = '\0'; + auto *fileBuffer = static_cast(memory->Alloc(static_cast(file.m_length + 1))); + file.m_stream->read(fileBuffer, file.m_length); + if (file.m_stream->gcount() != file.m_length) + return false; + fileBuffer[qdb->len] = '\0'; - qdb->buffer = static_cast(fileBuffer); - manager->AddAsset(ASSET_TYPE_QDB, assetName, qdb); + qdb->buffer = static_cast(fileBuffer); + manager->AddAsset(ASSET_TYPE_QDB, assetName, qdb); - return true; + return true; } diff --git a/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderQdb.h b/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderQdb.h index 5a4ea3558..ab1a209e1 100644 --- a/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderQdb.h +++ b/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderQdb.h @@ -1,16 +1,14 @@ #pragma once -#include "Game/T6/T6.h" #include "AssetLoading/BasicAssetLoader.h" #include "AssetLoading/IAssetLoadingManager.h" +#include "Game/T6/T6.h" #include "SearchPath/ISearchPath.h" -namespace T6 -{ - class AssetLoaderQdb final : public BasicAssetLoader - { - public: - _NODISCARD void* CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) override; - _NODISCARD bool CanLoadFromRaw() const override; - bool LoadFromRaw(const std::string& assetName, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const override; - }; -} +namespace T6 { +class AssetLoaderQdb final : public BasicAssetLoader { +public: + _NODISCARD void *CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) override; + _NODISCARD bool CanLoadFromRaw() const override; + bool LoadFromRaw(const std::string &assetName, ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager, Zone *zone) const override; +}; +} // namespace T6 diff --git a/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderRawFile.cpp b/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderRawFile.cpp index e4ce97897..a04997a59 100644 --- a/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderRawFile.cpp +++ b/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderRawFile.cpp @@ -7,37 +7,33 @@ using namespace T6; -void* AssetLoaderRawFile::CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) -{ - auto* rawFile = memory->Create(); - memset(rawFile, 0, sizeof(RawFile)); - rawFile->name = memory->Dup(assetName.c_str()); - return rawFile; +void *AssetLoaderRawFile::CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) { + auto *rawFile = memory->Create(); + memset(rawFile, 0, sizeof(RawFile)); + rawFile->name = memory->Dup(assetName.c_str()); + return rawFile; } -bool AssetLoaderRawFile::CanLoadFromRaw() const -{ - return true; -} +bool AssetLoaderRawFile::CanLoadFromRaw() const { return true; } -bool AssetLoaderRawFile::LoadFromRaw(const std::string& assetName, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const -{ - const auto file = searchPath->Open(assetName); - if (!file.IsOpen()) - return false; +bool AssetLoaderRawFile::LoadFromRaw(const std::string &assetName, ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager, + Zone *zone) const { + const auto file = searchPath->Open(assetName); + if (!file.IsOpen()) + return false; - auto* rawFile = memory->Create(); - rawFile->name = memory->Dup(assetName.c_str()); - rawFile->len = static_cast(file.m_length); + auto *rawFile = memory->Create(); + rawFile->name = memory->Dup(assetName.c_str()); + rawFile->len = static_cast(file.m_length); - auto* fileBuffer = static_cast(memory->Alloc(static_cast(file.m_length + 1))); - file.m_stream->read(fileBuffer, file.m_length); - if (file.m_stream->gcount() != file.m_length) - return false; - fileBuffer[rawFile->len] = '\0'; + auto *fileBuffer = static_cast(memory->Alloc(static_cast(file.m_length + 1))); + file.m_stream->read(fileBuffer, file.m_length); + if (file.m_stream->gcount() != file.m_length) + return false; + fileBuffer[rawFile->len] = '\0'; - rawFile->buffer = static_cast(fileBuffer); - manager->AddAsset(ASSET_TYPE_RAWFILE, assetName, rawFile); + rawFile->buffer = static_cast(fileBuffer); + manager->AddAsset(ASSET_TYPE_RAWFILE, assetName, rawFile); - return true; + return true; } diff --git a/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderRawFile.h b/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderRawFile.h index f233aecf3..b93d42df5 100644 --- a/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderRawFile.h +++ b/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderRawFile.h @@ -1,16 +1,14 @@ #pragma once -#include "Game/T6/T6.h" #include "AssetLoading/BasicAssetLoader.h" #include "AssetLoading/IAssetLoadingManager.h" +#include "Game/T6/T6.h" #include "SearchPath/ISearchPath.h" -namespace T6 -{ - class AssetLoaderRawFile final : public BasicAssetLoader - { - public: - _NODISCARD void* CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) override; - _NODISCARD bool CanLoadFromRaw() const override; - bool LoadFromRaw(const std::string& assetName, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const override; - }; -} +namespace T6 { +class AssetLoaderRawFile final : public BasicAssetLoader { +public: + _NODISCARD void *CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) override; + _NODISCARD bool CanLoadFromRaw() const override; + bool LoadFromRaw(const std::string &assetName, ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager, Zone *zone) const override; +}; +} // namespace T6 diff --git a/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderScriptParseTree.cpp b/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderScriptParseTree.cpp index eeaffa417..0bb94c950 100644 --- a/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderScriptParseTree.cpp +++ b/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderScriptParseTree.cpp @@ -7,37 +7,33 @@ using namespace T6; -void* AssetLoaderScriptParseTree::CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) -{ - auto* scriptParseTree = memory->Create(); - memset(scriptParseTree, 0, sizeof(ScriptParseTree)); - scriptParseTree->name = memory->Dup(assetName.c_str()); - return scriptParseTree; +void *AssetLoaderScriptParseTree::CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) { + auto *scriptParseTree = memory->Create(); + memset(scriptParseTree, 0, sizeof(ScriptParseTree)); + scriptParseTree->name = memory->Dup(assetName.c_str()); + return scriptParseTree; } -bool AssetLoaderScriptParseTree::CanLoadFromRaw() const -{ - return true; -} +bool AssetLoaderScriptParseTree::CanLoadFromRaw() const { return true; } -bool AssetLoaderScriptParseTree::LoadFromRaw(const std::string& assetName, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const -{ - const auto file = searchPath->Open(assetName); - if (!file.IsOpen()) - return false; +bool AssetLoaderScriptParseTree::LoadFromRaw(const std::string &assetName, ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager, + Zone *zone) const { + const auto file = searchPath->Open(assetName); + if (!file.IsOpen()) + return false; - auto* scriptParseTree = memory->Create(); - scriptParseTree->name = memory->Dup(assetName.c_str()); - scriptParseTree->len = static_cast(file.m_length); + auto *scriptParseTree = memory->Create(); + scriptParseTree->name = memory->Dup(assetName.c_str()); + scriptParseTree->len = static_cast(file.m_length); - auto* fileBuffer = static_cast(memory->Alloc(static_cast(file.m_length + 1))); - file.m_stream->read(fileBuffer, file.m_length); - if (file.m_stream->gcount() != file.m_length) - return false; - fileBuffer[scriptParseTree->len] = '\0'; + auto *fileBuffer = static_cast(memory->Alloc(static_cast(file.m_length + 1))); + file.m_stream->read(fileBuffer, file.m_length); + if (file.m_stream->gcount() != file.m_length) + return false; + fileBuffer[scriptParseTree->len] = '\0'; - scriptParseTree->buffer = static_cast(fileBuffer); - manager->AddAsset(ASSET_TYPE_SCRIPTPARSETREE, assetName, scriptParseTree); + scriptParseTree->buffer = static_cast(fileBuffer); + manager->AddAsset(ASSET_TYPE_SCRIPTPARSETREE, assetName, scriptParseTree); - return true; + return true; } diff --git a/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderScriptParseTree.h b/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderScriptParseTree.h index 6092b6a82..3a22997cc 100644 --- a/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderScriptParseTree.h +++ b/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderScriptParseTree.h @@ -1,16 +1,14 @@ #pragma once -#include "Game/T6/T6.h" #include "AssetLoading/BasicAssetLoader.h" #include "AssetLoading/IAssetLoadingManager.h" +#include "Game/T6/T6.h" #include "SearchPath/ISearchPath.h" -namespace T6 -{ - class AssetLoaderScriptParseTree final : public BasicAssetLoader - { - public: - _NODISCARD void* CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) override; - _NODISCARD bool CanLoadFromRaw() const override; - bool LoadFromRaw(const std::string& assetName, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const override; - }; -} +namespace T6 { +class AssetLoaderScriptParseTree final : public BasicAssetLoader { +public: + _NODISCARD void *CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) override; + _NODISCARD bool CanLoadFromRaw() const override; + bool LoadFromRaw(const std::string &assetName, ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager, Zone *zone) const override; +}; +} // namespace T6 diff --git a/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderSlug.cpp b/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderSlug.cpp index b1d425555..95fd88b12 100644 --- a/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderSlug.cpp +++ b/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderSlug.cpp @@ -7,37 +7,33 @@ using namespace T6; -void* AssetLoaderSlug::CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) -{ - auto* slug = memory->Create(); - memset(slug, 0, sizeof(Slug)); - slug->name = memory->Dup(assetName.c_str()); - return slug; +void *AssetLoaderSlug::CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) { + auto *slug = memory->Create(); + memset(slug, 0, sizeof(Slug)); + slug->name = memory->Dup(assetName.c_str()); + return slug; } -bool AssetLoaderSlug::CanLoadFromRaw() const -{ - return true; -} +bool AssetLoaderSlug::CanLoadFromRaw() const { return true; } -bool AssetLoaderSlug::LoadFromRaw(const std::string& assetName, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const -{ - const auto file = searchPath->Open(assetName); - if (!file.IsOpen()) - return false; +bool AssetLoaderSlug::LoadFromRaw(const std::string &assetName, ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager, + Zone *zone) const { + const auto file = searchPath->Open(assetName); + if (!file.IsOpen()) + return false; - auto* slug = memory->Create(); - slug->name = memory->Dup(assetName.c_str()); - slug->len = static_cast(file.m_length); + auto *slug = memory->Create(); + slug->name = memory->Dup(assetName.c_str()); + slug->len = static_cast(file.m_length); - auto* fileBuffer = static_cast(memory->Alloc(static_cast(file.m_length + 1))); - file.m_stream->read(fileBuffer, file.m_length); - if (file.m_stream->gcount() != file.m_length) - return false; - fileBuffer[slug->len] = '\0'; + auto *fileBuffer = static_cast(memory->Alloc(static_cast(file.m_length + 1))); + file.m_stream->read(fileBuffer, file.m_length); + if (file.m_stream->gcount() != file.m_length) + return false; + fileBuffer[slug->len] = '\0'; - slug->buffer = static_cast(fileBuffer); - manager->AddAsset(ASSET_TYPE_SLUG, assetName, slug); + slug->buffer = static_cast(fileBuffer); + manager->AddAsset(ASSET_TYPE_SLUG, assetName, slug); - return true; + return true; } diff --git a/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderSlug.h b/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderSlug.h index 83f2d030e..c04f5a6e1 100644 --- a/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderSlug.h +++ b/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderSlug.h @@ -1,16 +1,14 @@ #pragma once -#include "Game/T6/T6.h" #include "AssetLoading/BasicAssetLoader.h" #include "AssetLoading/IAssetLoadingManager.h" +#include "Game/T6/T6.h" #include "SearchPath/ISearchPath.h" -namespace T6 -{ - class AssetLoaderSlug final : public BasicAssetLoader - { - public: - _NODISCARD void* CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) override; - _NODISCARD bool CanLoadFromRaw() const override; - bool LoadFromRaw(const std::string& assetName, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const override; - }; -} +namespace T6 { +class AssetLoaderSlug final : public BasicAssetLoader { +public: + _NODISCARD void *CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) override; + _NODISCARD bool CanLoadFromRaw() const override; + bool LoadFromRaw(const std::string &assetName, ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager, Zone *zone) const override; +}; +} // namespace T6 diff --git a/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderStringTable.cpp b/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderStringTable.cpp index a1acde615..73cbe5eed 100644 --- a/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderStringTable.cpp +++ b/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderStringTable.cpp @@ -9,84 +9,74 @@ using namespace T6; -void* AssetLoaderStringTable::CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) -{ - auto* stringTable = memory->Create(); - memset(stringTable, 0, sizeof(StringTable)); - stringTable->name = memory->Dup(assetName.c_str()); - return stringTable; +void *AssetLoaderStringTable::CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) { + auto *stringTable = memory->Create(); + memset(stringTable, 0, sizeof(StringTable)); + stringTable->name = memory->Dup(assetName.c_str()); + return stringTable; } -bool AssetLoaderStringTable::CanLoadFromRaw() const -{ - return true; -} - -bool AssetLoaderStringTable::LoadFromRaw(const std::string& assetName, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const -{ - const auto file = searchPath->Open(assetName); - if (!file.IsOpen()) - return false; - - auto* stringTable = memory->Create(); - stringTable->name = memory->Dup(assetName.c_str()); - - std::vector> csvLines; - std::vector currentLine; - auto maxCols = 0u; - const CsvInputStream csv(*file.m_stream); - - while (csv.NextRow(currentLine)) - { - if (currentLine.size() > maxCols) - maxCols = currentLine.size(); - csvLines.emplace_back(std::move(currentLine)); - currentLine = std::vector(); +bool AssetLoaderStringTable::CanLoadFromRaw() const { return true; } + +bool AssetLoaderStringTable::LoadFromRaw(const std::string &assetName, ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager, + Zone *zone) const { + const auto file = searchPath->Open(assetName); + if (!file.IsOpen()) + return false; + + auto *stringTable = memory->Create(); + stringTable->name = memory->Dup(assetName.c_str()); + + std::vector> csvLines; + std::vector currentLine; + auto maxCols = 0u; + const CsvInputStream csv(*file.m_stream); + + while (csv.NextRow(currentLine)) { + if (currentLine.size() > maxCols) + maxCols = currentLine.size(); + csvLines.emplace_back(std::move(currentLine)); + currentLine = std::vector(); + } + + stringTable->columnCount = static_cast(maxCols); + stringTable->rowCount = static_cast(csvLines.size()); + const auto cellCount = static_cast(stringTable->rowCount) * static_cast(stringTable->columnCount); + + if (cellCount) { + stringTable->values = static_cast(memory->Alloc(sizeof(StringTableCell) * cellCount)); + stringTable->cellIndex = static_cast(memory->Alloc(sizeof(int16_t) * cellCount)); + + for (auto c = 0u; c < cellCount; c++) + stringTable->cellIndex[c] = static_cast(c); + + for (auto row = 0u; row < csvLines.size(); row++) { + const auto &rowValues = csvLines[row]; + for (auto col = 0u; col < maxCols; col++) { + auto &cell = stringTable->values[row * maxCols + col]; + if (col >= rowValues.size() || rowValues[col].empty()) + cell.string = ""; + else + cell.string = memory->Dup(rowValues[col].c_str()); + + cell.hash = Common::Com_HashString(cell.string); + } } - stringTable->columnCount = static_cast(maxCols); - stringTable->rowCount = static_cast(csvLines.size()); - const auto cellCount = static_cast(stringTable->rowCount) * static_cast(stringTable->columnCount); - - if (cellCount) - { - stringTable->values = static_cast(memory->Alloc(sizeof(StringTableCell) * cellCount)); - stringTable->cellIndex = static_cast(memory->Alloc(sizeof(int16_t) * cellCount)); - - for (auto c = 0u; c < cellCount; c++) - stringTable->cellIndex[c] = static_cast(c); - - for (auto row = 0u; row < csvLines.size(); row++) - { - const auto& rowValues = csvLines[row]; - for (auto col = 0u; col < maxCols; col++) - { - auto& cell = stringTable->values[row * maxCols + col]; - if (col >= rowValues.size() || rowValues[col].empty()) - cell.string = ""; - else - cell.string = memory->Dup(rowValues[col].c_str()); - - cell.hash = Common::Com_HashString(cell.string); - } - } - - std::sort(&stringTable->cellIndex[0], &stringTable->cellIndex[cellCount - 1], [stringTable, maxCols](const int16_t a, const int16_t b) - { - auto compareResult = stringTable->values[a].hash - stringTable->values[b].hash; - if (compareResult == 0) - compareResult = a % maxCols - b % maxCols; - return compareResult < 0; - }); - } + std::sort(&stringTable->cellIndex[0], &stringTable->cellIndex[cellCount - 1], [stringTable, maxCols](const int16_t a, const int16_t b) { + auto compareResult = stringTable->values[a].hash - stringTable->values[b].hash; + if (compareResult == 0) + compareResult = a % maxCols - b % maxCols; + return compareResult < 0; + }); + } - else - { - stringTable->values = nullptr; - stringTable->cellIndex = nullptr; - } + else { + stringTable->values = nullptr; + stringTable->cellIndex = nullptr; + } - manager->AddAsset(ASSET_TYPE_STRINGTABLE, assetName, stringTable); + manager->AddAsset(ASSET_TYPE_STRINGTABLE, assetName, stringTable); - return true; + return true; } diff --git a/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderStringTable.h b/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderStringTable.h index 40be6fafd..a33d35a4b 100644 --- a/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderStringTable.h +++ b/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderStringTable.h @@ -1,16 +1,14 @@ #pragma once -#include "Game/T6/T6.h" #include "AssetLoading/BasicAssetLoader.h" #include "AssetLoading/IAssetLoadingManager.h" +#include "Game/T6/T6.h" #include "SearchPath/ISearchPath.h" -namespace T6 -{ - class AssetLoaderStringTable final : public BasicAssetLoader - { - public: - _NODISCARD void* CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) override; - _NODISCARD bool CanLoadFromRaw() const override; - bool LoadFromRaw(const std::string& assetName, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const override; - }; -} +namespace T6 { +class AssetLoaderStringTable final : public BasicAssetLoader { +public: + _NODISCARD void *CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) override; + _NODISCARD bool CanLoadFromRaw() const override; + bool LoadFromRaw(const std::string &assetName, ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager, Zone *zone) const override; +}; +} // namespace T6 diff --git a/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderTracer.cpp b/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderTracer.cpp index d786d25e0..3e598ab60 100644 --- a/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderTracer.cpp +++ b/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderTracer.cpp @@ -1,112 +1,97 @@ #include "AssetLoaderTracer.h" +#include #include #include -#include -#include "Game/T6/ObjConstantsT6.h" -#include "Game/T6/T6.h" #include "Game/T6/InfoString/EnumStrings.h" #include "Game/T6/InfoString/InfoStringToStructConverter.h" #include "Game/T6/InfoString/TracerFields.h" +#include "Game/T6/ObjConstantsT6.h" +#include "Game/T6/T6.h" #include "InfoString/InfoString.h" using namespace T6; -namespace T6 -{ - class InfoStringToTracerConverter final : public InfoStringToStructConverter - { - protected: - bool ConvertExtensionField(const cspField_t& field, const std::string& value) override - { - switch (static_cast(field.iFieldType)) - { - case TFT_TRACERTYPE: - return ConvertEnumInt(value, field.iOffset, tracerTypeNames, std::extent::value); - - case TFT_NUM_FIELD_TYPES: - default: - assert(false); - return false; - } - } - - public: - InfoStringToTracerConverter(const InfoString& infoString, TracerDef* tracer, ZoneScriptStrings& zoneScriptStrings, MemoryManager* memory, IAssetLoadingManager* manager, - const cspField_t* fields, const size_t fieldCount) - : InfoStringToStructConverter(infoString, tracer, zoneScriptStrings, memory, manager, fields, fieldCount) - { - } - }; -} - -bool AssetLoaderTracer::LoadFromInfoString(const InfoString& infoString, const std::string& assetName, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) -{ - auto* tracer = memory->Create(); - memset(tracer, 0, sizeof(TracerDef)); - - InfoStringToTracerConverter converter(infoString, tracer, zone->m_script_strings, memory, manager, tracer_fields, std::extent::value); - if (!converter.Convert()) - { - std::cout << "Failed to parse tracer: \"" << assetName << "\"" << std::endl; - return true; +namespace T6 { +class InfoStringToTracerConverter final : public InfoStringToStructConverter { +protected: + bool ConvertExtensionField(const cspField_t &field, const std::string &value) override { + switch (static_cast(field.iFieldType)) { + case TFT_TRACERTYPE: + return ConvertEnumInt(value, field.iOffset, tracerTypeNames, std::extent::value); + + case TFT_NUM_FIELD_TYPES: + default: + assert(false); + return false; } + } + +public: + InfoStringToTracerConverter(const InfoString &infoString, TracerDef *tracer, ZoneScriptStrings &zoneScriptStrings, MemoryManager *memory, + IAssetLoadingManager *manager, const cspField_t *fields, const size_t fieldCount) + : InfoStringToStructConverter(infoString, tracer, zoneScriptStrings, memory, manager, fields, fieldCount) {} +}; +} // namespace T6 + +bool AssetLoaderTracer::LoadFromInfoString(const InfoString &infoString, const std::string &assetName, MemoryManager *memory, IAssetLoadingManager *manager, + Zone *zone) { + auto *tracer = memory->Create(); + memset(tracer, 0, sizeof(TracerDef)); + + InfoStringToTracerConverter converter(infoString, tracer, zone->m_script_strings, memory, manager, tracer_fields, + std::extent::value); + if (!converter.Convert()) { + std::cout << "Failed to parse tracer: \"" << assetName << "\"" << std::endl; + return true; + } - tracer->name = memory->Dup(assetName.c_str()); + tracer->name = memory->Dup(assetName.c_str()); - manager->AddAsset(ASSET_TYPE_TRACER, assetName, tracer, converter.GetDependencies(), converter.GetUsedScriptStrings()); + manager->AddAsset(ASSET_TYPE_TRACER, assetName, tracer, converter.GetDependencies(), converter.GetUsedScriptStrings()); - return true; + return true; } -void* AssetLoaderTracer::CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) -{ - auto* tracer = memory->Create(); - memset(tracer, 0, sizeof(TracerDef)); - tracer->name = memory->Dup(assetName.c_str()); - return tracer; +void *AssetLoaderTracer::CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) { + auto *tracer = memory->Create(); + memset(tracer, 0, sizeof(TracerDef)); + tracer->name = memory->Dup(assetName.c_str()); + return tracer; } -bool AssetLoaderTracer::CanLoadFromGdt() const -{ +bool AssetLoaderTracer::CanLoadFromGdt() const { return true; } + +bool AssetLoaderTracer::LoadFromGdt(const std::string &assetName, IGdtQueryable *gdtQueryable, MemoryManager *memory, IAssetLoadingManager *manager, + Zone *zone) const { + auto *gdtEntry = gdtQueryable->GetGdtEntryByGdfAndName(ObjConstants::GDF_FILENAME_TRACER, assetName); + if (gdtEntry == nullptr) + return false; + + InfoString infoString; + if (!infoString.FromGdtProperties(*gdtEntry)) { + std::cout << "Failed to read tracer gdt entry: \"" << assetName << "\"" << std::endl; return true; + } + + return LoadFromInfoString(infoString, assetName, memory, manager, zone); } -bool AssetLoaderTracer::LoadFromGdt(const std::string& assetName, IGdtQueryable* gdtQueryable, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const -{ - auto* gdtEntry = gdtQueryable->GetGdtEntryByGdfAndName(ObjConstants::GDF_FILENAME_TRACER, assetName); - if (gdtEntry == nullptr) - return false; - - InfoString infoString; - if (!infoString.FromGdtProperties(*gdtEntry)) - { - std::cout << "Failed to read tracer gdt entry: \"" << assetName << "\"" << std::endl; - return true; - } +bool AssetLoaderTracer::CanLoadFromRaw() const { return true; } - return LoadFromInfoString(infoString, assetName, memory, manager, zone); -} +bool AssetLoaderTracer::LoadFromRaw(const std::string &assetName, ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager, + Zone *zone) const { + const auto fileName = "tracer/" + assetName; + const auto file = searchPath->Open(fileName); + if (!file.IsOpen()) + return false; -bool AssetLoaderTracer::CanLoadFromRaw() const -{ + InfoString infoString; + if (!infoString.FromStream(ObjConstants::INFO_STRING_PREFIX_TRACER, *file.m_stream)) { + std::cout << "Failed to read tracer raw file: \"" << fileName << "\"" << std::endl; return true; -} - -bool AssetLoaderTracer::LoadFromRaw(const std::string& assetName, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const -{ - const auto fileName = "tracer/" + assetName; - const auto file = searchPath->Open(fileName); - if (!file.IsOpen()) - return false; - - InfoString infoString; - if (!infoString.FromStream(ObjConstants::INFO_STRING_PREFIX_TRACER, *file.m_stream)) - { - std::cout << "Failed to read tracer raw file: \"" << fileName << "\"" << std::endl; - return true; - } + } - return LoadFromInfoString(infoString, assetName, memory, manager, zone); + return LoadFromInfoString(infoString, assetName, memory, manager, zone); } diff --git a/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderTracer.h b/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderTracer.h index 18a18623a..a1261d01b 100644 --- a/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderTracer.h +++ b/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderTracer.h @@ -1,21 +1,19 @@ #pragma once -#include "Game/T6/T6.h" #include "AssetLoading/BasicAssetLoader.h" #include "AssetLoading/IAssetLoadingManager.h" +#include "Game/T6/T6.h" #include "InfoString/InfoString.h" #include "SearchPath/ISearchPath.h" -namespace T6 -{ - class AssetLoaderTracer final : public BasicAssetLoader - { - static bool LoadFromInfoString(const InfoString& infoString, const std::string& assetName, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone); +namespace T6 { +class AssetLoaderTracer final : public BasicAssetLoader { + static bool LoadFromInfoString(const InfoString &infoString, const std::string &assetName, MemoryManager *memory, IAssetLoadingManager *manager, Zone *zone); - public: - _NODISCARD void* CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) override; - _NODISCARD bool CanLoadFromGdt() const override; - bool LoadFromGdt(const std::string& assetName, IGdtQueryable* gdtQueryable, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const override; - _NODISCARD bool CanLoadFromRaw() const override; - bool LoadFromRaw(const std::string& assetName, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const override; - }; -} +public: + _NODISCARD void *CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) override; + _NODISCARD bool CanLoadFromGdt() const override; + bool LoadFromGdt(const std::string &assetName, IGdtQueryable *gdtQueryable, MemoryManager *memory, IAssetLoadingManager *manager, Zone *zone) const override; + _NODISCARD bool CanLoadFromRaw() const override; + bool LoadFromRaw(const std::string &assetName, ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager, Zone *zone) const override; +}; +} // namespace T6 diff --git a/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderVehicle.cpp b/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderVehicle.cpp index 25778260e..495b878a6 100644 --- a/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderVehicle.cpp +++ b/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderVehicle.cpp @@ -3,172 +3,149 @@ #include #include -#include "Game/T6/ObjConstantsT6.h" -#include "Game/T6/T6.h" #include "Game/T6/InfoString/EnumStrings.h" #include "Game/T6/InfoString/InfoStringToStructConverter.h" #include "Game/T6/InfoString/VehicleFields.h" +#include "Game/T6/ObjConstantsT6.h" +#include "Game/T6/T6.h" #include "InfoString/InfoString.h" #include "Pool/GlobalAssetPool.h" using namespace T6; -namespace T6 -{ - class InfoStringToVehicleConverter final : public InfoStringToStructConverter - { - protected: - bool ConvertExtensionField(const cspField_t& field, const std::string& value) override - { - switch (static_cast(field.iFieldType)) - { - case VFT_TYPE: - return ConvertEnumInt(value, field.iOffset, s_vehicleClassNames, std::extent::value); - - case VFT_CAMERAMODE: - return ConvertEnumInt(value, field.iOffset, s_vehicleCameraModes, std::extent::value); - - case VFT_TRACTION_TYPE: - return ConvertEnumInt(value, field.iOffset, s_tractionTypeNames, std::extent::value); - - case VFT_MPH_TO_INCHES_PER_SECOND: - { - char* endPtr; - *reinterpret_cast(reinterpret_cast(m_structure) + field.iOffset) = strtof(value.c_str(), &endPtr) * 17.6f; - - if (endPtr != &value[value.size()]) - { - std::cout << "Failed to parse value \"" << value << "\" as mph" << std::endl; - return false; - } - - return true; - } - - case VFT_POUNDS_TO_GAME_MASS: - { - char* endPtr; - *reinterpret_cast(reinterpret_cast(m_structure) + field.iOffset) = strtof(value.c_str(), &endPtr) * 0.001f; - - if (endPtr != &value[value.size()]) - { - std::cout << "Failed to parse value \"" << value << "\" as pounds" << std::endl; - return false; - } - - return true; - } - - case VFT_TEAM: - { - if (value == "axis") - { - *reinterpret_cast(reinterpret_cast(m_structure) + field.iOffset) = TEAM_AXIS; - return true; - } - - if (value == "allies") - { - *reinterpret_cast(reinterpret_cast(m_structure) + field.iOffset) = TEAM_ALLIES; - return true; - } - - if (value == "neutral") - { - *reinterpret_cast(reinterpret_cast(m_structure) + field.iOffset) = TEAM_FOUR; - return true; - } - - *reinterpret_cast(reinterpret_cast(m_structure) + field.iOffset) = TEAM_BAD; - std::cout << "Failed to parse value \"" << value << "\" as team" << std::endl; - return false; - } - - case VFT_KEY_BINDING: - case VFT_GRAPH: - case VFT_WIIUCONTROLOVERRIDE: - case VFT_NUM: - default: - assert(false); - return false; - } - } - - public: - InfoStringToVehicleConverter(const InfoString& infoString, VehicleDef* vehicleDef, ZoneScriptStrings& zoneScriptStrings, MemoryManager* memory, IAssetLoadingManager* manager, - const cspField_t* fields, const size_t fieldCount) - : InfoStringToStructConverter(infoString, vehicleDef, zoneScriptStrings, memory, manager, fields, fieldCount) - { - } - }; -} - -bool AssetLoaderVehicle::LoadFromInfoString(const InfoString& infoString, const std::string& assetName, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) -{ - auto* vehicleDef = memory->Create(); - memset(vehicleDef, 0, sizeof(VehicleDef)); +namespace T6 { +class InfoStringToVehicleConverter final : public InfoStringToStructConverter { +protected: + bool ConvertExtensionField(const cspField_t &field, const std::string &value) override { + switch (static_cast(field.iFieldType)) { + case VFT_TYPE: + return ConvertEnumInt(value, field.iOffset, s_vehicleClassNames, std::extent::value); - InfoStringToVehicleConverter converter(infoString, vehicleDef, zone->m_script_strings, memory, manager, vehicle_fields, std::extent::value); - if (!converter.Convert()) - { - std::cout << "Failed to parse vehicle: \"" << assetName << "\"" << std::endl; - return true; - } + case VFT_CAMERAMODE: + return ConvertEnumInt(value, field.iOffset, s_vehicleCameraModes, std::extent::value); - vehicleDef->name = memory->Dup(assetName.c_str()); + case VFT_TRACTION_TYPE: + return ConvertEnumInt(value, field.iOffset, s_tractionTypeNames, std::extent::value); - manager->AddAsset(ASSET_TYPE_VEHICLEDEF, assetName, vehicleDef, converter.GetDependencies(), converter.GetUsedScriptStrings()); + case VFT_MPH_TO_INCHES_PER_SECOND: { + char *endPtr; + *reinterpret_cast(reinterpret_cast(m_structure) + field.iOffset) = strtof(value.c_str(), &endPtr) * 17.6f; - return true; -} + if (endPtr != &value[value.size()]) { + std::cout << "Failed to parse value \"" << value << "\" as mph" << std::endl; + return false; + } -void* AssetLoaderVehicle::CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) -{ - auto* vehicleDef = memory->Create(); - memset(vehicleDef, 0, sizeof(VehicleDef)); - vehicleDef->name = memory->Dup(assetName.c_str()); - return vehicleDef; -} + return true; + } -bool AssetLoaderVehicle::CanLoadFromGdt() const -{ - return true; -} + case VFT_POUNDS_TO_GAME_MASS: { + char *endPtr; + *reinterpret_cast(reinterpret_cast(m_structure) + field.iOffset) = strtof(value.c_str(), &endPtr) * 0.001f; -bool AssetLoaderVehicle::LoadFromGdt(const std::string& assetName, IGdtQueryable* gdtQueryable, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const -{ - auto* gdtEntry = gdtQueryable->GetGdtEntryByGdfAndName(ObjConstants::GDF_FILENAME_VEHICLE, assetName); - if (gdtEntry == nullptr) + if (endPtr != &value[value.size()]) { + std::cout << "Failed to parse value \"" << value << "\" as pounds" << std::endl; return false; + } + + return true; + } + + case VFT_TEAM: { + if (value == "axis") { + *reinterpret_cast(reinterpret_cast(m_structure) + field.iOffset) = TEAM_AXIS; + return true; + } - InfoString infoString; - if (!infoString.FromGdtProperties(*gdtEntry)) - { - std::cout << "Failed to read vehicle gdt entry: \"" << assetName << "\"" << std::endl; + if (value == "allies") { + *reinterpret_cast(reinterpret_cast(m_structure) + field.iOffset) = TEAM_ALLIES; return true; + } + + if (value == "neutral") { + *reinterpret_cast(reinterpret_cast(m_structure) + field.iOffset) = TEAM_FOUR; + return true; + } + + *reinterpret_cast(reinterpret_cast(m_structure) + field.iOffset) = TEAM_BAD; + std::cout << "Failed to parse value \"" << value << "\" as team" << std::endl; + return false; + } + + case VFT_KEY_BINDING: + case VFT_GRAPH: + case VFT_WIIUCONTROLOVERRIDE: + case VFT_NUM: + default: + assert(false); + return false; } + } + +public: + InfoStringToVehicleConverter(const InfoString &infoString, VehicleDef *vehicleDef, ZoneScriptStrings &zoneScriptStrings, MemoryManager *memory, + IAssetLoadingManager *manager, const cspField_t *fields, const size_t fieldCount) + : InfoStringToStructConverter(infoString, vehicleDef, zoneScriptStrings, memory, manager, fields, fieldCount) {} +}; +} // namespace T6 + +bool AssetLoaderVehicle::LoadFromInfoString(const InfoString &infoString, const std::string &assetName, MemoryManager *memory, IAssetLoadingManager *manager, + Zone *zone) { + auto *vehicleDef = memory->Create(); + memset(vehicleDef, 0, sizeof(VehicleDef)); + + InfoStringToVehicleConverter converter(infoString, vehicleDef, zone->m_script_strings, memory, manager, vehicle_fields, + std::extent::value); + if (!converter.Convert()) { + std::cout << "Failed to parse vehicle: \"" << assetName << "\"" << std::endl; + return true; + } + + vehicleDef->name = memory->Dup(assetName.c_str()); + + manager->AddAsset(ASSET_TYPE_VEHICLEDEF, assetName, vehicleDef, converter.GetDependencies(), converter.GetUsedScriptStrings()); + + return true; +} - return LoadFromInfoString(infoString, assetName, memory, manager, zone); +void *AssetLoaderVehicle::CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) { + auto *vehicleDef = memory->Create(); + memset(vehicleDef, 0, sizeof(VehicleDef)); + vehicleDef->name = memory->Dup(assetName.c_str()); + return vehicleDef; } -bool AssetLoaderVehicle::CanLoadFromRaw() const -{ +bool AssetLoaderVehicle::CanLoadFromGdt() const { return true; } + +bool AssetLoaderVehicle::LoadFromGdt(const std::string &assetName, IGdtQueryable *gdtQueryable, MemoryManager *memory, IAssetLoadingManager *manager, + Zone *zone) const { + auto *gdtEntry = gdtQueryable->GetGdtEntryByGdfAndName(ObjConstants::GDF_FILENAME_VEHICLE, assetName); + if (gdtEntry == nullptr) + return false; + + InfoString infoString; + if (!infoString.FromGdtProperties(*gdtEntry)) { + std::cout << "Failed to read vehicle gdt entry: \"" << assetName << "\"" << std::endl; return true; + } + + return LoadFromInfoString(infoString, assetName, memory, manager, zone); } -bool AssetLoaderVehicle::LoadFromRaw(const std::string& assetName, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const -{ - const auto fileName = "vehicles/" + assetName; - const auto file = searchPath->Open(fileName); - if (!file.IsOpen()) - return false; +bool AssetLoaderVehicle::CanLoadFromRaw() const { return true; } - InfoString infoString; - if (!infoString.FromStream(ObjConstants::INFO_STRING_PREFIX_VEHICLE, *file.m_stream)) - { - std::cout << "Failed to read vehicle raw file: \"" << fileName << "\"" << std::endl; - return true; - } +bool AssetLoaderVehicle::LoadFromRaw(const std::string &assetName, ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager, + Zone *zone) const { + const auto fileName = "vehicles/" + assetName; + const auto file = searchPath->Open(fileName); + if (!file.IsOpen()) + return false; + + InfoString infoString; + if (!infoString.FromStream(ObjConstants::INFO_STRING_PREFIX_VEHICLE, *file.m_stream)) { + std::cout << "Failed to read vehicle raw file: \"" << fileName << "\"" << std::endl; + return true; + } - return LoadFromInfoString(infoString, assetName, memory, manager, zone); + return LoadFromInfoString(infoString, assetName, memory, manager, zone); } diff --git a/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderVehicle.h b/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderVehicle.h index 360562588..1c8c53a47 100644 --- a/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderVehicle.h +++ b/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderVehicle.h @@ -1,21 +1,19 @@ #pragma once -#include "Game/T6/T6.h" #include "AssetLoading/BasicAssetLoader.h" #include "AssetLoading/IAssetLoadingManager.h" +#include "Game/T6/T6.h" #include "InfoString/InfoString.h" #include "SearchPath/ISearchPath.h" -namespace T6 -{ - class AssetLoaderVehicle final : public BasicAssetLoader - { - static bool LoadFromInfoString(const InfoString& infoString, const std::string& assetName, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone); +namespace T6 { +class AssetLoaderVehicle final : public BasicAssetLoader { + static bool LoadFromInfoString(const InfoString &infoString, const std::string &assetName, MemoryManager *memory, IAssetLoadingManager *manager, Zone *zone); - public: - _NODISCARD void* CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) override; - _NODISCARD bool CanLoadFromGdt() const override; - bool LoadFromGdt(const std::string& assetName, IGdtQueryable* gdtQueryable, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const override; - _NODISCARD bool CanLoadFromRaw() const override; - bool LoadFromRaw(const std::string& assetName, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const override; - }; -} +public: + _NODISCARD void *CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) override; + _NODISCARD bool CanLoadFromGdt() const override; + bool LoadFromGdt(const std::string &assetName, IGdtQueryable *gdtQueryable, MemoryManager *memory, IAssetLoadingManager *manager, Zone *zone) const override; + _NODISCARD bool CanLoadFromRaw() const override; + bool LoadFromRaw(const std::string &assetName, ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager, Zone *zone) const override; +}; +} // namespace T6 diff --git a/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderWeapon.cpp b/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderWeapon.cpp index ed7fcf9a8..97987c008 100644 --- a/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderWeapon.cpp +++ b/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderWeapon.cpp @@ -1,584 +1,519 @@ #include "AssetLoaderWeapon.h" +#include #include #include -#include - #include "AssetLoaderWeaponAttachmentUnique.h" -#include "Utils/ClassUtils.h" -#include "Game/T6/ObjConstantsT6.h" -#include "Game/T6/T6.h" #include "Game/T6/InfoString/EnumStrings.h" #include "Game/T6/InfoString/InfoStringToStructConverter.h" #include "Game/T6/InfoString/WeaponFields.h" +#include "Game/T6/ObjConstantsT6.h" +#include "Game/T6/T6.h" #include "InfoString/InfoString.h" +#include "Utils/ClassUtils.h" using namespace T6; -namespace T6 -{ - class InfoStringToWeaponConverter final : public InfoStringToStructConverter - { - bool ConvertHideTags(const cspField_t& field, const std::string& value) - { - std::vector valueArray; - if (!ParseAsArray(value, valueArray)) - { - std::cout << "Failed to parse hide tags as array" << std::endl; - return false; - } - - if (valueArray.size() > std::extent::value) - { - std::cout << "Cannot have more than " << std::extent::value << " hide tags!" << std::endl; - return false; - } - - auto* hideTags = reinterpret_cast(reinterpret_cast(m_structure) + field.iOffset); - auto currentHideTag = 0u; - - if (valueArray.size() < std::extent::value) - { - m_used_script_string_list.emplace(m_zone_script_strings.AddOrGetScriptString("")); - } - - for (; currentHideTag < valueArray.size(); currentHideTag++) - { - const auto scrString = m_zone_script_strings.AddOrGetScriptString(valueArray[currentHideTag]); - hideTags[currentHideTag] = scrString; - m_used_script_string_list.emplace(scrString); - } - - for (; currentHideTag < std::extent::value; currentHideTag++) - { - hideTags[currentHideTag] = m_zone_script_strings.GetScriptString(""); - } - - return true; - } +namespace T6 { +class InfoStringToWeaponConverter final : public InfoStringToStructConverter { + bool ConvertHideTags(const cspField_t &field, const std::string &value) { + std::vector valueArray; + if (!ParseAsArray(value, valueArray)) { + std::cout << "Failed to parse hide tags as array" << std::endl; + return false; + } - _NODISCARD bool ConvertBounceSounds(const cspField_t& field, const std::string& value) const - { - auto*** bounceSound = reinterpret_cast(reinterpret_cast(m_structure) + field.iOffset); - if (value.empty()) - { - *bounceSound = nullptr; - return true; - } - - assert(std::extent::value == SURF_TYPE_NUM); - *bounceSound = static_cast(m_memory->Alloc(sizeof(const char*) * SURF_TYPE_NUM)); - for (auto i = 0u; i < SURF_TYPE_NUM; i++) - { - const auto currentBounceSound = value + bounceSoundSuffixes[i]; - (*bounceSound)[i] = m_memory->Dup(currentBounceSound.c_str()); - } - return true; - } + if (valueArray.size() > std::extent::value) { + std::cout << "Cannot have more than " << std::extent::value << " hide tags!" << std::endl; + return false; + } - _NODISCARD bool ConvertNotetrackSoundMap(const cspField_t& field, const std::string& value) - { - std::vector> pairs; - if (!ParseAsPairs(value, pairs)) - { - std::cout << "Failed to parse notetracksoundmap as pairs" << std::endl; - return false; - } - - if (pairs.size() > std::extent::value) - { - std::cout << "Cannot have more than " << std::extent::value << " notetracksoundmap entries!" << std::endl; - return false; - } - - auto* keys = reinterpret_cast(reinterpret_cast(m_structure) + field.iOffset); - auto* values = &keys[std::extent::value]; - auto currentEntryNum = 0u; - - if (pairs.size() < std::extent::value) - { - m_used_script_string_list.emplace(m_zone_script_strings.AddOrGetScriptString("")); - } - - for (; currentEntryNum < pairs.size(); currentEntryNum++) - { - keys[currentEntryNum] = m_zone_script_strings.AddOrGetScriptString(pairs[currentEntryNum].first); - m_used_script_string_list.emplace(keys[currentEntryNum]); - - values[currentEntryNum] = m_zone_script_strings.AddOrGetScriptString(pairs[currentEntryNum].second); - m_used_script_string_list.emplace(values[currentEntryNum]); - } - - for (; currentEntryNum < std::extent::value; currentEntryNum++) - { - const auto emptyScr = m_zone_script_strings.GetScriptString(""); - keys[currentEntryNum] = emptyScr; - values[currentEntryNum] = emptyScr; - } - - return true; - } + auto *hideTags = reinterpret_cast(reinterpret_cast(m_structure) + field.iOffset); + auto currentHideTag = 0u; + + if (valueArray.size() < std::extent::value) { + m_used_script_string_list.emplace(m_zone_script_strings.AddOrGetScriptString("")); + } - _NODISCARD bool ConvertWeaponCamo(const cspField_t& field, const std::string& value) - { - if (value.empty()) - { - *reinterpret_cast(reinterpret_cast(m_structure) + field.iOffset) = nullptr; - return true; - } + for (; currentHideTag < valueArray.size(); currentHideTag++) { + const auto scrString = m_zone_script_strings.AddOrGetScriptString(valueArray[currentHideTag]); + hideTags[currentHideTag] = scrString; + m_used_script_string_list.emplace(scrString); + } - auto* camo = m_loading_manager->LoadDependency(ASSET_TYPE_WEAPON_CAMO, value); + for (; currentHideTag < std::extent::value; currentHideTag++) { + hideTags[currentHideTag] = m_zone_script_strings.GetScriptString(""); + } - if (camo == nullptr) - { - std::cout << "Failed to load camo asset \"" << value << "\"" << std::endl; - return false; - } + return true; + } - m_dependencies.emplace(camo); - *reinterpret_cast(reinterpret_cast(m_structure) + field.iOffset) = camo->m_ptr; + _NODISCARD bool ConvertBounceSounds(const cspField_t &field, const std::string &value) const { + auto ***bounceSound = reinterpret_cast(reinterpret_cast(m_structure) + field.iOffset); + if (value.empty()) { + *bounceSound = nullptr; + return true; + } - return true; - } + assert(std::extent::value == SURF_TYPE_NUM); + *bounceSound = static_cast(m_memory->Alloc(sizeof(const char *) * SURF_TYPE_NUM)); + for (auto i = 0u; i < SURF_TYPE_NUM; i++) { + const auto currentBounceSound = value + bounceSoundSuffixes[i]; + (*bounceSound)[i] = m_memory->Dup(currentBounceSound.c_str()); + } + return true; + } - _NODISCARD bool ConvertAttachments(const cspField_t& field, const std::string& value) - { - std::vector valueArray; - if (!ParseAsArray(value, valueArray)) - { - std::cout << "Failed to parse attachments as array" << std::endl; - return false; - } - - auto** attachments = reinterpret_cast(reinterpret_cast(m_structure) + field.iOffset); - - for (const auto& attachmentName : valueArray) - { - auto* attachmentAssetInfo = m_loading_manager->LoadDependency(ASSET_TYPE_ATTACHMENT, attachmentName); - if (attachmentAssetInfo == nullptr) - { - std::cout << "Failed to load attachment asset \"" << attachmentName << "\"" << std::endl; - return false; - } - - auto* attachmentAsset = static_cast(attachmentAssetInfo->m_ptr); - - if (static_cast(attachmentAsset->attachmentType) >= ATTACHMENT_TYPE_COUNT) - { - std::cout << "Invalid attachment type " << attachmentAsset->attachmentType << " for attachment asset \"" << attachmentName << "\"" << std::endl; - return false; - } - - if (attachments[attachmentAsset->attachmentType] != nullptr) - { - std::cout << "Already loaded attachment with same type " << attachmentAsset->attachmentType - << ": \"" << attachments[attachmentAsset->attachmentType]->szInternalName << "\", \"" - << attachmentName << "\"" << std::endl; - return false; - } - - attachments[attachmentAsset->attachmentType] = attachmentAsset; - m_dependencies.emplace(attachmentAssetInfo); - } - - return true; - } + _NODISCARD bool ConvertNotetrackSoundMap(const cspField_t &field, const std::string &value) { + std::vector> pairs; + if (!ParseAsPairs(value, pairs)) { + std::cout << "Failed to parse notetracksoundmap as pairs" << std::endl; + return false; + } + + if (pairs.size() > std::extent::value) { + std::cout << "Cannot have more than " << std::extent::value << " notetracksoundmap entries!" << std::endl; + return false; + } + + auto *keys = reinterpret_cast(reinterpret_cast(m_structure) + field.iOffset); + auto *values = &keys[std::extent::value]; + auto currentEntryNum = 0u; + + if (pairs.size() < std::extent::value) { + m_used_script_string_list.emplace(m_zone_script_strings.AddOrGetScriptString("")); + } + + for (; currentEntryNum < pairs.size(); currentEntryNum++) { + keys[currentEntryNum] = m_zone_script_strings.AddOrGetScriptString(pairs[currentEntryNum].first); + m_used_script_string_list.emplace(keys[currentEntryNum]); + + values[currentEntryNum] = m_zone_script_strings.AddOrGetScriptString(pairs[currentEntryNum].second); + m_used_script_string_list.emplace(values[currentEntryNum]); + } + + for (; currentEntryNum < std::extent::value; currentEntryNum++) { + const auto emptyScr = m_zone_script_strings.GetScriptString(""); + keys[currentEntryNum] = emptyScr; + values[currentEntryNum] = emptyScr; + } + + return true; + } + + _NODISCARD bool ConvertWeaponCamo(const cspField_t &field, const std::string &value) { + if (value.empty()) { + *reinterpret_cast(reinterpret_cast(m_structure) + field.iOffset) = nullptr; + return true; + } + + auto *camo = m_loading_manager->LoadDependency(ASSET_TYPE_WEAPON_CAMO, value); + + if (camo == nullptr) { + std::cout << "Failed to load camo asset \"" << value << "\"" << std::endl; + return false; + } + + m_dependencies.emplace(camo); + *reinterpret_cast(reinterpret_cast(m_structure) + field.iOffset) = camo->m_ptr; + + return true; + } + + _NODISCARD bool ConvertAttachments(const cspField_t &field, const std::string &value) { + std::vector valueArray; + if (!ParseAsArray(value, valueArray)) { + std::cout << "Failed to parse attachments as array" << std::endl; + return false; + } + + auto **attachments = reinterpret_cast(reinterpret_cast(m_structure) + field.iOffset); - _NODISCARD static bool HasMoreThanOneAttachmentSetInMask(const int mask) - { - // Check if int has more than 1 bit set - return (mask & (mask - 1)) != 0; + for (const auto &attachmentName : valueArray) { + auto *attachmentAssetInfo = m_loading_manager->LoadDependency(ASSET_TYPE_ATTACHMENT, attachmentName); + if (attachmentAssetInfo == nullptr) { + std::cout << "Failed to load attachment asset \"" << attachmentName << "\"" << std::endl; + return false; + } + + auto *attachmentAsset = static_cast(attachmentAssetInfo->m_ptr); + + if (static_cast(attachmentAsset->attachmentType) >= ATTACHMENT_TYPE_COUNT) { + std::cout << "Invalid attachment type " << attachmentAsset->attachmentType << " for attachment asset \"" << attachmentName << "\"" << std::endl; + return false; + } + + if (attachments[attachmentAsset->attachmentType] != nullptr) { + std::cout << "Already loaded attachment with same type " << attachmentAsset->attachmentType << ": \"" + << attachments[attachmentAsset->attachmentType]->szInternalName << "\", \"" << attachmentName << "\"" << std::endl; + return false; + } + + attachments[attachmentAsset->attachmentType] = attachmentAsset; + m_dependencies.emplace(attachmentAssetInfo); + } + + return true; + } + + _NODISCARD static bool HasMoreThanOneAttachmentSetInMask(const int mask) { + // Check if int has more than 1 bit set + return (mask & (mask - 1)) != 0; + } + + _NODISCARD bool ConvertAttachmentUniques(const cspField_t &field, const std::string &value) { + std::vector valueArray; + if (!ParseAsArray(value, valueArray)) { + std::cout << "Failed to parse attachment uniques as array" << std::endl; + return false; + } + + auto **attachmentUniques = reinterpret_cast(reinterpret_cast(m_structure) + field.iOffset); + auto attachmentCombinationIndex = std::extent::value; + + for (const auto &attachmentUniqueName : valueArray) { + auto *attachmentUniqueAssetInfo = m_loading_manager->LoadDependency(ASSET_TYPE_ATTACHMENT_UNIQUE, attachmentUniqueName); + if (attachmentUniqueAssetInfo == nullptr) { + std::cout << "Failed to load attachment unique asset \"" << attachmentUniqueName << "\"" << std::endl; + return false; + } + + auto *attachmentUniqueAsset = static_cast(attachmentUniqueAssetInfo->m_ptr); + + if (HasMoreThanOneAttachmentSetInMask(attachmentUniqueAsset->combinedAttachmentTypeMask)) { + if (attachmentCombinationIndex >= std::extent::value) { + std::cout << "Cannot have more than " + << (std::extent::value - std::extent::value) + << " combined attachment attachment unique entries!" << std::endl; + return false; } - _NODISCARD bool ConvertAttachmentUniques(const cspField_t& field, const std::string& value) - { - std::vector valueArray; - if (!ParseAsArray(value, valueArray)) - { - std::cout << "Failed to parse attachment uniques as array" << std::endl; - return false; - } - - auto** attachmentUniques = reinterpret_cast(reinterpret_cast(m_structure) + field.iOffset); - auto attachmentCombinationIndex = std::extent::value; - - for (const auto& attachmentUniqueName : valueArray) - { - auto* attachmentUniqueAssetInfo = m_loading_manager->LoadDependency(ASSET_TYPE_ATTACHMENT_UNIQUE, attachmentUniqueName); - if (attachmentUniqueAssetInfo == nullptr) - { - std::cout << "Failed to load attachment unique asset \"" << attachmentUniqueName << "\"" << std::endl; - return false; - } - - auto* attachmentUniqueAsset = static_cast(attachmentUniqueAssetInfo->m_ptr); - - if (HasMoreThanOneAttachmentSetInMask(attachmentUniqueAsset->combinedAttachmentTypeMask)) - { - if (attachmentCombinationIndex >= std::extent::value) - { - std::cout << "Cannot have more than " - << (std::extent::value - std::extent::value) - << " combined attachment attachment unique entries!" << std::endl; - return false; - } - - attachmentUniques[attachmentCombinationIndex++] = attachmentUniqueAsset; - m_dependencies.emplace(attachmentUniqueAssetInfo); - } - else - { - if (static_cast(attachmentUniqueAsset->attachmentType) >= ATTACHMENT_TYPE_COUNT) - { - std::cout << "Invalid attachment type " << attachmentUniqueAsset->attachmentType << " for attachment unique asset \"" << attachmentUniqueName << "\"" << std::endl; - return false; - } - - if (attachmentUniques[attachmentUniqueAsset->attachmentType] != nullptr) - { - std::cout << "Already loaded attachment unique with same type " << attachmentUniqueAsset->attachmentType - << ": \"" << attachmentUniques[attachmentUniqueAsset->attachmentType]->szInternalName << "\", \"" - << attachmentUniqueName << "\"" << std::endl; - return false; - } - - attachmentUniques[attachmentUniqueAsset->attachmentType] = attachmentUniqueAsset; - m_dependencies.emplace(attachmentUniqueAssetInfo); - } - } - - return true; + attachmentUniques[attachmentCombinationIndex++] = attachmentUniqueAsset; + m_dependencies.emplace(attachmentUniqueAssetInfo); + } else { + if (static_cast(attachmentUniqueAsset->attachmentType) >= ATTACHMENT_TYPE_COUNT) { + std::cout << "Invalid attachment type " << attachmentUniqueAsset->attachmentType << " for attachment unique asset \"" << attachmentUniqueName << "\"" + << std::endl; + return false; } - protected: - bool ConvertExtensionField(const cspField_t& field, const std::string& value) override - { - switch (static_cast(field.iFieldType)) - { - case WFT_WEAPONTYPE: - return ConvertEnumInt(value, field.iOffset, szWeapTypeNames, std::extent::value); + if (attachmentUniques[attachmentUniqueAsset->attachmentType] != nullptr) { + std::cout << "Already loaded attachment unique with same type " << attachmentUniqueAsset->attachmentType << ": \"" + << attachmentUniques[attachmentUniqueAsset->attachmentType]->szInternalName << "\", \"" << attachmentUniqueName << "\"" << std::endl; + return false; + } - case WFT_WEAPONCLASS: - return ConvertEnumInt(value, field.iOffset, szWeapClassNames, std::extent::value); + attachmentUniques[attachmentUniqueAsset->attachmentType] = attachmentUniqueAsset; + m_dependencies.emplace(attachmentUniqueAssetInfo); + } + } - case WFT_OVERLAYRETICLE: - return ConvertEnumInt(value, field.iOffset, szWeapOverlayReticleNames, std::extent::value); + return true; + } - case WFT_PENETRATE_TYPE: - return ConvertEnumInt(value, field.iOffset, penetrateTypeNames, std::extent::value); +protected: + bool ConvertExtensionField(const cspField_t &field, const std::string &value) override { + switch (static_cast(field.iFieldType)) { + case WFT_WEAPONTYPE: + return ConvertEnumInt(value, field.iOffset, szWeapTypeNames, std::extent::value); - case WFT_IMPACT_TYPE: - return ConvertEnumInt(value, field.iOffset, impactTypeNames, std::extent::value); + case WFT_WEAPONCLASS: + return ConvertEnumInt(value, field.iOffset, szWeapClassNames, std::extent::value); - case WFT_STANCE: - return ConvertEnumInt(value, field.iOffset, szWeapStanceNames, std::extent::value); + case WFT_OVERLAYRETICLE: + return ConvertEnumInt(value, field.iOffset, szWeapOverlayReticleNames, std::extent::value); - case WFT_PROJ_EXPLOSION: - return ConvertEnumInt(value, field.iOffset, szProjectileExplosionNames, std::extent::value); + case WFT_PENETRATE_TYPE: + return ConvertEnumInt(value, field.iOffset, penetrateTypeNames, std::extent::value); - case WFT_OFFHAND_CLASS: - return ConvertEnumInt(value, field.iOffset, offhandClassNames, std::extent::value); + case WFT_IMPACT_TYPE: + return ConvertEnumInt(value, field.iOffset, impactTypeNames, std::extent::value); - case WFT_OFFHAND_SLOT: - return ConvertEnumInt(value, field.iOffset, offhandSlotNames, std::extent::value); + case WFT_STANCE: + return ConvertEnumInt(value, field.iOffset, szWeapStanceNames, std::extent::value); - case WFT_ANIMTYPE: - return ConvertEnumInt(value, field.iOffset, playerAnimTypeNames, std::extent::value); + case WFT_PROJ_EXPLOSION: + return ConvertEnumInt(value, field.iOffset, szProjectileExplosionNames, std::extent::value); - case WFT_ACTIVE_RETICLE_TYPE: - return ConvertEnumInt(value, field.iOffset, activeReticleNames, std::extent::value); + case WFT_OFFHAND_CLASS: + return ConvertEnumInt(value, field.iOffset, offhandClassNames, std::extent::value); - case WFT_GUIDED_MISSILE_TYPE: - return ConvertEnumInt(value, field.iOffset, guidedMissileNames, std::extent::value); + case WFT_OFFHAND_SLOT: + return ConvertEnumInt(value, field.iOffset, offhandSlotNames, std::extent::value); - case WFT_BOUNCE_SOUND: - return ConvertBounceSounds(field, value); + case WFT_ANIMTYPE: + return ConvertEnumInt(value, field.iOffset, playerAnimTypeNames, std::extent::value); - case WFT_STICKINESS: - return ConvertEnumInt(value, field.iOffset, stickinessNames, std::extent::value); + case WFT_ACTIVE_RETICLE_TYPE: + return ConvertEnumInt(value, field.iOffset, activeReticleNames, std::extent::value); - case WFT_ROTATETYPE: - return ConvertEnumInt(value, field.iOffset, rotateTypeNames, std::extent::value); + case WFT_GUIDED_MISSILE_TYPE: + return ConvertEnumInt(value, field.iOffset, guidedMissileNames, std::extent::value); - case WFT_OVERLAYINTERFACE: - return ConvertEnumInt(value, field.iOffset, overlayInterfaceNames, std::extent::value); + case WFT_BOUNCE_SOUND: + return ConvertBounceSounds(field, value); - case WFT_INVENTORYTYPE: - return ConvertEnumInt(value, field.iOffset, szWeapInventoryTypeNames, std::extent::value); + case WFT_STICKINESS: + return ConvertEnumInt(value, field.iOffset, stickinessNames, std::extent::value); - case WFT_FIRETYPE: - return ConvertEnumInt(value, field.iOffset, szWeapFireTypeNames, std::extent::value); + case WFT_ROTATETYPE: + return ConvertEnumInt(value, field.iOffset, rotateTypeNames, std::extent::value); - case WFT_CLIPTYPE: - return ConvertEnumInt(value, field.iOffset, szWeapClipTypeNames, std::extent::value); + case WFT_OVERLAYINTERFACE: + return ConvertEnumInt(value, field.iOffset, overlayInterfaceNames, std::extent::value); - case WFT_AMMOCOUNTER_CLIPTYPE: - return ConvertEnumInt(value, field.iOffset, ammoCounterClipNames, std::extent::value); + case WFT_INVENTORYTYPE: + return ConvertEnumInt(value, field.iOffset, szWeapInventoryTypeNames, std::extent::value); - case WFT_ICONRATIO_HUD: - case WFT_ICONRATIO_AMMOCOUNTER: - case WFT_ICONRATIO_KILL: - case WFT_ICONRATIO_DPAD: - case WFT_ICONRATIO_INDICATOR: - return ConvertEnumInt(value, field.iOffset, weapIconRatioNames, std::extent::value); + case WFT_FIRETYPE: + return ConvertEnumInt(value, field.iOffset, szWeapFireTypeNames, std::extent::value); - case WFT_BARRELTYPE: - return ConvertEnumInt(value, field.iOffset, barrelTypeNames, std::extent::value); + case WFT_CLIPTYPE: + return ConvertEnumInt(value, field.iOffset, szWeapClipTypeNames, std::extent::value); - case WFT_HIDETAGS: - return ConvertHideTags(field, value); + case WFT_AMMOCOUNTER_CLIPTYPE: + return ConvertEnumInt(value, field.iOffset, ammoCounterClipNames, std::extent::value); - case WFT_EXPLOSION_TAG: - return ConvertScriptString(value, field.iOffset); + case WFT_ICONRATIO_HUD: + case WFT_ICONRATIO_AMMOCOUNTER: + case WFT_ICONRATIO_KILL: + case WFT_ICONRATIO_DPAD: + case WFT_ICONRATIO_INDICATOR: + return ConvertEnumInt(value, field.iOffset, weapIconRatioNames, std::extent::value); - case WFT_NOTETRACKSOUNDMAP: - return ConvertNotetrackSoundMap(field, value); + case WFT_BARRELTYPE: + return ConvertEnumInt(value, field.iOffset, barrelTypeNames, std::extent::value); - case WFT_WEAPON_CAMO: - return ConvertWeaponCamo(field, value); + case WFT_HIDETAGS: + return ConvertHideTags(field, value); - case WFT_ATTACHMENTS: - return ConvertAttachments(field, value); + case WFT_EXPLOSION_TAG: + return ConvertScriptString(value, field.iOffset); - case WFT_ATTACHMENT_UNIQUES: - return ConvertAttachmentUniques(field, value); + case WFT_NOTETRACKSOUNDMAP: + return ConvertNotetrackSoundMap(field, value); - case WFT_NUM_FIELD_TYPES: - default: - assert(false); - return false; - } - } + case WFT_WEAPON_CAMO: + return ConvertWeaponCamo(field, value); - public: - InfoStringToWeaponConverter(const InfoString& infoString, WeaponFullDef* weaponFullDef, ZoneScriptStrings& zoneScriptStrings, MemoryManager* memory, IAssetLoadingManager* manager, - const cspField_t* fields, const size_t fieldCount) - : InfoStringToStructConverter(infoString, weaponFullDef, zoneScriptStrings, memory, manager, fields, fieldCount) - { - } - }; -} + case WFT_ATTACHMENTS: + return ConvertAttachments(field, value); -void AssetLoaderWeapon::LinkWeaponFullDefSubStructs(WeaponFullDef* weapon) -{ - weapon->weapVariantDef.weapDef = &weapon->weapDef; - weapon->weapVariantDef.attachments = weapon->attachments; - weapon->weapVariantDef.attachmentUniques = weapon->attachmentUniques; - weapon->weapDef.gunXModel = weapon->gunXModel; - weapon->weapVariantDef.szXAnims = weapon->szXAnims; - weapon->weapVariantDef.hideTags = weapon->hideTags; - weapon->weapDef.notetrackSoundMapKeys = weapon->notetrackSoundMapKeys; - weapon->weapDef.notetrackSoundMapValues = weapon->notetrackSoundMapValues; - weapon->weapDef.worldModel = weapon->worldModel; - weapon->weapVariantDef.attachViewModel = weapon->attachViewModel; - weapon->weapVariantDef.attachWorldModel = weapon->attachWorldModel; - weapon->weapVariantDef.attachViewModelTag = weapon->attachViewModelTag; - weapon->weapVariantDef.attachWorldModelTag = weapon->attachWorldModelTag; - weapon->weapDef.parallelBounce = weapon->parallelBounce; - weapon->weapDef.perpendicularBounce = weapon->perpendicularBounce; - weapon->weapDef.locationDamageMultipliers = weapon->locationDamageMultipliers; -} + case WFT_ATTACHMENT_UNIQUES: + return ConvertAttachmentUniques(field, value); -void AssetLoaderWeapon::CalculateWeaponFields(WeaponFullDef* weapon) -{ - // iAttachments - weapon->weapVariantDef.iAttachments = 0; - for (auto i = 1u; i < sizeof(WeaponVariantDef::iAttachments) * 8; i++) // Bit for default attachment always 0 - { - if (weapon->attachments[i]) - weapon->weapVariantDef.iAttachments |= 1 << i; + case WFT_NUM_FIELD_TYPES: + default: + assert(false); + return false; } + } + +public: + InfoStringToWeaponConverter(const InfoString &infoString, WeaponFullDef *weaponFullDef, ZoneScriptStrings &zoneScriptStrings, MemoryManager *memory, + IAssetLoadingManager *manager, const cspField_t *fields, const size_t fieldCount) + : InfoStringToStructConverter(infoString, weaponFullDef, zoneScriptStrings, memory, manager, fields, fieldCount) {} +}; +} // namespace T6 + +void AssetLoaderWeapon::LinkWeaponFullDefSubStructs(WeaponFullDef *weapon) { + weapon->weapVariantDef.weapDef = &weapon->weapDef; + weapon->weapVariantDef.attachments = weapon->attachments; + weapon->weapVariantDef.attachmentUniques = weapon->attachmentUniques; + weapon->weapDef.gunXModel = weapon->gunXModel; + weapon->weapVariantDef.szXAnims = weapon->szXAnims; + weapon->weapVariantDef.hideTags = weapon->hideTags; + weapon->weapDef.notetrackSoundMapKeys = weapon->notetrackSoundMapKeys; + weapon->weapDef.notetrackSoundMapValues = weapon->notetrackSoundMapValues; + weapon->weapDef.worldModel = weapon->worldModel; + weapon->weapVariantDef.attachViewModel = weapon->attachViewModel; + weapon->weapVariantDef.attachWorldModel = weapon->attachWorldModel; + weapon->weapVariantDef.attachViewModelTag = weapon->attachViewModelTag; + weapon->weapVariantDef.attachWorldModelTag = weapon->attachWorldModelTag; + weapon->weapDef.parallelBounce = weapon->parallelBounce; + weapon->weapDef.perpendicularBounce = weapon->perpendicularBounce; + weapon->weapDef.locationDamageMultipliers = weapon->locationDamageMultipliers; +} - if (weapon->weapVariantDef.iAdsTransInTime <= 0) - weapon->weapVariantDef.fOOPosAnimLength[0] = 0.0033333334f; - else - weapon->weapVariantDef.fOOPosAnimLength[0] = 1.0f / static_cast(weapon->weapVariantDef.iAdsTransInTime); - - if (weapon->weapVariantDef.iAdsTransOutTime <= 0) - weapon->weapVariantDef.fOOPosAnimLength[1] = 0.0020000001f; - else - weapon->weapVariantDef.fOOPosAnimLength[1] = 1.0f / static_cast(weapon->weapVariantDef.iAdsTransOutTime); +void AssetLoaderWeapon::CalculateWeaponFields(WeaponFullDef *weapon) { + // iAttachments + weapon->weapVariantDef.iAttachments = 0; + for (auto i = 1u; i < sizeof(WeaponVariantDef::iAttachments) * 8; i++) // Bit for default attachment always 0 + { + if (weapon->attachments[i]) + weapon->weapVariantDef.iAttachments |= 1 << i; + } + + if (weapon->weapVariantDef.iAdsTransInTime <= 0) + weapon->weapVariantDef.fOOPosAnimLength[0] = 0.0033333334f; + else + weapon->weapVariantDef.fOOPosAnimLength[0] = 1.0f / static_cast(weapon->weapVariantDef.iAdsTransInTime); + + if (weapon->weapVariantDef.iAdsTransOutTime <= 0) + weapon->weapVariantDef.fOOPosAnimLength[1] = 0.0020000001f; + else + weapon->weapVariantDef.fOOPosAnimLength[1] = 1.0f / static_cast(weapon->weapVariantDef.iAdsTransOutTime); } -bool AssetLoaderWeapon::IsStringOverride(const char* str1, const char* str2) -{ - if ((str1 == nullptr) != (str2 == nullptr)) - return true; +bool AssetLoaderWeapon::IsStringOverride(const char *str1, const char *str2) { + if ((str1 == nullptr) != (str2 == nullptr)) + return true; - if (str1 == nullptr) - return false; + if (str1 == nullptr) + return false; - return strcmp(str1, str2) != 0; + return strcmp(str1, str2) != 0; } -bool AssetLoaderWeapon::IsFxOverride(FxEffectDef* effect1, FxEffectDef* effect2) -{ - if ((effect1 == nullptr) != (effect2 == nullptr)) - return true; +bool AssetLoaderWeapon::IsFxOverride(FxEffectDef *effect1, FxEffectDef *effect2) { + if ((effect1 == nullptr) != (effect2 == nullptr)) + return true; - if (effect1 == nullptr) - return false; + if (effect1 == nullptr) + return false; - return strcmp(effect1->name, effect2->name) != 0; + return strcmp(effect1->name, effect2->name) != 0; } -void AssetLoaderWeapon::HandleSoundOverride(WeaponAttachmentUnique* attachmentUnique, const char* snd1, const char* snd2, const eAttachmentOverrideSounds sndOverrideIndex) -{ - if (IsStringOverride(snd1, snd2)) - attachmentUnique->soundOverrides |= 1 << static_cast(sndOverrideIndex); +void AssetLoaderWeapon::HandleSoundOverride(WeaponAttachmentUnique *attachmentUnique, const char *snd1, const char *snd2, + const eAttachmentOverrideSounds sndOverrideIndex) { + if (IsStringOverride(snd1, snd2)) + attachmentUnique->soundOverrides |= 1 << static_cast(sndOverrideIndex); } -void AssetLoaderWeapon::HandleFxOverride(WeaponAttachmentUnique* attachmentUnique, FxEffectDef* effect1, FxEffectDef* effect2, const eAttachmentOverrideEffects fxOverrideIndex) -{ - if (IsFxOverride(effect1, effect2)) - attachmentUnique->effectOverrides |= 1 << static_cast(fxOverrideIndex); +void AssetLoaderWeapon::HandleFxOverride(WeaponAttachmentUnique *attachmentUnique, FxEffectDef *effect1, FxEffectDef *effect2, + const eAttachmentOverrideEffects fxOverrideIndex) { + if (IsFxOverride(effect1, effect2)) + attachmentUnique->effectOverrides |= 1 << static_cast(fxOverrideIndex); } -void AssetLoaderWeapon::CalculateAttachmentFields(WeaponFullDef* weapon, unsigned attachmentIndex, WeaponAttachmentUnique* attachmentUnique) -{ - for (auto& val : attachmentUnique->animationOverrides) - val = 0; - - for (auto animIndex = 0u; animIndex < std::extent::value; animIndex++) - { - if (IsStringOverride(weapon->szXAnims[animIndex], attachmentUnique->szXAnims[animIndex])) - attachmentUnique->animationOverrides[animIndex / 32] |= 1 << (animIndex % 32); - } - - attachmentUnique->soundOverrides = 0; - HandleSoundOverride(attachmentUnique, weapon->weapDef.fireSound, attachmentUnique->fireSound, ATTACHMENT_OVERRIDE_SOUND_FIRE); - HandleSoundOverride(attachmentUnique, weapon->weapDef.fireSoundPlayer, attachmentUnique->fireSoundPlayer, ATTACHMENT_OVERRIDE_SOUND_FIRE_PLAYER); - HandleSoundOverride(attachmentUnique, weapon->weapDef.fireLoopSound, attachmentUnique->fireLoopSound, ATTACHMENT_OVERRIDE_SOUND_FIRE_LOOP); - HandleSoundOverride(attachmentUnique, weapon->weapDef.fireLoopSoundPlayer, attachmentUnique->fireLoopSoundPlayer, ATTACHMENT_OVERRIDE_SOUND_FIRE_LOOP_PLAYER); - HandleSoundOverride(attachmentUnique, weapon->weapDef.fireLoopEndSound, attachmentUnique->fireLoopEndSound, ATTACHMENT_OVERRIDE_SOUND_FIRE_LOOP_END); - HandleSoundOverride(attachmentUnique, weapon->weapDef.fireLoopEndSoundPlayer, attachmentUnique->fireLoopEndSoundPlayer, ATTACHMENT_OVERRIDE_SOUND_FIRE_LOOP_END_PLAYER); - HandleSoundOverride(attachmentUnique, weapon->weapDef.fireStartSound, attachmentUnique->fireStartSound, ATTACHMENT_OVERRIDE_SOUND_FIRE_START); - HandleSoundOverride(attachmentUnique, weapon->weapDef.fireStopSound, attachmentUnique->fireStopSound, ATTACHMENT_OVERRIDE_SOUND_FIRE_STOP); - HandleSoundOverride(attachmentUnique, weapon->weapDef.fireStartSoundPlayer, attachmentUnique->fireStartSoundPlayer, ATTACHMENT_OVERRIDE_SOUND_FIRE_START_PLAYER); - HandleSoundOverride(attachmentUnique, weapon->weapDef.fireStopSoundPlayer, attachmentUnique->fireStopSoundPlayer, ATTACHMENT_OVERRIDE_SOUND_FIRE_STOP_PLAYER); - HandleSoundOverride(attachmentUnique, weapon->weapDef.fireLastSound, attachmentUnique->fireLastSound, ATTACHMENT_OVERRIDE_SOUND_FIRE_LAST); - HandleSoundOverride(attachmentUnique, weapon->weapDef.fireLastSoundPlayer, attachmentUnique->fireLastSoundPlayer, ATTACHMENT_OVERRIDE_SOUND_FIRE_LAST_PLAYER); - - attachmentUnique->effectOverrides = 0; - HandleFxOverride(attachmentUnique, weapon->weapDef.viewFlashEffect, attachmentUnique->viewFlashEffect, ATTACHMENT_OVERRIDE_EFFECT_VIEW_FLASH); - HandleFxOverride(attachmentUnique, weapon->weapDef.worldFlashEffect, attachmentUnique->worldFlashEffect, ATTACHMENT_OVERRIDE_EFFECT_WORLD_FLASH); - - attachmentUnique->childLink = 0; - if (attachmentUnique->combinedAttachmentTypeMask == 0) - { - WeaponAttachmentUnique* lastSibling = nullptr; - for (auto attachmentUniqueIndex = std::extent::value; attachmentUniqueIndex < std::extent::value; - attachmentUniqueIndex++) - { - if (weapon->attachmentUniques[attachmentUniqueIndex] != nullptr - && weapon->attachmentUniques[attachmentUniqueIndex]->combinedAttachmentTypeMask & (1 << static_cast(attachmentUnique->attachmentType)) - && weapon->attachmentUniques[attachmentUniqueIndex]->attachmentType != attachmentUnique->attachmentType) - { - std::vector attachments; - if(AssetLoaderWeaponAttachmentUnique::ExtractAttachmentsFromAssetName(weapon->attachmentUniques[attachmentUniqueIndex]->szInternalName, attachments) - && attachments.front() == attachmentUnique->attachmentType) - { - if (lastSibling == nullptr) - { - attachmentUnique->childLink = attachmentUniqueIndex; - lastSibling = weapon->attachmentUniques[attachmentUniqueIndex]; - } - else - { - lastSibling->siblingLink = attachmentUniqueIndex; - lastSibling = weapon->attachmentUniques[attachmentUniqueIndex]; - } - } - } +void AssetLoaderWeapon::CalculateAttachmentFields(WeaponFullDef *weapon, unsigned attachmentIndex, WeaponAttachmentUnique *attachmentUnique) { + for (auto &val : attachmentUnique->animationOverrides) + val = 0; + + for (auto animIndex = 0u; animIndex < std::extent::value; animIndex++) { + if (IsStringOverride(weapon->szXAnims[animIndex], attachmentUnique->szXAnims[animIndex])) + attachmentUnique->animationOverrides[animIndex / 32] |= 1 << (animIndex % 32); + } + + attachmentUnique->soundOverrides = 0; + HandleSoundOverride(attachmentUnique, weapon->weapDef.fireSound, attachmentUnique->fireSound, ATTACHMENT_OVERRIDE_SOUND_FIRE); + HandleSoundOverride(attachmentUnique, weapon->weapDef.fireSoundPlayer, attachmentUnique->fireSoundPlayer, ATTACHMENT_OVERRIDE_SOUND_FIRE_PLAYER); + HandleSoundOverride(attachmentUnique, weapon->weapDef.fireLoopSound, attachmentUnique->fireLoopSound, ATTACHMENT_OVERRIDE_SOUND_FIRE_LOOP); + HandleSoundOverride(attachmentUnique, weapon->weapDef.fireLoopSoundPlayer, attachmentUnique->fireLoopSoundPlayer, ATTACHMENT_OVERRIDE_SOUND_FIRE_LOOP_PLAYER); + HandleSoundOverride(attachmentUnique, weapon->weapDef.fireLoopEndSound, attachmentUnique->fireLoopEndSound, ATTACHMENT_OVERRIDE_SOUND_FIRE_LOOP_END); + HandleSoundOverride(attachmentUnique, weapon->weapDef.fireLoopEndSoundPlayer, attachmentUnique->fireLoopEndSoundPlayer, + ATTACHMENT_OVERRIDE_SOUND_FIRE_LOOP_END_PLAYER); + HandleSoundOverride(attachmentUnique, weapon->weapDef.fireStartSound, attachmentUnique->fireStartSound, ATTACHMENT_OVERRIDE_SOUND_FIRE_START); + HandleSoundOverride(attachmentUnique, weapon->weapDef.fireStopSound, attachmentUnique->fireStopSound, ATTACHMENT_OVERRIDE_SOUND_FIRE_STOP); + HandleSoundOverride(attachmentUnique, weapon->weapDef.fireStartSoundPlayer, attachmentUnique->fireStartSoundPlayer, + ATTACHMENT_OVERRIDE_SOUND_FIRE_START_PLAYER); + HandleSoundOverride(attachmentUnique, weapon->weapDef.fireStopSoundPlayer, attachmentUnique->fireStopSoundPlayer, ATTACHMENT_OVERRIDE_SOUND_FIRE_STOP_PLAYER); + HandleSoundOverride(attachmentUnique, weapon->weapDef.fireLastSound, attachmentUnique->fireLastSound, ATTACHMENT_OVERRIDE_SOUND_FIRE_LAST); + HandleSoundOverride(attachmentUnique, weapon->weapDef.fireLastSoundPlayer, attachmentUnique->fireLastSoundPlayer, ATTACHMENT_OVERRIDE_SOUND_FIRE_LAST_PLAYER); + + attachmentUnique->effectOverrides = 0; + HandleFxOverride(attachmentUnique, weapon->weapDef.viewFlashEffect, attachmentUnique->viewFlashEffect, ATTACHMENT_OVERRIDE_EFFECT_VIEW_FLASH); + HandleFxOverride(attachmentUnique, weapon->weapDef.worldFlashEffect, attachmentUnique->worldFlashEffect, ATTACHMENT_OVERRIDE_EFFECT_WORLD_FLASH); + + attachmentUnique->childLink = 0; + if (attachmentUnique->combinedAttachmentTypeMask == 0) { + WeaponAttachmentUnique *lastSibling = nullptr; + for (auto attachmentUniqueIndex = std::extent::value; + attachmentUniqueIndex < std::extent::value; attachmentUniqueIndex++) { + if (weapon->attachmentUniques[attachmentUniqueIndex] != nullptr && + weapon->attachmentUniques[attachmentUniqueIndex]->combinedAttachmentTypeMask & (1 << static_cast(attachmentUnique->attachmentType)) && + weapon->attachmentUniques[attachmentUniqueIndex]->attachmentType != attachmentUnique->attachmentType) { + std::vector attachments; + if (AssetLoaderWeaponAttachmentUnique::ExtractAttachmentsFromAssetName(weapon->attachmentUniques[attachmentUniqueIndex]->szInternalName, attachments) && + attachments.front() == attachmentUnique->attachmentType) { + if (lastSibling == nullptr) { + attachmentUnique->childLink = attachmentUniqueIndex; + lastSibling = weapon->attachmentUniques[attachmentUniqueIndex]; + } else { + lastSibling->siblingLink = attachmentUniqueIndex; + lastSibling = weapon->attachmentUniques[attachmentUniqueIndex]; + } } + } } + } } -void AssetLoaderWeapon::CalculateAttachmentFields(WeaponFullDef* weapon) -{ - for (auto attachmentUniqueIndex = 0u; attachmentUniqueIndex < std::extent::value; attachmentUniqueIndex++) - { - if (weapon->attachmentUniques[attachmentUniqueIndex] == nullptr) - continue; +void AssetLoaderWeapon::CalculateAttachmentFields(WeaponFullDef *weapon) { + for (auto attachmentUniqueIndex = 0u; attachmentUniqueIndex < std::extent::value; attachmentUniqueIndex++) { + if (weapon->attachmentUniques[attachmentUniqueIndex] == nullptr) + continue; - CalculateAttachmentFields(weapon, attachmentUniqueIndex, weapon->attachmentUniques[attachmentUniqueIndex]); - } + CalculateAttachmentFields(weapon, attachmentUniqueIndex, weapon->attachmentUniques[attachmentUniqueIndex]); + } } -bool AssetLoaderWeapon::LoadFromInfoString(const InfoString& infoString, const std::string& assetName, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) -{ - auto* weaponFullDef = memory->Create(); - memset(weaponFullDef, 0, sizeof(WeaponFullDef)); - LinkWeaponFullDefSubStructs(weaponFullDef); - - InfoStringToWeaponConverter converter(infoString, weaponFullDef, zone->m_script_strings, memory, manager, weapon_fields, std::extent::value); - if (!converter.Convert()) - { - std::cout << "Failed to parse weapon: \"" << assetName << "\"" << std::endl; - return true; - } +bool AssetLoaderWeapon::LoadFromInfoString(const InfoString &infoString, const std::string &assetName, MemoryManager *memory, IAssetLoadingManager *manager, + Zone *zone) { + auto *weaponFullDef = memory->Create(); + memset(weaponFullDef, 0, sizeof(WeaponFullDef)); + LinkWeaponFullDefSubStructs(weaponFullDef); - weaponFullDef->weapVariantDef.szInternalName = memory->Dup(assetName.c_str()); + InfoStringToWeaponConverter converter(infoString, weaponFullDef, zone->m_script_strings, memory, manager, weapon_fields, + std::extent::value); + if (!converter.Convert()) { + std::cout << "Failed to parse weapon: \"" << assetName << "\"" << std::endl; + return true; + } - // TODO: Load accuracy graph and flametable - CalculateWeaponFields(weaponFullDef); - CalculateAttachmentFields(weaponFullDef); + weaponFullDef->weapVariantDef.szInternalName = memory->Dup(assetName.c_str()); - manager->AddAsset(ASSET_TYPE_WEAPON, assetName, &weaponFullDef->weapVariantDef, converter.GetDependencies(), converter.GetUsedScriptStrings()); + // TODO: Load accuracy graph and flametable + CalculateWeaponFields(weaponFullDef); + CalculateAttachmentFields(weaponFullDef); - return true; -} + manager->AddAsset(ASSET_TYPE_WEAPON, assetName, &weaponFullDef->weapVariantDef, converter.GetDependencies(), converter.GetUsedScriptStrings()); -void* AssetLoaderWeapon::CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) -{ - auto* weaponFullDef = memory->Create(); - memset(weaponFullDef, 0, sizeof(WeaponFullDef)); - LinkWeaponFullDefSubStructs(weaponFullDef); - CalculateWeaponFields(weaponFullDef); - weaponFullDef->weapVariantDef.szInternalName = memory->Dup(assetName.c_str()); - return weaponFullDef; + return true; } -bool AssetLoaderWeapon::CanLoadFromGdt() const -{ - return true; +void *AssetLoaderWeapon::CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) { + auto *weaponFullDef = memory->Create(); + memset(weaponFullDef, 0, sizeof(WeaponFullDef)); + LinkWeaponFullDefSubStructs(weaponFullDef); + CalculateWeaponFields(weaponFullDef); + weaponFullDef->weapVariantDef.szInternalName = memory->Dup(assetName.c_str()); + return weaponFullDef; } -bool AssetLoaderWeapon::LoadFromGdt(const std::string& assetName, IGdtQueryable* gdtQueryable, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const -{ - auto* gdtEntry = gdtQueryable->GetGdtEntryByGdfAndName(ObjConstants::GDF_FILENAME_WEAPON, assetName); - if (gdtEntry == nullptr) - return false; - - InfoString infoString; - if(!infoString.FromGdtProperties(*gdtEntry)) - { - std::cout << "Failed to read weapon gdt entry: \"" << assetName << "\"" << std::endl; - return true; - } +bool AssetLoaderWeapon::CanLoadFromGdt() const { return true; } - return LoadFromInfoString(infoString, assetName, memory, manager, zone); -} +bool AssetLoaderWeapon::LoadFromGdt(const std::string &assetName, IGdtQueryable *gdtQueryable, MemoryManager *memory, IAssetLoadingManager *manager, + Zone *zone) const { + auto *gdtEntry = gdtQueryable->GetGdtEntryByGdfAndName(ObjConstants::GDF_FILENAME_WEAPON, assetName); + if (gdtEntry == nullptr) + return false; -bool AssetLoaderWeapon::CanLoadFromRaw() const -{ + InfoString infoString; + if (!infoString.FromGdtProperties(*gdtEntry)) { + std::cout << "Failed to read weapon gdt entry: \"" << assetName << "\"" << std::endl; return true; + } + + return LoadFromInfoString(infoString, assetName, memory, manager, zone); } -bool AssetLoaderWeapon::LoadFromRaw(const std::string& assetName, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const -{ - const auto fileName = "weapons/" + assetName; - const auto file = searchPath->Open(fileName); - if (!file.IsOpen()) - return false; +bool AssetLoaderWeapon::CanLoadFromRaw() const { return true; } - InfoString infoString; - if (!infoString.FromStream(ObjConstants::INFO_STRING_PREFIX_WEAPON, *file.m_stream)) - { - std::cout << "Failed to read weapon raw file: \"" << fileName << "\"" << std::endl; - return true; - } +bool AssetLoaderWeapon::LoadFromRaw(const std::string &assetName, ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager, + Zone *zone) const { + const auto fileName = "weapons/" + assetName; + const auto file = searchPath->Open(fileName); + if (!file.IsOpen()) + return false; + + InfoString infoString; + if (!infoString.FromStream(ObjConstants::INFO_STRING_PREFIX_WEAPON, *file.m_stream)) { + std::cout << "Failed to read weapon raw file: \"" << fileName << "\"" << std::endl; + return true; + } - return LoadFromInfoString(infoString, assetName, memory, manager, zone); + return LoadFromInfoString(infoString, assetName, memory, manager, zone); } diff --git a/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderWeapon.h b/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderWeapon.h index 3c352d29b..b59034692 100644 --- a/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderWeapon.h +++ b/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderWeapon.h @@ -1,32 +1,31 @@ #pragma once -#include "Game/T6/T6.h" #include "AssetLoading/BasicAssetLoader.h" #include "AssetLoading/IAssetLoadingManager.h" +#include "Game/T6/T6.h" #include "InfoString/InfoString.h" #include "SearchPath/ISearchPath.h" -namespace T6 -{ - class AssetLoaderWeapon final : public BasicAssetLoader - { - static void LinkWeaponFullDefSubStructs(WeaponFullDef* weapon); +namespace T6 { +class AssetLoaderWeapon final : public BasicAssetLoader { + static void LinkWeaponFullDefSubStructs(WeaponFullDef *weapon); - static bool IsStringOverride(const char* str1, const char* str2); - static bool IsFxOverride(FxEffectDef* effect1, FxEffectDef* effect2); - static void HandleSoundOverride(WeaponAttachmentUnique* attachmentUnique, const char* snd1, const char* snd2, eAttachmentOverrideSounds sndOverrideIndex); - static void HandleFxOverride(WeaponAttachmentUnique* attachmentUnique, FxEffectDef* effect1, FxEffectDef* effect2, eAttachmentOverrideEffects fxOverrideIndex); + static bool IsStringOverride(const char *str1, const char *str2); + static bool IsFxOverride(FxEffectDef *effect1, FxEffectDef *effect2); + static void HandleSoundOverride(WeaponAttachmentUnique *attachmentUnique, const char *snd1, const char *snd2, eAttachmentOverrideSounds sndOverrideIndex); + static void HandleFxOverride(WeaponAttachmentUnique *attachmentUnique, FxEffectDef *effect1, FxEffectDef *effect2, + eAttachmentOverrideEffects fxOverrideIndex); - static void CalculateWeaponFields(WeaponFullDef* weapon); - static void CalculateAttachmentFields(WeaponFullDef* weapon, unsigned attachmentIndex, WeaponAttachmentUnique* attachmentUnique); - static void CalculateAttachmentFields(WeaponFullDef* weapon); + static void CalculateWeaponFields(WeaponFullDef *weapon); + static void CalculateAttachmentFields(WeaponFullDef *weapon, unsigned attachmentIndex, WeaponAttachmentUnique *attachmentUnique); + static void CalculateAttachmentFields(WeaponFullDef *weapon); - static bool LoadFromInfoString(const InfoString& infoString, const std::string& assetName, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone); + static bool LoadFromInfoString(const InfoString &infoString, const std::string &assetName, MemoryManager *memory, IAssetLoadingManager *manager, Zone *zone); - public: - _NODISCARD void* CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) override; - _NODISCARD bool CanLoadFromGdt() const override; - bool LoadFromGdt(const std::string& assetName, IGdtQueryable* gdtQueryable, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const override; - _NODISCARD bool CanLoadFromRaw() const override; - bool LoadFromRaw(const std::string& assetName, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const override; - }; -} +public: + _NODISCARD void *CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) override; + _NODISCARD bool CanLoadFromGdt() const override; + bool LoadFromGdt(const std::string &assetName, IGdtQueryable *gdtQueryable, MemoryManager *memory, IAssetLoadingManager *manager, Zone *zone) const override; + _NODISCARD bool CanLoadFromRaw() const override; + bool LoadFromRaw(const std::string &assetName, ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager, Zone *zone) const override; +}; +} // namespace T6 diff --git a/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderWeaponAttachment.cpp b/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderWeaponAttachment.cpp index 6f1cf1bae..11c066ab0 100644 --- a/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderWeaponAttachment.cpp +++ b/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderWeaponAttachment.cpp @@ -1,164 +1,146 @@ #include "AssetLoaderWeaponAttachment.h" +#include #include #include -#include -#include "Game/T6/ObjConstantsT6.h" -#include "Game/T6/T6.h" #include "Game/T6/InfoString/EnumStrings.h" #include "Game/T6/InfoString/InfoStringToStructConverter.h" #include "Game/T6/InfoString/WeaponAttachmentFields.h" +#include "Game/T6/ObjConstantsT6.h" +#include "Game/T6/T6.h" #include "InfoString/InfoString.h" using namespace T6; -namespace T6 -{ - eAttachmentPoint attachmentPointByAttachmentTable[] - { - ATTACHMENT_POINT_NONE, // none - ATTACHMENT_POINT_TOP, // acog - ATTACHMENT_POINT_TRIGGER, // dualclip - ATTACHMENT_POINT_TOP, // dualoptic - ATTACHMENT_POINT_BOTTOM, // dw - ATTACHMENT_POINT_MUZZLE, // extbarrel - ATTACHMENT_POINT_TRIGGER, // extclip - ATTACHMENT_POINT_TRIGGER, // extramags - ATTACHMENT_POINT_GUNPERK, // fastads - ATTACHMENT_POINT_TOP, // fastreload - ATTACHMENT_POINT_TRIGGER, // fmj - ATTACHMENT_POINT_BOTTOM, // gl - ATTACHMENT_POINT_BOTTOM, // grip - ATTACHMENT_POINT_TOP, // holo - ATTACHMENT_POINT_BOTTOM, // ir - ATTACHMENT_POINT_BOTTOM, // is - ATTACHMENT_POINT_GUNPERK, // longbreath - ATTACHMENT_POINT_BOTTOM, // mk - ATTACHMENT_POINT_TOP, // mms - ATTACHMENT_POINT_TOP, // rangefinder - ATTACHMENT_POINT_TOP, // reflex - ATTACHMENT_POINT_MUZZLE, // rf - ATTACHMENT_POINT_BOTTOM, // sf - ATTACHMENT_POINT_MUZZLE, // silencer - ATTACHMENT_POINT_TRIGGER, // stackfire - ATTACHMENT_POINT_GUNPERK, // stalker - ATTACHMENT_POINT_GUNPERK, // steadyaim - ATTACHMENT_POINT_GUNPERK, // swayreduc - ATTACHMENT_POINT_TOP, // tacknife - ATTACHMENT_POINT_TOP, // vzoom - }; - - static_assert(std::extent::value == ATTACHMENT_TYPE_COUNT); - - class InfoStringToWeaponAttachmentConverter final : public InfoStringToStructConverter - { - protected: - bool ConvertExtensionField(const cspField_t& field, const std::string& value) override - { - switch (static_cast(field.iFieldType)) - { - case AFT_ATTACHMENTTYPE: - return ConvertEnumInt(value, field.iOffset, szAttachmentTypeNames, std::extent::value); - - case AFT_PENETRATE_TYPE: - return ConvertEnumInt(value, field.iOffset, penetrateTypeNames, std::extent::value); - - case AFT_FIRETYPE: - return ConvertEnumInt(value, field.iOffset, szWeapFireTypeNames, std::extent::value); - - default: - assert(false); - return false; - } - } - - public: - InfoStringToWeaponAttachmentConverter(const InfoString& infoString, WeaponAttachment* weaponAttachment, ZoneScriptStrings& zoneScriptStrings, MemoryManager* memory, IAssetLoadingManager* manager, - const cspField_t* fields, const size_t fieldCount) - : InfoStringToStructConverter(infoString, weaponAttachment, zoneScriptStrings, memory, manager, fields, fieldCount) - { - } - }; -} - -void AssetLoaderWeaponAttachment::CalculateAttachmentFields(WeaponAttachment* attachment) -{ - // attachmentPoint - if(static_cast(attachment->attachmentType) < ATTACHMENT_TYPE_COUNT) - { - attachment->attachmentPoint = attachmentPointByAttachmentTable[attachment->attachmentType]; +namespace T6 { +eAttachmentPoint attachmentPointByAttachmentTable[]{ + ATTACHMENT_POINT_NONE, // none + ATTACHMENT_POINT_TOP, // acog + ATTACHMENT_POINT_TRIGGER, // dualclip + ATTACHMENT_POINT_TOP, // dualoptic + ATTACHMENT_POINT_BOTTOM, // dw + ATTACHMENT_POINT_MUZZLE, // extbarrel + ATTACHMENT_POINT_TRIGGER, // extclip + ATTACHMENT_POINT_TRIGGER, // extramags + ATTACHMENT_POINT_GUNPERK, // fastads + ATTACHMENT_POINT_TOP, // fastreload + ATTACHMENT_POINT_TRIGGER, // fmj + ATTACHMENT_POINT_BOTTOM, // gl + ATTACHMENT_POINT_BOTTOM, // grip + ATTACHMENT_POINT_TOP, // holo + ATTACHMENT_POINT_BOTTOM, // ir + ATTACHMENT_POINT_BOTTOM, // is + ATTACHMENT_POINT_GUNPERK, // longbreath + ATTACHMENT_POINT_BOTTOM, // mk + ATTACHMENT_POINT_TOP, // mms + ATTACHMENT_POINT_TOP, // rangefinder + ATTACHMENT_POINT_TOP, // reflex + ATTACHMENT_POINT_MUZZLE, // rf + ATTACHMENT_POINT_BOTTOM, // sf + ATTACHMENT_POINT_MUZZLE, // silencer + ATTACHMENT_POINT_TRIGGER, // stackfire + ATTACHMENT_POINT_GUNPERK, // stalker + ATTACHMENT_POINT_GUNPERK, // steadyaim + ATTACHMENT_POINT_GUNPERK, // swayreduc + ATTACHMENT_POINT_TOP, // tacknife + ATTACHMENT_POINT_TOP, // vzoom +}; + +static_assert(std::extent::value == ATTACHMENT_TYPE_COUNT); + +class InfoStringToWeaponAttachmentConverter final : public InfoStringToStructConverter { +protected: + bool ConvertExtensionField(const cspField_t &field, const std::string &value) override { + switch (static_cast(field.iFieldType)) { + case AFT_ATTACHMENTTYPE: + return ConvertEnumInt(value, field.iOffset, szAttachmentTypeNames, std::extent::value); + + case AFT_PENETRATE_TYPE: + return ConvertEnumInt(value, field.iOffset, penetrateTypeNames, std::extent::value); + + case AFT_FIRETYPE: + return ConvertEnumInt(value, field.iOffset, szWeapFireTypeNames, std::extent::value); + + default: + assert(false); + return false; } + } + +public: + InfoStringToWeaponAttachmentConverter(const InfoString &infoString, WeaponAttachment *weaponAttachment, ZoneScriptStrings &zoneScriptStrings, + MemoryManager *memory, IAssetLoadingManager *manager, const cspField_t *fields, const size_t fieldCount) + : InfoStringToStructConverter(infoString, weaponAttachment, zoneScriptStrings, memory, manager, fields, fieldCount) {} +}; +} // namespace T6 + +void AssetLoaderWeaponAttachment::CalculateAttachmentFields(WeaponAttachment *attachment) { + // attachmentPoint + if (static_cast(attachment->attachmentType) < ATTACHMENT_TYPE_COUNT) { + attachment->attachmentPoint = attachmentPointByAttachmentTable[attachment->attachmentType]; + } } -bool AssetLoaderWeaponAttachment::LoadFromInfoString(const InfoString& infoString, const std::string& assetName, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) -{ - auto* attachment = memory->Create(); - memset(attachment, 0, sizeof(WeaponAttachment)); +bool AssetLoaderWeaponAttachment::LoadFromInfoString(const InfoString &infoString, const std::string &assetName, MemoryManager *memory, + IAssetLoadingManager *manager, Zone *zone) { + auto *attachment = memory->Create(); + memset(attachment, 0, sizeof(WeaponAttachment)); - InfoStringToWeaponAttachmentConverter converter(infoString, attachment, zone->m_script_strings, memory, manager, attachment_fields, std::extent::value); - if (!converter.Convert()) - { - std::cout << "Failed to parse attachment: \"" << assetName << "\"" << std::endl; - return true; - } + InfoStringToWeaponAttachmentConverter converter(infoString, attachment, zone->m_script_strings, memory, manager, attachment_fields, + std::extent::value); + if (!converter.Convert()) { + std::cout << "Failed to parse attachment: \"" << assetName << "\"" << std::endl; + return true; + } - CalculateAttachmentFields(attachment); - attachment->szInternalName = memory->Dup(assetName.c_str()); + CalculateAttachmentFields(attachment); + attachment->szInternalName = memory->Dup(assetName.c_str()); - manager->AddAsset(ASSET_TYPE_ATTACHMENT, assetName, attachment, converter.GetDependencies(), converter.GetUsedScriptStrings()); + manager->AddAsset(ASSET_TYPE_ATTACHMENT, assetName, attachment, converter.GetDependencies(), converter.GetUsedScriptStrings()); - return true; + return true; } -void* AssetLoaderWeaponAttachment::CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) -{ - auto* attachment = memory->Create(); - memset(attachment, 0, sizeof(WeaponAttachment)); - CalculateAttachmentFields(attachment); - attachment->szInternalName = memory->Dup(assetName.c_str()); - return attachment; +void *AssetLoaderWeaponAttachment::CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) { + auto *attachment = memory->Create(); + memset(attachment, 0, sizeof(WeaponAttachment)); + CalculateAttachmentFields(attachment); + attachment->szInternalName = memory->Dup(assetName.c_str()); + return attachment; } -bool AssetLoaderWeaponAttachment::CanLoadFromGdt() const -{ +bool AssetLoaderWeaponAttachment::CanLoadFromGdt() const { return true; } + +bool AssetLoaderWeaponAttachment::LoadFromGdt(const std::string &assetName, IGdtQueryable *gdtQueryable, MemoryManager *memory, IAssetLoadingManager *manager, + Zone *zone) const { + auto *gdtEntry = gdtQueryable->GetGdtEntryByGdfAndName(ObjConstants::GDF_FILENAME_WEAPON_ATTACHMENT, assetName); + if (gdtEntry == nullptr) + return false; + + InfoString infoString; + if (!infoString.FromGdtProperties(*gdtEntry)) { + std::cout << "Failed to read attachment gdt entry: \"" << assetName << "\"" << std::endl; return true; + } + + return LoadFromInfoString(infoString, assetName, memory, manager, zone); } -bool AssetLoaderWeaponAttachment::LoadFromGdt(const std::string& assetName, IGdtQueryable* gdtQueryable, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const -{ - auto* gdtEntry = gdtQueryable->GetGdtEntryByGdfAndName(ObjConstants::GDF_FILENAME_WEAPON_ATTACHMENT, assetName); - if (gdtEntry == nullptr) - return false; - - InfoString infoString; - if (!infoString.FromGdtProperties(*gdtEntry)) - { - std::cout << "Failed to read attachment gdt entry: \"" << assetName << "\"" << std::endl; - return true; - } +bool AssetLoaderWeaponAttachment::CanLoadFromRaw() const { return true; } - return LoadFromInfoString(infoString, assetName, memory, manager, zone); -} +bool AssetLoaderWeaponAttachment::LoadFromRaw(const std::string &assetName, ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager, + Zone *zone) const { + const auto fileName = "attachment/" + assetName; + const auto file = searchPath->Open(fileName); + if (!file.IsOpen()) + return false; -bool AssetLoaderWeaponAttachment::CanLoadFromRaw() const -{ + InfoString infoString; + if (!infoString.FromStream(ObjConstants::INFO_STRING_PREFIX_WEAPON_ATTACHMENT, *file.m_stream)) { + std::cout << "Failed to read attachment raw file: \"" << fileName << "\"" << std::endl; return true; -} - -bool AssetLoaderWeaponAttachment::LoadFromRaw(const std::string& assetName, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const -{ - const auto fileName = "attachment/" + assetName; - const auto file = searchPath->Open(fileName); - if (!file.IsOpen()) - return false; - - InfoString infoString; - if (!infoString.FromStream(ObjConstants::INFO_STRING_PREFIX_WEAPON_ATTACHMENT, *file.m_stream)) - { - std::cout << "Failed to read attachment raw file: \"" << fileName << "\"" << std::endl; - return true; - } + } - return LoadFromInfoString(infoString, assetName, memory, manager, zone); + return LoadFromInfoString(infoString, assetName, memory, manager, zone); } diff --git a/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderWeaponAttachment.h b/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderWeaponAttachment.h index f0099634e..d9cd66c0e 100644 --- a/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderWeaponAttachment.h +++ b/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderWeaponAttachment.h @@ -1,23 +1,21 @@ #pragma once -#include "Game/T6/T6.h" #include "AssetLoading/BasicAssetLoader.h" #include "AssetLoading/IAssetLoadingManager.h" +#include "Game/T6/T6.h" #include "InfoString/InfoString.h" #include "SearchPath/ISearchPath.h" -namespace T6 -{ - class AssetLoaderWeaponAttachment final : public BasicAssetLoader - { - static void CalculateAttachmentFields(WeaponAttachment* attachment); +namespace T6 { +class AssetLoaderWeaponAttachment final : public BasicAssetLoader { + static void CalculateAttachmentFields(WeaponAttachment *attachment); - static bool LoadFromInfoString(const InfoString& infoString, const std::string& assetName, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone); + static bool LoadFromInfoString(const InfoString &infoString, const std::string &assetName, MemoryManager *memory, IAssetLoadingManager *manager, Zone *zone); - public: - _NODISCARD void* CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) override; - _NODISCARD bool CanLoadFromGdt() const override; - bool LoadFromGdt(const std::string& assetName, IGdtQueryable* gdtQueryable, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const override; - _NODISCARD bool CanLoadFromRaw() const override; - bool LoadFromRaw(const std::string& assetName, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const override; - }; -} +public: + _NODISCARD void *CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) override; + _NODISCARD bool CanLoadFromGdt() const override; + bool LoadFromGdt(const std::string &assetName, IGdtQueryable *gdtQueryable, MemoryManager *memory, IAssetLoadingManager *manager, Zone *zone) const override; + _NODISCARD bool CanLoadFromRaw() const override; + bool LoadFromRaw(const std::string &assetName, ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager, Zone *zone) const override; +}; +} // namespace T6 diff --git a/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderWeaponAttachmentUnique.cpp b/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderWeaponAttachmentUnique.cpp index 1fd65a4b5..099717d42 100644 --- a/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderWeaponAttachmentUnique.cpp +++ b/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderWeaponAttachmentUnique.cpp @@ -1,268 +1,232 @@ #include "AssetLoaderWeaponAttachmentUnique.h" +#include #include #include -#include -#include "Utils/ClassUtils.h" -#include "Game/T6/ObjConstantsT6.h" -#include "Game/T6/T6.h" #include "Game/T6/InfoString/EnumStrings.h" #include "Game/T6/InfoString/InfoStringToStructConverter.h" #include "Game/T6/InfoString/WeaponAttachmentUniqueFields.h" +#include "Game/T6/ObjConstantsT6.h" +#include "Game/T6/T6.h" #include "InfoString/InfoString.h" +#include "Utils/ClassUtils.h" using namespace T6; -namespace T6 -{ - class InfoStringToWeaponAttachmentUniqueConverter final : public InfoStringToStructConverter - { - bool ConvertHideTags(const cspField_t& field, const std::string& value) - { - std::vector valueArray; - if (!ParseAsArray(value, valueArray)) - { - std::cout << "Failed to parse hide tags as array" << std::endl; - return false; - } - - if (valueArray.size() > std::extent::value) - { - std::cout << "Cannot have more than " << std::extent::value << " hide tags!" << std::endl; - return false; - } - - auto* hideTags = reinterpret_cast(reinterpret_cast(m_structure) + field.iOffset); - auto currentHideTag = 0u; - - if (valueArray.size() < std::extent::value) - { - m_used_script_string_list.emplace(m_zone_script_strings.AddOrGetScriptString("")); - } - - for (; currentHideTag < valueArray.size(); currentHideTag++) - { - const auto scrString = m_zone_script_strings.AddOrGetScriptString(valueArray[currentHideTag]); - hideTags[currentHideTag] = scrString; - m_used_script_string_list.emplace(scrString); - } - - for (; currentHideTag < std::extent::value; currentHideTag++) - { - hideTags[currentHideTag] = m_zone_script_strings.GetScriptString(""); - } - - return true; - } - - _NODISCARD bool ConvertWeaponCamo(const cspField_t& field, const std::string& value) - { - if (value.empty()) - { - *reinterpret_cast(reinterpret_cast(m_structure) + field.iOffset) = nullptr; - return true; - } - - auto* camo = m_loading_manager->LoadDependency(ASSET_TYPE_WEAPON_CAMO, value); - - if (camo == nullptr) - { - std::cout << "Failed to load camo asset \"" << value << "\"" << std::endl; - return false; - } - - m_dependencies.emplace(camo); - *reinterpret_cast(reinterpret_cast(m_structure) + field.iOffset) = camo->m_ptr; - - return true; - } - - protected: - bool ConvertExtensionField(const cspField_t& field, const std::string& value) override - { - switch (static_cast(field.iFieldType)) - { - case AUFT_ATTACHMENTTYPE: - return ConvertEnumInt(value, field.iOffset, szAttachmentTypeNames, std::extent::value); - - case AUFT_HIDETAGS: - return ConvertHideTags(field, value); - - case AUFT_OVERLAYRETICLE: - return ConvertEnumInt(value, field.iOffset, szWeapOverlayReticleNames, std::extent::value); - - case AUFT_CAMO: - return ConvertWeaponCamo(field, value); - - default: - assert(false); - return false; - } - } - - public: - InfoStringToWeaponAttachmentUniqueConverter(const InfoString& infoString, WeaponAttachmentUniqueFull* attachmentUniqueFull, ZoneScriptStrings& zoneScriptStrings, MemoryManager* memory, IAssetLoadingManager* manager, - const cspField_t* fields, const size_t fieldCount) - : InfoStringToStructConverter(infoString, attachmentUniqueFull, zoneScriptStrings, memory, manager, fields, fieldCount) - { - } - }; -} +namespace T6 { +class InfoStringToWeaponAttachmentUniqueConverter final : public InfoStringToStructConverter { + bool ConvertHideTags(const cspField_t &field, const std::string &value) { + std::vector valueArray; + if (!ParseAsArray(value, valueArray)) { + std::cout << "Failed to parse hide tags as array" << std::endl; + return false; + } -bool AssetLoaderWeaponAttachmentUnique::ExtractAttachmentsFromAssetName(const std::string& assetName, std::vector& attachmentList) -{ - std::vector parts; - - auto attachCount = 1u; - auto partStart = 0u; - for(auto ci = 0u; ci < assetName.size(); ci++) - { - if(assetName[ci] == '_') - { - parts.emplace_back(assetName, partStart, ci - partStart); - partStart = ci + 1; - } - else if(assetName[ci] == '+') - { - attachCount++; - parts.emplace_back(assetName, partStart, ci - partStart); - partStart = ci + 1; - } + if (valueArray.size() > std::extent::value) { + std::cout << "Cannot have more than " << std::extent::value << " hide tags!" << std::endl; + return false; } - if(partStart < assetName.size()) - parts.emplace_back(assetName, partStart, assetName.size() - partStart); - - for(auto attachPartOffset = parts.size() - attachCount; attachPartOffset < parts.size(); attachPartOffset++) - { - auto& specifiedAttachName = parts[attachPartOffset]; - - for (auto& c : specifiedAttachName) - c = static_cast(tolower(c)); - - auto foundAttachment = false; - for(auto attachIndex = 0u; attachIndex < std::extent::value; attachIndex++) - { - if(specifiedAttachName == szAttachmentTypeNames[attachIndex]) - { - attachmentList.push_back(static_cast(attachIndex)); - foundAttachment = true; - break; - } - } - - if(!foundAttachment) - return false; + auto *hideTags = reinterpret_cast(reinterpret_cast(m_structure) + field.iOffset); + auto currentHideTag = 0u; + + if (valueArray.size() < std::extent::value) { + m_used_script_string_list.emplace(m_zone_script_strings.AddOrGetScriptString("")); } - return true; -} + for (; currentHideTag < valueArray.size(); currentHideTag++) { + const auto scrString = m_zone_script_strings.AddOrGetScriptString(valueArray[currentHideTag]); + hideTags[currentHideTag] = scrString; + m_used_script_string_list.emplace(scrString); + } -void AssetLoaderWeaponAttachmentUnique::LinkAttachmentUniqueFullSubStructs(WeaponAttachmentUniqueFull* attachmentUnique) -{ - attachmentUnique->attachment.hideTags = attachmentUnique->hideTags; - attachmentUnique->attachment.szXAnims = attachmentUnique->szXAnims; - attachmentUnique->attachment.locationDamageMultipliers = attachmentUnique->locationDamageMultipliers; -} + for (; currentHideTag < std::extent::value; currentHideTag++) { + hideTags[currentHideTag] = m_zone_script_strings.GetScriptString(""); + } + + return true; + } -bool AssetLoaderWeaponAttachmentUnique::CalculateAttachmentUniqueFields(const std::string& assetName, WeaponAttachmentUniqueFull* attachmentUnique) -{ - // combinedAttachmentTypeMask - std::vector attachmentsFromName; - if(!ExtractAttachmentsFromAssetName(assetName, attachmentsFromName)) - { - std::cout << "Failed to determine attachments from attachment unique name \"" << assetName << "\"" << std::endl; - return false; + _NODISCARD bool ConvertWeaponCamo(const cspField_t &field, const std::string &value) { + if (value.empty()) { + *reinterpret_cast(reinterpret_cast(m_structure) + field.iOffset) = nullptr; + return true; } - if (attachmentsFromName.size() > 1) - { - for(auto attachment : attachmentsFromName) - { - attachmentUnique->attachment.combinedAttachmentTypeMask |= 1 << attachment; - } + auto *camo = m_loading_manager->LoadDependency(ASSET_TYPE_WEAPON_CAMO, value); + + if (camo == nullptr) { + std::cout << "Failed to load camo asset \"" << value << "\"" << std::endl; + return false; } + m_dependencies.emplace(camo); + *reinterpret_cast(reinterpret_cast(m_structure) + field.iOffset) = camo->m_ptr; + return true; -} + } -bool AssetLoaderWeaponAttachmentUnique::LoadFromInfoString(const InfoString& infoString, const std::string& assetName, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) -{ +protected: + bool ConvertExtensionField(const cspField_t &field, const std::string &value) override { + switch (static_cast(field.iFieldType)) { + case AUFT_ATTACHMENTTYPE: + return ConvertEnumInt(value, field.iOffset, szAttachmentTypeNames, std::extent::value); - auto* attachmentUniqueFull = memory->Create(); - memset(attachmentUniqueFull, 0, sizeof(WeaponAttachmentUniqueFull)); - LinkAttachmentUniqueFullSubStructs(attachmentUniqueFull); + case AUFT_HIDETAGS: + return ConvertHideTags(field, value); - InfoStringToWeaponAttachmentUniqueConverter converter(infoString, attachmentUniqueFull, zone->m_script_strings, memory, manager, attachment_unique_fields, std::extent::value); - if (!converter.Convert()) - { - std::cout << "Failed to parse attachment unique: \"" << assetName << "\"" << std::endl; - return true; + case AUFT_OVERLAYRETICLE: + return ConvertEnumInt(value, field.iOffset, szWeapOverlayReticleNames, std::extent::value); + + case AUFT_CAMO: + return ConvertWeaponCamo(field, value); + + default: + assert(false); + return false; + } + } + +public: + InfoStringToWeaponAttachmentUniqueConverter(const InfoString &infoString, WeaponAttachmentUniqueFull *attachmentUniqueFull, + ZoneScriptStrings &zoneScriptStrings, MemoryManager *memory, IAssetLoadingManager *manager, + const cspField_t *fields, const size_t fieldCount) + : InfoStringToStructConverter(infoString, attachmentUniqueFull, zoneScriptStrings, memory, manager, fields, fieldCount) {} +}; +} // namespace T6 + +bool AssetLoaderWeaponAttachmentUnique::ExtractAttachmentsFromAssetName(const std::string &assetName, std::vector &attachmentList) { + std::vector parts; + + auto attachCount = 1u; + auto partStart = 0u; + for (auto ci = 0u; ci < assetName.size(); ci++) { + if (assetName[ci] == '_') { + parts.emplace_back(assetName, partStart, ci - partStart); + partStart = ci + 1; + } else if (assetName[ci] == '+') { + attachCount++; + parts.emplace_back(assetName, partStart, ci - partStart); + partStart = ci + 1; } + } - if (!CalculateAttachmentUniqueFields(assetName, attachmentUniqueFull)) - return true; + if (partStart < assetName.size()) + parts.emplace_back(assetName, partStart, assetName.size() - partStart); - attachmentUniqueFull->attachment.szInternalName = memory->Dup(assetName.c_str()); + for (auto attachPartOffset = parts.size() - attachCount; attachPartOffset < parts.size(); attachPartOffset++) { + auto &specifiedAttachName = parts[attachPartOffset]; - auto* assetInfo = GlobalAssetPool::GetAssetByName(assetName); - auto* asset = assetInfo ? assetInfo->Asset() : nullptr; + for (auto &c : specifiedAttachName) + c = static_cast(tolower(c)); - manager->AddAsset(ASSET_TYPE_ATTACHMENT_UNIQUE, assetName, &attachmentUniqueFull->attachment, converter.GetDependencies(), converter.GetUsedScriptStrings()); + auto foundAttachment = false; + for (auto attachIndex = 0u; attachIndex < std::extent::value; attachIndex++) { + if (specifiedAttachName == szAttachmentTypeNames[attachIndex]) { + attachmentList.push_back(static_cast(attachIndex)); + foundAttachment = true; + break; + } + } - return true; -} + if (!foundAttachment) + return false; + } -void* AssetLoaderWeaponAttachmentUnique::CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) -{ - auto* attachmentUniqueFull = memory->Create(); - memset(attachmentUniqueFull, 0, sizeof(WeaponAttachmentUniqueFull)); - LinkAttachmentUniqueFullSubStructs(attachmentUniqueFull); - CalculateAttachmentUniqueFields(assetName, attachmentUniqueFull); - attachmentUniqueFull->attachment.szInternalName = memory->Dup(assetName.c_str()); - return attachmentUniqueFull; + return true; } -bool AssetLoaderWeaponAttachmentUnique::CanLoadFromGdt() const -{ - return true; +void AssetLoaderWeaponAttachmentUnique::LinkAttachmentUniqueFullSubStructs(WeaponAttachmentUniqueFull *attachmentUnique) { + attachmentUnique->attachment.hideTags = attachmentUnique->hideTags; + attachmentUnique->attachment.szXAnims = attachmentUnique->szXAnims; + attachmentUnique->attachment.locationDamageMultipliers = attachmentUnique->locationDamageMultipliers; } -bool AssetLoaderWeaponAttachmentUnique::LoadFromGdt(const std::string& assetName, IGdtQueryable* gdtQueryable, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const -{ - auto* gdtEntry = gdtQueryable->GetGdtEntryByGdfAndName(ObjConstants::GDF_FILENAME_WEAPON_ATTACHMENT_UNIQUE, assetName); - if (gdtEntry == nullptr) - return false; - - InfoString infoString; - if (!infoString.FromGdtProperties(*gdtEntry)) - { - std::cout << "Failed to read attachment unique gdt entry: \"" << assetName << "\"" << std::endl; - return true; +bool AssetLoaderWeaponAttachmentUnique::CalculateAttachmentUniqueFields(const std::string &assetName, WeaponAttachmentUniqueFull *attachmentUnique) { + // combinedAttachmentTypeMask + std::vector attachmentsFromName; + if (!ExtractAttachmentsFromAssetName(assetName, attachmentsFromName)) { + std::cout << "Failed to determine attachments from attachment unique name \"" << assetName << "\"" << std::endl; + return false; + } + + if (attachmentsFromName.size() > 1) { + for (auto attachment : attachmentsFromName) { + attachmentUnique->attachment.combinedAttachmentTypeMask |= 1 << attachment; } + } + + return true; +} + +bool AssetLoaderWeaponAttachmentUnique::LoadFromInfoString(const InfoString &infoString, const std::string &assetName, MemoryManager *memory, + IAssetLoadingManager *manager, Zone *zone) { + + auto *attachmentUniqueFull = memory->Create(); + memset(attachmentUniqueFull, 0, sizeof(WeaponAttachmentUniqueFull)); + LinkAttachmentUniqueFullSubStructs(attachmentUniqueFull); + + InfoStringToWeaponAttachmentUniqueConverter converter(infoString, attachmentUniqueFull, zone->m_script_strings, memory, manager, attachment_unique_fields, + std::extent::value); + if (!converter.Convert()) { + std::cout << "Failed to parse attachment unique: \"" << assetName << "\"" << std::endl; + return true; + } + + if (!CalculateAttachmentUniqueFields(assetName, attachmentUniqueFull)) + return true; - return LoadFromInfoString(infoString, assetName, memory, manager, zone); + attachmentUniqueFull->attachment.szInternalName = memory->Dup(assetName.c_str()); + + auto *assetInfo = GlobalAssetPool::GetAssetByName(assetName); + auto *asset = assetInfo ? assetInfo->Asset() : nullptr; + + manager->AddAsset(ASSET_TYPE_ATTACHMENT_UNIQUE, assetName, &attachmentUniqueFull->attachment, converter.GetDependencies(), converter.GetUsedScriptStrings()); + + return true; } -bool AssetLoaderWeaponAttachmentUnique::CanLoadFromRaw() const -{ +void *AssetLoaderWeaponAttachmentUnique::CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) { + auto *attachmentUniqueFull = memory->Create(); + memset(attachmentUniqueFull, 0, sizeof(WeaponAttachmentUniqueFull)); + LinkAttachmentUniqueFullSubStructs(attachmentUniqueFull); + CalculateAttachmentUniqueFields(assetName, attachmentUniqueFull); + attachmentUniqueFull->attachment.szInternalName = memory->Dup(assetName.c_str()); + return attachmentUniqueFull; +} + +bool AssetLoaderWeaponAttachmentUnique::CanLoadFromGdt() const { return true; } + +bool AssetLoaderWeaponAttachmentUnique::LoadFromGdt(const std::string &assetName, IGdtQueryable *gdtQueryable, MemoryManager *memory, + IAssetLoadingManager *manager, Zone *zone) const { + auto *gdtEntry = gdtQueryable->GetGdtEntryByGdfAndName(ObjConstants::GDF_FILENAME_WEAPON_ATTACHMENT_UNIQUE, assetName); + if (gdtEntry == nullptr) + return false; + + InfoString infoString; + if (!infoString.FromGdtProperties(*gdtEntry)) { + std::cout << "Failed to read attachment unique gdt entry: \"" << assetName << "\"" << std::endl; return true; + } + + return LoadFromInfoString(infoString, assetName, memory, manager, zone); } -bool AssetLoaderWeaponAttachmentUnique::LoadFromRaw(const std::string& assetName, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const -{ - const auto fileName = "attachmentunique/" + assetName; - const auto file = searchPath->Open(fileName); - if (!file.IsOpen()) - return false; - - InfoString infoString; - if (!infoString.FromStream(ObjConstants::INFO_STRING_PREFIX_WEAPON_ATTACHMENT_UNIQUE, *file.m_stream)) - { - std::cout << "Failed to read attachment unique raw file: \"" << fileName << "\"" << std::endl; - return true; - } +bool AssetLoaderWeaponAttachmentUnique::CanLoadFromRaw() const { return true; } + +bool AssetLoaderWeaponAttachmentUnique::LoadFromRaw(const std::string &assetName, ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager, + Zone *zone) const { + const auto fileName = "attachmentunique/" + assetName; + const auto file = searchPath->Open(fileName); + if (!file.IsOpen()) + return false; + + InfoString infoString; + if (!infoString.FromStream(ObjConstants::INFO_STRING_PREFIX_WEAPON_ATTACHMENT_UNIQUE, *file.m_stream)) { + std::cout << "Failed to read attachment unique raw file: \"" << fileName << "\"" << std::endl; + return true; + } - return LoadFromInfoString(infoString, assetName, memory, manager, zone); + return LoadFromInfoString(infoString, assetName, memory, manager, zone); } diff --git a/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderWeaponAttachmentUnique.h b/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderWeaponAttachmentUnique.h index 9311a6dd5..0552b71ab 100644 --- a/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderWeaponAttachmentUnique.h +++ b/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderWeaponAttachmentUnique.h @@ -1,26 +1,24 @@ #pragma once -#include "Game/T6/T6.h" #include "AssetLoading/BasicAssetLoader.h" #include "AssetLoading/IAssetLoadingManager.h" +#include "Game/T6/T6.h" #include "InfoString/InfoString.h" #include "SearchPath/ISearchPath.h" -namespace T6 -{ - class AssetLoaderWeaponAttachmentUnique final : public BasicAssetLoader - { - static void LinkAttachmentUniqueFullSubStructs(WeaponAttachmentUniqueFull* attachmentUnique); - static bool CalculateAttachmentUniqueFields(const std::string& assetName, WeaponAttachmentUniqueFull* attachmentUnique); +namespace T6 { +class AssetLoaderWeaponAttachmentUnique final : public BasicAssetLoader { + static void LinkAttachmentUniqueFullSubStructs(WeaponAttachmentUniqueFull *attachmentUnique); + static bool CalculateAttachmentUniqueFields(const std::string &assetName, WeaponAttachmentUniqueFull *attachmentUnique); - static bool LoadFromInfoString(const InfoString& infoString, const std::string& assetName, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone); + static bool LoadFromInfoString(const InfoString &infoString, const std::string &assetName, MemoryManager *memory, IAssetLoadingManager *manager, Zone *zone); - public: - static bool ExtractAttachmentsFromAssetName(const std::string& assetName, std::vector& attachmentList); +public: + static bool ExtractAttachmentsFromAssetName(const std::string &assetName, std::vector &attachmentList); - _NODISCARD void* CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) override; - _NODISCARD bool CanLoadFromGdt() const override; - bool LoadFromGdt(const std::string& assetName, IGdtQueryable* gdtQueryable, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const override; - _NODISCARD bool CanLoadFromRaw() const override; - bool LoadFromRaw(const std::string& assetName, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const override; - }; -} + _NODISCARD void *CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) override; + _NODISCARD bool CanLoadFromGdt() const override; + bool LoadFromGdt(const std::string &assetName, IGdtQueryable *gdtQueryable, MemoryManager *memory, IAssetLoadingManager *manager, Zone *zone) const override; + _NODISCARD bool CanLoadFromRaw() const override; + bool LoadFromRaw(const std::string &assetName, ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager, Zone *zone) const override; +}; +} // namespace T6 diff --git a/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderZBarrier.cpp b/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderZBarrier.cpp index e4f5fe4f2..90e1fc6bb 100644 --- a/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderZBarrier.cpp +++ b/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderZBarrier.cpp @@ -1,125 +1,108 @@ #include "AssetLoaderZBarrier.h" +#include #include #include -#include -#include "Game/T6/ObjConstantsT6.h" -#include "Game/T6/T6.h" #include "Game/T6/InfoString/InfoStringToStructConverter.h" #include "Game/T6/InfoString/ZBarrierFields.h" +#include "Game/T6/ObjConstantsT6.h" +#include "Game/T6/T6.h" #include "InfoString/InfoString.h" using namespace T6; -namespace T6 -{ - class InfoStringToZBarrierConverter final : public InfoStringToStructConverter - { - protected: - bool ConvertExtensionField(const cspField_t& field, const std::string& value) override - { - assert(false); - return false; - } - - public: - InfoStringToZBarrierConverter(const InfoString& infoString, ZBarrierDef* zbarrier, ZoneScriptStrings& zoneScriptStrings, MemoryManager* memory, IAssetLoadingManager* manager, - const cspField_t* fields, const size_t fieldCount) - : InfoStringToStructConverter(infoString, zbarrier, zoneScriptStrings, memory, manager, fields, fieldCount) - { - } - }; -} - -void AssetLoaderZBarrier::CalculateZBarrierFields(ZBarrierDef* zbarrier) -{ - // numBoardsInBarrier - { - auto foundEnd = false; - for (auto i = 0u; i < std::extent::value; i++) - { - if (zbarrier->boards[i].pBoardModel == nullptr) - { - foundEnd = true; - zbarrier->numBoardsInBarrier = i; - break; - } - } - - if (!foundEnd) - zbarrier->numBoardsInBarrier = std::extent::value; +namespace T6 { +class InfoStringToZBarrierConverter final : public InfoStringToStructConverter { +protected: + bool ConvertExtensionField(const cspField_t &field, const std::string &value) override { + assert(false); + return false; + } + +public: + InfoStringToZBarrierConverter(const InfoString &infoString, ZBarrierDef *zbarrier, ZoneScriptStrings &zoneScriptStrings, MemoryManager *memory, + IAssetLoadingManager *manager, const cspField_t *fields, const size_t fieldCount) + : InfoStringToStructConverter(infoString, zbarrier, zoneScriptStrings, memory, manager, fields, fieldCount) {} +}; +} // namespace T6 + +void AssetLoaderZBarrier::CalculateZBarrierFields(ZBarrierDef *zbarrier) { + // numBoardsInBarrier + { + auto foundEnd = false; + for (auto i = 0u; i < std::extent::value; i++) { + if (zbarrier->boards[i].pBoardModel == nullptr) { + foundEnd = true; + zbarrier->numBoardsInBarrier = i; + break; + } } + + if (!foundEnd) + zbarrier->numBoardsInBarrier = std::extent::value; + } } -bool AssetLoaderZBarrier::LoadFromInfoString(const InfoString& infoString, const std::string& assetName, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) -{ - auto* zbarrier = memory->Create(); - memset(zbarrier, 0, sizeof(ZBarrierDef)); +bool AssetLoaderZBarrier::LoadFromInfoString(const InfoString &infoString, const std::string &assetName, MemoryManager *memory, IAssetLoadingManager *manager, + Zone *zone) { + auto *zbarrier = memory->Create(); + memset(zbarrier, 0, sizeof(ZBarrierDef)); - InfoStringToZBarrierConverter converter(infoString, zbarrier, zone->m_script_strings, memory, manager, zbarrier_fields, std::extent::value); - if (!converter.Convert()) - { - std::cout << "Failed to parse zbarrier: \"" << assetName << "\"" << std::endl; - return true; - } + InfoStringToZBarrierConverter converter(infoString, zbarrier, zone->m_script_strings, memory, manager, zbarrier_fields, + std::extent::value); + if (!converter.Convert()) { + std::cout << "Failed to parse zbarrier: \"" << assetName << "\"" << std::endl; + return true; + } - CalculateZBarrierFields(zbarrier); - zbarrier->name = memory->Dup(assetName.c_str()); + CalculateZBarrierFields(zbarrier); + zbarrier->name = memory->Dup(assetName.c_str()); - manager->AddAsset(ASSET_TYPE_ZBARRIER, assetName, zbarrier, converter.GetDependencies(), converter.GetUsedScriptStrings()); + manager->AddAsset(ASSET_TYPE_ZBARRIER, assetName, zbarrier, converter.GetDependencies(), converter.GetUsedScriptStrings()); - return true; + return true; } -void* AssetLoaderZBarrier::CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) -{ - auto* zbarrier = memory->Create(); - memset(zbarrier, 0, sizeof(ZBarrierDef)); - CalculateZBarrierFields(zbarrier); - zbarrier->name = memory->Dup(assetName.c_str()); - return zbarrier; +void *AssetLoaderZBarrier::CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) { + auto *zbarrier = memory->Create(); + memset(zbarrier, 0, sizeof(ZBarrierDef)); + CalculateZBarrierFields(zbarrier); + zbarrier->name = memory->Dup(assetName.c_str()); + return zbarrier; } -bool AssetLoaderZBarrier::CanLoadFromGdt() const -{ +bool AssetLoaderZBarrier::CanLoadFromGdt() const { return true; } + +bool AssetLoaderZBarrier::LoadFromGdt(const std::string &assetName, IGdtQueryable *gdtQueryable, MemoryManager *memory, IAssetLoadingManager *manager, + Zone *zone) const { + auto *gdtEntry = gdtQueryable->GetGdtEntryByGdfAndName(ObjConstants::GDF_FILENAME_ZBARRIER, assetName); + if (gdtEntry == nullptr) + return false; + + InfoString infoString; + if (!infoString.FromGdtProperties(*gdtEntry)) { + std::cout << "Failed to read zbarrier gdt entry: \"" << assetName << "\"" << std::endl; return true; + } + + return LoadFromInfoString(infoString, assetName, memory, manager, zone); } -bool AssetLoaderZBarrier::LoadFromGdt(const std::string& assetName, IGdtQueryable* gdtQueryable, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const -{ - auto* gdtEntry = gdtQueryable->GetGdtEntryByGdfAndName(ObjConstants::GDF_FILENAME_ZBARRIER, assetName); - if (gdtEntry == nullptr) - return false; - - InfoString infoString; - if (!infoString.FromGdtProperties(*gdtEntry)) - { - std::cout << "Failed to read zbarrier gdt entry: \"" << assetName << "\"" << std::endl; - return true; - } +bool AssetLoaderZBarrier::CanLoadFromRaw() const { return true; } - return LoadFromInfoString(infoString, assetName, memory, manager, zone); -} +bool AssetLoaderZBarrier::LoadFromRaw(const std::string &assetName, ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager, + Zone *zone) const { + const auto fileName = "zbarrier/" + assetName; + const auto file = searchPath->Open(fileName); + if (!file.IsOpen()) + return false; -bool AssetLoaderZBarrier::CanLoadFromRaw() const -{ + InfoString infoString; + if (!infoString.FromStream(ObjConstants::INFO_STRING_PREFIX_ZBARRIER, *file.m_stream)) { + std::cout << "Failed to read zbarrier raw file: \"" << fileName << "\"" << std::endl; return true; -} - -bool AssetLoaderZBarrier::LoadFromRaw(const std::string& assetName, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const -{ - const auto fileName = "zbarrier/" + assetName; - const auto file = searchPath->Open(fileName); - if (!file.IsOpen()) - return false; - - InfoString infoString; - if (!infoString.FromStream(ObjConstants::INFO_STRING_PREFIX_ZBARRIER, *file.m_stream)) - { - std::cout << "Failed to read zbarrier raw file: \"" << fileName << "\"" << std::endl; - return true; - } + } - return LoadFromInfoString(infoString, assetName, memory, manager, zone); + return LoadFromInfoString(infoString, assetName, memory, manager, zone); } diff --git a/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderZBarrier.h b/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderZBarrier.h index 8d52a9daf..0ff87c73c 100644 --- a/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderZBarrier.h +++ b/src/ObjLoading/Game/T6/AssetLoaders/AssetLoaderZBarrier.h @@ -1,23 +1,21 @@ #pragma once -#include "Game/T6/T6.h" #include "AssetLoading/BasicAssetLoader.h" #include "AssetLoading/IAssetLoadingManager.h" +#include "Game/T6/T6.h" #include "InfoString/InfoString.h" #include "SearchPath/ISearchPath.h" -namespace T6 -{ - class AssetLoaderZBarrier final : public BasicAssetLoader - { - static void CalculateZBarrierFields(ZBarrierDef* zbarrier); +namespace T6 { +class AssetLoaderZBarrier final : public BasicAssetLoader { + static void CalculateZBarrierFields(ZBarrierDef *zbarrier); - static bool LoadFromInfoString(const InfoString& infoString, const std::string& assetName, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone); + static bool LoadFromInfoString(const InfoString &infoString, const std::string &assetName, MemoryManager *memory, IAssetLoadingManager *manager, Zone *zone); - public: - _NODISCARD void* CreateEmptyAsset(const std::string& assetName, MemoryManager* memory) override; - _NODISCARD bool CanLoadFromGdt() const override; - bool LoadFromGdt(const std::string& assetName, IGdtQueryable* gdtQueryable, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const override; - _NODISCARD bool CanLoadFromRaw() const override; - bool LoadFromRaw(const std::string& assetName, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager, Zone* zone) const override; - }; -} +public: + _NODISCARD void *CreateEmptyAsset(const std::string &assetName, MemoryManager *memory) override; + _NODISCARD bool CanLoadFromGdt() const override; + bool LoadFromGdt(const std::string &assetName, IGdtQueryable *gdtQueryable, MemoryManager *memory, IAssetLoadingManager *manager, Zone *zone) const override; + _NODISCARD bool CanLoadFromRaw() const override; + bool LoadFromRaw(const std::string &assetName, ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager, Zone *zone) const override; +}; +} // namespace T6 diff --git a/src/ObjLoading/Game/T6/InfoString/InfoStringToStructConverter.cpp b/src/ObjLoading/Game/T6/InfoString/InfoStringToStructConverter.cpp index 8acf6f113..6e2bc1084 100644 --- a/src/ObjLoading/Game/T6/InfoString/InfoStringToStructConverter.cpp +++ b/src/ObjLoading/Game/T6/InfoString/InfoStringToStructConverter.cpp @@ -7,220 +7,190 @@ using namespace T6; -InfoStringToStructConverter::InfoStringToStructConverter(const InfoString& infoString, void* structure, ZoneScriptStrings& zoneScriptStrings, MemoryManager* memory, IAssetLoadingManager* manager, - const cspField_t* fields, const size_t fieldCount) - : InfoStringToStructConverterBase(infoString, structure, zoneScriptStrings, memory), - m_loading_manager(manager), - m_fields(fields), - m_field_count(fieldCount) -{ +InfoStringToStructConverter::InfoStringToStructConverter(const InfoString &infoString, void *structure, ZoneScriptStrings &zoneScriptStrings, + MemoryManager *memory, IAssetLoadingManager *manager, const cspField_t *fields, + const size_t fieldCount) + : InfoStringToStructConverterBase(infoString, structure, zoneScriptStrings, memory), m_loading_manager(manager), m_fields(fields), + m_field_count(fieldCount) {} + +bool InfoStringToStructConverter::GetHashValue(const std::string &value, unsigned &hash) { + if (!value.empty() && value[0] == '@') { + char *endPtr; + hash = strtoul(&value[1], &endPtr, 16); + return endPtr == &value[value.size()]; + } + + hash = Common::Com_HashString(value.c_str()); + return true; } -bool InfoStringToStructConverter::GetHashValue(const std::string& value, unsigned& hash) -{ - if (!value.empty() && value[0] == '@') - { - char* endPtr; - hash = strtoul(&value[1], &endPtr, 16); - return endPtr == &value[value.size()]; +bool InfoStringToStructConverter::ConvertBaseField(const cspField_t &field, const std::string &value) { + switch (static_cast(field.iFieldType)) { + case CSPFT_STRING: + return ConvertString(value, field.iOffset); + + case CSPFT_STRING_MAX_STRING_CHARS: + return ConvertStringBuffer(value, field.iOffset, 1024); + + case CSPFT_STRING_MAX_QPATH: + return ConvertStringBuffer(value, field.iOffset, 64); + + case CSPFT_STRING_MAX_OSPATH: + return ConvertStringBuffer(value, field.iOffset, 256); + + case CSPFT_INT: + return ConvertInt(value, field.iOffset); + + case CSPFT_UINT: + return ConvertUint(value, field.iOffset); + + case CSPFT_BOOL: + return ConvertBool(value, field.iOffset); + + case CSPFT_QBOOLEAN: + return ConvertQBoolean(value, field.iOffset); + + case CSPFT_FLOAT: + return ConvertFloat(value, field.iOffset); + + case CSPFT_MILLISECONDS: + return ConvertMilliseconds(value, field.iOffset); + + case CSPFT_FX: { + if (value.empty()) { + *reinterpret_cast(reinterpret_cast(m_structure) + field.iOffset) = nullptr; + return true; + } + + auto *fx = m_loading_manager->LoadDependency(ASSET_TYPE_FX, value); + + if (fx == nullptr) { + std::cout << "Failed to load fx asset \"" << value << "\"" << std::endl; + return false; } - hash = Common::Com_HashString(value.c_str()); + m_dependencies.emplace(fx); + *reinterpret_cast(reinterpret_cast(m_structure) + field.iOffset) = fx->m_ptr; + return true; -} + } + + case CSPFT_XMODEL: { + if (value.empty()) { + *reinterpret_cast(reinterpret_cast(m_structure) + field.iOffset) = nullptr; + return true; + } + + auto *xmodel = m_loading_manager->LoadDependency(ASSET_TYPE_XMODEL, value); + + if (xmodel == nullptr) { + std::cout << "Failed to load xmodel asset \"" << value << "\"" << std::endl; + return false; + } + + m_dependencies.emplace(xmodel); + *reinterpret_cast(reinterpret_cast(m_structure) + field.iOffset) = xmodel->m_ptr; + + return true; + } -bool InfoStringToStructConverter::ConvertBaseField(const cspField_t& field, const std::string& value) -{ - switch (static_cast(field.iFieldType)) - { - case CSPFT_STRING: - return ConvertString(value, field.iOffset); - - case CSPFT_STRING_MAX_STRING_CHARS: - return ConvertStringBuffer(value, field.iOffset, 1024); + case CSPFT_MATERIAL: + case CSPFT_MATERIAL_STREAM: { + if (value.empty()) { + *reinterpret_cast(reinterpret_cast(m_structure) + field.iOffset) = nullptr; + return true; + } - case CSPFT_STRING_MAX_QPATH: - return ConvertStringBuffer(value, field.iOffset, 64); + auto *material = m_loading_manager->LoadDependency(ASSET_TYPE_MATERIAL, value); - case CSPFT_STRING_MAX_OSPATH: - return ConvertStringBuffer(value, field.iOffset, 256); - - case CSPFT_INT: - return ConvertInt(value, field.iOffset); - - case CSPFT_UINT: - return ConvertUint(value, field.iOffset); + if (material == nullptr) { + std::cout << "Failed to load material asset \"" << value << "\"" << std::endl; + return false; + } - case CSPFT_BOOL: - return ConvertBool(value, field.iOffset); + m_dependencies.emplace(material); + *reinterpret_cast(reinterpret_cast(m_structure) + field.iOffset) = material->m_ptr; - case CSPFT_QBOOLEAN: - return ConvertQBoolean(value, field.iOffset); + return true; + } - case CSPFT_FLOAT: - return ConvertFloat(value, field.iOffset); - - case CSPFT_MILLISECONDS: - return ConvertMilliseconds(value, field.iOffset); + case CSPFT_PHYS_PRESET: { + if (value.empty()) { + *reinterpret_cast(reinterpret_cast(m_structure) + field.iOffset) = nullptr; + return true; + } - case CSPFT_FX: - { - if (value.empty()) - { - *reinterpret_cast(reinterpret_cast(m_structure) + field.iOffset) = nullptr; - return true; - } + auto *physPreset = m_loading_manager->LoadDependency(ASSET_TYPE_PHYSPRESET, value); - auto* fx = m_loading_manager->LoadDependency(ASSET_TYPE_FX, value); - - if (fx == nullptr) - { - std::cout << "Failed to load fx asset \"" << value << "\"" << std::endl; - return false; - } + if (physPreset == nullptr) { + std::cout << "Failed to load physpreset asset \"" << value << "\"" << std::endl; + return false; + } - m_dependencies.emplace(fx); - *reinterpret_cast(reinterpret_cast(m_structure) + field.iOffset) = fx->m_ptr; - - return true; - } - - case CSPFT_XMODEL: - { - if (value.empty()) - { - *reinterpret_cast(reinterpret_cast(m_structure) + field.iOffset) = nullptr; - return true; - } - - auto* xmodel = m_loading_manager->LoadDependency(ASSET_TYPE_XMODEL, value); - - if (xmodel == nullptr) - { - std::cout << "Failed to load xmodel asset \"" << value << "\"" << std::endl; - return false; - } - - m_dependencies.emplace(xmodel); - *reinterpret_cast(reinterpret_cast(m_structure) + field.iOffset) = xmodel->m_ptr; - - return true; - } - - case CSPFT_MATERIAL: - case CSPFT_MATERIAL_STREAM: - { - if (value.empty()) - { - *reinterpret_cast(reinterpret_cast(m_structure) + field.iOffset) = nullptr; - return true; - } - - auto* material = m_loading_manager->LoadDependency(ASSET_TYPE_MATERIAL, value); - - if (material == nullptr) - { - std::cout << "Failed to load material asset \"" << value << "\"" << std::endl; - return false; - } - - m_dependencies.emplace(material); - *reinterpret_cast(reinterpret_cast(m_structure) + field.iOffset) = material->m_ptr; - - return true; - } - - case CSPFT_PHYS_PRESET: - { - if (value.empty()) - { - *reinterpret_cast(reinterpret_cast(m_structure) + field.iOffset) = nullptr; - return true; - } - - auto* physPreset = m_loading_manager->LoadDependency(ASSET_TYPE_PHYSPRESET, value); - - if (physPreset == nullptr) - { - std::cout << "Failed to load physpreset asset \"" << value << "\"" << std::endl; - return false; - } - - m_dependencies.emplace(physPreset); - *reinterpret_cast(reinterpret_cast(m_structure) + field.iOffset) = physPreset->m_ptr; - - return true; - } - - case CSPFT_SCRIPT_STRING: - return ConvertScriptString(value, field.iOffset); - - case CSPFT_TRACER: - { - if (value.empty()) - { - *reinterpret_cast(reinterpret_cast(m_structure) + field.iOffset) = nullptr; - return true; - } - - auto* tracer = m_loading_manager->LoadDependency(ASSET_TYPE_TRACER, value); - - if (tracer == nullptr) - { - std::cout << "Failed to load tracer asset \"" << value << "\"" << std::endl; - return false; - } - - m_dependencies.emplace(tracer); - *reinterpret_cast(reinterpret_cast(m_structure) + field.iOffset) = tracer->m_ptr; - - return true; - } - - case CSPFT_SOUND_ALIAS_ID: - { - unsigned int soundAliasHash; - if (!GetHashValue(value, soundAliasHash)) - { - std::cout << "Failed to parse value \"" << value << "\" as hash" << std::endl; - return false; - } - - *reinterpret_cast(reinterpret_cast(m_structure) + field.iOffset) = soundAliasHash; - return true; - } - - case CSPFT_NUM_BASE_FIELD_TYPES: - default: - assert(false); - return false; + m_dependencies.emplace(physPreset); + *reinterpret_cast(reinterpret_cast(m_structure) + field.iOffset) = physPreset->m_ptr; + + return true; + } + + case CSPFT_SCRIPT_STRING: + return ConvertScriptString(value, field.iOffset); + + case CSPFT_TRACER: { + if (value.empty()) { + *reinterpret_cast(reinterpret_cast(m_structure) + field.iOffset) = nullptr; + return true; } -} -bool InfoStringToStructConverter::Convert() -{ - for (auto fieldIndex = 0u; fieldIndex < m_field_count; fieldIndex++) - { - const auto& field = m_fields[fieldIndex]; - assert(field.iFieldType >= 0); - - auto foundValue = false; - const auto& value = m_info_string.GetValueForKey(std::string(field.szName), &foundValue); - - if (foundValue) - { - if (field.iFieldType < CSPFT_NUM_BASE_FIELD_TYPES) - { - if (!ConvertBaseField(field, value)) - return false; - } - else - { - if (!ConvertExtensionField(field, value)) - return false; - } - } + auto *tracer = m_loading_manager->LoadDependency(ASSET_TYPE_TRACER, value); + + if (tracer == nullptr) { + std::cout << "Failed to load tracer asset \"" << value << "\"" << std::endl; + return false; + } + + m_dependencies.emplace(tracer); + *reinterpret_cast(reinterpret_cast(m_structure) + field.iOffset) = tracer->m_ptr; + + return true; + } + + case CSPFT_SOUND_ALIAS_ID: { + unsigned int soundAliasHash; + if (!GetHashValue(value, soundAliasHash)) { + std::cout << "Failed to parse value \"" << value << "\" as hash" << std::endl; + return false; } + *reinterpret_cast(reinterpret_cast(m_structure) + field.iOffset) = soundAliasHash; return true; + } + + case CSPFT_NUM_BASE_FIELD_TYPES: + default: + assert(false); + return false; + } +} + +bool InfoStringToStructConverter::Convert() { + for (auto fieldIndex = 0u; fieldIndex < m_field_count; fieldIndex++) { + const auto &field = m_fields[fieldIndex]; + assert(field.iFieldType >= 0); + + auto foundValue = false; + const auto &value = m_info_string.GetValueForKey(std::string(field.szName), &foundValue); + + if (foundValue) { + if (field.iFieldType < CSPFT_NUM_BASE_FIELD_TYPES) { + if (!ConvertBaseField(field, value)) + return false; + } else { + if (!ConvertExtensionField(field, value)) + return false; + } + } + } + + return true; } diff --git a/src/ObjLoading/Game/T6/InfoString/InfoStringToStructConverter.h b/src/ObjLoading/Game/T6/InfoString/InfoStringToStructConverter.h index 9e9ecc6da..417b00b9f 100644 --- a/src/ObjLoading/Game/T6/InfoString/InfoStringToStructConverter.h +++ b/src/ObjLoading/Game/T6/InfoString/InfoStringToStructConverter.h @@ -1,25 +1,23 @@ #pragma once #include "AssetLoading/IAssetLoadingManager.h" -#include "InfoString/InfoStringToStructConverterBase.h" #include "Game/T6/T6.h" +#include "InfoString/InfoStringToStructConverterBase.h" -namespace T6 -{ - class InfoStringToStructConverter : public InfoStringToStructConverterBase - { - protected: - IAssetLoadingManager* m_loading_manager; - const cspField_t* m_fields; - size_t m_field_count; +namespace T6 { +class InfoStringToStructConverter : public InfoStringToStructConverterBase { +protected: + IAssetLoadingManager *m_loading_manager; + const cspField_t *m_fields; + size_t m_field_count; - static bool GetHashValue(const std::string& value, unsigned int& hash); + static bool GetHashValue(const std::string &value, unsigned int &hash); - virtual bool ConvertExtensionField(const cspField_t& field, const std::string& value) = 0; - bool ConvertBaseField(const cspField_t& field, const std::string& value); + virtual bool ConvertExtensionField(const cspField_t &field, const std::string &value) = 0; + bool ConvertBaseField(const cspField_t &field, const std::string &value); - public: - InfoStringToStructConverter(const InfoString& infoString, void* structure, ZoneScriptStrings& zoneScriptStrings, MemoryManager* memory, IAssetLoadingManager* manager, const cspField_t* fields, - size_t fieldCount); - bool Convert() override; - }; -} +public: + InfoStringToStructConverter(const InfoString &infoString, void *structure, ZoneScriptStrings &zoneScriptStrings, MemoryManager *memory, + IAssetLoadingManager *manager, const cspField_t *fields, size_t fieldCount); + bool Convert() override; +}; +} // namespace T6 diff --git a/src/ObjLoading/Game/T6/ObjLoaderT6.cpp b/src/ObjLoading/Game/T6/ObjLoaderT6.cpp index 13b385e78..45546d15f 100644 --- a/src/ObjLoading/Game/T6/ObjLoaderT6.cpp +++ b/src/ObjLoading/Game/T6/ObjLoaderT6.cpp @@ -2,10 +2,6 @@ #include -#include "Game/T6/GameT6.h" -#include "Game/T6/GameAssetPoolT6.h" -#include "ObjContainer/IPak/IPak.h" -#include "ObjLoading.h" #include "AssetLoaders/AssetLoaderFontIcon.h" #include "AssetLoaders/AssetLoaderLocalizeEntry.h" #include "AssetLoaders/AssetLoaderPhysConstraints.h" @@ -22,443 +18,373 @@ #include "AssetLoaders/AssetLoaderWeaponAttachmentUnique.h" #include "AssetLoaders/AssetLoaderZBarrier.h" #include "AssetLoading/AssetLoadingManager.h" -#include "Image/Texture.h" -#include "Image/IwiLoader.h" #include "Game/T6/CommonT6.h" +#include "Game/T6/GameAssetPoolT6.h" +#include "Game/T6/GameT6.h" #include "Image/Dx12TextureLoader.h" +#include "Image/IwiLoader.h" #include "Image/IwiTypes.h" +#include "Image/Texture.h" +#include "ObjContainer/IPak/IPak.h" +#include "ObjLoading.h" -namespace T6 -{ - const int ObjLoader::IPAK_READ_HASH = Common::Com_HashKey("ipak_read", 64); - const int ObjLoader::GLOBAL_HASH = Common::Com_HashKey("GLOBAL", 64); +namespace T6 { +const int ObjLoader::IPAK_READ_HASH = Common::Com_HashKey("ipak_read", 64); +const int ObjLoader::GLOBAL_HASH = Common::Com_HashKey("GLOBAL", 64); - ObjLoader::ObjLoader() - { -#define REGISTER_ASSET_LOADER(t) {auto l = std::make_unique(); m_asset_loaders_by_type[l->GetHandlingAssetType()] = std::move(l);} +ObjLoader::ObjLoader() { +#define REGISTER_ASSET_LOADER(t) \ + { \ + auto l = std::make_unique(); \ + m_asset_loaders_by_type[l->GetHandlingAssetType()] = std::move(l); \ + } #define BASIC_LOADER(assetType, assetClass) BasicAssetLoader - REGISTER_ASSET_LOADER(AssetLoaderPhysPreset) - REGISTER_ASSET_LOADER(AssetLoaderPhysConstraints) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_DESTRUCTIBLEDEF, DestructibleDef)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_XANIMPARTS, XAnimParts)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_XMODEL, XModel)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_MATERIAL, Material)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_TECHNIQUE_SET, MaterialTechniqueSet)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_IMAGE, GfxImage)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_SOUND, SndBank)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_SOUND_PATCH, SndPatch)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_CLIPMAP, clipMap_t)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_CLIPMAP_PVS, clipMap_t)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_COMWORLD, ComWorld)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_GAMEWORLD_SP, GameWorldSp)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_GAMEWORLD_MP, GameWorldMp)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_MAP_ENTS, MapEnts)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_GFXWORLD, GfxWorld)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_LIGHT_DEF, GfxLightDef)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_FONT, Font_s)) - REGISTER_ASSET_LOADER(AssetLoaderFontIcon) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_MENULIST, MenuList)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_MENU, menuDef_t)) - REGISTER_ASSET_LOADER(AssetLoaderLocalizeEntry) - REGISTER_ASSET_LOADER(AssetLoaderWeapon) - REGISTER_ASSET_LOADER(AssetLoaderWeaponAttachment) - REGISTER_ASSET_LOADER(AssetLoaderWeaponAttachmentUnique) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_WEAPON_CAMO, WeaponCamo)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_SNDDRIVER_GLOBALS, SndDriverGlobals)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_FX, FxEffectDef)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_IMPACT_FX, FxImpactTable)) - REGISTER_ASSET_LOADER(AssetLoaderRawFile) - REGISTER_ASSET_LOADER(AssetLoaderStringTable) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_LEADERBOARD, LeaderboardDef)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_XGLOBALS, XGlobals)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_DDL, ddlRoot_t)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_GLASSES, Glasses)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_EMBLEMSET, EmblemSet)) - REGISTER_ASSET_LOADER(AssetLoaderScriptParseTree) - REGISTER_ASSET_LOADER(AssetLoaderVehicle) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_MEMORYBLOCK, MemoryBlock)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_ADDON_MAP_ENTS, AddonMapEnts)) - REGISTER_ASSET_LOADER(AssetLoaderTracer) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_SKINNEDVERTS, SkinnedVertsDef)) - REGISTER_ASSET_LOADER(AssetLoaderQdb) - REGISTER_ASSET_LOADER(AssetLoaderSlug) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_FOOTSTEP_TABLE, FootstepTableDef)) - REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_FOOTSTEPFX_TABLE, FootstepFXTableDef)) - REGISTER_ASSET_LOADER(AssetLoaderZBarrier) + REGISTER_ASSET_LOADER(AssetLoaderPhysPreset) + REGISTER_ASSET_LOADER(AssetLoaderPhysConstraints) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_DESTRUCTIBLEDEF, DestructibleDef)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_XANIMPARTS, XAnimParts)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_XMODEL, XModel)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_MATERIAL, Material)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_TECHNIQUE_SET, MaterialTechniqueSet)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_IMAGE, GfxImage)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_SOUND, SndBank)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_SOUND_PATCH, SndPatch)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_CLIPMAP, clipMap_t)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_CLIPMAP_PVS, clipMap_t)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_COMWORLD, ComWorld)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_GAMEWORLD_SP, GameWorldSp)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_GAMEWORLD_MP, GameWorldMp)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_MAP_ENTS, MapEnts)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_GFXWORLD, GfxWorld)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_LIGHT_DEF, GfxLightDef)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_FONT, Font_s)) + REGISTER_ASSET_LOADER(AssetLoaderFontIcon) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_MENULIST, MenuList)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_MENU, menuDef_t)) + REGISTER_ASSET_LOADER(AssetLoaderLocalizeEntry) + REGISTER_ASSET_LOADER(AssetLoaderWeapon) + REGISTER_ASSET_LOADER(AssetLoaderWeaponAttachment) + REGISTER_ASSET_LOADER(AssetLoaderWeaponAttachmentUnique) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_WEAPON_CAMO, WeaponCamo)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_SNDDRIVER_GLOBALS, SndDriverGlobals)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_FX, FxEffectDef)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_IMPACT_FX, FxImpactTable)) + REGISTER_ASSET_LOADER(AssetLoaderRawFile) + REGISTER_ASSET_LOADER(AssetLoaderStringTable) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_LEADERBOARD, LeaderboardDef)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_XGLOBALS, XGlobals)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_DDL, ddlRoot_t)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_GLASSES, Glasses)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_EMBLEMSET, EmblemSet)) + REGISTER_ASSET_LOADER(AssetLoaderScriptParseTree) + REGISTER_ASSET_LOADER(AssetLoaderVehicle) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_MEMORYBLOCK, MemoryBlock)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_ADDON_MAP_ENTS, AddonMapEnts)) + REGISTER_ASSET_LOADER(AssetLoaderTracer) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_SKINNEDVERTS, SkinnedVertsDef)) + REGISTER_ASSET_LOADER(AssetLoaderQdb) + REGISTER_ASSET_LOADER(AssetLoaderSlug) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_FOOTSTEP_TABLE, FootstepTableDef)) + REGISTER_ASSET_LOADER(BASIC_LOADER(ASSET_TYPE_FOOTSTEPFX_TABLE, FootstepFXTableDef)) + REGISTER_ASSET_LOADER(AssetLoaderZBarrier) #undef BASIC_LOADER #undef REGISTER_ASSET_LOADER - } +} - bool ObjLoader::SupportsZone(Zone* zone) const - { - return zone->m_game == &g_GameT6; - } +bool ObjLoader::SupportsZone(Zone *zone) const { return zone->m_game == &g_GameT6; } - bool ObjLoader::VerifySoundBankChecksum(const SoundBank* soundBank, const SndRuntimeAssetBank& sndRuntimeAssetBank) - { - SoundAssetBankChecksum checksum{}; - static_assert(sizeof(SoundAssetBankChecksum::checksumBytes) == sizeof(SndRuntimeAssetBank::linkTimeChecksum)); - for (auto i = 0u; i < sizeof(SoundAssetBankChecksum::checksumBytes); i++) - checksum.checksumBytes[i] = sndRuntimeAssetBank.linkTimeChecksum[i]; +bool ObjLoader::VerifySoundBankChecksum(const SoundBank *soundBank, const SndRuntimeAssetBank &sndRuntimeAssetBank) { + SoundAssetBankChecksum checksum{}; + static_assert(sizeof(SoundAssetBankChecksum::checksumBytes) == sizeof(SndRuntimeAssetBank::linkTimeChecksum)); + for (auto i = 0u; i < sizeof(SoundAssetBankChecksum::checksumBytes); i++) + checksum.checksumBytes[i] = sndRuntimeAssetBank.linkTimeChecksum[i]; - return soundBank->VerifyChecksum(checksum); - } + return soundBank->VerifyChecksum(checksum); +} - SoundBank* ObjLoader::LoadSoundBankForZone(ISearchPath* searchPath, const std::string& soundBankFileName, Zone* zone) - { - if (ObjLoading::Configuration.Verbose) - std::cout << "Trying to load sound bank '" << soundBankFileName << "' for zone '" << zone->m_name << "'" << std::endl; +SoundBank *ObjLoader::LoadSoundBankForZone(ISearchPath *searchPath, const std::string &soundBankFileName, Zone *zone) { + if (ObjLoading::Configuration.Verbose) + std::cout << "Trying to load sound bank '" << soundBankFileName << "' for zone '" << zone->m_name << "'" << std::endl; - auto* existingSoundBank = SoundBank::Repository.GetContainerByName(soundBankFileName); - if (existingSoundBank != nullptr) - { - if (ObjLoading::Configuration.Verbose) - std::cout << "Referencing loaded sound bank '" << soundBankFileName << "'." << std::endl; + auto *existingSoundBank = SoundBank::Repository.GetContainerByName(soundBankFileName); + if (existingSoundBank != nullptr) { + if (ObjLoading::Configuration.Verbose) + std::cout << "Referencing loaded sound bank '" << soundBankFileName << "'." << std::endl; - SoundBank::Repository.AddContainerReference(existingSoundBank, zone); - return existingSoundBank; - } + SoundBank::Repository.AddContainerReference(existingSoundBank, zone); + return existingSoundBank; + } - auto file = searchPath->Open(soundBankFileName); - if (file.IsOpen()) - { - auto sndBank = std::make_unique(soundBankFileName, std::move(file.m_stream), file.m_length); - auto* sndBankPtr = sndBank.get(); + auto file = searchPath->Open(soundBankFileName); + if (file.IsOpen()) { + auto sndBank = std::make_unique(soundBankFileName, std::move(file.m_stream), file.m_length); + auto *sndBankPtr = sndBank.get(); - if (!sndBank->Initialize()) - { - std::cout << "Failed to load sound bank '" << soundBankFileName << "'" << std::endl; - return nullptr; - } + if (!sndBank->Initialize()) { + std::cout << "Failed to load sound bank '" << soundBankFileName << "'" << std::endl; + return nullptr; + } - SoundBank::Repository.AddContainer(std::move(sndBank), zone); + SoundBank::Repository.AddContainer(std::move(sndBank), zone); - if (ObjLoading::Configuration.Verbose) - std::cout << "Found and loaded sound bank '" << soundBankFileName << "'" << std::endl; + if (ObjLoading::Configuration.Verbose) + std::cout << "Found and loaded sound bank '" << soundBankFileName << "'" << std::endl; - return sndBankPtr; - } + return sndBankPtr; + } - std::cout << "Failed to load sound bank '" << soundBankFileName << "'" << std::endl; - return nullptr; - } + std::cout << "Failed to load sound bank '" << soundBankFileName << "'" << std::endl; + return nullptr; +} - void ObjLoader::LoadSoundBankFromLinkedInfo(ISearchPath* searchPath, const std::string& soundBankFileName, const SndRuntimeAssetBank* sndBankLinkedInfo, Zone* zone, - std::set& loadedBanksForZone, std::stack& dependenciesToLoad) - { - if (loadedBanksForZone.find(soundBankFileName) == loadedBanksForZone.end()) - { - auto* soundBank = LoadSoundBankForZone(searchPath, soundBankFileName, zone); - - if (soundBank) - { - if (!VerifySoundBankChecksum(soundBank, *sndBankLinkedInfo)) - { - std::cout << "Checksum of sound bank does not match link time checksum for '" << soundBankFileName << "'" << std::endl; - } - loadedBanksForZone.emplace(soundBankFileName); - - for (const auto& dependency : soundBank->GetDependencies()) - { - dependenciesToLoad.emplace(dependency); - } - } - } +void ObjLoader::LoadSoundBankFromLinkedInfo(ISearchPath *searchPath, const std::string &soundBankFileName, const SndRuntimeAssetBank *sndBankLinkedInfo, + Zone *zone, std::set &loadedBanksForZone, std::stack &dependenciesToLoad) { + if (loadedBanksForZone.find(soundBankFileName) == loadedBanksForZone.end()) { + auto *soundBank = LoadSoundBankForZone(searchPath, soundBankFileName, zone); + + if (soundBank) { + if (!VerifySoundBankChecksum(soundBank, *sndBankLinkedInfo)) { + std::cout << "Checksum of sound bank does not match link time checksum for '" << soundBankFileName << "'" << std::endl; + } + loadedBanksForZone.emplace(soundBankFileName); + + for (const auto &dependency : soundBank->GetDependencies()) { + dependenciesToLoad.emplace(dependency); + } } + } +} - void ObjLoader::LoadSoundBanksFromAsset(ISearchPath* searchPath, const SndBank* sndBank, Zone* zone, std::set& loadedBanksForZone) - { - std::stack dependenciesToLoad; +void ObjLoader::LoadSoundBanksFromAsset(ISearchPath *searchPath, const SndBank *sndBank, Zone *zone, std::set &loadedBanksForZone) { + std::stack dependenciesToLoad; - if (sndBank->streamAssetBank.zone) - { - const auto soundBankFileName = SoundBank::GetFileNameForDefinition(true, sndBank->streamAssetBank.zone, sndBank->streamAssetBank.language); - LoadSoundBankFromLinkedInfo(searchPath, soundBankFileName, &sndBank->streamAssetBank, zone, loadedBanksForZone, dependenciesToLoad); - } + if (sndBank->streamAssetBank.zone) { + const auto soundBankFileName = SoundBank::GetFileNameForDefinition(true, sndBank->streamAssetBank.zone, sndBank->streamAssetBank.language); + LoadSoundBankFromLinkedInfo(searchPath, soundBankFileName, &sndBank->streamAssetBank, zone, loadedBanksForZone, dependenciesToLoad); + } - if (sndBank->runtimeAssetLoad && sndBank->loadAssetBank.zone) - { - const auto soundBankFileName = SoundBank::GetFileNameForDefinition(false, sndBank->loadAssetBank.zone, sndBank->loadAssetBank.language); - LoadSoundBankFromLinkedInfo(searchPath, soundBankFileName, &sndBank->loadAssetBank, zone, loadedBanksForZone, dependenciesToLoad); - } + if (sndBank->runtimeAssetLoad && sndBank->loadAssetBank.zone) { + const auto soundBankFileName = SoundBank::GetFileNameForDefinition(false, sndBank->loadAssetBank.zone, sndBank->loadAssetBank.language); + LoadSoundBankFromLinkedInfo(searchPath, soundBankFileName, &sndBank->loadAssetBank, zone, loadedBanksForZone, dependenciesToLoad); + } - while (!dependenciesToLoad.empty()) - { - auto dependencyFileName = dependenciesToLoad.top(); - dependenciesToLoad.pop(); - - if (loadedBanksForZone.find(dependencyFileName) == loadedBanksForZone.end()) - { - auto* soundBank = LoadSoundBankForZone(searchPath, dependencyFileName, zone); - - if (soundBank) - { - loadedBanksForZone.emplace(dependencyFileName); - - for (const auto& dependency : soundBank->GetDependencies()) - { - dependenciesToLoad.emplace(dependency); - } - } - } + while (!dependenciesToLoad.empty()) { + auto dependencyFileName = dependenciesToLoad.top(); + dependenciesToLoad.pop(); + + if (loadedBanksForZone.find(dependencyFileName) == loadedBanksForZone.end()) { + auto *soundBank = LoadSoundBankForZone(searchPath, dependencyFileName, zone); + + if (soundBank) { + loadedBanksForZone.emplace(dependencyFileName); + + for (const auto &dependency : soundBank->GetDependencies()) { + dependenciesToLoad.emplace(dependency); } + } } + } +} - void ObjLoader::LoadIPakForZone(ISearchPath* searchPath, const std::string& ipakName, Zone* zone) - { - if (ObjLoading::Configuration.Verbose) - printf("Trying to load ipak '%s' for zone '%s'\n", ipakName.c_str(), zone->m_name.c_str()); +void ObjLoader::LoadIPakForZone(ISearchPath *searchPath, const std::string &ipakName, Zone *zone) { + if (ObjLoading::Configuration.Verbose) + printf("Trying to load ipak '%s' for zone '%s'\n", ipakName.c_str(), zone->m_name.c_str()); - auto* existingIPak = IPak::Repository.GetContainerByName(ipakName); - if (existingIPak != nullptr) - { - if (ObjLoading::Configuration.Verbose) - printf("Referencing loaded ipak '%s'.\n", ipakName.c_str()); + auto *existingIPak = IPak::Repository.GetContainerByName(ipakName); + if (existingIPak != nullptr) { + if (ObjLoading::Configuration.Verbose) + printf("Referencing loaded ipak '%s'.\n", ipakName.c_str()); - IPak::Repository.AddContainerReference(existingIPak, zone); - return; - } + IPak::Repository.AddContainerReference(existingIPak, zone); + return; + } - const auto ipakFilename = ipakName + ".ipak"; + const auto ipakFilename = ipakName + ".ipak"; - auto file = searchPath->Open(ipakFilename); - if (file.IsOpen()) - { - auto ipak = std::make_unique(ipakFilename, std::move(file.m_stream)); + auto file = searchPath->Open(ipakFilename); + if (file.IsOpen()) { + auto ipak = std::make_unique(ipakFilename, std::move(file.m_stream)); - if (ipak->Initialize()) - { - IPak::Repository.AddContainer(std::move(ipak), zone); + if (ipak->Initialize()) { + IPak::Repository.AddContainer(std::move(ipak), zone); - if (ObjLoading::Configuration.Verbose) - printf("Found and loaded ipak '%s'.\n", ipakFilename.c_str()); - } - else - { - printf("Failed to load ipak '%s'!\n", ipakFilename.c_str()); - } - } + if (ObjLoading::Configuration.Verbose) + printf("Found and loaded ipak '%s'.\n", ipakFilename.c_str()); + } else { + printf("Failed to load ipak '%s'!\n", ipakFilename.c_str()); } + } +} - bool ObjLoader::IsMpZone(Zone* zone) - { - return zone->m_name.compare(0, 3, "mp_") == 0 - || zone->m_name.compare(zone->m_name.length() - 3, 3, "_mp") == 0; - } +bool ObjLoader::IsMpZone(Zone *zone) { return zone->m_name.compare(0, 3, "mp_") == 0 || zone->m_name.compare(zone->m_name.length() - 3, 3, "_mp") == 0; } - bool ObjLoader::IsZmZone(Zone* zone) - { - return zone->m_name.compare(0, 3, "zm_") == 0 - || zone->m_name.compare(zone->m_name.length() - 3, 3, "_zm") == 0; - } +bool ObjLoader::IsZmZone(Zone *zone) { return zone->m_name.compare(0, 3, "zm_") == 0 || zone->m_name.compare(zone->m_name.length() - 3, 3, "_zm") == 0; } - void ObjLoader::LoadCommonIPaks(ISearchPath* searchPath, Zone* zone) - { - if (ObjLoading::Configuration.Verbose) - printf("Loading common ipaks for zone \"%s\"\n", zone->m_name.c_str()); - - LoadIPakForZone(searchPath, "base", zone); - auto languagePrefixes = g_GameT6.GetLanguagePrefixes(); - for (const auto& languagePrefix : languagePrefixes) - { - LoadIPakForZone(searchPath, languagePrefix.m_prefix + "base", zone); - } +void ObjLoader::LoadCommonIPaks(ISearchPath *searchPath, Zone *zone) { + if (ObjLoading::Configuration.Verbose) + printf("Loading common ipaks for zone \"%s\"\n", zone->m_name.c_str()); - if (IsMpZone(zone)) - { - if (ObjLoading::Configuration.Verbose) - printf("Loading multiplayer ipaks for zone \"%s\"\n", zone->m_name.c_str()); + LoadIPakForZone(searchPath, "base", zone); + auto languagePrefixes = g_GameT6.GetLanguagePrefixes(); + for (const auto &languagePrefix : languagePrefixes) { + LoadIPakForZone(searchPath, languagePrefix.m_prefix + "base", zone); + } - LoadIPakForZone(searchPath, "mp", zone); - LoadIPakForZone(searchPath, "so", zone); - } - else if (IsZmZone(zone)) - { - if (ObjLoading::Configuration.Verbose) - printf("Loading zombie ipak for zone \"%s\"\n", zone->m_name.c_str()); + if (IsMpZone(zone)) { + if (ObjLoading::Configuration.Verbose) + printf("Loading multiplayer ipaks for zone \"%s\"\n", zone->m_name.c_str()); - LoadIPakForZone(searchPath, "zm", zone); - } - else - { - if (ObjLoading::Configuration.Verbose) - printf("Loading singleplayer ipak for zone \"%s\"\n", zone->m_name.c_str()); + LoadIPakForZone(searchPath, "mp", zone); + LoadIPakForZone(searchPath, "so", zone); + } else if (IsZmZone(zone)) { + if (ObjLoading::Configuration.Verbose) + printf("Loading zombie ipak for zone \"%s\"\n", zone->m_name.c_str()); - LoadIPakForZone(searchPath, "sp", zone); - } - } + LoadIPakForZone(searchPath, "zm", zone); + } else { + if (ObjLoading::Configuration.Verbose) + printf("Loading singleplayer ipak for zone \"%s\"\n", zone->m_name.c_str()); - void ObjLoader::LoadReferencedContainersForZone(ISearchPath* searchPath, Zone* zone) const - { - auto* assetPoolT6 = dynamic_cast(zone->m_pools.get()); - const auto zoneNameHash = Common::Com_HashKey(zone->m_name.c_str(), 64); - - LoadCommonIPaks(searchPath, zone); - - if (assetPoolT6->m_key_value_pairs != nullptr) - { - for (auto* keyValuePairsEntry : *assetPoolT6->m_key_value_pairs) - { - auto* keyValuePairs = keyValuePairsEntry->Asset(); - for (auto variableIndex = 0; variableIndex < keyValuePairs->numVariables; variableIndex++) - { - auto* variable = &keyValuePairs->keyValuePairs[variableIndex]; - - if (variable->namespaceHash == zoneNameHash && variable->keyHash == IPAK_READ_HASH) - { - LoadIPakForZone(searchPath, variable->value, zone); - } - } - } - } + LoadIPakForZone(searchPath, "sp", zone); + } +} + +void ObjLoader::LoadReferencedContainersForZone(ISearchPath *searchPath, Zone *zone) const { + auto *assetPoolT6 = dynamic_cast(zone->m_pools.get()); + const auto zoneNameHash = Common::Com_HashKey(zone->m_name.c_str(), 64); + + LoadCommonIPaks(searchPath, zone); - if (assetPoolT6->m_sound_bank != nullptr) - { - std::set loadedSoundBanksForZone; + if (assetPoolT6->m_key_value_pairs != nullptr) { + for (auto *keyValuePairsEntry : *assetPoolT6->m_key_value_pairs) { + auto *keyValuePairs = keyValuePairsEntry->Asset(); + for (auto variableIndex = 0; variableIndex < keyValuePairs->numVariables; variableIndex++) { + auto *variable = &keyValuePairs->keyValuePairs[variableIndex]; - for (auto* sndBankAssetInfo : *assetPoolT6->m_sound_bank) - { - LoadSoundBanksFromAsset(searchPath, sndBankAssetInfo->Asset(), zone, loadedSoundBanksForZone); - } + if (variable->namespaceHash == zoneNameHash && variable->keyHash == IPAK_READ_HASH) { + LoadIPakForZone(searchPath, variable->value, zone); } + } } + } - void ObjLoader::UnloadContainersOfZone(Zone* zone) const - { - IPak::Repository.RemoveContainerReferences(zone); - } + if (assetPoolT6->m_sound_bank != nullptr) { + std::set loadedSoundBanksForZone; - void ObjLoader::LoadImageFromLoadDef(GfxImage* image, Zone* zone) - { - const auto* loadDef = image->texture.loadDef; - Dx12TextureLoader textureLoader(zone->GetMemory()); - - textureLoader.Width(image->width).Height(image->height).Depth(image->depth); - - if (loadDef->flags & iwi27::IMG_FLAG_VOLMAP) - textureLoader.Type(TextureType::T_3D); - else if (loadDef->flags & iwi27::IMG_FLAG_CUBEMAP) - textureLoader.Type(TextureType::T_CUBE); - else - textureLoader.Type(TextureType::T_2D); - - textureLoader.Format(static_cast(loadDef->format)); - textureLoader.HasMipMaps(!(loadDef->flags & iwi27::IMG_FLAG_NOMIPMAPS)); - Texture* loadedTexture = textureLoader.LoadTexture(image->texture.loadDef->data); - - if (loadedTexture != nullptr) - { - image->texture.texture = loadedTexture; - image->loadedSize = 0; - - const auto textureMipCount = loadedTexture->GetMipMapCount(); - for (auto mipLevel = 0; mipLevel < textureMipCount; mipLevel++) - image->loadedSize += static_cast(loadedTexture->GetSizeOfMipLevel(mipLevel) * loadedTexture->GetFaceCount()); - } + for (auto *sndBankAssetInfo : *assetPoolT6->m_sound_bank) { + LoadSoundBanksFromAsset(searchPath, sndBankAssetInfo->Asset(), zone, loadedSoundBanksForZone); } + } +} - void ObjLoader::LoadImageFromIwi(GfxImage* image, ISearchPath* searchPath, Zone* zone) - { - Texture* loadedTexture = nullptr; - IwiLoader loader(zone->GetMemory()); - - if (image->streamedPartCount > 0) - { - for (auto* ipak : IPak::Repository) - { - auto ipakStream = ipak->GetEntryStream(image->hash, image->streamedParts[0].hash); - - if (ipakStream) - { - loadedTexture = loader.LoadIwi(*ipakStream); - - ipakStream->close(); - - if (loadedTexture != nullptr) - { - break; - } - } - } - } +void ObjLoader::UnloadContainersOfZone(Zone *zone) const { IPak::Repository.RemoveContainerReferences(zone); } - if (loadedTexture == nullptr) - { - const auto imageFileName = "images/" + std::string(image->name) + ".iwi"; - - { - const auto filePathImage = searchPath->Open(imageFileName); - if (filePathImage.IsOpen()) - { - loadedTexture = loader.LoadIwi(*filePathImage.m_stream); - } - } - } +void ObjLoader::LoadImageFromLoadDef(GfxImage *image, Zone *zone) { + const auto *loadDef = image->texture.loadDef; + Dx12TextureLoader textureLoader(zone->GetMemory()); - if (loadedTexture != nullptr) - { - image->texture.texture = loadedTexture; - image->loadedSize = 0; + textureLoader.Width(image->width).Height(image->height).Depth(image->depth); - const auto textureMipCount = loadedTexture->GetMipMapCount(); - for (auto mipLevel = 0; mipLevel < textureMipCount; mipLevel++) - image->loadedSize += loadedTexture->GetSizeOfMipLevel(mipLevel) * loadedTexture->GetFaceCount(); - } - else - { - printf("Could not find data for image \"%s\"\n", image->name); - } - } + if (loadDef->flags & iwi27::IMG_FLAG_VOLMAP) + textureLoader.Type(TextureType::T_3D); + else if (loadDef->flags & iwi27::IMG_FLAG_CUBEMAP) + textureLoader.Type(TextureType::T_CUBE); + else + textureLoader.Type(TextureType::T_2D); - void ObjLoader::LoadImageData(ISearchPath* searchPath, Zone* zone) - { - auto* assetPoolT6 = dynamic_cast(zone->m_pools.get()); - - if (assetPoolT6 && assetPoolT6->m_image != nullptr) - { - for (auto* imageEntry : *assetPoolT6->m_image) - { - auto* image = imageEntry->Asset(); - - if (image->loadedSize > 0) - { - continue; - } - - // Do not load linked assets - if (image->name && image->name[0] == ',') - { - continue; - } - - if (image->texture.loadDef && image->texture.loadDef->resourceSize > 0) - { - LoadImageFromLoadDef(image, zone); - } - else - { - LoadImageFromIwi(image, searchPath, zone); - } - } + textureLoader.Format(static_cast(loadDef->format)); + textureLoader.HasMipMaps(!(loadDef->flags & iwi27::IMG_FLAG_NOMIPMAPS)); + Texture *loadedTexture = textureLoader.LoadTexture(image->texture.loadDef->data); + + if (loadedTexture != nullptr) { + image->texture.texture = loadedTexture; + image->loadedSize = 0; + + const auto textureMipCount = loadedTexture->GetMipMapCount(); + for (auto mipLevel = 0; mipLevel < textureMipCount; mipLevel++) + image->loadedSize += static_cast(loadedTexture->GetSizeOfMipLevel(mipLevel) * loadedTexture->GetFaceCount()); + } +} + +void ObjLoader::LoadImageFromIwi(GfxImage *image, ISearchPath *searchPath, Zone *zone) { + Texture *loadedTexture = nullptr; + IwiLoader loader(zone->GetMemory()); + + if (image->streamedPartCount > 0) { + for (auto *ipak : IPak::Repository) { + auto ipakStream = ipak->GetEntryStream(image->hash, image->streamedParts[0].hash); + + if (ipakStream) { + loadedTexture = loader.LoadIwi(*ipakStream); + + ipakStream->close(); + + if (loadedTexture != nullptr) { + break; } + } } + } - void ObjLoader::LoadObjDataForZone(ISearchPath* searchPath, Zone* zone) const - { - LoadImageData(searchPath, zone); - } + if (loadedTexture == nullptr) { + const auto imageFileName = "images/" + std::string(image->name) + ".iwi"; - bool ObjLoader::LoadAssetForZone(AssetLoadingContext* context, const asset_type_t assetType, const std::string& assetName) const { - AssetLoadingManager assetLoadingManager(m_asset_loaders_by_type, *context); - return assetLoadingManager.LoadAssetFromLoader(assetType, assetName); + const auto filePathImage = searchPath->Open(imageFileName); + if (filePathImage.IsOpen()) { + loadedTexture = loader.LoadIwi(*filePathImage.m_stream); + } } + } + + if (loadedTexture != nullptr) { + image->texture.texture = loadedTexture; + image->loadedSize = 0; + + const auto textureMipCount = loadedTexture->GetMipMapCount(); + for (auto mipLevel = 0; mipLevel < textureMipCount; mipLevel++) + image->loadedSize += loadedTexture->GetSizeOfMipLevel(mipLevel) * loadedTexture->GetFaceCount(); + } else { + printf("Could not find data for image \"%s\"\n", image->name); + } +} - void ObjLoader::FinalizeAssetsForZone(AssetLoadingContext* context) const - { - for (const auto& [type, loader] : m_asset_loaders_by_type) - loader->FinalizeAssetsForZone(context); +void ObjLoader::LoadImageData(ISearchPath *searchPath, Zone *zone) { + auto *assetPoolT6 = dynamic_cast(zone->m_pools.get()); + + if (assetPoolT6 && assetPoolT6->m_image != nullptr) { + for (auto *imageEntry : *assetPoolT6->m_image) { + auto *image = imageEntry->Asset(); + + if (image->loadedSize > 0) { + continue; + } + + // Do not load linked assets + if (image->name && image->name[0] == ',') { + continue; + } + + if (image->texture.loadDef && image->texture.loadDef->resourceSize > 0) { + LoadImageFromLoadDef(image, zone); + } else { + LoadImageFromIwi(image, searchPath, zone); + } } + } +} + +void ObjLoader::LoadObjDataForZone(ISearchPath *searchPath, Zone *zone) const { LoadImageData(searchPath, zone); } + +bool ObjLoader::LoadAssetForZone(AssetLoadingContext *context, const asset_type_t assetType, const std::string &assetName) const { + AssetLoadingManager assetLoadingManager(m_asset_loaders_by_type, *context); + return assetLoadingManager.LoadAssetFromLoader(assetType, assetName); +} + +void ObjLoader::FinalizeAssetsForZone(AssetLoadingContext *context) const { + for (const auto &[type, loader] : m_asset_loaders_by_type) + loader->FinalizeAssetsForZone(context); } +} // namespace T6 diff --git a/src/ObjLoading/Game/T6/ObjLoaderT6.h b/src/ObjLoading/Game/T6/ObjLoaderT6.h index 73c73eed1..2ddabafc2 100644 --- a/src/ObjLoading/Game/T6/ObjLoaderT6.h +++ b/src/ObjLoading/Game/T6/ObjLoaderT6.h @@ -3,51 +3,49 @@ #include #include #include -#include #include +#include -#include "IObjLoader.h" #include "AssetLoading/IAssetLoader.h" -#include "SearchPath/ISearchPath.h" #include "Game/T6/T6.h" +#include "IObjLoader.h" #include "ObjContainer/SoundBank/SoundBank.h" +#include "SearchPath/ISearchPath.h" -namespace T6 -{ - class ObjLoader final : public IObjLoader - { - static const int IPAK_READ_HASH; - static const int GLOBAL_HASH; +namespace T6 { +class ObjLoader final : public IObjLoader { + static const int IPAK_READ_HASH; + static const int GLOBAL_HASH; - std::map> m_asset_loaders_by_type; + std::map> m_asset_loaders_by_type; - static bool VerifySoundBankChecksum(const SoundBank* soundBank, const SndRuntimeAssetBank& sndRuntimeAssetBank); - static SoundBank* LoadSoundBankForZone(ISearchPath* searchPath, const std::string& soundBankFileName, Zone* zone); - static void LoadSoundBankFromLinkedInfo(ISearchPath* searchPath, const std::string& soundBankFileName, const SndRuntimeAssetBank* sndBankLinkedInfo, Zone* zone, - std::set& loadedBanksForZone, std::stack& dependenciesToLoad); - static void LoadSoundBanksFromAsset(ISearchPath* searchPath, const SndBank* sndBank, Zone* zone, std::set& loadedBanksForZone); + static bool VerifySoundBankChecksum(const SoundBank *soundBank, const SndRuntimeAssetBank &sndRuntimeAssetBank); + static SoundBank *LoadSoundBankForZone(ISearchPath *searchPath, const std::string &soundBankFileName, Zone *zone); + static void LoadSoundBankFromLinkedInfo(ISearchPath *searchPath, const std::string &soundBankFileName, const SndRuntimeAssetBank *sndBankLinkedInfo, + Zone *zone, std::set &loadedBanksForZone, std::stack &dependenciesToLoad); + static void LoadSoundBanksFromAsset(ISearchPath *searchPath, const SndBank *sndBank, Zone *zone, std::set &loadedBanksForZone); - static void LoadIPakForZone(ISearchPath* searchPath, const std::string& ipakName, Zone* zone); + static void LoadIPakForZone(ISearchPath *searchPath, const std::string &ipakName, Zone *zone); - static void LoadImageFromIwi(GfxImage* image, ISearchPath* searchPath, Zone* zone); - static void LoadImageFromLoadDef(GfxImage* image, Zone* zone); - static void LoadImageData(ISearchPath* searchPath, Zone* zone); + static void LoadImageFromIwi(GfxImage *image, ISearchPath *searchPath, Zone *zone); + static void LoadImageFromLoadDef(GfxImage *image, Zone *zone); + static void LoadImageData(ISearchPath *searchPath, Zone *zone); - static bool IsMpZone(Zone* zone); - static bool IsZmZone(Zone* zone); - static void LoadCommonIPaks(ISearchPath* searchPath, Zone* zone); + static bool IsMpZone(Zone *zone); + static bool IsZmZone(Zone *zone); + static void LoadCommonIPaks(ISearchPath *searchPath, Zone *zone); - public: - ObjLoader(); +public: + ObjLoader(); - bool SupportsZone(Zone* zone) const override; + bool SupportsZone(Zone *zone) const override; - void LoadReferencedContainersForZone(ISearchPath* searchPath, Zone* zone) const override; - void UnloadContainersOfZone(Zone* zone) const override; + void LoadReferencedContainersForZone(ISearchPath *searchPath, Zone *zone) const override; + void UnloadContainersOfZone(Zone *zone) const override; - void LoadObjDataForZone(ISearchPath* searchPath, Zone* zone) const override; + void LoadObjDataForZone(ISearchPath *searchPath, Zone *zone) const override; - bool LoadAssetForZone(AssetLoadingContext* context, asset_type_t assetType, const std::string& assetName) const override; - void FinalizeAssetsForZone(AssetLoadingContext* context) const override; - }; -} + bool LoadAssetForZone(AssetLoadingContext *context, asset_type_t assetType, const std::string &assetName) const override; + void FinalizeAssetsForZone(AssetLoadingContext *context) const override; +}; +} // namespace T6 diff --git a/src/ObjLoading/IObjLoader.h b/src/ObjLoading/IObjLoader.h index d38a26e84..a1c28a489 100644 --- a/src/ObjLoading/IObjLoader.h +++ b/src/ObjLoading/IObjLoader.h @@ -4,38 +4,37 @@ #include "SearchPath/ISearchPath.h" #include "Zone/Zone.h" -class IObjLoader -{ +class IObjLoader { public: - virtual ~IObjLoader() = default; + virtual ~IObjLoader() = default; - /** - * \brief Checks whether this ObjLoader supports a specified zone. - * \param zone The zone to check. - * \return \c true if the specified zone is supported. - */ - virtual bool SupportsZone(Zone* zone) const = 0; + /** + * \brief Checks whether this ObjLoader supports a specified zone. + * \param zone The zone to check. + * \return \c true if the specified zone is supported. + */ + virtual bool SupportsZone(Zone *zone) const = 0; - /** - * \brief Loads all containers that are referenced by a specified zone. - * \param searchPath The search path object to use to find the referenced containers. - * \param zone The zone to check for referenced containers. - */ - virtual void LoadReferencedContainersForZone(ISearchPath* searchPath, Zone* zone) const = 0; + /** + * \brief Loads all containers that are referenced by a specified zone. + * \param searchPath The search path object to use to find the referenced containers. + * \param zone The zone to check for referenced containers. + */ + virtual void LoadReferencedContainersForZone(ISearchPath *searchPath, Zone *zone) const = 0; - /** - * \brief Unloads all containers of a specified zone. If a container is also loaded by another zone it will only be unloaded when all referencing zones are unloaded. - * \param zone The zone to unload all containers for. - */ - virtual void UnloadContainersOfZone(Zone* zone) const = 0; + /** + * \brief Unloads all containers of a specified zone. If a container is also loaded by another zone it will only be unloaded when all referencing zones are + * unloaded. \param zone The zone to unload all containers for. + */ + virtual void UnloadContainersOfZone(Zone *zone) const = 0; - /** - * \brief Loads the obj data for all assets of a specified zone. - * \param searchPath The search path object to use to find obj files. - * \param zone The zone of the assets to load the obj data for. - */ - virtual void LoadObjDataForZone(ISearchPath* searchPath, Zone* zone) const = 0; + /** + * \brief Loads the obj data for all assets of a specified zone. + * \param searchPath The search path object to use to find obj files. + * \param zone The zone of the assets to load the obj data for. + */ + virtual void LoadObjDataForZone(ISearchPath *searchPath, Zone *zone) const = 0; - virtual bool LoadAssetForZone(AssetLoadingContext* context, asset_type_t assetType, const std::string& assetName) const = 0; - virtual void FinalizeAssetsForZone(AssetLoadingContext* context) const = 0; + virtual bool LoadAssetForZone(AssetLoadingContext *context, asset_type_t assetType, const std::string &assetName) const = 0; + virtual void FinalizeAssetsForZone(AssetLoadingContext *context) const = 0; }; \ No newline at end of file diff --git a/src/ObjLoading/Image/DdsLoader.cpp b/src/ObjLoading/Image/DdsLoader.cpp index d26d566eb..4fff5c2c4 100644 --- a/src/ObjLoading/Image/DdsLoader.cpp +++ b/src/ObjLoading/Image/DdsLoader.cpp @@ -2,279 +2,229 @@ #include +#include "Image/DdsTypes.h" #include "Utils/ClassUtils.h" #include "Utils/FileUtils.h" -#include "Image/DdsTypes.h" -class DdsLoaderInternal -{ - static constexpr auto DDS_MAGIC = FileUtils::MakeMagic32('D', 'D', 'S', ' '); - - MemoryManager* m_memory_manager; - std::istream& m_stream; - - TextureType m_texture_type; - bool m_has_mip_maps; - size_t m_width; - size_t m_height; - size_t m_depth; - const ImageFormat* m_format; - - _NODISCARD bool ReadMagic() const - { - uint32_t magic; - m_stream.read(reinterpret_cast(&magic), sizeof(magic)); - if (m_stream.gcount() != sizeof(magic)) - { - std::cout << "Failed to read dds data" << std::endl; - return false; - } - - if (magic != DDS_MAGIC) - { - std::cout << "Invalid magic for dds" << std::endl; - return false; - } +class DdsLoaderInternal { + static constexpr auto DDS_MAGIC = FileUtils::MakeMagic32('D', 'D', 'S', ' '); + + MemoryManager *m_memory_manager; + std::istream &m_stream; + + TextureType m_texture_type; + bool m_has_mip_maps; + size_t m_width; + size_t m_height; + size_t m_depth; + const ImageFormat *m_format; + + _NODISCARD bool ReadMagic() const { + uint32_t magic; + m_stream.read(reinterpret_cast(&magic), sizeof(magic)); + if (m_stream.gcount() != sizeof(magic)) { + std::cout << "Failed to read dds data" << std::endl; + return false; + } - return true; + if (magic != DDS_MAGIC) { + std::cout << "Invalid magic for dds" << std::endl; + return false; } - _NODISCARD bool ReadDxt10Header() - { - DDS_HEADER_DXT10 headerDx10{}; - m_stream.read(reinterpret_cast(&headerDx10), sizeof(headerDx10)); - if (m_stream.gcount() != sizeof(headerDx10)) - { - std::cout << "Failed to read dds data" << std::endl; - return false; - } + return true; + } - if (headerDx10.resourceDimension == D3D10_RESOURCE_DIMENSION_TEXTURE3D) - { - m_texture_type = TextureType::T_3D; - } - else if (headerDx10.resourceDimension == D3D10_RESOURCE_DIMENSION_TEXTURE2D) - { - if (headerDx10.miscFlag & DDS_RESOURCE_MISC_TEXTURECUBE || headerDx10.arraySize == 6) - { - m_texture_type = TextureType::T_CUBE; - } - else - { - m_texture_type = TextureType::T_2D; - } - } - else - { - std::cout << "Unsupported dds resourceDimension " << headerDx10.resourceDimension << std::endl; - return false; - } + _NODISCARD bool ReadDxt10Header() { + DDS_HEADER_DXT10 headerDx10{}; + m_stream.read(reinterpret_cast(&headerDx10), sizeof(headerDx10)); + if (m_stream.gcount() != sizeof(headerDx10)) { + std::cout << "Failed to read dds data" << std::endl; + return false; + } - for (const auto* imageFormat : ImageFormat::ALL_FORMATS) - { - if (imageFormat->GetDxgiFormat() == headerDx10.dxgiFormat) - { - m_format = imageFormat; - return true; - } - } + if (headerDx10.resourceDimension == D3D10_RESOURCE_DIMENSION_TEXTURE3D) { + m_texture_type = TextureType::T_3D; + } else if (headerDx10.resourceDimension == D3D10_RESOURCE_DIMENSION_TEXTURE2D) { + if (headerDx10.miscFlag & DDS_RESOURCE_MISC_TEXTURECUBE || headerDx10.arraySize == 6) { + m_texture_type = TextureType::T_CUBE; + } else { + m_texture_type = TextureType::T_2D; + } + } else { + std::cout << "Unsupported dds resourceDimension " << headerDx10.resourceDimension << std::endl; + return false; + } - std::cout << "Unsupported dds dxgi format " << headerDx10.dxgiFormat << std::endl; - return false; + for (const auto *imageFormat : ImageFormat::ALL_FORMATS) { + if (imageFormat->GetDxgiFormat() == headerDx10.dxgiFormat) { + m_format = imageFormat; + return true; + } } - _NODISCARD bool ReadPixelFormatFourCc(DDS_PIXELFORMAT& pf) - { - switch (pf.dwFourCC) - { - case FileUtils::MakeMagic32('D', 'X', 'T', '1'): - m_format = &ImageFormat::FORMAT_BC1; - return true; + std::cout << "Unsupported dds dxgi format " << headerDx10.dxgiFormat << std::endl; + return false; + } - case FileUtils::MakeMagic32('D', 'X', 'T', '3'): - m_format = &ImageFormat::FORMAT_BC2; - return true; + _NODISCARD bool ReadPixelFormatFourCc(DDS_PIXELFORMAT &pf) { + switch (pf.dwFourCC) { + case FileUtils::MakeMagic32('D', 'X', 'T', '1'): + m_format = &ImageFormat::FORMAT_BC1; + return true; - case FileUtils::MakeMagic32('D', 'X', 'T', '5'): - m_format = &ImageFormat::FORMAT_BC3; - return true; + case FileUtils::MakeMagic32('D', 'X', 'T', '3'): + m_format = &ImageFormat::FORMAT_BC2; + return true; - case FileUtils::MakeMagic32('D', 'X', '1', '0'): - return ReadDxt10Header(); + case FileUtils::MakeMagic32('D', 'X', 'T', '5'): + m_format = &ImageFormat::FORMAT_BC3; + return true; - default: - std::cout << "Unknown dds FourCC " << pf.dwFourCC << std::endl; - return false; - } + case FileUtils::MakeMagic32('D', 'X', '1', '0'): + return ReadDxt10Header(); + + default: + std::cout << "Unknown dds FourCC " << pf.dwFourCC << std::endl; + return false; } + } - static void ExtractSizeAndOffsetFromMask(uint32_t mask, unsigned& offset, unsigned& size) - { - offset = 0; - size = 0; + static void ExtractSizeAndOffsetFromMask(uint32_t mask, unsigned &offset, unsigned &size) { + offset = 0; + size = 0; - if (mask == 0) - return; + if (mask == 0) + return; - while ((mask & 1) == 0) - { - offset++; - mask >>= 1; - } + while ((mask & 1) == 0) { + offset++; + mask >>= 1; + } - while ((mask & 1) == 1) - { - size++; - mask >>= 1; - } + while ((mask & 1) == 1) { + size++; + mask >>= 1; } + } - _NODISCARD bool ReadPixelFormatUnsigned(DDS_PIXELFORMAT& pf) - { - unsigned rOffset, rSize, gOffset, gSize, bOffset, bSize, aOffset, aSize; - - ExtractSizeAndOffsetFromMask(pf.dwRBitMask, rOffset, rSize); - ExtractSizeAndOffsetFromMask(pf.dwGBitMask, gOffset, gSize); - ExtractSizeAndOffsetFromMask(pf.dwBBitMask, bOffset, bSize); - ExtractSizeAndOffsetFromMask(pf.dwABitMask, aOffset, aSize); - - for (const auto* imageFormat : ImageFormat::ALL_FORMATS) - { - if (imageFormat->GetType() != ImageFormatType::UNSIGNED) - continue; - - const auto* unsignedImageFormat = dynamic_cast(imageFormat); - - if (unsignedImageFormat->m_r_offset == rOffset && unsignedImageFormat->m_r_size == rSize - && unsignedImageFormat->m_g_offset == gOffset && unsignedImageFormat->m_g_size == gSize - && unsignedImageFormat->m_b_offset == bOffset && unsignedImageFormat->m_b_size == bSize - && unsignedImageFormat->m_a_offset == aOffset && unsignedImageFormat->m_a_size == aSize) - { - m_format = imageFormat; - return true; - } - } + _NODISCARD bool ReadPixelFormatUnsigned(DDS_PIXELFORMAT &pf) { + unsigned rOffset, rSize, gOffset, gSize, bOffset, bSize, aOffset, aSize; - std::cout << "Failed to find dds pixel format: R=" << std::hex << pf.dwRBitMask - << " G=" << std::hex << pf.dwGBitMask - << " B=" << std::hex << pf.dwBBitMask - << " A=" << std::hex << pf.dwABitMask << std::endl; + ExtractSizeAndOffsetFromMask(pf.dwRBitMask, rOffset, rSize); + ExtractSizeAndOffsetFromMask(pf.dwGBitMask, gOffset, gSize); + ExtractSizeAndOffsetFromMask(pf.dwBBitMask, bOffset, bSize); + ExtractSizeAndOffsetFromMask(pf.dwABitMask, aOffset, aSize); - return false; - } + for (const auto *imageFormat : ImageFormat::ALL_FORMATS) { + if (imageFormat->GetType() != ImageFormatType::UNSIGNED) + continue; - _NODISCARD bool ReadPixelFormat(DDS_PIXELFORMAT& pf) - { - if (pf.dwFlags & DDPF_FOURCC) - return ReadPixelFormatFourCc(pf); + const auto *unsignedImageFormat = dynamic_cast(imageFormat); - return ReadPixelFormatUnsigned(pf); + if (unsignedImageFormat->m_r_offset == rOffset && unsignedImageFormat->m_r_size == rSize && unsignedImageFormat->m_g_offset == gOffset && + unsignedImageFormat->m_g_size == gSize && unsignedImageFormat->m_b_offset == bOffset && unsignedImageFormat->m_b_size == bSize && + unsignedImageFormat->m_a_offset == aOffset && unsignedImageFormat->m_a_size == aSize) { + m_format = imageFormat; + return true; + } } - _NODISCARD bool ReadHeader() - { - DDS_HEADER header{}; - m_stream.read(reinterpret_cast(&header), sizeof(header)); - if (m_stream.gcount() != sizeof(header)) - { - std::cout << "Failed to read dds data" << std::endl; - return false; - } + std::cout << "Failed to find dds pixel format: R=" << std::hex << pf.dwRBitMask << " G=" << std::hex << pf.dwGBitMask << " B=" << std::hex << pf.dwBBitMask + << " A=" << std::hex << pf.dwABitMask << std::endl; - m_width = header.dwWidth; - m_height = header.dwHeight; - m_depth = header.dwDepth; - m_has_mip_maps = (header.dwCaps & DDSCAPS_MIPMAP) != 0 || header.dwMipMapCount > 1; + return false; + } - if (header.dwCaps2 & DDSCAPS2_CUBEMAP) - m_texture_type = TextureType::T_CUBE; - else if (header.dwDepth > 1) - m_texture_type = TextureType::T_3D; - else - m_texture_type = TextureType::T_2D; + _NODISCARD bool ReadPixelFormat(DDS_PIXELFORMAT &pf) { + if (pf.dwFlags & DDPF_FOURCC) + return ReadPixelFormatFourCc(pf); - return ReadPixelFormat(header.ddspf); + return ReadPixelFormatUnsigned(pf); + } + + _NODISCARD bool ReadHeader() { + DDS_HEADER header{}; + m_stream.read(reinterpret_cast(&header), sizeof(header)); + if (m_stream.gcount() != sizeof(header)) { + std::cout << "Failed to read dds data" << std::endl; + return false; } - _NODISCARD Texture* ReadTextureData() const - { - Texture* result; + m_width = header.dwWidth; + m_height = header.dwHeight; + m_depth = header.dwDepth; + m_has_mip_maps = (header.dwCaps & DDSCAPS_MIPMAP) != 0 || header.dwMipMapCount > 1; - switch (m_texture_type) - { - case TextureType::T_2D: - result = new Texture2D(m_format, m_width, m_height, m_has_mip_maps); - break; + if (header.dwCaps2 & DDSCAPS2_CUBEMAP) + m_texture_type = TextureType::T_CUBE; + else if (header.dwDepth > 1) + m_texture_type = TextureType::T_3D; + else + m_texture_type = TextureType::T_2D; - case TextureType::T_3D: - result = new Texture3D(m_format, m_width, m_height, m_depth, m_has_mip_maps); - break; + return ReadPixelFormat(header.ddspf); + } - case TextureType::T_CUBE: - result = new TextureCube(m_format, m_width, m_height, m_has_mip_maps); - break; + _NODISCARD Texture *ReadTextureData() const { + Texture *result; - default: - return nullptr; - } + switch (m_texture_type) { + case TextureType::T_2D: + result = new Texture2D(m_format, m_width, m_height, m_has_mip_maps); + break; - const auto mipMapCount = m_has_mip_maps ? result->GetMipMapCount() : 1; - const auto faceCount = m_texture_type == TextureType::T_CUBE ? 6 : 1; + case TextureType::T_3D: + result = new Texture3D(m_format, m_width, m_height, m_depth, m_has_mip_maps); + break; - result->Allocate(); + case TextureType::T_CUBE: + result = new TextureCube(m_format, m_width, m_height, m_has_mip_maps); + break; - for (auto mipLevel = 0; mipLevel < mipMapCount; mipLevel++) - { - const auto mipSize = result->GetSizeOfMipLevel(mipLevel); + default: + return nullptr; + } - for (auto face = 0; face < faceCount; face++) - { - m_stream.read(reinterpret_cast(result->GetBufferForMipLevel(mipLevel, face)), mipSize); + const auto mipMapCount = m_has_mip_maps ? result->GetMipMapCount() : 1; + const auto faceCount = m_texture_type == TextureType::T_CUBE ? 6 : 1; - if (m_stream.gcount() != mipSize) - { - std::cout << "Failed to read texture data from dds" << std::endl; - delete result; - return nullptr; - } - } - } + result->Allocate(); - return result; - } + for (auto mipLevel = 0; mipLevel < mipMapCount; mipLevel++) { + const auto mipSize = result->GetSizeOfMipLevel(mipLevel); -public: - DdsLoaderInternal(MemoryManager* memoryManager, std::istream& stream) - : m_memory_manager(memoryManager), - m_stream(stream), - m_texture_type(TextureType::T_2D), - m_has_mip_maps(false), - m_width(0u), - m_height(0u), - m_depth(0u), - m_format(nullptr) - { - } + for (auto face = 0; face < faceCount; face++) { + m_stream.read(reinterpret_cast(result->GetBufferForMipLevel(mipLevel, face)), mipSize); - Texture* LoadDds() - { - if (!ReadMagic() - || !ReadHeader()) - { - return nullptr; + if (m_stream.gcount() != mipSize) { + std::cout << "Failed to read texture data from dds" << std::endl; + delete result; + return nullptr; } + } + } + + return result; + } - return ReadTextureData(); +public: + DdsLoaderInternal(MemoryManager *memoryManager, std::istream &stream) + : m_memory_manager(memoryManager), m_stream(stream), m_texture_type(TextureType::T_2D), m_has_mip_maps(false), m_width(0u), m_height(0u), m_depth(0u), + m_format(nullptr) {} + + Texture *LoadDds() { + if (!ReadMagic() || !ReadHeader()) { + return nullptr; } + + return ReadTextureData(); + } }; -DdsLoader::DdsLoader(MemoryManager* memoryManager) - : m_memory_manager(memoryManager) -{ -} +DdsLoader::DdsLoader(MemoryManager *memoryManager) : m_memory_manager(memoryManager) {} -Texture* DdsLoader::LoadDds(std::istream& stream) const -{ - DdsLoaderInternal internal(m_memory_manager, stream); - return internal.LoadDds(); +Texture *DdsLoader::LoadDds(std::istream &stream) const { + DdsLoaderInternal internal(m_memory_manager, stream); + return internal.LoadDds(); } diff --git a/src/ObjLoading/Image/DdsLoader.h b/src/ObjLoading/Image/DdsLoader.h index 6d80ab36d..9ba352992 100644 --- a/src/ObjLoading/Image/DdsLoader.h +++ b/src/ObjLoading/Image/DdsLoader.h @@ -1,15 +1,14 @@ #pragma once -#include -#include "Utils/MemoryManager.h" #include "Image/Texture.h" +#include "Utils/MemoryManager.h" +#include -class DdsLoader -{ - MemoryManager* m_memory_manager; +class DdsLoader { + MemoryManager *m_memory_manager; public: - explicit DdsLoader(MemoryManager* memoryManager); + explicit DdsLoader(MemoryManager *memoryManager); - Texture* LoadDds(std::istream& stream) const; + Texture *LoadDds(std::istream &stream) const; }; diff --git a/src/ObjLoading/Image/Dx12TextureLoader.cpp b/src/ObjLoading/Image/Dx12TextureLoader.cpp index 8ea1f69c7..94a726b78 100644 --- a/src/ObjLoading/Image/Dx12TextureLoader.cpp +++ b/src/ObjLoading/Image/Dx12TextureLoader.cpp @@ -2,104 +2,85 @@ #include -Dx12TextureLoader::Dx12TextureLoader(MemoryManager* memoryManager) - : m_memory_manager(memoryManager), - m_format(DXGI_FORMAT_UNKNOWN), - m_type(TextureType::T_2D), - m_has_mip_maps(false), - m_width(1u), - m_height(1u), - m_depth(1u) -{ +Dx12TextureLoader::Dx12TextureLoader(MemoryManager *memoryManager) + : m_memory_manager(memoryManager), m_format(DXGI_FORMAT_UNKNOWN), m_type(TextureType::T_2D), m_has_mip_maps(false), m_width(1u), m_height(1u), m_depth(1u) { } -const ImageFormat* Dx12TextureLoader::GetFormatForDx12Format() const -{ - for (auto i : ImageFormat::ALL_FORMATS) - { - if (i->GetDxgiFormat() == m_format) - return i; - } +const ImageFormat *Dx12TextureLoader::GetFormatForDx12Format() const { + for (auto i : ImageFormat::ALL_FORMATS) { + if (i->GetDxgiFormat() == m_format) + return i; + } - return nullptr; + return nullptr; } -Dx12TextureLoader& Dx12TextureLoader::Format(const DXGI_FORMAT format) -{ - m_format = format; - return *this; +Dx12TextureLoader &Dx12TextureLoader::Format(const DXGI_FORMAT format) { + m_format = format; + return *this; } -Dx12TextureLoader& Dx12TextureLoader::Type(const TextureType textureType) -{ - m_type = textureType; - return *this; +Dx12TextureLoader &Dx12TextureLoader::Type(const TextureType textureType) { + m_type = textureType; + return *this; } -Dx12TextureLoader& Dx12TextureLoader::HasMipMaps(const bool hasMipMaps) -{ - m_has_mip_maps = hasMipMaps; - return *this; +Dx12TextureLoader &Dx12TextureLoader::HasMipMaps(const bool hasMipMaps) { + m_has_mip_maps = hasMipMaps; + return *this; } -Dx12TextureLoader& Dx12TextureLoader::Width(const size_t width) -{ - m_width = width; - return *this; +Dx12TextureLoader &Dx12TextureLoader::Width(const size_t width) { + m_width = width; + return *this; } -Dx12TextureLoader& Dx12TextureLoader::Height(const size_t height) -{ - m_height = height; - return *this; +Dx12TextureLoader &Dx12TextureLoader::Height(const size_t height) { + m_height = height; + return *this; } -Dx12TextureLoader& Dx12TextureLoader::Depth(const size_t depth) -{ - m_depth = depth; - return *this; +Dx12TextureLoader &Dx12TextureLoader::Depth(const size_t depth) { + m_depth = depth; + return *this; } -Texture* Dx12TextureLoader::LoadTexture(const void* data) -{ - const auto* format = GetFormatForDx12Format(); - - if (format == nullptr) - return nullptr; +Texture *Dx12TextureLoader::LoadTexture(const void *data) { + const auto *format = GetFormatForDx12Format(); - Texture* texture; - switch (m_type) - { - case TextureType::T_2D: - texture = m_memory_manager->Create(format, m_width, m_height, m_has_mip_maps); - break; + if (format == nullptr) + return nullptr; - case TextureType::T_3D: - texture = m_memory_manager->Create(format, m_width, m_height, m_depth, m_has_mip_maps); - break; + Texture *texture; + switch (m_type) { + case TextureType::T_2D: + texture = m_memory_manager->Create(format, m_width, m_height, m_has_mip_maps); + break; - case TextureType::T_CUBE: - texture = m_memory_manager->Create(format, m_width, m_width, m_has_mip_maps); - break; + case TextureType::T_3D: + texture = m_memory_manager->Create(format, m_width, m_height, m_depth, m_has_mip_maps); + break; - default: - return nullptr; - } + case TextureType::T_CUBE: + texture = m_memory_manager->Create(format, m_width, m_width, m_has_mip_maps); + break; - texture->Allocate(); - const auto mipMapCount = m_has_mip_maps ? texture->GetMipMapCount() : 1; - const auto faceCount = m_type == TextureType::T_CUBE ? 6 : 1; - const void* currentDataOffset = data; - - for (auto currentMipLevel = 0; currentMipLevel < mipMapCount; currentMipLevel++) - { - for (auto currentFace = 0; currentFace < faceCount; currentFace++) - { - const auto mipSize = texture->GetSizeOfMipLevel(currentMipLevel); - memcpy(texture->GetBufferForMipLevel(currentMipLevel, currentFace), currentDataOffset, mipSize); - currentDataOffset = reinterpret_cast(reinterpret_cast(currentDataOffset) + mipSize); - } + default: + return nullptr; + } + + texture->Allocate(); + const auto mipMapCount = m_has_mip_maps ? texture->GetMipMapCount() : 1; + const auto faceCount = m_type == TextureType::T_CUBE ? 6 : 1; + const void *currentDataOffset = data; + + for (auto currentMipLevel = 0; currentMipLevel < mipMapCount; currentMipLevel++) { + for (auto currentFace = 0; currentFace < faceCount; currentFace++) { + const auto mipSize = texture->GetSizeOfMipLevel(currentMipLevel); + memcpy(texture->GetBufferForMipLevel(currentMipLevel, currentFace), currentDataOffset, mipSize); + currentDataOffset = reinterpret_cast(reinterpret_cast(currentDataOffset) + mipSize); } + } - return texture; + return texture; } diff --git a/src/ObjLoading/Image/Dx12TextureLoader.h b/src/ObjLoading/Image/Dx12TextureLoader.h index 48306fdfd..bf572b50d 100644 --- a/src/ObjLoading/Image/Dx12TextureLoader.h +++ b/src/ObjLoading/Image/Dx12TextureLoader.h @@ -2,34 +2,33 @@ #include -#include "Utils/ClassUtils.h" #include "Image/DxgiFormat.h" -#include "Utils/MemoryManager.h" #include "Image/Texture.h" +#include "Utils/ClassUtils.h" +#include "Utils/MemoryManager.h" -class Dx12TextureLoader -{ - static std::unordered_map m_conversion_table; +class Dx12TextureLoader { + static std::unordered_map m_conversion_table; - MemoryManager* m_memory_manager; - DXGI_FORMAT m_format; - TextureType m_type; - bool m_has_mip_maps; - size_t m_width; - size_t m_height; - size_t m_depth; + MemoryManager *m_memory_manager; + DXGI_FORMAT m_format; + TextureType m_type; + bool m_has_mip_maps; + size_t m_width; + size_t m_height; + size_t m_depth; - _NODISCARD const ImageFormat* GetFormatForDx12Format() const; + _NODISCARD const ImageFormat *GetFormatForDx12Format() const; public: - explicit Dx12TextureLoader(MemoryManager* memoryManager); + explicit Dx12TextureLoader(MemoryManager *memoryManager); - Dx12TextureLoader& Format(DXGI_FORMAT format); - Dx12TextureLoader& Type(TextureType textureType); - Dx12TextureLoader& HasMipMaps(bool hasMipMaps); - Dx12TextureLoader& Width(size_t width); - Dx12TextureLoader& Height(size_t height); - Dx12TextureLoader& Depth(size_t depth); + Dx12TextureLoader &Format(DXGI_FORMAT format); + Dx12TextureLoader &Type(TextureType textureType); + Dx12TextureLoader &HasMipMaps(bool hasMipMaps); + Dx12TextureLoader &Width(size_t width); + Dx12TextureLoader &Height(size_t height); + Dx12TextureLoader &Depth(size_t depth); - Texture* LoadTexture(const void* data); + Texture *LoadTexture(const void *data); }; diff --git a/src/ObjLoading/Image/Dx9TextureLoader.cpp b/src/ObjLoading/Image/Dx9TextureLoader.cpp index bd4171dfe..198387ecd 100644 --- a/src/ObjLoading/Image/Dx9TextureLoader.cpp +++ b/src/ObjLoading/Image/Dx9TextureLoader.cpp @@ -2,104 +2,84 @@ #include -Dx9TextureLoader::Dx9TextureLoader(MemoryManager* memoryManager) - : m_memory_manager(memoryManager), - m_format(D3DFMT_UNKNOWN), - m_type(TextureType::T_2D), - m_has_mip_maps(false), - m_width(1u), - m_height(1u), - m_depth(1u) -{ -} +Dx9TextureLoader::Dx9TextureLoader(MemoryManager *memoryManager) + : m_memory_manager(memoryManager), m_format(D3DFMT_UNKNOWN), m_type(TextureType::T_2D), m_has_mip_maps(false), m_width(1u), m_height(1u), m_depth(1u) {} -const ImageFormat* Dx9TextureLoader::GetFormatForDx9Format() const -{ - for (auto i : ImageFormat::ALL_FORMATS) - { - if (i->GetD3DFormat() == m_format) - return i; - } +const ImageFormat *Dx9TextureLoader::GetFormatForDx9Format() const { + for (auto i : ImageFormat::ALL_FORMATS) { + if (i->GetD3DFormat() == m_format) + return i; + } - return nullptr; + return nullptr; } -Dx9TextureLoader& Dx9TextureLoader::Format(const D3DFORMAT format) -{ - m_format = format; - return *this; +Dx9TextureLoader &Dx9TextureLoader::Format(const D3DFORMAT format) { + m_format = format; + return *this; } -Dx9TextureLoader& Dx9TextureLoader::Type(const TextureType textureType) -{ - m_type = textureType; - return *this; +Dx9TextureLoader &Dx9TextureLoader::Type(const TextureType textureType) { + m_type = textureType; + return *this; } -Dx9TextureLoader& Dx9TextureLoader::HasMipMaps(const bool hasMipMaps) -{ - m_has_mip_maps = hasMipMaps; - return *this; +Dx9TextureLoader &Dx9TextureLoader::HasMipMaps(const bool hasMipMaps) { + m_has_mip_maps = hasMipMaps; + return *this; } -Dx9TextureLoader& Dx9TextureLoader::Width(const size_t width) -{ - m_width = width; - return *this; +Dx9TextureLoader &Dx9TextureLoader::Width(const size_t width) { + m_width = width; + return *this; } -Dx9TextureLoader& Dx9TextureLoader::Height(const size_t height) -{ - m_height = height; - return *this; +Dx9TextureLoader &Dx9TextureLoader::Height(const size_t height) { + m_height = height; + return *this; } -Dx9TextureLoader& Dx9TextureLoader::Depth(const size_t depth) -{ - m_depth = depth; - return *this; +Dx9TextureLoader &Dx9TextureLoader::Depth(const size_t depth) { + m_depth = depth; + return *this; } -Texture* Dx9TextureLoader::LoadTexture(const void* data) -{ - const auto* format = GetFormatForDx9Format(); - - if (format == nullptr) - return nullptr; +Texture *Dx9TextureLoader::LoadTexture(const void *data) { + const auto *format = GetFormatForDx9Format(); - Texture* texture; - switch (m_type) - { - case TextureType::T_2D: - texture = m_memory_manager->Create(format, m_width, m_height, m_has_mip_maps); - break; + if (format == nullptr) + return nullptr; - case TextureType::T_3D: - texture = m_memory_manager->Create(format, m_width, m_height, m_depth, m_has_mip_maps); - break; + Texture *texture; + switch (m_type) { + case TextureType::T_2D: + texture = m_memory_manager->Create(format, m_width, m_height, m_has_mip_maps); + break; - case TextureType::T_CUBE: - texture = m_memory_manager->Create(format, m_width, m_width, m_has_mip_maps); - break; + case TextureType::T_3D: + texture = m_memory_manager->Create(format, m_width, m_height, m_depth, m_has_mip_maps); + break; - default: - return nullptr; - } + case TextureType::T_CUBE: + texture = m_memory_manager->Create(format, m_width, m_width, m_has_mip_maps); + break; - texture->Allocate(); - const auto mipMapCount = m_has_mip_maps ? texture->GetMipMapCount() : 1; - const auto faceCount = m_type == TextureType::T_CUBE ? 6 : 1; - const void* currentDataOffset = data; - - for (auto currentMipLevel = 0; currentMipLevel < mipMapCount; currentMipLevel++) - { - for (auto currentFace = 0; currentFace < faceCount; currentFace++) - { - const auto mipSize = texture->GetSizeOfMipLevel(currentMipLevel); - memcpy(texture->GetBufferForMipLevel(currentMipLevel, currentFace), currentDataOffset, mipSize); - currentDataOffset = reinterpret_cast(reinterpret_cast(currentDataOffset) + mipSize); - } + default: + return nullptr; + } + + texture->Allocate(); + const auto mipMapCount = m_has_mip_maps ? texture->GetMipMapCount() : 1; + const auto faceCount = m_type == TextureType::T_CUBE ? 6 : 1; + const void *currentDataOffset = data; + + for (auto currentMipLevel = 0; currentMipLevel < mipMapCount; currentMipLevel++) { + for (auto currentFace = 0; currentFace < faceCount; currentFace++) { + const auto mipSize = texture->GetSizeOfMipLevel(currentMipLevel); + memcpy(texture->GetBufferForMipLevel(currentMipLevel, currentFace), currentDataOffset, mipSize); + currentDataOffset = reinterpret_cast(reinterpret_cast(currentDataOffset) + mipSize); } + } - return texture; + return texture; } diff --git a/src/ObjLoading/Image/Dx9TextureLoader.h b/src/ObjLoading/Image/Dx9TextureLoader.h index 8af9afd76..0958d0e1c 100644 --- a/src/ObjLoading/Image/Dx9TextureLoader.h +++ b/src/ObjLoading/Image/Dx9TextureLoader.h @@ -2,32 +2,31 @@ #include -#include "Utils/ClassUtils.h" #include "Image/D3DFormat.h" -#include "Utils/MemoryManager.h" #include "Image/Texture.h" +#include "Utils/ClassUtils.h" +#include "Utils/MemoryManager.h" -class Dx9TextureLoader -{ - MemoryManager* m_memory_manager; - D3DFORMAT m_format; - TextureType m_type; - bool m_has_mip_maps; - size_t m_width; - size_t m_height; - size_t m_depth; +class Dx9TextureLoader { + MemoryManager *m_memory_manager; + D3DFORMAT m_format; + TextureType m_type; + bool m_has_mip_maps; + size_t m_width; + size_t m_height; + size_t m_depth; - _NODISCARD const ImageFormat* GetFormatForDx9Format() const; + _NODISCARD const ImageFormat *GetFormatForDx9Format() const; public: - explicit Dx9TextureLoader(MemoryManager* memoryManager); + explicit Dx9TextureLoader(MemoryManager *memoryManager); - Dx9TextureLoader& Format(D3DFORMAT format); - Dx9TextureLoader& Type(TextureType textureType); - Dx9TextureLoader& HasMipMaps(bool hasMipMaps); - Dx9TextureLoader& Width(size_t width); - Dx9TextureLoader& Height(size_t height); - Dx9TextureLoader& Depth(size_t depth); + Dx9TextureLoader &Format(D3DFORMAT format); + Dx9TextureLoader &Type(TextureType textureType); + Dx9TextureLoader &HasMipMaps(bool hasMipMaps); + Dx9TextureLoader &Width(size_t width); + Dx9TextureLoader &Height(size_t height); + Dx9TextureLoader &Depth(size_t depth); - Texture* LoadTexture(const void* data); + Texture *LoadTexture(const void *data); }; diff --git a/src/ObjLoading/Image/IwiLoader.cpp b/src/ObjLoading/Image/IwiLoader.cpp index c7206de6c..8fb957f6e 100644 --- a/src/ObjLoading/Image/IwiLoader.cpp +++ b/src/ObjLoading/Image/IwiLoader.cpp @@ -5,474 +5,418 @@ #include "Image/IwiTypes.h" -IwiLoader::IwiLoader(MemoryManager* memoryManager) -{ - m_memory_manager = memoryManager; +IwiLoader::IwiLoader(MemoryManager *memoryManager) { m_memory_manager = memoryManager; } + +const ImageFormat *IwiLoader::GetFormat6(int8_t format) { + switch (static_cast(format)) { + case iwi6::IwiFormat::IMG_FORMAT_BITMAP_RGBA: + return &ImageFormat::FORMAT_R8_G8_B8_A8; + case iwi6::IwiFormat::IMG_FORMAT_BITMAP_RGB: + return &ImageFormat::FORMAT_R8_G8_B8; + case iwi6::IwiFormat::IMG_FORMAT_BITMAP_ALPHA: + return &ImageFormat::FORMAT_A8; + case iwi6::IwiFormat::IMG_FORMAT_DXT1: + return &ImageFormat::FORMAT_BC1; + case iwi6::IwiFormat::IMG_FORMAT_DXT3: + return &ImageFormat::FORMAT_BC2; + case iwi6::IwiFormat::IMG_FORMAT_DXT5: + return &ImageFormat::FORMAT_BC3; + case iwi6::IwiFormat::IMG_FORMAT_DXN: + return &ImageFormat::FORMAT_BC5; + case iwi6::IwiFormat::IMG_FORMAT_BITMAP_LUMINANCE_ALPHA: + return &ImageFormat::FORMAT_R8_A8; + case iwi6::IwiFormat::IMG_FORMAT_BITMAP_LUMINANCE: + return &ImageFormat::FORMAT_R8; + case iwi6::IwiFormat::IMG_FORMAT_WAVELET_RGBA: // used + case iwi6::IwiFormat::IMG_FORMAT_WAVELET_RGB: // used + case iwi6::IwiFormat::IMG_FORMAT_WAVELET_LUMINANCE_ALPHA: + case iwi6::IwiFormat::IMG_FORMAT_WAVELET_LUMINANCE: + case iwi6::IwiFormat::IMG_FORMAT_WAVELET_ALPHA: + printf("Unsupported IWI format: %i\n", format); + break; + default: + printf("Unknown IWI format: %i\n", format); + break; + } + + return nullptr; } -const ImageFormat* IwiLoader::GetFormat6(int8_t format) -{ - switch (static_cast(format)) - { - case iwi6::IwiFormat::IMG_FORMAT_BITMAP_RGBA: - return &ImageFormat::FORMAT_R8_G8_B8_A8; - case iwi6::IwiFormat::IMG_FORMAT_BITMAP_RGB: - return &ImageFormat::FORMAT_R8_G8_B8; - case iwi6::IwiFormat::IMG_FORMAT_BITMAP_ALPHA: - return &ImageFormat::FORMAT_A8; - case iwi6::IwiFormat::IMG_FORMAT_DXT1: - return &ImageFormat::FORMAT_BC1; - case iwi6::IwiFormat::IMG_FORMAT_DXT3: - return &ImageFormat::FORMAT_BC2; - case iwi6::IwiFormat::IMG_FORMAT_DXT5: - return &ImageFormat::FORMAT_BC3; - case iwi6::IwiFormat::IMG_FORMAT_DXN: - return &ImageFormat::FORMAT_BC5; - case iwi6::IwiFormat::IMG_FORMAT_BITMAP_LUMINANCE_ALPHA: - return &ImageFormat::FORMAT_R8_A8; - case iwi6::IwiFormat::IMG_FORMAT_BITMAP_LUMINANCE: - return &ImageFormat::FORMAT_R8; - case iwi6::IwiFormat::IMG_FORMAT_WAVELET_RGBA: // used - case iwi6::IwiFormat::IMG_FORMAT_WAVELET_RGB: // used - case iwi6::IwiFormat::IMG_FORMAT_WAVELET_LUMINANCE_ALPHA: - case iwi6::IwiFormat::IMG_FORMAT_WAVELET_LUMINANCE: - case iwi6::IwiFormat::IMG_FORMAT_WAVELET_ALPHA: - printf("Unsupported IWI format: %i\n", format); - break; - default: - printf("Unknown IWI format: %i\n", format); - break; - } +Texture *IwiLoader::LoadIwi6(std::istream &stream) const { + iwi6::IwiHeader header{}; + stream.read(reinterpret_cast(&header), sizeof(header)); + if (stream.gcount() != sizeof(header)) return nullptr; -} - -Texture* IwiLoader::LoadIwi6(std::istream& stream) const -{ - iwi6::IwiHeader header{}; - - stream.read(reinterpret_cast(&header), sizeof(header)); - if (stream.gcount() != sizeof(header)) - return nullptr; - - const auto* format = GetFormat6(header.format); - if (format == nullptr) - return nullptr; - - auto width = header.dimensions[0]; - auto height = header.dimensions[1]; - auto depth = header.dimensions[2]; - auto hasMipMaps = !(header.flags & iwi6::IwiFlags::IMG_FLAG_NOMIPMAPS); - Texture* texture; - if (header.flags & iwi6::IwiFlags::IMG_FLAG_CUBEMAP) - { - texture = m_memory_manager->Create(format, width, height, hasMipMaps); - } - else if (header.flags & iwi6::IwiFlags::IMG_FLAG_VOLMAP) - { - texture = m_memory_manager->Create(format, width, height, depth, hasMipMaps); - } - else - { - texture = m_memory_manager->Create(format, width, height, hasMipMaps); - } + const auto *format = GetFormat6(header.format); + if (format == nullptr) + return nullptr; - texture->Allocate(); + auto width = header.dimensions[0]; + auto height = header.dimensions[1]; + auto depth = header.dimensions[2]; + auto hasMipMaps = !(header.flags & iwi6::IwiFlags::IMG_FLAG_NOMIPMAPS); - auto currentFileSize = sizeof(iwi6::IwiHeader) + sizeof(IwiVersion); - const auto mipMapCount = hasMipMaps ? texture->GetMipMapCount() : 1; + Texture *texture; + if (header.flags & iwi6::IwiFlags::IMG_FLAG_CUBEMAP) { + texture = m_memory_manager->Create(format, width, height, hasMipMaps); + } else if (header.flags & iwi6::IwiFlags::IMG_FLAG_VOLMAP) { + texture = m_memory_manager->Create(format, width, height, depth, hasMipMaps); + } else { + texture = m_memory_manager->Create(format, width, height, hasMipMaps); + } - for (auto currentMipLevel = mipMapCount - 1; currentMipLevel >= 0; currentMipLevel--) - { - const auto sizeOfMipLevel = texture->GetSizeOfMipLevel(currentMipLevel) * texture->GetFaceCount(); - currentFileSize += sizeOfMipLevel; + texture->Allocate(); - if (currentMipLevel < static_cast(std::extent::value) - && currentFileSize != header.fileSizeForPicmip[currentMipLevel]) - { - printf("Iwi has invalid file size for picmip %i\n", currentMipLevel); + auto currentFileSize = sizeof(iwi6::IwiHeader) + sizeof(IwiVersion); + const auto mipMapCount = hasMipMaps ? texture->GetMipMapCount() : 1; - m_memory_manager->Delete(texture); - return nullptr; - } + for (auto currentMipLevel = mipMapCount - 1; currentMipLevel >= 0; currentMipLevel--) { + const auto sizeOfMipLevel = texture->GetSizeOfMipLevel(currentMipLevel) * texture->GetFaceCount(); + currentFileSize += sizeOfMipLevel; - stream.read(reinterpret_cast(texture->GetBufferForMipLevel(currentMipLevel)), sizeOfMipLevel); - if (stream.gcount() != sizeOfMipLevel) - { - printf("Unexpected eof of iwi in mip level %i\n", currentMipLevel); + if (currentMipLevel < static_cast(std::extent::value) && + currentFileSize != header.fileSizeForPicmip[currentMipLevel]) { + printf("Iwi has invalid file size for picmip %i\n", currentMipLevel); - m_memory_manager->Delete(texture); - return nullptr; - } + m_memory_manager->Delete(texture); + return nullptr; } - return texture; -} + stream.read(reinterpret_cast(texture->GetBufferForMipLevel(currentMipLevel)), sizeOfMipLevel); + if (stream.gcount() != sizeOfMipLevel) { + printf("Unexpected eof of iwi in mip level %i\n", currentMipLevel); -const ImageFormat* IwiLoader::GetFormat8(int8_t format) -{ - switch (static_cast(format)) - { - case iwi8::IwiFormat::IMG_FORMAT_BITMAP_RGBA: - return &ImageFormat::FORMAT_R8_G8_B8_A8; - case iwi8::IwiFormat::IMG_FORMAT_BITMAP_RGB: - return &ImageFormat::FORMAT_R8_G8_B8; - case iwi8::IwiFormat::IMG_FORMAT_BITMAP_ALPHA: - return &ImageFormat::FORMAT_A8; - case iwi8::IwiFormat::IMG_FORMAT_DXT1: - return &ImageFormat::FORMAT_BC1; - case iwi8::IwiFormat::IMG_FORMAT_DXT3: - return &ImageFormat::FORMAT_BC2; - case iwi8::IwiFormat::IMG_FORMAT_DXT5: - return &ImageFormat::FORMAT_BC3; - case iwi8::IwiFormat::IMG_FORMAT_DXN: - return &ImageFormat::FORMAT_BC5; - case iwi8::IwiFormat::IMG_FORMAT_BITMAP_LUMINANCE_ALPHA: - return &ImageFormat::FORMAT_R8_A8; - case iwi8::IwiFormat::IMG_FORMAT_BITMAP_LUMINANCE: - return &ImageFormat::FORMAT_R8; - case iwi8::IwiFormat::IMG_FORMAT_WAVELET_RGBA: // used - case iwi8::IwiFormat::IMG_FORMAT_WAVELET_RGB: // used - case iwi8::IwiFormat::IMG_FORMAT_WAVELET_LUMINANCE_ALPHA: - case iwi8::IwiFormat::IMG_FORMAT_WAVELET_LUMINANCE: - case iwi8::IwiFormat::IMG_FORMAT_WAVELET_ALPHA: - case iwi8::IwiFormat::IMG_FORMAT_DXT3A_AS_LUMINANCE: - case iwi8::IwiFormat::IMG_FORMAT_DXT5A_AS_LUMINANCE: - case iwi8::IwiFormat::IMG_FORMAT_DXT3A_AS_ALPHA: - case iwi8::IwiFormat::IMG_FORMAT_DXT5A_AS_ALPHA: - case iwi8::IwiFormat::IMG_FORMAT_DXT1_AS_LUMINANCE_ALPHA: - case iwi8::IwiFormat::IMG_FORMAT_DXN_AS_LUMINANCE_ALPHA: - case iwi8::IwiFormat::IMG_FORMAT_DXT1_AS_LUMINANCE: - case iwi8::IwiFormat::IMG_FORMAT_DXT1_AS_ALPHA: - printf("Unsupported IWI format: %i\n", format); - break; - default: - printf("Unknown IWI format: %i\n", format); - break; + m_memory_manager->Delete(texture); + return nullptr; } + } - return nullptr; + return texture; } -Texture* IwiLoader::LoadIwi8(std::istream& stream) const -{ - iwi8::IwiHeader header{}; +const ImageFormat *IwiLoader::GetFormat8(int8_t format) { + switch (static_cast(format)) { + case iwi8::IwiFormat::IMG_FORMAT_BITMAP_RGBA: + return &ImageFormat::FORMAT_R8_G8_B8_A8; + case iwi8::IwiFormat::IMG_FORMAT_BITMAP_RGB: + return &ImageFormat::FORMAT_R8_G8_B8; + case iwi8::IwiFormat::IMG_FORMAT_BITMAP_ALPHA: + return &ImageFormat::FORMAT_A8; + case iwi8::IwiFormat::IMG_FORMAT_DXT1: + return &ImageFormat::FORMAT_BC1; + case iwi8::IwiFormat::IMG_FORMAT_DXT3: + return &ImageFormat::FORMAT_BC2; + case iwi8::IwiFormat::IMG_FORMAT_DXT5: + return &ImageFormat::FORMAT_BC3; + case iwi8::IwiFormat::IMG_FORMAT_DXN: + return &ImageFormat::FORMAT_BC5; + case iwi8::IwiFormat::IMG_FORMAT_BITMAP_LUMINANCE_ALPHA: + return &ImageFormat::FORMAT_R8_A8; + case iwi8::IwiFormat::IMG_FORMAT_BITMAP_LUMINANCE: + return &ImageFormat::FORMAT_R8; + case iwi8::IwiFormat::IMG_FORMAT_WAVELET_RGBA: // used + case iwi8::IwiFormat::IMG_FORMAT_WAVELET_RGB: // used + case iwi8::IwiFormat::IMG_FORMAT_WAVELET_LUMINANCE_ALPHA: + case iwi8::IwiFormat::IMG_FORMAT_WAVELET_LUMINANCE: + case iwi8::IwiFormat::IMG_FORMAT_WAVELET_ALPHA: + case iwi8::IwiFormat::IMG_FORMAT_DXT3A_AS_LUMINANCE: + case iwi8::IwiFormat::IMG_FORMAT_DXT5A_AS_LUMINANCE: + case iwi8::IwiFormat::IMG_FORMAT_DXT3A_AS_ALPHA: + case iwi8::IwiFormat::IMG_FORMAT_DXT5A_AS_ALPHA: + case iwi8::IwiFormat::IMG_FORMAT_DXT1_AS_LUMINANCE_ALPHA: + case iwi8::IwiFormat::IMG_FORMAT_DXN_AS_LUMINANCE_ALPHA: + case iwi8::IwiFormat::IMG_FORMAT_DXT1_AS_LUMINANCE: + case iwi8::IwiFormat::IMG_FORMAT_DXT1_AS_ALPHA: + printf("Unsupported IWI format: %i\n", format); + break; + default: + printf("Unknown IWI format: %i\n", format); + break; + } + + return nullptr; +} - stream.read(reinterpret_cast(&header), sizeof(header)); - if (stream.gcount() != sizeof(header)) - return nullptr; +Texture *IwiLoader::LoadIwi8(std::istream &stream) const { + iwi8::IwiHeader header{}; - const auto* format = GetFormat8(header.format); - if (format == nullptr) - return nullptr; + stream.read(reinterpret_cast(&header), sizeof(header)); + if (stream.gcount() != sizeof(header)) + return nullptr; - auto width = header.dimensions[0]; - auto height = header.dimensions[1]; - auto depth = header.dimensions[2]; - auto hasMipMaps = !(header.flags & iwi8::IwiFlags::IMG_FLAG_NOMIPMAPS); + const auto *format = GetFormat8(header.format); + if (format == nullptr) + return nullptr; - Texture* texture; - if ((header.flags & iwi8::IwiFlags::IMG_FLAG_MAPTYPE_MASK) == iwi8::IwiFlags::IMG_FLAG_MAPTYPE_CUBE) - { - texture = m_memory_manager->Create(format, width, height, hasMipMaps); - } - else if ((header.flags & iwi8::IwiFlags::IMG_FLAG_MAPTYPE_MASK) == iwi8::IwiFlags::IMG_FLAG_MAPTYPE_3D) - { - texture = m_memory_manager->Create(format, width, height, depth, hasMipMaps); - } - else if ((header.flags & iwi8::IwiFlags::IMG_FLAG_MAPTYPE_MASK) == iwi8::IwiFlags::IMG_FLAG_MAPTYPE_2D) - { - texture = m_memory_manager->Create(format, width, height, hasMipMaps); - } - else if ((header.flags & iwi8::IwiFlags::IMG_FLAG_MAPTYPE_MASK) == iwi8::IwiFlags::IMG_FLAG_MAPTYPE_1D) - { - printf("Iwi has unsupported map type 1D\n"); - return nullptr; - } - else - { - printf("Iwi has unsupported map type\n"); - return nullptr; - } + auto width = header.dimensions[0]; + auto height = header.dimensions[1]; + auto depth = header.dimensions[2]; + auto hasMipMaps = !(header.flags & iwi8::IwiFlags::IMG_FLAG_NOMIPMAPS); + + Texture *texture; + if ((header.flags & iwi8::IwiFlags::IMG_FLAG_MAPTYPE_MASK) == iwi8::IwiFlags::IMG_FLAG_MAPTYPE_CUBE) { + texture = m_memory_manager->Create(format, width, height, hasMipMaps); + } else if ((header.flags & iwi8::IwiFlags::IMG_FLAG_MAPTYPE_MASK) == iwi8::IwiFlags::IMG_FLAG_MAPTYPE_3D) { + texture = m_memory_manager->Create(format, width, height, depth, hasMipMaps); + } else if ((header.flags & iwi8::IwiFlags::IMG_FLAG_MAPTYPE_MASK) == iwi8::IwiFlags::IMG_FLAG_MAPTYPE_2D) { + texture = m_memory_manager->Create(format, width, height, hasMipMaps); + } else if ((header.flags & iwi8::IwiFlags::IMG_FLAG_MAPTYPE_MASK) == iwi8::IwiFlags::IMG_FLAG_MAPTYPE_1D) { + printf("Iwi has unsupported map type 1D\n"); + return nullptr; + } else { + printf("Iwi has unsupported map type\n"); + return nullptr; + } - texture->Allocate(); + texture->Allocate(); - auto currentFileSize = sizeof(iwi8::IwiHeader) + sizeof(IwiVersion); - const auto mipMapCount = hasMipMaps ? texture->GetMipMapCount() : 1; + auto currentFileSize = sizeof(iwi8::IwiHeader) + sizeof(IwiVersion); + const auto mipMapCount = hasMipMaps ? texture->GetMipMapCount() : 1; - for (auto currentMipLevel = mipMapCount - 1; currentMipLevel >= 0; currentMipLevel--) - { - const auto sizeOfMipLevel = texture->GetSizeOfMipLevel(currentMipLevel) * texture->GetFaceCount(); - currentFileSize += sizeOfMipLevel; + for (auto currentMipLevel = mipMapCount - 1; currentMipLevel >= 0; currentMipLevel--) { + const auto sizeOfMipLevel = texture->GetSizeOfMipLevel(currentMipLevel) * texture->GetFaceCount(); + currentFileSize += sizeOfMipLevel; - if (currentMipLevel < static_cast(std::extent::value) - && currentFileSize != header.fileSizeForPicmip[currentMipLevel]) - { - printf("Iwi has invalid file size for picmip %i\n", currentMipLevel); + if (currentMipLevel < static_cast(std::extent::value) && + currentFileSize != header.fileSizeForPicmip[currentMipLevel]) { + printf("Iwi has invalid file size for picmip %i\n", currentMipLevel); - m_memory_manager->Delete(texture); - return nullptr; - } + m_memory_manager->Delete(texture); + return nullptr; + } - stream.read(reinterpret_cast(texture->GetBufferForMipLevel(currentMipLevel)), sizeOfMipLevel); - if (stream.gcount() != sizeOfMipLevel) - { - printf("Unexpected eof of iwi in mip level %i\n", currentMipLevel); + stream.read(reinterpret_cast(texture->GetBufferForMipLevel(currentMipLevel)), sizeOfMipLevel); + if (stream.gcount() != sizeOfMipLevel) { + printf("Unexpected eof of iwi in mip level %i\n", currentMipLevel); - m_memory_manager->Delete(texture); - return nullptr; - } + m_memory_manager->Delete(texture); + return nullptr; } + } - return texture; + return texture; } -const ImageFormat* IwiLoader::GetFormat13(int8_t format) -{ - switch (static_cast(format)) - { - case iwi13::IwiFormat::IMG_FORMAT_BITMAP_RGBA: - return &ImageFormat::FORMAT_R8_G8_B8_A8; - case iwi13::IwiFormat::IMG_FORMAT_BITMAP_RGB: - return &ImageFormat::FORMAT_R8_G8_B8; - case iwi13::IwiFormat::IMG_FORMAT_BITMAP_ALPHA: - return &ImageFormat::FORMAT_A8; - case iwi13::IwiFormat::IMG_FORMAT_DXT1: - return &ImageFormat::FORMAT_BC1; - case iwi13::IwiFormat::IMG_FORMAT_DXT3: - return &ImageFormat::FORMAT_BC2; - case iwi13::IwiFormat::IMG_FORMAT_DXT5: - return &ImageFormat::FORMAT_BC3; - case iwi13::IwiFormat::IMG_FORMAT_DXN: - return &ImageFormat::FORMAT_BC5; - case iwi13::IwiFormat::IMG_FORMAT_BITMAP_LUMINANCE_ALPHA: - return &ImageFormat::FORMAT_R8_A8; - case iwi13::IwiFormat::IMG_FORMAT_BITMAP_LUMINANCE: - return &ImageFormat::FORMAT_R8; - case iwi13::IwiFormat::IMG_FORMAT_WAVELET_RGBA: // used - case iwi13::IwiFormat::IMG_FORMAT_WAVELET_RGB: // used - case iwi13::IwiFormat::IMG_FORMAT_WAVELET_LUMINANCE_ALPHA: - case iwi13::IwiFormat::IMG_FORMAT_WAVELET_LUMINANCE: - case iwi13::IwiFormat::IMG_FORMAT_WAVELET_ALPHA: - case iwi13::IwiFormat::IMG_FORMAT_BITMAP_RGB565: - case iwi13::IwiFormat::IMG_FORMAT_BITMAP_RGB5A3: - case iwi13::IwiFormat::IMG_FORMAT_BITMAP_C8: - case iwi13::IwiFormat::IMG_FORMAT_BITMAP_RGBA8: - case iwi13::IwiFormat::IMG_FORMAT_A16B16G16R16F: - printf("Unsupported IWI format: %i\n", format); - break; - default: - printf("Unknown IWI format: %i\n", format); - break; - } - - return nullptr; +const ImageFormat *IwiLoader::GetFormat13(int8_t format) { + switch (static_cast(format)) { + case iwi13::IwiFormat::IMG_FORMAT_BITMAP_RGBA: + return &ImageFormat::FORMAT_R8_G8_B8_A8; + case iwi13::IwiFormat::IMG_FORMAT_BITMAP_RGB: + return &ImageFormat::FORMAT_R8_G8_B8; + case iwi13::IwiFormat::IMG_FORMAT_BITMAP_ALPHA: + return &ImageFormat::FORMAT_A8; + case iwi13::IwiFormat::IMG_FORMAT_DXT1: + return &ImageFormat::FORMAT_BC1; + case iwi13::IwiFormat::IMG_FORMAT_DXT3: + return &ImageFormat::FORMAT_BC2; + case iwi13::IwiFormat::IMG_FORMAT_DXT5: + return &ImageFormat::FORMAT_BC3; + case iwi13::IwiFormat::IMG_FORMAT_DXN: + return &ImageFormat::FORMAT_BC5; + case iwi13::IwiFormat::IMG_FORMAT_BITMAP_LUMINANCE_ALPHA: + return &ImageFormat::FORMAT_R8_A8; + case iwi13::IwiFormat::IMG_FORMAT_BITMAP_LUMINANCE: + return &ImageFormat::FORMAT_R8; + case iwi13::IwiFormat::IMG_FORMAT_WAVELET_RGBA: // used + case iwi13::IwiFormat::IMG_FORMAT_WAVELET_RGB: // used + case iwi13::IwiFormat::IMG_FORMAT_WAVELET_LUMINANCE_ALPHA: + case iwi13::IwiFormat::IMG_FORMAT_WAVELET_LUMINANCE: + case iwi13::IwiFormat::IMG_FORMAT_WAVELET_ALPHA: + case iwi13::IwiFormat::IMG_FORMAT_BITMAP_RGB565: + case iwi13::IwiFormat::IMG_FORMAT_BITMAP_RGB5A3: + case iwi13::IwiFormat::IMG_FORMAT_BITMAP_C8: + case iwi13::IwiFormat::IMG_FORMAT_BITMAP_RGBA8: + case iwi13::IwiFormat::IMG_FORMAT_A16B16G16R16F: + printf("Unsupported IWI format: %i\n", format); + break; + default: + printf("Unknown IWI format: %i\n", format); + break; + } + + return nullptr; } -Texture* IwiLoader::LoadIwi13(std::istream& stream) const -{ - iwi13::IwiHeader header{}; +Texture *IwiLoader::LoadIwi13(std::istream &stream) const { + iwi13::IwiHeader header{}; - stream.read(reinterpret_cast(&header), sizeof(header)); - if (stream.gcount() != sizeof(header)) - return nullptr; + stream.read(reinterpret_cast(&header), sizeof(header)); + if (stream.gcount() != sizeof(header)) + return nullptr; - const auto* format = GetFormat6(header.format); - if (format == nullptr) - return nullptr; + const auto *format = GetFormat6(header.format); + if (format == nullptr) + return nullptr; - auto width = header.dimensions[0]; - auto height = header.dimensions[1]; - auto depth = header.dimensions[2]; - auto hasMipMaps = !(header.flags & iwi13::IwiFlags::IMG_FLAG_NOMIPMAPS); + auto width = header.dimensions[0]; + auto height = header.dimensions[1]; + auto depth = header.dimensions[2]; + auto hasMipMaps = !(header.flags & iwi13::IwiFlags::IMG_FLAG_NOMIPMAPS); - Texture* texture; - if (header.flags & iwi13::IwiFlags::IMG_FLAG_CUBEMAP) - { - texture = m_memory_manager->Create(format, width, height, hasMipMaps); - } - else if (header.flags & iwi13::IwiFlags::IMG_FLAG_VOLMAP) - { - texture = m_memory_manager->Create(format, width, height, depth, hasMipMaps); - } - else - { - texture = m_memory_manager->Create(format, width, height, hasMipMaps); - } + Texture *texture; + if (header.flags & iwi13::IwiFlags::IMG_FLAG_CUBEMAP) { + texture = m_memory_manager->Create(format, width, height, hasMipMaps); + } else if (header.flags & iwi13::IwiFlags::IMG_FLAG_VOLMAP) { + texture = m_memory_manager->Create(format, width, height, depth, hasMipMaps); + } else { + texture = m_memory_manager->Create(format, width, height, hasMipMaps); + } - texture->Allocate(); + texture->Allocate(); - auto currentFileSize = sizeof(iwi13::IwiHeader) + sizeof(IwiVersion); - const auto mipMapCount = hasMipMaps ? texture->GetMipMapCount() : 1; + auto currentFileSize = sizeof(iwi13::IwiHeader) + sizeof(IwiVersion); + const auto mipMapCount = hasMipMaps ? texture->GetMipMapCount() : 1; - for (auto currentMipLevel = mipMapCount - 1; currentMipLevel >= 0; currentMipLevel--) - { - const auto sizeOfMipLevel = texture->GetSizeOfMipLevel(currentMipLevel) * texture->GetFaceCount(); - currentFileSize += sizeOfMipLevel; + for (auto currentMipLevel = mipMapCount - 1; currentMipLevel >= 0; currentMipLevel--) { + const auto sizeOfMipLevel = texture->GetSizeOfMipLevel(currentMipLevel) * texture->GetFaceCount(); + currentFileSize += sizeOfMipLevel; - if (currentMipLevel < static_cast(std::extent::value) - && currentFileSize != header.fileSizeForPicmip[currentMipLevel]) - { - printf("Iwi has invalid file size for picmip %i\n", currentMipLevel); + if (currentMipLevel < static_cast(std::extent::value) && + currentFileSize != header.fileSizeForPicmip[currentMipLevel]) { + printf("Iwi has invalid file size for picmip %i\n", currentMipLevel); - m_memory_manager->Delete(texture); - return nullptr; - } + m_memory_manager->Delete(texture); + return nullptr; + } - stream.read(reinterpret_cast(texture->GetBufferForMipLevel(currentMipLevel)), sizeOfMipLevel); - if (stream.gcount() != sizeOfMipLevel) - { - printf("Unexpected eof of iwi in mip level %i\n", currentMipLevel); + stream.read(reinterpret_cast(texture->GetBufferForMipLevel(currentMipLevel)), sizeOfMipLevel); + if (stream.gcount() != sizeOfMipLevel) { + printf("Unexpected eof of iwi in mip level %i\n", currentMipLevel); - m_memory_manager->Delete(texture); - return nullptr; - } + m_memory_manager->Delete(texture); + return nullptr; } + } - return texture; + return texture; } -const ImageFormat* IwiLoader::GetFormat27(int8_t format) -{ - switch (static_cast(format)) - { - case iwi27::IwiFormat::IMG_FORMAT_BITMAP_RGBA: - return &ImageFormat::FORMAT_R8_G8_B8_A8; - case iwi27::IwiFormat::IMG_FORMAT_BITMAP_ALPHA: - return &ImageFormat::FORMAT_A8; - case iwi27::IwiFormat::IMG_FORMAT_DXT1: - return &ImageFormat::FORMAT_BC1; - case iwi27::IwiFormat::IMG_FORMAT_DXT3: - return &ImageFormat::FORMAT_BC2; - case iwi27::IwiFormat::IMG_FORMAT_DXT5: - return &ImageFormat::FORMAT_BC3; - case iwi27::IwiFormat::IMG_FORMAT_DXN: - return &ImageFormat::FORMAT_BC5; - case iwi27::IwiFormat::IMG_FORMAT_A16B16G16R16F: - assert(false); // Unsupported yet - return &ImageFormat::FORMAT_R16_G16_B16_A16_FLOAT; - case iwi27::IwiFormat::IMG_FORMAT_BITMAP_RGB: - return &ImageFormat::FORMAT_R8_G8_B8; - case iwi27::IwiFormat::IMG_FORMAT_BITMAP_LUMINANCE_ALPHA: - return &ImageFormat::FORMAT_R8_A8; - case iwi27::IwiFormat::IMG_FORMAT_BITMAP_LUMINANCE: - return &ImageFormat::FORMAT_R8; - case iwi27::IwiFormat::IMG_FORMAT_WAVELET_RGBA: - case iwi27::IwiFormat::IMG_FORMAT_WAVELET_RGB: - case iwi27::IwiFormat::IMG_FORMAT_WAVELET_LUMINANCE_ALPHA: - case iwi27::IwiFormat::IMG_FORMAT_WAVELET_LUMINANCE: - case iwi27::IwiFormat::IMG_FORMAT_WAVELET_ALPHA: - case iwi27::IwiFormat::IMG_FORMAT_BITMAP_RGB565: - case iwi27::IwiFormat::IMG_FORMAT_BITMAP_RGB5A3: - case iwi27::IwiFormat::IMG_FORMAT_BITMAP_C8: - case iwi27::IwiFormat::IMG_FORMAT_BITMAP_RGBA8: - printf("Unsupported IWI format: %i\n", format); - break; - default: - printf("Unknown IWI format: %i\n", format); - break; - } - - return nullptr; +const ImageFormat *IwiLoader::GetFormat27(int8_t format) { + switch (static_cast(format)) { + case iwi27::IwiFormat::IMG_FORMAT_BITMAP_RGBA: + return &ImageFormat::FORMAT_R8_G8_B8_A8; + case iwi27::IwiFormat::IMG_FORMAT_BITMAP_ALPHA: + return &ImageFormat::FORMAT_A8; + case iwi27::IwiFormat::IMG_FORMAT_DXT1: + return &ImageFormat::FORMAT_BC1; + case iwi27::IwiFormat::IMG_FORMAT_DXT3: + return &ImageFormat::FORMAT_BC2; + case iwi27::IwiFormat::IMG_FORMAT_DXT5: + return &ImageFormat::FORMAT_BC3; + case iwi27::IwiFormat::IMG_FORMAT_DXN: + return &ImageFormat::FORMAT_BC5; + case iwi27::IwiFormat::IMG_FORMAT_A16B16G16R16F: + assert(false); // Unsupported yet + return &ImageFormat::FORMAT_R16_G16_B16_A16_FLOAT; + case iwi27::IwiFormat::IMG_FORMAT_BITMAP_RGB: + return &ImageFormat::FORMAT_R8_G8_B8; + case iwi27::IwiFormat::IMG_FORMAT_BITMAP_LUMINANCE_ALPHA: + return &ImageFormat::FORMAT_R8_A8; + case iwi27::IwiFormat::IMG_FORMAT_BITMAP_LUMINANCE: + return &ImageFormat::FORMAT_R8; + case iwi27::IwiFormat::IMG_FORMAT_WAVELET_RGBA: + case iwi27::IwiFormat::IMG_FORMAT_WAVELET_RGB: + case iwi27::IwiFormat::IMG_FORMAT_WAVELET_LUMINANCE_ALPHA: + case iwi27::IwiFormat::IMG_FORMAT_WAVELET_LUMINANCE: + case iwi27::IwiFormat::IMG_FORMAT_WAVELET_ALPHA: + case iwi27::IwiFormat::IMG_FORMAT_BITMAP_RGB565: + case iwi27::IwiFormat::IMG_FORMAT_BITMAP_RGB5A3: + case iwi27::IwiFormat::IMG_FORMAT_BITMAP_C8: + case iwi27::IwiFormat::IMG_FORMAT_BITMAP_RGBA8: + printf("Unsupported IWI format: %i\n", format); + break; + default: + printf("Unknown IWI format: %i\n", format); + break; + } + + return nullptr; } -Texture* IwiLoader::LoadIwi27(std::istream& stream) const -{ - iwi27::IwiHeader header{}; +Texture *IwiLoader::LoadIwi27(std::istream &stream) const { + iwi27::IwiHeader header{}; - stream.read(reinterpret_cast(&header), sizeof(header)); - if (stream.gcount() != sizeof(header)) - return nullptr; + stream.read(reinterpret_cast(&header), sizeof(header)); + if (stream.gcount() != sizeof(header)) + return nullptr; - const auto* format = GetFormat27(header.format); - if (format == nullptr) - return nullptr; + const auto *format = GetFormat27(header.format); + if (format == nullptr) + return nullptr; - auto width = header.dimensions[0]; - auto height = header.dimensions[1]; - auto depth = header.dimensions[2]; - auto hasMipMaps = !(header.flags & iwi27::IwiFlags::IMG_FLAG_NOMIPMAPS); + auto width = header.dimensions[0]; + auto height = header.dimensions[1]; + auto depth = header.dimensions[2]; + auto hasMipMaps = !(header.flags & iwi27::IwiFlags::IMG_FLAG_NOMIPMAPS); - Texture* texture; - if (header.flags & iwi27::IwiFlags::IMG_FLAG_CUBEMAP) - { - texture = m_memory_manager->Create(format, width, height, hasMipMaps); - } - else if (header.flags & iwi27::IwiFlags::IMG_FLAG_VOLMAP) - { - texture = m_memory_manager->Create(format, width, height, depth, hasMipMaps); - } - else - { - texture = m_memory_manager->Create(format, width, height, hasMipMaps); - } + Texture *texture; + if (header.flags & iwi27::IwiFlags::IMG_FLAG_CUBEMAP) { + texture = m_memory_manager->Create(format, width, height, hasMipMaps); + } else if (header.flags & iwi27::IwiFlags::IMG_FLAG_VOLMAP) { + texture = m_memory_manager->Create(format, width, height, depth, hasMipMaps); + } else { + texture = m_memory_manager->Create(format, width, height, hasMipMaps); + } - texture->Allocate(); + texture->Allocate(); - auto currentFileSize = sizeof(iwi27::IwiHeader) + sizeof(IwiVersion); - const auto mipMapCount = hasMipMaps ? texture->GetMipMapCount() : 1; + auto currentFileSize = sizeof(iwi27::IwiHeader) + sizeof(IwiVersion); + const auto mipMapCount = hasMipMaps ? texture->GetMipMapCount() : 1; - for (auto currentMipLevel = mipMapCount - 1; currentMipLevel >= 0; currentMipLevel--) - { - const auto sizeOfMipLevel = texture->GetSizeOfMipLevel(currentMipLevel) * texture->GetFaceCount(); - currentFileSize += sizeOfMipLevel; + for (auto currentMipLevel = mipMapCount - 1; currentMipLevel >= 0; currentMipLevel--) { + const auto sizeOfMipLevel = texture->GetSizeOfMipLevel(currentMipLevel) * texture->GetFaceCount(); + currentFileSize += sizeOfMipLevel; - if (currentMipLevel < static_cast(std::extent::value) - && currentFileSize != header.fileSizeForPicmip[currentMipLevel]) - { - printf("Iwi has invalid file size for picmip %i\n", currentMipLevel); + if (currentMipLevel < static_cast(std::extent::value) && + currentFileSize != header.fileSizeForPicmip[currentMipLevel]) { + printf("Iwi has invalid file size for picmip %i\n", currentMipLevel); - m_memory_manager->Delete(texture); - return nullptr; - } + m_memory_manager->Delete(texture); + return nullptr; + } - stream.read(reinterpret_cast(texture->GetBufferForMipLevel(currentMipLevel)), sizeOfMipLevel); - if (stream.gcount() != sizeOfMipLevel) - { - printf("Unexpected eof of iwi in mip level %i\n", currentMipLevel); + stream.read(reinterpret_cast(texture->GetBufferForMipLevel(currentMipLevel)), sizeOfMipLevel); + if (stream.gcount() != sizeOfMipLevel) { + printf("Unexpected eof of iwi in mip level %i\n", currentMipLevel); - m_memory_manager->Delete(texture); - return nullptr; - } + m_memory_manager->Delete(texture); + return nullptr; } + } - return texture; + return texture; } -Texture* IwiLoader::LoadIwi(std::istream& stream) -{ - IwiVersion iwiVersion{}; +Texture *IwiLoader::LoadIwi(std::istream &stream) { + IwiVersion iwiVersion{}; - stream.read(reinterpret_cast(&iwiVersion), sizeof(iwiVersion)); - if (stream.gcount() != sizeof(iwiVersion)) - return nullptr; + stream.read(reinterpret_cast(&iwiVersion), sizeof(iwiVersion)); + if (stream.gcount() != sizeof(iwiVersion)) + return nullptr; - if (iwiVersion.tag[0] != 'I' - || iwiVersion.tag[1] != 'W' - || iwiVersion.tag[2] != 'i') - { - printf("Invalid IWI magic\n"); - } + if (iwiVersion.tag[0] != 'I' || iwiVersion.tag[1] != 'W' || iwiVersion.tag[2] != 'i') { + printf("Invalid IWI magic\n"); + } - switch (iwiVersion.version) - { - case 6: - return LoadIwi6(stream); + switch (iwiVersion.version) { + case 6: + return LoadIwi6(stream); - case 8: - return LoadIwi8(stream); + case 8: + return LoadIwi8(stream); - case 13: - return LoadIwi13(stream); + case 13: + return LoadIwi13(stream); - case 27: - return LoadIwi27(stream); + case 27: + return LoadIwi27(stream); - default: - break; - } + default: + break; + } - printf("Unknown IWI version %i\n", iwiVersion.version); - return nullptr; + printf("Unknown IWI version %i\n", iwiVersion.version); + return nullptr; } diff --git a/src/ObjLoading/Image/IwiLoader.h b/src/ObjLoading/Image/IwiLoader.h index c06337405..e5d912708 100644 --- a/src/ObjLoading/Image/IwiLoader.h +++ b/src/ObjLoading/Image/IwiLoader.h @@ -1,27 +1,26 @@ #pragma once -#include -#include "Utils/MemoryManager.h" #include "Image/Texture.h" +#include "Utils/MemoryManager.h" +#include -class IwiLoader -{ - MemoryManager* m_memory_manager; +class IwiLoader { + MemoryManager *m_memory_manager; - static const ImageFormat* GetFormat6(int8_t format); - Texture* LoadIwi6(std::istream& stream) const; + static const ImageFormat *GetFormat6(int8_t format); + Texture *LoadIwi6(std::istream &stream) const; - static const ImageFormat* GetFormat8(int8_t format); - Texture* LoadIwi8(std::istream& stream) const; + static const ImageFormat *GetFormat8(int8_t format); + Texture *LoadIwi8(std::istream &stream) const; - static const ImageFormat* GetFormat13(int8_t format); - Texture* LoadIwi13(std::istream& stream) const; + static const ImageFormat *GetFormat13(int8_t format); + Texture *LoadIwi13(std::istream &stream) const; - static const ImageFormat* GetFormat27(int8_t format); - Texture* LoadIwi27(std::istream& stream) const; + static const ImageFormat *GetFormat27(int8_t format); + Texture *LoadIwi27(std::istream &stream) const; public: - explicit IwiLoader(MemoryManager* memoryManager); + explicit IwiLoader(MemoryManager *memoryManager); - Texture* LoadIwi(std::istream& stream); + Texture *LoadIwi(std::istream &stream); }; diff --git a/src/ObjLoading/InfoString/InfoStringToStructConverterBase.cpp b/src/ObjLoading/InfoString/InfoStringToStructConverterBase.cpp index 1e4fb97a4..7d267c7ed 100644 --- a/src/ObjLoading/InfoString/InfoStringToStructConverterBase.cpp +++ b/src/ObjLoading/InfoString/InfoStringToStructConverterBase.cpp @@ -3,242 +3,200 @@ #include #include -InfoStringToStructConverterBase::InfoStringToStructConverterBase(const InfoString& infoString, void* structure, ZoneScriptStrings& zoneScriptStrings, MemoryManager* memory) - : m_info_string(infoString), - m_zone_script_strings(zoneScriptStrings), - m_memory(memory), - m_structure(structure) -{ +InfoStringToStructConverterBase::InfoStringToStructConverterBase(const InfoString &infoString, void *structure, ZoneScriptStrings &zoneScriptStrings, + MemoryManager *memory) + : m_info_string(infoString), m_zone_script_strings(zoneScriptStrings), m_memory(memory), m_structure(structure) {} + +bool InfoStringToStructConverterBase::ParseAsArray(const std::string &value, std::vector &valueArray) { + auto startPos = 0u; + for (auto ci = 0u; ci < value.size(); ci++) { + const auto c = value[ci]; + + if (c == '\r' && ci + 1 < value.size() && value[ci + 1] == '\n') { + valueArray.emplace_back(value, startPos, ci - startPos); + startPos = ++ci + 1; + } else if (c == '\n') { + valueArray.emplace_back(value, startPos, ci - startPos); + startPos = ci + 1; + } + } + + if (startPos < value.size()) { + valueArray.emplace_back(value, startPos, value.size() - startPos); + } + + return true; } -bool InfoStringToStructConverterBase::ParseAsArray(const std::string& value, std::vector& valueArray) -{ - auto startPos = 0u; - for (auto ci = 0u; ci < value.size(); ci++) - { - const auto c = value[ci]; - - if (c == '\r' && ci + 1 < value.size() && value[ci + 1] == '\n') - { - valueArray.emplace_back(value, startPos, ci - startPos); - startPos = ++ci + 1; - } - else if(c == '\n') - { - valueArray.emplace_back(value, startPos, ci - startPos); - startPos = ci + 1; - } - } +bool InfoStringToStructConverterBase::ParseAsPairs(const std::string &value, std::vector> &valueArray) const { + std::string key; + auto isKey = true; - if(startPos < value.size()) - { - valueArray.emplace_back(value, startPos, value.size() - startPos); + for (auto ci = 0u; ci < value.size(); ci++) { + auto c = value[ci]; + + if (c == '\r' && ci + 1 < value.size() && value[ci + 1] == '\n') + c = value[++ci]; + + if (c == '\n' && !isKey) { + std::cout << "Expected value but got new line" << std::endl; + return false; } - return true; -} + if (isspace(c)) + continue; + + int separator; + const auto startPos = ci; + while (true) { + ci++; + if (ci >= value.size()) { + separator = EOF; + break; + } + c = value[ci]; + if (c == '\r' && ci + 1 < value.size() && value[ci + 1] == '\n') + c = value[++ci]; + if (isspace(c)) { + separator = static_cast(static_cast(c)); + break; + } + } -bool InfoStringToStructConverterBase::ParseAsPairs(const std::string& value, std::vector>& valueArray) const -{ - std::string key; - auto isKey = true; - - for (auto ci = 0u; ci < value.size(); ci++) - { - auto c = value[ci]; - - if (c == '\r' && ci + 1 < value.size() && value[ci + 1] == '\n') - c = value[++ci]; - - if (c == '\n' && !isKey) - { - std::cout << "Expected value but got new line" << std::endl; - return false; - } - - if (isspace(c)) - continue; - - int separator; - const auto startPos = ci; - while (true) - { - ci++; - if (ci >= value.size()) - { - separator = EOF; - break; - } - c = value[ci]; - if (c == '\r' && ci + 1 < value.size() && value[ci + 1] == '\n') - c = value[++ci]; - if (isspace(c)) - { - separator = static_cast(static_cast(c)); - break; - } - } - - if (isKey) - { - if (separator == '\n' || separator == EOF) - { - std::cout << "Expected value but got new line" << std::endl; - return false; - } - key = std::string(value, startPos, ci - startPos); - } - else - { - auto parsedValue = std::string(value, startPos, ci - startPos); - valueArray.emplace_back(std::make_pair(std::move(key), std::move(parsedValue))); - key = std::string(); - } - isKey = !isKey; + if (isKey) { + if (separator == '\n' || separator == EOF) { + std::cout << "Expected value but got new line" << std::endl; + return false; + } + key = std::string(value, startPos, ci - startPos); + } else { + auto parsedValue = std::string(value, startPos, ci - startPos); + valueArray.emplace_back(std::make_pair(std::move(key), std::move(parsedValue))); + key = std::string(); } + isKey = !isKey; + } - return true; + return true; } -bool InfoStringToStructConverterBase::ConvertString(const std::string& value, const size_t offset) -{ - *reinterpret_cast(reinterpret_cast(m_structure) + offset) = m_memory->Dup(value.c_str()); - return true; +bool InfoStringToStructConverterBase::ConvertString(const std::string &value, const size_t offset) { + *reinterpret_cast(reinterpret_cast(m_structure) + offset) = m_memory->Dup(value.c_str()); + return true; } -bool InfoStringToStructConverterBase::ConvertStringBuffer(const std::string& value, const size_t offset, const size_t bufferSize) -{ - strncpy(reinterpret_cast(reinterpret_cast(m_structure) + offset), value.c_str(), bufferSize); - return true; +bool InfoStringToStructConverterBase::ConvertStringBuffer(const std::string &value, const size_t offset, const size_t bufferSize) { + strncpy(reinterpret_cast(reinterpret_cast(m_structure) + offset), value.c_str(), bufferSize); + return true; } -bool InfoStringToStructConverterBase::ConvertInt(const std::string& value, const size_t offset) -{ - char* endPtr; - *reinterpret_cast(reinterpret_cast(m_structure) + offset) = strtol(value.c_str(), &endPtr, 0); +bool InfoStringToStructConverterBase::ConvertInt(const std::string &value, const size_t offset) { + char *endPtr; + *reinterpret_cast(reinterpret_cast(m_structure) + offset) = strtol(value.c_str(), &endPtr, 0); - if(endPtr != &value[value.size()]) - { - std::cout << "Failed to parse value \"" << value << "\" as int" << std::endl; - return false; - } + if (endPtr != &value[value.size()]) { + std::cout << "Failed to parse value \"" << value << "\" as int" << std::endl; + return false; + } - return true; + return true; } -bool InfoStringToStructConverterBase::ConvertUint(const std::string& value, const size_t offset) -{ - char* endPtr; - *reinterpret_cast(reinterpret_cast(m_structure) + offset) = strtoul(value.c_str(), &endPtr, 0); +bool InfoStringToStructConverterBase::ConvertUint(const std::string &value, const size_t offset) { + char *endPtr; + *reinterpret_cast(reinterpret_cast(m_structure) + offset) = strtoul(value.c_str(), &endPtr, 0); - if (endPtr != &value[value.size()]) - { - std::cout << "Failed to parse value \"" << value << "\" as uint" << std::endl; - return false; - } + if (endPtr != &value[value.size()]) { + std::cout << "Failed to parse value \"" << value << "\" as uint" << std::endl; + return false; + } - return true; + return true; } -bool InfoStringToStructConverterBase::ConvertBool(const std::string& value, const size_t offset) -{ - char* endPtr; - const auto intValue = strtol(value.c_str(), &endPtr, 0); +bool InfoStringToStructConverterBase::ConvertBool(const std::string &value, const size_t offset) { + char *endPtr; + const auto intValue = strtol(value.c_str(), &endPtr, 0); - *reinterpret_cast(reinterpret_cast(m_structure) + offset) = intValue != 0; - if (endPtr != &value[value.size()]) - { - std::cout << "Failed to parse value \"" << value << "\" as bool" << std::endl; - return false; - } + *reinterpret_cast(reinterpret_cast(m_structure) + offset) = intValue != 0; + if (endPtr != &value[value.size()]) { + std::cout << "Failed to parse value \"" << value << "\" as bool" << std::endl; + return false; + } - return true; + return true; } -bool InfoStringToStructConverterBase::ConvertQBoolean(const std::string& value, const size_t offset) -{ - char* endPtr; - const auto intValue = strtol(value.c_str(), &endPtr, 0); +bool InfoStringToStructConverterBase::ConvertQBoolean(const std::string &value, const size_t offset) { + char *endPtr; + const auto intValue = strtol(value.c_str(), &endPtr, 0); - *reinterpret_cast(reinterpret_cast(m_structure) + offset) = intValue != 0 ? 1 : 0; - if (endPtr != &value[value.size()]) - { - std::cout << "Failed to parse value \"" << value << "\" as qboolean" << std::endl; - return false; - } + *reinterpret_cast(reinterpret_cast(m_structure) + offset) = intValue != 0 ? 1 : 0; + if (endPtr != &value[value.size()]) { + std::cout << "Failed to parse value \"" << value << "\" as qboolean" << std::endl; + return false; + } - return true; + return true; } -bool InfoStringToStructConverterBase::ConvertFloat(const std::string& value, const size_t offset) -{ - char* endPtr; - *reinterpret_cast(reinterpret_cast(m_structure) + offset) = strtof(value.c_str(), &endPtr); +bool InfoStringToStructConverterBase::ConvertFloat(const std::string &value, const size_t offset) { + char *endPtr; + *reinterpret_cast(reinterpret_cast(m_structure) + offset) = strtof(value.c_str(), &endPtr); - if (endPtr != &value[value.size()]) - { - std::cout << "Failed to parse value \"" << value << "\" as float" << std::endl; - return false; - } + if (endPtr != &value[value.size()]) { + std::cout << "Failed to parse value \"" << value << "\" as float" << std::endl; + return false; + } - return true; + return true; } -bool InfoStringToStructConverterBase::ConvertMilliseconds(const std::string& value, const size_t offset) -{ - char* endPtr; - *reinterpret_cast(reinterpret_cast(m_structure) + offset) = static_cast(strtof(value.c_str(), &endPtr) * 1000.0f); +bool InfoStringToStructConverterBase::ConvertMilliseconds(const std::string &value, const size_t offset) { + char *endPtr; + *reinterpret_cast(reinterpret_cast(m_structure) + offset) = static_cast(strtof(value.c_str(), &endPtr) * 1000.0f); - if (endPtr != &value[value.size()]) - { - std::cout << "Failed to parse value \"" << value << "\" as milliseconds" << std::endl; - return false; - } + if (endPtr != &value[value.size()]) { + std::cout << "Failed to parse value \"" << value << "\" as milliseconds" << std::endl; + return false; + } - return true; + return true; } -bool InfoStringToStructConverterBase::ConvertScriptString(const std::string& value, const size_t offset) -{ - auto scrStrValue = m_zone_script_strings.AddOrGetScriptString(value); - m_used_script_string_list.emplace(scrStrValue); - *reinterpret_cast(reinterpret_cast(m_structure) + offset) = scrStrValue; +bool InfoStringToStructConverterBase::ConvertScriptString(const std::string &value, const size_t offset) { + auto scrStrValue = m_zone_script_strings.AddOrGetScriptString(value); + m_used_script_string_list.emplace(scrStrValue); + *reinterpret_cast(reinterpret_cast(m_structure) + offset) = scrStrValue; - return true; + return true; } -bool InfoStringToStructConverterBase::ConvertEnumInt(const std::string& value, const size_t offset, const char** enumValues, const size_t enumSize) -{ - for(auto i = 0u; i < enumSize; i++) - { - if(value == enumValues[i]) - { - *reinterpret_cast(reinterpret_cast(m_structure) + offset) = static_cast(i); - return true; - } +bool InfoStringToStructConverterBase::ConvertEnumInt(const std::string &value, const size_t offset, const char **enumValues, const size_t enumSize) { + for (auto i = 0u; i < enumSize; i++) { + if (value == enumValues[i]) { + *reinterpret_cast(reinterpret_cast(m_structure) + offset) = static_cast(i); + return true; } - - return false; + } + + return false; } -std::vector InfoStringToStructConverterBase::GetUsedScriptStrings() const -{ - std::vector scrStringList; - for(auto scrStr : m_used_script_string_list) - { - scrStringList.push_back(scrStr); - } +std::vector InfoStringToStructConverterBase::GetUsedScriptStrings() const { + std::vector scrStringList; + for (auto scrStr : m_used_script_string_list) { + scrStringList.push_back(scrStr); + } - return scrStringList; + return scrStringList; } -std::vector InfoStringToStructConverterBase::GetDependencies() const -{ - std::vector dependencyList; - for (auto* dependency : m_dependencies) - { - dependencyList.push_back(dependency); - } +std::vector InfoStringToStructConverterBase::GetDependencies() const { + std::vector dependencyList; + for (auto *dependency : m_dependencies) { + dependencyList.push_back(dependency); + } - return dependencyList; + return dependencyList; } diff --git a/src/ObjLoading/InfoString/InfoStringToStructConverterBase.h b/src/ObjLoading/InfoString/InfoStringToStructConverterBase.h index 09380f1b4..c947594fd 100644 --- a/src/ObjLoading/InfoString/InfoStringToStructConverterBase.h +++ b/src/ObjLoading/InfoString/InfoStringToStructConverterBase.h @@ -4,45 +4,44 @@ #include #include -#include "Utils/ClassUtils.h" #include "InfoString/InfoString.h" #include "Pool/XAssetInfo.h" +#include "Utils/ClassUtils.h" #include "Utils/MemoryManager.h" #include "Zone/ZoneScriptStrings.h" -class InfoStringToStructConverterBase -{ +class InfoStringToStructConverterBase { protected: - const InfoString& m_info_string; - ZoneScriptStrings& m_zone_script_strings; - std::unordered_set m_used_script_string_list; - std::unordered_set m_dependencies; - MemoryManager* m_memory; - void* m_structure; + const InfoString &m_info_string; + ZoneScriptStrings &m_zone_script_strings; + std::unordered_set m_used_script_string_list; + std::unordered_set m_dependencies; + MemoryManager *m_memory; + void *m_structure; + + static bool ParseAsArray(const std::string &value, std::vector &valueArray); + bool ParseAsPairs(const std::string &value, std::vector> &valueArray) const; - static bool ParseAsArray(const std::string& value, std::vector& valueArray); - bool ParseAsPairs(const std::string& value, std::vector>& valueArray) const; - - bool ConvertString(const std::string& value, size_t offset); - bool ConvertStringBuffer(const std::string& value, size_t offset, size_t bufferSize); - bool ConvertInt(const std::string& value, size_t offset); - bool ConvertUint(const std::string& value, size_t offset); - bool ConvertBool(const std::string& value, size_t offset); - bool ConvertQBoolean(const std::string& value, size_t offset); - bool ConvertFloat(const std::string& value, size_t offset); - bool ConvertMilliseconds(const std::string& value, size_t offset); - bool ConvertScriptString(const std::string& value, size_t offset); - bool ConvertEnumInt(const std::string& value, size_t offset, const char** enumValues, size_t enumSize); + bool ConvertString(const std::string &value, size_t offset); + bool ConvertStringBuffer(const std::string &value, size_t offset, size_t bufferSize); + bool ConvertInt(const std::string &value, size_t offset); + bool ConvertUint(const std::string &value, size_t offset); + bool ConvertBool(const std::string &value, size_t offset); + bool ConvertQBoolean(const std::string &value, size_t offset); + bool ConvertFloat(const std::string &value, size_t offset); + bool ConvertMilliseconds(const std::string &value, size_t offset); + bool ConvertScriptString(const std::string &value, size_t offset); + bool ConvertEnumInt(const std::string &value, size_t offset, const char **enumValues, size_t enumSize); public: - InfoStringToStructConverterBase(const InfoString& infoString, void* structure, ZoneScriptStrings& zoneScriptStrings, MemoryManager* memory); - virtual ~InfoStringToStructConverterBase() = default; - InfoStringToStructConverterBase(const InfoStringToStructConverterBase& other) = delete; - InfoStringToStructConverterBase(InfoStringToStructConverterBase&& other) noexcept = delete; - InfoStringToStructConverterBase& operator=(const InfoStringToStructConverterBase& other) = delete; - InfoStringToStructConverterBase& operator=(InfoStringToStructConverterBase&& other) noexcept = delete; + InfoStringToStructConverterBase(const InfoString &infoString, void *structure, ZoneScriptStrings &zoneScriptStrings, MemoryManager *memory); + virtual ~InfoStringToStructConverterBase() = default; + InfoStringToStructConverterBase(const InfoStringToStructConverterBase &other) = delete; + InfoStringToStructConverterBase(InfoStringToStructConverterBase &&other) noexcept = delete; + InfoStringToStructConverterBase &operator=(const InfoStringToStructConverterBase &other) = delete; + InfoStringToStructConverterBase &operator=(InfoStringToStructConverterBase &&other) noexcept = delete; - virtual bool Convert() = 0; - _NODISCARD std::vector GetUsedScriptStrings() const; - _NODISCARD std::vector GetDependencies() const; + virtual bool Convert() = 0; + _NODISCARD std::vector GetUsedScriptStrings() const; + _NODISCARD std::vector GetDependencies() const; }; diff --git a/src/ObjLoading/Menu/AbstractMenuConverter.cpp b/src/ObjLoading/Menu/AbstractMenuConverter.cpp index 0b05d76f7..759179173 100644 --- a/src/ObjLoading/Menu/AbstractMenuConverter.cpp +++ b/src/ObjLoading/Menu/AbstractMenuConverter.cpp @@ -4,38 +4,29 @@ using namespace menu; -AbstractMenuConverter::AbstractMenuConverter(const bool disableOptimizations, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager) - : m_disable_optimizations(disableOptimizations), - m_search_path(searchPath), - m_memory(memory), - m_manager(manager) -{ -} - -void AbstractMenuConverter::PrintConversionExceptionDetails(const MenuConversionException& e) -{ - std::cout << "ERROR while converting menu:\n"; - std::cout << " Menu: " << e.m_menu->m_name << "\n"; +AbstractMenuConverter::AbstractMenuConverter(const bool disableOptimizations, ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager) + : m_disable_optimizations(disableOptimizations), m_search_path(searchPath), m_memory(memory), m_manager(manager) {} - if (e.m_item) - { - std::cout << "Item: "; +void AbstractMenuConverter::PrintConversionExceptionDetails(const MenuConversionException &e) { + std::cout << "ERROR while converting menu:\n"; + std::cout << " Menu: " << e.m_menu->m_name << "\n"; - if (!e.m_item->m_name.empty()) - { - std::cout << e.m_item->m_name << "\n"; - } + if (e.m_item) { + std::cout << "Item: "; - std::cout << "\n"; + if (!e.m_item->m_name.empty()) { + std::cout << e.m_item->m_name << "\n"; } - std::cout << " Message: " << e.m_message << "\n"; + std::cout << "\n"; + } + + std::cout << " Message: " << e.m_message << "\n"; } -const char* AbstractMenuConverter::ConvertString(const std::string& str) const -{ - if (str.empty()) - return nullptr; +const char *AbstractMenuConverter::ConvertString(const std::string &str) const { + if (str.empty()) + return nullptr; - return m_memory->Dup(str.c_str()); + return m_memory->Dup(str.c_str()); } diff --git a/src/ObjLoading/Menu/AbstractMenuConverter.h b/src/ObjLoading/Menu/AbstractMenuConverter.h index c82369501..4cc00c4f1 100644 --- a/src/ObjLoading/Menu/AbstractMenuConverter.h +++ b/src/ObjLoading/Menu/AbstractMenuConverter.h @@ -1,26 +1,24 @@ #pragma once -#include "MenuConversionException.h" #include "AssetLoading/IAssetLoadingManager.h" +#include "MenuConversionException.h" #include "SearchPath/ISearchPath.h" -#include "Utils/MemoryManager.h" #include "Utils/ClassUtils.h" +#include "Utils/MemoryManager.h" -namespace menu -{ - class AbstractMenuConverter - { - protected: - bool m_disable_optimizations; - ISearchPath* m_search_path; - MemoryManager* m_memory; - IAssetLoadingManager* m_manager; +namespace menu { +class AbstractMenuConverter { +protected: + bool m_disable_optimizations; + ISearchPath *m_search_path; + MemoryManager *m_memory; + IAssetLoadingManager *m_manager; - AbstractMenuConverter(bool disableOptimizations, ISearchPath* searchPath, MemoryManager* memory, IAssetLoadingManager* manager); + AbstractMenuConverter(bool disableOptimizations, ISearchPath *searchPath, MemoryManager *memory, IAssetLoadingManager *manager); - _NODISCARD const char* ConvertString(const std::string& str) const; + _NODISCARD const char *ConvertString(const std::string &str) const; - public: - static void PrintConversionExceptionDetails(const MenuConversionException& e); - }; -} +public: + static void PrintConversionExceptionDetails(const MenuConversionException &e); +}; +} // namespace menu diff --git a/src/ObjLoading/Menu/MenuConversionException.cpp b/src/ObjLoading/Menu/MenuConversionException.cpp index 41467c673..923bfcbf0 100644 --- a/src/ObjLoading/Menu/MenuConversionException.cpp +++ b/src/ObjLoading/Menu/MenuConversionException.cpp @@ -2,16 +2,8 @@ using namespace menu; -MenuConversionException::MenuConversionException(std::string message, const CommonMenuDef* menu) - : m_menu(menu), - m_item(nullptr), - m_message(std::move(message)) -{ -} +MenuConversionException::MenuConversionException(std::string message, const CommonMenuDef *menu) + : m_menu(menu), m_item(nullptr), m_message(std::move(message)) {} -MenuConversionException::MenuConversionException(std::string message, const CommonMenuDef* menu, const CommonItemDef* item) - : m_menu(menu), - m_item(item), - m_message(std::move(message)) -{ -} +MenuConversionException::MenuConversionException(std::string message, const CommonMenuDef *menu, const CommonItemDef *item) + : m_menu(menu), m_item(item), m_message(std::move(message)) {} diff --git a/src/ObjLoading/Menu/MenuConversionException.h b/src/ObjLoading/Menu/MenuConversionException.h index 20e32b696..50b0e2e35 100644 --- a/src/ObjLoading/Menu/MenuConversionException.h +++ b/src/ObjLoading/Menu/MenuConversionException.h @@ -1,16 +1,14 @@ #pragma once #include "Parsing/Menu/Domain/CommonMenuDef.h" -namespace menu -{ - class MenuConversionException final : public std::exception - { - public: - const CommonMenuDef* m_menu; - const CommonItemDef* m_item; - std::string m_message; +namespace menu { +class MenuConversionException final : public std::exception { +public: + const CommonMenuDef *m_menu; + const CommonItemDef *m_item; + std::string m_message; - explicit MenuConversionException(std::string message, const CommonMenuDef* menu); - MenuConversionException(std::string message, const CommonMenuDef* menu, const CommonItemDef* item); - }; -} + explicit MenuConversionException(std::string message, const CommonMenuDef *menu); + MenuConversionException(std::string message, const CommonMenuDef *menu, const CommonItemDef *item); +}; +} // namespace menu diff --git a/src/ObjLoading/ObjContainer/IPak/Exception/IPakLoadException.cpp b/src/ObjLoading/ObjContainer/IPak/Exception/IPakLoadException.cpp index 5d74b7675..872a1ef0e 100644 --- a/src/ObjLoading/ObjContainer/IPak/Exception/IPakLoadException.cpp +++ b/src/ObjLoading/ObjContainer/IPak/Exception/IPakLoadException.cpp @@ -1,16 +1,7 @@ #include "IPakLoadException.h" -IPakLoadException::IPakLoadException(std::string message) -{ - m_message = std::move(message); -} +IPakLoadException::IPakLoadException(std::string message) { m_message = std::move(message); } -const std::string& IPakLoadException::DetailedMessage() const -{ - return m_message; -} +const std::string &IPakLoadException::DetailedMessage() const { return m_message; } -char const* IPakLoadException::what() const noexcept -{ - return "There was an error when trying to load an ipak file."; -} \ No newline at end of file +char const *IPakLoadException::what() const noexcept { return "There was an error when trying to load an ipak file."; } \ No newline at end of file diff --git a/src/ObjLoading/ObjContainer/IPak/Exception/IPakLoadException.h b/src/ObjLoading/ObjContainer/IPak/Exception/IPakLoadException.h index ab899daac..b10d01e30 100644 --- a/src/ObjLoading/ObjContainer/IPak/Exception/IPakLoadException.h +++ b/src/ObjLoading/ObjContainer/IPak/Exception/IPakLoadException.h @@ -2,13 +2,12 @@ #include #include -class IPakLoadException final : public std::exception -{ - std::string m_message; +class IPakLoadException final : public std::exception { + std::string m_message; public: - explicit IPakLoadException(std::string message); + explicit IPakLoadException(std::string message); - const std::string& DetailedMessage() const; - char const* what() const noexcept override; + const std::string &DetailedMessage() const; + char const *what() const noexcept override; }; diff --git a/src/ObjLoading/ObjContainer/IPak/IPak.cpp b/src/ObjLoading/ObjContainer/IPak/IPak.cpp index b02f1c4e4..b4c70eb3e 100644 --- a/src/ObjLoading/ObjContainer/IPak/IPak.cpp +++ b/src/ObjLoading/ObjContainer/IPak/IPak.cpp @@ -1,245 +1,185 @@ #include "IPak.h" +#include +#include #include #include -#include -#include #include "zlib.h" -#include "Utils/FileUtils.h" #include "Exception/IPakLoadException.h" -#include "ObjContainer/IPak/IPakTypes.h" #include "IPakStreamManager.h" +#include "ObjContainer/IPak/IPakTypes.h" +#include "Utils/FileUtils.h" namespace fs = std::filesystem; ObjContainerRepository IPak::Repository; -class IPak::Impl : public ObjContainerReferenceable -{ - static const uint32_t MAGIC = FileUtils::MakeMagic32('K', 'A', 'P', 'I'); - static const uint32_t VERSION = 0x50000; +class IPak::Impl : public ObjContainerReferenceable { + static const uint32_t MAGIC = FileUtils::MakeMagic32('K', 'A', 'P', 'I'); + static const uint32_t VERSION = 0x50000; + + std::string m_path; + std::unique_ptr m_stream; - std::string m_path; - std::unique_ptr m_stream; + bool m_initialized; - bool m_initialized; + std::unique_ptr m_index_section; + std::unique_ptr m_data_section; - std::unique_ptr m_index_section; - std::unique_ptr m_data_section; + std::vector m_index_entries; - std::vector m_index_entries; + IPakStreamManager m_stream_manager; - IPakStreamManager m_stream_manager; + static uint32_t R_HashString(const char *str, uint32_t hash) { + for (const auto *pos = str; *pos; pos++) { + hash = 33 * hash ^ (*pos | 0x20); + } + + return hash; + } + + bool ReadIndexSection() { + m_stream->seekg(m_index_section->offset); + IPakIndexEntry indexEntry{}; - static uint32_t R_HashString(const char* str, uint32_t hash) - { - for (const auto* pos = str; *pos; pos++) - { - hash = 33 * hash ^ (*pos | 0x20); - } + for (unsigned itemIndex = 0; itemIndex < m_index_section->itemCount; itemIndex++) { + m_stream->read(reinterpret_cast(&indexEntry), sizeof indexEntry); + if (m_stream->gcount() != sizeof indexEntry) { + printf("Unexpected eof when trying to load index entry %u.\n", itemIndex); + return false; + } - return hash; + m_index_entries.push_back(indexEntry); } - bool ReadIndexSection() - { - m_stream->seekg(m_index_section->offset); - IPakIndexEntry indexEntry{}; - - for (unsigned itemIndex = 0; itemIndex < m_index_section->itemCount; itemIndex++) - { - m_stream->read(reinterpret_cast(&indexEntry), sizeof indexEntry); - if (m_stream->gcount() != sizeof indexEntry) - { - printf("Unexpected eof when trying to load index entry %u.\n", itemIndex); - return false; - } - - m_index_entries.push_back(indexEntry); - } - - std::sort(m_index_entries.begin(), m_index_entries.end(), - [](const IPakIndexEntry& entry1, const IPakIndexEntry& entry2) - { - return entry1.key.combinedKey < entry2.key.combinedKey; - }); - - return true; + std::sort(m_index_entries.begin(), m_index_entries.end(), + [](const IPakIndexEntry &entry1, const IPakIndexEntry &entry2) { return entry1.key.combinedKey < entry2.key.combinedKey; }); + + return true; + } + + bool ReadSection() { + IPakSection section{}; + + m_stream->read(reinterpret_cast(§ion), sizeof section); + if (m_stream->gcount() != sizeof section) { + printf("Unexpected eof when trying to load section.\n"); + return false; } - bool ReadSection() - { - IPakSection section{}; + switch (section.type) { + case 1: + m_index_section = std::make_unique(section); + break; - m_stream->read(reinterpret_cast(§ion), sizeof section); - if (m_stream->gcount() != sizeof section) - { - printf("Unexpected eof when trying to load section.\n"); - return false; - } + case 2: + m_data_section = std::make_unique(section); + break; - switch (section.type) - { - case 1: - m_index_section = std::make_unique(section); - break; + default: + break; + } - case 2: - m_data_section = std::make_unique(section); - break; + return true; + } - default: - break; - } + bool ReadHeader() { + IPakHeader header{}; - return true; + m_stream->read(reinterpret_cast(&header), sizeof header); + if (m_stream->gcount() != sizeof header) { + printf("Unexpected eof when trying to load header.\n"); + return false; } - bool ReadHeader() - { - IPakHeader header{}; - - m_stream->read(reinterpret_cast(&header), sizeof header); - if (m_stream->gcount() != sizeof header) - { - printf("Unexpected eof when trying to load header.\n"); - return false; - } - - if (header.magic != MAGIC) - { - printf("Invalid ipak magic '0x%x'.\n", header.magic); - return false; - } - - if (header.version != VERSION) - { - printf("Unsupported ipak version '%u'.\n", header.version); - return false; - } - - for (unsigned section = 0; section < header.sectionCount; section++) - { - if (!ReadSection()) - return false; - } - - if (m_index_section == nullptr) - { - printf("IPak does not contain an index section.\n"); - return false; - } - - if (m_data_section == nullptr) - { - printf("IPak does not contain a data section.\n"); - return false; - } - - if (!ReadIndexSection()) - return false; - - return true; + if (header.magic != MAGIC) { + printf("Invalid ipak magic '0x%x'.\n", header.magic); + return false; } -public: - Impl(std::string path, std::unique_ptr stream) - : m_path(std::move(path)), - m_stream(std::move(stream)), - m_initialized(false), - m_index_section(nullptr), - m_data_section(nullptr), - m_stream_manager(*m_stream) - { + if (header.version != VERSION) { + printf("Unsupported ipak version '%u'.\n", header.version); + return false; + } + + for (unsigned section = 0; section < header.sectionCount; section++) { + if (!ReadSection()) + return false; } - ~Impl() override - = default; + if (m_index_section == nullptr) { + printf("IPak does not contain an index section.\n"); + return false; + } - std::string GetName() override - { - return fs::path(m_path).filename().replace_extension("").string(); + if (m_data_section == nullptr) { + printf("IPak does not contain a data section.\n"); + return false; } - bool Initialize() - { - if (m_initialized) - return true; + if (!ReadIndexSection()) + return false; - if (!ReadHeader()) - return false; + return true; + } - m_initialized = true; - return true; - } +public: + Impl(std::string path, std::unique_ptr stream) + : m_path(std::move(path)), m_stream(std::move(stream)), m_initialized(false), m_index_section(nullptr), m_data_section(nullptr), + m_stream_manager(*m_stream) {} + + ~Impl() override = default; + + std::string GetName() override { return fs::path(m_path).filename().replace_extension("").string(); } + + bool Initialize() { + if (m_initialized) + return true; + + if (!ReadHeader()) + return false; + + m_initialized = true; + return true; + } - std::unique_ptr GetEntryData(const Hash nameHash, const Hash dataHash) - { - IPakIndexEntryKey wantedKey{}; - wantedKey.nameHash = nameHash; - wantedKey.dataHash = dataHash; - - for (auto& entry : m_index_entries) - { - if (entry.key.combinedKey == wantedKey.combinedKey) - { - return m_stream_manager.OpenStream(static_cast(m_data_section->offset) + entry.offset, entry.size); - } - else if (entry.key.combinedKey > wantedKey.combinedKey) - { - // The index entries are sorted so if the current entry is higher than the wanted entry we can cancel here - return nullptr; - } - } + std::unique_ptr GetEntryData(const Hash nameHash, const Hash dataHash) { + IPakIndexEntryKey wantedKey{}; + wantedKey.nameHash = nameHash; + wantedKey.dataHash = dataHash; + for (auto &entry : m_index_entries) { + if (entry.key.combinedKey == wantedKey.combinedKey) { + return m_stream_manager.OpenStream(static_cast(m_data_section->offset) + entry.offset, entry.size); + } else if (entry.key.combinedKey > wantedKey.combinedKey) { + // The index entries are sorted so if the current entry is higher than the wanted entry we can cancel here return nullptr; + } } - static Hash HashString(const std::string& str) - { - return R_HashString(str.c_str(), 0); - } + return nullptr; + } - static Hash HashData(const void* data, const size_t dataSize) - { - return crc32(0, static_cast(data), dataSize); - } + static Hash HashString(const std::string &str) { return R_HashString(str.c_str(), 0); } + + static Hash HashData(const void *data, const size_t dataSize) { return crc32(0, static_cast(data), dataSize); } }; -IPak::IPak(std::string path, std::unique_ptr stream) -{ - m_impl = new Impl(std::move(path), std::move(stream)); -} +IPak::IPak(std::string path, std::unique_ptr stream) { m_impl = new Impl(std::move(path), std::move(stream)); } -IPak::~IPak() -{ - delete m_impl; - m_impl = nullptr; +IPak::~IPak() { + delete m_impl; + m_impl = nullptr; } -std::string IPak::GetName() -{ - return m_impl->GetName(); -} +std::string IPak::GetName() { return m_impl->GetName(); } -bool IPak::Initialize() -{ - return m_impl->Initialize(); -} +bool IPak::Initialize() { return m_impl->Initialize(); } -std::unique_ptr IPak::GetEntryStream(const Hash nameHash, const Hash dataHash) const -{ - return m_impl->GetEntryData(nameHash, dataHash); -} +std::unique_ptr IPak::GetEntryStream(const Hash nameHash, const Hash dataHash) const { return m_impl->GetEntryData(nameHash, dataHash); } -IPak::Hash IPak::HashString(const std::string& str) -{ - return Impl::HashString(str); -} +IPak::Hash IPak::HashString(const std::string &str) { return Impl::HashString(str); } -IPak::Hash IPak::HashData(const void* data, const size_t dataSize) -{ - return Impl::HashData(data, dataSize); -} +IPak::Hash IPak::HashData(const void *data, const size_t dataSize) { return Impl::HashData(data, dataSize); } diff --git a/src/ObjLoading/ObjContainer/IPak/IPak.h b/src/ObjLoading/ObjContainer/IPak/IPak.h index 1c16633bf..8f0361efa 100644 --- a/src/ObjLoading/ObjContainer/IPak/IPak.h +++ b/src/ObjLoading/ObjContainer/IPak/IPak.h @@ -2,30 +2,29 @@ #include -#include "Utils/ClassUtils.h" #include "ObjContainer/ObjContainerReferenceable.h" #include "ObjContainer/ObjContainerRepository.h" +#include "Utils/ClassUtils.h" #include "Utils/ObjStream.h" #include "Zone/Zone.h" -class IPak final : public ObjContainerReferenceable -{ - class Impl; - Impl* m_impl; +class IPak final : public ObjContainerReferenceable { + class Impl; + Impl *m_impl; public: - typedef uint32_t Hash; + typedef uint32_t Hash; - static ObjContainerRepository Repository; + static ObjContainerRepository Repository; - IPak(std::string path, std::unique_ptr stream); - ~IPak() override; + IPak(std::string path, std::unique_ptr stream); + ~IPak() override; - std::string GetName() override; + std::string GetName() override; - bool Initialize(); - _NODISCARD std::unique_ptr GetEntryStream(Hash nameHash, Hash dataHash) const; + bool Initialize(); + _NODISCARD std::unique_ptr GetEntryStream(Hash nameHash, Hash dataHash) const; - static Hash HashString(const std::string& str); - static Hash HashData(const void* data, size_t dataSize); + static Hash HashString(const std::string &str); + static Hash HashData(const void *data, size_t dataSize); }; diff --git a/src/ObjLoading/ObjContainer/IPak/IPakEntryReadStream.cpp b/src/ObjLoading/ObjContainer/IPak/IPakEntryReadStream.cpp index f98f100e4..979a65629 100644 --- a/src/ObjLoading/ObjContainer/IPak/IPakEntryReadStream.cpp +++ b/src/ObjLoading/ObjContainer/IPak/IPakEntryReadStream.cpp @@ -9,405 +9,322 @@ using namespace ipak_consts; -IPakEntryReadStream::IPakEntryReadStream(std::istream& stream, IPakStreamManagerActions* streamManagerActions, - uint8_t* chunkBuffer, const int64_t startOffset, const size_t entrySize) - : m_chunk_buffer(chunkBuffer), - m_stream(stream), - m_stream_manager_actions(streamManagerActions), - m_file_offset(0), - m_file_head(0), - m_entry_size(entrySize), - m_decompress_buffer{}, - m_current_block(nullptr), - m_next_command(0), - m_current_command_buffer(nullptr), - m_current_command_length(0), - m_current_command_offset(0), - m_pos(startOffset), - m_base_pos(startOffset), - m_end_pos(startOffset + entrySize), - m_buffer_start_pos(0), - m_buffer_end_pos(0) -{ - lzo_init(); +IPakEntryReadStream::IPakEntryReadStream(std::istream &stream, IPakStreamManagerActions *streamManagerActions, uint8_t *chunkBuffer, const int64_t startOffset, + const size_t entrySize) + : m_chunk_buffer(chunkBuffer), m_stream(stream), m_stream_manager_actions(streamManagerActions), m_file_offset(0), m_file_head(0), m_entry_size(entrySize), + m_decompress_buffer{}, m_current_block(nullptr), m_next_command(0), m_current_command_buffer(nullptr), m_current_command_length(0), + m_current_command_offset(0), m_pos(startOffset), m_base_pos(startOffset), m_end_pos(startOffset + entrySize), m_buffer_start_pos(0), m_buffer_end_pos(0) { + lzo_init(); } -IPakEntryReadStream::~IPakEntryReadStream() -{ - close(); -} +IPakEntryReadStream::~IPakEntryReadStream() { close(); } -size_t IPakEntryReadStream::ReadChunks(uint8_t* buffer, const int64_t startPos, const size_t chunkCount) const -{ - m_stream_manager_actions->StartReading(); - m_stream.seekg(startPos); - m_stream.read(reinterpret_cast(buffer), static_cast(chunkCount) * IPAK_CHUNK_SIZE); - const auto readSize = static_cast(m_stream.gcount()); - m_stream_manager_actions->StopReading(); +size_t IPakEntryReadStream::ReadChunks(uint8_t *buffer, const int64_t startPos, const size_t chunkCount) const { + m_stream_manager_actions->StartReading(); + m_stream.seekg(startPos); + m_stream.read(reinterpret_cast(buffer), static_cast(chunkCount) * IPAK_CHUNK_SIZE); + const auto readSize = static_cast(m_stream.gcount()); + m_stream_manager_actions->StopReading(); - return readSize / IPAK_CHUNK_SIZE; + return readSize / IPAK_CHUNK_SIZE; } -bool IPakEntryReadStream::SetChunkBufferWindow(const int64_t startPos, size_t chunkCount) -{ - // Cannot load more than IPAK_CHUNK_COUNT_PER_READ chunks without overflowing the buffer - assert(chunkCount <= IPAK_CHUNK_COUNT_PER_READ); - - if (chunkCount > IPAK_CHUNK_COUNT_PER_READ) - chunkCount = IPAK_CHUNK_COUNT_PER_READ; +bool IPakEntryReadStream::SetChunkBufferWindow(const int64_t startPos, size_t chunkCount) { + // Cannot load more than IPAK_CHUNK_COUNT_PER_READ chunks without overflowing the buffer + assert(chunkCount <= IPAK_CHUNK_COUNT_PER_READ); - // The start position must be aligned to IPAK_CHUNK_SIZE - assert(startPos % IPAK_CHUNK_SIZE == 0); + if (chunkCount > IPAK_CHUNK_COUNT_PER_READ) + chunkCount = IPAK_CHUNK_COUNT_PER_READ; - if (chunkCount == 0) - { - m_buffer_start_pos = startPos; - m_buffer_end_pos = startPos; - return true; - } + // The start position must be aligned to IPAK_CHUNK_SIZE + assert(startPos % IPAK_CHUNK_SIZE == 0); - const auto endPos = startPos + static_cast(chunkCount) * IPAK_CHUNK_SIZE; + if (chunkCount == 0) { + m_buffer_start_pos = startPos; + m_buffer_end_pos = startPos; + return true; + } - if (startPos >= m_buffer_start_pos && startPos < m_buffer_end_pos) - { - if (m_buffer_start_pos != startPos) - { - const auto moveEnd = endPos < m_buffer_end_pos ? endPos : m_buffer_end_pos; - assert(IPAK_CHUNK_SIZE * IPAK_CHUNK_COUNT_PER_READ >= static_cast(moveEnd - startPos)); - memmove(m_chunk_buffer, &m_chunk_buffer[startPos - m_buffer_start_pos], static_cast(moveEnd - startPos)); - m_buffer_start_pos = startPos; - } + const auto endPos = startPos + static_cast(chunkCount) * IPAK_CHUNK_SIZE; - if (endPos > m_buffer_end_pos) - { - const auto readChunkCount = ReadChunks(&m_chunk_buffer[m_buffer_end_pos - startPos], m_buffer_end_pos, - static_cast(endPos - m_buffer_end_pos) / IPAK_CHUNK_SIZE); + if (startPos >= m_buffer_start_pos && startPos < m_buffer_end_pos) { + if (m_buffer_start_pos != startPos) { + const auto moveEnd = endPos < m_buffer_end_pos ? endPos : m_buffer_end_pos; + assert(IPAK_CHUNK_SIZE * IPAK_CHUNK_COUNT_PER_READ >= static_cast(moveEnd - startPos)); + memmove(m_chunk_buffer, &m_chunk_buffer[startPos - m_buffer_start_pos], static_cast(moveEnd - startPos)); + m_buffer_start_pos = startPos; + } - m_buffer_end_pos += static_cast(readChunkCount) * IPAK_CHUNK_SIZE; + if (endPos > m_buffer_end_pos) { + const auto readChunkCount = + ReadChunks(&m_chunk_buffer[m_buffer_end_pos - startPos], m_buffer_end_pos, static_cast(endPos - m_buffer_end_pos) / IPAK_CHUNK_SIZE); - return m_buffer_end_pos == endPos; - } + m_buffer_end_pos += static_cast(readChunkCount) * IPAK_CHUNK_SIZE; - m_buffer_end_pos = endPos; - return true; + return m_buffer_end_pos == endPos; } - if (endPos > m_buffer_start_pos && endPos <= m_buffer_end_pos) - { - assert(IPAK_CHUNK_SIZE * IPAK_CHUNK_COUNT_PER_READ - static_cast(m_buffer_start_pos - startPos) >= static_cast(endPos - m_buffer_start_pos)); - memmove(&m_chunk_buffer[m_buffer_start_pos - startPos], m_chunk_buffer, static_cast(endPos - m_buffer_start_pos)); + m_buffer_end_pos = endPos; + return true; + } - const auto readChunkCount = ReadChunks(m_chunk_buffer, - startPos, - static_cast(m_buffer_start_pos - startPos) / IPAK_CHUNK_SIZE); + if (endPos > m_buffer_start_pos && endPos <= m_buffer_end_pos) { + assert(IPAK_CHUNK_SIZE * IPAK_CHUNK_COUNT_PER_READ - static_cast(m_buffer_start_pos - startPos) >= + static_cast(endPos - m_buffer_start_pos)); + memmove(&m_chunk_buffer[m_buffer_start_pos - startPos], m_chunk_buffer, static_cast(endPos - m_buffer_start_pos)); - m_buffer_start_pos = startPos; - m_buffer_end_pos = readChunkCount == (m_buffer_start_pos - startPos) / IPAK_CHUNK_SIZE - ? endPos - : startPos + static_cast(readChunkCount) * IPAK_CHUNK_SIZE; + const auto readChunkCount = ReadChunks(m_chunk_buffer, startPos, static_cast(m_buffer_start_pos - startPos) / IPAK_CHUNK_SIZE); - return m_buffer_end_pos == endPos; - } + m_buffer_start_pos = startPos; + m_buffer_end_pos = + readChunkCount == (m_buffer_start_pos - startPos) / IPAK_CHUNK_SIZE ? endPos : startPos + static_cast(readChunkCount) * IPAK_CHUNK_SIZE; - const auto readChunkCount = ReadChunks(m_chunk_buffer, startPos, chunkCount); + return m_buffer_end_pos == endPos; + } - m_buffer_start_pos = startPos; - m_buffer_end_pos = startPos + static_cast(readChunkCount) * IPAK_CHUNK_SIZE; + const auto readChunkCount = ReadChunks(m_chunk_buffer, startPos, chunkCount); + + m_buffer_start_pos = startPos; + m_buffer_end_pos = startPos + static_cast(readChunkCount) * IPAK_CHUNK_SIZE; - return chunkCount == readChunkCount; + return chunkCount == readChunkCount; } -bool IPakEntryReadStream::ValidateBlockHeader(IPakDataBlockHeader* blockHeader) const -{ - if (blockHeader->count > 31) - { - printf("IPak block has more than 31 commands: %u -> Invalid\n", blockHeader->count); +bool IPakEntryReadStream::ValidateBlockHeader(IPakDataBlockHeader *blockHeader) const { + if (blockHeader->count > 31) { + printf("IPak block has more than 31 commands: %u -> Invalid\n", blockHeader->count); + return false; + } + if (blockHeader->offset != m_file_head) { + // A matching offset is only relevant if a command contains data. + for (unsigned currentCommand = 0; currentCommand < blockHeader->count; currentCommand++) { + if (blockHeader->_commands[currentCommand].compressed == 0 || blockHeader->_commands[currentCommand].compressed == 1) { + printf("IPak block offset is not the file head: %u != %lld -> Invalid\n", blockHeader->offset, m_file_head); return false; + } } - if (blockHeader->offset != m_file_head) - { - // A matching offset is only relevant if a command contains data. - for (unsigned currentCommand = 0; currentCommand < blockHeader->count; currentCommand++) - { - if (blockHeader->_commands[currentCommand].compressed == 0 - || blockHeader->_commands[currentCommand].compressed == 1) - { - printf("IPak block offset is not the file head: %u != %lld -> Invalid\n", blockHeader->offset, m_file_head); - return false; - } - } - } + } - return true; + return true; } -bool IPakEntryReadStream::AdjustChunkBufferWindowForBlockHeader(IPakDataBlockHeader* blockHeader, - const size_t blockOffsetInChunk) -{ - size_t commandsSize = 0; - for (unsigned commandIndex = 0; commandIndex < blockHeader->count; commandIndex++) - { - commandsSize += blockHeader->_commands[commandIndex].size; - } - - const size_t requiredChunkCount = AlignForward(blockOffsetInChunk + sizeof(IPakDataBlockHeader) + commandsSize, IPAK_CHUNK_SIZE) / IPAK_CHUNK_SIZE; +bool IPakEntryReadStream::AdjustChunkBufferWindowForBlockHeader(IPakDataBlockHeader *blockHeader, const size_t blockOffsetInChunk) { + size_t commandsSize = 0; + for (unsigned commandIndex = 0; commandIndex < blockHeader->count; commandIndex++) { + commandsSize += blockHeader->_commands[commandIndex].size; + } - const size_t amountOfReadChunks = static_cast(m_buffer_end_pos - m_buffer_start_pos) / IPAK_CHUNK_SIZE; + const size_t requiredChunkCount = AlignForward(blockOffsetInChunk + sizeof(IPakDataBlockHeader) + commandsSize, IPAK_CHUNK_SIZE) / IPAK_CHUNK_SIZE; - if (requiredChunkCount > amountOfReadChunks) - { - if (requiredChunkCount > IPAK_CHUNK_COUNT_PER_READ) - { - printf("IPak block spans over more than %u blocks (%u), which is not supported.\n", - IPAK_CHUNK_COUNT_PER_READ, requiredChunkCount); - return false; - } + const size_t amountOfReadChunks = static_cast(m_buffer_end_pos - m_buffer_start_pos) / IPAK_CHUNK_SIZE; - if (!SetChunkBufferWindow(m_buffer_start_pos, requiredChunkCount)) - return false; + if (requiredChunkCount > amountOfReadChunks) { + if (requiredChunkCount > IPAK_CHUNK_COUNT_PER_READ) { + printf("IPak block spans over more than %u blocks (%u), which is not supported.\n", IPAK_CHUNK_COUNT_PER_READ, requiredChunkCount); + return false; } - return true; + if (!SetChunkBufferWindow(m_buffer_start_pos, requiredChunkCount)) + return false; + } + + return true; } -bool IPakEntryReadStream::NextBlock() -{ - if (m_pos >= m_end_pos) - return false; +bool IPakEntryReadStream::NextBlock() { + if (m_pos >= m_end_pos) + return false; - m_pos = AlignForward(m_pos, sizeof(IPakDataBlockHeader)); + m_pos = AlignForward(m_pos, sizeof(IPakDataBlockHeader)); - const auto chunkStartPos = AlignBackwards(m_pos, IPAK_CHUNK_SIZE); - const auto blockOffsetInChunk = static_cast(m_pos - chunkStartPos); + const auto chunkStartPos = AlignBackwards(m_pos, IPAK_CHUNK_SIZE); + const auto blockOffsetInChunk = static_cast(m_pos - chunkStartPos); - const auto sizeLeftToRead = m_entry_size - m_file_head; - auto estimatedChunksToRead = AlignForward(m_entry_size - static_cast(m_pos - m_base_pos), IPAK_CHUNK_SIZE) - / IPAK_CHUNK_SIZE; + const auto sizeLeftToRead = m_entry_size - m_file_head; + auto estimatedChunksToRead = AlignForward(m_entry_size - static_cast(m_pos - m_base_pos), IPAK_CHUNK_SIZE) / IPAK_CHUNK_SIZE; - if (estimatedChunksToRead > IPAK_CHUNK_COUNT_PER_READ) - estimatedChunksToRead = IPAK_CHUNK_COUNT_PER_READ; + if (estimatedChunksToRead > IPAK_CHUNK_COUNT_PER_READ) + estimatedChunksToRead = IPAK_CHUNK_COUNT_PER_READ; - if (!SetChunkBufferWindow(chunkStartPos, estimatedChunksToRead)) - return false; + if (!SetChunkBufferWindow(chunkStartPos, estimatedChunksToRead)) + return false; - m_current_block = reinterpret_cast(&m_chunk_buffer[blockOffsetInChunk]); + m_current_block = reinterpret_cast(&m_chunk_buffer[blockOffsetInChunk]); - if (!ValidateBlockHeader(m_current_block)) - return false; + if (!ValidateBlockHeader(m_current_block)) + return false; - if (!AdjustChunkBufferWindowForBlockHeader(m_current_block, blockOffsetInChunk)) - return false; + if (!AdjustChunkBufferWindowForBlockHeader(m_current_block, blockOffsetInChunk)) + return false; - m_pos += sizeof(IPakDataBlockHeader); - m_next_command = 0; + m_pos += sizeof(IPakDataBlockHeader); + m_next_command = 0; - return true; + return true; } -bool IPakEntryReadStream::ProcessCommand(const size_t commandSize, const int compressed) -{ - if (compressed > 0) - { - if (compressed == 1) - { - lzo_uint outputSize = sizeof(m_decompress_buffer); - const auto result = lzo1x_decompress_safe(&m_chunk_buffer[m_pos - m_buffer_start_pos], commandSize, - m_decompress_buffer, &outputSize, nullptr); - - if (result != LZO_E_OK) - { - printf("Decompressing block with lzo failed: %i!\n", result); - return false; - } - - m_current_command_buffer = m_decompress_buffer; - m_current_command_length = outputSize; - m_current_command_offset = 0; - m_file_head += outputSize; - } - } - else - { - m_current_command_buffer = &m_chunk_buffer[m_pos - m_buffer_start_pos]; - m_current_command_length = commandSize; - m_current_command_offset = 0; - m_file_head += commandSize; - } - m_pos += commandSize; +bool IPakEntryReadStream::ProcessCommand(const size_t commandSize, const int compressed) { + if (compressed > 0) { + if (compressed == 1) { + lzo_uint outputSize = sizeof(m_decompress_buffer); + const auto result = lzo1x_decompress_safe(&m_chunk_buffer[m_pos - m_buffer_start_pos], commandSize, m_decompress_buffer, &outputSize, nullptr); - return true; -} + if (result != LZO_E_OK) { + printf("Decompressing block with lzo failed: %i!\n", result); + return false; + } -bool IPakEntryReadStream::AdvanceStream() -{ - if (m_current_block == nullptr || m_next_command >= m_current_block->count) - { - if (!NextBlock()) - return false; + m_current_command_buffer = m_decompress_buffer; + m_current_command_length = outputSize; + m_current_command_offset = 0; + m_file_head += outputSize; } + } else { + m_current_command_buffer = &m_chunk_buffer[m_pos - m_buffer_start_pos]; + m_current_command_length = commandSize; + m_current_command_offset = 0; + m_file_head += commandSize; + } + m_pos += commandSize; + + return true; +} - ProcessCommand(m_current_block->_commands[m_next_command].size, - m_current_block->_commands[m_next_command].compressed); - m_next_command++; +bool IPakEntryReadStream::AdvanceStream() { + if (m_current_block == nullptr || m_next_command >= m_current_block->count) { + if (!NextBlock()) + return false; + } - return true; -} + ProcessCommand(m_current_block->_commands[m_next_command].size, m_current_block->_commands[m_next_command].compressed); + m_next_command++; -bool IPakEntryReadStream::is_open() const -{ - return !m_stream.eof(); + return true; } -bool IPakEntryReadStream::close() -{ - if (is_open()) - { - m_stream_manager_actions->CloseStream(this); - } +bool IPakEntryReadStream::is_open() const { return !m_stream.eof(); } - return true; -} +bool IPakEntryReadStream::close() { + if (is_open()) { + m_stream_manager_actions->CloseStream(this); + } -std::streamsize IPakEntryReadStream::showmanyc() -{ - return m_end_pos - m_pos; + return true; } -std::streambuf::int_type IPakEntryReadStream::underflow() -{ - while (true) - { - if (m_current_command_offset >= m_current_command_length) - { - if (!AdvanceStream()) - break; - } - - if (m_current_command_length - m_current_command_offset < 1) - continue; +std::streamsize IPakEntryReadStream::showmanyc() { return m_end_pos - m_pos; } - return m_current_command_buffer[m_current_command_offset]; +std::streambuf::int_type IPakEntryReadStream::underflow() { + while (true) { + if (m_current_command_offset >= m_current_command_length) { + if (!AdvanceStream()) + break; } - return EOF; + if (m_current_command_length - m_current_command_offset < 1) + continue; + + return m_current_command_buffer[m_current_command_offset]; + } + + return EOF; } -std::streambuf::int_type IPakEntryReadStream::uflow() -{ - while (true) - { - if (m_current_command_offset >= m_current_command_length) - { - if (!AdvanceStream()) - break; - } +std::streambuf::int_type IPakEntryReadStream::uflow() { + while (true) { + if (m_current_command_offset >= m_current_command_length) { + if (!AdvanceStream()) + break; + } - if (m_current_command_length - m_current_command_offset < 1) - continue; + if (m_current_command_length - m_current_command_offset < 1) + continue; - const auto result = m_current_command_buffer[m_current_command_offset]; - m_current_command_offset++; - m_file_offset++; + const auto result = m_current_command_buffer[m_current_command_offset]; + m_current_command_offset++; + m_file_offset++; - return result; - } + return result; + } - return EOF; + return EOF; } -std::streamsize IPakEntryReadStream::xsgetn(char* ptr, const std::streamsize count) -{ - auto* destBuffer = reinterpret_cast(ptr); - int64_t countRead = 0; - - while (countRead < count) - { - if (m_current_command_offset >= m_current_command_length) - { - if (!AdvanceStream()) - break; - } - - auto sizeToRead = count - countRead; - if (sizeToRead > m_current_command_length - m_current_command_offset) - sizeToRead = m_current_command_length - m_current_command_offset; - - if (sizeToRead > 0) - { - assert(static_cast(count - countRead) >= static_cast(sizeToRead)); - memcpy(&destBuffer[countRead], &m_current_command_buffer[m_current_command_offset], static_cast(sizeToRead)); - countRead += sizeToRead; - m_current_command_offset += static_cast(sizeToRead); - m_file_offset += sizeToRead; - } +std::streamsize IPakEntryReadStream::xsgetn(char *ptr, const std::streamsize count) { + auto *destBuffer = reinterpret_cast(ptr); + int64_t countRead = 0; + + while (countRead < count) { + if (m_current_command_offset >= m_current_command_length) { + if (!AdvanceStream()) + break; } - return countRead; -} + auto sizeToRead = count - countRead; + if (sizeToRead > m_current_command_length - m_current_command_offset) + sizeToRead = m_current_command_length - m_current_command_offset; -std::streambuf::pos_type IPakEntryReadStream::seekoff(const off_type off, const std::ios_base::seekdir dir, const std::ios_base::openmode mode) -{ - pos_type pos; - if (dir == std::ios_base::beg) - { - pos = off; - } - else if (dir == std::ios_base::cur) - { - pos = off + m_file_offset; - } - else - { - pos = -1; + if (sizeToRead > 0) { + assert(static_cast(count - countRead) >= static_cast(sizeToRead)); + memcpy(&destBuffer[countRead], &m_current_command_buffer[m_current_command_offset], static_cast(sizeToRead)); + countRead += sizeToRead; + m_current_command_offset += static_cast(sizeToRead); + m_file_offset += sizeToRead; } + } - if (pos == 0 || pos > m_file_offset) - { - return seekpos(pos, mode); - } + return countRead; +} - return std::streampos(-1); +std::streambuf::pos_type IPakEntryReadStream::seekoff(const off_type off, const std::ios_base::seekdir dir, const std::ios_base::openmode mode) { + pos_type pos; + if (dir == std::ios_base::beg) { + pos = off; + } else if (dir == std::ios_base::cur) { + pos = off + m_file_offset; + } else { + pos = -1; + } + + if (pos == 0 || pos > m_file_offset) { + return seekpos(pos, mode); + } + + return std::streampos(-1); } -std::streambuf::pos_type IPakEntryReadStream::seekpos(const pos_type pos, std::ios_base::openmode mode) -{ - if (pos == 0) - { - m_pos = m_base_pos; +std::streambuf::pos_type IPakEntryReadStream::seekpos(const pos_type pos, std::ios_base::openmode mode) { + if (pos == 0) { + m_pos = m_base_pos; - m_file_head = 0; - m_file_offset = 0; + m_file_head = 0; + m_file_offset = 0; - m_current_block = nullptr; - m_next_command = 0; - m_current_command_buffer = nullptr; - m_current_command_length = 0; - m_current_command_offset = 0; + m_current_block = nullptr; + m_next_command = 0; + m_current_command_buffer = nullptr; + m_current_command_length = 0; + m_current_command_offset = 0; + + return pos; + } - return pos; + if (pos > m_file_offset) { + while (m_file_head < pos) { + if (!AdvanceStream()) + break; } - if (pos > m_file_offset) - { - while (m_file_head < pos) - { - if (!AdvanceStream()) - break; - } - - if (pos <= m_file_head) - { - m_current_command_offset = m_current_command_length - static_cast(m_file_head - pos); - m_file_offset = pos; - } - else - { - m_current_command_offset = m_current_command_length; - m_file_offset = m_file_head; - } - - return pos; + if (pos <= m_file_head) { + m_current_command_offset = m_current_command_length - static_cast(m_file_head - pos); + m_file_offset = pos; + } else { + m_current_command_offset = m_current_command_length; + m_file_offset = m_file_head; } - return std::streampos(-1); + return pos; + } + + return std::streampos(-1); } diff --git a/src/ObjLoading/ObjContainer/IPak/IPakEntryReadStream.h b/src/ObjLoading/ObjContainer/IPak/IPakEntryReadStream.h index f6b13a1c7..5e2dedcbb 100644 --- a/src/ObjLoading/ObjContainer/IPak/IPakEntryReadStream.h +++ b/src/ObjLoading/ObjContainer/IPak/IPakEntryReadStream.h @@ -2,69 +2,60 @@ #include -#include "Utils/ObjStream.h" #include "IPakStreamManager.h" #include "ObjContainer/IPak/IPakTypes.h" +#include "Utils/ObjStream.h" -class IPakEntryReadStream final : public objbuf -{ - static constexpr size_t IPAK_DECOMPRESS_BUFFER_SIZE = 0x8000; +class IPakEntryReadStream final : public objbuf { + static constexpr size_t IPAK_DECOMPRESS_BUFFER_SIZE = 0x8000; - uint8_t* m_chunk_buffer; + uint8_t *m_chunk_buffer; - std::istream& m_stream; - IPakStreamManagerActions* m_stream_manager_actions; + std::istream &m_stream; + IPakStreamManagerActions *m_stream_manager_actions; - int64_t m_file_offset; - int64_t m_file_head; + int64_t m_file_offset; + int64_t m_file_head; - size_t m_entry_size; + size_t m_entry_size; - uint8_t m_decompress_buffer[IPAK_DECOMPRESS_BUFFER_SIZE]; - IPakDataBlockHeader* m_current_block; - unsigned m_next_command; - uint8_t* m_current_command_buffer; - size_t m_current_command_length; - size_t m_current_command_offset; + uint8_t m_decompress_buffer[IPAK_DECOMPRESS_BUFFER_SIZE]; + IPakDataBlockHeader *m_current_block; + unsigned m_next_command; + uint8_t *m_current_command_buffer; + size_t m_current_command_length; + size_t m_current_command_offset; - int64_t m_pos; - int64_t m_base_pos; - int64_t m_end_pos; - int64_t m_buffer_start_pos; - int64_t m_buffer_end_pos; + int64_t m_pos; + int64_t m_base_pos; + int64_t m_end_pos; + int64_t m_buffer_start_pos; + int64_t m_buffer_end_pos; - template - static T AlignForward(const T num, const T alignTo) - { - return (num + alignTo - 1) / alignTo * alignTo; - } + template static T AlignForward(const T num, const T alignTo) { return (num + alignTo - 1) / alignTo * alignTo; } - template - static T AlignBackwards(const T num, const T alignTo) - { - return num / alignTo * alignTo; - } + template static T AlignBackwards(const T num, const T alignTo) { return num / alignTo * alignTo; } - size_t ReadChunks(uint8_t* buffer, int64_t startPos, size_t chunkCount) const; - bool SetChunkBufferWindow(int64_t startPos, size_t chunkCount); - bool ValidateBlockHeader(IPakDataBlockHeader* blockHeader) const; - bool AdjustChunkBufferWindowForBlockHeader(IPakDataBlockHeader* blockHeader, size_t blockOffsetInChunk); - bool NextBlock(); - bool ProcessCommand(size_t commandSize, int compressed); - bool AdvanceStream(); + size_t ReadChunks(uint8_t *buffer, int64_t startPos, size_t chunkCount) const; + bool SetChunkBufferWindow(int64_t startPos, size_t chunkCount); + bool ValidateBlockHeader(IPakDataBlockHeader *blockHeader) const; + bool AdjustChunkBufferWindowForBlockHeader(IPakDataBlockHeader *blockHeader, size_t blockOffsetInChunk); + bool NextBlock(); + bool ProcessCommand(size_t commandSize, int compressed); + bool AdvanceStream(); public: - IPakEntryReadStream(std::istream& stream, IPakStreamManagerActions* streamManagerActions, uint8_t* chunkBuffer, int64_t startOffset, size_t entrySize); - ~IPakEntryReadStream() override; + IPakEntryReadStream(std::istream &stream, IPakStreamManagerActions *streamManagerActions, uint8_t *chunkBuffer, int64_t startOffset, size_t entrySize); + ~IPakEntryReadStream() override; - _NODISCARD bool is_open() const override; - bool close() override; + _NODISCARD bool is_open() const override; + bool close() override; protected: - std::streamsize showmanyc() override; - int_type underflow() override; - int_type uflow() override; - std::streamsize xsgetn(char* ptr, std::streamsize count) override; - pos_type seekoff(off_type off, std::ios_base::seekdir dir, std::ios_base::openmode mode) override; - pos_type seekpos(pos_type pos, std::ios_base::openmode mode) override; + std::streamsize showmanyc() override; + int_type underflow() override; + int_type uflow() override; + std::streamsize xsgetn(char *ptr, std::streamsize count) override; + pos_type seekoff(off_type off, std::ios_base::seekdir dir, std::ios_base::openmode mode) override; + pos_type seekpos(pos_type pos, std::ios_base::openmode mode) override; }; \ No newline at end of file diff --git a/src/ObjLoading/ObjContainer/IPak/IPakStreamManager.cpp b/src/ObjLoading/ObjContainer/IPak/IPakStreamManager.cpp index 71e2e8248..0a1a67210 100644 --- a/src/ObjLoading/ObjContainer/IPak/IPakStreamManager.cpp +++ b/src/ObjLoading/ObjContainer/IPak/IPakStreamManager.cpp @@ -1,154 +1,122 @@ #include "IPakStreamManager.h" -#include #include +#include #include "IPakEntryReadStream.h" #include "ObjContainer/IPak/IPakTypes.h" using namespace ipak_consts; -class IPakStreamManager::Impl final : public IPakStreamManagerActions -{ - static constexpr int CHUNK_BUFFER_COUNT_IDLE_LIMIT = 3; - - class ChunkBuffer - { - public: - IPakEntryReadStream* m_using_stream = nullptr; - uint8_t m_buffer[IPAK_CHUNK_SIZE * IPAK_CHUNK_COUNT_PER_READ]{}; - }; - - class ManagedStream - { - public: - IPakEntryReadStream* m_stream; - ChunkBuffer* m_chunk_buffer; - - ManagedStream(IPakEntryReadStream* stream, ChunkBuffer* chunkBuffer) - { - m_stream = stream; - m_chunk_buffer = chunkBuffer; - } - }; +class IPakStreamManager::Impl final : public IPakStreamManagerActions { + static constexpr int CHUNK_BUFFER_COUNT_IDLE_LIMIT = 3; + + class ChunkBuffer { + public: + IPakEntryReadStream *m_using_stream = nullptr; + uint8_t m_buffer[IPAK_CHUNK_SIZE * IPAK_CHUNK_COUNT_PER_READ]{}; + }; + + class ManagedStream { + public: + IPakEntryReadStream *m_stream; + ChunkBuffer *m_chunk_buffer; - std::istream& m_stream; + ManagedStream(IPakEntryReadStream *stream, ChunkBuffer *chunkBuffer) { + m_stream = stream; + m_chunk_buffer = chunkBuffer; + } + }; + + std::istream &m_stream; - std::mutex m_read_mutex; - std::mutex m_stream_mutex; + std::mutex m_read_mutex; + std::mutex m_stream_mutex; - std::vector m_open_streams; - std::vector m_chunk_buffers; + std::vector m_open_streams; + std::vector m_chunk_buffers; public: - explicit Impl(std::istream& stream) - : m_stream(stream) - { - m_chunk_buffers.push_back(new ChunkBuffer()); + explicit Impl(std::istream &stream) : m_stream(stream) { m_chunk_buffers.push_back(new ChunkBuffer()); } + + Impl(const Impl &other) = delete; + Impl(Impl &&other) noexcept = delete; + + virtual ~Impl() { + m_stream_mutex.lock(); + + for (const auto &openStream : m_open_streams) { + openStream.m_stream->close(); } + m_open_streams.clear(); - Impl(const Impl& other) = delete; - Impl(Impl&& other) noexcept = delete; + m_stream_mutex.unlock(); + } - virtual ~Impl() - { - m_stream_mutex.lock(); + Impl &operator=(const Impl &other) = delete; + Impl &operator=(Impl &&other) noexcept = delete; - for (const auto& openStream : m_open_streams) - { - openStream.m_stream->close(); - } - m_open_streams.clear(); + std::unique_ptr OpenStream(const int64_t startPosition, const size_t length) { + m_stream_mutex.lock(); - m_stream_mutex.unlock(); - } + ChunkBuffer *reservedChunkBuffer; + const auto freeChunkBuffer = + std::find_if(m_chunk_buffers.begin(), m_chunk_buffers.end(), [](ChunkBuffer *chunkBuffer) { return chunkBuffer->m_using_stream == nullptr; }); - Impl& operator=(const Impl& other) = delete; - Impl& operator=(Impl&& other) noexcept = delete; + if (freeChunkBuffer == m_chunk_buffers.end()) { + reservedChunkBuffer = new ChunkBuffer(); + m_chunk_buffers.push_back(reservedChunkBuffer); + } else + reservedChunkBuffer = *freeChunkBuffer; - std::unique_ptr OpenStream(const int64_t startPosition, const size_t length) - { - m_stream_mutex.lock(); + auto ipakEntryStream = std::make_unique(m_stream, this, reservedChunkBuffer->m_buffer, startPosition, length); - ChunkBuffer* reservedChunkBuffer; - const auto freeChunkBuffer = std::find_if(m_chunk_buffers.begin(), m_chunk_buffers.end(), [](ChunkBuffer* chunkBuffer) - { - return chunkBuffer->m_using_stream == nullptr; - }); + reservedChunkBuffer->m_using_stream = ipakEntryStream.get(); - if (freeChunkBuffer == m_chunk_buffers.end()) - { - reservedChunkBuffer = new ChunkBuffer(); - m_chunk_buffers.push_back(reservedChunkBuffer); - } - else - reservedChunkBuffer = *freeChunkBuffer; + m_open_streams.emplace_back(ipakEntryStream.get(), reservedChunkBuffer); - auto ipakEntryStream = std::make_unique(m_stream, this, reservedChunkBuffer->m_buffer, startPosition, length); + m_stream_mutex.unlock(); - reservedChunkBuffer->m_using_stream = ipakEntryStream.get(); + return std::make_unique(std::move(ipakEntryStream)); + } - m_open_streams.emplace_back(ipakEntryStream.get(), reservedChunkBuffer); + void StartReading() override { m_read_mutex.lock(); } - m_stream_mutex.unlock(); + void StopReading() override { m_read_mutex.unlock(); } - return std::make_unique(std::move(ipakEntryStream)); - } + void CloseStream(objbuf *stream) override { + m_stream_mutex.lock(); - void StartReading() override - { - m_read_mutex.lock(); - } + const auto openStreamEntry = + std::find_if(m_open_streams.begin(), m_open_streams.end(), [stream](const ManagedStream &managedStream) { return managedStream.m_stream == stream; }); - void StopReading() override - { - m_read_mutex.unlock(); - } + if (openStreamEntry != m_open_streams.end()) { + auto *chunkBuffer = openStreamEntry->m_chunk_buffer; + m_open_streams.erase(openStreamEntry); + chunkBuffer->m_using_stream = nullptr; - void CloseStream(objbuf* stream) override - { - m_stream_mutex.lock(); - - const auto openStreamEntry = std::find_if(m_open_streams.begin(), m_open_streams.end(), [stream](const ManagedStream& managedStream) - { - return managedStream.m_stream == stream; - }); - - if (openStreamEntry != m_open_streams.end()) - { - auto* chunkBuffer = openStreamEntry->m_chunk_buffer; - m_open_streams.erase(openStreamEntry); - chunkBuffer->m_using_stream = nullptr; - - // Only keep previously allocated chunk buffer if we did not get over the limit of idle chunk buffers - if (m_chunk_buffers.size() > CHUNK_BUFFER_COUNT_IDLE_LIMIT) - { - const auto chunkBufferEntry = std::find(m_chunk_buffers.begin(), m_chunk_buffers.end(), chunkBuffer); - - if (chunkBufferEntry != m_chunk_buffers.end()) - { - m_chunk_buffers.erase(chunkBufferEntry); - delete chunkBuffer; - } - } - } + // Only keep previously allocated chunk buffer if we did not get over the limit of idle chunk buffers + if (m_chunk_buffers.size() > CHUNK_BUFFER_COUNT_IDLE_LIMIT) { + const auto chunkBufferEntry = std::find(m_chunk_buffers.begin(), m_chunk_buffers.end(), chunkBuffer); - m_stream_mutex.unlock(); + if (chunkBufferEntry != m_chunk_buffers.end()) { + m_chunk_buffers.erase(chunkBufferEntry); + delete chunkBuffer; + } + } } + + m_stream_mutex.unlock(); + } }; -IPakStreamManager::IPakStreamManager(std::istream& stream) - : m_impl(new Impl(stream)) -{ -} +IPakStreamManager::IPakStreamManager(std::istream &stream) : m_impl(new Impl(stream)) {} -IPakStreamManager::~IPakStreamManager() -{ - delete m_impl; - m_impl = nullptr; +IPakStreamManager::~IPakStreamManager() { + delete m_impl; + m_impl = nullptr; } -std::unique_ptr IPakStreamManager::OpenStream(const int64_t startPosition, const size_t length) const -{ - return m_impl->OpenStream(startPosition, length); +std::unique_ptr IPakStreamManager::OpenStream(const int64_t startPosition, const size_t length) const { + return m_impl->OpenStream(startPosition, length); } diff --git a/src/ObjLoading/ObjContainer/IPak/IPakStreamManager.h b/src/ObjLoading/ObjContainer/IPak/IPakStreamManager.h index 9de19c5c0..16f12da1c 100644 --- a/src/ObjLoading/ObjContainer/IPak/IPakStreamManager.h +++ b/src/ObjLoading/ObjContainer/IPak/IPakStreamManager.h @@ -1,34 +1,32 @@ #pragma once #include -#include #include +#include #include "Utils/ClassUtils.h" #include "Utils/ObjStream.h" -class IPakStreamManagerActions -{ +class IPakStreamManagerActions { public: - virtual void StartReading() = 0; - virtual void StopReading() = 0; + virtual void StartReading() = 0; + virtual void StopReading() = 0; - virtual void CloseStream(objbuf* stream) = 0; + virtual void CloseStream(objbuf *stream) = 0; }; -class IPakStreamManager -{ - class Impl; - Impl* m_impl; +class IPakStreamManager { + class Impl; + Impl *m_impl; public: - explicit IPakStreamManager(std::istream& stream); - IPakStreamManager(const IPakStreamManager& other) = delete; - IPakStreamManager(IPakStreamManager&& other) noexcept = delete; - ~IPakStreamManager(); + explicit IPakStreamManager(std::istream &stream); + IPakStreamManager(const IPakStreamManager &other) = delete; + IPakStreamManager(IPakStreamManager &&other) noexcept = delete; + ~IPakStreamManager(); - IPakStreamManager& operator=(const IPakStreamManager& other) = delete; - IPakStreamManager& operator=(IPakStreamManager&& other) noexcept = delete; + IPakStreamManager &operator=(const IPakStreamManager &other) = delete; + IPakStreamManager &operator=(IPakStreamManager &&other) noexcept = delete; - _NODISCARD std::unique_ptr OpenStream(int64_t startPosition, size_t length) const; + _NODISCARD std::unique_ptr OpenStream(int64_t startPosition, size_t length) const; }; \ No newline at end of file diff --git a/src/ObjLoading/ObjContainer/IWD/IWD.cpp b/src/ObjLoading/ObjContainer/IWD/IWD.cpp index 2ec1c3ba7..520cd1903 100644 --- a/src/ObjLoading/ObjContainer/IWD/IWD.cpp +++ b/src/ObjLoading/ObjContainer/IWD/IWD.cpp @@ -3,361 +3,278 @@ #include "ObjLoading.h" #include "Utils/FileToZlibWrapper.h" -#include -#include #include -#include +#include #include +#include #include +#include namespace fs = std::filesystem; ObjContainerRepository IWD::Repository; -class IWDFile final : public objbuf -{ +class IWDFile final : public objbuf { public: - class IParent - { - public: - virtual ~IParent() = default; + class IParent { + public: + virtual ~IParent() = default; - virtual void OnIWDFileClose() = 0; - }; + virtual void OnIWDFileClose() = 0; + }; private: - IParent* m_parent; - bool m_open; - int64_t m_size; - unzFile m_container; - bool m_peeked; - int_type m_peek_symbol; + IParent *m_parent; + bool m_open; + int64_t m_size; + unzFile m_container; + bool m_peeked; + int_type m_peek_symbol; public: - IWDFile(IParent* parent, const unzFile container, const int64_t size) - : m_parent(parent), - m_open(true), - m_size(size), - m_container(container), - m_peeked(false), - m_peek_symbol(0) - { - } + IWDFile(IParent *parent, const unzFile container, const int64_t size) + : m_parent(parent), m_open(true), m_size(size), m_container(container), m_peeked(false), m_peek_symbol(0) {} - ~IWDFile() override - { - if (m_open) - { - close(); - } + ~IWDFile() override { + if (m_open) { + close(); } + } protected: - int_type underflow() override - { - if (m_peeked) - return m_peek_symbol; + int_type underflow() override { + if (m_peeked) + return m_peek_symbol; - const auto result = unzReadCurrentFile(m_container, &m_peek_symbol, 1u); + const auto result = unzReadCurrentFile(m_container, &m_peek_symbol, 1u); + + if (result >= 0) { + m_peeked = true; + return static_cast(m_peek_symbol); + } - if (result >= 0) - { - m_peeked = true; - return static_cast(m_peek_symbol); - } + return EOF; + } - return EOF; + int_type uflow() override { + if (m_peeked) { + m_peeked = false; + return m_peek_symbol; } - int_type uflow() override - { - if (m_peeked) - { - m_peeked = false; - return m_peek_symbol; - } + const auto result = unzReadCurrentFile(m_container, &m_peek_symbol, 1u); + return result >= 0 ? static_cast(m_peek_symbol) : EOF; + } - const auto result = unzReadCurrentFile(m_container, &m_peek_symbol, 1u); - return result >= 0 ? static_cast(m_peek_symbol) : EOF; + std::streamsize xsgetn(char *ptr, std::streamsize count) override { + if (m_peeked && count >= 1) { + *ptr = static_cast(m_peek_symbol); + ptr++; + count--; } - std::streamsize xsgetn(char* ptr, std::streamsize count) override - { - if (m_peeked && count >= 1) - { - *ptr = static_cast(m_peek_symbol); - ptr++; - count--; - } + const auto result = unzReadCurrentFile(m_container, ptr, static_cast(count)); - const auto result = unzReadCurrentFile(m_container, ptr, static_cast(count)); + return result >= 0 ? static_cast(result) : 0; + } - return result >= 0 ? static_cast(result) : 0; + pos_type seekoff(const off_type off, const std::ios_base::seekdir dir, const std::ios_base::openmode mode) override { + const auto currentPos = unztell64(m_container); + + pos_type targetPos; + if (dir == std::ios_base::beg) { + targetPos = off; + } else if (dir == std::ios_base::cur) { + targetPos = currentPos + off; + } else { + targetPos = m_size - off; } - pos_type seekoff(const off_type off, const std::ios_base::seekdir dir, const std::ios_base::openmode mode) override - { - const auto currentPos = unztell64(m_container); - - pos_type targetPos; - if (dir == std::ios_base::beg) - { - targetPos = off; - } - else if (dir == std::ios_base::cur) - { - targetPos = currentPos + off; - } - else - { - targetPos = m_size - off; - } - - return seekpos(targetPos, mode); + return seekpos(targetPos, mode); + } + + pos_type seekpos(const pos_type pos, const std::ios_base::openmode mode) override { + const auto currentPos = unztell64(m_container); + + if (static_cast(currentPos) < pos) { + auto skipAmount = pos - static_cast(currentPos); + while (skipAmount > 0) { + char temp[1024]; + const auto toRead = skipAmount > sizeof temp ? sizeof temp : static_cast(skipAmount); + unzReadCurrentFile(m_container, temp, toRead); + skipAmount -= toRead; + } + + return pos; } - pos_type seekpos(const pos_type pos, const std::ios_base::openmode mode) override - { - const auto currentPos = unztell64(m_container); - - if (static_cast(currentPos) < pos) - { - auto skipAmount = pos - static_cast(currentPos); - while (skipAmount > 0) - { - char temp[1024]; - const auto toRead = skipAmount > sizeof temp ? sizeof temp : static_cast(skipAmount); - unzReadCurrentFile(m_container, temp, toRead); - skipAmount -= toRead; - } - - return pos; - } - - if (currentPos == pos) - { - // This is fine - return currentPos; - } - - return std::streampos(-1); + if (currentPos == pos) { + // This is fine + return currentPos; } + return std::streampos(-1); + } + public: - _NODISCARD bool is_open() const override - { - return m_open; - } + _NODISCARD bool is_open() const override { return m_open; } - bool close() override - { - unzCloseCurrentFile(m_container); - m_open = false; + bool close() override { + unzCloseCurrentFile(m_container); + m_open = false; - m_parent->OnIWDFileClose(); + m_parent->OnIWDFileClose(); - return true; - } + return true; + } }; -class IWD::Impl : public ISearchPath, public IObjContainer, public IWDFile::IParent -{ - class IWDEntry - { - public: - int64_t m_size{}; - unz_file_pos m_file_pos{}; - }; +class IWD::Impl : public ISearchPath, public IObjContainer, public IWDFile::IParent { + class IWDEntry { + public: + int64_t m_size{}; + unz_file_pos m_file_pos{}; + }; - std::string m_path; - std::unique_ptr m_stream; - unzFile m_unz_file; + std::string m_path; + std::unique_ptr m_stream; + unzFile m_unz_file; - IWDFile* m_last_file; + IWDFile *m_last_file; - std::map m_entry_map; + std::map m_entry_map; public: - Impl(std::string path, std::unique_ptr stream) - : m_path(std::move(path)), - m_stream(std::move(stream)), - m_unz_file(nullptr), - m_last_file(nullptr) - { + Impl(std::string path, std::unique_ptr stream) + : m_path(std::move(path)), m_stream(std::move(stream)), m_unz_file(nullptr), m_last_file(nullptr) {} + + ~Impl() override { + if (m_unz_file != nullptr) { + unzClose(m_unz_file); + m_unz_file = nullptr; + } + } + + Impl(const Impl &other) = delete; + Impl(Impl &&other) noexcept = default; + Impl &operator=(const Impl &other) = delete; + Impl &operator=(Impl &&other) noexcept = default; + + bool Initialize() { + auto ioFunctions = FileToZlibWrapper::CreateFunctions32ForFile(m_stream.get()); + m_unz_file = unzOpen2("", &ioFunctions); + + if (m_unz_file == nullptr) { + printf("Could not open IWD \"%s\"\n", m_path.c_str()); + return false; } - ~Impl() override - { - if (m_unz_file != nullptr) - { - unzClose(m_unz_file); - m_unz_file = nullptr; - } + auto ret = unzGoToFirstFile(m_unz_file); + while (ret == Z_OK) { + unz_file_info64 info; + char fileNameBuffer[256]; + unzGetCurrentFileInfo64(m_unz_file, &info, fileNameBuffer, sizeof fileNameBuffer, nullptr, 0, nullptr, 0); + + std::string fileName(fileNameBuffer); + std::filesystem::path path(fileName); + + if (path.has_filename()) { + IWDEntry entry; + entry.m_size = info.uncompressed_size; + unzGetFilePos(m_unz_file, &entry.m_file_pos); + m_entry_map.emplace(std::move(fileName), entry); + } + + ret = unzGoToNextFile(m_unz_file); } - Impl(const Impl& other) = delete; - Impl(Impl&& other) noexcept = default; - Impl& operator=(const Impl& other) = delete; - Impl& operator=(Impl&& other) noexcept = default; - - bool Initialize() - { - auto ioFunctions = FileToZlibWrapper::CreateFunctions32ForFile(m_stream.get()); - m_unz_file = unzOpen2("", &ioFunctions); - - if (m_unz_file == nullptr) - { - printf("Could not open IWD \"%s\"\n", m_path.c_str()); - return false; - } - - auto ret = unzGoToFirstFile(m_unz_file); - while (ret == Z_OK) - { - unz_file_info64 info; - char fileNameBuffer[256]; - unzGetCurrentFileInfo64(m_unz_file, &info, fileNameBuffer, sizeof fileNameBuffer, nullptr, 0, nullptr, 0); - - std::string fileName(fileNameBuffer); - std::filesystem::path path(fileName); - - if (path.has_filename()) - { - IWDEntry entry; - entry.m_size = info.uncompressed_size; - unzGetFilePos(m_unz_file, &entry.m_file_pos); - m_entry_map.emplace(std::move(fileName), entry); - } - - ret = unzGoToNextFile(m_unz_file); - } - - if (ObjLoading::Configuration.Verbose) - { - printf("Loaded IWD \"%s\" with %u entries\n", m_path.c_str(), m_entry_map.size()); - } - - return true; + if (ObjLoading::Configuration.Verbose) { + printf("Loaded IWD \"%s\" with %u entries\n", m_path.c_str(), m_entry_map.size()); } - SearchPathOpenFile Open(const std::string& fileName) override - { - if (m_unz_file == nullptr) - { - return SearchPathOpenFile(); - } + return true; + } - auto iwdFilename = fileName; - std::replace(iwdFilename.begin(), iwdFilename.end(), '\\', '/'); + SearchPathOpenFile Open(const std::string &fileName) override { + if (m_unz_file == nullptr) { + return SearchPathOpenFile(); + } - const auto iwdEntry = m_entry_map.find(iwdFilename); + auto iwdFilename = fileName; + std::replace(iwdFilename.begin(), iwdFilename.end(), '\\', '/'); - if (iwdEntry != m_entry_map.end()) - { - if (m_last_file != nullptr) - { - throw std::runtime_error("Trying to open new IWD file while last one was not yet closed."); - } + const auto iwdEntry = m_entry_map.find(iwdFilename); - auto pos = iwdEntry->second.m_file_pos; - unzGoToFilePos(m_unz_file, &pos); + if (iwdEntry != m_entry_map.end()) { + if (m_last_file != nullptr) { + throw std::runtime_error("Trying to open new IWD file while last one was not yet closed."); + } - if (unzOpenCurrentFile(m_unz_file) == UNZ_OK) - { - auto result = std::make_unique(this, m_unz_file, iwdEntry->second.m_size); - m_last_file = result.get(); - return SearchPathOpenFile(std::make_unique(std::move(result)), iwdEntry->second.m_size); - } + auto pos = iwdEntry->second.m_file_pos; + unzGoToFilePos(m_unz_file, &pos); - return SearchPathOpenFile(); - } + if (unzOpenCurrentFile(m_unz_file) == UNZ_OK) { + auto result = std::make_unique(this, m_unz_file, iwdEntry->second.m_size); + m_last_file = result.get(); + return SearchPathOpenFile(std::make_unique(std::move(result)), iwdEntry->second.m_size); + } - return SearchPathOpenFile(); + return SearchPathOpenFile(); } - std::string GetPath() override - { - return m_path; - } + return SearchPathOpenFile(); + } - std::string GetName() override - { - return fs::path(m_path).filename().string(); - } + std::string GetPath() override { return m_path; } - void Find(const SearchPathSearchOptions& options, const std::function& callback) override - { - if (options.m_disk_files_only) - { - return; - } + std::string GetName() override { return fs::path(m_path).filename().string(); } - for (auto& [entryName, entry] : m_entry_map) - { - std::filesystem::path entryPath(entryName); + void Find(const SearchPathSearchOptions &options, const std::function &callback) override { + if (options.m_disk_files_only) { + return; + } - if (!options.m_should_include_subdirectories && entryPath.has_parent_path()) - continue; + for (auto &[entryName, entry] : m_entry_map) { + std::filesystem::path entryPath(entryName); - if (options.m_filter_extensions && options.m_extension != entryPath.extension().string()) - continue; + if (!options.m_should_include_subdirectories && entryPath.has_parent_path()) + continue; - callback(entryName); - } - } + if (options.m_filter_extensions && options.m_extension != entryPath.extension().string()) + continue; - void OnIWDFileClose() override - { - m_last_file = nullptr; + callback(entryName); } + } + + void OnIWDFileClose() override { m_last_file = nullptr; } }; -IWD::IWD(std::string path, std::unique_ptr stream) -{ - m_impl = new Impl(std::move(path), std::move(stream)); -} +IWD::IWD(std::string path, std::unique_ptr stream) { m_impl = new Impl(std::move(path), std::move(stream)); } -IWD::~IWD() -{ - delete m_impl; - m_impl = nullptr; +IWD::~IWD() { + delete m_impl; + m_impl = nullptr; } -IWD::IWD(IWD&& other) noexcept -{ - m_impl = other.m_impl; - other.m_impl = nullptr; +IWD::IWD(IWD &&other) noexcept { + m_impl = other.m_impl; + other.m_impl = nullptr; } -IWD& IWD::operator=(IWD&& other) noexcept -{ - m_impl = other.m_impl; - other.m_impl = nullptr; +IWD &IWD::operator=(IWD &&other) noexcept { + m_impl = other.m_impl; + other.m_impl = nullptr; - return *this; + return *this; } -bool IWD::Initialize() -{ - return m_impl->Initialize(); -} +bool IWD::Initialize() { return m_impl->Initialize(); } -SearchPathOpenFile IWD::Open(const std::string& fileName) -{ - return m_impl->Open(fileName); -} +SearchPathOpenFile IWD::Open(const std::string &fileName) { return m_impl->Open(fileName); } -std::string IWD::GetPath() -{ - return m_impl->GetPath(); -} +std::string IWD::GetPath() { return m_impl->GetPath(); } -std::string IWD::GetName() -{ - return m_impl->GetName(); -} +std::string IWD::GetName() { return m_impl->GetName(); } -void IWD::Find(const SearchPathSearchOptions& options, const std::function& callback) -{ - return m_impl->Find(options, callback); -} +void IWD::Find(const SearchPathSearchOptions &options, const std::function &callback) { return m_impl->Find(options, callback); } diff --git a/src/ObjLoading/ObjContainer/IWD/IWD.h b/src/ObjLoading/ObjContainer/IWD/IWD.h index 26a29680e..43b2e5724 100644 --- a/src/ObjLoading/ObjContainer/IWD/IWD.h +++ b/src/ObjLoading/ObjContainer/IWD/IWD.h @@ -2,35 +2,34 @@ #include +#include "ObjContainer/ObjContainerRepository.h" +#include "SearchPath/ISearchPath.h" #include "Utils/ClassUtils.h" #include "Utils/ObjStream.h" -#include "SearchPath/ISearchPath.h" -#include "ObjContainer/ObjContainerRepository.h" -class IWD final : public ISearchPath, IObjContainer -{ - class Impl; - Impl* m_impl; +class IWD final : public ISearchPath, IObjContainer { + class Impl; + Impl *m_impl; public: - static ObjContainerRepository Repository; - - IWD(std::string path, std::unique_ptr stream); - ~IWD() override; - - IWD(const IWD& other) = delete; - IWD(IWD&& other) noexcept; - IWD& operator=(const IWD& other) = delete; - IWD& operator=(IWD&& other) noexcept; - - /** - * \brief Initializes the IWD container. - * \return \c true when initialization was successful. - */ - bool Initialize(); - - SearchPathOpenFile Open(const std::string& fileName) override; - std::string GetPath() override; - std::string GetName() override; - void Find(const SearchPathSearchOptions& options, const std::function& callback) override; + static ObjContainerRepository Repository; + + IWD(std::string path, std::unique_ptr stream); + ~IWD() override; + + IWD(const IWD &other) = delete; + IWD(IWD &&other) noexcept; + IWD &operator=(const IWD &other) = delete; + IWD &operator=(IWD &&other) noexcept; + + /** + * \brief Initializes the IWD container. + * \return \c true when initialization was successful. + */ + bool Initialize(); + + SearchPathOpenFile Open(const std::string &fileName) override; + std::string GetPath() override; + std::string GetName() override; + void Find(const SearchPathSearchOptions &options, const std::function &callback) override; }; \ No newline at end of file diff --git a/src/ObjLoading/ObjContainer/ObjContainerRepository.h b/src/ObjLoading/ObjContainer/ObjContainerRepository.h index f7b13470d..660eb1697 100644 --- a/src/ObjLoading/ObjContainer/ObjContainerRepository.h +++ b/src/ObjLoading/ObjContainer/ObjContainerRepository.h @@ -4,111 +4,87 @@ #include "Utils/TransformIterator.h" #include +#include +#include #include #include -#include -#include -template -class ObjContainerRepository -{ - class ObjContainerEntry - { - public: - std::unique_ptr m_container; - std::set m_references; - - explicit ObjContainerEntry(std::unique_ptr container) - : m_container(std::move(container)) - { - } - - ~ObjContainerEntry() = default; - ObjContainerEntry(const ObjContainerEntry& other) = delete; - ObjContainerEntry(ObjContainerEntry&& other) noexcept = default; - ObjContainerEntry& operator=(const ObjContainerEntry& other) = delete; - ObjContainerEntry& operator=(ObjContainerEntry&& other) noexcept = default; - }; - - std::vector m_containers; +template class ObjContainerRepository { + class ObjContainerEntry { + public: + std::unique_ptr m_container; + std::set m_references; -public: - ObjContainerRepository() = default; - ~ObjContainerRepository() = default; - ObjContainerRepository(const ObjContainerRepository& other) = delete; - ObjContainerRepository(ObjContainerRepository&& other) noexcept = default; - ObjContainerRepository& operator=(const ObjContainerRepository& other) = delete; - ObjContainerRepository& operator=(ObjContainerRepository&& other) noexcept = default; - - void AddContainer(std::unique_ptr container, ReferencerType* referencer) - { - ObjContainerEntry entry(std::move(container)); - entry.m_references.insert(referencer); - m_containers.emplace_back(std::move(entry)); - } + explicit ObjContainerEntry(std::unique_ptr container) : m_container(std::move(container)) {} - bool AddContainerReference(ContainerType* container, ReferencerType* referencer) - { - auto firstEntry = std::find_if(m_containers.begin(), m_containers.end(), [container](const ObjContainerEntry& entry) - { - return entry.m_container.get() == container; - }); + ~ObjContainerEntry() = default; + ObjContainerEntry(const ObjContainerEntry &other) = delete; + ObjContainerEntry(ObjContainerEntry &&other) noexcept = default; + ObjContainerEntry &operator=(const ObjContainerEntry &other) = delete; + ObjContainerEntry &operator=(ObjContainerEntry &&other) noexcept = default; + }; - if (firstEntry != m_containers.end()) - { - firstEntry->m_references.insert(referencer); - return true; - } + std::vector m_containers; - return false; +public: + ObjContainerRepository() = default; + ~ObjContainerRepository() = default; + ObjContainerRepository(const ObjContainerRepository &other) = delete; + ObjContainerRepository(ObjContainerRepository &&other) noexcept = default; + ObjContainerRepository &operator=(const ObjContainerRepository &other) = delete; + ObjContainerRepository &operator=(ObjContainerRepository &&other) noexcept = default; + + void AddContainer(std::unique_ptr container, ReferencerType *referencer) { + ObjContainerEntry entry(std::move(container)); + entry.m_references.insert(referencer); + m_containers.emplace_back(std::move(entry)); + } + + bool AddContainerReference(ContainerType *container, ReferencerType *referencer) { + auto firstEntry = + std::find_if(m_containers.begin(), m_containers.end(), [container](const ObjContainerEntry &entry) { return entry.m_container.get() == container; }); + + if (firstEntry != m_containers.end()) { + firstEntry->m_references.insert(referencer); + return true; } - void RemoveContainerReferences(ReferencerType* referencer) - { - for (auto iEntry = m_containers.begin(); iEntry != m_containers.end();) - { - auto foundReference = iEntry->m_references.find(referencer); - - if (foundReference != iEntry->m_references.end()) - { - iEntry->m_references.erase(foundReference); - } - - if (iEntry->m_references.empty()) - { - iEntry = m_containers.erase(iEntry); - } - else - { - ++iEntry; - } - } - } + return false; + } - ContainerType* GetContainerByName(const std::string& name) - { - auto foundEntry = std::find_if(m_containers.begin(), m_containers.end(), [name](ObjContainerEntry& entry) - { - return entry.m_container->GetName() == name; - }); + void RemoveContainerReferences(ReferencerType *referencer) { + for (auto iEntry = m_containers.begin(); iEntry != m_containers.end();) { + auto foundReference = iEntry->m_references.find(referencer); - if (foundEntry != m_containers.end()) - { - return foundEntry->m_container.get(); - } + if (foundReference != iEntry->m_references.end()) { + iEntry->m_references.erase(foundReference); + } - return nullptr; + if (iEntry->m_references.empty()) { + iEntry = m_containers.erase(iEntry); + } else { + ++iEntry; + } } + } - TransformIterator::iterator, ObjContainerEntry&, ContainerType*> begin() - { - return TransformIterator::iterator, ObjContainerEntry&, ContainerType*>( - m_containers.begin(), [](ObjContainerEntry& entry) { return entry.m_container.get(); }); - } + ContainerType *GetContainerByName(const std::string &name) { + auto foundEntry = std::find_if(m_containers.begin(), m_containers.end(), [name](ObjContainerEntry &entry) { return entry.m_container->GetName() == name; }); - TransformIterator::iterator, ObjContainerEntry&, ContainerType*> end() - { - return TransformIterator::iterator, ObjContainerEntry&, ContainerType*>( - m_containers.end(), [](ObjContainerEntry& entry){ return entry.m_container.get(); }); + if (foundEntry != m_containers.end()) { + return foundEntry->m_container.get(); } + + return nullptr; + } + + TransformIterator::iterator, ObjContainerEntry &, ContainerType *> begin() { + return TransformIterator::iterator, ObjContainerEntry &, ContainerType *>( + m_containers.begin(), [](ObjContainerEntry &entry) { return entry.m_container.get(); }); + } + + TransformIterator::iterator, ObjContainerEntry &, ContainerType *> end() { + return TransformIterator::iterator, ObjContainerEntry &, ContainerType *>( + m_containers.end(), [](ObjContainerEntry &entry) { return entry.m_container.get(); }); + } }; diff --git a/src/ObjLoading/ObjContainer/SoundBank/SoundBank.cpp b/src/ObjLoading/ObjContainer/SoundBank/SoundBank.cpp index 7bdaadff9..4fd9f71f9 100644 --- a/src/ObjLoading/ObjContainer/SoundBank/SoundBank.cpp +++ b/src/ObjLoading/ObjContainer/SoundBank/SoundBank.cpp @@ -1,9 +1,9 @@ #include "SoundBank.h" +#include +#include #include #include -#include -#include #include "zlib.h" @@ -11,306 +11,239 @@ ObjContainerRepository SoundBank::Repository; -class SoundBankInputBuffer final : public objbuf -{ - std::istream& m_stream; - int64_t m_base_offset; - size_t m_size; - size_t m_offset; - bool m_open; +class SoundBankInputBuffer final : public objbuf { + std::istream &m_stream; + int64_t m_base_offset; + size_t m_size; + size_t m_offset; + bool m_open; protected: - std::streamsize showmanyc() override - { - return m_size - m_offset; - } - - int_type underflow() override - { - if (m_offset >= m_size) - return EOF; + std::streamsize showmanyc() override { return m_size - m_offset; } - return m_stream.peek(); - } + int_type underflow() override { + if (m_offset >= m_size) + return EOF; - int_type uflow() override - { - if (m_offset >= m_size) - return EOF; + return m_stream.peek(); + } - m_offset++; - return m_stream.get(); - } + int_type uflow() override { + if (m_offset >= m_size) + return EOF; - std::streamsize xsgetn(char* ptr, std::streamsize count) override - { - if (m_offset + count > m_size) - count = m_size - m_offset; + m_offset++; + return m_stream.get(); + } - if (count > 0) - { - m_stream.read(ptr, count); + std::streamsize xsgetn(char *ptr, std::streamsize count) override { + if (m_offset + count > m_size) + count = m_size - m_offset; - const auto readSize = m_stream.gcount(); - m_offset += static_cast(readSize); - return readSize; - } + if (count > 0) { + m_stream.read(ptr, count); - return 0; + const auto readSize = m_stream.gcount(); + m_offset += static_cast(readSize); + return readSize; } - pos_type seekoff(const off_type off, const std::ios_base::seekdir dir, const std::ios_base::openmode mode) override - { - if (dir == std::ios_base::beg) - { - return seekpos(off, mode); - } + return 0; + } - if (dir == std::ios_base::end) - { - if (off > m_size) - return pos_type(-1); + pos_type seekoff(const off_type off, const std::ios_base::seekdir dir, const std::ios_base::openmode mode) override { + if (dir == std::ios_base::beg) { + return seekpos(off, mode); + } - return seekpos(m_size - off, mode); - } + if (dir == std::ios_base::end) { + if (off > m_size) + return pos_type(-1); - return seekpos(m_offset + off, mode); + return seekpos(m_size - off, mode); } - pos_type seekpos(const pos_type pos, std::ios_base::openmode mode) override - { - if (pos < 0 || pos >= m_size) - return pos_type(-1); + return seekpos(m_offset + off, mode); + } - m_stream.seekg(m_base_offset + pos); - m_offset = static_cast(pos); - return pos; - } + pos_type seekpos(const pos_type pos, std::ios_base::openmode mode) override { + if (pos < 0 || pos >= m_size) + return pos_type(-1); + + m_stream.seekg(m_base_offset + pos); + m_offset = static_cast(pos); + return pos; + } public: - SoundBankInputBuffer(std::istream& stream, const int64_t baseOffset, const size_t size) - : m_stream(stream), - m_base_offset(baseOffset), - m_size(size), - m_offset(0), - m_open(true) - { - } + SoundBankInputBuffer(std::istream &stream, const int64_t baseOffset, const size_t size) + : m_stream(stream), m_base_offset(baseOffset), m_size(size), m_offset(0), m_open(true) {} - _NODISCARD bool is_open() const override - { - return m_open; - } + _NODISCARD bool is_open() const override { return m_open; } - bool close() override - { - const auto result = m_open; - m_open = false; - return result; - } + bool close() override { + const auto result = m_open; + m_open = false; + return result; + } }; -SoundBankEntryInputStream::SoundBankEntryInputStream() - : m_entry{} -{ -} +SoundBankEntryInputStream::SoundBankEntryInputStream() : m_entry{} {} SoundBankEntryInputStream::SoundBankEntryInputStream(std::unique_ptr stream, SoundAssetBankEntry entry) - : m_stream(std::move(stream)), - m_entry(entry) -{ + : m_stream(std::move(stream)), m_entry(entry) {} + +bool SoundBankEntryInputStream::IsOpen() const { return m_stream.get() != nullptr; } + +bool SoundBank::ReadHeader() { + m_stream->read(reinterpret_cast(&m_header), sizeof(m_header)); + if (m_stream->gcount() != sizeof(m_header)) { + printf("Unexpected eof when trying to load sndbank header.\n"); + return false; + } + + if (m_header.magic != MAGIC) { + std::cout << "Invalid sndbank magic 0x" << std::hex << m_header.magic << std::endl; + return false; + } + + if (m_header.version != VERSION) { + std::cout << "Unsupported sndbank version " << m_header.version << " (should be " << VERSION << ")" << std::endl; + return false; + } + + if (m_header.entrySize != sizeof(SoundAssetBankEntry)) { + std::cout << "Invalid sndbank entry size 0x" << std::hex << m_header.entrySize << " (should be 0x" << std::hex << sizeof(SoundAssetBankEntry) << ")" + << std::endl; + return false; + } + + if (m_header.fileSize != m_file_size) { + std::cout << "Invalid sndbank " << m_file_size << " (header expects " << m_header.fileSize << ")" << std::endl; + return false; + } + + if (m_header.entryCount && (m_header.entryOffset <= 0 || m_header.entryOffset + sizeof(SoundAssetBankEntry) * m_header.entryCount > m_file_size)) { + std::cout << "Invalid sndbank entry offset " << m_header.entryOffset << " (filesize is " << m_file_size << ")" << std::endl; + return false; + } + + if (m_header.checksumOffset <= 0 || m_header.checksumOffset + sizeof(SoundAssetBankChecksum) * m_header.entryCount > m_file_size) { + std::cout << "Invalid sndbank checksum offset " << m_header.checksumOffset << " (filesize is " << m_file_size << ")" << std::endl; + return false; + } + + if (m_header.dependencyCount * m_header.dependencySize > sizeof(SoundAssetBankHeader::dependencies)) { + std::cout << "Invalid sndbank dependency sizes (count is " << m_header.dependencyCount << "; size is " << m_header.dependencySize << ")" << std::endl; + return false; + } + + for (auto i = 0u; i < m_header.dependencyCount; i++) { + const auto dependencyLen = strnlen(&m_header.dependencies[i * m_header.dependencySize], m_header.dependencySize); + std::string dependencyName(&m_header.dependencies[i * m_header.dependencySize], dependencyLen); + + if (dependencyName.empty()) + continue; + + m_dependencies.emplace_back(std::move(dependencyName)); + } + + return true; } -bool SoundBankEntryInputStream::IsOpen() const -{ - return m_stream.get() != nullptr; -} +bool SoundBank::ReadEntries() { + m_stream->seekg(m_header.entryOffset); -bool SoundBank::ReadHeader() -{ - m_stream->read(reinterpret_cast(&m_header), sizeof(m_header)); - if (m_stream->gcount() != sizeof(m_header)) - { - printf("Unexpected eof when trying to load sndbank header.\n"); - return false; - } + for (auto i = 0u; i < m_header.entryCount; i++) { + SoundAssetBankEntry entry{}; + m_stream->read(reinterpret_cast(&entry), sizeof(entry)); - if (m_header.magic != MAGIC) - { - std::cout << "Invalid sndbank magic 0x" << std::hex << m_header.magic << std::endl; - return false; + if (m_stream->gcount() != sizeof(entry)) { + std::cout << "Failed to read sound bank entry at index " << i << std::endl; + return false; } - if (m_header.version != VERSION) - { - std::cout << "Unsupported sndbank version " << m_header.version << " (should be " << VERSION << ")" << std::endl; - return false; + if (entry.offset == 0 || entry.offset + entry.size >= m_file_size) { + std::cout << "Invalid sound bank entry data offset " << entry.offset << " (filesize is " << m_header.fileSize << ")" << std::endl; + return false; } - if (m_header.entrySize != sizeof(SoundAssetBankEntry)) - { - std::cout << "Invalid sndbank entry size 0x" << std::hex << m_header.entrySize << " (should be 0x" << std::hex << sizeof(SoundAssetBankEntry) << ")" << std::endl; - return false; - } + m_entries.push_back(entry); + m_entries_by_id.emplace(std::make_pair(entry.id, i)); + } - if (m_header.fileSize != m_file_size) - { - std::cout << "Invalid sndbank " << m_file_size << " (header expects " << m_header.fileSize << ")" << std::endl; - return false; - } - - if (m_header.entryCount - && (m_header.entryOffset <= 0 || m_header.entryOffset + sizeof(SoundAssetBankEntry) * m_header.entryCount > m_file_size)) - { - std::cout << "Invalid sndbank entry offset " << m_header.entryOffset << " (filesize is " << m_file_size << ")" << std::endl; - return false; - } - - if (m_header.checksumOffset <= 0 || m_header.checksumOffset + sizeof(SoundAssetBankChecksum) * m_header.entryCount > m_file_size) - { - std::cout << "Invalid sndbank checksum offset " << m_header.checksumOffset << " (filesize is " << m_file_size << ")" << std::endl; - return false; - } - - if (m_header.dependencyCount * m_header.dependencySize > sizeof(SoundAssetBankHeader::dependencies)) - { - std::cout << "Invalid sndbank dependency sizes (count is " << m_header.dependencyCount << "; size is " << m_header.dependencySize << ")" << std::endl; - return false; - } - - for (auto i = 0u; i < m_header.dependencyCount; i++) - { - const auto dependencyLen = strnlen(&m_header.dependencies[i * m_header.dependencySize], m_header.dependencySize); - std::string dependencyName(&m_header.dependencies[i * m_header.dependencySize], dependencyLen); - - if (dependencyName.empty()) - continue; - - m_dependencies.emplace_back(std::move(dependencyName)); - } - - return true; -} - -bool SoundBank::ReadEntries() -{ - m_stream->seekg(m_header.entryOffset); - - for (auto i = 0u; i < m_header.entryCount; i++) - { - SoundAssetBankEntry entry{}; - m_stream->read(reinterpret_cast(&entry), sizeof(entry)); - - if (m_stream->gcount() != sizeof(entry)) - { - std::cout << "Failed to read sound bank entry at index " << i << std::endl; - return false; - } - - if (entry.offset == 0 || entry.offset + entry.size >= m_file_size) - { - std::cout << "Invalid sound bank entry data offset " << entry.offset << " (filesize is " << m_header.fileSize << ")" << std::endl; - return false; - } - - m_entries.push_back(entry); - m_entries_by_id.emplace(std::make_pair(entry.id, i)); - } - - return true; + return true; } -bool SoundBank::ReadChecksums() -{ - m_stream->seekg(m_header.entryOffset); - - for (auto i = 0u; i < m_header.entryCount; i++) - { - SoundAssetBankChecksum checksum{}; - m_stream->read(reinterpret_cast(&checksum), sizeof(checksum)); +bool SoundBank::ReadChecksums() { + m_stream->seekg(m_header.entryOffset); - if (m_stream->gcount() != sizeof(checksum)) - { - std::cout << "Failed to read sound bank checksum at index " << i << std::endl; - return false; - } + for (auto i = 0u; i < m_header.entryCount; i++) { + SoundAssetBankChecksum checksum{}; + m_stream->read(reinterpret_cast(&checksum), sizeof(checksum)); - m_checksums.push_back(checksum); + if (m_stream->gcount() != sizeof(checksum)) { + std::cout << "Failed to read sound bank checksum at index " << i << std::endl; + return false; } - return true; + m_checksums.push_back(checksum); + } + + return true; } -std::string SoundBank::GetFileNameForDefinition(const bool streamed, const char* zone, const char* language) -{ - std::ostringstream str; +std::string SoundBank::GetFileNameForDefinition(const bool streamed, const char *zone, const char *language) { + std::ostringstream str; - assert(zone != nullptr); + assert(zone != nullptr); - if (zone) - str << zone; + if (zone) + str << zone; - if (language) - str << "." << language; + if (language) + str << "." << language; - if (streamed) - str << ".sabs"; - else - str << ".sabl"; + if (streamed) + str << ".sabs"; + else + str << ".sabl"; - return str.str(); + return str.str(); } SoundBank::SoundBank(std::string fileName, std::unique_ptr stream, const int64_t fileSize) - : m_file_name(std::move(fileName)), - m_stream(std::move(stream)), - m_file_size(fileSize), - m_initialized(false), - m_header{} -{ -} + : m_file_name(std::move(fileName)), m_stream(std::move(stream)), m_file_size(fileSize), m_initialized(false), m_header{} {} -std::string SoundBank::GetName() -{ - return m_file_name; -} +std::string SoundBank::GetName() { return m_file_name; } -bool SoundBank::Initialize() -{ - if (m_initialized) - return true; +bool SoundBank::Initialize() { + if (m_initialized) + return true; - if (!ReadHeader() - || !ReadEntries() - || !ReadChecksums()) - return false; + if (!ReadHeader() || !ReadEntries() || !ReadChecksums()) + return false; - m_initialized = true; - return true; + m_initialized = true; + return true; } -const std::vector& SoundBank::GetDependencies() const -{ - return m_dependencies; -} +const std::vector &SoundBank::GetDependencies() const { return m_dependencies; } -bool SoundBank::VerifyChecksum(const SoundAssetBankChecksum& checksum) const -{ - return m_initialized && memcmp(checksum.checksumBytes, m_header.checksumChecksum.checksumBytes, sizeof(SoundAssetBankChecksum)) == 0; +bool SoundBank::VerifyChecksum(const SoundAssetBankChecksum &checksum) const { + return m_initialized && memcmp(checksum.checksumBytes, m_header.checksumChecksum.checksumBytes, sizeof(SoundAssetBankChecksum)) == 0; } -SoundBankEntryInputStream SoundBank::GetEntryStream(const unsigned id) const -{ - const auto foundEntry = m_entries_by_id.find(id); +SoundBankEntryInputStream SoundBank::GetEntryStream(const unsigned id) const { + const auto foundEntry = m_entries_by_id.find(id); - if (foundEntry != m_entries_by_id.end()) - { - const auto& entry = m_entries[foundEntry->second]; + if (foundEntry != m_entries_by_id.end()) { + const auto &entry = m_entries[foundEntry->second]; - m_stream->seekg(entry.offset); + m_stream->seekg(entry.offset); - return SoundBankEntryInputStream(std::make_unique(std::make_unique(*m_stream, entry.offset, entry.size)), entry); - } + return SoundBankEntryInputStream(std::make_unique(std::make_unique(*m_stream, entry.offset, entry.size)), entry); + } - return SoundBankEntryInputStream(); + return SoundBankEntryInputStream(); } diff --git a/src/ObjLoading/ObjContainer/SoundBank/SoundBank.h b/src/ObjLoading/ObjContainer/SoundBank/SoundBank.h index af0462223..ab2d1be95 100644 --- a/src/ObjLoading/ObjContainer/SoundBank/SoundBank.h +++ b/src/ObjLoading/ObjContainer/SoundBank/SoundBank.h @@ -2,64 +2,62 @@ #include -#include "Utils/ClassUtils.h" #include "ObjContainer/ObjContainerReferenceable.h" #include "ObjContainer/ObjContainerRepository.h" #include "ObjContainer/SoundBank/SoundBankTypes.h" #include "SearchPath/ISearchPath.h" +#include "Utils/ClassUtils.h" #include "Utils/FileUtils.h" #include "Utils/ObjStream.h" #include "Zone/Zone.h" -class SoundBankEntryInputStream -{ +class SoundBankEntryInputStream { public: - std::unique_ptr m_stream; - SoundAssetBankEntry m_entry; + std::unique_ptr m_stream; + SoundAssetBankEntry m_entry; - SoundBankEntryInputStream(); - SoundBankEntryInputStream(std::unique_ptr stream, SoundAssetBankEntry entry); + SoundBankEntryInputStream(); + SoundBankEntryInputStream(std::unique_ptr stream, SoundAssetBankEntry entry); - _NODISCARD bool IsOpen() const; + _NODISCARD bool IsOpen() const; }; -class SoundBank final : public ObjContainerReferenceable -{ - static constexpr uint32_t MAGIC = FileUtils::MakeMagic32('2', 'U', 'X', '#'); - static constexpr uint32_t VERSION = 14u; +class SoundBank final : public ObjContainerReferenceable { + static constexpr uint32_t MAGIC = FileUtils::MakeMagic32('2', 'U', 'X', '#'); + static constexpr uint32_t VERSION = 14u; - std::string m_file_name; - std::unique_ptr m_stream; - int64_t m_file_size; + std::string m_file_name; + std::unique_ptr m_stream; + int64_t m_file_size; - bool m_initialized; - SoundAssetBankHeader m_header; - std::vector m_dependencies; - std::vector m_entries; - std::vector m_checksums; - std::unordered_map m_entries_by_id; + bool m_initialized; + SoundAssetBankHeader m_header; + std::vector m_dependencies; + std::vector m_entries; + std::vector m_checksums; + std::unordered_map m_entries_by_id; - bool ReadHeader(); - bool ReadEntries(); - bool ReadChecksums(); + bool ReadHeader(); + bool ReadEntries(); + bool ReadChecksums(); public: - static ObjContainerRepository Repository; + static ObjContainerRepository Repository; - static std::string GetFileNameForDefinition(bool streamed, const char* zone, const char* language); + static std::string GetFileNameForDefinition(bool streamed, const char *zone, const char *language); - SoundBank(std::string fileName, std::unique_ptr stream, int64_t fileSize); - ~SoundBank() override = default; - SoundBank(const SoundBank& other) = delete; - SoundBank(SoundBank&& other) noexcept = default; - SoundBank& operator=(const SoundBank& other) = delete; - SoundBank& operator=(SoundBank&& other) noexcept = default; + SoundBank(std::string fileName, std::unique_ptr stream, int64_t fileSize); + ~SoundBank() override = default; + SoundBank(const SoundBank &other) = delete; + SoundBank(SoundBank &&other) noexcept = default; + SoundBank &operator=(const SoundBank &other) = delete; + SoundBank &operator=(SoundBank &&other) noexcept = default; - std::string GetName() override; + std::string GetName() override; - bool Initialize(); - _NODISCARD const std::vector& GetDependencies() const; + bool Initialize(); + _NODISCARD const std::vector &GetDependencies() const; - _NODISCARD bool VerifyChecksum(const SoundAssetBankChecksum& checksum) const; - _NODISCARD SoundBankEntryInputStream GetEntryStream(unsigned int id) const; + _NODISCARD bool VerifyChecksum(const SoundAssetBankChecksum &checksum) const; + _NODISCARD SoundBankEntryInputStream GetEntryStream(unsigned int id) const; }; diff --git a/src/ObjLoading/ObjContainer/SoundBank/SoundBankTypes.h b/src/ObjLoading/ObjContainer/SoundBank/SoundBankTypes.h index 46927c27c..3338a85b1 100644 --- a/src/ObjLoading/ObjContainer/SoundBank/SoundBankTypes.h +++ b/src/ObjLoading/ObjContainer/SoundBank/SoundBankTypes.h @@ -2,44 +2,40 @@ #include -class SoundBankConsts -{ - SoundBankConsts() = default; +class SoundBankConsts { + SoundBankConsts() = default; public: - static constexpr unsigned OFFSET_DATA_START = 0x800; + static constexpr unsigned OFFSET_DATA_START = 0x800; }; -struct SoundAssetBankChecksum -{ - char checksumBytes[16]; +struct SoundAssetBankChecksum { + char checksumBytes[16]; }; -struct SoundAssetBankHeader -{ - unsigned int magic; // + 0x0 - unsigned int version; // + 0x4 - unsigned int entrySize; // + 0x8 - unsigned int checksumSize; // + 0xC - unsigned int dependencySize; // + 0x10 - unsigned int entryCount; // + 0x14 - unsigned int dependencyCount; // + 0x18 - unsigned int pad32; // + 0x1C - int64_t fileSize; // + 0x20 - int64_t entryOffset; // + 0x28 - int64_t checksumOffset; // + 0x30 - SoundAssetBankChecksum checksumChecksum; // + 0x38 - char dependencies[512]; // + 0x48 +struct SoundAssetBankHeader { + unsigned int magic; // + 0x0 + unsigned int version; // + 0x4 + unsigned int entrySize; // + 0x8 + unsigned int checksumSize; // + 0xC + unsigned int dependencySize; // + 0x10 + unsigned int entryCount; // + 0x14 + unsigned int dependencyCount; // + 0x18 + unsigned int pad32; // + 0x1C + int64_t fileSize; // + 0x20 + int64_t entryOffset; // + 0x28 + int64_t checksumOffset; // + 0x30 + SoundAssetBankChecksum checksumChecksum; // + 0x38 + char dependencies[512]; // + 0x48 }; -struct SoundAssetBankEntry -{ - unsigned int id; - unsigned int size; - unsigned int offset; - unsigned int frameCount; - char frameRateIndex; - char channelCount; - char looping; - char format; +struct SoundAssetBankEntry { + unsigned int id; + unsigned int size; + unsigned int offset; + unsigned int frameCount; + char frameRateIndex; + char channelCount; + char looping; + char format; }; diff --git a/src/ObjLoading/ObjLoading.cpp b/src/ObjLoading/ObjLoading.cpp index 25c86747d..4d74be369 100644 --- a/src/ObjLoading/ObjLoading.cpp +++ b/src/ObjLoading/ObjLoading.cpp @@ -2,119 +2,88 @@ #include -#include "IObjLoader.h" #include "Game/IW3/ObjLoaderIW3.h" #include "Game/IW4/ObjLoaderIW4.h" #include "Game/IW5/ObjLoaderIW5.h" #include "Game/T5/ObjLoaderT5.h" #include "Game/T6/ObjLoaderT6.h" +#include "IObjLoader.h" #include "ObjContainer/IWD/IWD.h" #include "SearchPath/SearchPaths.h" #include "Utils/ObjFileStream.h" ObjLoading::Configuration_t ObjLoading::Configuration; -const IObjLoader* const OBJ_LOADERS[] -{ - new IW3::ObjLoader(), - new IW4::ObjLoader(), - new IW5::ObjLoader(), - new T5::ObjLoader(), - new T6::ObjLoader() -}; - -void ObjLoading::LoadReferencedContainersForZone(ISearchPath* searchPath, Zone* zone) -{ - for (const auto* loader : OBJ_LOADERS) - { - if (loader->SupportsZone(zone)) - { - loader->LoadReferencedContainersForZone(searchPath, zone); - return; - } +const IObjLoader *const OBJ_LOADERS[]{new IW3::ObjLoader(), new IW4::ObjLoader(), new IW5::ObjLoader(), new T5::ObjLoader(), new T6::ObjLoader()}; + +void ObjLoading::LoadReferencedContainersForZone(ISearchPath *searchPath, Zone *zone) { + for (const auto *loader : OBJ_LOADERS) { + if (loader->SupportsZone(zone)) { + loader->LoadReferencedContainersForZone(searchPath, zone); + return; } + } } -void ObjLoading::LoadObjDataForZone(ISearchPath* searchPath, Zone* zone) -{ - for (const auto* loader : OBJ_LOADERS) - { - if (loader->SupportsZone(zone)) - { - loader->LoadObjDataForZone(searchPath, zone); - return; - } +void ObjLoading::LoadObjDataForZone(ISearchPath *searchPath, Zone *zone) { + for (const auto *loader : OBJ_LOADERS) { + if (loader->SupportsZone(zone)) { + loader->LoadObjDataForZone(searchPath, zone); + return; } + } } -void ObjLoading::UnloadContainersOfZone(Zone* zone) -{ - for (const auto* loader : OBJ_LOADERS) - { - if (loader->SupportsZone(zone)) - { - loader->UnloadContainersOfZone(zone); - return; - } +void ObjLoading::UnloadContainersOfZone(Zone *zone) { + for (const auto *loader : OBJ_LOADERS) { + if (loader->SupportsZone(zone)) { + loader->UnloadContainersOfZone(zone); + return; } + } } -void ObjLoading::LoadIWDsInSearchPath(ISearchPath* searchPath) -{ - searchPath->Find(SearchPathSearchOptions().IncludeSubdirectories(false).FilterExtensions("iwd"), [searchPath](const std::string& path) - { - auto file = std::make_unique(path, std::fstream::in | std::fstream::binary); - - if (file->is_open()) - { - auto iwd = std::make_unique(path, std::move(file)); - - if (iwd->Initialize()) - { - IWD::Repository.AddContainer(std::move(iwd), searchPath); - } - } - }); -} +void ObjLoading::LoadIWDsInSearchPath(ISearchPath *searchPath) { + searchPath->Find(SearchPathSearchOptions().IncludeSubdirectories(false).FilterExtensions("iwd"), [searchPath](const std::string &path) { + auto file = std::make_unique(path, std::fstream::in | std::fstream::binary); -void ObjLoading::UnloadIWDsInSearchPath(ISearchPath* searchPath) -{ - IWD::Repository.RemoveContainerReferences(searchPath); + if (file->is_open()) { + auto iwd = std::make_unique(path, std::move(file)); + + if (iwd->Initialize()) { + IWD::Repository.AddContainer(std::move(iwd), searchPath); + } + } + }); } -SearchPaths ObjLoading::GetIWDSearchPaths() -{ - SearchPaths iwdPaths; +void ObjLoading::UnloadIWDsInSearchPath(ISearchPath *searchPath) { IWD::Repository.RemoveContainerReferences(searchPath); } - for (auto* iwd : IWD::Repository) - { - iwdPaths.IncludeSearchPath(iwd); - } +SearchPaths ObjLoading::GetIWDSearchPaths() { + SearchPaths iwdPaths; + + for (auto *iwd : IWD::Repository) { + iwdPaths.IncludeSearchPath(iwd); + } - return iwdPaths; + return iwdPaths; } -bool ObjLoading::LoadAssetForZone(AssetLoadingContext* context, const asset_type_t assetType, const std::string& assetName) -{ - for (const auto* loader : OBJ_LOADERS) - { - if (loader->SupportsZone(context->m_zone)) - { - return loader->LoadAssetForZone(context, assetType, assetName); - } +bool ObjLoading::LoadAssetForZone(AssetLoadingContext *context, const asset_type_t assetType, const std::string &assetName) { + for (const auto *loader : OBJ_LOADERS) { + if (loader->SupportsZone(context->m_zone)) { + return loader->LoadAssetForZone(context, assetType, assetName); } + } - return false; + return false; } -void ObjLoading::FinalizeAssetsForZone(AssetLoadingContext* context) -{ - for (const auto* loader : OBJ_LOADERS) - { - if (loader->SupportsZone(context->m_zone)) - { - loader->FinalizeAssetsForZone(context); - return; - } +void ObjLoading::FinalizeAssetsForZone(AssetLoadingContext *context) { + for (const auto *loader : OBJ_LOADERS) { + if (loader->SupportsZone(context->m_zone)) { + loader->FinalizeAssetsForZone(context); + return; } + } } diff --git a/src/ObjLoading/ObjLoading.h b/src/ObjLoading/ObjLoading.h index 663014c3f..d47ed7935 100644 --- a/src/ObjLoading/ObjLoading.h +++ b/src/ObjLoading/ObjLoading.h @@ -1,59 +1,57 @@ #pragma once #include "AssetLoading/AssetLoadingContext.h" -#include "Zone/Zone.h" #include "SearchPath/ISearchPath.h" #include "SearchPath/SearchPaths.h" +#include "Zone/Zone.h" -class ObjLoading -{ +class ObjLoading { public: - static class Configuration_t - { - public: - bool Verbose = false; - bool MenuPermissiveParsing = false; - bool MenuNoOptimization = false; - } Configuration; - - /** - * \brief Loads all containers that are being referenced by the specified zone. - * \param searchPath The search path to use to find the referenced containers. - * \param zone The zone to load all referenced containers of. - */ - static void LoadReferencedContainersForZone(ISearchPath* searchPath, Zone* zone); - - /** - * \brief Unloads all containers that were referenced by a specified zone. If referenced by more than one zone a container will only be unloaded once all referencing zones were unloaded the container. - * \param zone The zone to unload all referenced containers for. - */ - static void UnloadContainersOfZone(Zone* zone); - - /** - * \brief Loads all IWDs that can be found in a specified search path. - * \param searchPath The search path that contains IWDs to be loaded. - */ - static void LoadIWDsInSearchPath(ISearchPath* searchPath); - - /** - * \brief Unloads all IWDs that were loaded from the specified search path. - * \param searchPath The search path that was used to load the IWDs to be unloaded. - */ - static void UnloadIWDsInSearchPath(ISearchPath* searchPath); - - /** - * \brief Creates a \c SearchPaths object containing all IWDs that are currently loaded. - * \return A \c SearchPaths object containing all IWDs that are currently loaded. - */ - static SearchPaths GetIWDSearchPaths(); - - /** - * \brief Loads the obj data for all assets of a zone. - * \param searchPath The search path to use to search for all obj data files. - * \param zone The zone of the assets to load the obj data for. - */ - static void LoadObjDataForZone(ISearchPath* searchPath, Zone* zone); - - static bool LoadAssetForZone(AssetLoadingContext* context, asset_type_t assetType, const std::string& assetName); - static void FinalizeAssetsForZone(AssetLoadingContext* context); + static class Configuration_t { + public: + bool Verbose = false; + bool MenuPermissiveParsing = false; + bool MenuNoOptimization = false; + } Configuration; + + /** + * \brief Loads all containers that are being referenced by the specified zone. + * \param searchPath The search path to use to find the referenced containers. + * \param zone The zone to load all referenced containers of. + */ + static void LoadReferencedContainersForZone(ISearchPath *searchPath, Zone *zone); + + /** + * \brief Unloads all containers that were referenced by a specified zone. If referenced by more than one zone a container will only be unloaded once all + * referencing zones were unloaded the container. \param zone The zone to unload all referenced containers for. + */ + static void UnloadContainersOfZone(Zone *zone); + + /** + * \brief Loads all IWDs that can be found in a specified search path. + * \param searchPath The search path that contains IWDs to be loaded. + */ + static void LoadIWDsInSearchPath(ISearchPath *searchPath); + + /** + * \brief Unloads all IWDs that were loaded from the specified search path. + * \param searchPath The search path that was used to load the IWDs to be unloaded. + */ + static void UnloadIWDsInSearchPath(ISearchPath *searchPath); + + /** + * \brief Creates a \c SearchPaths object containing all IWDs that are currently loaded. + * \return A \c SearchPaths object containing all IWDs that are currently loaded. + */ + static SearchPaths GetIWDSearchPaths(); + + /** + * \brief Loads the obj data for all assets of a zone. + * \param searchPath The search path to use to search for all obj data files. + * \param zone The zone of the assets to load the obj data for. + */ + static void LoadObjDataForZone(ISearchPath *searchPath, Zone *zone); + + static bool LoadAssetForZone(AssetLoadingContext *context, asset_type_t assetType, const std::string &assetName); + static void FinalizeAssetsForZone(AssetLoadingContext *context); }; diff --git a/src/ObjLoading/Parsing/LocalizeFile/LocalizeFileParser.cpp b/src/ObjLoading/Parsing/LocalizeFile/LocalizeFileParser.cpp index 356e69803..9503f388b 100644 --- a/src/ObjLoading/Parsing/LocalizeFile/LocalizeFileParser.cpp +++ b/src/ObjLoading/Parsing/LocalizeFile/LocalizeFileParser.cpp @@ -8,31 +8,17 @@ #include "Sequence/SequenceLocalizeFileReference.h" #include "Sequence/SequenceLocalizeFileVersion.h" -LocalizeFileParser::LocalizeFileParser(SimpleLexer* lexer, GameLanguage language) - : AbstractParser(lexer, std::make_unique(language)) -{ -} +LocalizeFileParser::LocalizeFileParser(SimpleLexer *lexer, GameLanguage language) + : AbstractParser(lexer, std::make_unique(language)) {} -const std::vector::sequence_t*>& LocalizeFileParser::GetTestsForState() -{ - static std::vector tests({ - new SequenceLocalizeFileReference(), - new SequenceLocalizeFileConfig(), - new SequenceLocalizeFileNotes(), - new SequenceLocalizeFileVersion(), - new SequenceLocalizeFileEndMarker(), - new SequenceLocalizeFileLanguageValue(), - new SequenceLocalizeFileConsumeEmptyLines() - }); +const std::vector::sequence_t *> &LocalizeFileParser::GetTestsForState() { + static std::vector tests({new SequenceLocalizeFileReference(), new SequenceLocalizeFileConfig(), new SequenceLocalizeFileNotes(), + new SequenceLocalizeFileVersion(), new SequenceLocalizeFileEndMarker(), new SequenceLocalizeFileLanguageValue(), + new SequenceLocalizeFileConsumeEmptyLines()}); - static std::vector noTests({ - new SequenceLocalizeFileConsumeEmptyLines() - }); + static std::vector noTests({new SequenceLocalizeFileConsumeEmptyLines()}); - return !m_state->m_end ? tests : noTests; + return !m_state->m_end ? tests : noTests; } -std::vector LocalizeFileParser::GetParsedValues() -{ - return std::move(m_state->m_entries); -} +std::vector LocalizeFileParser::GetParsedValues() { return std::move(m_state->m_entries); } diff --git a/src/ObjLoading/Parsing/LocalizeFile/LocalizeFileParser.h b/src/ObjLoading/Parsing/LocalizeFile/LocalizeFileParser.h index b730d503f..6f1f3b712 100644 --- a/src/ObjLoading/Parsing/LocalizeFile/LocalizeFileParser.h +++ b/src/ObjLoading/Parsing/LocalizeFile/LocalizeFileParser.h @@ -1,17 +1,16 @@ #pragma once -#include "LocalizeFileParserState.h" #include "Game/GameLanguage.h" +#include "LocalizeFileParserState.h" +#include "Parsing/Impl/AbstractParser.h" #include "Parsing/Simple/SimpleLexer.h" #include "Parsing/Simple/SimpleParserValue.h" -#include "Parsing/Impl/AbstractParser.h" -class LocalizeFileParser final : public AbstractParser -{ +class LocalizeFileParser final : public AbstractParser { protected: - const std::vector& GetTestsForState() override; + const std::vector &GetTestsForState() override; public: - LocalizeFileParser(SimpleLexer* lexer, GameLanguage language); - std::vector GetParsedValues(); + LocalizeFileParser(SimpleLexer *lexer, GameLanguage language); + std::vector GetParsedValues(); }; diff --git a/src/ObjLoading/Parsing/LocalizeFile/LocalizeFileParserState.cpp b/src/ObjLoading/Parsing/LocalizeFile/LocalizeFileParserState.cpp index 803081ec6..dfd7c47ff 100644 --- a/src/ObjLoading/Parsing/LocalizeFile/LocalizeFileParserState.cpp +++ b/src/ObjLoading/Parsing/LocalizeFile/LocalizeFileParserState.cpp @@ -2,11 +2,8 @@ #include "Localize/LocalizeCommon.h" -LocalizeFileParserState::LocalizeFileParserState(const GameLanguage language) - : m_end(false), - m_language(language) -{ - m_language_name_caps = LocalizeCommon::GetNameOfLanguage(m_language); - for (auto& c : m_language_name_caps) - c = static_cast(toupper(c)); +LocalizeFileParserState::LocalizeFileParserState(const GameLanguage language) : m_end(false), m_language(language) { + m_language_name_caps = LocalizeCommon::GetNameOfLanguage(m_language); + for (auto &c : m_language_name_caps) + c = static_cast(toupper(c)); } diff --git a/src/ObjLoading/Parsing/LocalizeFile/LocalizeFileParserState.h b/src/ObjLoading/Parsing/LocalizeFile/LocalizeFileParserState.h index d8f01b011..512e28782 100644 --- a/src/ObjLoading/Parsing/LocalizeFile/LocalizeFileParserState.h +++ b/src/ObjLoading/Parsing/LocalizeFile/LocalizeFileParserState.h @@ -5,18 +5,17 @@ #include "Game/GameLanguage.h" #include "Localize/LocalizeFile.h" -class LocalizeFileParserState -{ +class LocalizeFileParserState { public: - bool m_end; + bool m_end; - std::vector m_entries; + std::vector m_entries; - GameLanguage m_language; - std::string m_language_name_caps; + GameLanguage m_language; + std::string m_language_name_caps; - std::string m_current_reference; - std::unordered_set m_current_reference_languages; + std::string m_current_reference; + std::unordered_set m_current_reference_languages; - explicit LocalizeFileParserState(GameLanguage language); + explicit LocalizeFileParserState(GameLanguage language); }; diff --git a/src/ObjLoading/Parsing/LocalizeFile/LocalizeFileReader.cpp b/src/ObjLoading/Parsing/LocalizeFile/LocalizeFileReader.cpp index d9a28df54..dc0a7b296 100644 --- a/src/ObjLoading/Parsing/LocalizeFile/LocalizeFileReader.cpp +++ b/src/ObjLoading/Parsing/LocalizeFile/LocalizeFileReader.cpp @@ -4,44 +4,38 @@ #include "Parsing/Impl/CommentRemovingStreamProxy.h" #include "Parsing/Impl/ParserSingleInputStream.h" -LocalizeFileReader::LocalizeFileReader(std::istream& stream, std::string fileName, GameLanguage language) - : m_file_name(std::move(fileName)), - m_stream(nullptr), - m_language(language) -{ - OpenBaseStream(stream); - SetupStreamProxies(); - m_stream = m_open_streams.back().get(); +LocalizeFileReader::LocalizeFileReader(std::istream &stream, std::string fileName, GameLanguage language) + : m_file_name(std::move(fileName)), m_stream(nullptr), m_language(language) { + OpenBaseStream(stream); + SetupStreamProxies(); + m_stream = m_open_streams.back().get(); } -bool LocalizeFileReader::OpenBaseStream(std::istream& stream) -{ - m_open_streams.emplace_back(std::make_unique(stream, m_file_name)); - return true; +bool LocalizeFileReader::OpenBaseStream(std::istream &stream) { + m_open_streams.emplace_back(std::make_unique(stream, m_file_name)); + return true; } -void LocalizeFileReader::SetupStreamProxies() -{ - m_open_streams.emplace_back(std::make_unique(m_open_streams.back().get())); +void LocalizeFileReader::SetupStreamProxies() { + m_open_streams.emplace_back(std::make_unique(m_open_streams.back().get())); - m_stream = m_open_streams.back().get(); + m_stream = m_open_streams.back().get(); } -std::vector LocalizeFileReader::ReadLocalizeFile() -{ - SimpleLexer::Config lexerConfig; - lexerConfig.m_emit_new_line_tokens = true; - lexerConfig.m_read_strings = true; - lexerConfig.m_string_escape_sequences = true; - lexerConfig.m_read_integer_numbers = false; - lexerConfig.m_read_floating_point_numbers = false; - const auto lexer = std::make_unique(m_stream, std::move(lexerConfig)); +std::vector LocalizeFileReader::ReadLocalizeFile() { + SimpleLexer::Config lexerConfig; + lexerConfig.m_emit_new_line_tokens = true; + lexerConfig.m_read_strings = true; + lexerConfig.m_string_escape_sequences = true; + lexerConfig.m_read_integer_numbers = false; + lexerConfig.m_read_floating_point_numbers = false; + const auto lexer = std::make_unique(m_stream, std::move(lexerConfig)); - const auto parser = std::make_unique(lexer.get(), m_language); + const auto parser = std::make_unique(lexer.get(), m_language); - if (parser->Parse()) - return parser->GetParsedValues(); + if (parser->Parse()) + return parser->GetParsedValues(); - std::cout << "Parsing localization file failed!" << std::endl; - return std::vector(); + std::cout << "Parsing localization file failed!" << std::endl; + return std::vector(); } diff --git a/src/ObjLoading/Parsing/LocalizeFile/LocalizeFileReader.h b/src/ObjLoading/Parsing/LocalizeFile/LocalizeFileReader.h index 43645efd9..b6161465e 100644 --- a/src/ObjLoading/Parsing/LocalizeFile/LocalizeFileReader.h +++ b/src/ObjLoading/Parsing/LocalizeFile/LocalizeFileReader.h @@ -8,18 +8,17 @@ #include "Localize/LocalizeFile.h" #include "Parsing/IParserLineStream.h" -class LocalizeFileReader -{ - std::string m_file_name; - IParserLineStream* m_stream; - std::vector> m_open_streams; - GameLanguage m_language; +class LocalizeFileReader { + std::string m_file_name; + IParserLineStream *m_stream; + std::vector> m_open_streams; + GameLanguage m_language; - bool OpenBaseStream(std::istream& stream); - void SetupStreamProxies(); + bool OpenBaseStream(std::istream &stream); + void SetupStreamProxies(); public: - LocalizeFileReader(std::istream& stream, std::string fileName, GameLanguage language); + LocalizeFileReader(std::istream &stream, std::string fileName, GameLanguage language); - std::vector ReadLocalizeFile(); + std::vector ReadLocalizeFile(); }; diff --git a/src/ObjLoading/Parsing/LocalizeFile/Sequence/SequenceLocalizeFileConfig.cpp b/src/ObjLoading/Parsing/LocalizeFile/Sequence/SequenceLocalizeFileConfig.cpp index a8c0e2b2d..098aa47ae 100644 --- a/src/ObjLoading/Parsing/LocalizeFile/Sequence/SequenceLocalizeFileConfig.cpp +++ b/src/ObjLoading/Parsing/LocalizeFile/Sequence/SequenceLocalizeFileConfig.cpp @@ -2,17 +2,10 @@ #include "Parsing/Simple/Matcher/SimpleMatcherFactory.h" -SequenceLocalizeFileConfig::SequenceLocalizeFileConfig() -{ - const SimpleMatcherFactory create(this); +SequenceLocalizeFileConfig::SequenceLocalizeFileConfig() { + const SimpleMatcherFactory create(this); - AddMatchers({ - create.Keyword("CONFIG"), - create.String(), - create.Type(SimpleParserValueType::NEW_LINE) - }); + AddMatchers({create.Keyword("CONFIG"), create.String(), create.Type(SimpleParserValueType::NEW_LINE)}); } -void SequenceLocalizeFileConfig::ProcessMatch(LocalizeFileParserState* state, SequenceResult& result) const -{ -} +void SequenceLocalizeFileConfig::ProcessMatch(LocalizeFileParserState *state, SequenceResult &result) const {} diff --git a/src/ObjLoading/Parsing/LocalizeFile/Sequence/SequenceLocalizeFileConfig.h b/src/ObjLoading/Parsing/LocalizeFile/Sequence/SequenceLocalizeFileConfig.h index a17bd0c97..b2c2c0b42 100644 --- a/src/ObjLoading/Parsing/LocalizeFile/Sequence/SequenceLocalizeFileConfig.h +++ b/src/ObjLoading/Parsing/LocalizeFile/Sequence/SequenceLocalizeFileConfig.h @@ -2,11 +2,10 @@ #include "Parsing/LocalizeFile/LocalizeFileParser.h" -class SequenceLocalizeFileConfig final : public LocalizeFileParser::sequence_t -{ +class SequenceLocalizeFileConfig final : public LocalizeFileParser::sequence_t { protected: - void ProcessMatch(LocalizeFileParserState* state, SequenceResult& result) const override; + void ProcessMatch(LocalizeFileParserState *state, SequenceResult &result) const override; public: - SequenceLocalizeFileConfig(); + SequenceLocalizeFileConfig(); }; diff --git a/src/ObjLoading/Parsing/LocalizeFile/Sequence/SequenceLocalizeFileConsumeEmptyLines.cpp b/src/ObjLoading/Parsing/LocalizeFile/Sequence/SequenceLocalizeFileConsumeEmptyLines.cpp index e9fe0e286..f0e32d43e 100644 --- a/src/ObjLoading/Parsing/LocalizeFile/Sequence/SequenceLocalizeFileConsumeEmptyLines.cpp +++ b/src/ObjLoading/Parsing/LocalizeFile/Sequence/SequenceLocalizeFileConsumeEmptyLines.cpp @@ -2,15 +2,10 @@ #include "Parsing/Simple/Matcher/SimpleMatcherFactory.h" -SequenceLocalizeFileConsumeEmptyLines::SequenceLocalizeFileConsumeEmptyLines() -{ - const SimpleMatcherFactory create(this); +SequenceLocalizeFileConsumeEmptyLines::SequenceLocalizeFileConsumeEmptyLines() { + const SimpleMatcherFactory create(this); - AddMatchers({ - create.Type(SimpleParserValueType::NEW_LINE) - }); + AddMatchers({create.Type(SimpleParserValueType::NEW_LINE)}); } -void SequenceLocalizeFileConsumeEmptyLines::ProcessMatch(LocalizeFileParserState* state, SequenceResult& result) const -{ -} +void SequenceLocalizeFileConsumeEmptyLines::ProcessMatch(LocalizeFileParserState *state, SequenceResult &result) const {} diff --git a/src/ObjLoading/Parsing/LocalizeFile/Sequence/SequenceLocalizeFileConsumeEmptyLines.h b/src/ObjLoading/Parsing/LocalizeFile/Sequence/SequenceLocalizeFileConsumeEmptyLines.h index 6f3b0e9e3..ffeaec8f6 100644 --- a/src/ObjLoading/Parsing/LocalizeFile/Sequence/SequenceLocalizeFileConsumeEmptyLines.h +++ b/src/ObjLoading/Parsing/LocalizeFile/Sequence/SequenceLocalizeFileConsumeEmptyLines.h @@ -2,11 +2,10 @@ #include "Parsing/LocalizeFile/LocalizeFileParser.h" -class SequenceLocalizeFileConsumeEmptyLines final : public LocalizeFileParser::sequence_t -{ +class SequenceLocalizeFileConsumeEmptyLines final : public LocalizeFileParser::sequence_t { protected: - void ProcessMatch(LocalizeFileParserState* state, SequenceResult& result) const override; + void ProcessMatch(LocalizeFileParserState *state, SequenceResult &result) const override; public: - SequenceLocalizeFileConsumeEmptyLines(); + SequenceLocalizeFileConsumeEmptyLines(); }; diff --git a/src/ObjLoading/Parsing/LocalizeFile/Sequence/SequenceLocalizeFileEndMarker.cpp b/src/ObjLoading/Parsing/LocalizeFile/Sequence/SequenceLocalizeFileEndMarker.cpp index 960ce3d1b..7091694be 100644 --- a/src/ObjLoading/Parsing/LocalizeFile/Sequence/SequenceLocalizeFileEndMarker.cpp +++ b/src/ObjLoading/Parsing/LocalizeFile/Sequence/SequenceLocalizeFileEndMarker.cpp @@ -2,16 +2,10 @@ #include "Parsing/Simple/Matcher/SimpleMatcherFactory.h" -SequenceLocalizeFileEndMarker::SequenceLocalizeFileEndMarker() -{ - const SimpleMatcherFactory create(this); +SequenceLocalizeFileEndMarker::SequenceLocalizeFileEndMarker() { + const SimpleMatcherFactory create(this); - AddMatchers({ - create.Keyword("ENDMARKER") - }); + AddMatchers({create.Keyword("ENDMARKER")}); } -void SequenceLocalizeFileEndMarker::ProcessMatch(LocalizeFileParserState* state, SequenceResult& result) const -{ - state->m_end = true; -} +void SequenceLocalizeFileEndMarker::ProcessMatch(LocalizeFileParserState *state, SequenceResult &result) const { state->m_end = true; } diff --git a/src/ObjLoading/Parsing/LocalizeFile/Sequence/SequenceLocalizeFileEndMarker.h b/src/ObjLoading/Parsing/LocalizeFile/Sequence/SequenceLocalizeFileEndMarker.h index 6c77f1ea6..ee92dc4ce 100644 --- a/src/ObjLoading/Parsing/LocalizeFile/Sequence/SequenceLocalizeFileEndMarker.h +++ b/src/ObjLoading/Parsing/LocalizeFile/Sequence/SequenceLocalizeFileEndMarker.h @@ -2,11 +2,10 @@ #include "Parsing/LocalizeFile/LocalizeFileParser.h" -class SequenceLocalizeFileEndMarker final : public LocalizeFileParser::sequence_t -{ +class SequenceLocalizeFileEndMarker final : public LocalizeFileParser::sequence_t { protected: - void ProcessMatch(LocalizeFileParserState* state, SequenceResult& result) const override; + void ProcessMatch(LocalizeFileParserState *state, SequenceResult &result) const override; public: - SequenceLocalizeFileEndMarker(); + SequenceLocalizeFileEndMarker(); }; diff --git a/src/ObjLoading/Parsing/LocalizeFile/Sequence/SequenceLocalizeFileLanguageValue.cpp b/src/ObjLoading/Parsing/LocalizeFile/Sequence/SequenceLocalizeFileLanguageValue.cpp index 3362aa6fc..eaf03c46a 100644 --- a/src/ObjLoading/Parsing/LocalizeFile/Sequence/SequenceLocalizeFileLanguageValue.cpp +++ b/src/ObjLoading/Parsing/LocalizeFile/Sequence/SequenceLocalizeFileLanguageValue.cpp @@ -4,32 +4,26 @@ #include "Parsing/Simple/Matcher/SimpleMatcherFactory.h" -SequenceLocalizeFileLanguageValue::SequenceLocalizeFileLanguageValue() -{ - const SimpleMatcherFactory create(this); +SequenceLocalizeFileLanguageValue::SequenceLocalizeFileLanguageValue() { + const SimpleMatcherFactory create(this); - AddMatchers({ - create.KeywordPrefix("LANG_").Capture(CAPTURE_LANGUAGE_NAME), - create.String().Capture(CAPTURE_ENTRY_VALUE), - create.Type(SimpleParserValueType::NEW_LINE) - }); + AddMatchers({create.KeywordPrefix("LANG_").Capture(CAPTURE_LANGUAGE_NAME), create.String().Capture(CAPTURE_ENTRY_VALUE), + create.Type(SimpleParserValueType::NEW_LINE)}); } -void SequenceLocalizeFileLanguageValue::ProcessMatch(LocalizeFileParserState* state, SequenceResult& result) const -{ - const auto& langToken = result.NextCapture(CAPTURE_LANGUAGE_NAME); - const auto& valueToken = result.NextCapture(CAPTURE_ENTRY_VALUE); +void SequenceLocalizeFileLanguageValue::ProcessMatch(LocalizeFileParserState *state, SequenceResult &result) const { + const auto &langToken = result.NextCapture(CAPTURE_LANGUAGE_NAME); + const auto &valueToken = result.NextCapture(CAPTURE_ENTRY_VALUE); - const auto langName = langToken.IdentifierValue().substr(std::char_traits::length("LANG_")); - const auto alreadyDefinedLanguage = state->m_current_reference_languages.find(langName); - if(alreadyDefinedLanguage != state->m_current_reference_languages.end()) - { - std::ostringstream str; - str << "Value for reference \"" << state->m_current_reference << "\" already defined for language \"" << langToken.IdentifierValue() << "\""; - throw ParsingException(langToken.GetPos(), str.str()); - } - state->m_current_reference_languages.emplace(langName); + const auto langName = langToken.IdentifierValue().substr(std::char_traits::length("LANG_")); + const auto alreadyDefinedLanguage = state->m_current_reference_languages.find(langName); + if (alreadyDefinedLanguage != state->m_current_reference_languages.end()) { + std::ostringstream str; + str << "Value for reference \"" << state->m_current_reference << "\" already defined for language \"" << langToken.IdentifierValue() << "\""; + throw ParsingException(langToken.GetPos(), str.str()); + } + state->m_current_reference_languages.emplace(langName); - if(langName == state->m_language_name_caps) - state->m_entries.emplace_back(state->m_current_reference, valueToken.StringValue()); + if (langName == state->m_language_name_caps) + state->m_entries.emplace_back(state->m_current_reference, valueToken.StringValue()); } diff --git a/src/ObjLoading/Parsing/LocalizeFile/Sequence/SequenceLocalizeFileLanguageValue.h b/src/ObjLoading/Parsing/LocalizeFile/Sequence/SequenceLocalizeFileLanguageValue.h index f6379745a..33ad85693 100644 --- a/src/ObjLoading/Parsing/LocalizeFile/Sequence/SequenceLocalizeFileLanguageValue.h +++ b/src/ObjLoading/Parsing/LocalizeFile/Sequence/SequenceLocalizeFileLanguageValue.h @@ -2,14 +2,13 @@ #include "Parsing/LocalizeFile/LocalizeFileParser.h" -class SequenceLocalizeFileLanguageValue final : public LocalizeFileParser::sequence_t -{ - static constexpr auto CAPTURE_LANGUAGE_NAME = 1; - static constexpr auto CAPTURE_ENTRY_VALUE = 2; +class SequenceLocalizeFileLanguageValue final : public LocalizeFileParser::sequence_t { + static constexpr auto CAPTURE_LANGUAGE_NAME = 1; + static constexpr auto CAPTURE_ENTRY_VALUE = 2; protected: - void ProcessMatch(LocalizeFileParserState* state, SequenceResult& result) const override; + void ProcessMatch(LocalizeFileParserState *state, SequenceResult &result) const override; public: - SequenceLocalizeFileLanguageValue(); + SequenceLocalizeFileLanguageValue(); }; diff --git a/src/ObjLoading/Parsing/LocalizeFile/Sequence/SequenceLocalizeFileNotes.cpp b/src/ObjLoading/Parsing/LocalizeFile/Sequence/SequenceLocalizeFileNotes.cpp index f00d45ec7..a9a93c23d 100644 --- a/src/ObjLoading/Parsing/LocalizeFile/Sequence/SequenceLocalizeFileNotes.cpp +++ b/src/ObjLoading/Parsing/LocalizeFile/Sequence/SequenceLocalizeFileNotes.cpp @@ -2,17 +2,10 @@ #include "Parsing/Simple/Matcher/SimpleMatcherFactory.h" -SequenceLocalizeFileNotes::SequenceLocalizeFileNotes() -{ - const SimpleMatcherFactory create(this); +SequenceLocalizeFileNotes::SequenceLocalizeFileNotes() { + const SimpleMatcherFactory create(this); - AddMatchers({ - create.Keyword("FILENOTES"), - create.String(), - create.Type(SimpleParserValueType::NEW_LINE) - }); + AddMatchers({create.Keyword("FILENOTES"), create.String(), create.Type(SimpleParserValueType::NEW_LINE)}); } -void SequenceLocalizeFileNotes::ProcessMatch(LocalizeFileParserState* state, SequenceResult& result) const -{ -} +void SequenceLocalizeFileNotes::ProcessMatch(LocalizeFileParserState *state, SequenceResult &result) const {} diff --git a/src/ObjLoading/Parsing/LocalizeFile/Sequence/SequenceLocalizeFileNotes.h b/src/ObjLoading/Parsing/LocalizeFile/Sequence/SequenceLocalizeFileNotes.h index e36d19c0f..811852283 100644 --- a/src/ObjLoading/Parsing/LocalizeFile/Sequence/SequenceLocalizeFileNotes.h +++ b/src/ObjLoading/Parsing/LocalizeFile/Sequence/SequenceLocalizeFileNotes.h @@ -2,11 +2,10 @@ #include "Parsing/LocalizeFile/LocalizeFileParser.h" -class SequenceLocalizeFileNotes final : public LocalizeFileParser::sequence_t -{ +class SequenceLocalizeFileNotes final : public LocalizeFileParser::sequence_t { protected: - void ProcessMatch(LocalizeFileParserState* state, SequenceResult& result) const override; + void ProcessMatch(LocalizeFileParserState *state, SequenceResult &result) const override; public: - SequenceLocalizeFileNotes(); + SequenceLocalizeFileNotes(); }; diff --git a/src/ObjLoading/Parsing/LocalizeFile/Sequence/SequenceLocalizeFileReference.cpp b/src/ObjLoading/Parsing/LocalizeFile/Sequence/SequenceLocalizeFileReference.cpp index 0b0dc73f8..df38e3fa8 100644 --- a/src/ObjLoading/Parsing/LocalizeFile/Sequence/SequenceLocalizeFileReference.cpp +++ b/src/ObjLoading/Parsing/LocalizeFile/Sequence/SequenceLocalizeFileReference.cpp @@ -2,23 +2,15 @@ #include "Parsing/Simple/Matcher/SimpleMatcherFactory.h" -SequenceLocalizeFileReference::SequenceLocalizeFileReference() -{ - const SimpleMatcherFactory create(this); +SequenceLocalizeFileReference::SequenceLocalizeFileReference() { + const SimpleMatcherFactory create(this); - AddMatchers({ - create.Keyword("REFERENCE"), - create.Or({ - create.Identifier(), - create.String() - }).Capture(CAPTURE_REFERENCE_NAME), - create.Type(SimpleParserValueType::NEW_LINE) - }); + AddMatchers({create.Keyword("REFERENCE"), create.Or({create.Identifier(), create.String()}).Capture(CAPTURE_REFERENCE_NAME), + create.Type(SimpleParserValueType::NEW_LINE)}); } -void SequenceLocalizeFileReference::ProcessMatch(LocalizeFileParserState* state, SequenceResult& result) const -{ - const auto& nameToken = result.NextCapture(CAPTURE_REFERENCE_NAME); - state->m_current_reference = nameToken.m_type == SimpleParserValueType::IDENTIFIER ? nameToken.IdentifierValue() : nameToken.StringValue(); - state->m_current_reference_languages.clear(); +void SequenceLocalizeFileReference::ProcessMatch(LocalizeFileParserState *state, SequenceResult &result) const { + const auto &nameToken = result.NextCapture(CAPTURE_REFERENCE_NAME); + state->m_current_reference = nameToken.m_type == SimpleParserValueType::IDENTIFIER ? nameToken.IdentifierValue() : nameToken.StringValue(); + state->m_current_reference_languages.clear(); } diff --git a/src/ObjLoading/Parsing/LocalizeFile/Sequence/SequenceLocalizeFileReference.h b/src/ObjLoading/Parsing/LocalizeFile/Sequence/SequenceLocalizeFileReference.h index c0d78402a..14bee7917 100644 --- a/src/ObjLoading/Parsing/LocalizeFile/Sequence/SequenceLocalizeFileReference.h +++ b/src/ObjLoading/Parsing/LocalizeFile/Sequence/SequenceLocalizeFileReference.h @@ -2,13 +2,12 @@ #include "Parsing/LocalizeFile/LocalizeFileParser.h" -class SequenceLocalizeFileReference final : public LocalizeFileParser::sequence_t -{ - static constexpr auto CAPTURE_REFERENCE_NAME = 1; +class SequenceLocalizeFileReference final : public LocalizeFileParser::sequence_t { + static constexpr auto CAPTURE_REFERENCE_NAME = 1; protected: - void ProcessMatch(LocalizeFileParserState* state, SequenceResult& result) const override; + void ProcessMatch(LocalizeFileParserState *state, SequenceResult &result) const override; public: - SequenceLocalizeFileReference(); + SequenceLocalizeFileReference(); }; diff --git a/src/ObjLoading/Parsing/LocalizeFile/Sequence/SequenceLocalizeFileVersion.cpp b/src/ObjLoading/Parsing/LocalizeFile/Sequence/SequenceLocalizeFileVersion.cpp index 0f195c615..58e4286b6 100644 --- a/src/ObjLoading/Parsing/LocalizeFile/Sequence/SequenceLocalizeFileVersion.cpp +++ b/src/ObjLoading/Parsing/LocalizeFile/Sequence/SequenceLocalizeFileVersion.cpp @@ -2,22 +2,15 @@ #include "Parsing/Simple/Matcher/SimpleMatcherFactory.h" -SequenceLocalizeFileVersion::SequenceLocalizeFileVersion() -{ - const SimpleMatcherFactory create(this); +SequenceLocalizeFileVersion::SequenceLocalizeFileVersion() { + const SimpleMatcherFactory create(this); - AddMatchers({ - create.Keyword("VERSION"), - create.String().Capture(CAPTURE_VERSION), - create.Type(SimpleParserValueType::NEW_LINE) - }); + AddMatchers({create.Keyword("VERSION"), create.String().Capture(CAPTURE_VERSION), create.Type(SimpleParserValueType::NEW_LINE)}); } -void SequenceLocalizeFileVersion::ProcessMatch(LocalizeFileParserState* state, SequenceResult& result) const -{ - const auto& versionCapture = result.NextCapture(CAPTURE_VERSION); - if(versionCapture.StringValue() != "1") - { - throw ParsingException(versionCapture.GetPos(), "Localize file needs to be version 1"); - } +void SequenceLocalizeFileVersion::ProcessMatch(LocalizeFileParserState *state, SequenceResult &result) const { + const auto &versionCapture = result.NextCapture(CAPTURE_VERSION); + if (versionCapture.StringValue() != "1") { + throw ParsingException(versionCapture.GetPos(), "Localize file needs to be version 1"); + } } diff --git a/src/ObjLoading/Parsing/LocalizeFile/Sequence/SequenceLocalizeFileVersion.h b/src/ObjLoading/Parsing/LocalizeFile/Sequence/SequenceLocalizeFileVersion.h index a74fdae82..8820df494 100644 --- a/src/ObjLoading/Parsing/LocalizeFile/Sequence/SequenceLocalizeFileVersion.h +++ b/src/ObjLoading/Parsing/LocalizeFile/Sequence/SequenceLocalizeFileVersion.h @@ -2,13 +2,12 @@ #include "Parsing/LocalizeFile/LocalizeFileParser.h" -class SequenceLocalizeFileVersion final : public LocalizeFileParser::sequence_t -{ - static constexpr auto CAPTURE_VERSION = 1; +class SequenceLocalizeFileVersion final : public LocalizeFileParser::sequence_t { + static constexpr auto CAPTURE_VERSION = 1; protected: - void ProcessMatch(LocalizeFileParserState* state, SequenceResult& result) const override; + void ProcessMatch(LocalizeFileParserState *state, SequenceResult &result) const override; public: - SequenceLocalizeFileVersion(); + SequenceLocalizeFileVersion(); }; diff --git a/src/ObjLoading/Parsing/Menu/Domain/CommonFunctionDef.h b/src/ObjLoading/Parsing/Menu/Domain/CommonFunctionDef.h index a9ec384d7..1857061f3 100644 --- a/src/ObjLoading/Parsing/Menu/Domain/CommonFunctionDef.h +++ b/src/ObjLoading/Parsing/Menu/Domain/CommonFunctionDef.h @@ -4,12 +4,10 @@ #include "Parsing/Simple/Expression/ISimpleExpression.h" -namespace menu -{ - class CommonFunctionDef - { - public: - std::string m_name; - std::unique_ptr m_value; - }; -} +namespace menu { +class CommonFunctionDef { +public: + std::string m_name; + std::unique_ptr m_value; +}; +} // namespace menu diff --git a/src/ObjLoading/Parsing/Menu/Domain/CommonItemDef.h b/src/ObjLoading/Parsing/Menu/Domain/CommonItemDef.h index 8960b4a22..02b119936 100644 --- a/src/ObjLoading/Parsing/Menu/Domain/CommonItemDef.h +++ b/src/ObjLoading/Parsing/Menu/Domain/CommonItemDef.h @@ -1,166 +1,150 @@ #pragma once -#include #include +#include #include "CommonMenuTypes.h" #include "EventHandler/CommonEventHandlerSet.h" #include "Parsing/Simple/Expression/ISimpleExpression.h" -namespace menu -{ - enum class CommonItemFeatureType - { - NONE, - LISTBOX, - EDIT_FIELD, - MULTI_VALUE, - ENUM_DVAR, - NEWS_TICKER - }; +namespace menu { +enum class CommonItemFeatureType { NONE, LISTBOX, EDIT_FIELD, MULTI_VALUE, ENUM_DVAR, NEWS_TICKER }; - class CommonItemFeaturesListBox - { - public: - class Column - { - public: - int m_x_pos = 0; - int m_y_pos = 0; - int m_width = 0; - int m_height = 0; - int m_max_chars = 0; - int m_alignment = 0; - }; +class CommonItemFeaturesListBox { +public: + class Column { + public: + int m_x_pos = 0; + int m_y_pos = 0; + int m_width = 0; + int m_height = 0; + int m_max_chars = 0; + int m_alignment = 0; + }; - bool m_not_selectable = false; - bool m_no_scrollbars = false; - bool m_use_paging = false; - double m_element_width = 0; - double m_element_height = 0; - double m_feeder = 0; - int m_element_style = 0; - CommonColor m_select_border; - std::string m_select_icon; + bool m_not_selectable = false; + bool m_no_scrollbars = false; + bool m_use_paging = false; + double m_element_width = 0; + double m_element_height = 0; + double m_feeder = 0; + int m_element_style = 0; + CommonColor m_select_border; + std::string m_select_icon; - std::unique_ptr m_on_double_click; - std::unique_ptr m_element_height_expression; - std::vector m_columns; - }; + std::unique_ptr m_on_double_click; + std::unique_ptr m_element_height_expression; + std::vector m_columns; +}; - class CommonItemFeaturesEditField - { - public: - std::string m_dvar; - std::string m_local_var; - double m_def_val = -1.0; - double m_min_val = -1.0; - double m_max_val = -1.0; - int m_max_chars = 0; - int m_max_paint_chars = 0; - bool m_max_chars_goto_next = false; - }; +class CommonItemFeaturesEditField { +public: + std::string m_dvar; + std::string m_local_var; + double m_def_val = -1.0; + double m_min_val = -1.0; + double m_max_val = -1.0; + int m_max_chars = 0; + int m_max_paint_chars = 0; + bool m_max_chars_goto_next = false; +}; - class CommonItemFeaturesMultiValue - { - public: - std::vector m_step_names; - std::vector m_string_values; - std::vector m_double_values; - }; +class CommonItemFeaturesMultiValue { +public: + std::vector m_step_names; + std::vector m_string_values; + std::vector m_double_values; +}; - class CommonItemFeaturesNewsTicker - { - public: - int m_spacing = 0; - int m_speed = 0; - int m_news_feed_id = 0; - }; +class CommonItemFeaturesNewsTicker { +public: + int m_spacing = 0; + int m_speed = 0; + int m_news_feed_id = 0; +}; - class CommonItemDef - { - public: - class ColorExpressions - { - public: - std::unique_ptr m_r_exp; - std::unique_ptr m_g_exp; - std::unique_ptr m_b_exp; - std::unique_ptr m_a_exp; - std::unique_ptr m_rgb_exp; - }; +class CommonItemDef { +public: + class ColorExpressions { + public: + std::unique_ptr m_r_exp; + std::unique_ptr m_g_exp; + std::unique_ptr m_b_exp; + std::unique_ptr m_a_exp; + std::unique_ptr m_rgb_exp; + }; - std::string m_name; - std::string m_text; - bool m_text_save_game = false; - bool m_text_cinematic_subtitle = false; - std::string m_group; - CommonRect m_rect; - int m_style = 0; - bool m_decoration = false; - bool m_auto_wrapped = false; - bool m_horizontal_scroll = false; - int m_type = 0; - CommonItemFeatureType m_feature_type = CommonItemFeatureType::NONE; - int m_border = 0; - double m_border_size = 0; - int m_owner_draw = 0; - int m_owner_draw_flags = 0; - int m_align = 0; - int m_text_align = 0; - double m_text_align_x = 0; - double m_text_align_y = 0; - double m_text_scale = 0; - int m_text_style = 0; - int m_text_font = 0; - CommonColor m_back_color; - CommonColor m_fore_color = CommonColor(1.0, 1.0, 1.0, 1.0); - CommonColor m_border_color; - CommonColor m_outline_color; - CommonColor m_disable_color; - CommonColor m_glow_color; - std::string m_background; - std::string m_focus_sound; - std::string m_dvar; - std::string m_dvar_test; - std::vector m_enable_dvar; - std::vector m_disable_dvar; - std::vector m_show_dvar; - std::vector m_hide_dvar; - std::vector m_focus_dvar; - int m_game_message_window_index = 0; - int m_game_message_window_mode = 0; - int m_fx_letter_time = 0; - int m_fx_decay_start_time = 0; - int m_fx_decay_duration = 0; + std::string m_name; + std::string m_text; + bool m_text_save_game = false; + bool m_text_cinematic_subtitle = false; + std::string m_group; + CommonRect m_rect; + int m_style = 0; + bool m_decoration = false; + bool m_auto_wrapped = false; + bool m_horizontal_scroll = false; + int m_type = 0; + CommonItemFeatureType m_feature_type = CommonItemFeatureType::NONE; + int m_border = 0; + double m_border_size = 0; + int m_owner_draw = 0; + int m_owner_draw_flags = 0; + int m_align = 0; + int m_text_align = 0; + double m_text_align_x = 0; + double m_text_align_y = 0; + double m_text_scale = 0; + int m_text_style = 0; + int m_text_font = 0; + CommonColor m_back_color; + CommonColor m_fore_color = CommonColor(1.0, 1.0, 1.0, 1.0); + CommonColor m_border_color; + CommonColor m_outline_color; + CommonColor m_disable_color; + CommonColor m_glow_color; + std::string m_background; + std::string m_focus_sound; + std::string m_dvar; + std::string m_dvar_test; + std::vector m_enable_dvar; + std::vector m_disable_dvar; + std::vector m_show_dvar; + std::vector m_hide_dvar; + std::vector m_focus_dvar; + int m_game_message_window_index = 0; + int m_game_message_window_mode = 0; + int m_fx_letter_time = 0; + int m_fx_decay_start_time = 0; + int m_fx_decay_duration = 0; - std::unique_ptr m_visible_expression; - std::unique_ptr m_disabled_expression; - std::unique_ptr m_text_expression; - std::unique_ptr m_text_align_y_expression; - std::unique_ptr m_material_expression; - std::unique_ptr m_rect_x_exp; - std::unique_ptr m_rect_y_exp; - std::unique_ptr m_rect_w_exp; - std::unique_ptr m_rect_h_exp; - ColorExpressions m_forecolor_expressions; - ColorExpressions m_glowcolor_expressions; - ColorExpressions m_backcolor_expressions; - std::unique_ptr m_on_focus; - std::unique_ptr m_has_focus; - std::unique_ptr m_on_leave_focus; - std::unique_ptr m_on_mouse_enter; - std::unique_ptr m_on_mouse_exit; - std::unique_ptr m_on_mouse_enter_text; - std::unique_ptr m_on_mouse_exit_text; - std::unique_ptr m_on_action; - std::unique_ptr m_on_accept; - std::multimap> m_key_handlers; + std::unique_ptr m_visible_expression; + std::unique_ptr m_disabled_expression; + std::unique_ptr m_text_expression; + std::unique_ptr m_text_align_y_expression; + std::unique_ptr m_material_expression; + std::unique_ptr m_rect_x_exp; + std::unique_ptr m_rect_y_exp; + std::unique_ptr m_rect_w_exp; + std::unique_ptr m_rect_h_exp; + ColorExpressions m_forecolor_expressions; + ColorExpressions m_glowcolor_expressions; + ColorExpressions m_backcolor_expressions; + std::unique_ptr m_on_focus; + std::unique_ptr m_has_focus; + std::unique_ptr m_on_leave_focus; + std::unique_ptr m_on_mouse_enter; + std::unique_ptr m_on_mouse_exit; + std::unique_ptr m_on_mouse_enter_text; + std::unique_ptr m_on_mouse_exit_text; + std::unique_ptr m_on_action; + std::unique_ptr m_on_accept; + std::multimap> m_key_handlers; - std::unique_ptr m_list_box_features; - std::unique_ptr m_edit_field_features; - std::unique_ptr m_multi_value_features; - std::string m_enum_dvar_name; - std::unique_ptr m_news_ticker_features; - }; -} + std::unique_ptr m_list_box_features; + std::unique_ptr m_edit_field_features; + std::unique_ptr m_multi_value_features; + std::string m_enum_dvar_name; + std::unique_ptr m_news_ticker_features; +}; +} // namespace menu diff --git a/src/ObjLoading/Parsing/Menu/Domain/CommonMenuDef.h b/src/ObjLoading/Parsing/Menu/Domain/CommonMenuDef.h index 43a8872bf..623633399 100644 --- a/src/ObjLoading/Parsing/Menu/Domain/CommonMenuDef.h +++ b/src/ObjLoading/Parsing/Menu/Domain/CommonMenuDef.h @@ -1,66 +1,64 @@ #pragma once -#include -#include #include #include +#include +#include #include "CommonItemDef.h" #include "CommonMenuTypes.h" #include "EventHandler/CommonEventHandlerSet.h" #include "Parsing/Simple/Expression/ISimpleExpression.h" -namespace menu -{ - class CommonMenuDef - { - public: - std::string m_name; - CommonRect m_rect; - int m_style = 0; - int m_border = 0; - double m_border_size = 0; - CommonColor m_back_color; - CommonColor m_fore_color = CommonColor(1.0, 1.0, 1.0, 1.0); - CommonColor m_border_color; - CommonColor m_focus_color; - CommonColor m_outline_color; - std::string m_background; - int m_owner_draw = 0; - int m_owner_draw_flags = 0; - std::string m_sound_loop; - std::unique_ptr m_sound_loop_exp; - double m_fade_clamp = 0; - int m_fade_cycle = 0; - double m_fade_amount = 0; - double m_fade_in_amount = 0; - double m_blur_radius = 0; - std::string m_allowed_binding; - std::unique_ptr m_visible_expression; - std::unique_ptr m_rect_x_exp; - std::unique_ptr m_rect_y_exp; - std::unique_ptr m_rect_w_exp; - std::unique_ptr m_rect_h_exp; - std::unique_ptr m_open_sound_exp; - std::unique_ptr m_close_sound_exp; - std::unique_ptr m_on_open; - std::unique_ptr m_on_close; - std::unique_ptr m_on_request_close; - std::unique_ptr m_on_esc; - std::unique_ptr m_on_focus_due_to_close; - std::multimap> m_key_handlers; +namespace menu { +class CommonMenuDef { +public: + std::string m_name; + CommonRect m_rect; + int m_style = 0; + int m_border = 0; + double m_border_size = 0; + CommonColor m_back_color; + CommonColor m_fore_color = CommonColor(1.0, 1.0, 1.0, 1.0); + CommonColor m_border_color; + CommonColor m_focus_color; + CommonColor m_outline_color; + std::string m_background; + int m_owner_draw = 0; + int m_owner_draw_flags = 0; + std::string m_sound_loop; + std::unique_ptr m_sound_loop_exp; + double m_fade_clamp = 0; + int m_fade_cycle = 0; + double m_fade_amount = 0; + double m_fade_in_amount = 0; + double m_blur_radius = 0; + std::string m_allowed_binding; + std::unique_ptr m_visible_expression; + std::unique_ptr m_rect_x_exp; + std::unique_ptr m_rect_y_exp; + std::unique_ptr m_rect_w_exp; + std::unique_ptr m_rect_h_exp; + std::unique_ptr m_open_sound_exp; + std::unique_ptr m_close_sound_exp; + std::unique_ptr m_on_open; + std::unique_ptr m_on_close; + std::unique_ptr m_on_request_close; + std::unique_ptr m_on_esc; + std::unique_ptr m_on_focus_due_to_close; + std::multimap> m_key_handlers; - bool m_full_screen = false; - bool m_screen_space = false; - bool m_decoration = false; - bool m_out_of_bounds_click = false; - bool m_popup = false; - bool m_legacy_split_screen_scale = false; - bool m_hidden_during_scope = false; - bool m_hidden_during_flashbang = false; - bool m_hidden_during_ui = false; - bool m_text_only_focus = false; + bool m_full_screen = false; + bool m_screen_space = false; + bool m_decoration = false; + bool m_out_of_bounds_click = false; + bool m_popup = false; + bool m_legacy_split_screen_scale = false; + bool m_hidden_during_scope = false; + bool m_hidden_during_flashbang = false; + bool m_hidden_during_ui = false; + bool m_text_only_focus = false; - std::vector> m_items; - }; -} + std::vector> m_items; +}; +} // namespace menu diff --git a/src/ObjLoading/Parsing/Menu/Domain/CommonMenuTypes.cpp b/src/ObjLoading/Parsing/Menu/Domain/CommonMenuTypes.cpp index 4e061a9a3..fce083cb1 100644 --- a/src/ObjLoading/Parsing/Menu/Domain/CommonMenuTypes.cpp +++ b/src/ObjLoading/Parsing/Menu/Domain/CommonMenuTypes.cpp @@ -1,52 +1,32 @@ #include "CommonMenuTypes.h" -#include #include +#include using namespace menu; -CommonColor::CommonColor() - : array{} -{ - r = 0.0; - g = 0.0; - b = 0.0; - a = 0.0; +CommonColor::CommonColor() : array{} { + r = 0.0; + g = 0.0; + b = 0.0; + a = 0.0; } -CommonColor::CommonColor(const double r, const double g, const double b, const double a) - : array{} -{ - this->r = r; - this->g = g; - this->b = b; - this->a = a; +CommonColor::CommonColor(const double r, const double g, const double b, const double a) : array{} { + this->r = r; + this->g = g; + this->b = b; + this->a = a; } -bool CommonColor::Equals(const CommonColor& other) const -{ - return std::fabs(this->r - other.r) < std::numeric_limits::epsilon() - && std::fabs(this->g - other.g) < std::numeric_limits::epsilon() - && std::fabs(this->b - other.b) < std::numeric_limits::epsilon() - && std::fabs(this->a - other.a) < std::numeric_limits::epsilon(); +bool CommonColor::Equals(const CommonColor &other) const { + return std::fabs(this->r - other.r) < std::numeric_limits::epsilon() && std::fabs(this->g - other.g) < std::numeric_limits::epsilon() && + std::fabs(this->b - other.b) < std::numeric_limits::epsilon() && std::fabs(this->a - other.a) < std::numeric_limits::epsilon(); } -CommonRect::CommonRect() - : CommonRect(0, 0, 0, 0) -{ -} +CommonRect::CommonRect() : CommonRect(0, 0, 0, 0) {} -CommonRect::CommonRect(const double x, const double y, const double w, const double h) - : CommonRect(x, y, w, h, 0, 0) -{ -} +CommonRect::CommonRect(const double x, const double y, const double w, const double h) : CommonRect(x, y, w, h, 0, 0) {} CommonRect::CommonRect(const double x, const double y, const double w, const double h, const int horizontalAlign, const int verticalAlign) - : x(x), - y(y), - w(w), - h(h), - horizontalAlign(horizontalAlign), - verticalAlign(verticalAlign) -{ -} + : x(x), y(y), w(w), h(h), horizontalAlign(horizontalAlign), verticalAlign(verticalAlign) {} diff --git a/src/ObjLoading/Parsing/Menu/Domain/CommonMenuTypes.h b/src/ObjLoading/Parsing/Menu/Domain/CommonMenuTypes.h index 0331be3d6..fd87f5f64 100644 --- a/src/ObjLoading/Parsing/Menu/Domain/CommonMenuTypes.h +++ b/src/ObjLoading/Parsing/Menu/Domain/CommonMenuTypes.h @@ -1,35 +1,31 @@ #pragma once -namespace menu -{ - union CommonColor - { - struct - { - double r; - double g; - double b; - double a; - }; - double array[4]; +namespace menu { +union CommonColor { + struct { + double r; + double g; + double b; + double a; + }; + double array[4]; - CommonColor(); - CommonColor(double r, double g, double b, double a); + CommonColor(); + CommonColor(double r, double g, double b, double a); - bool Equals(const CommonColor& other) const; - }; + bool Equals(const CommonColor &other) const; +}; - struct CommonRect - { - double x; - double y; - double w; - double h; - int horizontalAlign; - int verticalAlign; +struct CommonRect { + double x; + double y; + double w; + double h; + int horizontalAlign; + int verticalAlign; - CommonRect(); - CommonRect(double x, double y, double w, double h); - CommonRect(double x, double y, double w, double h, int horizontalAlign, int verticalAlign); - }; -} + CommonRect(); + CommonRect(double x, double y, double w, double h); + CommonRect(double x, double y, double w, double h, int horizontalAlign, int verticalAlign); +}; +} // namespace menu diff --git a/src/ObjLoading/Parsing/Menu/Domain/EventHandler/CommonEventHandlerCondition.cpp b/src/ObjLoading/Parsing/Menu/Domain/EventHandler/CommonEventHandlerCondition.cpp index 2de327614..92c2ddf61 100644 --- a/src/ObjLoading/Parsing/Menu/Domain/EventHandler/CommonEventHandlerCondition.cpp +++ b/src/ObjLoading/Parsing/Menu/Domain/EventHandler/CommonEventHandlerCondition.cpp @@ -2,18 +2,10 @@ using namespace menu; -CommonEventHandlerCondition::CommonEventHandlerCondition() -= default; +CommonEventHandlerCondition::CommonEventHandlerCondition() = default; CommonEventHandlerCondition::CommonEventHandlerCondition(std::unique_ptr condition, std::unique_ptr conditionElements, std::unique_ptr elseElements) - : m_condition(std::move(condition)), - m_condition_elements(std::move(conditionElements)), - m_else_elements(std::move(elseElements)) -{ -} + : m_condition(std::move(condition)), m_condition_elements(std::move(conditionElements)), m_else_elements(std::move(elseElements)) {} -CommonEventHandlerElementType CommonEventHandlerCondition::GetType() const -{ - return CommonEventHandlerElementType::CONDITION; -} +CommonEventHandlerElementType CommonEventHandlerCondition::GetType() const { return CommonEventHandlerElementType::CONDITION; } diff --git a/src/ObjLoading/Parsing/Menu/Domain/EventHandler/CommonEventHandlerCondition.h b/src/ObjLoading/Parsing/Menu/Domain/EventHandler/CommonEventHandlerCondition.h index 8d581411b..d030dfbed 100644 --- a/src/ObjLoading/Parsing/Menu/Domain/EventHandler/CommonEventHandlerCondition.h +++ b/src/ObjLoading/Parsing/Menu/Domain/EventHandler/CommonEventHandlerCondition.h @@ -6,19 +6,17 @@ #include "ICommonEventHandlerElement.h" #include "Parsing/Simple/Expression/ISimpleExpression.h" -namespace menu -{ - class CommonEventHandlerCondition final : public ICommonEventHandlerElement - { - public: - std::unique_ptr m_condition; - std::unique_ptr m_condition_elements; - std::unique_ptr m_else_elements; +namespace menu { +class CommonEventHandlerCondition final : public ICommonEventHandlerElement { +public: + std::unique_ptr m_condition; + std::unique_ptr m_condition_elements; + std::unique_ptr m_else_elements; - CommonEventHandlerCondition(); - CommonEventHandlerCondition(std::unique_ptr condition, std::unique_ptr conditionElements, - std::unique_ptr elseElements); + CommonEventHandlerCondition(); + CommonEventHandlerCondition(std::unique_ptr condition, std::unique_ptr conditionElements, + std::unique_ptr elseElements); - _NODISCARD CommonEventHandlerElementType GetType() const override; - }; -} + _NODISCARD CommonEventHandlerElementType GetType() const override; +}; +} // namespace menu diff --git a/src/ObjLoading/Parsing/Menu/Domain/EventHandler/CommonEventHandlerScript.cpp b/src/ObjLoading/Parsing/Menu/Domain/EventHandler/CommonEventHandlerScript.cpp index 7ce35e88e..bc6ca583f 100644 --- a/src/ObjLoading/Parsing/Menu/Domain/EventHandler/CommonEventHandlerScript.cpp +++ b/src/ObjLoading/Parsing/Menu/Domain/EventHandler/CommonEventHandlerScript.cpp @@ -2,15 +2,8 @@ using namespace menu; -CommonEventHandlerScript::CommonEventHandlerScript() -= default; +CommonEventHandlerScript::CommonEventHandlerScript() = default; -CommonEventHandlerScript::CommonEventHandlerScript(std::string script) - : m_script(std::move(script)) -{ -} +CommonEventHandlerScript::CommonEventHandlerScript(std::string script) : m_script(std::move(script)) {} -CommonEventHandlerElementType CommonEventHandlerScript::GetType() const -{ - return CommonEventHandlerElementType::SCRIPT; -} +CommonEventHandlerElementType CommonEventHandlerScript::GetType() const { return CommonEventHandlerElementType::SCRIPT; } diff --git a/src/ObjLoading/Parsing/Menu/Domain/EventHandler/CommonEventHandlerScript.h b/src/ObjLoading/Parsing/Menu/Domain/EventHandler/CommonEventHandlerScript.h index c6ec72d04..8cc175ead 100644 --- a/src/ObjLoading/Parsing/Menu/Domain/EventHandler/CommonEventHandlerScript.h +++ b/src/ObjLoading/Parsing/Menu/Domain/EventHandler/CommonEventHandlerScript.h @@ -4,16 +4,14 @@ #include "ICommonEventHandlerElement.h" -namespace menu -{ - class CommonEventHandlerScript final : public ICommonEventHandlerElement - { - public: - std::string m_script; +namespace menu { +class CommonEventHandlerScript final : public ICommonEventHandlerElement { +public: + std::string m_script; - CommonEventHandlerScript(); - explicit CommonEventHandlerScript(std::string script); + CommonEventHandlerScript(); + explicit CommonEventHandlerScript(std::string script); - _NODISCARD CommonEventHandlerElementType GetType() const override; - }; -} + _NODISCARD CommonEventHandlerElementType GetType() const override; +}; +} // namespace menu diff --git a/src/ObjLoading/Parsing/Menu/Domain/EventHandler/CommonEventHandlerSet.cpp b/src/ObjLoading/Parsing/Menu/Domain/EventHandler/CommonEventHandlerSet.cpp index bb7fd3dad..afda668fb 100644 --- a/src/ObjLoading/Parsing/Menu/Domain/EventHandler/CommonEventHandlerSet.cpp +++ b/src/ObjLoading/Parsing/Menu/Domain/EventHandler/CommonEventHandlerSet.cpp @@ -2,10 +2,6 @@ using namespace menu; -CommonEventHandlerSet::CommonEventHandlerSet() -= default; +CommonEventHandlerSet::CommonEventHandlerSet() = default; -CommonEventHandlerSet::CommonEventHandlerSet(std::vector> elements) - : m_elements(std::move(elements)) -{ -} +CommonEventHandlerSet::CommonEventHandlerSet(std::vector> elements) : m_elements(std::move(elements)) {} diff --git a/src/ObjLoading/Parsing/Menu/Domain/EventHandler/CommonEventHandlerSet.h b/src/ObjLoading/Parsing/Menu/Domain/EventHandler/CommonEventHandlerSet.h index ac4da860f..bc351ceb6 100644 --- a/src/ObjLoading/Parsing/Menu/Domain/EventHandler/CommonEventHandlerSet.h +++ b/src/ObjLoading/Parsing/Menu/Domain/EventHandler/CommonEventHandlerSet.h @@ -5,14 +5,12 @@ #include "ICommonEventHandlerElement.h" -namespace menu -{ - class CommonEventHandlerSet - { - public: - std::vector> m_elements; +namespace menu { +class CommonEventHandlerSet { +public: + std::vector> m_elements; - CommonEventHandlerSet(); - explicit CommonEventHandlerSet(std::vector> elements); - }; -} + CommonEventHandlerSet(); + explicit CommonEventHandlerSet(std::vector> elements); +}; +} // namespace menu diff --git a/src/ObjLoading/Parsing/Menu/Domain/EventHandler/CommonEventHandlerSetLocalVar.cpp b/src/ObjLoading/Parsing/Menu/Domain/EventHandler/CommonEventHandlerSetLocalVar.cpp index 7ebee3fdb..313b6e484 100644 --- a/src/ObjLoading/Parsing/Menu/Domain/EventHandler/CommonEventHandlerSetLocalVar.cpp +++ b/src/ObjLoading/Parsing/Menu/Domain/EventHandler/CommonEventHandlerSetLocalVar.cpp @@ -2,19 +2,9 @@ using namespace menu; -CommonEventHandlerSetLocalVar::CommonEventHandlerSetLocalVar() - : m_type(SetLocalVarType::UNKNOWN) -{ -} +CommonEventHandlerSetLocalVar::CommonEventHandlerSetLocalVar() : m_type(SetLocalVarType::UNKNOWN) {} CommonEventHandlerSetLocalVar::CommonEventHandlerSetLocalVar(SetLocalVarType type, std::string varName, std::unique_ptr value) - : m_type(type), - m_var_name(std::move(varName)), - m_value(std::move(value)) -{ -} + : m_type(type), m_var_name(std::move(varName)), m_value(std::move(value)) {} -CommonEventHandlerElementType CommonEventHandlerSetLocalVar::GetType() const -{ - return CommonEventHandlerElementType::SET_LOCAL_VAR; -} +CommonEventHandlerElementType CommonEventHandlerSetLocalVar::GetType() const { return CommonEventHandlerElementType::SET_LOCAL_VAR; } diff --git a/src/ObjLoading/Parsing/Menu/Domain/EventHandler/CommonEventHandlerSetLocalVar.h b/src/ObjLoading/Parsing/Menu/Domain/EventHandler/CommonEventHandlerSetLocalVar.h index 69324a517..433f04abd 100644 --- a/src/ObjLoading/Parsing/Menu/Domain/EventHandler/CommonEventHandlerSetLocalVar.h +++ b/src/ObjLoading/Parsing/Menu/Domain/EventHandler/CommonEventHandlerSetLocalVar.h @@ -5,27 +5,18 @@ #include "ICommonEventHandlerElement.h" #include "Parsing/Simple/Expression/ISimpleExpression.h" -namespace menu -{ - enum class SetLocalVarType - { - UNKNOWN, - BOOL, - INT, - FLOAT, - STRING - }; +namespace menu { +enum class SetLocalVarType { UNKNOWN, BOOL, INT, FLOAT, STRING }; - class CommonEventHandlerSetLocalVar final : public ICommonEventHandlerElement - { - public: - SetLocalVarType m_type; - std::string m_var_name; - std::unique_ptr m_value; +class CommonEventHandlerSetLocalVar final : public ICommonEventHandlerElement { +public: + SetLocalVarType m_type; + std::string m_var_name; + std::unique_ptr m_value; - CommonEventHandlerSetLocalVar(); - CommonEventHandlerSetLocalVar(SetLocalVarType type, std::string varName, std::unique_ptr value); + CommonEventHandlerSetLocalVar(); + CommonEventHandlerSetLocalVar(SetLocalVarType type, std::string varName, std::unique_ptr value); - _NODISCARD CommonEventHandlerElementType GetType() const override; - }; -} + _NODISCARD CommonEventHandlerElementType GetType() const override; +}; +} // namespace menu diff --git a/src/ObjLoading/Parsing/Menu/Domain/EventHandler/ICommonEventHandlerElement.h b/src/ObjLoading/Parsing/Menu/Domain/EventHandler/ICommonEventHandlerElement.h index 18e9bb342..14ef83971 100644 --- a/src/ObjLoading/Parsing/Menu/Domain/EventHandler/ICommonEventHandlerElement.h +++ b/src/ObjLoading/Parsing/Menu/Domain/EventHandler/ICommonEventHandlerElement.h @@ -2,27 +2,20 @@ #include "Utils/ClassUtils.h" -namespace menu -{ - enum class CommonEventHandlerElementType - { - SCRIPT, - CONDITION, - SET_LOCAL_VAR - }; +namespace menu { +enum class CommonEventHandlerElementType { SCRIPT, CONDITION, SET_LOCAL_VAR }; - class ICommonEventHandlerElement - { - protected: - ICommonEventHandlerElement() = default; +class ICommonEventHandlerElement { +protected: + ICommonEventHandlerElement() = default; - public: - virtual ~ICommonEventHandlerElement() = default; - ICommonEventHandlerElement(const ICommonEventHandlerElement& other) = default; - ICommonEventHandlerElement(ICommonEventHandlerElement&& other) noexcept = default; - ICommonEventHandlerElement& operator=(const ICommonEventHandlerElement& other) = default; - ICommonEventHandlerElement& operator=(ICommonEventHandlerElement&& other) noexcept = default; +public: + virtual ~ICommonEventHandlerElement() = default; + ICommonEventHandlerElement(const ICommonEventHandlerElement &other) = default; + ICommonEventHandlerElement(ICommonEventHandlerElement &&other) noexcept = default; + ICommonEventHandlerElement &operator=(const ICommonEventHandlerElement &other) = default; + ICommonEventHandlerElement &operator=(ICommonEventHandlerElement &&other) noexcept = default; - _NODISCARD virtual CommonEventHandlerElementType GetType() const = 0; - }; -} \ No newline at end of file + _NODISCARD virtual CommonEventHandlerElementType GetType() const = 0; +}; +} // namespace menu \ No newline at end of file diff --git a/src/ObjLoading/Parsing/Menu/Domain/Expression/CommonExpressionBaseFunctionCall.cpp b/src/ObjLoading/Parsing/Menu/Domain/Expression/CommonExpressionBaseFunctionCall.cpp index 79a269d77..f66b57274 100644 --- a/src/ObjLoading/Parsing/Menu/Domain/Expression/CommonExpressionBaseFunctionCall.cpp +++ b/src/ObjLoading/Parsing/Menu/Domain/Expression/CommonExpressionBaseFunctionCall.cpp @@ -3,46 +3,31 @@ using namespace menu; CommonExpressionBaseFunctionCall::CommonExpressionBaseFunctionCall(std::string functionName, size_t functionIndex) - : m_function_name(std::move(functionName)), - m_function_index(functionIndex) -{ -} + : m_function_name(std::move(functionName)), m_function_index(functionIndex) {} -bool CommonExpressionBaseFunctionCall::Equals(const ISimpleExpression* other) const -{ - const auto otherFunctionCall = dynamic_cast(other); +bool CommonExpressionBaseFunctionCall::Equals(const ISimpleExpression *other) const { + const auto otherFunctionCall = dynamic_cast(other); - if (!otherFunctionCall - || m_function_name != otherFunctionCall->m_function_name - || m_function_index != otherFunctionCall->m_function_index - || m_args.size() != otherFunctionCall->m_args.size()) - { - return false; - } + if (!otherFunctionCall || m_function_name != otherFunctionCall->m_function_name || m_function_index != otherFunctionCall->m_function_index || + m_args.size() != otherFunctionCall->m_args.size()) { + return false; + } - for (auto i = 0u; i < m_args.size(); i++) - { - const auto* arg = m_args[i].get(); - const auto* otherArg = otherFunctionCall->m_args[i].get(); + for (auto i = 0u; i < m_args.size(); i++) { + const auto *arg = m_args[i].get(); + const auto *otherArg = otherFunctionCall->m_args[i].get(); - if (!arg->Equals(otherArg)) - return false; - } + if (!arg->Equals(otherArg)) + return false; + } - return true; + return true; } -bool CommonExpressionBaseFunctionCall::IsStatic() const -{ - return false; -} +bool CommonExpressionBaseFunctionCall::IsStatic() const { return false; } -SimpleExpressionValue CommonExpressionBaseFunctionCall::EvaluateStatic() const -{ - return SimpleExpressionValue(0); -} +SimpleExpressionValue CommonExpressionBaseFunctionCall::EvaluateStatic() const { return SimpleExpressionValue(0); } -SimpleExpressionValue CommonExpressionBaseFunctionCall::EvaluateNonStatic(const ISimpleExpressionScopeValues* scopeValues) const -{ - return SimpleExpressionValue(0); +SimpleExpressionValue CommonExpressionBaseFunctionCall::EvaluateNonStatic(const ISimpleExpressionScopeValues *scopeValues) const { + return SimpleExpressionValue(0); } diff --git a/src/ObjLoading/Parsing/Menu/Domain/Expression/CommonExpressionBaseFunctionCall.h b/src/ObjLoading/Parsing/Menu/Domain/Expression/CommonExpressionBaseFunctionCall.h index f558e02ee..ba601bf0c 100644 --- a/src/ObjLoading/Parsing/Menu/Domain/Expression/CommonExpressionBaseFunctionCall.h +++ b/src/ObjLoading/Parsing/Menu/Domain/Expression/CommonExpressionBaseFunctionCall.h @@ -3,20 +3,18 @@ #include "Parsing/Simple/Expression/ISimpleExpression.h" -namespace menu -{ - class CommonExpressionBaseFunctionCall final : public ISimpleExpression - { - public: - std::string m_function_name; - size_t m_function_index; - std::vector> m_args; +namespace menu { +class CommonExpressionBaseFunctionCall final : public ISimpleExpression { +public: + std::string m_function_name; + size_t m_function_index; + std::vector> m_args; - CommonExpressionBaseFunctionCall(std::string functionName, size_t functionIndex); + CommonExpressionBaseFunctionCall(std::string functionName, size_t functionIndex); - _NODISCARD bool Equals(const ISimpleExpression* other) const override; - _NODISCARD bool IsStatic() const override; - _NODISCARD SimpleExpressionValue EvaluateStatic() const override; - _NODISCARD SimpleExpressionValue EvaluateNonStatic(const ISimpleExpressionScopeValues* scopeValues) const override; - }; -} + _NODISCARD bool Equals(const ISimpleExpression *other) const override; + _NODISCARD bool IsStatic() const override; + _NODISCARD SimpleExpressionValue EvaluateStatic() const override; + _NODISCARD SimpleExpressionValue EvaluateNonStatic(const ISimpleExpressionScopeValues *scopeValues) const override; +}; +} // namespace menu diff --git a/src/ObjLoading/Parsing/Menu/Domain/Expression/CommonExpressionCustomFunctionCall.cpp b/src/ObjLoading/Parsing/Menu/Domain/Expression/CommonExpressionCustomFunctionCall.cpp index ae53ee2b0..10c1c5473 100644 --- a/src/ObjLoading/Parsing/Menu/Domain/Expression/CommonExpressionCustomFunctionCall.cpp +++ b/src/ObjLoading/Parsing/Menu/Domain/Expression/CommonExpressionCustomFunctionCall.cpp @@ -2,28 +2,17 @@ using namespace menu; -CommonExpressionCustomFunctionCall::CommonExpressionCustomFunctionCall(std::string functionName) - : m_function_name(std::move(functionName)) -{ -} +CommonExpressionCustomFunctionCall::CommonExpressionCustomFunctionCall(std::string functionName) : m_function_name(std::move(functionName)) {} -bool CommonExpressionCustomFunctionCall::Equals(const ISimpleExpression* other) const -{ - const auto otherFunctionCall = dynamic_cast(other); - return otherFunctionCall && m_function_name == otherFunctionCall->m_function_name; +bool CommonExpressionCustomFunctionCall::Equals(const ISimpleExpression *other) const { + const auto otherFunctionCall = dynamic_cast(other); + return otherFunctionCall && m_function_name == otherFunctionCall->m_function_name; } -bool CommonExpressionCustomFunctionCall::IsStatic() const -{ - return false; -} +bool CommonExpressionCustomFunctionCall::IsStatic() const { return false; } -SimpleExpressionValue CommonExpressionCustomFunctionCall::EvaluateStatic() const -{ - return SimpleExpressionValue(0); -} +SimpleExpressionValue CommonExpressionCustomFunctionCall::EvaluateStatic() const { return SimpleExpressionValue(0); } -SimpleExpressionValue CommonExpressionCustomFunctionCall::EvaluateNonStatic(const ISimpleExpressionScopeValues* scopeValues) const -{ - return SimpleExpressionValue(0); +SimpleExpressionValue CommonExpressionCustomFunctionCall::EvaluateNonStatic(const ISimpleExpressionScopeValues *scopeValues) const { + return SimpleExpressionValue(0); } diff --git a/src/ObjLoading/Parsing/Menu/Domain/Expression/CommonExpressionCustomFunctionCall.h b/src/ObjLoading/Parsing/Menu/Domain/Expression/CommonExpressionCustomFunctionCall.h index f226c0986..1b5a11f10 100644 --- a/src/ObjLoading/Parsing/Menu/Domain/Expression/CommonExpressionCustomFunctionCall.h +++ b/src/ObjLoading/Parsing/Menu/Domain/Expression/CommonExpressionCustomFunctionCall.h @@ -2,18 +2,16 @@ #include "Parsing/Simple/Expression/ISimpleExpression.h" -namespace menu -{ - class CommonExpressionCustomFunctionCall final : public ISimpleExpression - { - public: - std::string m_function_name; +namespace menu { +class CommonExpressionCustomFunctionCall final : public ISimpleExpression { +public: + std::string m_function_name; - explicit CommonExpressionCustomFunctionCall(std::string functionName); + explicit CommonExpressionCustomFunctionCall(std::string functionName); - _NODISCARD bool Equals(const ISimpleExpression* other) const override; - _NODISCARD bool IsStatic() const override; - _NODISCARD SimpleExpressionValue EvaluateStatic() const override; - _NODISCARD SimpleExpressionValue EvaluateNonStatic(const ISimpleExpressionScopeValues* scopeValues) const override; - }; -} + _NODISCARD bool Equals(const ISimpleExpression *other) const override; + _NODISCARD bool IsStatic() const override; + _NODISCARD SimpleExpressionValue EvaluateStatic() const override; + _NODISCARD SimpleExpressionValue EvaluateNonStatic(const ISimpleExpressionScopeValues *scopeValues) const override; +}; +} // namespace menu diff --git a/src/ObjLoading/Parsing/Menu/Domain/MenuFeatureLevel.h b/src/ObjLoading/Parsing/Menu/Domain/MenuFeatureLevel.h index 8fb8c5e72..b49989497 100644 --- a/src/ObjLoading/Parsing/Menu/Domain/MenuFeatureLevel.h +++ b/src/ObjLoading/Parsing/Menu/Domain/MenuFeatureLevel.h @@ -1,10 +1,5 @@ #pragma once -namespace menu -{ - enum class FeatureLevel - { - IW4, - IW5 - }; +namespace menu { +enum class FeatureLevel { IW4, IW5 }; } \ No newline at end of file diff --git a/src/ObjLoading/Parsing/Menu/Domain/MenuParsingResult.h b/src/ObjLoading/Parsing/Menu/Domain/MenuParsingResult.h index 46c022974..4352db1dd 100644 --- a/src/ObjLoading/Parsing/Menu/Domain/MenuParsingResult.h +++ b/src/ObjLoading/Parsing/Menu/Domain/MenuParsingResult.h @@ -6,13 +6,11 @@ #include "CommonFunctionDef.h" #include "CommonMenuDef.h" -namespace menu -{ - class ParsingResult - { - public: - std::vector> m_menus; - std::vector> m_functions; - std::vector m_menus_to_load; - }; -} +namespace menu { +class ParsingResult { +public: + std::vector> m_menus; + std::vector> m_functions; + std::vector m_menus_to_load; +}; +} // namespace menu diff --git a/src/ObjLoading/Parsing/Menu/Matcher/MenuExpressionMatchers.cpp b/src/ObjLoading/Parsing/Menu/Matcher/MenuExpressionMatchers.cpp index 35e7bf055..b3a118b15 100644 --- a/src/ObjLoading/Parsing/Menu/Matcher/MenuExpressionMatchers.cpp +++ b/src/ObjLoading/Parsing/Menu/Matcher/MenuExpressionMatchers.cpp @@ -1,10 +1,10 @@ #include "MenuExpressionMatchers.h" -#include "MenuMatcherFactory.h" #include "Game/IW4/IW4.h" -#include "Game/IW5/IW5.h" #include "Game/IW4/MenuConstantsIW4.h" +#include "Game/IW5/IW5.h" #include "Game/IW5/MenuConstantsIW5.h" +#include "MenuMatcherFactory.h" #include "Parsing/Menu/Domain/Expression/CommonExpressionBaseFunctionCall.h" #include "Parsing/Menu/Domain/Expression/CommonExpressionCustomFunctionCall.h" @@ -15,104 +15,81 @@ static constexpr int TAG_EXPRESSION_FUNCTION_CALL_END = SimpleExpressionMatchers static constexpr int CAPTURE_FUNCTION_NAME = SimpleExpressionMatchers::CAPTURE_OFFSET_EXPRESSION_EXT + 1; -MenuExpressionMatchers::MenuExpressionMatchers(const MenuFileParserState* state) - : SimpleExpressionMatchers(true, true, true, true, true), - m_state(state) -{ -} +MenuExpressionMatchers::MenuExpressionMatchers(const MenuFileParserState *state) : SimpleExpressionMatchers(true, true, true, true, true), m_state(state) {} -MenuExpressionMatchers::MenuExpressionMatchers() - : MenuExpressionMatchers(nullptr) -{ -} +MenuExpressionMatchers::MenuExpressionMatchers() : MenuExpressionMatchers(nullptr) {} -std::unique_ptr MenuExpressionMatchers::ParseOperandExtension(const supplier_t* labelSupplier) const -{ - const MenuMatcherFactory create(labelSupplier); - - return create.Or({ - create.And({ - create.Identifier().Capture(CAPTURE_FUNCTION_NAME), - create.Char('('), - create.Optional(create.And({ - create.Label(LABEL_EXPRESSION), - create.OptionalLoop(create.And({ - create.Char(','), - create.Label(LABEL_EXPRESSION) - })), - })), - create.Char(')').Tag(TAG_EXPRESSION_FUNCTION_CALL_END) - }).Tag(TAG_EXPRESSION_FUNCTION_CALL) - }); -} +std::unique_ptr MenuExpressionMatchers::ParseOperandExtension(const supplier_t *labelSupplier) const { + const MenuMatcherFactory create(labelSupplier); -const std::map& MenuExpressionMatchers::GetBaseFunctionMapForFeatureLevel(const FeatureLevel featureLevel) -{ - if(featureLevel == FeatureLevel::IW4) - { - static std::map iw4FunctionMap; - static bool iw4FunctionMapInitialized = false; + return create.Or({create + .And({create.Identifier().Capture(CAPTURE_FUNCTION_NAME), create.Char('('), + create.Optional(create.And({ + create.Label(LABEL_EXPRESSION), + create.OptionalLoop(create.And({create.Char(','), create.Label(LABEL_EXPRESSION)})), + })), + create.Char(')').Tag(TAG_EXPRESSION_FUNCTION_CALL_END)}) + .Tag(TAG_EXPRESSION_FUNCTION_CALL)}); +} - if(!iw4FunctionMapInitialized) - { - for(size_t i = IW4::expressionFunction_e::EXP_FUNC_DYN_START; i < std::extent_v; i++) - iw4FunctionMap.emplace(std::make_pair(IW4::g_expFunctionNames[i], i)); - } +const std::map &MenuExpressionMatchers::GetBaseFunctionMapForFeatureLevel(const FeatureLevel featureLevel) { + if (featureLevel == FeatureLevel::IW4) { + static std::map iw4FunctionMap; + static bool iw4FunctionMapInitialized = false; - return iw4FunctionMap; + if (!iw4FunctionMapInitialized) { + for (size_t i = IW4::expressionFunction_e::EXP_FUNC_DYN_START; i < std::extent_v; i++) + iw4FunctionMap.emplace(std::make_pair(IW4::g_expFunctionNames[i], i)); } - if(featureLevel == FeatureLevel::IW5) - { - static std::map iw5FunctionMap; - static bool iw5FunctionMapInitialized = false; - - if(!iw5FunctionMapInitialized) - { - for(size_t i = IW5::expressionFunction_e::EXP_FUNC_DYN_START; i < std::extent_v; i++) - iw5FunctionMap.emplace(std::make_pair(IW5::g_expFunctionNames[i], i)); - } - - return iw5FunctionMap; + + return iw4FunctionMap; + } + if (featureLevel == FeatureLevel::IW5) { + static std::map iw5FunctionMap; + static bool iw5FunctionMapInitialized = false; + + if (!iw5FunctionMapInitialized) { + for (size_t i = IW5::expressionFunction_e::EXP_FUNC_DYN_START; i < std::extent_v; i++) + iw5FunctionMap.emplace(std::make_pair(IW5::g_expFunctionNames[i], i)); } - assert(false); - throw ParsingException(TokenPos(), "Feature level has no functions registered!!"); + return iw5FunctionMap; + } + + assert(false); + throw ParsingException(TokenPos(), "Feature level has no functions registered!!"); } -std::unique_ptr MenuExpressionMatchers::ProcessOperandExtension(SequenceResult& result) const -{ - assert(m_state); - if(m_state == nullptr) - throw ParsingException(TokenPos(), "No state when processing menu operand extension!!"); - - if (result.PeekAndRemoveIfTag(TAG_EXPRESSION_FUNCTION_CALL) != TAG_EXPRESSION_FUNCTION_CALL) - throw ParsingException(TokenPos(), "Menu Operand Extension must be function call"); - - const auto& functionCallToken = result.NextCapture(CAPTURE_FUNCTION_NAME); - auto functionCallName = functionCallToken.IdentifierValue(); - - const auto& baseFunctionMap = GetBaseFunctionMapForFeatureLevel(m_state->m_feature_level); - const auto foundBaseFunction = baseFunctionMap.find(functionCallName); - if(foundBaseFunction != baseFunctionMap.end()) - { - auto functionCall = std::make_unique(std::move(functionCallName), foundBaseFunction->second); - while (result.PeekAndRemoveIfTag(TAG_EXPRESSION_FUNCTION_CALL_END) != TAG_EXPRESSION_FUNCTION_CALL_END) - { - functionCall->m_args.emplace_back(ProcessExpression(result)); - } - return std::move(functionCall); - } +std::unique_ptr MenuExpressionMatchers::ProcessOperandExtension(SequenceResult &result) const { + assert(m_state); + if (m_state == nullptr) + throw ParsingException(TokenPos(), "No state when processing menu operand extension!!"); - const auto foundCustomFunction = m_state->m_functions_by_name.find(functionCallName); - if(foundCustomFunction != m_state->m_functions_by_name.end()) - { - auto functionCall = std::make_unique(std::move(functionCallName)); + if (result.PeekAndRemoveIfTag(TAG_EXPRESSION_FUNCTION_CALL) != TAG_EXPRESSION_FUNCTION_CALL) + throw ParsingException(TokenPos(), "Menu Operand Extension must be function call"); - if(result.PeekAndRemoveIfTag(TAG_EXPRESSION_FUNCTION_CALL_END) != TAG_EXPRESSION_FUNCTION_CALL_END) - throw ParsingException(functionCallToken.GetPos(), "Custom functions cannot be called with arguments"); + const auto &functionCallToken = result.NextCapture(CAPTURE_FUNCTION_NAME); + auto functionCallName = functionCallToken.IdentifierValue(); - return std::move(functionCall); + const auto &baseFunctionMap = GetBaseFunctionMapForFeatureLevel(m_state->m_feature_level); + const auto foundBaseFunction = baseFunctionMap.find(functionCallName); + if (foundBaseFunction != baseFunctionMap.end()) { + auto functionCall = std::make_unique(std::move(functionCallName), foundBaseFunction->second); + while (result.PeekAndRemoveIfTag(TAG_EXPRESSION_FUNCTION_CALL_END) != TAG_EXPRESSION_FUNCTION_CALL_END) { + functionCall->m_args.emplace_back(ProcessExpression(result)); } + return std::move(functionCall); + } + + const auto foundCustomFunction = m_state->m_functions_by_name.find(functionCallName); + if (foundCustomFunction != m_state->m_functions_by_name.end()) { + auto functionCall = std::make_unique(std::move(functionCallName)); + + if (result.PeekAndRemoveIfTag(TAG_EXPRESSION_FUNCTION_CALL_END) != TAG_EXPRESSION_FUNCTION_CALL_END) + throw ParsingException(functionCallToken.GetPos(), "Custom functions cannot be called with arguments"); + + return std::move(functionCall); + } - throw ParsingException(functionCallToken.GetPos(), "Unknown function"); + throw ParsingException(functionCallToken.GetPos(), "Unknown function"); } diff --git a/src/ObjLoading/Parsing/Menu/Matcher/MenuExpressionMatchers.h b/src/ObjLoading/Parsing/Menu/Matcher/MenuExpressionMatchers.h index b6821fced..66421e189 100644 --- a/src/ObjLoading/Parsing/Menu/Matcher/MenuExpressionMatchers.h +++ b/src/ObjLoading/Parsing/Menu/Matcher/MenuExpressionMatchers.h @@ -5,20 +5,18 @@ #include "Parsing/Menu/MenuFileParserState.h" #include "Parsing/Simple/Expression/SimpleExpressionMatchers.h" -namespace menu -{ - class MenuExpressionMatchers final : public SimpleExpressionMatchers - { - const MenuFileParserState* m_state; +namespace menu { +class MenuExpressionMatchers final : public SimpleExpressionMatchers { + const MenuFileParserState *m_state; - static const std::map& GetBaseFunctionMapForFeatureLevel(FeatureLevel featureLevel); + static const std::map &GetBaseFunctionMapForFeatureLevel(FeatureLevel featureLevel); - public: - MenuExpressionMatchers(); - explicit MenuExpressionMatchers(const MenuFileParserState* state); +public: + MenuExpressionMatchers(); + explicit MenuExpressionMatchers(const MenuFileParserState *state); - protected: - std::unique_ptr ParseOperandExtension(const supplier_t* labelSupplier) const override; - std::unique_ptr ProcessOperandExtension(SequenceResult& result) const override; - }; -} +protected: + std::unique_ptr ParseOperandExtension(const supplier_t *labelSupplier) const override; + std::unique_ptr ProcessOperandExtension(SequenceResult &result) const override; +}; +} // namespace menu diff --git a/src/ObjLoading/Parsing/Menu/Matcher/MenuMatcherFactory.cpp b/src/ObjLoading/Parsing/Menu/Matcher/MenuMatcherFactory.cpp index b857c6f4a..04ee47530 100644 --- a/src/ObjLoading/Parsing/Menu/Matcher/MenuMatcherFactory.cpp +++ b/src/ObjLoading/Parsing/Menu/Matcher/MenuMatcherFactory.cpp @@ -6,159 +6,121 @@ using namespace menu; -MenuMatcherFactory::MenuMatcherFactory(const IMatcherForLabelSupplier* labelSupplier) - : SimpleMatcherFactory(labelSupplier) -{ -} +MenuMatcherFactory::MenuMatcherFactory(const IMatcherForLabelSupplier *labelSupplier) : SimpleMatcherFactory(labelSupplier) {} -MatcherFactoryWrapper MenuMatcherFactory::StringChain() const -{ - return Or({ - And({ - String(), - Loop(String()) - }).Transform([](const token_list_t& tokens) -> SimpleParserValue - { - std::ostringstream ss; - - for (const auto& token : tokens) - { - ss << token.get().StringValue(); - } - - return SimpleParserValue::String(tokens[0].get().GetPos(), new std::string(ss.str())); - }), - String() - }); -} +MatcherFactoryWrapper MenuMatcherFactory::StringChain() const { + return Or({And({String(), Loop(String())}).Transform([](const token_list_t &tokens) -> SimpleParserValue { + std::ostringstream ss; -MatcherFactoryWrapper MenuMatcherFactory::Text() const -{ - return MatcherFactoryWrapper(Or({StringChain(), Identifier()})); -} + for (const auto &token : tokens) { + ss << token.get().StringValue(); + } -MatcherFactoryWrapper MenuMatcherFactory::TextNoChain() const -{ - return MatcherFactoryWrapper(Or({String(), Identifier()})); + return SimpleParserValue::String(tokens[0].get().GetPos(), new std::string(ss.str())); + }), + String()}); } -MatcherFactoryWrapper MenuMatcherFactory::Numeric() const -{ - return MatcherFactoryWrapper(Or({FloatingPoint(), Integer()})); -} +MatcherFactoryWrapper MenuMatcherFactory::Text() const { return MatcherFactoryWrapper(Or({StringChain(), Identifier()})); } -MatcherFactoryWrapper MenuMatcherFactory::IntExpression() const -{ - return MatcherFactoryWrapper(Or({ - Integer().Tag(TAG_INT).Capture(CAPTURE_INT), - And({ - Char('(').Capture(CAPTURE_FIRST_TOKEN), - Label(MenuExpressionMatchers::LABEL_EXPRESSION), - Char(')'), - }).Tag(TAG_EXPRESSION) - })); +MatcherFactoryWrapper MenuMatcherFactory::TextNoChain() const { return MatcherFactoryWrapper(Or({String(), Identifier()})); } + +MatcherFactoryWrapper MenuMatcherFactory::Numeric() const { return MatcherFactoryWrapper(Or({FloatingPoint(), Integer()})); } + +MatcherFactoryWrapper MenuMatcherFactory::IntExpression() const { + return MatcherFactoryWrapper(Or({Integer().Tag(TAG_INT).Capture(CAPTURE_INT), And({ + Char('(').Capture(CAPTURE_FIRST_TOKEN), + Label(MenuExpressionMatchers::LABEL_EXPRESSION), + Char(')'), + }) + .Tag(TAG_EXPRESSION)})); } -MatcherFactoryWrapper MenuMatcherFactory::NumericExpression() const -{ - return MatcherFactoryWrapper(Or({ - Numeric().Tag(TAG_NUMERIC).Capture(CAPTURE_NUMERIC), - And({ - Char('(').Capture(CAPTURE_FIRST_TOKEN), - Label(MenuExpressionMatchers::LABEL_EXPRESSION), - Char(')'), - }).Tag(TAG_EXPRESSION) - })); +MatcherFactoryWrapper MenuMatcherFactory::NumericExpression() const { + return MatcherFactoryWrapper(Or({Numeric().Tag(TAG_NUMERIC).Capture(CAPTURE_NUMERIC), And({ + Char('(').Capture(CAPTURE_FIRST_TOKEN), + Label(MenuExpressionMatchers::LABEL_EXPRESSION), + Char(')'), + }) + .Tag(TAG_EXPRESSION)})); } -int MenuMatcherFactory::TokenNumericIntValue(const SimpleParserValue& value) -{ - if (value.m_type == SimpleParserValueType::FLOATING_POINT) - { - return static_cast(value.FloatingPointValue()); - } +int MenuMatcherFactory::TokenNumericIntValue(const SimpleParserValue &value) { + if (value.m_type == SimpleParserValueType::FLOATING_POINT) { + return static_cast(value.FloatingPointValue()); + } - return value.IntegerValue(); + return value.IntegerValue(); } -double MenuMatcherFactory::TokenNumericFloatingPointValue(const SimpleParserValue& value) -{ - if (value.m_type == SimpleParserValueType::INTEGER) - { - return value.IntegerValue(); - } +double MenuMatcherFactory::TokenNumericFloatingPointValue(const SimpleParserValue &value) { + if (value.m_type == SimpleParserValueType::INTEGER) { + return value.IntegerValue(); + } - return value.FloatingPointValue(); + return value.FloatingPointValue(); } -std::string& MenuMatcherFactory::TokenTextValue(const SimpleParserValue& value) -{ - if (value.m_type == SimpleParserValueType::IDENTIFIER) - { - return value.IdentifierValue(); - } +std::string &MenuMatcherFactory::TokenTextValue(const SimpleParserValue &value) { + if (value.m_type == SimpleParserValueType::IDENTIFIER) { + return value.IdentifierValue(); + } - return value.StringValue(); + return value.StringValue(); } -int MenuMatcherFactory::TokenIntExpressionValue(MenuFileParserState* state, SequenceResult& result) -{ - const auto nextTag = result.PeekTag(); +int MenuMatcherFactory::TokenIntExpressionValue(MenuFileParserState *state, SequenceResult &result) { + const auto nextTag = result.PeekTag(); - assert(nextTag == TAG_INT || nextTag == TAG_EXPRESSION); - if (nextTag == TAG_INT) - { - result.NextTag(); - return result.NextCapture(CAPTURE_INT).IntegerValue(); - } + assert(nextTag == TAG_INT || nextTag == TAG_EXPRESSION); + if (nextTag == TAG_INT) { + result.NextTag(); + return result.NextCapture(CAPTURE_INT).IntegerValue(); + } - if (nextTag == TAG_EXPRESSION) - { - result.NextTag(); - const auto expression = MenuExpressionMatchers(state).ProcessExpression(result); + if (nextTag == TAG_EXPRESSION) { + result.NextTag(); + const auto expression = MenuExpressionMatchers(state).ProcessExpression(result); - if (!expression || !expression->IsStatic()) - throw ParsingException(result.NextCapture(CAPTURE_FIRST_TOKEN).GetPos(), "Not a valid static expression"); + if (!expression || !expression->IsStatic()) + throw ParsingException(result.NextCapture(CAPTURE_FIRST_TOKEN).GetPos(), "Not a valid static expression"); - const auto value = expression->EvaluateStatic(); + const auto value = expression->EvaluateStatic(); - if (value.m_type != SimpleExpressionValue::Type::INT) - throw ParsingException(result.NextCapture(CAPTURE_FIRST_TOKEN).GetPos(), "Expression MUST be int type"); + if (value.m_type != SimpleExpressionValue::Type::INT) + throw ParsingException(result.NextCapture(CAPTURE_FIRST_TOKEN).GetPos(), "Expression MUST be int type"); - return value.m_int_value; - } + return value.m_int_value; + } - throw ParsingException(TokenPos(), "TokenIntExpressionValue must be expression or int"); + throw ParsingException(TokenPos(), "TokenIntExpressionValue must be expression or int"); } -double MenuMatcherFactory::TokenNumericExpressionValue(MenuFileParserState* state, SequenceResult& result) -{ - const auto nextTag = result.PeekTag(); +double MenuMatcherFactory::TokenNumericExpressionValue(MenuFileParserState *state, SequenceResult &result) { + const auto nextTag = result.PeekTag(); - assert(nextTag == TAG_NUMERIC || nextTag == TAG_EXPRESSION); - if (nextTag == TAG_NUMERIC) - { - result.NextTag(); - return TokenNumericFloatingPointValue(result.NextCapture(CAPTURE_NUMERIC)); - } + assert(nextTag == TAG_NUMERIC || nextTag == TAG_EXPRESSION); + if (nextTag == TAG_NUMERIC) { + result.NextTag(); + return TokenNumericFloatingPointValue(result.NextCapture(CAPTURE_NUMERIC)); + } - if (nextTag == TAG_EXPRESSION) - { - result.NextTag(); - const auto expression = MenuExpressionMatchers(state).ProcessExpression(result); + if (nextTag == TAG_EXPRESSION) { + result.NextTag(); + const auto expression = MenuExpressionMatchers(state).ProcessExpression(result); - if (!expression || !expression->IsStatic()) - throw ParsingException(result.NextCapture(CAPTURE_FIRST_TOKEN).GetPos(), "Not a valid static expression"); + if (!expression || !expression->IsStatic()) + throw ParsingException(result.NextCapture(CAPTURE_FIRST_TOKEN).GetPos(), "Not a valid static expression"); - const auto value = expression->EvaluateStatic(); + const auto value = expression->EvaluateStatic(); - if (value.m_type == SimpleExpressionValue::Type::INT) - return value.m_int_value; - if (value.m_type == SimpleExpressionValue::Type::DOUBLE) - return value.m_double_value; + if (value.m_type == SimpleExpressionValue::Type::INT) + return value.m_int_value; + if (value.m_type == SimpleExpressionValue::Type::DOUBLE) + return value.m_double_value; - throw ParsingException(result.NextCapture(CAPTURE_FIRST_TOKEN).GetPos(), "Expression MUST be numeric type"); - } + throw ParsingException(result.NextCapture(CAPTURE_FIRST_TOKEN).GetPos(), "Expression MUST be numeric type"); + } - throw ParsingException(TokenPos(), "TokenNumericExpressionValue must be expression or numeric"); + throw ParsingException(TokenPos(), "TokenNumericExpressionValue must be expression or numeric"); } diff --git a/src/ObjLoading/Parsing/Menu/Matcher/MenuMatcherFactory.h b/src/ObjLoading/Parsing/Menu/Matcher/MenuMatcherFactory.h index 4762690b9..c12de7abd 100644 --- a/src/ObjLoading/Parsing/Menu/Matcher/MenuMatcherFactory.h +++ b/src/ObjLoading/Parsing/Menu/Matcher/MenuMatcherFactory.h @@ -1,37 +1,35 @@ #pragma once +#include "Parsing/Menu/MenuFileParserState.h" #include "Parsing/Sequence/SequenceResult.h" #include "Parsing/Simple/Matcher/SimpleMatcherFactory.h" -#include "Parsing/Menu/MenuFileParserState.h" -namespace menu -{ - class MenuMatcherFactory : public SimpleMatcherFactory - { - static constexpr auto TAG_INT = 1420; - static constexpr auto TAG_NUMERIC = 1421; - static constexpr auto TAG_EXPRESSION = 1422; - - static constexpr auto CAPTURE_FIRST_TOKEN = 1420; - static constexpr auto CAPTURE_INT = 1421; - static constexpr auto CAPTURE_NUMERIC = 1422; - - public: - explicit MenuMatcherFactory(const IMatcherForLabelSupplier* labelSupplier); - - _NODISCARD MatcherFactoryWrapper StringChain() const; - _NODISCARD MatcherFactoryWrapper Text() const; - _NODISCARD MatcherFactoryWrapper TextNoChain() const; - _NODISCARD MatcherFactoryWrapper Numeric() const; - - _NODISCARD MatcherFactoryWrapper IntExpression() const; - _NODISCARD MatcherFactoryWrapper NumericExpression() const; - - _NODISCARD static int TokenNumericIntValue(const SimpleParserValue& value); - _NODISCARD static double TokenNumericFloatingPointValue(const SimpleParserValue& value); - _NODISCARD static std::string& TokenTextValue(const SimpleParserValue& value); - - _NODISCARD static int TokenIntExpressionValue(MenuFileParserState* state, SequenceResult& result); - _NODISCARD static double TokenNumericExpressionValue(MenuFileParserState* state, SequenceResult& result); - }; -} +namespace menu { +class MenuMatcherFactory : public SimpleMatcherFactory { + static constexpr auto TAG_INT = 1420; + static constexpr auto TAG_NUMERIC = 1421; + static constexpr auto TAG_EXPRESSION = 1422; + + static constexpr auto CAPTURE_FIRST_TOKEN = 1420; + static constexpr auto CAPTURE_INT = 1421; + static constexpr auto CAPTURE_NUMERIC = 1422; + +public: + explicit MenuMatcherFactory(const IMatcherForLabelSupplier *labelSupplier); + + _NODISCARD MatcherFactoryWrapper StringChain() const; + _NODISCARD MatcherFactoryWrapper Text() const; + _NODISCARD MatcherFactoryWrapper TextNoChain() const; + _NODISCARD MatcherFactoryWrapper Numeric() const; + + _NODISCARD MatcherFactoryWrapper IntExpression() const; + _NODISCARD MatcherFactoryWrapper NumericExpression() const; + + _NODISCARD static int TokenNumericIntValue(const SimpleParserValue &value); + _NODISCARD static double TokenNumericFloatingPointValue(const SimpleParserValue &value); + _NODISCARD static std::string &TokenTextValue(const SimpleParserValue &value); + + _NODISCARD static int TokenIntExpressionValue(MenuFileParserState *state, SequenceResult &result); + _NODISCARD static double TokenNumericExpressionValue(MenuFileParserState *state, SequenceResult &result); +}; +} // namespace menu diff --git a/src/ObjLoading/Parsing/Menu/Matcher/MenuMatcherScriptInt.cpp b/src/ObjLoading/Parsing/Menu/Matcher/MenuMatcherScriptInt.cpp index 1b4a234f3..ee98d64ee 100644 --- a/src/ObjLoading/Parsing/Menu/Matcher/MenuMatcherScriptInt.cpp +++ b/src/ObjLoading/Parsing/Menu/Matcher/MenuMatcherScriptInt.cpp @@ -1,41 +1,38 @@ #include "MenuMatcherScriptInt.h" -MenuMatcherScriptInt::MenuMatcherScriptInt() -= default; +MenuMatcherScriptInt::MenuMatcherScriptInt() = default; -MatcherResult MenuMatcherScriptInt::CanMatch(ILexer* lexer, const unsigned tokenOffset) -{ - const auto& token = lexer->GetToken(tokenOffset); +MatcherResult MenuMatcherScriptInt::CanMatch(ILexer *lexer, const unsigned tokenOffset) { + const auto &token = lexer->GetToken(tokenOffset); - if (token.m_type == SimpleParserValueType::CHARACTER) - { - if (token.CharacterValue() != '-') - return MatcherResult::NoMatch(); + if (token.m_type == SimpleParserValueType::CHARACTER) { + if (token.CharacterValue() != '-') + return MatcherResult::NoMatch(); - const auto& nextToken = lexer->GetToken(tokenOffset + 1); - if (nextToken.m_type != SimpleParserValueType::INTEGER) - return MatcherResult::NoMatch(); + const auto &nextToken = lexer->GetToken(tokenOffset + 1); + if (nextToken.m_type != SimpleParserValueType::INTEGER) + return MatcherResult::NoMatch(); - return MatcherResult::Match(2); - } + return MatcherResult::Match(2); + } - if (token.m_type == SimpleParserValueType::INTEGER) - return MatcherResult::Match(1); + if (token.m_type == SimpleParserValueType::INTEGER) + return MatcherResult::Match(1); - if (token.m_type != SimpleParserValueType::STRING) - return MatcherResult::NoMatch(); + if (token.m_type != SimpleParserValueType::STRING) + return MatcherResult::NoMatch(); - const auto& stringValue = token.StringValue(); + const auto &stringValue = token.StringValue(); - if (stringValue.empty()) - return MatcherResult::NoMatch(); + if (stringValue.empty()) + return MatcherResult::NoMatch(); - char* endPtr; - // The return result does not matter here - const auto _ = strtol(stringValue.data(), &endPtr, 10); + char *endPtr; + // The return result does not matter here + const auto _ = strtol(stringValue.data(), &endPtr, 10); - if (endPtr != &stringValue[stringValue.size() - 1]) - return MatcherResult::NoMatch(); + if (endPtr != &stringValue[stringValue.size() - 1]) + return MatcherResult::NoMatch(); - return MatcherResult::Match(1); + return MatcherResult::Match(1); } diff --git a/src/ObjLoading/Parsing/Menu/Matcher/MenuMatcherScriptInt.h b/src/ObjLoading/Parsing/Menu/Matcher/MenuMatcherScriptInt.h index e6ed7e547..4555bcb0d 100644 --- a/src/ObjLoading/Parsing/Menu/Matcher/MenuMatcherScriptInt.h +++ b/src/ObjLoading/Parsing/Menu/Matcher/MenuMatcherScriptInt.h @@ -1,13 +1,12 @@ #pragma once -#include "Parsing/Simple/SimpleParserValue.h" #include "Parsing/Matcher/AbstractMatcher.h" +#include "Parsing/Simple/SimpleParserValue.h" -class MenuMatcherScriptInt final : public AbstractMatcher -{ +class MenuMatcherScriptInt final : public AbstractMatcher { protected: - MatcherResult CanMatch(ILexer* lexer, unsigned tokenOffset) override; + MatcherResult CanMatch(ILexer *lexer, unsigned tokenOffset) override; public: - MenuMatcherScriptInt(); + MenuMatcherScriptInt(); }; diff --git a/src/ObjLoading/Parsing/Menu/Matcher/MenuMatcherScriptNumeric.cpp b/src/ObjLoading/Parsing/Menu/Matcher/MenuMatcherScriptNumeric.cpp index 969349d2d..85d849439 100644 --- a/src/ObjLoading/Parsing/Menu/Matcher/MenuMatcherScriptNumeric.cpp +++ b/src/ObjLoading/Parsing/Menu/Matcher/MenuMatcherScriptNumeric.cpp @@ -1,41 +1,38 @@ #include "MenuMatcherScriptNumeric.h" -MenuMatcherScriptNumeric::MenuMatcherScriptNumeric() -= default; +MenuMatcherScriptNumeric::MenuMatcherScriptNumeric() = default; -MatcherResult MenuMatcherScriptNumeric::CanMatch(ILexer* lexer, const unsigned tokenOffset) -{ - const auto& token = lexer->GetToken(tokenOffset); +MatcherResult MenuMatcherScriptNumeric::CanMatch(ILexer *lexer, const unsigned tokenOffset) { + const auto &token = lexer->GetToken(tokenOffset); - if (token.m_type == SimpleParserValueType::CHARACTER) - { - if (token.CharacterValue() != '-') - return MatcherResult::NoMatch(); + if (token.m_type == SimpleParserValueType::CHARACTER) { + if (token.CharacterValue() != '-') + return MatcherResult::NoMatch(); - const auto& nextToken = lexer->GetToken(tokenOffset + 1); - if (nextToken.m_type != SimpleParserValueType::FLOATING_POINT && nextToken.m_type != SimpleParserValueType::INTEGER) - return MatcherResult::NoMatch(); + const auto &nextToken = lexer->GetToken(tokenOffset + 1); + if (nextToken.m_type != SimpleParserValueType::FLOATING_POINT && nextToken.m_type != SimpleParserValueType::INTEGER) + return MatcherResult::NoMatch(); - return MatcherResult::Match(2); - } + return MatcherResult::Match(2); + } - if (token.m_type == SimpleParserValueType::FLOATING_POINT || token.m_type == SimpleParserValueType::INTEGER) - return MatcherResult::Match(1); + if (token.m_type == SimpleParserValueType::FLOATING_POINT || token.m_type == SimpleParserValueType::INTEGER) + return MatcherResult::Match(1); - if (token.m_type != SimpleParserValueType::STRING) - return MatcherResult::NoMatch(); + if (token.m_type != SimpleParserValueType::STRING) + return MatcherResult::NoMatch(); - const auto& stringValue = token.StringValue(); + const auto &stringValue = token.StringValue(); - if (stringValue.empty()) - return MatcherResult::NoMatch(); + if (stringValue.empty()) + return MatcherResult::NoMatch(); - char* endPtr; - // The return result does not matter here - const auto _ = strtod(stringValue.data(), &endPtr); + char *endPtr; + // The return result does not matter here + const auto _ = strtod(stringValue.data(), &endPtr); - if(endPtr != &stringValue[stringValue.size()]) - return MatcherResult::NoMatch(); + if (endPtr != &stringValue[stringValue.size()]) + return MatcherResult::NoMatch(); - return MatcherResult::Match(1); + return MatcherResult::Match(1); } diff --git a/src/ObjLoading/Parsing/Menu/Matcher/MenuMatcherScriptNumeric.h b/src/ObjLoading/Parsing/Menu/Matcher/MenuMatcherScriptNumeric.h index e9325b297..5204493b4 100644 --- a/src/ObjLoading/Parsing/Menu/Matcher/MenuMatcherScriptNumeric.h +++ b/src/ObjLoading/Parsing/Menu/Matcher/MenuMatcherScriptNumeric.h @@ -1,13 +1,12 @@ #pragma once -#include "Parsing/Simple/SimpleParserValue.h" #include "Parsing/Matcher/AbstractMatcher.h" +#include "Parsing/Simple/SimpleParserValue.h" -class MenuMatcherScriptNumeric final : public AbstractMatcher -{ +class MenuMatcherScriptNumeric final : public AbstractMatcher { protected: - MatcherResult CanMatch(ILexer* lexer, unsigned tokenOffset) override; + MatcherResult CanMatch(ILexer *lexer, unsigned tokenOffset) override; public: - MenuMatcherScriptNumeric(); + MenuMatcherScriptNumeric(); }; diff --git a/src/ObjLoading/Parsing/Menu/MenuAssetZoneState.cpp b/src/ObjLoading/Parsing/Menu/MenuAssetZoneState.cpp index 0b3a8eb9c..2f3b0eec3 100644 --- a/src/ObjLoading/Parsing/Menu/MenuAssetZoneState.cpp +++ b/src/ObjLoading/Parsing/Menu/MenuAssetZoneState.cpp @@ -2,18 +2,13 @@ using namespace menu; -void MenuAssetZoneState::AddFunction(std::unique_ptr function) -{ - m_functions_by_name.emplace(std::make_pair(function->m_name, function.get())); - m_functions.emplace_back(std::move(function)); +void MenuAssetZoneState::AddFunction(std::unique_ptr function) { + m_functions_by_name.emplace(std::make_pair(function->m_name, function.get())); + m_functions.emplace_back(std::move(function)); } -void MenuAssetZoneState::AddMenu(std::unique_ptr menu) -{ - m_menus.emplace_back(std::move(menu)); -} +void MenuAssetZoneState::AddMenu(std::unique_ptr menu) { m_menus.emplace_back(std::move(menu)); } -void MenuAssetZoneState::AddMenusToLoad(std::string menuName, std::vector menusToLoad) -{ - m_menus_to_load_by_menu.emplace(std::make_pair(std::move(menuName), std::move(menusToLoad))); +void MenuAssetZoneState::AddMenusToLoad(std::string menuName, std::vector menusToLoad) { + m_menus_to_load_by_menu.emplace(std::make_pair(std::move(menuName), std::move(menusToLoad))); } diff --git a/src/ObjLoading/Parsing/Menu/MenuAssetZoneState.h b/src/ObjLoading/Parsing/Menu/MenuAssetZoneState.h index c6e0cadfe..da2afcb07 100644 --- a/src/ObjLoading/Parsing/Menu/MenuAssetZoneState.h +++ b/src/ObjLoading/Parsing/Menu/MenuAssetZoneState.h @@ -6,22 +6,20 @@ #include "Domain/CommonFunctionDef.h" #include "Domain/CommonMenuDef.h" -namespace menu -{ - class MenuAssetZoneState final : public IZoneAssetLoaderState - { - public: - std::vector> m_functions; - std::vector> m_menus; +namespace menu { +class MenuAssetZoneState final : public IZoneAssetLoaderState { +public: + std::vector> m_functions; + std::vector> m_menus; - std::map m_functions_by_name; + std::map m_functions_by_name; - std::map> m_menus_to_load_by_menu; + std::map> m_menus_to_load_by_menu; - MenuAssetZoneState() = default; - - void AddFunction(std::unique_ptr function); - void AddMenu(std::unique_ptr menu); - void AddMenusToLoad(std::string menuName, std::vector menusToLoad); - }; -} + MenuAssetZoneState() = default; + + void AddFunction(std::unique_ptr function); + void AddMenu(std::unique_ptr menu); + void AddMenusToLoad(std::string menuName, std::vector menusToLoad); +}; +} // namespace menu diff --git a/src/ObjLoading/Parsing/Menu/MenuFileCommonOperations.cpp b/src/ObjLoading/Parsing/Menu/MenuFileCommonOperations.cpp index 48abf663a..74277ced7 100644 --- a/src/ObjLoading/Parsing/Menu/MenuFileCommonOperations.cpp +++ b/src/ObjLoading/Parsing/Menu/MenuFileCommonOperations.cpp @@ -4,24 +4,20 @@ using namespace menu; -void MenuFileCommonOperations::EnsureIsNumericExpression(const MenuFileParserState* state, const TokenPos& pos, const ISimpleExpression& expression) -{ - if (!state->m_permissive_mode && expression.IsStatic()) - { - const auto staticValue = expression.EvaluateStatic(); +void MenuFileCommonOperations::EnsureIsNumericExpression(const MenuFileParserState *state, const TokenPos &pos, const ISimpleExpression &expression) { + if (!state->m_permissive_mode && expression.IsStatic()) { + const auto staticValue = expression.EvaluateStatic(); - if (staticValue.m_type != SimpleExpressionValue::Type::INT && staticValue.m_type != SimpleExpressionValue::Type::DOUBLE) - throw ParsingException(pos, "Expression is expected to be numeric. Use permissive mode to compile anyway."); - } + if (staticValue.m_type != SimpleExpressionValue::Type::INT && staticValue.m_type != SimpleExpressionValue::Type::DOUBLE) + throw ParsingException(pos, "Expression is expected to be numeric. Use permissive mode to compile anyway."); + } } -void MenuFileCommonOperations::EnsureIsStringExpression(const MenuFileParserState* state, const TokenPos& pos, const ISimpleExpression& expression) -{ - if (!state->m_permissive_mode && expression.IsStatic()) - { - const auto staticValue = expression.EvaluateStatic(); +void MenuFileCommonOperations::EnsureIsStringExpression(const MenuFileParserState *state, const TokenPos &pos, const ISimpleExpression &expression) { + if (!state->m_permissive_mode && expression.IsStatic()) { + const auto staticValue = expression.EvaluateStatic(); - if (staticValue.m_type != SimpleExpressionValue::Type::STRING) - throw ParsingException(pos, "Expression is expected to be string. Use permissive mode to compile anyway."); - } + if (staticValue.m_type != SimpleExpressionValue::Type::STRING) + throw ParsingException(pos, "Expression is expected to be string. Use permissive mode to compile anyway."); + } } \ No newline at end of file diff --git a/src/ObjLoading/Parsing/Menu/MenuFileCommonOperations.h b/src/ObjLoading/Parsing/Menu/MenuFileCommonOperations.h index b56c83b56..775bbf50a 100644 --- a/src/ObjLoading/Parsing/Menu/MenuFileCommonOperations.h +++ b/src/ObjLoading/Parsing/Menu/MenuFileCommonOperations.h @@ -1,14 +1,12 @@ #pragma once #include "MenuFileParserState.h" -#include "Parsing/TokenPos.h" #include "Parsing/Simple/Expression/ISimpleExpression.h" +#include "Parsing/TokenPos.h" -namespace menu -{ - class MenuFileCommonOperations - { - public: - static void EnsureIsNumericExpression(const MenuFileParserState* state, const TokenPos& pos, const ISimpleExpression& expression); - static void EnsureIsStringExpression(const MenuFileParserState* state, const TokenPos& pos, const ISimpleExpression& expression); - }; -} +namespace menu { +class MenuFileCommonOperations { +public: + static void EnsureIsNumericExpression(const MenuFileParserState *state, const TokenPos &pos, const ISimpleExpression &expression); + static void EnsureIsStringExpression(const MenuFileParserState *state, const TokenPos &pos, const ISimpleExpression &expression); +}; +} // namespace menu diff --git a/src/ObjLoading/Parsing/Menu/MenuFileParser.cpp b/src/ObjLoading/Parsing/Menu/MenuFileParser.cpp index c0e0668d9..b91333325 100644 --- a/src/ObjLoading/Parsing/Menu/MenuFileParser.cpp +++ b/src/ObjLoading/Parsing/Menu/MenuFileParser.cpp @@ -9,77 +9,69 @@ using namespace menu; -MenuFileParser::MenuFileParser(SimpleLexer* lexer, const FeatureLevel featureLevel, bool permissiveMode) - : AbstractParser(lexer, std::make_unique(featureLevel, permissiveMode)) -{ - CreateSequenceCollections(); +MenuFileParser::MenuFileParser(SimpleLexer *lexer, const FeatureLevel featureLevel, bool permissiveMode) + : AbstractParser(lexer, std::make_unique(featureLevel, permissiveMode)) { + CreateSequenceCollections(); } -MenuFileParser::MenuFileParser(SimpleLexer* lexer, FeatureLevel featureLevel, bool permissiveMode, const MenuAssetZoneState* zoneState) - : AbstractParser(lexer, std::make_unique(featureLevel, permissiveMode, zoneState)) -{ - CreateSequenceCollections(); +MenuFileParser::MenuFileParser(SimpleLexer *lexer, FeatureLevel featureLevel, bool permissiveMode, const MenuAssetZoneState *zoneState) + : AbstractParser(lexer, std::make_unique(featureLevel, permissiveMode, zoneState)) { + CreateSequenceCollections(); } -void MenuFileParser::AddSequence(std::vector& collection, std::unique_ptr test) -{ - collection.push_back(test.get()); - m_all_tests.emplace_back(std::move(test)); +void MenuFileParser::AddSequence(std::vector &collection, std::unique_ptr test) { + collection.push_back(test.get()); + m_all_tests.emplace_back(std::move(test)); } -void MenuFileParser::CreateSequenceCollections() -{ - m_all_tests.clear(); - m_no_scope_tests.clear(); - m_global_scope_tests.clear(); - m_function_scope_tests.clear(); - m_menu_scope_tests.clear(); - m_item_scope_tests.clear(); - m_event_handler_set_scope_tests.clear(); +void MenuFileParser::CreateSequenceCollections() { + m_all_tests.clear(); + m_no_scope_tests.clear(); + m_global_scope_tests.clear(); + m_function_scope_tests.clear(); + m_menu_scope_tests.clear(); + m_item_scope_tests.clear(); + m_event_handler_set_scope_tests.clear(); - const auto featureLevel = m_state->m_feature_level; - const auto permissive = m_state->m_permissive_mode; + const auto featureLevel = m_state->m_feature_level; + const auto permissive = m_state->m_permissive_mode; - NoScopeSequences noScopeSequences(m_all_tests, m_no_scope_tests); - noScopeSequences.AddSequences(featureLevel, permissive); + NoScopeSequences noScopeSequences(m_all_tests, m_no_scope_tests); + noScopeSequences.AddSequences(featureLevel, permissive); - GlobalScopeSequences globalScopeSequences(m_all_tests, m_global_scope_tests); - globalScopeSequences.AddSequences(featureLevel, permissive); + GlobalScopeSequences globalScopeSequences(m_all_tests, m_global_scope_tests); + globalScopeSequences.AddSequences(featureLevel, permissive); - MenuScopeSequences menuPropertySequences(m_all_tests, m_menu_scope_tests); - menuPropertySequences.AddSequences(featureLevel, permissive); + MenuScopeSequences menuPropertySequences(m_all_tests, m_menu_scope_tests); + menuPropertySequences.AddSequences(featureLevel, permissive); - ItemScopeSequences itemPropertySequences(m_all_tests, m_item_scope_tests); - itemPropertySequences.AddSequences(featureLevel, permissive); + ItemScopeSequences itemPropertySequences(m_all_tests, m_item_scope_tests); + itemPropertySequences.AddSequences(featureLevel, permissive); - FunctionScopeSequences functionPropertySequences(m_all_tests, m_function_scope_tests); - functionPropertySequences.AddSequences(featureLevel, permissive); + FunctionScopeSequences functionPropertySequences(m_all_tests, m_function_scope_tests); + functionPropertySequences.AddSequences(featureLevel, permissive); - EventHandlerSetScopeSequences eventHandlerSetScopeSequences(m_all_tests, m_event_handler_set_scope_tests); - eventHandlerSetScopeSequences.AddSequences(featureLevel, permissive); + EventHandlerSetScopeSequences eventHandlerSetScopeSequences(m_all_tests, m_event_handler_set_scope_tests); + eventHandlerSetScopeSequences.AddSequences(featureLevel, permissive); } -const std::vector& MenuFileParser::GetTestsForState() -{ - if (m_state->m_current_event_handler_set) - return m_event_handler_set_scope_tests; +const std::vector &MenuFileParser::GetTestsForState() { + if (m_state->m_current_event_handler_set) + return m_event_handler_set_scope_tests; - if (m_state->m_current_item) - return m_item_scope_tests; + if (m_state->m_current_item) + return m_item_scope_tests; - if (m_state->m_current_function) - return m_function_scope_tests; + if (m_state->m_current_function) + return m_function_scope_tests; - if (m_state->m_current_menu) - return m_menu_scope_tests; + if (m_state->m_current_menu) + return m_menu_scope_tests; - if (m_state->m_in_global_scope) - return m_global_scope_tests; + if (m_state->m_in_global_scope) + return m_global_scope_tests; - return m_no_scope_tests; + return m_no_scope_tests; } -MenuFileParserState* MenuFileParser::GetState() const -{ - return m_state.get(); -} +MenuFileParserState *MenuFileParser::GetState() const { return m_state.get(); } diff --git a/src/ObjLoading/Parsing/Menu/MenuFileParser.h b/src/ObjLoading/Parsing/Menu/MenuFileParser.h index 7e911f7de..694776f3e 100644 --- a/src/ObjLoading/Parsing/Menu/MenuFileParser.h +++ b/src/ObjLoading/Parsing/Menu/MenuFileParser.h @@ -1,33 +1,31 @@ #pragma once #include "MenuAssetZoneState.h" -#include "Utils/ClassUtils.h" #include "MenuFileParserState.h" +#include "Parsing/Impl/AbstractParser.h" #include "Parsing/Simple/SimpleLexer.h" #include "Parsing/Simple/SimpleParserValue.h" -#include "Parsing/Impl/AbstractParser.h" +#include "Utils/ClassUtils.h" -namespace menu -{ - class MenuFileParser final : public AbstractParser - { - std::vector> m_all_tests; - std::vector m_no_scope_tests; - std::vector m_global_scope_tests; - std::vector m_function_scope_tests; - std::vector m_menu_scope_tests; - std::vector m_item_scope_tests; - std::vector m_event_handler_set_scope_tests; +namespace menu { +class MenuFileParser final : public AbstractParser { + std::vector> m_all_tests; + std::vector m_no_scope_tests; + std::vector m_global_scope_tests; + std::vector m_function_scope_tests; + std::vector m_menu_scope_tests; + std::vector m_item_scope_tests; + std::vector m_event_handler_set_scope_tests; - void AddSequence(std::vector& collection, std::unique_ptr test); - void CreateSequenceCollections(); + void AddSequence(std::vector &collection, std::unique_ptr test); + void CreateSequenceCollections(); - protected: - const std::vector& GetTestsForState() override; +protected: + const std::vector &GetTestsForState() override; - public: - MenuFileParser(SimpleLexer* lexer, FeatureLevel featureLevel, bool permissiveMode); - MenuFileParser(SimpleLexer* lexer, FeatureLevel featureLevel, bool permissiveMode, const MenuAssetZoneState* zoneState); - _NODISCARD MenuFileParserState* GetState() const; - }; -} +public: + MenuFileParser(SimpleLexer *lexer, FeatureLevel featureLevel, bool permissiveMode); + MenuFileParser(SimpleLexer *lexer, FeatureLevel featureLevel, bool permissiveMode, const MenuAssetZoneState *zoneState); + _NODISCARD MenuFileParserState *GetState() const; +}; +} // namespace menu diff --git a/src/ObjLoading/Parsing/Menu/MenuFileParserState.cpp b/src/ObjLoading/Parsing/Menu/MenuFileParserState.cpp index 64fe0ffa9..f0358c098 100644 --- a/src/ObjLoading/Parsing/Menu/MenuFileParserState.cpp +++ b/src/ObjLoading/Parsing/Menu/MenuFileParserState.cpp @@ -2,41 +2,23 @@ using namespace menu; -MenuFileParserState::EventHandlerConditionState::EventHandlerConditionState(CommonEventHandlerCondition* condition) - : EventHandlerConditionState(condition, false) -{ -} +MenuFileParserState::EventHandlerConditionState::EventHandlerConditionState(CommonEventHandlerCondition *condition) + : EventHandlerConditionState(condition, false) {} -MenuFileParserState::EventHandlerConditionState::EventHandlerConditionState(CommonEventHandlerCondition* condition, const bool autoSkip) - : m_in_condition_elements(true), - m_auto_skip(autoSkip), - m_condition(condition) -{ -} +MenuFileParserState::EventHandlerConditionState::EventHandlerConditionState(CommonEventHandlerCondition *condition, const bool autoSkip) + : m_in_condition_elements(true), m_auto_skip(autoSkip), m_condition(condition) {} MenuFileParserState::MenuFileParserState(const FeatureLevel featureLevel, const bool permissiveMode) - : m_feature_level(featureLevel), - m_permissive_mode(permissiveMode), - m_in_global_scope(false), - m_current_function(nullptr), - m_current_menu(nullptr), - m_current_item(nullptr), - m_current_event_handler_set(nullptr), - m_current_script_statement_terminated(true), - m_current_nested_event_handler_set(nullptr) -{ -} + : m_feature_level(featureLevel), m_permissive_mode(permissiveMode), m_in_global_scope(false), m_current_function(nullptr), m_current_menu(nullptr), + m_current_item(nullptr), m_current_event_handler_set(nullptr), m_current_script_statement_terminated(true), m_current_nested_event_handler_set(nullptr) {} -MenuFileParserState::MenuFileParserState(const FeatureLevel featureLevel, const bool permissiveMode, const MenuAssetZoneState* zoneState) - : MenuFileParserState(featureLevel, permissiveMode) -{ - for (const auto& function : zoneState->m_functions) - { - m_functions_by_name.emplace(std::make_pair(function->m_name, function.get())); - } +MenuFileParserState::MenuFileParserState(const FeatureLevel featureLevel, const bool permissiveMode, const MenuAssetZoneState *zoneState) + : MenuFileParserState(featureLevel, permissiveMode) { + for (const auto &function : zoneState->m_functions) { + m_functions_by_name.emplace(std::make_pair(function->m_name, function.get())); + } - for (const auto& menu : zoneState->m_menus) - { - m_menus_by_name.emplace(std::make_pair(menu->m_name, menu.get())); - } + for (const auto &menu : zoneState->m_menus) { + m_menus_by_name.emplace(std::make_pair(menu->m_name, menu.get())); + } } diff --git a/src/ObjLoading/Parsing/Menu/MenuFileParserState.h b/src/ObjLoading/Parsing/Menu/MenuFileParserState.h index b01294ebd..397c8934c 100644 --- a/src/ObjLoading/Parsing/Menu/MenuFileParserState.h +++ b/src/ObjLoading/Parsing/Menu/MenuFileParserState.h @@ -2,55 +2,52 @@ #include #include -#include #include #include +#include -#include "MenuAssetZoneState.h" #include "Domain/CommonFunctionDef.h" #include "Domain/CommonMenuDef.h" -#include "Domain/MenuFeatureLevel.h" -#include "Domain/EventHandler/CommonEventHandlerSet.h" #include "Domain/EventHandler/CommonEventHandlerCondition.h" +#include "Domain/EventHandler/CommonEventHandlerSet.h" +#include "Domain/MenuFeatureLevel.h" +#include "MenuAssetZoneState.h" -namespace menu -{ - class MenuFileParserState - { - public: - class EventHandlerConditionState - { - public: - bool m_in_condition_elements; - bool m_auto_skip; - CommonEventHandlerCondition* m_condition; - - explicit EventHandlerConditionState(CommonEventHandlerCondition* condition); - EventHandlerConditionState(CommonEventHandlerCondition* condition, bool autoSkip); - }; - - const FeatureLevel m_feature_level; - const bool m_permissive_mode; - - std::vector m_menus_to_load; - std::vector> m_functions; - std::vector> m_menus; - - std::map m_functions_by_name; - std::map m_menus_by_name; - - bool m_in_global_scope; - CommonFunctionDef* m_current_function; - CommonMenuDef* m_current_menu; - CommonItemDef* m_current_item; - CommonEventHandlerSet* m_current_event_handler_set; - - std::ostringstream m_current_script; - bool m_current_script_statement_terminated; - std::stack m_condition_stack; - CommonEventHandlerSet* m_current_nested_event_handler_set; - - explicit MenuFileParserState(FeatureLevel featureLevel, bool permissiveMode); - MenuFileParserState(FeatureLevel featureLevel, bool permissiveMode, const MenuAssetZoneState* zoneState); - }; -} +namespace menu { +class MenuFileParserState { +public: + class EventHandlerConditionState { + public: + bool m_in_condition_elements; + bool m_auto_skip; + CommonEventHandlerCondition *m_condition; + + explicit EventHandlerConditionState(CommonEventHandlerCondition *condition); + EventHandlerConditionState(CommonEventHandlerCondition *condition, bool autoSkip); + }; + + const FeatureLevel m_feature_level; + const bool m_permissive_mode; + + std::vector m_menus_to_load; + std::vector> m_functions; + std::vector> m_menus; + + std::map m_functions_by_name; + std::map m_menus_by_name; + + bool m_in_global_scope; + CommonFunctionDef *m_current_function; + CommonMenuDef *m_current_menu; + CommonItemDef *m_current_item; + CommonEventHandlerSet *m_current_event_handler_set; + + std::ostringstream m_current_script; + bool m_current_script_statement_terminated; + std::stack m_condition_stack; + CommonEventHandlerSet *m_current_nested_event_handler_set; + + explicit MenuFileParserState(FeatureLevel featureLevel, bool permissiveMode); + MenuFileParserState(FeatureLevel featureLevel, bool permissiveMode, const MenuAssetZoneState *zoneState); +}; +} // namespace menu diff --git a/src/ObjLoading/Parsing/Menu/MenuFileReader.cpp b/src/ObjLoading/Parsing/Menu/MenuFileReader.cpp index d64eff638..f5919b290 100644 --- a/src/ObjLoading/Parsing/Menu/MenuFileReader.cpp +++ b/src/ObjLoading/Parsing/Menu/MenuFileReader.cpp @@ -1,7 +1,7 @@ #include "MenuFileReader.h" -#include "MenuFileParser.h" #include "Matcher/MenuExpressionMatchers.h" +#include "MenuFileParser.h" #include "Parsing/Impl/CommentRemovingStreamProxy.h" #include "Parsing/Impl/DefinesStreamProxy.h" #include "Parsing/Impl/IncludingStreamProxy.h" @@ -11,145 +11,117 @@ using namespace menu; -MenuFileReader::MenuFileReader(std::istream& stream, std::string fileName, const FeatureLevel featureLevel, include_callback_t includeCallback) - : m_feature_level(featureLevel), - m_file_name(std::move(fileName)), - m_stream(nullptr), - m_zone_state(nullptr), - m_permissive_mode(false) -{ - OpenBaseStream(stream, std::move(includeCallback)); - SetupStreamProxies(); - m_stream = m_open_streams.back().get(); +MenuFileReader::MenuFileReader(std::istream &stream, std::string fileName, const FeatureLevel featureLevel, include_callback_t includeCallback) + : m_feature_level(featureLevel), m_file_name(std::move(fileName)), m_stream(nullptr), m_zone_state(nullptr), m_permissive_mode(false) { + OpenBaseStream(stream, std::move(includeCallback)); + SetupStreamProxies(); + m_stream = m_open_streams.back().get(); } -MenuFileReader::MenuFileReader(std::istream& stream, std::string fileName, const FeatureLevel featureLevel) - : m_feature_level(featureLevel), - m_file_name(std::move(fileName)), - m_stream(nullptr), - m_zone_state(nullptr), - m_permissive_mode(false) -{ - OpenBaseStream(stream, nullptr); - SetupStreamProxies(); - m_stream = m_open_streams.back().get(); +MenuFileReader::MenuFileReader(std::istream &stream, std::string fileName, const FeatureLevel featureLevel) + : m_feature_level(featureLevel), m_file_name(std::move(fileName)), m_stream(nullptr), m_zone_state(nullptr), m_permissive_mode(false) { + OpenBaseStream(stream, nullptr); + SetupStreamProxies(); + m_stream = m_open_streams.back().get(); } -bool MenuFileReader::OpenBaseStream(std::istream& stream, include_callback_t includeCallback) -{ - if (includeCallback) - m_open_streams.emplace_back(std::make_unique(stream, m_file_name, std::move(includeCallback))); - else - m_open_streams.emplace_back(std::make_unique(stream, m_file_name)); +bool MenuFileReader::OpenBaseStream(std::istream &stream, include_callback_t includeCallback) { + if (includeCallback) + m_open_streams.emplace_back(std::make_unique(stream, m_file_name, std::move(includeCallback))); + else + m_open_streams.emplace_back(std::make_unique(stream, m_file_name)); - return true; + return true; } -void MenuFileReader::SetupDefinesProxy() -{ - auto defines = std::make_unique(m_open_streams.back().get()); - - defines->AddDefine(DefinesStreamProxy::Define("PC", "1")); - switch (m_feature_level) - { - case FeatureLevel::IW4: - defines->AddDefine(DefinesStreamProxy::Define("FEATURE_LEVEL_IW4", "1")); - break; - case FeatureLevel::IW5: - defines->AddDefine(DefinesStreamProxy::Define("FEATURE_LEVEL_IW5", "1")); - break; - default: - assert(false); - break; - } - - m_open_streams.emplace_back(std::move(defines)); +void MenuFileReader::SetupDefinesProxy() { + auto defines = std::make_unique(m_open_streams.back().get()); + + defines->AddDefine(DefinesStreamProxy::Define("PC", "1")); + switch (m_feature_level) { + case FeatureLevel::IW4: + defines->AddDefine(DefinesStreamProxy::Define("FEATURE_LEVEL_IW4", "1")); + break; + case FeatureLevel::IW5: + defines->AddDefine(DefinesStreamProxy::Define("FEATURE_LEVEL_IW5", "1")); + break; + default: + assert(false); + break; + } + + m_open_streams.emplace_back(std::move(defines)); } -void MenuFileReader::SetupStreamProxies() -{ - m_open_streams.emplace_back(std::make_unique(m_open_streams.back().get())); - m_open_streams.emplace_back(std::make_unique(m_open_streams.back().get())); - SetupDefinesProxy(); +void MenuFileReader::SetupStreamProxies() { + m_open_streams.emplace_back(std::make_unique(m_open_streams.back().get())); + m_open_streams.emplace_back(std::make_unique(m_open_streams.back().get())); + SetupDefinesProxy(); - m_stream = m_open_streams.back().get(); + m_stream = m_open_streams.back().get(); } -bool MenuFileReader::IsValidEndState(const MenuFileParserState* state) const -{ - if (state->m_current_item) - { - std::cerr << "In \"" << m_file_name << "\": Unclosed item at end of file!\n"; - return false; - } - - if (state->m_current_menu) - { - std::cerr << "In \"" << m_file_name << "\": Unclosed menu at end of file!\n"; - return false; - } - - if (state->m_current_function) - { - std::cerr << "In \"" << m_file_name << "\": Unclosed function at end of file!\n"; - return false; - } - - if (state->m_in_global_scope) - { - std::cerr << "In \"" << m_file_name << "\": Did not close global scope!\n"; - return false; - } - - return true; -} +bool MenuFileReader::IsValidEndState(const MenuFileParserState *state) const { + if (state->m_current_item) { + std::cerr << "In \"" << m_file_name << "\": Unclosed item at end of file!\n"; + return false; + } -std::unique_ptr MenuFileReader::CreateParsingResult(MenuFileParserState* state) const -{ - auto result = std::make_unique(); - result->m_menus = std::move(state->m_menus); - result->m_functions = std::move(state->m_functions); - result->m_menus_to_load = std::move(state->m_menus_to_load); + if (state->m_current_menu) { + std::cerr << "In \"" << m_file_name << "\": Unclosed menu at end of file!\n"; + return false; + } - return result; -} + if (state->m_current_function) { + std::cerr << "In \"" << m_file_name << "\": Unclosed function at end of file!\n"; + return false; + } -void MenuFileReader::IncludeZoneState(const MenuAssetZoneState* zoneState) -{ - m_zone_state = zoneState; + if (state->m_in_global_scope) { + std::cerr << "In \"" << m_file_name << "\": Did not close global scope!\n"; + return false; + } + + return true; } -void MenuFileReader::SetPermissiveMode(const bool usePermissiveMode) -{ - m_permissive_mode = usePermissiveMode; +std::unique_ptr MenuFileReader::CreateParsingResult(MenuFileParserState *state) const { + auto result = std::make_unique(); + result->m_menus = std::move(state->m_menus); + result->m_functions = std::move(state->m_functions); + result->m_menus_to_load = std::move(state->m_menus_to_load); + + return result; } -std::unique_ptr MenuFileReader::ReadMenuFile() -{ - SimpleLexer::Config lexerConfig; - lexerConfig.m_emit_new_line_tokens = false; - lexerConfig.m_read_strings = true; - lexerConfig.m_string_escape_sequences = true; - lexerConfig.m_read_integer_numbers = true; - lexerConfig.m_read_floating_point_numbers = true; - MenuExpressionMatchers().ApplyTokensToLexerConfig(lexerConfig); - - const auto lexer = std::make_unique(m_stream, std::move(lexerConfig)); - const auto parser = std::make_unique(lexer.get(), m_feature_level, m_permissive_mode, m_zone_state); - - if (!parser->Parse()) - { - std::cerr << "Parsing menu file failed!" << std::endl; - - const auto* parserEndState = parser->GetState(); - if(parserEndState->m_current_event_handler_set && !parserEndState->m_permissive_mode) - std::cerr << "You can use the --menu-permissive option to try to compile the event handler script anyway." << std::endl; - return nullptr; - } - - auto* parserEndState = parser->GetState(); - if (!IsValidEndState(parserEndState)) - return nullptr; - - return CreateParsingResult(parserEndState); +void MenuFileReader::IncludeZoneState(const MenuAssetZoneState *zoneState) { m_zone_state = zoneState; } + +void MenuFileReader::SetPermissiveMode(const bool usePermissiveMode) { m_permissive_mode = usePermissiveMode; } + +std::unique_ptr MenuFileReader::ReadMenuFile() { + SimpleLexer::Config lexerConfig; + lexerConfig.m_emit_new_line_tokens = false; + lexerConfig.m_read_strings = true; + lexerConfig.m_string_escape_sequences = true; + lexerConfig.m_read_integer_numbers = true; + lexerConfig.m_read_floating_point_numbers = true; + MenuExpressionMatchers().ApplyTokensToLexerConfig(lexerConfig); + + const auto lexer = std::make_unique(m_stream, std::move(lexerConfig)); + const auto parser = std::make_unique(lexer.get(), m_feature_level, m_permissive_mode, m_zone_state); + + if (!parser->Parse()) { + std::cerr << "Parsing menu file failed!" << std::endl; + + const auto *parserEndState = parser->GetState(); + if (parserEndState->m_current_event_handler_set && !parserEndState->m_permissive_mode) + std::cerr << "You can use the --menu-permissive option to try to compile the event handler script anyway." << std::endl; + return nullptr; + } + + auto *parserEndState = parser->GetState(); + if (!IsValidEndState(parserEndState)) + return nullptr; + + return CreateParsingResult(parserEndState); } diff --git a/src/ObjLoading/Parsing/Menu/MenuFileReader.h b/src/ObjLoading/Parsing/Menu/MenuFileReader.h index 990e5c31f..bbbe89a92 100644 --- a/src/ObjLoading/Parsing/Menu/MenuFileReader.h +++ b/src/ObjLoading/Parsing/Menu/MenuFileReader.h @@ -4,43 +4,41 @@ #include #include -#include "MenuFileParserState.h" #include "Domain/MenuFeatureLevel.h" #include "Domain/MenuParsingResult.h" -#include "Parsing/IParserLineStream.h" #include "MenuAssetZoneState.h" +#include "MenuFileParserState.h" +#include "Parsing/IParserLineStream.h" -namespace menu -{ - class MenuFileReader - { - public: - using include_callback_t = std::function(const std::string& filename, const std::string& sourceFile)>; +namespace menu { +class MenuFileReader { +public: + using include_callback_t = std::function(const std::string &filename, const std::string &sourceFile)>; - private: - const FeatureLevel m_feature_level; - const std::string m_file_name; +private: + const FeatureLevel m_feature_level; + const std::string m_file_name; - IParserLineStream* m_stream; - std::vector> m_open_streams; + IParserLineStream *m_stream; + std::vector> m_open_streams; - const MenuAssetZoneState* m_zone_state; - bool m_permissive_mode; + const MenuAssetZoneState *m_zone_state; + bool m_permissive_mode; - bool OpenBaseStream(std::istream& stream, include_callback_t includeCallback); - void SetupDefinesProxy(); - void SetupStreamProxies(); + bool OpenBaseStream(std::istream &stream, include_callback_t includeCallback); + void SetupDefinesProxy(); + void SetupStreamProxies(); - bool IsValidEndState(const MenuFileParserState* state) const; - std::unique_ptr CreateParsingResult(MenuFileParserState* state) const; + bool IsValidEndState(const MenuFileParserState *state) const; + std::unique_ptr CreateParsingResult(MenuFileParserState *state) const; - public: - MenuFileReader(std::istream& stream, std::string fileName, FeatureLevel featureLevel); - MenuFileReader(std::istream& stream, std::string fileName, FeatureLevel featureLevel, include_callback_t includeCallback); +public: + MenuFileReader(std::istream &stream, std::string fileName, FeatureLevel featureLevel); + MenuFileReader(std::istream &stream, std::string fileName, FeatureLevel featureLevel, include_callback_t includeCallback); - void IncludeZoneState(const MenuAssetZoneState* zoneState); - void SetPermissiveMode(bool usePermissiveMode); + void IncludeZoneState(const MenuAssetZoneState *zoneState); + void SetPermissiveMode(bool usePermissiveMode); - std::unique_ptr ReadMenuFile(); - }; -} + std::unique_ptr ReadMenuFile(); +}; +} // namespace menu diff --git a/src/ObjLoading/Parsing/Menu/Sequence/EventHandlerSetScopeSequences.cpp b/src/ObjLoading/Parsing/Menu/Sequence/EventHandlerSetScopeSequences.cpp index f4ee4011d..608623c07 100644 --- a/src/ObjLoading/Parsing/Menu/Sequence/EventHandlerSetScopeSequences.cpp +++ b/src/ObjLoading/Parsing/Menu/Sequence/EventHandlerSetScopeSequences.cpp @@ -1,8 +1,8 @@ #include "EventHandlerSetScopeSequences.h" -#include -#include #include +#include +#include #include "Generic/GenericStringPropertySequence.h" #include "Parsing/Menu/Domain/EventHandler/CommonEventHandlerScript.h" @@ -14,1293 +14,1093 @@ using namespace menu; -namespace menu -{ - enum class ExpectedScriptToken - { - NUMERIC, - INT, - TEXT - }; - - class ScriptMatcherFactory final : public MenuMatcherFactory - { - public: - explicit ScriptMatcherFactory(const IMatcherForLabelSupplier* labelSupplier) - : MenuMatcherFactory(labelSupplier) - { - } - - _NODISCARD MatcherFactoryWrapper ScriptStrictNumeric() const - { - return And({ - MatcherFactoryWrapper(std::make_unique()).Transform([](const token_list_t& tokens)-> SimpleParserValue - { - const auto& firstToken = tokens[0].get(); - - if (firstToken.m_type == SimpleParserValueType::CHARACTER) - { - const auto& secondToken = tokens[1].get(); - if (secondToken.m_type == SimpleParserValueType::INTEGER) - return SimpleParserValue::String(firstToken.GetPos(), new std::string(std::to_string(-secondToken.IntegerValue()))); - - std::ostringstream ss; - ss << std::noshowpoint << -firstToken.FloatingPointValue(); - return SimpleParserValue::String(firstToken.GetPos(), new std::string(ss.str())); - } - - if (firstToken.m_type == SimpleParserValueType::INTEGER) - return SimpleParserValue::String(firstToken.GetPos(), new std::string(std::to_string(firstToken.IntegerValue()))); - if (firstToken.m_type == SimpleParserValueType::FLOATING_POINT) - { - std::ostringstream ss; - ss << std::noshowpoint << firstToken.FloatingPointValue(); - return SimpleParserValue::String(firstToken.GetPos(), new std::string(ss.str())); - } - return SimpleParserValue::String(firstToken.GetPos(), new std::string(firstToken.StringValue())); - }) - }); - } - - _NODISCARD MatcherFactoryWrapper ScriptNumeric() const - { - return Or({ - ScriptStrictNumeric(), - Or({ - Type(SimpleParserValueType::CHARACTER), - Type(SimpleParserValueType::STRING), - Type(SimpleParserValueType::IDENTIFIER), - }).Transform([](const token_list_t& tokens) -> SimpleParserValue - { - return SimpleParserValue::Integer(tokens[0].get().GetPos(), static_cast(ExpectedScriptToken::NUMERIC)); - }) - }); - } - - _NODISCARD MatcherFactoryWrapper ScriptStrictInt() const - { - return And({ - MatcherFactoryWrapper(std::make_unique()).Transform([](const token_list_t& tokens)-> SimpleParserValue - { - const auto& firstToken = tokens[0].get(); - - if (firstToken.m_type == SimpleParserValueType::CHARACTER) - return SimpleParserValue::String(firstToken.GetPos(), new std::string(std::to_string(-tokens[1].get().IntegerValue()))); - - if (firstToken.m_type == SimpleParserValueType::INTEGER) - return SimpleParserValue::String(firstToken.GetPos(), new std::string(std::to_string(firstToken.IntegerValue()))); - return SimpleParserValue::String(firstToken.GetPos(), new std::string(firstToken.StringValue())); - }) - }); - } - - _NODISCARD MatcherFactoryWrapper ScriptChar(const char c) const - { - return Or({ - Char(c), - Or({ - Type(SimpleParserValueType::INTEGER), - Type(SimpleParserValueType::FLOATING_POINT), - Type(SimpleParserValueType::STRING), - Type(SimpleParserValueType::IDENTIFIER), - }).Transform([](const token_list_t& tokens) -> SimpleParserValue - { - return SimpleParserValue::Integer(tokens[0].get().GetPos(), static_cast(ExpectedScriptToken::INT)); - }) - }); - } - - _NODISCARD MatcherFactoryWrapper ScriptInt() const - { - return Or({ - ScriptStrictInt(), - Or({ - Type(SimpleParserValueType::CHARACTER), - Type(SimpleParserValueType::FLOATING_POINT), - Type(SimpleParserValueType::STRING), - Type(SimpleParserValueType::IDENTIFIER), - }).Transform([](const token_list_t& tokens) -> SimpleParserValue - { - return SimpleParserValue::Integer(tokens[0].get().GetPos(), static_cast(ExpectedScriptToken::INT)); - }) - }); - } - - _NODISCARD MatcherFactoryWrapper ScriptText() const - { - return Or({ - Type(SimpleParserValueType::STRING), - Type(SimpleParserValueType::IDENTIFIER), - Or({ - Type(SimpleParserValueType::CHARACTER), - Type(SimpleParserValueType::FLOATING_POINT), - Type(SimpleParserValueType::INTEGER), - }).Transform([](const token_list_t& tokens) -> SimpleParserValue - { - return SimpleParserValue::Integer(tokens[0].get().GetPos(), static_cast(ExpectedScriptToken::TEXT)); - }) - }); - } - - _NODISCARD MatcherFactoryWrapper ScriptKeyword(std::string keyword) const - { - return KeywordIgnoreCase(std::move(keyword)); - } - - _NODISCARD MatcherFactoryWrapper ScriptColor() const - { - return And({ - ScriptStrictNumeric(), - Optional(ScriptStrictNumeric()), - Optional(ScriptStrictNumeric()), - Optional(ScriptStrictNumeric()) - }); - } - - _NODISCARD MatcherFactoryWrapper ScriptLocalVarIntOrLiteral() const - { - return Or({ - And({ - ScriptKeyword("localVarInt"), - Char('('), - ScriptText(), - Char(')'), - }), - ScriptStrictInt(), - }); - } - - _NODISCARD MatcherFactoryWrapper ScriptLocalVarBoolOrLiteral() const - { - return Or({ - And({ - ScriptKeyword("localVarBool"), - Char('('), - ScriptText(), - Char(')'), - }), - ScriptStrictInt(), - }); - } - }; -} +namespace menu { +enum class ExpectedScriptToken { NUMERIC, INT, TEXT }; + +class ScriptMatcherFactory final : public MenuMatcherFactory { +public: + explicit ScriptMatcherFactory(const IMatcherForLabelSupplier *labelSupplier) : MenuMatcherFactory(labelSupplier) {} + + _NODISCARD MatcherFactoryWrapper ScriptStrictNumeric() const { + return And( + {MatcherFactoryWrapper(std::make_unique()).Transform([](const token_list_t &tokens) -> SimpleParserValue { + const auto &firstToken = tokens[0].get(); + + if (firstToken.m_type == SimpleParserValueType::CHARACTER) { + const auto &secondToken = tokens[1].get(); + if (secondToken.m_type == SimpleParserValueType::INTEGER) + return SimpleParserValue::String(firstToken.GetPos(), new std::string(std::to_string(-secondToken.IntegerValue()))); + + std::ostringstream ss; + ss << std::noshowpoint << -firstToken.FloatingPointValue(); + return SimpleParserValue::String(firstToken.GetPos(), new std::string(ss.str())); + } + + if (firstToken.m_type == SimpleParserValueType::INTEGER) + return SimpleParserValue::String(firstToken.GetPos(), new std::string(std::to_string(firstToken.IntegerValue()))); + if (firstToken.m_type == SimpleParserValueType::FLOATING_POINT) { + std::ostringstream ss; + ss << std::noshowpoint << firstToken.FloatingPointValue(); + return SimpleParserValue::String(firstToken.GetPos(), new std::string(ss.str())); + } + return SimpleParserValue::String(firstToken.GetPos(), new std::string(firstToken.StringValue())); + })}); + } + + _NODISCARD MatcherFactoryWrapper ScriptNumeric() const { + return Or({ScriptStrictNumeric(), Or({ + Type(SimpleParserValueType::CHARACTER), + Type(SimpleParserValueType::STRING), + Type(SimpleParserValueType::IDENTIFIER), + }) + .Transform([](const token_list_t &tokens) -> SimpleParserValue { + return SimpleParserValue::Integer(tokens[0].get().GetPos(), static_cast(ExpectedScriptToken::NUMERIC)); + })}); + } + + _NODISCARD MatcherFactoryWrapper ScriptStrictInt() const { + return And( + {MatcherFactoryWrapper(std::make_unique()).Transform([](const token_list_t &tokens) -> SimpleParserValue { + const auto &firstToken = tokens[0].get(); + + if (firstToken.m_type == SimpleParserValueType::CHARACTER) + return SimpleParserValue::String(firstToken.GetPos(), new std::string(std::to_string(-tokens[1].get().IntegerValue()))); + + if (firstToken.m_type == SimpleParserValueType::INTEGER) + return SimpleParserValue::String(firstToken.GetPos(), new std::string(std::to_string(firstToken.IntegerValue()))); + return SimpleParserValue::String(firstToken.GetPos(), new std::string(firstToken.StringValue())); + })}); + } + + _NODISCARD MatcherFactoryWrapper ScriptChar(const char c) const { + return Or({Char(c), Or({ + Type(SimpleParserValueType::INTEGER), + Type(SimpleParserValueType::FLOATING_POINT), + Type(SimpleParserValueType::STRING), + Type(SimpleParserValueType::IDENTIFIER), + }) + .Transform([](const token_list_t &tokens) -> SimpleParserValue { + return SimpleParserValue::Integer(tokens[0].get().GetPos(), static_cast(ExpectedScriptToken::INT)); + })}); + } + + _NODISCARD MatcherFactoryWrapper ScriptInt() const { + return Or({ScriptStrictInt(), Or({ + Type(SimpleParserValueType::CHARACTER), + Type(SimpleParserValueType::FLOATING_POINT), + Type(SimpleParserValueType::STRING), + Type(SimpleParserValueType::IDENTIFIER), + }) + .Transform([](const token_list_t &tokens) -> SimpleParserValue { + return SimpleParserValue::Integer(tokens[0].get().GetPos(), static_cast(ExpectedScriptToken::INT)); + })}); + } + + _NODISCARD MatcherFactoryWrapper ScriptText() const { + return Or({Type(SimpleParserValueType::STRING), Type(SimpleParserValueType::IDENTIFIER), + Or({ + Type(SimpleParserValueType::CHARACTER), + Type(SimpleParserValueType::FLOATING_POINT), + Type(SimpleParserValueType::INTEGER), + }) + .Transform([](const token_list_t &tokens) -> SimpleParserValue { + return SimpleParserValue::Integer(tokens[0].get().GetPos(), static_cast(ExpectedScriptToken::TEXT)); + })}); + } + + _NODISCARD MatcherFactoryWrapper ScriptKeyword(std::string keyword) const { return KeywordIgnoreCase(std::move(keyword)); } + + _NODISCARD MatcherFactoryWrapper ScriptColor() const { + return And({ScriptStrictNumeric(), Optional(ScriptStrictNumeric()), Optional(ScriptStrictNumeric()), Optional(ScriptStrictNumeric())}); + } + + _NODISCARD MatcherFactoryWrapper ScriptLocalVarIntOrLiteral() const { + return Or({ + And({ + ScriptKeyword("localVarInt"), + Char('('), + ScriptText(), + Char(')'), + }), + ScriptStrictInt(), + }); + } + + _NODISCARD MatcherFactoryWrapper ScriptLocalVarBoolOrLiteral() const { + return Or({ + And({ + ScriptKeyword("localVarBool"), + Char('('), + ScriptText(), + Char(')'), + }), + ScriptStrictInt(), + }); + } +}; +} // namespace menu + +namespace menu::event_handler_set_scope_sequences { +class SequenceCloseBlock final : public MenuFileParser::sequence_t { + static constexpr auto CAPTURE_TOKEN = 1; + +public: + SequenceCloseBlock() { + const MenuMatcherFactory create(this); + + AddMatchers({create.Char('}')}); + } + +protected: + void ProcessMatch(MenuFileParserState *state, SequenceResult &result) const override { + auto remainingScript = state->m_current_script.str(); + if (!remainingScript.empty()) + state->m_current_nested_event_handler_set->m_elements.emplace_back(std::make_unique(std::move(remainingScript))); + state->m_current_script.str(std::string()); + + bool conditionWasAutoSkip; + + do { + conditionWasAutoSkip = false; + if (!state->m_condition_stack.empty()) { + conditionWasAutoSkip = state->m_condition_stack.top().m_auto_skip; + state->m_condition_stack.pop(); + + if (!state->m_condition_stack.empty()) { + const auto &newConditionState = state->m_condition_stack.top(); + if (newConditionState.m_in_condition_elements) + state->m_current_nested_event_handler_set = newConditionState.m_condition->m_condition_elements.get(); + else + state->m_current_nested_event_handler_set = newConditionState.m_condition->m_else_elements.get(); + } else + state->m_current_nested_event_handler_set = state->m_current_event_handler_set; + } else { + state->m_current_event_handler_set = nullptr; + state->m_current_nested_event_handler_set = nullptr; + } + } while (conditionWasAutoSkip); + } +}; + +class SequenceSkipEmptyStatements final : public MenuFileParser::sequence_t { +public: + SequenceSkipEmptyStatements() { + const MenuMatcherFactory create(this); + + AddMatchers({create.Char(';')}); + } + +protected: + void ProcessMatch(MenuFileParserState *state, SequenceResult &result) const override { + if (!state->m_current_script_statement_terminated) { + state->m_current_script << "; "; + state->m_current_script_statement_terminated = true; + } + } +}; + +class SequenceSkipScriptToken final : public MenuFileParser::sequence_t { + static constexpr auto CAPTURE_SCRIPT_TOKEN = 1; + +public: + SequenceSkipScriptToken() { + const ScriptMatcherFactory create(this); + + AddMatchers({create + .Or({ + create.Numeric(), + create.String(), + create.Identifier(), + create.Type(SimpleParserValueType::CHARACTER), + }) + .Capture(CAPTURE_SCRIPT_TOKEN)}); + } + +protected: + void ProcessMatch(MenuFileParserState *state, SequenceResult &result) const override { + const auto &capture = result.NextCapture(CAPTURE_SCRIPT_TOKEN); + + switch (capture.m_type) { + case SimpleParserValueType::STRING: + state->m_current_script << "\"" << capture.StringValue() << "\" "; + break; + + case SimpleParserValueType::IDENTIFIER: + state->m_current_script << "\"" << capture.IdentifierValue() << "\" "; + break; + + case SimpleParserValueType::INTEGER: + state->m_current_script << "\"" << capture.IntegerValue() << "\" "; + break; + + case SimpleParserValueType::CHARACTER: + state->m_current_script << capture.CharacterValue() << " "; + break; + + case SimpleParserValueType::FLOATING_POINT: + state->m_current_script << "\"" << capture.FloatingPointValue() << "\" "; + break; + + default: + throw ParsingException(capture.GetPos(), "Invalid script token type for skipping"); + } -namespace menu::event_handler_set_scope_sequences -{ - class SequenceCloseBlock final : public MenuFileParser::sequence_t - { - static constexpr auto CAPTURE_TOKEN = 1; - - public: - SequenceCloseBlock() - { - const MenuMatcherFactory create(this); - - AddMatchers({ - create.Char('}') - }); - } - - protected: - void ProcessMatch(MenuFileParserState* state, SequenceResult& result) const override - { - auto remainingScript = state->m_current_script.str(); - if (!remainingScript.empty()) - state->m_current_nested_event_handler_set->m_elements.emplace_back(std::make_unique(std::move(remainingScript))); - state->m_current_script.str(std::string()); - - bool conditionWasAutoSkip; - - do - { - conditionWasAutoSkip = false; - if (!state->m_condition_stack.empty()) - { - conditionWasAutoSkip = state->m_condition_stack.top().m_auto_skip; - state->m_condition_stack.pop(); - - if (!state->m_condition_stack.empty()) - { - const auto& newConditionState = state->m_condition_stack.top(); - if (newConditionState.m_in_condition_elements) - state->m_current_nested_event_handler_set = newConditionState.m_condition->m_condition_elements.get(); - else - state->m_current_nested_event_handler_set = newConditionState.m_condition->m_else_elements.get(); - } - else - state->m_current_nested_event_handler_set = state->m_current_event_handler_set; - } - else - { - state->m_current_event_handler_set = nullptr; - state->m_current_nested_event_handler_set = nullptr; - } - } - while (conditionWasAutoSkip); - } - }; - - class SequenceSkipEmptyStatements final : public MenuFileParser::sequence_t - { - public: - SequenceSkipEmptyStatements() - { - const MenuMatcherFactory create(this); - - AddMatchers({ - create.Char(';') - }); - } - - protected: - void ProcessMatch(MenuFileParserState* state, SequenceResult& result) const override - { - if (!state->m_current_script_statement_terminated) - { - state->m_current_script << "; "; - state->m_current_script_statement_terminated = true; - } - } - }; - - class SequenceSkipScriptToken final : public MenuFileParser::sequence_t - { - static constexpr auto CAPTURE_SCRIPT_TOKEN = 1; - - public: - SequenceSkipScriptToken() - { - const ScriptMatcherFactory create(this); - - AddMatchers({ - create.Or({ - create.Numeric(), - create.String(), - create.Identifier(), - create.Type(SimpleParserValueType::CHARACTER), - }).Capture(CAPTURE_SCRIPT_TOKEN) - }); - } - - protected: - void ProcessMatch(MenuFileParserState* state, SequenceResult& result) const override - { - const auto& capture = result.NextCapture(CAPTURE_SCRIPT_TOKEN); - - switch (capture.m_type) - { - case SimpleParserValueType::STRING: - state->m_current_script << "\"" << capture.StringValue() << "\" "; - break; - - case SimpleParserValueType::IDENTIFIER: - state->m_current_script << "\"" << capture.IdentifierValue() << "\" "; - break; - - case SimpleParserValueType::INTEGER: - state->m_current_script << "\"" << capture.IntegerValue() << "\" "; - break; - - case SimpleParserValueType::CHARACTER: - state->m_current_script << capture.CharacterValue() << " "; - break; - - case SimpleParserValueType::FLOATING_POINT: - state->m_current_script << "\"" << capture.FloatingPointValue() << "\" "; - break; - - default: - throw ParsingException(capture.GetPos(), "Invalid script token type for skipping"); - } - - state->m_current_script_statement_terminated = false; - } - }; - - class SequenceGenericScriptStatement : public MenuFileParser::sequence_t - { - protected: - static constexpr auto CAPTURE_SCRIPT_TOKEN = 1; - - SequenceGenericScriptStatement() = default; - - public: - explicit SequenceGenericScriptStatement(std::initializer_list>>> matchers) - { - const MenuMatcherFactory create(this); - - AddMatchers({ - create.And(matchers).Capture(CAPTURE_SCRIPT_TOKEN), - create.Optional(create.Char(';')) - }); - } - - static std::unique_ptr Create(std::initializer_list>>> matchers) - { - return std::make_unique(matchers); - } - - private: - static std::string ScriptTokenTypeToString(int tokenType) - { - switch (static_cast(tokenType)) - { - case ExpectedScriptToken::INT: - return "INT"; - - case ExpectedScriptToken::NUMERIC: - return "NUMERIC"; - - case ExpectedScriptToken::TEXT: - return "TEXT"; - - default: - return "UNKNOWN"; - } - } - - protected: - void ProcessMatch(MenuFileParserState* state, SequenceResult& result) const override - { - while (result.HasNextCapture(CAPTURE_SCRIPT_TOKEN)) - { - const auto& capture = result.NextCapture(CAPTURE_SCRIPT_TOKEN); - - if (capture.m_type == SimpleParserValueType::IDENTIFIER) - { - state->m_current_script << "\"" << capture.IdentifierValue() << "\" "; - } - else if (capture.m_type == SimpleParserValueType::STRING) - { - state->m_current_script << "\"" << capture.StringValue() << "\" "; - } - else if (capture.m_type == SimpleParserValueType::CHARACTER) - { - state->m_current_script << capture.CharacterValue() << " "; - } - else if (capture.m_type == SimpleParserValueType::INTEGER) - { - std::ostringstream ss; - ss << "Invalid script token. Expected " << ScriptTokenTypeToString(capture.IntegerValue()) << "."; - - throw ParsingException(capture.GetPos(), ss.str()); - } - else - throw ParsingException(capture.GetPos(), "Invalid script capture"); - } - - state->m_current_script << "; "; - } - }; - - class SequenceUiScriptStatement final : public SequenceGenericScriptStatement - { - public: - explicit SequenceUiScriptStatement(std::initializer_list>>> matchers) - : SequenceGenericScriptStatement() - { - const ScriptMatcherFactory create(this); - - AddMatchers({ - create.And({ - create.ScriptKeyword("uiScript"), - create.And(matchers) - }).Capture(CAPTURE_SCRIPT_TOKEN), - create.Optional(create.Char(';')) - }); - } - - static std::unique_ptr Create(std::initializer_list>>> matchers) - { - return std::make_unique(matchers); - } - }; - - class AbstractSequenceWithPlayerData : public SequenceGenericScriptStatement - { - protected: - static constexpr auto LABEL_PLAYER_DATA_PATH_ELEMENT = 1; - - static std::unique_ptr PlayerDataPathMatchers(const ScriptMatcherFactory& create) - { - return create.Or({ - create.ScriptKeyword("false"), - create.ScriptKeyword("true"), - create.And({ - create.Or({ - create.ScriptKeyword("localvarstring"), - create.ScriptKeyword("localvarint"), - create.ScriptKeyword("localvarfloat"), - create.ScriptKeyword("localvarbool"), - }), - create.ScriptChar('('), - create.ScriptText(), - create.ScriptChar(')'), - }), - create.ScriptStrictInt(), - create.ScriptText() - }); - } - }; - - class SequenceSetPlayerData final : public AbstractSequenceWithPlayerData - { - public: - explicit SequenceSetPlayerData() - { - const ScriptMatcherFactory create(this); - - AddLabeledMatchers(PlayerDataPathMatchers(create), LABEL_PLAYER_DATA_PATH_ELEMENT); - AddMatchers({ - create.And({ - create.ScriptKeyword("setPlayerData"), - create.ScriptChar('('), - create.Label(LABEL_PLAYER_DATA_PATH_ELEMENT), - create.Loop(create.And({ - create.ScriptChar(','), - create.Label(LABEL_PLAYER_DATA_PATH_ELEMENT) - })), - create.ScriptChar(')'), - }).Capture(CAPTURE_SCRIPT_TOKEN), - create.Optional(create.Char(';')) - }); - } - }; - - class SequenceSetPlayerDataSplitscreen final : public AbstractSequenceWithPlayerData - { - public: - explicit SequenceSetPlayerDataSplitscreen() - { - const ScriptMatcherFactory create(this); - - AddLabeledMatchers(PlayerDataPathMatchers(create), LABEL_PLAYER_DATA_PATH_ELEMENT); - AddMatchers({ - create.And({ - create.ScriptKeyword("setPlayerDataSplitscreen"), - create.ScriptChar('('), - create.ScriptInt(), - create.ScriptChar(','), - create.Label(LABEL_PLAYER_DATA_PATH_ELEMENT), - create.Loop(create.And({ - create.ScriptChar(','), - create.Label(LABEL_PLAYER_DATA_PATH_ELEMENT) - })), - create.ScriptChar(')'), - }).Capture(CAPTURE_SCRIPT_TOKEN), - create.Optional(create.Char(';')) - }); - } - }; - - class SequenceLerp final : public SequenceGenericScriptStatement - { - public: - explicit SequenceLerp() - { - const ScriptMatcherFactory create(this); - - AddMatchers({ - create.And({ - create.ScriptKeyword("lerp"), - create.Or({ - create.ScriptKeyword("scale"), - create.ScriptKeyword("alpha"), - create.ScriptKeyword("x"), - create.ScriptKeyword("y"), - }), - create.ScriptKeyword("from"), - create.ScriptNumeric(), - create.ScriptKeyword("to"), - create.ScriptNumeric(), - create.ScriptKeyword("over"), - create.ScriptNumeric() - }).Capture(CAPTURE_SCRIPT_TOKEN), - create.Optional(create.Char(';')) - }); - } - }; - - class SequenceSetLocalVar final : public MenuFileParser::sequence_t - { - static constexpr auto TAG_BOOL = static_cast(SetLocalVarType::BOOL); - static constexpr auto TAG_INT = static_cast(SetLocalVarType::INT); - static constexpr auto TAG_FLOAT = static_cast(SetLocalVarType::FLOAT); - static constexpr auto TAG_STRING = static_cast(SetLocalVarType::STRING); - - static constexpr auto CAPTURE_VAR_NAME = 1; - - public: - SequenceSetLocalVar() - { - const ScriptMatcherFactory create(this); - const MenuExpressionMatchers expressionMatchers; - - AddLabeledMatchers(expressionMatchers.Expression(this), MenuExpressionMatchers::LABEL_EXPRESSION); - - AddMatchers({ - create.Or({ - create.ScriptKeyword("setLocalVarBool").Tag(TAG_BOOL), - create.ScriptKeyword("setLocalVarInt").Tag(TAG_INT), - create.ScriptKeyword("setLocalVarFloat").Tag(TAG_FLOAT), - create.ScriptKeyword("setLocalVarString").Tag(TAG_STRING) - }), - create.ScriptText().Capture(CAPTURE_VAR_NAME), - create.Label(MenuExpressionMatchers::LABEL_EXPRESSION), - create.Optional(create.Char(';')) - }); - } - - private: - static std::string ScriptKeywordForType(const SetLocalVarType type) - { - switch (type) - { - case SetLocalVarType::BOOL: - return "setLocalVarBool"; - case SetLocalVarType::INT: - return "setLocalVarInt"; - case SetLocalVarType::FLOAT: - return "setLocalVarFloat"; - case SetLocalVarType::STRING: - return "setLocalVarString"; - default: - return "unknown"; - } - } - - static void EmitStaticValue(MenuFileParserState* state, const SimpleExpressionValue& value) - { - switch (value.m_type) - { - case SimpleExpressionValue::Type::DOUBLE: - state->m_current_script << value.m_double_value; - break; - - case SimpleExpressionValue::Type::INT: - state->m_current_script << value.m_int_value; - break; - - case SimpleExpressionValue::Type::STRING: - state->m_current_script << *value.m_string_value; - break; - } - } - - static void CheckStaticValueType(const TokenPos& pos, const SetLocalVarType type, const SimpleExpressionValue& staticValue) - { - switch (type) - { - case SetLocalVarType::BOOL: - if (staticValue.m_type != SimpleExpressionValue::Type::INT) - throw ParsingException(pos, "Static value must be BOOL"); - break; - - case SetLocalVarType::INT: - if (staticValue.m_type != SimpleExpressionValue::Type::INT) - throw ParsingException(pos, "Static value must be INT"); - break; - - case SetLocalVarType::FLOAT: - if (staticValue.m_type != SimpleExpressionValue::Type::DOUBLE && staticValue.m_type != SimpleExpressionValue::Type::INT) - throw ParsingException(pos, "Static value must be FLOAT"); - break; - - case SetLocalVarType::STRING: - default: - break; - } - } - - static void EmitStaticSetLocalVar(MenuFileParserState* state, const TokenPos& pos, const SetLocalVarType type, const std::string& varName, std::unique_ptr expression) - { - state->m_current_script << "\"" << ScriptKeywordForType(type) << "\" \"" << varName << "\" \""; - const auto staticValue = expression->EvaluateStatic(); - CheckStaticValueType(pos, type, staticValue); - EmitStaticValue(state, staticValue); - state->m_current_script << "\" ; "; - } - - static void EmitDynamicSetLocalVar(MenuFileParserState* state, const SetLocalVarType type, const std::string& varName, std::unique_ptr expression) - { - auto remainingScript = state->m_current_script.str(); - if (!remainingScript.empty()) - state->m_current_nested_event_handler_set->m_elements.emplace_back(std::make_unique(std::move(remainingScript))); - state->m_current_script.str(std::string()); - - state->m_current_nested_event_handler_set->m_elements.emplace_back(std::make_unique(type, varName, std::move(expression))); - } - - protected: - void ProcessMatch(MenuFileParserState* state, SequenceResult& result) const override - { - const MenuExpressionMatchers expressionMatchers(state); - - const auto typeTag = static_cast(result.NextTag()); - const auto& varNameToken = result.NextCapture(CAPTURE_VAR_NAME); - const auto& varName = MenuMatcherFactory::TokenTextValue(varNameToken); - auto expression = expressionMatchers.ProcessExpression(result); - - if (!expression) - throw ParsingException(varNameToken.GetPos(), "No expression"); - - if (expression && expression->IsStatic()) - EmitStaticSetLocalVar(state, varNameToken.GetPos(), typeTag, varName, std::move(expression)); - else - EmitDynamicSetLocalVar(state, typeTag, varName, std::move(expression)); - } - }; - - class SequenceIf final : public MenuFileParser::sequence_t - { - static constexpr auto CAPTURE_KEYWORD = 1; - - public: - SequenceIf() - { - const ScriptMatcherFactory create(this); - const MenuExpressionMatchers expressionMatchers; - - AddLabeledMatchers(expressionMatchers.Expression(this), MenuExpressionMatchers::LABEL_EXPRESSION); - - AddMatchers({ - create.Keyword("if").Capture(CAPTURE_KEYWORD), - create.Char('('), - create.Label(MenuExpressionMatchers::LABEL_EXPRESSION), - create.Char(')'), - create.Char('{') - }); - } - - protected: - void ProcessMatch(MenuFileParserState* state, SequenceResult& result) const override - { - const MenuExpressionMatchers expressionMatchers(state); - auto expression = expressionMatchers.ProcessExpression(result); - - if (!expression) - throw ParsingException(result.NextCapture(CAPTURE_KEYWORD).GetPos(), "Could not parse expression"); - - auto remainingScript = state->m_current_script.str(); - if (!remainingScript.empty()) - state->m_current_nested_event_handler_set->m_elements.emplace_back(std::make_unique(std::move(remainingScript))); - state->m_current_script.str(std::string()); - - auto newCondition = std::make_unique(std::move(expression), std::make_unique(), nullptr); - auto* newConditionPtr = newCondition.get(); - state->m_current_nested_event_handler_set->m_elements.emplace_back(std::move(newCondition)); - - state->m_condition_stack.emplace(newConditionPtr); - state->m_current_nested_event_handler_set = newConditionPtr->m_condition_elements.get(); - } - }; - - class SequenceElseIf final : public MenuFileParser::sequence_t - { - static constexpr auto CAPTURE_KEYWORD = 1; - - public: - SequenceElseIf() - { - const ScriptMatcherFactory create(this); - const MenuExpressionMatchers expressionMatchers; - - AddLabeledMatchers(expressionMatchers.Expression(this), MenuExpressionMatchers::LABEL_EXPRESSION); - - AddMatchers({ - create.Char('}'), - create.Keyword("elseif").Capture(CAPTURE_KEYWORD), - create.Char('('), - create.Label(MenuExpressionMatchers::LABEL_EXPRESSION), - create.Char(')'), - create.Char('{') - }); - } - - protected: - void ProcessMatch(MenuFileParserState* state, SequenceResult& result) const override - { - const MenuExpressionMatchers expressionMatchers(state); - auto expression = expressionMatchers.ProcessExpression(result); - - if (!expression) - throw ParsingException(result.NextCapture(CAPTURE_KEYWORD).GetPos(), "Could not parse expression"); - - if (state->m_condition_stack.empty()) - throw ParsingException(result.NextCapture(CAPTURE_KEYWORD).GetPos(), "Not in an if statement"); - - auto remainingScript = state->m_current_script.str(); - if (!remainingScript.empty()) - state->m_current_nested_event_handler_set->m_elements.emplace_back(std::make_unique(std::move(remainingScript))); - state->m_current_script.str(std::string()); - - auto& currentCondition = state->m_condition_stack.top(); - - assert(currentCondition.m_in_condition_elements == (currentCondition.m_condition->m_else_elements == nullptr)); - if (!currentCondition.m_in_condition_elements) - throw ParsingException(result.NextCapture(CAPTURE_KEYWORD).GetPos(), "Cannot specify elseif after else"); - currentCondition.m_in_condition_elements = false; - - auto newCondition = std::make_unique(std::move(expression), std::make_unique(), nullptr); - auto* newConditionPtr = newCondition.get(); - currentCondition.m_condition->m_else_elements = std::make_unique(); - currentCondition.m_condition->m_else_elements->m_elements.emplace_back(std::move(newCondition)); - - state->m_condition_stack.emplace(newConditionPtr, true); - state->m_current_nested_event_handler_set = newConditionPtr->m_condition_elements.get(); - } - }; - - class SequenceElse final : public MenuFileParser::sequence_t - { - static constexpr auto CAPTURE_KEYWORD = 1; - - public: - SequenceElse() - { - const ScriptMatcherFactory create(this); - const MenuExpressionMatchers expressionMatchers; - - AddMatchers({ - create.Char('}'), - create.Keyword("else").Capture(CAPTURE_KEYWORD), - create.Char('{') - }); - } - - protected: - void ProcessMatch(MenuFileParserState* state, SequenceResult& result) const override - { - if (state->m_condition_stack.empty()) - throw ParsingException(result.NextCapture(CAPTURE_KEYWORD).GetPos(), "Not in an if statement"); - - auto& currentCondition = state->m_condition_stack.top(); - - assert(currentCondition.m_in_condition_elements == (currentCondition.m_condition->m_else_elements == nullptr)); - if (!currentCondition.m_in_condition_elements) - throw ParsingException(result.NextCapture(CAPTURE_KEYWORD).GetPos(), "Cannot specify second else block"); - - auto remainingScript = state->m_current_script.str(); - if (!remainingScript.empty()) - state->m_current_nested_event_handler_set->m_elements.emplace_back(std::make_unique(std::move(remainingScript))); - state->m_current_script.str(std::string()); - - currentCondition.m_in_condition_elements = false; - currentCondition.m_condition->m_else_elements = std::make_unique(); - state->m_current_nested_event_handler_set = currentCondition.m_condition->m_else_elements.get(); - } - }; - - class SequenceOnlineVault final : public SequenceGenericScriptStatement - { - static constexpr auto LABEL_OPEN = 1; - static constexpr auto LABEL_PARADIGM = 2; - static constexpr auto LABEL_PLATFORM = 3; - static constexpr auto LABEL_FILE_CATEGORY = 4; - - public: - explicit SequenceOnlineVault() - { - const ScriptMatcherFactory create(this); - - AddLabeledMatchers( - create.Or({ - create.ScriptKeyword("Browse"), - create.ScriptKeyword("Load"), - create.ScriptKeyword("Save"), - create.ScriptKeyword("Copy"), - }), LABEL_PARADIGM); - - AddLabeledMatchers( - create.Or({ - create.ScriptKeyword("Fb"), - create.ScriptKeyword("Elite"), - create.ScriptKeyword("Live"), - }), LABEL_PLATFORM); - - AddLabeledMatchers( - create.Or({ - create.ScriptKeyword("All"), - create.ScriptKeyword("Film"), - create.ScriptKeyword("Clip"), - create.ScriptKeyword("Screenshot"), - create.ScriptKeyword("Avi"), - create.ScriptKeyword("Cgm"), - create.ScriptKeyword("Rcu"), - }), LABEL_FILE_CATEGORY); - - AddLabeledMatchers( - create.And({ - create.ScriptKeyword("open"), - create.Label(LABEL_PARADIGM), - create.Optional(create.Label(LABEL_PLATFORM)), - create.Optional(create.Label(LABEL_FILE_CATEGORY)), - create.ScriptText() - }), LABEL_OPEN); - - AddMatchers({ - create.And({ - create.ScriptKeyword("uiScript"), - create.ScriptKeyword("OnlineVault"), - create.Or({ - create.Label(LABEL_OPEN), - create.ScriptKeyword("Pop"), - create.ScriptKeyword("CloseAll"), - create.ScriptKeyword("Load"), - create.ScriptKeyword("LoadAndRenderMovie"), - create.ScriptKeyword("TrySave"), - create.ScriptKeyword("Save"), - create.ScriptKeyword("Rename"), - create.ScriptKeyword("Delete"), - create.ScriptKeyword("Abort"), - create.ScriptKeyword("FacebookUploadPhoto"), - create.ScriptKeyword("FacebookUploadVideo"), - }) - }).Capture(CAPTURE_SCRIPT_TOKEN), - create.Optional(create.Char(';')) - }); - } - }; -} + state->m_current_script_statement_terminated = false; + } +}; -using namespace event_handler_set_scope_sequences; +class SequenceGenericScriptStatement : public MenuFileParser::sequence_t { +protected: + static constexpr auto CAPTURE_SCRIPT_TOKEN = 1; -EventHandlerSetScopeSequences::EventHandlerSetScopeSequences(std::vector>& allSequences, std::vector& scopeSequences) - : AbstractScopeSequenceHolder(allSequences, scopeSequences) -{ -} + SequenceGenericScriptStatement() = default; + +public: + explicit SequenceGenericScriptStatement(std::initializer_list>>> matchers) { + const MenuMatcherFactory create(this); + + AddMatchers({create.And(matchers).Capture(CAPTURE_SCRIPT_TOKEN), create.Optional(create.Char(';'))}); + } + + static std::unique_ptr Create(std::initializer_list>>> matchers) { + return std::make_unique(matchers); + } + +private: + static std::string ScriptTokenTypeToString(int tokenType) { + switch (static_cast(tokenType)) { + case ExpectedScriptToken::INT: + return "INT"; + + case ExpectedScriptToken::NUMERIC: + return "NUMERIC"; -void EventHandlerSetScopeSequences::AddSequences(const FeatureLevel featureLevel, const bool permissive) const -{ - AddSequence(std::make_unique()); - // If else and stuff - - // Creating factory with no label supplier. Cannot use labels with it. - const ScriptMatcherFactory create(nullptr); - - if (!permissive) - { - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("fadeIn"), create.ScriptText()})); // fadeIn - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("fadeOut"), create.ScriptText()})); // fadeOut - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("show"), create.ScriptText()})); // show - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("hide"), create.ScriptText()})); // hide - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("showMenu"), create.ScriptText()})); // showMenu - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("hideMenu"), create.ScriptText()})); // hideMenu - AddSequence(SequenceGenericScriptStatement::Create({ - create.ScriptKeyword("setColor"), - create.Or({create.ScriptKeyword("backColor"), create.ScriptKeyword("foreColor"), create.ScriptKeyword("borderColor")}), - create.ScriptColor() - })); // setColor ("backColor" | "foreColor" | "borderColor") [] [] [] - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("open"), create.ScriptText()})); // open - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("close"), create.ScriptText()})); // close ("self" | ) - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("escape"), create.ScriptText()})); // escape ("self" | ) - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("closeForAllPlayers"), create.ScriptText()})); // closeForAllPlayers - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("ingameOpen"), create.ScriptText()})); // ingameOpen - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("ingameClose"), create.ScriptText()})); // ingameClose - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("setBackground"), create.ScriptText()})); // setBackground - AddSequence(SequenceGenericScriptStatement::Create({ - create.ScriptKeyword("setItemColor"), - create.ScriptText(), - create.Or({create.ScriptKeyword("backColor"), create.ScriptKeyword("foreColor"), create.ScriptKeyword("borderColor"), create.ScriptKeyword("disableColor")}), - create.ScriptColor() - })); // setItemColor (backColor | foreColor | borderColor | disableColor) [] [] [] - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("focusFirst")})); - // setFocus game specific - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("setFocusByDvar"), create.ScriptText()})); // setFocusByDvar - // setDvar game specific - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("exec"), create.ScriptText()})); // exec - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("execNow"), create.ScriptText()})); // execNow - AddSequence(SequenceGenericScriptStatement::Create({ - create.ScriptKeyword("execOnDvarStringValue"), create.ScriptText(), create.ScriptText(), create.ScriptText() - })); // execOnDvarStringValue - AddSequence(SequenceGenericScriptStatement::Create({ - create.ScriptKeyword("execOnDvarIntValue"), create.ScriptText(), create.ScriptInt(), create.ScriptText() - })); // execOnDvarIntValue - AddSequence(SequenceGenericScriptStatement::Create({ - create.ScriptKeyword("execOnDvarFloatValue"), create.ScriptText(), create.ScriptNumeric(), create.ScriptText() - })); // execOnDvarFloatValue - AddSequence(SequenceGenericScriptStatement::Create({ - create.ScriptKeyword("execNowOnDvarStringValue"), create.ScriptText(), create.ScriptText(), create.ScriptText() - })); // execNowOnDvarStringValue - AddSequence(SequenceGenericScriptStatement::Create({ - create.ScriptKeyword("execNowOnDvarIntValue"), create.ScriptText(), create.ScriptInt(), create.ScriptText() - })); // execNowOnDvarIntValue - AddSequence(SequenceGenericScriptStatement::Create({ - create.ScriptKeyword("execNowOnDvarFloatValue"), create.ScriptText(), create.ScriptNumeric(), create.ScriptText() - })); // execNowOnDvarFloatValue - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("play"), create.ScriptText()})); // play - // scriptMenuResponse game specific - AddSequence(SequenceGenericScriptStatement::Create({ - create.ScriptKeyword("scriptMenuRespondOnDvarStringValue"), create.ScriptText(), create.ScriptText(), create.ScriptText() - })); // scriptMenuRespondOnDvarStringValue - AddSequence(SequenceGenericScriptStatement::Create({ - create.ScriptKeyword("scriptMenuRespondOnDvarIntValue"), create.ScriptText(), create.ScriptInt(), create.ScriptText() - })); // scriptMenuRespondOnDvarIntValue - AddSequence(SequenceGenericScriptStatement::Create({ - create.ScriptKeyword("scriptMenuRespondOnDvarFloatValue"), create.ScriptText(), create.ScriptNumeric(), create.ScriptText() - })); // scriptMenuRespondOnDvarFloatValue - AddSequence(std::make_unique()); - AddSequence(std::make_unique()); - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("resetStatsConfirm")})); - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("resetStatsCancel")})); - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("setGameMode"), create.ScriptText()})); // setGameMode - // feederTop / feederBottom game specific - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("showGamerCard")})); - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("openForGameType"), create.ScriptText()})); - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("closeForGameType"), create.ScriptText()})); - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("kickPlayer")})); - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("getKickPlayerQuestion")})); - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("partyUpdateMissingMapPackDvar")})); - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("togglePlayerMute")})); - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("resolveError")})); - AddSequence(std::make_unique()); - - // UiScripts - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("StartServer")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("loadArenas")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("loadGameInfo")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("clearError")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("Quit")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("Controls")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("Leave")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("closeingame")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("update"), create.ScriptText()})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("startSingleplayer")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("startMultiplayer")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("getLanguage")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("verifyLanguage")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("updateLanguage")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("mutePlayer")})); - AddSequence(SequenceUiScriptStatement::Create( - {create.ScriptKeyword("openMenuOnDvar"), create.ScriptText(), create.Or({create.ScriptStrictNumeric(), create.ScriptText()}), create.ScriptText()})); - AddSequence( - SequenceUiScriptStatement::Create({create.ScriptKeyword("openMenuOnDvarNot"), create.ScriptText(), create.Or({create.ScriptStrictNumeric(), create.ScriptText()}), create.ScriptText()})); - AddSequence(SequenceUiScriptStatement::Create({ - create.ScriptKeyword("closeMenuOnDvar"), create.ScriptText(), create.Or({create.ScriptStrictNumeric(), create.ScriptText()}), create.ScriptText() - })); - AddSequence(SequenceUiScriptStatement::Create( - {create.ScriptKeyword("closeMenuOnDvarNot"), create.ScriptText(), create.Or({create.ScriptStrictNumeric(), create.ScriptText()}), create.ScriptText()})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("setRecommended")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("clearLoadErrorsSummary")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("clearClientMatchData")})); - - if (featureLevel == FeatureLevel::IW4) - { - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("setFocus"), create.ScriptText()})); // setFocus - AddSequence(SequenceGenericScriptStatement::Create({ - create.ScriptKeyword("setDvar"), create.ScriptText(), create.Or({create.ScriptStrictNumeric(), create.ScriptText()}) - })); // setDvar - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("scriptMenuResponse"), create.ScriptText()})); // scriptMenuResponse - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("updateMail")})); - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("openMail")})); - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("deleteMail")})); - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("doMailLottery")})); - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("feederTop")})); - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("feederBottom")})); - // statClearPerkNew // TODO - // statSetUsingTable // TODO - // statClearBitMask // TODO - - - // IW4x UiScripts - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("LoadMods")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("RunMod")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("ClearMods")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("security_increase_cancel")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("mod_download_cancel")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("LoadFriends")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("JoinFriend")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("downloadDLC"), create.ScriptInt()})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("checkFirstLaunch")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("visitWebsite")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("visitWiki")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("visitDiscord")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("updateui_mousePitch")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("ServerStatus")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("UpdateFilter")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("RefreshFilter")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("RefreshServers")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("JoinServer")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("ServerSort"), create.ScriptInt()})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("CreateListFavorite")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("CreateFavorite")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("CreateCurrentServerFavorite")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("DeleteFavorite")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("nextStartupMessage")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("UpdateClasses")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("loadDemos")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("launchDemo")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("deleteDemo")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("ApplyMap")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("ApplyInitialMap")})); - } - - if (featureLevel == FeatureLevel::IW5) - { - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("forceClose"), create.ScriptText()})); // forceClose ("self" | ) - AddSequence(SequenceGenericScriptStatement::Create({ - create.ScriptKeyword("setFocus"), - create.Or({ - create.And({ - create.ScriptKeyword("localVarString"), - create.Char('('), - create.ScriptText(), - create.Char(')'), - }), - create.ScriptText() - }), - })); // setFocus ((localVarString '(' ')') | ) - AddSequence(SequenceGenericScriptStatement::Create({ - create.ScriptKeyword("setDvar"), - create.ScriptText(), - create.Or({ - create.And({ - create.ScriptKeyword("localVarString"), - create.Char('('), - create.ScriptText(), - create.Char(')'), - }), - create.ScriptStrictNumeric(), - create.ScriptText() - }), - })); // setDvar ((localVarString '(' ')') | ) - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("execFirstClient"), create.ScriptText()})); // execFirstClient - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("execKeyPress"), create.Or({create.ScriptStrictNumeric(), create.ScriptText()})})); // execKeyPress - AddSequence(SequenceGenericScriptStatement::Create({ - create.ScriptKeyword("scriptMenuResponse"), - create.Or({ - create.And({ - create.Or({ - create.ScriptKeyword("localVarInt"), - create.ScriptKeyword("localVarFloat"), - create.ScriptKeyword("localVarBool"), - create.ScriptKeyword("localVarString"), - }), - create.Char('('), - create.ScriptText(), - create.Char(')'), - }), - create.ScriptStrictInt(), - create.ScriptText(), - }), - })); // scriptMenuResponse (((localVarInt | localVarFloat | localVarBool | localVarString) '(' ')') | ) - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("deleteEliteCacFile")})); - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("integrateEliteCacFile")})); - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("setMatchRulesData")})); // unknown parameters - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("loadMatchRulesDataFromPlayer")})); // unknown parameters - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("saveMatchRulesDataToPlayer")})); // unknown parameters - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("loadMatchRulesDataFromHistory")})); // unknown parameters - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("loadMatchRulesDataDefaults")})); // unknown parameters - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("setUsingMatchRulesData")})); // unknown parameters - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("saveMatchRulesDedicatedServer")})); // unknown parameters - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("loadMatchRulesDedicatedServer")})); // unknown parameters - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("onlineVaultEditMetadata")})); // unknown parameters - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("includeInMapRotation")})); // unknown parameters - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("useCustomMapRotation")})); // unknown parameters - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("useIntermissionTimer")})); // unknown parameters - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("stopIntermissionTimer")})); // unknown parameters - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("feederTop"), create.Optional(create.Text())})); // feederTop [] - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("feederBottom"), create.Optional(create.Text())})); // feederBottom [] - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("feederPageUp"), create.Optional(create.Text())})); // feederPageUp [] - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("feederPageDown"), create.Optional(create.Text())})); // feederPageDown [] - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("showCoopGamerCard")})); // unknown parameters - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("showSplitscreenGamerCard")})); // unknown parameters - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("reportPlayerOffensive")})); - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("reportPlayerExploiting")})); - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("reportPlayerCheating")})); - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("reportPlayerBoosting")})); - AddSequence(SequenceGenericScriptStatement::Create({ - create.ScriptKeyword("setCardIcon"), create.Char('('), create.ScriptLocalVarIntOrLiteral(), create.Char(')') - })); // setCardIcon '(' ((localVarInt '(' ')') | ) ')' - AddSequence(SequenceGenericScriptStatement::Create({ - create.ScriptKeyword("setCardTitle"), create.Char('('), create.ScriptLocalVarIntOrLiteral(), create.Char(')') - })); // setCardTitle '(' ((localVarInt '(' ')') | ) ')' - AddSequence(SequenceGenericScriptStatement::Create({ - create.ScriptKeyword("setCardIconNew"), - create.Char('('), - create.ScriptLocalVarIntOrLiteral(), - create.Char(','), - create.Or({ - create.ScriptLocalVarIntOrLiteral(), - // This is wrong and the game does not even understand it. But because it's not a number it evaluates to 0... - // The game's menus do it and i don't want to fix it everywhere - create.ScriptKeyword("false"), - }), - create.Char(')') - })); // setCardIconNew '(' ((localVarInt '(' ')') | ) ',' ((localVarInt '(' ')') | ) ')' - AddSequence(SequenceGenericScriptStatement::Create({ - create.ScriptKeyword("setCardTitleNew"), - create.Char('('), - create.ScriptLocalVarIntOrLiteral(), - create.Char(','), - create.Or({ - create.ScriptLocalVarIntOrLiteral(), - // This is a hack (see setCardIconNew for details) - create.ScriptKeyword("false"), - }), - create.Char(')') - })); // setCardTitleNew '(' ((localVarInt '(' ')') | ) ',' ((localVarInt '(' ')') | ) ')' - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("setCardIconSplitScreen")})); // unknown - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("setCardTitleSplitScreen")})); // unknown - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("setCardIconNewSplitScreen")})); // unknown - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("setCardTitleNewSplitScreen")})); // unknown - AddSequence(SequenceGenericScriptStatement::Create({ - create.ScriptKeyword("purchasePrestigeTitle"), create.Char('('), create.ScriptText(), create.Char(')') - })); // purchasePrestigeTitle '(' ')' - AddSequence(SequenceGenericScriptStatement::Create({ - create.ScriptKeyword("setProfileItemNew"), create.Char('('), create.ScriptText(), create.Char(','), create.ScriptLocalVarIntOrLiteral(), create.Char(')') - })); // setProfileItemNew '(' <item name> ',' (0|1|(localVarInt '(' <var name> ')')) ')' - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("setProfileItemNewSplitScreen")})); // unknown - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("storePopupXuid")})); - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("getHostMigrateQuestion")})); - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("makeHost")})); - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("saveGameHide")})); // saveGameHide <item name> - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("saveGameShow")})); // saveGameShow <item name> - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("saveGameSetLocalBool"), create.ScriptText()})); // saveGameSetLocalBool <var name> - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("saveDelay")})); - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("writeSave")})); - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("setSaveExecOnSuccess"), create.ScriptText()})); // setSaveExecOnSuccess <command> - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("nextLevel")})); - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("disablePause")})); - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("enablePause")})); - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("runCompletionResolve")})); - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("clearCompletionResolve")})); - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("execWithResolve"), create.ScriptText()})); - AddSequence(SequenceGenericScriptStatement::Create({ - create.ScriptKeyword("playMenuVideo"), - create.Char('('), - create.ScriptText(), - create.Char(','), - create.ScriptLocalVarIntOrLiteral(), - create.Char(','), - create.ScriptLocalVarBoolOrLiteral(), - create.Char(')'), - })); // playMenuVideo '(' <video name> ',' ((localVarInt '(' <var name> ')') | <offset>) ',' ((localVarBool '(' <var name> ')') | <maybe looping bool>) ')' - AddSequence(SequenceGenericScriptStatement::Create({ - create.ScriptKeyword("setBackgroundVideo"), create.Char('('), create.ScriptText(), create.Char(')') - })); // setBackgroundVideo '(' <video name or empty string> ')' - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("clearEntitlementNew"), create.ScriptText()})); // clearEntitlementNew <entitlement name> - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("setPastTitleRank")})); // unknown - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("setPastTitlePrestige")})); // unknown - AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("anticheat_bancheck"), create.ScriptStrictNumeric()})); // anticheat_bancheck <num> - - // UiScripts - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("LoadSaveGames")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("LoadGame")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("SaveGame")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("ForceSave")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("DelSaveGame")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("SaveGameSort"), create.ScriptStrictInt()})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("playerStart")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("saveComplete")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("saveRevert")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("resetvscroll"), create.ScriptText()})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("RefreshLeaderboards")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("ViewGamerCard")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("OpenLeaderboard"), create.ScriptText()})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("OpenLeaderboardExt"), create.ScriptText(), create.Optional(create.Text())})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("ClearLeaderboard")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("FriendStoreXUID")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("FriendClearXUID")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("FriendInvite")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("FriendJoin")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("FriendGamerCard")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("FriendReportOffensive")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("FriendReportExploiter")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("FriendReportCheater")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("FriendReportBooster")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("RecentPlayerStoreXUID")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("RecentPlayerClearXUID")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("RecentPlayerGamerCard")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("RecentPlayerFriendRequest")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("RecentPlayerShowGroups")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("RecentPlayerJoin")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("RecentPlayerInvite")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("RecentPlayerReportOffensive")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("RecentPlayerReportExploiter")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("RecentPlayerReportCheater")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("RecentPlayerReportBooster")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("FacebookStoreXUID")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("FacebookClearXUID")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("FacebookGamerCard")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("FacebookFriendRequest")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("FacebookPageRight")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("FacebookPageLeft")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("FacebookJoin")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("FacebookInvite")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("FacebookReportOffensive")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("FacebookReportExploiter")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("FacebookReportCheater")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("FacebookReportBooster")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("EliteClanStoreXUID")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("EliteClanClearXUID")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("EliteClanGamerCard")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("EliteClanFriendRequest")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("EliteClanJoin")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("EliteClanInvite")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("EliteClanReportOffensive")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("EliteClanReportExploiter")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("EliteClanReportCheater")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("EliteClanReportBooster")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("coopPlayerShowGroups"), create.ScriptStrictInt()})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("simulateKeyPress"), create.ScriptStrictInt()})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("commerceShowStore")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("voteTypeMap")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("voteMap")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("voteGame")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("RefreshServers")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("RefreshFilter")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("closeJoin")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("StopRefresh")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("TrimRecipeName")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("ResetRecipeList")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("SelectServer")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("ShowCurrentServerTooltip")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("voteTempBan")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("addFavorite")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("deleteFavorite")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("PlayDemo")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("SwitchSegmentTransition"), create.ScriptStrictInt(), create.ScriptStrictInt()})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("PreviewSegment")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("MoveSegment"), create.ScriptStrictInt()})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("DeleteSegment")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("SetFocusOnSegmentButton")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("PopulateLocalDemoFileInformation")})); - AddSequence(std::make_unique<SequenceOnlineVault>()); - AddSequence(SequenceUiScriptStatement::Create({ - create.ScriptKeyword("Playlist"), - create.Or({ - create.And({ - create.ScriptKeyword("Open"), - create.ScriptStrictInt(), - }), - create.ScriptKeyword("DoAction"), - create.ScriptKeyword("Close"), - create.ScriptKeyword("CloseAll"), - }) - })); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("UpdateArenas")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("SortChallengesTop")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("xlaunchelitesearch")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("xlaunchelitelaunch")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("xlaunchelitestore")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("LobbyShowGroups")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("addPlayerProfiles")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("createPlayerProfile")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("deletePlayerProfile")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("loadPlayerProfile")})); - AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("selectActivePlayerProfile")})); - } + case ExpectedScriptToken::TEXT: + return "TEXT"; + + default: + return "UNKNOWN"; + } + } + +protected: + void ProcessMatch(MenuFileParserState *state, SequenceResult<SimpleParserValue> &result) const override { + while (result.HasNextCapture(CAPTURE_SCRIPT_TOKEN)) { + const auto &capture = result.NextCapture(CAPTURE_SCRIPT_TOKEN); + + if (capture.m_type == SimpleParserValueType::IDENTIFIER) { + state->m_current_script << "\"" << capture.IdentifierValue() << "\" "; + } else if (capture.m_type == SimpleParserValueType::STRING) { + state->m_current_script << "\"" << capture.StringValue() << "\" "; + } else if (capture.m_type == SimpleParserValueType::CHARACTER) { + state->m_current_script << capture.CharacterValue() << " "; + } else if (capture.m_type == SimpleParserValueType::INTEGER) { + std::ostringstream ss; + ss << "Invalid script token. Expected " << ScriptTokenTypeToString(capture.IntegerValue()) << "."; + + throw ParsingException(capture.GetPos(), ss.str()); + } else + throw ParsingException(capture.GetPos(), "Invalid script capture"); + } + + state->m_current_script << "; "; + } +}; + +class SequenceUiScriptStatement final : public SequenceGenericScriptStatement { +public: + explicit SequenceUiScriptStatement(std::initializer_list<Movable<std::unique_ptr<AbstractMatcher<SimpleParserValue>>>> matchers) + : SequenceGenericScriptStatement() { + const ScriptMatcherFactory create(this); + + AddMatchers({create.And({create.ScriptKeyword("uiScript"), create.And(matchers)}).Capture(CAPTURE_SCRIPT_TOKEN), create.Optional(create.Char(';'))}); + } + + static std::unique_ptr<SequenceUiScriptStatement> Create(std::initializer_list<Movable<std::unique_ptr<AbstractMatcher<SimpleParserValue>>>> matchers) { + return std::make_unique<SequenceUiScriptStatement>(matchers); + } +}; + +class AbstractSequenceWithPlayerData : public SequenceGenericScriptStatement { +protected: + static constexpr auto LABEL_PLAYER_DATA_PATH_ELEMENT = 1; + + static std::unique_ptr<matcher_t> PlayerDataPathMatchers(const ScriptMatcherFactory &create) { + return create.Or({create.ScriptKeyword("false"), create.ScriptKeyword("true"), + create.And({ + create.Or({ + create.ScriptKeyword("localvarstring"), + create.ScriptKeyword("localvarint"), + create.ScriptKeyword("localvarfloat"), + create.ScriptKeyword("localvarbool"), + }), + create.ScriptChar('('), + create.ScriptText(), + create.ScriptChar(')'), + }), + create.ScriptStrictInt(), create.ScriptText()}); + } +}; + +class SequenceSetPlayerData final : public AbstractSequenceWithPlayerData { +public: + explicit SequenceSetPlayerData() { + const ScriptMatcherFactory create(this); + + AddLabeledMatchers(PlayerDataPathMatchers(create), LABEL_PLAYER_DATA_PATH_ELEMENT); + AddMatchers({create + .And({ + create.ScriptKeyword("setPlayerData"), + create.ScriptChar('('), + create.Label(LABEL_PLAYER_DATA_PATH_ELEMENT), + create.Loop(create.And({create.ScriptChar(','), create.Label(LABEL_PLAYER_DATA_PATH_ELEMENT)})), + create.ScriptChar(')'), + }) + .Capture(CAPTURE_SCRIPT_TOKEN), + create.Optional(create.Char(';'))}); + } +}; + +class SequenceSetPlayerDataSplitscreen final : public AbstractSequenceWithPlayerData { +public: + explicit SequenceSetPlayerDataSplitscreen() { + const ScriptMatcherFactory create(this); + + AddLabeledMatchers(PlayerDataPathMatchers(create), LABEL_PLAYER_DATA_PATH_ELEMENT); + AddMatchers({create + .And({ + create.ScriptKeyword("setPlayerDataSplitscreen"), + create.ScriptChar('('), + create.ScriptInt(), + create.ScriptChar(','), + create.Label(LABEL_PLAYER_DATA_PATH_ELEMENT), + create.Loop(create.And({create.ScriptChar(','), create.Label(LABEL_PLAYER_DATA_PATH_ELEMENT)})), + create.ScriptChar(')'), + }) + .Capture(CAPTURE_SCRIPT_TOKEN), + create.Optional(create.Char(';'))}); + } +}; + +class SequenceLerp final : public SequenceGenericScriptStatement { +public: + explicit SequenceLerp() { + const ScriptMatcherFactory create(this); + + AddMatchers({create + .And({create.ScriptKeyword("lerp"), + create.Or({ + create.ScriptKeyword("scale"), + create.ScriptKeyword("alpha"), + create.ScriptKeyword("x"), + create.ScriptKeyword("y"), + }), + create.ScriptKeyword("from"), create.ScriptNumeric(), create.ScriptKeyword("to"), create.ScriptNumeric(), + create.ScriptKeyword("over"), create.ScriptNumeric()}) + .Capture(CAPTURE_SCRIPT_TOKEN), + create.Optional(create.Char(';'))}); + } +}; + +class SequenceSetLocalVar final : public MenuFileParser::sequence_t { + static constexpr auto TAG_BOOL = static_cast<int>(SetLocalVarType::BOOL); + static constexpr auto TAG_INT = static_cast<int>(SetLocalVarType::INT); + static constexpr auto TAG_FLOAT = static_cast<int>(SetLocalVarType::FLOAT); + static constexpr auto TAG_STRING = static_cast<int>(SetLocalVarType::STRING); + + static constexpr auto CAPTURE_VAR_NAME = 1; + +public: + SequenceSetLocalVar() { + const ScriptMatcherFactory create(this); + const MenuExpressionMatchers expressionMatchers; + + AddLabeledMatchers(expressionMatchers.Expression(this), MenuExpressionMatchers::LABEL_EXPRESSION); + + AddMatchers({create.Or({create.ScriptKeyword("setLocalVarBool").Tag(TAG_BOOL), create.ScriptKeyword("setLocalVarInt").Tag(TAG_INT), + create.ScriptKeyword("setLocalVarFloat").Tag(TAG_FLOAT), create.ScriptKeyword("setLocalVarString").Tag(TAG_STRING)}), + create.ScriptText().Capture(CAPTURE_VAR_NAME), create.Label(MenuExpressionMatchers::LABEL_EXPRESSION), create.Optional(create.Char(';'))}); + } + +private: + static std::string ScriptKeywordForType(const SetLocalVarType type) { + switch (type) { + case SetLocalVarType::BOOL: + return "setLocalVarBool"; + case SetLocalVarType::INT: + return "setLocalVarInt"; + case SetLocalVarType::FLOAT: + return "setLocalVarFloat"; + case SetLocalVarType::STRING: + return "setLocalVarString"; + default: + return "unknown"; + } + } + + static void EmitStaticValue(MenuFileParserState *state, const SimpleExpressionValue &value) { + switch (value.m_type) { + case SimpleExpressionValue::Type::DOUBLE: + state->m_current_script << value.m_double_value; + break; + + case SimpleExpressionValue::Type::INT: + state->m_current_script << value.m_int_value; + break; + + case SimpleExpressionValue::Type::STRING: + state->m_current_script << *value.m_string_value; + break; + } + } + + static void CheckStaticValueType(const TokenPos &pos, const SetLocalVarType type, const SimpleExpressionValue &staticValue) { + switch (type) { + case SetLocalVarType::BOOL: + if (staticValue.m_type != SimpleExpressionValue::Type::INT) + throw ParsingException(pos, "Static value must be BOOL"); + break; + + case SetLocalVarType::INT: + if (staticValue.m_type != SimpleExpressionValue::Type::INT) + throw ParsingException(pos, "Static value must be INT"); + break; + + case SetLocalVarType::FLOAT: + if (staticValue.m_type != SimpleExpressionValue::Type::DOUBLE && staticValue.m_type != SimpleExpressionValue::Type::INT) + throw ParsingException(pos, "Static value must be FLOAT"); + break; + + case SetLocalVarType::STRING: + default: + break; } + } + + static void EmitStaticSetLocalVar(MenuFileParserState *state, const TokenPos &pos, const SetLocalVarType type, const std::string &varName, + std::unique_ptr<ISimpleExpression> expression) { + state->m_current_script << "\"" << ScriptKeywordForType(type) << "\" \"" << varName << "\" \""; + const auto staticValue = expression->EvaluateStatic(); + CheckStaticValueType(pos, type, staticValue); + EmitStaticValue(state, staticValue); + state->m_current_script << "\" ; "; + } + + static void EmitDynamicSetLocalVar(MenuFileParserState *state, const SetLocalVarType type, const std::string &varName, + std::unique_ptr<ISimpleExpression> expression) { + auto remainingScript = state->m_current_script.str(); + if (!remainingScript.empty()) + state->m_current_nested_event_handler_set->m_elements.emplace_back(std::make_unique<CommonEventHandlerScript>(std::move(remainingScript))); + state->m_current_script.str(std::string()); + + state->m_current_nested_event_handler_set->m_elements.emplace_back(std::make_unique<CommonEventHandlerSetLocalVar>(type, varName, std::move(expression))); + } + +protected: + void ProcessMatch(MenuFileParserState *state, SequenceResult<SimpleParserValue> &result) const override { + const MenuExpressionMatchers expressionMatchers(state); + + const auto typeTag = static_cast<SetLocalVarType>(result.NextTag()); + const auto &varNameToken = result.NextCapture(CAPTURE_VAR_NAME); + const auto &varName = MenuMatcherFactory::TokenTextValue(varNameToken); + auto expression = expressionMatchers.ProcessExpression(result); + + if (!expression) + throw ParsingException(varNameToken.GetPos(), "No expression"); + + if (expression && expression->IsStatic()) + EmitStaticSetLocalVar(state, varNameToken.GetPos(), typeTag, varName, std::move(expression)); + else + EmitDynamicSetLocalVar(state, typeTag, varName, std::move(expression)); + } +}; + +class SequenceIf final : public MenuFileParser::sequence_t { + static constexpr auto CAPTURE_KEYWORD = 1; + +public: + SequenceIf() { + const ScriptMatcherFactory create(this); + const MenuExpressionMatchers expressionMatchers; + + AddLabeledMatchers(expressionMatchers.Expression(this), MenuExpressionMatchers::LABEL_EXPRESSION); + + AddMatchers({create.Keyword("if").Capture(CAPTURE_KEYWORD), create.Char('('), create.Label(MenuExpressionMatchers::LABEL_EXPRESSION), create.Char(')'), + create.Char('{')}); + } + +protected: + void ProcessMatch(MenuFileParserState *state, SequenceResult<SimpleParserValue> &result) const override { + const MenuExpressionMatchers expressionMatchers(state); + auto expression = expressionMatchers.ProcessExpression(result); + + if (!expression) + throw ParsingException(result.NextCapture(CAPTURE_KEYWORD).GetPos(), "Could not parse expression"); + + auto remainingScript = state->m_current_script.str(); + if (!remainingScript.empty()) + state->m_current_nested_event_handler_set->m_elements.emplace_back(std::make_unique<CommonEventHandlerScript>(std::move(remainingScript))); + state->m_current_script.str(std::string()); + + auto newCondition = std::make_unique<CommonEventHandlerCondition>(std::move(expression), std::make_unique<CommonEventHandlerSet>(), nullptr); + auto *newConditionPtr = newCondition.get(); + state->m_current_nested_event_handler_set->m_elements.emplace_back(std::move(newCondition)); + + state->m_condition_stack.emplace(newConditionPtr); + state->m_current_nested_event_handler_set = newConditionPtr->m_condition_elements.get(); + } +}; + +class SequenceElseIf final : public MenuFileParser::sequence_t { + static constexpr auto CAPTURE_KEYWORD = 1; + +public: + SequenceElseIf() { + const ScriptMatcherFactory create(this); + const MenuExpressionMatchers expressionMatchers; + + AddLabeledMatchers(expressionMatchers.Expression(this), MenuExpressionMatchers::LABEL_EXPRESSION); + + AddMatchers({create.Char('}'), create.Keyword("elseif").Capture(CAPTURE_KEYWORD), create.Char('('), create.Label(MenuExpressionMatchers::LABEL_EXPRESSION), + create.Char(')'), create.Char('{')}); + } + +protected: + void ProcessMatch(MenuFileParserState *state, SequenceResult<SimpleParserValue> &result) const override { + const MenuExpressionMatchers expressionMatchers(state); + auto expression = expressionMatchers.ProcessExpression(result); + + if (!expression) + throw ParsingException(result.NextCapture(CAPTURE_KEYWORD).GetPos(), "Could not parse expression"); + + if (state->m_condition_stack.empty()) + throw ParsingException(result.NextCapture(CAPTURE_KEYWORD).GetPos(), "Not in an if statement"); + + auto remainingScript = state->m_current_script.str(); + if (!remainingScript.empty()) + state->m_current_nested_event_handler_set->m_elements.emplace_back(std::make_unique<CommonEventHandlerScript>(std::move(remainingScript))); + state->m_current_script.str(std::string()); + + auto ¤tCondition = state->m_condition_stack.top(); + + assert(currentCondition.m_in_condition_elements == (currentCondition.m_condition->m_else_elements == nullptr)); + if (!currentCondition.m_in_condition_elements) + throw ParsingException(result.NextCapture(CAPTURE_KEYWORD).GetPos(), "Cannot specify elseif after else"); + currentCondition.m_in_condition_elements = false; + + auto newCondition = std::make_unique<CommonEventHandlerCondition>(std::move(expression), std::make_unique<CommonEventHandlerSet>(), nullptr); + auto *newConditionPtr = newCondition.get(); + currentCondition.m_condition->m_else_elements = std::make_unique<CommonEventHandlerSet>(); + currentCondition.m_condition->m_else_elements->m_elements.emplace_back(std::move(newCondition)); + + state->m_condition_stack.emplace(newConditionPtr, true); + state->m_current_nested_event_handler_set = newConditionPtr->m_condition_elements.get(); + } +}; + +class SequenceElse final : public MenuFileParser::sequence_t { + static constexpr auto CAPTURE_KEYWORD = 1; + +public: + SequenceElse() { + const ScriptMatcherFactory create(this); + const MenuExpressionMatchers expressionMatchers; + + AddMatchers({create.Char('}'), create.Keyword("else").Capture(CAPTURE_KEYWORD), create.Char('{')}); + } + +protected: + void ProcessMatch(MenuFileParserState *state, SequenceResult<SimpleParserValue> &result) const override { + if (state->m_condition_stack.empty()) + throw ParsingException(result.NextCapture(CAPTURE_KEYWORD).GetPos(), "Not in an if statement"); + + auto ¤tCondition = state->m_condition_stack.top(); + + assert(currentCondition.m_in_condition_elements == (currentCondition.m_condition->m_else_elements == nullptr)); + if (!currentCondition.m_in_condition_elements) + throw ParsingException(result.NextCapture(CAPTURE_KEYWORD).GetPos(), "Cannot specify second else block"); + + auto remainingScript = state->m_current_script.str(); + if (!remainingScript.empty()) + state->m_current_nested_event_handler_set->m_elements.emplace_back(std::make_unique<CommonEventHandlerScript>(std::move(remainingScript))); + state->m_current_script.str(std::string()); + + currentCondition.m_in_condition_elements = false; + currentCondition.m_condition->m_else_elements = std::make_unique<CommonEventHandlerSet>(); + state->m_current_nested_event_handler_set = currentCondition.m_condition->m_else_elements.get(); + } +}; + +class SequenceOnlineVault final : public SequenceGenericScriptStatement { + static constexpr auto LABEL_OPEN = 1; + static constexpr auto LABEL_PARADIGM = 2; + static constexpr auto LABEL_PLATFORM = 3; + static constexpr auto LABEL_FILE_CATEGORY = 4; + +public: + explicit SequenceOnlineVault() { + const ScriptMatcherFactory create(this); + + AddLabeledMatchers(create.Or({ + create.ScriptKeyword("Browse"), + create.ScriptKeyword("Load"), + create.ScriptKeyword("Save"), + create.ScriptKeyword("Copy"), + }), + LABEL_PARADIGM); + + AddLabeledMatchers(create.Or({ + create.ScriptKeyword("Fb"), + create.ScriptKeyword("Elite"), + create.ScriptKeyword("Live"), + }), + LABEL_PLATFORM); + + AddLabeledMatchers(create.Or({ + create.ScriptKeyword("All"), + create.ScriptKeyword("Film"), + create.ScriptKeyword("Clip"), + create.ScriptKeyword("Screenshot"), + create.ScriptKeyword("Avi"), + create.ScriptKeyword("Cgm"), + create.ScriptKeyword("Rcu"), + }), + LABEL_FILE_CATEGORY); + + AddLabeledMatchers(create.And({create.ScriptKeyword("open"), create.Label(LABEL_PARADIGM), create.Optional(create.Label(LABEL_PLATFORM)), + create.Optional(create.Label(LABEL_FILE_CATEGORY)), create.ScriptText()}), + LABEL_OPEN); + + AddMatchers({create + .And({create.ScriptKeyword("uiScript"), create.ScriptKeyword("OnlineVault"), + create.Or({ + create.Label(LABEL_OPEN), + create.ScriptKeyword("Pop"), + create.ScriptKeyword("CloseAll"), + create.ScriptKeyword("Load"), + create.ScriptKeyword("LoadAndRenderMovie"), + create.ScriptKeyword("TrySave"), + create.ScriptKeyword("Save"), + create.ScriptKeyword("Rename"), + create.ScriptKeyword("Delete"), + create.ScriptKeyword("Abort"), + create.ScriptKeyword("FacebookUploadPhoto"), + create.ScriptKeyword("FacebookUploadVideo"), + })}) + .Capture(CAPTURE_SCRIPT_TOKEN), + create.Optional(create.Char(';'))}); + } +}; +} // namespace menu::event_handler_set_scope_sequences - AddSequence(std::make_unique<SequenceSetLocalVar>()); - AddSequence(std::make_unique<SequenceIf>()); - AddSequence(std::make_unique<SequenceElseIf>()); - AddSequence(std::make_unique<SequenceElse>()); - AddSequence(std::make_unique<SequenceCloseBlock>()); +using namespace event_handler_set_scope_sequences; - if (permissive) - { - AddSequence(std::make_unique<SequenceSkipScriptToken>()); +EventHandlerSetScopeSequences::EventHandlerSetScopeSequences(std::vector<std::unique_ptr<MenuFileParser::sequence_t>> &allSequences, + std::vector<MenuFileParser::sequence_t *> &scopeSequences) + : AbstractScopeSequenceHolder(allSequences, scopeSequences) {} + +void EventHandlerSetScopeSequences::AddSequences(const FeatureLevel featureLevel, const bool permissive) const { + AddSequence(std::make_unique<SequenceSkipEmptyStatements>()); + // If else and stuff + + // Creating factory with no label supplier. Cannot use labels with it. + const ScriptMatcherFactory create(nullptr); + + if (!permissive) { + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("fadeIn"), create.ScriptText()})); // fadeIn <item group name> + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("fadeOut"), create.ScriptText()})); // fadeOut <item group name> + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("show"), create.ScriptText()})); // show <item group name> + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("hide"), create.ScriptText()})); // hide <item group name> + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("showMenu"), create.ScriptText()})); // showMenu <menu name> + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("hideMenu"), create.ScriptText()})); // hideMenu <menu name> + AddSequence(SequenceGenericScriptStatement::Create( + {create.ScriptKeyword("setColor"), + create.Or({create.ScriptKeyword("backColor"), create.ScriptKeyword("foreColor"), create.ScriptKeyword("borderColor")}), + create.ScriptColor()})); // setColor ("backColor" | "foreColor" | "borderColor") <r> [<g>] [<b>] [<a>] + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("open"), create.ScriptText()})); // open <menu name> + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("close"), create.ScriptText()})); // close ("self" | <menu name>) + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("escape"), create.ScriptText()})); // escape ("self" | <menu name>) + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("closeForAllPlayers"), create.ScriptText()})); // closeForAllPlayers <menu name> + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("ingameOpen"), create.ScriptText()})); // ingameOpen <menu name> + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("ingameClose"), create.ScriptText()})); // ingameClose <menu name> + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("setBackground"), create.ScriptText()})); // setBackground <material name> + AddSequence(SequenceGenericScriptStatement::Create( + {create.ScriptKeyword("setItemColor"), create.ScriptText(), + create.Or( + {create.ScriptKeyword("backColor"), create.ScriptKeyword("foreColor"), create.ScriptKeyword("borderColor"), create.ScriptKeyword("disableColor")}), + create.ScriptColor()})); // setItemColor <item group name> (backColor | foreColor | borderColor | disableColor) <r> [<g>] [<b>] [<a>] + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("focusFirst")})); + // setFocus game specific + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("setFocusByDvar"), create.ScriptText()})); // setFocusByDvar <dvar name> + // setDvar game specific + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("exec"), create.ScriptText()})); // exec <command> + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("execNow"), create.ScriptText()})); // execNow <command> + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("execOnDvarStringValue"), create.ScriptText(), create.ScriptText(), + create.ScriptText()})); // execOnDvarStringValue <dvar name> <value> <command> + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("execOnDvarIntValue"), create.ScriptText(), create.ScriptInt(), + create.ScriptText()})); // execOnDvarIntValue <dvar name> <value> <command> + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("execOnDvarFloatValue"), create.ScriptText(), create.ScriptNumeric(), + create.ScriptText()})); // execOnDvarFloatValue <dvar name> <value> <command> + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("execNowOnDvarStringValue"), create.ScriptText(), create.ScriptText(), + create.ScriptText()})); // execNowOnDvarStringValue <dvar name> <value> <command> + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("execNowOnDvarIntValue"), create.ScriptText(), create.ScriptInt(), + create.ScriptText()})); // execNowOnDvarIntValue <dvar name> <value> <command> + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("execNowOnDvarFloatValue"), create.ScriptText(), create.ScriptNumeric(), + create.ScriptText()})); // execNowOnDvarFloatValue <dvar name> <value> <command> + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("play"), create.ScriptText()})); // play <sound name> + // scriptMenuResponse game specific + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("scriptMenuRespondOnDvarStringValue"), create.ScriptText(), create.ScriptText(), + create.ScriptText()})); // scriptMenuRespondOnDvarStringValue <dvar name> <value> <response value> + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("scriptMenuRespondOnDvarIntValue"), create.ScriptText(), create.ScriptInt(), + create.ScriptText()})); // scriptMenuRespondOnDvarIntValue <dvar name> <value> <response value> + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("scriptMenuRespondOnDvarFloatValue"), create.ScriptText(), create.ScriptNumeric(), + create.ScriptText()})); // scriptMenuRespondOnDvarFloatValue <dvar name> <value> <response value> + AddSequence(std::make_unique<SequenceSetPlayerData>()); + AddSequence(std::make_unique<SequenceSetPlayerDataSplitscreen>()); + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("resetStatsConfirm")})); + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("resetStatsCancel")})); + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("setGameMode"), create.ScriptText()})); // setGameMode <mode name> + // feederTop / feederBottom game specific + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("showGamerCard")})); + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("openForGameType"), create.ScriptText()})); + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("closeForGameType"), create.ScriptText()})); + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("kickPlayer")})); + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("getKickPlayerQuestion")})); + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("partyUpdateMissingMapPackDvar")})); + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("togglePlayerMute")})); + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("resolveError")})); + AddSequence(std::make_unique<SequenceLerp>()); + + // UiScripts + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("StartServer")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("loadArenas")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("loadGameInfo")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("clearError")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("Quit")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("Controls")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("Leave")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("closeingame")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("update"), create.ScriptText()})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("startSingleplayer")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("startMultiplayer")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("getLanguage")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("verifyLanguage")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("updateLanguage")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("mutePlayer")})); + AddSequence(SequenceUiScriptStatement::Create( + {create.ScriptKeyword("openMenuOnDvar"), create.ScriptText(), create.Or({create.ScriptStrictNumeric(), create.ScriptText()}), create.ScriptText()})); + AddSequence(SequenceUiScriptStatement::Create( + {create.ScriptKeyword("openMenuOnDvarNot"), create.ScriptText(), create.Or({create.ScriptStrictNumeric(), create.ScriptText()}), create.ScriptText()})); + AddSequence(SequenceUiScriptStatement::Create( + {create.ScriptKeyword("closeMenuOnDvar"), create.ScriptText(), create.Or({create.ScriptStrictNumeric(), create.ScriptText()}), create.ScriptText()})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("closeMenuOnDvarNot"), create.ScriptText(), + create.Or({create.ScriptStrictNumeric(), create.ScriptText()}), create.ScriptText()})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("setRecommended")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("clearLoadErrorsSummary")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("clearClientMatchData")})); + + if (featureLevel == FeatureLevel::IW4) { + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("setFocus"), create.ScriptText()})); // setFocus <item name> + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("setDvar"), create.ScriptText(), + create.Or({create.ScriptStrictNumeric(), create.ScriptText()})})); // setDvar <dvar name> <dvar value> + AddSequence( + SequenceGenericScriptStatement::Create({create.ScriptKeyword("scriptMenuResponse"), create.ScriptText()})); // scriptMenuResponse <response value> + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("updateMail")})); + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("openMail")})); + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("deleteMail")})); + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("doMailLottery")})); + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("feederTop")})); + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("feederBottom")})); + // statClearPerkNew // TODO + // statSetUsingTable // TODO + // statClearBitMask // TODO + + // IW4x UiScripts + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("LoadMods")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("RunMod")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("ClearMods")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("security_increase_cancel")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("mod_download_cancel")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("LoadFriends")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("JoinFriend")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("downloadDLC"), create.ScriptInt()})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("checkFirstLaunch")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("visitWebsite")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("visitWiki")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("visitDiscord")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("updateui_mousePitch")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("ServerStatus")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("UpdateFilter")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("RefreshFilter")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("RefreshServers")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("JoinServer")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("ServerSort"), create.ScriptInt()})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("CreateListFavorite")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("CreateFavorite")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("CreateCurrentServerFavorite")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("DeleteFavorite")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("nextStartupMessage")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("UpdateClasses")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("loadDemos")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("launchDemo")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("deleteDemo")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("ApplyMap")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("ApplyInitialMap")})); } + + if (featureLevel == FeatureLevel::IW5) { + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("forceClose"), create.ScriptText()})); // forceClose ("self" | <menu name>) + AddSequence(SequenceGenericScriptStatement::Create({ + create.ScriptKeyword("setFocus"), + create.Or({create.And({ + create.ScriptKeyword("localVarString"), + create.Char('('), + create.ScriptText(), + create.Char(')'), + }), + create.ScriptText()}), + })); // setFocus ((localVarString '(' <var name> ')') | <item name>) + AddSequence(SequenceGenericScriptStatement::Create({ + create.ScriptKeyword("setDvar"), + create.ScriptText(), + create.Or({create.And({ + create.ScriptKeyword("localVarString"), + create.Char('('), + create.ScriptText(), + create.Char(')'), + }), + create.ScriptStrictNumeric(), create.ScriptText()}), + })); // setDvar <dvar name> ((localVarString '(' <var name> ')') | <dvar value>) + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("execFirstClient"), create.ScriptText()})); // execFirstClient <command> + AddSequence(SequenceGenericScriptStatement::Create( + {create.ScriptKeyword("execKeyPress"), create.Or({create.ScriptStrictNumeric(), create.ScriptText()})})); // execKeyPress <key number> + AddSequence(SequenceGenericScriptStatement::Create({ + create.ScriptKeyword("scriptMenuResponse"), + create.Or({ + create.And({ + create.Or({ + create.ScriptKeyword("localVarInt"), + create.ScriptKeyword("localVarFloat"), + create.ScriptKeyword("localVarBool"), + create.ScriptKeyword("localVarString"), + }), + create.Char('('), + create.ScriptText(), + create.Char(')'), + }), + create.ScriptStrictInt(), + create.ScriptText(), + }), + })); // scriptMenuResponse (((localVarInt | localVarFloat | localVarBool | localVarString) '(' <var name> ')') | <response value>) + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("deleteEliteCacFile")})); + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("integrateEliteCacFile")})); + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("setMatchRulesData")})); // unknown parameters + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("loadMatchRulesDataFromPlayer")})); // unknown parameters + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("saveMatchRulesDataToPlayer")})); // unknown parameters + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("loadMatchRulesDataFromHistory")})); // unknown parameters + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("loadMatchRulesDataDefaults")})); // unknown parameters + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("setUsingMatchRulesData")})); // unknown parameters + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("saveMatchRulesDedicatedServer")})); // unknown parameters + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("loadMatchRulesDedicatedServer")})); // unknown parameters + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("onlineVaultEditMetadata")})); // unknown parameters + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("includeInMapRotation")})); // unknown parameters + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("useCustomMapRotation")})); // unknown parameters + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("useIntermissionTimer")})); // unknown parameters + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("stopIntermissionTimer")})); // unknown parameters + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("feederTop"), create.Optional(create.Text())})); // feederTop [<var name>] + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("feederBottom"), create.Optional(create.Text())})); // feederBottom [<var name>] + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("feederPageUp"), create.Optional(create.Text())})); // feederPageUp [<var name>] + AddSequence( + SequenceGenericScriptStatement::Create({create.ScriptKeyword("feederPageDown"), create.Optional(create.Text())})); // feederPageDown [<var name>] + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("showCoopGamerCard")})); // unknown parameters + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("showSplitscreenGamerCard")})); // unknown parameters + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("reportPlayerOffensive")})); + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("reportPlayerExploiting")})); + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("reportPlayerCheating")})); + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("reportPlayerBoosting")})); + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("setCardIcon"), create.Char('('), create.ScriptLocalVarIntOrLiteral(), + create.Char(')')})); // setCardIcon '(' ((localVarInt '(' <var name> ')') | <card icon index>) ')' + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("setCardTitle"), create.Char('('), create.ScriptLocalVarIntOrLiteral(), + create.Char(')')})); // setCardTitle '(' ((localVarInt '(' <var name> ')') | <card title index>) ')' + AddSequence(SequenceGenericScriptStatement::Create( + {create.ScriptKeyword("setCardIconNew"), create.Char('('), create.ScriptLocalVarIntOrLiteral(), create.Char(','), + create.Or({ + create.ScriptLocalVarIntOrLiteral(), + // This is wrong and the game does not even understand it. But because it's not a number it evaluates to 0... + // The game's menus do it and i don't want to fix it everywhere + create.ScriptKeyword("false"), + }), + create.Char( + ')')})); // setCardIconNew '(' ((localVarInt '(' <var name> ')') | <card icon index>) ',' ((localVarInt '(' <var name> ')') | <is new>) ')' + AddSequence(SequenceGenericScriptStatement::Create( + {create.ScriptKeyword("setCardTitleNew"), create.Char('('), create.ScriptLocalVarIntOrLiteral(), create.Char(','), + create.Or({ + create.ScriptLocalVarIntOrLiteral(), + // This is a hack (see setCardIconNew for details) + create.ScriptKeyword("false"), + }), + create.Char( + ')')})); // setCardTitleNew '(' ((localVarInt '(' <var name> ')') | <card icon index>) ',' ((localVarInt '(' <var name> ')') | <is new>) ')' + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("setCardIconSplitScreen")})); // unknown + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("setCardTitleSplitScreen")})); // unknown + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("setCardIconNewSplitScreen")})); // unknown + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("setCardTitleNewSplitScreen")})); // unknown + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("purchasePrestigeTitle"), create.Char('('), create.ScriptText(), + create.Char(')')})); // purchasePrestigeTitle '(' <title name> ')' + AddSequence(SequenceGenericScriptStatement::Create( + {create.ScriptKeyword("setProfileItemNew"), create.Char('('), create.ScriptText(), create.Char(','), create.ScriptLocalVarIntOrLiteral(), + create.Char(')')})); // setProfileItemNew '(' <item name> ',' (0|1|(localVarInt '(' <var name> ')')) ')' + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("setProfileItemNewSplitScreen")})); // unknown + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("storePopupXuid")})); + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("getHostMigrateQuestion")})); + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("makeHost")})); + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("saveGameHide")})); // saveGameHide <item name> + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("saveGameShow")})); // saveGameShow <item name> + AddSequence( + SequenceGenericScriptStatement::Create({create.ScriptKeyword("saveGameSetLocalBool"), create.ScriptText()})); // saveGameSetLocalBool <var name> + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("saveDelay")})); + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("writeSave")})); + AddSequence( + SequenceGenericScriptStatement::Create({create.ScriptKeyword("setSaveExecOnSuccess"), create.ScriptText()})); // setSaveExecOnSuccess <command> + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("nextLevel")})); + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("disablePause")})); + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("enablePause")})); + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("runCompletionResolve")})); + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("clearCompletionResolve")})); + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("execWithResolve"), create.ScriptText()})); + AddSequence(SequenceGenericScriptStatement::Create({ + create.ScriptKeyword("playMenuVideo"), + create.Char('('), + create.ScriptText(), + create.Char(','), + create.ScriptLocalVarIntOrLiteral(), + create.Char(','), + create.ScriptLocalVarBoolOrLiteral(), + create.Char(')'), + })); // playMenuVideo '(' <video name> ',' ((localVarInt '(' <var name> ')') | <offset>) ',' ((localVarBool '(' <var name> ')') | <maybe looping bool>) + // ')' + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("setBackgroundVideo"), create.Char('('), create.ScriptText(), + create.Char(')')})); // setBackgroundVideo '(' <video name or empty string> ')' + AddSequence( + SequenceGenericScriptStatement::Create({create.ScriptKeyword("clearEntitlementNew"), create.ScriptText()})); // clearEntitlementNew <entitlement name> + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("setPastTitleRank")})); // unknown + AddSequence(SequenceGenericScriptStatement::Create({create.ScriptKeyword("setPastTitlePrestige")})); // unknown + AddSequence( + SequenceGenericScriptStatement::Create({create.ScriptKeyword("anticheat_bancheck"), create.ScriptStrictNumeric()})); // anticheat_bancheck <num> + + // UiScripts + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("LoadSaveGames")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("LoadGame")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("SaveGame")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("ForceSave")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("DelSaveGame")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("SaveGameSort"), create.ScriptStrictInt()})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("playerStart")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("saveComplete")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("saveRevert")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("resetvscroll"), create.ScriptText()})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("RefreshLeaderboards")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("ViewGamerCard")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("OpenLeaderboard"), create.ScriptText()})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("OpenLeaderboardExt"), create.ScriptText(), create.Optional(create.Text())})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("ClearLeaderboard")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("FriendStoreXUID")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("FriendClearXUID")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("FriendInvite")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("FriendJoin")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("FriendGamerCard")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("FriendReportOffensive")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("FriendReportExploiter")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("FriendReportCheater")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("FriendReportBooster")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("RecentPlayerStoreXUID")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("RecentPlayerClearXUID")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("RecentPlayerGamerCard")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("RecentPlayerFriendRequest")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("RecentPlayerShowGroups")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("RecentPlayerJoin")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("RecentPlayerInvite")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("RecentPlayerReportOffensive")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("RecentPlayerReportExploiter")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("RecentPlayerReportCheater")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("RecentPlayerReportBooster")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("FacebookStoreXUID")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("FacebookClearXUID")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("FacebookGamerCard")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("FacebookFriendRequest")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("FacebookPageRight")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("FacebookPageLeft")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("FacebookJoin")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("FacebookInvite")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("FacebookReportOffensive")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("FacebookReportExploiter")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("FacebookReportCheater")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("FacebookReportBooster")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("EliteClanStoreXUID")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("EliteClanClearXUID")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("EliteClanGamerCard")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("EliteClanFriendRequest")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("EliteClanJoin")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("EliteClanInvite")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("EliteClanReportOffensive")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("EliteClanReportExploiter")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("EliteClanReportCheater")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("EliteClanReportBooster")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("coopPlayerShowGroups"), create.ScriptStrictInt()})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("simulateKeyPress"), create.ScriptStrictInt()})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("commerceShowStore")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("voteTypeMap")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("voteMap")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("voteGame")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("RefreshServers")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("RefreshFilter")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("closeJoin")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("StopRefresh")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("TrimRecipeName")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("ResetRecipeList")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("SelectServer")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("ShowCurrentServerTooltip")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("voteTempBan")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("addFavorite")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("deleteFavorite")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("PlayDemo")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("SwitchSegmentTransition"), create.ScriptStrictInt(), create.ScriptStrictInt()})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("PreviewSegment")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("MoveSegment"), create.ScriptStrictInt()})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("DeleteSegment")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("SetFocusOnSegmentButton")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("PopulateLocalDemoFileInformation")})); + AddSequence(std::make_unique<SequenceOnlineVault>()); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("Playlist"), create.Or({ + create.And({ + create.ScriptKeyword("Open"), + create.ScriptStrictInt(), + }), + create.ScriptKeyword("DoAction"), + create.ScriptKeyword("Close"), + create.ScriptKeyword("CloseAll"), + })})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("UpdateArenas")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("SortChallengesTop")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("xlaunchelitesearch")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("xlaunchelitelaunch")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("xlaunchelitestore")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("LobbyShowGroups")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("addPlayerProfiles")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("createPlayerProfile")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("deletePlayerProfile")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("loadPlayerProfile")})); + AddSequence(SequenceUiScriptStatement::Create({create.ScriptKeyword("selectActivePlayerProfile")})); + } + } + + AddSequence(std::make_unique<SequenceSetLocalVar>()); + AddSequence(std::make_unique<SequenceIf>()); + AddSequence(std::make_unique<SequenceElseIf>()); + AddSequence(std::make_unique<SequenceElse>()); + AddSequence(std::make_unique<SequenceCloseBlock>()); + + if (permissive) { + AddSequence(std::make_unique<SequenceSkipScriptToken>()); + } } diff --git a/src/ObjLoading/Parsing/Menu/Sequence/EventHandlerSetScopeSequences.h b/src/ObjLoading/Parsing/Menu/Sequence/EventHandlerSetScopeSequences.h index 388117268..d21dfddf7 100644 --- a/src/ObjLoading/Parsing/Menu/Sequence/EventHandlerSetScopeSequences.h +++ b/src/ObjLoading/Parsing/Menu/Sequence/EventHandlerSetScopeSequences.h @@ -3,13 +3,12 @@ #include "Parsing/Menu/MenuFileParser.h" #include "Parsing/Sequence/AbstractScopeSequenceHolder.h" -namespace menu -{ - class EventHandlerSetScopeSequences final : AbstractScopeSequenceHolder<MenuFileParser> - { - public: - EventHandlerSetScopeSequences(std::vector<std::unique_ptr<MenuFileParser::sequence_t>>& allSequences, std::vector<MenuFileParser::sequence_t*>& scopeSequences); +namespace menu { +class EventHandlerSetScopeSequences final : AbstractScopeSequenceHolder<MenuFileParser> { +public: + EventHandlerSetScopeSequences(std::vector<std::unique_ptr<MenuFileParser::sequence_t>> &allSequences, + std::vector<MenuFileParser::sequence_t *> &scopeSequences); - void AddSequences(FeatureLevel featureLevel, bool permissive) const; - }; -} + void AddSequences(FeatureLevel featureLevel, bool permissive) const; +}; +} // namespace menu diff --git a/src/ObjLoading/Parsing/Menu/Sequence/FunctionScopeSequences.cpp b/src/ObjLoading/Parsing/Menu/Sequence/FunctionScopeSequences.cpp index 8cf41392f..83e8dcb88 100644 --- a/src/ObjLoading/Parsing/Menu/Sequence/FunctionScopeSequences.cpp +++ b/src/ObjLoading/Parsing/Menu/Sequence/FunctionScopeSequences.cpp @@ -8,79 +8,61 @@ using namespace menu; -namespace menu::function_scope_sequences -{ - class SequenceCloseBlock final : public MenuFileParser::sequence_t - { - static constexpr auto CAPTURE_TOKEN = 1; +namespace menu::function_scope_sequences { +class SequenceCloseBlock final : public MenuFileParser::sequence_t { + static constexpr auto CAPTURE_TOKEN = 1; - public: - SequenceCloseBlock() - { - const MenuMatcherFactory create(this); +public: + SequenceCloseBlock() { + const MenuMatcherFactory create(this); - AddMatchers({ - create.Char('}').Capture(CAPTURE_TOKEN) - }); - } + AddMatchers({create.Char('}').Capture(CAPTURE_TOKEN)}); + } - protected: - void ProcessMatch(MenuFileParserState* state, SequenceResult<SimpleParserValue>& result) const override - { - if (!state->m_current_function->m_value) - { - std::ostringstream ss; - ss << "Cannot define function name \"" << state->m_current_function->m_name << "\" without a value"; - throw ParsingException(result.NextCapture(CAPTURE_TOKEN).GetPos(), ss.str()); - } +protected: + void ProcessMatch(MenuFileParserState *state, SequenceResult<SimpleParserValue> &result) const override { + if (!state->m_current_function->m_value) { + std::ostringstream ss; + ss << "Cannot define function name \"" << state->m_current_function->m_name << "\" without a value"; + throw ParsingException(result.NextCapture(CAPTURE_TOKEN).GetPos(), ss.str()); + } - const auto existingFunction = state->m_functions_by_name.find(state->m_current_function->m_name); - if (existingFunction == state->m_functions_by_name.end()) - { - state->m_functions_by_name.emplace(std::make_pair(state->m_current_function->m_name, state->m_current_function)); - state->m_current_function = nullptr; - } - else if (!state->m_current_function->m_value->Equals(existingFunction->second->m_value.get())) - { - std::ostringstream ss; - ss << "Function with name \"" << state->m_current_function->m_name << "\" already exists"; - throw ParsingException(result.NextCapture(CAPTURE_TOKEN).GetPos(), ss.str()); - } - else - { - // Remove definition of function to not re-add it - const auto foundFunction = std::find_if(state->m_functions.rbegin(), state->m_functions.rend(), [state](const auto& element) - { - return element.get() == state->m_current_function; - }); - - assert(foundFunction != state->m_functions.rend()); - assert((foundFunction + 1).base()->get() == state->m_current_function); - if (foundFunction != state->m_functions.rend()) - state->m_functions.erase((foundFunction + 1).base()); + const auto existingFunction = state->m_functions_by_name.find(state->m_current_function->m_name); + if (existingFunction == state->m_functions_by_name.end()) { + state->m_functions_by_name.emplace(std::make_pair(state->m_current_function->m_name, state->m_current_function)); + state->m_current_function = nullptr; + } else if (!state->m_current_function->m_value->Equals(existingFunction->second->m_value.get())) { + std::ostringstream ss; + ss << "Function with name \"" << state->m_current_function->m_name << "\" already exists"; + throw ParsingException(result.NextCapture(CAPTURE_TOKEN).GetPos(), ss.str()); + } else { + // Remove definition of function to not re-add it + const auto foundFunction = std::find_if(state->m_functions.rbegin(), state->m_functions.rend(), + [state](const auto &element) { return element.get() == state->m_current_function; }); - state->m_current_function = nullptr; - } - } - }; -} + assert(foundFunction != state->m_functions.rend()); + assert((foundFunction + 1).base()->get() == state->m_current_function); + if (foundFunction != state->m_functions.rend()) + state->m_functions.erase((foundFunction + 1).base()); + + state->m_current_function = nullptr; + } + } +}; +} // namespace menu::function_scope_sequences using namespace function_scope_sequences; -FunctionScopeSequences::FunctionScopeSequences(std::vector<std::unique_ptr<MenuFileParser::sequence_t>>& allSequences, std::vector<MenuFileParser::sequence_t*>& scopeSequences) - : AbstractScopeSequenceHolder(allSequences, scopeSequences) -{ -} +FunctionScopeSequences::FunctionScopeSequences(std::vector<std::unique_ptr<MenuFileParser::sequence_t>> &allSequences, + std::vector<MenuFileParser::sequence_t *> &scopeSequences) + : AbstractScopeSequenceHolder(allSequences, scopeSequences) {} -void FunctionScopeSequences::AddSequences(FeatureLevel featureLevel, bool permissive) const -{ - AddSequence(std::make_unique<SequenceCloseBlock>()); - AddSequence(std::make_unique<GenericStringPropertySequence>("name", [](const MenuFileParserState* state, const TokenPos&, const std::string& value) - { - state->m_current_function->m_name = value; - })); - AddSequence(GenericExpressionPropertySequence::WithKeyword("value", [](const MenuFileParserState* state, const TokenPos&, std::unique_ptr<ISimpleExpression> value) - { - state->m_current_function->m_value = std::move(value); - })); +void FunctionScopeSequences::AddSequences(FeatureLevel featureLevel, bool permissive) const { + AddSequence(std::make_unique<SequenceCloseBlock>()); + AddSequence(std::make_unique<GenericStringPropertySequence>( + "name", [](const MenuFileParserState *state, const TokenPos &, const std::string &value) { state->m_current_function->m_name = value; })); + AddSequence( + GenericExpressionPropertySequence::WithKeyword("value", [](const MenuFileParserState *state, const TokenPos &, std::unique_ptr<ISimpleExpression> value) { + state->m_current_function->m_value = std::move(value); + })); } diff --git a/src/ObjLoading/Parsing/Menu/Sequence/FunctionScopeSequences.h b/src/ObjLoading/Parsing/Menu/Sequence/FunctionScopeSequences.h index 012f2606b..450df260a 100644 --- a/src/ObjLoading/Parsing/Menu/Sequence/FunctionScopeSequences.h +++ b/src/ObjLoading/Parsing/Menu/Sequence/FunctionScopeSequences.h @@ -3,13 +3,11 @@ #include "Parsing/Menu/MenuFileParser.h" #include "Parsing/Sequence/AbstractScopeSequenceHolder.h" -namespace menu -{ - class FunctionScopeSequences final : AbstractScopeSequenceHolder<MenuFileParser> - { - public: - FunctionScopeSequences(std::vector<std::unique_ptr<MenuFileParser::sequence_t>>& allSequences, std::vector<MenuFileParser::sequence_t*>& scopeSequences); +namespace menu { +class FunctionScopeSequences final : AbstractScopeSequenceHolder<MenuFileParser> { +public: + FunctionScopeSequences(std::vector<std::unique_ptr<MenuFileParser::sequence_t>> &allSequences, std::vector<MenuFileParser::sequence_t *> &scopeSequences); - void AddSequences(FeatureLevel featureLevel, bool permissive) const; - }; -} + void AddSequences(FeatureLevel featureLevel, bool permissive) const; +}; +} // namespace menu diff --git a/src/ObjLoading/Parsing/Menu/Sequence/Generic/GenericBoolPropertySequence.cpp b/src/ObjLoading/Parsing/Menu/Sequence/Generic/GenericBoolPropertySequence.cpp index 298f71bc9..5a50dcf63 100644 --- a/src/ObjLoading/Parsing/Menu/Sequence/Generic/GenericBoolPropertySequence.cpp +++ b/src/ObjLoading/Parsing/Menu/Sequence/Generic/GenericBoolPropertySequence.cpp @@ -6,22 +6,15 @@ using namespace menu; -GenericBoolPropertySequence::GenericBoolPropertySequence(std::string keywordName, callback_t setCallback) - : m_set_callback(std::move(setCallback)) -{ - const MenuMatcherFactory create(this); +GenericBoolPropertySequence::GenericBoolPropertySequence(std::string keywordName, callback_t setCallback) : m_set_callback(std::move(setCallback)) { + const MenuMatcherFactory create(this); - AddMatchers({ - create.KeywordIgnoreCase(std::move(keywordName)).Capture(CAPTURE_FIRST_TOKEN), - create.Integer().Capture(CAPTURE_VALUE) - }); + AddMatchers({create.KeywordIgnoreCase(std::move(keywordName)).Capture(CAPTURE_FIRST_TOKEN), create.Integer().Capture(CAPTURE_VALUE)}); } -void GenericBoolPropertySequence::ProcessMatch(MenuFileParserState* state, SequenceResult<SimpleParserValue>& result) const -{ - if (m_set_callback) - { - const auto value = result.NextCapture(CAPTURE_VALUE).IntegerValue(); - m_set_callback(state, result.NextCapture(CAPTURE_FIRST_TOKEN).GetPos(), value > 0); - } +void GenericBoolPropertySequence::ProcessMatch(MenuFileParserState *state, SequenceResult<SimpleParserValue> &result) const { + if (m_set_callback) { + const auto value = result.NextCapture(CAPTURE_VALUE).IntegerValue(); + m_set_callback(state, result.NextCapture(CAPTURE_FIRST_TOKEN).GetPos(), value > 0); + } } diff --git a/src/ObjLoading/Parsing/Menu/Sequence/Generic/GenericBoolPropertySequence.h b/src/ObjLoading/Parsing/Menu/Sequence/Generic/GenericBoolPropertySequence.h index 060298671..dee82932a 100644 --- a/src/ObjLoading/Parsing/Menu/Sequence/Generic/GenericBoolPropertySequence.h +++ b/src/ObjLoading/Parsing/Menu/Sequence/Generic/GenericBoolPropertySequence.h @@ -1,27 +1,25 @@ #pragma once -#include <string> #include <functional> +#include <string> #include "Parsing/Menu/MenuFileParser.h" -namespace menu -{ - class GenericBoolPropertySequence final : public MenuFileParser::sequence_t - { - public: - using callback_t = std::function<void(MenuFileParserState* state, const TokenPos& pos, bool value)>; +namespace menu { +class GenericBoolPropertySequence final : public MenuFileParser::sequence_t { +public: + using callback_t = std::function<void(MenuFileParserState *state, const TokenPos &pos, bool value)>; - private: - static constexpr auto CAPTURE_FIRST_TOKEN = 1; - static constexpr auto CAPTURE_VALUE = 2; +private: + static constexpr auto CAPTURE_FIRST_TOKEN = 1; + static constexpr auto CAPTURE_VALUE = 2; - const callback_t m_set_callback; + const callback_t m_set_callback; - protected: - void ProcessMatch(MenuFileParserState* state, SequenceResult<SimpleParserValue>& result) const override; +protected: + void ProcessMatch(MenuFileParserState *state, SequenceResult<SimpleParserValue> &result) const override; - public: - GenericBoolPropertySequence(std::string keywordName, callback_t setCallback); - }; -} +public: + GenericBoolPropertySequence(std::string keywordName, callback_t setCallback); +}; +} // namespace menu diff --git a/src/ObjLoading/Parsing/Menu/Sequence/Generic/GenericColorPropertySequence.cpp b/src/ObjLoading/Parsing/Menu/Sequence/Generic/GenericColorPropertySequence.cpp index cec2bfc99..200d881dc 100644 --- a/src/ObjLoading/Parsing/Menu/Sequence/Generic/GenericColorPropertySequence.cpp +++ b/src/ObjLoading/Parsing/Menu/Sequence/Generic/GenericColorPropertySequence.cpp @@ -7,39 +7,34 @@ using namespace menu; -GenericColorPropertySequence::GenericColorPropertySequence(std::string keywordName, callback_t setCallback) - : m_set_callback(std::move(setCallback)) -{ - const MenuMatcherFactory create(this); - - AddLabeledMatchers(MenuExpressionMatchers().Expression(this), MenuExpressionMatchers::LABEL_EXPRESSION); - AddMatchers({ - create.KeywordIgnoreCase(std::move(keywordName)).Capture(CAPTURE_FIRST_TOKEN), - create.NumericExpression().Tag(TAG_COLOR), // r - create.Optional(create.NumericExpression().Tag(TAG_COLOR)), // g - create.Optional(create.NumericExpression().Tag(TAG_COLOR)), // b - create.Optional(create.NumericExpression().Tag(TAG_COLOR)) // a - }); +GenericColorPropertySequence::GenericColorPropertySequence(std::string keywordName, callback_t setCallback) : m_set_callback(std::move(setCallback)) { + const MenuMatcherFactory create(this); + + AddLabeledMatchers(MenuExpressionMatchers().Expression(this), MenuExpressionMatchers::LABEL_EXPRESSION); + AddMatchers({ + create.KeywordIgnoreCase(std::move(keywordName)).Capture(CAPTURE_FIRST_TOKEN), + create.NumericExpression().Tag(TAG_COLOR), // r + create.Optional(create.NumericExpression().Tag(TAG_COLOR)), // g + create.Optional(create.NumericExpression().Tag(TAG_COLOR)), // b + create.Optional(create.NumericExpression().Tag(TAG_COLOR)) // a + }); } -double GenericColorPropertySequence::ReadColorValue(MenuFileParserState* state, SequenceResult<SimpleParserValue>& result) -{ - if (result.PeekAndRemoveIfTag(TAG_COLOR) == TAG_COLOR) - return MenuMatcherFactory::TokenNumericExpressionValue(state, result); +double GenericColorPropertySequence::ReadColorValue(MenuFileParserState *state, SequenceResult<SimpleParserValue> &result) { + if (result.PeekAndRemoveIfTag(TAG_COLOR) == TAG_COLOR) + return MenuMatcherFactory::TokenNumericExpressionValue(state, result); - return 0.0; + return 0.0; } -void GenericColorPropertySequence::ProcessMatch(MenuFileParserState* state, SequenceResult<SimpleParserValue>& result) const -{ - if (m_set_callback) - { - CommonColor color{}; - color.r = ReadColorValue(state, result); - color.g = ReadColorValue(state, result); - color.b = ReadColorValue(state, result); - color.a = ReadColorValue(state, result); - - m_set_callback(state, result.NextCapture(CAPTURE_FIRST_TOKEN).GetPos(), color); - } +void GenericColorPropertySequence::ProcessMatch(MenuFileParserState *state, SequenceResult<SimpleParserValue> &result) const { + if (m_set_callback) { + CommonColor color{}; + color.r = ReadColorValue(state, result); + color.g = ReadColorValue(state, result); + color.b = ReadColorValue(state, result); + color.a = ReadColorValue(state, result); + + m_set_callback(state, result.NextCapture(CAPTURE_FIRST_TOKEN).GetPos(), color); + } } diff --git a/src/ObjLoading/Parsing/Menu/Sequence/Generic/GenericColorPropertySequence.h b/src/ObjLoading/Parsing/Menu/Sequence/Generic/GenericColorPropertySequence.h index 49a0045a2..e35317752 100644 --- a/src/ObjLoading/Parsing/Menu/Sequence/Generic/GenericColorPropertySequence.h +++ b/src/ObjLoading/Parsing/Menu/Sequence/Generic/GenericColorPropertySequence.h @@ -1,31 +1,29 @@ #pragma once -#include <string> #include <functional> +#include <string> -#include "Parsing/Menu/MenuFileParser.h" #include "Parsing/Menu/Domain/CommonMenuTypes.h" +#include "Parsing/Menu/MenuFileParser.h" -namespace menu -{ - class GenericColorPropertySequence final : public MenuFileParser::sequence_t - { - public: - using callback_t = std::function<void(MenuFileParserState* state, const TokenPos& pos, CommonColor value)>; +namespace menu { +class GenericColorPropertySequence final : public MenuFileParser::sequence_t { +public: + using callback_t = std::function<void(MenuFileParserState *state, const TokenPos &pos, CommonColor value)>; - private: - static constexpr auto CAPTURE_FIRST_TOKEN = 1; +private: + static constexpr auto CAPTURE_FIRST_TOKEN = 1; - static constexpr auto TAG_COLOR = 1; + static constexpr auto TAG_COLOR = 1; - const callback_t m_set_callback; + const callback_t m_set_callback; - static double ReadColorValue(MenuFileParserState* state, SequenceResult<SimpleParserValue>& result); + static double ReadColorValue(MenuFileParserState *state, SequenceResult<SimpleParserValue> &result); - protected: - void ProcessMatch(MenuFileParserState* state, SequenceResult<SimpleParserValue>& result) const override; +protected: + void ProcessMatch(MenuFileParserState *state, SequenceResult<SimpleParserValue> &result) const override; - public: - GenericColorPropertySequence(std::string keywordName, callback_t setCallback); - }; -} +public: + GenericColorPropertySequence(std::string keywordName, callback_t setCallback); +}; +} // namespace menu diff --git a/src/ObjLoading/Parsing/Menu/Sequence/Generic/GenericExpressionPropertySequence.cpp b/src/ObjLoading/Parsing/Menu/Sequence/Generic/GenericExpressionPropertySequence.cpp index bfde58c7c..170d7b62f 100644 --- a/src/ObjLoading/Parsing/Menu/Sequence/Generic/GenericExpressionPropertySequence.cpp +++ b/src/ObjLoading/Parsing/Menu/Sequence/Generic/GenericExpressionPropertySequence.cpp @@ -7,66 +7,50 @@ using namespace menu; -GenericExpressionPropertySequence::GenericExpressionPropertySequence(callback_t setCallback) - : m_set_callback(std::move(setCallback)) -{ - const MenuExpressionMatchers expressionMatchers; - AddLabeledMatchers(expressionMatchers.Expression(this), MenuExpressionMatchers::LABEL_EXPRESSION); +GenericExpressionPropertySequence::GenericExpressionPropertySequence(callback_t setCallback) : m_set_callback(std::move(setCallback)) { + const MenuExpressionMatchers expressionMatchers; + AddLabeledMatchers(expressionMatchers.Expression(this), MenuExpressionMatchers::LABEL_EXPRESSION); } -std::unique_ptr<GenericExpressionPropertySequence> GenericExpressionPropertySequence::WithKeyword(std::string keyword, callback_t setCallback) -{ - auto result = std::unique_ptr<GenericExpressionPropertySequence>(new GenericExpressionPropertySequence(std::move(setCallback))); +std::unique_ptr<GenericExpressionPropertySequence> GenericExpressionPropertySequence::WithKeyword(std::string keyword, callback_t setCallback) { + auto result = std::unique_ptr<GenericExpressionPropertySequence>(new GenericExpressionPropertySequence(std::move(setCallback))); - const MenuMatcherFactory create(result.get()); - result->AddMatchers({ - create.KeywordIgnoreCase(std::move(keyword)).Capture(CAPTURE_FIRST_TOKEN), - create.Label(MenuExpressionMatchers::LABEL_EXPRESSION), - create.Optional(create.Char(';')) - }); + const MenuMatcherFactory create(result.get()); + result->AddMatchers({create.KeywordIgnoreCase(std::move(keyword)).Capture(CAPTURE_FIRST_TOKEN), create.Label(MenuExpressionMatchers::LABEL_EXPRESSION), + create.Optional(create.Char(';'))}); - return std::move(result); + return std::move(result); } -std::unique_ptr<GenericExpressionPropertySequence> GenericExpressionPropertySequence::WithKeywords(const std::initializer_list<std::string> keywords, callback_t setCallback) -{ - auto result = std::unique_ptr<GenericExpressionPropertySequence>(new GenericExpressionPropertySequence(std::move(setCallback))); +std::unique_ptr<GenericExpressionPropertySequence> GenericExpressionPropertySequence::WithKeywords(const std::initializer_list<std::string> keywords, + callback_t setCallback) { + auto result = std::unique_ptr<GenericExpressionPropertySequence>(new GenericExpressionPropertySequence(std::move(setCallback))); - const MenuMatcherFactory create(result.get()); - std::vector<std::unique_ptr<matcher_t>> keywordMatchers; - for (auto keyword : keywords) - keywordMatchers.emplace_back(create.KeywordIgnoreCase(std::move(keyword))); + const MenuMatcherFactory create(result.get()); + std::vector<std::unique_ptr<matcher_t>> keywordMatchers; + for (auto keyword : keywords) + keywordMatchers.emplace_back(create.KeywordIgnoreCase(std::move(keyword))); - result->AddMatchers({ - create.And(std::move(keywordMatchers)).Capture(CAPTURE_FIRST_TOKEN), - create.Label(MenuExpressionMatchers::LABEL_EXPRESSION), - create.Optional(create.Char(';')) - }); + result->AddMatchers({create.And(std::move(keywordMatchers)).Capture(CAPTURE_FIRST_TOKEN), create.Label(MenuExpressionMatchers::LABEL_EXPRESSION), + create.Optional(create.Char(';'))}); - return std::move(result); + return std::move(result); } -std::unique_ptr<GenericExpressionPropertySequence> GenericExpressionPropertySequence::WithKeywordAndBool(std::string keyword, callback_t setCallback) -{ - auto result = std::unique_ptr<GenericExpressionPropertySequence>(new GenericExpressionPropertySequence(std::move(setCallback))); +std::unique_ptr<GenericExpressionPropertySequence> GenericExpressionPropertySequence::WithKeywordAndBool(std::string keyword, callback_t setCallback) { + auto result = std::unique_ptr<GenericExpressionPropertySequence>(new GenericExpressionPropertySequence(std::move(setCallback))); - const MenuMatcherFactory create(result.get()); - result->AddMatchers({ - create.KeywordIgnoreCase(std::move(keyword)).Capture(CAPTURE_FIRST_TOKEN), - create.Optional(create.KeywordIgnoreCase("when")), - create.Label(MenuExpressionMatchers::LABEL_EXPRESSION), - create.Optional(create.Char(';')) - }); + const MenuMatcherFactory create(result.get()); + result->AddMatchers({create.KeywordIgnoreCase(std::move(keyword)).Capture(CAPTURE_FIRST_TOKEN), create.Optional(create.KeywordIgnoreCase("when")), + create.Label(MenuExpressionMatchers::LABEL_EXPRESSION), create.Optional(create.Char(';'))}); - return std::move(result); + return std::move(result); } -void GenericExpressionPropertySequence::ProcessMatch(MenuFileParserState* state, SequenceResult<SimpleParserValue>& result) const -{ - if (m_set_callback) - { - const MenuExpressionMatchers expressionMatchers(state); - auto expression = expressionMatchers.ProcessExpression(result); - m_set_callback(state, result.NextCapture(CAPTURE_FIRST_TOKEN).GetPos(), std::move(expression)); - } +void GenericExpressionPropertySequence::ProcessMatch(MenuFileParserState *state, SequenceResult<SimpleParserValue> &result) const { + if (m_set_callback) { + const MenuExpressionMatchers expressionMatchers(state); + auto expression = expressionMatchers.ProcessExpression(result); + m_set_callback(state, result.NextCapture(CAPTURE_FIRST_TOKEN).GetPos(), std::move(expression)); + } } diff --git a/src/ObjLoading/Parsing/Menu/Sequence/Generic/GenericExpressionPropertySequence.h b/src/ObjLoading/Parsing/Menu/Sequence/Generic/GenericExpressionPropertySequence.h index dab86f5e8..5a29dc36e 100644 --- a/src/ObjLoading/Parsing/Menu/Sequence/Generic/GenericExpressionPropertySequence.h +++ b/src/ObjLoading/Parsing/Menu/Sequence/Generic/GenericExpressionPropertySequence.h @@ -1,32 +1,30 @@ #pragma once -#include <string> #include <functional> +#include <string> #include "Parsing/Menu/MenuFileParser.h" #include "Parsing/Simple/Expression/ISimpleExpression.h" -namespace menu -{ - class GenericExpressionPropertySequence final : public MenuFileParser::sequence_t - { - public: - using callback_t = std::function<void(MenuFileParserState* state, const TokenPos& pos, std::unique_ptr<ISimpleExpression> value)>; +namespace menu { +class GenericExpressionPropertySequence final : public MenuFileParser::sequence_t { +public: + using callback_t = std::function<void(MenuFileParserState *state, const TokenPos &pos, std::unique_ptr<ISimpleExpression> value)>; - private: - static constexpr auto CAPTURE_FIRST_TOKEN = 1; +private: + static constexpr auto CAPTURE_FIRST_TOKEN = 1; - const callback_t m_set_callback; + const callback_t m_set_callback; - protected: - void ProcessMatch(MenuFileParserState* state, SequenceResult<SimpleParserValue>& result) const override; +protected: + void ProcessMatch(MenuFileParserState *state, SequenceResult<SimpleParserValue> &result) const override; - private: - explicit GenericExpressionPropertySequence(callback_t setCallback); +private: + explicit GenericExpressionPropertySequence(callback_t setCallback); - public: - static std::unique_ptr<GenericExpressionPropertySequence> WithKeyword(std::string keyword, callback_t setCallback); - static std::unique_ptr<GenericExpressionPropertySequence> WithKeywords(std::initializer_list<std::string> keywords, callback_t setCallback); - static std::unique_ptr<GenericExpressionPropertySequence> WithKeywordAndBool(std::string keyword, callback_t setCallback); - }; -} +public: + static std::unique_ptr<GenericExpressionPropertySequence> WithKeyword(std::string keyword, callback_t setCallback); + static std::unique_ptr<GenericExpressionPropertySequence> WithKeywords(std::initializer_list<std::string> keywords, callback_t setCallback); + static std::unique_ptr<GenericExpressionPropertySequence> WithKeywordAndBool(std::string keyword, callback_t setCallback); +}; +} // namespace menu diff --git a/src/ObjLoading/Parsing/Menu/Sequence/Generic/GenericFloatingPointPropertySequence.cpp b/src/ObjLoading/Parsing/Menu/Sequence/Generic/GenericFloatingPointPropertySequence.cpp index 14ebd5421..daa13590f 100644 --- a/src/ObjLoading/Parsing/Menu/Sequence/Generic/GenericFloatingPointPropertySequence.cpp +++ b/src/ObjLoading/Parsing/Menu/Sequence/Generic/GenericFloatingPointPropertySequence.cpp @@ -8,22 +8,16 @@ using namespace menu; GenericFloatingPointPropertySequence::GenericFloatingPointPropertySequence(std::string keywordName, callback_t setCallback) - : m_set_callback(std::move(setCallback)) -{ - const MenuMatcherFactory create(this); + : m_set_callback(std::move(setCallback)) { + const MenuMatcherFactory create(this); - AddLabeledMatchers(MenuExpressionMatchers().Expression(this), MenuExpressionMatchers::LABEL_EXPRESSION); - AddMatchers({ - create.KeywordIgnoreCase(std::move(keywordName)).Capture(CAPTURE_FIRST_TOKEN), - create.NumericExpression() - }); + AddLabeledMatchers(MenuExpressionMatchers().Expression(this), MenuExpressionMatchers::LABEL_EXPRESSION); + AddMatchers({create.KeywordIgnoreCase(std::move(keywordName)).Capture(CAPTURE_FIRST_TOKEN), create.NumericExpression()}); } -void GenericFloatingPointPropertySequence::ProcessMatch(MenuFileParserState* state, SequenceResult<SimpleParserValue>& result) const -{ - if (m_set_callback) - { - const auto value = MenuMatcherFactory::TokenNumericExpressionValue(state, result); - m_set_callback(state, result.NextCapture(CAPTURE_FIRST_TOKEN).GetPos(), value); - } +void GenericFloatingPointPropertySequence::ProcessMatch(MenuFileParserState *state, SequenceResult<SimpleParserValue> &result) const { + if (m_set_callback) { + const auto value = MenuMatcherFactory::TokenNumericExpressionValue(state, result); + m_set_callback(state, result.NextCapture(CAPTURE_FIRST_TOKEN).GetPos(), value); + } } diff --git a/src/ObjLoading/Parsing/Menu/Sequence/Generic/GenericFloatingPointPropertySequence.h b/src/ObjLoading/Parsing/Menu/Sequence/Generic/GenericFloatingPointPropertySequence.h index a424928e1..2df0a76d2 100644 --- a/src/ObjLoading/Parsing/Menu/Sequence/Generic/GenericFloatingPointPropertySequence.h +++ b/src/ObjLoading/Parsing/Menu/Sequence/Generic/GenericFloatingPointPropertySequence.h @@ -1,26 +1,24 @@ #pragma once -#include <string> #include <functional> +#include <string> #include "Parsing/Menu/MenuFileParser.h" -namespace menu -{ - class GenericFloatingPointPropertySequence final : public MenuFileParser::sequence_t - { - public: - using callback_t = std::function<void(MenuFileParserState* state, const TokenPos& pos, double value)>; +namespace menu { +class GenericFloatingPointPropertySequence final : public MenuFileParser::sequence_t { +public: + using callback_t = std::function<void(MenuFileParserState *state, const TokenPos &pos, double value)>; - private: - static constexpr auto CAPTURE_FIRST_TOKEN = 1; +private: + static constexpr auto CAPTURE_FIRST_TOKEN = 1; - const callback_t m_set_callback; + const callback_t m_set_callback; - protected: - void ProcessMatch(MenuFileParserState* state, SequenceResult<SimpleParserValue>& result) const override; +protected: + void ProcessMatch(MenuFileParserState *state, SequenceResult<SimpleParserValue> &result) const override; - public: - GenericFloatingPointPropertySequence(std::string keywordName, callback_t setCallback); - }; -} +public: + GenericFloatingPointPropertySequence(std::string keywordName, callback_t setCallback); +}; +} // namespace menu diff --git a/src/ObjLoading/Parsing/Menu/Sequence/Generic/GenericIntPropertySequence.cpp b/src/ObjLoading/Parsing/Menu/Sequence/Generic/GenericIntPropertySequence.cpp index d2747dd15..b008614fe 100644 --- a/src/ObjLoading/Parsing/Menu/Sequence/Generic/GenericIntPropertySequence.cpp +++ b/src/ObjLoading/Parsing/Menu/Sequence/Generic/GenericIntPropertySequence.cpp @@ -7,23 +7,19 @@ using namespace menu; -GenericIntPropertySequence::GenericIntPropertySequence(std::string keywordName, callback_t setCallback) - : m_set_callback(std::move(setCallback)) -{ - const MenuMatcherFactory create(this); +GenericIntPropertySequence::GenericIntPropertySequence(std::string keywordName, callback_t setCallback) : m_set_callback(std::move(setCallback)) { + const MenuMatcherFactory create(this); - AddLabeledMatchers(MenuExpressionMatchers().Expression(this), MenuExpressionMatchers::LABEL_EXPRESSION); - AddMatchers({ - create.KeywordIgnoreCase(std::move(keywordName)).Capture(CAPTURE_FIRST_TOKEN), - create.IntExpression(), // value - }); + AddLabeledMatchers(MenuExpressionMatchers().Expression(this), MenuExpressionMatchers::LABEL_EXPRESSION); + AddMatchers({ + create.KeywordIgnoreCase(std::move(keywordName)).Capture(CAPTURE_FIRST_TOKEN), + create.IntExpression(), // value + }); } -void GenericIntPropertySequence::ProcessMatch(MenuFileParserState* state, SequenceResult<SimpleParserValue>& result) const -{ - if (m_set_callback) - { - const auto value = MenuMatcherFactory::TokenIntExpressionValue(state, result); - m_set_callback(state, result.NextCapture(CAPTURE_FIRST_TOKEN).GetPos(), value); - } +void GenericIntPropertySequence::ProcessMatch(MenuFileParserState *state, SequenceResult<SimpleParserValue> &result) const { + if (m_set_callback) { + const auto value = MenuMatcherFactory::TokenIntExpressionValue(state, result); + m_set_callback(state, result.NextCapture(CAPTURE_FIRST_TOKEN).GetPos(), value); + } } diff --git a/src/ObjLoading/Parsing/Menu/Sequence/Generic/GenericIntPropertySequence.h b/src/ObjLoading/Parsing/Menu/Sequence/Generic/GenericIntPropertySequence.h index 63c6a73d1..7a2dcfdee 100644 --- a/src/ObjLoading/Parsing/Menu/Sequence/Generic/GenericIntPropertySequence.h +++ b/src/ObjLoading/Parsing/Menu/Sequence/Generic/GenericIntPropertySequence.h @@ -1,26 +1,24 @@ #pragma once -#include <string> #include <functional> +#include <string> #include "Parsing/Menu/MenuFileParser.h" -namespace menu -{ - class GenericIntPropertySequence final : public MenuFileParser::sequence_t - { - public: - using callback_t = std::function<void(MenuFileParserState* state, const TokenPos& pos, int value)>; +namespace menu { +class GenericIntPropertySequence final : public MenuFileParser::sequence_t { +public: + using callback_t = std::function<void(MenuFileParserState *state, const TokenPos &pos, int value)>; - private: - static constexpr auto CAPTURE_FIRST_TOKEN = 1; +private: + static constexpr auto CAPTURE_FIRST_TOKEN = 1; - const callback_t m_set_callback; + const callback_t m_set_callback; - protected: - void ProcessMatch(MenuFileParserState* state, SequenceResult<SimpleParserValue>& result) const override; +protected: + void ProcessMatch(MenuFileParserState *state, SequenceResult<SimpleParserValue> &result) const override; - public: - GenericIntPropertySequence(std::string keywordName, callback_t setCallback); - }; -} +public: + GenericIntPropertySequence(std::string keywordName, callback_t setCallback); +}; +} // namespace menu diff --git a/src/ObjLoading/Parsing/Menu/Sequence/Generic/GenericKeywordPropertySequence.cpp b/src/ObjLoading/Parsing/Menu/Sequence/Generic/GenericKeywordPropertySequence.cpp index 2a8033b28..9b0143a10 100644 --- a/src/ObjLoading/Parsing/Menu/Sequence/Generic/GenericKeywordPropertySequence.cpp +++ b/src/ObjLoading/Parsing/Menu/Sequence/Generic/GenericKeywordPropertySequence.cpp @@ -6,20 +6,16 @@ using namespace menu; -GenericKeywordPropertySequence::GenericKeywordPropertySequence(std::string keywordName, callback_t setCallback) - : m_set_callback(std::move(setCallback)) -{ - const MenuMatcherFactory create(this); +GenericKeywordPropertySequence::GenericKeywordPropertySequence(std::string keywordName, callback_t setCallback) : m_set_callback(std::move(setCallback)) { + const MenuMatcherFactory create(this); - AddMatchers({ - create.KeywordIgnoreCase(std::move(keywordName)).Capture(CAPTURE_FIRST_TOKEN), - }); + AddMatchers({ + create.KeywordIgnoreCase(std::move(keywordName)).Capture(CAPTURE_FIRST_TOKEN), + }); } -void GenericKeywordPropertySequence::ProcessMatch(MenuFileParserState* state, SequenceResult<SimpleParserValue>& result) const -{ - if (m_set_callback) - { - m_set_callback(state, result.NextCapture(CAPTURE_FIRST_TOKEN).GetPos()); - } +void GenericKeywordPropertySequence::ProcessMatch(MenuFileParserState *state, SequenceResult<SimpleParserValue> &result) const { + if (m_set_callback) { + m_set_callback(state, result.NextCapture(CAPTURE_FIRST_TOKEN).GetPos()); + } } diff --git a/src/ObjLoading/Parsing/Menu/Sequence/Generic/GenericKeywordPropertySequence.h b/src/ObjLoading/Parsing/Menu/Sequence/Generic/GenericKeywordPropertySequence.h index 4d67ad830..b8da8a432 100644 --- a/src/ObjLoading/Parsing/Menu/Sequence/Generic/GenericKeywordPropertySequence.h +++ b/src/ObjLoading/Parsing/Menu/Sequence/Generic/GenericKeywordPropertySequence.h @@ -1,26 +1,24 @@ #pragma once -#include <string> #include <functional> +#include <string> #include "Parsing/Menu/MenuFileParser.h" -namespace menu -{ - class GenericKeywordPropertySequence final : public MenuFileParser::sequence_t - { - public: - using callback_t = std::function<void(MenuFileParserState* state, const TokenPos& pos)>; +namespace menu { +class GenericKeywordPropertySequence final : public MenuFileParser::sequence_t { +public: + using callback_t = std::function<void(MenuFileParserState *state, const TokenPos &pos)>; - private: - static constexpr auto CAPTURE_FIRST_TOKEN = 1; +private: + static constexpr auto CAPTURE_FIRST_TOKEN = 1; - const callback_t m_set_callback; + const callback_t m_set_callback; - protected: - void ProcessMatch(MenuFileParserState* state, SequenceResult<SimpleParserValue>& result) const override; +protected: + void ProcessMatch(MenuFileParserState *state, SequenceResult<SimpleParserValue> &result) const override; - public: - GenericKeywordPropertySequence(std::string keywordName, callback_t setCallback); - }; -} +public: + GenericKeywordPropertySequence(std::string keywordName, callback_t setCallback); +}; +} // namespace menu diff --git a/src/ObjLoading/Parsing/Menu/Sequence/Generic/GenericMenuEventHandlerSetPropertySequence.cpp b/src/ObjLoading/Parsing/Menu/Sequence/Generic/GenericMenuEventHandlerSetPropertySequence.cpp index fafcfcc9d..7c196587a 100644 --- a/src/ObjLoading/Parsing/Menu/Sequence/Generic/GenericMenuEventHandlerSetPropertySequence.cpp +++ b/src/ObjLoading/Parsing/Menu/Sequence/Generic/GenericMenuEventHandlerSetPropertySequence.cpp @@ -7,25 +7,19 @@ using namespace menu; GenericMenuEventHandlerSetPropertySequence::GenericMenuEventHandlerSetPropertySequence(std::string keywordName, callback_t setCallback) - : m_set_callback(std::move(setCallback)) -{ - const MenuMatcherFactory create(this); + : m_set_callback(std::move(setCallback)) { + const MenuMatcherFactory create(this); - AddMatchers({ - create.KeywordIgnoreCase(std::move(keywordName)).Capture(CAPTURE_FIRST_TOKEN), - create.Char('{') - }); + AddMatchers({create.KeywordIgnoreCase(std::move(keywordName)).Capture(CAPTURE_FIRST_TOKEN), create.Char('{')}); } -void GenericMenuEventHandlerSetPropertySequence::ProcessMatch(MenuFileParserState* state, SequenceResult<SimpleParserValue>& result) const -{ - if (m_set_callback) - { - auto& eventHandlerPtr = m_set_callback(state, result.NextCapture(CAPTURE_FIRST_TOKEN).GetPos()); - if(!eventHandlerPtr) - eventHandlerPtr = std::make_unique<CommonEventHandlerSet>(); +void GenericMenuEventHandlerSetPropertySequence::ProcessMatch(MenuFileParserState *state, SequenceResult<SimpleParserValue> &result) const { + if (m_set_callback) { + auto &eventHandlerPtr = m_set_callback(state, result.NextCapture(CAPTURE_FIRST_TOKEN).GetPos()); + if (!eventHandlerPtr) + eventHandlerPtr = std::make_unique<CommonEventHandlerSet>(); - state->m_current_event_handler_set = eventHandlerPtr.get(); - state->m_current_nested_event_handler_set = eventHandlerPtr.get(); - } + state->m_current_event_handler_set = eventHandlerPtr.get(); + state->m_current_nested_event_handler_set = eventHandlerPtr.get(); + } } diff --git a/src/ObjLoading/Parsing/Menu/Sequence/Generic/GenericMenuEventHandlerSetPropertySequence.h b/src/ObjLoading/Parsing/Menu/Sequence/Generic/GenericMenuEventHandlerSetPropertySequence.h index 217c753f0..e56937282 100644 --- a/src/ObjLoading/Parsing/Menu/Sequence/Generic/GenericMenuEventHandlerSetPropertySequence.h +++ b/src/ObjLoading/Parsing/Menu/Sequence/Generic/GenericMenuEventHandlerSetPropertySequence.h @@ -1,27 +1,25 @@ #pragma once -#include <string> #include <functional> +#include <string> -#include "Parsing/Menu/MenuFileParser.h" #include "Parsing/Menu/Domain/EventHandler/CommonEventHandlerSet.h" +#include "Parsing/Menu/MenuFileParser.h" -namespace menu -{ - class GenericMenuEventHandlerSetPropertySequence final : public MenuFileParser::sequence_t - { - public: - using callback_t = std::function<std::unique_ptr<CommonEventHandlerSet>& (MenuFileParserState* state, const TokenPos& pos)>; +namespace menu { +class GenericMenuEventHandlerSetPropertySequence final : public MenuFileParser::sequence_t { +public: + using callback_t = std::function<std::unique_ptr<CommonEventHandlerSet> &(MenuFileParserState *state, const TokenPos &pos)>; - private: - static constexpr auto CAPTURE_FIRST_TOKEN = 1; +private: + static constexpr auto CAPTURE_FIRST_TOKEN = 1; - const callback_t m_set_callback; + const callback_t m_set_callback; - protected: - void ProcessMatch(MenuFileParserState* state, SequenceResult<SimpleParserValue>& result) const override; +protected: + void ProcessMatch(MenuFileParserState *state, SequenceResult<SimpleParserValue> &result) const override; - public: - GenericMenuEventHandlerSetPropertySequence(std::string keywordName, callback_t setCallback); - }; -} +public: + GenericMenuEventHandlerSetPropertySequence(std::string keywordName, callback_t setCallback); +}; +} // namespace menu diff --git a/src/ObjLoading/Parsing/Menu/Sequence/Generic/GenericStringPropertySequence.cpp b/src/ObjLoading/Parsing/Menu/Sequence/Generic/GenericStringPropertySequence.cpp index 8e554fd6e..5bd4a102c 100644 --- a/src/ObjLoading/Parsing/Menu/Sequence/Generic/GenericStringPropertySequence.cpp +++ b/src/ObjLoading/Parsing/Menu/Sequence/Generic/GenericStringPropertySequence.cpp @@ -6,22 +6,15 @@ using namespace menu; -GenericStringPropertySequence::GenericStringPropertySequence(std::string keywordName, callback_t setCallback) - : m_set_callback(std::move(setCallback)) -{ - const MenuMatcherFactory create(this); +GenericStringPropertySequence::GenericStringPropertySequence(std::string keywordName, callback_t setCallback) : m_set_callback(std::move(setCallback)) { + const MenuMatcherFactory create(this); - AddMatchers({ - create.KeywordIgnoreCase(std::move(keywordName)).Capture(CAPTURE_FIRST_TOKEN), - create.Text().Capture(CAPTURE_VALUE) - }); + AddMatchers({create.KeywordIgnoreCase(std::move(keywordName)).Capture(CAPTURE_FIRST_TOKEN), create.Text().Capture(CAPTURE_VALUE)}); } -void GenericStringPropertySequence::ProcessMatch(MenuFileParserState* state, SequenceResult<SimpleParserValue>& result) const -{ - if (m_set_callback) - { - const auto& value = MenuMatcherFactory::TokenTextValue(result.NextCapture(CAPTURE_VALUE)); - m_set_callback(state, result.NextCapture(CAPTURE_FIRST_TOKEN).GetPos(), value); - } +void GenericStringPropertySequence::ProcessMatch(MenuFileParserState *state, SequenceResult<SimpleParserValue> &result) const { + if (m_set_callback) { + const auto &value = MenuMatcherFactory::TokenTextValue(result.NextCapture(CAPTURE_VALUE)); + m_set_callback(state, result.NextCapture(CAPTURE_FIRST_TOKEN).GetPos(), value); + } } diff --git a/src/ObjLoading/Parsing/Menu/Sequence/Generic/GenericStringPropertySequence.h b/src/ObjLoading/Parsing/Menu/Sequence/Generic/GenericStringPropertySequence.h index 1f35d9fef..f3fd8a5fa 100644 --- a/src/ObjLoading/Parsing/Menu/Sequence/Generic/GenericStringPropertySequence.h +++ b/src/ObjLoading/Parsing/Menu/Sequence/Generic/GenericStringPropertySequence.h @@ -1,27 +1,25 @@ #pragma once -#include <string> #include <functional> +#include <string> #include "Parsing/Menu/MenuFileParser.h" -namespace menu -{ - class GenericStringPropertySequence final : public MenuFileParser::sequence_t - { - public: - using callback_t = std::function<void(MenuFileParserState* state, const TokenPos& pos, const std::string& value)>; +namespace menu { +class GenericStringPropertySequence final : public MenuFileParser::sequence_t { +public: + using callback_t = std::function<void(MenuFileParserState *state, const TokenPos &pos, const std::string &value)>; - private: - static constexpr auto CAPTURE_FIRST_TOKEN = 1; - static constexpr auto CAPTURE_VALUE = 2; +private: + static constexpr auto CAPTURE_FIRST_TOKEN = 1; + static constexpr auto CAPTURE_VALUE = 2; - const callback_t m_set_callback; + const callback_t m_set_callback; - protected: - void ProcessMatch(MenuFileParserState* state, SequenceResult<SimpleParserValue>& result) const override; +protected: + void ProcessMatch(MenuFileParserState *state, SequenceResult<SimpleParserValue> &result) const override; - public: - GenericStringPropertySequence(std::string keywordName, callback_t setCallback); - }; -} +public: + GenericStringPropertySequence(std::string keywordName, callback_t setCallback); +}; +} // namespace menu diff --git a/src/ObjLoading/Parsing/Menu/Sequence/GlobalScopeSequences.cpp b/src/ObjLoading/Parsing/Menu/Sequence/GlobalScopeSequences.cpp index 989544669..ba6911d80 100644 --- a/src/ObjLoading/Parsing/Menu/Sequence/GlobalScopeSequences.cpp +++ b/src/ObjLoading/Parsing/Menu/Sequence/GlobalScopeSequences.cpp @@ -5,112 +5,93 @@ using namespace menu; -namespace menu::global_scope_sequences -{ - class SequenceCloseBlock final : public MenuFileParser::sequence_t - { - public: - SequenceCloseBlock() - { - const MenuMatcherFactory create(this); - - AddMatchers({ - create.Char('}') - }); - } - - protected: - void ProcessMatch(MenuFileParserState* state, SequenceResult<SimpleParserValue>& result) const override - { - state->m_in_global_scope = false; - } - }; - - class SequenceFunctionDef final : public MenuFileParser::sequence_t - { - public: - SequenceFunctionDef() - { - const MenuMatcherFactory create(this); - - AddMatchers({ - create.Keyword("functionDef"), - create.Char('{'), - }); - } - - protected: - void ProcessMatch(MenuFileParserState* state, SequenceResult<SimpleParserValue>& result) const override - { - auto newFunction = std::make_unique<CommonFunctionDef>(); - state->m_current_function = newFunction.get(); - state->m_functions.emplace_back(std::move(newFunction)); - } - }; - - class SequenceMenuDef final : public MenuFileParser::sequence_t - { - public: - SequenceMenuDef() - { - const MenuMatcherFactory create(this); - - AddMatchers({ - create.Keyword("menuDef"), - create.Char('{'), - }); - } - - protected: - void ProcessMatch(MenuFileParserState* state, SequenceResult<SimpleParserValue>& result) const override - { - auto newMenu = std::make_unique<CommonMenuDef>(); - state->m_current_menu = newMenu.get(); - state->m_menus.emplace_back(std::move(newMenu)); - } - }; - - class SequenceLoadMenu final : public MenuFileParser::sequence_t - { - static constexpr auto CAPTURE_MENU_NAME = 1; - - public: - SequenceLoadMenu() - { - const MenuMatcherFactory create(this); - - AddMatchers({ - create.Keyword("loadMenu"), - create.Char('{'), - create.StringChain().Capture(CAPTURE_MENU_NAME), - create.Char('}'), - }); - } - - protected: - void ProcessMatch(MenuFileParserState* state, SequenceResult<SimpleParserValue>& result) const override - { - const auto& menuNameToken = result.NextCapture(CAPTURE_MENU_NAME); - - if (menuNameToken.StringValue().empty()) - throw ParsingException(menuNameToken.GetPos(), "Invalid menu name"); - - state->m_menus_to_load.emplace_back(menuNameToken.StringValue()); - } - }; -} +namespace menu::global_scope_sequences { +class SequenceCloseBlock final : public MenuFileParser::sequence_t { +public: + SequenceCloseBlock() { + const MenuMatcherFactory create(this); + + AddMatchers({create.Char('}')}); + } + +protected: + void ProcessMatch(MenuFileParserState *state, SequenceResult<SimpleParserValue> &result) const override { state->m_in_global_scope = false; } +}; + +class SequenceFunctionDef final : public MenuFileParser::sequence_t { +public: + SequenceFunctionDef() { + const MenuMatcherFactory create(this); + + AddMatchers({ + create.Keyword("functionDef"), + create.Char('{'), + }); + } + +protected: + void ProcessMatch(MenuFileParserState *state, SequenceResult<SimpleParserValue> &result) const override { + auto newFunction = std::make_unique<CommonFunctionDef>(); + state->m_current_function = newFunction.get(); + state->m_functions.emplace_back(std::move(newFunction)); + } +}; + +class SequenceMenuDef final : public MenuFileParser::sequence_t { +public: + SequenceMenuDef() { + const MenuMatcherFactory create(this); + + AddMatchers({ + create.Keyword("menuDef"), + create.Char('{'), + }); + } + +protected: + void ProcessMatch(MenuFileParserState *state, SequenceResult<SimpleParserValue> &result) const override { + auto newMenu = std::make_unique<CommonMenuDef>(); + state->m_current_menu = newMenu.get(); + state->m_menus.emplace_back(std::move(newMenu)); + } +}; + +class SequenceLoadMenu final : public MenuFileParser::sequence_t { + static constexpr auto CAPTURE_MENU_NAME = 1; + +public: + SequenceLoadMenu() { + const MenuMatcherFactory create(this); + + AddMatchers({ + create.Keyword("loadMenu"), + create.Char('{'), + create.StringChain().Capture(CAPTURE_MENU_NAME), + create.Char('}'), + }); + } + +protected: + void ProcessMatch(MenuFileParserState *state, SequenceResult<SimpleParserValue> &result) const override { + const auto &menuNameToken = result.NextCapture(CAPTURE_MENU_NAME); + + if (menuNameToken.StringValue().empty()) + throw ParsingException(menuNameToken.GetPos(), "Invalid menu name"); + + state->m_menus_to_load.emplace_back(menuNameToken.StringValue()); + } +}; +} // namespace menu::global_scope_sequences using namespace global_scope_sequences; -GlobalScopeSequences::GlobalScopeSequences(std::vector<std::unique_ptr<MenuFileParser::sequence_t>>& allSequences, std::vector<MenuFileParser::sequence_t*>& scopeSequences) - : AbstractScopeSequenceHolder(allSequences, scopeSequences) -{ -} +GlobalScopeSequences::GlobalScopeSequences(std::vector<std::unique_ptr<MenuFileParser::sequence_t>> &allSequences, + std::vector<MenuFileParser::sequence_t *> &scopeSequences) + : AbstractScopeSequenceHolder(allSequences, scopeSequences) {} -void GlobalScopeSequences::AddSequences(FeatureLevel featureLevel, bool permissive) const -{ - AddSequence(std::make_unique<SequenceCloseBlock>()); - AddSequence(std::make_unique<SequenceFunctionDef>()); - AddSequence(std::make_unique<SequenceMenuDef>()); - AddSequence(std::make_unique<SequenceLoadMenu>()); +void GlobalScopeSequences::AddSequences(FeatureLevel featureLevel, bool permissive) const { + AddSequence(std::make_unique<SequenceCloseBlock>()); + AddSequence(std::make_unique<SequenceFunctionDef>()); + AddSequence(std::make_unique<SequenceMenuDef>()); + AddSequence(std::make_unique<SequenceLoadMenu>()); } diff --git a/src/ObjLoading/Parsing/Menu/Sequence/GlobalScopeSequences.h b/src/ObjLoading/Parsing/Menu/Sequence/GlobalScopeSequences.h index e6b5d3fa5..34e892237 100644 --- a/src/ObjLoading/Parsing/Menu/Sequence/GlobalScopeSequences.h +++ b/src/ObjLoading/Parsing/Menu/Sequence/GlobalScopeSequences.h @@ -3,13 +3,11 @@ #include "Parsing/Menu/MenuFileParser.h" #include "Parsing/Sequence/AbstractScopeSequenceHolder.h" -namespace menu -{ - class GlobalScopeSequences final : AbstractScopeSequenceHolder<MenuFileParser> - { - public: - GlobalScopeSequences(std::vector<std::unique_ptr<MenuFileParser::sequence_t>>& allSequences, std::vector<MenuFileParser::sequence_t*>& scopeSequences); +namespace menu { +class GlobalScopeSequences final : AbstractScopeSequenceHolder<MenuFileParser> { +public: + GlobalScopeSequences(std::vector<std::unique_ptr<MenuFileParser::sequence_t>> &allSequences, std::vector<MenuFileParser::sequence_t *> &scopeSequences); - void AddSequences(FeatureLevel featureLevel, bool permissive) const; - }; -} + void AddSequences(FeatureLevel featureLevel, bool permissive) const; +}; +} // namespace menu diff --git a/src/ObjLoading/Parsing/Menu/Sequence/ItemScopeSequences.cpp b/src/ObjLoading/Parsing/Menu/Sequence/ItemScopeSequences.cpp index cb94bf8c6..9fa7f5c23 100644 --- a/src/ObjLoading/Parsing/Menu/Sequence/ItemScopeSequences.cpp +++ b/src/ObjLoading/Parsing/Menu/Sequence/ItemScopeSequences.cpp @@ -1,7 +1,7 @@ #include "ItemScopeSequences.h" -#include <vector> #include <string> +#include <vector> #include "Generic/GenericColorPropertySequence.h" #include "Generic/GenericExpressionPropertySequence.h" @@ -10,1037 +10,857 @@ #include "Generic/GenericKeywordPropertySequence.h" #include "Generic/GenericMenuEventHandlerSetPropertySequence.h" #include "Generic/GenericStringPropertySequence.h" -#include "Parsing/Menu/MenuFileCommonOperations.h" #include "Parsing/Menu/Matcher/MenuExpressionMatchers.h" #include "Parsing/Menu/Matcher/MenuMatcherFactory.h" +#include "Parsing/Menu/MenuFileCommonOperations.h" using namespace menu; -class ItemScopeOperations -{ - inline static const CommonItemFeatureType IW4_FEATURE_TYPE_BY_TYPE[0x18] - { - CommonItemFeatureType::EDIT_FIELD, // ITEM_TYPE_TEXT - CommonItemFeatureType::NONE, // ITEM_TYPE_BUTTON - CommonItemFeatureType::NONE, // ITEM_TYPE_RADIOBUTTON - CommonItemFeatureType::NONE, // ITEM_TYPE_CHECKBOX - CommonItemFeatureType::EDIT_FIELD, // ITEM_TYPE_EDITFIELD - CommonItemFeatureType::NONE, // ITEM_TYPE_COMBO - CommonItemFeatureType::LISTBOX, // ITEM_TYPE_LISTBOX - CommonItemFeatureType::NONE, // ITEM_TYPE_MODEL - CommonItemFeatureType::NONE, // ITEM_TYPE_OWNERDRAW - CommonItemFeatureType::EDIT_FIELD, // ITEM_TYPE_NUMERICFIELD - CommonItemFeatureType::EDIT_FIELD, // ITEM_TYPE_SLIDER - CommonItemFeatureType::EDIT_FIELD, // ITEM_TYPE_YESNO - CommonItemFeatureType::MULTI_VALUE, // ITEM_TYPE_MULTI - CommonItemFeatureType::ENUM_DVAR, // ITEM_TYPE_DVARENUM - CommonItemFeatureType::EDIT_FIELD, // ITEM_TYPE_BIND - CommonItemFeatureType::NONE, // ITEM_TYPE_MENUMODEL - CommonItemFeatureType::EDIT_FIELD, // ITEM_TYPE_VALIDFILEFIELD - CommonItemFeatureType::EDIT_FIELD, // ITEM_TYPE_DECIMALFIELD - CommonItemFeatureType::EDIT_FIELD, // ITEM_TYPE_UPREDITFIELD - CommonItemFeatureType::NONE, // ITEM_TYPE_GAME_MESSAGE_WINDOW - CommonItemFeatureType::NEWS_TICKER, // ITEM_TYPE_NEWS_TICKER - CommonItemFeatureType::NONE, // ITEM_TYPE_TEXT_SCROLL - CommonItemFeatureType::EDIT_FIELD, // ITEM_TYPE_EMAILFIELD - CommonItemFeatureType::EDIT_FIELD // ITEM_TYPE_PASSWORDFIELD - }; - - inline static const CommonItemFeatureType IW5_FEATURE_TYPE_BY_TYPE[0x18] - { - CommonItemFeatureType::EDIT_FIELD, // ITEM_TYPE_TEXT - CommonItemFeatureType::NONE, // ITEM_TYPE_BUTTON - CommonItemFeatureType::NONE, // ITEM_TYPE_RADIOBUTTON - CommonItemFeatureType::NONE, // ITEM_TYPE_CHECKBOX - CommonItemFeatureType::EDIT_FIELD, // ITEM_TYPE_EDITFIELD - CommonItemFeatureType::NONE, // ITEM_TYPE_COMBO - CommonItemFeatureType::LISTBOX, // ITEM_TYPE_LISTBOX - CommonItemFeatureType::NONE, // ITEM_TYPE_MODEL - CommonItemFeatureType::NONE, // ITEM_TYPE_OWNERDRAW - CommonItemFeatureType::EDIT_FIELD, // ITEM_TYPE_NUMERICFIELD - CommonItemFeatureType::EDIT_FIELD, // ITEM_TYPE_SLIDER - CommonItemFeatureType::EDIT_FIELD, // ITEM_TYPE_YESNO - CommonItemFeatureType::MULTI_VALUE, // ITEM_TYPE_MULTI - CommonItemFeatureType::ENUM_DVAR, // ITEM_TYPE_DVARENUM - CommonItemFeatureType::EDIT_FIELD, // ITEM_TYPE_BIND - CommonItemFeatureType::NONE, // ITEM_TYPE_MENUMODEL - CommonItemFeatureType::EDIT_FIELD, // ITEM_TYPE_VALIDFILEFIELD - CommonItemFeatureType::EDIT_FIELD, // ITEM_TYPE_DECIMALFIELD - CommonItemFeatureType::EDIT_FIELD, // ITEM_TYPE_UPREDITFIELD - CommonItemFeatureType::NONE, // ITEM_TYPE_GAME_MESSAGE_WINDOW - CommonItemFeatureType::NEWS_TICKER, // ITEM_TYPE_NEWS_TICKER - CommonItemFeatureType::NONE, // ITEM_TYPE_TEXT_SCROLL - CommonItemFeatureType::EDIT_FIELD, // ITEM_TYPE_EMAILFIELD - CommonItemFeatureType::EDIT_FIELD // ITEM_TYPE_PASSWORDFIELD - }; +class ItemScopeOperations { + inline static const CommonItemFeatureType IW4_FEATURE_TYPE_BY_TYPE[0x18]{ + CommonItemFeatureType::EDIT_FIELD, // ITEM_TYPE_TEXT + CommonItemFeatureType::NONE, // ITEM_TYPE_BUTTON + CommonItemFeatureType::NONE, // ITEM_TYPE_RADIOBUTTON + CommonItemFeatureType::NONE, // ITEM_TYPE_CHECKBOX + CommonItemFeatureType::EDIT_FIELD, // ITEM_TYPE_EDITFIELD + CommonItemFeatureType::NONE, // ITEM_TYPE_COMBO + CommonItemFeatureType::LISTBOX, // ITEM_TYPE_LISTBOX + CommonItemFeatureType::NONE, // ITEM_TYPE_MODEL + CommonItemFeatureType::NONE, // ITEM_TYPE_OWNERDRAW + CommonItemFeatureType::EDIT_FIELD, // ITEM_TYPE_NUMERICFIELD + CommonItemFeatureType::EDIT_FIELD, // ITEM_TYPE_SLIDER + CommonItemFeatureType::EDIT_FIELD, // ITEM_TYPE_YESNO + CommonItemFeatureType::MULTI_VALUE, // ITEM_TYPE_MULTI + CommonItemFeatureType::ENUM_DVAR, // ITEM_TYPE_DVARENUM + CommonItemFeatureType::EDIT_FIELD, // ITEM_TYPE_BIND + CommonItemFeatureType::NONE, // ITEM_TYPE_MENUMODEL + CommonItemFeatureType::EDIT_FIELD, // ITEM_TYPE_VALIDFILEFIELD + CommonItemFeatureType::EDIT_FIELD, // ITEM_TYPE_DECIMALFIELD + CommonItemFeatureType::EDIT_FIELD, // ITEM_TYPE_UPREDITFIELD + CommonItemFeatureType::NONE, // ITEM_TYPE_GAME_MESSAGE_WINDOW + CommonItemFeatureType::NEWS_TICKER, // ITEM_TYPE_NEWS_TICKER + CommonItemFeatureType::NONE, // ITEM_TYPE_TEXT_SCROLL + CommonItemFeatureType::EDIT_FIELD, // ITEM_TYPE_EMAILFIELD + CommonItemFeatureType::EDIT_FIELD // ITEM_TYPE_PASSWORDFIELD + }; + + inline static const CommonItemFeatureType IW5_FEATURE_TYPE_BY_TYPE[0x18]{ + CommonItemFeatureType::EDIT_FIELD, // ITEM_TYPE_TEXT + CommonItemFeatureType::NONE, // ITEM_TYPE_BUTTON + CommonItemFeatureType::NONE, // ITEM_TYPE_RADIOBUTTON + CommonItemFeatureType::NONE, // ITEM_TYPE_CHECKBOX + CommonItemFeatureType::EDIT_FIELD, // ITEM_TYPE_EDITFIELD + CommonItemFeatureType::NONE, // ITEM_TYPE_COMBO + CommonItemFeatureType::LISTBOX, // ITEM_TYPE_LISTBOX + CommonItemFeatureType::NONE, // ITEM_TYPE_MODEL + CommonItemFeatureType::NONE, // ITEM_TYPE_OWNERDRAW + CommonItemFeatureType::EDIT_FIELD, // ITEM_TYPE_NUMERICFIELD + CommonItemFeatureType::EDIT_FIELD, // ITEM_TYPE_SLIDER + CommonItemFeatureType::EDIT_FIELD, // ITEM_TYPE_YESNO + CommonItemFeatureType::MULTI_VALUE, // ITEM_TYPE_MULTI + CommonItemFeatureType::ENUM_DVAR, // ITEM_TYPE_DVARENUM + CommonItemFeatureType::EDIT_FIELD, // ITEM_TYPE_BIND + CommonItemFeatureType::NONE, // ITEM_TYPE_MENUMODEL + CommonItemFeatureType::EDIT_FIELD, // ITEM_TYPE_VALIDFILEFIELD + CommonItemFeatureType::EDIT_FIELD, // ITEM_TYPE_DECIMALFIELD + CommonItemFeatureType::EDIT_FIELD, // ITEM_TYPE_UPREDITFIELD + CommonItemFeatureType::NONE, // ITEM_TYPE_GAME_MESSAGE_WINDOW + CommonItemFeatureType::NEWS_TICKER, // ITEM_TYPE_NEWS_TICKER + CommonItemFeatureType::NONE, // ITEM_TYPE_TEXT_SCROLL + CommonItemFeatureType::EDIT_FIELD, // ITEM_TYPE_EMAILFIELD + CommonItemFeatureType::EDIT_FIELD // ITEM_TYPE_PASSWORDFIELD + }; public: - static void SetItemType(CommonItemDef& item, const FeatureLevel featureLevel, const TokenPos& pos, const int type) - { - if (type < 0) - throw ParsingException(pos, "Invalid item type"); - - if (item.m_feature_type != CommonItemFeatureType::NONE) - throw ParsingException(pos, "Item type has already been set"); - - item.m_type = type; - - switch (featureLevel) - { - case FeatureLevel::IW4: - if (static_cast<unsigned>(type) >= std::extent_v<decltype(IW4_FEATURE_TYPE_BY_TYPE)>) - throw ParsingException(pos, "Invalid item type"); - item.m_feature_type = IW4_FEATURE_TYPE_BY_TYPE[static_cast<unsigned>(type)]; - break; - - case FeatureLevel::IW5: - default: - if (static_cast<unsigned>(type) >= std::extent_v<decltype(IW5_FEATURE_TYPE_BY_TYPE)>) - throw ParsingException(pos, "Invalid item type"); - item.m_feature_type = IW5_FEATURE_TYPE_BY_TYPE[static_cast<unsigned>(type)]; - break; - } - - switch (item.m_feature_type) - { - case CommonItemFeatureType::LISTBOX: - item.m_list_box_features = std::make_unique<CommonItemFeaturesListBox>(); - break; - case CommonItemFeatureType::EDIT_FIELD: - item.m_edit_field_features = std::make_unique<CommonItemFeaturesEditField>(); - break; - case CommonItemFeatureType::MULTI_VALUE: - item.m_multi_value_features = std::make_unique<CommonItemFeaturesMultiValue>(); - break; - case CommonItemFeatureType::NEWS_TICKER: - item.m_news_ticker_features = std::make_unique<CommonItemFeaturesNewsTicker>(); - break; - default: - break; - } + static void SetItemType(CommonItemDef &item, const FeatureLevel featureLevel, const TokenPos &pos, const int type) { + if (type < 0) + throw ParsingException(pos, "Invalid item type"); + + if (item.m_feature_type != CommonItemFeatureType::NONE) + throw ParsingException(pos, "Item type has already been set"); + + item.m_type = type; + + switch (featureLevel) { + case FeatureLevel::IW4: + if (static_cast<unsigned>(type) >= std::extent_v<decltype(IW4_FEATURE_TYPE_BY_TYPE)>) + throw ParsingException(pos, "Invalid item type"); + item.m_feature_type = IW4_FEATURE_TYPE_BY_TYPE[static_cast<unsigned>(type)]; + break; + + case FeatureLevel::IW5: + default: + if (static_cast<unsigned>(type) >= std::extent_v<decltype(IW5_FEATURE_TYPE_BY_TYPE)>) + throw ParsingException(pos, "Invalid item type"); + item.m_feature_type = IW5_FEATURE_TYPE_BY_TYPE[static_cast<unsigned>(type)]; + break; + } + + switch (item.m_feature_type) { + case CommonItemFeatureType::LISTBOX: + item.m_list_box_features = std::make_unique<CommonItemFeaturesListBox>(); + break; + case CommonItemFeatureType::EDIT_FIELD: + item.m_edit_field_features = std::make_unique<CommonItemFeaturesEditField>(); + break; + case CommonItemFeatureType::MULTI_VALUE: + item.m_multi_value_features = std::make_unique<CommonItemFeaturesMultiValue>(); + break; + case CommonItemFeatureType::NEWS_TICKER: + item.m_news_ticker_features = std::make_unique<CommonItemFeaturesNewsTicker>(); + break; + default: + break; } + } + + static void EnsureHasListboxFeatures(const CommonItemDef &item, const TokenPos &pos) { + if (item.m_feature_type != CommonItemFeatureType::LISTBOX || !item.m_list_box_features) + throw ParsingException(pos, "Item must have be listbox to use this declaration"); + } + + static void EnsureHasEditFieldFeatures(const CommonItemDef &item, const TokenPos &pos) { + if (item.m_feature_type != CommonItemFeatureType::EDIT_FIELD || !item.m_edit_field_features) + throw ParsingException(pos, "Item must have be edit field to use this declaration"); + } + + static void EnsureHasMultiValueFeatures(const CommonItemDef &item, const TokenPos &pos) { + if (item.m_feature_type != CommonItemFeatureType::MULTI_VALUE || !item.m_multi_value_features) + throw ParsingException(pos, "Item must have be multi value to use this declaration"); + } + + static void EnsureHasEnumDvarFeatures(const CommonItemDef &item, const TokenPos &pos) { + if (item.m_feature_type != CommonItemFeatureType::ENUM_DVAR) + throw ParsingException(pos, "Item must have be enum dvar to use this declaration"); + } + + static void EnsureHasNewsTickerFeatures(const CommonItemDef &item, const TokenPos &pos) { + if (item.m_feature_type != CommonItemFeatureType::NEWS_TICKER || !item.m_news_ticker_features) + throw ParsingException(pos, "Item must have be news ticker to use this declaration"); + } +}; + +namespace menu::item_scope_sequences { +class SequenceCloseBlock final : public MenuFileParser::sequence_t { +public: + SequenceCloseBlock() { + const MenuMatcherFactory create(this); + + AddMatchers({create.Char('}')}); + } - static void EnsureHasListboxFeatures(const CommonItemDef& item, const TokenPos& pos) - { - if (item.m_feature_type != CommonItemFeatureType::LISTBOX || !item.m_list_box_features) - throw ParsingException(pos, "Item must have be listbox to use this declaration"); +protected: + void ProcessMatch(MenuFileParserState *state, SequenceResult<SimpleParserValue> &result) const override { state->m_current_item = nullptr; } +}; + +class SequenceConsumeSemicolons final : public MenuFileParser::sequence_t { +public: + SequenceConsumeSemicolons() { + const MenuMatcherFactory create(this); + + AddMatchers({create.Char(';')}); + } + +protected: + void ProcessMatch(MenuFileParserState *state, SequenceResult<SimpleParserValue> &result) const override {} +}; + +class SequenceRect final : public MenuFileParser::sequence_t { + static constexpr auto CAPTURE_ALIGN_HORIZONTAL = 1; + static constexpr auto CAPTURE_ALIGN_VERTICAL = 2; + +public: + SequenceRect() { + const MenuMatcherFactory create(this); + + AddLabeledMatchers(MenuExpressionMatchers().Expression(this), MenuExpressionMatchers::LABEL_EXPRESSION); + AddMatchers({create.KeywordIgnoreCase("rect"), + create.NumericExpression(), // x + create.NumericExpression(), // y + create.NumericExpression(), // w + create.NumericExpression(), // h + create.Optional(create.And({create.Integer().Capture(CAPTURE_ALIGN_HORIZONTAL), create.Integer().Capture(CAPTURE_ALIGN_VERTICAL)}))}); + } + +protected: + void ProcessMatch(MenuFileParserState *state, SequenceResult<SimpleParserValue> &result) const override { + assert(state->m_current_item); + + const auto x = MenuMatcherFactory::TokenNumericExpressionValue(state, result); + const auto y = MenuMatcherFactory::TokenNumericExpressionValue(state, result); + const auto w = MenuMatcherFactory::TokenNumericExpressionValue(state, result); + const auto h = MenuMatcherFactory::TokenNumericExpressionValue(state, result); + CommonRect rect{x, y, w, h, 0, 0}; + + if (result.HasNextCapture(CAPTURE_ALIGN_HORIZONTAL) && result.HasNextCapture(CAPTURE_ALIGN_VERTICAL)) { + rect.horizontalAlign = result.NextCapture(CAPTURE_ALIGN_HORIZONTAL).IntegerValue(); + rect.verticalAlign = result.NextCapture(CAPTURE_ALIGN_VERTICAL).IntegerValue(); } - static void EnsureHasEditFieldFeatures(const CommonItemDef& item, const TokenPos& pos) - { - if (item.m_feature_type != CommonItemFeatureType::EDIT_FIELD || !item.m_edit_field_features) - throw ParsingException(pos, "Item must have be edit field to use this declaration"); + state->m_current_item->m_rect = rect; + } +}; + +class SequenceOrigin final : public MenuFileParser::sequence_t { +public: + SequenceOrigin() { + const MenuMatcherFactory create(this); + + AddLabeledMatchers(MenuExpressionMatchers().Expression(this), MenuExpressionMatchers::LABEL_EXPRESSION); + AddMatchers({ + create.KeywordIgnoreCase("origin"), + create.NumericExpression(), // x + create.NumericExpression() // y + }); + } + +protected: + void ProcessMatch(MenuFileParserState *state, SequenceResult<SimpleParserValue> &result) const override { + assert(state->m_current_item); + + state->m_current_item->m_rect.x = MenuMatcherFactory::TokenNumericExpressionValue(state, result); + state->m_current_item->m_rect.y = MenuMatcherFactory::TokenNumericExpressionValue(state, result); + } +}; + +class SequenceDecodeEffect final : public MenuFileParser::sequence_t { + static constexpr auto CAPTURE_LETTER_TIME = 1; + static constexpr auto CAPTURE_DECAY_START_TIME = 2; + static constexpr auto CAPTURE_DECAY_DURATION = 3; + +public: + SequenceDecodeEffect() { + const MenuMatcherFactory create(this); + + AddLabeledMatchers(MenuExpressionMatchers().Expression(this), MenuExpressionMatchers::LABEL_EXPRESSION); + AddMatchers({ + create.KeywordIgnoreCase("decodeEffect"), + create.IntExpression(), // letter time + create.IntExpression(), // decay start time + create.IntExpression(), // decay duration + }); + } + +protected: + void ProcessMatch(MenuFileParserState *state, SequenceResult<SimpleParserValue> &result) const override { + assert(state->m_current_item); + + state->m_current_item->m_fx_letter_time = MenuMatcherFactory::TokenIntExpressionValue(state, result); + state->m_current_item->m_fx_decay_start_time = MenuMatcherFactory::TokenIntExpressionValue(state, result); + state->m_current_item->m_fx_decay_duration = MenuMatcherFactory::TokenIntExpressionValue(state, result); + } +}; + +class SequenceMultiTokenBlock final : public MenuFileParser::sequence_t { +public: + using callback_t = std::function<void(MenuFileParserState *state, const TokenPos &pos, std::vector<std::string> value)>; + +private: + static constexpr auto CAPTURE_FIRST_TOKEN = 1; + static constexpr auto CAPTURE_VALUE = 2; + + callback_t m_set_callback; + +public: + SequenceMultiTokenBlock(std::string keyName, callback_t setCallback) : m_set_callback(std::move(setCallback)) { + const MenuMatcherFactory create(this); + + AddMatchers({ + create.KeywordIgnoreCase(std::move(keyName)).Capture(CAPTURE_FIRST_TOKEN), + create.Char('{'), + create.Optional( + create.And({create.Text().Capture(CAPTURE_VALUE), create.OptionalLoop(create.And({create.Char(';'), create.Text().Capture(CAPTURE_VALUE)}))})), + create.Char('}'), + }); + } + +protected: + void ProcessMatch(MenuFileParserState *state, SequenceResult<SimpleParserValue> &result) const override { + if (!m_set_callback) + return; + + std::vector<std::string> values; + while (result.HasNextCapture(CAPTURE_VALUE)) { + values.emplace_back(MenuMatcherFactory::TokenTextValue(result.NextCapture(CAPTURE_VALUE))); } - static void EnsureHasMultiValueFeatures(const CommonItemDef& item, const TokenPos& pos) - { - if (item.m_feature_type != CommonItemFeatureType::MULTI_VALUE || !item.m_multi_value_features) - throw ParsingException(pos, "Item must have be multi value to use this declaration"); + m_set_callback(state, result.NextCapture(CAPTURE_FIRST_TOKEN).GetPos(), std::move(values)); + } +}; + +class SequenceDvarFloat final : public MenuFileParser::sequence_t { + static constexpr auto CAPTURE_FIRST_TOKEN = 1; + static constexpr auto CAPTURE_DVAR_NAME = 2; + +public: + SequenceDvarFloat() { + const MenuMatcherFactory create(this); + + AddLabeledMatchers(MenuExpressionMatchers().Expression(this), MenuExpressionMatchers::LABEL_EXPRESSION); + AddMatchers({ + create.KeywordIgnoreCase("dvarFloat").Capture(CAPTURE_FIRST_TOKEN), create.Text().Capture(CAPTURE_DVAR_NAME), + create.NumericExpression(), // def value + create.NumericExpression(), // min value + create.NumericExpression(), // max value + }); + } + +protected: + void ProcessMatch(MenuFileParserState *state, SequenceResult<SimpleParserValue> &result) const override { + assert(state->m_current_item); + + ItemScopeOperations::EnsureHasEditFieldFeatures(*state->m_current_item, result.NextCapture(CAPTURE_FIRST_TOKEN).GetPos()); + state->m_current_item->m_dvar = MenuMatcherFactory::TokenTextValue(result.NextCapture(CAPTURE_DVAR_NAME)); + state->m_current_item->m_edit_field_features->m_def_val = MenuMatcherFactory::TokenNumericExpressionValue(state, result); + state->m_current_item->m_edit_field_features->m_min_val = MenuMatcherFactory::TokenNumericExpressionValue(state, result); + state->m_current_item->m_edit_field_features->m_max_val = MenuMatcherFactory::TokenNumericExpressionValue(state, result); + } +}; + +class SequenceDvarStrList final : public MenuFileParser::sequence_t { + static constexpr auto CAPTURE_FIRST_TOKEN = 1; + static constexpr auto CAPTURE_STEP_NAME = 2; + static constexpr auto CAPTURE_STEP_VALUE = 3; + +public: + SequenceDvarStrList() { + const MenuMatcherFactory create(this); + + AddMatchers({create.KeywordIgnoreCase("dvarStrList").Capture(CAPTURE_FIRST_TOKEN), create.Char('{'), + create.OptionalLoop(create.And({ + create.TextNoChain().Capture(CAPTURE_STEP_NAME), + create.Optional(create.Char(';')), + create.TextNoChain().Capture(CAPTURE_STEP_VALUE), + create.Optional(create.Char(';')), + })), + create.Char('}')}); + } + +protected: + void ProcessMatch(MenuFileParserState *state, SequenceResult<SimpleParserValue> &result) const override { + assert(state->m_current_item); + + ItemScopeOperations::EnsureHasMultiValueFeatures(*state->m_current_item, result.NextCapture(CAPTURE_FIRST_TOKEN).GetPos()); + + const auto &multiValueFeatures = state->m_current_item->m_multi_value_features; + while (result.HasNextCapture(CAPTURE_STEP_NAME)) { + multiValueFeatures->m_step_names.emplace_back(MenuMatcherFactory::TokenTextValue(result.NextCapture(CAPTURE_STEP_NAME))); + multiValueFeatures->m_string_values.emplace_back(MenuMatcherFactory::TokenTextValue(result.NextCapture(CAPTURE_STEP_VALUE))); } + } +}; + +class SequenceDvarFloatList final : public MenuFileParser::sequence_t { + static constexpr auto CAPTURE_FIRST_TOKEN = 1; + static constexpr auto CAPTURE_STEP_NAME = 2; - static void EnsureHasEnumDvarFeatures(const CommonItemDef& item, const TokenPos& pos) - { - if (item.m_feature_type != CommonItemFeatureType::ENUM_DVAR) - throw ParsingException(pos, "Item must have be enum dvar to use this declaration"); +public: + SequenceDvarFloatList() { + const MenuMatcherFactory create(this); + + AddLabeledMatchers(MenuExpressionMatchers().Expression(this), MenuExpressionMatchers::LABEL_EXPRESSION); + AddMatchers({create.KeywordIgnoreCase("dvarFloatList").Capture(CAPTURE_FIRST_TOKEN), create.Char('{'), + create.OptionalLoop(create.And({ + create.Text().Capture(CAPTURE_STEP_NAME), + create.Optional(create.Char(';')), + create.NumericExpression(), + create.Optional(create.Char(';')), + })), + create.Char('}')}); + } + +protected: + void ProcessMatch(MenuFileParserState *state, SequenceResult<SimpleParserValue> &result) const override { + assert(state->m_current_item); + + ItemScopeOperations::EnsureHasMultiValueFeatures(*state->m_current_item, result.NextCapture(CAPTURE_FIRST_TOKEN).GetPos()); + + const auto &multiValueFeatures = state->m_current_item->m_multi_value_features; + while (result.HasNextCapture(CAPTURE_STEP_NAME)) { + multiValueFeatures->m_step_names.emplace_back(MenuMatcherFactory::TokenTextValue(result.NextCapture(CAPTURE_STEP_NAME))); + multiValueFeatures->m_double_values.emplace_back(MenuMatcherFactory::TokenNumericExpressionValue(state, result)); } + } +}; - static void EnsureHasNewsTickerFeatures(const CommonItemDef& item, const TokenPos& pos) - { - if (item.m_feature_type != CommonItemFeatureType::NEWS_TICKER || !item.m_news_ticker_features) - throw ParsingException(pos, "Item must have be news ticker to use this declaration"); +class SequenceColumns final : public MenuFileParser::sequence_t { + static constexpr auto CAPTURE_FIRST_TOKEN = 1; + static constexpr auto CAPTURE_COLUMN_COUNT = 2; + static constexpr auto CAPTURE_X_POS = 3; + static constexpr auto CAPTURE_Y_POS = 4; + static constexpr auto CAPTURE_WIDTH = 5; + static constexpr auto CAPTURE_HEIGHT = 6; + static constexpr auto CAPTURE_MAX_CHARS = 7; + static constexpr auto CAPTURE_ALIGNMENT = 8; + +public: + explicit SequenceColumns(const FeatureLevel featureLevel) { + const MenuMatcherFactory create(this); + + if (featureLevel == FeatureLevel::IW5) { + AddMatchers({ + create.KeywordIgnoreCase("columns").Capture(CAPTURE_FIRST_TOKEN), + create.Integer().Capture(CAPTURE_COLUMN_COUNT), + create.Loop(create.And({ + create.Integer().Capture(CAPTURE_X_POS), + create.Integer().Capture(CAPTURE_Y_POS), + create.Integer().Capture(CAPTURE_WIDTH), + create.Integer().Capture(CAPTURE_HEIGHT), + create.Integer().Capture(CAPTURE_MAX_CHARS), + create.Integer().Capture(CAPTURE_ALIGNMENT), + })), + }); + } else { + AddMatchers({ + create.KeywordIgnoreCase("columns").Capture(CAPTURE_FIRST_TOKEN), + create.Integer().Capture(CAPTURE_COLUMN_COUNT), + create.Loop(create.And({ + create.Integer().Capture(CAPTURE_X_POS), + create.Integer().Capture(CAPTURE_WIDTH), + create.Integer().Capture(CAPTURE_MAX_CHARS), + create.Integer().Capture(CAPTURE_ALIGNMENT), + })), + }); + } + } + +protected: + void ProcessMatch(MenuFileParserState *state, SequenceResult<SimpleParserValue> &result) const override { + assert(state->m_current_item); + + ItemScopeOperations::EnsureHasListboxFeatures(*state->m_current_item, result.NextCapture(CAPTURE_FIRST_TOKEN).GetPos()); + + const auto &listBoxFeatures = state->m_current_item->m_list_box_features; + while (result.HasNextCapture(CAPTURE_X_POS)) { + CommonItemFeaturesListBox::Column column{result.NextCapture(CAPTURE_X_POS).IntegerValue(), + state->m_feature_level == FeatureLevel::IW5 ? result.NextCapture(CAPTURE_Y_POS).IntegerValue() : 0, + result.NextCapture(CAPTURE_WIDTH).IntegerValue(), + state->m_feature_level == FeatureLevel::IW5 ? result.NextCapture(CAPTURE_HEIGHT).IntegerValue() : 0, + result.NextCapture(CAPTURE_MAX_CHARS).IntegerValue(), + result.NextCapture(CAPTURE_ALIGNMENT).IntegerValue()}; + listBoxFeatures->m_columns.emplace_back(column); } + } }; -namespace menu::item_scope_sequences -{ - class SequenceCloseBlock final : public MenuFileParser::sequence_t - { - public: - SequenceCloseBlock() - { - const MenuMatcherFactory create(this); - - AddMatchers({ - create.Char('}') - }); - } - - protected: - void ProcessMatch(MenuFileParserState* state, SequenceResult<SimpleParserValue>& result) const override - { - state->m_current_item = nullptr; - } - }; - - class SequenceConsumeSemicolons final : public MenuFileParser::sequence_t - { - public: - SequenceConsumeSemicolons() - { - const MenuMatcherFactory create(this); - - AddMatchers({ - create.Char(';') - }); - } - - protected: - void ProcessMatch(MenuFileParserState* state, SequenceResult<SimpleParserValue>& result) const override - { - } - }; - - class SequenceRect final : public MenuFileParser::sequence_t - { - static constexpr auto CAPTURE_ALIGN_HORIZONTAL = 1; - static constexpr auto CAPTURE_ALIGN_VERTICAL = 2; - - public: - SequenceRect() - { - const MenuMatcherFactory create(this); - - AddLabeledMatchers(MenuExpressionMatchers().Expression(this), MenuExpressionMatchers::LABEL_EXPRESSION); - AddMatchers({ - create.KeywordIgnoreCase("rect"), - create.NumericExpression(), // x - create.NumericExpression(), // y - create.NumericExpression(), // w - create.NumericExpression(), // h - create.Optional(create.And({ - create.Integer().Capture(CAPTURE_ALIGN_HORIZONTAL), - create.Integer().Capture(CAPTURE_ALIGN_VERTICAL) - })) - }); - } - - protected: - void ProcessMatch(MenuFileParserState* state, SequenceResult<SimpleParserValue>& result) const override - { - assert(state->m_current_item); - - const auto x = MenuMatcherFactory::TokenNumericExpressionValue(state, result); - const auto y = MenuMatcherFactory::TokenNumericExpressionValue(state, result); - const auto w = MenuMatcherFactory::TokenNumericExpressionValue(state, result); - const auto h = MenuMatcherFactory::TokenNumericExpressionValue(state, result); - CommonRect rect - { - x, - y, - w, - h, - 0, 0 - }; - - if (result.HasNextCapture(CAPTURE_ALIGN_HORIZONTAL) && result.HasNextCapture(CAPTURE_ALIGN_VERTICAL)) - { - rect.horizontalAlign = result.NextCapture(CAPTURE_ALIGN_HORIZONTAL).IntegerValue(); - rect.verticalAlign = result.NextCapture(CAPTURE_ALIGN_VERTICAL).IntegerValue(); - } - - state->m_current_item->m_rect = rect; - } - }; - - class SequenceOrigin final : public MenuFileParser::sequence_t - { - public: - SequenceOrigin() - { - const MenuMatcherFactory create(this); - - AddLabeledMatchers(MenuExpressionMatchers().Expression(this), MenuExpressionMatchers::LABEL_EXPRESSION); - AddMatchers({ - create.KeywordIgnoreCase("origin"), - create.NumericExpression(), // x - create.NumericExpression() // y - }); - } - - protected: - void ProcessMatch(MenuFileParserState* state, SequenceResult<SimpleParserValue>& result) const override - { - assert(state->m_current_item); - - state->m_current_item->m_rect.x = MenuMatcherFactory::TokenNumericExpressionValue(state, result); - state->m_current_item->m_rect.y = MenuMatcherFactory::TokenNumericExpressionValue(state, result); - } - }; - - class SequenceDecodeEffect final : public MenuFileParser::sequence_t - { - static constexpr auto CAPTURE_LETTER_TIME = 1; - static constexpr auto CAPTURE_DECAY_START_TIME = 2; - static constexpr auto CAPTURE_DECAY_DURATION = 3; - - public: - SequenceDecodeEffect() - { - const MenuMatcherFactory create(this); - - AddLabeledMatchers(MenuExpressionMatchers().Expression(this), MenuExpressionMatchers::LABEL_EXPRESSION); - AddMatchers({ - create.KeywordIgnoreCase("decodeEffect"), - create.IntExpression(), // letter time - create.IntExpression(), // decay start time - create.IntExpression(), // decay duration - }); - } - - protected: - void ProcessMatch(MenuFileParserState* state, SequenceResult<SimpleParserValue>& result) const override - { - assert(state->m_current_item); - - state->m_current_item->m_fx_letter_time = MenuMatcherFactory::TokenIntExpressionValue(state, result); - state->m_current_item->m_fx_decay_start_time = MenuMatcherFactory::TokenIntExpressionValue(state, result); - state->m_current_item->m_fx_decay_duration = MenuMatcherFactory::TokenIntExpressionValue(state, result); - } - }; - - class SequenceMultiTokenBlock final : public MenuFileParser::sequence_t - { - public: - using callback_t = std::function<void(MenuFileParserState* state, const TokenPos& pos, std::vector<std::string> value)>; - - private: - static constexpr auto CAPTURE_FIRST_TOKEN = 1; - static constexpr auto CAPTURE_VALUE = 2; - - callback_t m_set_callback; - - public: - SequenceMultiTokenBlock(std::string keyName, callback_t setCallback) - : m_set_callback(std::move(setCallback)) - { - const MenuMatcherFactory create(this); - - AddMatchers({ - create.KeywordIgnoreCase(std::move(keyName)).Capture(CAPTURE_FIRST_TOKEN), - create.Char('{'), - create.Optional(create.And({ - create.Text().Capture(CAPTURE_VALUE), - create.OptionalLoop(create.And({ - create.Char(';'), - create.Text().Capture(CAPTURE_VALUE) - })) - })), - create.Char('}'), - }); - } - - protected: - void ProcessMatch(MenuFileParserState* state, SequenceResult<SimpleParserValue>& result) const override - { - if (!m_set_callback) - return; - - std::vector<std::string> values; - while (result.HasNextCapture(CAPTURE_VALUE)) - { - values.emplace_back(MenuMatcherFactory::TokenTextValue(result.NextCapture(CAPTURE_VALUE))); - } - - m_set_callback(state, result.NextCapture(CAPTURE_FIRST_TOKEN).GetPos(), std::move(values)); - } - }; - - class SequenceDvarFloat final : public MenuFileParser::sequence_t - { - static constexpr auto CAPTURE_FIRST_TOKEN = 1; - static constexpr auto CAPTURE_DVAR_NAME = 2; - - public: - SequenceDvarFloat() - { - const MenuMatcherFactory create(this); - - AddLabeledMatchers(MenuExpressionMatchers().Expression(this), MenuExpressionMatchers::LABEL_EXPRESSION); - AddMatchers({ - create.KeywordIgnoreCase("dvarFloat").Capture(CAPTURE_FIRST_TOKEN), - create.Text().Capture(CAPTURE_DVAR_NAME), - create.NumericExpression(), // def value - create.NumericExpression(), // min value - create.NumericExpression(), // max value - }); - } - - protected: - void ProcessMatch(MenuFileParserState* state, SequenceResult<SimpleParserValue>& result) const override - { - assert(state->m_current_item); - - ItemScopeOperations::EnsureHasEditFieldFeatures(*state->m_current_item, result.NextCapture(CAPTURE_FIRST_TOKEN).GetPos()); - state->m_current_item->m_dvar = MenuMatcherFactory::TokenTextValue(result.NextCapture(CAPTURE_DVAR_NAME)); - state->m_current_item->m_edit_field_features->m_def_val = MenuMatcherFactory::TokenNumericExpressionValue(state, result); - state->m_current_item->m_edit_field_features->m_min_val = MenuMatcherFactory::TokenNumericExpressionValue(state, result); - state->m_current_item->m_edit_field_features->m_max_val = MenuMatcherFactory::TokenNumericExpressionValue(state, result); - } - }; - - class SequenceDvarStrList final : public MenuFileParser::sequence_t - { - static constexpr auto CAPTURE_FIRST_TOKEN = 1; - static constexpr auto CAPTURE_STEP_NAME = 2; - static constexpr auto CAPTURE_STEP_VALUE = 3; - - public: - SequenceDvarStrList() - { - const MenuMatcherFactory create(this); - - AddMatchers({ - create.KeywordIgnoreCase("dvarStrList").Capture(CAPTURE_FIRST_TOKEN), - create.Char('{'), - create.OptionalLoop(create.And({ - create.TextNoChain().Capture(CAPTURE_STEP_NAME), - create.Optional(create.Char(';')), - create.TextNoChain().Capture(CAPTURE_STEP_VALUE), - create.Optional(create.Char(';')), - })), - create.Char('}') - }); - } - - protected: - void ProcessMatch(MenuFileParserState* state, SequenceResult<SimpleParserValue>& result) const override - { - assert(state->m_current_item); - - ItemScopeOperations::EnsureHasMultiValueFeatures(*state->m_current_item, result.NextCapture(CAPTURE_FIRST_TOKEN).GetPos()); - - const auto& multiValueFeatures = state->m_current_item->m_multi_value_features; - while (result.HasNextCapture(CAPTURE_STEP_NAME)) - { - multiValueFeatures->m_step_names.emplace_back(MenuMatcherFactory::TokenTextValue(result.NextCapture(CAPTURE_STEP_NAME))); - multiValueFeatures->m_string_values.emplace_back(MenuMatcherFactory::TokenTextValue(result.NextCapture(CAPTURE_STEP_VALUE))); - } - } - }; - - class SequenceDvarFloatList final : public MenuFileParser::sequence_t - { - static constexpr auto CAPTURE_FIRST_TOKEN = 1; - static constexpr auto CAPTURE_STEP_NAME = 2; - - public: - SequenceDvarFloatList() - { - const MenuMatcherFactory create(this); - - AddLabeledMatchers(MenuExpressionMatchers().Expression(this), MenuExpressionMatchers::LABEL_EXPRESSION); - AddMatchers({ - create.KeywordIgnoreCase("dvarFloatList").Capture(CAPTURE_FIRST_TOKEN), - create.Char('{'), - create.OptionalLoop(create.And({ - create.Text().Capture(CAPTURE_STEP_NAME), - create.Optional(create.Char(';')), - create.NumericExpression(), - create.Optional(create.Char(';')), - })), - create.Char('}') - }); - } - - protected: - void ProcessMatch(MenuFileParserState* state, SequenceResult<SimpleParserValue>& result) const override - { - assert(state->m_current_item); - - ItemScopeOperations::EnsureHasMultiValueFeatures(*state->m_current_item, result.NextCapture(CAPTURE_FIRST_TOKEN).GetPos()); - - const auto& multiValueFeatures = state->m_current_item->m_multi_value_features; - while (result.HasNextCapture(CAPTURE_STEP_NAME)) - { - multiValueFeatures->m_step_names.emplace_back(MenuMatcherFactory::TokenTextValue(result.NextCapture(CAPTURE_STEP_NAME))); - multiValueFeatures->m_double_values.emplace_back(MenuMatcherFactory::TokenNumericExpressionValue(state, result)); - } - } - }; - - class SequenceColumns final : public MenuFileParser::sequence_t - { - static constexpr auto CAPTURE_FIRST_TOKEN = 1; - static constexpr auto CAPTURE_COLUMN_COUNT = 2; - static constexpr auto CAPTURE_X_POS = 3; - static constexpr auto CAPTURE_Y_POS = 4; - static constexpr auto CAPTURE_WIDTH = 5; - static constexpr auto CAPTURE_HEIGHT = 6; - static constexpr auto CAPTURE_MAX_CHARS = 7; - static constexpr auto CAPTURE_ALIGNMENT = 8; - - public: - explicit SequenceColumns(const FeatureLevel featureLevel) - { - const MenuMatcherFactory create(this); - - if (featureLevel == FeatureLevel::IW5) - { - AddMatchers({ - create.KeywordIgnoreCase("columns").Capture(CAPTURE_FIRST_TOKEN), - create.Integer().Capture(CAPTURE_COLUMN_COUNT), - create.Loop(create.And({ - create.Integer().Capture(CAPTURE_X_POS), - create.Integer().Capture(CAPTURE_Y_POS), - create.Integer().Capture(CAPTURE_WIDTH), - create.Integer().Capture(CAPTURE_HEIGHT), - create.Integer().Capture(CAPTURE_MAX_CHARS), - create.Integer().Capture(CAPTURE_ALIGNMENT), - })), - }); - } - else - { - AddMatchers({ - create.KeywordIgnoreCase("columns").Capture(CAPTURE_FIRST_TOKEN), - create.Integer().Capture(CAPTURE_COLUMN_COUNT), - create.Loop(create.And({ - create.Integer().Capture(CAPTURE_X_POS), - create.Integer().Capture(CAPTURE_WIDTH), - create.Integer().Capture(CAPTURE_MAX_CHARS), - create.Integer().Capture(CAPTURE_ALIGNMENT), - })), - }); - } - } - - protected: - void ProcessMatch(MenuFileParserState* state, SequenceResult<SimpleParserValue>& result) const override - { - assert(state->m_current_item); - - ItemScopeOperations::EnsureHasListboxFeatures(*state->m_current_item, result.NextCapture(CAPTURE_FIRST_TOKEN).GetPos()); - - const auto& listBoxFeatures = state->m_current_item->m_list_box_features; - while (result.HasNextCapture(CAPTURE_X_POS)) - { - CommonItemFeaturesListBox::Column column - { - result.NextCapture(CAPTURE_X_POS).IntegerValue(), - state->m_feature_level == FeatureLevel::IW5 ? result.NextCapture(CAPTURE_Y_POS).IntegerValue() : 0, - result.NextCapture(CAPTURE_WIDTH).IntegerValue(), - state->m_feature_level == FeatureLevel::IW5 ? result.NextCapture(CAPTURE_HEIGHT).IntegerValue() : 0, - result.NextCapture(CAPTURE_MAX_CHARS).IntegerValue(), - result.NextCapture(CAPTURE_ALIGNMENT).IntegerValue() - }; - listBoxFeatures->m_columns.emplace_back(column); - } - } - }; - - class SequenceExecKey final : public MenuFileParser::sequence_t - { - static constexpr auto CAPTURE_KEY = 1; - - public: - SequenceExecKey() - { - const MenuMatcherFactory create(this); - - AddMatchers({ - create.KeywordIgnoreCase("execKey"), - create.StringChain().Capture(CAPTURE_KEY), - create.Char('{') - }); - } - - protected: - void ProcessMatch(MenuFileParserState* state, SequenceResult<SimpleParserValue>& result) const override - { - assert(state->m_current_item); - - const auto& keyToken = result.NextCapture(CAPTURE_KEY); - const auto& keyValue = keyToken.StringValue(); - - if (keyValue.empty() || keyValue.size() > 1) - throw ParsingException(keyToken.GetPos(), "Key handler string must have exactly one character"); - - const auto key = static_cast<int>(static_cast<unsigned char>(keyValue[0])); - - auto newEventHandlerSet = std::make_unique<CommonEventHandlerSet>(); - state->m_current_event_handler_set = newEventHandlerSet.get(); - state->m_current_nested_event_handler_set = newEventHandlerSet.get(); - state->m_current_item->m_key_handlers.emplace(std::make_pair(key, std::move(newEventHandlerSet))); - } - }; - - class SequenceExecKeyInt final : public MenuFileParser::sequence_t - { - static constexpr auto CAPTURE_KEY = 1; - - public: - SequenceExecKeyInt() - { - const MenuMatcherFactory create(this); - - AddMatchers({ - create.KeywordIgnoreCase("execKeyInt"), - create.Integer().Capture(CAPTURE_KEY), - create.Char('{') - }); - } - - protected: - void ProcessMatch(MenuFileParserState* state, SequenceResult<SimpleParserValue>& result) const override - { - assert(state->m_current_item); - - const auto& keyToken = result.NextCapture(CAPTURE_KEY); - const auto& keyValue = keyToken.IntegerValue(); - - if (keyValue < 0) - throw ParsingException(keyToken.GetPos(), "Key handler value must be positive"); - - auto newEventHandlerSet = std::make_unique<CommonEventHandlerSet>(); - state->m_current_event_handler_set = newEventHandlerSet.get(); - state->m_current_nested_event_handler_set = newEventHandlerSet.get(); - state->m_current_item->m_key_handlers.emplace(std::make_pair(keyValue, std::move(newEventHandlerSet))); - } - }; -} +class SequenceExecKey final : public MenuFileParser::sequence_t { + static constexpr auto CAPTURE_KEY = 1; -using namespace item_scope_sequences; +public: + SequenceExecKey() { + const MenuMatcherFactory create(this); -ItemScopeSequences::ItemScopeSequences(std::vector<std::unique_ptr<MenuFileParser::sequence_t>>& allSequences, std::vector<MenuFileParser::sequence_t*>& scopeSequences) - : AbstractScopeSequenceHolder(allSequences, scopeSequences) -{ -} + AddMatchers({create.KeywordIgnoreCase("execKey"), create.StringChain().Capture(CAPTURE_KEY), create.Char('{')}); + } + +protected: + void ProcessMatch(MenuFileParserState *state, SequenceResult<SimpleParserValue> &result) const override { + assert(state->m_current_item); + + const auto &keyToken = result.NextCapture(CAPTURE_KEY); + const auto &keyValue = keyToken.StringValue(); + + if (keyValue.empty() || keyValue.size() > 1) + throw ParsingException(keyToken.GetPos(), "Key handler string must have exactly one character"); + + const auto key = static_cast<int>(static_cast<unsigned char>(keyValue[0])); + + auto newEventHandlerSet = std::make_unique<CommonEventHandlerSet>(); + state->m_current_event_handler_set = newEventHandlerSet.get(); + state->m_current_nested_event_handler_set = newEventHandlerSet.get(); + state->m_current_item->m_key_handlers.emplace(std::make_pair(key, std::move(newEventHandlerSet))); + } +}; + +class SequenceExecKeyInt final : public MenuFileParser::sequence_t { + static constexpr auto CAPTURE_KEY = 1; + +public: + SequenceExecKeyInt() { + const MenuMatcherFactory create(this); + + AddMatchers({create.KeywordIgnoreCase("execKeyInt"), create.Integer().Capture(CAPTURE_KEY), create.Char('{')}); + } + +protected: + void ProcessMatch(MenuFileParserState *state, SequenceResult<SimpleParserValue> &result) const override { + assert(state->m_current_item); + + const auto &keyToken = result.NextCapture(CAPTURE_KEY); + const auto &keyValue = keyToken.IntegerValue(); + + if (keyValue < 0) + throw ParsingException(keyToken.GetPos(), "Key handler value must be positive"); -void ItemScopeSequences::AddSequences(FeatureLevel featureLevel, bool permissive) const -{ - AddSequence(std::make_unique<SequenceCloseBlock>()); - AddSequence(std::make_unique<GenericStringPropertySequence>("name", [](const MenuFileParserState* state, const TokenPos&, const std::string& value) - { - state->m_current_item->m_name = value; - })); - AddSequence(std::make_unique<GenericStringPropertySequence>("text", [](const MenuFileParserState* state, const TokenPos&, const std::string& value) - { - state->m_current_item->m_text = value; - })); - // textfile - AddSequence(std::make_unique<GenericKeywordPropertySequence>("textsavegame", [](const MenuFileParserState* state, const TokenPos&) - { - state->m_current_item->m_text_save_game = true; - })); - AddSequence(std::make_unique<GenericKeywordPropertySequence>("textcinematicsubtitle", [](const MenuFileParserState* state, const TokenPos&) - { - state->m_current_item->m_text_cinematic_subtitle = true; - })); - AddSequence(std::make_unique<GenericStringPropertySequence>("group", [](const MenuFileParserState* state, const TokenPos&, const std::string& value) - { - state->m_current_item->m_group = value; - })); - AddSequence(std::make_unique<SequenceRect>()); - AddSequence(std::make_unique<SequenceOrigin>()); - // rect480 - // rect720 - // pos480 - // pos720 - AddSequence(std::make_unique<GenericIntPropertySequence>("style", [](const MenuFileParserState* state, const TokenPos&, const int value) - { - state->m_current_item->m_style = value; - })); - AddSequence(std::make_unique<GenericKeywordPropertySequence>("decoration", [](const MenuFileParserState* state, const TokenPos&) - { - state->m_current_item->m_decoration = true; - })); - AddSequence(std::make_unique<GenericKeywordPropertySequence>("autowrapped", [](const MenuFileParserState* state, const TokenPos&) - { - state->m_current_item->m_auto_wrapped = true; - })); - AddSequence(std::make_unique<GenericKeywordPropertySequence>("horizontalscroll", [](const MenuFileParserState* state, const TokenPos&) - { - state->m_current_item->m_horizontal_scroll = true; - })); - AddSequence(std::make_unique<GenericIntPropertySequence>("type", [](const MenuFileParserState* state, const TokenPos& pos, const int value) - { - ItemScopeOperations::SetItemType(*state->m_current_item, state->m_feature_level, pos, value); - })); - AddSequence(std::make_unique<GenericIntPropertySequence>("border", [](const MenuFileParserState* state, const TokenPos&, const int value) - { - state->m_current_item->m_border = value; - })); - AddSequence(std::make_unique<GenericFloatingPointPropertySequence>("borderSize", [](const MenuFileParserState* state, const TokenPos&, const double value) - { - state->m_current_item->m_border_size = value; - })); - AddSequence(GenericExpressionPropertySequence::WithKeywordAndBool("visible", [](const MenuFileParserState* state, const TokenPos& pos, std::unique_ptr<ISimpleExpression> value) - { + auto newEventHandlerSet = std::make_unique<CommonEventHandlerSet>(); + state->m_current_event_handler_set = newEventHandlerSet.get(); + state->m_current_nested_event_handler_set = newEventHandlerSet.get(); + state->m_current_item->m_key_handlers.emplace(std::make_pair(keyValue, std::move(newEventHandlerSet))); + } +}; +} // namespace menu::item_scope_sequences + +using namespace item_scope_sequences; + +ItemScopeSequences::ItemScopeSequences(std::vector<std::unique_ptr<MenuFileParser::sequence_t>> &allSequences, + std::vector<MenuFileParser::sequence_t *> &scopeSequences) + : AbstractScopeSequenceHolder(allSequences, scopeSequences) {} + +void ItemScopeSequences::AddSequences(FeatureLevel featureLevel, bool permissive) const { + AddSequence(std::make_unique<SequenceCloseBlock>()); + AddSequence(std::make_unique<GenericStringPropertySequence>( + "name", [](const MenuFileParserState *state, const TokenPos &, const std::string &value) { state->m_current_item->m_name = value; })); + AddSequence(std::make_unique<GenericStringPropertySequence>( + "text", [](const MenuFileParserState *state, const TokenPos &, const std::string &value) { state->m_current_item->m_text = value; })); + // textfile + AddSequence(std::make_unique<GenericKeywordPropertySequence>( + "textsavegame", [](const MenuFileParserState *state, const TokenPos &) { state->m_current_item->m_text_save_game = true; })); + AddSequence(std::make_unique<GenericKeywordPropertySequence>( + "textcinematicsubtitle", [](const MenuFileParserState *state, const TokenPos &) { state->m_current_item->m_text_cinematic_subtitle = true; })); + AddSequence(std::make_unique<GenericStringPropertySequence>( + "group", [](const MenuFileParserState *state, const TokenPos &, const std::string &value) { state->m_current_item->m_group = value; })); + AddSequence(std::make_unique<SequenceRect>()); + AddSequence(std::make_unique<SequenceOrigin>()); + // rect480 + // rect720 + // pos480 + // pos720 + AddSequence(std::make_unique<GenericIntPropertySequence>( + "style", [](const MenuFileParserState *state, const TokenPos &, const int value) { state->m_current_item->m_style = value; })); + AddSequence(std::make_unique<GenericKeywordPropertySequence>( + "decoration", [](const MenuFileParserState *state, const TokenPos &) { state->m_current_item->m_decoration = true; })); + AddSequence(std::make_unique<GenericKeywordPropertySequence>( + "autowrapped", [](const MenuFileParserState *state, const TokenPos &) { state->m_current_item->m_auto_wrapped = true; })); + AddSequence(std::make_unique<GenericKeywordPropertySequence>( + "horizontalscroll", [](const MenuFileParserState *state, const TokenPos &) { state->m_current_item->m_horizontal_scroll = true; })); + AddSequence(std::make_unique<GenericIntPropertySequence>("type", [](const MenuFileParserState *state, const TokenPos &pos, const int value) { + ItemScopeOperations::SetItemType(*state->m_current_item, state->m_feature_level, pos, value); + })); + AddSequence(std::make_unique<GenericIntPropertySequence>( + "border", [](const MenuFileParserState *state, const TokenPos &, const int value) { state->m_current_item->m_border = value; })); + AddSequence(std::make_unique<GenericFloatingPointPropertySequence>( + "borderSize", [](const MenuFileParserState *state, const TokenPos &, const double value) { state->m_current_item->m_border_size = value; })); + AddSequence(GenericExpressionPropertySequence::WithKeywordAndBool( + "visible", [](const MenuFileParserState *state, const TokenPos &pos, std::unique_ptr<ISimpleExpression> value) { MenuFileCommonOperations::EnsureIsNumericExpression(state, pos, *value); state->m_current_item->m_visible_expression = std::move(value); - })); - AddSequence(GenericExpressionPropertySequence::WithKeywordAndBool("disabled", [](const MenuFileParserState* state, const TokenPos& pos, std::unique_ptr<ISimpleExpression> value) - { + })); + AddSequence(GenericExpressionPropertySequence::WithKeywordAndBool( + "disabled", [](const MenuFileParserState *state, const TokenPos &pos, std::unique_ptr<ISimpleExpression> value) { MenuFileCommonOperations::EnsureIsNumericExpression(state, pos, *value); state->m_current_item->m_disabled_expression = std::move(value); - })); - AddSequence(std::make_unique<GenericIntPropertySequence>("ownerdraw", [](const MenuFileParserState* state, const TokenPos&, const int value) - { - state->m_current_item->m_owner_draw = value; - })); - AddSequence(std::make_unique<GenericIntPropertySequence>("align", [](const MenuFileParserState* state, const TokenPos&, const int value) - { - state->m_current_item->m_align = value; - })); - AddSequence(std::make_unique<GenericIntPropertySequence>("textalign", [](const MenuFileParserState* state, const TokenPos&, const int value) - { - state->m_current_item->m_text_align = value; - })); - AddSequence(std::make_unique<GenericFloatingPointPropertySequence>("textalignx", [](const MenuFileParserState* state, const TokenPos&, const double value) - { - state->m_current_item->m_text_align_x = value; - })); - AddSequence(std::make_unique<GenericFloatingPointPropertySequence>("textaligny", [](const MenuFileParserState* state, const TokenPos&, const double value) - { - state->m_current_item->m_text_align_y = value; - })); - AddSequence(std::make_unique<GenericFloatingPointPropertySequence>("textscale", [](const MenuFileParserState* state, const TokenPos&, const double value) - { - state->m_current_item->m_text_scale = value; - })); - AddSequence(std::make_unique<GenericIntPropertySequence>("textstyle", [](const MenuFileParserState* state, const TokenPos&, const int value) - { - state->m_current_item->m_text_style = value; - })); - AddSequence(std::make_unique<GenericIntPropertySequence>("textfont", [](const MenuFileParserState* state, const TokenPos&, const int value) - { - state->m_current_item->m_text_font = value; - })); - AddSequence(std::make_unique<GenericColorPropertySequence>("backcolor", [](const MenuFileParserState* state, const TokenPos&, const CommonColor value) - { - state->m_current_item->m_back_color = value; - })); - AddSequence(std::make_unique<GenericColorPropertySequence>("forecolor", [](const MenuFileParserState* state, const TokenPos&, const CommonColor value) - { - state->m_current_item->m_fore_color = value; - })); - AddSequence(std::make_unique<GenericColorPropertySequence>("bordercolor", [](const MenuFileParserState* state, const TokenPos&, const CommonColor value) - { - state->m_current_item->m_border_color = value; - })); - AddSequence(std::make_unique<GenericColorPropertySequence>("outlinecolor", [](const MenuFileParserState* state, const TokenPos&, const CommonColor value) - { - state->m_current_item->m_outline_color = value; - })); - AddSequence(std::make_unique<GenericColorPropertySequence>("disablecolor", [](const MenuFileParserState* state, const TokenPos&, const CommonColor value) - { - state->m_current_item->m_disable_color = value; - })); - AddSequence(std::make_unique<GenericColorPropertySequence>("glowcolor", [](const MenuFileParserState* state, const TokenPos&, const CommonColor value) - { - state->m_current_item->m_glow_color = value; - })); - AddSequence(std::make_unique<GenericStringPropertySequence>("background", [](const MenuFileParserState* state, const TokenPos&, const std::string& value) - { - state->m_current_item->m_background = value; - })); - AddSequence(std::make_unique<GenericMenuEventHandlerSetPropertySequence>("onFocus", [](const MenuFileParserState* state, const TokenPos&) -> std::unique_ptr<CommonEventHandlerSet>& { - return state->m_current_item->m_on_focus; - })); - AddSequence(std::make_unique<GenericMenuEventHandlerSetPropertySequence>("leaveFocus", [](const MenuFileParserState* state, const TokenPos&) -> std::unique_ptr<CommonEventHandlerSet>& { - return state->m_current_item->m_on_leave_focus; - })); - AddSequence(std::make_unique<GenericMenuEventHandlerSetPropertySequence>("mouseEnter", [](const MenuFileParserState* state, const TokenPos&) -> std::unique_ptr<CommonEventHandlerSet>& { - return state->m_current_item->m_on_mouse_enter; - })); - AddSequence(std::make_unique<GenericMenuEventHandlerSetPropertySequence>("mouseExit", [](const MenuFileParserState* state, const TokenPos&) -> std::unique_ptr<CommonEventHandlerSet>& { - return state->m_current_item->m_on_mouse_exit; - })); - AddSequence(std::make_unique<GenericMenuEventHandlerSetPropertySequence>("mouseEnterText", [](const MenuFileParserState* state, const TokenPos&) -> std::unique_ptr<CommonEventHandlerSet>& { + })); + AddSequence(std::make_unique<GenericIntPropertySequence>( + "ownerdraw", [](const MenuFileParserState *state, const TokenPos &, const int value) { state->m_current_item->m_owner_draw = value; })); + AddSequence(std::make_unique<GenericIntPropertySequence>( + "align", [](const MenuFileParserState *state, const TokenPos &, const int value) { state->m_current_item->m_align = value; })); + AddSequence(std::make_unique<GenericIntPropertySequence>( + "textalign", [](const MenuFileParserState *state, const TokenPos &, const int value) { state->m_current_item->m_text_align = value; })); + AddSequence(std::make_unique<GenericFloatingPointPropertySequence>( + "textalignx", [](const MenuFileParserState *state, const TokenPos &, const double value) { state->m_current_item->m_text_align_x = value; })); + AddSequence(std::make_unique<GenericFloatingPointPropertySequence>( + "textaligny", [](const MenuFileParserState *state, const TokenPos &, const double value) { state->m_current_item->m_text_align_y = value; })); + AddSequence(std::make_unique<GenericFloatingPointPropertySequence>( + "textscale", [](const MenuFileParserState *state, const TokenPos &, const double value) { state->m_current_item->m_text_scale = value; })); + AddSequence(std::make_unique<GenericIntPropertySequence>( + "textstyle", [](const MenuFileParserState *state, const TokenPos &, const int value) { state->m_current_item->m_text_style = value; })); + AddSequence(std::make_unique<GenericIntPropertySequence>( + "textfont", [](const MenuFileParserState *state, const TokenPos &, const int value) { state->m_current_item->m_text_font = value; })); + AddSequence(std::make_unique<GenericColorPropertySequence>( + "backcolor", [](const MenuFileParserState *state, const TokenPos &, const CommonColor value) { state->m_current_item->m_back_color = value; })); + AddSequence(std::make_unique<GenericColorPropertySequence>( + "forecolor", [](const MenuFileParserState *state, const TokenPos &, const CommonColor value) { state->m_current_item->m_fore_color = value; })); + AddSequence(std::make_unique<GenericColorPropertySequence>( + "bordercolor", [](const MenuFileParserState *state, const TokenPos &, const CommonColor value) { state->m_current_item->m_border_color = value; })); + AddSequence(std::make_unique<GenericColorPropertySequence>( + "outlinecolor", [](const MenuFileParserState *state, const TokenPos &, const CommonColor value) { state->m_current_item->m_outline_color = value; })); + AddSequence(std::make_unique<GenericColorPropertySequence>( + "disablecolor", [](const MenuFileParserState *state, const TokenPos &, const CommonColor value) { state->m_current_item->m_disable_color = value; })); + AddSequence(std::make_unique<GenericColorPropertySequence>( + "glowcolor", [](const MenuFileParserState *state, const TokenPos &, const CommonColor value) { state->m_current_item->m_glow_color = value; })); + AddSequence(std::make_unique<GenericStringPropertySequence>( + "background", [](const MenuFileParserState *state, const TokenPos &, const std::string &value) { state->m_current_item->m_background = value; })); + AddSequence(std::make_unique<GenericMenuEventHandlerSetPropertySequence>( + "onFocus", + [](const MenuFileParserState *state, const TokenPos &) -> std::unique_ptr<CommonEventHandlerSet> & { return state->m_current_item->m_on_focus; })); + AddSequence(std::make_unique<GenericMenuEventHandlerSetPropertySequence>( + "leaveFocus", + [](const MenuFileParserState *state, const TokenPos &) -> std::unique_ptr<CommonEventHandlerSet> & { return state->m_current_item->m_on_leave_focus; })); + AddSequence(std::make_unique<GenericMenuEventHandlerSetPropertySequence>( + "mouseEnter", + [](const MenuFileParserState *state, const TokenPos &) -> std::unique_ptr<CommonEventHandlerSet> & { return state->m_current_item->m_on_mouse_enter; })); + AddSequence(std::make_unique<GenericMenuEventHandlerSetPropertySequence>( + "mouseExit", + [](const MenuFileParserState *state, const TokenPos &) -> std::unique_ptr<CommonEventHandlerSet> & { return state->m_current_item->m_on_mouse_exit; })); + AddSequence(std::make_unique<GenericMenuEventHandlerSetPropertySequence>( + "mouseEnterText", [](const MenuFileParserState *state, const TokenPos &) -> std::unique_ptr<CommonEventHandlerSet> & { return state->m_current_item->m_on_mouse_enter_text; - })); - AddSequence(std::make_unique<GenericMenuEventHandlerSetPropertySequence>("mouseExitText", [](const MenuFileParserState* state, const TokenPos&) -> std::unique_ptr<CommonEventHandlerSet>& { + })); + AddSequence(std::make_unique<GenericMenuEventHandlerSetPropertySequence>( + "mouseExitText", [](const MenuFileParserState *state, const TokenPos &) -> std::unique_ptr<CommonEventHandlerSet> & { return state->m_current_item->m_on_mouse_exit_text; - })); - AddSequence(std::make_unique<GenericMenuEventHandlerSetPropertySequence>("action", [](const MenuFileParserState* state, const TokenPos&) -> std::unique_ptr<CommonEventHandlerSet>& { - return state->m_current_item->m_on_action; - })); - AddSequence(std::make_unique<GenericMenuEventHandlerSetPropertySequence>("accept", [](const MenuFileParserState* state, const TokenPos&) -> std::unique_ptr<CommonEventHandlerSet>& { - return state->m_current_item->m_on_accept; - })); - // special - AddSequence(std::make_unique<GenericStringPropertySequence>("dvar", [](const MenuFileParserState* state, const TokenPos&, const std::string& value) - { - state->m_current_item->m_dvar = value; - })); - AddSequence(std::make_unique<GenericStringPropertySequence>("focusSound", [](const MenuFileParserState* state, const TokenPos&, const std::string& value) - { - state->m_current_item->m_focus_sound = value; - })); - AddSequence(std::make_unique<GenericIntPropertySequence>("ownerdrawFlag", [](const MenuFileParserState* state, const TokenPos&, const int value) - { - state->m_current_item->m_owner_draw_flags |= value; - })); - AddSequence(std::make_unique<SequenceMultiTokenBlock>("enableDvar", [](const MenuFileParserState* state, const TokenPos&, std::vector<std::string> value) - { - state->m_current_item->m_enable_dvar = std::move(value); - })); - AddSequence(std::make_unique<GenericStringPropertySequence>("dvarTest", [](const MenuFileParserState* state, const TokenPos&, const std::string& value) - { - state->m_current_item->m_dvar_test = value; - })); - AddSequence(std::make_unique<SequenceMultiTokenBlock>("disableDvar", [](const MenuFileParserState* state, const TokenPos&, std::vector<std::string> value) - { - state->m_current_item->m_disable_dvar = std::move(value); - })); - AddSequence(std::make_unique<SequenceMultiTokenBlock>("showDvar", [](const MenuFileParserState* state, const TokenPos&, std::vector<std::string> value) - { - state->m_current_item->m_show_dvar = std::move(value); - })); - AddSequence(std::make_unique<SequenceMultiTokenBlock>("hideDvar", [](const MenuFileParserState* state, const TokenPos&, std::vector<std::string> value) - { - state->m_current_item->m_hide_dvar = std::move(value); - })); - AddSequence(std::make_unique<SequenceMultiTokenBlock>("focusDvar", [](const MenuFileParserState* state, const TokenPos&, std::vector<std::string> value) - { - state->m_current_item->m_focus_dvar = std::move(value); - })); - AddSequence(std::make_unique<SequenceExecKey>()); - AddSequence(std::make_unique<SequenceExecKeyInt>()); - AddSequence(std::make_unique<GenericIntPropertySequence>("gamemsgwindowindex", [](const MenuFileParserState* state, const TokenPos&, const int value) - { - state->m_current_item->m_game_message_window_index = value; - })); - AddSequence(std::make_unique<GenericIntPropertySequence>("gamemsgwindowmode", [](const MenuFileParserState* state, const TokenPos&, const int value) - { - state->m_current_item->m_game_message_window_mode = value; - })); - AddSequence(std::make_unique<SequenceDecodeEffect>()); - AddSequence(GenericExpressionPropertySequence::WithKeywords({"exp", "disabled"}, [](const MenuFileParserState* state, const TokenPos& pos, std::unique_ptr<ISimpleExpression> value) - { + })); + AddSequence(std::make_unique<GenericMenuEventHandlerSetPropertySequence>( + "action", + [](const MenuFileParserState *state, const TokenPos &) -> std::unique_ptr<CommonEventHandlerSet> & { return state->m_current_item->m_on_action; })); + AddSequence(std::make_unique<GenericMenuEventHandlerSetPropertySequence>( + "accept", + [](const MenuFileParserState *state, const TokenPos &) -> std::unique_ptr<CommonEventHandlerSet> & { return state->m_current_item->m_on_accept; })); + // special + AddSequence(std::make_unique<GenericStringPropertySequence>( + "dvar", [](const MenuFileParserState *state, const TokenPos &, const std::string &value) { state->m_current_item->m_dvar = value; })); + AddSequence(std::make_unique<GenericStringPropertySequence>( + "focusSound", [](const MenuFileParserState *state, const TokenPos &, const std::string &value) { state->m_current_item->m_focus_sound = value; })); + AddSequence(std::make_unique<GenericIntPropertySequence>( + "ownerdrawFlag", [](const MenuFileParserState *state, const TokenPos &, const int value) { state->m_current_item->m_owner_draw_flags |= value; })); + AddSequence(std::make_unique<SequenceMultiTokenBlock>("enableDvar", [](const MenuFileParserState *state, const TokenPos &, std::vector<std::string> value) { + state->m_current_item->m_enable_dvar = std::move(value); + })); + AddSequence(std::make_unique<GenericStringPropertySequence>( + "dvarTest", [](const MenuFileParserState *state, const TokenPos &, const std::string &value) { state->m_current_item->m_dvar_test = value; })); + AddSequence(std::make_unique<SequenceMultiTokenBlock>("disableDvar", [](const MenuFileParserState *state, const TokenPos &, std::vector<std::string> value) { + state->m_current_item->m_disable_dvar = std::move(value); + })); + AddSequence(std::make_unique<SequenceMultiTokenBlock>("showDvar", [](const MenuFileParserState *state, const TokenPos &, std::vector<std::string> value) { + state->m_current_item->m_show_dvar = std::move(value); + })); + AddSequence(std::make_unique<SequenceMultiTokenBlock>("hideDvar", [](const MenuFileParserState *state, const TokenPos &, std::vector<std::string> value) { + state->m_current_item->m_hide_dvar = std::move(value); + })); + AddSequence(std::make_unique<SequenceMultiTokenBlock>("focusDvar", [](const MenuFileParserState *state, const TokenPos &, std::vector<std::string> value) { + state->m_current_item->m_focus_dvar = std::move(value); + })); + AddSequence(std::make_unique<SequenceExecKey>()); + AddSequence(std::make_unique<SequenceExecKeyInt>()); + AddSequence(std::make_unique<GenericIntPropertySequence>("gamemsgwindowindex", [](const MenuFileParserState *state, const TokenPos &, const int value) { + state->m_current_item->m_game_message_window_index = value; + })); + AddSequence(std::make_unique<GenericIntPropertySequence>("gamemsgwindowmode", [](const MenuFileParserState *state, const TokenPos &, const int value) { + state->m_current_item->m_game_message_window_mode = value; + })); + AddSequence(std::make_unique<SequenceDecodeEffect>()); + AddSequence(GenericExpressionPropertySequence::WithKeywords( + {"exp", "disabled"}, [](const MenuFileParserState *state, const TokenPos &pos, std::unique_ptr<ISimpleExpression> value) { MenuFileCommonOperations::EnsureIsNumericExpression(state, pos, *value); state->m_current_item->m_disabled_expression = std::move(value); - })); - AddSequence(GenericExpressionPropertySequence::WithKeywords({"exp", "text"}, [](const MenuFileParserState* state, const TokenPos& pos, std::unique_ptr<ISimpleExpression> value) - { + })); + AddSequence(GenericExpressionPropertySequence::WithKeywords( + {"exp", "text"}, [](const MenuFileParserState *state, const TokenPos &pos, std::unique_ptr<ISimpleExpression> value) { MenuFileCommonOperations::EnsureIsStringExpression(state, pos, *value); state->m_current_item->m_text_expression = std::move(value); - })); - AddSequence(GenericExpressionPropertySequence::WithKeywords({"exp", "material"}, [](const MenuFileParserState* state, const TokenPos& pos, std::unique_ptr<ISimpleExpression> value) - { + })); + AddSequence(GenericExpressionPropertySequence::WithKeywords( + {"exp", "material"}, [](const MenuFileParserState *state, const TokenPos &pos, std::unique_ptr<ISimpleExpression> value) { MenuFileCommonOperations::EnsureIsStringExpression(state, pos, *value); state->m_current_item->m_material_expression = std::move(value); - })); - AddSequence(GenericExpressionPropertySequence::WithKeywords({"exp", "rect", "X"}, [](const MenuFileParserState* state, const TokenPos& pos, std::unique_ptr<ISimpleExpression> value) - { + })); + AddSequence(GenericExpressionPropertySequence::WithKeywords( + {"exp", "rect", "X"}, [](const MenuFileParserState *state, const TokenPos &pos, std::unique_ptr<ISimpleExpression> value) { MenuFileCommonOperations::EnsureIsNumericExpression(state, pos, *value); state->m_current_item->m_rect_x_exp = std::move(value); - })); - AddSequence(GenericExpressionPropertySequence::WithKeywords({"exp", "rect", "Y"}, [](const MenuFileParserState* state, const TokenPos& pos, std::unique_ptr<ISimpleExpression> value) - { + })); + AddSequence(GenericExpressionPropertySequence::WithKeywords( + {"exp", "rect", "Y"}, [](const MenuFileParserState *state, const TokenPos &pos, std::unique_ptr<ISimpleExpression> value) { MenuFileCommonOperations::EnsureIsNumericExpression(state, pos, *value); state->m_current_item->m_rect_y_exp = std::move(value); - })); - AddSequence(GenericExpressionPropertySequence::WithKeywords({"exp", "rect", "W"}, [](const MenuFileParserState* state, const TokenPos& pos, std::unique_ptr<ISimpleExpression> value) - { + })); + AddSequence(GenericExpressionPropertySequence::WithKeywords( + {"exp", "rect", "W"}, [](const MenuFileParserState *state, const TokenPos &pos, std::unique_ptr<ISimpleExpression> value) { MenuFileCommonOperations::EnsureIsNumericExpression(state, pos, *value); state->m_current_item->m_rect_w_exp = std::move(value); - })); - AddSequence(GenericExpressionPropertySequence::WithKeywords({"exp", "rect", "H"}, [](const MenuFileParserState* state, const TokenPos& pos, std::unique_ptr<ISimpleExpression> value) - { + })); + AddSequence(GenericExpressionPropertySequence::WithKeywords( + {"exp", "rect", "H"}, [](const MenuFileParserState *state, const TokenPos &pos, std::unique_ptr<ISimpleExpression> value) { MenuFileCommonOperations::EnsureIsNumericExpression(state, pos, *value); state->m_current_item->m_rect_h_exp = std::move(value); - })); - AddSequence(GenericExpressionPropertySequence::WithKeywords({"exp", "forecolor", "R"}, [](const MenuFileParserState* state, const TokenPos& pos, std::unique_ptr<ISimpleExpression> value) - { + })); + AddSequence(GenericExpressionPropertySequence::WithKeywords( + {"exp", "forecolor", "R"}, [](const MenuFileParserState *state, const TokenPos &pos, std::unique_ptr<ISimpleExpression> value) { MenuFileCommonOperations::EnsureIsNumericExpression(state, pos, *value); state->m_current_item->m_forecolor_expressions.m_r_exp = std::move(value); - })); - AddSequence(GenericExpressionPropertySequence::WithKeywords({"exp", "forecolor", "G"}, [](const MenuFileParserState* state, const TokenPos& pos, std::unique_ptr<ISimpleExpression> value) - { + })); + AddSequence(GenericExpressionPropertySequence::WithKeywords( + {"exp", "forecolor", "G"}, [](const MenuFileParserState *state, const TokenPos &pos, std::unique_ptr<ISimpleExpression> value) { MenuFileCommonOperations::EnsureIsNumericExpression(state, pos, *value); state->m_current_item->m_forecolor_expressions.m_g_exp = std::move(value); - })); - AddSequence(GenericExpressionPropertySequence::WithKeywords({"exp", "forecolor", "B"}, [](const MenuFileParserState* state, const TokenPos& pos, std::unique_ptr<ISimpleExpression> value) - { + })); + AddSequence(GenericExpressionPropertySequence::WithKeywords( + {"exp", "forecolor", "B"}, [](const MenuFileParserState *state, const TokenPos &pos, std::unique_ptr<ISimpleExpression> value) { MenuFileCommonOperations::EnsureIsNumericExpression(state, pos, *value); state->m_current_item->m_forecolor_expressions.m_b_exp = std::move(value); - })); - AddSequence(GenericExpressionPropertySequence::WithKeywords({"exp", "forecolor", "A"}, [](const MenuFileParserState* state, const TokenPos& pos, std::unique_ptr<ISimpleExpression> value) - { + })); + AddSequence(GenericExpressionPropertySequence::WithKeywords( + {"exp", "forecolor", "A"}, [](const MenuFileParserState *state, const TokenPos &pos, std::unique_ptr<ISimpleExpression> value) { MenuFileCommonOperations::EnsureIsNumericExpression(state, pos, *value); state->m_current_item->m_forecolor_expressions.m_a_exp = std::move(value); - })); - AddSequence(GenericExpressionPropertySequence::WithKeywords({"exp", "forecolor", "RGB"}, [](const MenuFileParserState* state, const TokenPos& pos, std::unique_ptr<ISimpleExpression> value) - { + })); + AddSequence(GenericExpressionPropertySequence::WithKeywords( + {"exp", "forecolor", "RGB"}, [](const MenuFileParserState *state, const TokenPos &pos, std::unique_ptr<ISimpleExpression> value) { MenuFileCommonOperations::EnsureIsNumericExpression(state, pos, *value); state->m_current_item->m_forecolor_expressions.m_rgb_exp = std::move(value); - })); - AddSequence(GenericExpressionPropertySequence::WithKeywords({"exp", "glowcolor", "R"}, [](const MenuFileParserState* state, const TokenPos& pos, std::unique_ptr<ISimpleExpression> value) - { + })); + AddSequence(GenericExpressionPropertySequence::WithKeywords( + {"exp", "glowcolor", "R"}, [](const MenuFileParserState *state, const TokenPos &pos, std::unique_ptr<ISimpleExpression> value) { MenuFileCommonOperations::EnsureIsNumericExpression(state, pos, *value); state->m_current_item->m_glowcolor_expressions.m_r_exp = std::move(value); - })); - AddSequence(GenericExpressionPropertySequence::WithKeywords({"exp", "glowcolor", "G"}, [](const MenuFileParserState* state, const TokenPos& pos, std::unique_ptr<ISimpleExpression> value) - { + })); + AddSequence(GenericExpressionPropertySequence::WithKeywords( + {"exp", "glowcolor", "G"}, [](const MenuFileParserState *state, const TokenPos &pos, std::unique_ptr<ISimpleExpression> value) { MenuFileCommonOperations::EnsureIsNumericExpression(state, pos, *value); state->m_current_item->m_glowcolor_expressions.m_g_exp = std::move(value); - })); - AddSequence(GenericExpressionPropertySequence::WithKeywords({"exp", "glowcolor", "B"}, [](const MenuFileParserState* state, const TokenPos& pos, std::unique_ptr<ISimpleExpression> value) - { + })); + AddSequence(GenericExpressionPropertySequence::WithKeywords( + {"exp", "glowcolor", "B"}, [](const MenuFileParserState *state, const TokenPos &pos, std::unique_ptr<ISimpleExpression> value) { MenuFileCommonOperations::EnsureIsNumericExpression(state, pos, *value); state->m_current_item->m_glowcolor_expressions.m_b_exp = std::move(value); - })); - AddSequence(GenericExpressionPropertySequence::WithKeywords({"exp", "glowcolor", "A"}, [](const MenuFileParserState* state, const TokenPos& pos, std::unique_ptr<ISimpleExpression> value) - { + })); + AddSequence(GenericExpressionPropertySequence::WithKeywords( + {"exp", "glowcolor", "A"}, [](const MenuFileParserState *state, const TokenPos &pos, std::unique_ptr<ISimpleExpression> value) { MenuFileCommonOperations::EnsureIsNumericExpression(state, pos, *value); state->m_current_item->m_glowcolor_expressions.m_a_exp = std::move(value); - })); - AddSequence(GenericExpressionPropertySequence::WithKeywords({"exp", "glowcolor", "RGB"}, [](const MenuFileParserState* state, const TokenPos& pos, std::unique_ptr<ISimpleExpression> value) - { + })); + AddSequence(GenericExpressionPropertySequence::WithKeywords( + {"exp", "glowcolor", "RGB"}, [](const MenuFileParserState *state, const TokenPos &pos, std::unique_ptr<ISimpleExpression> value) { MenuFileCommonOperations::EnsureIsNumericExpression(state, pos, *value); state->m_current_item->m_glowcolor_expressions.m_rgb_exp = std::move(value); - })); - AddSequence(GenericExpressionPropertySequence::WithKeywords({"exp", "backcolor", "R"}, [](const MenuFileParserState* state, const TokenPos& pos, std::unique_ptr<ISimpleExpression> value) - { + })); + AddSequence(GenericExpressionPropertySequence::WithKeywords( + {"exp", "backcolor", "R"}, [](const MenuFileParserState *state, const TokenPos &pos, std::unique_ptr<ISimpleExpression> value) { MenuFileCommonOperations::EnsureIsNumericExpression(state, pos, *value); state->m_current_item->m_backcolor_expressions.m_r_exp = std::move(value); - })); - AddSequence(GenericExpressionPropertySequence::WithKeywords({"exp", "backcolor", "G"}, [](const MenuFileParserState* state, const TokenPos& pos, std::unique_ptr<ISimpleExpression> value) - { + })); + AddSequence(GenericExpressionPropertySequence::WithKeywords( + {"exp", "backcolor", "G"}, [](const MenuFileParserState *state, const TokenPos &pos, std::unique_ptr<ISimpleExpression> value) { MenuFileCommonOperations::EnsureIsNumericExpression(state, pos, *value); state->m_current_item->m_backcolor_expressions.m_g_exp = std::move(value); - })); - AddSequence(GenericExpressionPropertySequence::WithKeywords({"exp", "backcolor", "B"}, [](const MenuFileParserState* state, const TokenPos& pos, std::unique_ptr<ISimpleExpression> value) - { + })); + AddSequence(GenericExpressionPropertySequence::WithKeywords( + {"exp", "backcolor", "B"}, [](const MenuFileParserState *state, const TokenPos &pos, std::unique_ptr<ISimpleExpression> value) { MenuFileCommonOperations::EnsureIsNumericExpression(state, pos, *value); state->m_current_item->m_backcolor_expressions.m_b_exp = std::move(value); - })); - AddSequence(GenericExpressionPropertySequence::WithKeywords({"exp", "backcolor", "A"}, [](const MenuFileParserState* state, const TokenPos& pos, std::unique_ptr<ISimpleExpression> value) - { + })); + AddSequence(GenericExpressionPropertySequence::WithKeywords( + {"exp", "backcolor", "A"}, [](const MenuFileParserState *state, const TokenPos &pos, std::unique_ptr<ISimpleExpression> value) { MenuFileCommonOperations::EnsureIsNumericExpression(state, pos, *value); state->m_current_item->m_backcolor_expressions.m_a_exp = std::move(value); - })); - AddSequence(GenericExpressionPropertySequence::WithKeywords({"exp", "backcolor", "RGB"}, [](const MenuFileParserState* state, const TokenPos& pos, std::unique_ptr<ISimpleExpression> value) - { + })); + AddSequence(GenericExpressionPropertySequence::WithKeywords( + {"exp", "backcolor", "RGB"}, [](const MenuFileParserState *state, const TokenPos &pos, std::unique_ptr<ISimpleExpression> value) { MenuFileCommonOperations::EnsureIsNumericExpression(state, pos, *value); state->m_current_item->m_backcolor_expressions.m_rgb_exp = std::move(value); - })); - - if (featureLevel == FeatureLevel::IW5) - { - AddSequence(std::make_unique<GenericMenuEventHandlerSetPropertySequence>("hasFocus", [](const MenuFileParserState* state, const TokenPos&) -> std::unique_ptr<CommonEventHandlerSet>& { - return state->m_current_item->m_has_focus; + })); + + if (featureLevel == FeatureLevel::IW5) { + AddSequence(std::make_unique<GenericMenuEventHandlerSetPropertySequence>( + "hasFocus", + [](const MenuFileParserState *state, const TokenPos &) -> std::unique_ptr<CommonEventHandlerSet> & { return state->m_current_item->m_has_focus; })); + AddSequence(GenericExpressionPropertySequence::WithKeywords( + {"exp", "textaligny"}, [](const MenuFileParserState *state, const TokenPos &pos, std::unique_ptr<ISimpleExpression> value) { + MenuFileCommonOperations::EnsureIsNumericExpression(state, pos, *value); + state->m_current_item->m_text_align_y_expression = std::move(value); })); - AddSequence(GenericExpressionPropertySequence::WithKeywords({"exp", "textaligny"}, [](const MenuFileParserState* state, const TokenPos& pos, std::unique_ptr<ISimpleExpression> value) - { - MenuFileCommonOperations::EnsureIsNumericExpression(state, pos, *value); - state->m_current_item->m_text_align_y_expression = std::move(value); - })); - } - - // ============== ListBox ============== - AddSequence(std::make_unique<SequenceColumns>(featureLevel)); - AddSequence(std::make_unique<GenericKeywordPropertySequence>("notselectable", [](const MenuFileParserState* state, const TokenPos& pos) - { - ItemScopeOperations::EnsureHasListboxFeatures(*state->m_current_item, pos); - state->m_current_item->m_list_box_features->m_not_selectable = true; - })); - AddSequence(std::make_unique<GenericKeywordPropertySequence>("noscrollbars", [](const MenuFileParserState* state, const TokenPos& pos) - { - ItemScopeOperations::EnsureHasListboxFeatures(*state->m_current_item, pos); - state->m_current_item->m_list_box_features->m_no_scrollbars = true; - })); - AddSequence(std::make_unique<GenericKeywordPropertySequence>("usepaging", [](const MenuFileParserState* state, const TokenPos& pos) - { - ItemScopeOperations::EnsureHasListboxFeatures(*state->m_current_item, pos); - state->m_current_item->m_list_box_features->m_use_paging = true; - })); - AddSequence(std::make_unique<GenericFloatingPointPropertySequence>("elementwidth", [](const MenuFileParserState* state, const TokenPos& pos, const double value) - { + } + + // ============== ListBox ============== + AddSequence(std::make_unique<SequenceColumns>(featureLevel)); + AddSequence(std::make_unique<GenericKeywordPropertySequence>("notselectable", [](const MenuFileParserState *state, const TokenPos &pos) { + ItemScopeOperations::EnsureHasListboxFeatures(*state->m_current_item, pos); + state->m_current_item->m_list_box_features->m_not_selectable = true; + })); + AddSequence(std::make_unique<GenericKeywordPropertySequence>("noscrollbars", [](const MenuFileParserState *state, const TokenPos &pos) { + ItemScopeOperations::EnsureHasListboxFeatures(*state->m_current_item, pos); + state->m_current_item->m_list_box_features->m_no_scrollbars = true; + })); + AddSequence(std::make_unique<GenericKeywordPropertySequence>("usepaging", [](const MenuFileParserState *state, const TokenPos &pos) { + ItemScopeOperations::EnsureHasListboxFeatures(*state->m_current_item, pos); + state->m_current_item->m_list_box_features->m_use_paging = true; + })); + AddSequence( + std::make_unique<GenericFloatingPointPropertySequence>("elementwidth", [](const MenuFileParserState *state, const TokenPos &pos, const double value) { ItemScopeOperations::EnsureHasListboxFeatures(*state->m_current_item, pos); state->m_current_item->m_list_box_features->m_element_width = value; - })); - AddSequence(std::make_unique<GenericFloatingPointPropertySequence>("elementheight", [](const MenuFileParserState* state, const TokenPos& pos, const double value) - { + })); + AddSequence( + std::make_unique<GenericFloatingPointPropertySequence>("elementheight", [](const MenuFileParserState *state, const TokenPos &pos, const double value) { ItemScopeOperations::EnsureHasListboxFeatures(*state->m_current_item, pos); state->m_current_item->m_list_box_features->m_element_height = value; - })); - AddSequence(std::make_unique<GenericFloatingPointPropertySequence>("feeder", [](const MenuFileParserState* state, const TokenPos& pos, const double value) - { - ItemScopeOperations::EnsureHasListboxFeatures(*state->m_current_item, pos); - state->m_current_item->m_list_box_features->m_feeder = value; - })); - AddSequence(std::make_unique<GenericIntPropertySequence>("elementtype", [](const MenuFileParserState* state, const TokenPos& pos, const int value) - { - ItemScopeOperations::EnsureHasListboxFeatures(*state->m_current_item, pos); - state->m_current_item->m_list_box_features->m_element_style = value; - })); - AddSequence(std::make_unique<GenericMenuEventHandlerSetPropertySequence>("doubleclick", [](const MenuFileParserState* state, const TokenPos& pos) -> std::unique_ptr<CommonEventHandlerSet>& { + })); + AddSequence(std::make_unique<GenericFloatingPointPropertySequence>("feeder", [](const MenuFileParserState *state, const TokenPos &pos, const double value) { + ItemScopeOperations::EnsureHasListboxFeatures(*state->m_current_item, pos); + state->m_current_item->m_list_box_features->m_feeder = value; + })); + AddSequence(std::make_unique<GenericIntPropertySequence>("elementtype", [](const MenuFileParserState *state, const TokenPos &pos, const int value) { + ItemScopeOperations::EnsureHasListboxFeatures(*state->m_current_item, pos); + state->m_current_item->m_list_box_features->m_element_style = value; + })); + AddSequence(std::make_unique<GenericMenuEventHandlerSetPropertySequence>( + "doubleclick", [](const MenuFileParserState *state, const TokenPos &pos) -> std::unique_ptr<CommonEventHandlerSet> & { ItemScopeOperations::EnsureHasListboxFeatures(*state->m_current_item, pos); return state->m_current_item->m_list_box_features->m_on_double_click; - })); - AddSequence(std::make_unique<GenericColorPropertySequence>("selectBorder", [](const MenuFileParserState* state, const TokenPos& pos, const CommonColor value) - { + })); + AddSequence( + std::make_unique<GenericColorPropertySequence>("selectBorder", [](const MenuFileParserState *state, const TokenPos &pos, const CommonColor value) { ItemScopeOperations::EnsureHasListboxFeatures(*state->m_current_item, pos); state->m_current_item->m_list_box_features->m_select_border = value; - })); - AddSequence(std::make_unique<GenericStringPropertySequence>("selectIcon", [](const MenuFileParserState* state, const TokenPos& pos, const std::string& value) - { + })); + AddSequence( + std::make_unique<GenericStringPropertySequence>("selectIcon", [](const MenuFileParserState *state, const TokenPos &pos, const std::string &value) { ItemScopeOperations::EnsureHasListboxFeatures(*state->m_current_item, pos); state->m_current_item->m_list_box_features->m_select_icon = value; - })); - - if (featureLevel == FeatureLevel::IW5) - { - AddSequence(GenericExpressionPropertySequence::WithKeywords({"exp", "elementheight"}, [](const MenuFileParserState* state, const TokenPos& pos, std::unique_ptr<ISimpleExpression> value) - { - ItemScopeOperations::EnsureHasListboxFeatures(*state->m_current_item, pos); - MenuFileCommonOperations::EnsureIsNumericExpression(state, pos, *value); - state->m_current_item->m_list_box_features->m_element_height_expression = std::move(value); + })); + + if (featureLevel == FeatureLevel::IW5) { + AddSequence(GenericExpressionPropertySequence::WithKeywords( + {"exp", "elementheight"}, [](const MenuFileParserState *state, const TokenPos &pos, std::unique_ptr<ISimpleExpression> value) { + ItemScopeOperations::EnsureHasListboxFeatures(*state->m_current_item, pos); + MenuFileCommonOperations::EnsureIsNumericExpression(state, pos, *value); + state->m_current_item->m_list_box_features->m_element_height_expression = std::move(value); })); - } - - // ============== Edit Field ============== - AddSequence(std::make_unique<SequenceDvarFloat>()); - AddSequence(std::make_unique<GenericStringPropertySequence>("localvar", [](const MenuFileParserState* state, const TokenPos& pos, const std::string& value) - { - ItemScopeOperations::EnsureHasEditFieldFeatures(*state->m_current_item, pos); - state->m_current_item->m_edit_field_features->m_local_var = value; - })); - AddSequence(std::make_unique<GenericIntPropertySequence>("maxChars", [](const MenuFileParserState* state, const TokenPos& pos, const int value) - { - ItemScopeOperations::EnsureHasEditFieldFeatures(*state->m_current_item, pos); - state->m_current_item->m_edit_field_features->m_max_chars = value; - })); - AddSequence(std::make_unique<GenericIntPropertySequence>("maxPaintChars", [](const MenuFileParserState* state, const TokenPos& pos, const int value) - { - ItemScopeOperations::EnsureHasEditFieldFeatures(*state->m_current_item, pos); - state->m_current_item->m_edit_field_features->m_max_paint_chars = value; - })); - AddSequence(std::make_unique<GenericKeywordPropertySequence>("maxCharsGotoNext", [](const MenuFileParserState* state, const TokenPos& pos) - { - ItemScopeOperations::EnsureHasEditFieldFeatures(*state->m_current_item, pos); - state->m_current_item->m_edit_field_features->m_max_chars_goto_next = true; - })); - - // ============== Multi Value ============== - AddSequence(std::make_unique<SequenceDvarStrList>()); - AddSequence(std::make_unique<SequenceDvarFloatList>()); - - // ============== Enum Dvar ============== - AddSequence(std::make_unique<GenericStringPropertySequence>("dvarEnumList", [](const MenuFileParserState* state, const TokenPos& pos, const std::string& value) - { + } + + // ============== Edit Field ============== + AddSequence(std::make_unique<SequenceDvarFloat>()); + AddSequence(std::make_unique<GenericStringPropertySequence>("localvar", [](const MenuFileParserState *state, const TokenPos &pos, const std::string &value) { + ItemScopeOperations::EnsureHasEditFieldFeatures(*state->m_current_item, pos); + state->m_current_item->m_edit_field_features->m_local_var = value; + })); + AddSequence(std::make_unique<GenericIntPropertySequence>("maxChars", [](const MenuFileParserState *state, const TokenPos &pos, const int value) { + ItemScopeOperations::EnsureHasEditFieldFeatures(*state->m_current_item, pos); + state->m_current_item->m_edit_field_features->m_max_chars = value; + })); + AddSequence(std::make_unique<GenericIntPropertySequence>("maxPaintChars", [](const MenuFileParserState *state, const TokenPos &pos, const int value) { + ItemScopeOperations::EnsureHasEditFieldFeatures(*state->m_current_item, pos); + state->m_current_item->m_edit_field_features->m_max_paint_chars = value; + })); + AddSequence(std::make_unique<GenericKeywordPropertySequence>("maxCharsGotoNext", [](const MenuFileParserState *state, const TokenPos &pos) { + ItemScopeOperations::EnsureHasEditFieldFeatures(*state->m_current_item, pos); + state->m_current_item->m_edit_field_features->m_max_chars_goto_next = true; + })); + + // ============== Multi Value ============== + AddSequence(std::make_unique<SequenceDvarStrList>()); + AddSequence(std::make_unique<SequenceDvarFloatList>()); + + // ============== Enum Dvar ============== + AddSequence( + std::make_unique<GenericStringPropertySequence>("dvarEnumList", [](const MenuFileParserState *state, const TokenPos &pos, const std::string &value) { ItemScopeOperations::EnsureHasEnumDvarFeatures(*state->m_current_item, pos); state->m_current_item->m_enum_dvar_name = value; - })); - - // ============== News Ticker ============== - AddSequence(std::make_unique<GenericIntPropertySequence>("spacing", [](const MenuFileParserState* state, const TokenPos& pos, const int value) - { - ItemScopeOperations::EnsureHasNewsTickerFeatures(*state->m_current_item, pos); - state->m_current_item->m_news_ticker_features->m_spacing = value; - })); - AddSequence(std::make_unique<GenericIntPropertySequence>("speed", [](const MenuFileParserState* state, const TokenPos& pos, const int value) - { - ItemScopeOperations::EnsureHasNewsTickerFeatures(*state->m_current_item, pos); - state->m_current_item->m_news_ticker_features->m_speed = value; - })); - AddSequence(std::make_unique<GenericIntPropertySequence>("newsfeed", [](const MenuFileParserState* state, const TokenPos& pos, const int value) - { - ItemScopeOperations::EnsureHasNewsTickerFeatures(*state->m_current_item, pos); - state->m_current_item->m_news_ticker_features->m_news_feed_id = value; - })); - - AddSequence(std::make_unique<SequenceConsumeSemicolons>()); + })); + + // ============== News Ticker ============== + AddSequence(std::make_unique<GenericIntPropertySequence>("spacing", [](const MenuFileParserState *state, const TokenPos &pos, const int value) { + ItemScopeOperations::EnsureHasNewsTickerFeatures(*state->m_current_item, pos); + state->m_current_item->m_news_ticker_features->m_spacing = value; + })); + AddSequence(std::make_unique<GenericIntPropertySequence>("speed", [](const MenuFileParserState *state, const TokenPos &pos, const int value) { + ItemScopeOperations::EnsureHasNewsTickerFeatures(*state->m_current_item, pos); + state->m_current_item->m_news_ticker_features->m_speed = value; + })); + AddSequence(std::make_unique<GenericIntPropertySequence>("newsfeed", [](const MenuFileParserState *state, const TokenPos &pos, const int value) { + ItemScopeOperations::EnsureHasNewsTickerFeatures(*state->m_current_item, pos); + state->m_current_item->m_news_ticker_features->m_news_feed_id = value; + })); + + AddSequence(std::make_unique<SequenceConsumeSemicolons>()); } diff --git a/src/ObjLoading/Parsing/Menu/Sequence/ItemScopeSequences.h b/src/ObjLoading/Parsing/Menu/Sequence/ItemScopeSequences.h index 357435939..8f575a281 100644 --- a/src/ObjLoading/Parsing/Menu/Sequence/ItemScopeSequences.h +++ b/src/ObjLoading/Parsing/Menu/Sequence/ItemScopeSequences.h @@ -3,13 +3,11 @@ #include "Parsing/Menu/MenuFileParser.h" #include "Parsing/Sequence/AbstractScopeSequenceHolder.h" -namespace menu -{ - class ItemScopeSequences final : AbstractScopeSequenceHolder<MenuFileParser> - { - public: - ItemScopeSequences(std::vector<std::unique_ptr<MenuFileParser::sequence_t>>& allSequences, std::vector<MenuFileParser::sequence_t*>& scopeSequences); +namespace menu { +class ItemScopeSequences final : AbstractScopeSequenceHolder<MenuFileParser> { +public: + ItemScopeSequences(std::vector<std::unique_ptr<MenuFileParser::sequence_t>> &allSequences, std::vector<MenuFileParser::sequence_t *> &scopeSequences); - void AddSequences(FeatureLevel featureLevel, bool permissive) const; - }; -} + void AddSequences(FeatureLevel featureLevel, bool permissive) const; +}; +} // namespace menu diff --git a/src/ObjLoading/Parsing/Menu/Sequence/MenuScopeSequences.cpp b/src/ObjLoading/Parsing/Menu/Sequence/MenuScopeSequences.cpp index cbfbbed64..d52397f0c 100644 --- a/src/ObjLoading/Parsing/Menu/Sequence/MenuScopeSequences.cpp +++ b/src/ObjLoading/Parsing/Menu/Sequence/MenuScopeSequences.cpp @@ -10,410 +10,299 @@ #include "Generic/GenericKeywordPropertySequence.h" #include "Generic/GenericMenuEventHandlerSetPropertySequence.h" #include "Generic/GenericStringPropertySequence.h" -#include "Parsing/Menu/MenuFileCommonOperations.h" -#include "Parsing/Menu/Matcher/MenuMatcherFactory.h" #include "Parsing/Menu/Domain/CommonMenuTypes.h" #include "Parsing/Menu/Matcher/MenuExpressionMatchers.h" +#include "Parsing/Menu/Matcher/MenuMatcherFactory.h" +#include "Parsing/Menu/MenuFileCommonOperations.h" using namespace menu; -namespace menu::menu_scope_sequences -{ - class SequenceCloseBlock final : public MenuFileParser::sequence_t - { - static constexpr auto CAPTURE_TOKEN = 1; - - public: - SequenceCloseBlock() - { - const MenuMatcherFactory create(this); - - AddMatchers({ - create.Char('}').Capture(CAPTURE_TOKEN) - }); - } - - protected: - void ProcessMatch(MenuFileParserState* state, SequenceResult<SimpleParserValue>& result) const override - { - if (state->m_current_menu->m_name.empty()) - throw ParsingException(result.NextCapture(CAPTURE_TOKEN).GetPos(), "Menu must have a name"); - - const auto existingMenu = state->m_menus_by_name.find(state->m_current_menu->m_name); - if (existingMenu == state->m_menus_by_name.end()) - { - state->m_menus_by_name.emplace(std::make_pair(state->m_current_menu->m_name, state->m_current_menu)); - state->m_current_menu = nullptr; - } - else - { - std::ostringstream ss; - ss << "Menu with name \"" << state->m_current_menu->m_name << "\" already exists"; - throw ParsingException(result.NextCapture(CAPTURE_TOKEN).GetPos(), ss.str()); - } - } - }; - - class SequenceConsumeSemicolons final : public MenuFileParser::sequence_t - { - public: - SequenceConsumeSemicolons() - { - const MenuMatcherFactory create(this); - - AddMatchers({ - create.Char(';') - }); - } - - protected: - void ProcessMatch(MenuFileParserState* state, SequenceResult<SimpleParserValue>& result) const override - { - } - }; - - class SequenceItemDef final : public MenuFileParser::sequence_t - { - static constexpr auto CAPTURE_TOKEN = 1; - - public: - SequenceItemDef() - { - const MenuMatcherFactory create(this); - - AddMatchers({ - create.Keyword("itemDef"), - create.Char('{') - }); - } - - protected: - void ProcessMatch(MenuFileParserState* state, SequenceResult<SimpleParserValue>& result) const override - { - auto newItemDef = std::make_unique<CommonItemDef>(); - state->m_current_item = newItemDef.get(); - state->m_current_menu->m_items.emplace_back(std::move(newItemDef)); - } - }; - - class SequenceRect final : public MenuFileParser::sequence_t - { - static constexpr auto CAPTURE_ALIGN_HORIZONTAL = 5; - static constexpr auto CAPTURE_ALIGN_VERTICAL = 6; - - public: - SequenceRect() - { - const MenuMatcherFactory create(this); - - AddLabeledMatchers(MenuExpressionMatchers().Expression(this), MenuExpressionMatchers::LABEL_EXPRESSION); - AddMatchers({ - create.KeywordIgnoreCase("rect"), - create.NumericExpression(), // x - create.NumericExpression(), // y - create.NumericExpression(), // w - create.NumericExpression(), // h - create.Optional(create.And({ - create.Integer().Capture(CAPTURE_ALIGN_HORIZONTAL), - create.Integer().Capture(CAPTURE_ALIGN_VERTICAL) - })) - }); - } - - protected: - void ProcessMatch(MenuFileParserState* state, SequenceResult<SimpleParserValue>& result) const override - { - assert(state->m_current_menu); - - const auto x = MenuMatcherFactory::TokenNumericExpressionValue(state, result); - const auto y = MenuMatcherFactory::TokenNumericExpressionValue(state, result); - const auto w = MenuMatcherFactory::TokenNumericExpressionValue(state, result); - const auto h = MenuMatcherFactory::TokenNumericExpressionValue(state, result); - CommonRect rect - { - x, - y, - w, - h, - 0, 0 - }; - - if (result.HasNextCapture(CAPTURE_ALIGN_HORIZONTAL) && result.HasNextCapture(CAPTURE_ALIGN_VERTICAL)) - { - rect.horizontalAlign = result.NextCapture(CAPTURE_ALIGN_HORIZONTAL).IntegerValue(); - rect.verticalAlign = result.NextCapture(CAPTURE_ALIGN_VERTICAL).IntegerValue(); - } - - state->m_current_menu->m_rect = rect; - } - }; - - class SequenceExecKey final : public MenuFileParser::sequence_t - { - static constexpr auto CAPTURE_KEY = 1; - - public: - SequenceExecKey() - { - const MenuMatcherFactory create(this); - - AddMatchers({ - create.KeywordIgnoreCase("execKey"), - create.StringChain().Capture(CAPTURE_KEY), - create.Char('{') - }); - } - - protected: - void ProcessMatch(MenuFileParserState* state, SequenceResult<SimpleParserValue>& result) const override - { - assert(state->m_current_menu); - - const auto& keyToken = result.NextCapture(CAPTURE_KEY); - const auto& keyValue = keyToken.StringValue(); - - if (keyValue.empty() || keyValue.size() > 1) - throw ParsingException(keyToken.GetPos(), "Key handler string must have exactly one character"); - - const auto key = static_cast<int>(static_cast<unsigned char>(keyValue[0])); - - auto newEventHandlerSet = std::make_unique<CommonEventHandlerSet>(); - state->m_current_event_handler_set = newEventHandlerSet.get(); - state->m_current_nested_event_handler_set = newEventHandlerSet.get(); - state->m_current_menu->m_key_handlers.emplace(std::make_pair(key, std::move(newEventHandlerSet))); - } - }; - - class SequenceExecKeyInt final : public MenuFileParser::sequence_t - { - static constexpr auto CAPTURE_KEY = 1; - - public: - SequenceExecKeyInt() - { - const MenuMatcherFactory create(this); - - AddMatchers({ - create.KeywordIgnoreCase("execKeyInt"), - create.Integer().Capture(CAPTURE_KEY), - create.Char('{') - }); - } - - protected: - void ProcessMatch(MenuFileParserState* state, SequenceResult<SimpleParserValue>& result) const override - { - assert(state->m_current_menu); - - const auto& keyToken = result.NextCapture(CAPTURE_KEY); - const auto& keyValue = keyToken.IntegerValue(); - - if (keyValue < 0) - throw ParsingException(keyToken.GetPos(), "Key handler value must be positive"); - - auto newEventHandlerSet = std::make_unique<CommonEventHandlerSet>(); - state->m_current_event_handler_set = newEventHandlerSet.get(); - state->m_current_nested_event_handler_set = newEventHandlerSet.get(); - state->m_current_menu->m_key_handlers.emplace(std::make_pair(keyValue, std::move(newEventHandlerSet))); - } - }; -} +namespace menu::menu_scope_sequences { +class SequenceCloseBlock final : public MenuFileParser::sequence_t { + static constexpr auto CAPTURE_TOKEN = 1; + +public: + SequenceCloseBlock() { + const MenuMatcherFactory create(this); + + AddMatchers({create.Char('}').Capture(CAPTURE_TOKEN)}); + } + +protected: + void ProcessMatch(MenuFileParserState *state, SequenceResult<SimpleParserValue> &result) const override { + if (state->m_current_menu->m_name.empty()) + throw ParsingException(result.NextCapture(CAPTURE_TOKEN).GetPos(), "Menu must have a name"); + + const auto existingMenu = state->m_menus_by_name.find(state->m_current_menu->m_name); + if (existingMenu == state->m_menus_by_name.end()) { + state->m_menus_by_name.emplace(std::make_pair(state->m_current_menu->m_name, state->m_current_menu)); + state->m_current_menu = nullptr; + } else { + std::ostringstream ss; + ss << "Menu with name \"" << state->m_current_menu->m_name << "\" already exists"; + throw ParsingException(result.NextCapture(CAPTURE_TOKEN).GetPos(), ss.str()); + } + } +}; + +class SequenceConsumeSemicolons final : public MenuFileParser::sequence_t { +public: + SequenceConsumeSemicolons() { + const MenuMatcherFactory create(this); + + AddMatchers({create.Char(';')}); + } + +protected: + void ProcessMatch(MenuFileParserState *state, SequenceResult<SimpleParserValue> &result) const override {} +}; + +class SequenceItemDef final : public MenuFileParser::sequence_t { + static constexpr auto CAPTURE_TOKEN = 1; + +public: + SequenceItemDef() { + const MenuMatcherFactory create(this); + + AddMatchers({create.Keyword("itemDef"), create.Char('{')}); + } + +protected: + void ProcessMatch(MenuFileParserState *state, SequenceResult<SimpleParserValue> &result) const override { + auto newItemDef = std::make_unique<CommonItemDef>(); + state->m_current_item = newItemDef.get(); + state->m_current_menu->m_items.emplace_back(std::move(newItemDef)); + } +}; + +class SequenceRect final : public MenuFileParser::sequence_t { + static constexpr auto CAPTURE_ALIGN_HORIZONTAL = 5; + static constexpr auto CAPTURE_ALIGN_VERTICAL = 6; + +public: + SequenceRect() { + const MenuMatcherFactory create(this); + + AddLabeledMatchers(MenuExpressionMatchers().Expression(this), MenuExpressionMatchers::LABEL_EXPRESSION); + AddMatchers({create.KeywordIgnoreCase("rect"), + create.NumericExpression(), // x + create.NumericExpression(), // y + create.NumericExpression(), // w + create.NumericExpression(), // h + create.Optional(create.And({create.Integer().Capture(CAPTURE_ALIGN_HORIZONTAL), create.Integer().Capture(CAPTURE_ALIGN_VERTICAL)}))}); + } + +protected: + void ProcessMatch(MenuFileParserState *state, SequenceResult<SimpleParserValue> &result) const override { + assert(state->m_current_menu); + + const auto x = MenuMatcherFactory::TokenNumericExpressionValue(state, result); + const auto y = MenuMatcherFactory::TokenNumericExpressionValue(state, result); + const auto w = MenuMatcherFactory::TokenNumericExpressionValue(state, result); + const auto h = MenuMatcherFactory::TokenNumericExpressionValue(state, result); + CommonRect rect{x, y, w, h, 0, 0}; + + if (result.HasNextCapture(CAPTURE_ALIGN_HORIZONTAL) && result.HasNextCapture(CAPTURE_ALIGN_VERTICAL)) { + rect.horizontalAlign = result.NextCapture(CAPTURE_ALIGN_HORIZONTAL).IntegerValue(); + rect.verticalAlign = result.NextCapture(CAPTURE_ALIGN_VERTICAL).IntegerValue(); + } -using namespace menu_scope_sequences; + state->m_current_menu->m_rect = rect; + } +}; -MenuScopeSequences::MenuScopeSequences(std::vector<std::unique_ptr<MenuFileParser::sequence_t>>& allSequences, std::vector<MenuFileParser::sequence_t*>& scopeSequences) - : AbstractScopeSequenceHolder(allSequences, scopeSequences) -{ -} +class SequenceExecKey final : public MenuFileParser::sequence_t { + static constexpr auto CAPTURE_KEY = 1; + +public: + SequenceExecKey() { + const MenuMatcherFactory create(this); + + AddMatchers({create.KeywordIgnoreCase("execKey"), create.StringChain().Capture(CAPTURE_KEY), create.Char('{')}); + } + +protected: + void ProcessMatch(MenuFileParserState *state, SequenceResult<SimpleParserValue> &result) const override { + assert(state->m_current_menu); + + const auto &keyToken = result.NextCapture(CAPTURE_KEY); + const auto &keyValue = keyToken.StringValue(); + + if (keyValue.empty() || keyValue.size() > 1) + throw ParsingException(keyToken.GetPos(), "Key handler string must have exactly one character"); -void MenuScopeSequences::AddSequences(FeatureLevel featureLevel, bool permissive) const -{ - AddSequence(std::make_unique<SequenceCloseBlock>()); - AddSequence(std::make_unique<SequenceItemDef>()); - AddSequence(std::make_unique<GenericStringPropertySequence>("name", [](const MenuFileParserState* state, const TokenPos&, const std::string& value) - { - state->m_current_menu->m_name = value; - })); - AddSequence(std::make_unique<GenericBoolPropertySequence>("fullScreen", [](const MenuFileParserState* state, const TokenPos&, const bool value) - { - state->m_current_menu->m_full_screen = value; - })); - AddSequence(std::make_unique<GenericKeywordPropertySequence>("screenSpace", [](const MenuFileParserState* state, const TokenPos&) - { - state->m_current_menu->m_screen_space = true; - })); - AddSequence(std::make_unique<GenericKeywordPropertySequence>("decoration", [](const MenuFileParserState* state, const TokenPos&) - { - state->m_current_menu->m_decoration = true; - })); - AddSequence(std::make_unique<SequenceRect>()); - // rect480 - // rect720 - // pos480 - // pos720 - AddSequence(std::make_unique<GenericIntPropertySequence>("style", [](const MenuFileParserState* state, const TokenPos&, const int value) - { - state->m_current_menu->m_style = value; - })); - AddSequence(GenericExpressionPropertySequence::WithKeywordAndBool("visible", [](const MenuFileParserState* state, const TokenPos& pos, std::unique_ptr<ISimpleExpression> value) - { + const auto key = static_cast<int>(static_cast<unsigned char>(keyValue[0])); + + auto newEventHandlerSet = std::make_unique<CommonEventHandlerSet>(); + state->m_current_event_handler_set = newEventHandlerSet.get(); + state->m_current_nested_event_handler_set = newEventHandlerSet.get(); + state->m_current_menu->m_key_handlers.emplace(std::make_pair(key, std::move(newEventHandlerSet))); + } +}; + +class SequenceExecKeyInt final : public MenuFileParser::sequence_t { + static constexpr auto CAPTURE_KEY = 1; + +public: + SequenceExecKeyInt() { + const MenuMatcherFactory create(this); + + AddMatchers({create.KeywordIgnoreCase("execKeyInt"), create.Integer().Capture(CAPTURE_KEY), create.Char('{')}); + } + +protected: + void ProcessMatch(MenuFileParserState *state, SequenceResult<SimpleParserValue> &result) const override { + assert(state->m_current_menu); + + const auto &keyToken = result.NextCapture(CAPTURE_KEY); + const auto &keyValue = keyToken.IntegerValue(); + + if (keyValue < 0) + throw ParsingException(keyToken.GetPos(), "Key handler value must be positive"); + + auto newEventHandlerSet = std::make_unique<CommonEventHandlerSet>(); + state->m_current_event_handler_set = newEventHandlerSet.get(); + state->m_current_nested_event_handler_set = newEventHandlerSet.get(); + state->m_current_menu->m_key_handlers.emplace(std::make_pair(keyValue, std::move(newEventHandlerSet))); + } +}; +} // namespace menu::menu_scope_sequences + +using namespace menu_scope_sequences; + +MenuScopeSequences::MenuScopeSequences(std::vector<std::unique_ptr<MenuFileParser::sequence_t>> &allSequences, + std::vector<MenuFileParser::sequence_t *> &scopeSequences) + : AbstractScopeSequenceHolder(allSequences, scopeSequences) {} + +void MenuScopeSequences::AddSequences(FeatureLevel featureLevel, bool permissive) const { + AddSequence(std::make_unique<SequenceCloseBlock>()); + AddSequence(std::make_unique<SequenceItemDef>()); + AddSequence(std::make_unique<GenericStringPropertySequence>( + "name", [](const MenuFileParserState *state, const TokenPos &, const std::string &value) { state->m_current_menu->m_name = value; })); + AddSequence(std::make_unique<GenericBoolPropertySequence>( + "fullScreen", [](const MenuFileParserState *state, const TokenPos &, const bool value) { state->m_current_menu->m_full_screen = value; })); + AddSequence(std::make_unique<GenericKeywordPropertySequence>( + "screenSpace", [](const MenuFileParserState *state, const TokenPos &) { state->m_current_menu->m_screen_space = true; })); + AddSequence(std::make_unique<GenericKeywordPropertySequence>( + "decoration", [](const MenuFileParserState *state, const TokenPos &) { state->m_current_menu->m_decoration = true; })); + AddSequence(std::make_unique<SequenceRect>()); + // rect480 + // rect720 + // pos480 + // pos720 + AddSequence(std::make_unique<GenericIntPropertySequence>( + "style", [](const MenuFileParserState *state, const TokenPos &, const int value) { state->m_current_menu->m_style = value; })); + AddSequence(GenericExpressionPropertySequence::WithKeywordAndBool( + "visible", [](const MenuFileParserState *state, const TokenPos &pos, std::unique_ptr<ISimpleExpression> value) { MenuFileCommonOperations::EnsureIsNumericExpression(state, pos, *value); state->m_current_menu->m_visible_expression = std::move(value); - })); - AddSequence(std::make_unique<GenericMenuEventHandlerSetPropertySequence>("onOpen", [](const MenuFileParserState* state, const TokenPos&) -> std::unique_ptr<CommonEventHandlerSet>& { - return state->m_current_menu->m_on_open; - })); - AddSequence(std::make_unique<GenericMenuEventHandlerSetPropertySequence>("onClose", [](const MenuFileParserState* state, const TokenPos&) -> std::unique_ptr<CommonEventHandlerSet>& { - return state->m_current_menu->m_on_close; - })); - AddSequence(std::make_unique<GenericMenuEventHandlerSetPropertySequence>("onRequestClose", [](const MenuFileParserState* state, const TokenPos&) -> std::unique_ptr<CommonEventHandlerSet>& { + })); + AddSequence(std::make_unique<GenericMenuEventHandlerSetPropertySequence>( + "onOpen", + [](const MenuFileParserState *state, const TokenPos &) -> std::unique_ptr<CommonEventHandlerSet> & { return state->m_current_menu->m_on_open; })); + AddSequence(std::make_unique<GenericMenuEventHandlerSetPropertySequence>( + "onClose", + [](const MenuFileParserState *state, const TokenPos &) -> std::unique_ptr<CommonEventHandlerSet> & { return state->m_current_menu->m_on_close; })); + AddSequence(std::make_unique<GenericMenuEventHandlerSetPropertySequence>( + "onRequestClose", [](const MenuFileParserState *state, const TokenPos &) -> std::unique_ptr<CommonEventHandlerSet> & { return state->m_current_menu->m_on_request_close; - })); - AddSequence(std::make_unique<GenericMenuEventHandlerSetPropertySequence>("onESC", [](const MenuFileParserState* state, const TokenPos&) -> std::unique_ptr<CommonEventHandlerSet>& { - return state->m_current_menu->m_on_esc; - })); - AddSequence(std::make_unique<GenericIntPropertySequence>("border", [](const MenuFileParserState* state, const TokenPos&, const int value) - { - state->m_current_menu->m_border = value; - })); - AddSequence(std::make_unique<GenericFloatingPointPropertySequence>("borderSize", [](const MenuFileParserState* state, const TokenPos&, const double value) - { - state->m_current_menu->m_border_size = value; - })); - AddSequence(std::make_unique<GenericColorPropertySequence>("backcolor", [](const MenuFileParserState* state, const TokenPos&, const CommonColor value) - { - state->m_current_menu->m_back_color = value; - })); - AddSequence(std::make_unique<GenericColorPropertySequence>("forecolor", [](const MenuFileParserState* state, const TokenPos&, const CommonColor value) - { - state->m_current_menu->m_fore_color = value; - })); - AddSequence(std::make_unique<GenericColorPropertySequence>("bordercolor", [](const MenuFileParserState* state, const TokenPos&, const CommonColor value) - { - state->m_current_menu->m_border_color = value; - })); - AddSequence(std::make_unique<GenericColorPropertySequence>("focuscolor", [](const MenuFileParserState* state, const TokenPos&, const CommonColor value) - { - state->m_current_menu->m_focus_color = value; - })); - AddSequence(std::make_unique<GenericColorPropertySequence>("outlinecolor", [](const MenuFileParserState* state, const TokenPos&, const CommonColor value) - { - state->m_current_menu->m_outline_color = value; - })); - AddSequence(std::make_unique<GenericStringPropertySequence>("background", [](const MenuFileParserState* state, const TokenPos&, const std::string& value) - { - state->m_current_menu->m_background = value; - })); - AddSequence(std::make_unique<GenericIntPropertySequence>("ownerdraw", [](const MenuFileParserState* state, const TokenPos&, const int value) - { - state->m_current_menu->m_owner_draw = value; - })); - AddSequence(std::make_unique<GenericIntPropertySequence>("ownerdrawFlag", [](const MenuFileParserState* state, const TokenPos&, const int value) - { - state->m_current_menu->m_owner_draw_flags |= value; - })); - AddSequence(std::make_unique<GenericKeywordPropertySequence>("outOfBoundsClick", [](const MenuFileParserState* state, const TokenPos&) - { - state->m_current_menu->m_out_of_bounds_click = true; - })); - AddSequence(std::make_unique<GenericStringPropertySequence>("soundLoop", [](const MenuFileParserState* state, const TokenPos&, const std::string& value) - { - state->m_current_menu->m_sound_loop = value; - })); - AddSequence(GenericExpressionPropertySequence::WithKeywords({"exp", "rect", "X"}, [](const MenuFileParserState* state, const TokenPos& pos, std::unique_ptr<ISimpleExpression> value) - { + })); + AddSequence(std::make_unique<GenericMenuEventHandlerSetPropertySequence>( + "onESC", [](const MenuFileParserState *state, const TokenPos &) -> std::unique_ptr<CommonEventHandlerSet> & { return state->m_current_menu->m_on_esc; })); + AddSequence(std::make_unique<GenericIntPropertySequence>( + "border", [](const MenuFileParserState *state, const TokenPos &, const int value) { state->m_current_menu->m_border = value; })); + AddSequence(std::make_unique<GenericFloatingPointPropertySequence>( + "borderSize", [](const MenuFileParserState *state, const TokenPos &, const double value) { state->m_current_menu->m_border_size = value; })); + AddSequence(std::make_unique<GenericColorPropertySequence>( + "backcolor", [](const MenuFileParserState *state, const TokenPos &, const CommonColor value) { state->m_current_menu->m_back_color = value; })); + AddSequence(std::make_unique<GenericColorPropertySequence>( + "forecolor", [](const MenuFileParserState *state, const TokenPos &, const CommonColor value) { state->m_current_menu->m_fore_color = value; })); + AddSequence(std::make_unique<GenericColorPropertySequence>( + "bordercolor", [](const MenuFileParserState *state, const TokenPos &, const CommonColor value) { state->m_current_menu->m_border_color = value; })); + AddSequence(std::make_unique<GenericColorPropertySequence>( + "focuscolor", [](const MenuFileParserState *state, const TokenPos &, const CommonColor value) { state->m_current_menu->m_focus_color = value; })); + AddSequence(std::make_unique<GenericColorPropertySequence>( + "outlinecolor", [](const MenuFileParserState *state, const TokenPos &, const CommonColor value) { state->m_current_menu->m_outline_color = value; })); + AddSequence(std::make_unique<GenericStringPropertySequence>( + "background", [](const MenuFileParserState *state, const TokenPos &, const std::string &value) { state->m_current_menu->m_background = value; })); + AddSequence(std::make_unique<GenericIntPropertySequence>( + "ownerdraw", [](const MenuFileParserState *state, const TokenPos &, const int value) { state->m_current_menu->m_owner_draw = value; })); + AddSequence(std::make_unique<GenericIntPropertySequence>( + "ownerdrawFlag", [](const MenuFileParserState *state, const TokenPos &, const int value) { state->m_current_menu->m_owner_draw_flags |= value; })); + AddSequence(std::make_unique<GenericKeywordPropertySequence>( + "outOfBoundsClick", [](const MenuFileParserState *state, const TokenPos &) { state->m_current_menu->m_out_of_bounds_click = true; })); + AddSequence(std::make_unique<GenericStringPropertySequence>( + "soundLoop", [](const MenuFileParserState *state, const TokenPos &, const std::string &value) { state->m_current_menu->m_sound_loop = value; })); + AddSequence(GenericExpressionPropertySequence::WithKeywords( + {"exp", "rect", "X"}, [](const MenuFileParserState *state, const TokenPos &pos, std::unique_ptr<ISimpleExpression> value) { MenuFileCommonOperations::EnsureIsNumericExpression(state, pos, *value); state->m_current_menu->m_rect_x_exp = std::move(value); - })); - AddSequence(GenericExpressionPropertySequence::WithKeywords({"exp", "rect", "Y"}, [](const MenuFileParserState* state, const TokenPos& pos, std::unique_ptr<ISimpleExpression> value) - { + })); + AddSequence(GenericExpressionPropertySequence::WithKeywords( + {"exp", "rect", "Y"}, [](const MenuFileParserState *state, const TokenPos &pos, std::unique_ptr<ISimpleExpression> value) { MenuFileCommonOperations::EnsureIsNumericExpression(state, pos, *value); state->m_current_menu->m_rect_y_exp = std::move(value); - })); - AddSequence(GenericExpressionPropertySequence::WithKeywords({"exp", "rect", "W"}, [](const MenuFileParserState* state, const TokenPos& pos, std::unique_ptr<ISimpleExpression> value) - { + })); + AddSequence(GenericExpressionPropertySequence::WithKeywords( + {"exp", "rect", "W"}, [](const MenuFileParserState *state, const TokenPos &pos, std::unique_ptr<ISimpleExpression> value) { MenuFileCommonOperations::EnsureIsNumericExpression(state, pos, *value); state->m_current_menu->m_rect_w_exp = std::move(value); - })); - AddSequence(GenericExpressionPropertySequence::WithKeywords({"exp", "rect", "H"}, [](const MenuFileParserState* state, const TokenPos& pos, std::unique_ptr<ISimpleExpression> value) - { + })); + AddSequence(GenericExpressionPropertySequence::WithKeywords( + {"exp", "rect", "H"}, [](const MenuFileParserState *state, const TokenPos &pos, std::unique_ptr<ISimpleExpression> value) { MenuFileCommonOperations::EnsureIsNumericExpression(state, pos, *value); state->m_current_menu->m_rect_h_exp = std::move(value); - })); - AddSequence(GenericExpressionPropertySequence::WithKeywords({"exp", "openSound"}, [](const MenuFileParserState* state, const TokenPos& pos, std::unique_ptr<ISimpleExpression> value) - { + })); + AddSequence(GenericExpressionPropertySequence::WithKeywords( + {"exp", "openSound"}, [](const MenuFileParserState *state, const TokenPos &pos, std::unique_ptr<ISimpleExpression> value) { MenuFileCommonOperations::EnsureIsStringExpression(state, pos, *value); state->m_current_menu->m_open_sound_exp = std::move(value); - })); - AddSequence(GenericExpressionPropertySequence::WithKeywords({"exp", "closeSound"}, [](const MenuFileParserState* state, const TokenPos& pos, std::unique_ptr<ISimpleExpression> value) - { + })); + AddSequence(GenericExpressionPropertySequence::WithKeywords( + {"exp", "closeSound"}, [](const MenuFileParserState *state, const TokenPos &pos, std::unique_ptr<ISimpleExpression> value) { MenuFileCommonOperations::EnsureIsStringExpression(state, pos, *value); state->m_current_menu->m_close_sound_exp = std::move(value); - })); - AddSequence(std::make_unique<GenericKeywordPropertySequence>("popup", [](const MenuFileParserState* state, const TokenPos&) - { - state->m_current_menu->m_popup = true; - })); - AddSequence(std::make_unique<GenericFloatingPointPropertySequence>("fadeClamp", [](const MenuFileParserState* state, const TokenPos&, const double value) - { - state->m_current_menu->m_fade_clamp = value; - })); - AddSequence(std::make_unique<GenericIntPropertySequence>("fadeCycle", [](const MenuFileParserState* state, const TokenPos&, const int value) - { - state->m_current_menu->m_fade_cycle = value; - })); - AddSequence(std::make_unique<GenericFloatingPointPropertySequence>("fadeAmount", [](const MenuFileParserState* state, const TokenPos&, const double value) - { - state->m_current_menu->m_fade_amount = value; - })); - AddSequence(std::make_unique<GenericFloatingPointPropertySequence>("fadeInAmount", [](const MenuFileParserState* state, const TokenPos&, const double value) - { - state->m_current_menu->m_fade_in_amount = value; - })); - AddSequence(std::make_unique<SequenceExecKey>()); - AddSequence(std::make_unique<SequenceExecKeyInt>()); - AddSequence(std::make_unique<GenericFloatingPointPropertySequence>("blurWorld", [](const MenuFileParserState* state, const TokenPos&, const double value) - { - state->m_current_menu->m_blur_radius = value; - })); - AddSequence(std::make_unique<GenericKeywordPropertySequence>("legacySplitScreenScale", [](const MenuFileParserState* state, const TokenPos&) - { - state->m_current_menu->m_legacy_split_screen_scale = true; - })); - AddSequence(std::make_unique<GenericKeywordPropertySequence>("hiddenDuringScope", [](const MenuFileParserState* state, const TokenPos&) - { - state->m_current_menu->m_hidden_during_scope = true; - })); - AddSequence(std::make_unique<GenericKeywordPropertySequence>("hiddenDuringFlashbang", [](const MenuFileParserState* state, const TokenPos&) - { - state->m_current_menu->m_hidden_during_flashbang = true; - })); - AddSequence(std::make_unique<GenericKeywordPropertySequence>("hiddenDuringUI", [](const MenuFileParserState* state, const TokenPos&) - { - state->m_current_menu->m_hidden_during_ui = true; - })); - AddSequence(std::make_unique<GenericStringPropertySequence>("allowedBinding", [](const MenuFileParserState* state, const TokenPos&, const std::string& value) - { + })); + AddSequence(std::make_unique<GenericKeywordPropertySequence>( + "popup", [](const MenuFileParserState *state, const TokenPos &) { state->m_current_menu->m_popup = true; })); + AddSequence(std::make_unique<GenericFloatingPointPropertySequence>( + "fadeClamp", [](const MenuFileParserState *state, const TokenPos &, const double value) { state->m_current_menu->m_fade_clamp = value; })); + AddSequence(std::make_unique<GenericIntPropertySequence>( + "fadeCycle", [](const MenuFileParserState *state, const TokenPos &, const int value) { state->m_current_menu->m_fade_cycle = value; })); + AddSequence(std::make_unique<GenericFloatingPointPropertySequence>( + "fadeAmount", [](const MenuFileParserState *state, const TokenPos &, const double value) { state->m_current_menu->m_fade_amount = value; })); + AddSequence(std::make_unique<GenericFloatingPointPropertySequence>( + "fadeInAmount", [](const MenuFileParserState *state, const TokenPos &, const double value) { state->m_current_menu->m_fade_in_amount = value; })); + AddSequence(std::make_unique<SequenceExecKey>()); + AddSequence(std::make_unique<SequenceExecKeyInt>()); + AddSequence(std::make_unique<GenericFloatingPointPropertySequence>( + "blurWorld", [](const MenuFileParserState *state, const TokenPos &, const double value) { state->m_current_menu->m_blur_radius = value; })); + AddSequence(std::make_unique<GenericKeywordPropertySequence>( + "legacySplitScreenScale", [](const MenuFileParserState *state, const TokenPos &) { state->m_current_menu->m_legacy_split_screen_scale = true; })); + AddSequence(std::make_unique<GenericKeywordPropertySequence>( + "hiddenDuringScope", [](const MenuFileParserState *state, const TokenPos &) { state->m_current_menu->m_hidden_during_scope = true; })); + AddSequence(std::make_unique<GenericKeywordPropertySequence>( + "hiddenDuringFlashbang", [](const MenuFileParserState *state, const TokenPos &) { state->m_current_menu->m_hidden_during_flashbang = true; })); + AddSequence(std::make_unique<GenericKeywordPropertySequence>( + "hiddenDuringUI", [](const MenuFileParserState *state, const TokenPos &) { state->m_current_menu->m_hidden_during_ui = true; })); + AddSequence( + std::make_unique<GenericStringPropertySequence>("allowedBinding", [](const MenuFileParserState *state, const TokenPos &, const std::string &value) { state->m_current_menu->m_allowed_binding = value; - })); - AddSequence(std::make_unique<GenericKeywordPropertySequence>("textOnlyFocus", [](const MenuFileParserState* state, const TokenPos&) - { - state->m_current_menu->m_text_only_focus = true; - })); - - - if (featureLevel == FeatureLevel::IW5) - { - AddSequence(GenericExpressionPropertySequence::WithKeywords({"exp", "soundLoop"}, [](const MenuFileParserState* state, const TokenPos& pos, std::unique_ptr<ISimpleExpression> value) - { - MenuFileCommonOperations::EnsureIsStringExpression(state, pos, *value); - state->m_current_menu->m_sound_loop_exp = std::move(value); + })); + AddSequence(std::make_unique<GenericKeywordPropertySequence>( + "textOnlyFocus", [](const MenuFileParserState *state, const TokenPos &) { state->m_current_menu->m_text_only_focus = true; })); + + if (featureLevel == FeatureLevel::IW5) { + AddSequence(GenericExpressionPropertySequence::WithKeywords( + {"exp", "soundLoop"}, [](const MenuFileParserState *state, const TokenPos &pos, std::unique_ptr<ISimpleExpression> value) { + MenuFileCommonOperations::EnsureIsStringExpression(state, pos, *value); + state->m_current_menu->m_sound_loop_exp = std::move(value); })); - AddSequence(std::make_unique<GenericMenuEventHandlerSetPropertySequence>("onFocusDueToClose", [](const MenuFileParserState* state, const TokenPos&) -> std::unique_ptr<CommonEventHandlerSet>& { - return state->m_current_menu->m_on_focus_due_to_close; + AddSequence(std::make_unique<GenericMenuEventHandlerSetPropertySequence>( + "onFocusDueToClose", [](const MenuFileParserState *state, const TokenPos &) -> std::unique_ptr<CommonEventHandlerSet> & { + return state->m_current_menu->m_on_focus_due_to_close; })); - } - + } - AddSequence(std::make_unique<SequenceConsumeSemicolons>()); + AddSequence(std::make_unique<SequenceConsumeSemicolons>()); } diff --git a/src/ObjLoading/Parsing/Menu/Sequence/MenuScopeSequences.h b/src/ObjLoading/Parsing/Menu/Sequence/MenuScopeSequences.h index fcf7596ab..5e6db9b90 100644 --- a/src/ObjLoading/Parsing/Menu/Sequence/MenuScopeSequences.h +++ b/src/ObjLoading/Parsing/Menu/Sequence/MenuScopeSequences.h @@ -3,13 +3,11 @@ #include "Parsing/Menu/MenuFileParser.h" #include "Parsing/Sequence/AbstractScopeSequenceHolder.h" -namespace menu -{ - class MenuScopeSequences final : AbstractScopeSequenceHolder<MenuFileParser> - { - public: - MenuScopeSequences(std::vector<std::unique_ptr<MenuFileParser::sequence_t>>& allSequences, std::vector<MenuFileParser::sequence_t*>& scopeSequences); +namespace menu { +class MenuScopeSequences final : AbstractScopeSequenceHolder<MenuFileParser> { +public: + MenuScopeSequences(std::vector<std::unique_ptr<MenuFileParser::sequence_t>> &allSequences, std::vector<MenuFileParser::sequence_t *> &scopeSequences); - void AddSequences(FeatureLevel featureLevel, bool permissive) const; - }; -} + void AddSequences(FeatureLevel featureLevel, bool permissive) const; +}; +} // namespace menu diff --git a/src/ObjLoading/Parsing/Menu/Sequence/NoScopeSequences.cpp b/src/ObjLoading/Parsing/Menu/Sequence/NoScopeSequences.cpp index 7c6135be0..c5446179e 100644 --- a/src/ObjLoading/Parsing/Menu/Sequence/NoScopeSequences.cpp +++ b/src/ObjLoading/Parsing/Menu/Sequence/NoScopeSequences.cpp @@ -5,36 +5,24 @@ using namespace menu; -namespace menu::no_scope_sequences -{ - class SequenceOpenGlobalScope final : public MenuFileParser::sequence_t - { - public: - SequenceOpenGlobalScope() - { - const MenuMatcherFactory create(this); - - AddMatchers({ - create.Char('{') - }); - } - - protected: - void ProcessMatch(MenuFileParserState* state, SequenceResult<SimpleParserValue>& result) const override - { - state->m_in_global_scope = true; - } - }; -} +namespace menu::no_scope_sequences { +class SequenceOpenGlobalScope final : public MenuFileParser::sequence_t { +public: + SequenceOpenGlobalScope() { + const MenuMatcherFactory create(this); + + AddMatchers({create.Char('{')}); + } + +protected: + void ProcessMatch(MenuFileParserState *state, SequenceResult<SimpleParserValue> &result) const override { state->m_in_global_scope = true; } +}; +} // namespace menu::no_scope_sequences using namespace no_scope_sequences; -NoScopeSequences::NoScopeSequences(std::vector<std::unique_ptr<MenuFileParser::sequence_t>>& allSequences, std::vector<MenuFileParser::sequence_t*>& scopeSequences) - : AbstractScopeSequenceHolder(allSequences, scopeSequences) -{ -} +NoScopeSequences::NoScopeSequences(std::vector<std::unique_ptr<MenuFileParser::sequence_t>> &allSequences, + std::vector<MenuFileParser::sequence_t *> &scopeSequences) + : AbstractScopeSequenceHolder(allSequences, scopeSequences) {} -void NoScopeSequences::AddSequences(FeatureLevel featureLevel, bool permissive) const -{ - AddSequence(std::make_unique<SequenceOpenGlobalScope>()); -} +void NoScopeSequences::AddSequences(FeatureLevel featureLevel, bool permissive) const { AddSequence(std::make_unique<SequenceOpenGlobalScope>()); } diff --git a/src/ObjLoading/Parsing/Menu/Sequence/NoScopeSequences.h b/src/ObjLoading/Parsing/Menu/Sequence/NoScopeSequences.h index b14a4ca78..30da5f844 100644 --- a/src/ObjLoading/Parsing/Menu/Sequence/NoScopeSequences.h +++ b/src/ObjLoading/Parsing/Menu/Sequence/NoScopeSequences.h @@ -3,13 +3,11 @@ #include "Parsing/Menu/MenuFileParser.h" #include "Parsing/Sequence/AbstractScopeSequenceHolder.h" -namespace menu -{ - class NoScopeSequences final : AbstractScopeSequenceHolder<MenuFileParser> - { - public: - NoScopeSequences(std::vector<std::unique_ptr<MenuFileParser::sequence_t>>& allSequences, std::vector<MenuFileParser::sequence_t*>& scopeSequences); +namespace menu { +class NoScopeSequences final : AbstractScopeSequenceHolder<MenuFileParser> { +public: + NoScopeSequences(std::vector<std::unique_ptr<MenuFileParser::sequence_t>> &allSequences, std::vector<MenuFileParser::sequence_t *> &scopeSequences); - void AddSequences(FeatureLevel featureLevel, bool permissive) const; - }; -} + void AddSequences(FeatureLevel featureLevel, bool permissive) const; +}; +} // namespace menu diff --git a/src/ObjLoading/SearchPath/ISearchPath.cpp b/src/ObjLoading/SearchPath/ISearchPath.cpp index 425201d4f..5585f95dc 100644 --- a/src/ObjLoading/SearchPath/ISearchPath.cpp +++ b/src/ObjLoading/SearchPath/ISearchPath.cpp @@ -1,17 +1,7 @@ #include "ISearchPath.h" -bool SearchPathOpenFile::IsOpen() const -{ - return m_stream != nullptr; -} +bool SearchPathOpenFile::IsOpen() const { return m_stream != nullptr; } -SearchPathOpenFile::SearchPathOpenFile() - : m_length(0) -{ -} +SearchPathOpenFile::SearchPathOpenFile() : m_length(0) {} -SearchPathOpenFile::SearchPathOpenFile(std::unique_ptr<std::istream> stream, const int64_t length) - : m_stream(std::move(stream)), - m_length(length) -{ -} +SearchPathOpenFile::SearchPathOpenFile(std::unique_ptr<std::istream> stream, const int64_t length) : m_stream(std::move(stream)), m_length(length) {} diff --git a/src/ObjLoading/SearchPath/ISearchPath.h b/src/ObjLoading/SearchPath/ISearchPath.h index bc07cfc6c..9b2f0e634 100644 --- a/src/ObjLoading/SearchPath/ISearchPath.h +++ b/src/ObjLoading/SearchPath/ISearchPath.h @@ -1,62 +1,57 @@ #pragma once +#include <cstdint> #include <functional> #include <istream> #include <memory> -#include <cstdint> -#include "Utils/ClassUtils.h" #include "SearchPathSearchOptions.h" +#include "Utils/ClassUtils.h" -class SearchPathOpenFile -{ +class SearchPathOpenFile { public: - std::unique_ptr<std::istream> m_stream; - int64_t m_length; + std::unique_ptr<std::istream> m_stream; + int64_t m_length; - _NODISCARD bool IsOpen() const; + _NODISCARD bool IsOpen() const; - SearchPathOpenFile(); - SearchPathOpenFile(std::unique_ptr<std::istream> stream, int64_t length); + SearchPathOpenFile(); + SearchPathOpenFile(std::unique_ptr<std::istream> stream, int64_t length); }; -class ISearchPath -{ +class ISearchPath { public: - ISearchPath() = default; - virtual ~ISearchPath() = default; - - ISearchPath(const ISearchPath& other) = default; - ISearchPath(ISearchPath&& other) noexcept = default; - ISearchPath& operator=(const ISearchPath& other) = default; - ISearchPath& operator=(ISearchPath&& other) noexcept = default; - - /** - * \brief Opens a file relative to the search path. - * \param fileName The relative path to the file to open. - * \return A pointer to an \c IFile object to read the found file or \c nullptr when no file could be found. - */ - virtual SearchPathOpenFile Open(const std::string& fileName) = 0; - - /** - * \brief Returns the path to the search path. - * \return The path to the search path. - */ - virtual std::string GetPath() = 0; - - /** - * \brief Iterates through all files of the search path. - * \param callback The callback to call for each found file with it's path relative to the search path. - * \param options Options that modify the search. - */ - virtual void Find(const SearchPathSearchOptions& options, const std::function<void(const std::string&)>& callback) = 0; - - /** - * \brief Iterates through all files of the search path. - * \param callback The callback to call for each found file with it's path relative to the search path. - */ - void Find(const std::function<void(const std::string&)>& callback) - { - Find(SearchPathSearchOptions(), callback); - } + ISearchPath() = default; + virtual ~ISearchPath() = default; + + ISearchPath(const ISearchPath &other) = default; + ISearchPath(ISearchPath &&other) noexcept = default; + ISearchPath &operator=(const ISearchPath &other) = default; + ISearchPath &operator=(ISearchPath &&other) noexcept = default; + + /** + * \brief Opens a file relative to the search path. + * \param fileName The relative path to the file to open. + * \return A pointer to an \c IFile object to read the found file or \c nullptr when no file could be found. + */ + virtual SearchPathOpenFile Open(const std::string &fileName) = 0; + + /** + * \brief Returns the path to the search path. + * \return The path to the search path. + */ + virtual std::string GetPath() = 0; + + /** + * \brief Iterates through all files of the search path. + * \param callback The callback to call for each found file with it's path relative to the search path. + * \param options Options that modify the search. + */ + virtual void Find(const SearchPathSearchOptions &options, const std::function<void(const std::string &)> &callback) = 0; + + /** + * \brief Iterates through all files of the search path. + * \param callback The callback to call for each found file with it's path relative to the search path. + */ + void Find(const std::function<void(const std::string &)> &callback) { Find(SearchPathSearchOptions(), callback); } }; diff --git a/src/ObjLoading/SearchPath/SearchPathFilesystem.cpp b/src/ObjLoading/SearchPath/SearchPathFilesystem.cpp index 3f5873377..3eeb5fb3c 100644 --- a/src/ObjLoading/SearchPath/SearchPathFilesystem.cpp +++ b/src/ObjLoading/SearchPath/SearchPathFilesystem.cpp @@ -7,58 +7,41 @@ namespace fs = std::filesystem; -SearchPathFilesystem::SearchPathFilesystem(std::string path) -{ - m_path = std::move(path); -} +SearchPathFilesystem::SearchPathFilesystem(std::string path) { m_path = std::move(path); } -std::string SearchPathFilesystem::GetPath() -{ - return m_path; -} +std::string SearchPathFilesystem::GetPath() { return m_path; } -SearchPathOpenFile SearchPathFilesystem::Open(const std::string& fileName) -{ - const auto filePath = fs::path(m_path).append(fileName); - std::ifstream file(filePath.string(), std::fstream::in | std::fstream::binary); +SearchPathOpenFile SearchPathFilesystem::Open(const std::string &fileName) { + const auto filePath = fs::path(m_path).append(fileName); + std::ifstream file(filePath.string(), std::fstream::in | std::fstream::binary); - if (file.is_open()) - { - return SearchPathOpenFile(std::make_unique<std::ifstream>(std::move(file)), static_cast<int64_t>(file_size(filePath))); - } + if (file.is_open()) { + return SearchPathOpenFile(std::make_unique<std::ifstream>(std::move(file)), static_cast<int64_t>(file_size(filePath))); + } - return SearchPathOpenFile(); + return SearchPathOpenFile(); } -void SearchPathFilesystem::Find(const SearchPathSearchOptions& options, const std::function<void(const std::string&)>& callback) -{ - try - { - if (options.m_should_include_subdirectories) - { - std::filesystem::recursive_directory_iterator iterator(m_path); - for (const auto entry = begin(iterator); iterator != end(iterator); ++iterator) - { - auto path = entry->path(); - if (options.m_filter_extensions && path.extension().string() != options.m_extension) - continue; - callback(options.m_absolute_paths ? absolute(path).string() : path.string()); - } - } - else - { - std::filesystem::directory_iterator iterator(m_path); - for (const auto entry = begin(iterator); iterator != end(iterator); ++iterator) - { - auto path = entry->path(); - if (options.m_filter_extensions && path.extension().string() != options.m_extension) - continue; - callback(options.m_absolute_paths ? absolute(path).string() : path.string()); - } - } - } - catch (std::filesystem::filesystem_error& e) - { - printf("Directory Iterator threw error when trying to find files: \"%s\"\n", e.what()); +void SearchPathFilesystem::Find(const SearchPathSearchOptions &options, const std::function<void(const std::string &)> &callback) { + try { + if (options.m_should_include_subdirectories) { + std::filesystem::recursive_directory_iterator iterator(m_path); + for (const auto entry = begin(iterator); iterator != end(iterator); ++iterator) { + auto path = entry->path(); + if (options.m_filter_extensions && path.extension().string() != options.m_extension) + continue; + callback(options.m_absolute_paths ? absolute(path).string() : path.string()); + } + } else { + std::filesystem::directory_iterator iterator(m_path); + for (const auto entry = begin(iterator); iterator != end(iterator); ++iterator) { + auto path = entry->path(); + if (options.m_filter_extensions && path.extension().string() != options.m_extension) + continue; + callback(options.m_absolute_paths ? absolute(path).string() : path.string()); + } } + } catch (std::filesystem::filesystem_error &e) { + printf("Directory Iterator threw error when trying to find files: \"%s\"\n", e.what()); + } } diff --git a/src/ObjLoading/SearchPath/SearchPathFilesystem.h b/src/ObjLoading/SearchPath/SearchPathFilesystem.h index d9997c856..b31969f79 100644 --- a/src/ObjLoading/SearchPath/SearchPathFilesystem.h +++ b/src/ObjLoading/SearchPath/SearchPathFilesystem.h @@ -4,14 +4,13 @@ #include "ISearchPath.h" -class SearchPathFilesystem final : public ISearchPath -{ - std::string m_path; +class SearchPathFilesystem final : public ISearchPath { + std::string m_path; public: - explicit SearchPathFilesystem(std::string path); + explicit SearchPathFilesystem(std::string path); - SearchPathOpenFile Open(const std::string& fileName) override; - std::string GetPath() override; - void Find(const SearchPathSearchOptions& options, const std::function<void(const std::string&)>& callback) override; + SearchPathOpenFile Open(const std::string &fileName) override; + std::string GetPath() override; + void Find(const SearchPathSearchOptions &options, const std::function<void(const std::string &)> &callback) override; }; \ No newline at end of file diff --git a/src/ObjLoading/SearchPath/SearchPathSearchOptions.cpp b/src/ObjLoading/SearchPath/SearchPathSearchOptions.cpp index bf943b41b..1a77020fe 100644 --- a/src/ObjLoading/SearchPath/SearchPathSearchOptions.cpp +++ b/src/ObjLoading/SearchPath/SearchPathSearchOptions.cpp @@ -1,41 +1,36 @@ #include "SearchPathSearchOptions.h" -SearchPathSearchOptions::SearchPathSearchOptions() -{ - m_should_include_subdirectories = true; - m_disk_files_only = false; - m_absolute_paths = false; - m_filter_extensions = false; +SearchPathSearchOptions::SearchPathSearchOptions() { + m_should_include_subdirectories = true; + m_disk_files_only = false; + m_absolute_paths = false; + m_filter_extensions = false; } -SearchPathSearchOptions& SearchPathSearchOptions::IncludeSubdirectories(const bool value) -{ - m_should_include_subdirectories = value; +SearchPathSearchOptions &SearchPathSearchOptions::IncludeSubdirectories(const bool value) { + m_should_include_subdirectories = value; - return *this; + return *this; } -SearchPathSearchOptions& SearchPathSearchOptions::OnlyDiskFiles(const bool value) -{ - m_disk_files_only = value; +SearchPathSearchOptions &SearchPathSearchOptions::OnlyDiskFiles(const bool value) { + m_disk_files_only = value; - return *this; + return *this; } -SearchPathSearchOptions& SearchPathSearchOptions::AbsolutePaths(const bool value) -{ - m_absolute_paths = value; +SearchPathSearchOptions &SearchPathSearchOptions::AbsolutePaths(const bool value) { + m_absolute_paths = value; - return *this; + return *this; } -SearchPathSearchOptions& SearchPathSearchOptions::FilterExtensions(std::string extension) -{ - m_extension = std::move(extension); - m_filter_extensions = true; +SearchPathSearchOptions &SearchPathSearchOptions::FilterExtensions(std::string extension) { + m_extension = std::move(extension); + m_filter_extensions = true; - if(m_extension[0] != '.') - m_extension = "." + m_extension; + if (m_extension[0] != '.') + m_extension = "." + m_extension; - return *this; + return *this; } diff --git a/src/ObjLoading/SearchPath/SearchPathSearchOptions.h b/src/ObjLoading/SearchPath/SearchPathSearchOptions.h index d34cd9f7a..3b627ac10 100644 --- a/src/ObjLoading/SearchPath/SearchPathSearchOptions.h +++ b/src/ObjLoading/SearchPath/SearchPathSearchOptions.h @@ -2,20 +2,19 @@ #include <string> -class SearchPathSearchOptions -{ +class SearchPathSearchOptions { public: - bool m_should_include_subdirectories; - bool m_disk_files_only; - bool m_absolute_paths; + bool m_should_include_subdirectories; + bool m_disk_files_only; + bool m_absolute_paths; - bool m_filter_extensions; - std::string m_extension; + bool m_filter_extensions; + std::string m_extension; - SearchPathSearchOptions(); + SearchPathSearchOptions(); - SearchPathSearchOptions& IncludeSubdirectories(bool value); - SearchPathSearchOptions& OnlyDiskFiles(bool value); - SearchPathSearchOptions& AbsolutePaths(bool value); - SearchPathSearchOptions& FilterExtensions(std::string extension); + SearchPathSearchOptions &IncludeSubdirectories(bool value); + SearchPathSearchOptions &OnlyDiskFiles(bool value); + SearchPathSearchOptions &AbsolutePaths(bool value); + SearchPathSearchOptions &FilterExtensions(std::string extension); }; \ No newline at end of file diff --git a/src/ObjLoading/SearchPath/SearchPaths.cpp b/src/ObjLoading/SearchPath/SearchPaths.cpp index 2065dea57..8efbf723d 100644 --- a/src/ObjLoading/SearchPath/SearchPaths.cpp +++ b/src/ObjLoading/SearchPath/SearchPaths.cpp @@ -2,63 +2,42 @@ #include <filesystem> -SearchPathOpenFile SearchPaths::Open(const std::string& fileName) -{ - for(auto* searchPathEntry : m_search_paths) - { - auto file = searchPathEntry->Open(fileName); +SearchPathOpenFile SearchPaths::Open(const std::string &fileName) { + for (auto *searchPathEntry : m_search_paths) { + auto file = searchPathEntry->Open(fileName); - if(file.IsOpen()) - { - return file; - } + if (file.IsOpen()) { + return file; } + } - return SearchPathOpenFile(); + return SearchPathOpenFile(); } -std::string SearchPaths::GetPath() -{ - return "SearchPaths: " + std::to_string(m_search_paths.size()) + " entries"; -} +std::string SearchPaths::GetPath() { return "SearchPaths: " + std::to_string(m_search_paths.size()) + " entries"; } -void SearchPaths::Find(const SearchPathSearchOptions& options, const std::function<void(const std::string&)>& callback) -{ - for (auto* searchPathEntry : m_search_paths) - { - searchPathEntry->Find(options, callback); - } +void SearchPaths::Find(const SearchPathSearchOptions &options, const std::function<void(const std::string &)> &callback) { + for (auto *searchPathEntry : m_search_paths) { + searchPathEntry->Find(options, callback); + } } -void SearchPaths::CommitSearchPath(std::unique_ptr<ISearchPath> searchPath) -{ - m_search_paths.push_back(searchPath.get()); - m_owned_search_paths.emplace_back(std::move(searchPath)); +void SearchPaths::CommitSearchPath(std::unique_ptr<ISearchPath> searchPath) { + m_search_paths.push_back(searchPath.get()); + m_owned_search_paths.emplace_back(std::move(searchPath)); } -void SearchPaths::IncludeSearchPath(ISearchPath* searchPath) -{ - m_search_paths.push_back(searchPath); -} +void SearchPaths::IncludeSearchPath(ISearchPath *searchPath) { m_search_paths.push_back(searchPath); } -void SearchPaths::RemoveSearchPath(ISearchPath* searchPath) -{ - for(auto i = m_search_paths.begin(); i != m_search_paths.end(); ++i) - { - if(*i == searchPath) - { - m_search_paths.erase(i); - return; - } +void SearchPaths::RemoveSearchPath(ISearchPath *searchPath) { + for (auto i = m_search_paths.begin(); i != m_search_paths.end(); ++i) { + if (*i == searchPath) { + m_search_paths.erase(i); + return; } + } } -SearchPaths::iterator SearchPaths::begin() -{ - return m_search_paths.begin(); -} +SearchPaths::iterator SearchPaths::begin() { return m_search_paths.begin(); } -SearchPaths::iterator SearchPaths::end() -{ - return m_search_paths.end(); -} \ No newline at end of file +SearchPaths::iterator SearchPaths::end() { return m_search_paths.end(); } \ No newline at end of file diff --git a/src/ObjLoading/SearchPath/SearchPaths.h b/src/ObjLoading/SearchPath/SearchPaths.h index a503a526a..22847319e 100644 --- a/src/ObjLoading/SearchPath/SearchPaths.h +++ b/src/ObjLoading/SearchPath/SearchPaths.h @@ -4,44 +4,43 @@ #include "ISearchPath.h" -class SearchPaths final : public ISearchPath -{ - std::vector<ISearchPath*> m_search_paths; - std::vector<std::unique_ptr<ISearchPath>> m_owned_search_paths; +class SearchPaths final : public ISearchPath { + std::vector<ISearchPath *> m_search_paths; + std::vector<std::unique_ptr<ISearchPath>> m_owned_search_paths; public: - using iterator = std::vector<ISearchPath*>::iterator; - - SearchPaths() = default; - ~SearchPaths() override = default; - - SearchPathOpenFile Open(const std::string& fileName) override; - std::string GetPath() override; - void Find(const SearchPathSearchOptions& options, const std::function<void(const std::string&)>& callback) override; - - SearchPaths(const SearchPaths& other) = delete; - SearchPaths(SearchPaths&& other) noexcept = default; - SearchPaths& operator=(const SearchPaths& other) = delete; - SearchPaths& operator=(SearchPaths&& other) noexcept = default; - - /** - * \brief Adds a search path that gets deleted upon destruction of the \c SearchPaths object. - * \param searchPath The search path to add. - */ - void CommitSearchPath(std::unique_ptr<ISearchPath> searchPath); - - /** - * \brief Adds a search path that does \b NOT get deleted upon destruction of the \c SearchPaths object. - * \param searchPath The search path to add. - */ - void IncludeSearchPath(ISearchPath* searchPath); - - /** - * \brief Removes a search path from the \c SearchPaths object. If the search path was committed then it will \b NOT be deleted when destructing the \c SearchPaths object. - * \param searchPath The search path to remove. - */ - void RemoveSearchPath(ISearchPath* searchPath); - - iterator begin(); - iterator end(); + using iterator = std::vector<ISearchPath *>::iterator; + + SearchPaths() = default; + ~SearchPaths() override = default; + + SearchPathOpenFile Open(const std::string &fileName) override; + std::string GetPath() override; + void Find(const SearchPathSearchOptions &options, const std::function<void(const std::string &)> &callback) override; + + SearchPaths(const SearchPaths &other) = delete; + SearchPaths(SearchPaths &&other) noexcept = default; + SearchPaths &operator=(const SearchPaths &other) = delete; + SearchPaths &operator=(SearchPaths &&other) noexcept = default; + + /** + * \brief Adds a search path that gets deleted upon destruction of the \c SearchPaths object. + * \param searchPath The search path to add. + */ + void CommitSearchPath(std::unique_ptr<ISearchPath> searchPath); + + /** + * \brief Adds a search path that does \b NOT get deleted upon destruction of the \c SearchPaths object. + * \param searchPath The search path to add. + */ + void IncludeSearchPath(ISearchPath *searchPath); + + /** + * \brief Removes a search path from the \c SearchPaths object. If the search path was committed then it will \b NOT be deleted when destructing the \c + * SearchPaths object. \param searchPath The search path to remove. + */ + void RemoveSearchPath(ISearchPath *searchPath); + + iterator begin(); + iterator end(); }; diff --git a/src/ObjLoading/StateMap/Parsing/Matcher/StateMapExpressionMatchers.cpp b/src/ObjLoading/StateMap/Parsing/Matcher/StateMapExpressionMatchers.cpp index 70a9b81c7..3f689c637 100644 --- a/src/ObjLoading/StateMap/Parsing/Matcher/StateMapExpressionMatchers.cpp +++ b/src/ObjLoading/StateMap/Parsing/Matcher/StateMapExpressionMatchers.cpp @@ -7,44 +7,35 @@ using namespace state_map; static constexpr int CAPTURE_VALUE = SimpleExpressionMatchers::CAPTURE_OFFSET_EXPRESSION_EXT + 1; -StateMapExpressionMatchers::StateMapExpressionMatchers() - : StateMapExpressionMatchers(nullptr) -{ -} +StateMapExpressionMatchers::StateMapExpressionMatchers() : StateMapExpressionMatchers(nullptr) {} -StateMapExpressionMatchers::StateMapExpressionMatchers(StateMapParserState* state) - : SimpleExpressionMatchers(false, false, false, false, true), - m_state(state) -{ -} +StateMapExpressionMatchers::StateMapExpressionMatchers(StateMapParserState *state) + : SimpleExpressionMatchers(false, false, false, false, true), m_state(state) {} -std::unique_ptr<SimpleExpressionMatchers::matcher_t> StateMapExpressionMatchers::ParseOperandExtension(const supplier_t* labelSupplier) const -{ - const SimpleMatcherFactory create(labelSupplier); +std::unique_ptr<SimpleExpressionMatchers::matcher_t> StateMapExpressionMatchers::ParseOperandExtension(const supplier_t *labelSupplier) const { + const SimpleMatcherFactory create(labelSupplier); - return create.Or({ - create.Identifier().Capture(CAPTURE_VALUE), - create.Integer().Capture(CAPTURE_VALUE), - }); + return create.Or({ + create.Identifier().Capture(CAPTURE_VALUE), + create.Integer().Capture(CAPTURE_VALUE), + }); } -std::unique_ptr<ISimpleExpression> StateMapExpressionMatchers::ProcessOperandExtension(SequenceResult<SimpleParserValue>& result) const -{ - assert(m_state); +std::unique_ptr<ISimpleExpression> StateMapExpressionMatchers::ProcessOperandExtension(SequenceResult<SimpleParserValue> &result) const { + assert(m_state); - const auto& valueToken = result.NextCapture(CAPTURE_VALUE); - auto value = valueToken.m_type == SimpleParserValueType::IDENTIFIER ? valueToken.IdentifierValue() : std::to_string(valueToken.IntegerValue()); + const auto &valueToken = result.NextCapture(CAPTURE_VALUE); + auto value = valueToken.m_type == SimpleParserValueType::IDENTIFIER ? valueToken.IdentifierValue() : std::to_string(valueToken.IntegerValue()); - if (value.rfind("mtl", 0) == 0) - { - if (m_state->m_valid_vars.find(value) == m_state->m_valid_vars.end()) - throw ParsingException(valueToken.GetPos(), "Unknown variable"); + if (value.rfind("mtl", 0) == 0) { + if (m_state->m_valid_vars.find(value) == m_state->m_valid_vars.end()) + throw ParsingException(valueToken.GetPos(), "Unknown variable"); - return std::make_unique<SimpleExpressionScopeValue>(value); - } + return std::make_unique<SimpleExpressionScopeValue>(value); + } - if (m_state->m_valid_values.find(value) == m_state->m_valid_values.end()) - throw ParsingException(valueToken.GetPos(), "Unknown value"); + if (m_state->m_valid_values.find(value) == m_state->m_valid_values.end()) + throw ParsingException(valueToken.GetPos(), "Unknown value"); - return std::make_unique<SimpleExpressionValue>(value); + return std::make_unique<SimpleExpressionValue>(value); } diff --git a/src/ObjLoading/StateMap/Parsing/Matcher/StateMapExpressionMatchers.h b/src/ObjLoading/StateMap/Parsing/Matcher/StateMapExpressionMatchers.h index 5be3ea1e6..925ae49b6 100644 --- a/src/ObjLoading/StateMap/Parsing/Matcher/StateMapExpressionMatchers.h +++ b/src/ObjLoading/StateMap/Parsing/Matcher/StateMapExpressionMatchers.h @@ -5,19 +5,17 @@ #include "Parsing/Simple/Expression/SimpleExpressionMatchers.h" #include "StateMap/Parsing/StateMapParserState.h" -namespace state_map -{ - class StateMapExpressionMatchers final : public SimpleExpressionMatchers - { - public: - StateMapExpressionMatchers(); - explicit StateMapExpressionMatchers(StateMapParserState* state); +namespace state_map { +class StateMapExpressionMatchers final : public SimpleExpressionMatchers { +public: + StateMapExpressionMatchers(); + explicit StateMapExpressionMatchers(StateMapParserState *state); - protected: - std::unique_ptr<matcher_t> ParseOperandExtension(const supplier_t* labelSupplier) const override; - std::unique_ptr<ISimpleExpression> ProcessOperandExtension(SequenceResult<SimpleParserValue>& result) const override; +protected: + std::unique_ptr<matcher_t> ParseOperandExtension(const supplier_t *labelSupplier) const override; + std::unique_ptr<ISimpleExpression> ProcessOperandExtension(SequenceResult<SimpleParserValue> &result) const override; - private: - StateMapParserState* m_state; - }; -} +private: + StateMapParserState *m_state; +}; +} // namespace state_map diff --git a/src/ObjLoading/StateMap/Parsing/StateMapParser.cpp b/src/ObjLoading/StateMap/Parsing/StateMapParser.cpp index 406bfa972..e825a26da 100644 --- a/src/ObjLoading/StateMap/Parsing/StateMapParser.cpp +++ b/src/ObjLoading/StateMap/Parsing/StateMapParser.cpp @@ -5,244 +5,178 @@ using namespace state_map; -namespace state_map -{ - class SequenceStateMapEntry final : public StateMapParser::sequence_t - { - static constexpr auto CAPTURE_ENTRY_NAME = 1; - - public: - SequenceStateMapEntry() - { - const SimpleMatcherFactory create(this); - - AddMatchers({ - create.Identifier().Capture(CAPTURE_ENTRY_NAME), - create.Char('{') - }); - } - - protected: - void ProcessMatch(StateMapParserState* state, SequenceResult<SimpleParserValue>& result) const override - { - const auto& entryNameToken = result.NextCapture(CAPTURE_ENTRY_NAME); - - const auto foundEntry = state->m_valid_state_map_entry_names.find(entryNameToken.IdentifierValue()); - if (foundEntry == state->m_valid_state_map_entry_names.end()) - throw ParsingException(entryNameToken.GetPos(), "Unknown entry name"); - - state->m_in_entry = true; - state->m_current_entry_index = foundEntry->second; - } - }; - - class SequenceStateMapEntryClose final : public StateMapParser::sequence_t - { - static constexpr auto CAPTURE_FIRST_TOKEN = 1; - - public: - SequenceStateMapEntryClose() - { - const SimpleMatcherFactory create(this); - - AddMatchers({ - create.Char('}').Capture(CAPTURE_FIRST_TOKEN) - }); - } - - protected: - void ProcessMatch(StateMapParserState* state, SequenceResult<SimpleParserValue>& result) const override - { - if (!state->m_entry_has_default) - throw ParsingException(result.NextCapture(CAPTURE_FIRST_TOKEN).GetPos(), "Entry must have a default case"); - - state->m_in_entry = false; - state->m_entry_has_default = false; - } - }; - - class SequenceCondition final : public StateMapParser::sequence_t - { - static constexpr auto TAG_DEFAULT = 1; - static constexpr auto TAG_EXPRESSION = 2; - - public: - SequenceCondition() - { - AddLabeledMatchers(StateMapExpressionMatchers().Expression(this), StateMapExpressionMatchers::LABEL_EXPRESSION); - const SimpleMatcherFactory create(this); - - AddMatchers({ - create.Or({ - create.Keyword("default").Tag(TAG_DEFAULT), - create.Label(StateMapExpressionMatchers::LABEL_EXPRESSION).Tag(TAG_EXPRESSION) - }), - create.Char(':') - }); - } - - protected: - void ProcessMatch(StateMapParserState* state, SequenceResult<SimpleParserValue>& result) const override - { - assert(state->m_definition); - assert(state->m_in_entry); - - if (!state->m_current_rule) - { - auto newRule = std::make_unique<StateMapRule>(); - state->m_current_rule = newRule.get(); - state->m_definition->m_state_map_entries[state->m_current_entry_index].m_rules.emplace_back(std::move(newRule)); - } - - if (result.PeekAndRemoveIfTag(TAG_EXPRESSION) == TAG_EXPRESSION) - { - auto expression = StateMapExpressionMatchers(state).ProcessExpression(result); - - state->m_current_rule->m_conditions.emplace_back(std::move(expression)); - } - else - { - assert(result.PeekAndRemoveIfTag(TAG_DEFAULT) == TAG_DEFAULT); - auto& entry = state->m_definition->m_state_map_entries[state->m_current_entry_index]; - state->m_entry_has_default = true; - entry.m_default_index = entry.m_rules.size() - 1; - } - } - }; - - class SequenceValue final : public StateMapParser::sequence_t - { - static constexpr auto TAG_PASSTHROUGH = 1; - static constexpr auto TAG_VALUE_LIST = 2; - - static constexpr auto CAPTURE_VALUE = 1; - static constexpr auto CAPTURE_VALUE_END = 2; - - static constexpr auto LABEL_VALUE_LIST = 1; - static constexpr auto LABEL_VALUE = 2; - - public: - SequenceValue() - { - const SimpleMatcherFactory create(this); - - AddLabeledMatchers(create.Or({ - create.Identifier(), - create.Integer() - }), LABEL_VALUE); - - AddLabeledMatchers({ - create.Label(LABEL_VALUE).Capture(CAPTURE_VALUE), - create.OptionalLoop(create.And({ - create.Char(','), - create.Label(LABEL_VALUE).Capture(CAPTURE_VALUE) - })) - }, LABEL_VALUE_LIST); - - AddMatchers({ - create.Or({ - create.Keyword("passthrough").Tag(TAG_PASSTHROUGH), - create.Label(LABEL_VALUE_LIST).Tag(TAG_VALUE_LIST) - }), - create.Char(';').Capture(CAPTURE_VALUE_END) - }); - } - - protected: - void ProcessMatch(StateMapParserState* state, SequenceResult<SimpleParserValue>& result) const override - { - assert(state->m_in_entry); - assert(state->m_current_rule); - - const auto& layoutEntry = state->m_layout.m_entry_layout.m_entries[state->m_current_entry_index]; - - if (result.PeekAndRemoveIfTag(TAG_VALUE_LIST) == TAG_VALUE_LIST) - { - auto resultIndex = 0u; - - while (result.HasNextCapture(CAPTURE_VALUE)) - { - const auto& valueToken = result.NextCapture(CAPTURE_VALUE); - - if (resultIndex >= layoutEntry.m_result_vars.size()) - throw ParsingException(valueToken.GetPos(), "Too many results"); - - const auto& resultVar = layoutEntry.m_result_vars[resultIndex]; - const auto varForResult = state->m_valid_vars.find(resultVar); - - if (varForResult != state->m_valid_vars.end()) - { - const auto& var = state->m_layout.m_var_layout.m_vars[varForResult->second]; - const auto tokenValue = valueToken.m_type == SimpleParserValueType::IDENTIFIER ? valueToken.IdentifierValue() : std::to_string(valueToken.IntegerValue()); - - const auto referencedValue = std::find_if(var.m_values.begin(), var.m_values.end(), [&tokenValue](const StateMapLayoutVarValue& value) - { - return value.m_name == tokenValue; - }); - - if (referencedValue == var.m_values.end()) - throw ParsingException(valueToken.GetPos(), "Not part of the valid values for this var"); - - state->m_current_rule->m_value |= referencedValue->m_state_bits_mask; - } - else - throw ParsingException(valueToken.GetPos(), "Unknown var for result?"); - - resultIndex++; - } - - if (resultIndex < layoutEntry.m_result_vars.size()) - throw ParsingException(result.NextCapture(CAPTURE_VALUE_END).GetPos(), "Not enough results"); - } - else - { - // A rule without values is considered passthrough therefore just don't add values - assert(result.PeekAndRemoveIfTag(TAG_PASSTHROUGH) == TAG_PASSTHROUGH); - state->m_current_rule->m_passthrough = true; - } - - state->m_current_rule = nullptr; - } - }; -} +namespace state_map { +class SequenceStateMapEntry final : public StateMapParser::sequence_t { + static constexpr auto CAPTURE_ENTRY_NAME = 1; + +public: + SequenceStateMapEntry() { + const SimpleMatcherFactory create(this); + + AddMatchers({create.Identifier().Capture(CAPTURE_ENTRY_NAME), create.Char('{')}); + } + +protected: + void ProcessMatch(StateMapParserState *state, SequenceResult<SimpleParserValue> &result) const override { + const auto &entryNameToken = result.NextCapture(CAPTURE_ENTRY_NAME); + + const auto foundEntry = state->m_valid_state_map_entry_names.find(entryNameToken.IdentifierValue()); + if (foundEntry == state->m_valid_state_map_entry_names.end()) + throw ParsingException(entryNameToken.GetPos(), "Unknown entry name"); + + state->m_in_entry = true; + state->m_current_entry_index = foundEntry->second; + } +}; + +class SequenceStateMapEntryClose final : public StateMapParser::sequence_t { + static constexpr auto CAPTURE_FIRST_TOKEN = 1; + +public: + SequenceStateMapEntryClose() { + const SimpleMatcherFactory create(this); + + AddMatchers({create.Char('}').Capture(CAPTURE_FIRST_TOKEN)}); + } + +protected: + void ProcessMatch(StateMapParserState *state, SequenceResult<SimpleParserValue> &result) const override { + if (!state->m_entry_has_default) + throw ParsingException(result.NextCapture(CAPTURE_FIRST_TOKEN).GetPos(), "Entry must have a default case"); + + state->m_in_entry = false; + state->m_entry_has_default = false; + } +}; + +class SequenceCondition final : public StateMapParser::sequence_t { + static constexpr auto TAG_DEFAULT = 1; + static constexpr auto TAG_EXPRESSION = 2; + +public: + SequenceCondition() { + AddLabeledMatchers(StateMapExpressionMatchers().Expression(this), StateMapExpressionMatchers::LABEL_EXPRESSION); + const SimpleMatcherFactory create(this); + + AddMatchers({create.Or({create.Keyword("default").Tag(TAG_DEFAULT), create.Label(StateMapExpressionMatchers::LABEL_EXPRESSION).Tag(TAG_EXPRESSION)}), + create.Char(':')}); + } + +protected: + void ProcessMatch(StateMapParserState *state, SequenceResult<SimpleParserValue> &result) const override { + assert(state->m_definition); + assert(state->m_in_entry); + + if (!state->m_current_rule) { + auto newRule = std::make_unique<StateMapRule>(); + state->m_current_rule = newRule.get(); + state->m_definition->m_state_map_entries[state->m_current_entry_index].m_rules.emplace_back(std::move(newRule)); + } -StateMapParser::StateMapParser(SimpleLexer* lexer, std::string stateMapName, const StateMapLayout& layout) - : AbstractParser(lexer, std::make_unique<StateMapParserState>(std::move(stateMapName), layout)) -{ -} + if (result.PeekAndRemoveIfTag(TAG_EXPRESSION) == TAG_EXPRESSION) { + auto expression = StateMapExpressionMatchers(state).ProcessExpression(result); -const std::vector<StateMapParser::sequence_t*>& StateMapParser::GetTestsForState() -{ - static std::vector<sequence_t*> rootSequences({ - new SequenceStateMapEntry() - }); - - static std::vector<sequence_t*> entrySequences({ - new SequenceStateMapEntryClose(), - new SequenceCondition() - }); - - static std::vector<sequence_t*> ruleSequences({ - new SequenceCondition(), - new SequenceValue() - }); - - if (m_state->m_in_entry) - { - return m_state->m_current_rule - ? ruleSequences - : entrySequences; + state->m_current_rule->m_conditions.emplace_back(std::move(expression)); + } else { + assert(result.PeekAndRemoveIfTag(TAG_DEFAULT) == TAG_DEFAULT); + auto &entry = state->m_definition->m_state_map_entries[state->m_current_entry_index]; + state->m_entry_has_default = true; + entry.m_default_index = entry.m_rules.size() - 1; } + } +}; - return rootSequences; -} +class SequenceValue final : public StateMapParser::sequence_t { + static constexpr auto TAG_PASSTHROUGH = 1; + static constexpr auto TAG_VALUE_LIST = 2; -std::unique_ptr<StateMapDefinition> StateMapParser::GetStateMapDefinition() const -{ - return std::move(m_state->m_definition); -} + static constexpr auto CAPTURE_VALUE = 1; + static constexpr auto CAPTURE_VALUE_END = 2; + + static constexpr auto LABEL_VALUE_LIST = 1; + static constexpr auto LABEL_VALUE = 2; + +public: + SequenceValue() { + const SimpleMatcherFactory create(this); + + AddLabeledMatchers(create.Or({create.Identifier(), create.Integer()}), LABEL_VALUE); + + AddLabeledMatchers({create.Label(LABEL_VALUE).Capture(CAPTURE_VALUE), + create.OptionalLoop(create.And({create.Char(','), create.Label(LABEL_VALUE).Capture(CAPTURE_VALUE)}))}, + LABEL_VALUE_LIST); + + AddMatchers({create.Or({create.Keyword("passthrough").Tag(TAG_PASSTHROUGH), create.Label(LABEL_VALUE_LIST).Tag(TAG_VALUE_LIST)}), + create.Char(';').Capture(CAPTURE_VALUE_END)}); + } + +protected: + void ProcessMatch(StateMapParserState *state, SequenceResult<SimpleParserValue> &result) const override { + assert(state->m_in_entry); + assert(state->m_current_rule); + + const auto &layoutEntry = state->m_layout.m_entry_layout.m_entries[state->m_current_entry_index]; + + if (result.PeekAndRemoveIfTag(TAG_VALUE_LIST) == TAG_VALUE_LIST) { + auto resultIndex = 0u; + + while (result.HasNextCapture(CAPTURE_VALUE)) { + const auto &valueToken = result.NextCapture(CAPTURE_VALUE); + + if (resultIndex >= layoutEntry.m_result_vars.size()) + throw ParsingException(valueToken.GetPos(), "Too many results"); + + const auto &resultVar = layoutEntry.m_result_vars[resultIndex]; + const auto varForResult = state->m_valid_vars.find(resultVar); -StateMapParserState* StateMapParser::GetState() const -{ - return m_state.get(); + if (varForResult != state->m_valid_vars.end()) { + const auto &var = state->m_layout.m_var_layout.m_vars[varForResult->second]; + const auto tokenValue = + valueToken.m_type == SimpleParserValueType::IDENTIFIER ? valueToken.IdentifierValue() : std::to_string(valueToken.IntegerValue()); + + const auto referencedValue = + std::find_if(var.m_values.begin(), var.m_values.end(), [&tokenValue](const StateMapLayoutVarValue &value) { return value.m_name == tokenValue; }); + + if (referencedValue == var.m_values.end()) + throw ParsingException(valueToken.GetPos(), "Not part of the valid values for this var"); + + state->m_current_rule->m_value |= referencedValue->m_state_bits_mask; + } else + throw ParsingException(valueToken.GetPos(), "Unknown var for result?"); + + resultIndex++; + } + + if (resultIndex < layoutEntry.m_result_vars.size()) + throw ParsingException(result.NextCapture(CAPTURE_VALUE_END).GetPos(), "Not enough results"); + } else { + // A rule without values is considered passthrough therefore just don't add values + assert(result.PeekAndRemoveIfTag(TAG_PASSTHROUGH) == TAG_PASSTHROUGH); + state->m_current_rule->m_passthrough = true; + } + + state->m_current_rule = nullptr; + } +}; +} // namespace state_map + +StateMapParser::StateMapParser(SimpleLexer *lexer, std::string stateMapName, const StateMapLayout &layout) + : AbstractParser(lexer, std::make_unique<StateMapParserState>(std::move(stateMapName), layout)) {} + +const std::vector<StateMapParser::sequence_t *> &StateMapParser::GetTestsForState() { + static std::vector<sequence_t *> rootSequences({new SequenceStateMapEntry()}); + + static std::vector<sequence_t *> entrySequences({new SequenceStateMapEntryClose(), new SequenceCondition()}); + + static std::vector<sequence_t *> ruleSequences({new SequenceCondition(), new SequenceValue()}); + + if (m_state->m_in_entry) { + return m_state->m_current_rule ? ruleSequences : entrySequences; + } + + return rootSequences; } + +std::unique_ptr<StateMapDefinition> StateMapParser::GetStateMapDefinition() const { return std::move(m_state->m_definition); } + +StateMapParserState *StateMapParser::GetState() const { return m_state.get(); } diff --git a/src/ObjLoading/StateMap/Parsing/StateMapParser.h b/src/ObjLoading/StateMap/Parsing/StateMapParser.h index 9dc490430..bab27a103 100644 --- a/src/ObjLoading/StateMap/Parsing/StateMapParser.h +++ b/src/ObjLoading/StateMap/Parsing/StateMapParser.h @@ -1,22 +1,20 @@ #pragma once -#include "StateMapParserState.h" -#include "Utils/ClassUtils.h" -#include "Techset/TechsetDefinition.h" +#include "Parsing/Impl/AbstractParser.h" #include "Parsing/Simple/SimpleLexer.h" #include "Parsing/Simple/SimpleParserValue.h" -#include "Parsing/Impl/AbstractParser.h" +#include "StateMapParserState.h" +#include "Techset/TechsetDefinition.h" +#include "Utils/ClassUtils.h" -namespace state_map -{ - class StateMapParser final : public AbstractParser<SimpleParserValue, StateMapParserState> - { - protected: - const std::vector<sequence_t*>& GetTestsForState() override; +namespace state_map { +class StateMapParser final : public AbstractParser<SimpleParserValue, StateMapParserState> { +protected: + const std::vector<sequence_t *> &GetTestsForState() override; - public: - StateMapParser(SimpleLexer* lexer, std::string stateMapName, const StateMapLayout& layout); - _NODISCARD std::unique_ptr<StateMapDefinition> GetStateMapDefinition() const; - _NODISCARD StateMapParserState* GetState() const; - }; -} +public: + StateMapParser(SimpleLexer *lexer, std::string stateMapName, const StateMapLayout &layout); + _NODISCARD std::unique_ptr<StateMapDefinition> GetStateMapDefinition() const; + _NODISCARD StateMapParserState *GetState() const; +}; +} // namespace state_map diff --git a/src/ObjLoading/StateMap/Parsing/StateMapParserState.cpp b/src/ObjLoading/StateMap/Parsing/StateMapParserState.cpp index cea85887f..6b3a1470c 100644 --- a/src/ObjLoading/StateMap/Parsing/StateMapParserState.cpp +++ b/src/ObjLoading/StateMap/Parsing/StateMapParserState.cpp @@ -2,23 +2,17 @@ using namespace state_map; -StateMapParserState::StateMapParserState(std::string stateMapName, const StateMapLayout& layout) - : m_layout(layout), - m_definition(std::make_unique<StateMapDefinition>(std::move(stateMapName), layout.m_entry_layout.m_entries.size())), - m_in_entry(false), - m_entry_has_default(false), - m_current_entry_index(0u), - m_current_rule(nullptr) -{ - for (auto i = 0u; i < m_layout.m_entry_layout.m_entries.size(); i++) - m_valid_state_map_entry_names.emplace(m_layout.m_entry_layout.m_entries[i].m_name, i); +StateMapParserState::StateMapParserState(std::string stateMapName, const StateMapLayout &layout) + : m_layout(layout), m_definition(std::make_unique<StateMapDefinition>(std::move(stateMapName), layout.m_entry_layout.m_entries.size())), m_in_entry(false), + m_entry_has_default(false), m_current_entry_index(0u), m_current_rule(nullptr) { + for (auto i = 0u; i < m_layout.m_entry_layout.m_entries.size(); i++) + m_valid_state_map_entry_names.emplace(m_layout.m_entry_layout.m_entries[i].m_name, i); - for (auto varIndex = 0u; varIndex < layout.m_var_layout.m_vars.size(); varIndex++) - { - const auto& var = layout.m_var_layout.m_vars[varIndex]; - m_valid_vars.emplace(std::make_pair(var.m_name, varIndex)); + for (auto varIndex = 0u; varIndex < layout.m_var_layout.m_vars.size(); varIndex++) { + const auto &var = layout.m_var_layout.m_vars[varIndex]; + m_valid_vars.emplace(std::make_pair(var.m_name, varIndex)); - for (const auto& value : var.m_values) - m_valid_values.emplace(value.m_name); - } + for (const auto &value : var.m_values) + m_valid_values.emplace(value.m_name); + } } diff --git a/src/ObjLoading/StateMap/Parsing/StateMapParserState.h b/src/ObjLoading/StateMap/Parsing/StateMapParserState.h index 6a056fb55..7904ee507 100644 --- a/src/ObjLoading/StateMap/Parsing/StateMapParserState.h +++ b/src/ObjLoading/StateMap/Parsing/StateMapParserState.h @@ -1,29 +1,27 @@ #pragma once -#include <unordered_map> #include <memory> #include <set> #include <string> +#include <unordered_map> #include "StateMap/StateMapDefinition.h" #include "StateMap/StateMapLayout.h" -namespace state_map -{ - class StateMapParserState - { - public: - const StateMapLayout& m_layout; - std::unordered_map<std::string, size_t> m_valid_state_map_entry_names; - std::unordered_map<std::string, size_t> m_valid_vars; - std::set<std::string> m_valid_values; - std::unique_ptr<StateMapDefinition> m_definition; +namespace state_map { +class StateMapParserState { +public: + const StateMapLayout &m_layout; + std::unordered_map<std::string, size_t> m_valid_state_map_entry_names; + std::unordered_map<std::string, size_t> m_valid_vars; + std::set<std::string> m_valid_values; + std::unique_ptr<StateMapDefinition> m_definition; - bool m_in_entry; - bool m_entry_has_default; - size_t m_current_entry_index; - StateMapRule* m_current_rule; + bool m_in_entry; + bool m_entry_has_default; + size_t m_current_entry_index; + StateMapRule *m_current_rule; - StateMapParserState(std::string stateMapName, const StateMapLayout& layout); - }; -} + StateMapParserState(std::string stateMapName, const StateMapLayout &layout); +}; +} // namespace state_map diff --git a/src/ObjLoading/StateMap/StateMapDefinition.cpp b/src/ObjLoading/StateMap/StateMapDefinition.cpp index e2cfc0923..13face324 100644 --- a/src/ObjLoading/StateMap/StateMapDefinition.cpp +++ b/src/ObjLoading/StateMap/StateMapDefinition.cpp @@ -2,19 +2,8 @@ using namespace state_map; -StateMapRule::StateMapRule() - : m_value(0u), - m_passthrough(false) -{ -} +StateMapRule::StateMapRule() : m_value(0u), m_passthrough(false) {} -StateMapEntry::StateMapEntry() - : m_default_index(0u) -{ -} +StateMapEntry::StateMapEntry() : m_default_index(0u) {} -StateMapDefinition::StateMapDefinition(std::string name, const size_t entryCount) - : m_name(std::move(name)), - m_state_map_entries(entryCount) -{ -} +StateMapDefinition::StateMapDefinition(std::string name, const size_t entryCount) : m_name(std::move(name)), m_state_map_entries(entryCount) {} diff --git a/src/ObjLoading/StateMap/StateMapDefinition.h b/src/ObjLoading/StateMap/StateMapDefinition.h index 4b691cbdd..cf92d6cda 100644 --- a/src/ObjLoading/StateMap/StateMapDefinition.h +++ b/src/ObjLoading/StateMap/StateMapDefinition.h @@ -6,33 +6,29 @@ #include "Parsing/Simple/Expression/ISimpleExpression.h" -namespace state_map -{ - class StateMapRule - { - public: - std::vector<std::unique_ptr<ISimpleExpression>> m_conditions; - size_t m_value; - bool m_passthrough; - - StateMapRule(); - }; - - class StateMapEntry - { - public: - size_t m_default_index; - std::vector<std::unique_ptr<StateMapRule>> m_rules; - - StateMapEntry(); - }; - - class StateMapDefinition - { - public: - StateMapDefinition(std::string name, size_t entryCount); - - std::string m_name; - std::vector<StateMapEntry> m_state_map_entries; - }; -} +namespace state_map { +class StateMapRule { +public: + std::vector<std::unique_ptr<ISimpleExpression>> m_conditions; + size_t m_value; + bool m_passthrough; + + StateMapRule(); +}; + +class StateMapEntry { +public: + size_t m_default_index; + std::vector<std::unique_ptr<StateMapRule>> m_rules; + + StateMapEntry(); +}; + +class StateMapDefinition { +public: + StateMapDefinition(std::string name, size_t entryCount); + + std::string m_name; + std::vector<StateMapEntry> m_state_map_entries; +}; +} // namespace state_map diff --git a/src/ObjLoading/StateMap/StateMapFromTechniqueExtractor.cpp b/src/ObjLoading/StateMap/StateMapFromTechniqueExtractor.cpp index 182e50144..70e83c907 100644 --- a/src/ObjLoading/StateMap/StateMapFromTechniqueExtractor.cpp +++ b/src/ObjLoading/StateMap/StateMapFromTechniqueExtractor.cpp @@ -2,57 +2,41 @@ using namespace state_map; -std::string StateMapFromTechniqueExtractor::RetrieveStateMap() -{ - return std::move(m_state_map); -} +std::string StateMapFromTechniqueExtractor::RetrieveStateMap() { return std::move(m_state_map); } -void StateMapFromTechniqueExtractor::AcceptNextPass() -{ -} +void StateMapFromTechniqueExtractor::AcceptNextPass() {} -bool StateMapFromTechniqueExtractor::AcceptEndPass(std::string& errorMessage) -{ - return true; -} +bool StateMapFromTechniqueExtractor::AcceptEndPass(std::string &errorMessage) { return true; } -bool StateMapFromTechniqueExtractor::AcceptStateMap(const std::string& stateMapName, std::string& errorMessage) -{ - m_state_map = stateMapName; - return true; +bool StateMapFromTechniqueExtractor::AcceptStateMap(const std::string &stateMapName, std::string &errorMessage) { + m_state_map = stateMapName; + return true; } -bool StateMapFromTechniqueExtractor::AcceptVertexShader(const std::string& vertexShaderName, std::string& errorMessage) -{ - return true; -} +bool StateMapFromTechniqueExtractor::AcceptVertexShader(const std::string &vertexShaderName, std::string &errorMessage) { return true; } -bool StateMapFromTechniqueExtractor::AcceptPixelShader(const std::string& pixelShaderName, std::string& errorMessage) -{ - return true; -} +bool StateMapFromTechniqueExtractor::AcceptPixelShader(const std::string &pixelShaderName, std::string &errorMessage) { return true; } -bool StateMapFromTechniqueExtractor::AcceptShaderConstantArgument(techset::ShaderSelector shader, techset::ShaderArgument shaderArgument, techset::ShaderArgumentCodeSource source, std::string& errorMessage) -{ - return true; +bool StateMapFromTechniqueExtractor::AcceptShaderConstantArgument(techset::ShaderSelector shader, techset::ShaderArgument shaderArgument, + techset::ShaderArgumentCodeSource source, std::string &errorMessage) { + return true; } -bool StateMapFromTechniqueExtractor::AcceptShaderSamplerArgument(techset::ShaderSelector shader, techset::ShaderArgument shaderArgument, techset::ShaderArgumentCodeSource source, std::string& errorMessage) -{ - return true; +bool StateMapFromTechniqueExtractor::AcceptShaderSamplerArgument(techset::ShaderSelector shader, techset::ShaderArgument shaderArgument, + techset::ShaderArgumentCodeSource source, std::string &errorMessage) { + return true; } -bool StateMapFromTechniqueExtractor::AcceptShaderLiteralArgument(techset::ShaderSelector shader, techset::ShaderArgument shaderArgument, techset::ShaderArgumentLiteralSource source, std::string& errorMessage) -{ - return true; +bool StateMapFromTechniqueExtractor::AcceptShaderLiteralArgument(techset::ShaderSelector shader, techset::ShaderArgument shaderArgument, + techset::ShaderArgumentLiteralSource source, std::string &errorMessage) { + return true; } -bool StateMapFromTechniqueExtractor::AcceptShaderMaterialArgument(techset::ShaderSelector shader, techset::ShaderArgument shaderArgument, techset::ShaderArgumentMaterialSource source, std::string& errorMessage) -{ - return true; +bool StateMapFromTechniqueExtractor::AcceptShaderMaterialArgument(techset::ShaderSelector shader, techset::ShaderArgument shaderArgument, + techset::ShaderArgumentMaterialSource source, std::string &errorMessage) { + return true; } -bool StateMapFromTechniqueExtractor::AcceptVertexStreamRouting(const std::string& destination, const std::string& source, std::string& errorMessage) -{ - return true; +bool StateMapFromTechniqueExtractor::AcceptVertexStreamRouting(const std::string &destination, const std::string &source, std::string &errorMessage) { + return true; } diff --git a/src/ObjLoading/StateMap/StateMapFromTechniqueExtractor.h b/src/ObjLoading/StateMap/StateMapFromTechniqueExtractor.h index 217d7ea65..4be3ced74 100644 --- a/src/ObjLoading/StateMap/StateMapFromTechniqueExtractor.h +++ b/src/ObjLoading/StateMap/StateMapFromTechniqueExtractor.h @@ -4,25 +4,27 @@ #include "Techset/TechniqueDefinitionAcceptor.h" -namespace state_map -{ - class StateMapFromTechniqueExtractor final : public techset::ITechniqueDefinitionAcceptor - { - public: - std::string RetrieveStateMap(); +namespace state_map { +class StateMapFromTechniqueExtractor final : public techset::ITechniqueDefinitionAcceptor { +public: + std::string RetrieveStateMap(); - void AcceptNextPass() override; - bool AcceptEndPass(std::string& errorMessage) override; - bool AcceptStateMap(const std::string& stateMapName, std::string& errorMessage) override; - bool AcceptVertexShader(const std::string& vertexShaderName, std::string& errorMessage) override; - bool AcceptPixelShader(const std::string& pixelShaderName, std::string& errorMessage) override; - bool AcceptShaderConstantArgument(techset::ShaderSelector shader, techset::ShaderArgument shaderArgument, techset::ShaderArgumentCodeSource source, std::string& errorMessage) override; - bool AcceptShaderSamplerArgument(techset::ShaderSelector shader, techset::ShaderArgument shaderArgument, techset::ShaderArgumentCodeSource source, std::string& errorMessage) override; - bool AcceptShaderLiteralArgument(techset::ShaderSelector shader, techset::ShaderArgument shaderArgument, techset::ShaderArgumentLiteralSource source, std::string& errorMessage) override; - bool AcceptShaderMaterialArgument(techset::ShaderSelector shader, techset::ShaderArgument shaderArgument, techset::ShaderArgumentMaterialSource source, std::string& errorMessage) override; - bool AcceptVertexStreamRouting(const std::string& destination, const std::string& source, std::string& errorMessage) override; + void AcceptNextPass() override; + bool AcceptEndPass(std::string &errorMessage) override; + bool AcceptStateMap(const std::string &stateMapName, std::string &errorMessage) override; + bool AcceptVertexShader(const std::string &vertexShaderName, std::string &errorMessage) override; + bool AcceptPixelShader(const std::string &pixelShaderName, std::string &errorMessage) override; + bool AcceptShaderConstantArgument(techset::ShaderSelector shader, techset::ShaderArgument shaderArgument, techset::ShaderArgumentCodeSource source, + std::string &errorMessage) override; + bool AcceptShaderSamplerArgument(techset::ShaderSelector shader, techset::ShaderArgument shaderArgument, techset::ShaderArgumentCodeSource source, + std::string &errorMessage) override; + bool AcceptShaderLiteralArgument(techset::ShaderSelector shader, techset::ShaderArgument shaderArgument, techset::ShaderArgumentLiteralSource source, + std::string &errorMessage) override; + bool AcceptShaderMaterialArgument(techset::ShaderSelector shader, techset::ShaderArgument shaderArgument, techset::ShaderArgumentMaterialSource source, + std::string &errorMessage) override; + bool AcceptVertexStreamRouting(const std::string &destination, const std::string &source, std::string &errorMessage) override; - private: - std::string m_state_map; - }; -} +private: + std::string m_state_map; +}; +} // namespace state_map diff --git a/src/ObjLoading/StateMap/StateMapHandler.cpp b/src/ObjLoading/StateMap/StateMapHandler.cpp index 7b56406ed..e3e2682ca 100644 --- a/src/ObjLoading/StateMap/StateMapHandler.cpp +++ b/src/ObjLoading/StateMap/StateMapHandler.cpp @@ -1,88 +1,73 @@ #include "StateMapHandler.h" +#include <algorithm> #include <cassert> #include <iostream> -#include <algorithm> using namespace state_map; -void StateMapVars::AddValue(std::string key, std::string value) -{ - m_vars.emplace(std::make_pair(std::move(key), std::move(value))); -} +void StateMapVars::AddValue(std::string key, std::string value) { m_vars.emplace(std::make_pair(std::move(key), std::move(value))); } -SimpleExpressionValue StateMapVars::ValueByName(const std::string& name) const -{ - const auto foundValue = m_vars.find(name); +SimpleExpressionValue StateMapVars::ValueByName(const std::string &name) const { + const auto foundValue = m_vars.find(name); - if (foundValue != m_vars.end()) - return SimpleExpressionValue(foundValue->second); + if (foundValue != m_vars.end()) + return SimpleExpressionValue(foundValue->second); - return SimpleExpressionValue(0); + return SimpleExpressionValue(0); } -StateMapHandler::StateMapHandler(const StateMapLayout& stateMapLayout, const StateMapDefinition& stateMap) - : m_state_map_layout(stateMapLayout), - m_state_map(stateMap) -{ -} +StateMapHandler::StateMapHandler(const StateMapLayout &stateMapLayout, const StateMapDefinition &stateMap) + : m_state_map_layout(stateMapLayout), m_state_map(stateMap) {} + +void StateMapHandler::ApplyStateMap(const uint32_t *baseStateBits, uint32_t *outStateBits) const { + assert(baseStateBits != nullptr); + assert(outStateBits != nullptr); + + const auto vars = BuildVars(baseStateBits); -void StateMapHandler::ApplyStateMap(const uint32_t* baseStateBits, uint32_t* outStateBits) const -{ - assert(baseStateBits != nullptr); - assert(outStateBits != nullptr); - - const auto vars = BuildVars(baseStateBits); - - for (auto i = 0u; i < m_state_map_layout.m_state_bits_count; i++) - outStateBits[i] = baseStateBits[i]; - - for (auto entryIndex = 0u; entryIndex < m_state_map.m_state_map_entries.size(); entryIndex++) - { - const auto& entry = m_state_map.m_state_map_entries[entryIndex]; - const auto matchingRule = std::find_if(entry.m_rules.begin(), entry.m_rules.end(), [&vars](const std::unique_ptr<StateMapRule>& rule) - { - const auto matchingCondition = std::find_if(rule->m_conditions.begin(), rule->m_conditions.end(), [&vars](std::unique_ptr<ISimpleExpression>& condition) - { - return condition->EvaluateNonStatic(&vars).IsTruthy(); - }); - - return matchingCondition != rule->m_conditions.end(); - }); - - if (matchingRule != entry.m_rules.end()) - ApplyRule(m_state_map_layout.m_entry_layout.m_entries[entryIndex], **matchingRule, outStateBits); - else - ApplyRule(m_state_map_layout.m_entry_layout.m_entries[entryIndex], *entry.m_rules[entry.m_default_index], outStateBits); - } + for (auto i = 0u; i < m_state_map_layout.m_state_bits_count; i++) + outStateBits[i] = baseStateBits[i]; + + for (auto entryIndex = 0u; entryIndex < m_state_map.m_state_map_entries.size(); entryIndex++) { + const auto &entry = m_state_map.m_state_map_entries[entryIndex]; + const auto matchingRule = std::find_if(entry.m_rules.begin(), entry.m_rules.end(), [&vars](const std::unique_ptr<StateMapRule> &rule) { + const auto matchingCondition = std::find_if(rule->m_conditions.begin(), rule->m_conditions.end(), [&vars](std::unique_ptr<ISimpleExpression> &condition) { + return condition->EvaluateNonStatic(&vars).IsTruthy(); + }); + + return matchingCondition != rule->m_conditions.end(); + }); + + if (matchingRule != entry.m_rules.end()) + ApplyRule(m_state_map_layout.m_entry_layout.m_entries[entryIndex], **matchingRule, outStateBits); + else + ApplyRule(m_state_map_layout.m_entry_layout.m_entries[entryIndex], *entry.m_rules[entry.m_default_index], outStateBits); + } } -StateMapVars StateMapHandler::BuildVars(const uint32_t* baseStateBits) const -{ - StateMapVars result; - - for (const auto& var : m_state_map_layout.m_var_layout.m_vars) - { - const auto baseStateBitField = baseStateBits[var.m_state_bits_index]; - const auto matchingValue = std::find_if(var.m_values.begin(), var.m_values.end(), [&baseStateBitField](const StateMapLayoutVarValue& value) - { - return (baseStateBitField & value.m_state_bits_mask) == value.m_state_bits_mask; - }); - - if (matchingValue != var.m_values.end()) - result.AddValue(var.m_name, matchingValue->m_name); - else - std::cerr << "Could not find base value for state map var \"" << var.m_name << "\"\n"; - } - - return result; +StateMapVars StateMapHandler::BuildVars(const uint32_t *baseStateBits) const { + StateMapVars result; + + for (const auto &var : m_state_map_layout.m_var_layout.m_vars) { + const auto baseStateBitField = baseStateBits[var.m_state_bits_index]; + const auto matchingValue = std::find_if(var.m_values.begin(), var.m_values.end(), [&baseStateBitField](const StateMapLayoutVarValue &value) { + return (baseStateBitField & value.m_state_bits_mask) == value.m_state_bits_mask; + }); + + if (matchingValue != var.m_values.end()) + result.AddValue(var.m_name, matchingValue->m_name); + else + std::cerr << "Could not find base value for state map var \"" << var.m_name << "\"\n"; + } + + return result; } -void StateMapHandler::ApplyRule(const StateMapLayoutEntry& entry, const StateMapRule& rule, uint32_t* outStateBits) -{ - if (rule.m_passthrough) - return; +void StateMapHandler::ApplyRule(const StateMapLayoutEntry &entry, const StateMapRule &rule, uint32_t *outStateBits) { + if (rule.m_passthrough) + return; - outStateBits[entry.m_state_bits_index] &= ~entry.m_state_bits_mask; - outStateBits[entry.m_state_bits_index] |= rule.m_value; + outStateBits[entry.m_state_bits_index] &= ~entry.m_state_bits_mask; + outStateBits[entry.m_state_bits_index] |= rule.m_value; } diff --git a/src/ObjLoading/StateMap/StateMapHandler.h b/src/ObjLoading/StateMap/StateMapHandler.h index 7fe44933d..3b8d932f4 100644 --- a/src/ObjLoading/StateMap/StateMapHandler.h +++ b/src/ObjLoading/StateMap/StateMapHandler.h @@ -3,34 +3,31 @@ #include <cstdint> #include <unordered_map> -#include "Utils/ClassUtils.h" #include "StateMap/StateMapDefinition.h" #include "StateMap/StateMapLayout.h" +#include "Utils/ClassUtils.h" + +namespace state_map { +class StateMapVars final : public ISimpleExpressionScopeValues { +public: + void AddValue(std::string key, std::string value); + _NODISCARD SimpleExpressionValue ValueByName(const std::string &name) const override; + +private: + std::unordered_map<std::string, std::string> m_vars; +}; + +class StateMapHandler { +public: + StateMapHandler(const StateMapLayout &stateMapLayout, const StateMapDefinition &stateMap); + + void ApplyStateMap(const uint32_t *baseStateBits, uint32_t *outStateBits) const; + +private: + StateMapVars BuildVars(const uint32_t *baseStateBits) const; + static void ApplyRule(const StateMapLayoutEntry &entry, const StateMapRule &rule, uint32_t *outStateBits); -namespace state_map -{ - class StateMapVars final : public ISimpleExpressionScopeValues - { - public: - void AddValue(std::string key, std::string value); - _NODISCARD SimpleExpressionValue ValueByName(const std::string& name) const override; - - private: - std::unordered_map<std::string, std::string> m_vars; - }; - - class StateMapHandler - { - public: - StateMapHandler(const StateMapLayout& stateMapLayout, const StateMapDefinition& stateMap); - - void ApplyStateMap(const uint32_t* baseStateBits, uint32_t* outStateBits) const; - - private: - StateMapVars BuildVars(const uint32_t* baseStateBits) const; - static void ApplyRule(const StateMapLayoutEntry& entry, const StateMapRule& rule, uint32_t* outStateBits); - - const StateMapLayout& m_state_map_layout; - const StateMapDefinition& m_state_map; - }; -} + const StateMapLayout &m_state_map_layout; + const StateMapDefinition &m_state_map; +}; +} // namespace state_map diff --git a/src/ObjLoading/StateMap/StateMapReader.cpp b/src/ObjLoading/StateMap/StateMapReader.cpp index 5190350d2..a75205bbf 100644 --- a/src/ObjLoading/StateMap/StateMapReader.cpp +++ b/src/ObjLoading/StateMap/StateMapReader.cpp @@ -2,70 +2,60 @@ #include <iostream> -#include "Parsing/StateMapParser.h" #include "Parsing/Impl/CommentRemovingStreamProxy.h" #include "Parsing/Impl/ParserSingleInputStream.h" #include "Parsing/Matcher/StateMapExpressionMatchers.h" +#include "Parsing/StateMapParser.h" using namespace state_map; -StateMapReader::StateMapReader(std::istream& stream, std::string fileName, std::string stateMapName, const StateMapLayout& layout) - : m_state_map_name(std::move(stateMapName)), - m_file_name(std::move(fileName)), - m_state_map_layout(layout) -{ - m_base_stream = std::make_unique<ParserSingleInputStream>(stream, m_file_name); - m_comment_proxy = std::make_unique<CommentRemovingStreamProxy>(m_base_stream.get()); +StateMapReader::StateMapReader(std::istream &stream, std::string fileName, std::string stateMapName, const StateMapLayout &layout) + : m_state_map_name(std::move(stateMapName)), m_file_name(std::move(fileName)), m_state_map_layout(layout) { + m_base_stream = std::make_unique<ParserSingleInputStream>(stream, m_file_name); + m_comment_proxy = std::make_unique<CommentRemovingStreamProxy>(m_base_stream.get()); } -bool StateMapReader::IsValidEndState(const StateMapParserState* state) const -{ - if (state->m_current_rule) - { - std::cerr << "In \"" << m_file_name << "\": Unclosed rule at end of file!\n"; - return false; - } - - if (state->m_in_entry) - { - std::cerr << "In \"" << m_file_name << "\": Unclosed entry at end of file!\n"; - return false; +bool StateMapReader::IsValidEndState(const StateMapParserState *state) const { + if (state->m_current_rule) { + std::cerr << "In \"" << m_file_name << "\": Unclosed rule at end of file!\n"; + return false; + } + + if (state->m_in_entry) { + std::cerr << "In \"" << m_file_name << "\": Unclosed entry at end of file!\n"; + return false; + } + + for (auto i = 0u; i < state->m_layout.m_entry_layout.m_entries.size(); i++) { + if (state->m_definition->m_state_map_entries[i].m_rules.empty()) { + std::cerr << "In \"" << m_file_name << "\": State map must define a rule for \"" << state->m_layout.m_entry_layout.m_entries[i].m_name << "\"!\n"; + return false; } + } - for (auto i = 0u; i < state->m_layout.m_entry_layout.m_entries.size(); i++) - { - if (state->m_definition->m_state_map_entries[i].m_rules.empty()) - { - std::cerr << "In \"" << m_file_name << "\": State map must define a rule for \"" << state->m_layout.m_entry_layout.m_entries[i].m_name << "\"!\n"; - return false; - } - } - - return true; + return true; } -std::unique_ptr<StateMapDefinition> StateMapReader::ReadStateMapDefinition() const -{ - SimpleLexer::Config lexerConfig; - lexerConfig.m_emit_new_line_tokens = false; - lexerConfig.m_read_strings = false; - lexerConfig.m_read_integer_numbers = true; - lexerConfig.m_read_floating_point_numbers = false; - StateMapExpressionMatchers().ApplyTokensToLexerConfig(lexerConfig); - const auto lexer = std::make_unique<SimpleLexer>(m_comment_proxy.get(), std::move(lexerConfig)); +std::unique_ptr<StateMapDefinition> StateMapReader::ReadStateMapDefinition() const { + SimpleLexer::Config lexerConfig; + lexerConfig.m_emit_new_line_tokens = false; + lexerConfig.m_read_strings = false; + lexerConfig.m_read_integer_numbers = true; + lexerConfig.m_read_floating_point_numbers = false; + StateMapExpressionMatchers().ApplyTokensToLexerConfig(lexerConfig); + const auto lexer = std::make_unique<SimpleLexer>(m_comment_proxy.get(), std::move(lexerConfig)); - const auto parser = std::make_unique<StateMapParser>(lexer.get(), m_state_map_name, m_state_map_layout); + const auto parser = std::make_unique<StateMapParser>(lexer.get(), m_state_map_name, m_state_map_layout); - const auto success = parser->Parse(); - if (!success) - { - std::cout << "Parsing state map file \"" << m_file_name << "\" failed!\n"; - return {}; - } + const auto success = parser->Parse(); + if (!success) { + std::cout << "Parsing state map file \"" << m_file_name << "\" failed!\n"; + return {}; + } - const auto* parserEndState = parser->GetState(); - if (!IsValidEndState(parserEndState)) - return nullptr; + const auto *parserEndState = parser->GetState(); + if (!IsValidEndState(parserEndState)) + return nullptr; - return parser->GetStateMapDefinition(); + return parser->GetStateMapDefinition(); } diff --git a/src/ObjLoading/StateMap/StateMapReader.h b/src/ObjLoading/StateMap/StateMapReader.h index bb89aeb3e..bd3d97a91 100644 --- a/src/ObjLoading/StateMap/StateMapReader.h +++ b/src/ObjLoading/StateMap/StateMapReader.h @@ -3,26 +3,24 @@ #include <memory> #include <string> -#include "Utils/ClassUtils.h" -#include "StateMapDefinition.h" -#include "StateMap/StateMapLayout.h" #include "Parsing/IParserLineStream.h" #include "Parsing/StateMapParserState.h" +#include "StateMap/StateMapLayout.h" +#include "StateMapDefinition.h" +#include "Utils/ClassUtils.h" -namespace state_map -{ - class StateMapReader - { - std::string m_state_map_name; - std::string m_file_name; - const StateMapLayout& m_state_map_layout; - std::unique_ptr<IParserLineStream> m_base_stream; - std::unique_ptr<IParserLineStream> m_comment_proxy; +namespace state_map { +class StateMapReader { + std::string m_state_map_name; + std::string m_file_name; + const StateMapLayout &m_state_map_layout; + std::unique_ptr<IParserLineStream> m_base_stream; + std::unique_ptr<IParserLineStream> m_comment_proxy; - public: - StateMapReader(std::istream& stream, std::string fileName, std::string stateMapName, const StateMapLayout& layout); +public: + StateMapReader(std::istream &stream, std::string fileName, std::string stateMapName, const StateMapLayout &layout); - _NODISCARD bool IsValidEndState(const StateMapParserState* state) const; - _NODISCARD std::unique_ptr<StateMapDefinition> ReadStateMapDefinition() const; - }; -} + _NODISCARD bool IsValidEndState(const StateMapParserState *state) const; + _NODISCARD std::unique_ptr<StateMapDefinition> ReadStateMapDefinition() const; +}; +} // namespace state_map diff --git a/src/ObjLoading/StructuredDataDef/Parsing/Sequence/StructuredDataDefScopeSequences.cpp b/src/ObjLoading/StructuredDataDef/Parsing/Sequence/StructuredDataDefScopeSequences.cpp index 56d536295..8a4a44c7f 100644 --- a/src/ObjLoading/StructuredDataDef/Parsing/Sequence/StructuredDataDefScopeSequences.cpp +++ b/src/ObjLoading/StructuredDataDef/Parsing/Sequence/StructuredDataDefScopeSequences.cpp @@ -5,291 +5,226 @@ #include "Parsing/Simple/Matcher/SimpleMatcherFactory.h" #include "StructuredDataDef/Parsing/StructuredDataDefSizeCalculator.h" -namespace sdd::def_scope_sequences -{ - class SequenceEnum final : public StructuredDataDefParser::sequence_t - { - static constexpr auto CAPTURE_NAME = 1; - static constexpr auto CAPTURE_RESERVED_COUNT = 2; - - public: - SequenceEnum() - { - const SimpleMatcherFactory create(this); - - AddMatchers({ - create.Keyword("enum"), - create.Optional(create.And({ - create.Char('('), - create.Integer().Capture(CAPTURE_RESERVED_COUNT), - create.Char(')') - })), - create.Identifier().Capture(CAPTURE_NAME), - create.Char('{') - }); +namespace sdd::def_scope_sequences { +class SequenceEnum final : public StructuredDataDefParser::sequence_t { + static constexpr auto CAPTURE_NAME = 1; + static constexpr auto CAPTURE_RESERVED_COUNT = 2; + +public: + SequenceEnum() { + const SimpleMatcherFactory create(this); + + AddMatchers({create.Keyword("enum"), create.Optional(create.And({create.Char('('), create.Integer().Capture(CAPTURE_RESERVED_COUNT), create.Char(')')})), + create.Identifier().Capture(CAPTURE_NAME), create.Char('{')}); + } + +protected: + void ProcessMatch(StructuredDataDefParserState *state, SequenceResult<SimpleParserValue> &result) const override { + assert(state->m_current_def); + + const auto &nameToken = result.NextCapture(CAPTURE_NAME); + auto newEnum = std::make_unique<CommonStructuredDataEnum>(nameToken.IdentifierValue()); + const auto newEnumIndex = state->m_current_def->m_enums.size(); + if (result.HasNextCapture(CAPTURE_RESERVED_COUNT)) { + const auto &reservedCountToken = result.NextCapture(CAPTURE_RESERVED_COUNT); + newEnum->m_reserved_entry_count = reservedCountToken.IntegerValue(); + + if (newEnum->m_reserved_entry_count <= 0) + throw ParsingException(reservedCountToken.GetPos(), "Reserved enum entry count must be greater than zero"); + } + + const auto existingType = state->m_def_types_by_name.find(newEnum->m_name); + if (existingType != state->m_def_types_by_name.end()) { + if (existingType->second.m_category == CommonStructuredDataTypeCategory::UNKNOWN) { + assert(existingType->second.m_info.type_index < state->m_undefined_types.size()); + auto &undefinedType = state->m_undefined_types[existingType->second.m_info.type_index]; + undefinedType.m_mapped_type = CommonStructuredDataType(CommonStructuredDataTypeCategory::ENUM, newEnumIndex); + existingType->second = undefinedType.m_mapped_type; + } else + throw ParsingException(nameToken.GetPos(), "Type with this name has already been defined"); + } else + state->m_def_types_by_name.emplace(newEnum->m_name, CommonStructuredDataType(CommonStructuredDataTypeCategory::ENUM, newEnumIndex)); + + state->m_current_enum = newEnum.get(); + state->m_current_def->m_enums.emplace_back(std::move(newEnum)); + } +}; + +class SequenceStruct final : public StructuredDataDefParser::sequence_t { + static constexpr auto CAPTURE_NAME = 1; + +public: + SequenceStruct() { + const SimpleMatcherFactory create(this); + + AddMatchers({create.Keyword("struct"), create.Identifier().Capture(CAPTURE_NAME), create.Char('{')}); + } + +protected: + void ProcessMatch(StructuredDataDefParserState *state, SequenceResult<SimpleParserValue> &result) const override { + assert(state->m_current_def); + + const auto &nameToken = result.NextCapture(CAPTURE_NAME); + auto newStruct = std::make_unique<CommonStructuredDataStruct>(nameToken.IdentifierValue()); + auto *newStructPtr = newStruct.get(); + const auto newStructIndex = state->m_current_def->m_structs.size(); + + const auto existingType = state->m_def_types_by_name.find(newStruct->m_name); + if (existingType != state->m_def_types_by_name.end()) { + if (existingType->second.m_category == CommonStructuredDataTypeCategory::UNKNOWN) { + assert(existingType->second.m_info.type_index < state->m_undefined_types.size()); + auto &undefinedType = state->m_undefined_types[existingType->second.m_info.type_index]; + undefinedType.m_mapped_type = CommonStructuredDataType(CommonStructuredDataTypeCategory::STRUCT, newStructIndex); + existingType->second = undefinedType.m_mapped_type; + } else + throw ParsingException(nameToken.GetPos(), "Type with this name has already been defined"); + } else + state->m_def_types_by_name.emplace(newStruct->m_name, CommonStructuredDataType(CommonStructuredDataTypeCategory::STRUCT, newStructIndex)); + + state->m_current_struct = newStructPtr; + state->m_current_def->m_structs.emplace_back(std::move(newStruct)); + state->m_current_struct_padding_offset = 0; + + if (newStructPtr->m_name == "root") { + state->m_current_struct_padding_offset = 64u; + state->m_current_struct_is_root = true; + state->m_current_def->m_root_type = CommonStructuredDataType(CommonStructuredDataTypeCategory::STRUCT, newStructIndex); + } else { + state->m_current_struct_is_root = false; + state->m_current_struct_padding_offset = 0; + } + } +}; + +class SequenceChecksumOverride final : public StructuredDataDefParser::sequence_t { + static constexpr auto CAPTURE_VALUE = 1; + +public: + SequenceChecksumOverride() { + const SimpleMatcherFactory create(this); + + AddMatchers({create.Keyword("checksumoverride"), create.Integer().Capture(CAPTURE_VALUE), create.Char(';')}); + } + +protected: + void ProcessMatch(StructuredDataDefParserState *state, SequenceResult<SimpleParserValue> &result) const override { + assert(state->m_current_def); + + state->m_checksum_overriden = true; + state->m_checksum_override_value = result.NextCapture(CAPTURE_VALUE).IntegerValue(); + } +}; + +class SequenceCloseScope final : public StructuredDataDefParser::sequence_t { + static constexpr auto CAPTURE_NAME = 1; + +public: + SequenceCloseScope() { + const SimpleMatcherFactory create(this); + + AddMatchers({create.Char('}')}); + } + +private: + static void CreateDefaultStructWhenNoStructsSpecified(const StructuredDataDefParserState *state) { + if (state->m_current_def->m_structs.empty()) { + state->m_current_def->m_structs.emplace_back(std::make_unique<CommonStructuredDataStruct>()); + state->m_current_def->m_root_type = CommonStructuredDataType(CommonStructuredDataTypeCategory::STRUCT, 0u); + } + } + + static void EnsureAllUsedTypesHaveBeenDefined(const StructuredDataDefParserState *state) { + for (const auto &undefinedType : state->m_undefined_types) { + if (undefinedType.m_mapped_type.m_category == CommonStructuredDataTypeCategory::UNKNOWN) { + std::ostringstream ss; + ss << "Type \"" << undefinedType.m_name << "\" has not been defined"; + throw ParsingException(undefinedType.m_first_usage_pos, ss.str()); + } + } + } + + static void ReplaceUndefinedTypeReference(const StructuredDataDefParserState *state) { + auto &def = *state->m_current_def; + + for (const auto &_struct : def.m_structs) { + for (auto &property : _struct->m_properties) { + if (property.m_type.m_category == CommonStructuredDataTypeCategory::UNKNOWN) { + assert(property.m_type.m_info.type_index < state->m_undefined_types.size()); + const auto &undefinedType = state->m_undefined_types[property.m_type.m_info.type_index]; + property.m_type = undefinedType.m_mapped_type; } - - protected: - void ProcessMatch(StructuredDataDefParserState* state, SequenceResult<SimpleParserValue>& result) const override - { - assert(state->m_current_def); - - const auto& nameToken = result.NextCapture(CAPTURE_NAME); - auto newEnum = std::make_unique<CommonStructuredDataEnum>(nameToken.IdentifierValue()); - const auto newEnumIndex = state->m_current_def->m_enums.size(); - if (result.HasNextCapture(CAPTURE_RESERVED_COUNT)) - { - const auto& reservedCountToken = result.NextCapture(CAPTURE_RESERVED_COUNT); - newEnum->m_reserved_entry_count = reservedCountToken.IntegerValue(); - - if (newEnum->m_reserved_entry_count <= 0) - throw ParsingException(reservedCountToken.GetPos(), "Reserved enum entry count must be greater than zero"); - } - - const auto existingType = state->m_def_types_by_name.find(newEnum->m_name); - if (existingType != state->m_def_types_by_name.end()) - { - if (existingType->second.m_category == CommonStructuredDataTypeCategory::UNKNOWN) - { - assert(existingType->second.m_info.type_index < state->m_undefined_types.size()); - auto& undefinedType = state->m_undefined_types[existingType->second.m_info.type_index]; - undefinedType.m_mapped_type = CommonStructuredDataType(CommonStructuredDataTypeCategory::ENUM, newEnumIndex); - existingType->second = undefinedType.m_mapped_type; - } - else - throw ParsingException(nameToken.GetPos(), "Type with this name has already been defined"); - } - else - state->m_def_types_by_name.emplace(newEnum->m_name, CommonStructuredDataType(CommonStructuredDataTypeCategory::ENUM, newEnumIndex)); - - state->m_current_enum = newEnum.get(); - state->m_current_def->m_enums.emplace_back(std::move(newEnum)); - } - }; - - class SequenceStruct final : public StructuredDataDefParser::sequence_t - { - static constexpr auto CAPTURE_NAME = 1; - - public: - SequenceStruct() - { - const SimpleMatcherFactory create(this); - - AddMatchers({ - create.Keyword("struct"), - create.Identifier().Capture(CAPTURE_NAME), - create.Char('{') - }); - } - - protected: - void ProcessMatch(StructuredDataDefParserState* state, SequenceResult<SimpleParserValue>& result) const override - { - assert(state->m_current_def); - - const auto& nameToken = result.NextCapture(CAPTURE_NAME); - auto newStruct = std::make_unique<CommonStructuredDataStruct>(nameToken.IdentifierValue()); - auto* newStructPtr = newStruct.get(); - const auto newStructIndex = state->m_current_def->m_structs.size(); - - const auto existingType = state->m_def_types_by_name.find(newStruct->m_name); - if (existingType != state->m_def_types_by_name.end()) - { - if (existingType->second.m_category == CommonStructuredDataTypeCategory::UNKNOWN) - { - assert(existingType->second.m_info.type_index < state->m_undefined_types.size()); - auto& undefinedType = state->m_undefined_types[existingType->second.m_info.type_index]; - undefinedType.m_mapped_type = CommonStructuredDataType(CommonStructuredDataTypeCategory::STRUCT, newStructIndex); - existingType->second = undefinedType.m_mapped_type; - } - else - throw ParsingException(nameToken.GetPos(), "Type with this name has already been defined"); - } - else - state->m_def_types_by_name.emplace(newStruct->m_name, CommonStructuredDataType(CommonStructuredDataTypeCategory::STRUCT, newStructIndex)); - - state->m_current_struct = newStructPtr; - state->m_current_def->m_structs.emplace_back(std::move(newStruct)); - state->m_current_struct_padding_offset = 0; - - if (newStructPtr->m_name == "root") - { - state->m_current_struct_padding_offset = 64u; - state->m_current_struct_is_root = true; - state->m_current_def->m_root_type = CommonStructuredDataType(CommonStructuredDataTypeCategory::STRUCT, newStructIndex); - } - else - { - state->m_current_struct_is_root = false; - state->m_current_struct_padding_offset = 0; - } - } - }; - - class SequenceChecksumOverride final : public StructuredDataDefParser::sequence_t - { - static constexpr auto CAPTURE_VALUE = 1; - - public: - SequenceChecksumOverride() - { - const SimpleMatcherFactory create(this); - - AddMatchers({ - create.Keyword("checksumoverride"), - create.Integer().Capture(CAPTURE_VALUE), - create.Char(';') - }); - } - - protected: - void ProcessMatch(StructuredDataDefParserState* state, SequenceResult<SimpleParserValue>& result) const override - { - assert(state->m_current_def); - - state->m_checksum_overriden = true; - state->m_checksum_override_value = result.NextCapture(CAPTURE_VALUE).IntegerValue(); - } - }; - - class SequenceCloseScope final : public StructuredDataDefParser::sequence_t - { - static constexpr auto CAPTURE_NAME = 1; - - public: - SequenceCloseScope() - { - const SimpleMatcherFactory create(this); - - AddMatchers({ - create.Char('}') - }); - } - - private: - static void CreateDefaultStructWhenNoStructsSpecified(const StructuredDataDefParserState* state) - { - if (state->m_current_def->m_structs.empty()) - { - state->m_current_def->m_structs.emplace_back(std::make_unique<CommonStructuredDataStruct>()); - state->m_current_def->m_root_type = CommonStructuredDataType(CommonStructuredDataTypeCategory::STRUCT, 0u); - } - } - - static void EnsureAllUsedTypesHaveBeenDefined(const StructuredDataDefParserState* state) - { - for(const auto& undefinedType : state->m_undefined_types) - { - if (undefinedType.m_mapped_type.m_category == CommonStructuredDataTypeCategory::UNKNOWN) - { - std::ostringstream ss; - ss << "Type \"" << undefinedType.m_name << "\" has not been defined"; - throw ParsingException(undefinedType.m_first_usage_pos, ss.str()); - } - } - } - - static void ReplaceUndefinedTypeReference(const StructuredDataDefParserState* state) - { - auto& def = *state->m_current_def; - - for(const auto& _struct : def.m_structs) - { - for(auto& property : _struct->m_properties) - { - if(property.m_type.m_category == CommonStructuredDataTypeCategory::UNKNOWN) - { - assert(property.m_type.m_info.type_index < state->m_undefined_types.size()); - const auto& undefinedType = state->m_undefined_types[property.m_type.m_info.type_index]; - property.m_type = undefinedType.m_mapped_type; - } - } - } - - for(auto& indexedArray : def.m_indexed_arrays) - { - if(indexedArray.m_array_type.m_category == CommonStructuredDataTypeCategory::UNKNOWN) - { - assert(indexedArray.m_array_type.m_info.type_index < state->m_undefined_types.size()); - const auto& undefinedType = state->m_undefined_types[indexedArray.m_array_type.m_info.type_index]; - indexedArray.m_array_type = undefinedType.m_mapped_type; - } - } - - for(auto& enumedArray : def.m_enumed_arrays) - { - if(enumedArray.m_array_type.m_category == CommonStructuredDataTypeCategory::UNKNOWN) - { - assert(enumedArray.m_array_type.m_info.type_index < state->m_undefined_types.size()); - const auto& undefinedType = state->m_undefined_types[enumedArray.m_array_type.m_info.type_index]; - enumedArray.m_array_type = undefinedType.m_mapped_type; - } - } - } - - static void CalculateSizesAndOffsetsForDef(const StructuredDataDefParserState* state) - { - try - { - StructuredDataDefSizeCalculator::CalculateSizesAndOffsetsForDef(*state->m_current_def); - } - catch(SizeCalculationException& e) - { - throw ParsingException(TokenPos(), e.Message()); - } - } - - static void SetDefSizeFromRootStruct(const StructuredDataDefParserState* state) - { - if (state->m_current_def->m_root_type.m_category == CommonStructuredDataTypeCategory::STRUCT - && state->m_current_def->m_root_type.m_info.type_index < state->m_current_def->m_structs.size()) - { - const auto* _struct = state->m_current_def->m_structs[state->m_current_def->m_root_type.m_info.type_index].get(); - state->m_current_def->m_size_in_byte = _struct->m_size_in_byte; - } - } - - protected: - void ProcessMatch(StructuredDataDefParserState* state, SequenceResult<SimpleParserValue>& result) const override - { - assert(state->m_current_enum == nullptr); - assert(state->m_current_struct == nullptr); - - CreateDefaultStructWhenNoStructsSpecified(state); - EnsureAllUsedTypesHaveBeenDefined(state); - ReplaceUndefinedTypeReference(state); - CalculateSizesAndOffsetsForDef(state); - SetDefSizeFromRootStruct(state); - - if (!state->m_checksum_overriden) - state->m_current_def->m_checksum = state->m_current_def->CalculateChecksum(); - else - state->m_current_def->m_checksum = state->m_checksum_override_value; - - state->m_current_def = nullptr; - state->m_def_types_by_name.clear(); - state->m_def_indexed_arrays.clear(); - state->m_def_enumed_arrays.clear(); - state->m_checksum_overriden = false; - state->m_checksum_override_value = 0u; - } - }; -} + } + } + + for (auto &indexedArray : def.m_indexed_arrays) { + if (indexedArray.m_array_type.m_category == CommonStructuredDataTypeCategory::UNKNOWN) { + assert(indexedArray.m_array_type.m_info.type_index < state->m_undefined_types.size()); + const auto &undefinedType = state->m_undefined_types[indexedArray.m_array_type.m_info.type_index]; + indexedArray.m_array_type = undefinedType.m_mapped_type; + } + } + + for (auto &enumedArray : def.m_enumed_arrays) { + if (enumedArray.m_array_type.m_category == CommonStructuredDataTypeCategory::UNKNOWN) { + assert(enumedArray.m_array_type.m_info.type_index < state->m_undefined_types.size()); + const auto &undefinedType = state->m_undefined_types[enumedArray.m_array_type.m_info.type_index]; + enumedArray.m_array_type = undefinedType.m_mapped_type; + } + } + } + + static void CalculateSizesAndOffsetsForDef(const StructuredDataDefParserState *state) { + try { + StructuredDataDefSizeCalculator::CalculateSizesAndOffsetsForDef(*state->m_current_def); + } catch (SizeCalculationException &e) { + throw ParsingException(TokenPos(), e.Message()); + } + } + + static void SetDefSizeFromRootStruct(const StructuredDataDefParserState *state) { + if (state->m_current_def->m_root_type.m_category == CommonStructuredDataTypeCategory::STRUCT && + state->m_current_def->m_root_type.m_info.type_index < state->m_current_def->m_structs.size()) { + const auto *_struct = state->m_current_def->m_structs[state->m_current_def->m_root_type.m_info.type_index].get(); + state->m_current_def->m_size_in_byte = _struct->m_size_in_byte; + } + } + +protected: + void ProcessMatch(StructuredDataDefParserState *state, SequenceResult<SimpleParserValue> &result) const override { + assert(state->m_current_enum == nullptr); + assert(state->m_current_struct == nullptr); + + CreateDefaultStructWhenNoStructsSpecified(state); + EnsureAllUsedTypesHaveBeenDefined(state); + ReplaceUndefinedTypeReference(state); + CalculateSizesAndOffsetsForDef(state); + SetDefSizeFromRootStruct(state); + + if (!state->m_checksum_overriden) + state->m_current_def->m_checksum = state->m_current_def->CalculateChecksum(); + else + state->m_current_def->m_checksum = state->m_checksum_override_value; + + state->m_current_def = nullptr; + state->m_def_types_by_name.clear(); + state->m_def_indexed_arrays.clear(); + state->m_def_enumed_arrays.clear(); + state->m_checksum_overriden = false; + state->m_checksum_override_value = 0u; + } +}; +} // namespace sdd::def_scope_sequences using namespace sdd; using namespace def_scope_sequences; -StructuredDataDefScopeSequences::StructuredDataDefScopeSequences(std::vector<std::unique_ptr<StructuredDataDefParser::sequence_t>>& allSequences, - std::vector<StructuredDataDefParser::sequence_t*>& scopeSequences) - : AbstractScopeSequenceHolder(allSequences, scopeSequences) -{ -} +StructuredDataDefScopeSequences::StructuredDataDefScopeSequences(std::vector<std::unique_ptr<StructuredDataDefParser::sequence_t>> &allSequences, + std::vector<StructuredDataDefParser::sequence_t *> &scopeSequences) + : AbstractScopeSequenceHolder(allSequences, scopeSequences) {} -void StructuredDataDefScopeSequences::AddSequences() const -{ - AddSequence(std::make_unique<SequenceCloseScope>()); - AddSequence(std::make_unique<SequenceEnum>()); - AddSequence(std::make_unique<SequenceStruct>()); - AddSequence(std::make_unique<SequenceChecksumOverride>()); +void StructuredDataDefScopeSequences::AddSequences() const { + AddSequence(std::make_unique<SequenceCloseScope>()); + AddSequence(std::make_unique<SequenceEnum>()); + AddSequence(std::make_unique<SequenceStruct>()); + AddSequence(std::make_unique<SequenceChecksumOverride>()); } diff --git a/src/ObjLoading/StructuredDataDef/Parsing/Sequence/StructuredDataDefScopeSequences.h b/src/ObjLoading/StructuredDataDef/Parsing/Sequence/StructuredDataDefScopeSequences.h index 7ca944271..eb40bba0d 100644 --- a/src/ObjLoading/StructuredDataDef/Parsing/Sequence/StructuredDataDefScopeSequences.h +++ b/src/ObjLoading/StructuredDataDef/Parsing/Sequence/StructuredDataDefScopeSequences.h @@ -3,13 +3,12 @@ #include "Parsing/Sequence/AbstractScopeSequenceHolder.h" #include "StructuredDataDef/Parsing/StructuredDataDefParser.h" -namespace sdd -{ - class StructuredDataDefScopeSequences final : AbstractScopeSequenceHolder<StructuredDataDefParser> - { - public: - StructuredDataDefScopeSequences(std::vector<std::unique_ptr<StructuredDataDefParser::sequence_t>>& allSequences, std::vector<StructuredDataDefParser::sequence_t*>& scopeSequences); +namespace sdd { +class StructuredDataDefScopeSequences final : AbstractScopeSequenceHolder<StructuredDataDefParser> { +public: + StructuredDataDefScopeSequences(std::vector<std::unique_ptr<StructuredDataDefParser::sequence_t>> &allSequences, + std::vector<StructuredDataDefParser::sequence_t *> &scopeSequences); - void AddSequences() const; - }; -} + void AddSequences() const; +}; +} // namespace sdd diff --git a/src/ObjLoading/StructuredDataDef/Parsing/Sequence/StructuredDataEnumScopeSequences.cpp b/src/ObjLoading/StructuredDataDef/Parsing/Sequence/StructuredDataEnumScopeSequences.cpp index 4e6153eb2..e36538e35 100644 --- a/src/ObjLoading/StructuredDataDef/Parsing/Sequence/StructuredDataEnumScopeSequences.cpp +++ b/src/ObjLoading/StructuredDataDef/Parsing/Sequence/StructuredDataEnumScopeSequences.cpp @@ -4,72 +4,54 @@ #include "Parsing/Simple/Matcher/SimpleMatcherFactory.h" -namespace sdd::enum_scope_sequences -{ - class SequenceEnumEntry final : public StructuredDataDefParser::sequence_t - { - static constexpr auto CAPTURE_ENTRY_VALUE = 1; - - public: - SequenceEnumEntry() - { - const SimpleMatcherFactory create(this); - - AddMatchers({ - create.String().Capture(CAPTURE_ENTRY_VALUE), - create.Or({ - create.Char(','), - create.Char('}').NoConsume() - }) - }); - } - - protected: - void ProcessMatch(StructuredDataDefParserState* state, SequenceResult<SimpleParserValue>& result) const override - { - assert(state->m_current_enum); - - const auto& entryValueToken = result.NextCapture(CAPTURE_ENTRY_VALUE); - if (state->m_current_enum->m_reserved_entry_count > 0 && static_cast<size_t>(state->m_current_enum->m_reserved_entry_count) <= state->m_current_enum->m_entries.size()) - throw ParsingException(entryValueToken.GetPos(), "Enum entry count exceeds reserved count"); - - state->m_current_enum->m_entries.emplace_back(entryValueToken.StringValue(), state->m_current_enum->m_entries.size()); - } - }; - - class SequenceCloseEnum final : public StructuredDataDefParser::sequence_t - { - public: - SequenceCloseEnum() - { - const SimpleMatcherFactory create(this); - - AddMatchers({ - create.Char('}'), - create.Optional(create.Char(';')) - }); - } - - protected: - void ProcessMatch(StructuredDataDefParserState* state, SequenceResult<SimpleParserValue>& result) const override - { - assert(state->m_current_enum != nullptr); - state->m_current_enum = nullptr; - } - }; -} +namespace sdd::enum_scope_sequences { +class SequenceEnumEntry final : public StructuredDataDefParser::sequence_t { + static constexpr auto CAPTURE_ENTRY_VALUE = 1; + +public: + SequenceEnumEntry() { + const SimpleMatcherFactory create(this); + + AddMatchers({create.String().Capture(CAPTURE_ENTRY_VALUE), create.Or({create.Char(','), create.Char('}').NoConsume()})}); + } + +protected: + void ProcessMatch(StructuredDataDefParserState *state, SequenceResult<SimpleParserValue> &result) const override { + assert(state->m_current_enum); + + const auto &entryValueToken = result.NextCapture(CAPTURE_ENTRY_VALUE); + if (state->m_current_enum->m_reserved_entry_count > 0 && + static_cast<size_t>(state->m_current_enum->m_reserved_entry_count) <= state->m_current_enum->m_entries.size()) + throw ParsingException(entryValueToken.GetPos(), "Enum entry count exceeds reserved count"); + + state->m_current_enum->m_entries.emplace_back(entryValueToken.StringValue(), state->m_current_enum->m_entries.size()); + } +}; + +class SequenceCloseEnum final : public StructuredDataDefParser::sequence_t { +public: + SequenceCloseEnum() { + const SimpleMatcherFactory create(this); + + AddMatchers({create.Char('}'), create.Optional(create.Char(';'))}); + } + +protected: + void ProcessMatch(StructuredDataDefParserState *state, SequenceResult<SimpleParserValue> &result) const override { + assert(state->m_current_enum != nullptr); + state->m_current_enum = nullptr; + } +}; +} // namespace sdd::enum_scope_sequences using namespace sdd; using namespace enum_scope_sequences; -StructuredDataEnumScopeSequences::StructuredDataEnumScopeSequences(std::vector<std::unique_ptr<StructuredDataDefParser::sequence_t>>& allSequences, - std::vector<StructuredDataDefParser::sequence_t*>& scopeSequences) - : AbstractScopeSequenceHolder(allSequences, scopeSequences) -{ -} +StructuredDataEnumScopeSequences::StructuredDataEnumScopeSequences(std::vector<std::unique_ptr<StructuredDataDefParser::sequence_t>> &allSequences, + std::vector<StructuredDataDefParser::sequence_t *> &scopeSequences) + : AbstractScopeSequenceHolder(allSequences, scopeSequences) {} -void StructuredDataEnumScopeSequences::AddSequences() const -{ - AddSequence(std::make_unique<SequenceCloseEnum>()); - AddSequence(std::make_unique<SequenceEnumEntry>()); +void StructuredDataEnumScopeSequences::AddSequences() const { + AddSequence(std::make_unique<SequenceCloseEnum>()); + AddSequence(std::make_unique<SequenceEnumEntry>()); } diff --git a/src/ObjLoading/StructuredDataDef/Parsing/Sequence/StructuredDataEnumScopeSequences.h b/src/ObjLoading/StructuredDataDef/Parsing/Sequence/StructuredDataEnumScopeSequences.h index 3cacf8558..6e7918a37 100644 --- a/src/ObjLoading/StructuredDataDef/Parsing/Sequence/StructuredDataEnumScopeSequences.h +++ b/src/ObjLoading/StructuredDataDef/Parsing/Sequence/StructuredDataEnumScopeSequences.h @@ -3,13 +3,12 @@ #include "Parsing/Sequence/AbstractScopeSequenceHolder.h" #include "StructuredDataDef/Parsing/StructuredDataDefParser.h" -namespace sdd -{ - class StructuredDataEnumScopeSequences final : AbstractScopeSequenceHolder<StructuredDataDefParser> - { - public: - StructuredDataEnumScopeSequences(std::vector<std::unique_ptr<StructuredDataDefParser::sequence_t>>& allSequences, std::vector<StructuredDataDefParser::sequence_t*>& scopeSequences); +namespace sdd { +class StructuredDataEnumScopeSequences final : AbstractScopeSequenceHolder<StructuredDataDefParser> { +public: + StructuredDataEnumScopeSequences(std::vector<std::unique_ptr<StructuredDataDefParser::sequence_t>> &allSequences, + std::vector<StructuredDataDefParser::sequence_t *> &scopeSequences); - void AddSequences() const; - }; -} + void AddSequences() const; +}; +} // namespace sdd diff --git a/src/ObjLoading/StructuredDataDef/Parsing/Sequence/StructuredDataNoScopeSequences.cpp b/src/ObjLoading/StructuredDataDef/Parsing/Sequence/StructuredDataNoScopeSequences.cpp index 02eaeca09..0f402101f 100644 --- a/src/ObjLoading/StructuredDataDef/Parsing/Sequence/StructuredDataNoScopeSequences.cpp +++ b/src/ObjLoading/StructuredDataDef/Parsing/Sequence/StructuredDataNoScopeSequences.cpp @@ -2,44 +2,31 @@ #include "Parsing/Simple/Matcher/SimpleMatcherFactory.h" -namespace sdd::no_scope_sequences -{ - class SequenceVersion final : public StructuredDataDefParser::sequence_t - { - static constexpr auto CAPTURE_VERSION = 1; - - public: - SequenceVersion() - { - const SimpleMatcherFactory create(this); - - AddMatchers({ - create.Keyword("version"), - create.Integer().Capture(CAPTURE_VERSION), - create.Char('{') - }); - } - - protected: - void ProcessMatch(StructuredDataDefParserState* state, SequenceResult<SimpleParserValue>& result) const override - { - auto newDef = std::make_unique<CommonStructuredDataDef>(result.NextCapture(CAPTURE_VERSION).IntegerValue()); - state->m_current_def = newDef.get(); - state->m_defs.emplace_back(std::move(newDef)); - } - }; -} +namespace sdd::no_scope_sequences { +class SequenceVersion final : public StructuredDataDefParser::sequence_t { + static constexpr auto CAPTURE_VERSION = 1; + +public: + SequenceVersion() { + const SimpleMatcherFactory create(this); + + AddMatchers({create.Keyword("version"), create.Integer().Capture(CAPTURE_VERSION), create.Char('{')}); + } + +protected: + void ProcessMatch(StructuredDataDefParserState *state, SequenceResult<SimpleParserValue> &result) const override { + auto newDef = std::make_unique<CommonStructuredDataDef>(result.NextCapture(CAPTURE_VERSION).IntegerValue()); + state->m_current_def = newDef.get(); + state->m_defs.emplace_back(std::move(newDef)); + } +}; +} // namespace sdd::no_scope_sequences using namespace sdd; using namespace no_scope_sequences; -StructuredDataNoScopeSequences::StructuredDataNoScopeSequences(std::vector<std::unique_ptr<StructuredDataDefParser::sequence_t>>& allSequences, - std::vector<StructuredDataDefParser::sequence_t*>& scopeSequences) - : AbstractScopeSequenceHolder(allSequences, scopeSequences) -{ -} +StructuredDataNoScopeSequences::StructuredDataNoScopeSequences(std::vector<std::unique_ptr<StructuredDataDefParser::sequence_t>> &allSequences, + std::vector<StructuredDataDefParser::sequence_t *> &scopeSequences) + : AbstractScopeSequenceHolder(allSequences, scopeSequences) {} -void StructuredDataNoScopeSequences::AddSequences() const -{ - AddSequence(std::make_unique<SequenceVersion>()); -} +void StructuredDataNoScopeSequences::AddSequences() const { AddSequence(std::make_unique<SequenceVersion>()); } diff --git a/src/ObjLoading/StructuredDataDef/Parsing/Sequence/StructuredDataNoScopeSequences.h b/src/ObjLoading/StructuredDataDef/Parsing/Sequence/StructuredDataNoScopeSequences.h index 52cd0a776..a5a6cafd2 100644 --- a/src/ObjLoading/StructuredDataDef/Parsing/Sequence/StructuredDataNoScopeSequences.h +++ b/src/ObjLoading/StructuredDataDef/Parsing/Sequence/StructuredDataNoScopeSequences.h @@ -3,13 +3,12 @@ #include "Parsing/Sequence/AbstractScopeSequenceHolder.h" #include "StructuredDataDef/Parsing/StructuredDataDefParser.h" -namespace sdd -{ - class StructuredDataNoScopeSequences final : AbstractScopeSequenceHolder<StructuredDataDefParser> - { - public: - StructuredDataNoScopeSequences(std::vector<std::unique_ptr<StructuredDataDefParser::sequence_t>>& allSequences, std::vector<StructuredDataDefParser::sequence_t*>& scopeSequences); +namespace sdd { +class StructuredDataNoScopeSequences final : AbstractScopeSequenceHolder<StructuredDataDefParser> { +public: + StructuredDataNoScopeSequences(std::vector<std::unique_ptr<StructuredDataDefParser::sequence_t>> &allSequences, + std::vector<StructuredDataDefParser::sequence_t *> &scopeSequences); - void AddSequences() const; - }; -} + void AddSequences() const; +}; +} // namespace sdd diff --git a/src/ObjLoading/StructuredDataDef/Parsing/Sequence/StructuredDataStructScopeSequences.cpp b/src/ObjLoading/StructuredDataDef/Parsing/Sequence/StructuredDataStructScopeSequences.cpp index 47f89265d..1cff60602 100644 --- a/src/ObjLoading/StructuredDataDef/Parsing/Sequence/StructuredDataStructScopeSequences.cpp +++ b/src/ObjLoading/StructuredDataDef/Parsing/Sequence/StructuredDataStructScopeSequences.cpp @@ -5,257 +5,207 @@ #include "Parsing/Simple/Matcher/SimpleMatcherFactory.h" #include "Utils/Alignment.h" -namespace sdd::struct_scope_sequences -{ - class SequenceStructEntry final : public StructuredDataDefParser::sequence_t - { - static constexpr auto TAG_TYPE_INT = 1; - static constexpr auto TAG_TYPE_BYTE = 2; - static constexpr auto TAG_TYPE_BOOL = 3; - static constexpr auto TAG_TYPE_FLOAT = 4; - static constexpr auto TAG_TYPE_SHORT = 5; - static constexpr auto TAG_TYPE_STRING = 6; - static constexpr auto TAG_TYPE_NAMED = 7; - - static constexpr auto CAPTURE_STRING_LENGTH = 1; - static constexpr auto CAPTURE_TYPE_NAME = 2; - static constexpr auto CAPTURE_ENTRY_NAME = 3; - static constexpr auto CAPTURE_ARRAY_SIZE = 4; - - static std::unique_ptr<matcher_t> TypeMatchers(const SimpleMatcherFactory& create) - { - return create.Or({ - create.Keyword("int").Tag(TAG_TYPE_INT), - create.Keyword("byte").Tag(TAG_TYPE_BYTE), - create.Keyword("bool").Tag(TAG_TYPE_BOOL), - create.Keyword("float").Tag(TAG_TYPE_FLOAT), - create.Keyword("short").Tag(TAG_TYPE_SHORT), - create.And({ - create.Keyword("string"), - create.Char('('), - create.Integer().Capture(CAPTURE_STRING_LENGTH), - create.Char(')') - }).Tag(TAG_TYPE_STRING), - create.Identifier().Tag(TAG_TYPE_NAMED).Capture(CAPTURE_TYPE_NAME) - }); - } - - static std::unique_ptr<matcher_t> ArrayMatchers(const SimpleMatcherFactory& create) - { - return create.And({ - create.Char('['), - create.Or({ - create.Integer().Capture(CAPTURE_ARRAY_SIZE), - create.Identifier().Capture(CAPTURE_ARRAY_SIZE) - }), - create.Char(']') - }); - } - - public: - SequenceStructEntry() - { - const SimpleMatcherFactory create(this); - - AddMatchers({ - TypeMatchers(create), - create.Identifier().Capture(CAPTURE_ENTRY_NAME), - create.OptionalLoop(ArrayMatchers(create)), - create.Char(';') - }); - } - - private: - static CommonStructuredDataType ProcessType(StructuredDataDefParserState* state, SequenceResult<SimpleParserValue>& result) - { - const auto typeTag = result.NextTag(); - - switch (typeTag) - { - case TAG_TYPE_INT: - return CommonStructuredDataType(CommonStructuredDataTypeCategory::INT); - case TAG_TYPE_BYTE: - return CommonStructuredDataType(CommonStructuredDataTypeCategory::BYTE); - case TAG_TYPE_BOOL: - return CommonStructuredDataType(CommonStructuredDataTypeCategory::BOOL); - case TAG_TYPE_FLOAT: - return CommonStructuredDataType(CommonStructuredDataTypeCategory::FLOAT); - case TAG_TYPE_SHORT: - return CommonStructuredDataType(CommonStructuredDataTypeCategory::SHORT); - case TAG_TYPE_STRING: - { - const auto& stringLengthToken = result.NextCapture(CAPTURE_STRING_LENGTH); - const auto stringLength = stringLengthToken.IntegerValue(); - - if (stringLength <= 0) - throw ParsingException(stringLengthToken.GetPos(), "String length must be greater than zero"); - - return {CommonStructuredDataTypeCategory::STRING, static_cast<size_t>(stringLength)}; - } - case TAG_TYPE_NAMED: - { - const auto& typeNameToken = result.NextCapture(CAPTURE_TYPE_NAME); - const auto typeName = typeNameToken.IdentifierValue(); - - const auto existingType = state->m_def_types_by_name.find(typeName); - if (existingType == state->m_def_types_by_name.end()) - { - const auto undefinedTypeIndex = state->m_undefined_types.size(); - const CommonStructuredDataType undefinedType(CommonStructuredDataTypeCategory::UNKNOWN, undefinedTypeIndex); - state->m_undefined_types.emplace_back(typeName, typeNameToken.GetPos()); - state->m_def_types_by_name.emplace(std::make_pair(typeName, undefinedType)); - return undefinedType; - } - - return existingType->second; - } - default: - throw ParsingException(TokenPos(), "Invalid Tag for Type @ ProcessType!!!"); - } - } - - static CommonStructuredDataType ProcessArray(StructuredDataDefParserState* state, const SimpleParserValue& arrayToken, const CommonStructuredDataType currentType) - { - if (arrayToken.m_type == SimpleParserValueType::INTEGER) - { - const auto arrayElementCount = arrayToken.IntegerValue(); - - if (arrayElementCount <= 0) - throw ParsingException(arrayToken.GetPos(), "Array size must be greater than zero"); - - const CommonStructuredDataIndexedArray indexedArray(currentType, arrayElementCount); - - const auto existingIndexedArray = state->m_def_indexed_arrays.find(indexedArray); - if (existingIndexedArray != state->m_def_indexed_arrays.end()) - return {CommonStructuredDataTypeCategory::INDEXED_ARRAY, existingIndexedArray->second}; - - const auto newIndexedArrayIndex = state->m_current_def->m_indexed_arrays.size(); - state->m_current_def->m_indexed_arrays.push_back(indexedArray); - return {CommonStructuredDataTypeCategory::INDEXED_ARRAY, newIndexedArrayIndex}; - } - - if (arrayToken.m_type == SimpleParserValueType::IDENTIFIER) - { - const auto enumName = arrayToken.IdentifierValue(); - - const auto existingType = state->m_def_types_by_name.find(enumName); - if (existingType == state->m_def_types_by_name.end()) - throw ParsingException(arrayToken.GetPos(), "No type defined under this name"); - if (existingType->second.m_category != CommonStructuredDataTypeCategory::ENUM) - throw ParsingException(arrayToken.GetPos(), "Type for enumed array must be an enum"); - - assert(existingType->second.m_info.type_index < state->m_current_def->m_enums.size()); - const auto* _enum = state->m_current_def->m_enums[existingType->second.m_info.type_index].get(); - - const auto enumElementCount = _enum->ElementCount(); - assert(enumElementCount > 0); - - const CommonStructuredDataEnumedArray enumedArray(currentType, existingType->second.m_info.type_index, _enum->ElementCount()); - - const auto existingEnumedArray = state->m_def_enumed_arrays.find(enumedArray); - if (existingEnumedArray != state->m_def_enumed_arrays.end()) - return {CommonStructuredDataTypeCategory::ENUM_ARRAY, existingEnumedArray->second}; - - const auto newEnumedArrayIndex = state->m_current_def->m_enumed_arrays.size(); - state->m_current_def->m_enumed_arrays.push_back(enumedArray); - return {CommonStructuredDataTypeCategory::ENUM_ARRAY, newEnumedArrayIndex}; - } - - throw ParsingException(arrayToken.GetPos(), "Invalid Token for Array @ ProcessArray!!!"); - } - - protected: - void ProcessMatch(StructuredDataDefParserState* state, SequenceResult<SimpleParserValue>& result) const override - { - assert(state->m_current_def != nullptr); - assert(state->m_current_struct != nullptr); - - auto currentType = ProcessType(state, result); - - std::vector<std::reference_wrapper<const SimpleParserValue>> arrayTokens; - while (result.HasNextCapture(CAPTURE_ARRAY_SIZE)) - arrayTokens.emplace_back(result.NextCapture(CAPTURE_ARRAY_SIZE)); - - for (auto i = arrayTokens.rbegin(); i != arrayTokens.rend(); ++i) - currentType = ProcessArray(state, i->get(), currentType); - - state->m_current_struct->m_properties.emplace_back(result.NextCapture(CAPTURE_ENTRY_NAME).IdentifierValue(), currentType, state->m_current_struct_padding_offset); - } - }; - - class SequencePadding final : public StructuredDataDefParser::sequence_t - { - static constexpr auto CAPTURE_PADDING_VALUE = 1; - - public: - SequencePadding() - { - const SimpleMatcherFactory create(this); - - AddMatchers({ - create.Keyword("pad"), - create.Char('('), - create.Integer().Capture(CAPTURE_PADDING_VALUE), - create.Char(')'), - create.Char(';') - }); - } - - protected: - void ProcessMatch(StructuredDataDefParserState* state, SequenceResult<SimpleParserValue>& result) const override - { - const auto& paddingValueToken = result.NextCapture(CAPTURE_PADDING_VALUE); - const auto paddingValue = paddingValueToken.IntegerValue(); - - if (paddingValue <= 0) - throw ParsingException(paddingValueToken.GetPos(), "Padding value must be greater than 0"); - - state->m_current_struct_padding_offset += paddingValue * 8; - } - }; - - class SequenceCloseStruct final : public StructuredDataDefParser::sequence_t - { - public: - SequenceCloseStruct() - { - const SimpleMatcherFactory create(this); - - AddMatchers({ - create.Char('}'), - create.Optional(create.Char(';')) - }); - } - - protected: - void ProcessMatch(StructuredDataDefParserState* state, SequenceResult<SimpleParserValue>& result) const override - { - assert(state->m_current_struct != nullptr); - - // Only include root struct offset of 8 byte when root struct is not empty - if (state->m_current_struct_is_root && state->m_current_struct->m_properties.empty()) - state->m_current_struct_padding_offset -= 64u; - - state->m_current_struct->m_size_in_byte = utils::Align(state->m_current_struct_padding_offset, 8u) / 8; - state->m_current_struct_padding_offset = 0u; - state->m_current_struct_is_root = false; - state->m_current_struct = nullptr; - } - }; -} +namespace sdd::struct_scope_sequences { +class SequenceStructEntry final : public StructuredDataDefParser::sequence_t { + static constexpr auto TAG_TYPE_INT = 1; + static constexpr auto TAG_TYPE_BYTE = 2; + static constexpr auto TAG_TYPE_BOOL = 3; + static constexpr auto TAG_TYPE_FLOAT = 4; + static constexpr auto TAG_TYPE_SHORT = 5; + static constexpr auto TAG_TYPE_STRING = 6; + static constexpr auto TAG_TYPE_NAMED = 7; + + static constexpr auto CAPTURE_STRING_LENGTH = 1; + static constexpr auto CAPTURE_TYPE_NAME = 2; + static constexpr auto CAPTURE_ENTRY_NAME = 3; + static constexpr auto CAPTURE_ARRAY_SIZE = 4; + + static std::unique_ptr<matcher_t> TypeMatchers(const SimpleMatcherFactory &create) { + return create.Or( + {create.Keyword("int").Tag(TAG_TYPE_INT), create.Keyword("byte").Tag(TAG_TYPE_BYTE), create.Keyword("bool").Tag(TAG_TYPE_BOOL), + create.Keyword("float").Tag(TAG_TYPE_FLOAT), create.Keyword("short").Tag(TAG_TYPE_SHORT), + create.And({create.Keyword("string"), create.Char('('), create.Integer().Capture(CAPTURE_STRING_LENGTH), create.Char(')')}).Tag(TAG_TYPE_STRING), + create.Identifier().Tag(TAG_TYPE_NAMED).Capture(CAPTURE_TYPE_NAME)}); + } + + static std::unique_ptr<matcher_t> ArrayMatchers(const SimpleMatcherFactory &create) { + return create.And( + {create.Char('['), create.Or({create.Integer().Capture(CAPTURE_ARRAY_SIZE), create.Identifier().Capture(CAPTURE_ARRAY_SIZE)}), create.Char(']')}); + } + +public: + SequenceStructEntry() { + const SimpleMatcherFactory create(this); + + AddMatchers({TypeMatchers(create), create.Identifier().Capture(CAPTURE_ENTRY_NAME), create.OptionalLoop(ArrayMatchers(create)), create.Char(';')}); + } + +private: + static CommonStructuredDataType ProcessType(StructuredDataDefParserState *state, SequenceResult<SimpleParserValue> &result) { + const auto typeTag = result.NextTag(); + + switch (typeTag) { + case TAG_TYPE_INT: + return CommonStructuredDataType(CommonStructuredDataTypeCategory::INT); + case TAG_TYPE_BYTE: + return CommonStructuredDataType(CommonStructuredDataTypeCategory::BYTE); + case TAG_TYPE_BOOL: + return CommonStructuredDataType(CommonStructuredDataTypeCategory::BOOL); + case TAG_TYPE_FLOAT: + return CommonStructuredDataType(CommonStructuredDataTypeCategory::FLOAT); + case TAG_TYPE_SHORT: + return CommonStructuredDataType(CommonStructuredDataTypeCategory::SHORT); + case TAG_TYPE_STRING: { + const auto &stringLengthToken = result.NextCapture(CAPTURE_STRING_LENGTH); + const auto stringLength = stringLengthToken.IntegerValue(); + + if (stringLength <= 0) + throw ParsingException(stringLengthToken.GetPos(), "String length must be greater than zero"); + + return {CommonStructuredDataTypeCategory::STRING, static_cast<size_t>(stringLength)}; + } + case TAG_TYPE_NAMED: { + const auto &typeNameToken = result.NextCapture(CAPTURE_TYPE_NAME); + const auto typeName = typeNameToken.IdentifierValue(); + + const auto existingType = state->m_def_types_by_name.find(typeName); + if (existingType == state->m_def_types_by_name.end()) { + const auto undefinedTypeIndex = state->m_undefined_types.size(); + const CommonStructuredDataType undefinedType(CommonStructuredDataTypeCategory::UNKNOWN, undefinedTypeIndex); + state->m_undefined_types.emplace_back(typeName, typeNameToken.GetPos()); + state->m_def_types_by_name.emplace(std::make_pair(typeName, undefinedType)); + return undefinedType; + } + + return existingType->second; + } + default: + throw ParsingException(TokenPos(), "Invalid Tag for Type @ ProcessType!!!"); + } + } + + static CommonStructuredDataType ProcessArray(StructuredDataDefParserState *state, const SimpleParserValue &arrayToken, + const CommonStructuredDataType currentType) { + if (arrayToken.m_type == SimpleParserValueType::INTEGER) { + const auto arrayElementCount = arrayToken.IntegerValue(); + + if (arrayElementCount <= 0) + throw ParsingException(arrayToken.GetPos(), "Array size must be greater than zero"); + + const CommonStructuredDataIndexedArray indexedArray(currentType, arrayElementCount); + + const auto existingIndexedArray = state->m_def_indexed_arrays.find(indexedArray); + if (existingIndexedArray != state->m_def_indexed_arrays.end()) + return {CommonStructuredDataTypeCategory::INDEXED_ARRAY, existingIndexedArray->second}; + + const auto newIndexedArrayIndex = state->m_current_def->m_indexed_arrays.size(); + state->m_current_def->m_indexed_arrays.push_back(indexedArray); + return {CommonStructuredDataTypeCategory::INDEXED_ARRAY, newIndexedArrayIndex}; + } + + if (arrayToken.m_type == SimpleParserValueType::IDENTIFIER) { + const auto enumName = arrayToken.IdentifierValue(); + + const auto existingType = state->m_def_types_by_name.find(enumName); + if (existingType == state->m_def_types_by_name.end()) + throw ParsingException(arrayToken.GetPos(), "No type defined under this name"); + if (existingType->second.m_category != CommonStructuredDataTypeCategory::ENUM) + throw ParsingException(arrayToken.GetPos(), "Type for enumed array must be an enum"); + + assert(existingType->second.m_info.type_index < state->m_current_def->m_enums.size()); + const auto *_enum = state->m_current_def->m_enums[existingType->second.m_info.type_index].get(); + + const auto enumElementCount = _enum->ElementCount(); + assert(enumElementCount > 0); + + const CommonStructuredDataEnumedArray enumedArray(currentType, existingType->second.m_info.type_index, _enum->ElementCount()); + + const auto existingEnumedArray = state->m_def_enumed_arrays.find(enumedArray); + if (existingEnumedArray != state->m_def_enumed_arrays.end()) + return {CommonStructuredDataTypeCategory::ENUM_ARRAY, existingEnumedArray->second}; + + const auto newEnumedArrayIndex = state->m_current_def->m_enumed_arrays.size(); + state->m_current_def->m_enumed_arrays.push_back(enumedArray); + return {CommonStructuredDataTypeCategory::ENUM_ARRAY, newEnumedArrayIndex}; + } + + throw ParsingException(arrayToken.GetPos(), "Invalid Token for Array @ ProcessArray!!!"); + } + +protected: + void ProcessMatch(StructuredDataDefParserState *state, SequenceResult<SimpleParserValue> &result) const override { + assert(state->m_current_def != nullptr); + assert(state->m_current_struct != nullptr); + + auto currentType = ProcessType(state, result); + + std::vector<std::reference_wrapper<const SimpleParserValue>> arrayTokens; + while (result.HasNextCapture(CAPTURE_ARRAY_SIZE)) + arrayTokens.emplace_back(result.NextCapture(CAPTURE_ARRAY_SIZE)); + + for (auto i = arrayTokens.rbegin(); i != arrayTokens.rend(); ++i) + currentType = ProcessArray(state, i->get(), currentType); + + state->m_current_struct->m_properties.emplace_back(result.NextCapture(CAPTURE_ENTRY_NAME).IdentifierValue(), currentType, + state->m_current_struct_padding_offset); + } +}; + +class SequencePadding final : public StructuredDataDefParser::sequence_t { + static constexpr auto CAPTURE_PADDING_VALUE = 1; + +public: + SequencePadding() { + const SimpleMatcherFactory create(this); + + AddMatchers({create.Keyword("pad"), create.Char('('), create.Integer().Capture(CAPTURE_PADDING_VALUE), create.Char(')'), create.Char(';')}); + } + +protected: + void ProcessMatch(StructuredDataDefParserState *state, SequenceResult<SimpleParserValue> &result) const override { + const auto &paddingValueToken = result.NextCapture(CAPTURE_PADDING_VALUE); + const auto paddingValue = paddingValueToken.IntegerValue(); + + if (paddingValue <= 0) + throw ParsingException(paddingValueToken.GetPos(), "Padding value must be greater than 0"); + + state->m_current_struct_padding_offset += paddingValue * 8; + } +}; + +class SequenceCloseStruct final : public StructuredDataDefParser::sequence_t { +public: + SequenceCloseStruct() { + const SimpleMatcherFactory create(this); + + AddMatchers({create.Char('}'), create.Optional(create.Char(';'))}); + } + +protected: + void ProcessMatch(StructuredDataDefParserState *state, SequenceResult<SimpleParserValue> &result) const override { + assert(state->m_current_struct != nullptr); + + // Only include root struct offset of 8 byte when root struct is not empty + if (state->m_current_struct_is_root && state->m_current_struct->m_properties.empty()) + state->m_current_struct_padding_offset -= 64u; + + state->m_current_struct->m_size_in_byte = utils::Align(state->m_current_struct_padding_offset, 8u) / 8; + state->m_current_struct_padding_offset = 0u; + state->m_current_struct_is_root = false; + state->m_current_struct = nullptr; + } +}; +} // namespace sdd::struct_scope_sequences using namespace sdd; using namespace struct_scope_sequences; -StructuredDataStructScopeSequences::StructuredDataStructScopeSequences(std::vector<std::unique_ptr<StructuredDataDefParser::sequence_t>>& allSequences, - std::vector<StructuredDataDefParser::sequence_t*>& scopeSequences) - : AbstractScopeSequenceHolder(allSequences, scopeSequences) -{ -} +StructuredDataStructScopeSequences::StructuredDataStructScopeSequences(std::vector<std::unique_ptr<StructuredDataDefParser::sequence_t>> &allSequences, + std::vector<StructuredDataDefParser::sequence_t *> &scopeSequences) + : AbstractScopeSequenceHolder(allSequences, scopeSequences) {} -void StructuredDataStructScopeSequences::AddSequences() const -{ - AddSequence(std::make_unique<SequenceCloseStruct>()); - AddSequence(std::make_unique<SequencePadding>()); - AddSequence(std::make_unique<SequenceStructEntry>()); +void StructuredDataStructScopeSequences::AddSequences() const { + AddSequence(std::make_unique<SequenceCloseStruct>()); + AddSequence(std::make_unique<SequencePadding>()); + AddSequence(std::make_unique<SequenceStructEntry>()); } diff --git a/src/ObjLoading/StructuredDataDef/Parsing/Sequence/StructuredDataStructScopeSequences.h b/src/ObjLoading/StructuredDataDef/Parsing/Sequence/StructuredDataStructScopeSequences.h index c67df87cc..1b17beb00 100644 --- a/src/ObjLoading/StructuredDataDef/Parsing/Sequence/StructuredDataStructScopeSequences.h +++ b/src/ObjLoading/StructuredDataDef/Parsing/Sequence/StructuredDataStructScopeSequences.h @@ -3,13 +3,12 @@ #include "Parsing/Sequence/AbstractScopeSequenceHolder.h" #include "StructuredDataDef/Parsing/StructuredDataDefParser.h" -namespace sdd -{ - class StructuredDataStructScopeSequences final : AbstractScopeSequenceHolder<StructuredDataDefParser> - { - public: - StructuredDataStructScopeSequences(std::vector<std::unique_ptr<StructuredDataDefParser::sequence_t>>& allSequences, std::vector<StructuredDataDefParser::sequence_t*>& scopeSequences); +namespace sdd { +class StructuredDataStructScopeSequences final : AbstractScopeSequenceHolder<StructuredDataDefParser> { +public: + StructuredDataStructScopeSequences(std::vector<std::unique_ptr<StructuredDataDefParser::sequence_t>> &allSequences, + std::vector<StructuredDataDefParser::sequence_t *> &scopeSequences); - void AddSequences() const; - }; -} + void AddSequences() const; +}; +} // namespace sdd diff --git a/src/ObjLoading/StructuredDataDef/Parsing/StructuredDataDefParser.cpp b/src/ObjLoading/StructuredDataDef/Parsing/StructuredDataDefParser.cpp index 72f0951cf..0576c45fe 100644 --- a/src/ObjLoading/StructuredDataDef/Parsing/StructuredDataDefParser.cpp +++ b/src/ObjLoading/StructuredDataDef/Parsing/StructuredDataDefParser.cpp @@ -7,48 +7,41 @@ using namespace sdd; -StructuredDataDefParser::StructuredDataDefParser(SimpleLexer* lexer) - : AbstractParser(lexer, std::make_unique<StructuredDataDefParserState>()) -{ - CreateSequenceCollections(); +StructuredDataDefParser::StructuredDataDefParser(SimpleLexer *lexer) : AbstractParser(lexer, std::make_unique<StructuredDataDefParserState>()) { + CreateSequenceCollections(); } -void StructuredDataDefParser::CreateSequenceCollections() -{ - m_all_tests.clear(); - m_no_scope_tests.clear(); - m_def_tests.clear(); - m_enum_tests.clear(); - m_struct_tests.clear(); +void StructuredDataDefParser::CreateSequenceCollections() { + m_all_tests.clear(); + m_no_scope_tests.clear(); + m_def_tests.clear(); + m_enum_tests.clear(); + m_struct_tests.clear(); - const StructuredDataNoScopeSequences noScopeSequences(m_all_tests, m_no_scope_tests); - noScopeSequences.AddSequences(); + const StructuredDataNoScopeSequences noScopeSequences(m_all_tests, m_no_scope_tests); + noScopeSequences.AddSequences(); - const StructuredDataDefScopeSequences defScopeSequences(m_all_tests, m_def_tests); - defScopeSequences.AddSequences(); + const StructuredDataDefScopeSequences defScopeSequences(m_all_tests, m_def_tests); + defScopeSequences.AddSequences(); - const StructuredDataEnumScopeSequences enumScopeSequences(m_all_tests, m_enum_tests); - enumScopeSequences.AddSequences(); + const StructuredDataEnumScopeSequences enumScopeSequences(m_all_tests, m_enum_tests); + enumScopeSequences.AddSequences(); - const StructuredDataStructScopeSequences structScopeSequences(m_all_tests, m_struct_tests); - structScopeSequences.AddSequences(); + const StructuredDataStructScopeSequences structScopeSequences(m_all_tests, m_struct_tests); + structScopeSequences.AddSequences(); } -const std::vector<StructuredDataDefParser::sequence_t*>& StructuredDataDefParser::GetTestsForState() -{ - if (!m_state->m_current_def) - return m_no_scope_tests; +const std::vector<StructuredDataDefParser::sequence_t *> &StructuredDataDefParser::GetTestsForState() { + if (!m_state->m_current_def) + return m_no_scope_tests; - if (m_state->m_current_enum) - return m_enum_tests; + if (m_state->m_current_enum) + return m_enum_tests; - if (m_state->m_current_struct) - return m_struct_tests; + if (m_state->m_current_struct) + return m_struct_tests; - return m_def_tests; + return m_def_tests; } -std::vector<std::unique_ptr<CommonStructuredDataDef>> StructuredDataDefParser::GetDefs() const -{ - return std::move(m_state->m_defs); -} +std::vector<std::unique_ptr<CommonStructuredDataDef>> StructuredDataDefParser::GetDefs() const { return std::move(m_state->m_defs); } diff --git a/src/ObjLoading/StructuredDataDef/Parsing/StructuredDataDefParser.h b/src/ObjLoading/StructuredDataDef/Parsing/StructuredDataDefParser.h index cf45b1a41..6a00a96e1 100644 --- a/src/ObjLoading/StructuredDataDef/Parsing/StructuredDataDefParser.h +++ b/src/ObjLoading/StructuredDataDef/Parsing/StructuredDataDefParser.h @@ -1,29 +1,27 @@ #pragma once -#include "Utils/ClassUtils.h" -#include "StructuredDataDefParserState.h" -#include "StructuredDataDef/CommonStructuredDataDef.h" +#include "Parsing/Impl/AbstractParser.h" #include "Parsing/Simple/SimpleLexer.h" #include "Parsing/Simple/SimpleParserValue.h" -#include "Parsing/Impl/AbstractParser.h" +#include "StructuredDataDef/CommonStructuredDataDef.h" +#include "StructuredDataDefParserState.h" +#include "Utils/ClassUtils.h" + +namespace sdd { +class StructuredDataDefParser final : public AbstractParser<SimpleParserValue, StructuredDataDefParserState> { + std::vector<std::unique_ptr<sequence_t>> m_all_tests; + std::vector<sequence_t *> m_no_scope_tests; + std::vector<sequence_t *> m_def_tests; + std::vector<sequence_t *> m_enum_tests; + std::vector<sequence_t *> m_struct_tests; -namespace sdd -{ - class StructuredDataDefParser final : public AbstractParser<SimpleParserValue, StructuredDataDefParserState> - { - std::vector<std::unique_ptr<sequence_t>> m_all_tests; - std::vector<sequence_t*> m_no_scope_tests; - std::vector<sequence_t*> m_def_tests; - std::vector<sequence_t*> m_enum_tests; - std::vector<sequence_t*> m_struct_tests; - - void CreateSequenceCollections(); + void CreateSequenceCollections(); - protected: - const std::vector<sequence_t*>& GetTestsForState() override; +protected: + const std::vector<sequence_t *> &GetTestsForState() override; - public: - explicit StructuredDataDefParser(SimpleLexer* lexer); - _NODISCARD std::vector<std::unique_ptr<CommonStructuredDataDef>> GetDefs() const; - }; -} +public: + explicit StructuredDataDefParser(SimpleLexer *lexer); + _NODISCARD std::vector<std::unique_ptr<CommonStructuredDataDef>> GetDefs() const; +}; +} // namespace sdd diff --git a/src/ObjLoading/StructuredDataDef/Parsing/StructuredDataDefParserState.cpp b/src/ObjLoading/StructuredDataDef/Parsing/StructuredDataDefParserState.cpp index 72c16d50b..7d55b69bf 100644 --- a/src/ObjLoading/StructuredDataDef/Parsing/StructuredDataDefParserState.cpp +++ b/src/ObjLoading/StructuredDataDef/Parsing/StructuredDataDefParserState.cpp @@ -2,21 +2,10 @@ using namespace sdd; -UndefinedType::UndefinedType() -= default; +UndefinedType::UndefinedType() = default; -UndefinedType::UndefinedType(std::string name, const TokenPos firstUsagePos) - : m_name(std::move(name)), - m_first_usage_pos(firstUsagePos) -{ -} +UndefinedType::UndefinedType(std::string name, const TokenPos firstUsagePos) : m_name(std::move(name)), m_first_usage_pos(firstUsagePos) {} StructuredDataDefParserState::StructuredDataDefParserState() - : m_current_def(nullptr), - m_current_enum(nullptr), - m_current_struct(nullptr), - m_current_struct_padding_offset(0u), - m_checksum_override_value(0u), - m_checksum_overriden(false) -{ -} + : m_current_def(nullptr), m_current_enum(nullptr), m_current_struct(nullptr), m_current_struct_padding_offset(0u), m_checksum_override_value(0u), + m_checksum_overriden(false) {} diff --git a/src/ObjLoading/StructuredDataDef/Parsing/StructuredDataDefParserState.h b/src/ObjLoading/StructuredDataDef/Parsing/StructuredDataDefParserState.h index 53abf4398..15d3c94a8 100644 --- a/src/ObjLoading/StructuredDataDef/Parsing/StructuredDataDefParserState.h +++ b/src/ObjLoading/StructuredDataDef/Parsing/StructuredDataDefParserState.h @@ -1,47 +1,44 @@ #pragma once +#include <cstddef> #include <map> #include <memory> -#include <vector> -#include <cstddef> #include <string> +#include <vector> #include "Parsing/TokenPos.h" #include "StructuredDataDef/CommonStructuredDataDef.h" -namespace sdd -{ - class UndefinedType - { - public: - std::string m_name; - TokenPos m_first_usage_pos; - CommonStructuredDataType m_mapped_type; - - UndefinedType(); - UndefinedType(std::string name, TokenPos firstUsagePos); - }; - - class StructuredDataDefParserState - { - public: - std::vector<std::unique_ptr<CommonStructuredDataDef>> m_defs; - - CommonStructuredDataDef* m_current_def; - CommonStructuredDataEnum* m_current_enum; - CommonStructuredDataStruct* m_current_struct; - - bool m_current_struct_is_root; - size_t m_current_struct_padding_offset; - - size_t m_checksum_override_value; - bool m_checksum_overriden; - - std::map<std::string, CommonStructuredDataType> m_def_types_by_name; - std::map<CommonStructuredDataIndexedArray, size_t> m_def_indexed_arrays; - std::map<CommonStructuredDataEnumedArray, size_t> m_def_enumed_arrays; - std::vector<UndefinedType> m_undefined_types; - - StructuredDataDefParserState(); - }; -} +namespace sdd { +class UndefinedType { +public: + std::string m_name; + TokenPos m_first_usage_pos; + CommonStructuredDataType m_mapped_type; + + UndefinedType(); + UndefinedType(std::string name, TokenPos firstUsagePos); +}; + +class StructuredDataDefParserState { +public: + std::vector<std::unique_ptr<CommonStructuredDataDef>> m_defs; + + CommonStructuredDataDef *m_current_def; + CommonStructuredDataEnum *m_current_enum; + CommonStructuredDataStruct *m_current_struct; + + bool m_current_struct_is_root; + size_t m_current_struct_padding_offset; + + size_t m_checksum_override_value; + bool m_checksum_overriden; + + std::map<std::string, CommonStructuredDataType> m_def_types_by_name; + std::map<CommonStructuredDataIndexedArray, size_t> m_def_indexed_arrays; + std::map<CommonStructuredDataEnumedArray, size_t> m_def_enumed_arrays; + std::vector<UndefinedType> m_undefined_types; + + StructuredDataDefParserState(); +}; +} // namespace sdd diff --git a/src/ObjLoading/StructuredDataDef/Parsing/StructuredDataDefSizeCalculator.cpp b/src/ObjLoading/StructuredDataDef/Parsing/StructuredDataDefSizeCalculator.cpp index 7953160f7..544f6faea 100644 --- a/src/ObjLoading/StructuredDataDef/Parsing/StructuredDataDefSizeCalculator.cpp +++ b/src/ObjLoading/StructuredDataDef/Parsing/StructuredDataDefSizeCalculator.cpp @@ -8,147 +8,118 @@ using namespace sdd; -SizeCalculationException::SizeCalculationException(std::string message) - : m_message(std::move(message)) -{ -} +SizeCalculationException::SizeCalculationException(std::string message) : m_message(std::move(message)) {} -const std::string& SizeCalculationException::Message() const -{ - return m_message; -} +const std::string &SizeCalculationException::Message() const { return m_message; } -char const* SizeCalculationException::what() const noexcept -{ - return m_message.c_str(); -} +char const *SizeCalculationException::what() const noexcept { return m_message.c_str(); } -class StructuredDataDefSizeCalculatorInternal -{ - CommonStructuredDataDef& m_def; - std::vector<CommonStructuredDataType> m_type_stack; - std::vector<bool> m_struct_in_calculation; - std::vector<bool> m_struct_calculated; - std::vector<bool> m_indexed_array_calculated; - std::vector<bool> m_enumed_array_calculated; - - _NORETURN void ThrowCircularDependencyException(const size_t structIndex) const - { - assert(structIndex < m_def.m_structs.size()); - - std::ostringstream ss; - - ss << "Circular dependencies detected: "; - - auto foundDependencyChainStart = false; - for (const auto& type : m_type_stack) - { - if (foundDependencyChainStart) - { - if (type.m_category == CommonStructuredDataTypeCategory::STRUCT) - { - assert(type.m_info.type_index < m_def.m_structs.size()); - ss << " -> " << m_def.m_structs[type.m_info.type_index]->m_name; - } - } - else if (type.m_category == CommonStructuredDataTypeCategory::STRUCT && type.m_info.type_index == structIndex) - { - foundDependencyChainStart = true; - ss << m_def.m_structs[structIndex]->m_name; - } - } +class StructuredDataDefSizeCalculatorInternal { + CommonStructuredDataDef &m_def; + std::vector<CommonStructuredDataType> m_type_stack; + std::vector<bool> m_struct_in_calculation; + std::vector<bool> m_struct_calculated; + std::vector<bool> m_indexed_array_calculated; + std::vector<bool> m_enumed_array_calculated; - ss << " -> " << m_def.m_structs[structIndex]->m_name; + _NORETURN void ThrowCircularDependencyException(const size_t structIndex) const { + assert(structIndex < m_def.m_structs.size()); - throw SizeCalculationException(ss.str()); - } + std::ostringstream ss; - void CalculateForStruct(const size_t index, CommonStructuredDataStruct& _struct) - { - if (m_struct_calculated[index]) - return; + ss << "Circular dependencies detected: "; - if (m_struct_in_calculation[index]) - ThrowCircularDependencyException(index); - m_struct_in_calculation[index] = true; + auto foundDependencyChainStart = false; + for (const auto &type : m_type_stack) { + if (foundDependencyChainStart) { + if (type.m_category == CommonStructuredDataTypeCategory::STRUCT) { + assert(type.m_info.type_index < m_def.m_structs.size()); + ss << " -> " << m_def.m_structs[type.m_info.type_index]->m_name; + } + } else if (type.m_category == CommonStructuredDataTypeCategory::STRUCT && type.m_info.type_index == structIndex) { + foundDependencyChainStart = true; + ss << m_def.m_structs[structIndex]->m_name; + } + } - m_type_stack.emplace_back(CommonStructuredDataTypeCategory::STRUCT, index); + ss << " -> " << m_def.m_structs[structIndex]->m_name; - auto currentOffset = 0u; - for (auto& property : _struct.m_properties) - { - CalculateForType(property.m_type); - currentOffset = utils::Align(currentOffset, property.m_type.GetAlignmentInBits()); + throw SizeCalculationException(ss.str()); + } - // Currently set offset is the padding since the start of the struct - property.m_offset_in_bits += currentOffset; + void CalculateForStruct(const size_t index, CommonStructuredDataStruct &_struct) { + if (m_struct_calculated[index]) + return; - currentOffset += property.m_type.GetSizeInBits(m_def); - } - currentOffset = utils::Align(currentOffset, 8u); - _struct.m_size_in_byte += currentOffset / 8; + if (m_struct_in_calculation[index]) + ThrowCircularDependencyException(index); + m_struct_in_calculation[index] = true; - m_struct_calculated[index] = true; - m_type_stack.pop_back(); - } + m_type_stack.emplace_back(CommonStructuredDataTypeCategory::STRUCT, index); - void CalculateForIndexedArray(CommonStructuredDataIndexedArray& indexedArray) - { - CalculateForType(indexedArray.m_array_type); - indexedArray.m_element_size_in_bits = indexedArray.m_array_type.GetSizeInBits(m_def); - } + auto currentOffset = 0u; + for (auto &property : _struct.m_properties) { + CalculateForType(property.m_type); + currentOffset = utils::Align(currentOffset, property.m_type.GetAlignmentInBits()); - void CalculateForEnumedArray(CommonStructuredDataEnumedArray& enumedArray) - { - CalculateForType(enumedArray.m_array_type); - enumedArray.m_element_size_in_bits = enumedArray.m_array_type.GetSizeInBits(m_def); - } + // Currently set offset is the padding since the start of the struct + property.m_offset_in_bits += currentOffset; - void CalculateForType(const CommonStructuredDataType type) - { - switch (type.m_category) - { - case CommonStructuredDataTypeCategory::STRUCT: - assert(type.m_info.type_index < m_def.m_structs.size()); - CalculateForStruct(type.m_info.type_index, *m_def.m_structs[type.m_info.type_index]); - break; - case CommonStructuredDataTypeCategory::INDEXED_ARRAY: - assert(type.m_info.type_index < m_def.m_indexed_arrays.size()); - CalculateForIndexedArray(m_def.m_indexed_arrays[type.m_info.type_index]); - break; - case CommonStructuredDataTypeCategory::ENUM_ARRAY: - assert(type.m_info.type_index < m_def.m_enumed_arrays.size()); - CalculateForEnumedArray(m_def.m_enumed_arrays[type.m_info.type_index]); - break; - default: - break; - } + currentOffset += property.m_type.GetSizeInBits(m_def); } - -public: - explicit StructuredDataDefSizeCalculatorInternal(CommonStructuredDataDef& def) - : m_def(def), - m_struct_in_calculation(def.m_structs.size()), - m_struct_calculated(def.m_structs.size()), - m_indexed_array_calculated(def.m_indexed_arrays.size()), - m_enumed_array_calculated(def.m_enumed_arrays.size()) - { + currentOffset = utils::Align(currentOffset, 8u); + _struct.m_size_in_byte += currentOffset / 8; + + m_struct_calculated[index] = true; + m_type_stack.pop_back(); + } + + void CalculateForIndexedArray(CommonStructuredDataIndexedArray &indexedArray) { + CalculateForType(indexedArray.m_array_type); + indexedArray.m_element_size_in_bits = indexedArray.m_array_type.GetSizeInBits(m_def); + } + + void CalculateForEnumedArray(CommonStructuredDataEnumedArray &enumedArray) { + CalculateForType(enumedArray.m_array_type); + enumedArray.m_element_size_in_bits = enumedArray.m_array_type.GetSizeInBits(m_def); + } + + void CalculateForType(const CommonStructuredDataType type) { + switch (type.m_category) { + case CommonStructuredDataTypeCategory::STRUCT: + assert(type.m_info.type_index < m_def.m_structs.size()); + CalculateForStruct(type.m_info.type_index, *m_def.m_structs[type.m_info.type_index]); + break; + case CommonStructuredDataTypeCategory::INDEXED_ARRAY: + assert(type.m_info.type_index < m_def.m_indexed_arrays.size()); + CalculateForIndexedArray(m_def.m_indexed_arrays[type.m_info.type_index]); + break; + case CommonStructuredDataTypeCategory::ENUM_ARRAY: + assert(type.m_info.type_index < m_def.m_enumed_arrays.size()); + CalculateForEnumedArray(m_def.m_enumed_arrays[type.m_info.type_index]); + break; + default: + break; } + } - void CalculateSizesAndOffsets() - { - auto index = 0u; - for (auto& _struct : m_def.m_structs) - CalculateForStruct(index++, *_struct); - for (auto& indexedArray : m_def.m_indexed_arrays) - CalculateForIndexedArray(indexedArray); - for (auto& enumedArray : m_def.m_enumed_arrays) - CalculateForEnumedArray(enumedArray); - } +public: + explicit StructuredDataDefSizeCalculatorInternal(CommonStructuredDataDef &def) + : m_def(def), m_struct_in_calculation(def.m_structs.size()), m_struct_calculated(def.m_structs.size()), + m_indexed_array_calculated(def.m_indexed_arrays.size()), m_enumed_array_calculated(def.m_enumed_arrays.size()) {} + + void CalculateSizesAndOffsets() { + auto index = 0u; + for (auto &_struct : m_def.m_structs) + CalculateForStruct(index++, *_struct); + for (auto &indexedArray : m_def.m_indexed_arrays) + CalculateForIndexedArray(indexedArray); + for (auto &enumedArray : m_def.m_enumed_arrays) + CalculateForEnumedArray(enumedArray); + } }; -void StructuredDataDefSizeCalculator::CalculateSizesAndOffsetsForDef(CommonStructuredDataDef& def) -{ - StructuredDataDefSizeCalculatorInternal calculator(def); - calculator.CalculateSizesAndOffsets(); +void StructuredDataDefSizeCalculator::CalculateSizesAndOffsetsForDef(CommonStructuredDataDef &def) { + StructuredDataDefSizeCalculatorInternal calculator(def); + calculator.CalculateSizesAndOffsets(); } diff --git a/src/ObjLoading/StructuredDataDef/Parsing/StructuredDataDefSizeCalculator.h b/src/ObjLoading/StructuredDataDef/Parsing/StructuredDataDefSizeCalculator.h index be8a8283a..8d6de8c88 100644 --- a/src/ObjLoading/StructuredDataDef/Parsing/StructuredDataDefSizeCalculator.h +++ b/src/ObjLoading/StructuredDataDef/Parsing/StructuredDataDefSizeCalculator.h @@ -1,27 +1,24 @@ #pragma once -#include <string> #include <exception> +#include <string> -#include "Utils/ClassUtils.h" #include "StructuredDataDef/CommonStructuredDataDef.h" +#include "Utils/ClassUtils.h" -namespace sdd -{ - class SizeCalculationException final : std::exception - { - std::string m_message; +namespace sdd { +class SizeCalculationException final : std::exception { + std::string m_message; - public: - explicit SizeCalculationException(std::string message); +public: + explicit SizeCalculationException(std::string message); - _NODISCARD const std::string& Message() const; - _NODISCARD char const* what() const noexcept override; - }; + _NODISCARD const std::string &Message() const; + _NODISCARD char const *what() const noexcept override; +}; - class StructuredDataDefSizeCalculator - { - public: - static void CalculateSizesAndOffsetsForDef(CommonStructuredDataDef& def); - }; -} +class StructuredDataDefSizeCalculator { +public: + static void CalculateSizesAndOffsetsForDef(CommonStructuredDataDef &def); +}; +} // namespace sdd diff --git a/src/ObjLoading/StructuredDataDef/StructuredDataDefReader.cpp b/src/ObjLoading/StructuredDataDef/StructuredDataDefReader.cpp index 5dba0a647..ceee00670 100644 --- a/src/ObjLoading/StructuredDataDef/StructuredDataDefReader.cpp +++ b/src/ObjLoading/StructuredDataDef/StructuredDataDefReader.cpp @@ -1,63 +1,55 @@ #include "StructuredDataDefReader.h" -#include "StructuredDataDef/Parsing/StructuredDataDefParser.h" #include "Parsing/Impl/CommentRemovingStreamProxy.h" #include "Parsing/Impl/DefinesStreamProxy.h" #include "Parsing/Impl/IncludingStreamProxy.h" #include "Parsing/Impl/ParserMultiInputStream.h" #include "Parsing/Impl/ParserSingleInputStream.h" +#include "StructuredDataDef/Parsing/StructuredDataDefParser.h" using namespace sdd; -StructuredDataDefReader::StructuredDataDefReader(std::istream& stream, std::string fileName) - : StructuredDataDefReader(stream, std::move(fileName), nullptr) -{ -} +StructuredDataDefReader::StructuredDataDefReader(std::istream &stream, std::string fileName) : StructuredDataDefReader(stream, std::move(fileName), nullptr) {} -StructuredDataDefReader::StructuredDataDefReader(std::istream& stream, std::string fileName, include_callback_t includeCallback) - : m_file_name(std::move(fileName)), - m_stream(nullptr) -{ - OpenBaseStream(stream, std::move(includeCallback)); - SetupStreamProxies(); - m_stream = m_open_streams.back().get(); +StructuredDataDefReader::StructuredDataDefReader(std::istream &stream, std::string fileName, include_callback_t includeCallback) + : m_file_name(std::move(fileName)), m_stream(nullptr) { + OpenBaseStream(stream, std::move(includeCallback)); + SetupStreamProxies(); + m_stream = m_open_streams.back().get(); } -bool StructuredDataDefReader::OpenBaseStream(std::istream& stream, include_callback_t includeCallback) -{ - if (includeCallback) - m_open_streams.emplace_back(std::make_unique<ParserMultiInputStream>(stream, m_file_name, std::move(includeCallback))); - else - m_open_streams.emplace_back(std::make_unique<ParserSingleInputStream>(stream, m_file_name)); +bool StructuredDataDefReader::OpenBaseStream(std::istream &stream, include_callback_t includeCallback) { + if (includeCallback) + m_open_streams.emplace_back(std::make_unique<ParserMultiInputStream>(stream, m_file_name, std::move(includeCallback))); + else + m_open_streams.emplace_back(std::make_unique<ParserSingleInputStream>(stream, m_file_name)); - return true; + return true; } -void StructuredDataDefReader::SetupStreamProxies() -{ - m_open_streams.emplace_back(std::make_unique<CommentRemovingStreamProxy>(m_open_streams.back().get())); - m_open_streams.emplace_back(std::make_unique<IncludingStreamProxy>(m_open_streams.back().get())); - m_open_streams.emplace_back(std::make_unique<DefinesStreamProxy>(m_open_streams.back().get())); +void StructuredDataDefReader::SetupStreamProxies() { + m_open_streams.emplace_back(std::make_unique<CommentRemovingStreamProxy>(m_open_streams.back().get())); + m_open_streams.emplace_back(std::make_unique<IncludingStreamProxy>(m_open_streams.back().get())); + m_open_streams.emplace_back(std::make_unique<DefinesStreamProxy>(m_open_streams.back().get())); - m_stream = m_open_streams.back().get(); + m_stream = m_open_streams.back().get(); } -std::vector<std::unique_ptr<CommonStructuredDataDef>> StructuredDataDefReader::ReadStructureDataDefs(bool& success) -{ - SimpleLexer::Config lexerConfig; - lexerConfig.m_emit_new_line_tokens = false; - lexerConfig.m_read_strings = true; - lexerConfig.m_string_escape_sequences = true; - lexerConfig.m_read_integer_numbers = true; - lexerConfig.m_read_floating_point_numbers = true; - const auto lexer = std::make_unique<SimpleLexer>(m_stream, std::move(lexerConfig)); +std::vector<std::unique_ptr<CommonStructuredDataDef>> StructuredDataDefReader::ReadStructureDataDefs(bool &success) { + SimpleLexer::Config lexerConfig; + lexerConfig.m_emit_new_line_tokens = false; + lexerConfig.m_read_strings = true; + lexerConfig.m_string_escape_sequences = true; + lexerConfig.m_read_integer_numbers = true; + lexerConfig.m_read_floating_point_numbers = true; + const auto lexer = std::make_unique<SimpleLexer>(m_stream, std::move(lexerConfig)); - const auto parser = std::make_unique<StructuredDataDefParser>(lexer.get()); + const auto parser = std::make_unique<StructuredDataDefParser>(lexer.get()); - success = parser->Parse(); - if (success) - return parser->GetDefs(); + success = parser->Parse(); + if (success) + return parser->GetDefs(); - std::cout << "Parsing structured data def file \"" << m_file_name << "\" failed!" << std::endl; - return {}; + std::cout << "Parsing structured data def file \"" << m_file_name << "\" failed!" << std::endl; + return {}; } diff --git a/src/ObjLoading/StructuredDataDef/StructuredDataDefReader.h b/src/ObjLoading/StructuredDataDef/StructuredDataDefReader.h index 34e1162fd..a9587c9e3 100644 --- a/src/ObjLoading/StructuredDataDef/StructuredDataDefReader.h +++ b/src/ObjLoading/StructuredDataDef/StructuredDataDefReader.h @@ -4,25 +4,24 @@ #include <string> #include <vector> -#include "StructuredDataDef/CommonStructuredDataDef.h" #include "Parsing/IParserLineStream.h" +#include "StructuredDataDef/CommonStructuredDataDef.h" -class StructuredDataDefReader -{ +class StructuredDataDefReader { public: - using include_callback_t = std::function<std::unique_ptr<std::istream>(const std::string& filename, const std::string& sourceFile)>; + using include_callback_t = std::function<std::unique_ptr<std::istream>(const std::string &filename, const std::string &sourceFile)>; private: - std::string m_file_name; - IParserLineStream* m_stream; - std::vector<std::unique_ptr<IParserLineStream>> m_open_streams; + std::string m_file_name; + IParserLineStream *m_stream; + std::vector<std::unique_ptr<IParserLineStream>> m_open_streams; - bool OpenBaseStream(std::istream& stream, include_callback_t includeCallback); - void SetupStreamProxies(); + bool OpenBaseStream(std::istream &stream, include_callback_t includeCallback); + void SetupStreamProxies(); public: - StructuredDataDefReader(std::istream& stream, std::string fileName); - StructuredDataDefReader(std::istream& stream, std::string fileName, include_callback_t includeCallback); + StructuredDataDefReader(std::istream &stream, std::string fileName); + StructuredDataDefReader(std::istream &stream, std::string fileName, include_callback_t includeCallback); - std::vector<std::unique_ptr<CommonStructuredDataDef>> ReadStructureDataDefs(bool& success); + std::vector<std::unique_ptr<CommonStructuredDataDef>> ReadStructureDataDefs(bool &success); }; diff --git a/src/ObjLoading/Techset/Parsing/Sequence/TechniqueNoScopeSequences.cpp b/src/ObjLoading/Techset/Parsing/Sequence/TechniqueNoScopeSequences.cpp index 3d5498cad..dce060c3d 100644 --- a/src/ObjLoading/Techset/Parsing/Sequence/TechniqueNoScopeSequences.cpp +++ b/src/ObjLoading/Techset/Parsing/Sequence/TechniqueNoScopeSequences.cpp @@ -6,36 +6,27 @@ using namespace techset; -namespace techset -{ - class SequencePass final : public TechniqueParser::sequence_t - { - public: - SequencePass() - { - const SimpleMatcherFactory create(this); - - AddMatchers({ - create.Char('{') - }); - } - - protected: - void ProcessMatch(TechniqueParserState* state, SequenceResult<SimpleParserValue>& result) const override - { - assert(state->m_in_pass == false); - state->m_in_pass = true; - - state->m_acceptor->AcceptNextPass(); - } - }; -} +namespace techset { +class SequencePass final : public TechniqueParser::sequence_t { +public: + SequencePass() { + const SimpleMatcherFactory create(this); + + AddMatchers({create.Char('{')}); + } + +protected: + void ProcessMatch(TechniqueParserState *state, SequenceResult<SimpleParserValue> &result) const override { + assert(state->m_in_pass == false); + state->m_in_pass = true; + + state->m_acceptor->AcceptNextPass(); + } +}; +} // namespace techset -const std::vector<TechniqueParser::sequence_t*>& TechniqueNoScopeSequences::GetSequences() -{ - static std::vector<TechniqueParser::sequence_t*> tests({ - new SequencePass() - }); +const std::vector<TechniqueParser::sequence_t *> &TechniqueNoScopeSequences::GetSequences() { + static std::vector<TechniqueParser::sequence_t *> tests({new SequencePass()}); - return tests; + return tests; } diff --git a/src/ObjLoading/Techset/Parsing/Sequence/TechniqueNoScopeSequences.h b/src/ObjLoading/Techset/Parsing/Sequence/TechniqueNoScopeSequences.h index d8f33f7e2..183992e9d 100644 --- a/src/ObjLoading/Techset/Parsing/Sequence/TechniqueNoScopeSequences.h +++ b/src/ObjLoading/Techset/Parsing/Sequence/TechniqueNoScopeSequences.h @@ -3,13 +3,11 @@ #include "Techset/Parsing/TechniqueFileParser.h" -namespace techset -{ - class TechniqueNoScopeSequences - { - TechniqueNoScopeSequences() = default; +namespace techset { +class TechniqueNoScopeSequences { + TechniqueNoScopeSequences() = default; - public: - static const std::vector<TechniqueParser::sequence_t*>& GetSequences(); - }; -} +public: + static const std::vector<TechniqueParser::sequence_t *> &GetSequences(); +}; +} // namespace techset diff --git a/src/ObjLoading/Techset/Parsing/Sequence/TechniquePassScopeSequences.cpp b/src/ObjLoading/Techset/Parsing/Sequence/TechniquePassScopeSequences.cpp index 76631ff5e..e491fa91e 100644 --- a/src/ObjLoading/Techset/Parsing/Sequence/TechniquePassScopeSequences.cpp +++ b/src/ObjLoading/Techset/Parsing/Sequence/TechniquePassScopeSequences.cpp @@ -7,207 +7,161 @@ using namespace techset; -namespace techset -{ - class SequenceEndPass final : public TechniqueParser::sequence_t - { - static constexpr auto CAPTURE_FIRST_TOKEN = 1; - - public: - SequenceEndPass() - { - const SimpleMatcherFactory create(this); - - AddMatchers({ - create.Char('}').Capture(CAPTURE_FIRST_TOKEN) - }); - } - - protected: - void ProcessMatch(TechniqueParserState* state, SequenceResult<SimpleParserValue>& result) const override - { - assert(state->m_in_pass == true); - - std::string errorMessage; - if (!state->m_acceptor->AcceptEndPass(errorMessage)) - throw ParsingException(result.NextCapture(CAPTURE_FIRST_TOKEN).GetPos(), errorMessage); - - state->m_in_pass = false; - } - }; - - class SequenceStateMap final : public TechniqueParser::sequence_t - { - static constexpr auto CAPTURE_START = 1; - static constexpr auto CAPTURE_STATE_MAP_NAME = 2; - - public: - SequenceStateMap() - { - const SimpleMatcherFactory create(this); - - AddMatchers({ - create.Keyword("stateMap").Capture(CAPTURE_START), - create.String().Capture(CAPTURE_STATE_MAP_NAME), - create.Char(';') - }); - } - - protected: - void ProcessMatch(TechniqueParserState* state, SequenceResult<SimpleParserValue>& result) const override - { - const auto& firstToken = result.NextCapture(CAPTURE_START); - - std::string errorMessage; - const auto acceptorResult = state->m_acceptor->AcceptStateMap(result.NextCapture(CAPTURE_STATE_MAP_NAME).StringValue(), errorMessage); - - if (!acceptorResult) - throw ParsingException(firstToken.GetPos(), std::move(errorMessage)); - } - }; - - class SequenceShader final : public TechniqueParser::sequence_t - { - static constexpr auto TAG_VERTEX_SHADER = 1; - static constexpr auto TAG_PIXEL_SHADER = 2; - - static constexpr auto CAPTURE_START = 1; - static constexpr auto CAPTURE_VERSION = 2; - static constexpr auto CAPTURE_VERSION_MAJOR = 3; - static constexpr auto CAPTURE_VERSION_MINOR = 4; - static constexpr auto CAPTURE_SHADER_NAME = 5; - - public: - SequenceShader() - { - const SimpleMatcherFactory create(this); - - AddMatchers({ - create.Or({ - create.Keyword("vertexShader").Tag(TAG_VERTEX_SHADER), - create.Keyword("pixelShader").Tag(TAG_PIXEL_SHADER), - }).Capture(CAPTURE_START), - create.Or({ - create.And({ - create.Integer().Capture(CAPTURE_VERSION_MAJOR), - create.Char('.'), - create.Integer().Capture(CAPTURE_VERSION_MINOR), - }), - create.FloatingPoint().Capture(CAPTURE_VERSION), // This is dumb but cod devs made the format so cannot change it - create.String().Capture(CAPTURE_VERSION) - }), - create.String().Capture(CAPTURE_SHADER_NAME), - create.Char('{') - }); - } - - protected: - void ProcessMatch(TechniqueParserState* state, SequenceResult<SimpleParserValue>& result) const override - { - const auto& firstToken = result.NextCapture(CAPTURE_START); - - // Don't care about shader version since it's stated in the shader bin anyway - - const auto& shaderNameToken = result.NextCapture(CAPTURE_SHADER_NAME); - - bool acceptorResult; - std::string errorMessage; - const auto shaderTag = result.NextTag(); - assert(shaderTag == TAG_VERTEX_SHADER || shaderTag == TAG_PIXEL_SHADER); - if (shaderTag == TAG_VERTEX_SHADER) - { - acceptorResult = state->m_acceptor->AcceptVertexShader(shaderNameToken.StringValue(), errorMessage); - state->m_current_shader = ShaderSelector::VERTEX_SHADER; - } - else - { - acceptorResult = state->m_acceptor->AcceptPixelShader(shaderNameToken.StringValue(), errorMessage); - state->m_current_shader = ShaderSelector::PIXEL_SHADER; - } - - state->m_in_shader = true; - - if (!acceptorResult) - throw ParsingException(firstToken.GetPos(), std::move(errorMessage)); - } - }; - - class SequenceVertexStreamRouting final : public TechniqueParser::sequence_t - { - static constexpr auto CAPTURE_FIRST_TOKEN = 1; - static constexpr auto CAPTURE_STREAM_DESTINATION_NAME = 2; - static constexpr auto CAPTURE_STREAM_DESTINATION_INDEX = 3; - static constexpr auto CAPTURE_STREAM_SOURCE_NAME = 4; - static constexpr auto CAPTURE_STREAM_SOURCE_INDEX = 5; - - public: - SequenceVertexStreamRouting() - { - const SimpleMatcherFactory create(this); - - AddMatchers({ - create.Keyword("vertex").Capture(CAPTURE_FIRST_TOKEN), - create.Char('.'), - create.Identifier().Capture(CAPTURE_STREAM_DESTINATION_NAME), - create.Optional(create.And({ - create.Char('['), - create.Integer().Capture(CAPTURE_STREAM_DESTINATION_INDEX), - create.Char(']') - })), - - create.Char('='), - - create.Keyword("code"), - create.Char('.'), - create.Identifier().Capture(CAPTURE_STREAM_SOURCE_NAME), - create.Optional(create.And({ - create.Char('['), - create.Integer().Capture(CAPTURE_STREAM_SOURCE_INDEX), - create.Char(']') - })), - - create.Char(';') - }); - } - - static std::string CreateRoutingString(SequenceResult<SimpleParserValue>& result, const int nameCapture, const int indexCapture) - { - if (result.HasNextCapture(indexCapture)) - { - const auto& indexToken = result.NextCapture(indexCapture); - if (indexToken.IntegerValue() < 0) - throw ParsingException(indexToken.GetPos(), "Index cannot be negative"); - - std::ostringstream ss; - ss << result.NextCapture(nameCapture).IdentifierValue() << '[' << indexToken.IntegerValue() << ']'; - return ss.str(); - } - - return result.NextCapture(nameCapture).IdentifierValue(); - } - - protected: - void ProcessMatch(TechniqueParserState* state, SequenceResult<SimpleParserValue>& result) const override - { - const auto& firstToken = result.NextCapture(CAPTURE_FIRST_TOKEN); - const std::string destinationString = CreateRoutingString(result, CAPTURE_STREAM_DESTINATION_NAME, CAPTURE_STREAM_DESTINATION_INDEX); - const std::string sourceString = CreateRoutingString(result, CAPTURE_STREAM_SOURCE_NAME, CAPTURE_STREAM_SOURCE_INDEX); - - std::string errorMessage; - if (!state->m_acceptor->AcceptVertexStreamRouting(destinationString, sourceString, errorMessage)) - throw ParsingException(firstToken.GetPos(), std::move(errorMessage)); - } - }; -} - -const std::vector<TechniqueParser::sequence_t*>& TechniquePassScopeSequences::GetSequences() -{ - static std::vector<TechniqueParser::sequence_t*> tests({ - new SequenceEndPass(), - new SequenceStateMap(), - new SequenceShader(), - new SequenceVertexStreamRouting() - }); - - return tests; +namespace techset { +class SequenceEndPass final : public TechniqueParser::sequence_t { + static constexpr auto CAPTURE_FIRST_TOKEN = 1; + +public: + SequenceEndPass() { + const SimpleMatcherFactory create(this); + + AddMatchers({create.Char('}').Capture(CAPTURE_FIRST_TOKEN)}); + } + +protected: + void ProcessMatch(TechniqueParserState *state, SequenceResult<SimpleParserValue> &result) const override { + assert(state->m_in_pass == true); + + std::string errorMessage; + if (!state->m_acceptor->AcceptEndPass(errorMessage)) + throw ParsingException(result.NextCapture(CAPTURE_FIRST_TOKEN).GetPos(), errorMessage); + + state->m_in_pass = false; + } +}; + +class SequenceStateMap final : public TechniqueParser::sequence_t { + static constexpr auto CAPTURE_START = 1; + static constexpr auto CAPTURE_STATE_MAP_NAME = 2; + +public: + SequenceStateMap() { + const SimpleMatcherFactory create(this); + + AddMatchers({create.Keyword("stateMap").Capture(CAPTURE_START), create.String().Capture(CAPTURE_STATE_MAP_NAME), create.Char(';')}); + } + +protected: + void ProcessMatch(TechniqueParserState *state, SequenceResult<SimpleParserValue> &result) const override { + const auto &firstToken = result.NextCapture(CAPTURE_START); + + std::string errorMessage; + const auto acceptorResult = state->m_acceptor->AcceptStateMap(result.NextCapture(CAPTURE_STATE_MAP_NAME).StringValue(), errorMessage); + + if (!acceptorResult) + throw ParsingException(firstToken.GetPos(), std::move(errorMessage)); + } +}; + +class SequenceShader final : public TechniqueParser::sequence_t { + static constexpr auto TAG_VERTEX_SHADER = 1; + static constexpr auto TAG_PIXEL_SHADER = 2; + + static constexpr auto CAPTURE_START = 1; + static constexpr auto CAPTURE_VERSION = 2; + static constexpr auto CAPTURE_VERSION_MAJOR = 3; + static constexpr auto CAPTURE_VERSION_MINOR = 4; + static constexpr auto CAPTURE_SHADER_NAME = 5; + +public: + SequenceShader() { + const SimpleMatcherFactory create(this); + + AddMatchers({create + .Or({ + create.Keyword("vertexShader").Tag(TAG_VERTEX_SHADER), + create.Keyword("pixelShader").Tag(TAG_PIXEL_SHADER), + }) + .Capture(CAPTURE_START), + create.Or({create.And({ + create.Integer().Capture(CAPTURE_VERSION_MAJOR), + create.Char('.'), + create.Integer().Capture(CAPTURE_VERSION_MINOR), + }), + create.FloatingPoint().Capture(CAPTURE_VERSION), // This is dumb but cod devs made the format so cannot change it + create.String().Capture(CAPTURE_VERSION)}), + create.String().Capture(CAPTURE_SHADER_NAME), create.Char('{')}); + } + +protected: + void ProcessMatch(TechniqueParserState *state, SequenceResult<SimpleParserValue> &result) const override { + const auto &firstToken = result.NextCapture(CAPTURE_START); + + // Don't care about shader version since it's stated in the shader bin anyway + + const auto &shaderNameToken = result.NextCapture(CAPTURE_SHADER_NAME); + + bool acceptorResult; + std::string errorMessage; + const auto shaderTag = result.NextTag(); + assert(shaderTag == TAG_VERTEX_SHADER || shaderTag == TAG_PIXEL_SHADER); + if (shaderTag == TAG_VERTEX_SHADER) { + acceptorResult = state->m_acceptor->AcceptVertexShader(shaderNameToken.StringValue(), errorMessage); + state->m_current_shader = ShaderSelector::VERTEX_SHADER; + } else { + acceptorResult = state->m_acceptor->AcceptPixelShader(shaderNameToken.StringValue(), errorMessage); + state->m_current_shader = ShaderSelector::PIXEL_SHADER; + } + + state->m_in_shader = true; + + if (!acceptorResult) + throw ParsingException(firstToken.GetPos(), std::move(errorMessage)); + } +}; + +class SequenceVertexStreamRouting final : public TechniqueParser::sequence_t { + static constexpr auto CAPTURE_FIRST_TOKEN = 1; + static constexpr auto CAPTURE_STREAM_DESTINATION_NAME = 2; + static constexpr auto CAPTURE_STREAM_DESTINATION_INDEX = 3; + static constexpr auto CAPTURE_STREAM_SOURCE_NAME = 4; + static constexpr auto CAPTURE_STREAM_SOURCE_INDEX = 5; + +public: + SequenceVertexStreamRouting() { + const SimpleMatcherFactory create(this); + + AddMatchers({create.Keyword("vertex").Capture(CAPTURE_FIRST_TOKEN), create.Char('.'), create.Identifier().Capture(CAPTURE_STREAM_DESTINATION_NAME), + create.Optional(create.And({create.Char('['), create.Integer().Capture(CAPTURE_STREAM_DESTINATION_INDEX), create.Char(']')})), + + create.Char('='), + + create.Keyword("code"), create.Char('.'), create.Identifier().Capture(CAPTURE_STREAM_SOURCE_NAME), + create.Optional(create.And({create.Char('['), create.Integer().Capture(CAPTURE_STREAM_SOURCE_INDEX), create.Char(']')})), + + create.Char(';')}); + } + + static std::string CreateRoutingString(SequenceResult<SimpleParserValue> &result, const int nameCapture, const int indexCapture) { + if (result.HasNextCapture(indexCapture)) { + const auto &indexToken = result.NextCapture(indexCapture); + if (indexToken.IntegerValue() < 0) + throw ParsingException(indexToken.GetPos(), "Index cannot be negative"); + + std::ostringstream ss; + ss << result.NextCapture(nameCapture).IdentifierValue() << '[' << indexToken.IntegerValue() << ']'; + return ss.str(); + } + + return result.NextCapture(nameCapture).IdentifierValue(); + } + +protected: + void ProcessMatch(TechniqueParserState *state, SequenceResult<SimpleParserValue> &result) const override { + const auto &firstToken = result.NextCapture(CAPTURE_FIRST_TOKEN); + const std::string destinationString = CreateRoutingString(result, CAPTURE_STREAM_DESTINATION_NAME, CAPTURE_STREAM_DESTINATION_INDEX); + const std::string sourceString = CreateRoutingString(result, CAPTURE_STREAM_SOURCE_NAME, CAPTURE_STREAM_SOURCE_INDEX); + + std::string errorMessage; + if (!state->m_acceptor->AcceptVertexStreamRouting(destinationString, sourceString, errorMessage)) + throw ParsingException(firstToken.GetPos(), std::move(errorMessage)); + } +}; +} // namespace techset + +const std::vector<TechniqueParser::sequence_t *> &TechniquePassScopeSequences::GetSequences() { + static std::vector<TechniqueParser::sequence_t *> tests( + {new SequenceEndPass(), new SequenceStateMap(), new SequenceShader(), new SequenceVertexStreamRouting()}); + + return tests; } diff --git a/src/ObjLoading/Techset/Parsing/Sequence/TechniquePassScopeSequences.h b/src/ObjLoading/Techset/Parsing/Sequence/TechniquePassScopeSequences.h index c159c4978..31caa8d95 100644 --- a/src/ObjLoading/Techset/Parsing/Sequence/TechniquePassScopeSequences.h +++ b/src/ObjLoading/Techset/Parsing/Sequence/TechniquePassScopeSequences.h @@ -3,13 +3,11 @@ #include "Techset/Parsing/TechniqueFileParser.h" -namespace techset -{ - class TechniquePassScopeSequences - { - TechniquePassScopeSequences() = default; +namespace techset { +class TechniquePassScopeSequences { + TechniquePassScopeSequences() = default; - public: - static const std::vector<TechniqueParser::sequence_t*>& GetSequences(); - }; -} +public: + static const std::vector<TechniqueParser::sequence_t *> &GetSequences(); +}; +} // namespace techset diff --git a/src/ObjLoading/Techset/Parsing/Sequence/TechniqueShaderScopeSequences.cpp b/src/ObjLoading/Techset/Parsing/Sequence/TechniqueShaderScopeSequences.cpp index eea462f44..3806e210e 100644 --- a/src/ObjLoading/Techset/Parsing/Sequence/TechniqueShaderScopeSequences.cpp +++ b/src/ObjLoading/Techset/Parsing/Sequence/TechniqueShaderScopeSequences.cpp @@ -6,231 +6,166 @@ using namespace techset; -namespace techset -{ - class SequenceEndShader final : public TechniqueParser::sequence_t - { - public: - SequenceEndShader() - { - const SimpleMatcherFactory create(this); - - AddMatchers({ - create.Char('}') - }); - } - - protected: - void ProcessMatch(TechniqueParserState* state, SequenceResult<SimpleParserValue>& result) const override - { - assert(state->m_in_shader == true); - state->m_in_shader = false; - } - }; - - class SequenceShaderArgument final : public TechniqueParser::sequence_t - { - static constexpr auto TAG_CONSTANT = 1; - static constexpr auto TAG_SAMPLER = 2; - static constexpr auto TAG_LITERAL = 3; - static constexpr auto TAG_MATERIAL = 4; - - static constexpr auto CAPTURE_FIRST_TOKEN = 1; - static constexpr auto CAPTURE_SHADER_ARGUMENT = 2; - static constexpr auto CAPTURE_SHADER_INDEX = 3; - static constexpr auto CAPTURE_CODE_ACCESSOR = 4; - static constexpr auto CAPTURE_CODE_INDEX = 5; - static constexpr auto CAPTURE_LITERAL_VALUE = 6; - static constexpr auto CAPTURE_MATERIAL_HASH = 7; - static constexpr auto CAPTURE_MATERIAL_NAME = 8; - - static std::unique_ptr<matcher_t> CodeMatchers(const SimpleMatcherFactory& create) - { - return create.And({ - create.Or({ - create.Keyword("constant").Tag(TAG_CONSTANT), - create.Keyword("sampler").Tag(TAG_SAMPLER) - }), - create.Char('.'), - create.Identifier().Capture(CAPTURE_CODE_ACCESSOR), - create.OptionalLoop(create.And({ - create.Char('.'), - create.Identifier().Capture(CAPTURE_CODE_ACCESSOR) - })), - create.Optional(create.And({ - create.Char('['), - create.Integer().Capture(CAPTURE_CODE_INDEX), - create.Char(']') - })) - }); - } - - static std::unique_ptr<matcher_t> LiteralValueMatchers(const SimpleMatcherFactory& create) - { - return create.Or({ - create.FloatingPoint(), - create.Integer() - }).Capture(CAPTURE_LITERAL_VALUE); - } - - static std::unique_ptr<matcher_t> LiteralMatchers(const SimpleMatcherFactory& create) - { - return create.And({ - create.Keyword("float4"), - create.Char('('), - LiteralValueMatchers(create), - create.Char(','), - LiteralValueMatchers(create), - create.Char(','), - LiteralValueMatchers(create), - create.Char(','), - LiteralValueMatchers(create), - create.Char(')'), - }).Tag(TAG_LITERAL); - } - - static std::unique_ptr<matcher_t> MaterialMatchers(const SimpleMatcherFactory& create) - { - return create.And({ - create.Keyword("material"), - create.Char('.'), - - create.Or({ - create.And({ - create.Char('#'), - create.Integer().Capture(CAPTURE_MATERIAL_HASH) - }), - create.Identifier().Capture(CAPTURE_MATERIAL_NAME) - }) - }).Tag(TAG_MATERIAL); - } - - public: - SequenceShaderArgument() - { - const SimpleMatcherFactory create(this); - - AddMatchers({ - create.Identifier().Capture(CAPTURE_FIRST_TOKEN).NoConsume(), - create.Identifier().Capture(CAPTURE_SHADER_ARGUMENT), - create.Optional(create.And({ - create.Char('['), - create.Integer().Capture(CAPTURE_SHADER_INDEX), - create.Char(']') - })), - create.Char('='), - create.Or({ - CodeMatchers(create), - LiteralMatchers(create), - MaterialMatchers(create) - }), - create.Char(';') - }); - } - - static void ProcessCodeArgument(const TechniqueParserState* state, SequenceResult<SimpleParserValue>& result, ShaderArgument arg, const bool isSampler) - { - std::vector<std::string> accessors; - while (result.HasNextCapture(CAPTURE_CODE_ACCESSOR)) - accessors.emplace_back(result.NextCapture(CAPTURE_CODE_ACCESSOR).IdentifierValue()); - - ShaderArgumentCodeSource source; - if (result.HasNextCapture(CAPTURE_CODE_INDEX)) - { - const auto& codeIndexToken = result.NextCapture(CAPTURE_CODE_INDEX); - if (codeIndexToken.IntegerValue() < 0) - throw ParsingException(codeIndexToken.GetPos(), "Index cannot be negative"); - source = ShaderArgumentCodeSource(std::move(accessors), static_cast<size_t>(codeIndexToken.IntegerValue())); - } - else - source = ShaderArgumentCodeSource(std::move(accessors)); - - std::string errorMessage; - if(!isSampler) - { - if (!state->m_acceptor->AcceptShaderConstantArgument(state->m_current_shader, std::move(arg), std::move(source), errorMessage)) - throw ParsingException(result.NextCapture(CAPTURE_FIRST_TOKEN).GetPos(), std::move(errorMessage)); - } - else - { - if (!state->m_acceptor->AcceptShaderSamplerArgument(state->m_current_shader, std::move(arg), std::move(source), errorMessage)) - throw ParsingException(result.NextCapture(CAPTURE_FIRST_TOKEN).GetPos(), std::move(errorMessage)); - } - } - - static void ProcessLiteralArgument(const TechniqueParserState* state, SequenceResult<SimpleParserValue>& result, ShaderArgument arg) - { - float value[4]; - for (float& i : value) - { - const auto& literalValueToken = result.NextCapture(CAPTURE_LITERAL_VALUE); - - if (literalValueToken.m_type == SimpleParserValueType::FLOATING_POINT) - i = static_cast<float>(literalValueToken.FloatingPointValue()); - else - i = static_cast<float>(literalValueToken.IntegerValue()); - } - - const ShaderArgumentLiteralSource source(value); - std::string errorMessage; - if (!state->m_acceptor->AcceptShaderLiteralArgument(state->m_current_shader, std::move(arg), source, errorMessage)) - throw ParsingException(result.NextCapture(CAPTURE_FIRST_TOKEN).GetPos(), std::move(errorMessage)); - } - - static void ProcessMaterialArgument(const TechniqueParserState* state, SequenceResult<SimpleParserValue>& result, ShaderArgument arg) - { - std::string errorMessage; - if (result.HasNextCapture(CAPTURE_MATERIAL_HASH)) - { - ShaderArgumentMaterialSource source(static_cast<size_t>(result.NextCapture(CAPTURE_MATERIAL_HASH).IntegerValue())); - if (!state->m_acceptor->AcceptShaderMaterialArgument(state->m_current_shader, std::move(arg), std::move(source), errorMessage)) - throw ParsingException(result.NextCapture(CAPTURE_FIRST_TOKEN).GetPos(), std::move(errorMessage)); - } - else - { - ShaderArgumentMaterialSource source(result.NextCapture(CAPTURE_MATERIAL_NAME).IdentifierValue()); - if (!state->m_acceptor->AcceptShaderMaterialArgument(state->m_current_shader, std::move(arg), std::move(source), errorMessage)) - throw ParsingException(result.NextCapture(CAPTURE_FIRST_TOKEN).GetPos(), std::move(errorMessage)); - } - } - - protected: - void ProcessMatch(TechniqueParserState* state, SequenceResult<SimpleParserValue>& result) const override - { - assert(state->m_in_shader == true); - - const auto& shaderArgumentNameToken = result.NextCapture(CAPTURE_SHADER_ARGUMENT); - - ShaderArgument arg; - if (result.HasNextCapture(CAPTURE_SHADER_INDEX)) - { - const auto& shaderArgumentIndexToken = result.NextCapture(CAPTURE_SHADER_INDEX); - if (shaderArgumentIndexToken.IntegerValue() < 0) - throw ParsingException(shaderArgumentIndexToken.GetPos(), "Index cannot be negative"); - const auto index = static_cast<size_t>(shaderArgumentIndexToken.IntegerValue()); - arg = ShaderArgument(shaderArgumentNameToken.IdentifierValue(), index); - } - else - arg = ShaderArgument(shaderArgumentNameToken.IdentifierValue()); - - const auto typeTag = result.NextTag(); - assert(typeTag == TAG_CONSTANT || typeTag == TAG_SAMPLER || typeTag == TAG_LITERAL || typeTag == TAG_MATERIAL); - if (typeTag == TAG_CONSTANT || typeTag == TAG_SAMPLER) - ProcessCodeArgument(state, result, std::move(arg), typeTag == TAG_SAMPLER); - else if (typeTag == TAG_LITERAL) - ProcessLiteralArgument(state, result, std::move(arg)); - else - ProcessMaterialArgument(state, result, std::move(arg)); - } - }; -} - -const std::vector<TechniqueParser::sequence_t*>& TechniqueShaderScopeSequences::GetSequences() -{ - static std::vector<TechniqueParser::sequence_t*> tests({ - new SequenceEndShader(), - new SequenceShaderArgument() - }); - - return tests; +namespace techset { +class SequenceEndShader final : public TechniqueParser::sequence_t { +public: + SequenceEndShader() { + const SimpleMatcherFactory create(this); + + AddMatchers({create.Char('}')}); + } + +protected: + void ProcessMatch(TechniqueParserState *state, SequenceResult<SimpleParserValue> &result) const override { + assert(state->m_in_shader == true); + state->m_in_shader = false; + } +}; + +class SequenceShaderArgument final : public TechniqueParser::sequence_t { + static constexpr auto TAG_CONSTANT = 1; + static constexpr auto TAG_SAMPLER = 2; + static constexpr auto TAG_LITERAL = 3; + static constexpr auto TAG_MATERIAL = 4; + + static constexpr auto CAPTURE_FIRST_TOKEN = 1; + static constexpr auto CAPTURE_SHADER_ARGUMENT = 2; + static constexpr auto CAPTURE_SHADER_INDEX = 3; + static constexpr auto CAPTURE_CODE_ACCESSOR = 4; + static constexpr auto CAPTURE_CODE_INDEX = 5; + static constexpr auto CAPTURE_LITERAL_VALUE = 6; + static constexpr auto CAPTURE_MATERIAL_HASH = 7; + static constexpr auto CAPTURE_MATERIAL_NAME = 8; + + static std::unique_ptr<matcher_t> CodeMatchers(const SimpleMatcherFactory &create) { + return create.And({create.Or({create.Keyword("constant").Tag(TAG_CONSTANT), create.Keyword("sampler").Tag(TAG_SAMPLER)}), create.Char('.'), + create.Identifier().Capture(CAPTURE_CODE_ACCESSOR), + create.OptionalLoop(create.And({create.Char('.'), create.Identifier().Capture(CAPTURE_CODE_ACCESSOR)})), + create.Optional(create.And({create.Char('['), create.Integer().Capture(CAPTURE_CODE_INDEX), create.Char(']')}))}); + } + + static std::unique_ptr<matcher_t> LiteralValueMatchers(const SimpleMatcherFactory &create) { + return create.Or({create.FloatingPoint(), create.Integer()}).Capture(CAPTURE_LITERAL_VALUE); + } + + static std::unique_ptr<matcher_t> LiteralMatchers(const SimpleMatcherFactory &create) { + return create + .And({ + create.Keyword("float4"), + create.Char('('), + LiteralValueMatchers(create), + create.Char(','), + LiteralValueMatchers(create), + create.Char(','), + LiteralValueMatchers(create), + create.Char(','), + LiteralValueMatchers(create), + create.Char(')'), + }) + .Tag(TAG_LITERAL); + } + + static std::unique_ptr<matcher_t> MaterialMatchers(const SimpleMatcherFactory &create) { + return create + .And({create.Keyword("material"), create.Char('.'), + + create.Or({create.And({create.Char('#'), create.Integer().Capture(CAPTURE_MATERIAL_HASH)}), create.Identifier().Capture(CAPTURE_MATERIAL_NAME)})}) + .Tag(TAG_MATERIAL); + } + +public: + SequenceShaderArgument() { + const SimpleMatcherFactory create(this); + + AddMatchers({create.Identifier().Capture(CAPTURE_FIRST_TOKEN).NoConsume(), create.Identifier().Capture(CAPTURE_SHADER_ARGUMENT), + create.Optional(create.And({create.Char('['), create.Integer().Capture(CAPTURE_SHADER_INDEX), create.Char(']')})), create.Char('='), + create.Or({CodeMatchers(create), LiteralMatchers(create), MaterialMatchers(create)}), create.Char(';')}); + } + + static void ProcessCodeArgument(const TechniqueParserState *state, SequenceResult<SimpleParserValue> &result, ShaderArgument arg, const bool isSampler) { + std::vector<std::string> accessors; + while (result.HasNextCapture(CAPTURE_CODE_ACCESSOR)) + accessors.emplace_back(result.NextCapture(CAPTURE_CODE_ACCESSOR).IdentifierValue()); + + ShaderArgumentCodeSource source; + if (result.HasNextCapture(CAPTURE_CODE_INDEX)) { + const auto &codeIndexToken = result.NextCapture(CAPTURE_CODE_INDEX); + if (codeIndexToken.IntegerValue() < 0) + throw ParsingException(codeIndexToken.GetPos(), "Index cannot be negative"); + source = ShaderArgumentCodeSource(std::move(accessors), static_cast<size_t>(codeIndexToken.IntegerValue())); + } else + source = ShaderArgumentCodeSource(std::move(accessors)); + + std::string errorMessage; + if (!isSampler) { + if (!state->m_acceptor->AcceptShaderConstantArgument(state->m_current_shader, std::move(arg), std::move(source), errorMessage)) + throw ParsingException(result.NextCapture(CAPTURE_FIRST_TOKEN).GetPos(), std::move(errorMessage)); + } else { + if (!state->m_acceptor->AcceptShaderSamplerArgument(state->m_current_shader, std::move(arg), std::move(source), errorMessage)) + throw ParsingException(result.NextCapture(CAPTURE_FIRST_TOKEN).GetPos(), std::move(errorMessage)); + } + } + + static void ProcessLiteralArgument(const TechniqueParserState *state, SequenceResult<SimpleParserValue> &result, ShaderArgument arg) { + float value[4]; + for (float &i : value) { + const auto &literalValueToken = result.NextCapture(CAPTURE_LITERAL_VALUE); + + if (literalValueToken.m_type == SimpleParserValueType::FLOATING_POINT) + i = static_cast<float>(literalValueToken.FloatingPointValue()); + else + i = static_cast<float>(literalValueToken.IntegerValue()); + } + + const ShaderArgumentLiteralSource source(value); + std::string errorMessage; + if (!state->m_acceptor->AcceptShaderLiteralArgument(state->m_current_shader, std::move(arg), source, errorMessage)) + throw ParsingException(result.NextCapture(CAPTURE_FIRST_TOKEN).GetPos(), std::move(errorMessage)); + } + + static void ProcessMaterialArgument(const TechniqueParserState *state, SequenceResult<SimpleParserValue> &result, ShaderArgument arg) { + std::string errorMessage; + if (result.HasNextCapture(CAPTURE_MATERIAL_HASH)) { + ShaderArgumentMaterialSource source(static_cast<size_t>(result.NextCapture(CAPTURE_MATERIAL_HASH).IntegerValue())); + if (!state->m_acceptor->AcceptShaderMaterialArgument(state->m_current_shader, std::move(arg), std::move(source), errorMessage)) + throw ParsingException(result.NextCapture(CAPTURE_FIRST_TOKEN).GetPos(), std::move(errorMessage)); + } else { + ShaderArgumentMaterialSource source(result.NextCapture(CAPTURE_MATERIAL_NAME).IdentifierValue()); + if (!state->m_acceptor->AcceptShaderMaterialArgument(state->m_current_shader, std::move(arg), std::move(source), errorMessage)) + throw ParsingException(result.NextCapture(CAPTURE_FIRST_TOKEN).GetPos(), std::move(errorMessage)); + } + } + +protected: + void ProcessMatch(TechniqueParserState *state, SequenceResult<SimpleParserValue> &result) const override { + assert(state->m_in_shader == true); + + const auto &shaderArgumentNameToken = result.NextCapture(CAPTURE_SHADER_ARGUMENT); + + ShaderArgument arg; + if (result.HasNextCapture(CAPTURE_SHADER_INDEX)) { + const auto &shaderArgumentIndexToken = result.NextCapture(CAPTURE_SHADER_INDEX); + if (shaderArgumentIndexToken.IntegerValue() < 0) + throw ParsingException(shaderArgumentIndexToken.GetPos(), "Index cannot be negative"); + const auto index = static_cast<size_t>(shaderArgumentIndexToken.IntegerValue()); + arg = ShaderArgument(shaderArgumentNameToken.IdentifierValue(), index); + } else + arg = ShaderArgument(shaderArgumentNameToken.IdentifierValue()); + + const auto typeTag = result.NextTag(); + assert(typeTag == TAG_CONSTANT || typeTag == TAG_SAMPLER || typeTag == TAG_LITERAL || typeTag == TAG_MATERIAL); + if (typeTag == TAG_CONSTANT || typeTag == TAG_SAMPLER) + ProcessCodeArgument(state, result, std::move(arg), typeTag == TAG_SAMPLER); + else if (typeTag == TAG_LITERAL) + ProcessLiteralArgument(state, result, std::move(arg)); + else + ProcessMaterialArgument(state, result, std::move(arg)); + } +}; +} // namespace techset + +const std::vector<TechniqueParser::sequence_t *> &TechniqueShaderScopeSequences::GetSequences() { + static std::vector<TechniqueParser::sequence_t *> tests({new SequenceEndShader(), new SequenceShaderArgument()}); + + return tests; } diff --git a/src/ObjLoading/Techset/Parsing/Sequence/TechniqueShaderScopeSequences.h b/src/ObjLoading/Techset/Parsing/Sequence/TechniqueShaderScopeSequences.h index e49fe54cc..6d49db381 100644 --- a/src/ObjLoading/Techset/Parsing/Sequence/TechniqueShaderScopeSequences.h +++ b/src/ObjLoading/Techset/Parsing/Sequence/TechniqueShaderScopeSequences.h @@ -3,13 +3,11 @@ #include "Techset/Parsing/TechniqueFileParser.h" -namespace techset -{ - class TechniqueShaderScopeSequences - { - TechniqueShaderScopeSequences() = default; +namespace techset { +class TechniqueShaderScopeSequences { + TechniqueShaderScopeSequences() = default; - public: - static const std::vector<TechniqueParser::sequence_t*>& GetSequences(); - }; -} +public: + static const std::vector<TechniqueParser::sequence_t *> &GetSequences(); +}; +} // namespace techset diff --git a/src/ObjLoading/Techset/Parsing/TechniqueFileParser.cpp b/src/ObjLoading/Techset/Parsing/TechniqueFileParser.cpp index 1032d6ed9..db4dccbed 100644 --- a/src/ObjLoading/Techset/Parsing/TechniqueFileParser.cpp +++ b/src/ObjLoading/Techset/Parsing/TechniqueFileParser.cpp @@ -6,18 +6,15 @@ using namespace techset; -TechniqueParser::TechniqueParser(SimpleLexer* lexer, ITechniqueDefinitionAcceptor* acceptor) - : AbstractParser(lexer, std::make_unique<TechniqueParserState>(acceptor)) -{ -} +TechniqueParser::TechniqueParser(SimpleLexer *lexer, ITechniqueDefinitionAcceptor *acceptor) + : AbstractParser(lexer, std::make_unique<TechniqueParserState>(acceptor)) {} -const std::vector<TechniqueParser::sequence_t*>& TechniqueParser::GetTestsForState() -{ - if (m_state->m_in_shader) - return TechniqueShaderScopeSequences::GetSequences(); +const std::vector<TechniqueParser::sequence_t *> &TechniqueParser::GetTestsForState() { + if (m_state->m_in_shader) + return TechniqueShaderScopeSequences::GetSequences(); - if (m_state->m_in_pass) - return TechniquePassScopeSequences::GetSequences(); + if (m_state->m_in_pass) + return TechniquePassScopeSequences::GetSequences(); - return TechniqueNoScopeSequences::GetSequences(); + return TechniqueNoScopeSequences::GetSequences(); } diff --git a/src/ObjLoading/Techset/Parsing/TechniqueFileParser.h b/src/ObjLoading/Techset/Parsing/TechniqueFileParser.h index 81570d133..73aba2a6a 100644 --- a/src/ObjLoading/Techset/Parsing/TechniqueFileParser.h +++ b/src/ObjLoading/Techset/Parsing/TechniqueFileParser.h @@ -1,18 +1,16 @@ #pragma once -#include "TechniqueFileParserState.h" +#include "Parsing/Impl/AbstractParser.h" #include "Parsing/Simple/SimpleLexer.h" #include "Parsing/Simple/SimpleParserValue.h" -#include "Parsing/Impl/AbstractParser.h" +#include "TechniqueFileParserState.h" -namespace techset -{ - class TechniqueParser final : public AbstractParser<SimpleParserValue, TechniqueParserState> - { - protected: - const std::vector<sequence_t*>& GetTestsForState() override; +namespace techset { +class TechniqueParser final : public AbstractParser<SimpleParserValue, TechniqueParserState> { +protected: + const std::vector<sequence_t *> &GetTestsForState() override; - public: - TechniqueParser(SimpleLexer* lexer, ITechniqueDefinitionAcceptor* acceptor); - }; -} +public: + TechniqueParser(SimpleLexer *lexer, ITechniqueDefinitionAcceptor *acceptor); +}; +} // namespace techset diff --git a/src/ObjLoading/Techset/Parsing/TechniqueFileParserState.cpp b/src/ObjLoading/Techset/Parsing/TechniqueFileParserState.cpp index 97cdfa52f..d982dd25f 100644 --- a/src/ObjLoading/Techset/Parsing/TechniqueFileParserState.cpp +++ b/src/ObjLoading/Techset/Parsing/TechniqueFileParserState.cpp @@ -4,11 +4,7 @@ using namespace techset; -TechniqueParserState::TechniqueParserState(ITechniqueDefinitionAcceptor* acceptor) - : m_acceptor(acceptor), - m_in_pass(false), - m_in_shader(false), - m_current_shader(ShaderSelector::VERTEX_SHADER) -{ - assert(acceptor); +TechniqueParserState::TechniqueParserState(ITechniqueDefinitionAcceptor *acceptor) + : m_acceptor(acceptor), m_in_pass(false), m_in_shader(false), m_current_shader(ShaderSelector::VERTEX_SHADER) { + assert(acceptor); } diff --git a/src/ObjLoading/Techset/Parsing/TechniqueFileParserState.h b/src/ObjLoading/Techset/Parsing/TechniqueFileParserState.h index 350007e58..3861be8c2 100644 --- a/src/ObjLoading/Techset/Parsing/TechniqueFileParserState.h +++ b/src/ObjLoading/Techset/Parsing/TechniqueFileParserState.h @@ -2,17 +2,15 @@ #include "Techset/TechniqueDefinitionAcceptor.h" -namespace techset -{ - class TechniqueParserState - { - public: - ITechniqueDefinitionAcceptor* const m_acceptor; - - bool m_in_pass; - bool m_in_shader; - ShaderSelector m_current_shader; +namespace techset { +class TechniqueParserState { +public: + ITechniqueDefinitionAcceptor *const m_acceptor; - explicit TechniqueParserState(ITechniqueDefinitionAcceptor* acceptor); - }; -} + bool m_in_pass; + bool m_in_shader; + ShaderSelector m_current_shader; + + explicit TechniqueParserState(ITechniqueDefinitionAcceptor *acceptor); +}; +} // namespace techset diff --git a/src/ObjLoading/Techset/Parsing/TechsetFileParser.cpp b/src/ObjLoading/Techset/Parsing/TechsetFileParser.cpp index ffa62c5d6..5341dfebf 100644 --- a/src/ObjLoading/Techset/Parsing/TechsetFileParser.cpp +++ b/src/ObjLoading/Techset/Parsing/TechsetFileParser.cpp @@ -4,90 +4,62 @@ using namespace techset; -namespace techset -{ - class SequenceTechniqueTypeName final : public TechsetParser::sequence_t - { - static constexpr auto CAPTURE_TYPE_NAME = 1; - - public: - SequenceTechniqueTypeName() - { - const SimpleMatcherFactory create(this); - - AddMatchers({ - create.String().Capture(CAPTURE_TYPE_NAME), - create.Char(':') - }); - } - - protected: - void ProcessMatch(TechsetParserState* state, SequenceResult<SimpleParserValue>& result) const override - { - const auto& typeNameToken = result.NextCapture(CAPTURE_TYPE_NAME); - - size_t techniqueTypeIndex; - if (!state->FindTechniqueTypeIndex(typeNameToken.StringValue(), techniqueTypeIndex)) - throw ParsingException(typeNameToken.GetPos(), "Unknown technique type name"); - - state->m_current_technique_types.push_back(techniqueTypeIndex); - } - }; - - class SequenceTechniqueName final : public TechsetParser::sequence_t - { - static constexpr auto CAPTURE_NAME = 1; - - public: - SequenceTechniqueName() - { - const SimpleMatcherFactory create(this); - - AddMatchers({ - create.Or({ - create.Identifier(), - create.String() - }).Capture(CAPTURE_NAME), - create.Char(';') - }); - } - - protected: - void ProcessMatch(TechsetParserState* state, SequenceResult<SimpleParserValue>& result) const override - { - assert(!state->m_current_technique_types.empty()); - - const auto& techniqueNameToken = result.NextCapture(CAPTURE_NAME); - const auto& techniqueName = techniqueNameToken.m_type == SimpleParserValueType::STRING - ? techniqueNameToken.StringValue() - : techniqueNameToken.IdentifierValue(); - - for (const auto techniqueTypeIndex : state->m_current_technique_types) - state->m_definition->SetTechniqueByIndex(techniqueTypeIndex, techniqueName); - state->m_current_technique_types.clear(); - } - }; -} +namespace techset { +class SequenceTechniqueTypeName final : public TechsetParser::sequence_t { + static constexpr auto CAPTURE_TYPE_NAME = 1; -TechsetParser::TechsetParser(SimpleLexer* lexer, const char** validTechniqueTypeNames, const size_t validTechniqueTypeNameCount) - : AbstractParser(lexer, std::make_unique<TechsetParserState>(validTechniqueTypeNames, validTechniqueTypeNameCount)) -{ -} +public: + SequenceTechniqueTypeName() { + const SimpleMatcherFactory create(this); -const std::vector<TechsetParser::sequence_t*>& TechsetParser::GetTestsForState() -{ - static std::vector<sequence_t*> allTests({ - new SequenceTechniqueTypeName(), - new SequenceTechniqueName() - }); - static std::vector<sequence_t*> techniqueTypeNameOnlyTests({ - new SequenceTechniqueTypeName() - }); - - return m_state->m_current_technique_types.empty() ? techniqueTypeNameOnlyTests : allTests; -} + AddMatchers({create.String().Capture(CAPTURE_TYPE_NAME), create.Char(':')}); + } + +protected: + void ProcessMatch(TechsetParserState *state, SequenceResult<SimpleParserValue> &result) const override { + const auto &typeNameToken = result.NextCapture(CAPTURE_TYPE_NAME); + + size_t techniqueTypeIndex; + if (!state->FindTechniqueTypeIndex(typeNameToken.StringValue(), techniqueTypeIndex)) + throw ParsingException(typeNameToken.GetPos(), "Unknown technique type name"); + + state->m_current_technique_types.push_back(techniqueTypeIndex); + } +}; + +class SequenceTechniqueName final : public TechsetParser::sequence_t { + static constexpr auto CAPTURE_NAME = 1; + +public: + SequenceTechniqueName() { + const SimpleMatcherFactory create(this); -std::unique_ptr<TechsetDefinition> TechsetParser::GetTechsetDefinition() const -{ - return std::move(m_state->m_definition); + AddMatchers({create.Or({create.Identifier(), create.String()}).Capture(CAPTURE_NAME), create.Char(';')}); + } + +protected: + void ProcessMatch(TechsetParserState *state, SequenceResult<SimpleParserValue> &result) const override { + assert(!state->m_current_technique_types.empty()); + + const auto &techniqueNameToken = result.NextCapture(CAPTURE_NAME); + const auto &techniqueName = + techniqueNameToken.m_type == SimpleParserValueType::STRING ? techniqueNameToken.StringValue() : techniqueNameToken.IdentifierValue(); + + for (const auto techniqueTypeIndex : state->m_current_technique_types) + state->m_definition->SetTechniqueByIndex(techniqueTypeIndex, techniqueName); + state->m_current_technique_types.clear(); + } +}; +} // namespace techset + +TechsetParser::TechsetParser(SimpleLexer *lexer, const char **validTechniqueTypeNames, const size_t validTechniqueTypeNameCount) + : AbstractParser(lexer, std::make_unique<TechsetParserState>(validTechniqueTypeNames, validTechniqueTypeNameCount)) {} + +const std::vector<TechsetParser::sequence_t *> &TechsetParser::GetTestsForState() { + static std::vector<sequence_t *> allTests({new SequenceTechniqueTypeName(), new SequenceTechniqueName()}); + static std::vector<sequence_t *> techniqueTypeNameOnlyTests({new SequenceTechniqueTypeName()}); + + return m_state->m_current_technique_types.empty() ? techniqueTypeNameOnlyTests : allTests; } + +std::unique_ptr<TechsetDefinition> TechsetParser::GetTechsetDefinition() const { return std::move(m_state->m_definition); } diff --git a/src/ObjLoading/Techset/Parsing/TechsetFileParser.h b/src/ObjLoading/Techset/Parsing/TechsetFileParser.h index cbe59df93..0f4f6c0d5 100644 --- a/src/ObjLoading/Techset/Parsing/TechsetFileParser.h +++ b/src/ObjLoading/Techset/Parsing/TechsetFileParser.h @@ -1,21 +1,19 @@ #pragma once -#include "Utils/ClassUtils.h" -#include "TechsetFileParserState.h" -#include "Techset/TechsetDefinition.h" +#include "Parsing/Impl/AbstractParser.h" #include "Parsing/Simple/SimpleLexer.h" #include "Parsing/Simple/SimpleParserValue.h" -#include "Parsing/Impl/AbstractParser.h" +#include "Techset/TechsetDefinition.h" +#include "TechsetFileParserState.h" +#include "Utils/ClassUtils.h" -namespace techset -{ - class TechsetParser final : public AbstractParser<SimpleParserValue, TechsetParserState> - { - protected: - const std::vector<sequence_t*>& GetTestsForState() override; +namespace techset { +class TechsetParser final : public AbstractParser<SimpleParserValue, TechsetParserState> { +protected: + const std::vector<sequence_t *> &GetTestsForState() override; - public: - TechsetParser(SimpleLexer* lexer, const char** validTechniqueTypeNames, size_t validTechniqueTypeNameCount); - _NODISCARD std::unique_ptr<TechsetDefinition> GetTechsetDefinition() const; - }; -} +public: + TechsetParser(SimpleLexer *lexer, const char **validTechniqueTypeNames, size_t validTechniqueTypeNameCount); + _NODISCARD std::unique_ptr<TechsetDefinition> GetTechsetDefinition() const; +}; +} // namespace techset diff --git a/src/ObjLoading/Techset/Parsing/TechsetFileParserState.cpp b/src/ObjLoading/Techset/Parsing/TechsetFileParserState.cpp index 78c89c757..a10736de3 100644 --- a/src/ObjLoading/Techset/Parsing/TechsetFileParserState.cpp +++ b/src/ObjLoading/Techset/Parsing/TechsetFileParserState.cpp @@ -2,24 +2,20 @@ using namespace techset; -TechsetParserState::TechsetParserState(const char** validTechniqueTypeNames, size_t validTechniqueTypeNameCount) - : m_definition(std::make_unique<TechsetDefinition>(validTechniqueTypeNameCount)) -{ - for (auto i = 0u; i < validTechniqueTypeNameCount; i++) - { - m_valid_technique_type_names.emplace(std::make_pair(std::string(validTechniqueTypeNames[i]), i)); - } +TechsetParserState::TechsetParserState(const char **validTechniqueTypeNames, size_t validTechniqueTypeNameCount) + : m_definition(std::make_unique<TechsetDefinition>(validTechniqueTypeNameCount)) { + for (auto i = 0u; i < validTechniqueTypeNameCount; i++) { + m_valid_technique_type_names.emplace(std::make_pair(std::string(validTechniqueTypeNames[i]), i)); + } } -bool TechsetParserState::FindTechniqueTypeIndex(const std::string& techniqueTypeName, size_t& techniqueTypeIndex) const -{ - const auto foundTechniqueType = m_valid_technique_type_names.find(techniqueTypeName); +bool TechsetParserState::FindTechniqueTypeIndex(const std::string &techniqueTypeName, size_t &techniqueTypeIndex) const { + const auto foundTechniqueType = m_valid_technique_type_names.find(techniqueTypeName); - if (foundTechniqueType != m_valid_technique_type_names.end()) - { - techniqueTypeIndex = foundTechniqueType->second; - return true; - } + if (foundTechniqueType != m_valid_technique_type_names.end()) { + techniqueTypeIndex = foundTechniqueType->second; + return true; + } - return false; + return false; } diff --git a/src/ObjLoading/Techset/Parsing/TechsetFileParserState.h b/src/ObjLoading/Techset/Parsing/TechsetFileParserState.h index ce0bad61e..1b821e4c1 100644 --- a/src/ObjLoading/Techset/Parsing/TechsetFileParserState.h +++ b/src/ObjLoading/Techset/Parsing/TechsetFileParserState.h @@ -6,17 +6,15 @@ #include "Techset/TechsetDefinition.h" -namespace techset -{ - class TechsetParserState - { - public: - std::map<std::string, size_t> m_valid_technique_type_names; - std::unique_ptr<TechsetDefinition> m_definition; - std::vector<size_t> m_current_technique_types; +namespace techset { +class TechsetParserState { +public: + std::map<std::string, size_t> m_valid_technique_type_names; + std::unique_ptr<TechsetDefinition> m_definition; + std::vector<size_t> m_current_technique_types; - TechsetParserState(const char** validTechniqueTypeNames, size_t validTechniqueTypeNameCount); + TechsetParserState(const char **validTechniqueTypeNames, size_t validTechniqueTypeNameCount); - bool FindTechniqueTypeIndex(const std::string& techniqueTypeName, size_t& techniqueTypeIndex) const; - }; -} + bool FindTechniqueTypeIndex(const std::string &techniqueTypeName, size_t &techniqueTypeIndex) const; +}; +} // namespace techset diff --git a/src/ObjLoading/Techset/TechniqueDefinitionAcceptor.cpp b/src/ObjLoading/Techset/TechniqueDefinitionAcceptor.cpp index e103aa338..5f2a05e0f 100644 --- a/src/ObjLoading/Techset/TechniqueDefinitionAcceptor.cpp +++ b/src/ObjLoading/Techset/TechniqueDefinitionAcceptor.cpp @@ -2,115 +2,57 @@ using namespace techset; -ShaderArgument::ShaderArgument() - : m_argument_index_specified(false), - m_argument_index(0u) -{ -} +ShaderArgument::ShaderArgument() : m_argument_index_specified(false), m_argument_index(0u) {} -ShaderArgument::ShaderArgument(std::string argumentName) - : m_argument_name(std::move(argumentName)), - m_argument_index_specified(false), - m_argument_index(0u) -{ -} +ShaderArgument::ShaderArgument(std::string argumentName) : m_argument_name(std::move(argumentName)), m_argument_index_specified(false), m_argument_index(0u) {} ShaderArgument::ShaderArgument(std::string argumentName, const size_t argumentIndex) - : m_argument_name(std::move(argumentName)), - m_argument_index_specified(true), - m_argument_index(argumentIndex) -{ -} + : m_argument_name(std::move(argumentName)), m_argument_index_specified(true), m_argument_index(argumentIndex) {} -ShaderArgumentCodeSource::ShaderArgumentCodeSource() - : m_index_accessor_specified(false), - m_index_accessor(0u) -{ -} +ShaderArgumentCodeSource::ShaderArgumentCodeSource() : m_index_accessor_specified(false), m_index_accessor(0u) {} ShaderArgumentCodeSource::ShaderArgumentCodeSource(std::vector<std::string> accessors) - : m_accessors(std::move(accessors)), - m_index_accessor_specified(false), - m_index_accessor(0u) -{ -} + : m_accessors(std::move(accessors)), m_index_accessor_specified(false), m_index_accessor(0u) {} ShaderArgumentCodeSource::ShaderArgumentCodeSource(std::vector<std::string> accessors, const size_t indexAccessor) - : m_accessors(std::move(accessors)), - m_index_accessor_specified(true), - m_index_accessor(indexAccessor) -{ -} + : m_accessors(std::move(accessors)), m_index_accessor_specified(true), m_index_accessor(indexAccessor) {} -ShaderArgumentLiteralSource::ShaderArgumentLiteralSource() - : m_value{} -{ -} +ShaderArgumentLiteralSource::ShaderArgumentLiteralSource() : m_value{} {} -ShaderArgumentLiteralSource::ShaderArgumentLiteralSource(const float v0, const float v1, const float v2, const float v3) - : m_value{v0, v1, v2, v3} -{ -} +ShaderArgumentLiteralSource::ShaderArgumentLiteralSource(const float v0, const float v1, const float v2, const float v3) : m_value{v0, v1, v2, v3} {} -ShaderArgumentLiteralSource::ShaderArgumentLiteralSource(float value[4]) - : m_value{value[0], value[1], value[2], value[3]} -{ -} +ShaderArgumentLiteralSource::ShaderArgumentLiteralSource(float value[4]) : m_value{value[0], value[1], value[2], value[3]} {} -namespace techset -{ - bool operator<(const ShaderArgumentLiteralSource& lhs, const ShaderArgumentLiteralSource& rhs) - { - if (lhs.m_value[0] < rhs.m_value[0]) - return true; - if (lhs.m_value[0] > rhs.m_value[0]) - return false; - if (lhs.m_value[1] < rhs.m_value[1]) - return true; - if (lhs.m_value[1] > rhs.m_value[1]) - return false; - if (lhs.m_value[2] < rhs.m_value[2]) - return true; - if (lhs.m_value[2] > rhs.m_value[2]) - return false; - if (lhs.m_value[3] < rhs.m_value[3]) - return true; - if (lhs.m_value[3] > rhs.m_value[3]) - return false; - return false; - } - - bool operator<=(const ShaderArgumentLiteralSource& lhs, const ShaderArgumentLiteralSource& rhs) - { - return !(rhs < lhs); - } - - bool operator>(const ShaderArgumentLiteralSource& lhs, const ShaderArgumentLiteralSource& rhs) - { - return rhs < lhs; - } - - bool operator>=(const ShaderArgumentLiteralSource& lhs, const ShaderArgumentLiteralSource& rhs) - { - return !(lhs < rhs); - } +namespace techset { +bool operator<(const ShaderArgumentLiteralSource &lhs, const ShaderArgumentLiteralSource &rhs) { + if (lhs.m_value[0] < rhs.m_value[0]) + return true; + if (lhs.m_value[0] > rhs.m_value[0]) + return false; + if (lhs.m_value[1] < rhs.m_value[1]) + return true; + if (lhs.m_value[1] > rhs.m_value[1]) + return false; + if (lhs.m_value[2] < rhs.m_value[2]) + return true; + if (lhs.m_value[2] > rhs.m_value[2]) + return false; + if (lhs.m_value[3] < rhs.m_value[3]) + return true; + if (lhs.m_value[3] > rhs.m_value[3]) + return false; + return false; } -ShaderArgumentMaterialSource::ShaderArgumentMaterialSource() - : m_is_hash(false), - m_hash(0u) -{ -} +bool operator<=(const ShaderArgumentLiteralSource &lhs, const ShaderArgumentLiteralSource &rhs) { return !(rhs < lhs); } -ShaderArgumentMaterialSource::ShaderArgumentMaterialSource(const size_t hash) - : m_is_hash(true), - m_hash(hash) -{ -} +bool operator>(const ShaderArgumentLiteralSource &lhs, const ShaderArgumentLiteralSource &rhs) { return rhs < lhs; } -ShaderArgumentMaterialSource::ShaderArgumentMaterialSource(std::string name) - : m_is_hash(false), - m_hash(0u), - m_name(std::move(name)) -{ -} +bool operator>=(const ShaderArgumentLiteralSource &lhs, const ShaderArgumentLiteralSource &rhs) { return !(lhs < rhs); } +} // namespace techset + +ShaderArgumentMaterialSource::ShaderArgumentMaterialSource() : m_is_hash(false), m_hash(0u) {} + +ShaderArgumentMaterialSource::ShaderArgumentMaterialSource(const size_t hash) : m_is_hash(true), m_hash(hash) {} + +ShaderArgumentMaterialSource::ShaderArgumentMaterialSource(std::string name) : m_is_hash(false), m_hash(0u), m_name(std::move(name)) {} diff --git a/src/ObjLoading/Techset/TechniqueDefinitionAcceptor.h b/src/ObjLoading/Techset/TechniqueDefinitionAcceptor.h index 2b1975a51..307f26865 100644 --- a/src/ObjLoading/Techset/TechniqueDefinitionAcceptor.h +++ b/src/ObjLoading/Techset/TechniqueDefinitionAcceptor.h @@ -3,89 +3,84 @@ #include <string> #include <vector> -namespace techset -{ - enum class ShaderSelector - { - VERTEX_SHADER, - PIXEL_SHADER - }; - - class ShaderArgument - { - public: - std::string m_argument_name; - bool m_argument_index_specified; - size_t m_argument_index; - - ShaderArgument(); - explicit ShaderArgument(std::string argumentName); - ShaderArgument(std::string argumentName, size_t argumentIndex); - }; - - class ShaderArgumentCodeSource - { - public: - std::vector<std::string> m_accessors; - bool m_index_accessor_specified; - size_t m_index_accessor; - - ShaderArgumentCodeSource(); - explicit ShaderArgumentCodeSource(std::vector<std::string> accessors); - ShaderArgumentCodeSource(std::vector<std::string> accessors, size_t indexAccessor); - }; - - class ShaderArgumentLiteralSource - { - public: - float m_value[4]; - - ShaderArgumentLiteralSource(); - ShaderArgumentLiteralSource(float v0, float v1, float v2, float v3); - explicit ShaderArgumentLiteralSource(float value[4]); - - friend bool operator<(const ShaderArgumentLiteralSource& lhs, const ShaderArgumentLiteralSource& rhs); - friend bool operator<=(const ShaderArgumentLiteralSource& lhs, const ShaderArgumentLiteralSource& rhs); - friend bool operator>(const ShaderArgumentLiteralSource& lhs, const ShaderArgumentLiteralSource& rhs); - friend bool operator>=(const ShaderArgumentLiteralSource& lhs, const ShaderArgumentLiteralSource& rhs); - }; - - class ShaderArgumentMaterialSource - { - public: - bool m_is_hash; - size_t m_hash; - std::string m_name; - - ShaderArgumentMaterialSource(); - explicit ShaderArgumentMaterialSource(size_t hash); - explicit ShaderArgumentMaterialSource(std::string name); - }; - - class ITechniqueDefinitionAcceptor - { - protected: - ITechniqueDefinitionAcceptor() = default; - public: - virtual ~ITechniqueDefinitionAcceptor() = default; - ITechniqueDefinitionAcceptor(const ITechniqueDefinitionAcceptor& other) = default; - ITechniqueDefinitionAcceptor(ITechniqueDefinitionAcceptor&& other) noexcept = default; - ITechniqueDefinitionAcceptor& operator=(const ITechniqueDefinitionAcceptor& other) = default; - ITechniqueDefinitionAcceptor& operator=(ITechniqueDefinitionAcceptor&& other) noexcept = default; - - virtual void AcceptNextPass() = 0; - virtual bool AcceptEndPass(std::string& errorMessage) = 0; - - virtual bool AcceptStateMap(const std::string& stateMapName, std::string& errorMessage) = 0; - - virtual bool AcceptVertexShader(const std::string& vertexShaderName, std::string& errorMessage) = 0; - virtual bool AcceptPixelShader(const std::string& pixelShaderName, std::string& errorMessage) = 0; - - virtual bool AcceptShaderConstantArgument(ShaderSelector shader, ShaderArgument shaderArgument, ShaderArgumentCodeSource source, std::string& errorMessage) = 0; - virtual bool AcceptShaderSamplerArgument(ShaderSelector shader, ShaderArgument shaderArgument, ShaderArgumentCodeSource source, std::string& errorMessage) = 0; - virtual bool AcceptShaderLiteralArgument(ShaderSelector shader, ShaderArgument shaderArgument, ShaderArgumentLiteralSource source, std::string& errorMessage) = 0; - virtual bool AcceptShaderMaterialArgument(ShaderSelector shader, ShaderArgument shaderArgument, ShaderArgumentMaterialSource source, std::string& errorMessage) = 0; - - virtual bool AcceptVertexStreamRouting(const std::string& destination, const std::string& source, std::string& errorMessage) = 0; - }; -} +namespace techset { +enum class ShaderSelector { VERTEX_SHADER, PIXEL_SHADER }; + +class ShaderArgument { +public: + std::string m_argument_name; + bool m_argument_index_specified; + size_t m_argument_index; + + ShaderArgument(); + explicit ShaderArgument(std::string argumentName); + ShaderArgument(std::string argumentName, size_t argumentIndex); +}; + +class ShaderArgumentCodeSource { +public: + std::vector<std::string> m_accessors; + bool m_index_accessor_specified; + size_t m_index_accessor; + + ShaderArgumentCodeSource(); + explicit ShaderArgumentCodeSource(std::vector<std::string> accessors); + ShaderArgumentCodeSource(std::vector<std::string> accessors, size_t indexAccessor); +}; + +class ShaderArgumentLiteralSource { +public: + float m_value[4]; + + ShaderArgumentLiteralSource(); + ShaderArgumentLiteralSource(float v0, float v1, float v2, float v3); + explicit ShaderArgumentLiteralSource(float value[4]); + + friend bool operator<(const ShaderArgumentLiteralSource &lhs, const ShaderArgumentLiteralSource &rhs); + friend bool operator<=(const ShaderArgumentLiteralSource &lhs, const ShaderArgumentLiteralSource &rhs); + friend bool operator>(const ShaderArgumentLiteralSource &lhs, const ShaderArgumentLiteralSource &rhs); + friend bool operator>=(const ShaderArgumentLiteralSource &lhs, const ShaderArgumentLiteralSource &rhs); +}; + +class ShaderArgumentMaterialSource { +public: + bool m_is_hash; + size_t m_hash; + std::string m_name; + + ShaderArgumentMaterialSource(); + explicit ShaderArgumentMaterialSource(size_t hash); + explicit ShaderArgumentMaterialSource(std::string name); +}; + +class ITechniqueDefinitionAcceptor { +protected: + ITechniqueDefinitionAcceptor() = default; + +public: + virtual ~ITechniqueDefinitionAcceptor() = default; + ITechniqueDefinitionAcceptor(const ITechniqueDefinitionAcceptor &other) = default; + ITechniqueDefinitionAcceptor(ITechniqueDefinitionAcceptor &&other) noexcept = default; + ITechniqueDefinitionAcceptor &operator=(const ITechniqueDefinitionAcceptor &other) = default; + ITechniqueDefinitionAcceptor &operator=(ITechniqueDefinitionAcceptor &&other) noexcept = default; + + virtual void AcceptNextPass() = 0; + virtual bool AcceptEndPass(std::string &errorMessage) = 0; + + virtual bool AcceptStateMap(const std::string &stateMapName, std::string &errorMessage) = 0; + + virtual bool AcceptVertexShader(const std::string &vertexShaderName, std::string &errorMessage) = 0; + virtual bool AcceptPixelShader(const std::string &pixelShaderName, std::string &errorMessage) = 0; + + virtual bool AcceptShaderConstantArgument(ShaderSelector shader, ShaderArgument shaderArgument, ShaderArgumentCodeSource source, + std::string &errorMessage) = 0; + virtual bool AcceptShaderSamplerArgument(ShaderSelector shader, ShaderArgument shaderArgument, ShaderArgumentCodeSource source, + std::string &errorMessage) = 0; + virtual bool AcceptShaderLiteralArgument(ShaderSelector shader, ShaderArgument shaderArgument, ShaderArgumentLiteralSource source, + std::string &errorMessage) = 0; + virtual bool AcceptShaderMaterialArgument(ShaderSelector shader, ShaderArgument shaderArgument, ShaderArgumentMaterialSource source, + std::string &errorMessage) = 0; + + virtual bool AcceptVertexStreamRouting(const std::string &destination, const std::string &source, std::string &errorMessage) = 0; +}; +} // namespace techset diff --git a/src/ObjLoading/Techset/TechniqueFileReader.cpp b/src/ObjLoading/Techset/TechniqueFileReader.cpp index 67d37fc75..e293d517f 100644 --- a/src/ObjLoading/Techset/TechniqueFileReader.cpp +++ b/src/ObjLoading/Techset/TechniqueFileReader.cpp @@ -2,37 +2,34 @@ #include <iostream> -#include "Parsing/TechniqueFileParser.h" #include "Parsing/Impl/CommentRemovingStreamProxy.h" #include "Parsing/Impl/ParserSingleInputStream.h" #include "Parsing/Simple/SimpleLexer.h" +#include "Parsing/TechniqueFileParser.h" using namespace techset; -TechniqueFileReader::TechniqueFileReader(std::istream& stream, std::string fileName, ITechniqueDefinitionAcceptor* acceptor) - : m_file_name(std::move(fileName)), - m_acceptor(acceptor) -{ - m_base_stream = std::make_unique<ParserSingleInputStream>(stream, m_file_name); - m_comment_proxy = std::make_unique<CommentRemovingStreamProxy>(m_base_stream.get()); +TechniqueFileReader::TechniqueFileReader(std::istream &stream, std::string fileName, ITechniqueDefinitionAcceptor *acceptor) + : m_file_name(std::move(fileName)), m_acceptor(acceptor) { + m_base_stream = std::make_unique<ParserSingleInputStream>(stream, m_file_name); + m_comment_proxy = std::make_unique<CommentRemovingStreamProxy>(m_base_stream.get()); } -bool TechniqueFileReader::ReadTechniqueDefinition() const -{ - SimpleLexer::Config lexerConfig; - lexerConfig.m_emit_new_line_tokens = false; - lexerConfig.m_read_strings = true; - lexerConfig.m_string_escape_sequences = false; - lexerConfig.m_read_integer_numbers = true; - lexerConfig.m_read_floating_point_numbers = true; - const auto lexer = std::make_unique<SimpleLexer>(m_comment_proxy.get(), std::move(lexerConfig)); +bool TechniqueFileReader::ReadTechniqueDefinition() const { + SimpleLexer::Config lexerConfig; + lexerConfig.m_emit_new_line_tokens = false; + lexerConfig.m_read_strings = true; + lexerConfig.m_string_escape_sequences = false; + lexerConfig.m_read_integer_numbers = true; + lexerConfig.m_read_floating_point_numbers = true; + const auto lexer = std::make_unique<SimpleLexer>(m_comment_proxy.get(), std::move(lexerConfig)); - const auto parser = std::make_unique<TechniqueParser>(lexer.get(), m_acceptor); + const auto parser = std::make_unique<TechniqueParser>(lexer.get(), m_acceptor); - const auto success = parser->Parse(); - if (success) - return true; + const auto success = parser->Parse(); + if (success) + return true; - std::cout << "Parsing technique file \"" << m_file_name << "\" failed!\n"; - return false; + std::cout << "Parsing technique file \"" << m_file_name << "\" failed!\n"; + return false; } diff --git a/src/ObjLoading/Techset/TechniqueFileReader.h b/src/ObjLoading/Techset/TechniqueFileReader.h index f508ea491..a8e9fd0bd 100644 --- a/src/ObjLoading/Techset/TechniqueFileReader.h +++ b/src/ObjLoading/Techset/TechniqueFileReader.h @@ -3,22 +3,20 @@ #include <memory> #include <string> -#include "Utils/ClassUtils.h" -#include "TechniqueDefinitionAcceptor.h" #include "Parsing/IParserLineStream.h" +#include "TechniqueDefinitionAcceptor.h" +#include "Utils/ClassUtils.h" -namespace techset -{ - class TechniqueFileReader - { - std::string m_file_name; - ITechniqueDefinitionAcceptor* m_acceptor; - std::unique_ptr<IParserLineStream> m_base_stream; - std::unique_ptr<IParserLineStream> m_comment_proxy; +namespace techset { +class TechniqueFileReader { + std::string m_file_name; + ITechniqueDefinitionAcceptor *m_acceptor; + std::unique_ptr<IParserLineStream> m_base_stream; + std::unique_ptr<IParserLineStream> m_comment_proxy; - public: - TechniqueFileReader(std::istream& stream, std::string fileName, ITechniqueDefinitionAcceptor* acceptor); +public: + TechniqueFileReader(std::istream &stream, std::string fileName, ITechniqueDefinitionAcceptor *acceptor); - _NODISCARD bool ReadTechniqueDefinition() const; - }; -} \ No newline at end of file + _NODISCARD bool ReadTechniqueDefinition() const; +}; +} // namespace techset \ No newline at end of file diff --git a/src/ObjLoading/Techset/TechniqueStateMapCache.cpp b/src/ObjLoading/Techset/TechniqueStateMapCache.cpp index f97713a64..4da44a0f1 100644 --- a/src/ObjLoading/Techset/TechniqueStateMapCache.cpp +++ b/src/ObjLoading/Techset/TechniqueStateMapCache.cpp @@ -2,32 +2,28 @@ using namespace techset; -const state_map::StateMapDefinition* TechniqueStateMapCache::GetCachedStateMap(const std::string& name) const -{ - const auto foundStateMap = m_state_map_cache.find(name); +const state_map::StateMapDefinition *TechniqueStateMapCache::GetCachedStateMap(const std::string &name) const { + const auto foundStateMap = m_state_map_cache.find(name); - if (foundStateMap != m_state_map_cache.end()) - return foundStateMap->second.get(); + if (foundStateMap != m_state_map_cache.end()) + return foundStateMap->second.get(); - return nullptr; + return nullptr; } -void TechniqueStateMapCache::AddStateMapToCache(std::unique_ptr<state_map::StateMapDefinition> stateMap) -{ - m_state_map_cache.emplace(std::make_pair(stateMap->m_name, std::move(stateMap))); +void TechniqueStateMapCache::AddStateMapToCache(std::unique_ptr<state_map::StateMapDefinition> stateMap) { + m_state_map_cache.emplace(std::make_pair(stateMap->m_name, std::move(stateMap))); } -const state_map::StateMapDefinition* TechniqueStateMapCache::GetStateMapForTechnique(const std::string& techniqueName) const -{ - const auto foundTechnique = m_state_map_per_technique.find(techniqueName); +const state_map::StateMapDefinition *TechniqueStateMapCache::GetStateMapForTechnique(const std::string &techniqueName) const { + const auto foundTechnique = m_state_map_per_technique.find(techniqueName); - if (foundTechnique != m_state_map_per_technique.end()) - return foundTechnique->second; + if (foundTechnique != m_state_map_per_technique.end()) + return foundTechnique->second; - return nullptr; + return nullptr; } -void TechniqueStateMapCache::SetTechniqueUsesStateMap(std::string techniqueName, const state_map::StateMapDefinition* stateMap) -{ - m_state_map_per_technique.emplace(std::make_pair(std::move(techniqueName), stateMap)); +void TechniqueStateMapCache::SetTechniqueUsesStateMap(std::string techniqueName, const state_map::StateMapDefinition *stateMap) { + m_state_map_per_technique.emplace(std::make_pair(std::move(techniqueName), stateMap)); } diff --git a/src/ObjLoading/Techset/TechniqueStateMapCache.h b/src/ObjLoading/Techset/TechniqueStateMapCache.h index 2b0eea239..93cc12988 100644 --- a/src/ObjLoading/Techset/TechniqueStateMapCache.h +++ b/src/ObjLoading/Techset/TechniqueStateMapCache.h @@ -5,22 +5,20 @@ #include <unordered_map> #include "AssetLoading/IZoneAssetLoaderState.h" -#include "Utils/ClassUtils.h" #include "StateMap/StateMapDefinition.h" +#include "Utils/ClassUtils.h" -namespace techset -{ - class TechniqueStateMapCache final : public IZoneAssetLoaderState - { - public: - _NODISCARD const state_map::StateMapDefinition* GetCachedStateMap(const std::string& name) const; - void AddStateMapToCache(std::unique_ptr<state_map::StateMapDefinition> stateMap); +namespace techset { +class TechniqueStateMapCache final : public IZoneAssetLoaderState { +public: + _NODISCARD const state_map::StateMapDefinition *GetCachedStateMap(const std::string &name) const; + void AddStateMapToCache(std::unique_ptr<state_map::StateMapDefinition> stateMap); - _NODISCARD const state_map::StateMapDefinition* GetStateMapForTechnique(const std::string& techniqueName) const; - void SetTechniqueUsesStateMap(std::string techniqueName, const state_map::StateMapDefinition* stateMap); + _NODISCARD const state_map::StateMapDefinition *GetStateMapForTechnique(const std::string &techniqueName) const; + void SetTechniqueUsesStateMap(std::string techniqueName, const state_map::StateMapDefinition *stateMap); - private: - std::unordered_map<std::string, const state_map::StateMapDefinition*> m_state_map_per_technique; - std::unordered_map<std::string, std::unique_ptr<state_map::StateMapDefinition>> m_state_map_cache; - }; -} +private: + std::unordered_map<std::string, const state_map::StateMapDefinition *> m_state_map_per_technique; + std::unordered_map<std::string, std::unique_ptr<state_map::StateMapDefinition>> m_state_map_cache; +}; +} // namespace techset diff --git a/src/ObjLoading/Techset/TechsetDefinition.cpp b/src/ObjLoading/Techset/TechsetDefinition.cpp index dc5cf268e..b46f36147 100644 --- a/src/ObjLoading/Techset/TechsetDefinition.cpp +++ b/src/ObjLoading/Techset/TechsetDefinition.cpp @@ -4,28 +4,22 @@ using namespace techset; -TechsetDefinition::TechsetDefinition(const size_t techniqueTypeCount) - : m_has_technique(techniqueTypeCount), - m_technique_names(techniqueTypeCount) -{ -} +TechsetDefinition::TechsetDefinition(const size_t techniqueTypeCount) : m_has_technique(techniqueTypeCount), m_technique_names(techniqueTypeCount) {} -bool TechsetDefinition::GetTechniqueByIndex(const size_t index, std::string& techniqueName) const -{ - assert(index < m_has_technique.size()); - if (index >= m_has_technique.size() || !m_has_technique[index]) - return false; +bool TechsetDefinition::GetTechniqueByIndex(const size_t index, std::string &techniqueName) const { + assert(index < m_has_technique.size()); + if (index >= m_has_technique.size() || !m_has_technique[index]) + return false; - techniqueName = m_technique_names[index]; - return true; + techniqueName = m_technique_names[index]; + return true; } -void TechsetDefinition::SetTechniqueByIndex(const size_t index, std::string techniqueName) -{ - assert(index < m_has_technique.size()); - if (index >= m_has_technique.size()) - return; +void TechsetDefinition::SetTechniqueByIndex(const size_t index, std::string techniqueName) { + assert(index < m_has_technique.size()); + if (index >= m_has_technique.size()) + return; - m_has_technique[index] = true; - m_technique_names[index] = std::move(techniqueName); + m_has_technique[index] = true; + m_technique_names[index] = std::move(techniqueName); } diff --git a/src/ObjLoading/Techset/TechsetDefinition.h b/src/ObjLoading/Techset/TechsetDefinition.h index 8dc533c3b..41c9651e6 100644 --- a/src/ObjLoading/Techset/TechsetDefinition.h +++ b/src/ObjLoading/Techset/TechsetDefinition.h @@ -3,16 +3,14 @@ #include <string> #include <vector> -namespace techset -{ - class TechsetDefinition - { - std::vector<bool> m_has_technique; - std::vector<std::string> m_technique_names; +namespace techset { +class TechsetDefinition { + std::vector<bool> m_has_technique; + std::vector<std::string> m_technique_names; - public: - explicit TechsetDefinition(size_t techniqueTypeCount); - bool GetTechniqueByIndex(size_t index, std::string& techniqueName) const; - void SetTechniqueByIndex(size_t index, std::string techniqueName); - }; -} +public: + explicit TechsetDefinition(size_t techniqueTypeCount); + bool GetTechniqueByIndex(size_t index, std::string &techniqueName) const; + void SetTechniqueByIndex(size_t index, std::string techniqueName); +}; +} // namespace techset diff --git a/src/ObjLoading/Techset/TechsetDefinitionCache.cpp b/src/ObjLoading/Techset/TechsetDefinitionCache.cpp index b4041b35d..4595e0944 100644 --- a/src/ObjLoading/Techset/TechsetDefinitionCache.cpp +++ b/src/ObjLoading/Techset/TechsetDefinitionCache.cpp @@ -2,17 +2,15 @@ using namespace techset; -TechsetDefinition* TechsetDefinitionCache::GetCachedTechsetDefinition(const std::string& techsetName) const -{ - const auto foundTechset = m_cache.find(techsetName); +TechsetDefinition *TechsetDefinitionCache::GetCachedTechsetDefinition(const std::string &techsetName) const { + const auto foundTechset = m_cache.find(techsetName); - if (foundTechset != m_cache.end()) - return foundTechset->second.get(); + if (foundTechset != m_cache.end()) + return foundTechset->second.get(); - return nullptr; + return nullptr; } -void TechsetDefinitionCache::AddTechsetDefinitionToCache(std::string name, std::unique_ptr<TechsetDefinition> definition) -{ - m_cache.emplace(std::make_pair(std::move(name), std::move(definition))); +void TechsetDefinitionCache::AddTechsetDefinitionToCache(std::string name, std::unique_ptr<TechsetDefinition> definition) { + m_cache.emplace(std::make_pair(std::move(name), std::move(definition))); } diff --git a/src/ObjLoading/Techset/TechsetDefinitionCache.h b/src/ObjLoading/Techset/TechsetDefinitionCache.h index 9ca3ad96d..2a3032016 100644 --- a/src/ObjLoading/Techset/TechsetDefinitionCache.h +++ b/src/ObjLoading/Techset/TechsetDefinitionCache.h @@ -1,22 +1,20 @@ #pragma once -#include <unordered_map> -#include <string> #include <memory> +#include <string> +#include <unordered_map> -#include "Utils/ClassUtils.h" -#include "TechsetDefinition.h" #include "AssetLoading/IZoneAssetLoaderState.h" +#include "TechsetDefinition.h" +#include "Utils/ClassUtils.h" -namespace techset -{ - class TechsetDefinitionCache final : public IZoneAssetLoaderState - { - public: - _NODISCARD TechsetDefinition* GetCachedTechsetDefinition(const std::string& techsetName) const; - void AddTechsetDefinitionToCache(std::string name, std::unique_ptr<TechsetDefinition> definition); +namespace techset { +class TechsetDefinitionCache final : public IZoneAssetLoaderState { +public: + _NODISCARD TechsetDefinition *GetCachedTechsetDefinition(const std::string &techsetName) const; + void AddTechsetDefinitionToCache(std::string name, std::unique_ptr<TechsetDefinition> definition); - private: - std::unordered_map<std::string, std::unique_ptr<TechsetDefinition>> m_cache; - }; -} +private: + std::unordered_map<std::string, std::unique_ptr<TechsetDefinition>> m_cache; +}; +} // namespace techset diff --git a/src/ObjLoading/Techset/TechsetFileReader.cpp b/src/ObjLoading/Techset/TechsetFileReader.cpp index 52fdd964d..82df697fe 100644 --- a/src/ObjLoading/Techset/TechsetFileReader.cpp +++ b/src/ObjLoading/Techset/TechsetFileReader.cpp @@ -2,37 +2,33 @@ #include <iostream> -#include "Parsing/TechsetFileParser.h" #include "Parsing/Impl/CommentRemovingStreamProxy.h" #include "Parsing/Impl/ParserSingleInputStream.h" +#include "Parsing/TechsetFileParser.h" using namespace techset; -TechsetFileReader::TechsetFileReader(std::istream& stream, std::string fileName, const char** validTechniqueTypeNames, const size_t validTechniqueTypeNameCount) - : m_file_name(std::move(fileName)), - m_valid_technique_type_names(validTechniqueTypeNames), - m_valid_technique_type_name_count(validTechniqueTypeNameCount) -{ - m_base_stream = std::make_unique<ParserSingleInputStream>(stream, m_file_name); - m_comment_proxy = std::make_unique<CommentRemovingStreamProxy>(m_base_stream.get()); +TechsetFileReader::TechsetFileReader(std::istream &stream, std::string fileName, const char **validTechniqueTypeNames, const size_t validTechniqueTypeNameCount) + : m_file_name(std::move(fileName)), m_valid_technique_type_names(validTechniqueTypeNames), m_valid_technique_type_name_count(validTechniqueTypeNameCount) { + m_base_stream = std::make_unique<ParserSingleInputStream>(stream, m_file_name); + m_comment_proxy = std::make_unique<CommentRemovingStreamProxy>(m_base_stream.get()); } -std::unique_ptr<techset::TechsetDefinition> TechsetFileReader::ReadTechsetDefinition() const -{ - SimpleLexer::Config lexerConfig; - lexerConfig.m_emit_new_line_tokens = false; - lexerConfig.m_read_strings = true; - lexerConfig.m_string_escape_sequences = false; - lexerConfig.m_read_integer_numbers = false; - lexerConfig.m_read_floating_point_numbers = false; - const auto lexer = std::make_unique<SimpleLexer>(m_comment_proxy.get(), std::move(lexerConfig)); +std::unique_ptr<techset::TechsetDefinition> TechsetFileReader::ReadTechsetDefinition() const { + SimpleLexer::Config lexerConfig; + lexerConfig.m_emit_new_line_tokens = false; + lexerConfig.m_read_strings = true; + lexerConfig.m_string_escape_sequences = false; + lexerConfig.m_read_integer_numbers = false; + lexerConfig.m_read_floating_point_numbers = false; + const auto lexer = std::make_unique<SimpleLexer>(m_comment_proxy.get(), std::move(lexerConfig)); - const auto parser = std::make_unique<techset::TechsetParser>(lexer.get(), m_valid_technique_type_names, m_valid_technique_type_name_count); + const auto parser = std::make_unique<techset::TechsetParser>(lexer.get(), m_valid_technique_type_names, m_valid_technique_type_name_count); - const auto success = parser->Parse(); - if (success) - return parser->GetTechsetDefinition(); + const auto success = parser->Parse(); + if (success) + return parser->GetTechsetDefinition(); - std::cout << "Parsing techset file \"" << m_file_name << "\" failed!\n"; - return {}; + std::cout << "Parsing techset file \"" << m_file_name << "\" failed!\n"; + return {}; } diff --git a/src/ObjLoading/Techset/TechsetFileReader.h b/src/ObjLoading/Techset/TechsetFileReader.h index d8eacb5ca..53c027056 100644 --- a/src/ObjLoading/Techset/TechsetFileReader.h +++ b/src/ObjLoading/Techset/TechsetFileReader.h @@ -3,23 +3,21 @@ #include <memory> #include <string> -#include "Utils/ClassUtils.h" -#include "TechsetDefinition.h" #include "Parsing/IParserLineStream.h" +#include "TechsetDefinition.h" +#include "Utils/ClassUtils.h" -namespace techset -{ - class TechsetFileReader - { - std::string m_file_name; - const char** m_valid_technique_type_names; - size_t m_valid_technique_type_name_count; - std::unique_ptr<IParserLineStream> m_base_stream; - std::unique_ptr<IParserLineStream> m_comment_proxy; +namespace techset { +class TechsetFileReader { + std::string m_file_name; + const char **m_valid_technique_type_names; + size_t m_valid_technique_type_name_count; + std::unique_ptr<IParserLineStream> m_base_stream; + std::unique_ptr<IParserLineStream> m_comment_proxy; - public: - TechsetFileReader(std::istream& stream, std::string fileName, const char** validTechniqueTypeNames, size_t validTechniqueTypeNameCount); +public: + TechsetFileReader(std::istream &stream, std::string fileName, const char **validTechniqueTypeNames, size_t validTechniqueTypeNameCount); - _NODISCARD std::unique_ptr<TechsetDefinition> ReadTechsetDefinition() const; - }; -} + _NODISCARD std::unique_ptr<TechsetDefinition> ReadTechsetDefinition() const; +}; +} // namespace techset diff --git a/src/ObjWriting/Dumping/AbstractAssetDumper.h b/src/ObjWriting/Dumping/AbstractAssetDumper.h index a18b5e6f5..c722414b8 100644 --- a/src/ObjWriting/Dumping/AbstractAssetDumper.h +++ b/src/ObjWriting/Dumping/AbstractAssetDumper.h @@ -2,28 +2,20 @@ #include "IAssetDumper.h" -template<class T> -class AbstractAssetDumper : public IAssetDumper<T> -{ +template <class T> class AbstractAssetDumper : public IAssetDumper<T> { protected: - virtual bool ShouldDump(XAssetInfo<T>* asset) - { - return true; - } + virtual bool ShouldDump(XAssetInfo<T> *asset) { return true; } - virtual void DumpAsset(AssetDumpingContext& context, XAssetInfo<T>* asset) = 0; + virtual void DumpAsset(AssetDumpingContext &context, XAssetInfo<T> *asset) = 0; public: - void DumpPool(AssetDumpingContext& context, AssetPool<T>* pool) override - { - for (auto assetInfo : *pool) - { - if (assetInfo->m_name[0] == ',' || !ShouldDump(assetInfo)) - { - continue; - } + void DumpPool(AssetDumpingContext &context, AssetPool<T> *pool) override { + for (auto assetInfo : *pool) { + if (assetInfo->m_name[0] == ',' || !ShouldDump(assetInfo)) { + continue; + } - DumpAsset(context, assetInfo); - } + DumpAsset(context, assetInfo); } + } }; diff --git a/src/ObjWriting/Dumping/AbstractTextDumper.cpp b/src/ObjWriting/Dumping/AbstractTextDumper.cpp index 5dcb847f2..93b0f31be 100644 --- a/src/ObjWriting/Dumping/AbstractTextDumper.cpp +++ b/src/ObjWriting/Dumping/AbstractTextDumper.cpp @@ -2,27 +2,17 @@ #include <cassert> -AbstractTextDumper::AbstractTextDumper(std::ostream& stream) - : m_stream(stream), - m_indent(0u) -{ +AbstractTextDumper::AbstractTextDumper(std::ostream &stream) : m_stream(stream), m_indent(0u) {} +void AbstractTextDumper::Indent() const { + for (auto i = 0u; i < m_indent; i++) + m_stream << " "; } -void AbstractTextDumper::Indent() const -{ - for (auto i = 0u; i < m_indent; i++) - m_stream << " "; -} - -void AbstractTextDumper::IncIndent() -{ - ++m_indent; -} +void AbstractTextDumper::IncIndent() { ++m_indent; } -void AbstractTextDumper::DecIndent() -{ - assert(m_indent > 0); - if (m_indent > 0) - m_indent--; +void AbstractTextDumper::DecIndent() { + assert(m_indent > 0); + if (m_indent > 0) + m_indent--; } \ No newline at end of file diff --git a/src/ObjWriting/Dumping/AbstractTextDumper.h b/src/ObjWriting/Dumping/AbstractTextDumper.h index 38ff119d5..24552e4f1 100644 --- a/src/ObjWriting/Dumping/AbstractTextDumper.h +++ b/src/ObjWriting/Dumping/AbstractTextDumper.h @@ -2,15 +2,14 @@ #include <ostream> -class AbstractTextDumper -{ +class AbstractTextDumper { protected: - std::ostream& m_stream; - size_t m_indent; + std::ostream &m_stream; + size_t m_indent; - void Indent() const; - void IncIndent(); - void DecIndent(); + void Indent() const; + void IncIndent(); + void DecIndent(); - explicit AbstractTextDumper(std::ostream& stream); + explicit AbstractTextDumper(std::ostream &stream); }; \ No newline at end of file diff --git a/src/ObjWriting/Dumping/AssetDumpingContext.cpp b/src/ObjWriting/Dumping/AssetDumpingContext.cpp index 9d6bfd1cc..d5cc335b5 100644 --- a/src/ObjWriting/Dumping/AssetDumpingContext.cpp +++ b/src/ObjWriting/Dumping/AssetDumpingContext.cpp @@ -3,27 +3,22 @@ #include <filesystem> #include <fstream> -AssetDumpingContext::AssetDumpingContext() - : m_zone(nullptr) -{ -} +AssetDumpingContext::AssetDumpingContext() : m_zone(nullptr) {} -std::unique_ptr<std::ostream> AssetDumpingContext::OpenAssetFile(const std::string& fileName) const -{ - std::filesystem::path assetFilePath(m_base_path); - assetFilePath.append(fileName); +std::unique_ptr<std::ostream> AssetDumpingContext::OpenAssetFile(const std::string &fileName) const { + std::filesystem::path assetFilePath(m_base_path); + assetFilePath.append(fileName); - auto assetFileFolder(assetFilePath); - assetFileFolder.replace_filename(""); - create_directories(assetFileFolder); + auto assetFileFolder(assetFilePath); + assetFileFolder.replace_filename(""); + create_directories(assetFileFolder); - auto file = std::make_unique<std::ofstream>(assetFilePath, std::fstream::out | std::fstream::binary); + auto file = std::make_unique<std::ofstream>(assetFilePath, std::fstream::out | std::fstream::binary); - if (!file->is_open()) - { - std::cout << "Failed to open file '" << assetFilePath.string() << "' to dump asset '" << fileName << "'\n"; - return nullptr; - } + if (!file->is_open()) { + std::cout << "Failed to open file '" << assetFilePath.string() << "' to dump asset '" << fileName << "'\n"; + return nullptr; + } - return std::move(file); + return std::move(file); } diff --git a/src/ObjWriting/Dumping/AssetDumpingContext.h b/src/ObjWriting/Dumping/AssetDumpingContext.h index 9e38bf29e..8636fbd93 100644 --- a/src/ObjWriting/Dumping/AssetDumpingContext.h +++ b/src/ObjWriting/Dumping/AssetDumpingContext.h @@ -1,42 +1,39 @@ #pragma once -#include <string> -#include <ostream> #include <memory> +#include <ostream> +#include <string> #include <typeindex> #include "IZoneAssetDumperState.h" -#include "Utils/ClassUtils.h" #include "Obj/Gdt/GdtStream.h" +#include "Utils/ClassUtils.h" #include "Zone/Zone.h" -class AssetDumpingContext -{ - std::unordered_map<std::type_index, std::unique_ptr<IZoneAssetDumperState>> m_zone_asset_dumper_states; +class AssetDumpingContext { + std::unordered_map<std::type_index, std::unique_ptr<IZoneAssetDumperState>> m_zone_asset_dumper_states; public: - Zone* m_zone; - std::string m_base_path; - std::unique_ptr<GdtOutputStream> m_gdt; - - AssetDumpingContext(); - - _NODISCARD std::unique_ptr<std::ostream> OpenAssetFile(const std::string& fileName) const; - - template<typename T> - T* GetZoneAssetDumperState() - { - static_assert(std::is_base_of_v<IZoneAssetDumperState, T>, "T must inherit IZoneAssetDumperState"); - // T must also have a public default constructor - - const auto foundEntry = m_zone_asset_dumper_states.find(typeid(T)); - if (foundEntry != m_zone_asset_dumper_states.end()) - return dynamic_cast<T*>(foundEntry->second.get()); - - auto newState = std::make_unique<T>(); - newState->SetZone(m_zone); - auto* newStatePtr = newState.get(); - m_zone_asset_dumper_states.emplace(std::make_pair<std::type_index, std::unique_ptr<IZoneAssetDumperState>>(typeid(T), std::move(newState))); - return newStatePtr; - } + Zone *m_zone; + std::string m_base_path; + std::unique_ptr<GdtOutputStream> m_gdt; + + AssetDumpingContext(); + + _NODISCARD std::unique_ptr<std::ostream> OpenAssetFile(const std::string &fileName) const; + + template <typename T> T *GetZoneAssetDumperState() { + static_assert(std::is_base_of_v<IZoneAssetDumperState, T>, "T must inherit IZoneAssetDumperState"); + // T must also have a public default constructor + + const auto foundEntry = m_zone_asset_dumper_states.find(typeid(T)); + if (foundEntry != m_zone_asset_dumper_states.end()) + return dynamic_cast<T *>(foundEntry->second.get()); + + auto newState = std::make_unique<T>(); + newState->SetZone(m_zone); + auto *newStatePtr = newState.get(); + m_zone_asset_dumper_states.emplace(std::make_pair<std::type_index, std::unique_ptr<IZoneAssetDumperState>>(typeid(T), std::move(newState))); + return newStatePtr; + } }; diff --git a/src/ObjWriting/Dumping/IAssetDumper.h b/src/ObjWriting/Dumping/IAssetDumper.h index 8efa5fe6e..112071637 100644 --- a/src/ObjWriting/Dumping/IAssetDumper.h +++ b/src/ObjWriting/Dumping/IAssetDumper.h @@ -3,16 +3,14 @@ #include "AssetDumpingContext.h" #include "Pool/AssetPool.h" -template<class T> -class IAssetDumper -{ +template <class T> class IAssetDumper { public: - IAssetDumper() = default; - virtual ~IAssetDumper() = default; - IAssetDumper(const IAssetDumper& other) = default; - IAssetDumper(IAssetDumper&& other) noexcept = default; - IAssetDumper& operator=(const IAssetDumper& other) = default; - IAssetDumper& operator=(IAssetDumper&& other) noexcept = default; + IAssetDumper() = default; + virtual ~IAssetDumper() = default; + IAssetDumper(const IAssetDumper &other) = default; + IAssetDumper(IAssetDumper &&other) noexcept = default; + IAssetDumper &operator=(const IAssetDumper &other) = default; + IAssetDumper &operator=(IAssetDumper &&other) noexcept = default; - virtual void DumpPool(AssetDumpingContext& context, AssetPool<T>* pool) = 0; + virtual void DumpPool(AssetDumpingContext &context, AssetPool<T> *pool) = 0; }; \ No newline at end of file diff --git a/src/ObjWriting/Dumping/IZoneAssetDumperState.h b/src/ObjWriting/Dumping/IZoneAssetDumperState.h index ad12d5e51..3c0d8a88e 100644 --- a/src/ObjWriting/Dumping/IZoneAssetDumperState.h +++ b/src/ObjWriting/Dumping/IZoneAssetDumperState.h @@ -1,20 +1,18 @@ #pragma once #include "Zone/Zone.h" -class IZoneAssetDumperState -{ +class IZoneAssetDumperState { protected: - IZoneAssetDumperState() = default; + IZoneAssetDumperState() = default; public: - virtual ~IZoneAssetDumperState() = default; - IZoneAssetDumperState(const IZoneAssetDumperState& other) = default; - IZoneAssetDumperState(IZoneAssetDumperState&& other) noexcept = default; - IZoneAssetDumperState& operator=(const IZoneAssetDumperState& other) = default; - IZoneAssetDumperState& operator=(IZoneAssetDumperState&& other) noexcept = default; + virtual ~IZoneAssetDumperState() = default; + IZoneAssetDumperState(const IZoneAssetDumperState &other) = default; + IZoneAssetDumperState(IZoneAssetDumperState &&other) noexcept = default; + IZoneAssetDumperState &operator=(const IZoneAssetDumperState &other) = default; + IZoneAssetDumperState &operator=(IZoneAssetDumperState &&other) noexcept = default; - virtual void SetZone(Zone* zone) - { - // Do nothing by default - } + virtual void SetZone(Zone *zone) { + // Do nothing by default + } }; diff --git a/src/ObjWriting/Dumping/IZoneDumper.h b/src/ObjWriting/Dumping/IZoneDumper.h index 8f17ba99a..192c4da64 100644 --- a/src/ObjWriting/Dumping/IZoneDumper.h +++ b/src/ObjWriting/Dumping/IZoneDumper.h @@ -2,16 +2,15 @@ #include "AssetDumpingContext.h" -class IZoneDumper -{ +class IZoneDumper { public: - IZoneDumper() = default; - virtual ~IZoneDumper() = default; - IZoneDumper(const IZoneDumper& other) = default; - IZoneDumper(IZoneDumper&& other) noexcept = default; - IZoneDumper& operator=(const IZoneDumper& other) = default; - IZoneDumper& operator=(IZoneDumper&& other) noexcept = default; + IZoneDumper() = default; + virtual ~IZoneDumper() = default; + IZoneDumper(const IZoneDumper &other) = default; + IZoneDumper(IZoneDumper &&other) noexcept = default; + IZoneDumper &operator=(const IZoneDumper &other) = default; + IZoneDumper &operator=(IZoneDumper &&other) noexcept = default; - virtual bool CanHandleZone(AssetDumpingContext& assetDumpingContext) const = 0; - virtual bool DumpZone(AssetDumpingContext& assetDumpingContext) const = 0; + virtual bool CanHandleZone(AssetDumpingContext &assetDumpingContext) const = 0; + virtual bool DumpZone(AssetDumpingContext &assetDumpingContext) const = 0; }; \ No newline at end of file diff --git a/src/ObjWriting/Dumping/Localize/StringFileDumper.cpp b/src/ObjWriting/Dumping/Localize/StringFileDumper.cpp index ba0ae1008..a0b8f0520 100644 --- a/src/ObjWriting/Dumping/Localize/StringFileDumper.cpp +++ b/src/ObjWriting/Dumping/Localize/StringFileDumper.cpp @@ -3,73 +3,56 @@ #include "Utils/StringUtils.h" -StringFileDumper::StringFileDumper(Zone* zone, std::ostream& stream) - : AbstractTextDumper(stream), - m_zone(zone), - m_language_caps("ENGLISH"), - m_wrote_header(false) -{ -} +StringFileDumper::StringFileDumper(Zone *zone, std::ostream &stream) + : AbstractTextDumper(stream), m_zone(zone), m_language_caps("ENGLISH"), m_wrote_header(false) {} -void StringFileDumper::SetLanguageName(std::string language) -{ - m_language_caps = std::move(language); - for (auto& c : m_language_caps) c = toupper(c); +void StringFileDumper::SetLanguageName(std::string language) { + m_language_caps = std::move(language); + for (auto &c : m_language_caps) + c = toupper(c); } -void StringFileDumper::SetConfigFile(std::string configFile) -{ - m_config_file = std::move(configFile); -} +void StringFileDumper::SetConfigFile(std::string configFile) { m_config_file = std::move(configFile); } -void StringFileDumper::SetNotes(std::string notes) -{ - m_notes = std::move(notes); -} +void StringFileDumper::SetNotes(std::string notes) { m_notes = std::move(notes); } -void StringFileDumper::WriteHeader() -{ - m_stream << "// Dumped from fastfile \"" << m_zone->m_name << "\".\n"; - m_stream << "// In their original format the strings might have been separated in multiple files.\n"; - m_stream << "VERSION \"1\"\n"; - m_stream << "CONFIG \"" << m_config_file << "\"\n"; - m_stream << "FILENOTES \"" << m_notes << "\"\n"; +void StringFileDumper::WriteHeader() { + m_stream << "// Dumped from fastfile \"" << m_zone->m_name << "\".\n"; + m_stream << "// In their original format the strings might have been separated in multiple files.\n"; + m_stream << "VERSION \"1\"\n"; + m_stream << "CONFIG \"" << m_config_file << "\"\n"; + m_stream << "FILENOTES \"" << m_notes << "\"\n"; - m_wrote_header = true; + m_wrote_header = true; } -void StringFileDumper::WriteReference(const std::string& reference) const -{ - if (reference.find_first_not_of(utils::LETTERS_AL_NUM_UNDERSCORE) != std::string::npos) - { - m_stream << "REFERENCE \""; +void StringFileDumper::WriteReference(const std::string &reference) const { + if (reference.find_first_not_of(utils::LETTERS_AL_NUM_UNDERSCORE) != std::string::npos) { + m_stream << "REFERENCE \""; - utils::EscapeStringForQuotationMarks(m_stream, reference); + utils::EscapeStringForQuotationMarks(m_stream, reference); - m_stream << "\"\n"; - } - else - m_stream << "REFERENCE " << reference << "\n"; + m_stream << "\"\n"; + } else + m_stream << "REFERENCE " << reference << "\n"; } -void StringFileDumper::WriteLocalizeEntry(const std::string& reference, const std::string& value) -{ - if (!m_wrote_header) - WriteHeader(); +void StringFileDumper::WriteLocalizeEntry(const std::string &reference, const std::string &value) { + if (!m_wrote_header) + WriteHeader(); - m_stream << "\n"; - WriteReference(reference); + m_stream << "\n"; + WriteReference(reference); - const auto valueSpacing = std::string(15 - m_language_caps.length(), ' '); - m_stream << "LANG_" << m_language_caps << valueSpacing << "\""; - utils::EscapeStringForQuotationMarks(m_stream, value); - m_stream << "\"\n"; + const auto valueSpacing = std::string(15 - m_language_caps.length(), ' '); + m_stream << "LANG_" << m_language_caps << valueSpacing << "\""; + utils::EscapeStringForQuotationMarks(m_stream, value); + m_stream << "\"\n"; } -void StringFileDumper::Finalize() -{ - if (!m_wrote_header) - WriteHeader(); +void StringFileDumper::Finalize() { + if (!m_wrote_header) + WriteHeader(); - m_stream << "\nENDMARKER"; + m_stream << "\nENDMARKER"; } diff --git a/src/ObjWriting/Dumping/Localize/StringFileDumper.h b/src/ObjWriting/Dumping/Localize/StringFileDumper.h index a78464c48..97a1d4f2e 100644 --- a/src/ObjWriting/Dumping/Localize/StringFileDumper.h +++ b/src/ObjWriting/Dumping/Localize/StringFileDumper.h @@ -3,27 +3,26 @@ #include "Dumping/AbstractTextDumper.h" #include "Zone/Zone.h" -class StringFileDumper : AbstractTextDumper -{ - Zone* m_zone; +class StringFileDumper : AbstractTextDumper { + Zone *m_zone; - std::string m_config_file; - std::string m_notes; - std::string m_language_caps; + std::string m_config_file; + std::string m_notes; + std::string m_language_caps; - bool m_wrote_header; + bool m_wrote_header; - void WriteHeader(); - void WriteReference(const std::string& reference) const; + void WriteHeader(); + void WriteReference(const std::string &reference) const; public: - StringFileDumper(Zone* zone, std::ostream& stream); + StringFileDumper(Zone *zone, std::ostream &stream); - void SetConfigFile(std::string configFile); - void SetNotes(std::string notes); - void SetLanguageName(std::string language); + void SetConfigFile(std::string configFile); + void SetNotes(std::string notes); + void SetLanguageName(std::string language); - void WriteLocalizeEntry(const std::string& reference, const std::string& value); + void WriteLocalizeEntry(const std::string &reference, const std::string &value); - void Finalize(); + void Finalize(); }; diff --git a/src/ObjWriting/Dumping/MapFile/MapFileDumper.cpp b/src/ObjWriting/Dumping/MapFile/MapFileDumper.cpp index a524ac573..539379569 100644 --- a/src/ObjWriting/Dumping/MapFile/MapFileDumper.cpp +++ b/src/ObjWriting/Dumping/MapFile/MapFileDumper.cpp @@ -3,160 +3,126 @@ #include <cassert> #include <iomanip> -MapFileDumper::Vec3::Vec3(const float x, const float y, const float z) - : v{} -{ - m_x = x; - m_y = y; - m_z = z; +MapFileDumper::Vec3::Vec3(const float x, const float y, const float z) : v{} { + m_x = x; + m_y = y; + m_z = z; } -MapFileDumper::Vec3::Vec3(float v[3]) - : v{v[0], v[1], v[2]} -{ -} +MapFileDumper::Vec3::Vec3(float v[3]) : v{v[0], v[1], v[2]} {} MapFileDumper::PhysicsBox::PhysicsBox(const Vec3 middlePoint, const Vec3 halfSize, const Vec3 orientationX, const Vec3 orientationY, const Vec3 orientationZ) - : m_middle_point(middlePoint), - m_half_size(halfSize), - m_orientation{orientationX, orientationY, orientationZ} -{ -} + : m_middle_point(middlePoint), m_half_size(halfSize), m_orientation{orientationX, orientationY, orientationZ} {} MapFileDumper::PhysicsCylinder::PhysicsCylinder(const Vec3 middlePoint, const float radius, const float height, const Vec3 orientation) - : m_middle_point(middlePoint), - m_radius(radius), - m_height(height), - m_orientation(orientation) -{ -} + : m_middle_point(middlePoint), m_radius(radius), m_height(height), m_orientation(orientation) {} -MapFileDumper::MapFileDumper(std::ostream& stream) - : AbstractTextDumper(stream), - m_flags{}, - m_entity_index(0u), - m_brush_index(0u) -{ -} +MapFileDumper::MapFileDumper(std::ostream &stream) : AbstractTextDumper(stream), m_flags{}, m_entity_index(0u), m_brush_index(0u) {} -void MapFileDumper::Init() const -{ - m_stream << "iwmap 4\n"; - m_stream << "\"000_Global\" flags active\n"; - m_stream << "\"The Map\" flags\n"; +void MapFileDumper::Init() const { + m_stream << "iwmap 4\n"; + m_stream << "\"000_Global\" flags active\n"; + m_stream << "\"The Map\" flags\n"; } -void MapFileDumper::WriteComment(const std::string& key) const -{ - Indent(); - m_stream << "// " << key << "\n"; +void MapFileDumper::WriteComment(const std::string &key) const { + Indent(); + m_stream << "// " << key << "\n"; } -void MapFileDumper::BeginEntity() -{ - assert(!m_flags.m_in_entity); - if (m_flags.m_in_entity) - return; +void MapFileDumper::BeginEntity() { + assert(!m_flags.m_in_entity); + if (m_flags.m_in_entity) + return; - Indent(); - m_stream << "// entity " << m_entity_index << "\n"; + Indent(); + m_stream << "// entity " << m_entity_index << "\n"; - Indent(); - m_stream << "{\n"; + Indent(); + m_stream << "{\n"; - IncIndent(); - m_entity_index++; - m_brush_index = 0; - m_flags.m_in_entity = true; + IncIndent(); + m_entity_index++; + m_brush_index = 0; + m_flags.m_in_entity = true; } -void MapFileDumper::EndEntity() -{ - assert(m_flags.m_in_entity); - if (!m_flags.m_in_entity) - return; +void MapFileDumper::EndEntity() { + assert(m_flags.m_in_entity); + if (!m_flags.m_in_entity) + return; - DecIndent(); - Indent(); - m_stream << "}\n"; - m_flags.m_in_entity = false; + DecIndent(); + Indent(); + m_stream << "}\n"; + m_flags.m_in_entity = false; } -void MapFileDumper::BeginBrush() -{ - assert(m_flags.m_in_entity && !m_flags.m_in_brush); - if (m_flags.m_in_brush) - return; +void MapFileDumper::BeginBrush() { + assert(m_flags.m_in_entity && !m_flags.m_in_brush); + if (m_flags.m_in_brush) + return; - Indent(); - m_stream << "// brush " << m_brush_index << "\n"; + Indent(); + m_stream << "// brush " << m_brush_index << "\n"; - Indent(); - m_stream << "{\n"; + Indent(); + m_stream << "{\n"; - IncIndent(); - m_brush_index++; - m_flags.m_in_brush = true; + IncIndent(); + m_brush_index++; + m_flags.m_in_brush = true; } -void MapFileDumper::EndBrush() -{ - assert(m_flags.m_in_entity && m_flags.m_in_brush); - if (!m_flags.m_in_brush) - return; +void MapFileDumper::EndBrush() { + assert(m_flags.m_in_entity && m_flags.m_in_brush); + if (!m_flags.m_in_brush) + return; - DecIndent(); - Indent(); - m_stream << "}\n"; - m_flags.m_in_brush = false; + DecIndent(); + Indent(); + m_stream << "}\n"; + m_flags.m_in_brush = false; } -void MapFileDumper::WriteKeyValue(const std::string& key, const std::string& value) const -{ - assert(m_flags.m_in_brush || m_flags.m_in_entity); +void MapFileDumper::WriteKeyValue(const std::string &key, const std::string &value) const { + assert(m_flags.m_in_brush || m_flags.m_in_entity); - Indent(); - m_stream << "\"" << key << "\" \"" << value << "\"\n"; + Indent(); + m_stream << "\"" << key << "\" \"" << value << "\"\n"; } -void MapFileDumper::WritePhysicsBox(const PhysicsBox box) -{ - Indent(); - m_stream << "physics_box\n"; - Indent(); - m_stream << "{\n"; - IncIndent(); - - Indent(); - m_stream << std::fixed << std::setprecision(6) - << box.m_orientation[0].m_x << " " << box.m_orientation[0].m_y << " " << box.m_orientation[0].m_z - << " " << box.m_orientation[1].m_x << " " << box.m_orientation[1].m_y << " " << box.m_orientation[1].m_z - << " " << box.m_orientation[2].m_x << " " << box.m_orientation[2].m_y << " " << box.m_orientation[2].m_z - << " " << box.m_middle_point.m_x << " " << box.m_middle_point.m_y << " " << box.m_middle_point.m_z - << " " << box.m_half_size.m_x << " " << box.m_half_size.m_y << " " << box.m_half_size.m_z - << "\n"; - - DecIndent(); - Indent(); - m_stream << "}\n"; +void MapFileDumper::WritePhysicsBox(const PhysicsBox box) { + Indent(); + m_stream << "physics_box\n"; + Indent(); + m_stream << "{\n"; + IncIndent(); + + Indent(); + m_stream << std::fixed << std::setprecision(6) << box.m_orientation[0].m_x << " " << box.m_orientation[0].m_y << " " << box.m_orientation[0].m_z << " " + << box.m_orientation[1].m_x << " " << box.m_orientation[1].m_y << " " << box.m_orientation[1].m_z << " " << box.m_orientation[2].m_x << " " + << box.m_orientation[2].m_y << " " << box.m_orientation[2].m_z << " " << box.m_middle_point.m_x << " " << box.m_middle_point.m_y << " " + << box.m_middle_point.m_z << " " << box.m_half_size.m_x << " " << box.m_half_size.m_y << " " << box.m_half_size.m_z << "\n"; + + DecIndent(); + Indent(); + m_stream << "}\n"; } -void MapFileDumper::WritePhysicsCylinder(PhysicsCylinder cylinder) -{ - Indent(); - m_stream << "physics_cylinder\n"; - Indent(); - m_stream << "{\n"; - IncIndent(); - - Indent(); - m_stream << std::fixed << std::setprecision(6) - << cylinder.m_orientation.m_x << " " << cylinder.m_orientation.m_y << " " << cylinder.m_orientation.m_z - << " " << cylinder.m_middle_point.m_x << " " << cylinder.m_middle_point.m_y << " " << cylinder.m_middle_point.m_z - << " " << cylinder.m_height << " " << cylinder.m_radius - << "\n"; - - DecIndent(); - Indent(); - m_stream << "}\n"; +void MapFileDumper::WritePhysicsCylinder(PhysicsCylinder cylinder) { + Indent(); + m_stream << "physics_cylinder\n"; + Indent(); + m_stream << "{\n"; + IncIndent(); + + Indent(); + m_stream << std::fixed << std::setprecision(6) << cylinder.m_orientation.m_x << " " << cylinder.m_orientation.m_y << " " << cylinder.m_orientation.m_z << " " + << cylinder.m_middle_point.m_x << " " << cylinder.m_middle_point.m_y << " " << cylinder.m_middle_point.m_z << " " << cylinder.m_height << " " + << cylinder.m_radius << "\n"; + + DecIndent(); + Indent(); + m_stream << "}\n"; } diff --git a/src/ObjWriting/Dumping/MapFile/MapFileDumper.h b/src/ObjWriting/Dumping/MapFile/MapFileDumper.h index fd8f20ec8..b0fee6047 100644 --- a/src/ObjWriting/Dumping/MapFile/MapFileDumper.h +++ b/src/ObjWriting/Dumping/MapFile/MapFileDumper.h @@ -4,66 +4,60 @@ #include "Dumping/AbstractTextDumper.h" -class MapFileDumper : AbstractTextDumper -{ +class MapFileDumper : AbstractTextDumper { public: - union Vec3 - { - struct - { - float m_x; - float m_y; - float m_z; - }; - - float v[3]; - - Vec3(float x, float y, float z); - explicit Vec3(float v[3]); + union Vec3 { + struct { + float m_x; + float m_y; + float m_z; }; - struct PhysicsBox - { - Vec3 m_middle_point; - Vec3 m_half_size; - Vec3 m_orientation[3]; + float v[3]; - PhysicsBox(Vec3 middlePoint, Vec3 halfSize, Vec3 orientationX, Vec3 orientationY, Vec3 orientationZ); - }; + Vec3(float x, float y, float z); + explicit Vec3(float v[3]); + }; - struct PhysicsCylinder - { - Vec3 m_middle_point; - float m_radius; - float m_height; - Vec3 m_orientation; + struct PhysicsBox { + Vec3 m_middle_point; + Vec3 m_half_size; + Vec3 m_orientation[3]; - PhysicsCylinder(Vec3 middlePoint, float radius, float height, Vec3 orientation); - }; + PhysicsBox(Vec3 middlePoint, Vec3 halfSize, Vec3 orientationX, Vec3 orientationY, Vec3 orientationZ); + }; + + struct PhysicsCylinder { + Vec3 m_middle_point; + float m_radius; + float m_height; + Vec3 m_orientation; + + PhysicsCylinder(Vec3 middlePoint, float radius, float height, Vec3 orientation); + }; private: - struct - { - bool m_in_entity : 1; - bool m_in_brush : 1; - } m_flags; + struct { + bool m_in_entity : 1; + bool m_in_brush : 1; + } m_flags; - size_t m_entity_index; - size_t m_brush_index; + size_t m_entity_index; + size_t m_brush_index; public: - explicit MapFileDumper(std::ostream& stream); + explicit MapFileDumper(std::ostream &stream); - void Init() const; - void WriteComment(const std::string& key) const; + void Init() const; + void WriteComment(const std::string &key) const; - void BeginEntity(); - void EndEntity(); + void BeginEntity(); + void EndEntity(); - void BeginBrush(); - void EndBrush(); + void BeginBrush(); + void EndBrush(); - void WriteKeyValue(const std::string& key, const std::string& value) const; - void WritePhysicsBox(PhysicsBox box); - void WritePhysicsCylinder(PhysicsCylinder cylinder); + void WriteKeyValue(const std::string &key, const std::string &value) const; + void WritePhysicsBox(PhysicsBox box); + void WritePhysicsCylinder(PhysicsCylinder cylinder); }; diff --git a/src/ObjWriting/Dumping/SndCurve/SndCurveDumper.cpp b/src/ObjWriting/Dumping/SndCurve/SndCurveDumper.cpp index 789a59872..efb9adfc9 100644 --- a/src/ObjWriting/Dumping/SndCurve/SndCurveDumper.cpp +++ b/src/ObjWriting/Dumping/SndCurve/SndCurveDumper.cpp @@ -3,42 +3,31 @@ #include <cassert> #include <iomanip> -SndCurveDumper::SndCurveDumper(std::ostream& stream) - : SndCurveDumper(stream, DEFAULT_PRECISION) -{ -} +SndCurveDumper::SndCurveDumper(std::ostream &stream) : SndCurveDumper(stream, DEFAULT_PRECISION) {} -SndCurveDumper::SndCurveDumper(std::ostream& stream, const size_t precision) - : AbstractTextDumper(stream), - m_precision(precision), - m_current_knot(0u), - m_total_knots(0u) -{ -} +SndCurveDumper::SndCurveDumper(std::ostream &stream, const size_t precision) + : AbstractTextDumper(stream), m_precision(precision), m_current_knot(0u), m_total_knots(0u) {} -void SndCurveDumper::Init(const size_t totalKnots) -{ - m_total_knots = totalKnots; - m_current_knot = 0; +void SndCurveDumper::Init(const size_t totalKnots) { + m_total_knots = totalKnots; + m_current_knot = 0; - m_stream << "SNDCURVE\n\n"; - m_stream << totalKnots; + m_stream << "SNDCURVE\n\n"; + m_stream << totalKnots; } -void SndCurveDumper::WriteKnot(const float x, const float y) -{ - assert(m_current_knot < m_total_knots); +void SndCurveDumper::WriteKnot(const float x, const float y) { + assert(m_current_knot < m_total_knots); - m_stream << "\n" << std::fixed << std::setprecision(m_precision) << x << " " << y; + m_stream << "\n" << std::fixed << std::setprecision(m_precision) << x << " " << y; - m_current_knot++; + m_current_knot++; } -void SndCurveDumper::WriteKnot(const double x, const double y) -{ - assert(m_current_knot < m_total_knots); +void SndCurveDumper::WriteKnot(const double x, const double y) { + assert(m_current_knot < m_total_knots); - m_stream << x << " " << y << "\n"; + m_stream << x << " " << y << "\n"; - m_current_knot++; + m_current_knot++; } diff --git a/src/ObjWriting/Dumping/SndCurve/SndCurveDumper.h b/src/ObjWriting/Dumping/SndCurve/SndCurveDumper.h index 5394bce0b..b93dca2ec 100644 --- a/src/ObjWriting/Dumping/SndCurve/SndCurveDumper.h +++ b/src/ObjWriting/Dumping/SndCurve/SndCurveDumper.h @@ -4,19 +4,18 @@ #include "Dumping/AbstractTextDumper.h" -class SndCurveDumper : AbstractTextDumper -{ - static constexpr auto DEFAULT_PRECISION = 4; +class SndCurveDumper : AbstractTextDumper { + static constexpr auto DEFAULT_PRECISION = 4; - size_t m_precision; - size_t m_current_knot; - size_t m_total_knots; + size_t m_precision; + size_t m_current_knot; + size_t m_total_knots; public: - explicit SndCurveDumper(std::ostream& stream); - SndCurveDumper(std::ostream& stream, size_t precision); + explicit SndCurveDumper(std::ostream &stream); + SndCurveDumper(std::ostream &stream, size_t precision); - void Init(size_t totalKnots); - void WriteKnot(float x, float y); - void WriteKnot(double x, double y); + void Init(size_t totalKnots); + void WriteKnot(float x, float y); + void WriteKnot(double x, double y); }; diff --git a/src/ObjWriting/Game/IW3/AssetDumpers/AssetDumperGfxImage.cpp b/src/ObjWriting/Game/IW3/AssetDumpers/AssetDumperGfxImage.cpp index 2fc3b4704..5e01fb503 100644 --- a/src/ObjWriting/Game/IW3/AssetDumpers/AssetDumperGfxImage.cpp +++ b/src/ObjWriting/Game/IW3/AssetDumpers/AssetDumperGfxImage.cpp @@ -2,62 +2,55 @@ #include <cassert> -#include "ObjWriting.h" -#include "Image/IwiWriter6.h" #include "Image/DdsWriter.h" +#include "Image/IwiWriter6.h" +#include "ObjWriting.h" using namespace IW3; -AssetDumperGfxImage::AssetDumperGfxImage() -{ - switch (ObjWriting::Configuration.ImageOutputFormat) - { - case ObjWriting::Configuration_t::ImageOutputFormat_e::DDS: - m_writer = std::make_unique<DdsWriter>(); - break; - case ObjWriting::Configuration_t::ImageOutputFormat_e::IWI: - m_writer = std::make_unique<iwi6::IwiWriter>(); - break; - default: - assert(false); - m_writer = nullptr; - break; - } +AssetDumperGfxImage::AssetDumperGfxImage() { + switch (ObjWriting::Configuration.ImageOutputFormat) { + case ObjWriting::Configuration_t::ImageOutputFormat_e::DDS: + m_writer = std::make_unique<DdsWriter>(); + break; + case ObjWriting::Configuration_t::ImageOutputFormat_e::IWI: + m_writer = std::make_unique<iwi6::IwiWriter>(); + break; + default: + assert(false); + m_writer = nullptr; + break; + } } -bool AssetDumperGfxImage::ShouldDump(XAssetInfo<GfxImage>* asset) -{ - const auto* image = asset->Asset(); - return image->cardMemory.platform[0] > 0; +bool AssetDumperGfxImage::ShouldDump(XAssetInfo<GfxImage> *asset) { + const auto *image = asset->Asset(); + return image->cardMemory.platform[0] > 0; } -std::string AssetDumperGfxImage::GetAssetFileName(XAssetInfo<GfxImage>* asset) const -{ - std::string cleanAssetName = asset->m_name; - for (auto& c : cleanAssetName) - { - switch (c) - { - case '*': - c = '_'; - break; - - default: - break; - } +std::string AssetDumperGfxImage::GetAssetFileName(XAssetInfo<GfxImage> *asset) const { + std::string cleanAssetName = asset->m_name; + for (auto &c : cleanAssetName) { + switch (c) { + case '*': + c = '_'; + break; + + default: + break; } + } - return "images/" + cleanAssetName + m_writer->GetFileExtension(); + return "images/" + cleanAssetName + m_writer->GetFileExtension(); } -void AssetDumperGfxImage::DumpAsset(AssetDumpingContext& context, XAssetInfo<GfxImage>* asset) -{ - const auto* image = asset->Asset(); - const auto assetFile = context.OpenAssetFile(GetAssetFileName(asset)); +void AssetDumperGfxImage::DumpAsset(AssetDumpingContext &context, XAssetInfo<GfxImage> *asset) { + const auto *image = asset->Asset(); + const auto assetFile = context.OpenAssetFile(GetAssetFileName(asset)); - if (!assetFile) - return; + if (!assetFile) + return; - auto& stream = *assetFile; - m_writer->DumpImage(stream, image->texture.texture); + auto &stream = *assetFile; + m_writer->DumpImage(stream, image->texture.texture); } diff --git a/src/ObjWriting/Game/IW3/AssetDumpers/AssetDumperGfxImage.h b/src/ObjWriting/Game/IW3/AssetDumpers/AssetDumperGfxImage.h index 0c42f400b..9e03a9794 100644 --- a/src/ObjWriting/Game/IW3/AssetDumpers/AssetDumperGfxImage.h +++ b/src/ObjWriting/Game/IW3/AssetDumpers/AssetDumperGfxImage.h @@ -6,19 +6,17 @@ #include "Game/IW3/IW3.h" #include "Image/IImageWriter.h" -namespace IW3 -{ - class AssetDumperGfxImage final : public AbstractAssetDumper<GfxImage> - { - std::unique_ptr<IImageWriter> m_writer; +namespace IW3 { +class AssetDumperGfxImage final : public AbstractAssetDumper<GfxImage> { + std::unique_ptr<IImageWriter> m_writer; - std::string GetAssetFileName(XAssetInfo<GfxImage>* asset) const; + std::string GetAssetFileName(XAssetInfo<GfxImage> *asset) const; - protected: - bool ShouldDump(XAssetInfo<GfxImage>* asset) override; - void DumpAsset(AssetDumpingContext& context, XAssetInfo<GfxImage>* asset) override; +protected: + bool ShouldDump(XAssetInfo<GfxImage> *asset) override; + void DumpAsset(AssetDumpingContext &context, XAssetInfo<GfxImage> *asset) override; - public: - AssetDumperGfxImage(); - }; -} +public: + AssetDumperGfxImage(); +}; +} // namespace IW3 diff --git a/src/ObjWriting/Game/IW3/AssetDumpers/AssetDumperLoadedSound.cpp b/src/ObjWriting/Game/IW3/AssetDumpers/AssetDumperLoadedSound.cpp index 52c00d832..b883007c3 100644 --- a/src/ObjWriting/Game/IW3/AssetDumpers/AssetDumperLoadedSound.cpp +++ b/src/ObjWriting/Game/IW3/AssetDumpers/AssetDumperLoadedSound.cpp @@ -4,69 +4,47 @@ using namespace IW3; -bool AssetDumperLoadedSound::ShouldDump(XAssetInfo<LoadedSound>* asset) -{ - return true; +bool AssetDumperLoadedSound::ShouldDump(XAssetInfo<LoadedSound> *asset) { return true; } + +void AssetDumperLoadedSound::DumpWavPcm(AssetDumpingContext &context, const LoadedSound *asset, std::ostream &stream) { + const auto riffMasterChunkSize = sizeof(WAV_CHUNK_ID_RIFF) + sizeof(uint32_t) + sizeof(WAV_WAVE_ID) + sizeof(WavChunkHeader) + sizeof(WavFormatChunkPcm) + + sizeof(WavChunkHeader) + sizeof(asset->sound.info.data_len); + + stream.write(reinterpret_cast<const char *>(&WAV_CHUNK_ID_RIFF), sizeof(WAV_CHUNK_ID_RIFF)); + stream.write(reinterpret_cast<const char *>(&riffMasterChunkSize), sizeof(riffMasterChunkSize)); + stream.write(reinterpret_cast<const char *>(&WAV_WAVE_ID), sizeof(WAV_WAVE_ID)); + + const WavChunkHeader formatChunkHeader{WAV_CHUNK_ID_FMT, sizeof(WavFormatChunkPcm)}; + stream.write(reinterpret_cast<const char *>(&formatChunkHeader), sizeof(formatChunkHeader)); + + WavFormatChunkPcm formatChunk{WavFormat::PCM, + static_cast<uint16_t>(asset->sound.info.channels), + asset->sound.info.rate, + asset->sound.info.rate * asset->sound.info.channels * asset->sound.info.bits / 8, + static_cast<uint16_t>(asset->sound.info.block_size), + static_cast<uint16_t>(asset->sound.info.bits)}; + stream.write(reinterpret_cast<const char *>(&formatChunk), sizeof(formatChunk)); + + const WavChunkHeader dataChunkHeader{WAV_CHUNK_ID_DATA, asset->sound.info.data_len}; + stream.write(reinterpret_cast<const char *>(&dataChunkHeader), sizeof(dataChunkHeader)); + stream.write(asset->sound.data, asset->sound.info.data_len); } -void AssetDumperLoadedSound::DumpWavPcm(AssetDumpingContext& context, const LoadedSound* asset, std::ostream& stream) -{ - const auto riffMasterChunkSize = sizeof(WAV_CHUNK_ID_RIFF) - + sizeof(uint32_t) - + sizeof(WAV_WAVE_ID) - + sizeof(WavChunkHeader) - + sizeof(WavFormatChunkPcm) - + sizeof(WavChunkHeader) - + sizeof(asset->sound.info.data_len); +void AssetDumperLoadedSound::DumpAsset(AssetDumpingContext &context, XAssetInfo<LoadedSound> *asset) { + const auto *loadedSound = asset->Asset(); + const auto assetFile = context.OpenAssetFile("sound/" + asset->m_name); - stream.write(reinterpret_cast<const char*>(&WAV_CHUNK_ID_RIFF), sizeof(WAV_CHUNK_ID_RIFF)); - stream.write(reinterpret_cast<const char*>(&riffMasterChunkSize), sizeof(riffMasterChunkSize)); - stream.write(reinterpret_cast<const char*>(&WAV_WAVE_ID), sizeof(WAV_WAVE_ID)); + if (!assetFile) + return; - const WavChunkHeader formatChunkHeader - { - WAV_CHUNK_ID_FMT, - sizeof(WavFormatChunkPcm) - }; - stream.write(reinterpret_cast<const char*>(&formatChunkHeader), sizeof(formatChunkHeader)); + auto &stream = *assetFile; + switch (static_cast<WavFormat>(loadedSound->sound.info.format)) { + case WavFormat::PCM: + DumpWavPcm(context, loadedSound, stream); + break; - WavFormatChunkPcm formatChunk - { - WavFormat::PCM, - static_cast<uint16_t>(asset->sound.info.channels), - asset->sound.info.rate, - asset->sound.info.rate * asset->sound.info.channels * asset->sound.info.bits / 8, - static_cast<uint16_t>(asset->sound.info.block_size), - static_cast<uint16_t>(asset->sound.info.bits) - }; - stream.write(reinterpret_cast<const char*>(&formatChunk), sizeof(formatChunk)); - - const WavChunkHeader dataChunkHeader - { - WAV_CHUNK_ID_DATA, - asset->sound.info.data_len - }; - stream.write(reinterpret_cast<const char*>(&dataChunkHeader), sizeof(dataChunkHeader)); - stream.write(asset->sound.data, asset->sound.info.data_len); -} - -void AssetDumperLoadedSound::DumpAsset(AssetDumpingContext& context, XAssetInfo<LoadedSound>* asset) -{ - const auto* loadedSound = asset->Asset(); - const auto assetFile = context.OpenAssetFile("sound/" + asset->m_name); - - if (!assetFile) - return; - - auto& stream = *assetFile; - switch (static_cast<WavFormat>(loadedSound->sound.info.format)) - { - case WavFormat::PCM: - DumpWavPcm(context, loadedSound, stream); - break; - - default: - printf("Unknown format %i for loaded sound: %s\n", loadedSound->sound.info.format, loadedSound->name); - break; - } + default: + printf("Unknown format %i for loaded sound: %s\n", loadedSound->sound.info.format, loadedSound->name); + break; + } } diff --git a/src/ObjWriting/Game/IW3/AssetDumpers/AssetDumperLoadedSound.h b/src/ObjWriting/Game/IW3/AssetDumpers/AssetDumperLoadedSound.h index 91ed3f7ef..9dcb988ce 100644 --- a/src/ObjWriting/Game/IW3/AssetDumpers/AssetDumperLoadedSound.h +++ b/src/ObjWriting/Game/IW3/AssetDumpers/AssetDumperLoadedSound.h @@ -3,14 +3,12 @@ #include "Dumping/AbstractAssetDumper.h" #include "Game/IW3/IW3.h" -namespace IW3 -{ - class AssetDumperLoadedSound final : public AbstractAssetDumper<LoadedSound> - { - static void DumpWavPcm(AssetDumpingContext& context, const LoadedSound* asset, std::ostream& stream); +namespace IW3 { +class AssetDumperLoadedSound final : public AbstractAssetDumper<LoadedSound> { + static void DumpWavPcm(AssetDumpingContext &context, const LoadedSound *asset, std::ostream &stream); - protected: - bool ShouldDump(XAssetInfo<LoadedSound>* asset) override; - void DumpAsset(AssetDumpingContext& context, XAssetInfo<LoadedSound>* asset) override; - }; -} +protected: + bool ShouldDump(XAssetInfo<LoadedSound> *asset) override; + void DumpAsset(AssetDumpingContext &context, XAssetInfo<LoadedSound> *asset) override; +}; +} // namespace IW3 diff --git a/src/ObjWriting/Game/IW3/AssetDumpers/AssetDumperLocalizeEntry.cpp b/src/ObjWriting/Game/IW3/AssetDumpers/AssetDumperLocalizeEntry.cpp index 8c1b8e08e..4ed62e46d 100644 --- a/src/ObjWriting/Game/IW3/AssetDumpers/AssetDumperLocalizeEntry.cpp +++ b/src/ObjWriting/Game/IW3/AssetDumpers/AssetDumperLocalizeEntry.cpp @@ -2,42 +2,37 @@ #include <sstream> -#include "Localize/LocalizeCommon.h" #include "Dumping/Localize/StringFileDumper.h" +#include "Localize/LocalizeCommon.h" using namespace IW3; -void AssetDumperLocalizeEntry::DumpPool(AssetDumpingContext& context, AssetPool<LocalizeEntry>* pool) -{ - if (pool->m_asset_lookup.empty()) - return; - - const auto language = LocalizeCommon::GetNameOfLanguage(context.m_zone->m_language); +void AssetDumperLocalizeEntry::DumpPool(AssetDumpingContext &context, AssetPool<LocalizeEntry> *pool) { + if (pool->m_asset_lookup.empty()) + return; - std::ostringstream ss; - ss << language << "/localizedstrings/" << context.m_zone->m_name << ".str"; - const auto assetFile = context.OpenAssetFile(ss.str()); + const auto language = LocalizeCommon::GetNameOfLanguage(context.m_zone->m_language); - if (assetFile) - { - StringFileDumper stringFileDumper(context.m_zone, *assetFile); + std::ostringstream ss; + ss << language << "/localizedstrings/" << context.m_zone->m_name << ".str"; + const auto assetFile = context.OpenAssetFile(ss.str()); - stringFileDumper.SetLanguageName(language); + if (assetFile) { + StringFileDumper stringFileDumper(context.m_zone, *assetFile); - // Magic string. Original string files do have this config file. The purpose of the config file is unknown though. - stringFileDumper.SetConfigFile(R"(C:/trees/cod3/cod3/bin/StringEd.cfg)"); + stringFileDumper.SetLanguageName(language); - stringFileDumper.SetNotes(""); + // Magic string. Original string files do have this config file. The purpose of the config file is unknown though. + stringFileDumper.SetConfigFile(R"(C:/trees/cod3/cod3/bin/StringEd.cfg)"); - for (auto* localizeEntry : *pool) - { - stringFileDumper.WriteLocalizeEntry(localizeEntry->m_name, localizeEntry->Asset()->value); - } + stringFileDumper.SetNotes(""); - stringFileDumper.Finalize(); - } - else - { - printf("Could not create string file for dumping localized strings of zone '%s'\n", context.m_zone->m_name.c_str()); + for (auto *localizeEntry : *pool) { + stringFileDumper.WriteLocalizeEntry(localizeEntry->m_name, localizeEntry->Asset()->value); } + + stringFileDumper.Finalize(); + } else { + printf("Could not create string file for dumping localized strings of zone '%s'\n", context.m_zone->m_name.c_str()); + } } \ No newline at end of file diff --git a/src/ObjWriting/Game/IW3/AssetDumpers/AssetDumperLocalizeEntry.h b/src/ObjWriting/Game/IW3/AssetDumpers/AssetDumperLocalizeEntry.h index fdb1c2739..3a3ee0395 100644 --- a/src/ObjWriting/Game/IW3/AssetDumpers/AssetDumperLocalizeEntry.h +++ b/src/ObjWriting/Game/IW3/AssetDumpers/AssetDumperLocalizeEntry.h @@ -3,11 +3,9 @@ #include "Dumping/AbstractAssetDumper.h" #include "Game/IW3/IW3.h" -namespace IW3 -{ - class AssetDumperLocalizeEntry final : public IAssetDumper<LocalizeEntry> - { - public: - void DumpPool(AssetDumpingContext& context, AssetPool<LocalizeEntry>* pool) override; - }; -} +namespace IW3 { +class AssetDumperLocalizeEntry final : public IAssetDumper<LocalizeEntry> { +public: + void DumpPool(AssetDumpingContext &context, AssetPool<LocalizeEntry> *pool) override; +}; +} // namespace IW3 diff --git a/src/ObjWriting/Game/IW3/AssetDumpers/AssetDumperMapEnts.cpp b/src/ObjWriting/Game/IW3/AssetDumpers/AssetDumperMapEnts.cpp index 9e9cd4412..51ebdd91f 100644 --- a/src/ObjWriting/Game/IW3/AssetDumpers/AssetDumperMapEnts.cpp +++ b/src/ObjWriting/Game/IW3/AssetDumpers/AssetDumperMapEnts.cpp @@ -2,19 +2,15 @@ using namespace IW3; -bool AssetDumperMapEnts::ShouldDump(XAssetInfo<MapEnts>* asset) -{ - return true; -} +bool AssetDumperMapEnts::ShouldDump(XAssetInfo<MapEnts> *asset) { return true; } -void AssetDumperMapEnts::DumpAsset(AssetDumpingContext& context, XAssetInfo<MapEnts>* asset) -{ - const auto* mapEnts = asset->Asset(); - const auto assetFile = context.OpenAssetFile(asset->m_name + ".ents"); +void AssetDumperMapEnts::DumpAsset(AssetDumpingContext &context, XAssetInfo<MapEnts> *asset) { + const auto *mapEnts = asset->Asset(); + const auto assetFile = context.OpenAssetFile(asset->m_name + ".ents"); - if (!assetFile) - return; + if (!assetFile) + return; - auto& stream = *assetFile; - stream.write(mapEnts->entityString, mapEnts->numEntityChars); + auto &stream = *assetFile; + stream.write(mapEnts->entityString, mapEnts->numEntityChars); } diff --git a/src/ObjWriting/Game/IW3/AssetDumpers/AssetDumperMapEnts.h b/src/ObjWriting/Game/IW3/AssetDumpers/AssetDumperMapEnts.h index 36da6a8e6..91db9eacd 100644 --- a/src/ObjWriting/Game/IW3/AssetDumpers/AssetDumperMapEnts.h +++ b/src/ObjWriting/Game/IW3/AssetDumpers/AssetDumperMapEnts.h @@ -3,12 +3,10 @@ #include "Dumping/AbstractAssetDumper.h" #include "Game/IW3/IW3.h" -namespace IW3 -{ - class AssetDumperMapEnts final : public AbstractAssetDumper<MapEnts> - { - protected: - bool ShouldDump(XAssetInfo<MapEnts>* asset) override; - void DumpAsset(AssetDumpingContext& context, XAssetInfo<MapEnts>* asset) override; - }; -} +namespace IW3 { +class AssetDumperMapEnts final : public AbstractAssetDumper<MapEnts> { +protected: + bool ShouldDump(XAssetInfo<MapEnts> *asset) override; + void DumpAsset(AssetDumpingContext &context, XAssetInfo<MapEnts> *asset) override; +}; +} // namespace IW3 diff --git a/src/ObjWriting/Game/IW3/AssetDumpers/AssetDumperMaterial.cpp b/src/ObjWriting/Game/IW3/AssetDumpers/AssetDumperMaterial.cpp index 006133f1a..78ad5b68d 100644 --- a/src/ObjWriting/Game/IW3/AssetDumpers/AssetDumperMaterial.cpp +++ b/src/ObjWriting/Game/IW3/AssetDumpers/AssetDumperMaterial.cpp @@ -1,487 +1,378 @@ #include "AssetDumperMaterial.h" #include <iomanip> -#include <sstream> #include <nlohmann/json.hpp> +#include <sstream> #include "Game/IW3/MaterialConstantsIW3.h" #include "Game/IW3/TechsetConstantsIW3.h" -//#define FLAGS_DEBUG 1 +// #define FLAGS_DEBUG 1 using namespace IW3; using json = nlohmann::json; -namespace IW3 -{ - const char* AssetName(const char* name) - { - if (name && name[0] == ',') - return &name[1]; - return name; - } +namespace IW3 { +const char *AssetName(const char *name) { + if (name && name[0] == ',') + return &name[1]; + return name; +} - template <size_t S> - json ArrayEntry(const char* (&a)[S], const size_t index) - { - assert(index < S); - if (index < S) - return a[index]; +template <size_t S> json ArrayEntry(const char *(&a)[S], const size_t index) { + assert(index < S); + if (index < S) + return a[index]; - return json{}; - } + return json{}; +} - json BuildComplexTableJson(const complex_s* complexTable, const size_t count) - { - auto jArray = json::array(); - - if (complexTable) - { - for (auto index = 0u; index < count; index++) - { - const auto& entry = complexTable[index]; - jArray.emplace_back(json{ - {"real", entry.real}, - {"imag", entry.imag} - }); - } - } +json BuildComplexTableJson(const complex_s *complexTable, const size_t count) { + auto jArray = json::array(); - return jArray; + if (complexTable) { + for (auto index = 0u; index < count; index++) { + const auto &entry = complexTable[index]; + jArray.emplace_back(json{ + {"real", entry.real}, + {"imag", entry.imag} + }); } + } - json BuildWaterJson(water_t* water) - { - if (!water) - return json{}; - - return json{ - {"floatTime", water->writable.floatTime}, - {"H0", BuildComplexTableJson(water->H0, water->M * water->N)}, - {"wTerm", water->wTerm ? json{std::vector(water->wTerm, water->wTerm + (water->M * water->N))} : json::array()}, - {"M", water->M}, - {"N", water->N}, - {"Lx", water->Lx}, - {"Lz", water->Lz}, - {"windvel", water->windvel}, - {"winddir", std::vector(std::begin(water->winddir), std::end(water->winddir))}, - {"amplitude", water->amplitude}, - {"codeConstant", std::vector(std::begin(water->codeConstant), std::end(water->codeConstant))}, - {"image", water->image && water->image->name ? AssetName(water->image->name) : nullptr} - }; - } + return jArray; +} - json BuildSamplerStateJson(unsigned char samplerState) - { - static const char* samplerFilterNames[] - { - "none", - "nearest", - "linear", - "aniso2x", - "aniso4x" - }; - static const char* samplerMipmapNames[] - { - "disabled", - "nearest", - "linear" - }; - - return json{ - {"filter", ArrayEntry(samplerFilterNames, (samplerState & SAMPLER_FILTER_MASK) >> SAMPLER_FILTER_SHIFT)}, - {"mipmap", ArrayEntry(samplerMipmapNames, (samplerState & SAMPLER_MIPMAP_MASK) >> SAMPLER_MIPMAP_SHIFT)}, - {"clampU", (samplerState & SAMPLER_CLAMP_U) ? true : false}, - {"clampV", (samplerState & SAMPLER_CLAMP_V) ? true : false}, - {"clampW", (samplerState & SAMPLER_CLAMP_W) ? true : false}, - }; - } +json BuildWaterJson(water_t *water) { + if (!water) + return json{}; + + return json{ + {"floatTime", water->writable.floatTime}, + {"H0", BuildComplexTableJson(water->H0, water->M * water->N)}, + {"wTerm", water->wTerm ? json{std::vector(water->wTerm, water->wTerm + (water->M * water->N))} : json::array()}, + {"M", water->M}, + {"N", water->N}, + {"Lx", water->Lx}, + {"Lz", water->Lz}, + {"windvel", water->windvel}, + {"winddir", std::vector(std::begin(water->winddir), std::end(water->winddir))}, + {"amplitude", water->amplitude}, + {"codeConstant", std::vector(std::begin(water->codeConstant), std::end(water->codeConstant))}, + {"image", water->image && water->image->name ? AssetName(water->image->name) : nullptr} + }; +} - json BuildTextureTableJson(const MaterialTextureDef* textureTable, const size_t count) - { - static const char* semanticNames[] - { - "2d", - "function", - "colorMap", - "unused1", - "unused2", - "normalMap", - "unused3", - "unused4", - "specularMap", - "unused5", - "unused6", - "waterMap" - }; - - auto jArray = json::array(); - - if (textureTable) - { - for (auto index = 0u; index < count; index++) - { - const auto& entry = textureTable[index]; - - json jEntry = { - {"samplerState", BuildSamplerStateJson(entry.samplerState)}, - {"semantic", ArrayEntry(semanticNames, entry.semantic)} - }; - - const auto knownMaterialSourceName = knownMaterialSourceNames.find(entry.nameHash); - if (knownMaterialSourceName != knownMaterialSourceNames.end()) - { - jEntry["name"] = knownMaterialSourceName->second; - } - else - { - jEntry.merge_patch({ - {"nameHash", entry.nameHash}, - {"nameStart", entry.nameStart}, - {"nameEnd", entry.nameEnd}, - }); - } - - if (entry.semantic == TS_WATER_MAP) - { - jEntry["water"] = BuildWaterJson(entry.u.water); - } - else - { - jEntry["image"] = entry.u.image && entry.u.image->name ? AssetName(entry.u.image->name) : nullptr; - } - - jArray.emplace_back(std::move(jEntry)); - } - } +json BuildSamplerStateJson(unsigned char samplerState) { + static const char *samplerFilterNames[]{"none", "nearest", "linear", "aniso2x", "aniso4x"}; + static const char *samplerMipmapNames[]{"disabled", "nearest", "linear"}; + + return json{ + {"filter", ArrayEntry(samplerFilterNames, (samplerState & SAMPLER_FILTER_MASK) >> SAMPLER_FILTER_SHIFT)}, + {"mipmap", ArrayEntry(samplerMipmapNames, (samplerState & SAMPLER_MIPMAP_MASK) >> SAMPLER_MIPMAP_SHIFT)}, + {"clampU", (samplerState & SAMPLER_CLAMP_U) ? true : false}, + {"clampV", (samplerState & SAMPLER_CLAMP_V) ? true : false}, + {"clampW", (samplerState & SAMPLER_CLAMP_W) ? true : false}, + }; +} - return jArray; +json BuildTextureTableJson(const MaterialTextureDef *textureTable, const size_t count) { + static const char *semanticNames[]{"2d", "function", "colorMap", "unused1", "unused2", "normalMap", + "unused3", "unused4", "specularMap", "unused5", "unused6", "waterMap"}; + + auto jArray = json::array(); + + if (textureTable) { + for (auto index = 0u; index < count; index++) { + const auto &entry = textureTable[index]; + + json jEntry = { + {"samplerState", BuildSamplerStateJson(entry.samplerState)}, + {"semantic", ArrayEntry(semanticNames, entry.semantic)} + }; + + const auto knownMaterialSourceName = knownMaterialSourceNames.find(entry.nameHash); + if (knownMaterialSourceName != knownMaterialSourceNames.end()) { + jEntry["name"] = knownMaterialSourceName->second; + } else { + jEntry.merge_patch({ + {"nameHash", entry.nameHash }, + {"nameStart", entry.nameStart}, + {"nameEnd", entry.nameEnd }, + }); + } + + if (entry.semantic == TS_WATER_MAP) { + jEntry["water"] = BuildWaterJson(entry.u.water); + } else { + jEntry["image"] = entry.u.image && entry.u.image->name ? AssetName(entry.u.image->name) : nullptr; + } + + jArray.emplace_back(std::move(jEntry)); } + } + + return jArray; +} - json BuildConstantTableJson(const MaterialConstantDef* constantTable, const size_t count) - { - auto jArray = json::array(); - - if (constantTable) - { - for (auto index = 0u; index < count; index++) - { - const auto& entry = constantTable[index]; - json jEntry = { - {"literal", std::vector(std::begin(entry.literal), std::end(entry.literal))} - }; - - const auto nameLen = strnlen(entry.name, std::extent_v<decltype(MaterialConstantDef::name)>); - if (nameLen == std::extent_v<decltype(MaterialConstantDef::name)>) - { - std::string fullLengthName(entry.name, std::extent_v<decltype(MaterialConstantDef::name)>); - const auto fullLengthHash = Common::R_HashString(fullLengthName.c_str(), 0); - - if (fullLengthHash == entry.nameHash) - { - jEntry["name"] = fullLengthName; - } - else - { - const auto knownMaterialSourceName = knownMaterialSourceNames.find(entry.nameHash); - if (knownMaterialSourceName != knownMaterialSourceNames.end()) - { - jEntry["name"] = knownMaterialSourceName->second; - } - else - { - jEntry.merge_patch({ - {"nameHash", entry.nameHash}, - {"namePart", fullLengthName} - }); - } - } - } - else - { - jEntry["name"] = std::string(entry.name, nameLen); - } - - jArray.emplace_back(std::move(jEntry)); - } +json BuildConstantTableJson(const MaterialConstantDef *constantTable, const size_t count) { + auto jArray = json::array(); + + if (constantTable) { + for (auto index = 0u; index < count; index++) { + const auto &entry = constantTable[index]; + json jEntry = { + {"literal", std::vector(std::begin(entry.literal), std::end(entry.literal))} + }; + + const auto nameLen = strnlen(entry.name, std::extent_v<decltype(MaterialConstantDef::name)>); + if (nameLen == std::extent_v<decltype(MaterialConstantDef::name)>) { + std::string fullLengthName(entry.name, std::extent_v<decltype(MaterialConstantDef::name)>); + const auto fullLengthHash = Common::R_HashString(fullLengthName.c_str(), 0); + + if (fullLengthHash == entry.nameHash) { + jEntry["name"] = fullLengthName; + } else { + const auto knownMaterialSourceName = knownMaterialSourceNames.find(entry.nameHash); + if (knownMaterialSourceName != knownMaterialSourceNames.end()) { + jEntry["name"] = knownMaterialSourceName->second; + } else { + jEntry.merge_patch({ + {"nameHash", entry.nameHash}, + {"namePart", fullLengthName} + }); + } } + } else { + jEntry["name"] = std::string(entry.name, nameLen); + } - return jArray; + jArray.emplace_back(std::move(jEntry)); } + } - json BuildStateBitsTableJson(const GfxStateBits* stateBitsTable, const size_t count) - { - static const char* blendNames[] - { - "disabled", - "zero", - "one", - "srcColor", - "invSrcColor", - "srcAlpha", - "invSrcAlpha", - "destAlpha", - "invDestAlpha", - "destColor", - "invDestColor", - }; - static const char* blendOpNames[] - { - "disabled", - "add", - "subtract", - "revSubtract", - "min", - "max" - }; - static const char* depthTestNames[] - { - "always", - "less", - "equal", - "lessEqual", - }; - static const char* polygonOffsetNames[] - { - "0", - "1", - "2", - "shadowMap", - }; - static const char* stencilOpNames[] - { - "keep", - "zero", - "replace", - "incrSat", - "decrSat", - "invert", - "incr", - "decr" - }; - - auto jArray = json::array(); - - if (stateBitsTable) - { - for (auto index = 0u; index < count; index++) - { - const auto& entry = stateBitsTable[index]; - - const auto srcBlendRgb = (entry.loadBits[0] & GFXS0_SRCBLEND_RGB_MASK) >> GFXS0_SRCBLEND_RGB_SHIFT; - const auto dstBlendRgb = (entry.loadBits[0] & GFXS0_DSTBLEND_RGB_MASK) >> GFXS0_DSTBLEND_RGB_SHIFT; - const auto blendOpRgb = (entry.loadBits[0] & GFXS0_BLENDOP_RGB_MASK) >> GFXS0_BLENDOP_RGB_SHIFT; - const auto srcBlendAlpha = (entry.loadBits[0] & GFXS0_SRCBLEND_ALPHA_MASK) >> GFXS0_SRCBLEND_ALPHA_SHIFT; - const auto dstBlendAlpha = (entry.loadBits[0] & GFXS0_DSTBLEND_ALPHA_MASK) >> GFXS0_DSTBLEND_ALPHA_SHIFT; - const auto blendOpAlpha = (entry.loadBits[0] & GFXS0_BLENDOP_ALPHA_MASK) >> GFXS0_BLENDOP_ALPHA_SHIFT; - const auto depthTest = (entry.loadBits[1] & GFXS1_DEPTHTEST_MASK) >> GFXS1_DEPTHTEST_SHIFT; - const auto polygonOffset = (entry.loadBits[1] & GFXS1_POLYGON_OFFSET_MASK) >> GFXS1_POLYGON_OFFSET_SHIFT; - - const auto* alphaTest = "disable"; - if (entry.loadBits[0] & GFXS0_ATEST_GT_0) - alphaTest = "gt0"; - else if (entry.loadBits[0] & GFXS0_ATEST_LT_128) - alphaTest = "lt128"; - else if (entry.loadBits[0] & GFXS0_ATEST_GE_128) - alphaTest = "ge128"; - else - assert(entry.loadBits[0] & GFXS0_ATEST_DISABLE); - - const auto* cullFace = "none"; - if ((entry.loadBits[0] & GFXS0_CULL_MASK) == GFXS0_CULL_BACK) - cullFace = "back"; - else if ((entry.loadBits[0] & GFXS0_CULL_MASK) == GFXS0_CULL_FRONT) - cullFace = "front"; - else - assert((entry.loadBits[0] & GFXS0_CULL_MASK) == GFXS0_CULL_NONE); - - jArray.emplace_back(json{ - {"srcBlendRgb", ArrayEntry(blendNames, srcBlendRgb)}, - {"dstBlendRgb", ArrayEntry(blendNames, dstBlendRgb)}, - {"blendOpRgb", ArrayEntry(blendOpNames, blendOpRgb)}, - {"alphaTest", alphaTest}, - {"cullFace", cullFace}, - {"srcBlendAlpha", ArrayEntry(blendNames, srcBlendAlpha)}, - {"dstBlendAlpha", ArrayEntry(blendNames, dstBlendAlpha)}, - {"blendOpAlpha", ArrayEntry(blendOpNames, blendOpAlpha)}, - {"colorWriteRgb", (entry.loadBits[0] & GFXS0_COLORWRITE_RGB) ? true : false}, - {"colorWriteAlpha", (entry.loadBits[0] & GFXS0_COLORWRITE_ALPHA) ? true : false}, - {"polymodeLine", (entry.loadBits[0] & GFXS0_POLYMODE_LINE) ? true : false}, - - {"depthWrite", (entry.loadBits[1] & GFXS1_DEPTHWRITE) ? true : false}, - {"depthTest", (entry.loadBits[1] & GFXS1_DEPTHTEST_DISABLE) ? json("disable") : ArrayEntry(depthTestNames, depthTest)}, - {"polygonOffset", ArrayEntry(polygonOffsetNames, polygonOffset)}, - {"stencilFrontEnabled", (entry.loadBits[1] & GFXS1_STENCIL_FRONT_ENABLE) ? true : false}, - {"stencilBackEnabled", (entry.loadBits[1] & GFXS1_STENCIL_BACK_ENABLE) ? true : false}, - {"stencilFrontPass", ArrayEntry(stencilOpNames, (entry.loadBits[1] >> GFXS1_STENCIL_FRONT_PASS_SHIFT) & GFXS_STENCILOP_MASK)}, - {"stencilFrontFail", ArrayEntry(stencilOpNames, (entry.loadBits[1] >> GFXS1_STENCIL_FRONT_FAIL_SHIFT) & GFXS_STENCILOP_MASK)}, - {"stencilFrontZFail", ArrayEntry(stencilOpNames, (entry.loadBits[1] >> GFXS1_STENCIL_FRONT_ZFAIL_SHIFT) & GFXS_STENCILOP_MASK)}, - {"stencilFrontFunc", ArrayEntry(stencilOpNames, (entry.loadBits[1] >> GFXS1_STENCIL_FRONT_FUNC_SHIFT) & GFXS_STENCILOP_MASK)}, - {"stencilBackPass", ArrayEntry(stencilOpNames, (entry.loadBits[1] >> GFXS1_STENCIL_BACK_PASS_SHIFT) & GFXS_STENCILOP_MASK)}, - {"stencilBackFail", ArrayEntry(stencilOpNames, (entry.loadBits[1] >> GFXS1_STENCIL_BACK_FAIL_SHIFT) & GFXS_STENCILOP_MASK)}, - {"stencilBackZFail", ArrayEntry(stencilOpNames, (entry.loadBits[1] >> GFXS1_STENCIL_BACK_ZFAIL_SHIFT) & GFXS_STENCILOP_MASK)}, - {"stencilBackFunc", ArrayEntry(stencilOpNames, (entry.loadBits[1] >> GFXS1_STENCIL_BACK_FUNC_SHIFT) & GFXS_STENCILOP_MASK)}, - }); - } - } + return jArray; +} - return jArray; +json BuildStateBitsTableJson(const GfxStateBits *stateBitsTable, const size_t count) { + static const char *blendNames[]{ + "disabled", "zero", "one", "srcColor", "invSrcColor", "srcAlpha", "invSrcAlpha", "destAlpha", "invDestAlpha", "destColor", "invDestColor", + }; + static const char *blendOpNames[]{"disabled", "add", "subtract", "revSubtract", "min", "max"}; + static const char *depthTestNames[]{ + "always", + "less", + "equal", + "lessEqual", + }; + static const char *polygonOffsetNames[]{ + "0", + "1", + "2", + "shadowMap", + }; + static const char *stencilOpNames[]{"keep", "zero", "replace", "incrSat", "decrSat", "invert", "incr", "decr"}; + + auto jArray = json::array(); + + if (stateBitsTable) { + for (auto index = 0u; index < count; index++) { + const auto &entry = stateBitsTable[index]; + + const auto srcBlendRgb = (entry.loadBits[0] & GFXS0_SRCBLEND_RGB_MASK) >> GFXS0_SRCBLEND_RGB_SHIFT; + const auto dstBlendRgb = (entry.loadBits[0] & GFXS0_DSTBLEND_RGB_MASK) >> GFXS0_DSTBLEND_RGB_SHIFT; + const auto blendOpRgb = (entry.loadBits[0] & GFXS0_BLENDOP_RGB_MASK) >> GFXS0_BLENDOP_RGB_SHIFT; + const auto srcBlendAlpha = (entry.loadBits[0] & GFXS0_SRCBLEND_ALPHA_MASK) >> GFXS0_SRCBLEND_ALPHA_SHIFT; + const auto dstBlendAlpha = (entry.loadBits[0] & GFXS0_DSTBLEND_ALPHA_MASK) >> GFXS0_DSTBLEND_ALPHA_SHIFT; + const auto blendOpAlpha = (entry.loadBits[0] & GFXS0_BLENDOP_ALPHA_MASK) >> GFXS0_BLENDOP_ALPHA_SHIFT; + const auto depthTest = (entry.loadBits[1] & GFXS1_DEPTHTEST_MASK) >> GFXS1_DEPTHTEST_SHIFT; + const auto polygonOffset = (entry.loadBits[1] & GFXS1_POLYGON_OFFSET_MASK) >> GFXS1_POLYGON_OFFSET_SHIFT; + + const auto *alphaTest = "disable"; + if (entry.loadBits[0] & GFXS0_ATEST_GT_0) + alphaTest = "gt0"; + else if (entry.loadBits[0] & GFXS0_ATEST_LT_128) + alphaTest = "lt128"; + else if (entry.loadBits[0] & GFXS0_ATEST_GE_128) + alphaTest = "ge128"; + else + assert(entry.loadBits[0] & GFXS0_ATEST_DISABLE); + + const auto *cullFace = "none"; + if ((entry.loadBits[0] & GFXS0_CULL_MASK) == GFXS0_CULL_BACK) + cullFace = "back"; + else if ((entry.loadBits[0] & GFXS0_CULL_MASK) == GFXS0_CULL_FRONT) + cullFace = "front"; + else + assert((entry.loadBits[0] & GFXS0_CULL_MASK) == GFXS0_CULL_NONE); + + jArray.emplace_back(json{ + {"srcBlendRgb", ArrayEntry(blendNames, srcBlendRgb)}, + {"dstBlendRgb", ArrayEntry(blendNames, dstBlendRgb)}, + {"blendOpRgb", ArrayEntry(blendOpNames, blendOpRgb)}, + {"alphaTest", alphaTest}, + {"cullFace", cullFace}, + {"srcBlendAlpha", ArrayEntry(blendNames, srcBlendAlpha)}, + {"dstBlendAlpha", ArrayEntry(blendNames, dstBlendAlpha)}, + {"blendOpAlpha", ArrayEntry(blendOpNames, blendOpAlpha)}, + {"colorWriteRgb", (entry.loadBits[0] & GFXS0_COLORWRITE_RGB) ? true : false}, + {"colorWriteAlpha", (entry.loadBits[0] & GFXS0_COLORWRITE_ALPHA) ? true : false}, + {"polymodeLine", (entry.loadBits[0] & GFXS0_POLYMODE_LINE) ? true : false}, + + {"depthWrite", (entry.loadBits[1] & GFXS1_DEPTHWRITE) ? true : false}, + {"depthTest", (entry.loadBits[1] & GFXS1_DEPTHTEST_DISABLE) ? json("disable") : ArrayEntry(depthTestNames, depthTest)}, + {"polygonOffset", ArrayEntry(polygonOffsetNames, polygonOffset)}, + {"stencilFrontEnabled", (entry.loadBits[1] & GFXS1_STENCIL_FRONT_ENABLE) ? true : false}, + {"stencilBackEnabled", (entry.loadBits[1] & GFXS1_STENCIL_BACK_ENABLE) ? true : false}, + {"stencilFrontPass", ArrayEntry(stencilOpNames, (entry.loadBits[1] >> GFXS1_STENCIL_FRONT_PASS_SHIFT) & GFXS_STENCILOP_MASK)}, + {"stencilFrontFail", ArrayEntry(stencilOpNames, (entry.loadBits[1] >> GFXS1_STENCIL_FRONT_FAIL_SHIFT) & GFXS_STENCILOP_MASK)}, + {"stencilFrontZFail", ArrayEntry(stencilOpNames, (entry.loadBits[1] >> GFXS1_STENCIL_FRONT_ZFAIL_SHIFT) & GFXS_STENCILOP_MASK)}, + {"stencilFrontFunc", ArrayEntry(stencilOpNames, (entry.loadBits[1] >> GFXS1_STENCIL_FRONT_FUNC_SHIFT) & GFXS_STENCILOP_MASK)}, + {"stencilBackPass", ArrayEntry(stencilOpNames, (entry.loadBits[1] >> GFXS1_STENCIL_BACK_PASS_SHIFT) & GFXS_STENCILOP_MASK)}, + {"stencilBackFail", ArrayEntry(stencilOpNames, (entry.loadBits[1] >> GFXS1_STENCIL_BACK_FAIL_SHIFT) & GFXS_STENCILOP_MASK)}, + {"stencilBackZFail", ArrayEntry(stencilOpNames, (entry.loadBits[1] >> GFXS1_STENCIL_BACK_ZFAIL_SHIFT) & GFXS_STENCILOP_MASK)}, + {"stencilBackFunc", ArrayEntry(stencilOpNames, (entry.loadBits[1] >> GFXS1_STENCIL_BACK_FUNC_SHIFT) & GFXS_STENCILOP_MASK)}, + }); } + } - json BuildSurfaceTypeBitsJson(const unsigned surfaceTypeBits) - { - if (!surfaceTypeBits) - return json(surfaceTypeNames[SURF_TYPE_DEFAULT]); - - static constexpr auto NON_SURFACE_TYPE_BITS = ~(std::numeric_limits<unsigned>::max() >> ((sizeof(unsigned) * 8) - (static_cast<unsigned>(SURF_TYPE_NUM) - 1))); - assert((surfaceTypeBits & NON_SURFACE_TYPE_BITS) == 0); - - std::ostringstream ss; - auto firstSurfaceType = true; - for (auto surfaceTypeIndex = static_cast<unsigned>(SURF_TYPE_BARK); surfaceTypeIndex < SURF_TYPE_NUM; surfaceTypeIndex++) - { - if ((surfaceTypeBits & (1 << (surfaceTypeIndex - 1))) == 0) - continue; - - if (firstSurfaceType) - firstSurfaceType = false; - else - ss << ","; - ss << surfaceTypeNames[surfaceTypeIndex]; - } + return jArray; +} - if (firstSurfaceType) - return json(surfaceTypeNames[SURF_TYPE_DEFAULT]); +json BuildSurfaceTypeBitsJson(const unsigned surfaceTypeBits) { + if (!surfaceTypeBits) + return json(surfaceTypeNames[SURF_TYPE_DEFAULT]); - return json(ss.str()); - } + static constexpr auto NON_SURFACE_TYPE_BITS = + ~(std::numeric_limits<unsigned>::max() >> ((sizeof(unsigned) * 8) - (static_cast<unsigned>(SURF_TYPE_NUM) - 1))); + assert((surfaceTypeBits & NON_SURFACE_TYPE_BITS) == 0); - json BuildCharFlagsJson(const std::string& prefix, const unsigned char gameFlags) - { - std::vector<std::string> values; - - for (auto i = 0u; i < (sizeof(gameFlags) * 8u); i++) - { - if (gameFlags & (1 << i)) - { - std::ostringstream ss; - ss << prefix << " 0x" << std::hex << (1 << i); - values.emplace_back(ss.str()); - } - } + std::ostringstream ss; + auto firstSurfaceType = true; + for (auto surfaceTypeIndex = static_cast<unsigned>(SURF_TYPE_BARK); surfaceTypeIndex < SURF_TYPE_NUM; surfaceTypeIndex++) { + if ((surfaceTypeBits & (1 << (surfaceTypeIndex - 1))) == 0) + continue; - return json(values); - } -} + if (firstSurfaceType) + firstSurfaceType = false; + else + ss << ","; + ss << surfaceTypeNames[surfaceTypeIndex]; + } -bool AssetDumperMaterial::ShouldDump(XAssetInfo<Material>* asset) -{ - return true; + if (firstSurfaceType) + return json(surfaceTypeNames[SURF_TYPE_DEFAULT]); + + return json(ss.str()); } -void AssetDumperMaterial::DumpAsset(AssetDumpingContext& context, XAssetInfo<Material>* asset) -{ - auto* material = asset->Asset(); - - std::ostringstream ss; - ss << "materials/" << asset->m_name << ".json"; - const auto assetFile = context.OpenAssetFile(ss.str()); - - if (!assetFile) - return; - - auto& stream = *assetFile; - - static const char* cameraRegionNames[] - { - "lit", - "decal", - "emissive", - "none" - }; - static std::unordered_map<size_t, std::string> sortKeyNames - { - {0, "distortion"}, - {1, "opaque water"}, - {2, "boat hull"}, - {3, "opaque ambient"}, - {4, "opaque"}, - {5, "sky"}, - {6, "skybox - sun / moon"}, - {7, "skybox - clouds"}, - {8, "skybox - horizon"}, - {9, "decal - bottom 1"}, - {10, "decal - bottom 2"}, - {11, "decal - bottom 3"}, - {12, "decal - static decal"}, - {13, "decal - middle 1"}, - {14, "decal - middle 2"}, - {15, "decal - middle 3"}, - {24, "decal - weapon impact"}, - {29, "decal - top 1"}, - {30, "decal - top 2"}, - {31, "decal - top 3"}, - {32, "multiplicative"}, - {33, "banner / curtain"}, - {34, "hair"}, - {35, "underwater"}, - {36, "transparent water"}, - {37, "corona"}, - {38, "window inside"}, - {39, "window outside"}, - {40, "before effects - bottom"}, - {41, "before effects - middle"}, - {42, "before effects - top"}, - {43, "blend / additive"}, - {48, "effect - auto sort"}, - {56, "after effects - bottom"}, - {57, "after effects - middle"}, - {58, "after effects - top"}, - {59, "viewmodel effect"}, - }; - - const auto foundSortKeyName = sortKeyNames.find(material->info.sortKey); - assert(foundSortKeyName != sortKeyNames.end()); - - const json j = { - { - "info", { +json BuildCharFlagsJson(const std::string &prefix, const unsigned char gameFlags) { + std::vector<std::string> values; + + for (auto i = 0u; i < (sizeof(gameFlags) * 8u); i++) { + if (gameFlags & (1 << i)) { + std::ostringstream ss; + ss << prefix << " 0x" << std::hex << (1 << i); + values.emplace_back(ss.str()); + } + } + + return json(values); +} +} // namespace IW3 + +bool AssetDumperMaterial::ShouldDump(XAssetInfo<Material> *asset) { return true; } + +void AssetDumperMaterial::DumpAsset(AssetDumpingContext &context, XAssetInfo<Material> *asset) { + auto *material = asset->Asset(); + + std::ostringstream ss; + ss << "materials/" << asset->m_name << ".json"; + const auto assetFile = context.OpenAssetFile(ss.str()); + + if (!assetFile) + return; + + auto &stream = *assetFile; + + static const char *cameraRegionNames[]{"lit", "decal", "emissive", "none"}; + static std::unordered_map<size_t, std::string> sortKeyNames{ + {0, "distortion" }, + {1, "opaque water" }, + {2, "boat hull" }, + {3, "opaque ambient" }, + {4, "opaque" }, + {5, "sky" }, + {6, "skybox - sun / moon" }, + {7, "skybox - clouds" }, + {8, "skybox - horizon" }, + {9, "decal - bottom 1" }, + {10, "decal - bottom 2" }, + {11, "decal - bottom 3" }, + {12, "decal - static decal" }, + {13, "decal - middle 1" }, + {14, "decal - middle 2" }, + {15, "decal - middle 3" }, + {24, "decal - weapon impact" }, + {29, "decal - top 1" }, + {30, "decal - top 2" }, + {31, "decal - top 3" }, + {32, "multiplicative" }, + {33, "banner / curtain" }, + {34, "hair" }, + {35, "underwater" }, + {36, "transparent water" }, + {37, "corona" }, + {38, "window inside" }, + {39, "window outside" }, + {40, "before effects - bottom"}, + {41, "before effects - middle"}, + {42, "before effects - top" }, + {43, "blend / additive" }, + {48, "effect - auto sort" }, + {56, "after effects - bottom" }, + {57, "after effects - middle" }, + {58, "after effects - top" }, + {59, "viewmodel effect" }, + }; + + const auto foundSortKeyName = sortKeyNames.find(material->info.sortKey); + assert(foundSortKeyName != sortKeyNames.end()); + + const json j = { + {"info", + { #if defined(FLAGS_DEBUG) && FLAGS_DEBUG == 1 - {"gameFlags", BuildCharFlagsJson("gameFlag", material->info.gameFlags)}, // TODO: Find out what gameflags mean + {"gameFlags", BuildCharFlagsJson("gameFlag", material->info.gameFlags)}, // TODO: Find out what gameflags mean #else - {"gameFlags", material->info.gameFlags}, // TODO: Find out what gameflags mean + {"gameFlags", material->info.gameFlags}, // TODO: Find out what gameflags mean #endif - {"sortKey", foundSortKeyName != sortKeyNames.end() ? foundSortKeyName->second : std::to_string(material->info.sortKey)}, - {"textureAtlasRowCount", material->info.textureAtlasRowCount}, - {"textureAtlasColumnCount", material->info.textureAtlasColumnCount}, - { - "drawSurf", { - {"objectId", static_cast<unsigned>(material->info.drawSurf.fields.objectId)}, - {"reflectionProbeIndex", static_cast<unsigned>(material->info.drawSurf.fields.reflectionProbeIndex)}, - {"customIndex", static_cast<unsigned>(material->info.drawSurf.fields.customIndex)}, - {"materialSortedIndex", static_cast<unsigned>(material->info.drawSurf.fields.materialSortedIndex)}, - {"prepass", static_cast<unsigned>(material->info.drawSurf.fields.prepass)}, - {"useHeroLighting", static_cast<unsigned>(material->info.drawSurf.fields.primaryLightIndex)}, - {"surfType", static_cast<unsigned>(material->info.drawSurf.fields.surfType)}, - {"primarySortKey", static_cast<unsigned>(material->info.drawSurf.fields.primarySortKey)} - } - }, - {"surfaceTypeBits", BuildSurfaceTypeBitsJson(material->info.surfaceTypeBits)}, - {"hashIndex", material->info.hashIndex} - } - }, - {"stateBitsEntry", std::vector(std::begin(material->stateBitsEntry), std::end(material->stateBitsEntry))}, + {"sortKey", foundSortKeyName != sortKeyNames.end() ? foundSortKeyName->second : std::to_string(material->info.sortKey)}, + {"textureAtlasRowCount", material->info.textureAtlasRowCount}, + {"textureAtlasColumnCount", material->info.textureAtlasColumnCount}, + {"drawSurf", + {{"objectId", static_cast<unsigned>(material->info.drawSurf.fields.objectId)}, + {"reflectionProbeIndex", static_cast<unsigned>(material->info.drawSurf.fields.reflectionProbeIndex)}, + {"customIndex", static_cast<unsigned>(material->info.drawSurf.fields.customIndex)}, + {"materialSortedIndex", static_cast<unsigned>(material->info.drawSurf.fields.materialSortedIndex)}, + {"prepass", static_cast<unsigned>(material->info.drawSurf.fields.prepass)}, + {"useHeroLighting", static_cast<unsigned>(material->info.drawSurf.fields.primaryLightIndex)}, + {"surfType", static_cast<unsigned>(material->info.drawSurf.fields.surfType)}, + {"primarySortKey", static_cast<unsigned>(material->info.drawSurf.fields.primarySortKey)}}}, + {"surfaceTypeBits", BuildSurfaceTypeBitsJson(material->info.surfaceTypeBits)}, + {"hashIndex", material->info.hashIndex}}}, + {"stateBitsEntry", std::vector(std::begin(material->stateBitsEntry), std::end(material->stateBitsEntry))}, #if defined(FLAGS_DEBUG) && FLAGS_DEBUG == 1 - {"stateFlags", BuildCharFlagsJson("stateFlag", material->stateFlags)}, + {"stateFlags", BuildCharFlagsJson("stateFlag", material->stateFlags)}, #else - {"stateFlags", material->stateFlags}, + {"stateFlags", material->stateFlags}, #endif - {"cameraRegion", ArrayEntry(cameraRegionNames, material->cameraRegion)}, - {"techniqueSet", material->techniqueSet && material->techniqueSet->name ? AssetName(material->techniqueSet->name) : nullptr}, - {"textureTable", BuildTextureTableJson(material->textureTable, material->textureCount)}, - {"constantTable", BuildConstantTableJson(material->constantTable, material->constantCount)}, - {"stateBitsTable", BuildStateBitsTableJson(material->stateBitsTable, material->stateBitsCount)} - }; - - stream << std::setw(4) << j; + {"cameraRegion", ArrayEntry(cameraRegionNames, material->cameraRegion)}, + {"techniqueSet", material->techniqueSet && material->techniqueSet->name ? AssetName(material->techniqueSet->name) : nullptr}, + {"textureTable", BuildTextureTableJson(material->textureTable, material->textureCount)}, + {"constantTable", BuildConstantTableJson(material->constantTable, material->constantCount)}, + {"stateBitsTable", BuildStateBitsTableJson(material->stateBitsTable, material->stateBitsCount)} + }; + + stream << std::setw(4) << j; } diff --git a/src/ObjWriting/Game/IW3/AssetDumpers/AssetDumperMaterial.h b/src/ObjWriting/Game/IW3/AssetDumpers/AssetDumperMaterial.h index 94f9e54d2..5905befc1 100644 --- a/src/ObjWriting/Game/IW3/AssetDumpers/AssetDumperMaterial.h +++ b/src/ObjWriting/Game/IW3/AssetDumpers/AssetDumperMaterial.h @@ -3,12 +3,10 @@ #include "Dumping/AbstractAssetDumper.h" #include "Game/IW3/IW3.h" -namespace IW3 -{ - class AssetDumperMaterial final : public AbstractAssetDumper<Material> - { - protected: - bool ShouldDump(XAssetInfo<Material>* asset) override; - void DumpAsset(AssetDumpingContext& context, XAssetInfo<Material>* asset) override; - }; -} +namespace IW3 { +class AssetDumperMaterial final : public AbstractAssetDumper<Material> { +protected: + bool ShouldDump(XAssetInfo<Material> *asset) override; + void DumpAsset(AssetDumpingContext &context, XAssetInfo<Material> *asset) override; +}; +} // namespace IW3 diff --git a/src/ObjWriting/Game/IW3/AssetDumpers/AssetDumperRawFile.cpp b/src/ObjWriting/Game/IW3/AssetDumpers/AssetDumperRawFile.cpp index bd9b7ecd1..2ceed90c1 100644 --- a/src/ObjWriting/Game/IW3/AssetDumpers/AssetDumperRawFile.cpp +++ b/src/ObjWriting/Game/IW3/AssetDumpers/AssetDumperRawFile.cpp @@ -2,19 +2,15 @@ using namespace IW3; -bool AssetDumperRawFile::ShouldDump(XAssetInfo<RawFile>* asset) -{ - return true; -} +bool AssetDumperRawFile::ShouldDump(XAssetInfo<RawFile> *asset) { return true; } -void AssetDumperRawFile::DumpAsset(AssetDumpingContext& context, XAssetInfo<RawFile>* asset) -{ - const auto* rawFile = asset->Asset(); - const auto assetFile = context.OpenAssetFile(asset->m_name); +void AssetDumperRawFile::DumpAsset(AssetDumpingContext &context, XAssetInfo<RawFile> *asset) { + const auto *rawFile = asset->Asset(); + const auto assetFile = context.OpenAssetFile(asset->m_name); - if (!assetFile) - return; + if (!assetFile) + return; - auto& stream = *assetFile; - stream.write(rawFile->buffer, rawFile->len); + auto &stream = *assetFile; + stream.write(rawFile->buffer, rawFile->len); } diff --git a/src/ObjWriting/Game/IW3/AssetDumpers/AssetDumperRawFile.h b/src/ObjWriting/Game/IW3/AssetDumpers/AssetDumperRawFile.h index 7c79a4235..26dbc997c 100644 --- a/src/ObjWriting/Game/IW3/AssetDumpers/AssetDumperRawFile.h +++ b/src/ObjWriting/Game/IW3/AssetDumpers/AssetDumperRawFile.h @@ -3,12 +3,10 @@ #include "Dumping/AbstractAssetDumper.h" #include "Game/IW3/IW3.h" -namespace IW3 -{ - class AssetDumperRawFile final : public AbstractAssetDumper<RawFile> - { - protected: - bool ShouldDump(XAssetInfo<RawFile>* asset) override; - void DumpAsset(AssetDumpingContext& context, XAssetInfo<RawFile>* asset) override; - }; -} +namespace IW3 { +class AssetDumperRawFile final : public AbstractAssetDumper<RawFile> { +protected: + bool ShouldDump(XAssetInfo<RawFile> *asset) override; + void DumpAsset(AssetDumpingContext &context, XAssetInfo<RawFile> *asset) override; +}; +} // namespace IW3 diff --git a/src/ObjWriting/Game/IW3/AssetDumpers/AssetDumperStringTable.cpp b/src/ObjWriting/Game/IW3/AssetDumpers/AssetDumperStringTable.cpp index 26c8d514b..2c69c0696 100644 --- a/src/ObjWriting/Game/IW3/AssetDumpers/AssetDumperStringTable.cpp +++ b/src/ObjWriting/Game/IW3/AssetDumpers/AssetDumperStringTable.cpp @@ -4,28 +4,22 @@ using namespace IW3; -bool AssetDumperStringTable::ShouldDump(XAssetInfo<StringTable>* asset) -{ - return true; -} - -void AssetDumperStringTable::DumpAsset(AssetDumpingContext& context, XAssetInfo<StringTable>* asset) -{ - const auto* stringTable = asset->Asset(); - const auto assetFile = context.OpenAssetFile(asset->m_name); +bool AssetDumperStringTable::ShouldDump(XAssetInfo<StringTable> *asset) { return true; } - if (!assetFile) - return; +void AssetDumperStringTable::DumpAsset(AssetDumpingContext &context, XAssetInfo<StringTable> *asset) { + const auto *stringTable = asset->Asset(); + const auto assetFile = context.OpenAssetFile(asset->m_name); - CsvOutputStream csv(*assetFile); + if (!assetFile) + return; - for (auto row = 0; row < stringTable->rowCount; row++) - { - for (auto column = 0; column < stringTable->columnCount; column++) - { - csv.WriteColumn(stringTable->values[column + row * stringTable->columnCount]); - } + CsvOutputStream csv(*assetFile); - csv.NextRow(); + for (auto row = 0; row < stringTable->rowCount; row++) { + for (auto column = 0; column < stringTable->columnCount; column++) { + csv.WriteColumn(stringTable->values[column + row * stringTable->columnCount]); } + + csv.NextRow(); + } } diff --git a/src/ObjWriting/Game/IW3/AssetDumpers/AssetDumperStringTable.h b/src/ObjWriting/Game/IW3/AssetDumpers/AssetDumperStringTable.h index d4cb92991..736536f6f 100644 --- a/src/ObjWriting/Game/IW3/AssetDumpers/AssetDumperStringTable.h +++ b/src/ObjWriting/Game/IW3/AssetDumpers/AssetDumperStringTable.h @@ -3,12 +3,10 @@ #include "Dumping/AbstractAssetDumper.h" #include "Game/IW3/IW3.h" -namespace IW3 -{ - class AssetDumperStringTable final : public AbstractAssetDumper<StringTable> - { - protected: - bool ShouldDump(XAssetInfo<StringTable>* asset) override; - void DumpAsset(AssetDumpingContext& context, XAssetInfo<StringTable>* asset) override; - }; -} +namespace IW3 { +class AssetDumperStringTable final : public AbstractAssetDumper<StringTable> { +protected: + bool ShouldDump(XAssetInfo<StringTable> *asset) override; + void DumpAsset(AssetDumpingContext &context, XAssetInfo<StringTable> *asset) override; +}; +} // namespace IW3 diff --git a/src/ObjWriting/Game/IW3/AssetDumpers/AssetDumperXModel.cpp b/src/ObjWriting/Game/IW3/AssetDumpers/AssetDumperXModel.cpp index 68977d75c..6255d5c34 100644 --- a/src/ObjWriting/Game/IW3/AssetDumpers/AssetDumperXModel.cpp +++ b/src/ObjWriting/Game/IW3/AssetDumpers/AssetDumperXModel.cpp @@ -3,640 +3,527 @@ #include <cassert> #include <sstream> -#include "ObjWriting.h" #include "Game/IW3/CommonIW3.h" #include "Math/Quaternion.h" #include "Model/XModel/XModelExportWriter.h" +#include "ObjWriting.h" #include "Utils/HalfFloat.h" #include "Utils/QuatInt16.h" using namespace IW3; -bool AssetDumperXModel::ShouldDump(XAssetInfo<XModel>* asset) -{ - return !asset->m_name.empty() && asset->m_name[0] != ','; -} +bool AssetDumperXModel::ShouldDump(XAssetInfo<XModel> *asset) { return !asset->m_name.empty() && asset->m_name[0] != ','; } -GfxImage* AssetDumperXModel::GetMaterialColorMap(const Material* material) -{ - std::vector<MaterialTextureDef*> potentialTextureDefs; +GfxImage *AssetDumperXModel::GetMaterialColorMap(const Material *material) { + std::vector<MaterialTextureDef *> potentialTextureDefs; - for (auto textureIndex = 0u; textureIndex < material->textureCount; textureIndex++) - { - MaterialTextureDef* def = &material->textureTable[textureIndex]; + for (auto textureIndex = 0u; textureIndex < material->textureCount; textureIndex++) { + MaterialTextureDef *def = &material->textureTable[textureIndex]; - if (def->semantic == TS_COLOR_MAP) - potentialTextureDefs.push_back(def); - } + if (def->semantic == TS_COLOR_MAP) + potentialTextureDefs.push_back(def); + } - if (potentialTextureDefs.empty()) - return nullptr; - if (potentialTextureDefs.size() == 1) - return potentialTextureDefs[0]->u.image; + if (potentialTextureDefs.empty()) + return nullptr; + if (potentialTextureDefs.size() == 1) + return potentialTextureDefs[0]->u.image; - for (const auto* def : potentialTextureDefs) - { - if (def->nameStart == 'c' && def->nameEnd == 'p') - return def->u.image; - } + for (const auto *def : potentialTextureDefs) { + if (def->nameStart == 'c' && def->nameEnd == 'p') + return def->u.image; + } - return potentialTextureDefs[0]->u.image; + return potentialTextureDefs[0]->u.image; } -GfxImage* AssetDumperXModel::GetMaterialNormalMap(const Material* material) -{ - std::vector<MaterialTextureDef*> potentialTextureDefs; +GfxImage *AssetDumperXModel::GetMaterialNormalMap(const Material *material) { + std::vector<MaterialTextureDef *> potentialTextureDefs; - for (auto textureIndex = 0u; textureIndex < material->textureCount; textureIndex++) - { - MaterialTextureDef* def = &material->textureTable[textureIndex]; + for (auto textureIndex = 0u; textureIndex < material->textureCount; textureIndex++) { + MaterialTextureDef *def = &material->textureTable[textureIndex]; - if (def->semantic == TS_NORMAL_MAP) - potentialTextureDefs.push_back(def); - } + if (def->semantic == TS_NORMAL_MAP) + potentialTextureDefs.push_back(def); + } - if (potentialTextureDefs.empty()) - return nullptr; - if (potentialTextureDefs.size() == 1) - return potentialTextureDefs[0]->u.image; + if (potentialTextureDefs.empty()) + return nullptr; + if (potentialTextureDefs.size() == 1) + return potentialTextureDefs[0]->u.image; - for (const auto* def : potentialTextureDefs) - { - if (def->nameStart == 'n' && def->nameEnd == 'p') - return def->u.image; - } + for (const auto *def : potentialTextureDefs) { + if (def->nameStart == 'n' && def->nameEnd == 'p') + return def->u.image; + } - return potentialTextureDefs[0]->u.image; + return potentialTextureDefs[0]->u.image; } -GfxImage* AssetDumperXModel::GetMaterialSpecularMap(const Material* material) -{ - std::vector<MaterialTextureDef*> potentialTextureDefs; +GfxImage *AssetDumperXModel::GetMaterialSpecularMap(const Material *material) { + std::vector<MaterialTextureDef *> potentialTextureDefs; - for (auto textureIndex = 0u; textureIndex < material->textureCount; textureIndex++) - { - MaterialTextureDef* def = &material->textureTable[textureIndex]; + for (auto textureIndex = 0u; textureIndex < material->textureCount; textureIndex++) { + MaterialTextureDef *def = &material->textureTable[textureIndex]; - if (def->semantic == TS_SPECULAR_MAP) - potentialTextureDefs.push_back(def); - } + if (def->semantic == TS_SPECULAR_MAP) + potentialTextureDefs.push_back(def); + } - if (potentialTextureDefs.empty()) - return nullptr; - if (potentialTextureDefs.size() == 1) - return potentialTextureDefs[0]->u.image; + if (potentialTextureDefs.empty()) + return nullptr; + if (potentialTextureDefs.size() == 1) + return potentialTextureDefs[0]->u.image; - for (const auto* def : potentialTextureDefs) - { - if (def->nameStart == 's' && def->nameEnd == 'p') - return def->u.image; - } + for (const auto *def : potentialTextureDefs) { + if (def->nameStart == 's' && def->nameEnd == 'p') + return def->u.image; + } - return potentialTextureDefs[0]->u.image; + return potentialTextureDefs[0]->u.image; } -void AssetDumperXModel::AddObjMaterials(ObjWriter& writer, DistinctMapper<Material*>& materialMapper, const XModel* model) -{ - if (!model->materialHandles) - return; +void AssetDumperXModel::AddObjMaterials(ObjWriter &writer, DistinctMapper<Material *> &materialMapper, const XModel *model) { + if (!model->materialHandles) + return; - for (auto surfIndex = 0u; surfIndex < model->numsurfs; surfIndex++) - { - Material* material = model->materialHandles[surfIndex]; - if (!materialMapper.Add(material)) - continue; + for (auto surfIndex = 0u; surfIndex < model->numsurfs; surfIndex++) { + Material *material = model->materialHandles[surfIndex]; + if (!materialMapper.Add(material)) + continue; - MtlMaterial mtl; - mtl.materialName = std::string(material->info.name); + MtlMaterial mtl; + mtl.materialName = std::string(material->info.name); - GfxImage* colorMap = GetMaterialColorMap(material); - GfxImage* normalMap = GetMaterialNormalMap(material); - GfxImage* specularMap = GetMaterialSpecularMap(material); + GfxImage *colorMap = GetMaterialColorMap(material); + GfxImage *normalMap = GetMaterialNormalMap(material); + GfxImage *specularMap = GetMaterialSpecularMap(material); - if (colorMap != nullptr) - mtl.colorMapName = colorMap->name; - if (normalMap != nullptr) - mtl.normalMapName = normalMap->name; - if (specularMap != nullptr) - mtl.specularMapName = specularMap->name; + if (colorMap != nullptr) + mtl.colorMapName = colorMap->name; + if (normalMap != nullptr) + mtl.normalMapName = normalMap->name; + if (specularMap != nullptr) + mtl.specularMapName = specularMap->name; - writer.AddMaterial(std::move(mtl)); - } + writer.AddMaterial(std::move(mtl)); + } } -void AssetDumperXModel::AddObjObjects(ObjWriter& writer, const DistinctMapper<Material*>& materialMapper, const XModel* model, const unsigned lod) -{ - const auto surfCount = model->lodInfo[lod].numsurfs; - const auto baseSurfIndex = model->lodInfo[lod].surfIndex; +void AssetDumperXModel::AddObjObjects(ObjWriter &writer, const DistinctMapper<Material *> &materialMapper, const XModel *model, const unsigned lod) { + const auto surfCount = model->lodInfo[lod].numsurfs; + const auto baseSurfIndex = model->lodInfo[lod].surfIndex; - for (auto surfIndex = 0u; surfIndex < surfCount; surfIndex++) - { - ObjObject object; - object.name = "surf" + std::to_string(surfIndex); - object.materialIndex = static_cast<int>(materialMapper.GetDistinctPositionByInputPosition(surfIndex + baseSurfIndex)); + for (auto surfIndex = 0u; surfIndex < surfCount; surfIndex++) { + ObjObject object; + object.name = "surf" + std::to_string(surfIndex); + object.materialIndex = static_cast<int>(materialMapper.GetDistinctPositionByInputPosition(surfIndex + baseSurfIndex)); - writer.AddObject(std::move(object)); - } + writer.AddObject(std::move(object)); + } } -void AssetDumperXModel::AddObjVertices(ObjWriter& writer, const XModel* model, const unsigned lod) -{ - const auto* surfs = &model->surfs[model->lodInfo[lod].surfIndex]; - const auto surfCount = model->lodInfo[lod].numsurfs; - - for (auto surfIndex = 0u; surfIndex < surfCount; surfIndex++) - { - const auto& surface = surfs[surfIndex]; - - for (auto vertexIndex = 0u; vertexIndex < surface.vertCount; vertexIndex++) - { - const auto& v = surface.verts0[vertexIndex]; - vec2_t uv; - vec3_t normalVec; - - Common::Vec2UnpackTexCoords(v.texCoord, &uv); - Common::Vec3UnpackUnitVec(v.normal, &normalVec); - - ObjVertex objVertex{}; - ObjNormal objNormal{}; - ObjUv objUv{}; - objVertex.coordinates[0] = v.xyz[0]; - objVertex.coordinates[1] = v.xyz[2]; - objVertex.coordinates[2] = -v.xyz[1]; - objNormal.normal[0] = normalVec[0]; - objNormal.normal[1] = normalVec[2]; - objNormal.normal[2] = -normalVec[1]; - objUv.uv[0] = uv[0]; - objUv.uv[1] = 1.0f - uv[1]; - - writer.AddVertex(static_cast<int>(surfIndex), objVertex); - writer.AddNormal(static_cast<int>(surfIndex), objNormal); - writer.AddUv(static_cast<int>(surfIndex), objUv); - } +void AssetDumperXModel::AddObjVertices(ObjWriter &writer, const XModel *model, const unsigned lod) { + const auto *surfs = &model->surfs[model->lodInfo[lod].surfIndex]; + const auto surfCount = model->lodInfo[lod].numsurfs; + + for (auto surfIndex = 0u; surfIndex < surfCount; surfIndex++) { + const auto &surface = surfs[surfIndex]; + + for (auto vertexIndex = 0u; vertexIndex < surface.vertCount; vertexIndex++) { + const auto &v = surface.verts0[vertexIndex]; + vec2_t uv; + vec3_t normalVec; + + Common::Vec2UnpackTexCoords(v.texCoord, &uv); + Common::Vec3UnpackUnitVec(v.normal, &normalVec); + + ObjVertex objVertex{}; + ObjNormal objNormal{}; + ObjUv objUv{}; + objVertex.coordinates[0] = v.xyz[0]; + objVertex.coordinates[1] = v.xyz[2]; + objVertex.coordinates[2] = -v.xyz[1]; + objNormal.normal[0] = normalVec[0]; + objNormal.normal[1] = normalVec[2]; + objNormal.normal[2] = -normalVec[1]; + objUv.uv[0] = uv[0]; + objUv.uv[1] = 1.0f - uv[1]; + + writer.AddVertex(static_cast<int>(surfIndex), objVertex); + writer.AddNormal(static_cast<int>(surfIndex), objNormal); + writer.AddUv(static_cast<int>(surfIndex), objUv); } + } } -void AssetDumperXModel::AddObjFaces(ObjWriter& writer, const XModel* model, const unsigned lod) -{ - const auto* surfs = &model->surfs[model->lodInfo[lod].surfIndex]; - const auto surfCount = model->lodInfo[lod].numsurfs; - - for (auto surfIndex = 0u; surfIndex < surfCount; surfIndex++) - { - const auto& surface = surfs[surfIndex]; - for (auto triIndex = 0u; triIndex < surface.triCount; triIndex++) - { - const auto& tri = surface.triIndices[triIndex]; - - ObjFace face{}; - face.vertexIndex[0] = tri[2] + surface.baseVertIndex; - face.vertexIndex[1] = tri[1] + surface.baseVertIndex; - face.vertexIndex[2] = tri[0] + surface.baseVertIndex; - face.normalIndex[0] = face.vertexIndex[0]; - face.normalIndex[1] = face.vertexIndex[1]; - face.normalIndex[2] = face.vertexIndex[2]; - face.uvIndex[0] = face.vertexIndex[0]; - face.uvIndex[1] = face.vertexIndex[1]; - face.uvIndex[2] = face.vertexIndex[2]; - writer.AddFace(static_cast<int>(surfIndex), face); - } +void AssetDumperXModel::AddObjFaces(ObjWriter &writer, const XModel *model, const unsigned lod) { + const auto *surfs = &model->surfs[model->lodInfo[lod].surfIndex]; + const auto surfCount = model->lodInfo[lod].numsurfs; + + for (auto surfIndex = 0u; surfIndex < surfCount; surfIndex++) { + const auto &surface = surfs[surfIndex]; + for (auto triIndex = 0u; triIndex < surface.triCount; triIndex++) { + const auto &tri = surface.triIndices[triIndex]; + + ObjFace face{}; + face.vertexIndex[0] = tri[2] + surface.baseVertIndex; + face.vertexIndex[1] = tri[1] + surface.baseVertIndex; + face.vertexIndex[2] = tri[0] + surface.baseVertIndex; + face.normalIndex[0] = face.vertexIndex[0]; + face.normalIndex[1] = face.vertexIndex[1]; + face.normalIndex[2] = face.vertexIndex[2]; + face.uvIndex[0] = face.vertexIndex[0]; + face.uvIndex[1] = face.vertexIndex[1]; + face.uvIndex[2] = face.vertexIndex[2]; + writer.AddFace(static_cast<int>(surfIndex), face); } + } } -void AssetDumperXModel::DumpObjMat(const AssetDumpingContext& context, XAssetInfo<XModel>* asset) -{ - const auto* model = asset->Asset(); - const auto matFile = context.OpenAssetFile("model_export/" + std::string(model->name) + ".mtl"); +void AssetDumperXModel::DumpObjMat(const AssetDumpingContext &context, XAssetInfo<XModel> *asset) { + const auto *model = asset->Asset(); + const auto matFile = context.OpenAssetFile("model_export/" + std::string(model->name) + ".mtl"); - if (!matFile) - return; + if (!matFile) + return; - ObjWriter writer(context.m_zone->m_game->GetShortName(), context.m_zone->m_name); - DistinctMapper<Material*> materialMapper(model->numsurfs); + ObjWriter writer(context.m_zone->m_game->GetShortName(), context.m_zone->m_name); + DistinctMapper<Material *> materialMapper(model->numsurfs); - AddObjMaterials(writer, materialMapper, model); - writer.WriteMtl(*matFile); + AddObjMaterials(writer, materialMapper, model); + writer.WriteMtl(*matFile); } -void AssetDumperXModel::DumpObjLod(AssetDumpingContext& context, XAssetInfo<XModel>* asset, const unsigned lod) -{ - const auto* model = asset->Asset(); - std::ostringstream ss; - ss << "model_export/" << model->name << "_lod" << lod << ".OBJ"; +void AssetDumperXModel::DumpObjLod(AssetDumpingContext &context, XAssetInfo<XModel> *asset, const unsigned lod) { + const auto *model = asset->Asset(); + std::ostringstream ss; + ss << "model_export/" << model->name << "_lod" << lod << ".OBJ"; - const auto assetFile = context.OpenAssetFile(ss.str()); + const auto assetFile = context.OpenAssetFile(ss.str()); - if (!assetFile) - return; + if (!assetFile) + return; - ObjWriter writer(context.m_zone->m_game->GetShortName(), context.m_zone->m_name); - DistinctMapper<Material*> materialMapper(model->numsurfs); + ObjWriter writer(context.m_zone->m_game->GetShortName(), context.m_zone->m_name); + DistinctMapper<Material *> materialMapper(model->numsurfs); - AddObjMaterials(writer, materialMapper, model); - AddObjObjects(writer, materialMapper, model, lod); - AddObjVertices(writer, model, lod); - AddObjFaces(writer, model, lod); + AddObjMaterials(writer, materialMapper, model); + AddObjObjects(writer, materialMapper, model, lod); + AddObjVertices(writer, model, lod); + AddObjFaces(writer, model, lod); - writer.WriteObj(*assetFile, std::string(model->name) + ".mtl"); + writer.WriteObj(*assetFile, std::string(model->name) + ".mtl"); } -void AssetDumperXModel::DumpObj(AssetDumpingContext& context, XAssetInfo<XModel>* asset) -{ - const auto* model = asset->Asset(); +void AssetDumperXModel::DumpObj(AssetDumpingContext &context, XAssetInfo<XModel> *asset) { + const auto *model = asset->Asset(); - DumpObjMat(context, asset); - for (auto currentLod = 0u; currentLod < model->numLods; currentLod++) - { - DumpObjLod(context, asset, currentLod); - } + DumpObjMat(context, asset); + for (auto currentLod = 0u; currentLod < model->numLods; currentLod++) { + DumpObjLod(context, asset, currentLod); + } } -void AssetDumperXModel::AddXModelBones(const AssetDumpingContext& context, AbstractXModelWriter& writer, const XModel* model) -{ - for (auto boneNum = 0u; boneNum < model->numBones; boneNum++) - { - XModelBone bone; - if (model->boneNames[boneNum] < context.m_zone->m_script_strings.Count()) - bone.name = context.m_zone->m_script_strings[model->boneNames[boneNum]]; - else - bone.name = "INVALID_BONE_NAME"; - - if (boneNum < model->numRootBones) - bone.parentIndex = -1; - else - bone.parentIndex = static_cast<int>(boneNum - static_cast<unsigned int>(model->parentList[boneNum - model->numRootBones])); - - bone.scale[0] = 1.0f; - bone.scale[1] = 1.0f; - bone.scale[2] = 1.0f; - - bone.globalOffset[0] = model->baseMat[boneNum].trans[0]; - bone.globalOffset[1] = model->baseMat[boneNum].trans[1]; - bone.globalOffset[2] = model->baseMat[boneNum].trans[2]; - bone.globalRotation = Quaternion32(model->baseMat[boneNum].quat[0], model->baseMat[boneNum].quat[1], model->baseMat[boneNum].quat[2], model->baseMat[boneNum].quat[3]); - - if (boneNum < model->numRootBones) - { - bone.localOffset[0] = 0; - bone.localOffset[1] = 0; - bone.localOffset[2] = 0; - bone.localRotation = Quaternion32(0, 0, 0, 1); - } - else - { - bone.localOffset[0] = model->trans[boneNum - model->numRootBones][0]; - bone.localOffset[1] = model->trans[boneNum - model->numRootBones][1]; - bone.localOffset[2] = model->trans[boneNum - model->numRootBones][2]; - bone.localRotation = Quaternion32( - QuatInt16::ToFloat(model->quats[boneNum - model->numRootBones][0]), - QuatInt16::ToFloat(model->quats[boneNum - model->numRootBones][1]), - QuatInt16::ToFloat(model->quats[boneNum - model->numRootBones][2]), - QuatInt16::ToFloat(model->quats[boneNum - model->numRootBones][3]) - ); - } - - writer.AddBone(std::move(bone)); +void AssetDumperXModel::AddXModelBones(const AssetDumpingContext &context, AbstractXModelWriter &writer, const XModel *model) { + for (auto boneNum = 0u; boneNum < model->numBones; boneNum++) { + XModelBone bone; + if (model->boneNames[boneNum] < context.m_zone->m_script_strings.Count()) + bone.name = context.m_zone->m_script_strings[model->boneNames[boneNum]]; + else + bone.name = "INVALID_BONE_NAME"; + + if (boneNum < model->numRootBones) + bone.parentIndex = -1; + else + bone.parentIndex = static_cast<int>(boneNum - static_cast<unsigned int>(model->parentList[boneNum - model->numRootBones])); + + bone.scale[0] = 1.0f; + bone.scale[1] = 1.0f; + bone.scale[2] = 1.0f; + + bone.globalOffset[0] = model->baseMat[boneNum].trans[0]; + bone.globalOffset[1] = model->baseMat[boneNum].trans[1]; + bone.globalOffset[2] = model->baseMat[boneNum].trans[2]; + bone.globalRotation = + Quaternion32(model->baseMat[boneNum].quat[0], model->baseMat[boneNum].quat[1], model->baseMat[boneNum].quat[2], model->baseMat[boneNum].quat[3]); + + if (boneNum < model->numRootBones) { + bone.localOffset[0] = 0; + bone.localOffset[1] = 0; + bone.localOffset[2] = 0; + bone.localRotation = Quaternion32(0, 0, 0, 1); + } else { + bone.localOffset[0] = model->trans[boneNum - model->numRootBones][0]; + bone.localOffset[1] = model->trans[boneNum - model->numRootBones][1]; + bone.localOffset[2] = model->trans[boneNum - model->numRootBones][2]; + bone.localRotation = + Quaternion32(QuatInt16::ToFloat(model->quats[boneNum - model->numRootBones][0]), QuatInt16::ToFloat(model->quats[boneNum - model->numRootBones][1]), + QuatInt16::ToFloat(model->quats[boneNum - model->numRootBones][2]), QuatInt16::ToFloat(model->quats[boneNum - model->numRootBones][3])); } + + writer.AddBone(std::move(bone)); + } } -void AssetDumperXModel::AddXModelMaterials(AbstractXModelWriter& writer, DistinctMapper<Material*>& materialMapper, const XModel* model) -{ - for (auto surfaceMaterialNum = 0; surfaceMaterialNum < model->numsurfs; surfaceMaterialNum++) - { - Material* material = model->materialHandles[surfaceMaterialNum]; - if (materialMapper.Add(material)) - { - XModelMaterial xMaterial; - xMaterial.ApplyDefaults(); - - xMaterial.name = material->info.name; - const auto* colorMap = GetMaterialColorMap(material); - if (colorMap) - xMaterial.colorMapName = std::string(colorMap->name); - - writer.AddMaterial(std::move(xMaterial)); - } +void AssetDumperXModel::AddXModelMaterials(AbstractXModelWriter &writer, DistinctMapper<Material *> &materialMapper, const XModel *model) { + for (auto surfaceMaterialNum = 0; surfaceMaterialNum < model->numsurfs; surfaceMaterialNum++) { + Material *material = model->materialHandles[surfaceMaterialNum]; + if (materialMapper.Add(material)) { + XModelMaterial xMaterial; + xMaterial.ApplyDefaults(); + + xMaterial.name = material->info.name; + const auto *colorMap = GetMaterialColorMap(material); + if (colorMap) + xMaterial.colorMapName = std::string(colorMap->name); + + writer.AddMaterial(std::move(xMaterial)); } + } } -void AssetDumperXModel::AddXModelObjects(AbstractXModelWriter& writer, const XModel* model, const unsigned lod) -{ - const auto surfCount = model->lodInfo[lod].numsurfs; +void AssetDumperXModel::AddXModelObjects(AbstractXModelWriter &writer, const XModel *model, const unsigned lod) { + const auto surfCount = model->lodInfo[lod].numsurfs; - for (auto surfIndex = 0u; surfIndex < surfCount; surfIndex++) - { - XModelObject object; - object.name = "surf" + std::to_string(surfIndex); + for (auto surfIndex = 0u; surfIndex < surfCount; surfIndex++) { + XModelObject object; + object.name = "surf" + std::to_string(surfIndex); - writer.AddObject(std::move(object)); - } + writer.AddObject(std::move(object)); + } } -void AssetDumperXModel::AddXModelVertices(AbstractXModelWriter& writer, const XModel* model, const unsigned lod) -{ - const auto* surfs = &model->surfs[model->lodInfo[lod].surfIndex]; - const auto surfCount = model->lodInfo[lod].numsurfs; - - for (auto surfIndex = 0u; surfIndex < surfCount; surfIndex++) - { - const auto& surface = surfs[surfIndex]; - - for (auto vertexIndex = 0u; vertexIndex < surface.vertCount; vertexIndex++) - { - const auto& v = surface.verts0[vertexIndex]; - vec2_t uv; - vec3_t normalVec; - vec4_t color; - - Common::Vec2UnpackTexCoords(v.texCoord, &uv); - Common::Vec3UnpackUnitVec(v.normal, &normalVec); - Common::Vec4UnpackGfxColor(v.color, &color); - - XModelVertex vertex{}; - vertex.coordinates[0] = v.xyz[0]; - vertex.coordinates[1] = v.xyz[1]; - vertex.coordinates[2] = v.xyz[2]; - vertex.normal[0] = normalVec[0]; - vertex.normal[1] = normalVec[1]; - vertex.normal[2] = normalVec[2]; - vertex.color[0] = color[0]; - vertex.color[1] = color[1]; - vertex.color[2] = color[2]; - vertex.color[3] = color[3]; - vertex.uv[0] = uv[0]; - vertex.uv[1] = uv[1]; - - writer.AddVertex(vertex); - } +void AssetDumperXModel::AddXModelVertices(AbstractXModelWriter &writer, const XModel *model, const unsigned lod) { + const auto *surfs = &model->surfs[model->lodInfo[lod].surfIndex]; + const auto surfCount = model->lodInfo[lod].numsurfs; + + for (auto surfIndex = 0u; surfIndex < surfCount; surfIndex++) { + const auto &surface = surfs[surfIndex]; + + for (auto vertexIndex = 0u; vertexIndex < surface.vertCount; vertexIndex++) { + const auto &v = surface.verts0[vertexIndex]; + vec2_t uv; + vec3_t normalVec; + vec4_t color; + + Common::Vec2UnpackTexCoords(v.texCoord, &uv); + Common::Vec3UnpackUnitVec(v.normal, &normalVec); + Common::Vec4UnpackGfxColor(v.color, &color); + + XModelVertex vertex{}; + vertex.coordinates[0] = v.xyz[0]; + vertex.coordinates[1] = v.xyz[1]; + vertex.coordinates[2] = v.xyz[2]; + vertex.normal[0] = normalVec[0]; + vertex.normal[1] = normalVec[1]; + vertex.normal[2] = normalVec[2]; + vertex.color[0] = color[0]; + vertex.color[1] = color[1]; + vertex.color[2] = color[2]; + vertex.color[3] = color[3]; + vertex.uv[0] = uv[0]; + vertex.uv[1] = uv[1]; + + writer.AddVertex(vertex); } + } } -void AssetDumperXModel::AllocateXModelBoneWeights(const XModel* model, const unsigned lod, XModelVertexBoneWeightCollection& weightCollection) -{ - const auto* surfs = &model->surfs[model->lodInfo[lod].surfIndex]; - const auto surfCount = model->lodInfo[lod].numsurfs; +void AssetDumperXModel::AllocateXModelBoneWeights(const XModel *model, const unsigned lod, XModelVertexBoneWeightCollection &weightCollection) { + const auto *surfs = &model->surfs[model->lodInfo[lod].surfIndex]; + const auto surfCount = model->lodInfo[lod].numsurfs; - weightCollection.totalWeightCount = 0u; - for (auto surfIndex = 0u; surfIndex < surfCount; surfIndex++) - { - const auto& surface = surfs[surfIndex]; + weightCollection.totalWeightCount = 0u; + for (auto surfIndex = 0u; surfIndex < surfCount; surfIndex++) { + const auto &surface = surfs[surfIndex]; - if (surface.vertList) - { - weightCollection.totalWeightCount += surface.vertListCount; - } + if (surface.vertList) { + weightCollection.totalWeightCount += surface.vertListCount; + } - if (surface.vertInfo.vertsBlend) - { - weightCollection.totalWeightCount += surface.vertInfo.vertCount[0] * 1; - weightCollection.totalWeightCount += surface.vertInfo.vertCount[1] * 2; - weightCollection.totalWeightCount += surface.vertInfo.vertCount[2] * 3; - weightCollection.totalWeightCount += surface.vertInfo.vertCount[3] * 4; - } + if (surface.vertInfo.vertsBlend) { + weightCollection.totalWeightCount += surface.vertInfo.vertCount[0] * 1; + weightCollection.totalWeightCount += surface.vertInfo.vertCount[1] * 2; + weightCollection.totalWeightCount += surface.vertInfo.vertCount[2] * 3; + weightCollection.totalWeightCount += surface.vertInfo.vertCount[3] * 4; } + } - weightCollection.weights = std::make_unique<XModelBoneWeight[]>(weightCollection.totalWeightCount); + weightCollection.weights = std::make_unique<XModelBoneWeight[]>(weightCollection.totalWeightCount); } -void AssetDumperXModel::AddXModelVertexBoneWeights(AbstractXModelWriter& writer, const XModel* model, const unsigned lod, XModelVertexBoneWeightCollection& weightCollection) -{ - const auto* surfs = &model->surfs[model->lodInfo[lod].surfIndex]; - const auto surfCount = model->lodInfo[lod].numsurfs; - - size_t weightOffset = 0u; - - for (auto surfIndex = 0u; surfIndex < surfCount; surfIndex++) - { - const auto& surface = surfs[surfIndex]; - auto handledVertices = 0u; - - if (surface.vertList) - { - for (auto vertListIndex = 0u; vertListIndex < surface.vertListCount; vertListIndex++) - { - const auto& vertList = surface.vertList[vertListIndex]; - const auto* boneWeightOffset = &weightCollection.weights[weightOffset]; - - weightCollection.weights[weightOffset++] = XModelBoneWeight{ - static_cast<int>(vertList.boneOffset / sizeof(DObjSkelMat)), - 1.0f - }; - - for (auto vertListVertexOffset = 0u; vertListVertexOffset < vertList.vertCount; vertListVertexOffset++) - { - writer.AddVertexBoneWeights(XModelVertexBoneWeights{ - boneWeightOffset, - 1 - }); - } - handledVertices += vertList.vertCount; - } - } +void AssetDumperXModel::AddXModelVertexBoneWeights(AbstractXModelWriter &writer, const XModel *model, const unsigned lod, + XModelVertexBoneWeightCollection &weightCollection) { + const auto *surfs = &model->surfs[model->lodInfo[lod].surfIndex]; + const auto surfCount = model->lodInfo[lod].numsurfs; - auto vertsBlendOffset = 0u; - if (surface.vertInfo.vertsBlend) - { - // 1 bone weight - for (auto vertIndex = 0; vertIndex < surface.vertInfo.vertCount[0]; vertIndex++) - { - const auto* boneWeightOffset = &weightCollection.weights[weightOffset]; - const auto boneIndex0 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 0] / sizeof(DObjSkelMat)); - weightCollection.weights[weightOffset++] = XModelBoneWeight{ - boneIndex0, - 1.0f - }; - - vertsBlendOffset += 1; - - writer.AddVertexBoneWeights(XModelVertexBoneWeights{ - boneWeightOffset, - 1 - }); - } - - // 2 bone weights - for (auto vertIndex = 0; vertIndex < surface.vertInfo.vertCount[1]; vertIndex++) - { - const auto* boneWeightOffset = &weightCollection.weights[weightOffset]; - const auto boneIndex0 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 0] / sizeof(DObjSkelMat)); - const auto boneIndex1 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 1] / sizeof(DObjSkelMat)); - const auto boneWeight1 = HalfFloat::ToFloat(surface.vertInfo.vertsBlend[vertsBlendOffset + 2]); - const auto boneWeight0 = 1.0f - boneWeight1; - - weightCollection.weights[weightOffset++] = XModelBoneWeight{ - boneIndex0, - boneWeight0 - }; - weightCollection.weights[weightOffset++] = XModelBoneWeight{ - boneIndex1, - boneWeight1 - }; - - vertsBlendOffset += 3; - - writer.AddVertexBoneWeights(XModelVertexBoneWeights{ - boneWeightOffset, - 2 - }); - } - - // 3 bone weights - for (auto vertIndex = 0; vertIndex < surface.vertInfo.vertCount[2]; vertIndex++) - { - const auto* boneWeightOffset = &weightCollection.weights[weightOffset]; - const auto boneIndex0 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 0] / sizeof(DObjSkelMat)); - const auto boneIndex1 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 1] / sizeof(DObjSkelMat)); - const auto boneWeight1 = HalfFloat::ToFloat(surface.vertInfo.vertsBlend[vertsBlendOffset + 2]); - const auto boneIndex2 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 3] / sizeof(DObjSkelMat)); - const auto boneWeight2 = HalfFloat::ToFloat(surface.vertInfo.vertsBlend[vertsBlendOffset + 4]); - const auto boneWeight0 = 1.0f - boneWeight1 - boneWeight2; - - weightCollection.weights[weightOffset++] = XModelBoneWeight{ - boneIndex0, - boneWeight0 - }; - weightCollection.weights[weightOffset++] = XModelBoneWeight{ - boneIndex1, - boneWeight1 - }; - weightCollection.weights[weightOffset++] = XModelBoneWeight{ - boneIndex2, - boneWeight2 - }; - - vertsBlendOffset += 5; - - writer.AddVertexBoneWeights(XModelVertexBoneWeights{ - boneWeightOffset, - 3 - }); - } - - // 4 bone weights - for (auto vertIndex = 0; vertIndex < surface.vertInfo.vertCount[3]; vertIndex++) - { - const auto* boneWeightOffset = &weightCollection.weights[weightOffset]; - const auto boneIndex0 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 0] / sizeof(DObjSkelMat)); - const auto boneIndex1 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 1] / sizeof(DObjSkelMat)); - const auto boneWeight1 = HalfFloat::ToFloat(surface.vertInfo.vertsBlend[vertsBlendOffset + 2]); - const auto boneIndex2 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 3] / sizeof(DObjSkelMat)); - const auto boneWeight2 = HalfFloat::ToFloat(surface.vertInfo.vertsBlend[vertsBlendOffset + 4]); - const auto boneIndex3 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 5] / sizeof(DObjSkelMat)); - const auto boneWeight3 = HalfFloat::ToFloat(surface.vertInfo.vertsBlend[vertsBlendOffset + 6]); - const auto boneWeight0 = 1.0f - boneWeight1 - boneWeight2 - boneWeight3; - - weightCollection.weights[weightOffset++] = XModelBoneWeight{ - boneIndex0, - boneWeight0 - }; - weightCollection.weights[weightOffset++] = XModelBoneWeight{ - boneIndex1, - boneWeight1 - }; - weightCollection.weights[weightOffset++] = XModelBoneWeight{ - boneIndex2, - boneWeight2 - }; - weightCollection.weights[weightOffset++] = XModelBoneWeight{ - boneIndex3, - boneWeight3 - }; - - vertsBlendOffset += 7; - - writer.AddVertexBoneWeights(XModelVertexBoneWeights{ - boneWeightOffset, - 4 - }); - } - - handledVertices += surface.vertInfo.vertCount[0] + surface.vertInfo.vertCount[1] + surface.vertInfo.vertCount[2] + surface.vertInfo.vertCount[3]; - } + size_t weightOffset = 0u; + + for (auto surfIndex = 0u; surfIndex < surfCount; surfIndex++) { + const auto &surface = surfs[surfIndex]; + auto handledVertices = 0u; - for (; handledVertices < surface.vertCount; handledVertices++) - { - writer.AddVertexBoneWeights(XModelVertexBoneWeights{ - nullptr, - 0 - }); + if (surface.vertList) { + for (auto vertListIndex = 0u; vertListIndex < surface.vertListCount; vertListIndex++) { + const auto &vertList = surface.vertList[vertListIndex]; + const auto *boneWeightOffset = &weightCollection.weights[weightOffset]; + + weightCollection.weights[weightOffset++] = XModelBoneWeight{static_cast<int>(vertList.boneOffset / sizeof(DObjSkelMat)), 1.0f}; + + for (auto vertListVertexOffset = 0u; vertListVertexOffset < vertList.vertCount; vertListVertexOffset++) { + writer.AddVertexBoneWeights(XModelVertexBoneWeights{boneWeightOffset, 1}); } + handledVertices += vertList.vertCount; + } + } + + auto vertsBlendOffset = 0u; + if (surface.vertInfo.vertsBlend) { + // 1 bone weight + for (auto vertIndex = 0; vertIndex < surface.vertInfo.vertCount[0]; vertIndex++) { + const auto *boneWeightOffset = &weightCollection.weights[weightOffset]; + const auto boneIndex0 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 0] / sizeof(DObjSkelMat)); + weightCollection.weights[weightOffset++] = XModelBoneWeight{boneIndex0, 1.0f}; + + vertsBlendOffset += 1; + + writer.AddVertexBoneWeights(XModelVertexBoneWeights{boneWeightOffset, 1}); + } + + // 2 bone weights + for (auto vertIndex = 0; vertIndex < surface.vertInfo.vertCount[1]; vertIndex++) { + const auto *boneWeightOffset = &weightCollection.weights[weightOffset]; + const auto boneIndex0 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 0] / sizeof(DObjSkelMat)); + const auto boneIndex1 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 1] / sizeof(DObjSkelMat)); + const auto boneWeight1 = HalfFloat::ToFloat(surface.vertInfo.vertsBlend[vertsBlendOffset + 2]); + const auto boneWeight0 = 1.0f - boneWeight1; + + weightCollection.weights[weightOffset++] = XModelBoneWeight{boneIndex0, boneWeight0}; + weightCollection.weights[weightOffset++] = XModelBoneWeight{boneIndex1, boneWeight1}; + + vertsBlendOffset += 3; + + writer.AddVertexBoneWeights(XModelVertexBoneWeights{boneWeightOffset, 2}); + } + + // 3 bone weights + for (auto vertIndex = 0; vertIndex < surface.vertInfo.vertCount[2]; vertIndex++) { + const auto *boneWeightOffset = &weightCollection.weights[weightOffset]; + const auto boneIndex0 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 0] / sizeof(DObjSkelMat)); + const auto boneIndex1 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 1] / sizeof(DObjSkelMat)); + const auto boneWeight1 = HalfFloat::ToFloat(surface.vertInfo.vertsBlend[vertsBlendOffset + 2]); + const auto boneIndex2 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 3] / sizeof(DObjSkelMat)); + const auto boneWeight2 = HalfFloat::ToFloat(surface.vertInfo.vertsBlend[vertsBlendOffset + 4]); + const auto boneWeight0 = 1.0f - boneWeight1 - boneWeight2; + + weightCollection.weights[weightOffset++] = XModelBoneWeight{boneIndex0, boneWeight0}; + weightCollection.weights[weightOffset++] = XModelBoneWeight{boneIndex1, boneWeight1}; + weightCollection.weights[weightOffset++] = XModelBoneWeight{boneIndex2, boneWeight2}; + + vertsBlendOffset += 5; + + writer.AddVertexBoneWeights(XModelVertexBoneWeights{boneWeightOffset, 3}); + } + + // 4 bone weights + for (auto vertIndex = 0; vertIndex < surface.vertInfo.vertCount[3]; vertIndex++) { + const auto *boneWeightOffset = &weightCollection.weights[weightOffset]; + const auto boneIndex0 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 0] / sizeof(DObjSkelMat)); + const auto boneIndex1 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 1] / sizeof(DObjSkelMat)); + const auto boneWeight1 = HalfFloat::ToFloat(surface.vertInfo.vertsBlend[vertsBlendOffset + 2]); + const auto boneIndex2 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 3] / sizeof(DObjSkelMat)); + const auto boneWeight2 = HalfFloat::ToFloat(surface.vertInfo.vertsBlend[vertsBlendOffset + 4]); + const auto boneIndex3 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 5] / sizeof(DObjSkelMat)); + const auto boneWeight3 = HalfFloat::ToFloat(surface.vertInfo.vertsBlend[vertsBlendOffset + 6]); + const auto boneWeight0 = 1.0f - boneWeight1 - boneWeight2 - boneWeight3; + + weightCollection.weights[weightOffset++] = XModelBoneWeight{boneIndex0, boneWeight0}; + weightCollection.weights[weightOffset++] = XModelBoneWeight{boneIndex1, boneWeight1}; + weightCollection.weights[weightOffset++] = XModelBoneWeight{boneIndex2, boneWeight2}; + weightCollection.weights[weightOffset++] = XModelBoneWeight{boneIndex3, boneWeight3}; + + vertsBlendOffset += 7; + + writer.AddVertexBoneWeights(XModelVertexBoneWeights{boneWeightOffset, 4}); + } + + handledVertices += surface.vertInfo.vertCount[0] + surface.vertInfo.vertCount[1] + surface.vertInfo.vertCount[2] + surface.vertInfo.vertCount[3]; + } + + for (; handledVertices < surface.vertCount; handledVertices++) { + writer.AddVertexBoneWeights(XModelVertexBoneWeights{nullptr, 0}); } + } } -void AssetDumperXModel::AddXModelFaces(AbstractXModelWriter& writer, const DistinctMapper<Material*>& materialMapper, const XModel* model, const unsigned lod) -{ - const auto* surfs = &model->surfs[model->lodInfo[lod].surfIndex]; - const auto surfCount = model->lodInfo[lod].numsurfs; - const auto baseSurfIndex = model->lodInfo[lod].surfIndex; - - for (auto surfIndex = 0u; surfIndex < surfCount; surfIndex++) - { - const auto& surface = surfs[surfIndex]; - for (auto triIndex = 0u; triIndex < surface.triCount; triIndex++) - { - const auto& tri = surface.triIndices[triIndex]; - - XModelFace face{}; - face.vertexIndex[0] = tri[0] + surface.baseVertIndex; - face.vertexIndex[1] = tri[1] + surface.baseVertIndex; - face.vertexIndex[2] = tri[2] + surface.baseVertIndex; - face.objectIndex = static_cast<int>(surfIndex); - face.materialIndex = static_cast<int>(materialMapper.GetDistinctPositionByInputPosition(surfIndex + baseSurfIndex)); - writer.AddFace(face); - } +void AssetDumperXModel::AddXModelFaces(AbstractXModelWriter &writer, const DistinctMapper<Material *> &materialMapper, const XModel *model, + const unsigned lod) { + const auto *surfs = &model->surfs[model->lodInfo[lod].surfIndex]; + const auto surfCount = model->lodInfo[lod].numsurfs; + const auto baseSurfIndex = model->lodInfo[lod].surfIndex; + + for (auto surfIndex = 0u; surfIndex < surfCount; surfIndex++) { + const auto &surface = surfs[surfIndex]; + for (auto triIndex = 0u; triIndex < surface.triCount; triIndex++) { + const auto &tri = surface.triIndices[triIndex]; + + XModelFace face{}; + face.vertexIndex[0] = tri[0] + surface.baseVertIndex; + face.vertexIndex[1] = tri[1] + surface.baseVertIndex; + face.vertexIndex[2] = tri[2] + surface.baseVertIndex; + face.objectIndex = static_cast<int>(surfIndex); + face.materialIndex = static_cast<int>(materialMapper.GetDistinctPositionByInputPosition(surfIndex + baseSurfIndex)); + writer.AddFace(face); } + } } -void AssetDumperXModel::DumpXModelExportLod(const AssetDumpingContext& context, XAssetInfo<XModel>* asset, const unsigned lod) -{ - const auto* model = asset->Asset(); +void AssetDumperXModel::DumpXModelExportLod(const AssetDumpingContext &context, XAssetInfo<XModel> *asset, const unsigned lod) { + const auto *model = asset->Asset(); - std::ostringstream ss; - ss << "model_export/" << model->name << "_lod" << lod << ".XMODEL_EXPORT"; + std::ostringstream ss; + ss << "model_export/" << model->name << "_lod" << lod << ".XMODEL_EXPORT"; - const auto assetFile = context.OpenAssetFile(ss.str()); + const auto assetFile = context.OpenAssetFile(ss.str()); - if (!assetFile) - return; + if (!assetFile) + return; - const auto writer = XModelExportWriter::CreateWriterForVersion6(context.m_zone->m_game->GetShortName(), context.m_zone->m_name); - DistinctMapper<Material*> materialMapper(model->numsurfs); - XModelVertexBoneWeightCollection boneWeightCollection; - AllocateXModelBoneWeights(model, lod, boneWeightCollection); + const auto writer = XModelExportWriter::CreateWriterForVersion6(context.m_zone->m_game->GetShortName(), context.m_zone->m_name); + DistinctMapper<Material *> materialMapper(model->numsurfs); + XModelVertexBoneWeightCollection boneWeightCollection; + AllocateXModelBoneWeights(model, lod, boneWeightCollection); - AddXModelBones(context, *writer, model); - AddXModelMaterials(*writer, materialMapper, model); - AddXModelObjects(*writer, model, lod); - AddXModelVertices(*writer, model, lod); - AddXModelVertexBoneWeights(*writer, model, lod, boneWeightCollection); - AddXModelFaces(*writer, materialMapper, model, lod); + AddXModelBones(context, *writer, model); + AddXModelMaterials(*writer, materialMapper, model); + AddXModelObjects(*writer, model, lod); + AddXModelVertices(*writer, model, lod); + AddXModelVertexBoneWeights(*writer, model, lod, boneWeightCollection); + AddXModelFaces(*writer, materialMapper, model, lod); - writer->Write(*assetFile); + writer->Write(*assetFile); } -void AssetDumperXModel::DumpXModelExport(const AssetDumpingContext& context, XAssetInfo<XModel>* asset) -{ - const auto* model = asset->Asset(); - for (auto currentLod = 0u; currentLod < model->numLods; currentLod++) - { - DumpXModelExportLod(context, asset, currentLod); - } +void AssetDumperXModel::DumpXModelExport(const AssetDumpingContext &context, XAssetInfo<XModel> *asset) { + const auto *model = asset->Asset(); + for (auto currentLod = 0u; currentLod < model->numLods; currentLod++) { + DumpXModelExportLod(context, asset, currentLod); + } } -void AssetDumperXModel::DumpAsset(AssetDumpingContext& context, XAssetInfo<XModel>* asset) -{ - switch (ObjWriting::Configuration.ModelOutputFormat) - { - case ObjWriting::Configuration_t::ModelOutputFormat_e::OBJ: - DumpObj(context, asset); - break; - - case ObjWriting::Configuration_t::ModelOutputFormat_e::XMODEL_EXPORT: - DumpXModelExport(context, asset); - break; - - default: - assert(false); - break; - } +void AssetDumperXModel::DumpAsset(AssetDumpingContext &context, XAssetInfo<XModel> *asset) { + switch (ObjWriting::Configuration.ModelOutputFormat) { + case ObjWriting::Configuration_t::ModelOutputFormat_e::OBJ: + DumpObj(context, asset); + break; + + case ObjWriting::Configuration_t::ModelOutputFormat_e::XMODEL_EXPORT: + DumpXModelExport(context, asset); + break; + + default: + assert(false); + break; + } } diff --git a/src/ObjWriting/Game/IW3/AssetDumpers/AssetDumperXModel.h b/src/ObjWriting/Game/IW3/AssetDumpers/AssetDumperXModel.h index 5c57f42a1..5910a81c8 100644 --- a/src/ObjWriting/Game/IW3/AssetDumpers/AssetDumperXModel.h +++ b/src/ObjWriting/Game/IW3/AssetDumpers/AssetDumperXModel.h @@ -2,38 +2,36 @@ #include "Dumping/AbstractAssetDumper.h" #include "Game/IW3/IW3.h" -#include "Utils/DistinctMapper.h" -#include "Model/XModel/AbstractXModelWriter.h" #include "Model/Obj/ObjWriter.h" +#include "Model/XModel/AbstractXModelWriter.h" +#include "Utils/DistinctMapper.h" -namespace IW3 -{ - class AssetDumperXModel final : public AbstractAssetDumper<XModel> - { - static GfxImage* GetMaterialColorMap(const Material* material); - static GfxImage* GetMaterialNormalMap(const Material* material); - static GfxImage* GetMaterialSpecularMap(const Material* material); +namespace IW3 { +class AssetDumperXModel final : public AbstractAssetDumper<XModel> { + static GfxImage *GetMaterialColorMap(const Material *material); + static GfxImage *GetMaterialNormalMap(const Material *material); + static GfxImage *GetMaterialSpecularMap(const Material *material); - static void AddObjMaterials(ObjWriter& writer, DistinctMapper<Material*>& materialMapper, const XModel* model); - static void AddObjObjects(ObjWriter& writer, const DistinctMapper<Material*>& materialMapper, const XModel* model, unsigned lod); - static void AddObjVertices(ObjWriter& writer, const XModel* model, unsigned lod); - static void AddObjFaces(ObjWriter& writer, const XModel* model, unsigned lod); - static void DumpObjLod(AssetDumpingContext& context, XAssetInfo<XModel>* asset, unsigned lod); - static void DumpObjMat(const AssetDumpingContext& context, XAssetInfo<XModel>* asset); - static void DumpObj(AssetDumpingContext& context, XAssetInfo<XModel>* asset); + static void AddObjMaterials(ObjWriter &writer, DistinctMapper<Material *> &materialMapper, const XModel *model); + static void AddObjObjects(ObjWriter &writer, const DistinctMapper<Material *> &materialMapper, const XModel *model, unsigned lod); + static void AddObjVertices(ObjWriter &writer, const XModel *model, unsigned lod); + static void AddObjFaces(ObjWriter &writer, const XModel *model, unsigned lod); + static void DumpObjLod(AssetDumpingContext &context, XAssetInfo<XModel> *asset, unsigned lod); + static void DumpObjMat(const AssetDumpingContext &context, XAssetInfo<XModel> *asset); + static void DumpObj(AssetDumpingContext &context, XAssetInfo<XModel> *asset); - static void AddXModelBones(const AssetDumpingContext& context, AbstractXModelWriter& writer, const XModel* model); - static void AddXModelMaterials(AbstractXModelWriter& writer, DistinctMapper<Material*>& materialMapper, const XModel* model); - static void AddXModelObjects(AbstractXModelWriter& writer, const XModel* model, unsigned lod); - static void AddXModelVertices(AbstractXModelWriter& writer, const XModel* model, unsigned lod); - static void AllocateXModelBoneWeights(const XModel* model, unsigned lod, XModelVertexBoneWeightCollection& weightCollection); - static void AddXModelVertexBoneWeights(AbstractXModelWriter& writer, const XModel* model, unsigned lod, XModelVertexBoneWeightCollection& weightCollection); - static void AddXModelFaces(AbstractXModelWriter& writer, const DistinctMapper<Material*>& materialMapper, const XModel* model, unsigned lod); - static void DumpXModelExportLod(const AssetDumpingContext& context, XAssetInfo<XModel>* asset, unsigned lod); - static void DumpXModelExport(const AssetDumpingContext& context, XAssetInfo<XModel>* asset); + static void AddXModelBones(const AssetDumpingContext &context, AbstractXModelWriter &writer, const XModel *model); + static void AddXModelMaterials(AbstractXModelWriter &writer, DistinctMapper<Material *> &materialMapper, const XModel *model); + static void AddXModelObjects(AbstractXModelWriter &writer, const XModel *model, unsigned lod); + static void AddXModelVertices(AbstractXModelWriter &writer, const XModel *model, unsigned lod); + static void AllocateXModelBoneWeights(const XModel *model, unsigned lod, XModelVertexBoneWeightCollection &weightCollection); + static void AddXModelVertexBoneWeights(AbstractXModelWriter &writer, const XModel *model, unsigned lod, XModelVertexBoneWeightCollection &weightCollection); + static void AddXModelFaces(AbstractXModelWriter &writer, const DistinctMapper<Material *> &materialMapper, const XModel *model, unsigned lod); + static void DumpXModelExportLod(const AssetDumpingContext &context, XAssetInfo<XModel> *asset, unsigned lod); + static void DumpXModelExport(const AssetDumpingContext &context, XAssetInfo<XModel> *asset); - protected: - bool ShouldDump(XAssetInfo<XModel>* asset) override; - void DumpAsset(AssetDumpingContext& context, XAssetInfo<XModel>* asset) override; - }; -} +protected: + bool ShouldDump(XAssetInfo<XModel> *asset) override; + void DumpAsset(AssetDumpingContext &context, XAssetInfo<XModel> *asset) override; +}; +} // namespace IW3 diff --git a/src/ObjWriting/Game/IW3/ZoneDumperIW3.cpp b/src/ObjWriting/Game/IW3/ZoneDumperIW3.cpp index a01e839ec..efbdb882d 100644 --- a/src/ObjWriting/Game/IW3/ZoneDumperIW3.cpp +++ b/src/ObjWriting/Game/IW3/ZoneDumperIW3.cpp @@ -1,8 +1,8 @@ #include "ZoneDumperIW3.h" -#include "ObjWriting.h" -#include "Game/IW3/GameIW3.h" #include "Game/IW3/GameAssetPoolIW3.h" +#include "Game/IW3/GameIW3.h" +#include "ObjWriting.h" #include "AssetDumpers/AssetDumperGfxImage.h" #include "AssetDumpers/AssetDumperLoadedSound.h" @@ -16,50 +16,45 @@ using namespace IW3; -bool ZoneDumper::CanHandleZone(AssetDumpingContext& context) const -{ - return context.m_zone->m_game == &g_GameIW3; -} - -bool ZoneDumper::DumpZone(AssetDumpingContext& context) const -{ -#define DUMP_ASSET_POOL(dumperType, poolName, assetType) \ - if(assetPools->poolName && ObjWriting::ShouldHandleAssetType(assetType)) \ - { \ - dumperType dumper; \ - dumper.DumpPool(context, assetPools->poolName.get()); \ - } - - const auto* assetPools = dynamic_cast<GameAssetPoolIW3*>(context.m_zone->m_pools.get()); - - // DUMP_ASSET_POOL(AssetDumperPhysPreset, m_phys_preset, ASSET_TYPE_PHYSPRESET) - // DUMP_ASSET_POOL(AssetDumperXAnimParts, m_xanim_parts, ASSET_TYPE_XANIMPARTS) - DUMP_ASSET_POOL(AssetDumperXModel, m_xmodel, ASSET_TYPE_XMODEL) - DUMP_ASSET_POOL(AssetDumperMaterial, m_material, ASSET_TYPE_MATERIAL) - // DUMP_ASSET_POOL(AssetDumperMaterialTechniqueSet, m_technique_set, ASSET_TYPE_TECHNIQUE_SET) - DUMP_ASSET_POOL(AssetDumperGfxImage, m_image, ASSET_TYPE_IMAGE) - // DUMP_ASSET_POOL(AssetDumpersnd_alias_list_t, m_sound, ASSET_TYPE_SOUND) - // DUMP_ASSET_POOL(AssetDumperSndCurve, m_sound_curve, ASSET_TYPE_SOUND_CURVE) - DUMP_ASSET_POOL(AssetDumperLoadedSound, m_loaded_sound, ASSET_TYPE_LOADED_SOUND) - // DUMP_ASSET_POOL(AssetDumperclipMap_t, m_clip_map, ASSET_TYPE_CLIPMAP) - // DUMP_ASSET_POOL(AssetDumperComWorld, m_com_world, ASSET_TYPE_COMWORLD) - // DUMP_ASSET_POOL(AssetDumperGameWorldSp, m_game_world_sp, ASSET_TYPE_GAMEWORLD_SP) - // DUMP_ASSET_POOL(AssetDumperGameWorldMp, m_game_world_mp, ASSET_TYPE_GAMEWORLD_MP) - DUMP_ASSET_POOL(AssetDumperMapEnts, m_map_ents, ASSET_TYPE_MAP_ENTS) - // DUMP_ASSET_POOL(AssetDumperGfxWorld, m_gfx_world, ASSET_TYPE_GFXWORLD) - // DUMP_ASSET_POOL(AssetDumperGfxLightDef, m_gfx_light_def, ASSET_TYPE_LIGHT_DEF) - // DUMP_ASSET_POOL(AssetDumperFont_s, m_font, ASSET_TYPE_FONT) - // DUMP_ASSET_POOL(AssetDumperMenuList, m_menu_list, ASSET_TYPE_MENULIST) - // DUMP_ASSET_POOL(AssetDumpermenuDef_t, m_menu_def, ASSET_TYPE_MENU) - DUMP_ASSET_POOL(AssetDumperLocalizeEntry, m_localize, ASSET_TYPE_LOCALIZE_ENTRY) - // DUMP_ASSET_POOL(AssetDumperWeapon, m_weapon, ASSET_TYPE_WEAPON) - // DUMP_ASSET_POOL(AssetDumperSndDriverGlobals, m_snd_driver_globals, ASSET_TYPE_SNDDRIVER_GLOBALS) - // DUMP_ASSET_POOL(AssetDumperFxEffectDef, m_fx, ASSET_TYPE_FX) - // DUMP_ASSET_POOL(AssetDumperFxImpactTable, m_fx_impact_table, ASSET_TYPE_IMPACT_FX) - DUMP_ASSET_POOL(AssetDumperRawFile, m_raw_file, ASSET_TYPE_RAWFILE) - DUMP_ASSET_POOL(AssetDumperStringTable, m_string_table, ASSET_TYPE_STRINGTABLE) - - return true; +bool ZoneDumper::CanHandleZone(AssetDumpingContext &context) const { return context.m_zone->m_game == &g_GameIW3; } + +bool ZoneDumper::DumpZone(AssetDumpingContext &context) const { +#define DUMP_ASSET_POOL(dumperType, poolName, assetType) \ + if (assetPools->poolName && ObjWriting::ShouldHandleAssetType(assetType)) { \ + dumperType dumper; \ + dumper.DumpPool(context, assetPools->poolName.get()); \ + } + + const auto *assetPools = dynamic_cast<GameAssetPoolIW3 *>(context.m_zone->m_pools.get()); + + // DUMP_ASSET_POOL(AssetDumperPhysPreset, m_phys_preset, ASSET_TYPE_PHYSPRESET) + // DUMP_ASSET_POOL(AssetDumperXAnimParts, m_xanim_parts, ASSET_TYPE_XANIMPARTS) + DUMP_ASSET_POOL(AssetDumperXModel, m_xmodel, ASSET_TYPE_XMODEL) + DUMP_ASSET_POOL(AssetDumperMaterial, m_material, ASSET_TYPE_MATERIAL) + // DUMP_ASSET_POOL(AssetDumperMaterialTechniqueSet, m_technique_set, ASSET_TYPE_TECHNIQUE_SET) + DUMP_ASSET_POOL(AssetDumperGfxImage, m_image, ASSET_TYPE_IMAGE) + // DUMP_ASSET_POOL(AssetDumpersnd_alias_list_t, m_sound, ASSET_TYPE_SOUND) + // DUMP_ASSET_POOL(AssetDumperSndCurve, m_sound_curve, ASSET_TYPE_SOUND_CURVE) + DUMP_ASSET_POOL(AssetDumperLoadedSound, m_loaded_sound, ASSET_TYPE_LOADED_SOUND) + // DUMP_ASSET_POOL(AssetDumperclipMap_t, m_clip_map, ASSET_TYPE_CLIPMAP) + // DUMP_ASSET_POOL(AssetDumperComWorld, m_com_world, ASSET_TYPE_COMWORLD) + // DUMP_ASSET_POOL(AssetDumperGameWorldSp, m_game_world_sp, ASSET_TYPE_GAMEWORLD_SP) + // DUMP_ASSET_POOL(AssetDumperGameWorldMp, m_game_world_mp, ASSET_TYPE_GAMEWORLD_MP) + DUMP_ASSET_POOL(AssetDumperMapEnts, m_map_ents, ASSET_TYPE_MAP_ENTS) + // DUMP_ASSET_POOL(AssetDumperGfxWorld, m_gfx_world, ASSET_TYPE_GFXWORLD) + // DUMP_ASSET_POOL(AssetDumperGfxLightDef, m_gfx_light_def, ASSET_TYPE_LIGHT_DEF) + // DUMP_ASSET_POOL(AssetDumperFont_s, m_font, ASSET_TYPE_FONT) + // DUMP_ASSET_POOL(AssetDumperMenuList, m_menu_list, ASSET_TYPE_MENULIST) + // DUMP_ASSET_POOL(AssetDumpermenuDef_t, m_menu_def, ASSET_TYPE_MENU) + DUMP_ASSET_POOL(AssetDumperLocalizeEntry, m_localize, ASSET_TYPE_LOCALIZE_ENTRY) + // DUMP_ASSET_POOL(AssetDumperWeapon, m_weapon, ASSET_TYPE_WEAPON) + // DUMP_ASSET_POOL(AssetDumperSndDriverGlobals, m_snd_driver_globals, ASSET_TYPE_SNDDRIVER_GLOBALS) + // DUMP_ASSET_POOL(AssetDumperFxEffectDef, m_fx, ASSET_TYPE_FX) + // DUMP_ASSET_POOL(AssetDumperFxImpactTable, m_fx_impact_table, ASSET_TYPE_IMPACT_FX) + DUMP_ASSET_POOL(AssetDumperRawFile, m_raw_file, ASSET_TYPE_RAWFILE) + DUMP_ASSET_POOL(AssetDumperStringTable, m_string_table, ASSET_TYPE_STRINGTABLE) + + return true; #undef DUMP_ASSET_POOL } diff --git a/src/ObjWriting/Game/IW3/ZoneDumperIW3.h b/src/ObjWriting/Game/IW3/ZoneDumperIW3.h index 4de44f6b7..84f96a3a8 100644 --- a/src/ObjWriting/Game/IW3/ZoneDumperIW3.h +++ b/src/ObjWriting/Game/IW3/ZoneDumperIW3.h @@ -1,12 +1,10 @@ #pragma once #include "Dumping/IZoneDumper.h" -namespace IW3 -{ - class ZoneDumper final : public IZoneDumper - { - public: - bool CanHandleZone(AssetDumpingContext& context) const override; - bool DumpZone(AssetDumpingContext& context) const override; - }; -} +namespace IW3 { +class ZoneDumper final : public IZoneDumper { +public: + bool CanHandleZone(AssetDumpingContext &context) const override; + bool DumpZone(AssetDumpingContext &context) const override; +}; +} // namespace IW3 diff --git a/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperAddonMapEnts.cpp b/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperAddonMapEnts.cpp index 58c745c5e..80c5acd2a 100644 --- a/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperAddonMapEnts.cpp +++ b/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperAddonMapEnts.cpp @@ -5,20 +5,16 @@ using namespace IW4; -bool AssetDumperAddonMapEnts::ShouldDump(XAssetInfo<AddonMapEnts>* asset) -{ - return true; -} +bool AssetDumperAddonMapEnts::ShouldDump(XAssetInfo<AddonMapEnts> *asset) { return true; } -void AssetDumperAddonMapEnts::DumpAsset(AssetDumpingContext& context, XAssetInfo<AddonMapEnts>* asset) -{ - const auto* addonMapEnts = asset->Asset(); - const auto assetFile = context.OpenAssetFile(asset->m_name); +void AssetDumperAddonMapEnts::DumpAsset(AssetDumpingContext &context, XAssetInfo<AddonMapEnts> *asset) { + const auto *addonMapEnts = asset->Asset(); + const auto assetFile = context.OpenAssetFile(asset->m_name); - if (!assetFile) - return; + if (!assetFile) + return; - auto& stream = *assetFile; + auto &stream = *assetFile; - stream.write(addonMapEnts->entityString, std::max(addonMapEnts->numEntityChars - 1, 0)); + stream.write(addonMapEnts->entityString, std::max(addonMapEnts->numEntityChars - 1, 0)); } diff --git a/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperAddonMapEnts.h b/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperAddonMapEnts.h index 94da070ea..d47605701 100644 --- a/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperAddonMapEnts.h +++ b/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperAddonMapEnts.h @@ -3,12 +3,10 @@ #include "Dumping/AbstractAssetDumper.h" #include "Game/IW4/IW4.h" -namespace IW4 -{ - class AssetDumperAddonMapEnts final : public AbstractAssetDumper<AddonMapEnts> - { - protected: - bool ShouldDump(XAssetInfo<AddonMapEnts>* asset) override; - void DumpAsset(AssetDumpingContext& context, XAssetInfo<AddonMapEnts>* asset) override; - }; -} +namespace IW4 { +class AssetDumperAddonMapEnts final : public AbstractAssetDumper<AddonMapEnts> { +protected: + bool ShouldDump(XAssetInfo<AddonMapEnts> *asset) override; + void DumpAsset(AssetDumpingContext &context, XAssetInfo<AddonMapEnts> *asset) override; +}; +} // namespace IW4 diff --git a/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperGfxImage.cpp b/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperGfxImage.cpp index 916eaca26..7366a0797 100644 --- a/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperGfxImage.cpp +++ b/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperGfxImage.cpp @@ -2,62 +2,55 @@ #include <cassert> -#include "ObjWriting.h" -#include "Image/IwiWriter8.h" #include "Image/DdsWriter.h" +#include "Image/IwiWriter8.h" +#include "ObjWriting.h" using namespace IW4; -AssetDumperGfxImage::AssetDumperGfxImage() -{ - switch (ObjWriting::Configuration.ImageOutputFormat) - { - case ObjWriting::Configuration_t::ImageOutputFormat_e::DDS: - m_writer = std::make_unique<DdsWriter>(); - break; - case ObjWriting::Configuration_t::ImageOutputFormat_e::IWI: - m_writer = std::make_unique<iwi8::IwiWriter>(); - break; - default: - assert(false); - m_writer = nullptr; - break; - } +AssetDumperGfxImage::AssetDumperGfxImage() { + switch (ObjWriting::Configuration.ImageOutputFormat) { + case ObjWriting::Configuration_t::ImageOutputFormat_e::DDS: + m_writer = std::make_unique<DdsWriter>(); + break; + case ObjWriting::Configuration_t::ImageOutputFormat_e::IWI: + m_writer = std::make_unique<iwi8::IwiWriter>(); + break; + default: + assert(false); + m_writer = nullptr; + break; + } } -bool AssetDumperGfxImage::ShouldDump(XAssetInfo<GfxImage>* asset) -{ - const auto* image = asset->Asset(); - return image->cardMemory.platform[0] > 0; +bool AssetDumperGfxImage::ShouldDump(XAssetInfo<GfxImage> *asset) { + const auto *image = asset->Asset(); + return image->cardMemory.platform[0] > 0; } -std::string AssetDumperGfxImage::GetAssetFileName(XAssetInfo<GfxImage>* asset) const -{ - std::string cleanAssetName = asset->m_name; - for (auto& c : cleanAssetName) - { - switch (c) - { - case '*': - c = '_'; - break; - - default: - break; - } +std::string AssetDumperGfxImage::GetAssetFileName(XAssetInfo<GfxImage> *asset) const { + std::string cleanAssetName = asset->m_name; + for (auto &c : cleanAssetName) { + switch (c) { + case '*': + c = '_'; + break; + + default: + break; } + } - return "images/" + cleanAssetName + m_writer->GetFileExtension(); + return "images/" + cleanAssetName + m_writer->GetFileExtension(); } -void AssetDumperGfxImage::DumpAsset(AssetDumpingContext& context, XAssetInfo<GfxImage>* asset) -{ - const auto* image = asset->Asset(); - const auto assetFile = context.OpenAssetFile(GetAssetFileName(asset)); +void AssetDumperGfxImage::DumpAsset(AssetDumpingContext &context, XAssetInfo<GfxImage> *asset) { + const auto *image = asset->Asset(); + const auto assetFile = context.OpenAssetFile(GetAssetFileName(asset)); - if (!assetFile) - return; + if (!assetFile) + return; - auto& stream = *assetFile; - m_writer->DumpImage(stream, image->texture.texture); + auto &stream = *assetFile; + m_writer->DumpImage(stream, image->texture.texture); } diff --git a/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperGfxImage.h b/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperGfxImage.h index 5d04301df..ad8586ddb 100644 --- a/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperGfxImage.h +++ b/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperGfxImage.h @@ -6,19 +6,17 @@ #include "Game/IW4/IW4.h" #include "Image/IImageWriter.h" -namespace IW4 -{ - class AssetDumperGfxImage final : public AbstractAssetDumper<GfxImage> - { - std::unique_ptr<IImageWriter> m_writer; +namespace IW4 { +class AssetDumperGfxImage final : public AbstractAssetDumper<GfxImage> { + std::unique_ptr<IImageWriter> m_writer; - std::string GetAssetFileName(XAssetInfo<GfxImage>* asset) const; + std::string GetAssetFileName(XAssetInfo<GfxImage> *asset) const; - protected: - bool ShouldDump(XAssetInfo<GfxImage>* asset) override; - void DumpAsset(AssetDumpingContext& context, XAssetInfo<GfxImage>* asset) override; +protected: + bool ShouldDump(XAssetInfo<GfxImage> *asset) override; + void DumpAsset(AssetDumpingContext &context, XAssetInfo<GfxImage> *asset) override; - public: - AssetDumperGfxImage(); - }; -} +public: + AssetDumperGfxImage(); +}; +} // namespace IW4 diff --git a/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperGfxLightDef.cpp b/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperGfxLightDef.cpp index af05c62de..8e90f9025 100644 --- a/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperGfxLightDef.cpp +++ b/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperGfxLightDef.cpp @@ -4,33 +4,28 @@ using namespace IW4; -std::string AssetDumperGfxLightDef::GetAssetFilename(const std::string& assetName) -{ - std::ostringstream ss; +std::string AssetDumperGfxLightDef::GetAssetFilename(const std::string &assetName) { + std::ostringstream ss; - ss << "lights/" << assetName; + ss << "lights/" << assetName; - return ss.str(); + return ss.str(); } -bool AssetDumperGfxLightDef::ShouldDump(XAssetInfo<GfxLightDef>* asset) -{ - return true; -} +bool AssetDumperGfxLightDef::ShouldDump(XAssetInfo<GfxLightDef> *asset) { return true; } -void AssetDumperGfxLightDef::DumpAsset(AssetDumpingContext& context, XAssetInfo<GfxLightDef>* asset) -{ - const auto* lightDef = asset->Asset(); - const auto assetFile = context.OpenAssetFile(GetAssetFilename(asset->m_name)); +void AssetDumperGfxLightDef::DumpAsset(AssetDumpingContext &context, XAssetInfo<GfxLightDef> *asset) { + const auto *lightDef = asset->Asset(); + const auto assetFile = context.OpenAssetFile(GetAssetFilename(asset->m_name)); - if (!assetFile || lightDef->attenuation.image == nullptr || lightDef->attenuation.image->name == nullptr) - return; + if (!assetFile || lightDef->attenuation.image == nullptr || lightDef->attenuation.image->name == nullptr) + return; - auto& stream = *assetFile; + auto &stream = *assetFile; - const auto* imageName = lightDef->attenuation.image->name; - if (imageName[0] == ',') - imageName = &imageName[1]; + const auto *imageName = lightDef->attenuation.image->name; + if (imageName[0] == ',') + imageName = &imageName[1]; - stream << lightDef->attenuation.samplerState << imageName << static_cast<char>(lightDef->lmapLookupStart); + stream << lightDef->attenuation.samplerState << imageName << static_cast<char>(lightDef->lmapLookupStart); } diff --git a/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperGfxLightDef.h b/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperGfxLightDef.h index 9ac707518..2adeec25f 100644 --- a/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperGfxLightDef.h +++ b/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperGfxLightDef.h @@ -3,14 +3,12 @@ #include "Dumping/AbstractAssetDumper.h" #include "Game/IW4/IW4.h" -namespace IW4 -{ - class AssetDumperGfxLightDef final : public AbstractAssetDumper<GfxLightDef> - { - static std::string GetAssetFilename(const std::string& assetName); +namespace IW4 { +class AssetDumperGfxLightDef final : public AbstractAssetDumper<GfxLightDef> { + static std::string GetAssetFilename(const std::string &assetName); - protected: - bool ShouldDump(XAssetInfo<GfxLightDef>* asset) override; - void DumpAsset(AssetDumpingContext& context, XAssetInfo<GfxLightDef>* asset) override; - }; -} +protected: + bool ShouldDump(XAssetInfo<GfxLightDef> *asset) override; + void DumpAsset(AssetDumpingContext &context, XAssetInfo<GfxLightDef> *asset) override; +}; +} // namespace IW4 diff --git a/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperLoadedSound.cpp b/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperLoadedSound.cpp index f7c97209d..2581eacfb 100644 --- a/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperLoadedSound.cpp +++ b/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperLoadedSound.cpp @@ -4,69 +4,47 @@ using namespace IW4; -bool AssetDumperLoadedSound::ShouldDump(XAssetInfo<LoadedSound>* asset) -{ - return true; +bool AssetDumperLoadedSound::ShouldDump(XAssetInfo<LoadedSound> *asset) { return true; } + +void AssetDumperLoadedSound::DumpWavPcm(AssetDumpingContext &context, const LoadedSound *asset, std::ostream &stream) { + const auto riffMasterChunkSize = sizeof(WAV_CHUNK_ID_RIFF) + sizeof(uint32_t) + sizeof(WAV_WAVE_ID) + sizeof(WavChunkHeader) + sizeof(WavFormatChunkPcm) + + sizeof(WavChunkHeader) + sizeof(asset->sound.info.data_len); + + stream.write(reinterpret_cast<const char *>(&WAV_CHUNK_ID_RIFF), sizeof(WAV_CHUNK_ID_RIFF)); + stream.write(reinterpret_cast<const char *>(&riffMasterChunkSize), sizeof(riffMasterChunkSize)); + stream.write(reinterpret_cast<const char *>(&WAV_WAVE_ID), sizeof(WAV_WAVE_ID)); + + const WavChunkHeader formatChunkHeader{WAV_CHUNK_ID_FMT, sizeof(WavFormatChunkPcm)}; + stream.write(reinterpret_cast<const char *>(&formatChunkHeader), sizeof(formatChunkHeader)); + + WavFormatChunkPcm formatChunk{WavFormat::PCM, + static_cast<uint16_t>(asset->sound.info.channels), + asset->sound.info.rate, + asset->sound.info.rate * asset->sound.info.channels * asset->sound.info.bits / 8, + static_cast<uint16_t>(asset->sound.info.block_size), + static_cast<uint16_t>(asset->sound.info.bits)}; + stream.write(reinterpret_cast<const char *>(&formatChunk), sizeof(formatChunk)); + + const WavChunkHeader dataChunkHeader{WAV_CHUNK_ID_DATA, asset->sound.info.data_len}; + stream.write(reinterpret_cast<const char *>(&dataChunkHeader), sizeof(dataChunkHeader)); + stream.write(asset->sound.data, asset->sound.info.data_len); } -void AssetDumperLoadedSound::DumpWavPcm(AssetDumpingContext& context, const LoadedSound* asset, std::ostream& stream) -{ - const auto riffMasterChunkSize = sizeof(WAV_CHUNK_ID_RIFF) - + sizeof(uint32_t) - + sizeof(WAV_WAVE_ID) - + sizeof(WavChunkHeader) - + sizeof(WavFormatChunkPcm) - + sizeof(WavChunkHeader) - + sizeof(asset->sound.info.data_len); +void AssetDumperLoadedSound::DumpAsset(AssetDumpingContext &context, XAssetInfo<LoadedSound> *asset) { + const auto *loadedSound = asset->Asset(); + const auto assetFile = context.OpenAssetFile("sound/" + asset->m_name); - stream.write(reinterpret_cast<const char*>(&WAV_CHUNK_ID_RIFF), sizeof(WAV_CHUNK_ID_RIFF)); - stream.write(reinterpret_cast<const char*>(&riffMasterChunkSize), sizeof(riffMasterChunkSize)); - stream.write(reinterpret_cast<const char*>(&WAV_WAVE_ID), sizeof(WAV_WAVE_ID)); + if (!assetFile) + return; - const WavChunkHeader formatChunkHeader - { - WAV_CHUNK_ID_FMT, - sizeof(WavFormatChunkPcm) - }; - stream.write(reinterpret_cast<const char*>(&formatChunkHeader), sizeof(formatChunkHeader)); + auto &stream = *assetFile; + switch (static_cast<WavFormat>(loadedSound->sound.info.format)) { + case WavFormat::PCM: + DumpWavPcm(context, loadedSound, stream); + break; - WavFormatChunkPcm formatChunk - { - WavFormat::PCM, - static_cast<uint16_t>(asset->sound.info.channels), - asset->sound.info.rate, - asset->sound.info.rate * asset->sound.info.channels * asset->sound.info.bits / 8, - static_cast<uint16_t>(asset->sound.info.block_size), - static_cast<uint16_t>(asset->sound.info.bits) - }; - stream.write(reinterpret_cast<const char*>(&formatChunk), sizeof(formatChunk)); - - const WavChunkHeader dataChunkHeader - { - WAV_CHUNK_ID_DATA, - asset->sound.info.data_len - }; - stream.write(reinterpret_cast<const char*>(&dataChunkHeader), sizeof(dataChunkHeader)); - stream.write(asset->sound.data, asset->sound.info.data_len); -} - -void AssetDumperLoadedSound::DumpAsset(AssetDumpingContext& context, XAssetInfo<LoadedSound>* asset) -{ - const auto* loadedSound = asset->Asset(); - const auto assetFile = context.OpenAssetFile("sound/" + asset->m_name); - - if (!assetFile) - return; - - auto& stream = *assetFile; - switch (static_cast<WavFormat>(loadedSound->sound.info.format)) - { - case WavFormat::PCM: - DumpWavPcm(context, loadedSound, stream); - break; - - default: - printf("Unknown format %i for loaded sound: %s\n", loadedSound->sound.info.format, loadedSound->name); - break; - } + default: + printf("Unknown format %i for loaded sound: %s\n", loadedSound->sound.info.format, loadedSound->name); + break; + } } diff --git a/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperLoadedSound.h b/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperLoadedSound.h index 915d54022..8b89e12fb 100644 --- a/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperLoadedSound.h +++ b/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperLoadedSound.h @@ -3,13 +3,12 @@ #include "Dumping/AbstractAssetDumper.h" #include "Game/IW4/IW4.h" -namespace IW4 -{ - class AssetDumperLoadedSound final : public AbstractAssetDumper<LoadedSound> - { - static void DumpWavPcm(AssetDumpingContext& context, const LoadedSound* asset, std::ostream& stream); - protected: - bool ShouldDump(XAssetInfo<LoadedSound>* asset) override; - void DumpAsset(AssetDumpingContext& context, XAssetInfo<LoadedSound>* asset) override; - }; -} +namespace IW4 { +class AssetDumperLoadedSound final : public AbstractAssetDumper<LoadedSound> { + static void DumpWavPcm(AssetDumpingContext &context, const LoadedSound *asset, std::ostream &stream); + +protected: + bool ShouldDump(XAssetInfo<LoadedSound> *asset) override; + void DumpAsset(AssetDumpingContext &context, XAssetInfo<LoadedSound> *asset) override; +}; +} // namespace IW4 diff --git a/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperLocalizeEntry.cpp b/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperLocalizeEntry.cpp index 4e4f4c180..f468bb699 100644 --- a/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperLocalizeEntry.cpp +++ b/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperLocalizeEntry.cpp @@ -2,42 +2,37 @@ #include <sstream> -#include "Localize/LocalizeCommon.h" #include "Dumping/Localize/StringFileDumper.h" +#include "Localize/LocalizeCommon.h" using namespace IW4; -void AssetDumperLocalizeEntry::DumpPool(AssetDumpingContext& context, AssetPool<LocalizeEntry>* pool) -{ - if (pool->m_asset_lookup.empty()) - return; - - const auto language = LocalizeCommon::GetNameOfLanguage(context.m_zone->m_language); +void AssetDumperLocalizeEntry::DumpPool(AssetDumpingContext &context, AssetPool<LocalizeEntry> *pool) { + if (pool->m_asset_lookup.empty()) + return; - std::ostringstream ss; - ss << language << "/localizedstrings/" << context.m_zone->m_name << ".str"; - const auto assetFile = context.OpenAssetFile(ss.str()); + const auto language = LocalizeCommon::GetNameOfLanguage(context.m_zone->m_language); - if (assetFile) - { - StringFileDumper stringFileDumper(context.m_zone, *assetFile); + std::ostringstream ss; + ss << language << "/localizedstrings/" << context.m_zone->m_name << ".str"; + const auto assetFile = context.OpenAssetFile(ss.str()); - stringFileDumper.SetLanguageName(language); + if (assetFile) { + StringFileDumper stringFileDumper(context.m_zone, *assetFile); - // Magic string. Original string files do have this config file. The purpose of the config file is unknown though. - stringFileDumper.SetConfigFile(R"(C:/trees/cod3/cod3/bin/StringEd.cfg)"); + stringFileDumper.SetLanguageName(language); - stringFileDumper.SetNotes(""); + // Magic string. Original string files do have this config file. The purpose of the config file is unknown though. + stringFileDumper.SetConfigFile(R"(C:/trees/cod3/cod3/bin/StringEd.cfg)"); - for (auto* localizeEntry : *pool) - { - stringFileDumper.WriteLocalizeEntry(localizeEntry->m_name, localizeEntry->Asset()->value); - } + stringFileDumper.SetNotes(""); - stringFileDumper.Finalize(); - } - else - { - printf("Could not create string file for dumping localized strings of zone '%s'\n", context.m_zone->m_name.c_str()); + for (auto *localizeEntry : *pool) { + stringFileDumper.WriteLocalizeEntry(localizeEntry->m_name, localizeEntry->Asset()->value); } + + stringFileDumper.Finalize(); + } else { + printf("Could not create string file for dumping localized strings of zone '%s'\n", context.m_zone->m_name.c_str()); + } } \ No newline at end of file diff --git a/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperLocalizeEntry.h b/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperLocalizeEntry.h index 69641d33e..5b434f4f9 100644 --- a/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperLocalizeEntry.h +++ b/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperLocalizeEntry.h @@ -3,11 +3,9 @@ #include "Dumping/AbstractAssetDumper.h" #include "Game/IW4/IW4.h" -namespace IW4 -{ - class AssetDumperLocalizeEntry final : public IAssetDumper<LocalizeEntry> - { - public: - void DumpPool(AssetDumpingContext& context, AssetPool<LocalizeEntry>* pool) override; - }; -} +namespace IW4 { +class AssetDumperLocalizeEntry final : public IAssetDumper<LocalizeEntry> { +public: + void DumpPool(AssetDumpingContext &context, AssetPool<LocalizeEntry> *pool) override; +}; +} // namespace IW4 diff --git a/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperMaterial.cpp b/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperMaterial.cpp index 616c35799..ba79098a1 100644 --- a/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperMaterial.cpp +++ b/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperMaterial.cpp @@ -1,1503 +1,1232 @@ #include "AssetDumperMaterial.h" #include <iomanip> +#include <nlohmann/json.hpp> #include <sstream> #include <string> #include <type_traits> #include <vector> -#include <nlohmann/json.hpp> -#include "Utils/ClassUtils.h" #include "Game/IW4/MaterialConstantsIW4.h" #include "Game/IW4/ObjConstantsIW4.h" #include "Game/IW4/TechsetConstantsIW4.h" #include "Math/Vector.h" +#include "Utils/ClassUtils.h" #define DUMP_AS_JSON 1 -//#define DUMP_AS_GDT 1 -//#define FLAGS_DEBUG 1 +// #define DUMP_AS_GDT 1 +// #define FLAGS_DEBUG 1 using namespace IW4; using json = nlohmann::json; using namespace std::string_literals; -namespace IW4 -{ - const char* AssetName(const char* name) - { - if (name && name[0] == ',') - return &name[1]; - return name; - } +namespace IW4 { +const char *AssetName(const char *name) { + if (name && name[0] == ',') + return &name[1]; + return name; +} - template <size_t S> - json ArrayEntry(const char* (&a)[S], const size_t index) - { - assert(index < S); - if (index < S) - return a[index]; +template <size_t S> json ArrayEntry(const char *(&a)[S], const size_t index) { + assert(index < S); + if (index < S) + return a[index]; - return json{}; - } + return json{}; +} - json BuildComplexTableJson(const complex_s* complexTable, const size_t count) - { - auto jArray = json::array(); - - if (complexTable) - { - for (auto index = 0u; index < count; index++) - { - const auto& entry = complexTable[index]; - jArray.emplace_back(json{ - {"real", entry.real}, - {"imag", entry.imag} - }); - } - } +json BuildComplexTableJson(const complex_s *complexTable, const size_t count) { + auto jArray = json::array(); - return jArray; + if (complexTable) { + for (auto index = 0u; index < count; index++) { + const auto &entry = complexTable[index]; + jArray.emplace_back(json{ + {"real", entry.real}, + {"imag", entry.imag} + }); } + } - json BuildWaterJson(water_t* water) - { - if (!water) - return json{}; - - return json{ - {"floatTime", water->writable.floatTime}, - {"H0", BuildComplexTableJson(water->H0, water->M * water->N)}, - {"wTerm", water->wTerm ? json{std::vector(water->wTerm, water->wTerm + (water->M * water->N))} : json::array()}, - {"M", water->M}, - {"N", water->N}, - {"Lx", water->Lx}, - {"Lz", water->Lz}, - {"windvel", water->windvel}, - {"winddir", std::vector(std::begin(water->winddir), std::end(water->winddir))}, - {"amplitude", water->amplitude}, - {"codeConstant", std::vector(std::begin(water->codeConstant), std::end(water->codeConstant))}, - {"image", water->image && water->image->name ? AssetName(water->image->name) : nullptr} - }; - } + return jArray; +} - json BuildSamplerStateJson(unsigned char samplerState) - { - static const char* samplerFilterNames[] - { - "none", - "nearest", - "linear", - "aniso2x", - "aniso4x" - }; - static const char* samplerMipmapNames[] - { - "disabled", - "nearest", - "linear" - }; - - return json{ - {"filter", ArrayEntry(samplerFilterNames, (samplerState & SAMPLER_FILTER_MASK) >> SAMPLER_FILTER_SHIFT)}, - {"mipmap", ArrayEntry(samplerMipmapNames, (samplerState & SAMPLER_MIPMAP_MASK) >> SAMPLER_MIPMAP_SHIFT)}, - {"clampU", (samplerState & SAMPLER_CLAMP_U) ? true : false}, - {"clampV", (samplerState & SAMPLER_CLAMP_V) ? true : false}, - {"clampW", (samplerState & SAMPLER_CLAMP_W) ? true : false}, - }; - } +json BuildWaterJson(water_t *water) { + if (!water) + return json{}; + + return json{ + {"floatTime", water->writable.floatTime}, + {"H0", BuildComplexTableJson(water->H0, water->M * water->N)}, + {"wTerm", water->wTerm ? json{std::vector(water->wTerm, water->wTerm + (water->M * water->N))} : json::array()}, + {"M", water->M}, + {"N", water->N}, + {"Lx", water->Lx}, + {"Lz", water->Lz}, + {"windvel", water->windvel}, + {"winddir", std::vector(std::begin(water->winddir), std::end(water->winddir))}, + {"amplitude", water->amplitude}, + {"codeConstant", std::vector(std::begin(water->codeConstant), std::end(water->codeConstant))}, + {"image", water->image && water->image->name ? AssetName(water->image->name) : nullptr} + }; +} - json BuildTextureTableJson(MaterialTextureDef* textureTable, const size_t count) - { - static const char* semanticNames[] - { - "2d", - "function", - "colorMap", - "detailMap", - "unused2", - "normalMap", - "unused3", - "unused4", - "specularMap", - "unused5", - "unused6", - "waterMap" - }; - - auto jArray = json::array(); - - if (textureTable) - { - for (auto index = 0u; index < count; index++) - { - const auto& entry = textureTable[index]; - - json jEntry = { - {"samplerState", BuildSamplerStateJson(entry.samplerState)}, - {"semantic", ArrayEntry(semanticNames, entry.semantic)} - }; - - const auto knownMaterialSourceName = knownTextureMaps.find(entry.nameHash); - if (knownMaterialSourceName != knownTextureMaps.end()) - { - jEntry["name"] = knownMaterialSourceName->second.m_name; - } - else - { - jEntry.merge_patch({ - {"nameHash", entry.nameHash}, - {"nameStart", entry.nameStart}, - {"nameEnd", entry.nameEnd}, - }); - } - - if (entry.semantic == TS_WATER_MAP) - { - jEntry["water"] = BuildWaterJson(entry.u.water); - } - else - { - jEntry["image"] = entry.u.image && entry.u.image->name ? AssetName(entry.u.image->name) : nullptr; - } - - jArray.emplace_back(std::move(jEntry)); - } - } +json BuildSamplerStateJson(unsigned char samplerState) { + static const char *samplerFilterNames[]{"none", "nearest", "linear", "aniso2x", "aniso4x"}; + static const char *samplerMipmapNames[]{"disabled", "nearest", "linear"}; + + return json{ + {"filter", ArrayEntry(samplerFilterNames, (samplerState & SAMPLER_FILTER_MASK) >> SAMPLER_FILTER_SHIFT)}, + {"mipmap", ArrayEntry(samplerMipmapNames, (samplerState & SAMPLER_MIPMAP_MASK) >> SAMPLER_MIPMAP_SHIFT)}, + {"clampU", (samplerState & SAMPLER_CLAMP_U) ? true : false}, + {"clampV", (samplerState & SAMPLER_CLAMP_V) ? true : false}, + {"clampW", (samplerState & SAMPLER_CLAMP_W) ? true : false}, + }; +} - return jArray; +json BuildTextureTableJson(MaterialTextureDef *textureTable, const size_t count) { + static const char *semanticNames[]{"2d", "function", "colorMap", "detailMap", "unused2", "normalMap", + "unused3", "unused4", "specularMap", "unused5", "unused6", "waterMap"}; + + auto jArray = json::array(); + + if (textureTable) { + for (auto index = 0u; index < count; index++) { + const auto &entry = textureTable[index]; + + json jEntry = { + {"samplerState", BuildSamplerStateJson(entry.samplerState)}, + {"semantic", ArrayEntry(semanticNames, entry.semantic)} + }; + + const auto knownMaterialSourceName = knownTextureMaps.find(entry.nameHash); + if (knownMaterialSourceName != knownTextureMaps.end()) { + jEntry["name"] = knownMaterialSourceName->second.m_name; + } else { + jEntry.merge_patch({ + {"nameHash", entry.nameHash }, + {"nameStart", entry.nameStart}, + {"nameEnd", entry.nameEnd }, + }); + } + + if (entry.semantic == TS_WATER_MAP) { + jEntry["water"] = BuildWaterJson(entry.u.water); + } else { + jEntry["image"] = entry.u.image && entry.u.image->name ? AssetName(entry.u.image->name) : nullptr; + } + + jArray.emplace_back(std::move(jEntry)); } + } - json BuildConstantTableJson(const MaterialConstantDef* constantTable, const size_t count) - { - auto jArray = json::array(); - - if (constantTable) - { - for (auto index = 0u; index < count; index++) - { - const auto& entry = constantTable[index]; - json jEntry = { - {"literal", std::vector(std::begin(entry.literal), std::end(entry.literal))} - }; - - const auto nameLen = strnlen(entry.name, std::extent_v<decltype(MaterialConstantDef::name)>); - if (nameLen == std::extent_v<decltype(MaterialConstantDef::name)>) - { - std::string fullLengthName(entry.name, std::extent_v<decltype(MaterialConstantDef::name)>); - const auto fullLengthHash = Common::R_HashString(fullLengthName.c_str(), 0); - - if (fullLengthHash == entry.nameHash) - { - jEntry["name"] = fullLengthName; - } - else - { - const auto knownMaterialSourceName = knownConstantNames.find(entry.nameHash); - if (knownMaterialSourceName != knownConstantNames.end()) - { - jEntry["name"] = knownMaterialSourceName->second; - } - else - { - jEntry.merge_patch({ - {"nameHash", entry.nameHash}, - {"namePart", fullLengthName} - }); - } - } - } - else - { - jEntry["name"] = std::string(entry.name, nameLen); - } - - jArray.emplace_back(std::move(jEntry)); - } + return jArray; +} + +json BuildConstantTableJson(const MaterialConstantDef *constantTable, const size_t count) { + auto jArray = json::array(); + + if (constantTable) { + for (auto index = 0u; index < count; index++) { + const auto &entry = constantTable[index]; + json jEntry = { + {"literal", std::vector(std::begin(entry.literal), std::end(entry.literal))} + }; + + const auto nameLen = strnlen(entry.name, std::extent_v<decltype(MaterialConstantDef::name)>); + if (nameLen == std::extent_v<decltype(MaterialConstantDef::name)>) { + std::string fullLengthName(entry.name, std::extent_v<decltype(MaterialConstantDef::name)>); + const auto fullLengthHash = Common::R_HashString(fullLengthName.c_str(), 0); + + if (fullLengthHash == entry.nameHash) { + jEntry["name"] = fullLengthName; + } else { + const auto knownMaterialSourceName = knownConstantNames.find(entry.nameHash); + if (knownMaterialSourceName != knownConstantNames.end()) { + jEntry["name"] = knownMaterialSourceName->second; + } else { + jEntry.merge_patch({ + {"nameHash", entry.nameHash}, + {"namePart", fullLengthName} + }); + } } + } else { + jEntry["name"] = std::string(entry.name, nameLen); + } - return jArray; + jArray.emplace_back(std::move(jEntry)); } + } - json BuildStateBitsTableJson(const GfxStateBits* stateBitsTable, const size_t count) - { - static const char* blendNames[] - { - "disabled", - "zero", - "one", - "srcColor", - "invSrcColor", - "srcAlpha", - "invSrcAlpha", - "destAlpha", - "invDestAlpha", - "destColor", - "invDestColor", - }; - static const char* blendOpNames[] - { - "disabled", - "add", - "subtract", - "revSubtract", - "min", - "max" - }; - static const char* depthTestNames[] - { - "always", - "less", - "equal", - "lessEqual", - }; - static const char* polygonOffsetNames[] - { - "0", - "1", - "2", - "shadowMap", - }; - static const char* stencilOpNames[] - { - "keep", - "zero", - "replace", - "incrSat", - "decrSat", - "invert", - "incr", - "decr" - }; - static const char* stencilFuncNames[] - { - "never", - "less", - "equal", - "lessEqual", - "greater", - "notEqual", - "greaterEqual", - "always" - }; - - auto jArray = json::array(); - - if (stateBitsTable) - { - for (auto index = 0u; index < count; index++) - { - const auto& entry = stateBitsTable[index]; - - const auto srcBlendRgb = (entry.loadBits[0] & GFXS0_SRCBLEND_RGB_MASK) >> GFXS0_SRCBLEND_RGB_SHIFT; - const auto dstBlendRgb = (entry.loadBits[0] & GFXS0_DSTBLEND_RGB_MASK) >> GFXS0_DSTBLEND_RGB_SHIFT; - const auto blendOpRgb = (entry.loadBits[0] & GFXS0_BLENDOP_RGB_MASK) >> GFXS0_BLENDOP_RGB_SHIFT; - const auto srcBlendAlpha = (entry.loadBits[0] & GFXS0_SRCBLEND_ALPHA_MASK) >> GFXS0_SRCBLEND_ALPHA_SHIFT; - const auto dstBlendAlpha = (entry.loadBits[0] & GFXS0_DSTBLEND_ALPHA_MASK) >> GFXS0_DSTBLEND_ALPHA_SHIFT; - const auto blendOpAlpha = (entry.loadBits[0] & GFXS0_BLENDOP_ALPHA_MASK) >> GFXS0_BLENDOP_ALPHA_SHIFT; - const auto depthTest = (entry.loadBits[1] & GFXS1_DEPTHTEST_MASK) >> GFXS1_DEPTHTEST_SHIFT; - const auto polygonOffset = (entry.loadBits[1] & GFXS1_POLYGON_OFFSET_MASK) >> GFXS1_POLYGON_OFFSET_SHIFT; - - const auto* alphaTest = "disable"; - if ((entry.loadBits[0] & GFXS0_ATEST_MASK) == GFXS0_ATEST_GT_0) - alphaTest = "gt0"; - else if ((entry.loadBits[0] & GFXS0_ATEST_MASK) == GFXS0_ATEST_LT_128) - alphaTest = "lt128"; - else if ((entry.loadBits[0] & GFXS0_ATEST_MASK) == GFXS0_ATEST_GE_128) - alphaTest = "ge128"; - else - assert(entry.loadBits[0] & GFXS0_ATEST_DISABLE); - - const auto* cullFace = "none"; - if ((entry.loadBits[0] & GFXS0_CULL_MASK) == GFXS0_CULL_BACK) - cullFace = "back"; - else if ((entry.loadBits[0] & GFXS0_CULL_MASK) == GFXS0_CULL_FRONT) - cullFace = "front"; - else - assert((entry.loadBits[0] & GFXS0_CULL_MASK) == GFXS0_CULL_NONE); - - jArray.emplace_back(json{ - {"srcBlendRgb", ArrayEntry(blendNames, srcBlendRgb)}, - {"dstBlendRgb", ArrayEntry(blendNames, dstBlendRgb)}, - {"blendOpRgb", ArrayEntry(blendOpNames, blendOpRgb)}, - {"alphaTest", alphaTest}, - {"cullFace", cullFace}, - {"srcBlendAlpha", ArrayEntry(blendNames, srcBlendAlpha)}, - {"dstBlendAlpha", ArrayEntry(blendNames, dstBlendAlpha)}, - {"blendOpAlpha", ArrayEntry(blendOpNames, blendOpAlpha)}, - {"colorWriteRgb", (entry.loadBits[0] & GFXS0_COLORWRITE_RGB) ? true : false}, - {"colorWriteAlpha", (entry.loadBits[0] & GFXS0_COLORWRITE_ALPHA) ? true : false}, - {"gammaWrite", (entry.loadBits[0] & GFXS0_GAMMAWRITE) ? true : false}, - {"polymodeLine", (entry.loadBits[0] & GFXS0_POLYMODE_LINE) ? true : false}, - - {"depthWrite", (entry.loadBits[1] & GFXS1_DEPTHWRITE) ? true : false}, - {"depthTest", (entry.loadBits[1] & GFXS1_DEPTHTEST_DISABLE) ? json("disable") : ArrayEntry(depthTestNames, depthTest)}, - {"polygonOffset", ArrayEntry(polygonOffsetNames, polygonOffset)}, - {"stencilFrontEnabled", (entry.loadBits[1] & GFXS1_STENCIL_FRONT_ENABLE) ? true : false}, - {"stencilBackEnabled", (entry.loadBits[1] & GFXS1_STENCIL_BACK_ENABLE) ? true : false}, - {"stencilFrontPass", ArrayEntry(stencilOpNames, (entry.loadBits[1] >> GFXS1_STENCIL_FRONT_PASS_SHIFT) & GFXS_STENCILOP_MASK)}, - {"stencilFrontFail", ArrayEntry(stencilOpNames, (entry.loadBits[1] >> GFXS1_STENCIL_FRONT_FAIL_SHIFT) & GFXS_STENCILOP_MASK)}, - {"stencilFrontZFail", ArrayEntry(stencilOpNames, (entry.loadBits[1] >> GFXS1_STENCIL_FRONT_ZFAIL_SHIFT) & GFXS_STENCILOP_MASK)}, - {"stencilFrontFunc", ArrayEntry(stencilFuncNames, (entry.loadBits[1] >> GFXS1_STENCIL_FRONT_FUNC_SHIFT) & GFXS_STENCILFUNC_MASK)}, - {"stencilBackPass", ArrayEntry(stencilOpNames, (entry.loadBits[1] >> GFXS1_STENCIL_BACK_PASS_SHIFT) & GFXS_STENCILOP_MASK)}, - {"stencilBackFail", ArrayEntry(stencilOpNames, (entry.loadBits[1] >> GFXS1_STENCIL_BACK_FAIL_SHIFT) & GFXS_STENCILOP_MASK)}, - {"stencilBackZFail", ArrayEntry(stencilOpNames, (entry.loadBits[1] >> GFXS1_STENCIL_BACK_ZFAIL_SHIFT) & GFXS_STENCILOP_MASK)}, - {"stencilBackFunc", ArrayEntry(stencilFuncNames, (entry.loadBits[1] >> GFXS1_STENCIL_BACK_FUNC_SHIFT) & GFXS_STENCILFUNC_MASK)}, - }); - } - } + return jArray; +} - return jArray; +json BuildStateBitsTableJson(const GfxStateBits *stateBitsTable, const size_t count) { + static const char *blendNames[]{ + "disabled", "zero", "one", "srcColor", "invSrcColor", "srcAlpha", "invSrcAlpha", "destAlpha", "invDestAlpha", "destColor", "invDestColor", + }; + static const char *blendOpNames[]{"disabled", "add", "subtract", "revSubtract", "min", "max"}; + static const char *depthTestNames[]{ + "always", + "less", + "equal", + "lessEqual", + }; + static const char *polygonOffsetNames[]{ + "0", + "1", + "2", + "shadowMap", + }; + static const char *stencilOpNames[]{"keep", "zero", "replace", "incrSat", "decrSat", "invert", "incr", "decr"}; + static const char *stencilFuncNames[]{"never", "less", "equal", "lessEqual", "greater", "notEqual", "greaterEqual", "always"}; + + auto jArray = json::array(); + + if (stateBitsTable) { + for (auto index = 0u; index < count; index++) { + const auto &entry = stateBitsTable[index]; + + const auto srcBlendRgb = (entry.loadBits[0] & GFXS0_SRCBLEND_RGB_MASK) >> GFXS0_SRCBLEND_RGB_SHIFT; + const auto dstBlendRgb = (entry.loadBits[0] & GFXS0_DSTBLEND_RGB_MASK) >> GFXS0_DSTBLEND_RGB_SHIFT; + const auto blendOpRgb = (entry.loadBits[0] & GFXS0_BLENDOP_RGB_MASK) >> GFXS0_BLENDOP_RGB_SHIFT; + const auto srcBlendAlpha = (entry.loadBits[0] & GFXS0_SRCBLEND_ALPHA_MASK) >> GFXS0_SRCBLEND_ALPHA_SHIFT; + const auto dstBlendAlpha = (entry.loadBits[0] & GFXS0_DSTBLEND_ALPHA_MASK) >> GFXS0_DSTBLEND_ALPHA_SHIFT; + const auto blendOpAlpha = (entry.loadBits[0] & GFXS0_BLENDOP_ALPHA_MASK) >> GFXS0_BLENDOP_ALPHA_SHIFT; + const auto depthTest = (entry.loadBits[1] & GFXS1_DEPTHTEST_MASK) >> GFXS1_DEPTHTEST_SHIFT; + const auto polygonOffset = (entry.loadBits[1] & GFXS1_POLYGON_OFFSET_MASK) >> GFXS1_POLYGON_OFFSET_SHIFT; + + const auto *alphaTest = "disable"; + if ((entry.loadBits[0] & GFXS0_ATEST_MASK) == GFXS0_ATEST_GT_0) + alphaTest = "gt0"; + else if ((entry.loadBits[0] & GFXS0_ATEST_MASK) == GFXS0_ATEST_LT_128) + alphaTest = "lt128"; + else if ((entry.loadBits[0] & GFXS0_ATEST_MASK) == GFXS0_ATEST_GE_128) + alphaTest = "ge128"; + else + assert(entry.loadBits[0] & GFXS0_ATEST_DISABLE); + + const auto *cullFace = "none"; + if ((entry.loadBits[0] & GFXS0_CULL_MASK) == GFXS0_CULL_BACK) + cullFace = "back"; + else if ((entry.loadBits[0] & GFXS0_CULL_MASK) == GFXS0_CULL_FRONT) + cullFace = "front"; + else + assert((entry.loadBits[0] & GFXS0_CULL_MASK) == GFXS0_CULL_NONE); + + jArray.emplace_back(json{ + {"srcBlendRgb", ArrayEntry(blendNames, srcBlendRgb)}, + {"dstBlendRgb", ArrayEntry(blendNames, dstBlendRgb)}, + {"blendOpRgb", ArrayEntry(blendOpNames, blendOpRgb)}, + {"alphaTest", alphaTest}, + {"cullFace", cullFace}, + {"srcBlendAlpha", ArrayEntry(blendNames, srcBlendAlpha)}, + {"dstBlendAlpha", ArrayEntry(blendNames, dstBlendAlpha)}, + {"blendOpAlpha", ArrayEntry(blendOpNames, blendOpAlpha)}, + {"colorWriteRgb", (entry.loadBits[0] & GFXS0_COLORWRITE_RGB) ? true : false}, + {"colorWriteAlpha", (entry.loadBits[0] & GFXS0_COLORWRITE_ALPHA) ? true : false}, + {"gammaWrite", (entry.loadBits[0] & GFXS0_GAMMAWRITE) ? true : false}, + {"polymodeLine", (entry.loadBits[0] & GFXS0_POLYMODE_LINE) ? true : false}, + + {"depthWrite", (entry.loadBits[1] & GFXS1_DEPTHWRITE) ? true : false}, + {"depthTest", (entry.loadBits[1] & GFXS1_DEPTHTEST_DISABLE) ? json("disable") : ArrayEntry(depthTestNames, depthTest)}, + {"polygonOffset", ArrayEntry(polygonOffsetNames, polygonOffset)}, + {"stencilFrontEnabled", (entry.loadBits[1] & GFXS1_STENCIL_FRONT_ENABLE) ? true : false}, + {"stencilBackEnabled", (entry.loadBits[1] & GFXS1_STENCIL_BACK_ENABLE) ? true : false}, + {"stencilFrontPass", ArrayEntry(stencilOpNames, (entry.loadBits[1] >> GFXS1_STENCIL_FRONT_PASS_SHIFT) & GFXS_STENCILOP_MASK)}, + {"stencilFrontFail", ArrayEntry(stencilOpNames, (entry.loadBits[1] >> GFXS1_STENCIL_FRONT_FAIL_SHIFT) & GFXS_STENCILOP_MASK)}, + {"stencilFrontZFail", ArrayEntry(stencilOpNames, (entry.loadBits[1] >> GFXS1_STENCIL_FRONT_ZFAIL_SHIFT) & GFXS_STENCILOP_MASK)}, + {"stencilFrontFunc", ArrayEntry(stencilFuncNames, (entry.loadBits[1] >> GFXS1_STENCIL_FRONT_FUNC_SHIFT) & GFXS_STENCILFUNC_MASK)}, + {"stencilBackPass", ArrayEntry(stencilOpNames, (entry.loadBits[1] >> GFXS1_STENCIL_BACK_PASS_SHIFT) & GFXS_STENCILOP_MASK)}, + {"stencilBackFail", ArrayEntry(stencilOpNames, (entry.loadBits[1] >> GFXS1_STENCIL_BACK_FAIL_SHIFT) & GFXS_STENCILOP_MASK)}, + {"stencilBackZFail", ArrayEntry(stencilOpNames, (entry.loadBits[1] >> GFXS1_STENCIL_BACK_ZFAIL_SHIFT) & GFXS_STENCILOP_MASK)}, + {"stencilBackFunc", ArrayEntry(stencilFuncNames, (entry.loadBits[1] >> GFXS1_STENCIL_BACK_FUNC_SHIFT) & GFXS_STENCILFUNC_MASK)}, + }); } + } - json BuildCharFlagsJson(const std::string& prefix, const unsigned char gameFlags) - { - std::vector<std::string> values; - - for (auto i = 0u; i < (sizeof(gameFlags) * 8u); i++) - { - if (gameFlags & (1 << i)) - { - std::ostringstream ss; - ss << prefix << " 0x" << std::hex << (1 << i); - values.emplace_back(ss.str()); - } - } + return jArray; +} + +json BuildCharFlagsJson(const std::string &prefix, const unsigned char gameFlags) { + std::vector<std::string> values; - return json(values); + for (auto i = 0u; i < (sizeof(gameFlags) * 8u); i++) { + if (gameFlags & (1 << i)) { + std::ostringstream ss; + ss << prefix << " 0x" << std::hex << (1 << i); + values.emplace_back(ss.str()); } + } - std::string CreateSurfaceTypeString(const unsigned surfaceTypeBits) - { - if (!surfaceTypeBits) - return "<none>"; - - static constexpr auto NON_SURFACE_TYPE_BITS = ~(std::numeric_limits<unsigned>::max() >> ((sizeof(unsigned) * 8) - (static_cast<unsigned>(SURF_TYPE_NUM) - 1))); - assert((surfaceTypeBits & NON_SURFACE_TYPE_BITS) == 0); - - std::ostringstream ss; - auto firstSurfaceType = true; - for (auto surfaceTypeIndex = static_cast<unsigned>(SURF_TYPE_BARK); surfaceTypeIndex < SURF_TYPE_NUM; surfaceTypeIndex++) - { - if ((surfaceTypeBits & (1 << (surfaceTypeIndex - 1))) == 0) - continue; - - if (firstSurfaceType) - firstSurfaceType = false; - else - ss << ","; - ss << surfaceTypeNames[surfaceTypeIndex]; - } + return json(values); +} - if (firstSurfaceType) - return "<none>"; +std::string CreateSurfaceTypeString(const unsigned surfaceTypeBits) { + if (!surfaceTypeBits) + return "<none>"; - return ss.str(); - } + static constexpr auto NON_SURFACE_TYPE_BITS = + ~(std::numeric_limits<unsigned>::max() >> ((sizeof(unsigned) * 8) - (static_cast<unsigned>(SURF_TYPE_NUM) - 1))); + assert((surfaceTypeBits & NON_SURFACE_TYPE_BITS) == 0); + + std::ostringstream ss; + auto firstSurfaceType = true; + for (auto surfaceTypeIndex = static_cast<unsigned>(SURF_TYPE_BARK); surfaceTypeIndex < SURF_TYPE_NUM; surfaceTypeIndex++) { + if ((surfaceTypeBits & (1 << (surfaceTypeIndex - 1))) == 0) + continue; + + if (firstSurfaceType) + firstSurfaceType = false; + else + ss << ","; + ss << surfaceTypeNames[surfaceTypeIndex]; + } + + if (firstSurfaceType) + return "<none>"; + + return ss.str(); +} - void DumpMaterialAsJson(Material* material, std::ostream& stream) - { - static const char* cameraRegionNames[] - { - "litOpaque", - "litTrans", - "emissive", - "depthHack", - "none" - }; - - const json j = { - { - "info", { +void DumpMaterialAsJson(Material *material, std::ostream &stream) { + static const char *cameraRegionNames[]{"litOpaque", "litTrans", "emissive", "depthHack", "none"}; + + const json j = { + {"info", + { #if defined(FLAGS_DEBUG) && FLAGS_DEBUG == 1 - {"gameFlags", BuildCharFlagsJson("gameFlag", material->info.gameFlags)}, // TODO: Find out what gameflags mean + {"gameFlags", BuildCharFlagsJson("gameFlag", material->info.gameFlags)}, // TODO: Find out what gameflags mean #else - {"gameFlags", material->info.gameFlags}, // TODO: Find out what gameflags mean + {"gameFlags", material->info.gameFlags}, // TODO: Find out what gameflags mean #endif - {"sortKey", material->info.sortKey}, - {"textureAtlasRowCount", material->info.textureAtlasRowCount}, - {"textureAtlasColumnCount", material->info.textureAtlasColumnCount}, - { - "drawSurf", { - {"objectId", static_cast<unsigned>(material->info.drawSurf.fields.objectId)}, - {"reflectionProbeIndex", static_cast<unsigned>(material->info.drawSurf.fields.reflectionProbeIndex)}, - {"hasGfxEntIndex", static_cast<unsigned>(material->info.drawSurf.fields.hasGfxEntIndex)}, - {"customIndex", static_cast<unsigned>(material->info.drawSurf.fields.customIndex)}, - {"materialSortedIndex", static_cast<unsigned>(material->info.drawSurf.fields.materialSortedIndex)}, - {"prepass", static_cast<unsigned>(material->info.drawSurf.fields.prepass)}, - {"useHeroLighting", static_cast<unsigned>(material->info.drawSurf.fields.useHeroLighting)}, - {"sceneLightIndex", static_cast<unsigned>(material->info.drawSurf.fields.sceneLightIndex)}, - {"surfType", static_cast<unsigned>(material->info.drawSurf.fields.surfType)}, - {"primarySortKey", static_cast<unsigned>(material->info.drawSurf.fields.primarySortKey)} - } - }, - {"surfaceTypeBits", CreateSurfaceTypeString(material->info.surfaceTypeBits)}, - {"hashIndex", material->info.hashIndex} - } - }, - {"stateBitsEntry", std::vector(std::begin(material->stateBitsEntry), std::end(material->stateBitsEntry))}, + {"sortKey", material->info.sortKey}, + {"textureAtlasRowCount", material->info.textureAtlasRowCount}, + {"textureAtlasColumnCount", material->info.textureAtlasColumnCount}, + {"drawSurf", + {{"objectId", static_cast<unsigned>(material->info.drawSurf.fields.objectId)}, + {"reflectionProbeIndex", static_cast<unsigned>(material->info.drawSurf.fields.reflectionProbeIndex)}, + {"hasGfxEntIndex", static_cast<unsigned>(material->info.drawSurf.fields.hasGfxEntIndex)}, + {"customIndex", static_cast<unsigned>(material->info.drawSurf.fields.customIndex)}, + {"materialSortedIndex", static_cast<unsigned>(material->info.drawSurf.fields.materialSortedIndex)}, + {"prepass", static_cast<unsigned>(material->info.drawSurf.fields.prepass)}, + {"useHeroLighting", static_cast<unsigned>(material->info.drawSurf.fields.useHeroLighting)}, + {"sceneLightIndex", static_cast<unsigned>(material->info.drawSurf.fields.sceneLightIndex)}, + {"surfType", static_cast<unsigned>(material->info.drawSurf.fields.surfType)}, + {"primarySortKey", static_cast<unsigned>(material->info.drawSurf.fields.primarySortKey)}}}, + {"surfaceTypeBits", CreateSurfaceTypeString(material->info.surfaceTypeBits)}, + {"hashIndex", material->info.hashIndex}}}, + {"stateBitsEntry", std::vector(std::begin(material->stateBitsEntry), std::end(material->stateBitsEntry))}, #if defined(FLAGS_DEBUG) && FLAGS_DEBUG == 1 - {"stateFlags", BuildCharFlagsJson("stateFlag", material->stateFlags)}, + {"stateFlags", BuildCharFlagsJson("stateFlag", material->stateFlags)}, #else - {"stateFlags", material->stateFlags}, + {"stateFlags", material->stateFlags}, #endif - {"cameraRegion", ArrayEntry(cameraRegionNames, material->cameraRegion)}, - {"techniqueSet", material->techniqueSet && material->techniqueSet->name ? AssetName(material->techniqueSet->name) : json{}}, - {"textureTable", BuildTextureTableJson(material->textureTable, material->textureCount)}, - {"constantTable", BuildConstantTableJson(material->constantTable, material->constantCount)}, - {"stateBitsTable", BuildStateBitsTableJson(material->stateBitsTable, material->stateBitsCount)} - }; - - stream << std::setw(4) << j; + {"cameraRegion", ArrayEntry(cameraRegionNames, material->cameraRegion)}, + {"techniqueSet", material->techniqueSet && material->techniqueSet->name ? AssetName(material->techniqueSet->name) : json{}}, + {"textureTable", BuildTextureTableJson(material->textureTable, material->textureCount)}, + {"constantTable", BuildConstantTableJson(material->constantTable, material->constantCount)}, + {"stateBitsTable", BuildStateBitsTableJson(material->stateBitsTable, material->stateBitsCount)} + }; + + stream << std::setw(4) << j; +} + +class TechsetInfo { +public: + std::string m_techset_name; + std::string m_techset_base_name; + std::string m_techset_prefix; + GdtMaterialType m_gdt_material_type = MATERIAL_TYPE_UNKNOWN; + GdtCustomMaterialTypes m_gdt_custom_material_type = CUSTOM_MATERIAL_TYPE_NONE; + std::string m_gdt_custom_string; + MaterialType m_engine_material_type = MTL_TYPE_DEFAULT; + std::string m_sort_key_name; + bool m_no_cast_shadow = false; + bool m_no_receive_dynamic_shadow = false; + bool m_no_fog = false; + bool m_tex_scroll = false; + bool m_uv_anim = false; + bool m_has_color_map = false; + bool m_has_detail_map = false; + bool m_has_normal_map = false; + bool m_has_detail_normal_map = false; + bool m_has_specular_map = false; + bool m_zfeather = false; + bool m_use_spot_light = false; + bool m_falloff = false; + bool m_dist_falloff = false; + bool m_outdoor_only = false; + + // TODO: Find out what p0 in techset name actually means, seems like it only does stuff for techsets using a specular texture though + // TODO: Find out what o0 in techset name actually means, seems like it gives the colormap a blue/whiteish tint and is almost exclusively used on snow-related + // materials + // TODO: Find out what _lin in techset name actually means + bool m_specular_p_flag = false; + bool m_color_o_flag = false; + bool m_effect_lin_flag = false; +}; + +class StateBitsInfo { +public: + BlendFunc_e m_blend_func = BlendFunc_e::UNKNOWN; + BlendOp_e m_custom_blend_op_rgb = BlendOp_e::UNKNOWN; + BlendOp_e m_custom_blend_op_alpha = BlendOp_e::UNKNOWN; + CustomBlendFunc_e m_custom_src_blend_func = CustomBlendFunc_e::UNKNOWN; + CustomBlendFunc_e m_custom_dst_blend_func = CustomBlendFunc_e::UNKNOWN; + CustomBlendFunc_e m_custom_src_blend_func_alpha = CustomBlendFunc_e::UNKNOWN; + CustomBlendFunc_e m_custom_dst_blend_func_alpha = CustomBlendFunc_e::UNKNOWN; + AlphaTest_e m_alpha_test = AlphaTest_e::UNKNOWN; + DepthTest_e m_depth_test = DepthTest_e::UNKNOWN; + StateBitsEnabledStatus_e m_depth_write = StateBitsEnabledStatus_e::UNKNOWN; + CullFace_e m_cull_face = CullFace_e::UNKNOWN; + PolygonOffset_e m_polygon_offset = PolygonOffset_e::UNKNOWN; + StateBitsEnabledStatus_e m_color_write_rgb = StateBitsEnabledStatus_e::UNKNOWN; + StateBitsEnabledStatus_e m_color_write_alpha = StateBitsEnabledStatus_e::UNKNOWN; + StateBitsEnabledStatus_e m_gamma_write = StateBitsEnabledStatus_e::UNKNOWN; + StencilMode_e m_stencil_mode = StencilMode_e::UNKNOWN; + StencilFunc_e m_stencil_front_func = StencilFunc_e::UNKNOWN; + StencilOp_e m_stencil_front_fail = StencilOp_e::UNKNOWN; + StencilOp_e m_stencil_front_zfail = StencilOp_e::UNKNOWN; + StencilOp_e m_stencil_front_pass = StencilOp_e::UNKNOWN; + StencilFunc_e m_stencil_back_func = StencilFunc_e::UNKNOWN; + StencilOp_e m_stencil_back_fail = StencilOp_e::UNKNOWN; + StencilOp_e m_stencil_back_zfail = StencilOp_e::UNKNOWN; + StencilOp_e m_stencil_back_pass = StencilOp_e::UNKNOWN; +}; + +class ConstantsInfo { +public: + Vector4f m_color_tint = Vector4f(1.0f, 1.0f, 1.0f, 1.0f); + float m_env_map_min = 0.2f; + float m_env_map_max = 1.0f; + float m_env_map_exponent = 2.5f; + float m_zfeather_depth = 40.0f; + float m_eye_offset_depth = 0.0f; + float m_falloff_begin_angle = 35.0f; + float m_falloff_end_angle = 65.0f; + float m_dist_falloff_begin_distance = 200.0f; + float m_dist_falloff_end_distance = 10.0f; + Vector4f m_falloff_begin_color = Vector4f(1.0f, 1.0f, 1.0f, 1.0f); + Vector4f m_falloff_end_color = Vector4f(0.5f, 0.5f, 0.5f, 0.5f); + Vector2f m_detail_scale = Vector2f(8.0f, 8.0f); + Vector2f m_distortion_scale = Vector2f(0.5f, 0.5f); + Vector4f m_color_obj_min = Vector4f(0.0f, 0.0f, 0.0f, 0.0f); + Vector4f m_color_obj_max = Vector4f(1.0f, 1.0f, 1.0f, 1.0f); + Vector4f m_water_color = Vector4f(1.0f, 1.0f, 1.0f, 1.0f); + + // Speed in which the wave animation is played + float m_flag_speed = 1.0f; + // Offset of the wave animation + float m_flag_phase = 0.0f; + + float m_uv_scroll_x = 0.0f; + float m_uv_scroll_y = 0.0f; + float m_uv_rotate = 0.0f; +}; + +class MaterialGdtDumper { + TechsetInfo m_techset_info; + StateBitsInfo m_state_bits_info; + ConstantsInfo m_constants_info; + + const Material *m_material; + GdtEntry m_entry; + + void SetValue(const std::string &key, const char *value) { m_entry.m_properties.emplace(std::make_pair(key, value)); } + + void SetValue(const std::string &key, std::string value) { m_entry.m_properties.emplace(std::make_pair(key, std::move(value))); } + + void SetValue(const std::string &key, const Vector4f &v) { + std::ostringstream ss; + ss << v.x() << " " << v.y() << " " << v.z() << " " << v.w(); + m_entry.m_properties.emplace(std::make_pair(key, ss.str())); + } + + void SetValue(const std::string &key, const bool value) { m_entry.m_properties.emplace(std::make_pair(key, value ? "1" : "0")); } + + template <typename T, typename = typename std::enable_if_t<std::is_arithmetic_v<T>, T>> void SetValue(const std::string &key, T value) { + m_entry.m_properties.emplace(std::make_pair(key, std::to_string(value))); + } + + void SetCommonValues() { + SetValue("textureAtlasRowCount", m_material->info.textureAtlasRowCount); + SetValue("textureAtlasColumnCount", m_material->info.textureAtlasColumnCount); + SetValue("surfaceType", CreateSurfaceTypeString(m_material->info.surfaceTypeBits)); + } + + _NODISCARD bool MaterialCouldPossiblyUseCustomTemplate() const { + if (m_material->constantCount > 0) + return false; + + if (m_material->textureTable) { + static constexpr auto COLOR_MAP_HASH = Common::R_HashString("colorMap", 0u); + static constexpr auto DETAIL_MAP_HASH = Common::R_HashString("detailMap", 0u); + + for (auto i = 0u; i < m_material->textureCount; i++) { + const auto nameHash = m_material->textureTable[i].nameHash; + if (nameHash != COLOR_MAP_HASH && nameHash != DETAIL_MAP_HASH) + return false; + } } - class TechsetInfo - { - public: - std::string m_techset_name; - std::string m_techset_base_name; - std::string m_techset_prefix; - GdtMaterialType m_gdt_material_type = MATERIAL_TYPE_UNKNOWN; - GdtCustomMaterialTypes m_gdt_custom_material_type = CUSTOM_MATERIAL_TYPE_NONE; - std::string m_gdt_custom_string; - MaterialType m_engine_material_type = MTL_TYPE_DEFAULT; - std::string m_sort_key_name; - bool m_no_cast_shadow = false; - bool m_no_receive_dynamic_shadow = false; - bool m_no_fog = false; - bool m_tex_scroll = false; - bool m_uv_anim = false; - bool m_has_color_map = false; - bool m_has_detail_map = false; - bool m_has_normal_map = false; - bool m_has_detail_normal_map = false; - bool m_has_specular_map = false; - bool m_zfeather = false; - bool m_use_spot_light = false; - bool m_falloff = false; - bool m_dist_falloff = false; - bool m_outdoor_only = false; - - // TODO: Find out what p0 in techset name actually means, seems like it only does stuff for techsets using a specular texture though - // TODO: Find out what o0 in techset name actually means, seems like it gives the colormap a blue/whiteish tint and is almost exclusively used on snow-related materials - // TODO: Find out what _lin in techset name actually means - bool m_specular_p_flag = false; - bool m_color_o_flag = false; - bool m_effect_lin_flag = false; - }; - - class StateBitsInfo - { - public: - BlendFunc_e m_blend_func = BlendFunc_e::UNKNOWN; - BlendOp_e m_custom_blend_op_rgb = BlendOp_e::UNKNOWN; - BlendOp_e m_custom_blend_op_alpha = BlendOp_e::UNKNOWN; - CustomBlendFunc_e m_custom_src_blend_func = CustomBlendFunc_e::UNKNOWN; - CustomBlendFunc_e m_custom_dst_blend_func = CustomBlendFunc_e::UNKNOWN; - CustomBlendFunc_e m_custom_src_blend_func_alpha = CustomBlendFunc_e::UNKNOWN; - CustomBlendFunc_e m_custom_dst_blend_func_alpha = CustomBlendFunc_e::UNKNOWN; - AlphaTest_e m_alpha_test = AlphaTest_e::UNKNOWN; - DepthTest_e m_depth_test = DepthTest_e::UNKNOWN; - StateBitsEnabledStatus_e m_depth_write = StateBitsEnabledStatus_e::UNKNOWN; - CullFace_e m_cull_face = CullFace_e::UNKNOWN; - PolygonOffset_e m_polygon_offset = PolygonOffset_e::UNKNOWN; - StateBitsEnabledStatus_e m_color_write_rgb = StateBitsEnabledStatus_e::UNKNOWN; - StateBitsEnabledStatus_e m_color_write_alpha = StateBitsEnabledStatus_e::UNKNOWN; - StateBitsEnabledStatus_e m_gamma_write = StateBitsEnabledStatus_e::UNKNOWN; - StencilMode_e m_stencil_mode = StencilMode_e::UNKNOWN; - StencilFunc_e m_stencil_front_func = StencilFunc_e::UNKNOWN; - StencilOp_e m_stencil_front_fail = StencilOp_e::UNKNOWN; - StencilOp_e m_stencil_front_zfail = StencilOp_e::UNKNOWN; - StencilOp_e m_stencil_front_pass = StencilOp_e::UNKNOWN; - StencilFunc_e m_stencil_back_func = StencilFunc_e::UNKNOWN; - StencilOp_e m_stencil_back_fail = StencilOp_e::UNKNOWN; - StencilOp_e m_stencil_back_zfail = StencilOp_e::UNKNOWN; - StencilOp_e m_stencil_back_pass = StencilOp_e::UNKNOWN; - }; - - class ConstantsInfo - { - public: - Vector4f m_color_tint = Vector4f(1.0f, 1.0f, 1.0f, 1.0f); - float m_env_map_min = 0.2f; - float m_env_map_max = 1.0f; - float m_env_map_exponent = 2.5f; - float m_zfeather_depth = 40.0f; - float m_eye_offset_depth = 0.0f; - float m_falloff_begin_angle = 35.0f; - float m_falloff_end_angle = 65.0f; - float m_dist_falloff_begin_distance = 200.0f; - float m_dist_falloff_end_distance = 10.0f; - Vector4f m_falloff_begin_color = Vector4f(1.0f, 1.0f, 1.0f, 1.0f); - Vector4f m_falloff_end_color = Vector4f(0.5f, 0.5f, 0.5f, 0.5f); - Vector2f m_detail_scale = Vector2f(8.0f, 8.0f); - Vector2f m_distortion_scale = Vector2f(0.5f, 0.5f); - Vector4f m_color_obj_min = Vector4f(0.0f, 0.0f, 0.0f, 0.0f); - Vector4f m_color_obj_max = Vector4f(1.0f, 1.0f, 1.0f, 1.0f); - Vector4f m_water_color = Vector4f(1.0f, 1.0f, 1.0f, 1.0f); - - // Speed in which the wave animation is played - float m_flag_speed = 1.0f; - // Offset of the wave animation - float m_flag_phase = 0.0f; - - float m_uv_scroll_x = 0.0f; - float m_uv_scroll_y = 0.0f; - float m_uv_rotate = 0.0f; - }; - - class MaterialGdtDumper - { - TechsetInfo m_techset_info; - StateBitsInfo m_state_bits_info; - ConstantsInfo m_constants_info; - - const Material* m_material; - GdtEntry m_entry; - - void SetValue(const std::string& key, const char* value) - { - m_entry.m_properties.emplace(std::make_pair(key, value)); - } + return true; + } + + static std::vector<std::string> GetTechsetNameParts(const std::string &basename) { + std::vector<std::string> result; + + auto partStartPosition = 0u; + auto currentPosition = 0u; + for (const auto &c : basename) { + if (c == '_') { + result.emplace_back(basename, partStartPosition, currentPosition - partStartPosition); + partStartPosition = currentPosition + 1; + } + currentPosition++; + } - void SetValue(const std::string& key, std::string value) - { - m_entry.m_properties.emplace(std::make_pair(key, std::move(value))); + if (partStartPosition < basename.size()) + result.emplace_back(basename, partStartPosition); + + return result; + } + + void ExamineCommonUnlitTechsetInfo() { + const auto nameParts = GetTechsetNameParts(m_techset_info.m_techset_base_name); + bool inCustomName = false; + bool customNameStart = true; + std::ostringstream customNameStream; + + for (const auto &namePart : nameParts) { + if (inCustomName) { + if (customNameStart) + customNameStart = false; + else + customNameStream << "_"; + customNameStream << namePart; + continue; + } + + // Anything after a custom part is part of its custom name + if (namePart == "custom") { + inCustomName = true; + continue; + } + + if (namePart == "falloff") + m_techset_info.m_falloff = true; + else if (namePart == "distfalloff") + m_techset_info.m_dist_falloff = true; + else if (namePart == "zfeather") + m_techset_info.m_zfeather = true; + else if (namePart == "nofog") + m_techset_info.m_no_fog = true; + else if (namePart == "nocast") + m_techset_info.m_no_cast_shadow = true; + else if (namePart == "spot") + m_techset_info.m_use_spot_light = true; + else if (namePart == "lin") + m_techset_info.m_effect_lin_flag = true; + else if (namePart == "outdoor") + m_techset_info.m_outdoor_only = true; + else if (namePart == "ua") + m_techset_info.m_uv_anim = true; + else { + if (namePart != "add" && namePart != "replace" && namePart != "blend" && namePart != "eyeoffset" && namePart != "screen" && namePart != "effect" && + namePart != "unlit" && namePart != "multiply" && namePart != "sm") { + assert(false); } + } + } - void SetValue(const std::string& key, const Vector4f& v) - { - std::ostringstream ss; - ss << v.x() << " " << v.y() << " " << v.z() << " " << v.w(); - m_entry.m_properties.emplace(std::make_pair(key, ss.str())); + if (inCustomName) { + m_techset_info.m_gdt_custom_string = customNameStream.str(); + } + } + + void ExamineLitTechsetInfo() { + if (!m_techset_info.m_techset_prefix.empty() && m_techset_info.m_techset_prefix[0] == 'm') + m_techset_info.m_gdt_material_type = MATERIAL_TYPE_MODEL_PHONG; + else + m_techset_info.m_gdt_material_type = MATERIAL_TYPE_WORLD_PHONG; + + const auto nameParts = GetTechsetNameParts(m_techset_info.m_techset_base_name); + bool inCustomName = false; + bool customNameStart = true; + std::ostringstream customNameStream; + + m_techset_info.m_no_receive_dynamic_shadow = true; + for (const auto &namePart : nameParts) { + if (namePart == "l") + continue; + + if (inCustomName) { + if (customNameStart) + customNameStart = false; + else + customNameStream << "_"; + customNameStream << namePart; + continue; + } + + // Anything after a custom part is part of its custom name + if (namePart == "custom") { + inCustomName = true; + continue; + } + + if (namePart == "scroll") + m_techset_info.m_tex_scroll = true; + else if (namePart == "ua") + m_techset_info.m_uv_anim = true; + else if (namePart == "nocast") + m_techset_info.m_no_cast_shadow = true; + else if (namePart == "nofog") + m_techset_info.m_no_fog = true; + else if (namePart == "sm" || namePart == "hsm") + m_techset_info.m_no_receive_dynamic_shadow = false; + else if (namePart == "flag") { + m_techset_info.m_gdt_material_type = MATERIAL_TYPE_CUSTOM; + m_techset_info.m_gdt_custom_material_type = CUSTOM_MATERIAL_TYPE_PHONG_FLAG; + } else if (namePart.size() >= 2 && namePart[1] == '0') { + for (auto i = 0u; i < namePart.size(); i += 2) { + switch (namePart[i]) { + case 'r': + m_state_bits_info.m_blend_func = BlendFunc_e::REPLACE; + m_state_bits_info.m_alpha_test = AlphaTest_e::ALWAYS; + break; + case 'a': + m_state_bits_info.m_blend_func = BlendFunc_e::ADD; + break; + case 'b': + m_state_bits_info.m_blend_func = BlendFunc_e::BLEND; + break; + case 't': + m_state_bits_info.m_blend_func = BlendFunc_e::REPLACE; + m_state_bits_info.m_alpha_test = AlphaTest_e::GE128; + break; + case 'c': + m_techset_info.m_has_color_map = true; + break; + case 'd': + m_techset_info.m_has_detail_map = true; + break; + case 'n': + m_techset_info.m_has_normal_map = true; + break; + case 'q': + m_techset_info.m_has_detail_normal_map = true; + break; + case 's': + m_techset_info.m_has_specular_map = true; + break; + case 'p': + m_techset_info.m_specular_p_flag = true; + break; + case 'o': + m_techset_info.m_color_o_flag = true; + break; + default: + assert(false); + break; + } } + } else + assert(false); + } - void SetValue(const std::string& key, const bool value) - { - m_entry.m_properties.emplace(std::make_pair(key, value ? "1" : "0")); - } + if (inCustomName) { + m_techset_info.m_gdt_custom_string = customNameStream.str(); + } + } + + void ExamineUnlitTechsetInfo() { + if (!m_techset_info.m_techset_prefix.empty()) { + if (m_techset_info.m_techset_prefix[0] == 'm') + m_techset_info.m_gdt_material_type = MATERIAL_TYPE_MODEL_UNLIT; + else + m_techset_info.m_gdt_material_type = MATERIAL_TYPE_WORLD_UNLIT; + } else + m_techset_info.m_gdt_material_type = MATERIAL_TYPE_UNLIT; + + ExamineCommonUnlitTechsetInfo(); + } + + void ExamineTechsetInfo() { + if (!m_material->techniqueSet || !m_material->techniqueSet->name) + return; + + m_techset_info.m_techset_name = AssetName(m_material->techniqueSet->name); + m_techset_info.m_techset_base_name = m_techset_info.m_techset_name; + + for (auto materialType = MTL_TYPE_DEFAULT + 1; materialType < MTL_TYPE_COUNT; materialType++) { + const std::string_view techsetPrefix(g_materialTypeInfo[materialType].techniqueSetPrefix); + if (m_techset_info.m_techset_name.rfind(techsetPrefix, 0) == 0) { + m_techset_info.m_techset_base_name = m_techset_info.m_techset_name.substr(techsetPrefix.size()); + m_techset_info.m_techset_prefix = std::string(techsetPrefix); + break; + } + } - template <typename T, - typename = typename std::enable_if_t<std::is_arithmetic_v<T>, T>> - void SetValue(const std::string& key, T value) - { - m_entry.m_properties.emplace(std::make_pair(key, std::to_string(value))); - } + if (m_material->info.sortKey < SORTKEY_MAX && SortKeyNames[m_material->info.sortKey]) { + m_techset_info.m_sort_key_name = SortKeyNames[m_material->info.sortKey]; + } else { + m_techset_info.m_sort_key_name = std::to_string(m_material->info.sortKey); + } - void SetCommonValues() - { - SetValue("textureAtlasRowCount", m_material->info.textureAtlasRowCount); - SetValue("textureAtlasColumnCount", m_material->info.textureAtlasColumnCount); - SetValue("surfaceType", CreateSurfaceTypeString(m_material->info.surfaceTypeBits)); - } + if (m_techset_info.m_techset_base_name == "2d") { + m_techset_info.m_gdt_material_type = MATERIAL_TYPE_2D; + } else if (m_techset_info.m_techset_base_name == "tools") { + m_techset_info.m_gdt_material_type = MATERIAL_TYPE_TOOLS; + } else if (m_techset_info.m_techset_base_name == "objective") { + m_techset_info.m_gdt_material_type = MATERIAL_TYPE_OBJECTIVE; + } else if (m_techset_info.m_techset_base_name == "sky") { + m_techset_info.m_gdt_material_type = MATERIAL_TYPE_SKY; + } else if (m_techset_info.m_techset_base_name == "water") { + m_techset_info.m_gdt_material_type = MATERIAL_TYPE_WATER; + } else if (m_techset_info.m_techset_base_name.rfind("ambient_", 0) == 0) { + m_techset_info.m_gdt_material_type = MATERIAL_TYPE_MODEL_AMBIENT; + } else if (m_techset_info.m_techset_base_name.rfind("distortion_", 0) == 0) { + m_techset_info.m_gdt_material_type = MATERIAL_TYPE_DISTORTION; + } else if (m_techset_info.m_techset_base_name.rfind("particle_cloud", 0) == 0) { + m_techset_info.m_gdt_material_type = MATERIAL_TYPE_PARTICLE_CLOUD; + } else if (m_techset_info.m_techset_base_name == "grain_overlay") { + m_techset_info.m_gdt_material_type = MATERIAL_TYPE_CUSTOM; + m_techset_info.m_gdt_custom_material_type = CUSTOM_MATERIAL_TYPE_GRAIN_OVERLAY; + } else if (m_techset_info.m_techset_base_name == "effect_add_eyeoffset") { + m_techset_info.m_gdt_material_type = MATERIAL_TYPE_CUSTOM; + m_techset_info.m_gdt_custom_material_type = CUSTOM_MATERIAL_TYPE_EFFECT_EYE_OFFSET; + } else if (m_techset_info.m_techset_base_name == "reflexsight") { + m_techset_info.m_gdt_material_type = MATERIAL_TYPE_CUSTOM; + m_techset_info.m_gdt_custom_material_type = CUSTOM_MATERIAL_TYPE_REFLEX_SIGHT; + } else if (m_techset_info.m_techset_base_name == "shadowclear") { + m_techset_info.m_gdt_material_type = MATERIAL_TYPE_CUSTOM; + m_techset_info.m_gdt_custom_material_type = CUSTOM_MATERIAL_TYPE_SHADOW_CLEAR; + } else if (m_techset_info.m_techset_base_name == "shadowoverlay") { + m_techset_info.m_gdt_material_type = MATERIAL_TYPE_CUSTOM; + m_techset_info.m_gdt_custom_material_type = CUSTOM_MATERIAL_TYPE_SHADOW_OVERLAY; + } else if (m_techset_info.m_techset_base_name.rfind("splatter", 0) == 0) { + m_techset_info.m_gdt_material_type = MATERIAL_TYPE_CUSTOM; + m_techset_info.m_gdt_custom_material_type = CUSTOM_MATERIAL_TYPE_SPLATTER; + } else if (m_techset_info.m_techset_base_name.rfind("effect", 0) == 0) { + m_techset_info.m_gdt_material_type = MATERIAL_TYPE_EFFECT; + ExamineCommonUnlitTechsetInfo(); + } else if (m_techset_info.m_techset_base_name.rfind("l_", 0) == 0) { + ExamineLitTechsetInfo(); + } else if (m_techset_info.m_techset_base_name.rfind("unlit", 0) == 0) { + m_techset_info.m_gdt_material_type = MATERIAL_TYPE_UNLIT; + ExamineUnlitTechsetInfo(); + } else if (MaterialCouldPossiblyUseCustomTemplate()) { + m_techset_info.m_gdt_material_type = MATERIAL_TYPE_CUSTOM; + m_techset_info.m_gdt_custom_material_type = CUSTOM_MATERIAL_TYPE_CUSTOM; + m_techset_info.m_gdt_custom_string = m_techset_info.m_techset_base_name; + } else { + std::cout << "Could not determine material type for material \"" << m_material->info.name << "\"\n"; + } + } + + struct BlendFuncParameters { + BlendFunc_e m_blend_func; + BlendOp_e m_blend_op_rgb; + CustomBlendFunc_e m_src_blend_func; + CustomBlendFunc_e m_dst_blend_func; + BlendOp_e m_blend_op_alpha; + CustomBlendFunc_e m_src_blend_func_alpha; + CustomBlendFunc_e m_dst_blend_func_alpha; + }; + + static inline BlendFuncParameters knownBlendFuncs[]{ + // Only considering passthrough statemap + {BlendFunc_e::ADD, BlendOp_e::ADD, CustomBlendFunc_e::ONE, CustomBlendFunc_e::ONE, BlendOp_e::DISABLE, CustomBlendFunc_e::UNKNOWN, + CustomBlendFunc_e::UNKNOWN}, + {BlendFunc_e::BLEND, BlendOp_e::ADD, CustomBlendFunc_e::SRC_ALPHA, CustomBlendFunc_e::INV_SRC_ALPHA, BlendOp_e::DISABLE, CustomBlendFunc_e::UNKNOWN, + CustomBlendFunc_e::UNKNOWN}, + {BlendFunc_e::MULTIPLY, BlendOp_e::ADD, CustomBlendFunc_e::ZERO, CustomBlendFunc_e::SRC_COLOR, BlendOp_e::DISABLE, CustomBlendFunc_e::UNKNOWN, + CustomBlendFunc_e::UNKNOWN}, + {BlendFunc_e::REPLACE, BlendOp_e::DISABLE, CustomBlendFunc_e::UNKNOWN, CustomBlendFunc_e::UNKNOWN, BlendOp_e::DISABLE, CustomBlendFunc_e::UNKNOWN, + CustomBlendFunc_e::UNKNOWN}, + {BlendFunc_e::SCREEN_ADD, BlendOp_e::ADD, CustomBlendFunc_e::INV_DST_COLOR, CustomBlendFunc_e::ONE, BlendOp_e::DISABLE, CustomBlendFunc_e::UNKNOWN, + CustomBlendFunc_e::UNKNOWN}, + + // TODO: Enable when using statemaps + // Considering default statemap + {BlendFunc_e::ADD, BlendOp_e::ADD, CustomBlendFunc_e::ONE, CustomBlendFunc_e::ONE, BlendOp_e::ADD, CustomBlendFunc_e::INV_DST_ALPHA, + CustomBlendFunc_e::ONE }, + {BlendFunc_e::BLEND, BlendOp_e::ADD, CustomBlendFunc_e::SRC_ALPHA, CustomBlendFunc_e::INV_SRC_ALPHA, BlendOp_e::ADD, CustomBlendFunc_e::INV_DST_ALPHA, + CustomBlendFunc_e::ONE }, + {BlendFunc_e::MULTIPLY, BlendOp_e::ADD, CustomBlendFunc_e::ZERO, CustomBlendFunc_e::SRC_COLOR, BlendOp_e::ADD, CustomBlendFunc_e::INV_DST_ALPHA, + CustomBlendFunc_e::ONE }, + // REPLACE matches passthrough statemap + {BlendFunc_e::SCREEN_ADD, BlendOp_e::ADD, CustomBlendFunc_e::INV_DST_COLOR, CustomBlendFunc_e::ONE, BlendOp_e::ADD, CustomBlendFunc_e::INV_DST_ALPHA, + CustomBlendFunc_e::ONE }, + }; + + template <typename T> bool KnownBlendFuncParameterMatches(const T materialValue, const T blendFuncValue) { + if (blendFuncValue == T::UNKNOWN) + return true; + if (materialValue == T::UNKNOWN) + return false; + + return static_cast<unsigned>(materialValue) == static_cast<unsigned>(blendFuncValue); + } + + void ExamineBlendFunc() { + if (m_state_bits_info.m_blend_func != BlendFunc_e::UNKNOWN) + return; + + for (const auto &knownBlendFunc : knownBlendFuncs) { + if (KnownBlendFuncParameterMatches(m_state_bits_info.m_custom_blend_op_rgb, knownBlendFunc.m_blend_op_rgb) && + KnownBlendFuncParameterMatches(m_state_bits_info.m_custom_src_blend_func, knownBlendFunc.m_src_blend_func) && + KnownBlendFuncParameterMatches(m_state_bits_info.m_custom_dst_blend_func, knownBlendFunc.m_dst_blend_func) && + KnownBlendFuncParameterMatches(m_state_bits_info.m_custom_blend_op_alpha, knownBlendFunc.m_blend_op_alpha) && + KnownBlendFuncParameterMatches(m_state_bits_info.m_custom_src_blend_func_alpha, knownBlendFunc.m_src_blend_func_alpha) && + KnownBlendFuncParameterMatches(m_state_bits_info.m_custom_dst_blend_func_alpha, knownBlendFunc.m_dst_blend_func_alpha)) { + m_state_bits_info.m_blend_func = knownBlendFunc.m_blend_func; + return; + } + } - _NODISCARD bool MaterialCouldPossiblyUseCustomTemplate() const - { - if (m_material->constantCount > 0) - return false; - - if (m_material->textureTable) - { - static constexpr auto COLOR_MAP_HASH = Common::R_HashString("colorMap", 0u); - static constexpr auto DETAIL_MAP_HASH = Common::R_HashString("detailMap", 0u); - - for (auto i = 0u; i < m_material->textureCount; i++) - { - const auto nameHash = m_material->textureTable[i].nameHash; - if (nameHash != COLOR_MAP_HASH && nameHash != DETAIL_MAP_HASH) - return false; - } - } - - return true; - } + m_state_bits_info.m_blend_func = BlendFunc_e::CUSTOM; + } + + template <typename T> T StateBitsToEnum(const unsigned input, const size_t mask, const size_t shift) { + const unsigned value = (input & mask) >> shift; + return value >= (static_cast<unsigned>(T::COUNT) - 1) ? T::UNKNOWN : static_cast<T>(value + 1); + } + + void ExamineStateBitsInfo() { + if (!m_material->stateBitsTable || m_material->stateBitsCount == 0) + return; + + // This assumes the statemap of these techniques is passthrough which it is most likely not + // This should still not produce any wrong values + GfxStateBits stateBits{}; + if (m_material->stateBitsEntry[TECHNIQUE_LIT] < m_material->stateBitsCount) + stateBits = m_material->stateBitsTable[m_material->stateBitsEntry[TECHNIQUE_LIT]]; + else if (m_material->stateBitsEntry[TECHNIQUE_EMISSIVE] < m_material->stateBitsCount) + stateBits = m_material->stateBitsTable[m_material->stateBitsEntry[TECHNIQUE_EMISSIVE]]; + else if (m_material->stateBitsEntry[TECHNIQUE_UNLIT] < m_material->stateBitsCount) + stateBits = m_material->stateBitsTable[m_material->stateBitsEntry[TECHNIQUE_UNLIT]]; + else if (m_material->stateBitsEntry[TECHNIQUE_DEPTH_PREPASS] < m_material->stateBitsCount) + stateBits = m_material->stateBitsTable[m_material->stateBitsEntry[TECHNIQUE_DEPTH_PREPASS]]; + else { + assert(false); + return; + } - static std::vector<std::string> GetTechsetNameParts(const std::string& basename) - { - std::vector<std::string> result; - - auto partStartPosition = 0u; - auto currentPosition = 0u; - for (const auto& c : basename) - { - if (c == '_') - { - result.emplace_back(basename, partStartPosition, currentPosition - partStartPosition); - partStartPosition = currentPosition + 1; - } - currentPosition++; - } - - if (partStartPosition < basename.size()) - result.emplace_back(basename, partStartPosition); - - return result; - } + if (m_state_bits_info.m_custom_blend_op_rgb == BlendOp_e::UNKNOWN) + m_state_bits_info.m_custom_blend_op_rgb = StateBitsToEnum<BlendOp_e>(stateBits.loadBits[0], GFXS0_BLENDOP_RGB_MASK, GFXS0_BLENDOP_RGB_SHIFT); + + if (m_state_bits_info.m_custom_blend_op_alpha == BlendOp_e::UNKNOWN) + m_state_bits_info.m_custom_blend_op_alpha = StateBitsToEnum<BlendOp_e>(stateBits.loadBits[0], GFXS0_BLENDOP_ALPHA_MASK, GFXS0_BLENDOP_ALPHA_SHIFT); + + if (m_state_bits_info.m_custom_src_blend_func == CustomBlendFunc_e::UNKNOWN) + m_state_bits_info.m_custom_src_blend_func = StateBitsToEnum<CustomBlendFunc_e>(stateBits.loadBits[0], GFXS0_SRCBLEND_RGB_MASK, GFXS0_SRCBLEND_RGB_SHIFT); + + if (m_state_bits_info.m_custom_dst_blend_func == CustomBlendFunc_e::UNKNOWN) + m_state_bits_info.m_custom_dst_blend_func = StateBitsToEnum<CustomBlendFunc_e>(stateBits.loadBits[0], GFXS0_DSTBLEND_RGB_MASK, GFXS0_DSTBLEND_RGB_SHIFT); + + if (m_state_bits_info.m_custom_src_blend_func_alpha == CustomBlendFunc_e::UNKNOWN) + m_state_bits_info.m_custom_src_blend_func_alpha = + StateBitsToEnum<CustomBlendFunc_e>(stateBits.loadBits[0], GFXS0_SRCBLEND_ALPHA_MASK, GFXS0_SRCBLEND_ALPHA_SHIFT); + + if (m_state_bits_info.m_custom_dst_blend_func_alpha == CustomBlendFunc_e::UNKNOWN) + m_state_bits_info.m_custom_dst_blend_func_alpha = + StateBitsToEnum<CustomBlendFunc_e>(stateBits.loadBits[0], GFXS0_DSTBLEND_ALPHA_MASK, GFXS0_DSTBLEND_ALPHA_SHIFT); + + if (m_state_bits_info.m_alpha_test == AlphaTest_e::UNKNOWN) { + if (stateBits.loadBits[0] & GFXS0_ATEST_DISABLE) + m_state_bits_info.m_alpha_test = AlphaTest_e::ALWAYS; + else if ((stateBits.loadBits[0] & GFXS0_ATEST_MASK) == GFXS0_ATEST_GE_128) + m_state_bits_info.m_alpha_test = AlphaTest_e::GE128; + else if ((stateBits.loadBits[0] & GFXS0_ATEST_MASK) == GFXS0_ATEST_GT_0) + m_state_bits_info.m_alpha_test = AlphaTest_e::GT0; + else if ((stateBits.loadBits[0] & GFXS0_ATEST_MASK) == GFXS0_ATEST_LT_128) + m_state_bits_info.m_alpha_test = AlphaTest_e::LT128; + else + assert(false); + } - void ExamineCommonUnlitTechsetInfo() - { - const auto nameParts = GetTechsetNameParts(m_techset_info.m_techset_base_name); - bool inCustomName = false; - bool customNameStart = true; - std::ostringstream customNameStream; - - for (const auto& namePart : nameParts) - { - if (inCustomName) - { - if (customNameStart) - customNameStart = false; - else - customNameStream << "_"; - customNameStream << namePart; - continue; - } - - // Anything after a custom part is part of its custom name - if (namePart == "custom") - { - inCustomName = true; - continue; - } - - if (namePart == "falloff") - m_techset_info.m_falloff = true; - else if (namePart == "distfalloff") - m_techset_info.m_dist_falloff = true; - else if (namePart == "zfeather") - m_techset_info.m_zfeather = true; - else if (namePart == "nofog") - m_techset_info.m_no_fog = true; - else if (namePart == "nocast") - m_techset_info.m_no_cast_shadow = true; - else if (namePart == "spot") - m_techset_info.m_use_spot_light = true; - else if (namePart == "lin") - m_techset_info.m_effect_lin_flag = true; - else if (namePart == "outdoor") - m_techset_info.m_outdoor_only = true; - else if (namePart == "ua") - m_techset_info.m_uv_anim = true; - else - { - if (namePart != "add" && namePart != "replace" && namePart != "blend" && namePart != "eyeoffset" && namePart != "screen" && namePart != "effect" && namePart != "unlit" - && namePart != "multiply" && namePart != "sm") - { - assert(false); - } - } - } - - if (inCustomName) - { - m_techset_info.m_gdt_custom_string = customNameStream.str(); - } - } + if (m_state_bits_info.m_depth_test == DepthTest_e::UNKNOWN) { + if (stateBits.loadBits[1] & GFXS1_DEPTHTEST_DISABLE) + m_state_bits_info.m_depth_test = DepthTest_e::DISABLE; + else if (stateBits.loadBits[1] & GFXS1_DEPTHTEST_LESSEQUAL) + m_state_bits_info.m_depth_test = DepthTest_e::LESS_EQUAL; + else if (stateBits.loadBits[1] & GFXS1_DEPTHTEST_LESS) + m_state_bits_info.m_depth_test = DepthTest_e::LESS; + else if (stateBits.loadBits[1] & GFXS1_DEPTHTEST_EQUAL) + m_state_bits_info.m_depth_test = DepthTest_e::EQUAL; + else + m_state_bits_info.m_depth_test = DepthTest_e::ALWAYS; + } - void ExamineLitTechsetInfo() - { - if (!m_techset_info.m_techset_prefix.empty() && m_techset_info.m_techset_prefix[0] == 'm') - m_techset_info.m_gdt_material_type = MATERIAL_TYPE_MODEL_PHONG; - else - m_techset_info.m_gdt_material_type = MATERIAL_TYPE_WORLD_PHONG; - - const auto nameParts = GetTechsetNameParts(m_techset_info.m_techset_base_name); - bool inCustomName = false; - bool customNameStart = true; - std::ostringstream customNameStream; - - m_techset_info.m_no_receive_dynamic_shadow = true; - for (const auto& namePart : nameParts) - { - if (namePart == "l") - continue; - - if (inCustomName) - { - if (customNameStart) - customNameStart = false; - else - customNameStream << "_"; - customNameStream << namePart; - continue; - } - - // Anything after a custom part is part of its custom name - if (namePart == "custom") - { - inCustomName = true; - continue; - } - - if (namePart == "scroll") - m_techset_info.m_tex_scroll = true; - else if (namePart == "ua") - m_techset_info.m_uv_anim = true; - else if (namePart == "nocast") - m_techset_info.m_no_cast_shadow = true; - else if (namePart == "nofog") - m_techset_info.m_no_fog = true; - else if (namePart == "sm" || namePart == "hsm") - m_techset_info.m_no_receive_dynamic_shadow = false; - else if (namePart == "flag") - { - m_techset_info.m_gdt_material_type = MATERIAL_TYPE_CUSTOM; - m_techset_info.m_gdt_custom_material_type = CUSTOM_MATERIAL_TYPE_PHONG_FLAG; - } - else if (namePart.size() >= 2 && namePart[1] == '0') - { - for (auto i = 0u; i < namePart.size(); i += 2) - { - switch (namePart[i]) - { - case 'r': - m_state_bits_info.m_blend_func = BlendFunc_e::REPLACE; - m_state_bits_info.m_alpha_test = AlphaTest_e::ALWAYS; - break; - case 'a': - m_state_bits_info.m_blend_func = BlendFunc_e::ADD; - break; - case 'b': - m_state_bits_info.m_blend_func = BlendFunc_e::BLEND; - break; - case 't': - m_state_bits_info.m_blend_func = BlendFunc_e::REPLACE; - m_state_bits_info.m_alpha_test = AlphaTest_e::GE128; - break; - case 'c': - m_techset_info.m_has_color_map = true; - break; - case 'd': - m_techset_info.m_has_detail_map = true; - break; - case 'n': - m_techset_info.m_has_normal_map = true; - break; - case 'q': - m_techset_info.m_has_detail_normal_map = true; - break; - case 's': - m_techset_info.m_has_specular_map = true; - break; - case 'p': - m_techset_info.m_specular_p_flag = true; - break; - case 'o': - m_techset_info.m_color_o_flag = true; - break; - default: - assert(false); - break; - } - } - } - else - assert(false); - } - - if (inCustomName) - { - m_techset_info.m_gdt_custom_string = customNameStream.str(); - } - } + if (m_state_bits_info.m_depth_write == StateBitsEnabledStatus_e::UNKNOWN) + m_state_bits_info.m_depth_write = (stateBits.loadBits[1] & GFXS1_DEPTHWRITE) ? StateBitsEnabledStatus_e::ENABLED : StateBitsEnabledStatus_e::DISABLED; + + if (m_state_bits_info.m_cull_face == CullFace_e::UNKNOWN) { + if (stateBits.loadBits[0] & GFXS0_CULL_NONE) + m_state_bits_info.m_cull_face = CullFace_e::NONE; + else if (stateBits.loadBits[0] & GFXS0_CULL_BACK) + m_state_bits_info.m_cull_face = CullFace_e::BACK; + else if (stateBits.loadBits[0] & GFXS0_CULL_FRONT) + m_state_bits_info.m_cull_face = CullFace_e::FRONT; + else + assert(false); + } - void ExamineUnlitTechsetInfo() - { - if (!m_techset_info.m_techset_prefix.empty()) - { - if (m_techset_info.m_techset_prefix[0] == 'm') - m_techset_info.m_gdt_material_type = MATERIAL_TYPE_MODEL_UNLIT; - else - m_techset_info.m_gdt_material_type = MATERIAL_TYPE_WORLD_UNLIT; - } - else - m_techset_info.m_gdt_material_type = MATERIAL_TYPE_UNLIT; - - ExamineCommonUnlitTechsetInfo(); - } + if (m_state_bits_info.m_polygon_offset == PolygonOffset_e::UNKNOWN) + m_state_bits_info.m_polygon_offset = StateBitsToEnum<PolygonOffset_e>(stateBits.loadBits[1], GFXS1_POLYGON_OFFSET_MASK, GFXS1_POLYGON_OFFSET_SHIFT); + + if (m_state_bits_info.m_color_write_rgb == StateBitsEnabledStatus_e::UNKNOWN) + m_state_bits_info.m_color_write_rgb = + (stateBits.loadBits[0] & GFXS0_COLORWRITE_RGB) ? StateBitsEnabledStatus_e::ENABLED : StateBitsEnabledStatus_e::DISABLED; + + if (m_state_bits_info.m_color_write_alpha == StateBitsEnabledStatus_e::UNKNOWN) + m_state_bits_info.m_color_write_alpha = + (stateBits.loadBits[0] & GFXS0_COLORWRITE_ALPHA) ? StateBitsEnabledStatus_e::ENABLED : StateBitsEnabledStatus_e::DISABLED; + + if (m_state_bits_info.m_gamma_write == StateBitsEnabledStatus_e::UNKNOWN) + m_state_bits_info.m_gamma_write = (stateBits.loadBits[0] & GFXS0_GAMMAWRITE) ? StateBitsEnabledStatus_e::ENABLED : StateBitsEnabledStatus_e::DISABLED; + + if (m_state_bits_info.m_stencil_mode == StencilMode_e::UNKNOWN) { + if ((stateBits.loadBits[1] & GFXS1_STENCIL_BACK_ENABLE) == 0 && (stateBits.loadBits[1] & GFXS1_STENCIL_FRONT_ENABLE) == 0) { + m_state_bits_info.m_stencil_mode = StencilMode_e::DISABLED; + } else if (stateBits.loadBits[1] & GFXS1_STENCIL_BACK_ENABLE) { + assert(stateBits.loadBits[1] & GFXS1_STENCIL_FRONT_ENABLE); + m_state_bits_info.m_stencil_mode = StencilMode_e::TWO_SIDED; + } else { + assert(stateBits.loadBits[1] & GFXS1_STENCIL_FRONT_ENABLE); + m_state_bits_info.m_stencil_mode = StencilMode_e::ONE_SIDED; + } + } - void ExamineTechsetInfo() - { - if (!m_material->techniqueSet || !m_material->techniqueSet->name) - return; - - m_techset_info.m_techset_name = AssetName(m_material->techniqueSet->name); - m_techset_info.m_techset_base_name = m_techset_info.m_techset_name; - - for (auto materialType = MTL_TYPE_DEFAULT + 1; materialType < MTL_TYPE_COUNT; materialType++) - { - const std::string_view techsetPrefix(g_materialTypeInfo[materialType].techniqueSetPrefix); - if (m_techset_info.m_techset_name.rfind(techsetPrefix, 0) == 0) - { - m_techset_info.m_techset_base_name = m_techset_info.m_techset_name.substr(techsetPrefix.size()); - m_techset_info.m_techset_prefix = std::string(techsetPrefix); - break; - } - } - - if (m_material->info.sortKey < SORTKEY_MAX && SortKeyNames[m_material->info.sortKey]) - { - m_techset_info.m_sort_key_name = SortKeyNames[m_material->info.sortKey]; - } - else - { - m_techset_info.m_sort_key_name = std::to_string(m_material->info.sortKey); - } - - if (m_techset_info.m_techset_base_name == "2d") - { - m_techset_info.m_gdt_material_type = MATERIAL_TYPE_2D; - } - else if (m_techset_info.m_techset_base_name == "tools") - { - m_techset_info.m_gdt_material_type = MATERIAL_TYPE_TOOLS; - } - else if (m_techset_info.m_techset_base_name == "objective") - { - m_techset_info.m_gdt_material_type = MATERIAL_TYPE_OBJECTIVE; - } - else if (m_techset_info.m_techset_base_name == "sky") - { - m_techset_info.m_gdt_material_type = MATERIAL_TYPE_SKY; - } - else if (m_techset_info.m_techset_base_name == "water") - { - m_techset_info.m_gdt_material_type = MATERIAL_TYPE_WATER; - } - else if (m_techset_info.m_techset_base_name.rfind("ambient_", 0) == 0) - { - m_techset_info.m_gdt_material_type = MATERIAL_TYPE_MODEL_AMBIENT; - } - else if (m_techset_info.m_techset_base_name.rfind("distortion_", 0) == 0) - { - m_techset_info.m_gdt_material_type = MATERIAL_TYPE_DISTORTION; - } - else if (m_techset_info.m_techset_base_name.rfind("particle_cloud", 0) == 0) - { - m_techset_info.m_gdt_material_type = MATERIAL_TYPE_PARTICLE_CLOUD; - } - else if (m_techset_info.m_techset_base_name == "grain_overlay") - { - m_techset_info.m_gdt_material_type = MATERIAL_TYPE_CUSTOM; - m_techset_info.m_gdt_custom_material_type = CUSTOM_MATERIAL_TYPE_GRAIN_OVERLAY; - } - else if (m_techset_info.m_techset_base_name == "effect_add_eyeoffset") - { - m_techset_info.m_gdt_material_type = MATERIAL_TYPE_CUSTOM; - m_techset_info.m_gdt_custom_material_type = CUSTOM_MATERIAL_TYPE_EFFECT_EYE_OFFSET; - } - else if (m_techset_info.m_techset_base_name == "reflexsight") - { - m_techset_info.m_gdt_material_type = MATERIAL_TYPE_CUSTOM; - m_techset_info.m_gdt_custom_material_type = CUSTOM_MATERIAL_TYPE_REFLEX_SIGHT; - } - else if (m_techset_info.m_techset_base_name == "shadowclear") - { - m_techset_info.m_gdt_material_type = MATERIAL_TYPE_CUSTOM; - m_techset_info.m_gdt_custom_material_type = CUSTOM_MATERIAL_TYPE_SHADOW_CLEAR; - } - else if (m_techset_info.m_techset_base_name == "shadowoverlay") - { - m_techset_info.m_gdt_material_type = MATERIAL_TYPE_CUSTOM; - m_techset_info.m_gdt_custom_material_type = CUSTOM_MATERIAL_TYPE_SHADOW_OVERLAY; - } - else if (m_techset_info.m_techset_base_name.rfind("splatter", 0) == 0) - { - m_techset_info.m_gdt_material_type = MATERIAL_TYPE_CUSTOM; - m_techset_info.m_gdt_custom_material_type = CUSTOM_MATERIAL_TYPE_SPLATTER; - } - else if (m_techset_info.m_techset_base_name.rfind("effect", 0) == 0) - { - m_techset_info.m_gdt_material_type = MATERIAL_TYPE_EFFECT; - ExamineCommonUnlitTechsetInfo(); - } - else if (m_techset_info.m_techset_base_name.rfind("l_", 0) == 0) - { - ExamineLitTechsetInfo(); - } - else if (m_techset_info.m_techset_base_name.rfind("unlit", 0) == 0) - { - m_techset_info.m_gdt_material_type = MATERIAL_TYPE_UNLIT; - ExamineUnlitTechsetInfo(); - } - else if (MaterialCouldPossiblyUseCustomTemplate()) - { - m_techset_info.m_gdt_material_type = MATERIAL_TYPE_CUSTOM; - m_techset_info.m_gdt_custom_material_type = CUSTOM_MATERIAL_TYPE_CUSTOM; - m_techset_info.m_gdt_custom_string = m_techset_info.m_techset_base_name; - } - else - { - std::cout << "Could not determine material type for material \"" << m_material->info.name << "\"\n"; - } - } + if (m_state_bits_info.m_stencil_front_func == StencilFunc_e::UNKNOWN) + m_state_bits_info.m_stencil_front_func = + StateBitsToEnum<StencilFunc_e>(stateBits.loadBits[1], GFXS1_STENCIL_FRONT_FUNC_MASK, GFXS1_STENCIL_FRONT_FUNC_SHIFT); - struct BlendFuncParameters - { - BlendFunc_e m_blend_func; - BlendOp_e m_blend_op_rgb; - CustomBlendFunc_e m_src_blend_func; - CustomBlendFunc_e m_dst_blend_func; - BlendOp_e m_blend_op_alpha; - CustomBlendFunc_e m_src_blend_func_alpha; - CustomBlendFunc_e m_dst_blend_func_alpha; - }; - - static inline BlendFuncParameters knownBlendFuncs[] - { - // Only considering passthrough statemap - {BlendFunc_e::ADD, BlendOp_e::ADD, CustomBlendFunc_e::ONE, CustomBlendFunc_e::ONE, BlendOp_e::DISABLE, CustomBlendFunc_e::UNKNOWN, CustomBlendFunc_e::UNKNOWN}, - {BlendFunc_e::BLEND, BlendOp_e::ADD, CustomBlendFunc_e::SRC_ALPHA, CustomBlendFunc_e::INV_SRC_ALPHA, BlendOp_e::DISABLE, CustomBlendFunc_e::UNKNOWN, CustomBlendFunc_e::UNKNOWN}, - {BlendFunc_e::MULTIPLY, BlendOp_e::ADD, CustomBlendFunc_e::ZERO, CustomBlendFunc_e::SRC_COLOR, BlendOp_e::DISABLE, CustomBlendFunc_e::UNKNOWN, CustomBlendFunc_e::UNKNOWN}, - {BlendFunc_e::REPLACE, BlendOp_e::DISABLE, CustomBlendFunc_e::UNKNOWN, CustomBlendFunc_e::UNKNOWN, BlendOp_e::DISABLE, CustomBlendFunc_e::UNKNOWN, CustomBlendFunc_e::UNKNOWN}, - {BlendFunc_e::SCREEN_ADD, BlendOp_e::ADD, CustomBlendFunc_e::INV_DST_COLOR, CustomBlendFunc_e::ONE, BlendOp_e::DISABLE, CustomBlendFunc_e::UNKNOWN, CustomBlendFunc_e::UNKNOWN}, - - // TODO: Enable when using statemaps - // Considering default statemap - {BlendFunc_e::ADD, BlendOp_e::ADD, CustomBlendFunc_e::ONE, CustomBlendFunc_e::ONE, BlendOp_e::ADD, CustomBlendFunc_e::INV_DST_ALPHA, CustomBlendFunc_e::ONE}, - {BlendFunc_e::BLEND, BlendOp_e::ADD, CustomBlendFunc_e::SRC_ALPHA, CustomBlendFunc_e::INV_SRC_ALPHA, BlendOp_e::ADD, CustomBlendFunc_e::INV_DST_ALPHA, CustomBlendFunc_e::ONE}, - {BlendFunc_e::MULTIPLY, BlendOp_e::ADD, CustomBlendFunc_e::ZERO, CustomBlendFunc_e::SRC_COLOR, BlendOp_e::ADD, CustomBlendFunc_e::INV_DST_ALPHA, CustomBlendFunc_e::ONE}, - // REPLACE matches passthrough statemap - {BlendFunc_e::SCREEN_ADD, BlendOp_e::ADD, CustomBlendFunc_e::INV_DST_COLOR, CustomBlendFunc_e::ONE, BlendOp_e::ADD, CustomBlendFunc_e::INV_DST_ALPHA, CustomBlendFunc_e::ONE}, - }; - - template <typename T> - bool KnownBlendFuncParameterMatches(const T materialValue, const T blendFuncValue) - { - if (blendFuncValue == T::UNKNOWN) - return true; - if (materialValue == T::UNKNOWN) - return false; - - return static_cast<unsigned>(materialValue) == static_cast<unsigned>(blendFuncValue); - } + if (m_state_bits_info.m_stencil_front_pass == StencilOp_e::UNKNOWN) + m_state_bits_info.m_stencil_front_pass = + StateBitsToEnum<StencilOp_e>(stateBits.loadBits[1], GFXS1_STENCIL_FRONT_PASS_MASK, GFXS1_STENCIL_FRONT_PASS_SHIFT); - void ExamineBlendFunc() - { - if (m_state_bits_info.m_blend_func != BlendFunc_e::UNKNOWN) - return; - - for (const auto& knownBlendFunc : knownBlendFuncs) - { - if (KnownBlendFuncParameterMatches(m_state_bits_info.m_custom_blend_op_rgb, knownBlendFunc.m_blend_op_rgb) - && KnownBlendFuncParameterMatches(m_state_bits_info.m_custom_src_blend_func, knownBlendFunc.m_src_blend_func) - && KnownBlendFuncParameterMatches(m_state_bits_info.m_custom_dst_blend_func, knownBlendFunc.m_dst_blend_func) - && KnownBlendFuncParameterMatches(m_state_bits_info.m_custom_blend_op_alpha, knownBlendFunc.m_blend_op_alpha) - && KnownBlendFuncParameterMatches(m_state_bits_info.m_custom_src_blend_func_alpha, knownBlendFunc.m_src_blend_func_alpha) - && KnownBlendFuncParameterMatches(m_state_bits_info.m_custom_dst_blend_func_alpha, knownBlendFunc.m_dst_blend_func_alpha) - ) - { - m_state_bits_info.m_blend_func = knownBlendFunc.m_blend_func; - return; - } - } - - m_state_bits_info.m_blend_func = BlendFunc_e::CUSTOM; - } + if (m_state_bits_info.m_stencil_front_fail == StencilOp_e::UNKNOWN) + m_state_bits_info.m_stencil_front_fail = + StateBitsToEnum<StencilOp_e>(stateBits.loadBits[1], GFXS1_STENCIL_FRONT_FAIL_MASK, GFXS1_STENCIL_FRONT_FAIL_SHIFT); - template <typename T> - T StateBitsToEnum(const unsigned input, const size_t mask, const size_t shift) - { - const unsigned value = (input & mask) >> shift; - return value >= (static_cast<unsigned>(T::COUNT) - 1) ? T::UNKNOWN : static_cast<T>(value + 1); - } + if (m_state_bits_info.m_stencil_front_zfail == StencilOp_e::UNKNOWN) + m_state_bits_info.m_stencil_front_zfail = + StateBitsToEnum<StencilOp_e>(stateBits.loadBits[1], GFXS1_STENCIL_FRONT_ZFAIL_MASK, GFXS1_STENCIL_FRONT_ZFAIL_SHIFT); - void ExamineStateBitsInfo() - { - if (!m_material->stateBitsTable || m_material->stateBitsCount == 0) - return; - - // This assumes the statemap of these techniques is passthrough which it is most likely not - // This should still not produce any wrong values - GfxStateBits stateBits{}; - if (m_material->stateBitsEntry[TECHNIQUE_LIT] < m_material->stateBitsCount) - stateBits = m_material->stateBitsTable[m_material->stateBitsEntry[TECHNIQUE_LIT]]; - else if (m_material->stateBitsEntry[TECHNIQUE_EMISSIVE] < m_material->stateBitsCount) - stateBits = m_material->stateBitsTable[m_material->stateBitsEntry[TECHNIQUE_EMISSIVE]]; - else if (m_material->stateBitsEntry[TECHNIQUE_UNLIT] < m_material->stateBitsCount) - stateBits = m_material->stateBitsTable[m_material->stateBitsEntry[TECHNIQUE_UNLIT]]; - else if (m_material->stateBitsEntry[TECHNIQUE_DEPTH_PREPASS] < m_material->stateBitsCount) - stateBits = m_material->stateBitsTable[m_material->stateBitsEntry[TECHNIQUE_DEPTH_PREPASS]]; - else - { - assert(false); - return; - } - - if (m_state_bits_info.m_custom_blend_op_rgb == BlendOp_e::UNKNOWN) - m_state_bits_info.m_custom_blend_op_rgb = StateBitsToEnum<BlendOp_e>(stateBits.loadBits[0], GFXS0_BLENDOP_RGB_MASK, GFXS0_BLENDOP_RGB_SHIFT); - - if (m_state_bits_info.m_custom_blend_op_alpha == BlendOp_e::UNKNOWN) - m_state_bits_info.m_custom_blend_op_alpha = StateBitsToEnum<BlendOp_e>(stateBits.loadBits[0], GFXS0_BLENDOP_ALPHA_MASK, GFXS0_BLENDOP_ALPHA_SHIFT); - - if (m_state_bits_info.m_custom_src_blend_func == CustomBlendFunc_e::UNKNOWN) - m_state_bits_info.m_custom_src_blend_func = StateBitsToEnum<CustomBlendFunc_e>(stateBits.loadBits[0], GFXS0_SRCBLEND_RGB_MASK, GFXS0_SRCBLEND_RGB_SHIFT); - - if (m_state_bits_info.m_custom_dst_blend_func == CustomBlendFunc_e::UNKNOWN) - m_state_bits_info.m_custom_dst_blend_func = StateBitsToEnum<CustomBlendFunc_e>(stateBits.loadBits[0], GFXS0_DSTBLEND_RGB_MASK, GFXS0_DSTBLEND_RGB_SHIFT); - - if (m_state_bits_info.m_custom_src_blend_func_alpha == CustomBlendFunc_e::UNKNOWN) - m_state_bits_info.m_custom_src_blend_func_alpha = StateBitsToEnum<CustomBlendFunc_e>(stateBits.loadBits[0], GFXS0_SRCBLEND_ALPHA_MASK, GFXS0_SRCBLEND_ALPHA_SHIFT); - - if (m_state_bits_info.m_custom_dst_blend_func_alpha == CustomBlendFunc_e::UNKNOWN) - m_state_bits_info.m_custom_dst_blend_func_alpha = StateBitsToEnum<CustomBlendFunc_e>(stateBits.loadBits[0], GFXS0_DSTBLEND_ALPHA_MASK, GFXS0_DSTBLEND_ALPHA_SHIFT); - - if (m_state_bits_info.m_alpha_test == AlphaTest_e::UNKNOWN) - { - if (stateBits.loadBits[0] & GFXS0_ATEST_DISABLE) - m_state_bits_info.m_alpha_test = AlphaTest_e::ALWAYS; - else if ((stateBits.loadBits[0] & GFXS0_ATEST_MASK) == GFXS0_ATEST_GE_128) - m_state_bits_info.m_alpha_test = AlphaTest_e::GE128; - else if ((stateBits.loadBits[0] & GFXS0_ATEST_MASK) == GFXS0_ATEST_GT_0) - m_state_bits_info.m_alpha_test = AlphaTest_e::GT0; - else if ((stateBits.loadBits[0] & GFXS0_ATEST_MASK) == GFXS0_ATEST_LT_128) - m_state_bits_info.m_alpha_test = AlphaTest_e::LT128; - else - assert(false); - } - - if (m_state_bits_info.m_depth_test == DepthTest_e::UNKNOWN) - { - if (stateBits.loadBits[1] & GFXS1_DEPTHTEST_DISABLE) - m_state_bits_info.m_depth_test = DepthTest_e::DISABLE; - else if (stateBits.loadBits[1] & GFXS1_DEPTHTEST_LESSEQUAL) - m_state_bits_info.m_depth_test = DepthTest_e::LESS_EQUAL; - else if (stateBits.loadBits[1] & GFXS1_DEPTHTEST_LESS) - m_state_bits_info.m_depth_test = DepthTest_e::LESS; - else if (stateBits.loadBits[1] & GFXS1_DEPTHTEST_EQUAL) - m_state_bits_info.m_depth_test = DepthTest_e::EQUAL; - else - m_state_bits_info.m_depth_test = DepthTest_e::ALWAYS; - } - - if (m_state_bits_info.m_depth_write == StateBitsEnabledStatus_e::UNKNOWN) - m_state_bits_info.m_depth_write = (stateBits.loadBits[1] & GFXS1_DEPTHWRITE) ? StateBitsEnabledStatus_e::ENABLED : StateBitsEnabledStatus_e::DISABLED; - - if (m_state_bits_info.m_cull_face == CullFace_e::UNKNOWN) - { - if (stateBits.loadBits[0] & GFXS0_CULL_NONE) - m_state_bits_info.m_cull_face = CullFace_e::NONE; - else if (stateBits.loadBits[0] & GFXS0_CULL_BACK) - m_state_bits_info.m_cull_face = CullFace_e::BACK; - else if (stateBits.loadBits[0] & GFXS0_CULL_FRONT) - m_state_bits_info.m_cull_face = CullFace_e::FRONT; - else - assert(false); - } - - if (m_state_bits_info.m_polygon_offset == PolygonOffset_e::UNKNOWN) - m_state_bits_info.m_polygon_offset = StateBitsToEnum<PolygonOffset_e>(stateBits.loadBits[1], GFXS1_POLYGON_OFFSET_MASK, GFXS1_POLYGON_OFFSET_SHIFT); - - if (m_state_bits_info.m_color_write_rgb == StateBitsEnabledStatus_e::UNKNOWN) - m_state_bits_info.m_color_write_rgb = (stateBits.loadBits[0] & GFXS0_COLORWRITE_RGB) ? StateBitsEnabledStatus_e::ENABLED : StateBitsEnabledStatus_e::DISABLED; - - if (m_state_bits_info.m_color_write_alpha == StateBitsEnabledStatus_e::UNKNOWN) - m_state_bits_info.m_color_write_alpha = (stateBits.loadBits[0] & GFXS0_COLORWRITE_ALPHA) ? StateBitsEnabledStatus_e::ENABLED : StateBitsEnabledStatus_e::DISABLED; - - if (m_state_bits_info.m_gamma_write == StateBitsEnabledStatus_e::UNKNOWN) - m_state_bits_info.m_gamma_write = (stateBits.loadBits[0] & GFXS0_GAMMAWRITE) ? StateBitsEnabledStatus_e::ENABLED : StateBitsEnabledStatus_e::DISABLED; - - if (m_state_bits_info.m_stencil_mode == StencilMode_e::UNKNOWN) - { - if ((stateBits.loadBits[1] & GFXS1_STENCIL_BACK_ENABLE) == 0 && (stateBits.loadBits[1] & GFXS1_STENCIL_FRONT_ENABLE) == 0) - { - m_state_bits_info.m_stencil_mode = StencilMode_e::DISABLED; - } - else if (stateBits.loadBits[1] & GFXS1_STENCIL_BACK_ENABLE) - { - assert(stateBits.loadBits[1] & GFXS1_STENCIL_FRONT_ENABLE); - m_state_bits_info.m_stencil_mode = StencilMode_e::TWO_SIDED; - } - else - { - assert(stateBits.loadBits[1] & GFXS1_STENCIL_FRONT_ENABLE); - m_state_bits_info.m_stencil_mode = StencilMode_e::ONE_SIDED; - } - } - - if (m_state_bits_info.m_stencil_front_func == StencilFunc_e::UNKNOWN) - m_state_bits_info.m_stencil_front_func = StateBitsToEnum<StencilFunc_e>(stateBits.loadBits[1], GFXS1_STENCIL_FRONT_FUNC_MASK, GFXS1_STENCIL_FRONT_FUNC_SHIFT); - - if (m_state_bits_info.m_stencil_front_pass == StencilOp_e::UNKNOWN) - m_state_bits_info.m_stencil_front_pass = StateBitsToEnum<StencilOp_e>(stateBits.loadBits[1], GFXS1_STENCIL_FRONT_PASS_MASK, GFXS1_STENCIL_FRONT_PASS_SHIFT); - - if (m_state_bits_info.m_stencil_front_fail == StencilOp_e::UNKNOWN) - m_state_bits_info.m_stencil_front_fail = StateBitsToEnum<StencilOp_e>(stateBits.loadBits[1], GFXS1_STENCIL_FRONT_FAIL_MASK, GFXS1_STENCIL_FRONT_FAIL_SHIFT); - - if (m_state_bits_info.m_stencil_front_zfail == StencilOp_e::UNKNOWN) - m_state_bits_info.m_stencil_front_zfail = StateBitsToEnum<StencilOp_e>(stateBits.loadBits[1], GFXS1_STENCIL_FRONT_ZFAIL_MASK, GFXS1_STENCIL_FRONT_ZFAIL_SHIFT); - - if (m_state_bits_info.m_stencil_back_func == StencilFunc_e::UNKNOWN) - m_state_bits_info.m_stencil_back_func = StateBitsToEnum<StencilFunc_e>(stateBits.loadBits[1], GFXS1_STENCIL_BACK_FUNC_MASK, GFXS1_STENCIL_BACK_FUNC_SHIFT); - - if (m_state_bits_info.m_stencil_back_pass == StencilOp_e::UNKNOWN) - m_state_bits_info.m_stencil_back_pass = StateBitsToEnum<StencilOp_e>(stateBits.loadBits[1], GFXS1_STENCIL_BACK_PASS_MASK, GFXS1_STENCIL_BACK_PASS_SHIFT); - - if (m_state_bits_info.m_stencil_back_fail == StencilOp_e::UNKNOWN) - m_state_bits_info.m_stencil_back_fail = StateBitsToEnum<StencilOp_e>(stateBits.loadBits[1], GFXS1_STENCIL_BACK_FAIL_MASK, GFXS1_STENCIL_BACK_FAIL_SHIFT); - - if (m_state_bits_info.m_stencil_back_zfail == StencilOp_e::UNKNOWN) - m_state_bits_info.m_stencil_back_zfail = StateBitsToEnum<StencilOp_e>(stateBits.loadBits[1], GFXS1_STENCIL_BACK_ZFAIL_MASK, GFXS1_STENCIL_BACK_ZFAIL_SHIFT); - - ExamineBlendFunc(); - } + if (m_state_bits_info.m_stencil_back_func == StencilFunc_e::UNKNOWN) + m_state_bits_info.m_stencil_back_func = + StateBitsToEnum<StencilFunc_e>(stateBits.loadBits[1], GFXS1_STENCIL_BACK_FUNC_MASK, GFXS1_STENCIL_BACK_FUNC_SHIFT); - _NODISCARD int FindConstant(const std::string& constantName) const - { - const auto constantHash = Common::R_HashString(constantName.c_str(), 0u); + if (m_state_bits_info.m_stencil_back_pass == StencilOp_e::UNKNOWN) + m_state_bits_info.m_stencil_back_pass = StateBitsToEnum<StencilOp_e>(stateBits.loadBits[1], GFXS1_STENCIL_BACK_PASS_MASK, GFXS1_STENCIL_BACK_PASS_SHIFT); - if (m_material->constantTable) - { - for (auto i = 0; i < m_material->constantCount; i++) - { - if (m_material->constantTable[i].nameHash == constantHash) - return i; - } - } + if (m_state_bits_info.m_stencil_back_fail == StencilOp_e::UNKNOWN) + m_state_bits_info.m_stencil_back_fail = StateBitsToEnum<StencilOp_e>(stateBits.loadBits[1], GFXS1_STENCIL_BACK_FAIL_MASK, GFXS1_STENCIL_BACK_FAIL_SHIFT); - return -1; - } + if (m_state_bits_info.m_stencil_back_zfail == StencilOp_e::UNKNOWN) + m_state_bits_info.m_stencil_back_zfail = + StateBitsToEnum<StencilOp_e>(stateBits.loadBits[1], GFXS1_STENCIL_BACK_ZFAIL_MASK, GFXS1_STENCIL_BACK_ZFAIL_SHIFT); - _NODISCARD int FindTexture(const std::string& textureTypeName) const - { - const auto textureTypeHash = Common::R_HashString(textureTypeName.c_str(), 0u); + ExamineBlendFunc(); + } - if (m_material->textureTable) - { - for (auto i = 0; i < m_material->textureCount; i++) - { - if (m_material->textureTable[i].nameHash == textureTypeHash) - return i; - } - } + _NODISCARD int FindConstant(const std::string &constantName) const { + const auto constantHash = Common::R_HashString(constantName.c_str(), 0u); - return -1; - } + if (m_material->constantTable) { + for (auto i = 0; i < m_material->constantCount; i++) { + if (m_material->constantTable[i].nameHash == constantHash) + return i; + } + } - void ExamineConstants() - { - if (!m_material->constantTable) - return; - - for (auto i = 0u; i < m_material->constantCount; i++) - { - const auto& constant = m_material->constantTable[i]; - - if (constant.nameHash == Common::R_HashString("colorTint")) - { - m_constants_info.m_color_tint = Vector4f(constant.literal); - } - else if (constant.nameHash == Common::R_HashString("envMapParms")) - { - // TODO: Calculate actual values - m_constants_info.m_env_map_min = 0; - m_constants_info.m_env_map_max = 0; - m_constants_info.m_env_map_exponent = 0; - } - else if (constant.nameHash == Common::R_HashString("featherParms")) - { - m_constants_info.m_zfeather_depth = constant.literal[1]; - } - else if (constant.nameHash == Common::R_HashString("falloffBeginColor")) - { - m_constants_info.m_falloff_begin_color = Vector4f(constant.literal); - } - else if (constant.nameHash == Common::R_HashString("falloffEndColor")) - { - m_constants_info.m_falloff_end_color = Vector4f(constant.literal); - } - else if (constant.nameHash == Common::R_HashString("eyeOffsetParms")) - { - m_constants_info.m_eye_offset_depth = constant.literal[0]; - } - else if (constant.nameHash == Common::R_HashString("detailScale")) - { - const auto materialType = m_techset_info.m_gdt_material_type; - const auto colorMapIndex = FindTexture("colorMap"); - const auto detailMapIndex = FindTexture("detailMap"); - const auto hasColorMap = colorMapIndex >= 0 && m_material->textureTable[colorMapIndex].semantic != TS_WATER_MAP && m_material->textureTable[colorMapIndex].u.image; - const auto hasDetailMap = detailMapIndex >= 0 && m_material->textureTable[detailMapIndex].semantic != TS_WATER_MAP && m_material->textureTable[detailMapIndex].u.image; - - if ((materialType == MATERIAL_TYPE_MODEL_PHONG || materialType == MATERIAL_TYPE_WORLD_PHONG) - && hasColorMap && hasDetailMap) - { - const auto colorMapTexture = m_material->textureTable[colorMapIndex].u.image; - const auto detailMapTexture = m_material->textureTable[detailMapIndex].u.image; - - if (colorMapTexture->width != 0 && colorMapTexture->height != 0 - && detailMapTexture->width != 0 && detailMapTexture->height != 0) - { - const auto detailScaleFactorX = static_cast<float>(colorMapTexture->width) / static_cast<float>(detailMapTexture->width); - const auto detailScaleFactorY = static_cast<float>(colorMapTexture->height) / static_cast<float>(detailMapTexture->height); - m_constants_info.m_detail_scale = Vector2f(constant.literal[0] / detailScaleFactorX, constant.literal[1] / detailScaleFactorY); - } - else - m_constants_info.m_detail_scale = Vector2f(constant.literal[0], constant.literal[1]); - } - else - { - m_constants_info.m_detail_scale = Vector2f(constant.literal[0], constant.literal[1]); - } - } - else if (constant.nameHash == Common::R_HashString("flagParms")) - { - m_constants_info.m_flag_speed = constant.literal[0]; - m_constants_info.m_flag_phase = constant.literal[1]; - } - else if (constant.nameHash == Common::R_HashString("falloffParms")) - { - // TODO: Calculate actual values - m_constants_info.m_falloff_begin_angle = 0.0f; - m_constants_info.m_falloff_end_angle = 0.0f; - m_constants_info.m_dist_falloff_begin_distance = 0.0f; - m_constants_info.m_dist_falloff_end_distance = 0.0f; - } - else if (constant.nameHash == Common::R_HashString("distortionScale")) - { - m_constants_info.m_distortion_scale = Vector2f(constant.literal[0], constant.literal[1]); - } - else if (constant.nameHash == Common::R_HashString("uvAnimParms")) - { - m_constants_info.m_uv_scroll_x = constant.literal[0]; - m_constants_info.m_uv_scroll_y = constant.literal[1]; - m_constants_info.m_uv_rotate = constant.literal[2]; - } - else if (constant.nameHash == Common::R_HashString("colorObjMin")) - { - m_constants_info.m_color_obj_min = Vector4f(constant.literal); - } - else if (constant.nameHash == Common::R_HashString("colorObjMax")) - { - m_constants_info.m_color_obj_max = Vector4f(constant.literal); - } - else if (constant.nameHash == Common::R_HashString("waterColor")) - { - m_constants_info.m_water_color = Vector4f(constant.literal); - } - else - { - std::string constantNamePart(constant.name, strnlen(constant.name, std::extent_v<decltype(constant.name)>)); - std::cout << "Unknown constant: " << constantNamePart << "\n"; - } - } - } + return -1; + } - void SetMaterialTypeValues() - { - ExamineTechsetInfo(); - ExamineStateBitsInfo(); - ExamineConstants(); - - SetValue("materialType", GdtMaterialTypeNames[static_cast<size_t>(m_techset_info.m_gdt_material_type)]); - SetValue("customTemplate", GdtCustomMaterialTypeNames[static_cast<size_t>(m_techset_info.m_gdt_custom_material_type)]); - SetValue("customString", m_techset_info.m_gdt_custom_string); - SetValue("sort", m_techset_info.m_sort_key_name); - SetValue("noCastShadow", m_techset_info.m_no_cast_shadow); - SetValue("noReceiveDynamicShadow", m_techset_info.m_no_receive_dynamic_shadow); - SetValue("noFog", m_techset_info.m_no_fog); - SetValue("texScroll", m_techset_info.m_tex_scroll); - SetValue("uvAnim", m_techset_info.m_uv_anim); - SetValue("zFeather", m_techset_info.m_zfeather); - SetValue("zFeatherDepth", m_constants_info.m_zfeather_depth); - SetValue("useSpotLight", m_techset_info.m_use_spot_light); - SetValue("falloff", m_techset_info.m_falloff); - SetValue("distFalloff", m_techset_info.m_dist_falloff); - SetValue("outdoorOnly", m_techset_info.m_outdoor_only); - SetValue("eyeOffsetDepth", m_constants_info.m_eye_offset_depth); - - - // TODO: These are not good names, change when known what they do - SetValue("specularP", m_techset_info.m_specular_p_flag); - SetValue("colorO", m_techset_info.m_color_o_flag); - SetValue("effectLinFlag", m_techset_info.m_effect_lin_flag); - - SetValue("blendFunc", GdtBlendFuncNames[static_cast<size_t>(m_state_bits_info.m_blend_func)]); - SetValue("customBlendOpRgb", GdtBlendOpNames[static_cast<size_t>(m_state_bits_info.m_custom_blend_op_rgb)]); - SetValue("customBlendOpAlpha", GdtBlendOpNames[static_cast<size_t>(m_state_bits_info.m_custom_blend_op_alpha)]); - SetValue("srcCustomBlendFunc", GdtCustomBlendFuncNames[static_cast<size_t>(m_state_bits_info.m_custom_src_blend_func)]); - SetValue("destCustomBlendFunc", GdtCustomBlendFuncNames[static_cast<size_t>(m_state_bits_info.m_custom_dst_blend_func)]); - SetValue("srcCustomBlendFuncAlpha", GdtCustomBlendFuncNames[static_cast<size_t>(m_state_bits_info.m_custom_src_blend_func_alpha)]); - SetValue("destCustomBlendFuncAlpha", GdtCustomBlendFuncNames[static_cast<size_t>(m_state_bits_info.m_custom_dst_blend_func_alpha)]); - SetValue("alphaTest", GdtAlphaTestNames[static_cast<size_t>(m_state_bits_info.m_alpha_test)]); - SetValue("depthTest", GdtDepthTestNames[static_cast<size_t>(m_state_bits_info.m_depth_test)]); - SetValue("depthWrite", GdtStateBitsOnOffStatusNames[static_cast<size_t>(m_state_bits_info.m_depth_write)]); - SetValue("cullFace", GdtCullFaceNames[static_cast<size_t>(m_state_bits_info.m_cull_face)]); - SetValue("polygonOffset", GdtPolygonOffsetNames[static_cast<size_t>(m_state_bits_info.m_polygon_offset)]); - SetValue("colorWriteRed", GdtStateBitsEnabledStatusNames[static_cast<size_t>(m_state_bits_info.m_color_write_rgb)]); - SetValue("colorWriteGreen", GdtStateBitsEnabledStatusNames[static_cast<size_t>(m_state_bits_info.m_color_write_rgb)]); - SetValue("colorWriteBlue", GdtStateBitsEnabledStatusNames[static_cast<size_t>(m_state_bits_info.m_color_write_rgb)]); - SetValue("colorWriteAlpha", GdtStateBitsEnabledStatusNames[static_cast<size_t>(m_state_bits_info.m_color_write_alpha)]); - SetValue("gammaWrite", GdtStateBitsOnOffStatusNames[static_cast<size_t>(m_state_bits_info.m_gamma_write)]); - SetValue("stencil", GdtStencilModeNames[static_cast<size_t>(m_state_bits_info.m_stencil_mode)]); - SetValue("stencilFunc1", GdtStencilFuncNames[static_cast<size_t>(m_state_bits_info.m_stencil_front_func)]); - SetValue("stencilOpPass1", GdtStencilOpNames[static_cast<size_t>(m_state_bits_info.m_stencil_front_pass)]); - SetValue("stencilOpFail1", GdtStencilOpNames[static_cast<size_t>(m_state_bits_info.m_stencil_front_fail)]); - SetValue("stencilOpZFail1", GdtStencilOpNames[static_cast<size_t>(m_state_bits_info.m_stencil_front_zfail)]); - SetValue("stencilFunc2", GdtStencilFuncNames[static_cast<size_t>(m_state_bits_info.m_stencil_back_func)]); - SetValue("stencilOpPass2", GdtStencilOpNames[static_cast<size_t>(m_state_bits_info.m_stencil_back_pass)]); - SetValue("stencilOpFail2", GdtStencilOpNames[static_cast<size_t>(m_state_bits_info.m_stencil_back_fail)]); - SetValue("stencilOpZFail2", GdtStencilOpNames[static_cast<size_t>(m_state_bits_info.m_stencil_back_zfail)]); - - SetValue("colorTint", m_constants_info.m_color_tint); - SetValue("envMapMin", m_constants_info.m_env_map_min); - SetValue("envMapMax", m_constants_info.m_env_map_max); - SetValue("envMapExponent", m_constants_info.m_env_map_exponent); - SetValue("zFeatherDepth", m_constants_info.m_zfeather_depth); - SetValue("eyeOffsetDepth", m_constants_info.m_eye_offset_depth); - SetValue("falloffBeginColor", m_constants_info.m_falloff_begin_color); - SetValue("falloffEndColor", m_constants_info.m_falloff_end_color); - SetValue("detailScaleX", m_constants_info.m_detail_scale.x()); - SetValue("detailScaleY", m_constants_info.m_detail_scale.y()); - SetValue("distortionScaleX", m_constants_info.m_distortion_scale.x()); - SetValue("distortionScaleY", m_constants_info.m_distortion_scale.y()); - SetValue("colorObjMin", m_constants_info.m_color_obj_min); - SetValue("colorObjMax", m_constants_info.m_color_obj_max); - SetValue("waterColor", m_constants_info.m_water_color); - SetValue("flagSpeed", m_constants_info.m_flag_speed); - SetValue("flagPhase", m_constants_info.m_flag_phase); - SetValue("uvScrollX", m_constants_info.m_uv_scroll_x); - SetValue("uvScrollY", m_constants_info.m_uv_scroll_y); - SetValue("uvScrollRotate", m_constants_info.m_uv_rotate); - } + _NODISCARD int FindTexture(const std::string &textureTypeName) const { + const auto textureTypeHash = Common::R_HashString(textureTypeName.c_str(), 0u); - void SetTextureTableValues() - { - if (m_material->textureTable == nullptr || m_material->textureCount <= 0) - return; - - for (auto i = 0u; i < m_material->textureCount; i++) - { - const auto& entry = m_material->textureTable[i]; - const auto knownMaterialSourceName = knownTextureMaps.find(entry.nameHash); - if (knownMaterialSourceName == knownTextureMaps.end()) - { - assert(false); - std::cout << "Unknown material texture source name hash: 0x" << std::hex << entry.nameHash << " (" << entry.nameStart << "..." << entry.nameEnd << ")\n"; - continue; - } - - const char* imageName; - if (entry.semantic != TS_WATER_MAP) - { - if (!entry.u.image || !entry.u.image->name) - continue; - imageName = AssetName(entry.u.image->name); - } - else - { - if (!entry.u.water || !entry.u.water->image || !entry.u.water->image->name) - continue; - imageName = AssetName(entry.u.water->image->name); - } - - TileMode_e tileMode; - if (entry.samplerState & SAMPLER_CLAMP_U && entry.samplerState & SAMPLER_CLAMP_V && entry.samplerState & SAMPLER_CLAMP_W) - tileMode = TileMode_e::TILE_BOTH; - else if (entry.samplerState & SAMPLER_CLAMP_U) - tileMode = TileMode_e::TILE_VERTICAL; - else if (entry.samplerState & SAMPLER_CLAMP_V) - tileMode = TileMode_e::TILE_HORIZONTAL; - else - tileMode = TileMode_e::NO_TILE; - - auto filter = GdtFilter_e::UNKNOWN; - if ((entry.samplerState & SAMPLER_FILTER_MASK) == SAMPLER_FILTER_ANISO2X) - { - if (entry.samplerState & SAMPLER_MIPMAP_NEAREST) - filter = GdtFilter_e::MIP_2X_BILINEAR; - else if (entry.samplerState & SAMPLER_MIPMAP_LINEAR) - filter = GdtFilter_e::MIP_2X_TRILINEAR; - } - else if ((entry.samplerState & SAMPLER_FILTER_MASK) == SAMPLER_FILTER_ANISO4X) - { - if (entry.samplerState & SAMPLER_MIPMAP_NEAREST) - filter = GdtFilter_e::MIP_4X_BILINEAR; - else if (entry.samplerState & SAMPLER_MIPMAP_LINEAR) - filter = GdtFilter_e::MIP_4X_TRILINEAR; - } - else if ((entry.samplerState & SAMPLER_FILTER_MASK) == SAMPLER_FILTER_NEAREST) - { - assert((entry.samplerState & SAMPLER_MIPMAP_MASK) == SAMPLER_MIPMAP_DISABLED); - filter = GdtFilter_e::NOMIP_NEAREST; - } - else if ((entry.samplerState & SAMPLER_FILTER_MASK) == SAMPLER_FILTER_LINEAR) - { - assert((entry.samplerState & SAMPLER_MIPMAP_MASK) == SAMPLER_MIPMAP_DISABLED); - filter = GdtFilter_e::NOMIP_BILINEAR; - } - - assert(filter != GdtFilter_e::UNKNOWN); - if (filter == GdtFilter_e::UNKNOWN) - { - std::cout << "Unknown filter/mipmap combination: " << entry.samplerState << "\n"; - continue; - } - - SetValue(knownMaterialSourceName->second.m_name, imageName); - SetValue("tile"s + knownMaterialSourceName->second.m_additional_property_suffix, GdtTileModeNames[static_cast<size_t>(tileMode)]); - SetValue("filter"s + knownMaterialSourceName->second.m_additional_property_suffix, GdtSamplerFilterNames[static_cast<size_t>(filter)]); - } - } + if (m_material->textureTable) { + for (auto i = 0; i < m_material->textureCount; i++) { + if (m_material->textureTable[i].nameHash == textureTypeHash) + return i; + } + } - public: - explicit MaterialGdtDumper(const Material* material) - : m_material(material) - { + return -1; + } + + void ExamineConstants() { + if (!m_material->constantTable) + return; + + for (auto i = 0u; i < m_material->constantCount; i++) { + const auto &constant = m_material->constantTable[i]; + + if (constant.nameHash == Common::R_HashString("colorTint")) { + m_constants_info.m_color_tint = Vector4f(constant.literal); + } else if (constant.nameHash == Common::R_HashString("envMapParms")) { + // TODO: Calculate actual values + m_constants_info.m_env_map_min = 0; + m_constants_info.m_env_map_max = 0; + m_constants_info.m_env_map_exponent = 0; + } else if (constant.nameHash == Common::R_HashString("featherParms")) { + m_constants_info.m_zfeather_depth = constant.literal[1]; + } else if (constant.nameHash == Common::R_HashString("falloffBeginColor")) { + m_constants_info.m_falloff_begin_color = Vector4f(constant.literal); + } else if (constant.nameHash == Common::R_HashString("falloffEndColor")) { + m_constants_info.m_falloff_end_color = Vector4f(constant.literal); + } else if (constant.nameHash == Common::R_HashString("eyeOffsetParms")) { + m_constants_info.m_eye_offset_depth = constant.literal[0]; + } else if (constant.nameHash == Common::R_HashString("detailScale")) { + const auto materialType = m_techset_info.m_gdt_material_type; + const auto colorMapIndex = FindTexture("colorMap"); + const auto detailMapIndex = FindTexture("detailMap"); + const auto hasColorMap = + colorMapIndex >= 0 && m_material->textureTable[colorMapIndex].semantic != TS_WATER_MAP && m_material->textureTable[colorMapIndex].u.image; + const auto hasDetailMap = + detailMapIndex >= 0 && m_material->textureTable[detailMapIndex].semantic != TS_WATER_MAP && m_material->textureTable[detailMapIndex].u.image; + + if ((materialType == MATERIAL_TYPE_MODEL_PHONG || materialType == MATERIAL_TYPE_WORLD_PHONG) && hasColorMap && hasDetailMap) { + const auto colorMapTexture = m_material->textureTable[colorMapIndex].u.image; + const auto detailMapTexture = m_material->textureTable[detailMapIndex].u.image; + + if (colorMapTexture->width != 0 && colorMapTexture->height != 0 && detailMapTexture->width != 0 && detailMapTexture->height != 0) { + const auto detailScaleFactorX = static_cast<float>(colorMapTexture->width) / static_cast<float>(detailMapTexture->width); + const auto detailScaleFactorY = static_cast<float>(colorMapTexture->height) / static_cast<float>(detailMapTexture->height); + m_constants_info.m_detail_scale = Vector2f(constant.literal[0] / detailScaleFactorX, constant.literal[1] / detailScaleFactorY); + } else + m_constants_info.m_detail_scale = Vector2f(constant.literal[0], constant.literal[1]); + } else { + m_constants_info.m_detail_scale = Vector2f(constant.literal[0], constant.literal[1]); } + } else if (constant.nameHash == Common::R_HashString("flagParms")) { + m_constants_info.m_flag_speed = constant.literal[0]; + m_constants_info.m_flag_phase = constant.literal[1]; + } else if (constant.nameHash == Common::R_HashString("falloffParms")) { + // TODO: Calculate actual values + m_constants_info.m_falloff_begin_angle = 0.0f; + m_constants_info.m_falloff_end_angle = 0.0f; + m_constants_info.m_dist_falloff_begin_distance = 0.0f; + m_constants_info.m_dist_falloff_end_distance = 0.0f; + } else if (constant.nameHash == Common::R_HashString("distortionScale")) { + m_constants_info.m_distortion_scale = Vector2f(constant.literal[0], constant.literal[1]); + } else if (constant.nameHash == Common::R_HashString("uvAnimParms")) { + m_constants_info.m_uv_scroll_x = constant.literal[0]; + m_constants_info.m_uv_scroll_y = constant.literal[1]; + m_constants_info.m_uv_rotate = constant.literal[2]; + } else if (constant.nameHash == Common::R_HashString("colorObjMin")) { + m_constants_info.m_color_obj_min = Vector4f(constant.literal); + } else if (constant.nameHash == Common::R_HashString("colorObjMax")) { + m_constants_info.m_color_obj_max = Vector4f(constant.literal); + } else if (constant.nameHash == Common::R_HashString("waterColor")) { + m_constants_info.m_water_color = Vector4f(constant.literal); + } else { + std::string constantNamePart(constant.name, strnlen(constant.name, std::extent_v<decltype(constant.name)>)); + std::cout << "Unknown constant: " << constantNamePart << "\n"; + } + } + } + + void SetMaterialTypeValues() { + ExamineTechsetInfo(); + ExamineStateBitsInfo(); + ExamineConstants(); + + SetValue("materialType", GdtMaterialTypeNames[static_cast<size_t>(m_techset_info.m_gdt_material_type)]); + SetValue("customTemplate", GdtCustomMaterialTypeNames[static_cast<size_t>(m_techset_info.m_gdt_custom_material_type)]); + SetValue("customString", m_techset_info.m_gdt_custom_string); + SetValue("sort", m_techset_info.m_sort_key_name); + SetValue("noCastShadow", m_techset_info.m_no_cast_shadow); + SetValue("noReceiveDynamicShadow", m_techset_info.m_no_receive_dynamic_shadow); + SetValue("noFog", m_techset_info.m_no_fog); + SetValue("texScroll", m_techset_info.m_tex_scroll); + SetValue("uvAnim", m_techset_info.m_uv_anim); + SetValue("zFeather", m_techset_info.m_zfeather); + SetValue("zFeatherDepth", m_constants_info.m_zfeather_depth); + SetValue("useSpotLight", m_techset_info.m_use_spot_light); + SetValue("falloff", m_techset_info.m_falloff); + SetValue("distFalloff", m_techset_info.m_dist_falloff); + SetValue("outdoorOnly", m_techset_info.m_outdoor_only); + SetValue("eyeOffsetDepth", m_constants_info.m_eye_offset_depth); + + // TODO: These are not good names, change when known what they do + SetValue("specularP", m_techset_info.m_specular_p_flag); + SetValue("colorO", m_techset_info.m_color_o_flag); + SetValue("effectLinFlag", m_techset_info.m_effect_lin_flag); + + SetValue("blendFunc", GdtBlendFuncNames[static_cast<size_t>(m_state_bits_info.m_blend_func)]); + SetValue("customBlendOpRgb", GdtBlendOpNames[static_cast<size_t>(m_state_bits_info.m_custom_blend_op_rgb)]); + SetValue("customBlendOpAlpha", GdtBlendOpNames[static_cast<size_t>(m_state_bits_info.m_custom_blend_op_alpha)]); + SetValue("srcCustomBlendFunc", GdtCustomBlendFuncNames[static_cast<size_t>(m_state_bits_info.m_custom_src_blend_func)]); + SetValue("destCustomBlendFunc", GdtCustomBlendFuncNames[static_cast<size_t>(m_state_bits_info.m_custom_dst_blend_func)]); + SetValue("srcCustomBlendFuncAlpha", GdtCustomBlendFuncNames[static_cast<size_t>(m_state_bits_info.m_custom_src_blend_func_alpha)]); + SetValue("destCustomBlendFuncAlpha", GdtCustomBlendFuncNames[static_cast<size_t>(m_state_bits_info.m_custom_dst_blend_func_alpha)]); + SetValue("alphaTest", GdtAlphaTestNames[static_cast<size_t>(m_state_bits_info.m_alpha_test)]); + SetValue("depthTest", GdtDepthTestNames[static_cast<size_t>(m_state_bits_info.m_depth_test)]); + SetValue("depthWrite", GdtStateBitsOnOffStatusNames[static_cast<size_t>(m_state_bits_info.m_depth_write)]); + SetValue("cullFace", GdtCullFaceNames[static_cast<size_t>(m_state_bits_info.m_cull_face)]); + SetValue("polygonOffset", GdtPolygonOffsetNames[static_cast<size_t>(m_state_bits_info.m_polygon_offset)]); + SetValue("colorWriteRed", GdtStateBitsEnabledStatusNames[static_cast<size_t>(m_state_bits_info.m_color_write_rgb)]); + SetValue("colorWriteGreen", GdtStateBitsEnabledStatusNames[static_cast<size_t>(m_state_bits_info.m_color_write_rgb)]); + SetValue("colorWriteBlue", GdtStateBitsEnabledStatusNames[static_cast<size_t>(m_state_bits_info.m_color_write_rgb)]); + SetValue("colorWriteAlpha", GdtStateBitsEnabledStatusNames[static_cast<size_t>(m_state_bits_info.m_color_write_alpha)]); + SetValue("gammaWrite", GdtStateBitsOnOffStatusNames[static_cast<size_t>(m_state_bits_info.m_gamma_write)]); + SetValue("stencil", GdtStencilModeNames[static_cast<size_t>(m_state_bits_info.m_stencil_mode)]); + SetValue("stencilFunc1", GdtStencilFuncNames[static_cast<size_t>(m_state_bits_info.m_stencil_front_func)]); + SetValue("stencilOpPass1", GdtStencilOpNames[static_cast<size_t>(m_state_bits_info.m_stencil_front_pass)]); + SetValue("stencilOpFail1", GdtStencilOpNames[static_cast<size_t>(m_state_bits_info.m_stencil_front_fail)]); + SetValue("stencilOpZFail1", GdtStencilOpNames[static_cast<size_t>(m_state_bits_info.m_stencil_front_zfail)]); + SetValue("stencilFunc2", GdtStencilFuncNames[static_cast<size_t>(m_state_bits_info.m_stencil_back_func)]); + SetValue("stencilOpPass2", GdtStencilOpNames[static_cast<size_t>(m_state_bits_info.m_stencil_back_pass)]); + SetValue("stencilOpFail2", GdtStencilOpNames[static_cast<size_t>(m_state_bits_info.m_stencil_back_fail)]); + SetValue("stencilOpZFail2", GdtStencilOpNames[static_cast<size_t>(m_state_bits_info.m_stencil_back_zfail)]); + + SetValue("colorTint", m_constants_info.m_color_tint); + SetValue("envMapMin", m_constants_info.m_env_map_min); + SetValue("envMapMax", m_constants_info.m_env_map_max); + SetValue("envMapExponent", m_constants_info.m_env_map_exponent); + SetValue("zFeatherDepth", m_constants_info.m_zfeather_depth); + SetValue("eyeOffsetDepth", m_constants_info.m_eye_offset_depth); + SetValue("falloffBeginColor", m_constants_info.m_falloff_begin_color); + SetValue("falloffEndColor", m_constants_info.m_falloff_end_color); + SetValue("detailScaleX", m_constants_info.m_detail_scale.x()); + SetValue("detailScaleY", m_constants_info.m_detail_scale.y()); + SetValue("distortionScaleX", m_constants_info.m_distortion_scale.x()); + SetValue("distortionScaleY", m_constants_info.m_distortion_scale.y()); + SetValue("colorObjMin", m_constants_info.m_color_obj_min); + SetValue("colorObjMax", m_constants_info.m_color_obj_max); + SetValue("waterColor", m_constants_info.m_water_color); + SetValue("flagSpeed", m_constants_info.m_flag_speed); + SetValue("flagPhase", m_constants_info.m_flag_phase); + SetValue("uvScrollX", m_constants_info.m_uv_scroll_x); + SetValue("uvScrollY", m_constants_info.m_uv_scroll_y); + SetValue("uvScrollRotate", m_constants_info.m_uv_rotate); + } + + void SetTextureTableValues() { + if (m_material->textureTable == nullptr || m_material->textureCount <= 0) + return; + + for (auto i = 0u; i < m_material->textureCount; i++) { + const auto &entry = m_material->textureTable[i]; + const auto knownMaterialSourceName = knownTextureMaps.find(entry.nameHash); + if (knownMaterialSourceName == knownTextureMaps.end()) { + assert(false); + std::cout << "Unknown material texture source name hash: 0x" << std::hex << entry.nameHash << " (" << entry.nameStart << "..." << entry.nameEnd + << ")\n"; + continue; + } + + const char *imageName; + if (entry.semantic != TS_WATER_MAP) { + if (!entry.u.image || !entry.u.image->name) + continue; + imageName = AssetName(entry.u.image->name); + } else { + if (!entry.u.water || !entry.u.water->image || !entry.u.water->image->name) + continue; + imageName = AssetName(entry.u.water->image->name); + } + + TileMode_e tileMode; + if (entry.samplerState & SAMPLER_CLAMP_U && entry.samplerState & SAMPLER_CLAMP_V && entry.samplerState & SAMPLER_CLAMP_W) + tileMode = TileMode_e::TILE_BOTH; + else if (entry.samplerState & SAMPLER_CLAMP_U) + tileMode = TileMode_e::TILE_VERTICAL; + else if (entry.samplerState & SAMPLER_CLAMP_V) + tileMode = TileMode_e::TILE_HORIZONTAL; + else + tileMode = TileMode_e::NO_TILE; + + auto filter = GdtFilter_e::UNKNOWN; + if ((entry.samplerState & SAMPLER_FILTER_MASK) == SAMPLER_FILTER_ANISO2X) { + if (entry.samplerState & SAMPLER_MIPMAP_NEAREST) + filter = GdtFilter_e::MIP_2X_BILINEAR; + else if (entry.samplerState & SAMPLER_MIPMAP_LINEAR) + filter = GdtFilter_e::MIP_2X_TRILINEAR; + } else if ((entry.samplerState & SAMPLER_FILTER_MASK) == SAMPLER_FILTER_ANISO4X) { + if (entry.samplerState & SAMPLER_MIPMAP_NEAREST) + filter = GdtFilter_e::MIP_4X_BILINEAR; + else if (entry.samplerState & SAMPLER_MIPMAP_LINEAR) + filter = GdtFilter_e::MIP_4X_TRILINEAR; + } else if ((entry.samplerState & SAMPLER_FILTER_MASK) == SAMPLER_FILTER_NEAREST) { + assert((entry.samplerState & SAMPLER_MIPMAP_MASK) == SAMPLER_MIPMAP_DISABLED); + filter = GdtFilter_e::NOMIP_NEAREST; + } else if ((entry.samplerState & SAMPLER_FILTER_MASK) == SAMPLER_FILTER_LINEAR) { + assert((entry.samplerState & SAMPLER_MIPMAP_MASK) == SAMPLER_MIPMAP_DISABLED); + filter = GdtFilter_e::NOMIP_BILINEAR; + } + + assert(filter != GdtFilter_e::UNKNOWN); + if (filter == GdtFilter_e::UNKNOWN) { + std::cout << "Unknown filter/mipmap combination: " << entry.samplerState << "\n"; + continue; + } + + SetValue(knownMaterialSourceName->second.m_name, imageName); + SetValue("tile"s + knownMaterialSourceName->second.m_additional_property_suffix, GdtTileModeNames[static_cast<size_t>(tileMode)]); + SetValue("filter"s + knownMaterialSourceName->second.m_additional_property_suffix, GdtSamplerFilterNames[static_cast<size_t>(filter)]); + } + } - GdtEntry& CreateGdtEntry() - { - m_entry = GdtEntry(); - m_entry.m_gdf_name = ObjConstants::GDF_FILENAME_MATERIAL; - m_entry.m_name = m_material->info.name; +public: + explicit MaterialGdtDumper(const Material *material) : m_material(material) {} - SetCommonValues(); - SetMaterialTypeValues(); - SetTextureTableValues(); + GdtEntry &CreateGdtEntry() { + m_entry = GdtEntry(); + m_entry.m_gdf_name = ObjConstants::GDF_FILENAME_MATERIAL; + m_entry.m_name = m_material->info.name; - return m_entry; - } - }; -} + SetCommonValues(); + SetMaterialTypeValues(); + SetTextureTableValues(); -bool AssetDumperMaterial::ShouldDump(XAssetInfo<Material>* asset) -{ - return true; -} + return m_entry; + } +}; +} // namespace IW4 -void AssetDumperMaterial::DumpAsset(AssetDumpingContext& context, XAssetInfo<Material>* asset) -{ - auto* material = asset->Asset(); +bool AssetDumperMaterial::ShouldDump(XAssetInfo<Material> *asset) { return true; } + +void AssetDumperMaterial::DumpAsset(AssetDumpingContext &context, XAssetInfo<Material> *asset) { + auto *material = asset->Asset(); #if defined(DUMP_AS_JSON) && DUMP_AS_JSON == 1 - { - std::ostringstream ss; - ss << "materials/" << asset->m_name << ".json"; - const auto assetFile = context.OpenAssetFile(ss.str()); - if (!assetFile) - return; - auto& stream = *assetFile; - DumpMaterialAsJson(material, stream); - } + { + std::ostringstream ss; + ss << "materials/" << asset->m_name << ".json"; + const auto assetFile = context.OpenAssetFile(ss.str()); + if (!assetFile) + return; + auto &stream = *assetFile; + DumpMaterialAsJson(material, stream); + } #endif #if defined(DUMP_AS_GDT) && DUMP_AS_GDT == 1 - { - std::ostringstream ss; - ss << "materials/" << asset->m_name << ".gdt"; - const auto assetFile = context.OpenAssetFile(ss.str()); - if (!assetFile) - return; - auto& stream = *assetFile; - MaterialGdtDumper dumper(material); - Gdt gdt(GdtVersion("IW4", 1)); - gdt.m_entries.emplace_back(std::make_unique<GdtEntry>(std::move(dumper.CreateGdtEntry()))); - GdtOutputStream::WriteGdt(gdt, stream); - } + { + std::ostringstream ss; + ss << "materials/" << asset->m_name << ".gdt"; + const auto assetFile = context.OpenAssetFile(ss.str()); + if (!assetFile) + return; + auto &stream = *assetFile; + MaterialGdtDumper dumper(material); + Gdt gdt(GdtVersion("IW4", 1)); + gdt.m_entries.emplace_back(std::make_unique<GdtEntry>(std::move(dumper.CreateGdtEntry()))); + GdtOutputStream::WriteGdt(gdt, stream); + } #endif - if (context.m_gdt) - { - MaterialGdtDumper dumper(material); - context.m_gdt->WriteEntry(dumper.CreateGdtEntry()); - } + if (context.m_gdt) { + MaterialGdtDumper dumper(material); + context.m_gdt->WriteEntry(dumper.CreateGdtEntry()); + } } diff --git a/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperMaterial.h b/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperMaterial.h index 330d33cda..fbbd85616 100644 --- a/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperMaterial.h +++ b/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperMaterial.h @@ -3,12 +3,10 @@ #include "Dumping/AbstractAssetDumper.h" #include "Game/IW4/IW4.h" -namespace IW4 -{ - class AssetDumperMaterial final : public AbstractAssetDumper<Material> - { - protected: - bool ShouldDump(XAssetInfo<Material>* asset) override; - void DumpAsset(AssetDumpingContext& context, XAssetInfo<Material>* asset) override; - }; -} +namespace IW4 { +class AssetDumperMaterial final : public AbstractAssetDumper<Material> { +protected: + bool ShouldDump(XAssetInfo<Material> *asset) override; + void DumpAsset(AssetDumpingContext &context, XAssetInfo<Material> *asset) override; +}; +} // namespace IW4 diff --git a/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperMenuDef.cpp b/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperMenuDef.cpp index ce642791e..2ac75622c 100644 --- a/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperMenuDef.cpp +++ b/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperMenuDef.cpp @@ -4,50 +4,44 @@ #include <string> #include "AssetDumperMenuList.h" -#include "ObjWriting.h" #include "Game/IW4/GameAssetPoolIW4.h" #include "Game/IW4/Menu/MenuDumperIW4.h" #include "Menu/AbstractMenuDumper.h" +#include "ObjWriting.h" using namespace IW4; -std::string AssetDumperMenuDef::GetPathForMenu(menu::MenuDumpingZoneState* zoneState, XAssetInfo<menuDef_t>* asset) -{ - const auto menuDumpingState = zoneState->m_menu_dumping_state_map.find(asset->Asset()); +std::string AssetDumperMenuDef::GetPathForMenu(menu::MenuDumpingZoneState *zoneState, XAssetInfo<menuDef_t> *asset) { + const auto menuDumpingState = zoneState->m_menu_dumping_state_map.find(asset->Asset()); - if (menuDumpingState == zoneState->m_menu_dumping_state_map.end()) - return "ui_mp/" + std::string(asset->Asset()->window.name) + ".menu"; + if (menuDumpingState == zoneState->m_menu_dumping_state_map.end()) + return "ui_mp/" + std::string(asset->Asset()->window.name) + ".menu"; - return menuDumpingState->second.m_path; + return menuDumpingState->second.m_path; } -bool AssetDumperMenuDef::ShouldDump(XAssetInfo<menuDef_t>* asset) -{ - return true; -} +bool AssetDumperMenuDef::ShouldDump(XAssetInfo<menuDef_t> *asset) { return true; } -void AssetDumperMenuDef::DumpAsset(AssetDumpingContext& context, XAssetInfo<menuDef_t>* asset) -{ - const auto* menu = asset->Asset(); - auto* zoneState = context.GetZoneAssetDumperState<menu::MenuDumpingZoneState>(); +void AssetDumperMenuDef::DumpAsset(AssetDumpingContext &context, XAssetInfo<menuDef_t> *asset) { + const auto *menu = asset->Asset(); + auto *zoneState = context.GetZoneAssetDumperState<menu::MenuDumpingZoneState>(); - if(!ObjWriting::ShouldHandleAssetType(ASSET_TYPE_MENULIST)) - { - // Make sure menu paths based on menu lists are created - const auto* gameAssetPool = dynamic_cast<GameAssetPoolIW4*>(asset->m_zone->m_pools.get()); - for (auto* menuListAsset : *gameAssetPool->m_menu_list) - AssetDumperMenuList::CreateDumpingStateForMenuList(zoneState, menuListAsset->Asset()); - } + if (!ObjWriting::ShouldHandleAssetType(ASSET_TYPE_MENULIST)) { + // Make sure menu paths based on menu lists are created + const auto *gameAssetPool = dynamic_cast<GameAssetPoolIW4 *>(asset->m_zone->m_pools.get()); + for (auto *menuListAsset : *gameAssetPool->m_menu_list) + AssetDumperMenuList::CreateDumpingStateForMenuList(zoneState, menuListAsset->Asset()); + } - const auto menuFilePath = GetPathForMenu(zoneState, asset); - const auto assetFile = context.OpenAssetFile(menuFilePath); + const auto menuFilePath = GetPathForMenu(zoneState, asset); + const auto assetFile = context.OpenAssetFile(menuFilePath); - if (!assetFile) - return; + if (!assetFile) + return; - MenuDumper menuDumper(*assetFile); + MenuDumper menuDumper(*assetFile); - menuDumper.Start(); - menuDumper.WriteMenu(menu); - menuDumper.End(); + menuDumper.Start(); + menuDumper.WriteMenu(menu); + menuDumper.End(); } diff --git a/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperMenuDef.h b/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperMenuDef.h index 3fa4a8d2a..bb4c1e4ec 100644 --- a/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperMenuDef.h +++ b/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperMenuDef.h @@ -4,14 +4,12 @@ #include "Game/IW4/IW4.h" #include "Menu/MenuDumpingZoneState.h" -namespace IW4 -{ - class AssetDumperMenuDef final : public AbstractAssetDumper<menuDef_t> - { - static std::string GetPathForMenu(menu::MenuDumpingZoneState* zoneState, XAssetInfo<menuDef_t>* asset); +namespace IW4 { +class AssetDumperMenuDef final : public AbstractAssetDumper<menuDef_t> { + static std::string GetPathForMenu(menu::MenuDumpingZoneState *zoneState, XAssetInfo<menuDef_t> *asset); - protected: - bool ShouldDump(XAssetInfo<menuDef_t>* asset) override; - void DumpAsset(AssetDumpingContext& context, XAssetInfo<menuDef_t>* asset) override; - }; -} +protected: + bool ShouldDump(XAssetInfo<menuDef_t> *asset) override; + void DumpAsset(AssetDumpingContext &context, XAssetInfo<menuDef_t> *asset) override; +}; +} // namespace IW4 diff --git a/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperMenuList.cpp b/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperMenuList.cpp index 86c112d7a..f9bdc0b64 100644 --- a/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperMenuList.cpp +++ b/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperMenuList.cpp @@ -2,178 +2,157 @@ #include <cassert> #include <filesystem> -#include <sstream> #include <set> +#include <sstream> -#include "ObjWriting.h" #include "Game/IW4/Menu/MenuDumperIW4.h" #include "Menu/AbstractMenuDumper.h" +#include "ObjWriting.h" namespace fs = std::filesystem; using namespace IW4; -std::vector<const ExpressionSupportingData*> AssetDumperMenuList::GetAllUniqueExpressionSupportingData(const MenuList* menuList) -{ - std::vector<const ExpressionSupportingData*> result; - std::set<const ExpressionSupportingData*> alreadyAddedSupportingData; +std::vector<const ExpressionSupportingData *> AssetDumperMenuList::GetAllUniqueExpressionSupportingData(const MenuList *menuList) { + std::vector<const ExpressionSupportingData *> result; + std::set<const ExpressionSupportingData *> alreadyAddedSupportingData; - if (menuList->menus == nullptr) - return result; + if (menuList->menus == nullptr) + return result; - for(auto i = 0; i < menuList->menuCount; i++) - { - if(menuList->menus[i] == nullptr) - continue; + for (auto i = 0; i < menuList->menuCount; i++) { + if (menuList->menus[i] == nullptr) + continue; - const auto* menu = menuList->menus[i]; + const auto *menu = menuList->menus[i]; - if(menu->expressionData == nullptr) - continue; + if (menu->expressionData == nullptr) + continue; - if(alreadyAddedSupportingData.find(menu->expressionData) == alreadyAddedSupportingData.end()) - { - result.push_back(menu->expressionData); - alreadyAddedSupportingData.emplace(menu->expressionData); - } + if (alreadyAddedSupportingData.find(menu->expressionData) == alreadyAddedSupportingData.end()) { + result.push_back(menu->expressionData); + alreadyAddedSupportingData.emplace(menu->expressionData); } + } - return result; + return result; } -void AssetDumperMenuList::DumpFunctions(MenuDumper& menuDumper, const MenuList* menuList) -{ - const auto allSupportingData = GetAllUniqueExpressionSupportingData(menuList); - auto functionIndex = 0u; +void AssetDumperMenuList::DumpFunctions(MenuDumper &menuDumper, const MenuList *menuList) { + const auto allSupportingData = GetAllUniqueExpressionSupportingData(menuList); + auto functionIndex = 0u; - assert(allSupportingData.size() <= 1); + assert(allSupportingData.size() <= 1); - for (const auto* supportingData : allSupportingData) - { - if (supportingData->uifunctions.functions == nullptr) - continue; + for (const auto *supportingData : allSupportingData) { + if (supportingData->uifunctions.functions == nullptr) + continue; - for(auto i = 0; i < supportingData->uifunctions.totalFunctions; i++) - { - const auto* function = supportingData->uifunctions.functions[i]; - if(function != nullptr) - { - std::stringstream ss; - ss << "FUNC_" << functionIndex; + for (auto i = 0; i < supportingData->uifunctions.totalFunctions; i++) { + const auto *function = supportingData->uifunctions.functions[i]; + if (function != nullptr) { + std::stringstream ss; + ss << "FUNC_" << functionIndex; - menuDumper.WriteFunctionDef(ss.str(), function); - } + menuDumper.WriteFunctionDef(ss.str(), function); + } - functionIndex++; - } + functionIndex++; } + } } -void AssetDumperMenuList::DumpMenus(MenuDumper& menuDumper, menu::MenuDumpingZoneState* zoneState, const MenuList* menuList) -{ - for (auto menuNum = 0; menuNum < menuList->menuCount; menuNum++) - { - const auto* menu = menuList->menus[menuNum]; - - const auto menuDumpingState = zoneState->m_menu_dumping_state_map.find(menu); - if(menuDumpingState == zoneState->m_menu_dumping_state_map.end()) - continue; - - // If the menu was embedded directly as menu list write its data in the menu list file - if (menuDumpingState->second.m_alias_menu_list == menuList) - menuDumper.WriteMenu(menu); - else - menuDumper.IncludeMenu(menuDumpingState->second.m_path); - } -} +void AssetDumperMenuList::DumpMenus(MenuDumper &menuDumper, menu::MenuDumpingZoneState *zoneState, const MenuList *menuList) { + for (auto menuNum = 0; menuNum < menuList->menuCount; menuNum++) { + const auto *menu = menuList->menus[menuNum]; -bool AssetDumperMenuList::ShouldDump(XAssetInfo<MenuList>* asset) -{ - return true; + const auto menuDumpingState = zoneState->m_menu_dumping_state_map.find(menu); + if (menuDumpingState == zoneState->m_menu_dumping_state_map.end()) + continue; + + // If the menu was embedded directly as menu list write its data in the menu list file + if (menuDumpingState->second.m_alias_menu_list == menuList) + menuDumper.WriteMenu(menu); + else + menuDumper.IncludeMenu(menuDumpingState->second.m_path); + } } -void AssetDumperMenuList::DumpAsset(AssetDumpingContext& context, XAssetInfo<MenuList>* asset) -{ - const auto* menuList = asset->Asset(); - const auto assetFile = context.OpenAssetFile(asset->m_name); +bool AssetDumperMenuList::ShouldDump(XAssetInfo<MenuList> *asset) { return true; } + +void AssetDumperMenuList::DumpAsset(AssetDumpingContext &context, XAssetInfo<MenuList> *asset) { + const auto *menuList = asset->Asset(); + const auto assetFile = context.OpenAssetFile(asset->m_name); - if (!assetFile) - return; + if (!assetFile) + return; - auto* zoneState = context.GetZoneAssetDumperState<menu::MenuDumpingZoneState>(); + auto *zoneState = context.GetZoneAssetDumperState<menu::MenuDumpingZoneState>(); - MenuDumper menuDumper(*assetFile); + MenuDumper menuDumper(*assetFile); - menuDumper.Start(); + menuDumper.Start(); - if(!ObjWriting::Configuration.MenuLegacyMode) - DumpFunctions(menuDumper, menuList); + if (!ObjWriting::Configuration.MenuLegacyMode) + DumpFunctions(menuDumper, menuList); - DumpMenus(menuDumper, zoneState, menuList); + DumpMenus(menuDumper, zoneState, menuList); - menuDumper.End(); + menuDumper.End(); } -std::string AssetDumperMenuList::PathForMenu(const std::string& menuListParentPath, const menuDef_t* menu) -{ - const auto* menuAssetName = menu->window.name; +std::string AssetDumperMenuList::PathForMenu(const std::string &menuListParentPath, const menuDef_t *menu) { + const auto *menuAssetName = menu->window.name; - if (!menuAssetName) - return ""; + if (!menuAssetName) + return ""; - if (menuAssetName[0] == ',') - menuAssetName = &menuAssetName[1]; + if (menuAssetName[0] == ',') + menuAssetName = &menuAssetName[1]; - std::ostringstream ss; - ss << menuListParentPath << menuAssetName << ".menu"; + std::ostringstream ss; + ss << menuListParentPath << menuAssetName << ".menu"; - return ss.str(); + return ss.str(); } -void AssetDumperMenuList::CreateDumpingStateForMenuList(menu::MenuDumpingZoneState* zoneState, const MenuList* menuList) -{ - if (menuList->menuCount <= 0 || menuList->menus == nullptr || menuList->name == nullptr) - return; - - const std::string menuListName(menuList->name); - const fs::path p(menuListName); - std::string parentPath; - if (p.has_parent_path()) - parentPath = p.parent_path().string() + "/"; - - for(auto i = 0; i < menuList->menuCount; i++) - { - auto* menu = menuList->menus[i]; - - if(menu == nullptr) - continue; - - auto existingState = zoneState->m_menu_dumping_state_map.find(menu); - if(existingState == zoneState->m_menu_dumping_state_map.end()) - { - auto menuPath = PathForMenu(parentPath, menu); - const auto isTheSameAsMenuList = menuPath == menuListName; - zoneState->CreateMenuDumpingState(menu, std::move(menuPath), isTheSameAsMenuList ? menuList : nullptr); - } - else if(existingState->second.m_alias_menu_list == nullptr) - { - auto menuPath = PathForMenu(parentPath, menu); - const auto isTheSameAsMenuList = menuPath == menuListName; - if (isTheSameAsMenuList) - { - existingState->second.m_alias_menu_list = menuList; - existingState->second.m_path = std::move(menuPath); - } - } +void AssetDumperMenuList::CreateDumpingStateForMenuList(menu::MenuDumpingZoneState *zoneState, const MenuList *menuList) { + if (menuList->menuCount <= 0 || menuList->menus == nullptr || menuList->name == nullptr) + return; + + const std::string menuListName(menuList->name); + const fs::path p(menuListName); + std::string parentPath; + if (p.has_parent_path()) + parentPath = p.parent_path().string() + "/"; + + for (auto i = 0; i < menuList->menuCount; i++) { + auto *menu = menuList->menus[i]; + + if (menu == nullptr) + continue; + + auto existingState = zoneState->m_menu_dumping_state_map.find(menu); + if (existingState == zoneState->m_menu_dumping_state_map.end()) { + auto menuPath = PathForMenu(parentPath, menu); + const auto isTheSameAsMenuList = menuPath == menuListName; + zoneState->CreateMenuDumpingState(menu, std::move(menuPath), isTheSameAsMenuList ? menuList : nullptr); + } else if (existingState->second.m_alias_menu_list == nullptr) { + auto menuPath = PathForMenu(parentPath, menu); + const auto isTheSameAsMenuList = menuPath == menuListName; + if (isTheSameAsMenuList) { + existingState->second.m_alias_menu_list = menuList; + existingState->second.m_path = std::move(menuPath); + } } + } } -void AssetDumperMenuList::DumpPool(AssetDumpingContext& context, AssetPool<MenuList>* pool) -{ - auto* zoneState = context.GetZoneAssetDumperState<menu::MenuDumpingZoneState>(); +void AssetDumperMenuList::DumpPool(AssetDumpingContext &context, AssetPool<MenuList> *pool) { + auto *zoneState = context.GetZoneAssetDumperState<menu::MenuDumpingZoneState>(); - for(auto* asset : *pool) - CreateDumpingStateForMenuList(zoneState, asset->Asset()); + for (auto *asset : *pool) + CreateDumpingStateForMenuList(zoneState, asset->Asset()); - AbstractAssetDumper<MenuList>::DumpPool(context, pool); + AbstractAssetDumper<MenuList>::DumpPool(context, pool); } diff --git a/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperMenuList.h b/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperMenuList.h index eb75e852a..404e6cc7f 100644 --- a/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperMenuList.h +++ b/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperMenuList.h @@ -5,23 +5,21 @@ #include "Game/IW4/Menu/MenuDumperIW4.h" #include "Menu/MenuDumpingZoneState.h" -namespace IW4 -{ - class AssetDumperMenuList final : public AbstractAssetDumper<MenuList> - { - static std::vector<const ExpressionSupportingData*> GetAllUniqueExpressionSupportingData(const MenuList* menuList); +namespace IW4 { +class AssetDumperMenuList final : public AbstractAssetDumper<MenuList> { + static std::vector<const ExpressionSupportingData *> GetAllUniqueExpressionSupportingData(const MenuList *menuList); - static void DumpFunctions(MenuDumper& menuDumper, const MenuList* menuList); - static void DumpMenus(MenuDumper& menuDumper, menu::MenuDumpingZoneState* zoneState, const MenuList* menuList); + static void DumpFunctions(MenuDumper &menuDumper, const MenuList *menuList); + static void DumpMenus(MenuDumper &menuDumper, menu::MenuDumpingZoneState *zoneState, const MenuList *menuList); - static std::string PathForMenu(const std::string& menuListParentPath, const menuDef_t* menu); + static std::string PathForMenu(const std::string &menuListParentPath, const menuDef_t *menu); - protected: - bool ShouldDump(XAssetInfo<MenuList>* asset) override; - void DumpAsset(AssetDumpingContext& context, XAssetInfo<MenuList>* asset) override; +protected: + bool ShouldDump(XAssetInfo<MenuList> *asset) override; + void DumpAsset(AssetDumpingContext &context, XAssetInfo<MenuList> *asset) override; - public: - static void CreateDumpingStateForMenuList(menu::MenuDumpingZoneState* zoneState, const MenuList* menuList); - void DumpPool(AssetDumpingContext& context, AssetPool<MenuList>* pool) override; - }; -} +public: + static void CreateDumpingStateForMenuList(menu::MenuDumpingZoneState *zoneState, const MenuList *menuList); + void DumpPool(AssetDumpingContext &context, AssetPool<MenuList> *pool) override; +}; +} // namespace IW4 diff --git a/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperPhysCollmap.cpp b/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperPhysCollmap.cpp index 314ca79a7..7a6c8cc4d 100644 --- a/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperPhysCollmap.cpp +++ b/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperPhysCollmap.cpp @@ -7,81 +7,74 @@ using namespace IW4; -std::string AssetDumperPhysCollmap::GetAssetFilename(const std::string& assetName) -{ - std::ostringstream ss; +std::string AssetDumperPhysCollmap::GetAssetFilename(const std::string &assetName) { + std::ostringstream ss; - ss << "phys_collmaps/" << assetName << ".map"; + ss << "phys_collmaps/" << assetName << ".map"; - return ss.str(); + return ss.str(); } -bool AssetDumperPhysCollmap::ShouldDump(XAssetInfo<PhysCollmap>* asset) -{ - return true; -} - -void AssetDumperPhysCollmap::DumpAsset(AssetDumpingContext& context, XAssetInfo<PhysCollmap>* asset) -{ - const auto* physCollmap = asset->Asset(); - const auto assetFile = context.OpenAssetFile(GetAssetFilename(asset->m_name)); - - if (!assetFile) - return; - - MapFileDumper mapFileDumper(*assetFile); - mapFileDumper.Init(); - - if (physCollmap->count <= 0 || physCollmap->geoms == nullptr) - return; - - mapFileDumper.BeginEntity(); - - mapFileDumper.WriteKeyValue("classname", "worldspawn"); - - for (auto i = 0u; i < physCollmap->count; i++) - { - const auto& geom = physCollmap->geoms[i]; - mapFileDumper.BeginBrush(); - - switch (geom.type) - { - case PHYS_GEOM_NONE: - // TODO: Dump BrushWrapper (probably GJK related) - mapFileDumper.WriteComment("TODO: Brush data"); - break; - case PHYS_GEOM_BOX: - mapFileDumper.WritePhysicsBox({ - {geom.bounds.midPoint[0], geom.bounds.midPoint[1], geom.bounds.midPoint[2]}, - {geom.bounds.halfSize[0], geom.bounds.halfSize[1], geom.bounds.halfSize[2]}, - {geom.orientation[0][0], geom.orientation[0][1], geom.orientation[0][2]}, - {geom.orientation[1][0], geom.orientation[1][1], geom.orientation[1][2]}, - {geom.orientation[2][0], geom.orientation[2][1], geom.orientation[2][2]} - }); - break; - - case PHYS_GEOM_CYLINDER: - mapFileDumper.WritePhysicsCylinder({ - {geom.bounds.midPoint[0], geom.bounds.midPoint[1], geom.bounds.midPoint[2]}, - geom.bounds.halfSize[0], - geom.bounds.halfSize[2] * 2, - {geom.orientation[0][0], geom.orientation[0][1], geom.orientation[0][2]} - }); - break; - - case PHYS_GEOM_BRUSHMODEL: - case PHYS_GEOM_BRUSH: - case PHYS_GEOM_COLLMAP: - case PHYS_GEOM_CAPSULE: - case PHYS_GEOM_GLASS: - default: - // These do not seem to appear inside any collmap assets - assert(false); - break; - } - - mapFileDumper.EndBrush(); +bool AssetDumperPhysCollmap::ShouldDump(XAssetInfo<PhysCollmap> *asset) { return true; } + +void AssetDumperPhysCollmap::DumpAsset(AssetDumpingContext &context, XAssetInfo<PhysCollmap> *asset) { + const auto *physCollmap = asset->Asset(); + const auto assetFile = context.OpenAssetFile(GetAssetFilename(asset->m_name)); + + if (!assetFile) + return; + + MapFileDumper mapFileDumper(*assetFile); + mapFileDumper.Init(); + + if (physCollmap->count <= 0 || physCollmap->geoms == nullptr) + return; + + mapFileDumper.BeginEntity(); + + mapFileDumper.WriteKeyValue("classname", "worldspawn"); + + for (auto i = 0u; i < physCollmap->count; i++) { + const auto &geom = physCollmap->geoms[i]; + mapFileDumper.BeginBrush(); + + switch (geom.type) { + case PHYS_GEOM_NONE: + // TODO: Dump BrushWrapper (probably GJK related) + mapFileDumper.WriteComment("TODO: Brush data"); + break; + case PHYS_GEOM_BOX: + mapFileDumper.WritePhysicsBox({ + {geom.bounds.midPoint[0], geom.bounds.midPoint[1], geom.bounds.midPoint[2]}, + {geom.bounds.halfSize[0], geom.bounds.halfSize[1], geom.bounds.halfSize[2]}, + {geom.orientation[0][0], geom.orientation[0][1], geom.orientation[0][2] }, + {geom.orientation[1][0], geom.orientation[1][1], geom.orientation[1][2] }, + {geom.orientation[2][0], geom.orientation[2][1], geom.orientation[2][2] } + }); + break; + + case PHYS_GEOM_CYLINDER: + mapFileDumper.WritePhysicsCylinder({ + {geom.bounds.midPoint[0], geom.bounds.midPoint[1], geom.bounds.midPoint[2]}, + geom.bounds.halfSize[0], + geom.bounds.halfSize[2] * 2, + {geom.orientation[0][0], geom.orientation[0][1], geom.orientation[0][2] } + }); + break; + + case PHYS_GEOM_BRUSHMODEL: + case PHYS_GEOM_BRUSH: + case PHYS_GEOM_COLLMAP: + case PHYS_GEOM_CAPSULE: + case PHYS_GEOM_GLASS: + default: + // These do not seem to appear inside any collmap assets + assert(false); + break; } - mapFileDumper.EndEntity(); + mapFileDumper.EndBrush(); + } + + mapFileDumper.EndEntity(); } diff --git a/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperPhysCollmap.h b/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperPhysCollmap.h index 22bde8836..113fe4c53 100644 --- a/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperPhysCollmap.h +++ b/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperPhysCollmap.h @@ -3,14 +3,12 @@ #include "Dumping/AbstractAssetDumper.h" #include "Game/IW4/IW4.h" -namespace IW4 -{ - class AssetDumperPhysCollmap final : public AbstractAssetDumper<PhysCollmap> - { - static std::string GetAssetFilename(const std::string& assetName); +namespace IW4 { +class AssetDumperPhysCollmap final : public AbstractAssetDumper<PhysCollmap> { + static std::string GetAssetFilename(const std::string &assetName); - protected: - bool ShouldDump(XAssetInfo<PhysCollmap>* asset) override; - void DumpAsset(AssetDumpingContext& context, XAssetInfo<PhysCollmap>* asset) override; - }; -} +protected: + bool ShouldDump(XAssetInfo<PhysCollmap> *asset) override; + void DumpAsset(AssetDumpingContext &context, XAssetInfo<PhysCollmap> *asset) override; +}; +} // namespace IW4 diff --git a/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperPhysPreset.cpp b/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperPhysPreset.cpp index c673c1141..592531d4f 100644 --- a/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperPhysPreset.cpp +++ b/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperPhysPreset.cpp @@ -5,97 +5,79 @@ #include <cmath> #include <type_traits> -#include "Game/IW4/ObjConstantsIW4.h" #include "Game/IW4/InfoString/InfoStringFromStructConverter.h" #include "Game/IW4/InfoString/PhysPresetFields.h" +#include "Game/IW4/ObjConstantsIW4.h" using namespace IW4; -namespace IW4 -{ - class InfoStringFromPhysPresetConverter final : public InfoStringFromStructConverter - { - protected: - void FillFromExtensionField(const cspField_t& field) override - { - assert(false); - } - - public: - InfoStringFromPhysPresetConverter(const PhysPresetInfo* structure, const cspField_t* fields, const size_t fieldCount, std::function<std::string(scr_string_t)> scriptStringValueCallback) - : InfoStringFromStructConverter(structure, fields, fieldCount, std::move(scriptStringValueCallback)) - { - } - }; -} - -void AssetDumperPhysPreset::CopyToPhysPresetInfo(const PhysPreset* physPreset, PhysPresetInfo* physPresetInfo) -{ - physPresetInfo->mass = std::clamp(physPreset->mass * 1000.0f, 1.0f, 2000.0f); - physPresetInfo->bounce = physPreset->bounce; - - if (std::isinf(physPreset->friction)) - { - physPresetInfo->isFrictionInfinity = 1; - physPresetInfo->friction = 0; - } - else - { - physPresetInfo->isFrictionInfinity = 0; - physPresetInfo->friction = physPreset->friction; - } - - physPresetInfo->bulletForceScale = physPreset->bulletForceScale; - physPresetInfo->explosiveForceScale = physPreset->explosiveForceScale; - physPresetInfo->sndAliasPrefix = physPreset->sndAliasPrefix; - physPresetInfo->piecesSpreadFraction = physPreset->piecesSpreadFraction; - physPresetInfo->piecesUpwardVelocity = physPreset->piecesUpwardVelocity; - physPresetInfo->tempDefaultToCylinder = physPreset->tempDefaultToCylinder ? 1 : 0; - physPresetInfo->perSurfaceSndAlias = physPreset->perSurfaceSndAlias ? 1 : 0; +namespace IW4 { +class InfoStringFromPhysPresetConverter final : public InfoStringFromStructConverter { +protected: + void FillFromExtensionField(const cspField_t &field) override { assert(false); } + +public: + InfoStringFromPhysPresetConverter(const PhysPresetInfo *structure, const cspField_t *fields, const size_t fieldCount, + std::function<std::string(scr_string_t)> scriptStringValueCallback) + : InfoStringFromStructConverter(structure, fields, fieldCount, std::move(scriptStringValueCallback)) {} +}; +} // namespace IW4 + +void AssetDumperPhysPreset::CopyToPhysPresetInfo(const PhysPreset *physPreset, PhysPresetInfo *physPresetInfo) { + physPresetInfo->mass = std::clamp(physPreset->mass * 1000.0f, 1.0f, 2000.0f); + physPresetInfo->bounce = physPreset->bounce; + + if (std::isinf(physPreset->friction)) { + physPresetInfo->isFrictionInfinity = 1; + physPresetInfo->friction = 0; + } else { + physPresetInfo->isFrictionInfinity = 0; + physPresetInfo->friction = physPreset->friction; + } + + physPresetInfo->bulletForceScale = physPreset->bulletForceScale; + physPresetInfo->explosiveForceScale = physPreset->explosiveForceScale; + physPresetInfo->sndAliasPrefix = physPreset->sndAliasPrefix; + physPresetInfo->piecesSpreadFraction = physPreset->piecesSpreadFraction; + physPresetInfo->piecesUpwardVelocity = physPreset->piecesUpwardVelocity; + physPresetInfo->tempDefaultToCylinder = physPreset->tempDefaultToCylinder ? 1 : 0; + physPresetInfo->perSurfaceSndAlias = physPreset->perSurfaceSndAlias ? 1 : 0; } -InfoString AssetDumperPhysPreset::CreateInfoString(XAssetInfo<PhysPreset>* asset) -{ - auto* physPresetInfo = new PhysPresetInfo; - CopyToPhysPresetInfo(asset->Asset(), physPresetInfo); - - InfoStringFromPhysPresetConverter converter(physPresetInfo, phys_preset_fields, std::extent<decltype(phys_preset_fields)>::value, [asset](const scr_string_t scrStr) -> std::string - { - assert(scrStr < asset->m_zone->m_script_strings.Count()); - if (scrStr >= asset->m_zone->m_script_strings.Count()) - return ""; +InfoString AssetDumperPhysPreset::CreateInfoString(XAssetInfo<PhysPreset> *asset) { + auto *physPresetInfo = new PhysPresetInfo; + CopyToPhysPresetInfo(asset->Asset(), physPresetInfo); - return asset->m_zone->m_script_strings[scrStr]; - }); + InfoStringFromPhysPresetConverter converter(physPresetInfo, phys_preset_fields, std::extent<decltype(phys_preset_fields)>::value, + [asset](const scr_string_t scrStr) -> std::string { + assert(scrStr < asset->m_zone->m_script_strings.Count()); + if (scrStr >= asset->m_zone->m_script_strings.Count()) + return ""; - return converter.Convert(); -} + return asset->m_zone->m_script_strings[scrStr]; + }); -bool AssetDumperPhysPreset::ShouldDump(XAssetInfo<PhysPreset>* asset) -{ - return true; + return converter.Convert(); } -void AssetDumperPhysPreset::DumpAsset(AssetDumpingContext& context, XAssetInfo<PhysPreset>* asset) -{ - // Only dump raw when no gdt available - if (context.m_gdt) - { - const auto infoString = CreateInfoString(asset); - GdtEntry gdtEntry(asset->m_name, ObjConstants::GDF_FILENAME_PHYS_PRESET); - infoString.ToGdtProperties(ObjConstants::INFO_STRING_PREFIX_PHYS_PRESET, gdtEntry); - context.m_gdt->WriteEntry(gdtEntry); - } - else - { - const auto assetFile = context.OpenAssetFile("physic/" + asset->m_name); - - if (!assetFile) - return; - - auto& stream = *assetFile; - const auto infoString = CreateInfoString(asset); - const auto stringValue = infoString.ToString(ObjConstants::INFO_STRING_PREFIX_PHYS_PRESET); - stream.write(stringValue.c_str(), stringValue.size()); - } +bool AssetDumperPhysPreset::ShouldDump(XAssetInfo<PhysPreset> *asset) { return true; } + +void AssetDumperPhysPreset::DumpAsset(AssetDumpingContext &context, XAssetInfo<PhysPreset> *asset) { + // Only dump raw when no gdt available + if (context.m_gdt) { + const auto infoString = CreateInfoString(asset); + GdtEntry gdtEntry(asset->m_name, ObjConstants::GDF_FILENAME_PHYS_PRESET); + infoString.ToGdtProperties(ObjConstants::INFO_STRING_PREFIX_PHYS_PRESET, gdtEntry); + context.m_gdt->WriteEntry(gdtEntry); + } else { + const auto assetFile = context.OpenAssetFile("physic/" + asset->m_name); + + if (!assetFile) + return; + + auto &stream = *assetFile; + const auto infoString = CreateInfoString(asset); + const auto stringValue = infoString.ToString(ObjConstants::INFO_STRING_PREFIX_PHYS_PRESET); + stream.write(stringValue.c_str(), stringValue.size()); + } } \ No newline at end of file diff --git a/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperPhysPreset.h b/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperPhysPreset.h index 6db3528e0..840ad7efb 100644 --- a/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperPhysPreset.h +++ b/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperPhysPreset.h @@ -4,15 +4,13 @@ #include "Game/IW4/IW4.h" #include "InfoString/InfoString.h" -namespace IW4 -{ - class AssetDumperPhysPreset final : public AbstractAssetDumper<PhysPreset> - { - static void CopyToPhysPresetInfo(const PhysPreset* physPreset, PhysPresetInfo* physPresetInfo); - static InfoString CreateInfoString(XAssetInfo<PhysPreset>* asset); +namespace IW4 { +class AssetDumperPhysPreset final : public AbstractAssetDumper<PhysPreset> { + static void CopyToPhysPresetInfo(const PhysPreset *physPreset, PhysPresetInfo *physPresetInfo); + static InfoString CreateInfoString(XAssetInfo<PhysPreset> *asset); - protected: - bool ShouldDump(XAssetInfo<PhysPreset>* asset) override; - void DumpAsset(AssetDumpingContext& context, XAssetInfo<PhysPreset>* asset) override; - }; -} +protected: + bool ShouldDump(XAssetInfo<PhysPreset> *asset) override; + void DumpAsset(AssetDumpingContext &context, XAssetInfo<PhysPreset> *asset) override; +}; +} // namespace IW4 diff --git a/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperPixelShader.cpp b/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperPixelShader.cpp index 5062d18c4..286a2cd96 100644 --- a/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperPixelShader.cpp +++ b/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperPixelShader.cpp @@ -4,22 +4,19 @@ using namespace IW4; -bool AssetDumperPixelShader::ShouldDump(XAssetInfo<MaterialPixelShader>* asset) -{ - return true; -} +bool AssetDumperPixelShader::ShouldDump(XAssetInfo<MaterialPixelShader> *asset) { return true; } -void AssetDumperPixelShader::DumpAsset(AssetDumpingContext& context, XAssetInfo<MaterialPixelShader>* asset) -{ - const auto* pixelShader = asset->Asset(); +void AssetDumperPixelShader::DumpAsset(AssetDumpingContext &context, XAssetInfo<MaterialPixelShader> *asset) { + const auto *pixelShader = asset->Asset(); - std::ostringstream ss; - ss << "shader_bin/ps_" << pixelShader->name << ".cso"; + std::ostringstream ss; + ss << "shader_bin/ps_" << pixelShader->name << ".cso"; - const auto shaderFile = context.OpenAssetFile(ss.str()); + const auto shaderFile = context.OpenAssetFile(ss.str()); - if (!shaderFile) - return; + if (!shaderFile) + return; - shaderFile->write(reinterpret_cast<const char*>(pixelShader->prog.loadDef.program), static_cast<std::streamsize>(pixelShader->prog.loadDef.programSize) * 4u); + shaderFile->write(reinterpret_cast<const char *>(pixelShader->prog.loadDef.program), + static_cast<std::streamsize>(pixelShader->prog.loadDef.programSize) * 4u); } diff --git a/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperPixelShader.h b/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperPixelShader.h index a01be4a92..56e8ec0dc 100644 --- a/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperPixelShader.h +++ b/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperPixelShader.h @@ -3,12 +3,10 @@ #include "Dumping/AbstractAssetDumper.h" #include "Game/IW4/IW4.h" -namespace IW4 -{ - class AssetDumperPixelShader final : public AbstractAssetDumper<MaterialPixelShader> - { - protected: - bool ShouldDump(XAssetInfo<MaterialPixelShader>* asset) override; - void DumpAsset(AssetDumpingContext& context, XAssetInfo<MaterialPixelShader>* asset) override; - }; -} +namespace IW4 { +class AssetDumperPixelShader final : public AbstractAssetDumper<MaterialPixelShader> { +protected: + bool ShouldDump(XAssetInfo<MaterialPixelShader> *asset) override; + void DumpAsset(AssetDumpingContext &context, XAssetInfo<MaterialPixelShader> *asset) override; +}; +} // namespace IW4 diff --git a/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperRawFile.cpp b/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperRawFile.cpp index 507d2cfa2..06e4c041e 100644 --- a/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperRawFile.cpp +++ b/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperRawFile.cpp @@ -1,66 +1,56 @@ #include "AssetDumperRawFile.h" -#include <zlib.h> #include <stdexcept> +#include <zlib.h> using namespace IW4; -bool AssetDumperRawFile::ShouldDump(XAssetInfo<RawFile>* asset) -{ - return true; -} - -void AssetDumperRawFile::DumpAsset(AssetDumpingContext& context, XAssetInfo<RawFile>* asset) -{ - const auto* rawFile = asset->Asset(); - const auto assetFile = context.OpenAssetFile(asset->m_name); - - if (!assetFile) - return; +bool AssetDumperRawFile::ShouldDump(XAssetInfo<RawFile> *asset) { return true; } - auto& stream = *assetFile; - if (rawFile->compressedLen > 0) - { - z_stream_s zs{}; +void AssetDumperRawFile::DumpAsset(AssetDumpingContext &context, XAssetInfo<RawFile> *asset) { + const auto *rawFile = asset->Asset(); + const auto assetFile = context.OpenAssetFile(asset->m_name); - zs.zalloc = Z_NULL; - zs.zfree = Z_NULL; - zs.opaque = Z_NULL; - zs.avail_in = 0; - zs.next_in = Z_NULL; + if (!assetFile) + return; - int ret = inflateInit(&zs); + auto &stream = *assetFile; + if (rawFile->compressedLen > 0) { + z_stream_s zs{}; - if (ret != Z_OK) - { - throw std::runtime_error("Initializing inflate failed"); - } + zs.zalloc = Z_NULL; + zs.zfree = Z_NULL; + zs.opaque = Z_NULL; + zs.avail_in = 0; + zs.next_in = Z_NULL; - zs.next_in = reinterpret_cast<const Bytef*>(rawFile->data.compressedBuffer); - zs.avail_in = rawFile->compressedLen; + int ret = inflateInit(&zs); - Bytef buffer[0x1000]; + if (ret != Z_OK) { + throw std::runtime_error("Initializing inflate failed"); + } - while (zs.avail_in > 0) - { - zs.next_out = buffer; - zs.avail_out = sizeof buffer; - ret = inflate(&zs, Z_SYNC_FLUSH); + zs.next_in = reinterpret_cast<const Bytef *>(rawFile->data.compressedBuffer); + zs.avail_in = rawFile->compressedLen; - if (ret < 0) - { - printf("Inflate failed for dumping rawfile '%s'\n", rawFile->name); - inflateEnd(&zs); - return; - } + Bytef buffer[0x1000]; - stream.write(reinterpret_cast<char*>(buffer), sizeof buffer - zs.avail_out); - } + while (zs.avail_in > 0) { + zs.next_out = buffer; + zs.avail_out = sizeof buffer; + ret = inflate(&zs, Z_SYNC_FLUSH); + if (ret < 0) { + printf("Inflate failed for dumping rawfile '%s'\n", rawFile->name); inflateEnd(&zs); + return; + } + + stream.write(reinterpret_cast<char *>(buffer), sizeof buffer - zs.avail_out); } - else if (rawFile->len > 0) - { - stream.write(rawFile->data.buffer, rawFile->len); - } + + inflateEnd(&zs); + } else if (rawFile->len > 0) { + stream.write(rawFile->data.buffer, rawFile->len); + } } diff --git a/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperRawFile.h b/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperRawFile.h index 66a2c000f..181876728 100644 --- a/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperRawFile.h +++ b/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperRawFile.h @@ -3,12 +3,10 @@ #include "Dumping/AbstractAssetDumper.h" #include "Game/IW4/IW4.h" -namespace IW4 -{ - class AssetDumperRawFile final : public AbstractAssetDumper<RawFile> - { - protected: - bool ShouldDump(XAssetInfo<RawFile>* asset) override; - void DumpAsset(AssetDumpingContext& context, XAssetInfo<RawFile>* asset) override; - }; -} +namespace IW4 { +class AssetDumperRawFile final : public AbstractAssetDumper<RawFile> { +protected: + bool ShouldDump(XAssetInfo<RawFile> *asset) override; + void DumpAsset(AssetDumpingContext &context, XAssetInfo<RawFile> *asset) override; +}; +} // namespace IW4 diff --git a/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperSndCurve.cpp b/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperSndCurve.cpp index 988549ecb..b90993499 100644 --- a/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperSndCurve.cpp +++ b/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperSndCurve.cpp @@ -6,34 +6,29 @@ using namespace IW4; -std::string AssetDumperSndCurve::GetAssetFilename(const std::string& assetName) -{ - std::ostringstream ss; +std::string AssetDumperSndCurve::GetAssetFilename(const std::string &assetName) { + std::ostringstream ss; - ss << "soundaliases/" << assetName << ".vfcurve"; + ss << "soundaliases/" << assetName << ".vfcurve"; - return ss.str(); + return ss.str(); } -bool AssetDumperSndCurve::ShouldDump(XAssetInfo<SndCurve>* asset) -{ - return true; -} +bool AssetDumperSndCurve::ShouldDump(XAssetInfo<SndCurve> *asset) { return true; } -void AssetDumperSndCurve::DumpAsset(AssetDumpingContext& context, XAssetInfo<SndCurve>* asset) -{ - const auto* sndCurve = asset->Asset(); +void AssetDumperSndCurve::DumpAsset(AssetDumpingContext &context, XAssetInfo<SndCurve> *asset) { + const auto *sndCurve = asset->Asset(); - const auto assetFile = context.OpenAssetFile(GetAssetFilename(sndCurve->filename)); + const auto assetFile = context.OpenAssetFile(GetAssetFilename(sndCurve->filename)); - if (!assetFile) - return; + if (!assetFile) + return; - SndCurveDumper dumper(*assetFile); + SndCurveDumper dumper(*assetFile); - const auto knotCount = std::min(static_cast<size_t>(sndCurve->knotCount), std::extent_v<decltype(SndCurve::knots)>); - dumper.Init(knotCount); + const auto knotCount = std::min(static_cast<size_t>(sndCurve->knotCount), std::extent_v<decltype(SndCurve::knots)>); + dumper.Init(knotCount); - for (auto i = 0u; i < knotCount; i++) - dumper.WriteKnot(sndCurve->knots[i][0], sndCurve->knots[i][1]); + for (auto i = 0u; i < knotCount; i++) + dumper.WriteKnot(sndCurve->knots[i][0], sndCurve->knots[i][1]); } diff --git a/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperSndCurve.h b/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperSndCurve.h index 6cad3ee74..0dd25b6e8 100644 --- a/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperSndCurve.h +++ b/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperSndCurve.h @@ -3,14 +3,12 @@ #include "Dumping/AbstractAssetDumper.h" #include "Game/IW4/IW4.h" -namespace IW4 -{ - class AssetDumperSndCurve final : public AbstractAssetDumper<SndCurve> - { - static std::string GetAssetFilename(const std::string& assetName); +namespace IW4 { +class AssetDumperSndCurve final : public AbstractAssetDumper<SndCurve> { + static std::string GetAssetFilename(const std::string &assetName); - protected: - bool ShouldDump(XAssetInfo<SndCurve>* asset) override; - void DumpAsset(AssetDumpingContext& context, XAssetInfo<SndCurve>* asset) override; - }; -} +protected: + bool ShouldDump(XAssetInfo<SndCurve> *asset) override; + void DumpAsset(AssetDumpingContext &context, XAssetInfo<SndCurve> *asset) override; +}; +} // namespace IW4 diff --git a/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperStringTable.cpp b/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperStringTable.cpp index cadfd739b..b6127043a 100644 --- a/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperStringTable.cpp +++ b/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperStringTable.cpp @@ -4,29 +4,23 @@ using namespace IW4; -bool AssetDumperStringTable::ShouldDump(XAssetInfo<StringTable>* asset) -{ - return true; -} +bool AssetDumperStringTable::ShouldDump(XAssetInfo<StringTable> *asset) { return true; } + +void AssetDumperStringTable::DumpAsset(AssetDumpingContext &context, XAssetInfo<StringTable> *asset) { + const auto *stringTable = asset->Asset(); + const auto assetFile = context.OpenAssetFile(asset->m_name); + + if (!assetFile) + return; -void AssetDumperStringTable::DumpAsset(AssetDumpingContext& context, XAssetInfo<StringTable>* asset) -{ - const auto* stringTable = asset->Asset(); - const auto assetFile = context.OpenAssetFile(asset->m_name); - - if (!assetFile) - return; - - CsvOutputStream csv(*assetFile); - - for (auto row = 0; row < stringTable->rowCount; row++) - { - for (auto column = 0; column < stringTable->columnCount; column++) - { - const auto* cell = &stringTable->values[column + row * stringTable->columnCount]; - csv.WriteColumn(cell->string); - } - - csv.NextRow(); + CsvOutputStream csv(*assetFile); + + for (auto row = 0; row < stringTable->rowCount; row++) { + for (auto column = 0; column < stringTable->columnCount; column++) { + const auto *cell = &stringTable->values[column + row * stringTable->columnCount]; + csv.WriteColumn(cell->string); } + + csv.NextRow(); + } } diff --git a/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperStringTable.h b/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperStringTable.h index 0194b747d..ebba57406 100644 --- a/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperStringTable.h +++ b/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperStringTable.h @@ -3,12 +3,10 @@ #include "Dumping/AbstractAssetDumper.h" #include "Game/IW4/IW4.h" -namespace IW4 -{ - class AssetDumperStringTable final : public AbstractAssetDumper<StringTable> - { - protected: - bool ShouldDump(XAssetInfo<StringTable>* asset) override; - void DumpAsset(AssetDumpingContext& context, XAssetInfo<StringTable>* asset) override; - }; -} +namespace IW4 { +class AssetDumperStringTable final : public AbstractAssetDumper<StringTable> { +protected: + bool ShouldDump(XAssetInfo<StringTable> *asset) override; + void DumpAsset(AssetDumpingContext &context, XAssetInfo<StringTable> *asset) override; +}; +} // namespace IW4 diff --git a/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperStructuredDataDefSet.cpp b/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperStructuredDataDefSet.cpp index ea98bde8f..07121df82 100644 --- a/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperStructuredDataDefSet.cpp +++ b/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperStructuredDataDefSet.cpp @@ -1,198 +1,181 @@ #include "AssetDumperStructuredDataDefSet.h" +#include <algorithm> #include <cassert> #include <sstream> -#include <algorithm> #include "StructuredDataDef/StructuredDataDefDumper.h" using namespace IW4; using namespace std::string_literals; -CommonStructuredDataType AssetDumperStructuredDataDefSet::ConvertType(const CommonStructuredDataDef* def, const StructuredDataType in) -{ - CommonStructuredDataType out; - - switch (in.type) - { - case DATA_INT: - out.m_category = CommonStructuredDataTypeCategory::INT; - break; - case DATA_BYTE: - out.m_category = CommonStructuredDataTypeCategory::BYTE; - break; - case DATA_BOOL: - out.m_category = CommonStructuredDataTypeCategory::BOOL; - break; - case DATA_FLOAT: - out.m_category = CommonStructuredDataTypeCategory::FLOAT; - break; - case DATA_SHORT: - out.m_category = CommonStructuredDataTypeCategory::SHORT; - break; - case DATA_STRING: - out.m_category = CommonStructuredDataTypeCategory::STRING; - out.m_info.string_length = in.u.stringDataLength; - break; - case DATA_ENUM: - assert(!def->m_enums.empty()); - out.m_category = CommonStructuredDataTypeCategory::ENUM; - out.m_info.type_index = std::max(std::min(static_cast<size_t>(in.u.enumIndex), def->m_enums.size() - 1u), 0u); - break; - case DATA_STRUCT: - assert(!def->m_structs.empty()); - out.m_category = CommonStructuredDataTypeCategory::STRUCT; - out.m_info.type_index = std::max(std::min(static_cast<size_t>(in.u.structIndex), def->m_structs.size() - 1u), 0u); - break; - case DATA_INDEXED_ARRAY: - assert(!def->m_indexed_arrays.empty()); - out.m_category = CommonStructuredDataTypeCategory::INDEXED_ARRAY; - out.m_info.type_index = std::max(std::min(static_cast<size_t>(in.u.indexedArrayIndex), def->m_indexed_arrays.size() - 1u), 0u); - break; - case DATA_ENUM_ARRAY: - assert(!def->m_enumed_arrays.empty()); - out.m_category = CommonStructuredDataTypeCategory::ENUM_ARRAY; - out.m_info.type_index = std::max(std::min(static_cast<size_t>(in.u.enumedArrayIndex), def->m_enumed_arrays.size() - 1u), 0u); - break; - case DATA_COUNT: - default: - assert(false); - break; - } - - return out; +CommonStructuredDataType AssetDumperStructuredDataDefSet::ConvertType(const CommonStructuredDataDef *def, const StructuredDataType in) { + CommonStructuredDataType out; + + switch (in.type) { + case DATA_INT: + out.m_category = CommonStructuredDataTypeCategory::INT; + break; + case DATA_BYTE: + out.m_category = CommonStructuredDataTypeCategory::BYTE; + break; + case DATA_BOOL: + out.m_category = CommonStructuredDataTypeCategory::BOOL; + break; + case DATA_FLOAT: + out.m_category = CommonStructuredDataTypeCategory::FLOAT; + break; + case DATA_SHORT: + out.m_category = CommonStructuredDataTypeCategory::SHORT; + break; + case DATA_STRING: + out.m_category = CommonStructuredDataTypeCategory::STRING; + out.m_info.string_length = in.u.stringDataLength; + break; + case DATA_ENUM: + assert(!def->m_enums.empty()); + out.m_category = CommonStructuredDataTypeCategory::ENUM; + out.m_info.type_index = std::max(std::min(static_cast<size_t>(in.u.enumIndex), def->m_enums.size() - 1u), 0u); + break; + case DATA_STRUCT: + assert(!def->m_structs.empty()); + out.m_category = CommonStructuredDataTypeCategory::STRUCT; + out.m_info.type_index = std::max(std::min(static_cast<size_t>(in.u.structIndex), def->m_structs.size() - 1u), 0u); + break; + case DATA_INDEXED_ARRAY: + assert(!def->m_indexed_arrays.empty()); + out.m_category = CommonStructuredDataTypeCategory::INDEXED_ARRAY; + out.m_info.type_index = std::max(std::min(static_cast<size_t>(in.u.indexedArrayIndex), def->m_indexed_arrays.size() - 1u), 0u); + break; + case DATA_ENUM_ARRAY: + assert(!def->m_enumed_arrays.empty()); + out.m_category = CommonStructuredDataTypeCategory::ENUM_ARRAY; + out.m_info.type_index = std::max(std::min(static_cast<size_t>(in.u.enumedArrayIndex), def->m_enumed_arrays.size() - 1u), 0u); + break; + case DATA_COUNT: + default: + assert(false); + break; + } + + return out; } -void AssetDumperStructuredDataDefSet::ConvertEnum(CommonStructuredDataEnum* out, const StructuredDataEnum* in, const size_t enumIndex) -{ - out->m_name = "ENUM_" + std::to_string(enumIndex); +void AssetDumperStructuredDataDefSet::ConvertEnum(CommonStructuredDataEnum *out, const StructuredDataEnum *in, const size_t enumIndex) { + out->m_name = "ENUM_" + std::to_string(enumIndex); - if (in->reservedEntryCount > 0 && in->reservedEntryCount != in->entryCount) - out->m_reserved_entry_count = std::max(in->reservedEntryCount, 0); - else - out->m_reserved_entry_count = -1; + if (in->reservedEntryCount > 0 && in->reservedEntryCount != in->entryCount) + out->m_reserved_entry_count = std::max(in->reservedEntryCount, 0); + else + out->m_reserved_entry_count = -1; - out->m_entries.resize(static_cast<size_t>(std::max(in->entryCount, 0))); - for(auto i = 0u; i < out->m_entries.size(); i++) - { - auto& outEntry = out->m_entries[i]; - const auto& inEntry = in->entries[i]; + out->m_entries.resize(static_cast<size_t>(std::max(in->entryCount, 0))); + for (auto i = 0u; i < out->m_entries.size(); i++) { + auto &outEntry = out->m_entries[i]; + const auto &inEntry = in->entries[i]; - outEntry.m_name = std::string(inEntry.string); - outEntry.m_value = inEntry.index; - } + outEntry.m_name = std::string(inEntry.string); + outEntry.m_value = inEntry.index; + } - out->SortEntriesByOffset(); + out->SortEntriesByOffset(); } -void AssetDumperStructuredDataDefSet::ConvertStruct(const CommonStructuredDataDef* def, const StructuredDataDef* gameDef, CommonStructuredDataStruct* out, const StructuredDataStruct* in, const size_t structIndex) -{ - if (gameDef->rootType.type == DATA_STRUCT && structIndex == static_cast<size_t>(gameDef->rootType.u.structIndex)) - { - out->m_name = "root"; - out->m_size_in_byte = gameDef->size; - } - else - { - out->m_name = "STRUCT_" + std::to_string(structIndex); - out->m_size_in_byte = static_cast<size_t>(std::max(in->size, 0)); - } +void AssetDumperStructuredDataDefSet::ConvertStruct(const CommonStructuredDataDef *def, const StructuredDataDef *gameDef, CommonStructuredDataStruct *out, + const StructuredDataStruct *in, const size_t structIndex) { + if (gameDef->rootType.type == DATA_STRUCT && structIndex == static_cast<size_t>(gameDef->rootType.u.structIndex)) { + out->m_name = "root"; + out->m_size_in_byte = gameDef->size; + } else { + out->m_name = "STRUCT_" + std::to_string(structIndex); + out->m_size_in_byte = static_cast<size_t>(std::max(in->size, 0)); + } - out->m_bit_offset = in->bitOffset; + out->m_bit_offset = in->bitOffset; - out->m_properties.resize(static_cast<size_t>(std::max(in->propertyCount, 0))); - for (auto i = 0u; i < out->m_properties.size(); i++) - { - auto& outProperty = out->m_properties[i]; - const auto& inProperty = in->properties[i]; + out->m_properties.resize(static_cast<size_t>(std::max(in->propertyCount, 0))); + for (auto i = 0u; i < out->m_properties.size(); i++) { + auto &outProperty = out->m_properties[i]; + const auto &inProperty = in->properties[i]; - outProperty.m_name = std::string(inProperty.name); - outProperty.m_type = ConvertType(def, inProperty.type); + outProperty.m_name = std::string(inProperty.name); + outProperty.m_type = ConvertType(def, inProperty.type); - if (inProperty.type.type == DATA_BOOL) - outProperty.m_offset_in_bits = inProperty.offset; - else - outProperty.m_offset_in_bits = inProperty.offset * 8; - } + if (inProperty.type.type == DATA_BOOL) + outProperty.m_offset_in_bits = inProperty.offset; + else + outProperty.m_offset_in_bits = inProperty.offset * 8; + } - out->SortPropertiesByOffset(); + out->SortPropertiesByOffset(); } -void AssetDumperStructuredDataDefSet::ConvertIndexedArray(const CommonStructuredDataDef* def, CommonStructuredDataIndexedArray* out, const StructuredDataIndexedArray* in) -{ - out->m_element_count = static_cast<size_t>(std::max(in->arraySize, 0)); - out->m_element_size_in_bits = in->elementType.type == DATA_BOOL ? 1 : in->elementSize * 8; - out->m_array_type = ConvertType(def, in->elementType); +void AssetDumperStructuredDataDefSet::ConvertIndexedArray(const CommonStructuredDataDef *def, CommonStructuredDataIndexedArray *out, + const StructuredDataIndexedArray *in) { + out->m_element_count = static_cast<size_t>(std::max(in->arraySize, 0)); + out->m_element_size_in_bits = in->elementType.type == DATA_BOOL ? 1 : in->elementSize * 8; + out->m_array_type = ConvertType(def, in->elementType); } -void AssetDumperStructuredDataDefSet::ConvertEnumedArray(const CommonStructuredDataDef* def, CommonStructuredDataEnumedArray* out, const StructuredDataEnumedArray* in) -{ - assert(!def->m_enums.empty()); - out->m_element_size_in_bits = in->elementType.type == DATA_BOOL ? 1 : in->elementSize * 8; - out->m_array_type = ConvertType(def, in->elementType); - out->m_enum_index = std::max(std::min(static_cast<size_t>(in->enumIndex), def->m_enums.size() - 1u), 0u); +void AssetDumperStructuredDataDefSet::ConvertEnumedArray(const CommonStructuredDataDef *def, CommonStructuredDataEnumedArray *out, + const StructuredDataEnumedArray *in) { + assert(!def->m_enums.empty()); + out->m_element_size_in_bits = in->elementType.type == DATA_BOOL ? 1 : in->elementSize * 8; + out->m_array_type = ConvertType(def, in->elementType); + out->m_enum_index = std::max(std::min(static_cast<size_t>(in->enumIndex), def->m_enums.size() - 1u), 0u); - if (def->m_enums.empty()) - { - assert(false); - return; - } + if (def->m_enums.empty()) { + assert(false); + return; + } - out->m_element_count = def->m_enums[out->m_enum_index]->ElementCount(); + out->m_element_count = def->m_enums[out->m_enum_index]->ElementCount(); } -std::unique_ptr<CommonStructuredDataDef> AssetDumperStructuredDataDefSet::ConvertDef(const StructuredDataDef* in) -{ - auto out = std::make_unique<CommonStructuredDataDef>(); - - out->m_version = in->version; - out->m_checksum = in->formatChecksum; - out->m_size_in_byte = in->size; - - out->m_enums.resize(static_cast<size_t>(std::max(in->enumCount, 0))); - out->m_structs.resize(static_cast<size_t>(std::max(in->structCount, 0))); - out->m_indexed_arrays.resize(static_cast<size_t>(std::max(in->indexedArrayCount, 0))); - out->m_enumed_arrays.resize(static_cast<size_t>(std::max(in->enumedArrayCount, 0))); - - for (auto i = 0u; i < out->m_enums.size(); i++) - { - auto _enum = std::make_unique<CommonStructuredDataEnum>(); - ConvertEnum(_enum.get(), &in->enums[i], i); - out->m_enums[i] = std::move(_enum); - } - for (auto i = 0u; i < out->m_structs.size(); i++) - { - auto _struct = std::make_unique<CommonStructuredDataStruct>(); - ConvertStruct(out.get(), in, _struct.get(), &in->structs[i], i); - out->m_structs[i] = std::move(_struct); - } - for (auto i = 0u; i < out->m_indexed_arrays.size(); i++) - ConvertIndexedArray(out.get(), &out->m_indexed_arrays[i], &in->indexedArrays[i]); - for (auto i = 0u; i < out->m_enumed_arrays.size(); i++) - ConvertEnumedArray(out.get(), &out->m_enumed_arrays[i], &in->enumedArrays[i]); - - out->m_root_type = ConvertType(out.get(), in->rootType); - - return out; +std::unique_ptr<CommonStructuredDataDef> AssetDumperStructuredDataDefSet::ConvertDef(const StructuredDataDef *in) { + auto out = std::make_unique<CommonStructuredDataDef>(); + + out->m_version = in->version; + out->m_checksum = in->formatChecksum; + out->m_size_in_byte = in->size; + + out->m_enums.resize(static_cast<size_t>(std::max(in->enumCount, 0))); + out->m_structs.resize(static_cast<size_t>(std::max(in->structCount, 0))); + out->m_indexed_arrays.resize(static_cast<size_t>(std::max(in->indexedArrayCount, 0))); + out->m_enumed_arrays.resize(static_cast<size_t>(std::max(in->enumedArrayCount, 0))); + + for (auto i = 0u; i < out->m_enums.size(); i++) { + auto _enum = std::make_unique<CommonStructuredDataEnum>(); + ConvertEnum(_enum.get(), &in->enums[i], i); + out->m_enums[i] = std::move(_enum); + } + for (auto i = 0u; i < out->m_structs.size(); i++) { + auto _struct = std::make_unique<CommonStructuredDataStruct>(); + ConvertStruct(out.get(), in, _struct.get(), &in->structs[i], i); + out->m_structs[i] = std::move(_struct); + } + for (auto i = 0u; i < out->m_indexed_arrays.size(); i++) + ConvertIndexedArray(out.get(), &out->m_indexed_arrays[i], &in->indexedArrays[i]); + for (auto i = 0u; i < out->m_enumed_arrays.size(); i++) + ConvertEnumedArray(out.get(), &out->m_enumed_arrays[i], &in->enumedArrays[i]); + + out->m_root_type = ConvertType(out.get(), in->rootType); + + return out; } -bool AssetDumperStructuredDataDefSet::ShouldDump(XAssetInfo<StructuredDataDefSet>* asset) -{ - return true; -} +bool AssetDumperStructuredDataDefSet::ShouldDump(XAssetInfo<StructuredDataDefSet> *asset) { return true; } -void AssetDumperStructuredDataDefSet::DumpAsset(AssetDumpingContext& context, XAssetInfo<StructuredDataDefSet>* asset) -{ - const auto* set = asset->Asset(); - const auto assetFile = context.OpenAssetFile(asset->m_name); +void AssetDumperStructuredDataDefSet::DumpAsset(AssetDumpingContext &context, XAssetInfo<StructuredDataDefSet> *asset) { + const auto *set = asset->Asset(); + const auto assetFile = context.OpenAssetFile(asset->m_name); - if (!assetFile || set->defs == nullptr) - return; + if (!assetFile || set->defs == nullptr) + return; - StructuredDataDefDumper dumper(*assetFile); - for (auto i = 0u; i < set->defCount; i++) - { - const auto def = ConvertDef(&set->defs[i]); - dumper.DumpDef(*def); - } + StructuredDataDefDumper dumper(*assetFile); + for (auto i = 0u; i < set->defCount; i++) { + const auto def = ConvertDef(&set->defs[i]); + dumper.DumpDef(*def); + } } diff --git a/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperStructuredDataDefSet.h b/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperStructuredDataDefSet.h index 703cd9772..84c05b52b 100644 --- a/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperStructuredDataDefSet.h +++ b/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperStructuredDataDefSet.h @@ -6,19 +6,18 @@ #include "Game/IW4/IW4.h" #include "StructuredDataDef/CommonStructuredDataDef.h" -namespace IW4 -{ - class AssetDumperStructuredDataDefSet final : public AbstractAssetDumper<StructuredDataDefSet> - { - static CommonStructuredDataType ConvertType(const CommonStructuredDataDef* def, StructuredDataType in); - static void ConvertEnum(CommonStructuredDataEnum* out, const StructuredDataEnum* in, size_t enumIndex); - static void ConvertStruct(const CommonStructuredDataDef* def, const StructuredDataDef* gameDef, CommonStructuredDataStruct* out, const StructuredDataStruct* in, size_t structIndex); - static void ConvertIndexedArray(const CommonStructuredDataDef* def, CommonStructuredDataIndexedArray* out, const StructuredDataIndexedArray* in); - static void ConvertEnumedArray(const CommonStructuredDataDef* def, CommonStructuredDataEnumedArray* out, const StructuredDataEnumedArray* in); - static std::unique_ptr<CommonStructuredDataDef> ConvertDef(const StructuredDataDef* in); +namespace IW4 { +class AssetDumperStructuredDataDefSet final : public AbstractAssetDumper<StructuredDataDefSet> { + static CommonStructuredDataType ConvertType(const CommonStructuredDataDef *def, StructuredDataType in); + static void ConvertEnum(CommonStructuredDataEnum *out, const StructuredDataEnum *in, size_t enumIndex); + static void ConvertStruct(const CommonStructuredDataDef *def, const StructuredDataDef *gameDef, CommonStructuredDataStruct *out, + const StructuredDataStruct *in, size_t structIndex); + static void ConvertIndexedArray(const CommonStructuredDataDef *def, CommonStructuredDataIndexedArray *out, const StructuredDataIndexedArray *in); + static void ConvertEnumedArray(const CommonStructuredDataDef *def, CommonStructuredDataEnumedArray *out, const StructuredDataEnumedArray *in); + static std::unique_ptr<CommonStructuredDataDef> ConvertDef(const StructuredDataDef *in); - protected: - bool ShouldDump(XAssetInfo<StructuredDataDefSet>* asset) override; - void DumpAsset(AssetDumpingContext& context, XAssetInfo<StructuredDataDefSet>* asset) override; - }; -} +protected: + bool ShouldDump(XAssetInfo<StructuredDataDefSet> *asset) override; + void DumpAsset(AssetDumpingContext &context, XAssetInfo<StructuredDataDefSet> *asset) override; +}; +} // namespace IW4 diff --git a/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperTechniqueSet.cpp b/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperTechniqueSet.cpp index 8e8a3c257..f3ec7d071 100644 --- a/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperTechniqueSet.cpp +++ b/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperTechniqueSet.cpp @@ -12,563 +12,455 @@ using namespace IW4; -namespace IW4 -{ - class TechniqueDumpingZoneState final : public IZoneAssetDumperState - { - std::set<const MaterialTechnique*> m_dumped_techniques; - - public: - bool ShouldDumpTechnique(const MaterialTechnique* technique) - { - if (m_dumped_techniques.find(technique) != m_dumped_techniques.end()) - return false; - - m_dumped_techniques.emplace(technique); - return true; +namespace IW4 { +class TechniqueDumpingZoneState final : public IZoneAssetDumperState { + std::set<const MaterialTechnique *> m_dumped_techniques; + +public: + bool ShouldDumpTechnique(const MaterialTechnique *technique) { + if (m_dumped_techniques.find(technique) != m_dumped_techniques.end()) + return false; + + m_dumped_techniques.emplace(technique); + return true; + } +}; + +class TechniqueFileWriter : public AbstractTextDumper { + void DumpStateMap() const { + Indent(); + // TODO: Actual statemap: Maybe find all materials using this techset and try to make out rules for the flags based on the statebitstable + m_stream << "stateMap \"passthrough\"; // TODO\n"; + } + + static bool FindCodeConstantSourceAccessor(const MaterialConstantSource sourceIndexToFind, const CodeConstantSource *codeConstantTable, + std::string &codeSourceAccessor) { + const auto *currentCodeConst = codeConstantTable; + while (currentCodeConst->name != nullptr) { + if (currentCodeConst->subtable != nullptr) { + std::string accessorInSubTable; + if (FindCodeConstantSourceAccessor(sourceIndexToFind, currentCodeConst->subtable, accessorInSubTable)) { + std::ostringstream ss; + ss << currentCodeConst->name << '.' << accessorInSubTable; + codeSourceAccessor = ss.str(); + return true; } - }; - - class TechniqueFileWriter : public AbstractTextDumper - { - void DumpStateMap() const - { - Indent(); - // TODO: Actual statemap: Maybe find all materials using this techset and try to make out rules for the flags based on the statebitstable - m_stream << "stateMap \"passthrough\"; // TODO\n"; + } else if (currentCodeConst->arrayCount > 0) { + if (currentCodeConst->source <= sourceIndexToFind && + static_cast<unsigned>(currentCodeConst->source) + currentCodeConst->arrayCount > static_cast<unsigned>(sourceIndexToFind)) { + std::ostringstream ss; + ss << currentCodeConst->name << '[' << (static_cast<unsigned>(sourceIndexToFind) - static_cast<unsigned>(currentCodeConst->source)) << ']'; + codeSourceAccessor = ss.str(); + return true; } + } else if (currentCodeConst->source == sourceIndexToFind) { + codeSourceAccessor = currentCodeConst->name; + return true; + } - static bool FindCodeConstantSourceAccessor(const MaterialConstantSource sourceIndexToFind, const CodeConstantSource* codeConstantTable, std::string& codeSourceAccessor) - { - const auto* currentCodeConst = codeConstantTable; - while (currentCodeConst->name != nullptr) - { - if (currentCodeConst->subtable != nullptr) - { - std::string accessorInSubTable; - if (FindCodeConstantSourceAccessor(sourceIndexToFind, currentCodeConst->subtable, accessorInSubTable)) - { - std::ostringstream ss; - ss << currentCodeConst->name << '.' << accessorInSubTable; - codeSourceAccessor = ss.str(); - return true; - } - } - else if (currentCodeConst->arrayCount > 0) - { - if (currentCodeConst->source <= sourceIndexToFind - && static_cast<unsigned>(currentCodeConst->source) + currentCodeConst->arrayCount > static_cast<unsigned>(sourceIndexToFind)) - { - std::ostringstream ss; - ss << currentCodeConst->name << '[' << (static_cast<unsigned>(sourceIndexToFind) - static_cast<unsigned>(currentCodeConst->source)) << ']'; - codeSourceAccessor = ss.str(); - return true; - } - } - else if (currentCodeConst->source == sourceIndexToFind) - { - codeSourceAccessor = currentCodeConst->name; - return true; - } - - currentCodeConst++; - } - - return false; - } + currentCodeConst++; + } - static bool FindCodeSamplerSourceAccessor(const MaterialTextureSource sourceIndexToFind, const CodeSamplerSource* codeSamplerTable, std::string& codeSourceAccessor) - { - const auto* currentCodeConst = codeSamplerTable; - while (currentCodeConst->name != nullptr) - { - if (currentCodeConst->subtable != nullptr) - { - std::string accessorInSubTable; - if (FindCodeSamplerSourceAccessor(sourceIndexToFind, currentCodeConst->subtable, accessorInSubTable)) - { - std::ostringstream ss; - ss << currentCodeConst->name << '.' << accessorInSubTable; - codeSourceAccessor = ss.str(); - return true; - } - } - else if (currentCodeConst->arrayCount > 0) - { - if (currentCodeConst->source <= sourceIndexToFind - && static_cast<unsigned>(currentCodeConst->source) + currentCodeConst->arrayCount > static_cast<unsigned>(sourceIndexToFind)) - { - std::ostringstream ss; - ss << currentCodeConst->name << '[' << (static_cast<unsigned>(sourceIndexToFind) - static_cast<unsigned>(currentCodeConst->source)) << ']'; - codeSourceAccessor = ss.str(); - return true; - } - } - else if (currentCodeConst->source == sourceIndexToFind) - { - codeSourceAccessor = currentCodeConst->name; - return true; - } - - currentCodeConst++; - } - - return false; + return false; + } + + static bool FindCodeSamplerSourceAccessor(const MaterialTextureSource sourceIndexToFind, const CodeSamplerSource *codeSamplerTable, + std::string &codeSourceAccessor) { + const auto *currentCodeConst = codeSamplerTable; + while (currentCodeConst->name != nullptr) { + if (currentCodeConst->subtable != nullptr) { + std::string accessorInSubTable; + if (FindCodeSamplerSourceAccessor(sourceIndexToFind, currentCodeConst->subtable, accessorInSubTable)) { + std::ostringstream ss; + ss << currentCodeConst->name << '.' << accessorInSubTable; + codeSourceAccessor = ss.str(); + return true; + } + } else if (currentCodeConst->arrayCount > 0) { + if (currentCodeConst->source <= sourceIndexToFind && + static_cast<unsigned>(currentCodeConst->source) + currentCodeConst->arrayCount > static_cast<unsigned>(sourceIndexToFind)) { + std::ostringstream ss; + ss << currentCodeConst->name << '[' << (static_cast<unsigned>(sourceIndexToFind) - static_cast<unsigned>(currentCodeConst->source)) << ']'; + codeSourceAccessor = ss.str(); + return true; } + } else if (currentCodeConst->source == sourceIndexToFind) { + codeSourceAccessor = currentCodeConst->name; + return true; + } - void DumpShaderArg(const MaterialShaderArgument& arg, const d3d9::ShaderInfo& shaderInfo) const - { - const auto expectedRegisterSet = arg.type == MTL_ARG_CODE_PIXEL_SAMPLER || arg.type == MTL_ARG_MATERIAL_PIXEL_SAMPLER ? d3d9::RegisterSet::SAMPLER : d3d9::RegisterSet::FLOAT_4; - const auto targetShaderArg = std::find_if(shaderInfo.m_constants.begin(), shaderInfo.m_constants.end(), [arg, expectedRegisterSet](const d3d9::ShaderConstant& constant) - { - return constant.m_register_set == expectedRegisterSet && constant.m_register_index <= arg.dest && constant.m_register_index + constant.m_register_count > arg.dest; - }); - - assert(targetShaderArg != shaderInfo.m_constants.end()); - if (targetShaderArg == shaderInfo.m_constants.end()) - { - m_stream << "// Unrecognized arg dest:" << arg.dest << " type: " << arg.type << "\n"; - return; - } - - std::string codeDestAccessor; - if (targetShaderArg->m_type_elements > 1) - { - std::ostringstream ss; - ss << targetShaderArg->m_name << '[' << (arg.dest - targetShaderArg->m_register_index) << ']'; - codeDestAccessor = ss.str(); - } - else - codeDestAccessor = targetShaderArg->m_name; - - if (arg.type == MTL_ARG_CODE_VERTEX_CONST || arg.type == MTL_ARG_CODE_PIXEL_CONST) - { - const auto sourceIndex = static_cast<MaterialConstantSource>(arg.u.codeConst.index); - std::string codeSourceAccessor; - if (FindCodeConstantSourceAccessor(sourceIndex, s_codeConsts, codeSourceAccessor) - || FindCodeConstantSourceAccessor(sourceIndex, s_defaultCodeConsts, codeSourceAccessor)) - { - if (codeDestAccessor != codeSourceAccessor) - { - Indent(); - m_stream << codeDestAccessor << " = constant." << codeSourceAccessor << ";\n"; - } - else - { + currentCodeConst++; + } + + return false; + } + + void DumpShaderArg(const MaterialShaderArgument &arg, const d3d9::ShaderInfo &shaderInfo) const { + const auto expectedRegisterSet = + arg.type == MTL_ARG_CODE_PIXEL_SAMPLER || arg.type == MTL_ARG_MATERIAL_PIXEL_SAMPLER ? d3d9::RegisterSet::SAMPLER : d3d9::RegisterSet::FLOAT_4; + const auto targetShaderArg = + std::find_if(shaderInfo.m_constants.begin(), shaderInfo.m_constants.end(), [arg, expectedRegisterSet](const d3d9::ShaderConstant &constant) { + return constant.m_register_set == expectedRegisterSet && constant.m_register_index <= arg.dest && + constant.m_register_index + constant.m_register_count > arg.dest; + }); + + assert(targetShaderArg != shaderInfo.m_constants.end()); + if (targetShaderArg == shaderInfo.m_constants.end()) { + m_stream << "// Unrecognized arg dest:" << arg.dest << " type: " << arg.type << "\n"; + return; + } + + std::string codeDestAccessor; + if (targetShaderArg->m_type_elements > 1) { + std::ostringstream ss; + ss << targetShaderArg->m_name << '[' << (arg.dest - targetShaderArg->m_register_index) << ']'; + codeDestAccessor = ss.str(); + } else + codeDestAccessor = targetShaderArg->m_name; + + if (arg.type == MTL_ARG_CODE_VERTEX_CONST || arg.type == MTL_ARG_CODE_PIXEL_CONST) { + const auto sourceIndex = static_cast<MaterialConstantSource>(arg.u.codeConst.index); + std::string codeSourceAccessor; + if (FindCodeConstantSourceAccessor(sourceIndex, s_codeConsts, codeSourceAccessor) || + FindCodeConstantSourceAccessor(sourceIndex, s_defaultCodeConsts, codeSourceAccessor)) { + if (codeDestAccessor != codeSourceAccessor) { + Indent(); + m_stream << codeDestAccessor << " = constant." << codeSourceAccessor << ";\n"; + } else { #ifdef TECHSET_DEBUG - Indent(); - m_stream << "// Omitted due to matching accessors: " << codeDestAccessor << " = constant." << codeSourceAccessor << ";\n"; + Indent(); + m_stream << "// Omitted due to matching accessors: " << codeDestAccessor << " = constant." << codeSourceAccessor << ";\n"; #endif - } - } - else - { - assert(false); - Indent(); - m_stream << codeDestAccessor << " = UNKNOWN;\n"; - } - } - else if (arg.type == MTL_ARG_CODE_PIXEL_SAMPLER) - { - const auto sourceIndex = static_cast<MaterialTextureSource>(arg.u.codeSampler); - std::string codeSourceAccessor; - if (FindCodeSamplerSourceAccessor(sourceIndex, s_codeSamplers, codeSourceAccessor) - || FindCodeSamplerSourceAccessor(sourceIndex, s_defaultCodeSamplers, codeSourceAccessor)) - { - if (codeDestAccessor != codeSourceAccessor) - { - Indent(); - m_stream << codeDestAccessor << " = sampler." << codeSourceAccessor << ";\n"; - } - else - { + } + } else { + assert(false); + Indent(); + m_stream << codeDestAccessor << " = UNKNOWN;\n"; + } + } else if (arg.type == MTL_ARG_CODE_PIXEL_SAMPLER) { + const auto sourceIndex = static_cast<MaterialTextureSource>(arg.u.codeSampler); + std::string codeSourceAccessor; + if (FindCodeSamplerSourceAccessor(sourceIndex, s_codeSamplers, codeSourceAccessor) || + FindCodeSamplerSourceAccessor(sourceIndex, s_defaultCodeSamplers, codeSourceAccessor)) { + if (codeDestAccessor != codeSourceAccessor) { + Indent(); + m_stream << codeDestAccessor << " = sampler." << codeSourceAccessor << ";\n"; + } else { #ifdef TECHSET_DEBUG - Indent(); - m_stream << "// Omitted due to matching accessors: " << codeDestAccessor << " = sampler." << codeSourceAccessor << ";\n"; + Indent(); + m_stream << "// Omitted due to matching accessors: " << codeDestAccessor << " = sampler." << codeSourceAccessor << ";\n"; #endif - } - } - else - { - assert(false); - Indent(); - m_stream << codeDestAccessor << " = UNKNOWN;\n"; - } - } - else if (arg.type == MTL_ARG_LITERAL_VERTEX_CONST || arg.type == MTL_ARG_LITERAL_PIXEL_CONST) - { - if (arg.u.literalConst) - { - Indent(); - m_stream << codeDestAccessor << " = float4( " << (*arg.u.literalConst)[0] - << ", " << (*arg.u.literalConst)[1] - << ", " << (*arg.u.literalConst)[2] - << ", " << (*arg.u.literalConst)[3] - << " );\n"; - } - } - else if (arg.type == MTL_ARG_MATERIAL_PIXEL_CONST || arg.type == MTL_ARG_MATERIAL_VERTEX_CONST || arg.type == MTL_ARG_MATERIAL_PIXEL_SAMPLER) - { - Indent(); - m_stream << codeDestAccessor << " = material."; - - const auto knownConstantName = knownConstantNames.find(arg.u.nameHash); - if (knownConstantName != knownConstantNames.end()) - { - m_stream << knownConstantName->second; - } - else - { - const auto knownMaterialTextureName = knownTextureMaps.find(arg.u.nameHash); - - if(knownMaterialTextureName != knownTextureMaps.end()) - { - m_stream << knownMaterialTextureName->second.m_name; - } - else - { - const auto shaderArgNameHash = Common::R_HashString(targetShaderArg->m_name.c_str(), 0u); - if (shaderArgNameHash == arg.u.nameHash) - m_stream << targetShaderArg->m_name; - else - m_stream << "#0x" << std::hex << arg.u.nameHash; - } - } - - m_stream << ";\n"; - } - else - { - assert(false); - } } - - void DumpVertexShader(const MaterialPass& pass) - { - auto vertexShader = pass.vertexShader; - - if (vertexShader == nullptr || vertexShader->name == nullptr) - return; - - if (vertexShader->name[0] == ',') - { - const auto loadedVertexShaderFromOtherZone = GlobalAssetPool<MaterialVertexShader>::GetAssetByName(&vertexShader->name[1]); - - if (loadedVertexShaderFromOtherZone == nullptr) - { - // Cannot dump when shader is referenced due to unknown constant names and unknown version - Indent(); - std::cerr << "Cannot dump vertex shader " << &vertexShader->name[1] << " due to being a referenced asset\n"; - m_stream << "// Cannot dump vertex shader " << &vertexShader->name[1] << " due to being a referenced asset\n"; - return; - } - vertexShader = loadedVertexShaderFromOtherZone->Asset(); - } - - const auto vertexShaderInfo = d3d9::ShaderAnalyser::GetShaderInfo(vertexShader->prog.loadDef.program, vertexShader->prog.loadDef.programSize * sizeof(uint32_t)); - assert(vertexShaderInfo); - if (!vertexShaderInfo) - return; - - m_stream << "\n"; - Indent(); - m_stream << "vertexShader " << vertexShaderInfo->m_version_major << "." << vertexShaderInfo->m_version_minor << " \"" << vertexShader->name << "\"\n"; - Indent(); - m_stream << "{\n"; - IncIndent(); - - if (pass.args) - { - const auto totalArgCount = static_cast<size_t>(pass.perPrimArgCount) - + static_cast<size_t>(pass.perObjArgCount) - + static_cast<size_t>(pass.stableArgCount); - for (auto i = 0u; i < totalArgCount; i++) - { - const auto& arg = pass.args[i]; - if (arg.type == MTL_ARG_MATERIAL_VERTEX_CONST - || arg.type == MTL_ARG_LITERAL_VERTEX_CONST - || arg.type == MTL_ARG_CODE_VERTEX_CONST) - { - DumpShaderArg(arg, *vertexShaderInfo); - } - } - } - - DecIndent(); - Indent(); - m_stream << "}\n"; + } else { + assert(false); + Indent(); + m_stream << codeDestAccessor << " = UNKNOWN;\n"; + } + } else if (arg.type == MTL_ARG_LITERAL_VERTEX_CONST || arg.type == MTL_ARG_LITERAL_PIXEL_CONST) { + if (arg.u.literalConst) { + Indent(); + m_stream << codeDestAccessor << " = float4( " << (*arg.u.literalConst)[0] << ", " << (*arg.u.literalConst)[1] << ", " << (*arg.u.literalConst)[2] + << ", " << (*arg.u.literalConst)[3] << " );\n"; + } + } else if (arg.type == MTL_ARG_MATERIAL_PIXEL_CONST || arg.type == MTL_ARG_MATERIAL_VERTEX_CONST || arg.type == MTL_ARG_MATERIAL_PIXEL_SAMPLER) { + Indent(); + m_stream << codeDestAccessor << " = material."; + + const auto knownConstantName = knownConstantNames.find(arg.u.nameHash); + if (knownConstantName != knownConstantNames.end()) { + m_stream << knownConstantName->second; + } else { + const auto knownMaterialTextureName = knownTextureMaps.find(arg.u.nameHash); + + if (knownMaterialTextureName != knownTextureMaps.end()) { + m_stream << knownMaterialTextureName->second.m_name; + } else { + const auto shaderArgNameHash = Common::R_HashString(targetShaderArg->m_name.c_str(), 0u); + if (shaderArgNameHash == arg.u.nameHash) + m_stream << targetShaderArg->m_name; + else + m_stream << "#0x" << std::hex << arg.u.nameHash; } + } - void DumpPixelShader(const MaterialPass& pass) - { - auto pixelShader = pass.pixelShader; - - if (pixelShader == nullptr || pixelShader->name == nullptr) - return; - - if (pixelShader->name[0] == ',') - { - const auto loadedPixelShaderFromOtherZone = GlobalAssetPool<MaterialPixelShader>::GetAssetByName(&pixelShader->name[1]); - - if (loadedPixelShaderFromOtherZone == nullptr) - { - // Cannot dump when shader is referenced due to unknown constant names and unknown version - Indent(); - std::cerr << "Cannot dump pixel shader " << &pixelShader->name[1] << " due to being a referenced asset\n"; - m_stream << "// Cannot dump pixel shader " << &pixelShader->name[1] << " due to being a referenced asset\n"; - return; - } - pixelShader = loadedPixelShaderFromOtherZone->Asset(); - } - - const auto pixelShaderInfo = d3d9::ShaderAnalyser::GetShaderInfo(pixelShader->prog.loadDef.program, pixelShader->prog.loadDef.programSize * sizeof(uint32_t)); - assert(pixelShaderInfo); - if (!pixelShaderInfo) - return; - - m_stream << "\n"; - Indent(); - m_stream << "pixelShader " << pixelShaderInfo->m_version_major << "." << pixelShaderInfo->m_version_minor << " \"" << pixelShader->name << "\"\n"; - Indent(); - m_stream << "{\n"; - IncIndent(); - - if (pass.args) - { - const auto totalArgCount = static_cast<size_t>(pass.perPrimArgCount) - + static_cast<size_t>(pass.perObjArgCount) - + static_cast<size_t>(pass.stableArgCount); - for (auto i = 0u; i < totalArgCount; i++) - { - const auto& arg = pass.args[i]; - if (arg.type == MTL_ARG_MATERIAL_PIXEL_SAMPLER - || arg.type == MTL_ARG_CODE_PIXEL_SAMPLER - || arg.type == MTL_ARG_CODE_PIXEL_CONST - || arg.type == MTL_ARG_MATERIAL_PIXEL_CONST - || arg.type == MTL_ARG_LITERAL_PIXEL_CONST) - { - DumpShaderArg(arg, *pixelShaderInfo); - } - } - } - - DecIndent(); - Indent(); - m_stream << "}\n"; - } + m_stream << ";\n"; + } else { + assert(false); + } + } + + void DumpVertexShader(const MaterialPass &pass) { + auto vertexShader = pass.vertexShader; + + if (vertexShader == nullptr || vertexShader->name == nullptr) + return; + + if (vertexShader->name[0] == ',') { + const auto loadedVertexShaderFromOtherZone = GlobalAssetPool<MaterialVertexShader>::GetAssetByName(&vertexShader->name[1]); + + if (loadedVertexShaderFromOtherZone == nullptr) { + // Cannot dump when shader is referenced due to unknown constant names and unknown version + Indent(); + std::cerr << "Cannot dump vertex shader " << &vertexShader->name[1] << " due to being a referenced asset\n"; + m_stream << "// Cannot dump vertex shader " << &vertexShader->name[1] << " due to being a referenced asset\n"; + return; + } + vertexShader = loadedVertexShaderFromOtherZone->Asset(); + } - static const char* GetStreamDestinationString(const MaterialStreamDestination_e dst) - { - const auto dstIndex = static_cast<size_t>(dst); - assert(dstIndex < std::extent_v<decltype(materialStreamDestinationNames)>); - if (dstIndex < std::extent_v<decltype(materialStreamDestinationNames)>) - return materialStreamDestinationNames[dstIndex]; - return ""; + const auto vertexShaderInfo = + d3d9::ShaderAnalyser::GetShaderInfo(vertexShader->prog.loadDef.program, vertexShader->prog.loadDef.programSize * sizeof(uint32_t)); + assert(vertexShaderInfo); + if (!vertexShaderInfo) + return; + + m_stream << "\n"; + Indent(); + m_stream << "vertexShader " << vertexShaderInfo->m_version_major << "." << vertexShaderInfo->m_version_minor << " \"" << vertexShader->name << "\"\n"; + Indent(); + m_stream << "{\n"; + IncIndent(); + + if (pass.args) { + const auto totalArgCount = + static_cast<size_t>(pass.perPrimArgCount) + static_cast<size_t>(pass.perObjArgCount) + static_cast<size_t>(pass.stableArgCount); + for (auto i = 0u; i < totalArgCount; i++) { + const auto &arg = pass.args[i]; + if (arg.type == MTL_ARG_MATERIAL_VERTEX_CONST || arg.type == MTL_ARG_LITERAL_VERTEX_CONST || arg.type == MTL_ARG_CODE_VERTEX_CONST) { + DumpShaderArg(arg, *vertexShaderInfo); } + } + } + + DecIndent(); + Indent(); + m_stream << "}\n"; + } + + void DumpPixelShader(const MaterialPass &pass) { + auto pixelShader = pass.pixelShader; - static const char* GetStreamSourceString(const MaterialStreamStreamSource_e src) - { - const auto srcIndex = static_cast<size_t>(src); - assert(srcIndex < std::extent_v<decltype(materialStreamSourceNames)>); - if (srcIndex < std::extent_v<decltype(materialStreamSourceNames)>) - return materialStreamSourceNames[srcIndex]; - return ""; + if (pixelShader == nullptr || pixelShader->name == nullptr) + return; + + if (pixelShader->name[0] == ',') { + const auto loadedPixelShaderFromOtherZone = GlobalAssetPool<MaterialPixelShader>::GetAssetByName(&pixelShader->name[1]); + + if (loadedPixelShaderFromOtherZone == nullptr) { + // Cannot dump when shader is referenced due to unknown constant names and unknown version + Indent(); + std::cerr << "Cannot dump pixel shader " << &pixelShader->name[1] << " due to being a referenced asset\n"; + m_stream << "// Cannot dump pixel shader " << &pixelShader->name[1] << " due to being a referenced asset\n"; + return; + } + pixelShader = loadedPixelShaderFromOtherZone->Asset(); + } + + const auto pixelShaderInfo = + d3d9::ShaderAnalyser::GetShaderInfo(pixelShader->prog.loadDef.program, pixelShader->prog.loadDef.programSize * sizeof(uint32_t)); + assert(pixelShaderInfo); + if (!pixelShaderInfo) + return; + + m_stream << "\n"; + Indent(); + m_stream << "pixelShader " << pixelShaderInfo->m_version_major << "." << pixelShaderInfo->m_version_minor << " \"" << pixelShader->name << "\"\n"; + Indent(); + m_stream << "{\n"; + IncIndent(); + + if (pass.args) { + const auto totalArgCount = + static_cast<size_t>(pass.perPrimArgCount) + static_cast<size_t>(pass.perObjArgCount) + static_cast<size_t>(pass.stableArgCount); + for (auto i = 0u; i < totalArgCount; i++) { + const auto &arg = pass.args[i]; + if (arg.type == MTL_ARG_MATERIAL_PIXEL_SAMPLER || arg.type == MTL_ARG_CODE_PIXEL_SAMPLER || arg.type == MTL_ARG_CODE_PIXEL_CONST || + arg.type == MTL_ARG_MATERIAL_PIXEL_CONST || arg.type == MTL_ARG_LITERAL_PIXEL_CONST) { + DumpShaderArg(arg, *pixelShaderInfo); } + } + } + + DecIndent(); + Indent(); + m_stream << "}\n"; + } + + static const char *GetStreamDestinationString(const MaterialStreamDestination_e dst) { + const auto dstIndex = static_cast<size_t>(dst); + assert(dstIndex < std::extent_v<decltype(materialStreamDestinationNames)>); + if (dstIndex < std::extent_v<decltype(materialStreamDestinationNames)>) + return materialStreamDestinationNames[dstIndex]; + return ""; + } + + static const char *GetStreamSourceString(const MaterialStreamStreamSource_e src) { + const auto srcIndex = static_cast<size_t>(src); + assert(srcIndex < std::extent_v<decltype(materialStreamSourceNames)>); + if (srcIndex < std::extent_v<decltype(materialStreamSourceNames)>) + return materialStreamSourceNames[srcIndex]; + return ""; + } + + void DumpVertexDecl(const MaterialPass &pass) { + const auto *vertexDecl = pass.vertexDecl; + if (vertexDecl == nullptr) + return; + + if (vertexDecl->name && vertexDecl->name[0] == ',') { + const auto loadedVertexDeclFromOtherZone = GlobalAssetPool<MaterialVertexDeclaration>::GetAssetByName(&vertexDecl->name[1]); + + if (loadedVertexDeclFromOtherZone == nullptr) { + // Cannot dump when shader is referenced due to unknown constant names and unknown version + Indent(); + std::cerr << "Cannot dump vertex decl " << &vertexDecl->name[1] << " due to being a referenced asset\n"; + m_stream << "// Cannot dump vertex decl " << &vertexDecl->name[1] << " due to being a referenced asset\n"; + return; + } + vertexDecl = loadedVertexDeclFromOtherZone->Asset(); + } - void DumpVertexDecl(const MaterialPass& pass) - { - const auto* vertexDecl = pass.vertexDecl; - if (vertexDecl == nullptr) - return; - - if (vertexDecl->name && vertexDecl->name[0] == ',') - { - const auto loadedVertexDeclFromOtherZone = GlobalAssetPool<MaterialVertexDeclaration>::GetAssetByName(&vertexDecl->name[1]); - - if (loadedVertexDeclFromOtherZone == nullptr) - { - // Cannot dump when shader is referenced due to unknown constant names and unknown version - Indent(); - std::cerr << "Cannot dump vertex decl " << &vertexDecl->name[1] << " due to being a referenced asset\n"; - m_stream << "// Cannot dump vertex decl " << &vertexDecl->name[1] << " due to being a referenced asset\n"; - return; - } - vertexDecl = loadedVertexDeclFromOtherZone->Asset(); - } - - m_stream << "\n"; + m_stream << "\n"; #ifdef TECHSET_DEBUG - Indent(); - m_stream << "// Decl: " << vertexDecl->name << "\n"; + Indent(); + m_stream << "// Decl: " << vertexDecl->name << "\n"; #endif - const auto streamCount = std::min(static_cast<size_t>(vertexDecl->streamCount), std::extent_v<decltype(MaterialVertexStreamRouting::data)>); - for (auto streamIndex = 0u; streamIndex < streamCount; streamIndex++) - { - const auto& stream = vertexDecl->routing.data[streamIndex]; - Indent(); - m_stream << "vertex." << GetStreamDestinationString(static_cast<MaterialStreamDestination_e>(stream.dest)) - << " = code." << GetStreamSourceString(static_cast<MaterialStreamStreamSource_e>(stream.source)) << ";\n"; - } - } + const auto streamCount = std::min(static_cast<size_t>(vertexDecl->streamCount), std::extent_v<decltype(MaterialVertexStreamRouting::data)>); + for (auto streamIndex = 0u; streamIndex < streamCount; streamIndex++) { + const auto &stream = vertexDecl->routing.data[streamIndex]; + Indent(); + m_stream << "vertex." << GetStreamDestinationString(static_cast<MaterialStreamDestination_e>(stream.dest)) << " = code." + << GetStreamSourceString(static_cast<MaterialStreamStreamSource_e>(stream.source)) << ";\n"; + } + } - void DumpPass(const MaterialPass& pass) - { - m_stream << "{\n"; - IncIndent(); + void DumpPass(const MaterialPass &pass) { + m_stream << "{\n"; + IncIndent(); #ifdef TECHSET_DEBUG - for (auto i = 0u; i < 8; i++) - { - const auto mask = 1u << i; - if (pass.customSamplerFlags & mask) - { - Indent(); - m_stream << "// CUSTOM SAMPLER FLAGS: 0x" << std::hex << mask << "\n"; - } - } + for (auto i = 0u; i < 8; i++) { + const auto mask = 1u << i; + if (pass.customSamplerFlags & mask) { + Indent(); + m_stream << "// CUSTOM SAMPLER FLAGS: 0x" << std::hex << mask << "\n"; + } + } #endif - DumpStateMap(); - DumpVertexShader(pass); - DumpPixelShader(pass); - DumpVertexDecl(pass); + DumpStateMap(); + DumpVertexShader(pass); + DumpPixelShader(pass); + DumpVertexDecl(pass); - DecIndent(); - m_stream << "}\n"; - } + DecIndent(); + m_stream << "}\n"; + } - public: - explicit TechniqueFileWriter(std::ostream& stream) - : AbstractTextDumper(stream) - { - } +public: + explicit TechniqueFileWriter(std::ostream &stream) : AbstractTextDumper(stream) {} - void DumpTechnique(const MaterialTechnique* technique) - { + void DumpTechnique(const MaterialTechnique *technique) { #ifdef TECHSET_DEBUG - if(technique->flags) - { - for(auto i = 0u; i < 16; i++) - { - const auto mask = 1u << i; - if(technique->flags & mask) - { - Indent(); - m_stream << "// TECHNIQUE FLAGS: 0x" << std::hex << mask << "\n"; - } - } - } -#endif - for (auto i = 0u; i < technique->passCount; i++) - DumpPass(technique->passArray[i]); + if (technique->flags) { + for (auto i = 0u; i < 16; i++) { + const auto mask = 1u << i; + if (technique->flags & mask) { + Indent(); + m_stream << "// TECHNIQUE FLAGS: 0x" << std::hex << mask << "\n"; } - }; - - class TechsetFileWriter : public AbstractTextDumper - { - bool m_last_write_was_value; + } + } +#endif + for (auto i = 0u; i < technique->passCount; i++) + DumpPass(technique->passArray[i]); + } +}; - public: - explicit TechsetFileWriter(std::ostream& stream) - : AbstractTextDumper(stream), - m_last_write_was_value(false) - { - } +class TechsetFileWriter : public AbstractTextDumper { + bool m_last_write_was_value; - void WriteTechniqueType(const size_t techniqueIndex) - { - assert(techniqueIndex < std::extent_v<decltype(techniqueTypeNames)>); +public: + explicit TechsetFileWriter(std::ostream &stream) : AbstractTextDumper(stream), m_last_write_was_value(false) {} - if (m_last_write_was_value) - { - m_stream << "\n"; - m_last_write_was_value = false; - } - m_stream << '"' << techniqueTypeNames[techniqueIndex] << "\":\n"; - } + void WriteTechniqueType(const size_t techniqueIndex) { + assert(techniqueIndex < std::extent_v<decltype(techniqueTypeNames)>); - void WriteTechniqueValue(const char* value) - { - m_last_write_was_value = true; + if (m_last_write_was_value) { + m_stream << "\n"; + m_last_write_was_value = false; + } + m_stream << '"' << techniqueTypeNames[techniqueIndex] << "\":\n"; + } - IncIndent(); - Indent(); - m_stream << value << ";\n"; - DecIndent(); - } + void WriteTechniqueValue(const char *value) { + m_last_write_was_value = true; - void DumpTechset(const MaterialTechniqueSet* techset) - { - std::vector<bool> dumpedTechniques(std::extent_v<decltype(MaterialTechniqueSet::techniques)>); + IncIndent(); + Indent(); + m_stream << value << ";\n"; + DecIndent(); + } - for (auto techniqueIndex = 0u; techniqueIndex < std::extent_v<decltype(MaterialTechniqueSet::techniques)>; techniqueIndex++) - { - const auto* technique = techset->techniques[techniqueIndex]; - if (technique == nullptr || dumpedTechniques[techniqueIndex]) - continue; + void DumpTechset(const MaterialTechniqueSet *techset) { + std::vector<bool> dumpedTechniques(std::extent_v<decltype(MaterialTechniqueSet::techniques)>); - dumpedTechniques[techniqueIndex] = true; - WriteTechniqueType(techniqueIndex); + for (auto techniqueIndex = 0u; techniqueIndex < std::extent_v<decltype(MaterialTechniqueSet::techniques)>; techniqueIndex++) { + const auto *technique = techset->techniques[techniqueIndex]; + if (technique == nullptr || dumpedTechniques[techniqueIndex]) + continue; - for (auto nextTechniqueIndex = techniqueIndex + 1; nextTechniqueIndex < std::extent_v<decltype(MaterialTechniqueSet::techniques)>; nextTechniqueIndex++) - { - if (techset->techniques[nextTechniqueIndex] != technique) - continue; + dumpedTechniques[techniqueIndex] = true; + WriteTechniqueType(techniqueIndex); - dumpedTechniques[nextTechniqueIndex] = true; - WriteTechniqueType(nextTechniqueIndex); - } + for (auto nextTechniqueIndex = techniqueIndex + 1; nextTechniqueIndex < std::extent_v<decltype(MaterialTechniqueSet::techniques)>; nextTechniqueIndex++) { + if (techset->techniques[nextTechniqueIndex] != technique) + continue; - WriteTechniqueValue(technique->name); - } - } - }; -} + dumpedTechniques[nextTechniqueIndex] = true; + WriteTechniqueType(nextTechniqueIndex); + } -std::string AssetDumperTechniqueSet::GetTechniqueFileName(const MaterialTechnique* technique) -{ - std::ostringstream ss; - ss << "techniques/" << technique->name << ".tech"; - return ss.str(); + WriteTechniqueValue(technique->name); + } + } +}; +} // namespace IW4 + +std::string AssetDumperTechniqueSet::GetTechniqueFileName(const MaterialTechnique *technique) { + std::ostringstream ss; + ss << "techniques/" << technique->name << ".tech"; + return ss.str(); } -std::string AssetDumperTechniqueSet::GetTechsetFileName(const MaterialTechniqueSet* techset) -{ - std::ostringstream ss; - ss << "techsets/" << techset->name << ".techset"; - return ss.str(); +std::string AssetDumperTechniqueSet::GetTechsetFileName(const MaterialTechniqueSet *techset) { + std::ostringstream ss; + ss << "techsets/" << techset->name << ".techset"; + return ss.str(); } -bool AssetDumperTechniqueSet::ShouldDump(XAssetInfo<MaterialTechniqueSet>* asset) -{ - return true; -} +bool AssetDumperTechniqueSet::ShouldDump(XAssetInfo<MaterialTechniqueSet> *asset) { return true; } -void AssetDumperTechniqueSet::DumpAsset(AssetDumpingContext& context, XAssetInfo<MaterialTechniqueSet>* asset) -{ - const auto* techset = asset->Asset(); +void AssetDumperTechniqueSet::DumpAsset(AssetDumpingContext &context, XAssetInfo<MaterialTechniqueSet> *asset) { + const auto *techset = asset->Asset(); - const auto techsetFile = context.OpenAssetFile(GetTechsetFileName(techset)); + const auto techsetFile = context.OpenAssetFile(GetTechsetFileName(techset)); - if (techsetFile) - { - TechsetFileWriter writer(*techsetFile); - writer.DumpTechset(techset); - } + if (techsetFile) { + TechsetFileWriter writer(*techsetFile); + writer.DumpTechset(techset); + } - auto* techniqueState = context.GetZoneAssetDumperState<TechniqueDumpingZoneState>(); - for (const auto* technique : techset->techniques) - { - if (technique && techniqueState->ShouldDumpTechnique(technique)) - { - const auto techniqueFile = context.OpenAssetFile(GetTechniqueFileName(technique)); - if (techniqueFile) - { - TechniqueFileWriter writer(*techniqueFile); - writer.DumpTechnique(technique); - } - } + auto *techniqueState = context.GetZoneAssetDumperState<TechniqueDumpingZoneState>(); + for (const auto *technique : techset->techniques) { + if (technique && techniqueState->ShouldDumpTechnique(technique)) { + const auto techniqueFile = context.OpenAssetFile(GetTechniqueFileName(technique)); + if (techniqueFile) { + TechniqueFileWriter writer(*techniqueFile); + writer.DumpTechnique(technique); + } } + } } diff --git a/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperTechniqueSet.h b/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperTechniqueSet.h index fc503d4b8..db707aa9f 100644 --- a/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperTechniqueSet.h +++ b/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperTechniqueSet.h @@ -3,15 +3,13 @@ #include "Dumping/AbstractAssetDumper.h" #include "Game/IW4/IW4.h" -namespace IW4 -{ - class AssetDumperTechniqueSet final : public AbstractAssetDumper<MaterialTechniqueSet> - { - static std::string GetTechniqueFileName(const MaterialTechnique* technique); - static std::string GetTechsetFileName(const MaterialTechniqueSet* techset); +namespace IW4 { +class AssetDumperTechniqueSet final : public AbstractAssetDumper<MaterialTechniqueSet> { + static std::string GetTechniqueFileName(const MaterialTechnique *technique); + static std::string GetTechsetFileName(const MaterialTechniqueSet *techset); - protected: - bool ShouldDump(XAssetInfo<MaterialTechniqueSet>* asset) override; - void DumpAsset(AssetDumpingContext& context, XAssetInfo<MaterialTechniqueSet>* asset) override; - }; -} +protected: + bool ShouldDump(XAssetInfo<MaterialTechniqueSet> *asset) override; + void DumpAsset(AssetDumpingContext &context, XAssetInfo<MaterialTechniqueSet> *asset) override; +}; +} // namespace IW4 diff --git a/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperTracer.cpp b/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperTracer.cpp index d648fd6a6..f79eb416f 100644 --- a/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperTracer.cpp +++ b/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperTracer.cpp @@ -5,69 +5,55 @@ #include <type_traits> #include "Game/IW4/CommonIW4.h" -#include "Game/IW4/ObjConstantsIW4.h" #include "Game/IW4/InfoString/InfoStringFromStructConverter.h" #include "Game/IW4/InfoString/TracerFields.h" +#include "Game/IW4/ObjConstantsIW4.h" using namespace IW4; -namespace IW4 -{ - class InfoStringFromTracerConverter final : public InfoStringFromStructConverter - { - protected: - void FillFromExtensionField(const cspField_t& field) override - { - assert(false); - } - - public: - InfoStringFromTracerConverter(const TracerDef* structure, const cspField_t* fields, const size_t fieldCount, std::function<std::string(scr_string_t)> scriptStringValueCallback) - : InfoStringFromStructConverter(structure, fields, fieldCount, std::move(scriptStringValueCallback)) - { - } - }; +namespace IW4 { +class InfoStringFromTracerConverter final : public InfoStringFromStructConverter { +protected: + void FillFromExtensionField(const cspField_t &field) override { assert(false); } + +public: + InfoStringFromTracerConverter(const TracerDef *structure, const cspField_t *fields, const size_t fieldCount, + std::function<std::string(scr_string_t)> scriptStringValueCallback) + : InfoStringFromStructConverter(structure, fields, fieldCount, std::move(scriptStringValueCallback)) {} +}; +} // namespace IW4 + +InfoString AssetDumperTracer::CreateInfoString(XAssetInfo<TracerDef> *asset) { + InfoStringFromTracerConverter converter(asset->Asset(), tracer_fields, std::extent<decltype(tracer_fields)>::value, + [asset](const scr_string_t scrStr) -> std::string { + assert(scrStr < asset->m_zone->m_script_strings.Count()); + if (scrStr >= asset->m_zone->m_script_strings.Count()) + return ""; + + return asset->m_zone->m_script_strings[scrStr]; + }); + + return converter.Convert(); } -InfoString AssetDumperTracer::CreateInfoString(XAssetInfo<TracerDef>* asset) -{ - InfoStringFromTracerConverter converter(asset->Asset(), tracer_fields, std::extent<decltype(tracer_fields)>::value, [asset](const scr_string_t scrStr) -> std::string - { - assert(scrStr < asset->m_zone->m_script_strings.Count()); - if (scrStr >= asset->m_zone->m_script_strings.Count()) - return ""; - - return asset->m_zone->m_script_strings[scrStr]; - }); - - return converter.Convert(); -} - -bool AssetDumperTracer::ShouldDump(XAssetInfo<TracerDef>* asset) -{ - return true; -} - -void AssetDumperTracer::DumpAsset(AssetDumpingContext& context, XAssetInfo<TracerDef>* asset) -{ - // Only dump raw when no gdt available - if (context.m_gdt) - { - const auto infoString = CreateInfoString(asset); - GdtEntry gdtEntry(asset->m_name, ObjConstants::GDF_FILENAME_TRACER); - infoString.ToGdtProperties(ObjConstants::INFO_STRING_PREFIX_TRACER, gdtEntry); - context.m_gdt->WriteEntry(gdtEntry); - } - else - { - const auto assetFile = context.OpenAssetFile("tracer/" + asset->m_name); - - if (!assetFile) - return; - - auto& stream = *assetFile; - const auto infoString = CreateInfoString(asset); - const auto stringValue = infoString.ToString(ObjConstants::INFO_STRING_PREFIX_TRACER); - stream.write(stringValue.c_str(), stringValue.size()); - } +bool AssetDumperTracer::ShouldDump(XAssetInfo<TracerDef> *asset) { return true; } + +void AssetDumperTracer::DumpAsset(AssetDumpingContext &context, XAssetInfo<TracerDef> *asset) { + // Only dump raw when no gdt available + if (context.m_gdt) { + const auto infoString = CreateInfoString(asset); + GdtEntry gdtEntry(asset->m_name, ObjConstants::GDF_FILENAME_TRACER); + infoString.ToGdtProperties(ObjConstants::INFO_STRING_PREFIX_TRACER, gdtEntry); + context.m_gdt->WriteEntry(gdtEntry); + } else { + const auto assetFile = context.OpenAssetFile("tracer/" + asset->m_name); + + if (!assetFile) + return; + + auto &stream = *assetFile; + const auto infoString = CreateInfoString(asset); + const auto stringValue = infoString.ToString(ObjConstants::INFO_STRING_PREFIX_TRACER); + stream.write(stringValue.c_str(), stringValue.size()); + } } diff --git a/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperTracer.h b/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperTracer.h index 02fe88de7..f164cdee7 100644 --- a/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperTracer.h +++ b/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperTracer.h @@ -4,14 +4,12 @@ #include "Game/IW4/IW4.h" #include "InfoString/InfoString.h" -namespace IW4 -{ - class AssetDumperTracer final : public AbstractAssetDumper<TracerDef> - { - static InfoString CreateInfoString(XAssetInfo<TracerDef>* asset); +namespace IW4 { +class AssetDumperTracer final : public AbstractAssetDumper<TracerDef> { + static InfoString CreateInfoString(XAssetInfo<TracerDef> *asset); - protected: - bool ShouldDump(XAssetInfo<TracerDef>* asset) override; - void DumpAsset(AssetDumpingContext& context, XAssetInfo<TracerDef>* asset) override; - }; -} +protected: + bool ShouldDump(XAssetInfo<TracerDef> *asset) override; + void DumpAsset(AssetDumpingContext &context, XAssetInfo<TracerDef> *asset) override; +}; +} // namespace IW4 diff --git a/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperVehicle.cpp b/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperVehicle.cpp index 75ac80f63..2cd2f31d8 100644 --- a/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperVehicle.cpp +++ b/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperVehicle.cpp @@ -5,110 +5,94 @@ #include <type_traits> #include "Game/IW4/CommonIW4.h" -#include "Game/IW4/InfoString/InfoStringFromStructConverter.h" -#include "Game/IW4/ObjConstantsIW4.h" #include "Game/IW4/InfoString/EnumStrings.h" +#include "Game/IW4/InfoString/InfoStringFromStructConverter.h" #include "Game/IW4/InfoString/VehicleFields.h" +#include "Game/IW4/ObjConstantsIW4.h" using namespace IW4; -namespace IW4 -{ - class InfoStringFromVehicleConverter final : public InfoStringFromStructConverter - { - protected: - void FillFromExtensionField(const cspField_t& field) override - { - switch (static_cast<VehicleFieldType>(field.iFieldType)) - { - case VFT_TYPE: - FillFromEnumInt(std::string(field.szName), field.iOffset, s_vehicleClassNames, std::extent<decltype(s_vehicleClassNames)>::value); - break; - - case VFT_AXLE_STEERING: - case VFT_AXLE_POWER: - case VFT_AXLE_BRAKING: - FillFromEnumInt(std::string(field.szName), field.iOffset, s_vehicleAxleTypeNames, std::extent<decltype(s_vehicleAxleTypeNames)>::value); - break; - - case VFT_TROPHY_TAGS: - { - const auto* trophyTags = reinterpret_cast<scr_string_t*>(reinterpret_cast<uintptr_t>(m_structure) + field.iOffset); - std::stringstream ss; - bool first = true; - - for (auto i = 0u; i < std::extent<decltype(VehicleDef::trophyTags)>::value; i++) - { - const auto& str = m_get_scr_string(trophyTags[i]); - if (!str.empty()) - { - if (!first) - ss << "\n"; - else - first = false; - - ss << str; - } - } - - m_info_string.SetValueForKey(std::string(field.szName), ss.str()); - break; - } - - case VFT_NUM: - default: - assert(false); - break; - } +namespace IW4 { +class InfoStringFromVehicleConverter final : public InfoStringFromStructConverter { +protected: + void FillFromExtensionField(const cspField_t &field) override { + switch (static_cast<VehicleFieldType>(field.iFieldType)) { + case VFT_TYPE: + FillFromEnumInt(std::string(field.szName), field.iOffset, s_vehicleClassNames, std::extent<decltype(s_vehicleClassNames)>::value); + break; + + case VFT_AXLE_STEERING: + case VFT_AXLE_POWER: + case VFT_AXLE_BRAKING: + FillFromEnumInt(std::string(field.szName), field.iOffset, s_vehicleAxleTypeNames, std::extent<decltype(s_vehicleAxleTypeNames)>::value); + break; + + case VFT_TROPHY_TAGS: { + const auto *trophyTags = reinterpret_cast<scr_string_t *>(reinterpret_cast<uintptr_t>(m_structure) + field.iOffset); + std::stringstream ss; + bool first = true; + + for (auto i = 0u; i < std::extent<decltype(VehicleDef::trophyTags)>::value; i++) { + const auto &str = m_get_scr_string(trophyTags[i]); + if (!str.empty()) { + if (!first) + ss << "\n"; + else + first = false; + + ss << str; } + } - public: - InfoStringFromVehicleConverter(const VehicleDef* structure, const cspField_t* fields, const size_t fieldCount, std::function<std::string(scr_string_t)> scriptStringValueCallback) - : InfoStringFromStructConverter(structure, fields, fieldCount, std::move(scriptStringValueCallback)) - { - } - }; -} - -InfoString AssetDumperVehicle::CreateInfoString(XAssetInfo<VehicleDef>* asset) -{ - InfoStringFromVehicleConverter converter(asset->Asset(), vehicle_fields, std::extent<decltype(vehicle_fields)>::value, [asset](const scr_string_t scrStr) -> std::string - { - assert(scrStr < asset->m_zone->m_script_strings.Count()); - if (scrStr >= asset->m_zone->m_script_strings.Count()) - return ""; - - return asset->m_zone->m_script_strings[scrStr]; - }); - - return converter.Convert(); -} - -bool AssetDumperVehicle::ShouldDump(XAssetInfo<VehicleDef>* asset) -{ - return true; -} - -void AssetDumperVehicle::DumpAsset(AssetDumpingContext& context, XAssetInfo<VehicleDef>* asset) -{ - // Only dump raw when no gdt available - if (context.m_gdt) - { - const auto infoString = CreateInfoString(asset); - GdtEntry gdtEntry(asset->m_name, ObjConstants::GDF_FILENAME_VEHICLE); - infoString.ToGdtProperties(ObjConstants::INFO_STRING_PREFIX_VEHICLE, gdtEntry); - context.m_gdt->WriteEntry(gdtEntry); + m_info_string.SetValueForKey(std::string(field.szName), ss.str()); + break; } - else - { - const auto assetFile = context.OpenAssetFile("vehicles/" + asset->m_name); - - if (!assetFile) - return; - auto& stream = *assetFile; - const auto infoString = CreateInfoString(asset); - const auto stringValue = infoString.ToString(ObjConstants::INFO_STRING_PREFIX_VEHICLE); - stream.write(stringValue.c_str(), stringValue.size()); + case VFT_NUM: + default: + assert(false); + break; } + } + +public: + InfoStringFromVehicleConverter(const VehicleDef *structure, const cspField_t *fields, const size_t fieldCount, + std::function<std::string(scr_string_t)> scriptStringValueCallback) + : InfoStringFromStructConverter(structure, fields, fieldCount, std::move(scriptStringValueCallback)) {} +}; +} // namespace IW4 + +InfoString AssetDumperVehicle::CreateInfoString(XAssetInfo<VehicleDef> *asset) { + InfoStringFromVehicleConverter converter(asset->Asset(), vehicle_fields, std::extent<decltype(vehicle_fields)>::value, + [asset](const scr_string_t scrStr) -> std::string { + assert(scrStr < asset->m_zone->m_script_strings.Count()); + if (scrStr >= asset->m_zone->m_script_strings.Count()) + return ""; + + return asset->m_zone->m_script_strings[scrStr]; + }); + + return converter.Convert(); +} + +bool AssetDumperVehicle::ShouldDump(XAssetInfo<VehicleDef> *asset) { return true; } + +void AssetDumperVehicle::DumpAsset(AssetDumpingContext &context, XAssetInfo<VehicleDef> *asset) { + // Only dump raw when no gdt available + if (context.m_gdt) { + const auto infoString = CreateInfoString(asset); + GdtEntry gdtEntry(asset->m_name, ObjConstants::GDF_FILENAME_VEHICLE); + infoString.ToGdtProperties(ObjConstants::INFO_STRING_PREFIX_VEHICLE, gdtEntry); + context.m_gdt->WriteEntry(gdtEntry); + } else { + const auto assetFile = context.OpenAssetFile("vehicles/" + asset->m_name); + + if (!assetFile) + return; + + auto &stream = *assetFile; + const auto infoString = CreateInfoString(asset); + const auto stringValue = infoString.ToString(ObjConstants::INFO_STRING_PREFIX_VEHICLE); + stream.write(stringValue.c_str(), stringValue.size()); + } } diff --git a/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperVehicle.h b/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperVehicle.h index 9215e0d5c..f26d41e97 100644 --- a/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperVehicle.h +++ b/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperVehicle.h @@ -4,14 +4,12 @@ #include "Game/IW4/IW4.h" #include "InfoString/InfoString.h" -namespace IW4 -{ - class AssetDumperVehicle final : public AbstractAssetDumper<VehicleDef> - { - static InfoString CreateInfoString(XAssetInfo<VehicleDef>* asset); +namespace IW4 { +class AssetDumperVehicle final : public AbstractAssetDumper<VehicleDef> { + static InfoString CreateInfoString(XAssetInfo<VehicleDef> *asset); - protected: - bool ShouldDump(XAssetInfo<VehicleDef>* asset) override; - void DumpAsset(AssetDumpingContext& context, XAssetInfo<VehicleDef>* asset) override; - }; -} +protected: + bool ShouldDump(XAssetInfo<VehicleDef> *asset) override; + void DumpAsset(AssetDumpingContext &context, XAssetInfo<VehicleDef> *asset) override; +}; +} // namespace IW4 diff --git a/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperVertexShader.cpp b/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperVertexShader.cpp index 4124fb68b..cc0d3d9f6 100644 --- a/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperVertexShader.cpp +++ b/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperVertexShader.cpp @@ -4,22 +4,19 @@ using namespace IW4; -bool AssetDumperVertexShader::ShouldDump(XAssetInfo<MaterialVertexShader>* asset) -{ - return true; -} +bool AssetDumperVertexShader::ShouldDump(XAssetInfo<MaterialVertexShader> *asset) { return true; } -void AssetDumperVertexShader::DumpAsset(AssetDumpingContext& context, XAssetInfo<MaterialVertexShader>* asset) -{ - const auto* vertexShader = asset->Asset(); +void AssetDumperVertexShader::DumpAsset(AssetDumpingContext &context, XAssetInfo<MaterialVertexShader> *asset) { + const auto *vertexShader = asset->Asset(); - std::ostringstream ss; - ss << "shader_bin/vs_" << vertexShader->name << ".cso"; + std::ostringstream ss; + ss << "shader_bin/vs_" << vertexShader->name << ".cso"; - const auto shaderFile = context.OpenAssetFile(ss.str()); + const auto shaderFile = context.OpenAssetFile(ss.str()); - if (!shaderFile) - return; + if (!shaderFile) + return; - shaderFile->write(reinterpret_cast<const char*>(vertexShader->prog.loadDef.program), static_cast<std::streamsize>(vertexShader->prog.loadDef.programSize) * 4u); + shaderFile->write(reinterpret_cast<const char *>(vertexShader->prog.loadDef.program), + static_cast<std::streamsize>(vertexShader->prog.loadDef.programSize) * 4u); } diff --git a/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperVertexShader.h b/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperVertexShader.h index c2b634306..372406d91 100644 --- a/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperVertexShader.h +++ b/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperVertexShader.h @@ -3,12 +3,10 @@ #include "Dumping/AbstractAssetDumper.h" #include "Game/IW4/IW4.h" -namespace IW4 -{ - class AssetDumperVertexShader final : public AbstractAssetDumper<MaterialVertexShader> - { - protected: - bool ShouldDump(XAssetInfo<MaterialVertexShader>* asset) override; - void DumpAsset(AssetDumpingContext& context, XAssetInfo<MaterialVertexShader>* asset) override; - }; -} +namespace IW4 { +class AssetDumperVertexShader final : public AbstractAssetDumper<MaterialVertexShader> { +protected: + bool ShouldDump(XAssetInfo<MaterialVertexShader> *asset) override; + void DumpAsset(AssetDumpingContext &context, XAssetInfo<MaterialVertexShader> *asset) override; +}; +} // namespace IW4 diff --git a/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperWeapon.cpp b/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperWeapon.cpp index 1d488b83d..fa2877742 100644 --- a/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperWeapon.cpp +++ b/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperWeapon.cpp @@ -6,360 +6,323 @@ #include <type_traits> #include "Game/IW4/CommonIW4.h" -#include "Game/IW4/ObjConstantsIW4.h" #include "Game/IW4/InfoString/EnumStrings.h" #include "Game/IW4/InfoString/InfoStringFromStructConverter.h" #include "Game/IW4/InfoString/WeaponFields.h" +#include "Game/IW4/ObjConstantsIW4.h" using namespace IW4; -namespace IW4 -{ - class InfoStringFromWeaponConverter final : public InfoStringFromStructConverter - { - protected: - void FillFromExtensionField(const cspField_t& field) override - { - switch (static_cast<weapFieldType_t>(field.iFieldType)) - { - case WFT_WEAPONTYPE: - FillFromEnumInt(std::string(field.szName), field.iOffset, szWeapTypeNames, std::extent<decltype(szWeapTypeNames)>::value); - break; - - case WFT_WEAPONCLASS: - FillFromEnumInt(std::string(field.szName), field.iOffset, szWeapClassNames, std::extent<decltype(szWeapClassNames)>::value); - break; - - case WFT_OVERLAYRETICLE: - FillFromEnumInt(std::string(field.szName), field.iOffset, szWeapOverlayReticleNames, std::extent<decltype(szWeapOverlayReticleNames)>::value); - break; - - case WFT_PENETRATE_TYPE: - FillFromEnumInt(std::string(field.szName), field.iOffset, penetrateTypeNames, std::extent<decltype(penetrateTypeNames)>::value); - break; - - case WFT_IMPACT_TYPE: - FillFromEnumInt(std::string(field.szName), field.iOffset, impactTypeNames, std::extent<decltype(impactTypeNames)>::value); - break; - - case WFT_STANCE: - FillFromEnumInt(std::string(field.szName), field.iOffset, szWeapStanceNames, std::extent<decltype(szWeapStanceNames)>::value); - break; - - case WFT_PROJ_EXPLOSION: - FillFromEnumInt(std::string(field.szName), field.iOffset, szProjectileExplosionNames, std::extent<decltype(szProjectileExplosionNames)>::value); - break; - - case WFT_OFFHAND_CLASS: - FillFromEnumInt(std::string(field.szName), field.iOffset, offhandClassNames, std::extent<decltype(offhandClassNames)>::value); - break; - - case WFT_ANIMTYPE: - FillFromEnumInt(std::string(field.szName), field.iOffset, playerAnimTypeNames, std::extent<decltype(playerAnimTypeNames)>::value); - break; - - case WFT_ACTIVE_RETICLE_TYPE: - FillFromEnumInt(std::string(field.szName), field.iOffset, activeReticleNames, std::extent<decltype(activeReticleNames)>::value); - break; - - case WFT_GUIDED_MISSILE_TYPE: - FillFromEnumInt(std::string(field.szName), field.iOffset, guidedMissileNames, std::extent<decltype(guidedMissileNames)>::value); - break; - - case WFT_BOUNCE_SOUND: - { - const auto* bounceSound = *reinterpret_cast<SndAliasCustom**>(reinterpret_cast<uintptr_t>(m_structure) + field.iOffset); - - if (bounceSound && bounceSound->name) - { - const std::string firstBounceSound(bounceSound->name->soundName); - const auto endOfBouncePrefix = firstBounceSound.rfind("_default"); - assert(endOfBouncePrefix != std::string::npos); - - if (endOfBouncePrefix != std::string::npos) - { - m_info_string.SetValueForKey(std::string(field.szName), - firstBounceSound.substr(0, endOfBouncePrefix)); - } - else - m_info_string.SetValueForKey(std::string(field.szName), ""); - } - else - m_info_string.SetValueForKey(std::string(field.szName), ""); - - break; - } - - case WFT_STICKINESS: - FillFromEnumInt(std::string(field.szName), field.iOffset, stickinessNames, std::extent<decltype(stickinessNames)>::value); - break; - - case WFT_OVERLAYINTERFACE: - FillFromEnumInt(std::string(field.szName), field.iOffset, overlayInterfaceNames, std::extent<decltype(overlayInterfaceNames)>::value); - break; - - case WFT_INVENTORYTYPE: - FillFromEnumInt(std::string(field.szName), field.iOffset, szWeapInventoryTypeNames, std::extent<decltype(szWeapInventoryTypeNames)>::value); - break; - - case WFT_FIRETYPE: - FillFromEnumInt(std::string(field.szName), field.iOffset, szWeapFireTypeNames, std::extent<decltype(szWeapFireTypeNames)>::value); - break; - - case WFT_AMMOCOUNTER_CLIPTYPE: - FillFromEnumInt(std::string(field.szName), field.iOffset, ammoCounterClipNames, std::extent<decltype(ammoCounterClipNames)>::value); - break; - - case WFT_ICONRATIO_HUD: - case WFT_ICONRATIO_PICKUP: - case WFT_ICONRATIO_AMMOCOUNTER: - case WFT_ICONRATIO_KILL: - case WFT_ICONRATIO_DPAD: - FillFromEnumInt(std::string(field.szName), field.iOffset, weapIconRatioNames, std::extent<decltype(weapIconRatioNames)>::value); - break; - - case WFT_HIDETAGS: - { - const auto* hideTags = reinterpret_cast<scr_string_t*>(reinterpret_cast<uintptr_t>(m_structure) + field.iOffset); - std::stringstream ss; - bool first = true; - - for (auto i = 0u; i < std::extent<decltype(WeaponFullDef::hideTags)>::value; i++) - { - const auto& str = m_get_scr_string(hideTags[i]); - if (!str.empty()) - { - if (!first) - ss << "\n"; - else - first = false; - - ss << str; - } - } - - m_info_string.SetValueForKey(std::string(field.szName), ss.str()); - break; - } - - case WFT_NOTETRACKSOUNDMAP: - { - const auto* keys = reinterpret_cast<scr_string_t*>(reinterpret_cast<uintptr_t>(m_structure) + field.iOffset); - const auto* values = &keys[std::extent<decltype(WeaponFullDef::notetrackSoundMapKeys)>::value]; - std::stringstream ss; - bool first = true; - - for (auto i = 0u; i < std::extent<decltype(WeaponFullDef::notetrackSoundMapKeys)>::value; i++) - { - const auto& key = m_get_scr_string(keys[i]); - const auto& value = m_get_scr_string(values[i]); - if (!key.empty()) - { - if (!first) - ss << "\n"; - else - first = false; - - ss << key; - - if (!value.empty()) - ss << " " << value; - } - } - - m_info_string.SetValueForKey(std::string(field.szName), ss.str()); - break; - } - - case WFT_NOTETRACKRUMBLEMAP: - { - const auto* keys = reinterpret_cast<scr_string_t*>(reinterpret_cast<uintptr_t>(m_structure) + field.iOffset); - const auto* values = &keys[std::extent<decltype(WeaponFullDef::notetrackRumbleMapKeys)>::value]; - std::stringstream ss; - bool first = true; - - for (auto i = 0u; i < std::extent<decltype(WeaponFullDef::notetrackRumbleMapKeys)>::value; i++) - { - const auto& key = m_get_scr_string(keys[i]); - const auto& value = m_get_scr_string(values[i]); - if (!key.empty()) - { - if (!first) - ss << "\n"; - else - first = false; - - ss << key; - - if (!value.empty()) - ss << " " << value; - } - } - - m_info_string.SetValueForKey(std::string(field.szName), ss.str()); - break; - } - - case WFT_NUM_FIELD_TYPES: - default: - assert(false); - break; - } - } - - public: - InfoStringFromWeaponConverter(const WeaponFullDef* structure, const cspField_t* fields, const size_t fieldCount, std::function<std::string(scr_string_t)> scriptStringValueCallback) - : InfoStringFromStructConverter(structure, fields, fieldCount, std::move(scriptStringValueCallback)) - { - } - }; -} - -void AssetDumperWeapon::CopyToFullDef(const WeaponCompleteDef* weapon, WeaponFullDef* fullDef) -{ - fullDef->weapCompleteDef = *weapon; - - if (weapon->weapDef) - { - fullDef->weapDef = *weapon->weapDef; - fullDef->weapCompleteDef.weapDef = &fullDef->weapDef; - } - - if (weapon->hideTags) - { - assert(sizeof(WeaponFullDef::hideTags) >= sizeof(scr_string_t) * std::extent<decltype(WeaponFullDef::hideTags)>::value); - memcpy(fullDef->hideTags, weapon->hideTags, sizeof(scr_string_t) * std::extent<decltype(WeaponFullDef::hideTags)>::value); - fullDef->weapCompleteDef.hideTags = fullDef->hideTags; - } - - if (weapon->szXAnims) - { - assert(sizeof(WeaponFullDef::szXAnims) >= sizeof(void*) * NUM_WEAP_ANIMS); - memcpy(fullDef->szXAnims, weapon->szXAnims, sizeof(void*) * NUM_WEAP_ANIMS); - fullDef->weapCompleteDef.szXAnims = fullDef->szXAnims; - } - - if (fullDef->weapDef.gunXModel) - { - assert(sizeof(WeaponFullDef::gunXModel) >= sizeof(void*) * std::extent<decltype(WeaponFullDef::gunXModel)>::value); - memcpy(fullDef->gunXModel, fullDef->weapDef.gunXModel, sizeof(void*) * std::extent<decltype(WeaponFullDef::gunXModel)>::value); - fullDef->weapDef.gunXModel = fullDef->gunXModel; - } - - if (fullDef->weapDef.szXAnimsRightHanded) - { - assert(sizeof(WeaponFullDef::szXAnimsRightHanded) >= sizeof(void*) * NUM_WEAP_ANIMS); - memcpy(fullDef->szXAnimsRightHanded, fullDef->weapDef.szXAnimsRightHanded, sizeof(void*) * NUM_WEAP_ANIMS); - fullDef->weapDef.szXAnimsRightHanded = fullDef->szXAnimsRightHanded; +namespace IW4 { +class InfoStringFromWeaponConverter final : public InfoStringFromStructConverter { +protected: + void FillFromExtensionField(const cspField_t &field) override { + switch (static_cast<weapFieldType_t>(field.iFieldType)) { + case WFT_WEAPONTYPE: + FillFromEnumInt(std::string(field.szName), field.iOffset, szWeapTypeNames, std::extent<decltype(szWeapTypeNames)>::value); + break; + + case WFT_WEAPONCLASS: + FillFromEnumInt(std::string(field.szName), field.iOffset, szWeapClassNames, std::extent<decltype(szWeapClassNames)>::value); + break; + + case WFT_OVERLAYRETICLE: + FillFromEnumInt(std::string(field.szName), field.iOffset, szWeapOverlayReticleNames, std::extent<decltype(szWeapOverlayReticleNames)>::value); + break; + + case WFT_PENETRATE_TYPE: + FillFromEnumInt(std::string(field.szName), field.iOffset, penetrateTypeNames, std::extent<decltype(penetrateTypeNames)>::value); + break; + + case WFT_IMPACT_TYPE: + FillFromEnumInt(std::string(field.szName), field.iOffset, impactTypeNames, std::extent<decltype(impactTypeNames)>::value); + break; + + case WFT_STANCE: + FillFromEnumInt(std::string(field.szName), field.iOffset, szWeapStanceNames, std::extent<decltype(szWeapStanceNames)>::value); + break; + + case WFT_PROJ_EXPLOSION: + FillFromEnumInt(std::string(field.szName), field.iOffset, szProjectileExplosionNames, std::extent<decltype(szProjectileExplosionNames)>::value); + break; + + case WFT_OFFHAND_CLASS: + FillFromEnumInt(std::string(field.szName), field.iOffset, offhandClassNames, std::extent<decltype(offhandClassNames)>::value); + break; + + case WFT_ANIMTYPE: + FillFromEnumInt(std::string(field.szName), field.iOffset, playerAnimTypeNames, std::extent<decltype(playerAnimTypeNames)>::value); + break; + + case WFT_ACTIVE_RETICLE_TYPE: + FillFromEnumInt(std::string(field.szName), field.iOffset, activeReticleNames, std::extent<decltype(activeReticleNames)>::value); + break; + + case WFT_GUIDED_MISSILE_TYPE: + FillFromEnumInt(std::string(field.szName), field.iOffset, guidedMissileNames, std::extent<decltype(guidedMissileNames)>::value); + break; + + case WFT_BOUNCE_SOUND: { + const auto *bounceSound = *reinterpret_cast<SndAliasCustom **>(reinterpret_cast<uintptr_t>(m_structure) + field.iOffset); + + if (bounceSound && bounceSound->name) { + const std::string firstBounceSound(bounceSound->name->soundName); + const auto endOfBouncePrefix = firstBounceSound.rfind("_default"); + assert(endOfBouncePrefix != std::string::npos); + + if (endOfBouncePrefix != std::string::npos) { + m_info_string.SetValueForKey(std::string(field.szName), firstBounceSound.substr(0, endOfBouncePrefix)); + } else + m_info_string.SetValueForKey(std::string(field.szName), ""); + } else + m_info_string.SetValueForKey(std::string(field.szName), ""); + + break; } - if (fullDef->weapDef.szXAnimsLeftHanded) - { - assert(sizeof(WeaponFullDef::szXAnimsLeftHanded) >= sizeof(void*) * NUM_WEAP_ANIMS); - memcpy(fullDef->szXAnimsLeftHanded, fullDef->weapDef.szXAnimsLeftHanded, sizeof(void*) * NUM_WEAP_ANIMS); - fullDef->weapDef.szXAnimsLeftHanded = fullDef->szXAnimsLeftHanded; - } - - if (fullDef->weapDef.notetrackSoundMapKeys) - { - assert(sizeof(WeaponFullDef::notetrackSoundMapKeys) >= sizeof(scr_string_t) * std::extent<decltype(WeaponFullDef::notetrackSoundMapKeys)>::value); - memcpy(fullDef->notetrackSoundMapKeys, fullDef->weapDef.notetrackSoundMapKeys, sizeof(scr_string_t) * std::extent<decltype(WeaponFullDef::notetrackSoundMapKeys)>::value); - fullDef->weapDef.notetrackSoundMapKeys = fullDef->notetrackSoundMapKeys; - } - - if (fullDef->weapDef.notetrackSoundMapValues) - { - assert(sizeof(WeaponFullDef::notetrackSoundMapValues) >= sizeof(scr_string_t) * std::extent<decltype(WeaponFullDef::notetrackSoundMapKeys)>::value); - memcpy(fullDef->notetrackSoundMapValues, fullDef->weapDef.notetrackSoundMapValues, sizeof(scr_string_t) * std::extent<decltype(WeaponFullDef::notetrackSoundMapKeys)>::value); - fullDef->weapDef.notetrackSoundMapValues = fullDef->notetrackSoundMapValues; - } + case WFT_STICKINESS: + FillFromEnumInt(std::string(field.szName), field.iOffset, stickinessNames, std::extent<decltype(stickinessNames)>::value); + break; + + case WFT_OVERLAYINTERFACE: + FillFromEnumInt(std::string(field.szName), field.iOffset, overlayInterfaceNames, std::extent<decltype(overlayInterfaceNames)>::value); + break; + + case WFT_INVENTORYTYPE: + FillFromEnumInt(std::string(field.szName), field.iOffset, szWeapInventoryTypeNames, std::extent<decltype(szWeapInventoryTypeNames)>::value); + break; + + case WFT_FIRETYPE: + FillFromEnumInt(std::string(field.szName), field.iOffset, szWeapFireTypeNames, std::extent<decltype(szWeapFireTypeNames)>::value); + break; + + case WFT_AMMOCOUNTER_CLIPTYPE: + FillFromEnumInt(std::string(field.szName), field.iOffset, ammoCounterClipNames, std::extent<decltype(ammoCounterClipNames)>::value); + break; + + case WFT_ICONRATIO_HUD: + case WFT_ICONRATIO_PICKUP: + case WFT_ICONRATIO_AMMOCOUNTER: + case WFT_ICONRATIO_KILL: + case WFT_ICONRATIO_DPAD: + FillFromEnumInt(std::string(field.szName), field.iOffset, weapIconRatioNames, std::extent<decltype(weapIconRatioNames)>::value); + break; + + case WFT_HIDETAGS: { + const auto *hideTags = reinterpret_cast<scr_string_t *>(reinterpret_cast<uintptr_t>(m_structure) + field.iOffset); + std::stringstream ss; + bool first = true; + + for (auto i = 0u; i < std::extent<decltype(WeaponFullDef::hideTags)>::value; i++) { + const auto &str = m_get_scr_string(hideTags[i]); + if (!str.empty()) { + if (!first) + ss << "\n"; + else + first = false; + + ss << str; + } + } - if (fullDef->weapDef.notetrackRumbleMapKeys) - { - assert(sizeof(WeaponFullDef::notetrackRumbleMapKeys) >= sizeof(scr_string_t) * std::extent<decltype(WeaponFullDef::notetrackRumbleMapKeys)>::value); - memcpy(fullDef->notetrackRumbleMapKeys, fullDef->weapDef.notetrackRumbleMapKeys, sizeof(scr_string_t) * std::extent<decltype(WeaponFullDef::notetrackRumbleMapKeys)>::value); - fullDef->weapDef.notetrackRumbleMapKeys = fullDef->notetrackRumbleMapKeys; + m_info_string.SetValueForKey(std::string(field.szName), ss.str()); + break; } - if (fullDef->weapDef.notetrackRumbleMapValues) - { - assert(sizeof(WeaponFullDef::notetrackRumbleMapValues) >= sizeof(scr_string_t) * std::extent<decltype(WeaponFullDef::notetrackRumbleMapKeys)>::value); - memcpy(fullDef->notetrackRumbleMapValues, fullDef->weapDef.notetrackRumbleMapValues, sizeof(scr_string_t) * std::extent<decltype(WeaponFullDef::notetrackRumbleMapKeys)>::value); - fullDef->weapDef.notetrackRumbleMapValues = fullDef->notetrackRumbleMapValues; - } + case WFT_NOTETRACKSOUNDMAP: { + const auto *keys = reinterpret_cast<scr_string_t *>(reinterpret_cast<uintptr_t>(m_structure) + field.iOffset); + const auto *values = &keys[std::extent<decltype(WeaponFullDef::notetrackSoundMapKeys)>::value]; + std::stringstream ss; + bool first = true; + + for (auto i = 0u; i < std::extent<decltype(WeaponFullDef::notetrackSoundMapKeys)>::value; i++) { + const auto &key = m_get_scr_string(keys[i]); + const auto &value = m_get_scr_string(values[i]); + if (!key.empty()) { + if (!first) + ss << "\n"; + else + first = false; + + ss << key; + + if (!value.empty()) + ss << " " << value; + } + } - if (fullDef->weapDef.worldModel) - { - assert(sizeof(WeaponFullDef::worldModel) >= sizeof(void*) * std::extent<decltype(WeaponFullDef::worldModel)>::value); - memcpy(fullDef->worldModel, fullDef->weapDef.worldModel, sizeof(void*) * std::extent<decltype(WeaponFullDef::worldModel)>::value); - fullDef->weapDef.worldModel = fullDef->worldModel; + m_info_string.SetValueForKey(std::string(field.szName), ss.str()); + break; } - if (fullDef->weapDef.parallelBounce) - { - assert(sizeof(WeaponFullDef::parallelBounce) >= sizeof(float) * std::extent<decltype(WeaponFullDef::parallelBounce)>::value); - memcpy(fullDef->parallelBounce, fullDef->weapDef.parallelBounce, sizeof(float) * std::extent<decltype(WeaponFullDef::parallelBounce)>::value); - fullDef->weapDef.parallelBounce = fullDef->parallelBounce; - } + case WFT_NOTETRACKRUMBLEMAP: { + const auto *keys = reinterpret_cast<scr_string_t *>(reinterpret_cast<uintptr_t>(m_structure) + field.iOffset); + const auto *values = &keys[std::extent<decltype(WeaponFullDef::notetrackRumbleMapKeys)>::value]; + std::stringstream ss; + bool first = true; + + for (auto i = 0u; i < std::extent<decltype(WeaponFullDef::notetrackRumbleMapKeys)>::value; i++) { + const auto &key = m_get_scr_string(keys[i]); + const auto &value = m_get_scr_string(values[i]); + if (!key.empty()) { + if (!first) + ss << "\n"; + else + first = false; + + ss << key; + + if (!value.empty()) + ss << " " << value; + } + } - if (fullDef->weapDef.perpendicularBounce) - { - assert(sizeof(WeaponFullDef::perpendicularBounce) >= sizeof(float) * std::extent<decltype(WeaponFullDef::perpendicularBounce)>::value); - memcpy(fullDef->perpendicularBounce, fullDef->weapDef.perpendicularBounce, sizeof(float) * std::extent<decltype(WeaponFullDef::perpendicularBounce)>::value); - fullDef->weapDef.perpendicularBounce = fullDef->perpendicularBounce; + m_info_string.SetValueForKey(std::string(field.szName), ss.str()); + break; } - if (fullDef->weapDef.locationDamageMultipliers) - { - assert(sizeof(WeaponFullDef::locationDamageMultipliers) >= sizeof(float) * std::extent<decltype(WeaponFullDef::locationDamageMultipliers)>::value); - memcpy(fullDef->locationDamageMultipliers, fullDef->weapDef.locationDamageMultipliers, sizeof(float) * std::extent<decltype(WeaponFullDef::locationDamageMultipliers)>::value); - fullDef->weapDef.locationDamageMultipliers = fullDef->locationDamageMultipliers; + case WFT_NUM_FIELD_TYPES: + default: + assert(false); + break; } + } + +public: + InfoStringFromWeaponConverter(const WeaponFullDef *structure, const cspField_t *fields, const size_t fieldCount, + std::function<std::string(scr_string_t)> scriptStringValueCallback) + : InfoStringFromStructConverter(structure, fields, fieldCount, std::move(scriptStringValueCallback)) {} +}; +} // namespace IW4 + +void AssetDumperWeapon::CopyToFullDef(const WeaponCompleteDef *weapon, WeaponFullDef *fullDef) { + fullDef->weapCompleteDef = *weapon; + + if (weapon->weapDef) { + fullDef->weapDef = *weapon->weapDef; + fullDef->weapCompleteDef.weapDef = &fullDef->weapDef; + } + + if (weapon->hideTags) { + assert(sizeof(WeaponFullDef::hideTags) >= sizeof(scr_string_t) * std::extent<decltype(WeaponFullDef::hideTags)>::value); + memcpy(fullDef->hideTags, weapon->hideTags, sizeof(scr_string_t) * std::extent<decltype(WeaponFullDef::hideTags)>::value); + fullDef->weapCompleteDef.hideTags = fullDef->hideTags; + } + + if (weapon->szXAnims) { + assert(sizeof(WeaponFullDef::szXAnims) >= sizeof(void *) * NUM_WEAP_ANIMS); + memcpy(fullDef->szXAnims, weapon->szXAnims, sizeof(void *) * NUM_WEAP_ANIMS); + fullDef->weapCompleteDef.szXAnims = fullDef->szXAnims; + } + + if (fullDef->weapDef.gunXModel) { + assert(sizeof(WeaponFullDef::gunXModel) >= sizeof(void *) * std::extent<decltype(WeaponFullDef::gunXModel)>::value); + memcpy(fullDef->gunXModel, fullDef->weapDef.gunXModel, sizeof(void *) * std::extent<decltype(WeaponFullDef::gunXModel)>::value); + fullDef->weapDef.gunXModel = fullDef->gunXModel; + } + + if (fullDef->weapDef.szXAnimsRightHanded) { + assert(sizeof(WeaponFullDef::szXAnimsRightHanded) >= sizeof(void *) * NUM_WEAP_ANIMS); + memcpy(fullDef->szXAnimsRightHanded, fullDef->weapDef.szXAnimsRightHanded, sizeof(void *) * NUM_WEAP_ANIMS); + fullDef->weapDef.szXAnimsRightHanded = fullDef->szXAnimsRightHanded; + } + + if (fullDef->weapDef.szXAnimsLeftHanded) { + assert(sizeof(WeaponFullDef::szXAnimsLeftHanded) >= sizeof(void *) * NUM_WEAP_ANIMS); + memcpy(fullDef->szXAnimsLeftHanded, fullDef->weapDef.szXAnimsLeftHanded, sizeof(void *) * NUM_WEAP_ANIMS); + fullDef->weapDef.szXAnimsLeftHanded = fullDef->szXAnimsLeftHanded; + } + + if (fullDef->weapDef.notetrackSoundMapKeys) { + assert(sizeof(WeaponFullDef::notetrackSoundMapKeys) >= sizeof(scr_string_t) * std::extent<decltype(WeaponFullDef::notetrackSoundMapKeys)>::value); + memcpy(fullDef->notetrackSoundMapKeys, fullDef->weapDef.notetrackSoundMapKeys, + sizeof(scr_string_t) * std::extent<decltype(WeaponFullDef::notetrackSoundMapKeys)>::value); + fullDef->weapDef.notetrackSoundMapKeys = fullDef->notetrackSoundMapKeys; + } + + if (fullDef->weapDef.notetrackSoundMapValues) { + assert(sizeof(WeaponFullDef::notetrackSoundMapValues) >= sizeof(scr_string_t) * std::extent<decltype(WeaponFullDef::notetrackSoundMapKeys)>::value); + memcpy(fullDef->notetrackSoundMapValues, fullDef->weapDef.notetrackSoundMapValues, + sizeof(scr_string_t) * std::extent<decltype(WeaponFullDef::notetrackSoundMapKeys)>::value); + fullDef->weapDef.notetrackSoundMapValues = fullDef->notetrackSoundMapValues; + } + + if (fullDef->weapDef.notetrackRumbleMapKeys) { + assert(sizeof(WeaponFullDef::notetrackRumbleMapKeys) >= sizeof(scr_string_t) * std::extent<decltype(WeaponFullDef::notetrackRumbleMapKeys)>::value); + memcpy(fullDef->notetrackRumbleMapKeys, fullDef->weapDef.notetrackRumbleMapKeys, + sizeof(scr_string_t) * std::extent<decltype(WeaponFullDef::notetrackRumbleMapKeys)>::value); + fullDef->weapDef.notetrackRumbleMapKeys = fullDef->notetrackRumbleMapKeys; + } + + if (fullDef->weapDef.notetrackRumbleMapValues) { + assert(sizeof(WeaponFullDef::notetrackRumbleMapValues) >= sizeof(scr_string_t) * std::extent<decltype(WeaponFullDef::notetrackRumbleMapKeys)>::value); + memcpy(fullDef->notetrackRumbleMapValues, fullDef->weapDef.notetrackRumbleMapValues, + sizeof(scr_string_t) * std::extent<decltype(WeaponFullDef::notetrackRumbleMapKeys)>::value); + fullDef->weapDef.notetrackRumbleMapValues = fullDef->notetrackRumbleMapValues; + } + + if (fullDef->weapDef.worldModel) { + assert(sizeof(WeaponFullDef::worldModel) >= sizeof(void *) * std::extent<decltype(WeaponFullDef::worldModel)>::value); + memcpy(fullDef->worldModel, fullDef->weapDef.worldModel, sizeof(void *) * std::extent<decltype(WeaponFullDef::worldModel)>::value); + fullDef->weapDef.worldModel = fullDef->worldModel; + } + + if (fullDef->weapDef.parallelBounce) { + assert(sizeof(WeaponFullDef::parallelBounce) >= sizeof(float) * std::extent<decltype(WeaponFullDef::parallelBounce)>::value); + memcpy(fullDef->parallelBounce, fullDef->weapDef.parallelBounce, sizeof(float) * std::extent<decltype(WeaponFullDef::parallelBounce)>::value); + fullDef->weapDef.parallelBounce = fullDef->parallelBounce; + } + + if (fullDef->weapDef.perpendicularBounce) { + assert(sizeof(WeaponFullDef::perpendicularBounce) >= sizeof(float) * std::extent<decltype(WeaponFullDef::perpendicularBounce)>::value); + memcpy(fullDef->perpendicularBounce, fullDef->weapDef.perpendicularBounce, + sizeof(float) * std::extent<decltype(WeaponFullDef::perpendicularBounce)>::value); + fullDef->weapDef.perpendicularBounce = fullDef->perpendicularBounce; + } + + if (fullDef->weapDef.locationDamageMultipliers) { + assert(sizeof(WeaponFullDef::locationDamageMultipliers) >= sizeof(float) * std::extent<decltype(WeaponFullDef::locationDamageMultipliers)>::value); + memcpy(fullDef->locationDamageMultipliers, fullDef->weapDef.locationDamageMultipliers, + sizeof(float) * std::extent<decltype(WeaponFullDef::locationDamageMultipliers)>::value); + fullDef->weapDef.locationDamageMultipliers = fullDef->locationDamageMultipliers; + } } -InfoString AssetDumperWeapon::CreateInfoString(XAssetInfo<WeaponCompleteDef>* asset) -{ - const auto fullDef = std::make_unique<WeaponFullDef>(); - memset(fullDef.get(), 0, sizeof(WeaponFullDef)); - CopyToFullDef(asset->Asset(), fullDef.get()); +InfoString AssetDumperWeapon::CreateInfoString(XAssetInfo<WeaponCompleteDef> *asset) { + const auto fullDef = std::make_unique<WeaponFullDef>(); + memset(fullDef.get(), 0, sizeof(WeaponFullDef)); + CopyToFullDef(asset->Asset(), fullDef.get()); - InfoStringFromWeaponConverter converter(fullDef.get(), weapon_fields, std::extent<decltype(weapon_fields)>::value, [asset](const scr_string_t scrStr) -> std::string - { - assert(scrStr < asset->m_zone->m_script_strings.Count()); - if (scrStr >= asset->m_zone->m_script_strings.Count()) - return ""; + InfoStringFromWeaponConverter converter(fullDef.get(), weapon_fields, std::extent<decltype(weapon_fields)>::value, + [asset](const scr_string_t scrStr) -> std::string { + assert(scrStr < asset->m_zone->m_script_strings.Count()); + if (scrStr >= asset->m_zone->m_script_strings.Count()) + return ""; - return asset->m_zone->m_script_strings[scrStr]; - }); - - return converter.Convert(); -} + return asset->m_zone->m_script_strings[scrStr]; + }); -bool AssetDumperWeapon::ShouldDump(XAssetInfo<WeaponCompleteDef>* asset) -{ - return true; + return converter.Convert(); } -void AssetDumperWeapon::DumpAsset(AssetDumpingContext& context, XAssetInfo<WeaponCompleteDef>* asset) -{ - // Only dump raw when no gdt available - if (context.m_gdt) - { - const auto infoString = CreateInfoString(asset); - GdtEntry gdtEntry(asset->m_name, ObjConstants::GDF_FILENAME_WEAPON); - infoString.ToGdtProperties(ObjConstants::INFO_STRING_PREFIX_WEAPON, gdtEntry); - context.m_gdt->WriteEntry(gdtEntry); - } - else - { - const auto assetFile = context.OpenAssetFile("weapons/" + asset->m_name); - - if (!assetFile) - return; - - auto& stream = *assetFile; - const auto infoString = CreateInfoString(asset); - const auto stringValue = infoString.ToString(ObjConstants::INFO_STRING_PREFIX_WEAPON); - stream.write(stringValue.c_str(), stringValue.size()); - } +bool AssetDumperWeapon::ShouldDump(XAssetInfo<WeaponCompleteDef> *asset) { return true; } + +void AssetDumperWeapon::DumpAsset(AssetDumpingContext &context, XAssetInfo<WeaponCompleteDef> *asset) { + // Only dump raw when no gdt available + if (context.m_gdt) { + const auto infoString = CreateInfoString(asset); + GdtEntry gdtEntry(asset->m_name, ObjConstants::GDF_FILENAME_WEAPON); + infoString.ToGdtProperties(ObjConstants::INFO_STRING_PREFIX_WEAPON, gdtEntry); + context.m_gdt->WriteEntry(gdtEntry); + } else { + const auto assetFile = context.OpenAssetFile("weapons/" + asset->m_name); + + if (!assetFile) + return; + + auto &stream = *assetFile; + const auto infoString = CreateInfoString(asset); + const auto stringValue = infoString.ToString(ObjConstants::INFO_STRING_PREFIX_WEAPON); + stream.write(stringValue.c_str(), stringValue.size()); + } } diff --git a/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperWeapon.h b/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperWeapon.h index 0407b7506..428082881 100644 --- a/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperWeapon.h +++ b/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperWeapon.h @@ -4,15 +4,13 @@ #include "Game/IW4/IW4.h" #include "InfoString/InfoString.h" -namespace IW4 -{ - class AssetDumperWeapon final : public AbstractAssetDumper<WeaponCompleteDef> - { - static void CopyToFullDef(const WeaponCompleteDef* weapon, WeaponFullDef* fullDef); - static InfoString CreateInfoString(XAssetInfo<WeaponCompleteDef>* asset); +namespace IW4 { +class AssetDumperWeapon final : public AbstractAssetDumper<WeaponCompleteDef> { + static void CopyToFullDef(const WeaponCompleteDef *weapon, WeaponFullDef *fullDef); + static InfoString CreateInfoString(XAssetInfo<WeaponCompleteDef> *asset); - protected: - bool ShouldDump(XAssetInfo<WeaponCompleteDef>* asset) override; - void DumpAsset(AssetDumpingContext& context, XAssetInfo<WeaponCompleteDef>* asset) override; - }; -} +protected: + bool ShouldDump(XAssetInfo<WeaponCompleteDef> *asset) override; + void DumpAsset(AssetDumpingContext &context, XAssetInfo<WeaponCompleteDef> *asset) override; +}; +} // namespace IW4 diff --git a/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperXModel.cpp b/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperXModel.cpp index c0243cec6..43d211003 100644 --- a/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperXModel.cpp +++ b/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperXModel.cpp @@ -2,645 +2,529 @@ #include <cassert> -#include "ObjWriting.h" #include "Game/IW4/CommonIW4.h" #include "Math/Quaternion.h" #include "Model/XModel/XModelExportWriter.h" +#include "ObjWriting.h" #include "Utils/HalfFloat.h" #include "Utils/QuatInt16.h" using namespace IW4; -namespace IW4 -{ - class SurfsDumpingZoneState final : public IZoneAssetDumperState - { - std::set<const XModelSurfs*> m_dumped_surfs; +namespace IW4 { +class SurfsDumpingZoneState final : public IZoneAssetDumperState { + std::set<const XModelSurfs *> m_dumped_surfs; - public: - bool ShouldDumpTechnique(const XModelSurfs* surfs) - { - if (m_dumped_surfs.find(surfs) != m_dumped_surfs.end()) - return false; +public: + bool ShouldDumpTechnique(const XModelSurfs *surfs) { + if (m_dumped_surfs.find(surfs) != m_dumped_surfs.end()) + return false; - m_dumped_surfs.emplace(surfs); - return true; - } - }; -} + m_dumped_surfs.emplace(surfs); + return true; + } +}; +} // namespace IW4 -bool AssetDumperXModel::ShouldDump(XAssetInfo<XModel>* asset) -{ - return !asset->m_name.empty() && asset->m_name[0] != ','; -} +bool AssetDumperXModel::ShouldDump(XAssetInfo<XModel> *asset) { return !asset->m_name.empty() && asset->m_name[0] != ','; } -GfxImage* AssetDumperXModel::GetMaterialColorMap(const Material* material) -{ - std::vector<MaterialTextureDef*> potentialTextureDefs; +GfxImage *AssetDumperXModel::GetMaterialColorMap(const Material *material) { + std::vector<MaterialTextureDef *> potentialTextureDefs; - for (auto textureIndex = 0u; textureIndex < material->textureCount; textureIndex++) - { - MaterialTextureDef* def = &material->textureTable[textureIndex]; + for (auto textureIndex = 0u; textureIndex < material->textureCount; textureIndex++) { + MaterialTextureDef *def = &material->textureTable[textureIndex]; - if (def->semantic == TS_COLOR_MAP) - potentialTextureDefs.push_back(def); - } + if (def->semantic == TS_COLOR_MAP) + potentialTextureDefs.push_back(def); + } - if (potentialTextureDefs.empty()) - return nullptr; - if (potentialTextureDefs.size() == 1) - return potentialTextureDefs[0]->u.image; + if (potentialTextureDefs.empty()) + return nullptr; + if (potentialTextureDefs.size() == 1) + return potentialTextureDefs[0]->u.image; - for (const auto* def : potentialTextureDefs) - { - if (def->nameStart == 'c' && def->nameEnd == 'p') - return def->u.image; - } + for (const auto *def : potentialTextureDefs) { + if (def->nameStart == 'c' && def->nameEnd == 'p') + return def->u.image; + } - return potentialTextureDefs[0]->u.image; + return potentialTextureDefs[0]->u.image; } -GfxImage* AssetDumperXModel::GetMaterialNormalMap(const Material* material) -{ - std::vector<MaterialTextureDef*> potentialTextureDefs; +GfxImage *AssetDumperXModel::GetMaterialNormalMap(const Material *material) { + std::vector<MaterialTextureDef *> potentialTextureDefs; - for (auto textureIndex = 0u; textureIndex < material->textureCount; textureIndex++) - { - MaterialTextureDef* def = &material->textureTable[textureIndex]; + for (auto textureIndex = 0u; textureIndex < material->textureCount; textureIndex++) { + MaterialTextureDef *def = &material->textureTable[textureIndex]; - if (def->semantic == TS_NORMAL_MAP) - potentialTextureDefs.push_back(def); - } + if (def->semantic == TS_NORMAL_MAP) + potentialTextureDefs.push_back(def); + } - if (potentialTextureDefs.empty()) - return nullptr; - if (potentialTextureDefs.size() == 1) - return potentialTextureDefs[0]->u.image; + if (potentialTextureDefs.empty()) + return nullptr; + if (potentialTextureDefs.size() == 1) + return potentialTextureDefs[0]->u.image; - for (const auto* def : potentialTextureDefs) - { - if (def->nameStart == 'n' && def->nameEnd == 'p') - return def->u.image; - } + for (const auto *def : potentialTextureDefs) { + if (def->nameStart == 'n' && def->nameEnd == 'p') + return def->u.image; + } - return potentialTextureDefs[0]->u.image; + return potentialTextureDefs[0]->u.image; } -GfxImage* AssetDumperXModel::GetMaterialSpecularMap(const Material* material) -{ - std::vector<MaterialTextureDef*> potentialTextureDefs; +GfxImage *AssetDumperXModel::GetMaterialSpecularMap(const Material *material) { + std::vector<MaterialTextureDef *> potentialTextureDefs; - for (auto textureIndex = 0u; textureIndex < material->textureCount; textureIndex++) - { - MaterialTextureDef* def = &material->textureTable[textureIndex]; + for (auto textureIndex = 0u; textureIndex < material->textureCount; textureIndex++) { + MaterialTextureDef *def = &material->textureTable[textureIndex]; - if (def->semantic == TS_SPECULAR_MAP) - potentialTextureDefs.push_back(def); - } + if (def->semantic == TS_SPECULAR_MAP) + potentialTextureDefs.push_back(def); + } - if (potentialTextureDefs.empty()) - return nullptr; - if (potentialTextureDefs.size() == 1) - return potentialTextureDefs[0]->u.image; + if (potentialTextureDefs.empty()) + return nullptr; + if (potentialTextureDefs.size() == 1) + return potentialTextureDefs[0]->u.image; - for (const auto* def : potentialTextureDefs) - { - if (def->nameStart == 's' && def->nameEnd == 'p') - return def->u.image; - } + for (const auto *def : potentialTextureDefs) { + if (def->nameStart == 's' && def->nameEnd == 'p') + return def->u.image; + } - return potentialTextureDefs[0]->u.image; + return potentialTextureDefs[0]->u.image; } -void AssetDumperXModel::AddObjMaterials(ObjWriter& writer, DistinctMapper<Material*>& materialMapper, const XModel* model) -{ - if (!model->materialHandles) - return; +void AssetDumperXModel::AddObjMaterials(ObjWriter &writer, DistinctMapper<Material *> &materialMapper, const XModel *model) { + if (!model->materialHandles) + return; - for (auto surfIndex = 0u; surfIndex < model->numsurfs; surfIndex++) - { - Material* material = model->materialHandles[surfIndex]; - if (!materialMapper.Add(material)) - continue; + for (auto surfIndex = 0u; surfIndex < model->numsurfs; surfIndex++) { + Material *material = model->materialHandles[surfIndex]; + if (!materialMapper.Add(material)) + continue; - MtlMaterial mtl; - mtl.materialName = std::string(material->info.name); + MtlMaterial mtl; + mtl.materialName = std::string(material->info.name); - GfxImage* colorMap = GetMaterialColorMap(material); - GfxImage* normalMap = GetMaterialNormalMap(material); - GfxImage* specularMap = GetMaterialSpecularMap(material); + GfxImage *colorMap = GetMaterialColorMap(material); + GfxImage *normalMap = GetMaterialNormalMap(material); + GfxImage *specularMap = GetMaterialSpecularMap(material); - if (colorMap != nullptr) - mtl.colorMapName = colorMap->name; - if (normalMap != nullptr) - mtl.normalMapName = normalMap->name; - if (specularMap != nullptr) - mtl.specularMapName = specularMap->name; + if (colorMap != nullptr) + mtl.colorMapName = colorMap->name; + if (normalMap != nullptr) + mtl.normalMapName = normalMap->name; + if (specularMap != nullptr) + mtl.specularMapName = specularMap->name; - writer.AddMaterial(std::move(mtl)); - } + writer.AddMaterial(std::move(mtl)); + } } -void AssetDumperXModel::AddObjObjects(ObjWriter& writer, const DistinctMapper<Material*>& materialMapper, const XModelSurfs* modelSurfs, int baseSurfaceIndex) -{ - for (auto surfIndex = 0u; surfIndex < modelSurfs->numsurfs; surfIndex++) - { - ObjObject object; - object.name = "surf" + std::to_string(surfIndex); - object.materialIndex = static_cast<int>(materialMapper.GetDistinctPositionByInputPosition(surfIndex + baseSurfaceIndex)); +void AssetDumperXModel::AddObjObjects(ObjWriter &writer, const DistinctMapper<Material *> &materialMapper, const XModelSurfs *modelSurfs, + int baseSurfaceIndex) { + for (auto surfIndex = 0u; surfIndex < modelSurfs->numsurfs; surfIndex++) { + ObjObject object; + object.name = "surf" + std::to_string(surfIndex); + object.materialIndex = static_cast<int>(materialMapper.GetDistinctPositionByInputPosition(surfIndex + baseSurfaceIndex)); - writer.AddObject(std::move(object)); - } + writer.AddObject(std::move(object)); + } } -void AssetDumperXModel::AddObjVertices(ObjWriter& writer, const XModelSurfs* modelSurfs) -{ - for (auto surfIndex = 0u; surfIndex < modelSurfs->numsurfs; surfIndex++) - { - const auto& surface = modelSurfs->surfs[surfIndex]; - - for (auto vertexIndex = 0u; vertexIndex < surface.vertCount; vertexIndex++) - { - const auto& v = surface.verts0[vertexIndex]; - vec2_t uv; - vec3_t normalVec; - - Common::Vec2UnpackTexCoords(v.texCoord, &uv); - Common::Vec3UnpackUnitVec(v.normal, &normalVec); - - ObjVertex objVertex{}; - ObjNormal objNormal{}; - ObjUv objUv{}; - objVertex.coordinates[0] = v.xyz[0]; - objVertex.coordinates[1] = v.xyz[2]; - objVertex.coordinates[2] = -v.xyz[1]; - objNormal.normal[0] = normalVec[0]; - objNormal.normal[1] = normalVec[2]; - objNormal.normal[2] = -normalVec[1]; - objUv.uv[0] = uv[0]; - objUv.uv[1] = 1.0f - uv[1]; - - writer.AddVertex(static_cast<int>(surfIndex), objVertex); - writer.AddNormal(static_cast<int>(surfIndex), objNormal); - writer.AddUv(static_cast<int>(surfIndex), objUv); - } +void AssetDumperXModel::AddObjVertices(ObjWriter &writer, const XModelSurfs *modelSurfs) { + for (auto surfIndex = 0u; surfIndex < modelSurfs->numsurfs; surfIndex++) { + const auto &surface = modelSurfs->surfs[surfIndex]; + + for (auto vertexIndex = 0u; vertexIndex < surface.vertCount; vertexIndex++) { + const auto &v = surface.verts0[vertexIndex]; + vec2_t uv; + vec3_t normalVec; + + Common::Vec2UnpackTexCoords(v.texCoord, &uv); + Common::Vec3UnpackUnitVec(v.normal, &normalVec); + + ObjVertex objVertex{}; + ObjNormal objNormal{}; + ObjUv objUv{}; + objVertex.coordinates[0] = v.xyz[0]; + objVertex.coordinates[1] = v.xyz[2]; + objVertex.coordinates[2] = -v.xyz[1]; + objNormal.normal[0] = normalVec[0]; + objNormal.normal[1] = normalVec[2]; + objNormal.normal[2] = -normalVec[1]; + objUv.uv[0] = uv[0]; + objUv.uv[1] = 1.0f - uv[1]; + + writer.AddVertex(static_cast<int>(surfIndex), objVertex); + writer.AddNormal(static_cast<int>(surfIndex), objNormal); + writer.AddUv(static_cast<int>(surfIndex), objUv); } + } } -void AssetDumperXModel::AddObjFaces(ObjWriter& writer, const XModelSurfs* modelSurfs) -{ - for (auto surfIndex = 0u; surfIndex < modelSurfs->numsurfs; surfIndex++) - { - const auto& surface = modelSurfs->surfs[surfIndex]; - for (auto triIndex = 0u; triIndex < surface.triCount; triIndex++) - { - const auto& tri = surface.triIndices[triIndex]; - - ObjFace face{}; - face.vertexIndex[0] = tri[2] + surface.baseVertIndex; - face.vertexIndex[1] = tri[1] + surface.baseVertIndex; - face.vertexIndex[2] = tri[0] + surface.baseVertIndex; - face.normalIndex[0] = face.vertexIndex[0]; - face.normalIndex[1] = face.vertexIndex[1]; - face.normalIndex[2] = face.vertexIndex[2]; - face.uvIndex[0] = face.vertexIndex[0]; - face.uvIndex[1] = face.vertexIndex[1]; - face.uvIndex[2] = face.vertexIndex[2]; - writer.AddFace(static_cast<int>(surfIndex), face); - } +void AssetDumperXModel::AddObjFaces(ObjWriter &writer, const XModelSurfs *modelSurfs) { + for (auto surfIndex = 0u; surfIndex < modelSurfs->numsurfs; surfIndex++) { + const auto &surface = modelSurfs->surfs[surfIndex]; + for (auto triIndex = 0u; triIndex < surface.triCount; triIndex++) { + const auto &tri = surface.triIndices[triIndex]; + + ObjFace face{}; + face.vertexIndex[0] = tri[2] + surface.baseVertIndex; + face.vertexIndex[1] = tri[1] + surface.baseVertIndex; + face.vertexIndex[2] = tri[0] + surface.baseVertIndex; + face.normalIndex[0] = face.vertexIndex[0]; + face.normalIndex[1] = face.vertexIndex[1]; + face.normalIndex[2] = face.vertexIndex[2]; + face.uvIndex[0] = face.vertexIndex[0]; + face.uvIndex[1] = face.vertexIndex[1]; + face.uvIndex[2] = face.vertexIndex[2]; + writer.AddFace(static_cast<int>(surfIndex), face); } + } } -void AssetDumperXModel::DumpObjMat(const AssetDumpingContext& context, XAssetInfo<XModel>* asset) -{ - const auto* model = asset->Asset(); - const auto matFile = context.OpenAssetFile("model_export/" + std::string(model->name) + ".mtl"); +void AssetDumperXModel::DumpObjMat(const AssetDumpingContext &context, XAssetInfo<XModel> *asset) { + const auto *model = asset->Asset(); + const auto matFile = context.OpenAssetFile("model_export/" + std::string(model->name) + ".mtl"); - if (!matFile) - return; + if (!matFile) + return; - ObjWriter writer(context.m_zone->m_game->GetShortName(), context.m_zone->m_name); - DistinctMapper<Material*> materialMapper(model->numsurfs); + ObjWriter writer(context.m_zone->m_game->GetShortName(), context.m_zone->m_name); + DistinctMapper<Material *> materialMapper(model->numsurfs); - AddObjMaterials(writer, materialMapper, model); - writer.WriteMtl(*matFile); + AddObjMaterials(writer, materialMapper, model); + writer.WriteMtl(*matFile); } -void AssetDumperXModel::DumpObjLod(const AssetDumpingContext& context, XAssetInfo<XModel>* asset, const unsigned lod) -{ - const auto* model = asset->Asset(); - const auto* modelSurfs = model->lodInfo[lod].modelSurfs; +void AssetDumperXModel::DumpObjLod(const AssetDumpingContext &context, XAssetInfo<XModel> *asset, const unsigned lod) { + const auto *model = asset->Asset(); + const auto *modelSurfs = model->lodInfo[lod].modelSurfs; - if (modelSurfs->name[0] == ',' || modelSurfs->surfs == nullptr) - return; + if (modelSurfs->name[0] == ',' || modelSurfs->surfs == nullptr) + return; - const auto assetFile = context.OpenAssetFile("model_export/" + std::string(modelSurfs->name) + ".obj"); + const auto assetFile = context.OpenAssetFile("model_export/" + std::string(modelSurfs->name) + ".obj"); - if (!assetFile) - return; + if (!assetFile) + return; - ObjWriter writer(context.m_zone->m_game->GetShortName(), context.m_zone->m_name); - DistinctMapper<Material*> materialMapper(model->numsurfs); + ObjWriter writer(context.m_zone->m_game->GetShortName(), context.m_zone->m_name); + DistinctMapper<Material *> materialMapper(model->numsurfs); - AddObjMaterials(writer, materialMapper, model); - AddObjObjects(writer, materialMapper, modelSurfs, model->lodInfo[lod].surfIndex); - AddObjVertices(writer, modelSurfs); - AddObjFaces(writer, modelSurfs); + AddObjMaterials(writer, materialMapper, model); + AddObjObjects(writer, materialMapper, modelSurfs, model->lodInfo[lod].surfIndex); + AddObjVertices(writer, modelSurfs); + AddObjFaces(writer, modelSurfs); - writer.WriteObj(*assetFile, std::string(model->name) + ".mtl"); + writer.WriteObj(*assetFile, std::string(model->name) + ".mtl"); } -void AssetDumperXModel::DumpObj(AssetDumpingContext& context, XAssetInfo<XModel>* asset) -{ - const auto* model = asset->Asset(); - auto* surfZoneState = context.GetZoneAssetDumperState<SurfsDumpingZoneState>(); +void AssetDumperXModel::DumpObj(AssetDumpingContext &context, XAssetInfo<XModel> *asset) { + const auto *model = asset->Asset(); + auto *surfZoneState = context.GetZoneAssetDumperState<SurfsDumpingZoneState>(); - DumpObjMat(context, asset); - for (auto currentLod = 0u; currentLod < model->numLods; currentLod++) - { - if (!model->lodInfo[currentLod].modelSurfs || !surfZoneState->ShouldDumpTechnique(model->lodInfo[currentLod].modelSurfs)) - continue; + DumpObjMat(context, asset); + for (auto currentLod = 0u; currentLod < model->numLods; currentLod++) { + if (!model->lodInfo[currentLod].modelSurfs || !surfZoneState->ShouldDumpTechnique(model->lodInfo[currentLod].modelSurfs)) + continue; - DumpObjLod(context, asset, currentLod); - } + DumpObjLod(context, asset, currentLod); + } } -void AssetDumperXModel::AddXModelBones(const AssetDumpingContext& context, AbstractXModelWriter& writer, const XModel* model) -{ - for (auto boneNum = 0u; boneNum < model->numBones; boneNum++) - { - XModelBone bone; - if (model->boneNames[boneNum] < context.m_zone->m_script_strings.Count()) - bone.name = context.m_zone->m_script_strings[model->boneNames[boneNum]]; - else - bone.name = "INVALID_BONE_NAME"; - - if (boneNum < model->numRootBones) - bone.parentIndex = -1; - else - bone.parentIndex = static_cast<int>(boneNum - static_cast<unsigned int>(model->parentList[boneNum - model->numRootBones])); - - bone.scale[0] = 1.0f; - bone.scale[1] = 1.0f; - bone.scale[2] = 1.0f; - - bone.globalOffset[0] = model->baseMat[boneNum].trans[0]; - bone.globalOffset[1] = model->baseMat[boneNum].trans[1]; - bone.globalOffset[2] = model->baseMat[boneNum].trans[2]; - bone.globalRotation = Quaternion32(model->baseMat[boneNum].quat[0], model->baseMat[boneNum].quat[1], model->baseMat[boneNum].quat[2], model->baseMat[boneNum].quat[3]); - - if (boneNum < model->numRootBones) - { - bone.localOffset[0] = 0; - bone.localOffset[1] = 0; - bone.localOffset[2] = 0; - bone.localRotation = Quaternion32(0, 0, 0, 1); - } - else - { - bone.localOffset[0] = model->trans[boneNum - model->numRootBones][0]; - bone.localOffset[1] = model->trans[boneNum - model->numRootBones][1]; - bone.localOffset[2] = model->trans[boneNum - model->numRootBones][2]; - bone.localRotation = Quaternion32( - QuatInt16::ToFloat(model->quats[boneNum - model->numRootBones][0]), - QuatInt16::ToFloat(model->quats[boneNum - model->numRootBones][1]), - QuatInt16::ToFloat(model->quats[boneNum - model->numRootBones][2]), - QuatInt16::ToFloat(model->quats[boneNum - model->numRootBones][3]) - ); - } - - writer.AddBone(std::move(bone)); +void AssetDumperXModel::AddXModelBones(const AssetDumpingContext &context, AbstractXModelWriter &writer, const XModel *model) { + for (auto boneNum = 0u; boneNum < model->numBones; boneNum++) { + XModelBone bone; + if (model->boneNames[boneNum] < context.m_zone->m_script_strings.Count()) + bone.name = context.m_zone->m_script_strings[model->boneNames[boneNum]]; + else + bone.name = "INVALID_BONE_NAME"; + + if (boneNum < model->numRootBones) + bone.parentIndex = -1; + else + bone.parentIndex = static_cast<int>(boneNum - static_cast<unsigned int>(model->parentList[boneNum - model->numRootBones])); + + bone.scale[0] = 1.0f; + bone.scale[1] = 1.0f; + bone.scale[2] = 1.0f; + + bone.globalOffset[0] = model->baseMat[boneNum].trans[0]; + bone.globalOffset[1] = model->baseMat[boneNum].trans[1]; + bone.globalOffset[2] = model->baseMat[boneNum].trans[2]; + bone.globalRotation = + Quaternion32(model->baseMat[boneNum].quat[0], model->baseMat[boneNum].quat[1], model->baseMat[boneNum].quat[2], model->baseMat[boneNum].quat[3]); + + if (boneNum < model->numRootBones) { + bone.localOffset[0] = 0; + bone.localOffset[1] = 0; + bone.localOffset[2] = 0; + bone.localRotation = Quaternion32(0, 0, 0, 1); + } else { + bone.localOffset[0] = model->trans[boneNum - model->numRootBones][0]; + bone.localOffset[1] = model->trans[boneNum - model->numRootBones][1]; + bone.localOffset[2] = model->trans[boneNum - model->numRootBones][2]; + bone.localRotation = + Quaternion32(QuatInt16::ToFloat(model->quats[boneNum - model->numRootBones][0]), QuatInt16::ToFloat(model->quats[boneNum - model->numRootBones][1]), + QuatInt16::ToFloat(model->quats[boneNum - model->numRootBones][2]), QuatInt16::ToFloat(model->quats[boneNum - model->numRootBones][3])); } + + writer.AddBone(std::move(bone)); + } } -void AssetDumperXModel::AddXModelMaterials(AbstractXModelWriter& writer, DistinctMapper<Material*>& materialMapper, const XModel* model) -{ - for (auto surfaceMaterialNum = 0; surfaceMaterialNum < model->numsurfs; surfaceMaterialNum++) - { - Material* material = model->materialHandles[surfaceMaterialNum]; - if (materialMapper.Add(material)) - { - XModelMaterial xMaterial; - xMaterial.ApplyDefaults(); - - xMaterial.name = material->info.name; - const auto* colorMap = GetMaterialColorMap(material); - if (colorMap) - xMaterial.colorMapName = std::string(colorMap->name); - - writer.AddMaterial(std::move(xMaterial)); - } +void AssetDumperXModel::AddXModelMaterials(AbstractXModelWriter &writer, DistinctMapper<Material *> &materialMapper, const XModel *model) { + for (auto surfaceMaterialNum = 0; surfaceMaterialNum < model->numsurfs; surfaceMaterialNum++) { + Material *material = model->materialHandles[surfaceMaterialNum]; + if (materialMapper.Add(material)) { + XModelMaterial xMaterial; + xMaterial.ApplyDefaults(); + + xMaterial.name = material->info.name; + const auto *colorMap = GetMaterialColorMap(material); + if (colorMap) + xMaterial.colorMapName = std::string(colorMap->name); + + writer.AddMaterial(std::move(xMaterial)); } + } } -void AssetDumperXModel::AddXModelObjects(AbstractXModelWriter& writer, const XModelSurfs* modelSurfs) -{ - for (auto surfIndex = 0u; surfIndex < modelSurfs->numsurfs; surfIndex++) - { - XModelObject object; - object.name = "surf" + std::to_string(surfIndex); +void AssetDumperXModel::AddXModelObjects(AbstractXModelWriter &writer, const XModelSurfs *modelSurfs) { + for (auto surfIndex = 0u; surfIndex < modelSurfs->numsurfs; surfIndex++) { + XModelObject object; + object.name = "surf" + std::to_string(surfIndex); - writer.AddObject(std::move(object)); - } + writer.AddObject(std::move(object)); + } } -void AssetDumperXModel::AddXModelVertices(AbstractXModelWriter& writer, const XModelSurfs* modelSurfs) -{ - for (auto surfIndex = 0u; surfIndex < modelSurfs->numsurfs; surfIndex++) - { - const auto& surface = modelSurfs->surfs[surfIndex]; - - for (auto vertexIndex = 0u; vertexIndex < surface.vertCount; vertexIndex++) - { - const auto& v = surface.verts0[vertexIndex]; - vec2_t uv; - vec3_t normalVec; - vec4_t color; - - Common::Vec2UnpackTexCoords(v.texCoord, &uv); - Common::Vec3UnpackUnitVec(v.normal, &normalVec); - Common::Vec4UnpackGfxColor(v.color, &color); - - XModelVertex vertex{}; - vertex.coordinates[0] = v.xyz[0]; - vertex.coordinates[1] = v.xyz[1]; - vertex.coordinates[2] = v.xyz[2]; - vertex.normal[0] = normalVec[0]; - vertex.normal[1] = normalVec[1]; - vertex.normal[2] = normalVec[2]; - vertex.color[0] = color[0]; - vertex.color[1] = color[1]; - vertex.color[2] = color[2]; - vertex.color[3] = color[3]; - vertex.uv[0] = uv[0]; - vertex.uv[1] = uv[1]; - - writer.AddVertex(vertex); - } +void AssetDumperXModel::AddXModelVertices(AbstractXModelWriter &writer, const XModelSurfs *modelSurfs) { + for (auto surfIndex = 0u; surfIndex < modelSurfs->numsurfs; surfIndex++) { + const auto &surface = modelSurfs->surfs[surfIndex]; + + for (auto vertexIndex = 0u; vertexIndex < surface.vertCount; vertexIndex++) { + const auto &v = surface.verts0[vertexIndex]; + vec2_t uv; + vec3_t normalVec; + vec4_t color; + + Common::Vec2UnpackTexCoords(v.texCoord, &uv); + Common::Vec3UnpackUnitVec(v.normal, &normalVec); + Common::Vec4UnpackGfxColor(v.color, &color); + + XModelVertex vertex{}; + vertex.coordinates[0] = v.xyz[0]; + vertex.coordinates[1] = v.xyz[1]; + vertex.coordinates[2] = v.xyz[2]; + vertex.normal[0] = normalVec[0]; + vertex.normal[1] = normalVec[1]; + vertex.normal[2] = normalVec[2]; + vertex.color[0] = color[0]; + vertex.color[1] = color[1]; + vertex.color[2] = color[2]; + vertex.color[3] = color[3]; + vertex.uv[0] = uv[0]; + vertex.uv[1] = uv[1]; + + writer.AddVertex(vertex); } + } } -void AssetDumperXModel::AllocateXModelBoneWeights(const XModelSurfs* modelSurfs, XModelVertexBoneWeightCollection& weightCollection) -{ - weightCollection.totalWeightCount = 0u; - for (auto surfIndex = 0u; surfIndex < modelSurfs->numsurfs; surfIndex++) - { - const auto& surface = modelSurfs->surfs[surfIndex]; +void AssetDumperXModel::AllocateXModelBoneWeights(const XModelSurfs *modelSurfs, XModelVertexBoneWeightCollection &weightCollection) { + weightCollection.totalWeightCount = 0u; + for (auto surfIndex = 0u; surfIndex < modelSurfs->numsurfs; surfIndex++) { + const auto &surface = modelSurfs->surfs[surfIndex]; - if (surface.vertList) - { - weightCollection.totalWeightCount += surface.vertListCount; - } + if (surface.vertList) { + weightCollection.totalWeightCount += surface.vertListCount; + } - if (surface.vertInfo.vertsBlend) - { - weightCollection.totalWeightCount += surface.vertInfo.vertCount[0] * 1; - weightCollection.totalWeightCount += surface.vertInfo.vertCount[1] * 2; - weightCollection.totalWeightCount += surface.vertInfo.vertCount[2] * 3; - weightCollection.totalWeightCount += surface.vertInfo.vertCount[3] * 4; - } + if (surface.vertInfo.vertsBlend) { + weightCollection.totalWeightCount += surface.vertInfo.vertCount[0] * 1; + weightCollection.totalWeightCount += surface.vertInfo.vertCount[1] * 2; + weightCollection.totalWeightCount += surface.vertInfo.vertCount[2] * 3; + weightCollection.totalWeightCount += surface.vertInfo.vertCount[3] * 4; } + } - weightCollection.weights = std::make_unique<XModelBoneWeight[]>(weightCollection.totalWeightCount); + weightCollection.weights = std::make_unique<XModelBoneWeight[]>(weightCollection.totalWeightCount); } -void AssetDumperXModel::AddXModelVertexBoneWeights(AbstractXModelWriter& writer, const XModelSurfs* modelSurfs, XModelVertexBoneWeightCollection& weightCollection) -{ - size_t weightOffset = 0u; - - for (auto surfIndex = 0u; surfIndex < modelSurfs->numsurfs; surfIndex++) - { - const auto& surface = modelSurfs->surfs[surfIndex]; - auto handledVertices = 0u; - - if (surface.vertList) - { - for (auto vertListIndex = 0u; vertListIndex < surface.vertListCount; vertListIndex++) - { - const auto& vertList = surface.vertList[vertListIndex]; - const auto* boneWeightOffset = &weightCollection.weights[weightOffset]; - - weightCollection.weights[weightOffset++] = XModelBoneWeight{ - static_cast<int>(vertList.boneOffset / sizeof(DObjSkelMat)), - 1.0f - }; - - for (auto vertListVertexOffset = 0u; vertListVertexOffset < vertList.vertCount; vertListVertexOffset++) - { - writer.AddVertexBoneWeights(XModelVertexBoneWeights{ - boneWeightOffset, - 1 - }); - } - handledVertices += vertList.vertCount; - } - } +void AssetDumperXModel::AddXModelVertexBoneWeights(AbstractXModelWriter &writer, const XModelSurfs *modelSurfs, + XModelVertexBoneWeightCollection &weightCollection) { + size_t weightOffset = 0u; - auto vertsBlendOffset = 0u; - if (surface.vertInfo.vertsBlend) - { - // 1 bone weight - for (auto vertIndex = 0; vertIndex < surface.vertInfo.vertCount[0]; vertIndex++) - { - const auto* boneWeightOffset = &weightCollection.weights[weightOffset]; - const auto boneIndex0 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 0] / sizeof(DObjSkelMat)); - weightCollection.weights[weightOffset++] = XModelBoneWeight{ - boneIndex0, - 1.0f - }; - - vertsBlendOffset += 1; - - writer.AddVertexBoneWeights(XModelVertexBoneWeights{ - boneWeightOffset, - 1 - }); - } - - // 2 bone weights - for (auto vertIndex = 0; vertIndex < surface.vertInfo.vertCount[1]; vertIndex++) - { - const auto* boneWeightOffset = &weightCollection.weights[weightOffset]; - const auto boneIndex0 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 0] / sizeof(DObjSkelMat)); - const auto boneIndex1 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 1] / sizeof(DObjSkelMat)); - const auto boneWeight1 = HalfFloat::ToFloat(surface.vertInfo.vertsBlend[vertsBlendOffset + 2]); - const auto boneWeight0 = 1.0f - boneWeight1; - - weightCollection.weights[weightOffset++] = XModelBoneWeight{ - boneIndex0, - boneWeight0 - }; - weightCollection.weights[weightOffset++] = XModelBoneWeight{ - boneIndex1, - boneWeight1 - }; - - vertsBlendOffset += 3; - - writer.AddVertexBoneWeights(XModelVertexBoneWeights{ - boneWeightOffset, - 2 - }); - } - - // 3 bone weights - for (auto vertIndex = 0; vertIndex < surface.vertInfo.vertCount[2]; vertIndex++) - { - const auto* boneWeightOffset = &weightCollection.weights[weightOffset]; - const auto boneIndex0 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 0] / sizeof(DObjSkelMat)); - const auto boneIndex1 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 1] / sizeof(DObjSkelMat)); - const auto boneWeight1 = HalfFloat::ToFloat(surface.vertInfo.vertsBlend[vertsBlendOffset + 2]); - const auto boneIndex2 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 3] / sizeof(DObjSkelMat)); - const auto boneWeight2 = HalfFloat::ToFloat(surface.vertInfo.vertsBlend[vertsBlendOffset + 4]); - const auto boneWeight0 = 1.0f - boneWeight1 - boneWeight2; - - weightCollection.weights[weightOffset++] = XModelBoneWeight{ - boneIndex0, - boneWeight0 - }; - weightCollection.weights[weightOffset++] = XModelBoneWeight{ - boneIndex1, - boneWeight1 - }; - weightCollection.weights[weightOffset++] = XModelBoneWeight{ - boneIndex2, - boneWeight2 - }; - - vertsBlendOffset += 5; - - writer.AddVertexBoneWeights(XModelVertexBoneWeights{ - boneWeightOffset, - 3 - }); - } - - // 4 bone weights - for (auto vertIndex = 0; vertIndex < surface.vertInfo.vertCount[3]; vertIndex++) - { - const auto* boneWeightOffset = &weightCollection.weights[weightOffset]; - const auto boneIndex0 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 0] / sizeof(DObjSkelMat)); - const auto boneIndex1 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 1] / sizeof(DObjSkelMat)); - const auto boneWeight1 = HalfFloat::ToFloat(surface.vertInfo.vertsBlend[vertsBlendOffset + 2]); - const auto boneIndex2 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 3] / sizeof(DObjSkelMat)); - const auto boneWeight2 = HalfFloat::ToFloat(surface.vertInfo.vertsBlend[vertsBlendOffset + 4]); - const auto boneIndex3 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 5] / sizeof(DObjSkelMat)); - const auto boneWeight3 = HalfFloat::ToFloat(surface.vertInfo.vertsBlend[vertsBlendOffset + 6]); - const auto boneWeight0 = 1.0f - boneWeight1 - boneWeight2 - boneWeight3; - - weightCollection.weights[weightOffset++] = XModelBoneWeight{ - boneIndex0, - boneWeight0 - }; - weightCollection.weights[weightOffset++] = XModelBoneWeight{ - boneIndex1, - boneWeight1 - }; - weightCollection.weights[weightOffset++] = XModelBoneWeight{ - boneIndex2, - boneWeight2 - }; - weightCollection.weights[weightOffset++] = XModelBoneWeight{ - boneIndex3, - boneWeight3 - }; - - vertsBlendOffset += 7; - - writer.AddVertexBoneWeights(XModelVertexBoneWeights{ - boneWeightOffset, - 4 - }); - } - - handledVertices += surface.vertInfo.vertCount[0] + surface.vertInfo.vertCount[1] + surface.vertInfo.vertCount[2] + surface.vertInfo.vertCount[3]; - } + for (auto surfIndex = 0u; surfIndex < modelSurfs->numsurfs; surfIndex++) { + const auto &surface = modelSurfs->surfs[surfIndex]; + auto handledVertices = 0u; - for (; handledVertices < surface.vertCount; handledVertices++) - { - writer.AddVertexBoneWeights(XModelVertexBoneWeights{ - nullptr, - 0 - }); + if (surface.vertList) { + for (auto vertListIndex = 0u; vertListIndex < surface.vertListCount; vertListIndex++) { + const auto &vertList = surface.vertList[vertListIndex]; + const auto *boneWeightOffset = &weightCollection.weights[weightOffset]; + + weightCollection.weights[weightOffset++] = XModelBoneWeight{static_cast<int>(vertList.boneOffset / sizeof(DObjSkelMat)), 1.0f}; + + for (auto vertListVertexOffset = 0u; vertListVertexOffset < vertList.vertCount; vertListVertexOffset++) { + writer.AddVertexBoneWeights(XModelVertexBoneWeights{boneWeightOffset, 1}); } + handledVertices += vertList.vertCount; + } + } + + auto vertsBlendOffset = 0u; + if (surface.vertInfo.vertsBlend) { + // 1 bone weight + for (auto vertIndex = 0; vertIndex < surface.vertInfo.vertCount[0]; vertIndex++) { + const auto *boneWeightOffset = &weightCollection.weights[weightOffset]; + const auto boneIndex0 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 0] / sizeof(DObjSkelMat)); + weightCollection.weights[weightOffset++] = XModelBoneWeight{boneIndex0, 1.0f}; + + vertsBlendOffset += 1; + + writer.AddVertexBoneWeights(XModelVertexBoneWeights{boneWeightOffset, 1}); + } + + // 2 bone weights + for (auto vertIndex = 0; vertIndex < surface.vertInfo.vertCount[1]; vertIndex++) { + const auto *boneWeightOffset = &weightCollection.weights[weightOffset]; + const auto boneIndex0 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 0] / sizeof(DObjSkelMat)); + const auto boneIndex1 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 1] / sizeof(DObjSkelMat)); + const auto boneWeight1 = HalfFloat::ToFloat(surface.vertInfo.vertsBlend[vertsBlendOffset + 2]); + const auto boneWeight0 = 1.0f - boneWeight1; + + weightCollection.weights[weightOffset++] = XModelBoneWeight{boneIndex0, boneWeight0}; + weightCollection.weights[weightOffset++] = XModelBoneWeight{boneIndex1, boneWeight1}; + + vertsBlendOffset += 3; + + writer.AddVertexBoneWeights(XModelVertexBoneWeights{boneWeightOffset, 2}); + } + + // 3 bone weights + for (auto vertIndex = 0; vertIndex < surface.vertInfo.vertCount[2]; vertIndex++) { + const auto *boneWeightOffset = &weightCollection.weights[weightOffset]; + const auto boneIndex0 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 0] / sizeof(DObjSkelMat)); + const auto boneIndex1 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 1] / sizeof(DObjSkelMat)); + const auto boneWeight1 = HalfFloat::ToFloat(surface.vertInfo.vertsBlend[vertsBlendOffset + 2]); + const auto boneIndex2 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 3] / sizeof(DObjSkelMat)); + const auto boneWeight2 = HalfFloat::ToFloat(surface.vertInfo.vertsBlend[vertsBlendOffset + 4]); + const auto boneWeight0 = 1.0f - boneWeight1 - boneWeight2; + + weightCollection.weights[weightOffset++] = XModelBoneWeight{boneIndex0, boneWeight0}; + weightCollection.weights[weightOffset++] = XModelBoneWeight{boneIndex1, boneWeight1}; + weightCollection.weights[weightOffset++] = XModelBoneWeight{boneIndex2, boneWeight2}; + + vertsBlendOffset += 5; + + writer.AddVertexBoneWeights(XModelVertexBoneWeights{boneWeightOffset, 3}); + } + + // 4 bone weights + for (auto vertIndex = 0; vertIndex < surface.vertInfo.vertCount[3]; vertIndex++) { + const auto *boneWeightOffset = &weightCollection.weights[weightOffset]; + const auto boneIndex0 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 0] / sizeof(DObjSkelMat)); + const auto boneIndex1 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 1] / sizeof(DObjSkelMat)); + const auto boneWeight1 = HalfFloat::ToFloat(surface.vertInfo.vertsBlend[vertsBlendOffset + 2]); + const auto boneIndex2 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 3] / sizeof(DObjSkelMat)); + const auto boneWeight2 = HalfFloat::ToFloat(surface.vertInfo.vertsBlend[vertsBlendOffset + 4]); + const auto boneIndex3 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 5] / sizeof(DObjSkelMat)); + const auto boneWeight3 = HalfFloat::ToFloat(surface.vertInfo.vertsBlend[vertsBlendOffset + 6]); + const auto boneWeight0 = 1.0f - boneWeight1 - boneWeight2 - boneWeight3; + + weightCollection.weights[weightOffset++] = XModelBoneWeight{boneIndex0, boneWeight0}; + weightCollection.weights[weightOffset++] = XModelBoneWeight{boneIndex1, boneWeight1}; + weightCollection.weights[weightOffset++] = XModelBoneWeight{boneIndex2, boneWeight2}; + weightCollection.weights[weightOffset++] = XModelBoneWeight{boneIndex3, boneWeight3}; + + vertsBlendOffset += 7; + + writer.AddVertexBoneWeights(XModelVertexBoneWeights{boneWeightOffset, 4}); + } + + handledVertices += surface.vertInfo.vertCount[0] + surface.vertInfo.vertCount[1] + surface.vertInfo.vertCount[2] + surface.vertInfo.vertCount[3]; + } + + for (; handledVertices < surface.vertCount; handledVertices++) { + writer.AddVertexBoneWeights(XModelVertexBoneWeights{nullptr, 0}); } + } } -void AssetDumperXModel::AddXModelFaces(AbstractXModelWriter& writer, const DistinctMapper<Material*>& materialMapper, const XModelSurfs* modelSurfs, - const int baseSurfaceIndex) -{ - for (auto surfIndex = 0u; surfIndex < modelSurfs->numsurfs; surfIndex++) - { - const auto& surface = modelSurfs->surfs[surfIndex]; - for (auto triIndex = 0u; triIndex < surface.triCount; triIndex++) - { - const auto& tri = surface.triIndices[triIndex]; - - XModelFace face{}; - face.vertexIndex[0] = tri[0] + surface.baseVertIndex; - face.vertexIndex[1] = tri[1] + surface.baseVertIndex; - face.vertexIndex[2] = tri[2] + surface.baseVertIndex; - face.objectIndex = static_cast<int>(surfIndex); - face.materialIndex = static_cast<int>(materialMapper.GetDistinctPositionByInputPosition(surfIndex + baseSurfaceIndex)); - writer.AddFace(face); - } +void AssetDumperXModel::AddXModelFaces(AbstractXModelWriter &writer, const DistinctMapper<Material *> &materialMapper, const XModelSurfs *modelSurfs, + const int baseSurfaceIndex) { + for (auto surfIndex = 0u; surfIndex < modelSurfs->numsurfs; surfIndex++) { + const auto &surface = modelSurfs->surfs[surfIndex]; + for (auto triIndex = 0u; triIndex < surface.triCount; triIndex++) { + const auto &tri = surface.triIndices[triIndex]; + + XModelFace face{}; + face.vertexIndex[0] = tri[0] + surface.baseVertIndex; + face.vertexIndex[1] = tri[1] + surface.baseVertIndex; + face.vertexIndex[2] = tri[2] + surface.baseVertIndex; + face.objectIndex = static_cast<int>(surfIndex); + face.materialIndex = static_cast<int>(materialMapper.GetDistinctPositionByInputPosition(surfIndex + baseSurfaceIndex)); + writer.AddFace(face); } + } } -void AssetDumperXModel::DumpXModelExportLod(const AssetDumpingContext& context, XAssetInfo<XModel>* asset, const unsigned lod) -{ - const auto* model = asset->Asset(); - const auto* modelSurfs = model->lodInfo[lod].modelSurfs; +void AssetDumperXModel::DumpXModelExportLod(const AssetDumpingContext &context, XAssetInfo<XModel> *asset, const unsigned lod) { + const auto *model = asset->Asset(); + const auto *modelSurfs = model->lodInfo[lod].modelSurfs; - if (modelSurfs->name[0] == ',' || modelSurfs->surfs == nullptr) - return; + if (modelSurfs->name[0] == ',' || modelSurfs->surfs == nullptr) + return; - const auto assetFile = context.OpenAssetFile("model_export/" + std::string(modelSurfs->name) + ".XMODEL_EXPORT"); + const auto assetFile = context.OpenAssetFile("model_export/" + std::string(modelSurfs->name) + ".XMODEL_EXPORT"); - if (!assetFile) - return; + if (!assetFile) + return; - const auto writer = XModelExportWriter::CreateWriterForVersion6(context.m_zone->m_game->GetShortName(), context.m_zone->m_name); - DistinctMapper<Material*> materialMapper(model->numsurfs); - XModelVertexBoneWeightCollection boneWeightCollection; - AllocateXModelBoneWeights(modelSurfs, boneWeightCollection); + const auto writer = XModelExportWriter::CreateWriterForVersion6(context.m_zone->m_game->GetShortName(), context.m_zone->m_name); + DistinctMapper<Material *> materialMapper(model->numsurfs); + XModelVertexBoneWeightCollection boneWeightCollection; + AllocateXModelBoneWeights(modelSurfs, boneWeightCollection); - AddXModelBones(context, *writer, model); - AddXModelMaterials(*writer, materialMapper, model); - AddXModelObjects(*writer, modelSurfs); - AddXModelVertices(*writer, modelSurfs); - AddXModelVertexBoneWeights(*writer, modelSurfs, boneWeightCollection); - AddXModelFaces(*writer, materialMapper, modelSurfs, model->lodInfo[lod].surfIndex); + AddXModelBones(context, *writer, model); + AddXModelMaterials(*writer, materialMapper, model); + AddXModelObjects(*writer, modelSurfs); + AddXModelVertices(*writer, modelSurfs); + AddXModelVertexBoneWeights(*writer, modelSurfs, boneWeightCollection); + AddXModelFaces(*writer, materialMapper, modelSurfs, model->lodInfo[lod].surfIndex); - writer->Write(*assetFile); + writer->Write(*assetFile); } -void AssetDumperXModel::DumpXModelExport(AssetDumpingContext& context, XAssetInfo<XModel>* asset) -{ - auto* surfZoneState = context.GetZoneAssetDumperState<SurfsDumpingZoneState>(); - const auto* model = asset->Asset(); - for (auto currentLod = 0u; currentLod < model->numLods; currentLod++) - { - if (!model->lodInfo[currentLod].modelSurfs || !surfZoneState->ShouldDumpTechnique(model->lodInfo[currentLod].modelSurfs)) - continue; - DumpXModelExportLod(context, asset, currentLod); - } +void AssetDumperXModel::DumpXModelExport(AssetDumpingContext &context, XAssetInfo<XModel> *asset) { + auto *surfZoneState = context.GetZoneAssetDumperState<SurfsDumpingZoneState>(); + const auto *model = asset->Asset(); + for (auto currentLod = 0u; currentLod < model->numLods; currentLod++) { + if (!model->lodInfo[currentLod].modelSurfs || !surfZoneState->ShouldDumpTechnique(model->lodInfo[currentLod].modelSurfs)) + continue; + DumpXModelExportLod(context, asset, currentLod); + } } -void AssetDumperXModel::DumpAsset(AssetDumpingContext& context, XAssetInfo<XModel>* asset) -{ - switch (ObjWriting::Configuration.ModelOutputFormat) - { - case ObjWriting::Configuration_t::ModelOutputFormat_e::OBJ: - DumpObj(context, asset); - break; - - case ObjWriting::Configuration_t::ModelOutputFormat_e::XMODEL_EXPORT: - DumpXModelExport(context, asset); - break; - - default: - assert(false); - break; - } +void AssetDumperXModel::DumpAsset(AssetDumpingContext &context, XAssetInfo<XModel> *asset) { + switch (ObjWriting::Configuration.ModelOutputFormat) { + case ObjWriting::Configuration_t::ModelOutputFormat_e::OBJ: + DumpObj(context, asset); + break; + + case ObjWriting::Configuration_t::ModelOutputFormat_e::XMODEL_EXPORT: + DumpXModelExport(context, asset); + break; + + default: + assert(false); + break; + } } diff --git a/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperXModel.h b/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperXModel.h index b4f3af49d..39059b556 100644 --- a/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperXModel.h +++ b/src/ObjWriting/Game/IW4/AssetDumpers/AssetDumperXModel.h @@ -2,38 +2,37 @@ #include "Dumping/AbstractAssetDumper.h" #include "Game/IW4/IW4.h" -#include "Utils/DistinctMapper.h" -#include "Model/XModel/AbstractXModelWriter.h" #include "Model/Obj/ObjWriter.h" +#include "Model/XModel/AbstractXModelWriter.h" +#include "Utils/DistinctMapper.h" -namespace IW4 -{ - class AssetDumperXModel final : public AbstractAssetDumper<XModel> - { - static GfxImage* GetMaterialColorMap(const Material* material); - static GfxImage* GetMaterialNormalMap(const Material* material); - static GfxImage* GetMaterialSpecularMap(const Material* material); +namespace IW4 { +class AssetDumperXModel final : public AbstractAssetDumper<XModel> { + static GfxImage *GetMaterialColorMap(const Material *material); + static GfxImage *GetMaterialNormalMap(const Material *material); + static GfxImage *GetMaterialSpecularMap(const Material *material); - static void AddObjMaterials(ObjWriter& writer, DistinctMapper<Material*>& materialMapper, const XModel* model); - static void AddObjObjects(ObjWriter& writer, const DistinctMapper<Material*>& materialMapper, const XModelSurfs* modelSurfs, int baseSurfaceIndex); - static void AddObjVertices(ObjWriter& writer, const XModelSurfs* modelSurfs); - static void AddObjFaces(ObjWriter& writer, const XModelSurfs* modelSurfs); - static void DumpObjLod(const AssetDumpingContext& context, XAssetInfo<XModel>* asset, const unsigned lod); - static void DumpObjMat(const AssetDumpingContext& context, XAssetInfo<XModel>* asset); - static void DumpObj(AssetDumpingContext& context, XAssetInfo<XModel>* asset); + static void AddObjMaterials(ObjWriter &writer, DistinctMapper<Material *> &materialMapper, const XModel *model); + static void AddObjObjects(ObjWriter &writer, const DistinctMapper<Material *> &materialMapper, const XModelSurfs *modelSurfs, int baseSurfaceIndex); + static void AddObjVertices(ObjWriter &writer, const XModelSurfs *modelSurfs); + static void AddObjFaces(ObjWriter &writer, const XModelSurfs *modelSurfs); + static void DumpObjLod(const AssetDumpingContext &context, XAssetInfo<XModel> *asset, const unsigned lod); + static void DumpObjMat(const AssetDumpingContext &context, XAssetInfo<XModel> *asset); + static void DumpObj(AssetDumpingContext &context, XAssetInfo<XModel> *asset); - static void AddXModelBones(const AssetDumpingContext& context, AbstractXModelWriter& writer, const XModel* model); - static void AddXModelMaterials(AbstractXModelWriter& writer, DistinctMapper<Material*>& materialMapper, const XModel* model); - static void AddXModelObjects(AbstractXModelWriter& writer, const XModelSurfs* modelSurfs); - static void AddXModelVertices(AbstractXModelWriter& writer, const XModelSurfs* modelSurfs); - static void AllocateXModelBoneWeights(const XModelSurfs* modelSurfs, XModelVertexBoneWeightCollection& weightCollection); - static void AddXModelVertexBoneWeights(AbstractXModelWriter& writer, const XModelSurfs* modelSurfs, XModelVertexBoneWeightCollection& weightCollection); - static void AddXModelFaces(AbstractXModelWriter& writer, const DistinctMapper<Material*>& materialMapper, const XModelSurfs* modelSurfs, int baseSurfaceIndex); - static void DumpXModelExportLod(const AssetDumpingContext& context, XAssetInfo<XModel>* asset, unsigned lod); - static void DumpXModelExport(AssetDumpingContext& context, XAssetInfo<XModel>* asset); + static void AddXModelBones(const AssetDumpingContext &context, AbstractXModelWriter &writer, const XModel *model); + static void AddXModelMaterials(AbstractXModelWriter &writer, DistinctMapper<Material *> &materialMapper, const XModel *model); + static void AddXModelObjects(AbstractXModelWriter &writer, const XModelSurfs *modelSurfs); + static void AddXModelVertices(AbstractXModelWriter &writer, const XModelSurfs *modelSurfs); + static void AllocateXModelBoneWeights(const XModelSurfs *modelSurfs, XModelVertexBoneWeightCollection &weightCollection); + static void AddXModelVertexBoneWeights(AbstractXModelWriter &writer, const XModelSurfs *modelSurfs, XModelVertexBoneWeightCollection &weightCollection); + static void AddXModelFaces(AbstractXModelWriter &writer, const DistinctMapper<Material *> &materialMapper, const XModelSurfs *modelSurfs, + int baseSurfaceIndex); + static void DumpXModelExportLod(const AssetDumpingContext &context, XAssetInfo<XModel> *asset, unsigned lod); + static void DumpXModelExport(AssetDumpingContext &context, XAssetInfo<XModel> *asset); - protected: - bool ShouldDump(XAssetInfo<XModel>* asset) override; - void DumpAsset(AssetDumpingContext& context, XAssetInfo<XModel>* asset) override; - }; -} +protected: + bool ShouldDump(XAssetInfo<XModel> *asset) override; + void DumpAsset(AssetDumpingContext &context, XAssetInfo<XModel> *asset) override; +}; +} // namespace IW4 diff --git a/src/ObjWriting/Game/IW4/InfoString/InfoStringFromStructConverter.cpp b/src/ObjWriting/Game/IW4/InfoString/InfoStringFromStructConverter.cpp index ca9fe6205..c95e1a2e7 100644 --- a/src/ObjWriting/Game/IW4/InfoString/InfoStringFromStructConverter.cpp +++ b/src/ObjWriting/Game/IW4/InfoString/InfoStringFromStructConverter.cpp @@ -4,156 +4,132 @@ using namespace IW4; -void InfoStringFromStructConverter::FillFromBaseField(const cspField_t& field) -{ - switch (static_cast<csParseFieldType_t>(field.iFieldType)) - { - case CSPFT_STRING: - FillFromString(std::string(field.szName), field.iOffset); - break; - - case CSPFT_STRING_MAX_STRING_CHARS: - FillFromStringBuffer(std::string(field.szName), field.iOffset, 1024); - break; - - case CSPFT_STRING_MAX_QPATH: - FillFromStringBuffer(std::string(field.szName), field.iOffset, 64); - break; - - case CSPFT_STRING_MAX_OSPATH: - FillFromStringBuffer(std::string(field.szName), field.iOffset, 256); - break; - - case CSPFT_INT: - FillFromInt(std::string(field.szName), field.iOffset); - break; - - case CSPFT_QBOOLEAN: - FillFromQBoolean(std::string(field.szName), field.iOffset); - break; - - case CSPFT_BOOL: - FillFromBool(std::string(field.szName), field.iOffset); - break; - - case CSPFT_FLOAT: - FillFromFloat(std::string(field.szName), field.iOffset); - break; - - case CSPFT_MPH_TO_INCHES_PER_SEC: - { - const auto* num = reinterpret_cast<float*>(reinterpret_cast<uintptr_t>(m_structure) + field.iOffset); - m_info_string.SetValueForKey(std::string(field.szName), std::to_string(*num / 17.6f)); - break; - } - - case CSPFT_MILLISECONDS: - FillFromMilliseconds(std::string(field.szName), field.iOffset); - break; - - case CSPFT_FX: - { - const auto* fx = *reinterpret_cast<FxEffectDef**>(reinterpret_cast<uintptr_t>(m_structure) + field.iOffset); - - if (fx) - m_info_string.SetValueForKey(std::string(field.szName), std::string(AssetName(fx->name))); - else - m_info_string.SetValueForKey(std::string(field.szName), ""); - break; - } - - case CSPFT_XMODEL: - { - const auto* model = *reinterpret_cast<XModel**>(reinterpret_cast<uintptr_t>(m_structure) + field.iOffset); - - if (model) - m_info_string.SetValueForKey(std::string(field.szName), std::string(AssetName(model->name))); - else - m_info_string.SetValueForKey(std::string(field.szName), ""); - break; - } - - case CSPFT_MATERIAL: - { - const auto* material = *reinterpret_cast<Material**>(reinterpret_cast<uintptr_t>(m_structure) + field. - iOffset); - - if (material) - m_info_string.SetValueForKey(std::string(field.szName), std::string(AssetName(material->info.name))); - else - m_info_string.SetValueForKey(std::string(field.szName), ""); - break; - } - - case CSPFT_PHYS_COLLMAP: - { - const auto* physCollMap = *reinterpret_cast<PhysCollmap**>(reinterpret_cast<uintptr_t>(m_structure) + field. - iOffset); - - if (physCollMap) - m_info_string.SetValueForKey(std::string(field.szName), std::string(AssetName(physCollMap->name))); - else - m_info_string.SetValueForKey(std::string(field.szName), ""); - break; - } - - case CSPFT_SOUND: - { - const auto* sndAlias = reinterpret_cast<SndAliasCustom*>(reinterpret_cast<uintptr_t>(m_structure) + field. - iOffset); - - if (sndAlias->name) - m_info_string.SetValueForKey(std::string(field.szName), std::string(sndAlias->name->soundName)); - else - m_info_string.SetValueForKey(std::string(field.szName), ""); - break; - } - - case CSPFT_TRACER: - { - const auto* tracer = *reinterpret_cast<TracerDef**>(reinterpret_cast<uintptr_t>(m_structure) + field. - iOffset); - - if (tracer) - m_info_string.SetValueForKey(std::string(field.szName), std::string(AssetName(tracer->name))); - else - m_info_string.SetValueForKey(std::string(field.szName), ""); - break; - } - - case CSPFT_NUM_BASE_FIELD_TYPES: - default: - assert(false); - break; - } +void InfoStringFromStructConverter::FillFromBaseField(const cspField_t &field) { + switch (static_cast<csParseFieldType_t>(field.iFieldType)) { + case CSPFT_STRING: + FillFromString(std::string(field.szName), field.iOffset); + break; + + case CSPFT_STRING_MAX_STRING_CHARS: + FillFromStringBuffer(std::string(field.szName), field.iOffset, 1024); + break; + + case CSPFT_STRING_MAX_QPATH: + FillFromStringBuffer(std::string(field.szName), field.iOffset, 64); + break; + + case CSPFT_STRING_MAX_OSPATH: + FillFromStringBuffer(std::string(field.szName), field.iOffset, 256); + break; + + case CSPFT_INT: + FillFromInt(std::string(field.szName), field.iOffset); + break; + + case CSPFT_QBOOLEAN: + FillFromQBoolean(std::string(field.szName), field.iOffset); + break; + + case CSPFT_BOOL: + FillFromBool(std::string(field.szName), field.iOffset); + break; + + case CSPFT_FLOAT: + FillFromFloat(std::string(field.szName), field.iOffset); + break; + + case CSPFT_MPH_TO_INCHES_PER_SEC: { + const auto *num = reinterpret_cast<float *>(reinterpret_cast<uintptr_t>(m_structure) + field.iOffset); + m_info_string.SetValueForKey(std::string(field.szName), std::to_string(*num / 17.6f)); + break; + } + + case CSPFT_MILLISECONDS: + FillFromMilliseconds(std::string(field.szName), field.iOffset); + break; + + case CSPFT_FX: { + const auto *fx = *reinterpret_cast<FxEffectDef **>(reinterpret_cast<uintptr_t>(m_structure) + field.iOffset); + + if (fx) + m_info_string.SetValueForKey(std::string(field.szName), std::string(AssetName(fx->name))); + else + m_info_string.SetValueForKey(std::string(field.szName), ""); + break; + } + + case CSPFT_XMODEL: { + const auto *model = *reinterpret_cast<XModel **>(reinterpret_cast<uintptr_t>(m_structure) + field.iOffset); + + if (model) + m_info_string.SetValueForKey(std::string(field.szName), std::string(AssetName(model->name))); + else + m_info_string.SetValueForKey(std::string(field.szName), ""); + break; + } + + case CSPFT_MATERIAL: { + const auto *material = *reinterpret_cast<Material **>(reinterpret_cast<uintptr_t>(m_structure) + field.iOffset); + + if (material) + m_info_string.SetValueForKey(std::string(field.szName), std::string(AssetName(material->info.name))); + else + m_info_string.SetValueForKey(std::string(field.szName), ""); + break; + } + + case CSPFT_PHYS_COLLMAP: { + const auto *physCollMap = *reinterpret_cast<PhysCollmap **>(reinterpret_cast<uintptr_t>(m_structure) + field.iOffset); + + if (physCollMap) + m_info_string.SetValueForKey(std::string(field.szName), std::string(AssetName(physCollMap->name))); + else + m_info_string.SetValueForKey(std::string(field.szName), ""); + break; + } + + case CSPFT_SOUND: { + const auto *sndAlias = reinterpret_cast<SndAliasCustom *>(reinterpret_cast<uintptr_t>(m_structure) + field.iOffset); + + if (sndAlias->name) + m_info_string.SetValueForKey(std::string(field.szName), std::string(sndAlias->name->soundName)); + else + m_info_string.SetValueForKey(std::string(field.szName), ""); + break; + } + + case CSPFT_TRACER: { + const auto *tracer = *reinterpret_cast<TracerDef **>(reinterpret_cast<uintptr_t>(m_structure) + field.iOffset); + + if (tracer) + m_info_string.SetValueForKey(std::string(field.szName), std::string(AssetName(tracer->name))); + else + m_info_string.SetValueForKey(std::string(field.szName), ""); + break; + } + + case CSPFT_NUM_BASE_FIELD_TYPES: + default: + assert(false); + break; + } } -void InfoStringFromStructConverter::FillInfoString() -{ - for (auto fieldIndex = 0u; fieldIndex < m_field_count; fieldIndex++) - { - const auto& field = m_fields[fieldIndex]; - assert(field.iFieldType >= 0); - - if (field.iFieldType < CSPFT_NUM_BASE_FIELD_TYPES) - FillFromBaseField(field); - else - FillFromExtensionField(field); - } -} +void InfoStringFromStructConverter::FillInfoString() { + for (auto fieldIndex = 0u; fieldIndex < m_field_count; fieldIndex++) { + const auto &field = m_fields[fieldIndex]; + assert(field.iFieldType >= 0); -InfoStringFromStructConverter::InfoStringFromStructConverter(const void* structure, const cspField_t* fields, - const size_t fieldCount) - : InfoStringFromStructConverterBase(structure), - m_fields(fields), - m_field_count(fieldCount) -{ + if (field.iFieldType < CSPFT_NUM_BASE_FIELD_TYPES) + FillFromBaseField(field); + else + FillFromExtensionField(field); + } } -InfoStringFromStructConverter::InfoStringFromStructConverter(const void* structure, const cspField_t* fields, const size_t fieldCount, - std::function<std::string(scr_string_t)> scriptStringValueCallback) - : InfoStringFromStructConverterBase(structure, std::move(scriptStringValueCallback)), - m_fields(fields), - m_field_count(fieldCount) -{ -} +InfoStringFromStructConverter::InfoStringFromStructConverter(const void *structure, const cspField_t *fields, const size_t fieldCount) + : InfoStringFromStructConverterBase(structure), m_fields(fields), m_field_count(fieldCount) {} + +InfoStringFromStructConverter::InfoStringFromStructConverter(const void *structure, const cspField_t *fields, const size_t fieldCount, + std::function<std::string(scr_string_t)> scriptStringValueCallback) + : InfoStringFromStructConverterBase(structure, std::move(scriptStringValueCallback)), m_fields(fields), m_field_count(fieldCount) {} diff --git a/src/ObjWriting/Game/IW4/InfoString/InfoStringFromStructConverter.h b/src/ObjWriting/Game/IW4/InfoString/InfoStringFromStructConverter.h index 2e33b602d..e49998643 100644 --- a/src/ObjWriting/Game/IW4/InfoString/InfoStringFromStructConverter.h +++ b/src/ObjWriting/Game/IW4/InfoString/InfoStringFromStructConverter.h @@ -1,21 +1,20 @@ #pragma once -#include "InfoString/InfoStringFromStructConverterBase.h" #include "Game/IW4/IW4.h" +#include "InfoString/InfoStringFromStructConverterBase.h" -namespace IW4 -{ - class InfoStringFromStructConverter : public InfoStringFromStructConverterBase - { - protected: - const cspField_t* m_fields; - size_t m_field_count; +namespace IW4 { +class InfoStringFromStructConverter : public InfoStringFromStructConverterBase { +protected: + const cspField_t *m_fields; + size_t m_field_count; - virtual void FillFromExtensionField(const cspField_t& field) = 0; - void FillFromBaseField(const cspField_t& field); - void FillInfoString() override; + virtual void FillFromExtensionField(const cspField_t &field) = 0; + void FillFromBaseField(const cspField_t &field); + void FillInfoString() override; - public: - InfoStringFromStructConverter(const void* structure, const cspField_t* fields, size_t fieldCount); - InfoStringFromStructConverter(const void* structure, const cspField_t* fields, size_t fieldCount, std::function<std::string(scr_string_t)> scriptStringValueCallback); - }; -} \ No newline at end of file +public: + InfoStringFromStructConverter(const void *structure, const cspField_t *fields, size_t fieldCount); + InfoStringFromStructConverter(const void *structure, const cspField_t *fields, size_t fieldCount, + std::function<std::string(scr_string_t)> scriptStringValueCallback); +}; +} // namespace IW4 \ No newline at end of file diff --git a/src/ObjWriting/Game/IW4/Menu/MenuDumperIW4.cpp b/src/ObjWriting/Game/IW4/Menu/MenuDumperIW4.cpp index 9aa5b3383..10c30b8c9 100644 --- a/src/ObjWriting/Game/IW4/Menu/MenuDumperIW4.cpp +++ b/src/ObjWriting/Game/IW4/Menu/MenuDumperIW4.cpp @@ -1,836 +1,740 @@ #include "MenuDumperIW4.h" -#include <cmath> #include <cassert> +#include <cmath> #include <sstream> -#include "ObjWriting.h" #include "Game/IW4/MenuConstantsIW4.h" +#include "ObjWriting.h" using namespace IW4; -size_t MenuDumper::FindStatementClosingParenthesis(const Statement_s* statement, size_t openingParenthesisPosition) -{ - assert(statement->numEntries >= 0); - assert(openingParenthesisPosition < static_cast<size_t>(statement->numEntries)); - - const auto statementEnd = static_cast<size_t>(statement->numEntries); - - // The openingParenthesisPosition does not necessarily point to an actual opening parenthesis operator. That's fine though. - // We will pretend it does since the game does sometimes leave out opening parenthesis from the entries. - auto currentParenthesisDepth = 1; - for (auto currentSearchPosition = openingParenthesisPosition + 1; currentSearchPosition < statementEnd; currentSearchPosition++) - { - const auto& expEntry = statement->entries[currentSearchPosition]; - if (expEntry.type != EET_OPERATOR) - continue; - - // Any function means a "left out" left paren - if (expEntry.data.op == OP_LEFTPAREN || expEntry.data.op >= OP_COUNT) - { - currentParenthesisDepth++; - } - else if (expEntry.data.op == OP_RIGHTPAREN) - { - if (currentParenthesisDepth > 0) - currentParenthesisDepth--; - if (currentParenthesisDepth == 0) - return currentSearchPosition; - } +size_t MenuDumper::FindStatementClosingParenthesis(const Statement_s *statement, size_t openingParenthesisPosition) { + assert(statement->numEntries >= 0); + assert(openingParenthesisPosition < static_cast<size_t>(statement->numEntries)); + + const auto statementEnd = static_cast<size_t>(statement->numEntries); + + // The openingParenthesisPosition does not necessarily point to an actual opening parenthesis operator. That's fine though. + // We will pretend it does since the game does sometimes leave out opening parenthesis from the entries. + auto currentParenthesisDepth = 1; + for (auto currentSearchPosition = openingParenthesisPosition + 1; currentSearchPosition < statementEnd; currentSearchPosition++) { + const auto &expEntry = statement->entries[currentSearchPosition]; + if (expEntry.type != EET_OPERATOR) + continue; + + // Any function means a "left out" left paren + if (expEntry.data.op == OP_LEFTPAREN || expEntry.data.op >= OP_COUNT) { + currentParenthesisDepth++; + } else if (expEntry.data.op == OP_RIGHTPAREN) { + if (currentParenthesisDepth > 0) + currentParenthesisDepth--; + if (currentParenthesisDepth == 0) + return currentSearchPosition; } + } - return statementEnd; + return statementEnd; } -void MenuDumper::WriteStatementOperator(const Statement_s* statement, size_t& currentPos, bool& spaceNext) const -{ - const auto& expEntry = statement->entries[currentPos]; +void MenuDumper::WriteStatementOperator(const Statement_s *statement, size_t ¤tPos, bool &spaceNext) const { + const auto &expEntry = statement->entries[currentPos]; - if (spaceNext && expEntry.data.op != OP_COMMA) - m_stream << " "; + if (spaceNext && expEntry.data.op != OP_COMMA) + m_stream << " "; - if (expEntry.data.op == OP_LEFTPAREN) - { - const auto closingParenPos = FindStatementClosingParenthesis(statement, currentPos); - m_stream << "("; - WriteStatementEntryRange(statement, currentPos + 1, closingParenPos); - m_stream << ")"; + if (expEntry.data.op == OP_LEFTPAREN) { + const auto closingParenPos = FindStatementClosingParenthesis(statement, currentPos); + m_stream << "("; + WriteStatementEntryRange(statement, currentPos + 1, closingParenPos); + m_stream << ")"; - currentPos = closingParenPos + 1; - spaceNext = true; - } - else if (expEntry.data.op >= EXP_FUNC_STATIC_DVAR_INT && expEntry.data.op <= EXP_FUNC_STATIC_DVAR_STRING) - { - switch (expEntry.data.op) - { - case EXP_FUNC_STATIC_DVAR_INT: - m_stream << "dvarint"; - break; - - case EXP_FUNC_STATIC_DVAR_BOOL: - m_stream << "dvarbool"; - break; - - case EXP_FUNC_STATIC_DVAR_FLOAT: - m_stream << "dvarfloat"; - break; - - case EXP_FUNC_STATIC_DVAR_STRING: - m_stream << "dvarstring"; - break; - - default: - break; - } + currentPos = closingParenPos + 1; + spaceNext = true; + } else if (expEntry.data.op >= EXP_FUNC_STATIC_DVAR_INT && expEntry.data.op <= EXP_FUNC_STATIC_DVAR_STRING) { + switch (expEntry.data.op) { + case EXP_FUNC_STATIC_DVAR_INT: + m_stream << "dvarint"; + break; - // Functions do not have opening parenthesis in the entries. We can just pretend they do though - const auto closingParenPos = FindStatementClosingParenthesis(statement, currentPos); - m_stream << "("; - - if (closingParenPos - currentPos + 1 >= 1) - { - const auto& staticDvarEntry = statement->entries[currentPos + 1]; - if (staticDvarEntry.type == EET_OPERAND && staticDvarEntry.data.operand.dataType == VAL_INT) - { - if (statement->supportingData - && statement->supportingData->staticDvarList.staticDvars - && staticDvarEntry.data.operand.internals.intVal >= 0 - && staticDvarEntry.data.operand.internals.intVal < statement->supportingData->staticDvarList.numStaticDvars) - { - const auto* staticDvar = statement->supportingData->staticDvarList.staticDvars[staticDvarEntry.data.operand.internals.intVal]; - if (staticDvar && staticDvar->dvarName) - m_stream << staticDvar->dvarName; - } - else - { - m_stream << "#INVALID_DVAR_INDEX"; - } - } - else - { - m_stream << "#INVALID_DVAR_OPERAND"; - } - } + case EXP_FUNC_STATIC_DVAR_BOOL: + m_stream << "dvarbool"; + break; + + case EXP_FUNC_STATIC_DVAR_FLOAT: + m_stream << "dvarfloat"; + break; + + case EXP_FUNC_STATIC_DVAR_STRING: + m_stream << "dvarstring"; + break; - m_stream << ")"; - currentPos = closingParenPos + 1; - spaceNext = true; + default: + break; } - else - { - if (expEntry.data.op >= 0 && static_cast<unsigned>(expEntry.data.op) < std::extent_v<decltype(g_expFunctionNames)>) - m_stream << g_expFunctionNames[expEntry.data.op]; - - if (expEntry.data.op >= OP_COUNT) - { - // Functions do not have opening parenthesis in the entries. We can just pretend they do though - const auto closingParenPos = FindStatementClosingParenthesis(statement, currentPos); - m_stream << "("; - WriteStatementEntryRange(statement, currentPos + 1, closingParenPos); - m_stream << ")"; - currentPos = closingParenPos + 1; - } - else - currentPos++; - spaceNext = expEntry.data.op != OP_NOT; + // Functions do not have opening parenthesis in the entries. We can just pretend they do though + const auto closingParenPos = FindStatementClosingParenthesis(statement, currentPos); + m_stream << "("; + + if (closingParenPos - currentPos + 1 >= 1) { + const auto &staticDvarEntry = statement->entries[currentPos + 1]; + if (staticDvarEntry.type == EET_OPERAND && staticDvarEntry.data.operand.dataType == VAL_INT) { + if (statement->supportingData && statement->supportingData->staticDvarList.staticDvars && staticDvarEntry.data.operand.internals.intVal >= 0 && + staticDvarEntry.data.operand.internals.intVal < statement->supportingData->staticDvarList.numStaticDvars) { + const auto *staticDvar = statement->supportingData->staticDvarList.staticDvars[staticDvarEntry.data.operand.internals.intVal]; + if (staticDvar && staticDvar->dvarName) + m_stream << staticDvar->dvarName; + } else { + m_stream << "#INVALID_DVAR_INDEX"; + } + } else { + m_stream << "#INVALID_DVAR_OPERAND"; + } } + + m_stream << ")"; + currentPos = closingParenPos + 1; + spaceNext = true; + } else { + if (expEntry.data.op >= 0 && static_cast<unsigned>(expEntry.data.op) < std::extent_v<decltype(g_expFunctionNames)>) + m_stream << g_expFunctionNames[expEntry.data.op]; + + if (expEntry.data.op >= OP_COUNT) { + // Functions do not have opening parenthesis in the entries. We can just pretend they do though + const auto closingParenPos = FindStatementClosingParenthesis(statement, currentPos); + m_stream << "("; + WriteStatementEntryRange(statement, currentPos + 1, closingParenPos); + m_stream << ")"; + currentPos = closingParenPos + 1; + } else + currentPos++; + + spaceNext = expEntry.data.op != OP_NOT; + } } -void MenuDumper::WriteStatementOperandFunction(const Statement_s* statement, const size_t currentPos) const -{ - const auto& operand = statement->entries[currentPos].data.operand; - - if (operand.internals.function == nullptr) - return; - - if (!ObjWriting::Configuration.MenuLegacyMode) - { - int functionIndex = -1; - if (statement->supportingData && statement->supportingData->uifunctions.functions) - { - for (auto supportingFunctionIndex = 0; supportingFunctionIndex < statement->supportingData->uifunctions.totalFunctions; supportingFunctionIndex++) - { - if (statement->supportingData->uifunctions.functions[supportingFunctionIndex] == operand.internals.function) - { - functionIndex = supportingFunctionIndex; - break; - } - } - } +void MenuDumper::WriteStatementOperandFunction(const Statement_s *statement, const size_t currentPos) const { + const auto &operand = statement->entries[currentPos].data.operand; + + if (operand.internals.function == nullptr) + return; - if (functionIndex >= 0) - m_stream << "FUNC_" << functionIndex << "()"; - else - m_stream << "INVALID_FUNC"; - m_stream << "()"; + if (!ObjWriting::Configuration.MenuLegacyMode) { + int functionIndex = -1; + if (statement->supportingData && statement->supportingData->uifunctions.functions) { + for (auto supportingFunctionIndex = 0; supportingFunctionIndex < statement->supportingData->uifunctions.totalFunctions; supportingFunctionIndex++) { + if (statement->supportingData->uifunctions.functions[supportingFunctionIndex] == operand.internals.function) { + functionIndex = supportingFunctionIndex; + break; + } + } } + + if (functionIndex >= 0) + m_stream << "FUNC_" << functionIndex << "()"; else - { - m_stream << "("; - WriteStatementSkipInitialUnnecessaryParenthesis(operand.internals.function); - m_stream << ")"; - } + m_stream << "INVALID_FUNC"; + m_stream << "()"; + } else { + m_stream << "("; + WriteStatementSkipInitialUnnecessaryParenthesis(operand.internals.function); + m_stream << ")"; + } } -void MenuDumper::WriteStatementOperand(const Statement_s* statement, size_t& currentPos, bool& spaceNext) const -{ - const auto& expEntry = statement->entries[currentPos]; +void MenuDumper::WriteStatementOperand(const Statement_s *statement, size_t ¤tPos, bool &spaceNext) const { + const auto &expEntry = statement->entries[currentPos]; - if (spaceNext) - m_stream << " "; + if (spaceNext) + m_stream << " "; - const auto& operand = expEntry.data.operand; + const auto &operand = expEntry.data.operand; - switch (operand.dataType) - { - case VAL_FLOAT: - m_stream << operand.internals.floatVal; - break; + switch (operand.dataType) { + case VAL_FLOAT: + m_stream << operand.internals.floatVal; + break; - case VAL_INT: - m_stream << operand.internals.intVal; - break; + case VAL_INT: + m_stream << operand.internals.intVal; + break; - case VAL_STRING: - WriteEscapedString(operand.internals.stringVal.string); - break; + case VAL_STRING: + WriteEscapedString(operand.internals.stringVal.string); + break; - case VAL_FUNCTION: - WriteStatementOperandFunction(statement, currentPos); - break; + case VAL_FUNCTION: + WriteStatementOperandFunction(statement, currentPos); + break; - default: - break; - } + default: + break; + } - currentPos++; - spaceNext = true; + currentPos++; + spaceNext = true; } -void MenuDumper::WriteStatementEntryRange(const Statement_s* statement, size_t startOffset, size_t endOffset) const -{ - assert(startOffset <= endOffset); - assert(endOffset <= static_cast<size_t>(statement->numEntries)); +void MenuDumper::WriteStatementEntryRange(const Statement_s *statement, size_t startOffset, size_t endOffset) const { + assert(startOffset <= endOffset); + assert(endOffset <= static_cast<size_t>(statement->numEntries)); - auto currentPos = startOffset; - auto spaceNext = false; - while (currentPos < endOffset) - { - const auto& expEntry = statement->entries[currentPos]; + auto currentPos = startOffset; + auto spaceNext = false; + while (currentPos < endOffset) { + const auto &expEntry = statement->entries[currentPos]; - if (expEntry.type == EET_OPERATOR) - { - WriteStatementOperator(statement, currentPos, spaceNext); - } - else - { - WriteStatementOperand(statement, currentPos, spaceNext); - } + if (expEntry.type == EET_OPERATOR) { + WriteStatementOperator(statement, currentPos, spaceNext); + } else { + WriteStatementOperand(statement, currentPos, spaceNext); } + } } -void MenuDumper::WriteStatement(const Statement_s* statement) const -{ - if (statement == nullptr || statement->numEntries < 0) - return; +void MenuDumper::WriteStatement(const Statement_s *statement) const { + if (statement == nullptr || statement->numEntries < 0) + return; - WriteStatementEntryRange(statement, 0, static_cast<size_t>(statement->numEntries)); + WriteStatementEntryRange(statement, 0, static_cast<size_t>(statement->numEntries)); } -void MenuDumper::WriteStatementSkipInitialUnnecessaryParenthesis(const Statement_s* statementValue) const -{ - if (statementValue == nullptr || statementValue->numEntries < 0) - return; +void MenuDumper::WriteStatementSkipInitialUnnecessaryParenthesis(const Statement_s *statementValue) const { + if (statementValue == nullptr || statementValue->numEntries < 0) + return; - const auto statementEnd = static_cast<size_t>(statementValue->numEntries); + const auto statementEnd = static_cast<size_t>(statementValue->numEntries); - if (statementValue->numEntries >= 1 - && statementValue->entries[0].type == EET_OPERATOR - && statementValue->entries[0].data.op == OP_LEFTPAREN) - { - const auto parenthesisEnd = FindStatementClosingParenthesis(statementValue, 0); + if (statementValue->numEntries >= 1 && statementValue->entries[0].type == EET_OPERATOR && statementValue->entries[0].data.op == OP_LEFTPAREN) { + const auto parenthesisEnd = FindStatementClosingParenthesis(statementValue, 0); - if (parenthesisEnd >= statementEnd) - WriteStatementEntryRange(statementValue, 1, statementEnd); - else if (parenthesisEnd == statementEnd - 1) - WriteStatementEntryRange(statementValue, 1, statementEnd - 1); - else - WriteStatementEntryRange(statementValue, 0, statementEnd); - } + if (parenthesisEnd >= statementEnd) + WriteStatementEntryRange(statementValue, 1, statementEnd); + else if (parenthesisEnd == statementEnd - 1) + WriteStatementEntryRange(statementValue, 1, statementEnd - 1); else - { - WriteStatementEntryRange(statementValue, 0, statementEnd); - } + WriteStatementEntryRange(statementValue, 0, statementEnd); + } else { + WriteStatementEntryRange(statementValue, 0, statementEnd); + } } -void MenuDumper::WriteStatementProperty(const std::string& propertyKey, const Statement_s* statementValue, bool isBooleanStatement) const -{ - if (statementValue == nullptr || statementValue->numEntries < 0) - return; +void MenuDumper::WriteStatementProperty(const std::string &propertyKey, const Statement_s *statementValue, bool isBooleanStatement) const { + if (statementValue == nullptr || statementValue->numEntries < 0) + return; - Indent(); - WriteKey(propertyKey); + Indent(); + WriteKey(propertyKey); - if (isBooleanStatement) - { - m_stream << "when("; - WriteStatementSkipInitialUnnecessaryParenthesis(statementValue); - m_stream << ");\n"; - } - else - { - WriteStatementSkipInitialUnnecessaryParenthesis(statementValue); - m_stream << ";\n"; - } + if (isBooleanStatement) { + m_stream << "when("; + WriteStatementSkipInitialUnnecessaryParenthesis(statementValue); + m_stream << ");\n"; + } else { + WriteStatementSkipInitialUnnecessaryParenthesis(statementValue); + m_stream << ";\n"; + } } -void MenuDumper::WriteSetLocalVarData(const std::string& setFunction, const SetLocalVarData* setLocalVarData) const -{ - if (setLocalVarData == nullptr) - return; +void MenuDumper::WriteSetLocalVarData(const std::string &setFunction, const SetLocalVarData *setLocalVarData) const { + if (setLocalVarData == nullptr) + return; - Indent(); - m_stream << setFunction << " " << setLocalVarData->localVarName << " "; - WriteStatement(setLocalVarData->expression); - m_stream << ";\n"; + Indent(); + m_stream << setFunction << " " << setLocalVarData->localVarName << " "; + WriteStatement(setLocalVarData->expression); + m_stream << ";\n"; } -//#define WRITE_ORIGINAL_SCRIPT +// #define WRITE_ORIGINAL_SCRIPT -void MenuDumper::WriteUnconditionalScript(const char* script) const -{ +void MenuDumper::WriteUnconditionalScript(const char *script) const { #ifdef WRITE_ORIGINAL_SCRIPT - Indent(); - m_stream << script << "\n"; - return; + Indent(); + m_stream << script << "\n"; + return; #endif - const auto tokenList = CreateScriptTokenList(script); + const auto tokenList = CreateScriptTokenList(script); - auto isNewStatement = true; - for (const auto& token : tokenList) - { - if (isNewStatement) - { - if (token == ";") - continue; + auto isNewStatement = true; + for (const auto &token : tokenList) { + if (isNewStatement) { + if (token == ";") + continue; - Indent(); - } - - if (token == ";") - { - m_stream << ";\n"; - isNewStatement = true; - continue; - } - - if (!isNewStatement) - m_stream << " "; - else - isNewStatement = false; + Indent(); + } - if (DoesTokenNeedQuotationMarks(token)) - m_stream << "\"" << token << "\""; - else - m_stream << token; + if (token == ";") { + m_stream << ";\n"; + isNewStatement = true; + continue; } if (!isNewStatement) - m_stream << ";\n"; -} + m_stream << " "; + else + isNewStatement = false; -void MenuDumper::WriteMenuEventHandlerSet(const MenuEventHandlerSet* eventHandlerSet) -{ - Indent(); - m_stream << "{\n"; - IncIndent(); - - for (auto i = 0; i < eventHandlerSet->eventHandlerCount; i++) - { - const auto* eventHandler = eventHandlerSet->eventHandlers[i]; - if (eventHandler == nullptr) - continue; - - switch (eventHandler->eventType) - { - case EVENT_UNCONDITIONAL: - WriteUnconditionalScript(eventHandler->eventData.unconditionalScript); - break; - - case EVENT_IF: - if (eventHandler->eventData.conditionalScript == nullptr - || eventHandler->eventData.conditionalScript->eventExpression == nullptr - || eventHandler->eventData.conditionalScript->eventHandlerSet == nullptr) - { - continue; - } - - Indent(); - m_stream << "if ("; - WriteStatementSkipInitialUnnecessaryParenthesis(eventHandler->eventData.conditionalScript->eventExpression); - m_stream << ")\n"; - WriteMenuEventHandlerSet(eventHandler->eventData.conditionalScript->eventHandlerSet); - break; - - case EVENT_ELSE: - if (eventHandler->eventData.elseScript == nullptr) - continue; - - Indent(); - m_stream << "else\n"; - WriteMenuEventHandlerSet(eventHandler->eventData.elseScript); - break; - - case EVENT_SET_LOCAL_VAR_BOOL: - WriteSetLocalVarData("setLocalVarBool", eventHandler->eventData.setLocalVarData); - break; - - case EVENT_SET_LOCAL_VAR_INT: - WriteSetLocalVarData("setLocalVarInt", eventHandler->eventData.setLocalVarData); - break; - - case EVENT_SET_LOCAL_VAR_FLOAT: - WriteSetLocalVarData("setLocalVarFloat", eventHandler->eventData.setLocalVarData); - break; - - case EVENT_SET_LOCAL_VAR_STRING: - WriteSetLocalVarData("setLocalVarString", eventHandler->eventData.setLocalVarData); - break; - - default: - break; - } - } + if (DoesTokenNeedQuotationMarks(token)) + m_stream << "\"" << token << "\""; + else + m_stream << token; + } - DecIndent(); - Indent(); - m_stream << "}\n"; + if (!isNewStatement) + m_stream << ";\n"; } -void MenuDumper::WriteMenuEventHandlerSetProperty(const std::string& propertyKey, const MenuEventHandlerSet* eventHandlerSetValue) -{ - if (eventHandlerSetValue == nullptr) - return; +void MenuDumper::WriteMenuEventHandlerSet(const MenuEventHandlerSet *eventHandlerSet) { + Indent(); + m_stream << "{\n"; + IncIndent(); - Indent(); - m_stream << propertyKey << "\n"; - WriteMenuEventHandlerSet(eventHandlerSetValue); -} + for (auto i = 0; i < eventHandlerSet->eventHandlerCount; i++) { + const auto *eventHandler = eventHandlerSet->eventHandlers[i]; + if (eventHandler == nullptr) + continue; -void MenuDumper::WriteRectProperty(const std::string& propertyKey, const rectDef_s& rect) const -{ - Indent(); - WriteKey(propertyKey); - m_stream << rect.x << " " << rect.y << " " << rect.w << " " << rect.h << " " << static_cast<int>(rect.horzAlign) << " " << static_cast<int>(rect.vertAlign) << "\n"; -} + switch (eventHandler->eventType) { + case EVENT_UNCONDITIONAL: + WriteUnconditionalScript(eventHandler->eventData.unconditionalScript); + break; -void MenuDumper::WriteMaterialProperty(const std::string& propertyKey, const Material* materialValue) const -{ - if (materialValue == nullptr || materialValue->info.name == nullptr) - return; + case EVENT_IF: + if (eventHandler->eventData.conditionalScript == nullptr || eventHandler->eventData.conditionalScript->eventExpression == nullptr || + eventHandler->eventData.conditionalScript->eventHandlerSet == nullptr) { + continue; + } - if (materialValue->info.name[0] == ',') - WriteStringProperty(propertyKey, &materialValue->info.name[1]); - else - WriteStringProperty(propertyKey, materialValue->info.name); -} + Indent(); + m_stream << "if ("; + WriteStatementSkipInitialUnnecessaryParenthesis(eventHandler->eventData.conditionalScript->eventExpression); + m_stream << ")\n"; + WriteMenuEventHandlerSet(eventHandler->eventData.conditionalScript->eventHandlerSet); + break; -void MenuDumper::WriteSoundAliasProperty(const std::string& propertyKey, const snd_alias_list_t* soundAliasValue) const -{ - if (soundAliasValue == nullptr) - return; + case EVENT_ELSE: + if (eventHandler->eventData.elseScript == nullptr) + continue; - WriteStringProperty(propertyKey, soundAliasValue->aliasName); -} + Indent(); + m_stream << "else\n"; + WriteMenuEventHandlerSet(eventHandler->eventData.elseScript); + break; -void MenuDumper::WriteDecodeEffectProperty(const std::string& propertyKey, const itemDef_s* item) const -{ - if (!item->decayActive) - return; + case EVENT_SET_LOCAL_VAR_BOOL: + WriteSetLocalVarData("setLocalVarBool", eventHandler->eventData.setLocalVarData); + break; - Indent(); - WriteKey(propertyKey); - m_stream << item->fxLetterTime << " " << item->fxDecayStartTime << " " << item->fxDecayDuration << "\n"; -} - -void MenuDumper::WriteItemKeyHandlerProperty(const ItemKeyHandler* itemKeyHandlerValue) -{ - for (const auto* currentHandler = itemKeyHandlerValue; currentHandler; currentHandler = currentHandler->next) - { - if (currentHandler->key >= '!' && currentHandler->key <= '~' && currentHandler->key != '"') - { - std::ostringstream ss; - ss << "execKey \"" << static_cast<char>(currentHandler->key) << "\""; - WriteMenuEventHandlerSetProperty(ss.str(), currentHandler->action); - } - else - { - std::ostringstream ss; - ss << "execKeyInt " << currentHandler->key; - WriteMenuEventHandlerSetProperty(ss.str(), currentHandler->action); - } + case EVENT_SET_LOCAL_VAR_INT: + WriteSetLocalVarData("setLocalVarInt", eventHandler->eventData.setLocalVarData); + break; + + case EVENT_SET_LOCAL_VAR_FLOAT: + WriteSetLocalVarData("setLocalVarFloat", eventHandler->eventData.setLocalVarData); + break; + + case EVENT_SET_LOCAL_VAR_STRING: + WriteSetLocalVarData("setLocalVarString", eventHandler->eventData.setLocalVarData); + break; + + default: + break; } + } + + DecIndent(); + Indent(); + m_stream << "}\n"; } -void MenuDumper::WriteFloatExpressionsProperty(const ItemFloatExpression* floatExpressions, int floatExpressionCount) const -{ - if (!floatExpressions) - return; +void MenuDumper::WriteMenuEventHandlerSetProperty(const std::string &propertyKey, const MenuEventHandlerSet *eventHandlerSetValue) { + if (eventHandlerSetValue == nullptr) + return; - for (int i = 0; i < floatExpressionCount; i++) - { - const auto& floatExpression = floatExpressions[i]; + Indent(); + m_stream << propertyKey << "\n"; + WriteMenuEventHandlerSet(eventHandlerSetValue); +} - if (floatExpression.target < 0 || floatExpression.target >= ITEM_FLOATEXP_TGT_COUNT) - continue; +void MenuDumper::WriteRectProperty(const std::string &propertyKey, const rectDef_s &rect) const { + Indent(); + WriteKey(propertyKey); + m_stream << rect.x << " " << rect.y << " " << rect.w << " " << rect.h << " " << static_cast<int>(rect.horzAlign) << " " << static_cast<int>(rect.vertAlign) + << "\n"; +} - std::string propertyName = std::string("exp ") + floatExpressionTargetBindings[floatExpression.target].name + std::string(" ") - + floatExpressionTargetBindings[floatExpression.target].componentName; +void MenuDumper::WriteMaterialProperty(const std::string &propertyKey, const Material *materialValue) const { + if (materialValue == nullptr || materialValue->info.name == nullptr) + return; - WriteStatementProperty(propertyName, floatExpression.expression, false); - } + if (materialValue->info.name[0] == ',') + WriteStringProperty(propertyKey, &materialValue->info.name[1]); + else + WriteStringProperty(propertyKey, materialValue->info.name); } -void MenuDumper::WriteMultiTokenStringProperty(const std::string& propertyKey, const char* value) const -{ - if (!value) - return; +void MenuDumper::WriteSoundAliasProperty(const std::string &propertyKey, const snd_alias_list_t *soundAliasValue) const { + if (soundAliasValue == nullptr) + return; - Indent(); - WriteKey(propertyKey); - - const auto tokenList = CreateScriptTokenList(value); - - auto firstToken = true; - m_stream << "{ "; - for (const auto& token : tokenList) - { - if (firstToken) - firstToken = false; - else - m_stream << ";"; - m_stream << "\"" << token << "\""; - } - if (!firstToken) - m_stream << " "; - m_stream << "}\n"; + WriteStringProperty(propertyKey, soundAliasValue->aliasName); } -void MenuDumper::WriteColumnProperty(const std::string& propertyKey, const listBoxDef_s* listBox) const -{ - if (listBox->numColumns <= 0) - return; +void MenuDumper::WriteDecodeEffectProperty(const std::string &propertyKey, const itemDef_s *item) const { + if (!item->decayActive) + return; - Indent(); - WriteKey(propertyKey); - m_stream << listBox->numColumns << "\n"; - - for (auto col = 0; col < listBox->numColumns; col++) - { - Indent(); - for (auto i = 0u; i < MENU_KEY_SPACING; i++) - m_stream << " "; - - m_stream << listBox->columnInfo[col].pos - << " " << listBox->columnInfo[col].width - << " " << listBox->columnInfo[col].maxChars - << " " << listBox->columnInfo[col].alignment << "\n"; + Indent(); + WriteKey(propertyKey); + m_stream << item->fxLetterTime << " " << item->fxDecayStartTime << " " << item->fxDecayDuration << "\n"; +} + +void MenuDumper::WriteItemKeyHandlerProperty(const ItemKeyHandler *itemKeyHandlerValue) { + for (const auto *currentHandler = itemKeyHandlerValue; currentHandler; currentHandler = currentHandler->next) { + if (currentHandler->key >= '!' && currentHandler->key <= '~' && currentHandler->key != '"') { + std::ostringstream ss; + ss << "execKey \"" << static_cast<char>(currentHandler->key) << "\""; + WriteMenuEventHandlerSetProperty(ss.str(), currentHandler->action); + } else { + std::ostringstream ss; + ss << "execKeyInt " << currentHandler->key; + WriteMenuEventHandlerSetProperty(ss.str(), currentHandler->action); } + } } -void MenuDumper::WriteListBoxProperties(const itemDef_s* item) -{ - if (item->type != ITEM_TYPE_LISTBOX || item->typeData.listBox == nullptr) - return; +void MenuDumper::WriteFloatExpressionsProperty(const ItemFloatExpression *floatExpressions, int floatExpressionCount) const { + if (!floatExpressions) + return; - const auto* listBox = item->typeData.listBox; - WriteKeywordProperty("notselectable", listBox->notselectable != 0); - WriteKeywordProperty("noscrollbars", listBox->noScrollBars != 0); - WriteKeywordProperty("usepaging", listBox->usePaging != 0); - WriteFloatProperty("elementwidth", listBox->elementWidth, 0.0f); - WriteFloatProperty("elementheight", listBox->elementHeight, 0.0f); - WriteFloatProperty("feeder", item->special, 0.0f); - WriteIntProperty("elementtype", listBox->elementStyle, 0); - WriteColumnProperty("columns", listBox); - WriteMenuEventHandlerSetProperty("doubleclick", listBox->onDoubleClick); - WriteColorProperty("selectBorder", listBox->selectBorder, COLOR_0000); - WriteMaterialProperty("selectIcon", listBox->selectIcon); -} + for (int i = 0; i < floatExpressionCount; i++) { + const auto &floatExpression = floatExpressions[i]; -void MenuDumper::WriteDvarFloatProperty(const std::string& propertyKey, const itemDef_s* item, const editFieldDef_s* editField) const -{ - if (item->dvar == nullptr) - return; + if (floatExpression.target < 0 || floatExpression.target >= ITEM_FLOATEXP_TGT_COUNT) + continue; - Indent(); - WriteKey(propertyKey); - m_stream << "\"" << item->dvar << "\" " << editField->defVal << " " << editField->minVal << " " << editField->maxVal << "\n"; -} - -void MenuDumper::WriteEditFieldProperties(const itemDef_s* item) const -{ - switch (item->type) - { - case ITEM_TYPE_TEXT: - case ITEM_TYPE_EDITFIELD: - case ITEM_TYPE_NUMERICFIELD: - case ITEM_TYPE_SLIDER: - case ITEM_TYPE_YESNO: - case ITEM_TYPE_BIND: - case ITEM_TYPE_VALIDFILEFIELD: - case ITEM_TYPE_DECIMALFIELD: - case ITEM_TYPE_UPREDITFIELD: - case ITEM_TYPE_EMAILFIELD: - case ITEM_TYPE_PASSWORDFIELD: - break; + std::string propertyName = std::string("exp ") + floatExpressionTargetBindings[floatExpression.target].name + std::string(" ") + + floatExpressionTargetBindings[floatExpression.target].componentName; - default: - return; - } + WriteStatementProperty(propertyName, floatExpression.expression, false); + } +} - if (item->typeData.editField == nullptr) - return; +void MenuDumper::WriteMultiTokenStringProperty(const std::string &propertyKey, const char *value) const { + if (!value) + return; - const auto* editField = item->typeData.editField; - if (std::fabs(-1.0f - editField->defVal) >= std::numeric_limits<float>::epsilon() - || std::fabs(-1.0f - editField->minVal) >= std::numeric_limits<float>::epsilon() - || std::fabs(-1.0f - editField->maxVal) >= std::numeric_limits<float>::epsilon()) - { - WriteDvarFloatProperty("dvarFloat", item, editField); - } + Indent(); + WriteKey(propertyKey); + + const auto tokenList = CreateScriptTokenList(value); + + auto firstToken = true; + m_stream << "{ "; + for (const auto &token : tokenList) { + if (firstToken) + firstToken = false; else - { - WriteStringProperty("dvar", item->dvar); - } - WriteStringProperty("localvar", item->localVar); - WriteIntProperty("maxChars", editField->maxChars, 0); - WriteKeywordProperty("maxCharsGotoNext", editField->maxCharsGotoNext != 0); - WriteIntProperty("maxPaintChars", editField->maxPaintChars, 0); + m_stream << ";"; + m_stream << "\"" << token << "\""; + } + if (!firstToken) + m_stream << " "; + m_stream << "}\n"; } -void MenuDumper::WriteMultiValueProperty(const multiDef_s* multiDef) const -{ - Indent(); - if (multiDef->strDef) - WriteKey("dvarStrList"); - else - WriteKey("dvarFloatList"); +void MenuDumper::WriteColumnProperty(const std::string &propertyKey, const listBoxDef_s *listBox) const { + if (listBox->numColumns <= 0) + return; - m_stream << "{"; - for (auto i = 0; i < multiDef->count; i++) - { - if (multiDef->dvarList[i] == nullptr || multiDef->strDef && multiDef->dvarStr[i] == nullptr) - continue; + Indent(); + WriteKey(propertyKey); + m_stream << listBox->numColumns << "\n"; - m_stream << " \"" << multiDef->dvarList[i] << "\""; + for (auto col = 0; col < listBox->numColumns; col++) { + Indent(); + for (auto i = 0u; i < MENU_KEY_SPACING; i++) + m_stream << " "; - if (multiDef->strDef) - m_stream << " \"" << multiDef->dvarStr[i] << "\""; - else - m_stream << " " << multiDef->dvarValue[i] << ""; - } - m_stream << " }\n"; + m_stream << listBox->columnInfo[col].pos << " " << listBox->columnInfo[col].width << " " << listBox->columnInfo[col].maxChars << " " + << listBox->columnInfo[col].alignment << "\n"; + } } -void MenuDumper::WriteMultiProperties(const itemDef_s* item) const -{ - if (item->type != ITEM_TYPE_MULTI || item->typeData.multi == nullptr) - return; +void MenuDumper::WriteListBoxProperties(const itemDef_s *item) { + if (item->type != ITEM_TYPE_LISTBOX || item->typeData.listBox == nullptr) + return; - const auto* multiDef = item->typeData.multi; + const auto *listBox = item->typeData.listBox; + WriteKeywordProperty("notselectable", listBox->notselectable != 0); + WriteKeywordProperty("noscrollbars", listBox->noScrollBars != 0); + WriteKeywordProperty("usepaging", listBox->usePaging != 0); + WriteFloatProperty("elementwidth", listBox->elementWidth, 0.0f); + WriteFloatProperty("elementheight", listBox->elementHeight, 0.0f); + WriteFloatProperty("feeder", item->special, 0.0f); + WriteIntProperty("elementtype", listBox->elementStyle, 0); + WriteColumnProperty("columns", listBox); + WriteMenuEventHandlerSetProperty("doubleclick", listBox->onDoubleClick); + WriteColorProperty("selectBorder", listBox->selectBorder, COLOR_0000); + WriteMaterialProperty("selectIcon", listBox->selectIcon); +} + +void MenuDumper::WriteDvarFloatProperty(const std::string &propertyKey, const itemDef_s *item, const editFieldDef_s *editField) const { + if (item->dvar == nullptr) + return; - if (multiDef->count <= 0) - return; + Indent(); + WriteKey(propertyKey); + m_stream << "\"" << item->dvar << "\" " << editField->defVal << " " << editField->minVal << " " << editField->maxVal << "\n"; +} + +void MenuDumper::WriteEditFieldProperties(const itemDef_s *item) const { + switch (item->type) { + case ITEM_TYPE_TEXT: + case ITEM_TYPE_EDITFIELD: + case ITEM_TYPE_NUMERICFIELD: + case ITEM_TYPE_SLIDER: + case ITEM_TYPE_YESNO: + case ITEM_TYPE_BIND: + case ITEM_TYPE_VALIDFILEFIELD: + case ITEM_TYPE_DECIMALFIELD: + case ITEM_TYPE_UPREDITFIELD: + case ITEM_TYPE_EMAILFIELD: + case ITEM_TYPE_PASSWORDFIELD: + break; + + default: + return; + } + if (item->typeData.editField == nullptr) + return; + + const auto *editField = item->typeData.editField; + if (std::fabs(-1.0f - editField->defVal) >= std::numeric_limits<float>::epsilon() || + std::fabs(-1.0f - editField->minVal) >= std::numeric_limits<float>::epsilon() || + std::fabs(-1.0f - editField->maxVal) >= std::numeric_limits<float>::epsilon()) { + WriteDvarFloatProperty("dvarFloat", item, editField); + } else { WriteStringProperty("dvar", item->dvar); - WriteStringProperty("localvar", item->localVar); - WriteMultiValueProperty(multiDef); + } + WriteStringProperty("localvar", item->localVar); + WriteIntProperty("maxChars", editField->maxChars, 0); + WriteKeywordProperty("maxCharsGotoNext", editField->maxCharsGotoNext != 0); + WriteIntProperty("maxPaintChars", editField->maxPaintChars, 0); } -void MenuDumper::WriteEnumDvarProperties(const itemDef_s* item) const -{ - if (item->type != ITEM_TYPE_DVARENUM) - return; +void MenuDumper::WriteMultiValueProperty(const multiDef_s *multiDef) const { + Indent(); + if (multiDef->strDef) + WriteKey("dvarStrList"); + else + WriteKey("dvarFloatList"); - WriteStringProperty("dvar", item->dvar); - WriteStringProperty("localvar", item->localVar); - WriteStringProperty("dvarEnumList", item->typeData.enumDvarName); -} - -void MenuDumper::WriteTickerProperties(const itemDef_s* item) const -{ - if (item->type != ITEM_TYPE_NEWS_TICKER || item->typeData.ticker == nullptr) - return; - - const auto* newsTickerDef = item->typeData.ticker; - WriteIntProperty("spacing", newsTickerDef->spacing, 0); - WriteIntProperty("speed", newsTickerDef->speed, 0); - WriteIntProperty("newsfeed", newsTickerDef->feedId, 0); -} - -void MenuDumper::WriteItemData(const itemDef_s* item) -{ - WriteStringProperty("name", item->window.name); - WriteStringProperty("text", item->text); - WriteKeywordProperty("textsavegame", item->itemFlags & ITEM_FLAG_SAVE_GAME_INFO); - WriteKeywordProperty("textcinematicsubtitle", item->itemFlags & ITEM_FLAG_CINEMATIC_SUBTITLE); - WriteStringProperty("group", item->window.group); - WriteRectProperty("rect", item->window.rectClient); - WriteIntProperty("style", item->window.style, 0); - WriteKeywordProperty("decoration", item->window.staticFlags & WINDOW_FLAG_DECORATION); - WriteKeywordProperty("autowrapped", item->window.staticFlags & WINDOW_FLAG_AUTO_WRAPPED); - WriteKeywordProperty("horizontalscroll", item->window.staticFlags & WINDOW_FLAG_HORIZONTAL_SCROLL); - WriteIntProperty("type", item->type, ITEM_TYPE_TEXT); - WriteIntProperty("border", item->window.border, 0); - WriteFloatProperty("borderSize", item->window.borderSize, 0.0f); - - if (item->visibleExp) - WriteStatementProperty("visible", item->visibleExp, true); - else if (item->window.dynamicFlags[0] & WINDOW_FLAG_VISIBLE) - WriteIntProperty("visible", 1, 0); - - WriteStatementProperty("disabled", item->disabledExp, true); - WriteIntProperty("ownerdraw", item->window.ownerDraw, 0); - WriteFlagsProperty("ownerdrawFlag", item->window.ownerDrawFlags); - WriteIntProperty("align", item->alignment, 0); - WriteIntProperty("textalign", item->textAlignMode, 0); - WriteFloatProperty("textalignx", item->textalignx, 0.0f); - WriteFloatProperty("textaligny", item->textaligny, 0.0f); - WriteFloatProperty("textscale", item->textscale, 0.0f); - WriteIntProperty("textstyle", item->textStyle, 0); - WriteIntProperty("textfont", item->fontEnum, 0); - WriteColorProperty("backcolor", item->window.backColor, COLOR_0000); - WriteColorProperty("forecolor", item->window.foreColor, COLOR_1111); - WriteColorProperty("bordercolor", item->window.borderColor, COLOR_0000); - WriteColorProperty("outlinecolor", item->window.outlineColor, COLOR_0000); - WriteColorProperty("disablecolor", item->window.disableColor, COLOR_0000); - WriteColorProperty("glowcolor", item->glowColor, COLOR_0000); - WriteMaterialProperty("background", item->window.background); - WriteMenuEventHandlerSetProperty("onFocus", item->onFocus); - WriteMenuEventHandlerSetProperty("leaveFocus", item->leaveFocus); - WriteMenuEventHandlerSetProperty("mouseEnter", item->mouseEnter); - WriteMenuEventHandlerSetProperty("mouseExit", item->mouseExit); - WriteMenuEventHandlerSetProperty("mouseEnterText", item->mouseEnterText); - WriteMenuEventHandlerSetProperty("mouseExitText", item->mouseExitText); - WriteMenuEventHandlerSetProperty("action", item->action); - WriteMenuEventHandlerSetProperty("accept", item->accept); - // WriteFloatProperty("special", item->special, 0.0f); - WriteSoundAliasProperty("focusSound", item->focusSound); - WriteStringProperty("dvarTest", item->dvarTest); - - if (item->dvarFlags & ITEM_DVAR_FLAG_ENABLE) - WriteMultiTokenStringProperty("enableDvar", item->enableDvar); - else if (item->dvarFlags & ITEM_DVAR_FLAG_DISABLE) - WriteMultiTokenStringProperty("disableDvar", item->enableDvar); - else if (item->dvarFlags & ITEM_DVAR_FLAG_SHOW) - WriteMultiTokenStringProperty("showDvar", item->enableDvar); - else if (item->dvarFlags & ITEM_DVAR_FLAG_HIDE) - WriteMultiTokenStringProperty("hideDvar", item->enableDvar); - else if (item->dvarFlags & ITEM_DVAR_FLAG_FOCUS) - WriteMultiTokenStringProperty("focusDvar", item->enableDvar); - - WriteItemKeyHandlerProperty(item->onKey); - WriteStatementProperty("exp text", item->textExp, false); - WriteStatementProperty("exp material", item->materialExp, false); - WriteStatementProperty("exp disabled", item->disabledExp, false); - WriteFloatExpressionsProperty(item->floatExpressions, item->floatExpressionCount); - WriteIntProperty("gamemsgwindowindex", item->gameMsgWindowIndex, 0); - WriteIntProperty("gamemsgwindowmode", item->gameMsgWindowMode, 0); - WriteDecodeEffectProperty("decodeEffect", item); - - WriteListBoxProperties(item); - WriteEditFieldProperties(item); - WriteMultiProperties(item); - WriteEnumDvarProperties(item); - WriteTickerProperties(item); -} - -void MenuDumper::WriteItemDefs(const itemDef_s* const* itemDefs, size_t itemCount) -{ - for (auto i = 0u; i < itemCount; i++) - { - StartItemDefScope(); - - WriteItemData(itemDefs[i]); - - EndScope(); - } + m_stream << "{"; + for (auto i = 0; i < multiDef->count; i++) { + if (multiDef->dvarList[i] == nullptr || multiDef->strDef && multiDef->dvarStr[i] == nullptr) + continue; + + m_stream << " \"" << multiDef->dvarList[i] << "\""; + + if (multiDef->strDef) + m_stream << " \"" << multiDef->dvarStr[i] << "\""; + else + m_stream << " " << multiDef->dvarValue[i] << ""; + } + m_stream << " }\n"; } -void MenuDumper::WriteMenuData(const menuDef_t* menu) -{ - WriteStringProperty("name", menu->window.name); - WriteBoolProperty("fullscreen", menu->fullScreen, false); - WriteKeywordProperty("screenSpace", menu->window.staticFlags & WINDOW_FLAG_SCREEN_SPACE); - WriteKeywordProperty("decoration", menu->window.staticFlags & WINDOW_FLAG_DECORATION); - WriteRectProperty("rect", menu->window.rect); - WriteIntProperty("style", menu->window.style, 0); - WriteIntProperty("border", menu->window.border, 0); - WriteFloatProperty("borderSize", menu->window.borderSize, 0.0f); - WriteColorProperty("backcolor", menu->window.backColor, COLOR_0000); - WriteColorProperty("forecolor", menu->window.foreColor, COLOR_1111); - WriteColorProperty("bordercolor", menu->window.borderColor, COLOR_0000); - WriteColorProperty("focuscolor", menu->focusColor, COLOR_0000); - WriteColorProperty("outlinecolor", menu->window.outlineColor, COLOR_0000); - WriteMaterialProperty("background", menu->window.background); - WriteIntProperty("ownerdraw", menu->window.ownerDraw, 0); - WriteFlagsProperty("ownerdrawFlag", menu->window.ownerDrawFlags); - WriteKeywordProperty("outOfBoundsClick", menu->window.staticFlags & WINDOW_FLAG_OUT_OF_BOUNDS_CLICK); - WriteStringProperty("soundLoop", menu->soundName); - WriteKeywordProperty("popup", menu->window.staticFlags & WINDOW_FLAG_POPUP); - WriteFloatProperty("fadeClamp", menu->fadeClamp, 0.0f); - WriteIntProperty("fadeCycle", menu->fadeCycle, 0); - WriteFloatProperty("fadeAmount", menu->fadeAmount, 0.0f); - WriteFloatProperty("fadeInAmount", menu->fadeInAmount, 0.0f); - WriteFloatProperty("blurWorld", menu->blurRadius, 0.0f); - WriteKeywordProperty("legacySplitScreenScale", menu->window.staticFlags & WINDOW_FLAG_LEGACY_SPLIT_SCREEN_SCALE); - WriteKeywordProperty("hiddenDuringScope", menu->window.staticFlags & WINDOW_FLAG_HIDDEN_DURING_SCOPE); - WriteKeywordProperty("hiddenDuringFlashbang", menu->window.staticFlags & WINDOW_FLAG_HIDDEN_DURING_FLASH_BANG); - WriteKeywordProperty("hiddenDuringUI", menu->window.staticFlags & WINDOW_FLAG_HIDDEN_DURING_UI); - WriteStringProperty("allowedBinding", menu->allowedBinding); - WriteKeywordProperty("textOnlyFocus", menu->window.staticFlags & WINDOW_FLAG_TEXT_ONLY_FOCUS); - - if (menu->visibleExp) - WriteStatementProperty("visible", menu->visibleExp, true); - else if (menu->window.dynamicFlags[0] & WINDOW_FLAG_VISIBLE) - WriteIntProperty("visible", 1, 0); - - WriteStatementProperty("exp rect X", menu->rectXExp, false); - WriteStatementProperty("exp rect Y", menu->rectYExp, false); - WriteStatementProperty("exp rect W", menu->rectWExp, false); - WriteStatementProperty("exp rect H", menu->rectHExp, false); - WriteStatementProperty("exp openSound", menu->openSoundExp, false); - WriteStatementProperty("exp closeSound", menu->closeSoundExp, false); - WriteMenuEventHandlerSetProperty("onOpen", menu->onOpen); - WriteMenuEventHandlerSetProperty("onClose", menu->onClose); - WriteMenuEventHandlerSetProperty("onRequestClose", menu->onCloseRequest); - WriteMenuEventHandlerSetProperty("onESC", menu->onESC); - WriteItemKeyHandlerProperty(menu->onKey); - WriteItemDefs(menu->items, menu->itemCount); -} - -MenuDumper::MenuDumper(std::ostream& stream) - : AbstractMenuDumper(stream) -{ -} - -void MenuDumper::WriteFunctionDef(const std::string& functionName, const Statement_s* statement) -{ - StartFunctionDefScope(); - - WriteStringProperty("name", functionName); - WriteStatementProperty("value", statement, false); +void MenuDumper::WriteMultiProperties(const itemDef_s *item) const { + if (item->type != ITEM_TYPE_MULTI || item->typeData.multi == nullptr) + return; + + const auto *multiDef = item->typeData.multi; - EndScope(); + if (multiDef->count <= 0) + return; + + WriteStringProperty("dvar", item->dvar); + WriteStringProperty("localvar", item->localVar); + WriteMultiValueProperty(multiDef); } -void MenuDumper::WriteMenu(const menuDef_t* menu) -{ - StartMenuDefScope(); +void MenuDumper::WriteEnumDvarProperties(const itemDef_s *item) const { + if (item->type != ITEM_TYPE_DVARENUM) + return; + + WriteStringProperty("dvar", item->dvar); + WriteStringProperty("localvar", item->localVar); + WriteStringProperty("dvarEnumList", item->typeData.enumDvarName); +} + +void MenuDumper::WriteTickerProperties(const itemDef_s *item) const { + if (item->type != ITEM_TYPE_NEWS_TICKER || item->typeData.ticker == nullptr) + return; - WriteMenuData(menu); + const auto *newsTickerDef = item->typeData.ticker; + WriteIntProperty("spacing", newsTickerDef->spacing, 0); + WriteIntProperty("speed", newsTickerDef->speed, 0); + WriteIntProperty("newsfeed", newsTickerDef->feedId, 0); +} + +void MenuDumper::WriteItemData(const itemDef_s *item) { + WriteStringProperty("name", item->window.name); + WriteStringProperty("text", item->text); + WriteKeywordProperty("textsavegame", item->itemFlags & ITEM_FLAG_SAVE_GAME_INFO); + WriteKeywordProperty("textcinematicsubtitle", item->itemFlags & ITEM_FLAG_CINEMATIC_SUBTITLE); + WriteStringProperty("group", item->window.group); + WriteRectProperty("rect", item->window.rectClient); + WriteIntProperty("style", item->window.style, 0); + WriteKeywordProperty("decoration", item->window.staticFlags & WINDOW_FLAG_DECORATION); + WriteKeywordProperty("autowrapped", item->window.staticFlags & WINDOW_FLAG_AUTO_WRAPPED); + WriteKeywordProperty("horizontalscroll", item->window.staticFlags & WINDOW_FLAG_HORIZONTAL_SCROLL); + WriteIntProperty("type", item->type, ITEM_TYPE_TEXT); + WriteIntProperty("border", item->window.border, 0); + WriteFloatProperty("borderSize", item->window.borderSize, 0.0f); + + if (item->visibleExp) + WriteStatementProperty("visible", item->visibleExp, true); + else if (item->window.dynamicFlags[0] & WINDOW_FLAG_VISIBLE) + WriteIntProperty("visible", 1, 0); + + WriteStatementProperty("disabled", item->disabledExp, true); + WriteIntProperty("ownerdraw", item->window.ownerDraw, 0); + WriteFlagsProperty("ownerdrawFlag", item->window.ownerDrawFlags); + WriteIntProperty("align", item->alignment, 0); + WriteIntProperty("textalign", item->textAlignMode, 0); + WriteFloatProperty("textalignx", item->textalignx, 0.0f); + WriteFloatProperty("textaligny", item->textaligny, 0.0f); + WriteFloatProperty("textscale", item->textscale, 0.0f); + WriteIntProperty("textstyle", item->textStyle, 0); + WriteIntProperty("textfont", item->fontEnum, 0); + WriteColorProperty("backcolor", item->window.backColor, COLOR_0000); + WriteColorProperty("forecolor", item->window.foreColor, COLOR_1111); + WriteColorProperty("bordercolor", item->window.borderColor, COLOR_0000); + WriteColorProperty("outlinecolor", item->window.outlineColor, COLOR_0000); + WriteColorProperty("disablecolor", item->window.disableColor, COLOR_0000); + WriteColorProperty("glowcolor", item->glowColor, COLOR_0000); + WriteMaterialProperty("background", item->window.background); + WriteMenuEventHandlerSetProperty("onFocus", item->onFocus); + WriteMenuEventHandlerSetProperty("leaveFocus", item->leaveFocus); + WriteMenuEventHandlerSetProperty("mouseEnter", item->mouseEnter); + WriteMenuEventHandlerSetProperty("mouseExit", item->mouseExit); + WriteMenuEventHandlerSetProperty("mouseEnterText", item->mouseEnterText); + WriteMenuEventHandlerSetProperty("mouseExitText", item->mouseExitText); + WriteMenuEventHandlerSetProperty("action", item->action); + WriteMenuEventHandlerSetProperty("accept", item->accept); + // WriteFloatProperty("special", item->special, 0.0f); + WriteSoundAliasProperty("focusSound", item->focusSound); + WriteStringProperty("dvarTest", item->dvarTest); + + if (item->dvarFlags & ITEM_DVAR_FLAG_ENABLE) + WriteMultiTokenStringProperty("enableDvar", item->enableDvar); + else if (item->dvarFlags & ITEM_DVAR_FLAG_DISABLE) + WriteMultiTokenStringProperty("disableDvar", item->enableDvar); + else if (item->dvarFlags & ITEM_DVAR_FLAG_SHOW) + WriteMultiTokenStringProperty("showDvar", item->enableDvar); + else if (item->dvarFlags & ITEM_DVAR_FLAG_HIDE) + WriteMultiTokenStringProperty("hideDvar", item->enableDvar); + else if (item->dvarFlags & ITEM_DVAR_FLAG_FOCUS) + WriteMultiTokenStringProperty("focusDvar", item->enableDvar); + + WriteItemKeyHandlerProperty(item->onKey); + WriteStatementProperty("exp text", item->textExp, false); + WriteStatementProperty("exp material", item->materialExp, false); + WriteStatementProperty("exp disabled", item->disabledExp, false); + WriteFloatExpressionsProperty(item->floatExpressions, item->floatExpressionCount); + WriteIntProperty("gamemsgwindowindex", item->gameMsgWindowIndex, 0); + WriteIntProperty("gamemsgwindowmode", item->gameMsgWindowMode, 0); + WriteDecodeEffectProperty("decodeEffect", item); + + WriteListBoxProperties(item); + WriteEditFieldProperties(item); + WriteMultiProperties(item); + WriteEnumDvarProperties(item); + WriteTickerProperties(item); +} + +void MenuDumper::WriteItemDefs(const itemDef_s *const *itemDefs, size_t itemCount) { + for (auto i = 0u; i < itemCount; i++) { + StartItemDefScope(); + + WriteItemData(itemDefs[i]); EndScope(); + } +} + +void MenuDumper::WriteMenuData(const menuDef_t *menu) { + WriteStringProperty("name", menu->window.name); + WriteBoolProperty("fullscreen", menu->fullScreen, false); + WriteKeywordProperty("screenSpace", menu->window.staticFlags & WINDOW_FLAG_SCREEN_SPACE); + WriteKeywordProperty("decoration", menu->window.staticFlags & WINDOW_FLAG_DECORATION); + WriteRectProperty("rect", menu->window.rect); + WriteIntProperty("style", menu->window.style, 0); + WriteIntProperty("border", menu->window.border, 0); + WriteFloatProperty("borderSize", menu->window.borderSize, 0.0f); + WriteColorProperty("backcolor", menu->window.backColor, COLOR_0000); + WriteColorProperty("forecolor", menu->window.foreColor, COLOR_1111); + WriteColorProperty("bordercolor", menu->window.borderColor, COLOR_0000); + WriteColorProperty("focuscolor", menu->focusColor, COLOR_0000); + WriteColorProperty("outlinecolor", menu->window.outlineColor, COLOR_0000); + WriteMaterialProperty("background", menu->window.background); + WriteIntProperty("ownerdraw", menu->window.ownerDraw, 0); + WriteFlagsProperty("ownerdrawFlag", menu->window.ownerDrawFlags); + WriteKeywordProperty("outOfBoundsClick", menu->window.staticFlags & WINDOW_FLAG_OUT_OF_BOUNDS_CLICK); + WriteStringProperty("soundLoop", menu->soundName); + WriteKeywordProperty("popup", menu->window.staticFlags & WINDOW_FLAG_POPUP); + WriteFloatProperty("fadeClamp", menu->fadeClamp, 0.0f); + WriteIntProperty("fadeCycle", menu->fadeCycle, 0); + WriteFloatProperty("fadeAmount", menu->fadeAmount, 0.0f); + WriteFloatProperty("fadeInAmount", menu->fadeInAmount, 0.0f); + WriteFloatProperty("blurWorld", menu->blurRadius, 0.0f); + WriteKeywordProperty("legacySplitScreenScale", menu->window.staticFlags & WINDOW_FLAG_LEGACY_SPLIT_SCREEN_SCALE); + WriteKeywordProperty("hiddenDuringScope", menu->window.staticFlags & WINDOW_FLAG_HIDDEN_DURING_SCOPE); + WriteKeywordProperty("hiddenDuringFlashbang", menu->window.staticFlags & WINDOW_FLAG_HIDDEN_DURING_FLASH_BANG); + WriteKeywordProperty("hiddenDuringUI", menu->window.staticFlags & WINDOW_FLAG_HIDDEN_DURING_UI); + WriteStringProperty("allowedBinding", menu->allowedBinding); + WriteKeywordProperty("textOnlyFocus", menu->window.staticFlags & WINDOW_FLAG_TEXT_ONLY_FOCUS); + + if (menu->visibleExp) + WriteStatementProperty("visible", menu->visibleExp, true); + else if (menu->window.dynamicFlags[0] & WINDOW_FLAG_VISIBLE) + WriteIntProperty("visible", 1, 0); + + WriteStatementProperty("exp rect X", menu->rectXExp, false); + WriteStatementProperty("exp rect Y", menu->rectYExp, false); + WriteStatementProperty("exp rect W", menu->rectWExp, false); + WriteStatementProperty("exp rect H", menu->rectHExp, false); + WriteStatementProperty("exp openSound", menu->openSoundExp, false); + WriteStatementProperty("exp closeSound", menu->closeSoundExp, false); + WriteMenuEventHandlerSetProperty("onOpen", menu->onOpen); + WriteMenuEventHandlerSetProperty("onClose", menu->onClose); + WriteMenuEventHandlerSetProperty("onRequestClose", menu->onCloseRequest); + WriteMenuEventHandlerSetProperty("onESC", menu->onESC); + WriteItemKeyHandlerProperty(menu->onKey); + WriteItemDefs(menu->items, menu->itemCount); +} + +MenuDumper::MenuDumper(std::ostream &stream) : AbstractMenuDumper(stream) {} + +void MenuDumper::WriteFunctionDef(const std::string &functionName, const Statement_s *statement) { + StartFunctionDefScope(); + + WriteStringProperty("name", functionName); + WriteStatementProperty("value", statement, false); + + EndScope(); +} + +void MenuDumper::WriteMenu(const menuDef_t *menu) { + StartMenuDefScope(); + + WriteMenuData(menu); + + EndScope(); } diff --git a/src/ObjWriting/Game/IW4/Menu/MenuDumperIW4.h b/src/ObjWriting/Game/IW4/Menu/MenuDumperIW4.h index 85eaf2c0b..093e06fe3 100644 --- a/src/ObjWriting/Game/IW4/Menu/MenuDumperIW4.h +++ b/src/ObjWriting/Game/IW4/Menu/MenuDumperIW4.h @@ -2,54 +2,52 @@ #include <string> -#include "Menu/AbstractMenuDumper.h" #include "Game/IW4/IW4.h" +#include "Menu/AbstractMenuDumper.h" -namespace IW4 -{ - class MenuDumper : public AbstractMenuDumper - { - static size_t FindStatementClosingParenthesis(const Statement_s* statement, size_t openingParenthesisPosition); - - void WriteStatementOperator(const Statement_s* statement, size_t& currentPos, bool& spaceNext) const; - void WriteStatementOperandFunction(const Statement_s* statement, size_t currentPos) const; - void WriteStatementOperand(const Statement_s* statement, size_t& currentPos, bool& spaceNext) const; - void WriteStatementEntryRange(const Statement_s* statement, size_t startOffset, size_t endOffset) const; - void WriteStatement(const Statement_s* statement) const; - void WriteStatementSkipInitialUnnecessaryParenthesis(const Statement_s* statementValue) const; - void WriteStatementProperty(const std::string& propertyKey, const Statement_s* statementValue, bool isBooleanStatement) const; - - void WriteSetLocalVarData(const std::string& setFunction, const SetLocalVarData* setLocalVarData) const; - void WriteUnconditionalScript(const char* script) const; - void WriteMenuEventHandlerSet(const MenuEventHandlerSet* eventHandlerSet); - void WriteMenuEventHandlerSetProperty(const std::string& propertyKey, const MenuEventHandlerSet* eventHandlerSetValue); - - void WriteRectProperty(const std::string& propertyKey, const rectDef_s& rect) const; - void WriteMaterialProperty(const std::string& propertyKey, const Material* materialValue) const; - void WriteSoundAliasProperty(const std::string& propertyKey, const snd_alias_list_t* soundAliasValue) const; - void WriteDecodeEffectProperty(const std::string& propertyKey, const itemDef_s* item) const; - void WriteItemKeyHandlerProperty(const ItemKeyHandler* itemKeyHandlerValue); - void WriteMultiTokenStringProperty(const std::string& propertyKey, const char* value) const; - void WriteFloatExpressionsProperty(const ItemFloatExpression* floatExpressions, int floatExpressionCount) const; - void WriteColumnProperty(const std::string& propertyKey, const listBoxDef_s* listBox) const; - - void WriteListBoxProperties(const itemDef_s* item); - void WriteDvarFloatProperty(const std::string& propertyKey, const itemDef_s* item, const editFieldDef_s* editField) const; - void WriteEditFieldProperties(const itemDef_s* item) const; - void WriteMultiValueProperty(const multiDef_s* multiDef) const; - void WriteMultiProperties(const itemDef_s* item) const; - void WriteEnumDvarProperties(const itemDef_s* item) const; - void WriteTickerProperties(const itemDef_s* item) const; - - void WriteItemData(const itemDef_s* item); - void WriteItemDefs(const itemDef_s* const* itemDefs, size_t itemCount); - - void WriteMenuData(const menuDef_t* menu); - - public: - explicit MenuDumper(std::ostream& stream); - - void WriteFunctionDef(const std::string& functionName, const Statement_s* statement); - void WriteMenu(const menuDef_t* menu); - }; -} +namespace IW4 { +class MenuDumper : public AbstractMenuDumper { + static size_t FindStatementClosingParenthesis(const Statement_s *statement, size_t openingParenthesisPosition); + + void WriteStatementOperator(const Statement_s *statement, size_t ¤tPos, bool &spaceNext) const; + void WriteStatementOperandFunction(const Statement_s *statement, size_t currentPos) const; + void WriteStatementOperand(const Statement_s *statement, size_t ¤tPos, bool &spaceNext) const; + void WriteStatementEntryRange(const Statement_s *statement, size_t startOffset, size_t endOffset) const; + void WriteStatement(const Statement_s *statement) const; + void WriteStatementSkipInitialUnnecessaryParenthesis(const Statement_s *statementValue) const; + void WriteStatementProperty(const std::string &propertyKey, const Statement_s *statementValue, bool isBooleanStatement) const; + + void WriteSetLocalVarData(const std::string &setFunction, const SetLocalVarData *setLocalVarData) const; + void WriteUnconditionalScript(const char *script) const; + void WriteMenuEventHandlerSet(const MenuEventHandlerSet *eventHandlerSet); + void WriteMenuEventHandlerSetProperty(const std::string &propertyKey, const MenuEventHandlerSet *eventHandlerSetValue); + + void WriteRectProperty(const std::string &propertyKey, const rectDef_s &rect) const; + void WriteMaterialProperty(const std::string &propertyKey, const Material *materialValue) const; + void WriteSoundAliasProperty(const std::string &propertyKey, const snd_alias_list_t *soundAliasValue) const; + void WriteDecodeEffectProperty(const std::string &propertyKey, const itemDef_s *item) const; + void WriteItemKeyHandlerProperty(const ItemKeyHandler *itemKeyHandlerValue); + void WriteMultiTokenStringProperty(const std::string &propertyKey, const char *value) const; + void WriteFloatExpressionsProperty(const ItemFloatExpression *floatExpressions, int floatExpressionCount) const; + void WriteColumnProperty(const std::string &propertyKey, const listBoxDef_s *listBox) const; + + void WriteListBoxProperties(const itemDef_s *item); + void WriteDvarFloatProperty(const std::string &propertyKey, const itemDef_s *item, const editFieldDef_s *editField) const; + void WriteEditFieldProperties(const itemDef_s *item) const; + void WriteMultiValueProperty(const multiDef_s *multiDef) const; + void WriteMultiProperties(const itemDef_s *item) const; + void WriteEnumDvarProperties(const itemDef_s *item) const; + void WriteTickerProperties(const itemDef_s *item) const; + + void WriteItemData(const itemDef_s *item); + void WriteItemDefs(const itemDef_s *const *itemDefs, size_t itemCount); + + void WriteMenuData(const menuDef_t *menu); + +public: + explicit MenuDumper(std::ostream &stream); + + void WriteFunctionDef(const std::string &functionName, const Statement_s *statement); + void WriteMenu(const menuDef_t *menu); +}; +} // namespace IW4 diff --git a/src/ObjWriting/Game/IW4/ZoneDumperIW4.cpp b/src/ObjWriting/Game/IW4/ZoneDumperIW4.cpp index 4ed897dc8..5f58a452e 100644 --- a/src/ObjWriting/Game/IW4/ZoneDumperIW4.cpp +++ b/src/ObjWriting/Game/IW4/ZoneDumperIW4.cpp @@ -1,8 +1,8 @@ #include "ZoneDumperIW4.h" -#include "ObjWriting.h" -#include "Game/IW4/GameIW4.h" #include "Game/IW4/GameAssetPoolIW4.h" +#include "Game/IW4/GameIW4.h" +#include "ObjWriting.h" #include "AssetDumpers/AssetDumperAddonMapEnts.h" #include "AssetDumpers/AssetDumperGfxImage.h" @@ -28,59 +28,54 @@ using namespace IW4; -bool ZoneDumper::CanHandleZone(AssetDumpingContext& context) const -{ - return context.m_zone->m_game == &g_GameIW4; -} +bool ZoneDumper::CanHandleZone(AssetDumpingContext &context) const { return context.m_zone->m_game == &g_GameIW4; } -bool ZoneDumper::DumpZone(AssetDumpingContext& context) const -{ -#define DUMP_ASSET_POOL(dumperType, poolName, assetType) \ - if(assetPools->poolName && ObjWriting::ShouldHandleAssetType(assetType)) \ - { \ - dumperType dumper; \ - dumper.DumpPool(context, assetPools->poolName.get()); \ - } +bool ZoneDumper::DumpZone(AssetDumpingContext &context) const { +#define DUMP_ASSET_POOL(dumperType, poolName, assetType) \ + if (assetPools->poolName && ObjWriting::ShouldHandleAssetType(assetType)) { \ + dumperType dumper; \ + dumper.DumpPool(context, assetPools->poolName.get()); \ + } - const auto* assetPools = dynamic_cast<GameAssetPoolIW4*>(context.m_zone->m_pools.get()); + const auto *assetPools = dynamic_cast<GameAssetPoolIW4 *>(context.m_zone->m_pools.get()); - DUMP_ASSET_POOL(AssetDumperPhysPreset, m_phys_preset, ASSET_TYPE_PHYSPRESET) - DUMP_ASSET_POOL(AssetDumperPhysCollmap, m_phys_collmap, ASSET_TYPE_PHYSCOLLMAP) - // DUMP_ASSET_POOL(AssetDumperXAnimParts, m_xanim_parts, ASSET_TYPE_XANIMPARTS) - DUMP_ASSET_POOL(AssetDumperXModel, m_xmodel, ASSET_TYPE_XMODEL) - DUMP_ASSET_POOL(AssetDumperMaterial, m_material, ASSET_TYPE_MATERIAL) - DUMP_ASSET_POOL(AssetDumperPixelShader, m_material_pixel_shader, ASSET_TYPE_PIXELSHADER) - DUMP_ASSET_POOL(AssetDumperVertexShader, m_material_vertex_shader, ASSET_TYPE_VERTEXSHADER) - DUMP_ASSET_POOL(AssetDumperTechniqueSet, m_technique_set, ASSET_TYPE_TECHNIQUE_SET) - DUMP_ASSET_POOL(AssetDumperGfxImage, m_image, ASSET_TYPE_IMAGE) - // DUMP_ASSET_POOL(AssetDumpersnd_alias_list_t, m_sound, ASSET_TYPE_SOUND) - DUMP_ASSET_POOL(AssetDumperSndCurve, m_sound_curve, ASSET_TYPE_SOUND_CURVE) - DUMP_ASSET_POOL(AssetDumperLoadedSound, m_loaded_sound, ASSET_TYPE_LOADED_SOUND) - // DUMP_ASSET_POOL(AssetDumperclipMap_t, m_clip_map, ASSET_TYPE_CLIPMAP_MP) - // DUMP_ASSET_POOL(AssetDumperComWorld, m_com_world, ASSET_TYPE_COMWORLD) - // DUMP_ASSET_POOL(AssetDumperGameWorldSp, m_game_world_sp, ASSET_TYPE_GAMEWORLD_SP) - // DUMP_ASSET_POOL(AssetDumperGameWorldMp, m_game_world_mp, ASSET_TYPE_GAMEWORLD_MP) - // DUMP_ASSET_POOL(AssetDumperMapEnts, m_map_ents, ASSET_TYPE_MAP_ENTS) - // DUMP_ASSET_POOL(AssetDumperFxWorld, m_fx_world, ASSET_TYPE_FXWORLD) - // DUMP_ASSET_POOL(AssetDumperGfxWorld, m_gfx_world, ASSET_TYPE_GFXWORLD) - DUMP_ASSET_POOL(AssetDumperGfxLightDef, m_gfx_light_def, ASSET_TYPE_LIGHT_DEF) - // DUMP_ASSET_POOL(AssetDumperFont_s, m_font, ASSET_TYPE_FONT) - DUMP_ASSET_POOL(AssetDumperMenuList, m_menu_list, ASSET_TYPE_MENULIST) - DUMP_ASSET_POOL(AssetDumperMenuDef, m_menu_def, ASSET_TYPE_MENU) - DUMP_ASSET_POOL(AssetDumperLocalizeEntry, m_localize, ASSET_TYPE_LOCALIZE_ENTRY) - DUMP_ASSET_POOL(AssetDumperWeapon, m_weapon, ASSET_TYPE_WEAPON) - // DUMP_ASSET_POOL(AssetDumperSndDriverGlobals, m_snd_driver_globals, ASSET_TYPE_SNDDRIVER_GLOBALS) - // DUMP_ASSET_POOL(AssetDumperFxEffectDef, m_fx, ASSET_TYPE_FX) - // DUMP_ASSET_POOL(AssetDumperFxImpactTable, m_fx_impact_table, ASSET_TYPE_IMPACT_FX) - DUMP_ASSET_POOL(AssetDumperRawFile, m_raw_file, ASSET_TYPE_RAWFILE) - DUMP_ASSET_POOL(AssetDumperStringTable, m_string_table, ASSET_TYPE_STRINGTABLE) - // DUMP_ASSET_POOL(AssetDumperLeaderboardDef, m_leaderboard, ASSET_TYPE_LEADERBOARD) - DUMP_ASSET_POOL(AssetDumperStructuredDataDefSet, m_structed_data_def_set, ASSET_TYPE_STRUCTURED_DATA_DEF) - DUMP_ASSET_POOL(AssetDumperTracer, m_tracer, ASSET_TYPE_TRACER) - DUMP_ASSET_POOL(AssetDumperVehicle, m_vehicle, ASSET_TYPE_VEHICLE) - DUMP_ASSET_POOL(AssetDumperAddonMapEnts, m_addon_map_ents, ASSET_TYPE_ADDON_MAP_ENTS) + DUMP_ASSET_POOL(AssetDumperPhysPreset, m_phys_preset, ASSET_TYPE_PHYSPRESET) + DUMP_ASSET_POOL(AssetDumperPhysCollmap, m_phys_collmap, ASSET_TYPE_PHYSCOLLMAP) + // DUMP_ASSET_POOL(AssetDumperXAnimParts, m_xanim_parts, ASSET_TYPE_XANIMPARTS) + DUMP_ASSET_POOL(AssetDumperXModel, m_xmodel, ASSET_TYPE_XMODEL) + DUMP_ASSET_POOL(AssetDumperMaterial, m_material, ASSET_TYPE_MATERIAL) + DUMP_ASSET_POOL(AssetDumperPixelShader, m_material_pixel_shader, ASSET_TYPE_PIXELSHADER) + DUMP_ASSET_POOL(AssetDumperVertexShader, m_material_vertex_shader, ASSET_TYPE_VERTEXSHADER) + DUMP_ASSET_POOL(AssetDumperTechniqueSet, m_technique_set, ASSET_TYPE_TECHNIQUE_SET) + DUMP_ASSET_POOL(AssetDumperGfxImage, m_image, ASSET_TYPE_IMAGE) + // DUMP_ASSET_POOL(AssetDumpersnd_alias_list_t, m_sound, ASSET_TYPE_SOUND) + DUMP_ASSET_POOL(AssetDumperSndCurve, m_sound_curve, ASSET_TYPE_SOUND_CURVE) + DUMP_ASSET_POOL(AssetDumperLoadedSound, m_loaded_sound, ASSET_TYPE_LOADED_SOUND) + // DUMP_ASSET_POOL(AssetDumperclipMap_t, m_clip_map, ASSET_TYPE_CLIPMAP_MP) + // DUMP_ASSET_POOL(AssetDumperComWorld, m_com_world, ASSET_TYPE_COMWORLD) + // DUMP_ASSET_POOL(AssetDumperGameWorldSp, m_game_world_sp, ASSET_TYPE_GAMEWORLD_SP) + // DUMP_ASSET_POOL(AssetDumperGameWorldMp, m_game_world_mp, ASSET_TYPE_GAMEWORLD_MP) + // DUMP_ASSET_POOL(AssetDumperMapEnts, m_map_ents, ASSET_TYPE_MAP_ENTS) + // DUMP_ASSET_POOL(AssetDumperFxWorld, m_fx_world, ASSET_TYPE_FXWORLD) + // DUMP_ASSET_POOL(AssetDumperGfxWorld, m_gfx_world, ASSET_TYPE_GFXWORLD) + DUMP_ASSET_POOL(AssetDumperGfxLightDef, m_gfx_light_def, ASSET_TYPE_LIGHT_DEF) + // DUMP_ASSET_POOL(AssetDumperFont_s, m_font, ASSET_TYPE_FONT) + DUMP_ASSET_POOL(AssetDumperMenuList, m_menu_list, ASSET_TYPE_MENULIST) + DUMP_ASSET_POOL(AssetDumperMenuDef, m_menu_def, ASSET_TYPE_MENU) + DUMP_ASSET_POOL(AssetDumperLocalizeEntry, m_localize, ASSET_TYPE_LOCALIZE_ENTRY) + DUMP_ASSET_POOL(AssetDumperWeapon, m_weapon, ASSET_TYPE_WEAPON) + // DUMP_ASSET_POOL(AssetDumperSndDriverGlobals, m_snd_driver_globals, ASSET_TYPE_SNDDRIVER_GLOBALS) + // DUMP_ASSET_POOL(AssetDumperFxEffectDef, m_fx, ASSET_TYPE_FX) + // DUMP_ASSET_POOL(AssetDumperFxImpactTable, m_fx_impact_table, ASSET_TYPE_IMPACT_FX) + DUMP_ASSET_POOL(AssetDumperRawFile, m_raw_file, ASSET_TYPE_RAWFILE) + DUMP_ASSET_POOL(AssetDumperStringTable, m_string_table, ASSET_TYPE_STRINGTABLE) + // DUMP_ASSET_POOL(AssetDumperLeaderboardDef, m_leaderboard, ASSET_TYPE_LEADERBOARD) + DUMP_ASSET_POOL(AssetDumperStructuredDataDefSet, m_structed_data_def_set, ASSET_TYPE_STRUCTURED_DATA_DEF) + DUMP_ASSET_POOL(AssetDumperTracer, m_tracer, ASSET_TYPE_TRACER) + DUMP_ASSET_POOL(AssetDumperVehicle, m_vehicle, ASSET_TYPE_VEHICLE) + DUMP_ASSET_POOL(AssetDumperAddonMapEnts, m_addon_map_ents, ASSET_TYPE_ADDON_MAP_ENTS) - return true; + return true; #undef DUMP_ASSET_POOL } diff --git a/src/ObjWriting/Game/IW4/ZoneDumperIW4.h b/src/ObjWriting/Game/IW4/ZoneDumperIW4.h index c46601785..6d7d7e15b 100644 --- a/src/ObjWriting/Game/IW4/ZoneDumperIW4.h +++ b/src/ObjWriting/Game/IW4/ZoneDumperIW4.h @@ -1,12 +1,10 @@ #pragma once #include "Dumping/IZoneDumper.h" -namespace IW4 -{ - class ZoneDumper final : public IZoneDumper - { - public: - bool CanHandleZone(AssetDumpingContext& context) const override; - bool DumpZone(AssetDumpingContext& context) const override; - }; -} +namespace IW4 { +class ZoneDumper final : public IZoneDumper { +public: + bool CanHandleZone(AssetDumpingContext &context) const override; + bool DumpZone(AssetDumpingContext &context) const override; +}; +} // namespace IW4 diff --git a/src/ObjWriting/Game/IW5/AssetDumpers/AssetDumperAddonMapEnts.cpp b/src/ObjWriting/Game/IW5/AssetDumpers/AssetDumperAddonMapEnts.cpp index 547881cf7..2432a4266 100644 --- a/src/ObjWriting/Game/IW5/AssetDumpers/AssetDumperAddonMapEnts.cpp +++ b/src/ObjWriting/Game/IW5/AssetDumpers/AssetDumperAddonMapEnts.cpp @@ -5,19 +5,15 @@ using namespace IW5; -bool AssetDumperAddonMapEnts::ShouldDump(XAssetInfo<AddonMapEnts>* asset) -{ - return true; -} +bool AssetDumperAddonMapEnts::ShouldDump(XAssetInfo<AddonMapEnts> *asset) { return true; } -void AssetDumperAddonMapEnts::DumpAsset(AssetDumpingContext& context, XAssetInfo<AddonMapEnts>* asset) -{ - const auto* addonMapEnts = asset->Asset(); - const auto assetFile = context.OpenAssetFile(asset->m_name); +void AssetDumperAddonMapEnts::DumpAsset(AssetDumpingContext &context, XAssetInfo<AddonMapEnts> *asset) { + const auto *addonMapEnts = asset->Asset(); + const auto assetFile = context.OpenAssetFile(asset->m_name); - if (!assetFile) - return; + if (!assetFile) + return; - auto& stream = *assetFile; - stream.write(addonMapEnts->entityString, std::max(addonMapEnts->numEntityChars - 1, 0)); + auto &stream = *assetFile; + stream.write(addonMapEnts->entityString, std::max(addonMapEnts->numEntityChars - 1, 0)); } diff --git a/src/ObjWriting/Game/IW5/AssetDumpers/AssetDumperAddonMapEnts.h b/src/ObjWriting/Game/IW5/AssetDumpers/AssetDumperAddonMapEnts.h index 47a6098e9..e12961e7f 100644 --- a/src/ObjWriting/Game/IW5/AssetDumpers/AssetDumperAddonMapEnts.h +++ b/src/ObjWriting/Game/IW5/AssetDumpers/AssetDumperAddonMapEnts.h @@ -3,12 +3,10 @@ #include "Dumping/AbstractAssetDumper.h" #include "Game/IW5/IW5.h" -namespace IW5 -{ - class AssetDumperAddonMapEnts final : public AbstractAssetDumper<AddonMapEnts> - { - protected: - bool ShouldDump(XAssetInfo<AddonMapEnts>* asset) override; - void DumpAsset(AssetDumpingContext& context, XAssetInfo<AddonMapEnts>* asset) override; - }; -} +namespace IW5 { +class AssetDumperAddonMapEnts final : public AbstractAssetDumper<AddonMapEnts> { +protected: + bool ShouldDump(XAssetInfo<AddonMapEnts> *asset) override; + void DumpAsset(AssetDumpingContext &context, XAssetInfo<AddonMapEnts> *asset) override; +}; +} // namespace IW5 diff --git a/src/ObjWriting/Game/IW5/AssetDumpers/AssetDumperGfxImage.cpp b/src/ObjWriting/Game/IW5/AssetDumpers/AssetDumperGfxImage.cpp index 6c00be0a0..899f96623 100644 --- a/src/ObjWriting/Game/IW5/AssetDumpers/AssetDumperGfxImage.cpp +++ b/src/ObjWriting/Game/IW5/AssetDumpers/AssetDumperGfxImage.cpp @@ -2,62 +2,55 @@ #include <cassert> -#include "ObjWriting.h" -#include "Image/IwiWriter8.h" #include "Image/DdsWriter.h" +#include "Image/IwiWriter8.h" +#include "ObjWriting.h" using namespace IW5; -AssetDumperGfxImage::AssetDumperGfxImage() -{ - switch (ObjWriting::Configuration.ImageOutputFormat) - { - case ObjWriting::Configuration_t::ImageOutputFormat_e::DDS: - m_writer = std::make_unique<DdsWriter>(); - break; - case ObjWriting::Configuration_t::ImageOutputFormat_e::IWI: - m_writer = std::make_unique<iwi8::IwiWriter>(); - break; - default: - assert(false); - m_writer = nullptr; - break; - } +AssetDumperGfxImage::AssetDumperGfxImage() { + switch (ObjWriting::Configuration.ImageOutputFormat) { + case ObjWriting::Configuration_t::ImageOutputFormat_e::DDS: + m_writer = std::make_unique<DdsWriter>(); + break; + case ObjWriting::Configuration_t::ImageOutputFormat_e::IWI: + m_writer = std::make_unique<iwi8::IwiWriter>(); + break; + default: + assert(false); + m_writer = nullptr; + break; + } } -bool AssetDumperGfxImage::ShouldDump(XAssetInfo<GfxImage>* asset) -{ - const auto* image = asset->Asset(); - return image->cardMemory.platform[0] > 0; +bool AssetDumperGfxImage::ShouldDump(XAssetInfo<GfxImage> *asset) { + const auto *image = asset->Asset(); + return image->cardMemory.platform[0] > 0; } -std::string AssetDumperGfxImage::GetAssetFileName(XAssetInfo<GfxImage>* asset) const -{ - std::string cleanAssetName = asset->m_name; - for (auto& c : cleanAssetName) - { - switch (c) - { - case '*': - c = '_'; - break; - - default: - break; - } +std::string AssetDumperGfxImage::GetAssetFileName(XAssetInfo<GfxImage> *asset) const { + std::string cleanAssetName = asset->m_name; + for (auto &c : cleanAssetName) { + switch (c) { + case '*': + c = '_'; + break; + + default: + break; } + } - return "images/" + cleanAssetName + m_writer->GetFileExtension(); + return "images/" + cleanAssetName + m_writer->GetFileExtension(); } -void AssetDumperGfxImage::DumpAsset(AssetDumpingContext& context, XAssetInfo<GfxImage>* asset) -{ - const auto* image = asset->Asset(); - const auto assetFile = context.OpenAssetFile(GetAssetFileName(asset)); +void AssetDumperGfxImage::DumpAsset(AssetDumpingContext &context, XAssetInfo<GfxImage> *asset) { + const auto *image = asset->Asset(); + const auto assetFile = context.OpenAssetFile(GetAssetFileName(asset)); - if (!assetFile) - return; + if (!assetFile) + return; - auto& stream = *assetFile; - m_writer->DumpImage(stream, image->texture.texture); + auto &stream = *assetFile; + m_writer->DumpImage(stream, image->texture.texture); } diff --git a/src/ObjWriting/Game/IW5/AssetDumpers/AssetDumperGfxImage.h b/src/ObjWriting/Game/IW5/AssetDumpers/AssetDumperGfxImage.h index 64a9267cc..7fb6bd796 100644 --- a/src/ObjWriting/Game/IW5/AssetDumpers/AssetDumperGfxImage.h +++ b/src/ObjWriting/Game/IW5/AssetDumpers/AssetDumperGfxImage.h @@ -6,19 +6,17 @@ #include "Game/IW5/IW5.h" #include "Image/IImageWriter.h" -namespace IW5 -{ - class AssetDumperGfxImage final : public AbstractAssetDumper<GfxImage> - { - std::unique_ptr<IImageWriter> m_writer; +namespace IW5 { +class AssetDumperGfxImage final : public AbstractAssetDumper<GfxImage> { + std::unique_ptr<IImageWriter> m_writer; - std::string GetAssetFileName(XAssetInfo<GfxImage>* asset) const; + std::string GetAssetFileName(XAssetInfo<GfxImage> *asset) const; - protected: - bool ShouldDump(XAssetInfo<GfxImage>* asset) override; - void DumpAsset(AssetDumpingContext& context, XAssetInfo<GfxImage>* asset) override; +protected: + bool ShouldDump(XAssetInfo<GfxImage> *asset) override; + void DumpAsset(AssetDumpingContext &context, XAssetInfo<GfxImage> *asset) override; - public: - AssetDumperGfxImage(); - }; -} +public: + AssetDumperGfxImage(); +}; +} // namespace IW5 diff --git a/src/ObjWriting/Game/IW5/AssetDumpers/AssetDumperLoadedSound.cpp b/src/ObjWriting/Game/IW5/AssetDumpers/AssetDumperLoadedSound.cpp index 392d22ea2..71f216d8b 100644 --- a/src/ObjWriting/Game/IW5/AssetDumpers/AssetDumperLoadedSound.cpp +++ b/src/ObjWriting/Game/IW5/AssetDumpers/AssetDumperLoadedSound.cpp @@ -4,69 +4,47 @@ using namespace IW5; -bool AssetDumperLoadedSound::ShouldDump(XAssetInfo<LoadedSound>* asset) -{ - return true; +bool AssetDumperLoadedSound::ShouldDump(XAssetInfo<LoadedSound> *asset) { return true; } + +void AssetDumperLoadedSound::DumpWavPcm(AssetDumpingContext &context, const LoadedSound *asset, std::ostream &stream) { + const auto riffMasterChunkSize = sizeof(WAV_CHUNK_ID_RIFF) + sizeof(uint32_t) + sizeof(WAV_WAVE_ID) + sizeof(WavChunkHeader) + sizeof(WavFormatChunkPcm) + + sizeof(WavChunkHeader) + sizeof(asset->sound.info.data_len); + + stream.write(reinterpret_cast<const char *>(&WAV_CHUNK_ID_RIFF), sizeof(WAV_CHUNK_ID_RIFF)); + stream.write(reinterpret_cast<const char *>(&riffMasterChunkSize), sizeof(riffMasterChunkSize)); + stream.write(reinterpret_cast<const char *>(&WAV_WAVE_ID), sizeof(WAV_WAVE_ID)); + + const WavChunkHeader formatChunkHeader{WAV_CHUNK_ID_FMT, sizeof(WavFormatChunkPcm)}; + stream.write(reinterpret_cast<const char *>(&formatChunkHeader), sizeof(formatChunkHeader)); + + WavFormatChunkPcm formatChunk{WavFormat::PCM, + static_cast<uint16_t>(asset->sound.info.channels), + asset->sound.info.rate, + asset->sound.info.rate * asset->sound.info.channels * asset->sound.info.bits / 8, + static_cast<uint16_t>(asset->sound.info.block_size), + static_cast<uint16_t>(asset->sound.info.bits)}; + stream.write(reinterpret_cast<const char *>(&formatChunk), sizeof(formatChunk)); + + const WavChunkHeader dataChunkHeader{WAV_CHUNK_ID_DATA, asset->sound.info.data_len}; + stream.write(reinterpret_cast<const char *>(&dataChunkHeader), sizeof(dataChunkHeader)); + stream.write(asset->sound.data, asset->sound.info.data_len); } -void AssetDumperLoadedSound::DumpWavPcm(AssetDumpingContext& context, const LoadedSound* asset, std::ostream& stream) -{ - const auto riffMasterChunkSize = sizeof(WAV_CHUNK_ID_RIFF) - + sizeof(uint32_t) - + sizeof(WAV_WAVE_ID) - + sizeof(WavChunkHeader) - + sizeof(WavFormatChunkPcm) - + sizeof(WavChunkHeader) - + sizeof(asset->sound.info.data_len); +void AssetDumperLoadedSound::DumpAsset(AssetDumpingContext &context, XAssetInfo<LoadedSound> *asset) { + const auto *loadedSound = asset->Asset(); + const auto assetFile = context.OpenAssetFile("sound/" + asset->m_name); - stream.write(reinterpret_cast<const char*>(&WAV_CHUNK_ID_RIFF), sizeof(WAV_CHUNK_ID_RIFF)); - stream.write(reinterpret_cast<const char*>(&riffMasterChunkSize), sizeof(riffMasterChunkSize)); - stream.write(reinterpret_cast<const char*>(&WAV_WAVE_ID), sizeof(WAV_WAVE_ID)); + if (!assetFile) + return; - const WavChunkHeader formatChunkHeader - { - WAV_CHUNK_ID_FMT, - sizeof(WavFormatChunkPcm) - }; - stream.write(reinterpret_cast<const char*>(&formatChunkHeader), sizeof(formatChunkHeader)); + auto &stream = *assetFile; + switch (static_cast<WavFormat>(loadedSound->sound.info.format)) { + case WavFormat::PCM: + DumpWavPcm(context, loadedSound, stream); + break; - WavFormatChunkPcm formatChunk - { - WavFormat::PCM, - static_cast<uint16_t>(asset->sound.info.channels), - asset->sound.info.rate, - asset->sound.info.rate * asset->sound.info.channels * asset->sound.info.bits / 8, - static_cast<uint16_t>(asset->sound.info.block_size), - static_cast<uint16_t>(asset->sound.info.bits) - }; - stream.write(reinterpret_cast<const char*>(&formatChunk), sizeof(formatChunk)); - - const WavChunkHeader dataChunkHeader - { - WAV_CHUNK_ID_DATA, - asset->sound.info.data_len - }; - stream.write(reinterpret_cast<const char*>(&dataChunkHeader), sizeof(dataChunkHeader)); - stream.write(asset->sound.data, asset->sound.info.data_len); -} - -void AssetDumperLoadedSound::DumpAsset(AssetDumpingContext& context, XAssetInfo<LoadedSound>* asset) -{ - const auto* loadedSound = asset->Asset(); - const auto assetFile = context.OpenAssetFile("sound/" + asset->m_name); - - if (!assetFile) - return; - - auto& stream = *assetFile; - switch (static_cast<WavFormat>(loadedSound->sound.info.format)) - { - case WavFormat::PCM: - DumpWavPcm(context, loadedSound, stream); - break; - - default: - printf("Unknown format %i for loaded sound: %s\n", loadedSound->sound.info.format, loadedSound->name); - break; - } + default: + printf("Unknown format %i for loaded sound: %s\n", loadedSound->sound.info.format, loadedSound->name); + break; + } } diff --git a/src/ObjWriting/Game/IW5/AssetDumpers/AssetDumperLoadedSound.h b/src/ObjWriting/Game/IW5/AssetDumpers/AssetDumperLoadedSound.h index d60e60882..d96e74dc7 100644 --- a/src/ObjWriting/Game/IW5/AssetDumpers/AssetDumperLoadedSound.h +++ b/src/ObjWriting/Game/IW5/AssetDumpers/AssetDumperLoadedSound.h @@ -3,14 +3,12 @@ #include "Dumping/AbstractAssetDumper.h" #include "Game/IW5/IW5.h" -namespace IW5 -{ - class AssetDumperLoadedSound final : public AbstractAssetDumper<LoadedSound> - { - static void DumpWavPcm(AssetDumpingContext& context, const LoadedSound* asset, std::ostream& stream); +namespace IW5 { +class AssetDumperLoadedSound final : public AbstractAssetDumper<LoadedSound> { + static void DumpWavPcm(AssetDumpingContext &context, const LoadedSound *asset, std::ostream &stream); - protected: - bool ShouldDump(XAssetInfo<LoadedSound>* asset) override; - void DumpAsset(AssetDumpingContext& context, XAssetInfo<LoadedSound>* asset) override; - }; -} +protected: + bool ShouldDump(XAssetInfo<LoadedSound> *asset) override; + void DumpAsset(AssetDumpingContext &context, XAssetInfo<LoadedSound> *asset) override; +}; +} // namespace IW5 diff --git a/src/ObjWriting/Game/IW5/AssetDumpers/AssetDumperLocalizeEntry.cpp b/src/ObjWriting/Game/IW5/AssetDumpers/AssetDumperLocalizeEntry.cpp index 476fc32e1..8db048912 100644 --- a/src/ObjWriting/Game/IW5/AssetDumpers/AssetDumperLocalizeEntry.cpp +++ b/src/ObjWriting/Game/IW5/AssetDumpers/AssetDumperLocalizeEntry.cpp @@ -2,42 +2,37 @@ #include <sstream> -#include "Localize/LocalizeCommon.h" #include "Dumping/Localize/StringFileDumper.h" +#include "Localize/LocalizeCommon.h" using namespace IW5; -void AssetDumperLocalizeEntry::DumpPool(AssetDumpingContext& context, AssetPool<LocalizeEntry>* pool) -{ - if (pool->m_asset_lookup.empty()) - return; - - const auto language = LocalizeCommon::GetNameOfLanguage(context.m_zone->m_language); +void AssetDumperLocalizeEntry::DumpPool(AssetDumpingContext &context, AssetPool<LocalizeEntry> *pool) { + if (pool->m_asset_lookup.empty()) + return; - std::ostringstream ss; - ss << language << "/localizedstrings/" << context.m_zone->m_name << ".str"; - const auto assetFile = context.OpenAssetFile(ss.str()); + const auto language = LocalizeCommon::GetNameOfLanguage(context.m_zone->m_language); - if (assetFile) - { - StringFileDumper stringFileDumper(context.m_zone, *assetFile); + std::ostringstream ss; + ss << language << "/localizedstrings/" << context.m_zone->m_name << ".str"; + const auto assetFile = context.OpenAssetFile(ss.str()); - stringFileDumper.SetLanguageName(language); + if (assetFile) { + StringFileDumper stringFileDumper(context.m_zone, *assetFile); - // Magic string. Original string files do have this config file. The purpose of the config file is unknown though. - stringFileDumper.SetConfigFile(R"(C:/trees/cod3/cod3/bin/StringEd.cfg)"); + stringFileDumper.SetLanguageName(language); - stringFileDumper.SetNotes(""); + // Magic string. Original string files do have this config file. The purpose of the config file is unknown though. + stringFileDumper.SetConfigFile(R"(C:/trees/cod3/cod3/bin/StringEd.cfg)"); - for (auto* localizeEntry : *pool) - { - stringFileDumper.WriteLocalizeEntry(localizeEntry->m_name, localizeEntry->Asset()->value); - } + stringFileDumper.SetNotes(""); - stringFileDumper.Finalize(); - } - else - { - printf("Could not create string file for dumping localized strings of zone '%s'\n", context.m_zone->m_name.c_str()); + for (auto *localizeEntry : *pool) { + stringFileDumper.WriteLocalizeEntry(localizeEntry->m_name, localizeEntry->Asset()->value); } + + stringFileDumper.Finalize(); + } else { + printf("Could not create string file for dumping localized strings of zone '%s'\n", context.m_zone->m_name.c_str()); + } } \ No newline at end of file diff --git a/src/ObjWriting/Game/IW5/AssetDumpers/AssetDumperLocalizeEntry.h b/src/ObjWriting/Game/IW5/AssetDumpers/AssetDumperLocalizeEntry.h index ecbd837cd..5c45143dd 100644 --- a/src/ObjWriting/Game/IW5/AssetDumpers/AssetDumperLocalizeEntry.h +++ b/src/ObjWriting/Game/IW5/AssetDumpers/AssetDumperLocalizeEntry.h @@ -3,11 +3,9 @@ #include "Dumping/AbstractAssetDumper.h" #include "Game/IW5/IW5.h" -namespace IW5 -{ - class AssetDumperLocalizeEntry final : public IAssetDumper<LocalizeEntry> - { - public: - void DumpPool(AssetDumpingContext& context, AssetPool<LocalizeEntry>* pool) override; - }; -} +namespace IW5 { +class AssetDumperLocalizeEntry final : public IAssetDumper<LocalizeEntry> { +public: + void DumpPool(AssetDumpingContext &context, AssetPool<LocalizeEntry> *pool) override; +}; +} // namespace IW5 diff --git a/src/ObjWriting/Game/IW5/AssetDumpers/AssetDumperMenuDef.cpp b/src/ObjWriting/Game/IW5/AssetDumpers/AssetDumperMenuDef.cpp index 47154ffa0..0bb99d5a0 100644 --- a/src/ObjWriting/Game/IW5/AssetDumpers/AssetDumperMenuDef.cpp +++ b/src/ObjWriting/Game/IW5/AssetDumpers/AssetDumperMenuDef.cpp @@ -3,74 +3,65 @@ #include <filesystem> #include <string> -#include "ObjWriting.h" #include "Game/IW5/GameAssetPoolIW5.h" #include "Game/IW5/Menu/MenuDumperIW5.h" #include "Menu/AbstractMenuDumper.h" +#include "ObjWriting.h" namespace fs = std::filesystem; using namespace IW5; -const MenuList* AssetDumperMenuDef::GetParentMenuList(XAssetInfo<menuDef_t>* asset) -{ - const auto* menu = asset->Asset(); - const auto* gameAssetPool = dynamic_cast<GameAssetPoolIW5*>(asset->m_zone->m_pools.get()); - for (const auto* menuList : *gameAssetPool->m_menu_list) - { - const auto* menuListAsset = menuList->Asset(); - - for (auto menuIndex = 0; menuIndex < menuListAsset->menuCount; menuIndex++) - { - if (menuListAsset->menus[menuIndex] == menu) - return menuListAsset; - } +const MenuList *AssetDumperMenuDef::GetParentMenuList(XAssetInfo<menuDef_t> *asset) { + const auto *menu = asset->Asset(); + const auto *gameAssetPool = dynamic_cast<GameAssetPoolIW5 *>(asset->m_zone->m_pools.get()); + for (const auto *menuList : *gameAssetPool->m_menu_list) { + const auto *menuListAsset = menuList->Asset(); + + for (auto menuIndex = 0; menuIndex < menuListAsset->menuCount; menuIndex++) { + if (menuListAsset->menus[menuIndex] == menu) + return menuListAsset; } + } - return nullptr; + return nullptr; } -std::string AssetDumperMenuDef::GetPathForMenu(XAssetInfo<menuDef_t>* asset) -{ - const auto* list = GetParentMenuList(asset); +std::string AssetDumperMenuDef::GetPathForMenu(XAssetInfo<menuDef_t> *asset) { + const auto *list = GetParentMenuList(asset); - if (!list) - return "ui_mp/" + std::string(asset->Asset()->window.name) + ".menu"; + if (!list) + return "ui_mp/" + std::string(asset->Asset()->window.name) + ".menu"; - const fs::path p(list->name); - std::string parentPath; - if (p.has_parent_path()) - parentPath = p.parent_path().string() + "/"; + const fs::path p(list->name); + std::string parentPath; + if (p.has_parent_path()) + parentPath = p.parent_path().string() + "/"; - return parentPath + std::string(asset->Asset()->window.name) + ".menu"; + return parentPath + std::string(asset->Asset()->window.name) + ".menu"; } -bool AssetDumperMenuDef::ShouldDump(XAssetInfo<menuDef_t>* asset) -{ - return true; -} +bool AssetDumperMenuDef::ShouldDump(XAssetInfo<menuDef_t> *asset) { return true; } -void AssetDumperMenuDef::DumpAsset(AssetDumpingContext& context, XAssetInfo<menuDef_t>* asset) -{ - const auto* menu = asset->Asset(); - const auto menuFilePath = GetPathForMenu(asset); - - if(ObjWriting::ShouldHandleAssetType(ASSET_TYPE_MENULIST)) - { - // Don't dump menu file separately if the name matches the menu list - const auto* menuListParent = GetParentMenuList(asset); - if (menuListParent && menuFilePath == menuListParent->name) - return; - } +void AssetDumperMenuDef::DumpAsset(AssetDumpingContext &context, XAssetInfo<menuDef_t> *asset) { + const auto *menu = asset->Asset(); + const auto menuFilePath = GetPathForMenu(asset); + + if (ObjWriting::ShouldHandleAssetType(ASSET_TYPE_MENULIST)) { + // Don't dump menu file separately if the name matches the menu list + const auto *menuListParent = GetParentMenuList(asset); + if (menuListParent && menuFilePath == menuListParent->name) + return; + } - const auto assetFile = context.OpenAssetFile(menuFilePath); + const auto assetFile = context.OpenAssetFile(menuFilePath); - if (!assetFile) - return; + if (!assetFile) + return; - MenuDumper menuDumper(*assetFile); + MenuDumper menuDumper(*assetFile); - menuDumper.Start(); - menuDumper.WriteMenu(menu); - menuDumper.End(); + menuDumper.Start(); + menuDumper.WriteMenu(menu); + menuDumper.End(); } diff --git a/src/ObjWriting/Game/IW5/AssetDumpers/AssetDumperMenuDef.h b/src/ObjWriting/Game/IW5/AssetDumpers/AssetDumperMenuDef.h index d965cc91b..0a0282965 100644 --- a/src/ObjWriting/Game/IW5/AssetDumpers/AssetDumperMenuDef.h +++ b/src/ObjWriting/Game/IW5/AssetDumpers/AssetDumperMenuDef.h @@ -3,15 +3,13 @@ #include "Dumping/AbstractAssetDumper.h" #include "Game/IW5/IW5.h" -namespace IW5 -{ - class AssetDumperMenuDef final : public AbstractAssetDumper<menuDef_t> - { - static const MenuList* GetParentMenuList(XAssetInfo<menuDef_t>* asset); - static std::string GetPathForMenu(XAssetInfo<menuDef_t>* asset); +namespace IW5 { +class AssetDumperMenuDef final : public AbstractAssetDumper<menuDef_t> { + static const MenuList *GetParentMenuList(XAssetInfo<menuDef_t> *asset); + static std::string GetPathForMenu(XAssetInfo<menuDef_t> *asset); - protected: - bool ShouldDump(XAssetInfo<menuDef_t>* asset) override; - void DumpAsset(AssetDumpingContext& context, XAssetInfo<menuDef_t>* asset) override; - }; -} +protected: + bool ShouldDump(XAssetInfo<menuDef_t> *asset) override; + void DumpAsset(AssetDumpingContext &context, XAssetInfo<menuDef_t> *asset) override; +}; +} // namespace IW5 diff --git a/src/ObjWriting/Game/IW5/AssetDumpers/AssetDumperMenuList.cpp b/src/ObjWriting/Game/IW5/AssetDumpers/AssetDumperMenuList.cpp index b5909f780..fefbf005d 100644 --- a/src/ObjWriting/Game/IW5/AssetDumpers/AssetDumperMenuList.cpp +++ b/src/ObjWriting/Game/IW5/AssetDumpers/AssetDumperMenuList.cpp @@ -2,122 +2,110 @@ #include <cassert> #include <filesystem> -#include <sstream> #include <set> +#include <sstream> -#include "ObjWriting.h" #include "Game/IW5/Menu/MenuDumperIW5.h" #include "Menu/AbstractMenuDumper.h" +#include "ObjWriting.h" namespace fs = std::filesystem; using namespace IW5; -std::vector<const ExpressionSupportingData*> AssetDumperMenuList::GetAllUniqueExpressionSupportingData(const MenuList* menuList) -{ - std::vector<const ExpressionSupportingData*> result; - std::set<const ExpressionSupportingData*> alreadyAddedSupportingData; +std::vector<const ExpressionSupportingData *> AssetDumperMenuList::GetAllUniqueExpressionSupportingData(const MenuList *menuList) { + std::vector<const ExpressionSupportingData *> result; + std::set<const ExpressionSupportingData *> alreadyAddedSupportingData; - if (menuList->menus == nullptr) - return result; + if (menuList->menus == nullptr) + return result; - for(auto i = 0; i < menuList->menuCount; i++) - { - if(menuList->menus[i] == nullptr) - continue; + for (auto i = 0; i < menuList->menuCount; i++) { + if (menuList->menus[i] == nullptr) + continue; - const auto* menu = menuList->menus[i]; + const auto *menu = menuList->menus[i]; - if(menu->data == nullptr || menu->data->expressionData == nullptr) - continue; + if (menu->data == nullptr || menu->data->expressionData == nullptr) + continue; - if(alreadyAddedSupportingData.find(menu->data->expressionData) == alreadyAddedSupportingData.end()) - { - result.push_back(menu->data->expressionData); - alreadyAddedSupportingData.emplace(menu->data->expressionData); - } + if (alreadyAddedSupportingData.find(menu->data->expressionData) == alreadyAddedSupportingData.end()) { + result.push_back(menu->data->expressionData); + alreadyAddedSupportingData.emplace(menu->data->expressionData); } + } - return result; + return result; } -void AssetDumperMenuList::DumpFunctions(MenuDumper& menuDumper, const MenuList* menuList) -{ - const auto allSupportingData = GetAllUniqueExpressionSupportingData(menuList); - auto functionIndex = 0u; +void AssetDumperMenuList::DumpFunctions(MenuDumper &menuDumper, const MenuList *menuList) { + const auto allSupportingData = GetAllUniqueExpressionSupportingData(menuList); + auto functionIndex = 0u; - assert(allSupportingData.size() <= 1); + assert(allSupportingData.size() <= 1); - for (const auto* supportingData : allSupportingData) - { - if (supportingData->uifunctions.functions == nullptr) - continue; + for (const auto *supportingData : allSupportingData) { + if (supportingData->uifunctions.functions == nullptr) + continue; - for(auto i = 0; i < supportingData->uifunctions.totalFunctions; i++) - { - const auto* function = supportingData->uifunctions.functions[i]; - if(function == nullptr) - continue; + for (auto i = 0; i < supportingData->uifunctions.totalFunctions; i++) { + const auto *function = supportingData->uifunctions.functions[i]; + if (function == nullptr) + continue; - std::stringstream ss; - ss << "FUNC_" << functionIndex; + std::stringstream ss; + ss << "FUNC_" << functionIndex; - menuDumper.WriteFunctionDef(ss.str(), function); + menuDumper.WriteFunctionDef(ss.str(), function); - functionIndex++; - } + functionIndex++; } + } } -void AssetDumperMenuList::DumpMenus(MenuDumper& menuDumper, const MenuList* menuList) -{ - const fs::path p(menuList->name); +void AssetDumperMenuList::DumpMenus(MenuDumper &menuDumper, const MenuList *menuList) { + const fs::path p(menuList->name); - std::string parentPath; - if (p.has_parent_path()) - parentPath = p.parent_path().string() + "/"; + std::string parentPath; + if (p.has_parent_path()) + parentPath = p.parent_path().string() + "/"; - for (auto menuNum = 0; menuNum < menuList->menuCount; menuNum++) - { - const auto* menu = menuList->menus[menuNum]; - const auto* menuAssetName = menu->window.name; - if (menuAssetName && menuAssetName[0] == ',') - menuAssetName = &menuAssetName[1]; + for (auto menuNum = 0; menuNum < menuList->menuCount; menuNum++) { + const auto *menu = menuList->menus[menuNum]; + const auto *menuAssetName = menu->window.name; + if (menuAssetName && menuAssetName[0] == ',') + menuAssetName = &menuAssetName[1]; - std::ostringstream ss; - ss << parentPath << menuAssetName << ".menu"; + std::ostringstream ss; + ss << parentPath << menuAssetName << ".menu"; - const auto menuName = ss.str(); + const auto menuName = ss.str(); - // If the menu was embedded directly as menu list write its data in the menu list file - if (menuName == menuList->name) - menuDumper.WriteMenu(menu); - else - menuDumper.IncludeMenu(ss.str()); - } + // If the menu was embedded directly as menu list write its data in the menu list file + if (menuName == menuList->name) + menuDumper.WriteMenu(menu); + else + menuDumper.IncludeMenu(ss.str()); + } } -bool AssetDumperMenuList::ShouldDump(XAssetInfo<MenuList>* asset) -{ - return true; -} +bool AssetDumperMenuList::ShouldDump(XAssetInfo<MenuList> *asset) { return true; } -void AssetDumperMenuList::DumpAsset(AssetDumpingContext& context, XAssetInfo<MenuList>* asset) -{ - const auto* menuList = asset->Asset(); - const auto assetFile = context.OpenAssetFile(asset->m_name); +void AssetDumperMenuList::DumpAsset(AssetDumpingContext &context, XAssetInfo<MenuList> *asset) { + const auto *menuList = asset->Asset(); + const auto assetFile = context.OpenAssetFile(asset->m_name); - if (!assetFile) - return; + if (!assetFile) + return; - MenuDumper menuDumper(*assetFile); + MenuDumper menuDumper(*assetFile); - menuDumper.Start(); + menuDumper.Start(); - if(!ObjWriting::Configuration.MenuLegacyMode) - DumpFunctions(menuDumper, menuList); + if (!ObjWriting::Configuration.MenuLegacyMode) + DumpFunctions(menuDumper, menuList); - DumpMenus(menuDumper, menuList); + DumpMenus(menuDumper, menuList); - menuDumper.End(); + menuDumper.End(); } diff --git a/src/ObjWriting/Game/IW5/AssetDumpers/AssetDumperMenuList.h b/src/ObjWriting/Game/IW5/AssetDumpers/AssetDumperMenuList.h index 6f12aaf39..be71795e9 100644 --- a/src/ObjWriting/Game/IW5/AssetDumpers/AssetDumperMenuList.h +++ b/src/ObjWriting/Game/IW5/AssetDumpers/AssetDumperMenuList.h @@ -4,17 +4,15 @@ #include "Game/IW5/IW5.h" #include "Game/IW5/Menu/MenuDumperIW5.h" -namespace IW5 -{ - class AssetDumperMenuList final : public AbstractAssetDumper<MenuList> - { - static std::vector<const ExpressionSupportingData*> GetAllUniqueExpressionSupportingData(const MenuList* menuList); +namespace IW5 { +class AssetDumperMenuList final : public AbstractAssetDumper<MenuList> { + static std::vector<const ExpressionSupportingData *> GetAllUniqueExpressionSupportingData(const MenuList *menuList); - static void DumpFunctions(MenuDumper& menuDumper, const MenuList* menuList); - static void DumpMenus(MenuDumper& menuDumper, const MenuList* menuList); + static void DumpFunctions(MenuDumper &menuDumper, const MenuList *menuList); + static void DumpMenus(MenuDumper &menuDumper, const MenuList *menuList); - protected: - bool ShouldDump(XAssetInfo<MenuList>* asset) override; - void DumpAsset(AssetDumpingContext& context, XAssetInfo<MenuList>* asset) override; - }; -} +protected: + bool ShouldDump(XAssetInfo<MenuList> *asset) override; + void DumpAsset(AssetDumpingContext &context, XAssetInfo<MenuList> *asset) override; +}; +} // namespace IW5 diff --git a/src/ObjWriting/Game/IW5/AssetDumpers/AssetDumperRawFile.cpp b/src/ObjWriting/Game/IW5/AssetDumpers/AssetDumperRawFile.cpp index 47ef898b1..74a4f70c7 100644 --- a/src/ObjWriting/Game/IW5/AssetDumpers/AssetDumperRawFile.cpp +++ b/src/ObjWriting/Game/IW5/AssetDumpers/AssetDumperRawFile.cpp @@ -1,80 +1,70 @@ #include "AssetDumperRawFile.h" -#include <zlib.h> #include <stdexcept> +#include <zlib.h> using namespace IW5; -bool AssetDumperRawFile::ShouldDump(XAssetInfo<RawFile>* asset) -{ - return true; -} +bool AssetDumperRawFile::ShouldDump(XAssetInfo<RawFile> *asset) { return true; } + +std::string AssetDumperRawFile::GetAssetFileName(XAssetInfo<GfxImage> *asset) { + std::string cleanAssetName = asset->m_name; + for (auto &c : cleanAssetName) { + switch (c) { + case '*': + c = '_'; + break; -std::string AssetDumperRawFile::GetAssetFileName(XAssetInfo<GfxImage>* asset) -{ - std::string cleanAssetName = asset->m_name; - for (auto& c : cleanAssetName) - { - switch (c) - { - case '*': - c = '_'; - break; - - default: - break; - } + default: + break; } + } - return cleanAssetName; + return cleanAssetName; } -void AssetDumperRawFile::DumpAsset(AssetDumpingContext& context, XAssetInfo<RawFile>* asset) -{ - const auto* rawFile = asset->Asset(); - const auto assetFile = context.OpenAssetFile(asset->m_name); +void AssetDumperRawFile::DumpAsset(AssetDumpingContext &context, XAssetInfo<RawFile> *asset) { + const auto *rawFile = asset->Asset(); + const auto assetFile = context.OpenAssetFile(asset->m_name); - if (!assetFile) - return; + if (!assetFile) + return; - auto& stream = *assetFile; - if (rawFile->compressedLen <= 0) - return; + auto &stream = *assetFile; + if (rawFile->compressedLen <= 0) + return; - z_stream_s zs{}; - zs.zalloc = Z_NULL; - zs.zfree = Z_NULL; - zs.opaque = Z_NULL; - zs.avail_in = 0; - zs.next_in = Z_NULL; + z_stream_s zs{}; + zs.zalloc = Z_NULL; + zs.zfree = Z_NULL; + zs.opaque = Z_NULL; + zs.avail_in = 0; + zs.next_in = Z_NULL; - int ret = inflateInit(&zs); + int ret = inflateInit(&zs); - if (ret != Z_OK) - { - throw std::runtime_error("Initializing inflate failed"); - } - - zs.next_in = reinterpret_cast<const Bytef*>(rawFile->buffer); - zs.avail_in = rawFile->compressedLen; + if (ret != Z_OK) { + throw std::runtime_error("Initializing inflate failed"); + } - Bytef buffer[0x1000]; + zs.next_in = reinterpret_cast<const Bytef *>(rawFile->buffer); + zs.avail_in = rawFile->compressedLen; - while (zs.avail_in > 0) - { - zs.next_out = buffer; - zs.avail_out = sizeof buffer; - ret = inflate(&zs, Z_SYNC_FLUSH); + Bytef buffer[0x1000]; - if (ret < 0) - { - printf("Inflate failed for dumping rawfile '%s'\n", rawFile->name); - inflateEnd(&zs); - return; - } + while (zs.avail_in > 0) { + zs.next_out = buffer; + zs.avail_out = sizeof buffer; + ret = inflate(&zs, Z_SYNC_FLUSH); - stream.write(reinterpret_cast<char*>(buffer), sizeof buffer - zs.avail_out); + if (ret < 0) { + printf("Inflate failed for dumping rawfile '%s'\n", rawFile->name); + inflateEnd(&zs); + return; } - inflateEnd(&zs); + stream.write(reinterpret_cast<char *>(buffer), sizeof buffer - zs.avail_out); + } + + inflateEnd(&zs); } diff --git a/src/ObjWriting/Game/IW5/AssetDumpers/AssetDumperRawFile.h b/src/ObjWriting/Game/IW5/AssetDumpers/AssetDumperRawFile.h index b1c87b88b..8d07cd33a 100644 --- a/src/ObjWriting/Game/IW5/AssetDumpers/AssetDumperRawFile.h +++ b/src/ObjWriting/Game/IW5/AssetDumpers/AssetDumperRawFile.h @@ -3,14 +3,12 @@ #include "Dumping/AbstractAssetDumper.h" #include "Game/IW5/IW5.h" -namespace IW5 -{ - class AssetDumperRawFile final : public AbstractAssetDumper<RawFile> - { - static std::string GetAssetFileName(XAssetInfo<GfxImage>* asset); +namespace IW5 { +class AssetDumperRawFile final : public AbstractAssetDumper<RawFile> { + static std::string GetAssetFileName(XAssetInfo<GfxImage> *asset); - protected: - bool ShouldDump(XAssetInfo<RawFile>* asset) override; - void DumpAsset(AssetDumpingContext& context, XAssetInfo<RawFile>* asset) override; - }; -} +protected: + bool ShouldDump(XAssetInfo<RawFile> *asset) override; + void DumpAsset(AssetDumpingContext &context, XAssetInfo<RawFile> *asset) override; +}; +} // namespace IW5 diff --git a/src/ObjWriting/Game/IW5/AssetDumpers/AssetDumperStringTable.cpp b/src/ObjWriting/Game/IW5/AssetDumpers/AssetDumperStringTable.cpp index 0502816d5..e1659c7da 100644 --- a/src/ObjWriting/Game/IW5/AssetDumpers/AssetDumperStringTable.cpp +++ b/src/ObjWriting/Game/IW5/AssetDumpers/AssetDumperStringTable.cpp @@ -4,29 +4,23 @@ using namespace IW5; -bool AssetDumperStringTable::ShouldDump(XAssetInfo<StringTable>* asset) -{ - return true; -} - -void AssetDumperStringTable::DumpAsset(AssetDumpingContext& context, XAssetInfo<StringTable>* asset) -{ - const auto* stringTable = asset->Asset(); - const auto assetFile = context.OpenAssetFile(asset->m_name); +bool AssetDumperStringTable::ShouldDump(XAssetInfo<StringTable> *asset) { return true; } - if (!assetFile) - return; +void AssetDumperStringTable::DumpAsset(AssetDumpingContext &context, XAssetInfo<StringTable> *asset) { + const auto *stringTable = asset->Asset(); + const auto assetFile = context.OpenAssetFile(asset->m_name); - CsvOutputStream csv(*assetFile); + if (!assetFile) + return; - for (auto row = 0; row < stringTable->rowCount; row++) - { - for (auto column = 0; column < stringTable->columnCount; column++) - { - const auto* cell = &stringTable->values[column + row * stringTable->columnCount]; - csv.WriteColumn(cell->string); - } + CsvOutputStream csv(*assetFile); - csv.NextRow(); + for (auto row = 0; row < stringTable->rowCount; row++) { + for (auto column = 0; column < stringTable->columnCount; column++) { + const auto *cell = &stringTable->values[column + row * stringTable->columnCount]; + csv.WriteColumn(cell->string); } + + csv.NextRow(); + } } diff --git a/src/ObjWriting/Game/IW5/AssetDumpers/AssetDumperStringTable.h b/src/ObjWriting/Game/IW5/AssetDumpers/AssetDumperStringTable.h index bdc480fa9..7b7686cdb 100644 --- a/src/ObjWriting/Game/IW5/AssetDumpers/AssetDumperStringTable.h +++ b/src/ObjWriting/Game/IW5/AssetDumpers/AssetDumperStringTable.h @@ -3,12 +3,10 @@ #include "Dumping/AbstractAssetDumper.h" #include "Game/IW5/IW5.h" -namespace IW5 -{ - class AssetDumperStringTable final : public AbstractAssetDumper<StringTable> - { - protected: - bool ShouldDump(XAssetInfo<StringTable>* asset) override; - void DumpAsset(AssetDumpingContext& context, XAssetInfo<StringTable>* asset) override; - }; -} +namespace IW5 { +class AssetDumperStringTable final : public AbstractAssetDumper<StringTable> { +protected: + bool ShouldDump(XAssetInfo<StringTable> *asset) override; + void DumpAsset(AssetDumpingContext &context, XAssetInfo<StringTable> *asset) override; +}; +} // namespace IW5 diff --git a/src/ObjWriting/Game/IW5/AssetDumpers/AssetDumperXModel.cpp b/src/ObjWriting/Game/IW5/AssetDumpers/AssetDumperXModel.cpp index 34433ea99..b0e3c586f 100644 --- a/src/ObjWriting/Game/IW5/AssetDumpers/AssetDumperXModel.cpp +++ b/src/ObjWriting/Game/IW5/AssetDumpers/AssetDumperXModel.cpp @@ -2,644 +2,528 @@ #include <cassert> -#include "ObjWriting.h" #include "Game/IW5/CommonIW5.h" #include "Math/Quaternion.h" #include "Model/XModel/XModelExportWriter.h" +#include "ObjWriting.h" #include "Utils/HalfFloat.h" #include "Utils/QuatInt16.h" using namespace IW5; -namespace IW5 -{ - class SurfsDumpingZoneState final : public IZoneAssetDumperState - { - std::set<const XModelSurfs*> m_dumped_surfs; +namespace IW5 { +class SurfsDumpingZoneState final : public IZoneAssetDumperState { + std::set<const XModelSurfs *> m_dumped_surfs; - public: - bool ShouldDumpTechnique(const XModelSurfs* surfs) - { - if (m_dumped_surfs.find(surfs) != m_dumped_surfs.end()) - return false; +public: + bool ShouldDumpTechnique(const XModelSurfs *surfs) { + if (m_dumped_surfs.find(surfs) != m_dumped_surfs.end()) + return false; - m_dumped_surfs.emplace(surfs); - return true; - } - }; -} + m_dumped_surfs.emplace(surfs); + return true; + } +}; +} // namespace IW5 -bool AssetDumperXModel::ShouldDump(XAssetInfo<XModel>* asset) -{ - return !asset->m_name.empty() && asset->m_name[0] != ','; -} +bool AssetDumperXModel::ShouldDump(XAssetInfo<XModel> *asset) { return !asset->m_name.empty() && asset->m_name[0] != ','; } -GfxImage* AssetDumperXModel::GetMaterialColorMap(const Material* material) -{ - std::vector<MaterialTextureDef*> potentialTextureDefs; +GfxImage *AssetDumperXModel::GetMaterialColorMap(const Material *material) { + std::vector<MaterialTextureDef *> potentialTextureDefs; - for (auto textureIndex = 0u; textureIndex < material->textureCount; textureIndex++) - { - MaterialTextureDef* def = &material->textureTable[textureIndex]; + for (auto textureIndex = 0u; textureIndex < material->textureCount; textureIndex++) { + MaterialTextureDef *def = &material->textureTable[textureIndex]; - if (def->semantic == TS_COLOR_MAP) - potentialTextureDefs.push_back(def); - } + if (def->semantic == TS_COLOR_MAP) + potentialTextureDefs.push_back(def); + } - if (potentialTextureDefs.empty()) - return nullptr; - if (potentialTextureDefs.size() == 1) - return potentialTextureDefs[0]->u.image; + if (potentialTextureDefs.empty()) + return nullptr; + if (potentialTextureDefs.size() == 1) + return potentialTextureDefs[0]->u.image; - for (const auto* def : potentialTextureDefs) - { - if (def->nameStart == 'c' && def->nameEnd == 'p') - return def->u.image; - } + for (const auto *def : potentialTextureDefs) { + if (def->nameStart == 'c' && def->nameEnd == 'p') + return def->u.image; + } - return potentialTextureDefs[0]->u.image; + return potentialTextureDefs[0]->u.image; } -GfxImage* AssetDumperXModel::GetMaterialNormalMap(const Material* material) -{ - std::vector<MaterialTextureDef*> potentialTextureDefs; +GfxImage *AssetDumperXModel::GetMaterialNormalMap(const Material *material) { + std::vector<MaterialTextureDef *> potentialTextureDefs; - for (auto textureIndex = 0u; textureIndex < material->textureCount; textureIndex++) - { - MaterialTextureDef* def = &material->textureTable[textureIndex]; + for (auto textureIndex = 0u; textureIndex < material->textureCount; textureIndex++) { + MaterialTextureDef *def = &material->textureTable[textureIndex]; - if (def->semantic == TS_NORMAL_MAP) - potentialTextureDefs.push_back(def); - } + if (def->semantic == TS_NORMAL_MAP) + potentialTextureDefs.push_back(def); + } - if (potentialTextureDefs.empty()) - return nullptr; - if (potentialTextureDefs.size() == 1) - return potentialTextureDefs[0]->u.image; + if (potentialTextureDefs.empty()) + return nullptr; + if (potentialTextureDefs.size() == 1) + return potentialTextureDefs[0]->u.image; - for (const auto* def : potentialTextureDefs) - { - if (def->nameStart == 'n' && def->nameEnd == 'p') - return def->u.image; - } + for (const auto *def : potentialTextureDefs) { + if (def->nameStart == 'n' && def->nameEnd == 'p') + return def->u.image; + } - return potentialTextureDefs[0]->u.image; + return potentialTextureDefs[0]->u.image; } -GfxImage* AssetDumperXModel::GetMaterialSpecularMap(const Material* material) -{ - std::vector<MaterialTextureDef*> potentialTextureDefs; +GfxImage *AssetDumperXModel::GetMaterialSpecularMap(const Material *material) { + std::vector<MaterialTextureDef *> potentialTextureDefs; - for (auto textureIndex = 0u; textureIndex < material->textureCount; textureIndex++) - { - MaterialTextureDef* def = &material->textureTable[textureIndex]; + for (auto textureIndex = 0u; textureIndex < material->textureCount; textureIndex++) { + MaterialTextureDef *def = &material->textureTable[textureIndex]; - if (def->semantic == TS_SPECULAR_MAP) - potentialTextureDefs.push_back(def); - } + if (def->semantic == TS_SPECULAR_MAP) + potentialTextureDefs.push_back(def); + } - if (potentialTextureDefs.empty()) - return nullptr; - if (potentialTextureDefs.size() == 1) - return potentialTextureDefs[0]->u.image; + if (potentialTextureDefs.empty()) + return nullptr; + if (potentialTextureDefs.size() == 1) + return potentialTextureDefs[0]->u.image; - for (const auto* def : potentialTextureDefs) - { - if (def->nameStart == 's' && def->nameEnd == 'p') - return def->u.image; - } + for (const auto *def : potentialTextureDefs) { + if (def->nameStart == 's' && def->nameEnd == 'p') + return def->u.image; + } - return potentialTextureDefs[0]->u.image; + return potentialTextureDefs[0]->u.image; } -void AssetDumperXModel::AddObjMaterials(ObjWriter& writer, DistinctMapper<Material*>& materialMapper, const XModel* model) -{ - if (!model->materialHandles) - return; - - for (auto surfIndex = 0u; surfIndex < model->numsurfs; surfIndex++) - { - Material* material = model->materialHandles[surfIndex]; - if (!materialMapper.Add(material)) - continue; - - MtlMaterial mtl; - mtl.materialName = std::string(material->info.name); - GfxImage* colorMap = GetMaterialColorMap(material); - GfxImage* normalMap = GetMaterialNormalMap(material); - GfxImage* specularMap = GetMaterialSpecularMap(material); - - if (colorMap != nullptr) - mtl.colorMapName = colorMap->name; - if (normalMap != nullptr) - mtl.normalMapName = normalMap->name; - if (specularMap != nullptr) - mtl.specularMapName = specularMap->name; - - writer.AddMaterial(std::move(mtl)); - } +void AssetDumperXModel::AddObjMaterials(ObjWriter &writer, DistinctMapper<Material *> &materialMapper, const XModel *model) { + if (!model->materialHandles) + return; + + for (auto surfIndex = 0u; surfIndex < model->numsurfs; surfIndex++) { + Material *material = model->materialHandles[surfIndex]; + if (!materialMapper.Add(material)) + continue; + + MtlMaterial mtl; + mtl.materialName = std::string(material->info.name); + GfxImage *colorMap = GetMaterialColorMap(material); + GfxImage *normalMap = GetMaterialNormalMap(material); + GfxImage *specularMap = GetMaterialSpecularMap(material); + + if (colorMap != nullptr) + mtl.colorMapName = colorMap->name; + if (normalMap != nullptr) + mtl.normalMapName = normalMap->name; + if (specularMap != nullptr) + mtl.specularMapName = specularMap->name; + + writer.AddMaterial(std::move(mtl)); + } } -void AssetDumperXModel::AddObjObjects(ObjWriter& writer, const DistinctMapper<Material*>& materialMapper, const XModelSurfs* modelSurfs, int baseSurfaceIndex) -{ - for (auto surfIndex = 0u; surfIndex < modelSurfs->numsurfs; surfIndex++) - { - ObjObject object; - object.name = "surf" + std::to_string(surfIndex); - object.materialIndex = static_cast<int>(materialMapper.GetDistinctPositionByInputPosition(surfIndex + baseSurfaceIndex)); +void AssetDumperXModel::AddObjObjects(ObjWriter &writer, const DistinctMapper<Material *> &materialMapper, const XModelSurfs *modelSurfs, + int baseSurfaceIndex) { + for (auto surfIndex = 0u; surfIndex < modelSurfs->numsurfs; surfIndex++) { + ObjObject object; + object.name = "surf" + std::to_string(surfIndex); + object.materialIndex = static_cast<int>(materialMapper.GetDistinctPositionByInputPosition(surfIndex + baseSurfaceIndex)); - writer.AddObject(std::move(object)); - } + writer.AddObject(std::move(object)); + } } -void AssetDumperXModel::AddObjVertices(ObjWriter& writer, const XModelSurfs* modelSurfs) -{ - for (auto surfIndex = 0u; surfIndex < modelSurfs->numsurfs; surfIndex++) - { - const auto& surface = modelSurfs->surfs[surfIndex]; - - for (auto vertexIndex = 0u; vertexIndex < surface.vertCount; vertexIndex++) - { - const auto& v = surface.verts0.packedVerts0[vertexIndex]; - vec2_t uv; - vec3_t normalVec; - - Common::Vec2UnpackTexCoords(v.texCoord, &uv); - Common::Vec3UnpackUnitVec(v.normal, &normalVec); - - ObjVertex objVertex{}; - ObjNormal objNormal{}; - ObjUv objUv{}; - objVertex.coordinates[0] = v.xyz[0]; - objVertex.coordinates[1] = v.xyz[2]; - objVertex.coordinates[2] = -v.xyz[1]; - objNormal.normal[0] = normalVec[0]; - objNormal.normal[1] = normalVec[2]; - objNormal.normal[2] = -normalVec[1]; - objUv.uv[0] = uv[0]; - objUv.uv[1] = 1.0f - uv[1]; - - writer.AddVertex(static_cast<int>(surfIndex), objVertex); - writer.AddNormal(static_cast<int>(surfIndex), objNormal); - writer.AddUv(static_cast<int>(surfIndex), objUv); - } +void AssetDumperXModel::AddObjVertices(ObjWriter &writer, const XModelSurfs *modelSurfs) { + for (auto surfIndex = 0u; surfIndex < modelSurfs->numsurfs; surfIndex++) { + const auto &surface = modelSurfs->surfs[surfIndex]; + + for (auto vertexIndex = 0u; vertexIndex < surface.vertCount; vertexIndex++) { + const auto &v = surface.verts0.packedVerts0[vertexIndex]; + vec2_t uv; + vec3_t normalVec; + + Common::Vec2UnpackTexCoords(v.texCoord, &uv); + Common::Vec3UnpackUnitVec(v.normal, &normalVec); + + ObjVertex objVertex{}; + ObjNormal objNormal{}; + ObjUv objUv{}; + objVertex.coordinates[0] = v.xyz[0]; + objVertex.coordinates[1] = v.xyz[2]; + objVertex.coordinates[2] = -v.xyz[1]; + objNormal.normal[0] = normalVec[0]; + objNormal.normal[1] = normalVec[2]; + objNormal.normal[2] = -normalVec[1]; + objUv.uv[0] = uv[0]; + objUv.uv[1] = 1.0f - uv[1]; + + writer.AddVertex(static_cast<int>(surfIndex), objVertex); + writer.AddNormal(static_cast<int>(surfIndex), objNormal); + writer.AddUv(static_cast<int>(surfIndex), objUv); } + } } -void AssetDumperXModel::AddObjFaces(ObjWriter& writer, const XModelSurfs* modelSurfs) -{ - for (auto surfIndex = 0u; surfIndex < modelSurfs->numsurfs; surfIndex++) - { - const auto& surface = modelSurfs->surfs[surfIndex]; - for (auto triIndex = 0u; triIndex < surface.triCount; triIndex++) - { - const auto& tri = surface.triIndices[triIndex]; - - ObjFace face{}; - face.vertexIndex[0] = tri[2] + surface.baseVertIndex; - face.vertexIndex[1] = tri[1] + surface.baseVertIndex; - face.vertexIndex[2] = tri[0] + surface.baseVertIndex; - face.normalIndex[0] = face.vertexIndex[0]; - face.normalIndex[1] = face.vertexIndex[1]; - face.normalIndex[2] = face.vertexIndex[2]; - face.uvIndex[0] = face.vertexIndex[0]; - face.uvIndex[1] = face.vertexIndex[1]; - face.uvIndex[2] = face.vertexIndex[2]; - writer.AddFace(static_cast<int>(surfIndex), face); - } +void AssetDumperXModel::AddObjFaces(ObjWriter &writer, const XModelSurfs *modelSurfs) { + for (auto surfIndex = 0u; surfIndex < modelSurfs->numsurfs; surfIndex++) { + const auto &surface = modelSurfs->surfs[surfIndex]; + for (auto triIndex = 0u; triIndex < surface.triCount; triIndex++) { + const auto &tri = surface.triIndices[triIndex]; + + ObjFace face{}; + face.vertexIndex[0] = tri[2] + surface.baseVertIndex; + face.vertexIndex[1] = tri[1] + surface.baseVertIndex; + face.vertexIndex[2] = tri[0] + surface.baseVertIndex; + face.normalIndex[0] = face.vertexIndex[0]; + face.normalIndex[1] = face.vertexIndex[1]; + face.normalIndex[2] = face.vertexIndex[2]; + face.uvIndex[0] = face.vertexIndex[0]; + face.uvIndex[1] = face.vertexIndex[1]; + face.uvIndex[2] = face.vertexIndex[2]; + writer.AddFace(static_cast<int>(surfIndex), face); } + } } -void AssetDumperXModel::DumpObjMat(const AssetDumpingContext& context, XAssetInfo<XModel>* asset) -{ - const auto* model = asset->Asset(); - const auto matFile = context.OpenAssetFile("model_export/" + std::string(model->name) + ".mtl"); +void AssetDumperXModel::DumpObjMat(const AssetDumpingContext &context, XAssetInfo<XModel> *asset) { + const auto *model = asset->Asset(); + const auto matFile = context.OpenAssetFile("model_export/" + std::string(model->name) + ".mtl"); - if (!matFile) - return; + if (!matFile) + return; - ObjWriter writer(context.m_zone->m_game->GetShortName(), context.m_zone->m_name); - DistinctMapper<Material*> materialMapper(model->numsurfs); + ObjWriter writer(context.m_zone->m_game->GetShortName(), context.m_zone->m_name); + DistinctMapper<Material *> materialMapper(model->numsurfs); - AddObjMaterials(writer, materialMapper, model); - writer.WriteMtl(*matFile); + AddObjMaterials(writer, materialMapper, model); + writer.WriteMtl(*matFile); } -void AssetDumperXModel::DumpObjLod(const AssetDumpingContext& context, XAssetInfo<XModel>* asset, const unsigned lod) -{ - const auto* model = asset->Asset(); - const auto* modelSurfs = model->lodInfo[lod].modelSurfs; +void AssetDumperXModel::DumpObjLod(const AssetDumpingContext &context, XAssetInfo<XModel> *asset, const unsigned lod) { + const auto *model = asset->Asset(); + const auto *modelSurfs = model->lodInfo[lod].modelSurfs; - if (modelSurfs->name[0] == ',' || modelSurfs->surfs == nullptr) - return; + if (modelSurfs->name[0] == ',' || modelSurfs->surfs == nullptr) + return; - const auto assetFile = context.OpenAssetFile("model_export/" + std::string(modelSurfs->name) + ".obj"); + const auto assetFile = context.OpenAssetFile("model_export/" + std::string(modelSurfs->name) + ".obj"); - if (!assetFile) - return; + if (!assetFile) + return; - ObjWriter writer(context.m_zone->m_game->GetShortName(), context.m_zone->m_name); - DistinctMapper<Material*> materialMapper(model->numsurfs); + ObjWriter writer(context.m_zone->m_game->GetShortName(), context.m_zone->m_name); + DistinctMapper<Material *> materialMapper(model->numsurfs); - AddObjMaterials(writer, materialMapper, model); - AddObjObjects(writer, materialMapper, modelSurfs, model->lodInfo[lod].surfIndex); - AddObjVertices(writer, modelSurfs); - AddObjFaces(writer, modelSurfs); + AddObjMaterials(writer, materialMapper, model); + AddObjObjects(writer, materialMapper, modelSurfs, model->lodInfo[lod].surfIndex); + AddObjVertices(writer, modelSurfs); + AddObjFaces(writer, modelSurfs); - writer.WriteObj(*assetFile, std::string(model->name) + ".mtl"); + writer.WriteObj(*assetFile, std::string(model->name) + ".mtl"); } -void AssetDumperXModel::DumpObj(AssetDumpingContext& context, XAssetInfo<XModel>* asset) -{ - const auto* model = asset->Asset(); - auto* surfZoneState = context.GetZoneAssetDumperState<SurfsDumpingZoneState>(); +void AssetDumperXModel::DumpObj(AssetDumpingContext &context, XAssetInfo<XModel> *asset) { + const auto *model = asset->Asset(); + auto *surfZoneState = context.GetZoneAssetDumperState<SurfsDumpingZoneState>(); - DumpObjMat(context, asset); - for (auto currentLod = 0u; currentLod < model->numLods; currentLod++) - { - if (!model->lodInfo[currentLod].modelSurfs || !surfZoneState->ShouldDumpTechnique(model->lodInfo[currentLod].modelSurfs)) - continue; + DumpObjMat(context, asset); + for (auto currentLod = 0u; currentLod < model->numLods; currentLod++) { + if (!model->lodInfo[currentLod].modelSurfs || !surfZoneState->ShouldDumpTechnique(model->lodInfo[currentLod].modelSurfs)) + continue; - DumpObjLod(context, asset, currentLod); - } + DumpObjLod(context, asset, currentLod); + } } -void AssetDumperXModel::AddXModelBones(const AssetDumpingContext& context, AbstractXModelWriter& writer, const XModel* model) -{ - for (auto boneNum = 0u; boneNum < model->numBones; boneNum++) - { - XModelBone bone; - if (model->boneNames[boneNum] < context.m_zone->m_script_strings.Count()) - bone.name = context.m_zone->m_script_strings[model->boneNames[boneNum]]; - else - bone.name = "INVALID_BONE_NAME"; - - if (boneNum < model->numRootBones) - bone.parentIndex = -1; - else - bone.parentIndex = static_cast<int>(boneNum - static_cast<unsigned int>(model->parentList[boneNum - model->numRootBones])); - - bone.scale[0] = 1.0f; - bone.scale[1] = 1.0f; - bone.scale[2] = 1.0f; - - bone.globalOffset[0] = model->baseMat[boneNum].trans[0]; - bone.globalOffset[1] = model->baseMat[boneNum].trans[1]; - bone.globalOffset[2] = model->baseMat[boneNum].trans[2]; - bone.globalRotation = Quaternion32(model->baseMat[boneNum].quat[0], model->baseMat[boneNum].quat[1], model->baseMat[boneNum].quat[2], model->baseMat[boneNum].quat[3]); - - if (boneNum < model->numRootBones) - { - bone.localOffset[0] = 0; - bone.localOffset[1] = 0; - bone.localOffset[2] = 0; - bone.localRotation = Quaternion32(0, 0, 0, 1); - } - else - { - bone.localOffset[0] = model->trans[boneNum - model->numRootBones][0]; - bone.localOffset[1] = model->trans[boneNum - model->numRootBones][1]; - bone.localOffset[2] = model->trans[boneNum - model->numRootBones][2]; - bone.localRotation = Quaternion32( - QuatInt16::ToFloat(model->quats[boneNum - model->numRootBones][0]), - QuatInt16::ToFloat(model->quats[boneNum - model->numRootBones][1]), - QuatInt16::ToFloat(model->quats[boneNum - model->numRootBones][2]), - QuatInt16::ToFloat(model->quats[boneNum - model->numRootBones][3]) - ); - } - - writer.AddBone(std::move(bone)); +void AssetDumperXModel::AddXModelBones(const AssetDumpingContext &context, AbstractXModelWriter &writer, const XModel *model) { + for (auto boneNum = 0u; boneNum < model->numBones; boneNum++) { + XModelBone bone; + if (model->boneNames[boneNum] < context.m_zone->m_script_strings.Count()) + bone.name = context.m_zone->m_script_strings[model->boneNames[boneNum]]; + else + bone.name = "INVALID_BONE_NAME"; + + if (boneNum < model->numRootBones) + bone.parentIndex = -1; + else + bone.parentIndex = static_cast<int>(boneNum - static_cast<unsigned int>(model->parentList[boneNum - model->numRootBones])); + + bone.scale[0] = 1.0f; + bone.scale[1] = 1.0f; + bone.scale[2] = 1.0f; + + bone.globalOffset[0] = model->baseMat[boneNum].trans[0]; + bone.globalOffset[1] = model->baseMat[boneNum].trans[1]; + bone.globalOffset[2] = model->baseMat[boneNum].trans[2]; + bone.globalRotation = + Quaternion32(model->baseMat[boneNum].quat[0], model->baseMat[boneNum].quat[1], model->baseMat[boneNum].quat[2], model->baseMat[boneNum].quat[3]); + + if (boneNum < model->numRootBones) { + bone.localOffset[0] = 0; + bone.localOffset[1] = 0; + bone.localOffset[2] = 0; + bone.localRotation = Quaternion32(0, 0, 0, 1); + } else { + bone.localOffset[0] = model->trans[boneNum - model->numRootBones][0]; + bone.localOffset[1] = model->trans[boneNum - model->numRootBones][1]; + bone.localOffset[2] = model->trans[boneNum - model->numRootBones][2]; + bone.localRotation = + Quaternion32(QuatInt16::ToFloat(model->quats[boneNum - model->numRootBones][0]), QuatInt16::ToFloat(model->quats[boneNum - model->numRootBones][1]), + QuatInt16::ToFloat(model->quats[boneNum - model->numRootBones][2]), QuatInt16::ToFloat(model->quats[boneNum - model->numRootBones][3])); } + + writer.AddBone(std::move(bone)); + } } -void AssetDumperXModel::AddXModelMaterials(AbstractXModelWriter& writer, DistinctMapper<Material*>& materialMapper, const XModel* model) -{ - for (auto surfaceMaterialNum = 0; surfaceMaterialNum < model->numsurfs; surfaceMaterialNum++) - { - Material* material = model->materialHandles[surfaceMaterialNum]; - if (materialMapper.Add(material)) - { - XModelMaterial xMaterial; - xMaterial.ApplyDefaults(); - - xMaterial.name = material->info.name; - const auto* colorMap = GetMaterialColorMap(material); - if (colorMap) - xMaterial.colorMapName = std::string(colorMap->name); - - writer.AddMaterial(std::move(xMaterial)); - } +void AssetDumperXModel::AddXModelMaterials(AbstractXModelWriter &writer, DistinctMapper<Material *> &materialMapper, const XModel *model) { + for (auto surfaceMaterialNum = 0; surfaceMaterialNum < model->numsurfs; surfaceMaterialNum++) { + Material *material = model->materialHandles[surfaceMaterialNum]; + if (materialMapper.Add(material)) { + XModelMaterial xMaterial; + xMaterial.ApplyDefaults(); + + xMaterial.name = material->info.name; + const auto *colorMap = GetMaterialColorMap(material); + if (colorMap) + xMaterial.colorMapName = std::string(colorMap->name); + + writer.AddMaterial(std::move(xMaterial)); } + } } -void AssetDumperXModel::AddXModelObjects(AbstractXModelWriter& writer, const XModelSurfs* modelSurfs) -{ - for (auto surfIndex = 0u; surfIndex < modelSurfs->numsurfs; surfIndex++) - { - XModelObject object; - object.name = "surf" + std::to_string(surfIndex); +void AssetDumperXModel::AddXModelObjects(AbstractXModelWriter &writer, const XModelSurfs *modelSurfs) { + for (auto surfIndex = 0u; surfIndex < modelSurfs->numsurfs; surfIndex++) { + XModelObject object; + object.name = "surf" + std::to_string(surfIndex); - writer.AddObject(std::move(object)); - } + writer.AddObject(std::move(object)); + } } -void AssetDumperXModel::AddXModelVertices(AbstractXModelWriter& writer, const XModelSurfs* modelSurfs) -{ - for (auto surfIndex = 0u; surfIndex < modelSurfs->numsurfs; surfIndex++) - { - const auto& surface = modelSurfs->surfs[surfIndex]; - - for (auto vertexIndex = 0u; vertexIndex < surface.vertCount; vertexIndex++) - { - const auto& v = surface.verts0.packedVerts0[vertexIndex]; - vec2_t uv; - vec3_t normalVec; - vec4_t color; - - Common::Vec2UnpackTexCoords(v.texCoord, &uv); - Common::Vec3UnpackUnitVec(v.normal, &normalVec); - Common::Vec4UnpackGfxColor(v.color, &color); - - XModelVertex vertex{}; - vertex.coordinates[0] = v.xyz[0]; - vertex.coordinates[1] = v.xyz[1]; - vertex.coordinates[2] = v.xyz[2]; - vertex.normal[0] = normalVec[0]; - vertex.normal[1] = normalVec[1]; - vertex.normal[2] = normalVec[2]; - vertex.color[0] = color[0]; - vertex.color[1] = color[1]; - vertex.color[2] = color[2]; - vertex.color[3] = color[3]; - vertex.uv[0] = uv[0]; - vertex.uv[1] = uv[1]; - - writer.AddVertex(vertex); - } +void AssetDumperXModel::AddXModelVertices(AbstractXModelWriter &writer, const XModelSurfs *modelSurfs) { + for (auto surfIndex = 0u; surfIndex < modelSurfs->numsurfs; surfIndex++) { + const auto &surface = modelSurfs->surfs[surfIndex]; + + for (auto vertexIndex = 0u; vertexIndex < surface.vertCount; vertexIndex++) { + const auto &v = surface.verts0.packedVerts0[vertexIndex]; + vec2_t uv; + vec3_t normalVec; + vec4_t color; + + Common::Vec2UnpackTexCoords(v.texCoord, &uv); + Common::Vec3UnpackUnitVec(v.normal, &normalVec); + Common::Vec4UnpackGfxColor(v.color, &color); + + XModelVertex vertex{}; + vertex.coordinates[0] = v.xyz[0]; + vertex.coordinates[1] = v.xyz[1]; + vertex.coordinates[2] = v.xyz[2]; + vertex.normal[0] = normalVec[0]; + vertex.normal[1] = normalVec[1]; + vertex.normal[2] = normalVec[2]; + vertex.color[0] = color[0]; + vertex.color[1] = color[1]; + vertex.color[2] = color[2]; + vertex.color[3] = color[3]; + vertex.uv[0] = uv[0]; + vertex.uv[1] = uv[1]; + + writer.AddVertex(vertex); } + } } -void AssetDumperXModel::AllocateXModelBoneWeights(const XModelSurfs* modelSurfs, XModelVertexBoneWeightCollection& weightCollection) -{ - weightCollection.totalWeightCount = 0u; - for (auto surfIndex = 0u; surfIndex < modelSurfs->numsurfs; surfIndex++) - { - const auto& surface = modelSurfs->surfs[surfIndex]; +void AssetDumperXModel::AllocateXModelBoneWeights(const XModelSurfs *modelSurfs, XModelVertexBoneWeightCollection &weightCollection) { + weightCollection.totalWeightCount = 0u; + for (auto surfIndex = 0u; surfIndex < modelSurfs->numsurfs; surfIndex++) { + const auto &surface = modelSurfs->surfs[surfIndex]; - if (surface.vertList) - { - weightCollection.totalWeightCount += surface.vertListCount; - } + if (surface.vertList) { + weightCollection.totalWeightCount += surface.vertListCount; + } - if (surface.vertInfo.vertsBlend) - { - weightCollection.totalWeightCount += surface.vertInfo.vertCount[0] * 1; - weightCollection.totalWeightCount += surface.vertInfo.vertCount[1] * 2; - weightCollection.totalWeightCount += surface.vertInfo.vertCount[2] * 3; - weightCollection.totalWeightCount += surface.vertInfo.vertCount[3] * 4; - } + if (surface.vertInfo.vertsBlend) { + weightCollection.totalWeightCount += surface.vertInfo.vertCount[0] * 1; + weightCollection.totalWeightCount += surface.vertInfo.vertCount[1] * 2; + weightCollection.totalWeightCount += surface.vertInfo.vertCount[2] * 3; + weightCollection.totalWeightCount += surface.vertInfo.vertCount[3] * 4; } + } - weightCollection.weights = std::make_unique<XModelBoneWeight[]>(weightCollection.totalWeightCount); + weightCollection.weights = std::make_unique<XModelBoneWeight[]>(weightCollection.totalWeightCount); } -void AssetDumperXModel::AddXModelVertexBoneWeights(AbstractXModelWriter& writer, const XModelSurfs* modelSurfs, XModelVertexBoneWeightCollection& weightCollection) -{ - size_t weightOffset = 0u; - - for (auto surfIndex = 0u; surfIndex < modelSurfs->numsurfs; surfIndex++) - { - const auto& surface = modelSurfs->surfs[surfIndex]; - auto handledVertices = 0u; - - if (surface.vertList) - { - for (auto vertListIndex = 0u; vertListIndex < surface.vertListCount; vertListIndex++) - { - const auto& vertList = surface.vertList[vertListIndex]; - const auto* boneWeightOffset = &weightCollection.weights[weightOffset]; - - weightCollection.weights[weightOffset++] = XModelBoneWeight{ - static_cast<int>(vertList.boneOffset / sizeof(DObjSkelMat)), - 1.0f - }; - - for (auto vertListVertexOffset = 0u; vertListVertexOffset < vertList.vertCount; vertListVertexOffset++) - { - writer.AddVertexBoneWeights(XModelVertexBoneWeights{ - boneWeightOffset, - 1 - }); - } - handledVertices += vertList.vertCount; - } - } +void AssetDumperXModel::AddXModelVertexBoneWeights(AbstractXModelWriter &writer, const XModelSurfs *modelSurfs, + XModelVertexBoneWeightCollection &weightCollection) { + size_t weightOffset = 0u; - auto vertsBlendOffset = 0u; - if (surface.vertInfo.vertsBlend) - { - // 1 bone weight - for (auto vertIndex = 0; vertIndex < surface.vertInfo.vertCount[0]; vertIndex++) - { - const auto* boneWeightOffset = &weightCollection.weights[weightOffset]; - const auto boneIndex0 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 0] / sizeof(DObjSkelMat)); - weightCollection.weights[weightOffset++] = XModelBoneWeight{ - boneIndex0, - 1.0f - }; - - vertsBlendOffset += 1; - - writer.AddVertexBoneWeights(XModelVertexBoneWeights{ - boneWeightOffset, - 1 - }); - } - - // 2 bone weights - for (auto vertIndex = 0; vertIndex < surface.vertInfo.vertCount[1]; vertIndex++) - { - const auto* boneWeightOffset = &weightCollection.weights[weightOffset]; - const auto boneIndex0 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 0] / sizeof(DObjSkelMat)); - const auto boneIndex1 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 1] / sizeof(DObjSkelMat)); - const auto boneWeight1 = HalfFloat::ToFloat(surface.vertInfo.vertsBlend[vertsBlendOffset + 2]); - const auto boneWeight0 = 1.0f - boneWeight1; - - weightCollection.weights[weightOffset++] = XModelBoneWeight{ - boneIndex0, - boneWeight0 - }; - weightCollection.weights[weightOffset++] = XModelBoneWeight{ - boneIndex1, - boneWeight1 - }; - - vertsBlendOffset += 3; - - writer.AddVertexBoneWeights(XModelVertexBoneWeights{ - boneWeightOffset, - 2 - }); - } - - // 3 bone weights - for (auto vertIndex = 0; vertIndex < surface.vertInfo.vertCount[2]; vertIndex++) - { - const auto* boneWeightOffset = &weightCollection.weights[weightOffset]; - const auto boneIndex0 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 0] / sizeof(DObjSkelMat)); - const auto boneIndex1 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 1] / sizeof(DObjSkelMat)); - const auto boneWeight1 = HalfFloat::ToFloat(surface.vertInfo.vertsBlend[vertsBlendOffset + 2]); - const auto boneIndex2 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 3] / sizeof(DObjSkelMat)); - const auto boneWeight2 = HalfFloat::ToFloat(surface.vertInfo.vertsBlend[vertsBlendOffset + 4]); - const auto boneWeight0 = 1.0f - boneWeight1 - boneWeight2; - - weightCollection.weights[weightOffset++] = XModelBoneWeight{ - boneIndex0, - boneWeight0 - }; - weightCollection.weights[weightOffset++] = XModelBoneWeight{ - boneIndex1, - boneWeight1 - }; - weightCollection.weights[weightOffset++] = XModelBoneWeight{ - boneIndex2, - boneWeight2 - }; - - vertsBlendOffset += 5; - - writer.AddVertexBoneWeights(XModelVertexBoneWeights{ - boneWeightOffset, - 3 - }); - } - - // 4 bone weights - for (auto vertIndex = 0; vertIndex < surface.vertInfo.vertCount[3]; vertIndex++) - { - const auto* boneWeightOffset = &weightCollection.weights[weightOffset]; - const auto boneIndex0 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 0] / sizeof(DObjSkelMat)); - const auto boneIndex1 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 1] / sizeof(DObjSkelMat)); - const auto boneWeight1 = HalfFloat::ToFloat(surface.vertInfo.vertsBlend[vertsBlendOffset + 2]); - const auto boneIndex2 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 3] / sizeof(DObjSkelMat)); - const auto boneWeight2 = HalfFloat::ToFloat(surface.vertInfo.vertsBlend[vertsBlendOffset + 4]); - const auto boneIndex3 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 5] / sizeof(DObjSkelMat)); - const auto boneWeight3 = HalfFloat::ToFloat(surface.vertInfo.vertsBlend[vertsBlendOffset + 6]); - const auto boneWeight0 = 1.0f - boneWeight1 - boneWeight2 - boneWeight3; - - weightCollection.weights[weightOffset++] = XModelBoneWeight{ - boneIndex0, - boneWeight0 - }; - weightCollection.weights[weightOffset++] = XModelBoneWeight{ - boneIndex1, - boneWeight1 - }; - weightCollection.weights[weightOffset++] = XModelBoneWeight{ - boneIndex2, - boneWeight2 - }; - weightCollection.weights[weightOffset++] = XModelBoneWeight{ - boneIndex3, - boneWeight3 - }; - - vertsBlendOffset += 7; - - writer.AddVertexBoneWeights(XModelVertexBoneWeights{ - boneWeightOffset, - 4 - }); - } - - handledVertices += surface.vertInfo.vertCount[0] + surface.vertInfo.vertCount[1] + surface.vertInfo.vertCount[2] + surface.vertInfo.vertCount[3]; - } + for (auto surfIndex = 0u; surfIndex < modelSurfs->numsurfs; surfIndex++) { + const auto &surface = modelSurfs->surfs[surfIndex]; + auto handledVertices = 0u; - for (; handledVertices < surface.vertCount; handledVertices++) - { - writer.AddVertexBoneWeights(XModelVertexBoneWeights{ - nullptr, - 0 - }); + if (surface.vertList) { + for (auto vertListIndex = 0u; vertListIndex < surface.vertListCount; vertListIndex++) { + const auto &vertList = surface.vertList[vertListIndex]; + const auto *boneWeightOffset = &weightCollection.weights[weightOffset]; + + weightCollection.weights[weightOffset++] = XModelBoneWeight{static_cast<int>(vertList.boneOffset / sizeof(DObjSkelMat)), 1.0f}; + + for (auto vertListVertexOffset = 0u; vertListVertexOffset < vertList.vertCount; vertListVertexOffset++) { + writer.AddVertexBoneWeights(XModelVertexBoneWeights{boneWeightOffset, 1}); } + handledVertices += vertList.vertCount; + } + } + + auto vertsBlendOffset = 0u; + if (surface.vertInfo.vertsBlend) { + // 1 bone weight + for (auto vertIndex = 0; vertIndex < surface.vertInfo.vertCount[0]; vertIndex++) { + const auto *boneWeightOffset = &weightCollection.weights[weightOffset]; + const auto boneIndex0 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 0] / sizeof(DObjSkelMat)); + weightCollection.weights[weightOffset++] = XModelBoneWeight{boneIndex0, 1.0f}; + + vertsBlendOffset += 1; + + writer.AddVertexBoneWeights(XModelVertexBoneWeights{boneWeightOffset, 1}); + } + + // 2 bone weights + for (auto vertIndex = 0; vertIndex < surface.vertInfo.vertCount[1]; vertIndex++) { + const auto *boneWeightOffset = &weightCollection.weights[weightOffset]; + const auto boneIndex0 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 0] / sizeof(DObjSkelMat)); + const auto boneIndex1 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 1] / sizeof(DObjSkelMat)); + const auto boneWeight1 = HalfFloat::ToFloat(surface.vertInfo.vertsBlend[vertsBlendOffset + 2]); + const auto boneWeight0 = 1.0f - boneWeight1; + + weightCollection.weights[weightOffset++] = XModelBoneWeight{boneIndex0, boneWeight0}; + weightCollection.weights[weightOffset++] = XModelBoneWeight{boneIndex1, boneWeight1}; + + vertsBlendOffset += 3; + + writer.AddVertexBoneWeights(XModelVertexBoneWeights{boneWeightOffset, 2}); + } + + // 3 bone weights + for (auto vertIndex = 0; vertIndex < surface.vertInfo.vertCount[2]; vertIndex++) { + const auto *boneWeightOffset = &weightCollection.weights[weightOffset]; + const auto boneIndex0 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 0] / sizeof(DObjSkelMat)); + const auto boneIndex1 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 1] / sizeof(DObjSkelMat)); + const auto boneWeight1 = HalfFloat::ToFloat(surface.vertInfo.vertsBlend[vertsBlendOffset + 2]); + const auto boneIndex2 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 3] / sizeof(DObjSkelMat)); + const auto boneWeight2 = HalfFloat::ToFloat(surface.vertInfo.vertsBlend[vertsBlendOffset + 4]); + const auto boneWeight0 = 1.0f - boneWeight1 - boneWeight2; + + weightCollection.weights[weightOffset++] = XModelBoneWeight{boneIndex0, boneWeight0}; + weightCollection.weights[weightOffset++] = XModelBoneWeight{boneIndex1, boneWeight1}; + weightCollection.weights[weightOffset++] = XModelBoneWeight{boneIndex2, boneWeight2}; + + vertsBlendOffset += 5; + + writer.AddVertexBoneWeights(XModelVertexBoneWeights{boneWeightOffset, 3}); + } + + // 4 bone weights + for (auto vertIndex = 0; vertIndex < surface.vertInfo.vertCount[3]; vertIndex++) { + const auto *boneWeightOffset = &weightCollection.weights[weightOffset]; + const auto boneIndex0 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 0] / sizeof(DObjSkelMat)); + const auto boneIndex1 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 1] / sizeof(DObjSkelMat)); + const auto boneWeight1 = HalfFloat::ToFloat(surface.vertInfo.vertsBlend[vertsBlendOffset + 2]); + const auto boneIndex2 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 3] / sizeof(DObjSkelMat)); + const auto boneWeight2 = HalfFloat::ToFloat(surface.vertInfo.vertsBlend[vertsBlendOffset + 4]); + const auto boneIndex3 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 5] / sizeof(DObjSkelMat)); + const auto boneWeight3 = HalfFloat::ToFloat(surface.vertInfo.vertsBlend[vertsBlendOffset + 6]); + const auto boneWeight0 = 1.0f - boneWeight1 - boneWeight2 - boneWeight3; + + weightCollection.weights[weightOffset++] = XModelBoneWeight{boneIndex0, boneWeight0}; + weightCollection.weights[weightOffset++] = XModelBoneWeight{boneIndex1, boneWeight1}; + weightCollection.weights[weightOffset++] = XModelBoneWeight{boneIndex2, boneWeight2}; + weightCollection.weights[weightOffset++] = XModelBoneWeight{boneIndex3, boneWeight3}; + + vertsBlendOffset += 7; + + writer.AddVertexBoneWeights(XModelVertexBoneWeights{boneWeightOffset, 4}); + } + + handledVertices += surface.vertInfo.vertCount[0] + surface.vertInfo.vertCount[1] + surface.vertInfo.vertCount[2] + surface.vertInfo.vertCount[3]; + } + + for (; handledVertices < surface.vertCount; handledVertices++) { + writer.AddVertexBoneWeights(XModelVertexBoneWeights{nullptr, 0}); } + } } -void AssetDumperXModel::AddXModelFaces(AbstractXModelWriter& writer, const DistinctMapper<Material*>& materialMapper, const XModelSurfs* modelSurfs, - const int baseSurfaceIndex) -{ - for (auto surfIndex = 0u; surfIndex < modelSurfs->numsurfs; surfIndex++) - { - const auto& surface = modelSurfs->surfs[surfIndex]; - for (auto triIndex = 0u; triIndex < surface.triCount; triIndex++) - { - const auto& tri = surface.triIndices[triIndex]; - - XModelFace face{}; - face.vertexIndex[0] = tri[0] + surface.baseVertIndex; - face.vertexIndex[1] = tri[1] + surface.baseVertIndex; - face.vertexIndex[2] = tri[2] + surface.baseVertIndex; - face.objectIndex = static_cast<int>(surfIndex); - face.materialIndex = static_cast<int>(materialMapper.GetDistinctPositionByInputPosition(surfIndex + baseSurfaceIndex)); - writer.AddFace(face); - } +void AssetDumperXModel::AddXModelFaces(AbstractXModelWriter &writer, const DistinctMapper<Material *> &materialMapper, const XModelSurfs *modelSurfs, + const int baseSurfaceIndex) { + for (auto surfIndex = 0u; surfIndex < modelSurfs->numsurfs; surfIndex++) { + const auto &surface = modelSurfs->surfs[surfIndex]; + for (auto triIndex = 0u; triIndex < surface.triCount; triIndex++) { + const auto &tri = surface.triIndices[triIndex]; + + XModelFace face{}; + face.vertexIndex[0] = tri[0] + surface.baseVertIndex; + face.vertexIndex[1] = tri[1] + surface.baseVertIndex; + face.vertexIndex[2] = tri[2] + surface.baseVertIndex; + face.objectIndex = static_cast<int>(surfIndex); + face.materialIndex = static_cast<int>(materialMapper.GetDistinctPositionByInputPosition(surfIndex + baseSurfaceIndex)); + writer.AddFace(face); } + } } -void AssetDumperXModel::DumpXModelExportLod(const AssetDumpingContext& context, XAssetInfo<XModel>* asset, const unsigned lod) -{ - const auto* model = asset->Asset(); - const auto* modelSurfs = model->lodInfo[lod].modelSurfs; +void AssetDumperXModel::DumpXModelExportLod(const AssetDumpingContext &context, XAssetInfo<XModel> *asset, const unsigned lod) { + const auto *model = asset->Asset(); + const auto *modelSurfs = model->lodInfo[lod].modelSurfs; - if (modelSurfs->name[0] == ',' || modelSurfs->surfs == nullptr) - return; + if (modelSurfs->name[0] == ',' || modelSurfs->surfs == nullptr) + return; - const auto assetFile = context.OpenAssetFile("model_export/" + std::string(modelSurfs->name) + ".XMODEL_EXPORT"); + const auto assetFile = context.OpenAssetFile("model_export/" + std::string(modelSurfs->name) + ".XMODEL_EXPORT"); - if (!assetFile) - return; + if (!assetFile) + return; - const auto writer = XModelExportWriter::CreateWriterForVersion6(context.m_zone->m_game->GetShortName(), context.m_zone->m_name); - DistinctMapper<Material*> materialMapper(model->numsurfs); - XModelVertexBoneWeightCollection boneWeightCollection; - AllocateXModelBoneWeights(modelSurfs, boneWeightCollection); + const auto writer = XModelExportWriter::CreateWriterForVersion6(context.m_zone->m_game->GetShortName(), context.m_zone->m_name); + DistinctMapper<Material *> materialMapper(model->numsurfs); + XModelVertexBoneWeightCollection boneWeightCollection; + AllocateXModelBoneWeights(modelSurfs, boneWeightCollection); - AddXModelBones(context, *writer, model); - AddXModelMaterials(*writer, materialMapper, model); - AddXModelObjects(*writer, modelSurfs); - AddXModelVertices(*writer, modelSurfs); - AddXModelVertexBoneWeights(*writer, modelSurfs, boneWeightCollection); - AddXModelFaces(*writer, materialMapper, modelSurfs, model->lodInfo[lod].surfIndex); + AddXModelBones(context, *writer, model); + AddXModelMaterials(*writer, materialMapper, model); + AddXModelObjects(*writer, modelSurfs); + AddXModelVertices(*writer, modelSurfs); + AddXModelVertexBoneWeights(*writer, modelSurfs, boneWeightCollection); + AddXModelFaces(*writer, materialMapper, modelSurfs, model->lodInfo[lod].surfIndex); - writer->Write(*assetFile); + writer->Write(*assetFile); } -void AssetDumperXModel::DumpXModelExport(AssetDumpingContext& context, XAssetInfo<XModel>* asset) -{ - auto* surfZoneState = context.GetZoneAssetDumperState<SurfsDumpingZoneState>(); - const auto* model = asset->Asset(); - for (auto currentLod = 0u; currentLod < model->numLods; currentLod++) - { - if (!model->lodInfo[currentLod].modelSurfs || !surfZoneState->ShouldDumpTechnique(model->lodInfo[currentLod].modelSurfs)) - continue; - DumpXModelExportLod(context, asset, currentLod); - } +void AssetDumperXModel::DumpXModelExport(AssetDumpingContext &context, XAssetInfo<XModel> *asset) { + auto *surfZoneState = context.GetZoneAssetDumperState<SurfsDumpingZoneState>(); + const auto *model = asset->Asset(); + for (auto currentLod = 0u; currentLod < model->numLods; currentLod++) { + if (!model->lodInfo[currentLod].modelSurfs || !surfZoneState->ShouldDumpTechnique(model->lodInfo[currentLod].modelSurfs)) + continue; + DumpXModelExportLod(context, asset, currentLod); + } } -void AssetDumperXModel::DumpAsset(AssetDumpingContext& context, XAssetInfo<XModel>* asset) -{ - switch (ObjWriting::Configuration.ModelOutputFormat) - { - case ObjWriting::Configuration_t::ModelOutputFormat_e::OBJ: - DumpObj(context, asset); - break; - - case ObjWriting::Configuration_t::ModelOutputFormat_e::XMODEL_EXPORT: - DumpXModelExport(context, asset); - break; - - default: - assert(false); - break; - } +void AssetDumperXModel::DumpAsset(AssetDumpingContext &context, XAssetInfo<XModel> *asset) { + switch (ObjWriting::Configuration.ModelOutputFormat) { + case ObjWriting::Configuration_t::ModelOutputFormat_e::OBJ: + DumpObj(context, asset); + break; + + case ObjWriting::Configuration_t::ModelOutputFormat_e::XMODEL_EXPORT: + DumpXModelExport(context, asset); + break; + + default: + assert(false); + break; + } } diff --git a/src/ObjWriting/Game/IW5/AssetDumpers/AssetDumperXModel.h b/src/ObjWriting/Game/IW5/AssetDumpers/AssetDumperXModel.h index 823c73870..046293078 100644 --- a/src/ObjWriting/Game/IW5/AssetDumpers/AssetDumperXModel.h +++ b/src/ObjWriting/Game/IW5/AssetDumpers/AssetDumperXModel.h @@ -2,38 +2,37 @@ #include "Dumping/AbstractAssetDumper.h" #include "Game/IW5/IW5.h" -#include "Utils/DistinctMapper.h" -#include "Model/XModel/AbstractXModelWriter.h" #include "Model/Obj/ObjWriter.h" +#include "Model/XModel/AbstractXModelWriter.h" +#include "Utils/DistinctMapper.h" -namespace IW5 -{ - class AssetDumperXModel final : public AbstractAssetDumper<XModel> - { - static GfxImage* GetMaterialColorMap(const Material* material); - static GfxImage* GetMaterialNormalMap(const Material* material); - static GfxImage* GetMaterialSpecularMap(const Material* material); +namespace IW5 { +class AssetDumperXModel final : public AbstractAssetDumper<XModel> { + static GfxImage *GetMaterialColorMap(const Material *material); + static GfxImage *GetMaterialNormalMap(const Material *material); + static GfxImage *GetMaterialSpecularMap(const Material *material); - static void AddObjMaterials(ObjWriter& writer, DistinctMapper<Material*>& materialMapper, const XModel* model); - static void AddObjObjects(ObjWriter& writer, const DistinctMapper<Material*>& materialMapper, const XModelSurfs* modelSurfs, int baseSurfaceIndex); - static void AddObjVertices(ObjWriter& writer, const XModelSurfs* modelSurfs); - static void AddObjFaces(ObjWriter& writer, const XModelSurfs* modelSurfs); - static void DumpObjLod(const AssetDumpingContext& context, XAssetInfo<XModel>* asset, const unsigned lod); - static void DumpObjMat(const AssetDumpingContext& context, XAssetInfo<XModel>* asset); - static void DumpObj(AssetDumpingContext& context, XAssetInfo<XModel>* asset); + static void AddObjMaterials(ObjWriter &writer, DistinctMapper<Material *> &materialMapper, const XModel *model); + static void AddObjObjects(ObjWriter &writer, const DistinctMapper<Material *> &materialMapper, const XModelSurfs *modelSurfs, int baseSurfaceIndex); + static void AddObjVertices(ObjWriter &writer, const XModelSurfs *modelSurfs); + static void AddObjFaces(ObjWriter &writer, const XModelSurfs *modelSurfs); + static void DumpObjLod(const AssetDumpingContext &context, XAssetInfo<XModel> *asset, const unsigned lod); + static void DumpObjMat(const AssetDumpingContext &context, XAssetInfo<XModel> *asset); + static void DumpObj(AssetDumpingContext &context, XAssetInfo<XModel> *asset); - static void AddXModelBones(const AssetDumpingContext& context, AbstractXModelWriter& writer, const XModel* model); - static void AddXModelMaterials(AbstractXModelWriter& writer, DistinctMapper<Material*>& materialMapper, const XModel* model); - static void AddXModelObjects(AbstractXModelWriter& writer, const XModelSurfs* modelSurfs); - static void AddXModelVertices(AbstractXModelWriter& writer, const XModelSurfs* modelSurfs); - static void AllocateXModelBoneWeights(const XModelSurfs* modelSurfs, XModelVertexBoneWeightCollection& weightCollection); - static void AddXModelVertexBoneWeights(AbstractXModelWriter& writer, const XModelSurfs* modelSurfs, XModelVertexBoneWeightCollection& weightCollection); - static void AddXModelFaces(AbstractXModelWriter& writer, const DistinctMapper<Material*>& materialMapper, const XModelSurfs* modelSurfs, int baseSurfaceIndex); - static void DumpXModelExportLod(const AssetDumpingContext& context, XAssetInfo<XModel>* asset, unsigned lod); - static void DumpXModelExport(AssetDumpingContext& context, XAssetInfo<XModel>* asset); + static void AddXModelBones(const AssetDumpingContext &context, AbstractXModelWriter &writer, const XModel *model); + static void AddXModelMaterials(AbstractXModelWriter &writer, DistinctMapper<Material *> &materialMapper, const XModel *model); + static void AddXModelObjects(AbstractXModelWriter &writer, const XModelSurfs *modelSurfs); + static void AddXModelVertices(AbstractXModelWriter &writer, const XModelSurfs *modelSurfs); + static void AllocateXModelBoneWeights(const XModelSurfs *modelSurfs, XModelVertexBoneWeightCollection &weightCollection); + static void AddXModelVertexBoneWeights(AbstractXModelWriter &writer, const XModelSurfs *modelSurfs, XModelVertexBoneWeightCollection &weightCollection); + static void AddXModelFaces(AbstractXModelWriter &writer, const DistinctMapper<Material *> &materialMapper, const XModelSurfs *modelSurfs, + int baseSurfaceIndex); + static void DumpXModelExportLod(const AssetDumpingContext &context, XAssetInfo<XModel> *asset, unsigned lod); + static void DumpXModelExport(AssetDumpingContext &context, XAssetInfo<XModel> *asset); - protected: - bool ShouldDump(XAssetInfo<XModel>* asset) override; - void DumpAsset(AssetDumpingContext& context, XAssetInfo<XModel>* asset) override; - }; -} +protected: + bool ShouldDump(XAssetInfo<XModel> *asset) override; + void DumpAsset(AssetDumpingContext &context, XAssetInfo<XModel> *asset) override; +}; +} // namespace IW5 diff --git a/src/ObjWriting/Game/IW5/InfoString/InfoStringFromStructConverter.cpp b/src/ObjWriting/Game/IW5/InfoString/InfoStringFromStructConverter.cpp index 33f30e255..f867f7ffb 100644 --- a/src/ObjWriting/Game/IW5/InfoString/InfoStringFromStructConverter.cpp +++ b/src/ObjWriting/Game/IW5/InfoString/InfoStringFromStructConverter.cpp @@ -4,144 +4,122 @@ using namespace IW5; -void InfoStringFromStructConverter::FillFromBaseField(const cspField_t& field) -{ - switch (static_cast<csParseFieldType_t>(field.iFieldType)) - { - case CSPFT_STRING: - FillFromString(std::string(field.szName), field.iOffset); - break; - - case CSPFT_STRING_MAX_STRING_CHARS: - FillFromStringBuffer(std::string(field.szName), field.iOffset, 1024); - break; - - case CSPFT_STRING_MAX_QPATH: - FillFromStringBuffer(std::string(field.szName), field.iOffset, 64); - break; - - case CSPFT_STRING_MAX_OSPATH: - FillFromStringBuffer(std::string(field.szName), field.iOffset, 256); - break; - - case CSPFT_INT: - FillFromInt(std::string(field.szName), field.iOffset); - break; - - case CSPFT_QBOOLEAN: - FillFromQBoolean(std::string(field.szName), field.iOffset); - break; - - case CSPFT_BOOL: - FillFromBool(std::string(field.szName), field.iOffset); - break; - - case CSPFT_FLOAT: - FillFromFloat(std::string(field.szName), field.iOffset); - break; - - case CSPFT_MPH_TO_INCHES_PER_SEC: - { - const auto* num = reinterpret_cast<float*>(reinterpret_cast<uintptr_t>(m_structure) + field.iOffset); - m_info_string.SetValueForKey(std::string(field.szName), std::to_string(*num / 17.6f)); - break; - } - - case CSPFT_MILLISECONDS: - FillFromMilliseconds(std::string(field.szName), field.iOffset); - break; - - case CSPFT_FX: - { - const auto* fx = *reinterpret_cast<FxEffectDef**>(reinterpret_cast<uintptr_t>(m_structure) + field.iOffset); - - if (fx) - m_info_string.SetValueForKey(std::string(field.szName), std::string(AssetName(fx->name))); - else - m_info_string.SetValueForKey(std::string(field.szName), ""); - break; - } - - case CSPFT_XMODEL: - { - const auto* model = *reinterpret_cast<XModel**>(reinterpret_cast<uintptr_t>(m_structure) + field.iOffset); - - if (model) - m_info_string.SetValueForKey(std::string(field.szName), std::string(AssetName(model->name))); - else - m_info_string.SetValueForKey(std::string(field.szName), ""); - break; - } - - case CSPFT_MATERIAL: - { - const auto* material = *reinterpret_cast<Material**>(reinterpret_cast<uintptr_t>(m_structure) + field. - iOffset); - - if (material) - m_info_string.SetValueForKey(std::string(field.szName), std::string(AssetName(material->info.name))); - else - m_info_string.SetValueForKey(std::string(field.szName), ""); - break; - } - - case CSPFT_SOUND: - { - const auto* sndAlias = reinterpret_cast<SndAliasCustom*>(reinterpret_cast<uintptr_t>(m_structure) + field. - iOffset); - - if (sndAlias->name) - m_info_string.SetValueForKey(std::string(field.szName), std::string(sndAlias->name->soundName)); - else - m_info_string.SetValueForKey(std::string(field.szName), ""); - break; - } - - case CSPFT_TRACER: - { - const auto* tracer = *reinterpret_cast<TracerDef**>(reinterpret_cast<uintptr_t>(m_structure) + field. - iOffset); - - if (tracer) - m_info_string.SetValueForKey(std::string(field.szName), std::string(AssetName(tracer->name))); - else - m_info_string.SetValueForKey(std::string(field.szName), ""); - break; - } - - case CSPFT_NUM_BASE_FIELD_TYPES: - default: - assert(false); - break; - } +void InfoStringFromStructConverter::FillFromBaseField(const cspField_t &field) { + switch (static_cast<csParseFieldType_t>(field.iFieldType)) { + case CSPFT_STRING: + FillFromString(std::string(field.szName), field.iOffset); + break; + + case CSPFT_STRING_MAX_STRING_CHARS: + FillFromStringBuffer(std::string(field.szName), field.iOffset, 1024); + break; + + case CSPFT_STRING_MAX_QPATH: + FillFromStringBuffer(std::string(field.szName), field.iOffset, 64); + break; + + case CSPFT_STRING_MAX_OSPATH: + FillFromStringBuffer(std::string(field.szName), field.iOffset, 256); + break; + + case CSPFT_INT: + FillFromInt(std::string(field.szName), field.iOffset); + break; + + case CSPFT_QBOOLEAN: + FillFromQBoolean(std::string(field.szName), field.iOffset); + break; + + case CSPFT_BOOL: + FillFromBool(std::string(field.szName), field.iOffset); + break; + + case CSPFT_FLOAT: + FillFromFloat(std::string(field.szName), field.iOffset); + break; + + case CSPFT_MPH_TO_INCHES_PER_SEC: { + const auto *num = reinterpret_cast<float *>(reinterpret_cast<uintptr_t>(m_structure) + field.iOffset); + m_info_string.SetValueForKey(std::string(field.szName), std::to_string(*num / 17.6f)); + break; + } + + case CSPFT_MILLISECONDS: + FillFromMilliseconds(std::string(field.szName), field.iOffset); + break; + + case CSPFT_FX: { + const auto *fx = *reinterpret_cast<FxEffectDef **>(reinterpret_cast<uintptr_t>(m_structure) + field.iOffset); + + if (fx) + m_info_string.SetValueForKey(std::string(field.szName), std::string(AssetName(fx->name))); + else + m_info_string.SetValueForKey(std::string(field.szName), ""); + break; + } + + case CSPFT_XMODEL: { + const auto *model = *reinterpret_cast<XModel **>(reinterpret_cast<uintptr_t>(m_structure) + field.iOffset); + + if (model) + m_info_string.SetValueForKey(std::string(field.szName), std::string(AssetName(model->name))); + else + m_info_string.SetValueForKey(std::string(field.szName), ""); + break; + } + + case CSPFT_MATERIAL: { + const auto *material = *reinterpret_cast<Material **>(reinterpret_cast<uintptr_t>(m_structure) + field.iOffset); + + if (material) + m_info_string.SetValueForKey(std::string(field.szName), std::string(AssetName(material->info.name))); + else + m_info_string.SetValueForKey(std::string(field.szName), ""); + break; + } + + case CSPFT_SOUND: { + const auto *sndAlias = reinterpret_cast<SndAliasCustom *>(reinterpret_cast<uintptr_t>(m_structure) + field.iOffset); + + if (sndAlias->name) + m_info_string.SetValueForKey(std::string(field.szName), std::string(sndAlias->name->soundName)); + else + m_info_string.SetValueForKey(std::string(field.szName), ""); + break; + } + + case CSPFT_TRACER: { + const auto *tracer = *reinterpret_cast<TracerDef **>(reinterpret_cast<uintptr_t>(m_structure) + field.iOffset); + + if (tracer) + m_info_string.SetValueForKey(std::string(field.szName), std::string(AssetName(tracer->name))); + else + m_info_string.SetValueForKey(std::string(field.szName), ""); + break; + } + + case CSPFT_NUM_BASE_FIELD_TYPES: + default: + assert(false); + break; + } } -void InfoStringFromStructConverter::FillInfoString() -{ - for (auto fieldIndex = 0u; fieldIndex < m_field_count; fieldIndex++) - { - const auto& field = m_fields[fieldIndex]; - assert(field.iFieldType >= 0); - - if (field.iFieldType < CSPFT_NUM_BASE_FIELD_TYPES) - FillFromBaseField(field); - else - FillFromExtensionField(field); - } -} +void InfoStringFromStructConverter::FillInfoString() { + for (auto fieldIndex = 0u; fieldIndex < m_field_count; fieldIndex++) { + const auto &field = m_fields[fieldIndex]; + assert(field.iFieldType >= 0); -InfoStringFromStructConverter::InfoStringFromStructConverter(const void* structure, const cspField_t* fields, - const size_t fieldCount) - : InfoStringFromStructConverterBase(structure), - m_fields(fields), - m_field_count(fieldCount) -{ + if (field.iFieldType < CSPFT_NUM_BASE_FIELD_TYPES) + FillFromBaseField(field); + else + FillFromExtensionField(field); + } } -InfoStringFromStructConverter::InfoStringFromStructConverter(const void* structure, const cspField_t* fields, const size_t fieldCount, - std::function<std::string(scr_string_t)> scriptStringValueCallback) - : InfoStringFromStructConverterBase(structure, std::move(scriptStringValueCallback)), - m_fields(fields), - m_field_count(fieldCount) -{ -} +InfoStringFromStructConverter::InfoStringFromStructConverter(const void *structure, const cspField_t *fields, const size_t fieldCount) + : InfoStringFromStructConverterBase(structure), m_fields(fields), m_field_count(fieldCount) {} + +InfoStringFromStructConverter::InfoStringFromStructConverter(const void *structure, const cspField_t *fields, const size_t fieldCount, + std::function<std::string(scr_string_t)> scriptStringValueCallback) + : InfoStringFromStructConverterBase(structure, std::move(scriptStringValueCallback)), m_fields(fields), m_field_count(fieldCount) {} diff --git a/src/ObjWriting/Game/IW5/InfoString/InfoStringFromStructConverter.h b/src/ObjWriting/Game/IW5/InfoString/InfoStringFromStructConverter.h index 9521faae1..0fc5820cd 100644 --- a/src/ObjWriting/Game/IW5/InfoString/InfoStringFromStructConverter.h +++ b/src/ObjWriting/Game/IW5/InfoString/InfoStringFromStructConverter.h @@ -1,21 +1,20 @@ #pragma once -#include "InfoString/InfoStringFromStructConverterBase.h" #include "Game/IW5/IW5.h" +#include "InfoString/InfoStringFromStructConverterBase.h" -namespace IW5 -{ - class InfoStringFromStructConverter : public InfoStringFromStructConverterBase - { - protected: - const cspField_t* m_fields; - size_t m_field_count; +namespace IW5 { +class InfoStringFromStructConverter : public InfoStringFromStructConverterBase { +protected: + const cspField_t *m_fields; + size_t m_field_count; - virtual void FillFromExtensionField(const cspField_t& field) = 0; - void FillFromBaseField(const cspField_t& field); - void FillInfoString() override; + virtual void FillFromExtensionField(const cspField_t &field) = 0; + void FillFromBaseField(const cspField_t &field); + void FillInfoString() override; - public: - InfoStringFromStructConverter(const void* structure, const cspField_t* fields, size_t fieldCount); - InfoStringFromStructConverter(const void* structure, const cspField_t* fields, size_t fieldCount, std::function<std::string(scr_string_t)> scriptStringValueCallback); - }; -} \ No newline at end of file +public: + InfoStringFromStructConverter(const void *structure, const cspField_t *fields, size_t fieldCount); + InfoStringFromStructConverter(const void *structure, const cspField_t *fields, size_t fieldCount, + std::function<std::string(scr_string_t)> scriptStringValueCallback); +}; +} // namespace IW5 \ No newline at end of file diff --git a/src/ObjWriting/Game/IW5/Menu/MenuDumperIW5.cpp b/src/ObjWriting/Game/IW5/Menu/MenuDumperIW5.cpp index cc153b02b..04371e885 100644 --- a/src/ObjWriting/Game/IW5/Menu/MenuDumperIW5.cpp +++ b/src/ObjWriting/Game/IW5/Menu/MenuDumperIW5.cpp @@ -1,842 +1,744 @@ #include "MenuDumperIW5.h" -#include <cmath> #include <cassert> +#include <cmath> #include <sstream> -#include "ObjWriting.h" #include "Game/IW5/MenuConstantsIW5.h" +#include "ObjWriting.h" using namespace IW5; -size_t MenuDumper::FindStatementClosingParenthesis(const Statement_s* statement, size_t openingParenthesisPosition) -{ - assert(statement->numEntries >= 0); - assert(openingParenthesisPosition < static_cast<size_t>(statement->numEntries)); - - const auto statementEnd = static_cast<size_t>(statement->numEntries); - - // The openingParenthesisPosition does not necessarily point to an actual opening parenthesis operator. That's fine though. - // We will pretend it does since the game does sometimes leave out opening parenthesis from the entries. - auto currentParenthesisDepth = 1; - for (auto currentSearchPosition = openingParenthesisPosition + 1; currentSearchPosition < statementEnd; currentSearchPosition++) - { - const auto& expEntry = statement->entries[currentSearchPosition]; - if (expEntry.type != EET_OPERATOR) - continue; - - // Any function means a "left out" left paren - if (expEntry.data.op == OP_LEFTPAREN || expEntry.data.op >= OP_COUNT) - { - currentParenthesisDepth++; - } - else if (expEntry.data.op == OP_RIGHTPAREN) - { - if (currentParenthesisDepth > 0) - currentParenthesisDepth--; - if (currentParenthesisDepth == 0) - return currentSearchPosition; - } +size_t MenuDumper::FindStatementClosingParenthesis(const Statement_s *statement, size_t openingParenthesisPosition) { + assert(statement->numEntries >= 0); + assert(openingParenthesisPosition < static_cast<size_t>(statement->numEntries)); + + const auto statementEnd = static_cast<size_t>(statement->numEntries); + + // The openingParenthesisPosition does not necessarily point to an actual opening parenthesis operator. That's fine though. + // We will pretend it does since the game does sometimes leave out opening parenthesis from the entries. + auto currentParenthesisDepth = 1; + for (auto currentSearchPosition = openingParenthesisPosition + 1; currentSearchPosition < statementEnd; currentSearchPosition++) { + const auto &expEntry = statement->entries[currentSearchPosition]; + if (expEntry.type != EET_OPERATOR) + continue; + + // Any function means a "left out" left paren + if (expEntry.data.op == OP_LEFTPAREN || expEntry.data.op >= OP_COUNT) { + currentParenthesisDepth++; + } else if (expEntry.data.op == OP_RIGHTPAREN) { + if (currentParenthesisDepth > 0) + currentParenthesisDepth--; + if (currentParenthesisDepth == 0) + return currentSearchPosition; } + } - return statementEnd; + return statementEnd; } -void MenuDumper::WriteStatementOperator(const Statement_s* statement, size_t& currentPos, bool& spaceNext) const -{ - const auto& expEntry = statement->entries[currentPos]; +void MenuDumper::WriteStatementOperator(const Statement_s *statement, size_t ¤tPos, bool &spaceNext) const { + const auto &expEntry = statement->entries[currentPos]; - if (spaceNext && expEntry.data.op != OP_COMMA) - m_stream << " "; + if (spaceNext && expEntry.data.op != OP_COMMA) + m_stream << " "; - if (expEntry.data.op == OP_LEFTPAREN) - { - const auto closingParenPos = FindStatementClosingParenthesis(statement, currentPos); - m_stream << "("; - WriteStatementEntryRange(statement, currentPos + 1, closingParenPos); - m_stream << ")"; + if (expEntry.data.op == OP_LEFTPAREN) { + const auto closingParenPos = FindStatementClosingParenthesis(statement, currentPos); + m_stream << "("; + WriteStatementEntryRange(statement, currentPos + 1, closingParenPos); + m_stream << ")"; - currentPos = closingParenPos + 1; - spaceNext = true; - } - else if (expEntry.data.op >= EXP_FUNC_STATIC_DVAR_INT && expEntry.data.op <= EXP_FUNC_STATIC_DVAR_STRING) - { - switch (expEntry.data.op) - { - case EXP_FUNC_STATIC_DVAR_INT: - m_stream << "dvarint"; - break; - - case EXP_FUNC_STATIC_DVAR_BOOL: - m_stream << "dvarbool"; - break; - - case EXP_FUNC_STATIC_DVAR_FLOAT: - m_stream << "dvarfloat"; - break; - - case EXP_FUNC_STATIC_DVAR_STRING: - m_stream << "dvarstring"; - break; - - default: - break; - } + currentPos = closingParenPos + 1; + spaceNext = true; + } else if (expEntry.data.op >= EXP_FUNC_STATIC_DVAR_INT && expEntry.data.op <= EXP_FUNC_STATIC_DVAR_STRING) { + switch (expEntry.data.op) { + case EXP_FUNC_STATIC_DVAR_INT: + m_stream << "dvarint"; + break; - // Functions do not have opening parenthesis in the entries. We can just pretend they do though - const auto closingParenPos = FindStatementClosingParenthesis(statement, currentPos); - m_stream << "("; - - if (closingParenPos - currentPos + 1 >= 1) - { - const auto& staticDvarEntry = statement->entries[currentPos + 1]; - if (staticDvarEntry.type == EET_OPERAND && staticDvarEntry.data.operand.dataType == VAL_INT) - { - if (statement->supportingData - && statement->supportingData->staticDvarList.staticDvars - && staticDvarEntry.data.operand.internals.intVal >= 0 - && staticDvarEntry.data.operand.internals.intVal < statement->supportingData->staticDvarList.numStaticDvars) - { - const auto* staticDvar = statement->supportingData->staticDvarList.staticDvars[staticDvarEntry.data.operand.internals.intVal]; - if (staticDvar && staticDvar->dvarName) - m_stream << staticDvar->dvarName; - } - else - { - m_stream << "#INVALID_DVAR_INDEX"; - } - } - else - { - m_stream << "#INVALID_DVAR_OPERAND"; - } - } + case EXP_FUNC_STATIC_DVAR_BOOL: + m_stream << "dvarbool"; + break; + + case EXP_FUNC_STATIC_DVAR_FLOAT: + m_stream << "dvarfloat"; + break; + + case EXP_FUNC_STATIC_DVAR_STRING: + m_stream << "dvarstring"; + break; - m_stream << ")"; - currentPos = closingParenPos + 1; - spaceNext = true; + default: + break; } - else - { - if (expEntry.data.op >= 0 && static_cast<unsigned>(expEntry.data.op) < std::extent_v<decltype(g_expFunctionNames)>) - m_stream << g_expFunctionNames[expEntry.data.op]; - - if (expEntry.data.op >= OP_COUNT) - { - // Functions do not have opening parenthesis in the entries. We can just pretend they do though - const auto closingParenPos = FindStatementClosingParenthesis(statement, currentPos); - m_stream << "("; - WriteStatementEntryRange(statement, currentPos + 1, closingParenPos); - m_stream << ")"; - currentPos = closingParenPos + 1; - } - else - currentPos++; - spaceNext = expEntry.data.op != OP_NOT; + // Functions do not have opening parenthesis in the entries. We can just pretend they do though + const auto closingParenPos = FindStatementClosingParenthesis(statement, currentPos); + m_stream << "("; + + if (closingParenPos - currentPos + 1 >= 1) { + const auto &staticDvarEntry = statement->entries[currentPos + 1]; + if (staticDvarEntry.type == EET_OPERAND && staticDvarEntry.data.operand.dataType == VAL_INT) { + if (statement->supportingData && statement->supportingData->staticDvarList.staticDvars && staticDvarEntry.data.operand.internals.intVal >= 0 && + staticDvarEntry.data.operand.internals.intVal < statement->supportingData->staticDvarList.numStaticDvars) { + const auto *staticDvar = statement->supportingData->staticDvarList.staticDvars[staticDvarEntry.data.operand.internals.intVal]; + if (staticDvar && staticDvar->dvarName) + m_stream << staticDvar->dvarName; + } else { + m_stream << "#INVALID_DVAR_INDEX"; + } + } else { + m_stream << "#INVALID_DVAR_OPERAND"; + } } + + m_stream << ")"; + currentPos = closingParenPos + 1; + spaceNext = true; + } else { + if (expEntry.data.op >= 0 && static_cast<unsigned>(expEntry.data.op) < std::extent_v<decltype(g_expFunctionNames)>) + m_stream << g_expFunctionNames[expEntry.data.op]; + + if (expEntry.data.op >= OP_COUNT) { + // Functions do not have opening parenthesis in the entries. We can just pretend they do though + const auto closingParenPos = FindStatementClosingParenthesis(statement, currentPos); + m_stream << "("; + WriteStatementEntryRange(statement, currentPos + 1, closingParenPos); + m_stream << ")"; + currentPos = closingParenPos + 1; + } else + currentPos++; + + spaceNext = expEntry.data.op != OP_NOT; + } } -void MenuDumper::WriteStatementOperandFunction(const Statement_s* statement, const size_t currentPos) const -{ - const auto& operand = statement->entries[currentPos].data.operand; - - if (operand.internals.function == nullptr) - return; - - if (!ObjWriting::Configuration.MenuLegacyMode) - { - int functionIndex = -1; - if (statement->supportingData && statement->supportingData->uifunctions.functions) - { - for (auto supportingFunctionIndex = 0; supportingFunctionIndex < statement->supportingData->uifunctions.totalFunctions; supportingFunctionIndex++) - { - if (statement->supportingData->uifunctions.functions[supportingFunctionIndex] == operand.internals.function) - { - functionIndex = supportingFunctionIndex; - break; - } - } - } +void MenuDumper::WriteStatementOperandFunction(const Statement_s *statement, const size_t currentPos) const { + const auto &operand = statement->entries[currentPos].data.operand; + + if (operand.internals.function == nullptr) + return; - if (functionIndex >= 0) - m_stream << "FUNC_" << functionIndex << "()"; - else - m_stream << "INVALID_FUNC"; + if (!ObjWriting::Configuration.MenuLegacyMode) { + int functionIndex = -1; + if (statement->supportingData && statement->supportingData->uifunctions.functions) { + for (auto supportingFunctionIndex = 0; supportingFunctionIndex < statement->supportingData->uifunctions.totalFunctions; supportingFunctionIndex++) { + if (statement->supportingData->uifunctions.functions[supportingFunctionIndex] == operand.internals.function) { + functionIndex = supportingFunctionIndex; + break; + } + } } + + if (functionIndex >= 0) + m_stream << "FUNC_" << functionIndex << "()"; else - { - m_stream << "("; - WriteStatementSkipInitialUnnecessaryParenthesis(operand.internals.function); - m_stream << ")"; - } + m_stream << "INVALID_FUNC"; + } else { + m_stream << "("; + WriteStatementSkipInitialUnnecessaryParenthesis(operand.internals.function); + m_stream << ")"; + } } -void MenuDumper::WriteStatementOperand(const Statement_s* statement, size_t& currentPos, bool& spaceNext) const -{ - const auto& expEntry = statement->entries[currentPos]; +void MenuDumper::WriteStatementOperand(const Statement_s *statement, size_t ¤tPos, bool &spaceNext) const { + const auto &expEntry = statement->entries[currentPos]; - if (spaceNext) - m_stream << " "; + if (spaceNext) + m_stream << " "; - const auto& operand = expEntry.data.operand; + const auto &operand = expEntry.data.operand; - switch (operand.dataType) - { - case VAL_FLOAT: - m_stream << operand.internals.floatVal; - break; + switch (operand.dataType) { + case VAL_FLOAT: + m_stream << operand.internals.floatVal; + break; - case VAL_INT: - m_stream << operand.internals.intVal; - break; + case VAL_INT: + m_stream << operand.internals.intVal; + break; - case VAL_STRING: - WriteEscapedString(operand.internals.stringVal.string); - break; + case VAL_STRING: + WriteEscapedString(operand.internals.stringVal.string); + break; - case VAL_FUNCTION: - WriteStatementOperandFunction(statement, currentPos); - break; + case VAL_FUNCTION: + WriteStatementOperandFunction(statement, currentPos); + break; - default: - break; - } + default: + break; + } - currentPos++; - spaceNext = true; + currentPos++; + spaceNext = true; } -void MenuDumper::WriteStatementEntryRange(const Statement_s* statement, size_t startOffset, size_t endOffset) const -{ - assert(startOffset <= endOffset); - assert(endOffset <= static_cast<size_t>(statement->numEntries)); +void MenuDumper::WriteStatementEntryRange(const Statement_s *statement, size_t startOffset, size_t endOffset) const { + assert(startOffset <= endOffset); + assert(endOffset <= static_cast<size_t>(statement->numEntries)); - auto currentPos = startOffset; - auto spaceNext = false; - while (currentPos < endOffset) - { - const auto& expEntry = statement->entries[currentPos]; + auto currentPos = startOffset; + auto spaceNext = false; + while (currentPos < endOffset) { + const auto &expEntry = statement->entries[currentPos]; - if (expEntry.type == EET_OPERATOR) - { - WriteStatementOperator(statement, currentPos, spaceNext); - } - else - { - WriteStatementOperand(statement, currentPos, spaceNext); - } + if (expEntry.type == EET_OPERATOR) { + WriteStatementOperator(statement, currentPos, spaceNext); + } else { + WriteStatementOperand(statement, currentPos, spaceNext); } + } } -void MenuDumper::WriteStatement(const Statement_s* statement) const -{ - if (statement == nullptr || statement->numEntries < 0) - return; +void MenuDumper::WriteStatement(const Statement_s *statement) const { + if (statement == nullptr || statement->numEntries < 0) + return; - WriteStatementEntryRange(statement, 0, static_cast<size_t>(statement->numEntries)); + WriteStatementEntryRange(statement, 0, static_cast<size_t>(statement->numEntries)); } -void MenuDumper::WriteStatementSkipInitialUnnecessaryParenthesis(const Statement_s* statementValue) const -{ - if (statementValue == nullptr || statementValue->numEntries < 0) - return; +void MenuDumper::WriteStatementSkipInitialUnnecessaryParenthesis(const Statement_s *statementValue) const { + if (statementValue == nullptr || statementValue->numEntries < 0) + return; - const auto statementEnd = static_cast<size_t>(statementValue->numEntries); + const auto statementEnd = static_cast<size_t>(statementValue->numEntries); - if (statementValue->numEntries >= 1 - && statementValue->entries[0].type == EET_OPERATOR - && statementValue->entries[0].data.op == OP_LEFTPAREN) - { - const auto parenthesisEnd = FindStatementClosingParenthesis(statementValue, 0); + if (statementValue->numEntries >= 1 && statementValue->entries[0].type == EET_OPERATOR && statementValue->entries[0].data.op == OP_LEFTPAREN) { + const auto parenthesisEnd = FindStatementClosingParenthesis(statementValue, 0); - if (parenthesisEnd >= statementEnd) - WriteStatementEntryRange(statementValue, 1, statementEnd); - else if (parenthesisEnd == statementEnd - 1) - WriteStatementEntryRange(statementValue, 1, statementEnd - 1); - else - WriteStatementEntryRange(statementValue, 0, statementEnd); - } + if (parenthesisEnd >= statementEnd) + WriteStatementEntryRange(statementValue, 1, statementEnd); + else if (parenthesisEnd == statementEnd - 1) + WriteStatementEntryRange(statementValue, 1, statementEnd - 1); else - { - WriteStatementEntryRange(statementValue, 0, statementEnd); - } + WriteStatementEntryRange(statementValue, 0, statementEnd); + } else { + WriteStatementEntryRange(statementValue, 0, statementEnd); + } } -void MenuDumper::WriteStatementProperty(const std::string& propertyKey, const Statement_s* statementValue, bool isBooleanStatement) const -{ - if (statementValue == nullptr || statementValue->numEntries < 0) - return; +void MenuDumper::WriteStatementProperty(const std::string &propertyKey, const Statement_s *statementValue, bool isBooleanStatement) const { + if (statementValue == nullptr || statementValue->numEntries < 0) + return; - Indent(); - WriteKey(propertyKey); + Indent(); + WriteKey(propertyKey); - if (isBooleanStatement) - { - m_stream << "when("; - WriteStatementSkipInitialUnnecessaryParenthesis(statementValue); - m_stream << ");\n"; - } - else - { - WriteStatementSkipInitialUnnecessaryParenthesis(statementValue); - m_stream << ";\n"; - } + if (isBooleanStatement) { + m_stream << "when("; + WriteStatementSkipInitialUnnecessaryParenthesis(statementValue); + m_stream << ");\n"; + } else { + WriteStatementSkipInitialUnnecessaryParenthesis(statementValue); + m_stream << ";\n"; + } } -void MenuDumper::WriteSetLocalVarData(const std::string& setFunction, const SetLocalVarData* setLocalVarData) const -{ - if (setLocalVarData == nullptr) - return; +void MenuDumper::WriteSetLocalVarData(const std::string &setFunction, const SetLocalVarData *setLocalVarData) const { + if (setLocalVarData == nullptr) + return; - Indent(); - m_stream << setFunction << " " << setLocalVarData->localVarName << " "; - WriteStatement(setLocalVarData->expression); - m_stream << ";\n"; + Indent(); + m_stream << setFunction << " " << setLocalVarData->localVarName << " "; + WriteStatement(setLocalVarData->expression); + m_stream << ";\n"; } -//#define WRITE_ORIGINAL_SCRIPT +// #define WRITE_ORIGINAL_SCRIPT -void MenuDumper::WriteUnconditionalScript(const char* script) const -{ +void MenuDumper::WriteUnconditionalScript(const char *script) const { #ifdef WRITE_ORIGINAL_SCRIPT - Indent(); - m_stream << script << "\n"; - return; + Indent(); + m_stream << script << "\n"; + return; #endif - const auto tokenList = CreateScriptTokenList(script); + const auto tokenList = CreateScriptTokenList(script); - auto isNewStatement = true; - for (const auto& token : tokenList) - { - if (isNewStatement) - { - if (token == ";") - continue; + auto isNewStatement = true; + for (const auto &token : tokenList) { + if (isNewStatement) { + if (token == ";") + continue; - Indent(); - } - - if (token == ";") - { - m_stream << ";\n"; - isNewStatement = true; - continue; - } - - if (!isNewStatement) - m_stream << " "; - else - isNewStatement = false; + Indent(); + } - if (DoesTokenNeedQuotationMarks(token)) - m_stream << "\"" << token << "\""; - else - m_stream << token; + if (token == ";") { + m_stream << ";\n"; + isNewStatement = true; + continue; } if (!isNewStatement) - m_stream << ";\n"; -} + m_stream << " "; + else + isNewStatement = false; -void MenuDumper::WriteMenuEventHandlerSet(const MenuEventHandlerSet* eventHandlerSet) -{ - Indent(); - m_stream << "{\n"; - IncIndent(); - - for (auto i = 0; i < eventHandlerSet->eventHandlerCount; i++) - { - const auto* eventHandler = eventHandlerSet->eventHandlers[i]; - if (eventHandler == nullptr) - continue; - - switch (eventHandler->eventType) - { - case EVENT_UNCONDITIONAL: - WriteUnconditionalScript(eventHandler->eventData.unconditionalScript); - break; - - case EVENT_IF: - if (eventHandler->eventData.conditionalScript == nullptr - || eventHandler->eventData.conditionalScript->eventExpression == nullptr - || eventHandler->eventData.conditionalScript->eventHandlerSet == nullptr) - { - continue; - } - - Indent(); - m_stream << "if ("; - WriteStatementSkipInitialUnnecessaryParenthesis(eventHandler->eventData.conditionalScript->eventExpression); - m_stream << ")\n"; - WriteMenuEventHandlerSet(eventHandler->eventData.conditionalScript->eventHandlerSet); - break; - - case EVENT_ELSE: - if (eventHandler->eventData.elseScript == nullptr) - continue; - - Indent(); - m_stream << "else\n"; - WriteMenuEventHandlerSet(eventHandler->eventData.elseScript); - break; - - case EVENT_SET_LOCAL_VAR_BOOL: - WriteSetLocalVarData("setLocalVarBool", eventHandler->eventData.setLocalVarData); - break; - - case EVENT_SET_LOCAL_VAR_INT: - WriteSetLocalVarData("setLocalVarInt", eventHandler->eventData.setLocalVarData); - break; - - case EVENT_SET_LOCAL_VAR_FLOAT: - WriteSetLocalVarData("setLocalVarFloat", eventHandler->eventData.setLocalVarData); - break; - - case EVENT_SET_LOCAL_VAR_STRING: - WriteSetLocalVarData("setLocalVarString", eventHandler->eventData.setLocalVarData); - break; - - default: - break; - } - } + if (DoesTokenNeedQuotationMarks(token)) + m_stream << "\"" << token << "\""; + else + m_stream << token; + } - DecIndent(); - Indent(); - m_stream << "}\n"; + if (!isNewStatement) + m_stream << ";\n"; } -void MenuDumper::WriteMenuEventHandlerSetProperty(const std::string& propertyKey, const MenuEventHandlerSet* eventHandlerSetValue) -{ - if (eventHandlerSetValue == nullptr) - return; +void MenuDumper::WriteMenuEventHandlerSet(const MenuEventHandlerSet *eventHandlerSet) { + Indent(); + m_stream << "{\n"; + IncIndent(); - Indent(); - m_stream << propertyKey << "\n"; - WriteMenuEventHandlerSet(eventHandlerSetValue); -} + for (auto i = 0; i < eventHandlerSet->eventHandlerCount; i++) { + const auto *eventHandler = eventHandlerSet->eventHandlers[i]; + if (eventHandler == nullptr) + continue; -void MenuDumper::WriteRectProperty(const std::string& propertyKey, const rectDef_s& rect) const -{ - Indent(); - WriteKey(propertyKey); - m_stream << rect.x << " " << rect.y << " " << rect.w << " " << rect.h << " " << static_cast<int>(rect.horzAlign) << " " << static_cast<int>(rect.vertAlign) << "\n"; -} + switch (eventHandler->eventType) { + case EVENT_UNCONDITIONAL: + WriteUnconditionalScript(eventHandler->eventData.unconditionalScript); + break; -void MenuDumper::WriteMaterialProperty(const std::string& propertyKey, const Material* materialValue) const -{ - if (materialValue == nullptr || materialValue->info.name == nullptr) - return; + case EVENT_IF: + if (eventHandler->eventData.conditionalScript == nullptr || eventHandler->eventData.conditionalScript->eventExpression == nullptr || + eventHandler->eventData.conditionalScript->eventHandlerSet == nullptr) { + continue; + } - if (materialValue->info.name[0] == ',') - WriteStringProperty(propertyKey, &materialValue->info.name[1]); - else - WriteStringProperty(propertyKey, materialValue->info.name); -} + Indent(); + m_stream << "if ("; + WriteStatementSkipInitialUnnecessaryParenthesis(eventHandler->eventData.conditionalScript->eventExpression); + m_stream << ")\n"; + WriteMenuEventHandlerSet(eventHandler->eventData.conditionalScript->eventHandlerSet); + break; -void MenuDumper::WriteSoundAliasProperty(const std::string& propertyKey, const snd_alias_list_t* soundAliasValue) const -{ - if (soundAliasValue == nullptr) - return; + case EVENT_ELSE: + if (eventHandler->eventData.elseScript == nullptr) + continue; - WriteStringProperty(propertyKey, soundAliasValue->aliasName); -} + Indent(); + m_stream << "else\n"; + WriteMenuEventHandlerSet(eventHandler->eventData.elseScript); + break; -void MenuDumper::WriteDecodeEffectProperty(const std::string& propertyKey, const itemDef_s* item) const -{ - if (!item->decayActive) - return; + case EVENT_SET_LOCAL_VAR_BOOL: + WriteSetLocalVarData("setLocalVarBool", eventHandler->eventData.setLocalVarData); + break; - Indent(); - WriteKey(propertyKey); - m_stream << item->fxLetterTime << " " << item->fxDecayStartTime << " " << item->fxDecayDuration << "\n"; -} - -void MenuDumper::WriteItemKeyHandlerProperty(const ItemKeyHandler* itemKeyHandlerValue) -{ - for (const auto* currentHandler = itemKeyHandlerValue; currentHandler; currentHandler = currentHandler->next) - { - if (currentHandler->key >= '!' && currentHandler->key <= '~' && currentHandler->key != '"') - { - std::ostringstream ss; - ss << "execKey \"" << static_cast<char>(currentHandler->key) << "\""; - WriteMenuEventHandlerSetProperty(ss.str(), currentHandler->action); - } - else - { - std::ostringstream ss; - ss << "execKeyInt " << currentHandler->key; - WriteMenuEventHandlerSetProperty(ss.str(), currentHandler->action); - } + case EVENT_SET_LOCAL_VAR_INT: + WriteSetLocalVarData("setLocalVarInt", eventHandler->eventData.setLocalVarData); + break; + + case EVENT_SET_LOCAL_VAR_FLOAT: + WriteSetLocalVarData("setLocalVarFloat", eventHandler->eventData.setLocalVarData); + break; + + case EVENT_SET_LOCAL_VAR_STRING: + WriteSetLocalVarData("setLocalVarString", eventHandler->eventData.setLocalVarData); + break; + + default: + break; } + } + + DecIndent(); + Indent(); + m_stream << "}\n"; } -void MenuDumper::WriteFloatExpressionsProperty(const ItemFloatExpression* floatExpressions, int floatExpressionCount) const -{ - if (!floatExpressions) - return; +void MenuDumper::WriteMenuEventHandlerSetProperty(const std::string &propertyKey, const MenuEventHandlerSet *eventHandlerSetValue) { + if (eventHandlerSetValue == nullptr) + return; - for (int i = 0; i < floatExpressionCount; i++) - { - const auto& floatExpression = floatExpressions[i]; + Indent(); + m_stream << propertyKey << "\n"; + WriteMenuEventHandlerSet(eventHandlerSetValue); +} - if (floatExpression.target < 0 || floatExpression.target >= ITEM_FLOATEXP_TGT_COUNT) - continue; +void MenuDumper::WriteRectProperty(const std::string &propertyKey, const rectDef_s &rect) const { + Indent(); + WriteKey(propertyKey); + m_stream << rect.x << " " << rect.y << " " << rect.w << " " << rect.h << " " << static_cast<int>(rect.horzAlign) << " " << static_cast<int>(rect.vertAlign) + << "\n"; +} - std::string propertyName = std::string("exp ") + floatExpressionTargetBindings[floatExpression.target].name + std::string(" ") - + floatExpressionTargetBindings[floatExpression.target].componentName; +void MenuDumper::WriteMaterialProperty(const std::string &propertyKey, const Material *materialValue) const { + if (materialValue == nullptr || materialValue->info.name == nullptr) + return; - WriteStatementProperty(propertyName, floatExpression.expression, false); - } + if (materialValue->info.name[0] == ',') + WriteStringProperty(propertyKey, &materialValue->info.name[1]); + else + WriteStringProperty(propertyKey, materialValue->info.name); } -void MenuDumper::WriteMultiTokenStringProperty(const std::string& propertyKey, const char* value) const -{ - if (!value) - return; +void MenuDumper::WriteSoundAliasProperty(const std::string &propertyKey, const snd_alias_list_t *soundAliasValue) const { + if (soundAliasValue == nullptr) + return; - Indent(); - WriteKey(propertyKey); - - const auto tokenList = CreateScriptTokenList(value); - - auto firstToken = true; - m_stream << "{ "; - for (const auto& token : tokenList) - { - if (firstToken) - firstToken = false; - else - m_stream << ";"; - m_stream << "\"" << token << "\""; - } - if (!firstToken) - m_stream << " "; - m_stream << "}\n"; + WriteStringProperty(propertyKey, soundAliasValue->aliasName); } -void MenuDumper::WriteColumnProperty(const std::string& propertyKey, const listBoxDef_s* listBox) const -{ - if (listBox->numColumns <= 0) - return; +void MenuDumper::WriteDecodeEffectProperty(const std::string &propertyKey, const itemDef_s *item) const { + if (!item->decayActive) + return; - Indent(); - WriteKey(propertyKey); - m_stream << listBox->numColumns << "\n"; - - for (auto col = 0; col < listBox->numColumns; col++) - { - Indent(); - for (auto i = 0u; i < MENU_KEY_SPACING; i++) - m_stream << " "; - - m_stream << listBox->columnInfo[col].xpos - << " " << listBox->columnInfo[col].ypos - << " " << listBox->columnInfo[col].width - << " " << listBox->columnInfo[col].height - << " " << listBox->columnInfo[col].maxChars - << " " << listBox->columnInfo[col].alignment << "\n"; + Indent(); + WriteKey(propertyKey); + m_stream << item->fxLetterTime << " " << item->fxDecayStartTime << " " << item->fxDecayDuration << "\n"; +} + +void MenuDumper::WriteItemKeyHandlerProperty(const ItemKeyHandler *itemKeyHandlerValue) { + for (const auto *currentHandler = itemKeyHandlerValue; currentHandler; currentHandler = currentHandler->next) { + if (currentHandler->key >= '!' && currentHandler->key <= '~' && currentHandler->key != '"') { + std::ostringstream ss; + ss << "execKey \"" << static_cast<char>(currentHandler->key) << "\""; + WriteMenuEventHandlerSetProperty(ss.str(), currentHandler->action); + } else { + std::ostringstream ss; + ss << "execKeyInt " << currentHandler->key; + WriteMenuEventHandlerSetProperty(ss.str(), currentHandler->action); } + } } -void MenuDumper::WriteListBoxProperties(const itemDef_s* item) -{ - if (item->type != ITEM_TYPE_LISTBOX || item->typeData.listBox == nullptr) - return; +void MenuDumper::WriteFloatExpressionsProperty(const ItemFloatExpression *floatExpressions, int floatExpressionCount) const { + if (!floatExpressions) + return; - const auto* listBox = item->typeData.listBox; - WriteKeywordProperty("notselectable", listBox->notselectable != 0); - WriteKeywordProperty("noscrollbars", listBox->noScrollBars != 0); - WriteKeywordProperty("usepaging", listBox->usePaging != 0); - WriteFloatProperty("elementwidth", listBox->elementWidth, 0.0f); - WriteFloatProperty("elementheight", listBox->elementHeight, 0.0f); - WriteFloatProperty("feeder", item->special, 0.0f); - WriteIntProperty("elementtype", listBox->elementStyle, 0); - WriteColumnProperty("columns", listBox); - WriteMenuEventHandlerSetProperty("doubleclick", listBox->onDoubleClick); - WriteColorProperty("selectBorder", listBox->selectBorder, COLOR_0000); - WriteMaterialProperty("selectIcon", listBox->selectIcon); - WriteStatementProperty("exp elementheight", listBox->elementHeightExp, false); -} + for (int i = 0; i < floatExpressionCount; i++) { + const auto &floatExpression = floatExpressions[i]; -void MenuDumper::WriteDvarFloatProperty(const std::string& propertyKey, const itemDef_s* item, const editFieldDef_s* editField) const -{ - if (item->dvar == nullptr) - return; + if (floatExpression.target < 0 || floatExpression.target >= ITEM_FLOATEXP_TGT_COUNT) + continue; - Indent(); - WriteKey(propertyKey); - m_stream << "\"" << item->dvar << "\" " << editField->stepVal << " " << editField->minVal << " " << editField->maxVal << "\n"; -} - -void MenuDumper::WriteEditFieldProperties(const itemDef_s* item) const -{ - switch (item->type) - { - case ITEM_TYPE_TEXT: - case ITEM_TYPE_EDITFIELD: - case ITEM_TYPE_NUMERICFIELD: - case ITEM_TYPE_SLIDER: - case ITEM_TYPE_YESNO: - case ITEM_TYPE_BIND: - case ITEM_TYPE_VALIDFILEFIELD: - case ITEM_TYPE_DECIMALFIELD: - case ITEM_TYPE_UPREDITFIELD: - case ITEM_TYPE_EMAILFIELD: - case ITEM_TYPE_PASSWORDFIELD: - break; + std::string propertyName = std::string("exp ") + floatExpressionTargetBindings[floatExpression.target].name + std::string(" ") + + floatExpressionTargetBindings[floatExpression.target].componentName; - default: - return; - } + WriteStatementProperty(propertyName, floatExpression.expression, false); + } +} - if (item->typeData.editField == nullptr) - return; +void MenuDumper::WriteMultiTokenStringProperty(const std::string &propertyKey, const char *value) const { + if (!value) + return; - const auto* editField = item->typeData.editField; - if (std::fabs(-1.0f - editField->stepVal) >= std::numeric_limits<float>::epsilon() - || std::fabs(-1.0f - editField->minVal) >= std::numeric_limits<float>::epsilon() - || std::fabs(-1.0f - editField->maxVal) >= std::numeric_limits<float>::epsilon()) - { - WriteDvarFloatProperty("dvarFloat", item, editField); - } + Indent(); + WriteKey(propertyKey); + + const auto tokenList = CreateScriptTokenList(value); + + auto firstToken = true; + m_stream << "{ "; + for (const auto &token : tokenList) { + if (firstToken) + firstToken = false; else - { - WriteStringProperty("dvar", item->dvar); - } - WriteStringProperty("localvar", item->localVar); - WriteIntProperty("maxChars", editField->maxChars, 0); - WriteKeywordProperty("maxCharsGotoNext", editField->maxCharsGotoNext != 0); - WriteIntProperty("maxPaintChars", editField->maxPaintChars, 0); + m_stream << ";"; + m_stream << "\"" << token << "\""; + } + if (!firstToken) + m_stream << " "; + m_stream << "}\n"; } -void MenuDumper::WriteMultiValueProperty(const multiDef_s* multiDef) const -{ - Indent(); - if (multiDef->strDef) - WriteKey("dvarStrList"); - else - WriteKey("dvarFloatList"); +void MenuDumper::WriteColumnProperty(const std::string &propertyKey, const listBoxDef_s *listBox) const { + if (listBox->numColumns <= 0) + return; - m_stream << "{"; - for (auto i = 0; i < multiDef->count; i++) - { - if (multiDef->dvarList[i] == nullptr || multiDef->strDef && multiDef->dvarStr[i] == nullptr) - continue; + Indent(); + WriteKey(propertyKey); + m_stream << listBox->numColumns << "\n"; - m_stream << " \"" << multiDef->dvarList[i] << "\""; + for (auto col = 0; col < listBox->numColumns; col++) { + Indent(); + for (auto i = 0u; i < MENU_KEY_SPACING; i++) + m_stream << " "; - if (multiDef->strDef) - m_stream << " \"" << multiDef->dvarStr[i] << "\""; - else - m_stream << " " << multiDef->dvarValue[i] << ""; - } - m_stream << " }\n"; + m_stream << listBox->columnInfo[col].xpos << " " << listBox->columnInfo[col].ypos << " " << listBox->columnInfo[col].width << " " + << listBox->columnInfo[col].height << " " << listBox->columnInfo[col].maxChars << " " << listBox->columnInfo[col].alignment << "\n"; + } } -void MenuDumper::WriteMultiProperties(const itemDef_s* item) const -{ - if (item->type != ITEM_TYPE_MULTI || item->typeData.multi == nullptr) - return; +void MenuDumper::WriteListBoxProperties(const itemDef_s *item) { + if (item->type != ITEM_TYPE_LISTBOX || item->typeData.listBox == nullptr) + return; - const auto* multiDef = item->typeData.multi; + const auto *listBox = item->typeData.listBox; + WriteKeywordProperty("notselectable", listBox->notselectable != 0); + WriteKeywordProperty("noscrollbars", listBox->noScrollBars != 0); + WriteKeywordProperty("usepaging", listBox->usePaging != 0); + WriteFloatProperty("elementwidth", listBox->elementWidth, 0.0f); + WriteFloatProperty("elementheight", listBox->elementHeight, 0.0f); + WriteFloatProperty("feeder", item->special, 0.0f); + WriteIntProperty("elementtype", listBox->elementStyle, 0); + WriteColumnProperty("columns", listBox); + WriteMenuEventHandlerSetProperty("doubleclick", listBox->onDoubleClick); + WriteColorProperty("selectBorder", listBox->selectBorder, COLOR_0000); + WriteMaterialProperty("selectIcon", listBox->selectIcon); + WriteStatementProperty("exp elementheight", listBox->elementHeightExp, false); +} + +void MenuDumper::WriteDvarFloatProperty(const std::string &propertyKey, const itemDef_s *item, const editFieldDef_s *editField) const { + if (item->dvar == nullptr) + return; - if (multiDef->count <= 0) - return; + Indent(); + WriteKey(propertyKey); + m_stream << "\"" << item->dvar << "\" " << editField->stepVal << " " << editField->minVal << " " << editField->maxVal << "\n"; +} + +void MenuDumper::WriteEditFieldProperties(const itemDef_s *item) const { + switch (item->type) { + case ITEM_TYPE_TEXT: + case ITEM_TYPE_EDITFIELD: + case ITEM_TYPE_NUMERICFIELD: + case ITEM_TYPE_SLIDER: + case ITEM_TYPE_YESNO: + case ITEM_TYPE_BIND: + case ITEM_TYPE_VALIDFILEFIELD: + case ITEM_TYPE_DECIMALFIELD: + case ITEM_TYPE_UPREDITFIELD: + case ITEM_TYPE_EMAILFIELD: + case ITEM_TYPE_PASSWORDFIELD: + break; + + default: + return; + } + if (item->typeData.editField == nullptr) + return; + + const auto *editField = item->typeData.editField; + if (std::fabs(-1.0f - editField->stepVal) >= std::numeric_limits<float>::epsilon() || + std::fabs(-1.0f - editField->minVal) >= std::numeric_limits<float>::epsilon() || + std::fabs(-1.0f - editField->maxVal) >= std::numeric_limits<float>::epsilon()) { + WriteDvarFloatProperty("dvarFloat", item, editField); + } else { WriteStringProperty("dvar", item->dvar); - WriteStringProperty("localvar", item->localVar); - WriteMultiValueProperty(multiDef); + } + WriteStringProperty("localvar", item->localVar); + WriteIntProperty("maxChars", editField->maxChars, 0); + WriteKeywordProperty("maxCharsGotoNext", editField->maxCharsGotoNext != 0); + WriteIntProperty("maxPaintChars", editField->maxPaintChars, 0); } -void MenuDumper::WriteEnumDvarProperties(const itemDef_s* item) const -{ - if (item->type != ITEM_TYPE_DVARENUM) - return; +void MenuDumper::WriteMultiValueProperty(const multiDef_s *multiDef) const { + Indent(); + if (multiDef->strDef) + WriteKey("dvarStrList"); + else + WriteKey("dvarFloatList"); - WriteStringProperty("dvar", item->dvar); - WriteStringProperty("localvar", item->localVar); - WriteStringProperty("dvarEnumList", item->typeData.enumDvarName); -} - -void MenuDumper::WriteTickerProperties(const itemDef_s* item) const -{ - if (item->type != ITEM_TYPE_NEWS_TICKER || item->typeData.ticker == nullptr) - return; - - const auto* newsTickerDef = item->typeData.ticker; - WriteIntProperty("spacing", newsTickerDef->spacing, 0); - WriteIntProperty("speed", newsTickerDef->speed, 0); - WriteIntProperty("newsfeed", newsTickerDef->feedId, 0); -} - -void MenuDumper::WriteItemData(const itemDef_s* item) -{ - WriteStringProperty("name", item->window.name); - WriteStringProperty("text", item->text); - WriteKeywordProperty("textsavegame", item->itemFlags & ITEM_FLAG_SAVE_GAME_INFO); - WriteKeywordProperty("textcinematicsubtitle", item->itemFlags & ITEM_FLAG_CINEMATIC_SUBTITLE); - WriteStringProperty("group", item->window.group); - WriteRectProperty("rect", item->window.rectClient); - WriteIntProperty("style", item->window.style, 0); - WriteKeywordProperty("decoration", item->window.staticFlags & WINDOW_FLAG_DECORATION); - WriteKeywordProperty("autowrapped", item->window.staticFlags & WINDOW_FLAG_AUTO_WRAPPED); - WriteKeywordProperty("horizontalscroll", item->window.staticFlags & WINDOW_FLAG_HORIZONTAL_SCROLL); - WriteIntProperty("type", item->type, ITEM_TYPE_TEXT); - WriteIntProperty("border", item->window.border, 0); - WriteFloatProperty("borderSize", item->window.borderSize, 0.0f); - - if (item->visibleExp) - WriteStatementProperty("visible", item->visibleExp, true); - else if (item->window.dynamicFlags[0] & WINDOW_FLAG_VISIBLE) - WriteIntProperty("visible", 1, 0); - - WriteStatementProperty("disabled", item->disabledExp, true); - WriteIntProperty("ownerdraw", item->window.ownerDraw, 0); - WriteFlagsProperty("ownerdrawFlag", item->window.ownerDrawFlags); - WriteIntProperty("align", item->alignment, 0); - WriteIntProperty("textalign", item->textAlignMode, 0); - WriteFloatProperty("textalignx", item->textalignx, 0.0f); - WriteFloatProperty("textaligny", item->textaligny, 0.0f); - WriteFloatProperty("textscale", item->textscale, 0.0f); - WriteIntProperty("textstyle", item->textStyle, 0); - WriteIntProperty("textfont", item->fontEnum, 0); - WriteColorProperty("backcolor", item->window.backColor, COLOR_0000); - WriteColorProperty("forecolor", item->window.foreColor, COLOR_1111); - WriteColorProperty("bordercolor", item->window.borderColor, COLOR_0000); - WriteColorProperty("outlinecolor", item->window.outlineColor, COLOR_0000); - WriteColorProperty("disablecolor", item->window.disableColor, COLOR_0000); - WriteColorProperty("glowcolor", item->glowColor, COLOR_0000); - WriteMaterialProperty("background", item->window.background); - WriteMenuEventHandlerSetProperty("onFocus", item->onFocus); - WriteMenuEventHandlerSetProperty("hasFocus", item->hasFocus); - WriteMenuEventHandlerSetProperty("leaveFocus", item->leaveFocus); - WriteMenuEventHandlerSetProperty("mouseEnter", item->mouseEnter); - WriteMenuEventHandlerSetProperty("mouseExit", item->mouseExit); - WriteMenuEventHandlerSetProperty("mouseEnterText", item->mouseEnterText); - WriteMenuEventHandlerSetProperty("mouseExitText", item->mouseExitText); - WriteMenuEventHandlerSetProperty("action", item->action); - WriteMenuEventHandlerSetProperty("accept", item->accept); - // WriteFloatProperty("special", item->special, 0.0f); - WriteSoundAliasProperty("focusSound", item->focusSound); - WriteStringProperty("dvarTest", item->dvarTest); - - if (item->dvarFlags & ITEM_DVAR_FLAG_ENABLE) - WriteMultiTokenStringProperty("enableDvar", item->enableDvar); - else if (item->dvarFlags & ITEM_DVAR_FLAG_DISABLE) - WriteMultiTokenStringProperty("disableDvar", item->enableDvar); - else if (item->dvarFlags & ITEM_DVAR_FLAG_SHOW) - WriteMultiTokenStringProperty("showDvar", item->enableDvar); - else if (item->dvarFlags & ITEM_DVAR_FLAG_HIDE) - WriteMultiTokenStringProperty("hideDvar", item->enableDvar); - else if (item->dvarFlags & ITEM_DVAR_FLAG_FOCUS) - WriteMultiTokenStringProperty("focusDvar", item->enableDvar); - - WriteItemKeyHandlerProperty(item->onKey); - WriteStatementProperty("exp text", item->textExp, false); - WriteStatementProperty("exp textaligny", item->textAlignYExp, false); - WriteStatementProperty("exp material", item->materialExp, false); - WriteStatementProperty("exp disabled", item->disabledExp, false); - WriteFloatExpressionsProperty(item->floatExpressions, item->floatExpressionCount); - WriteIntProperty("gamemsgwindowindex", item->gameMsgWindowIndex, 0); - WriteIntProperty("gamemsgwindowmode", item->gameMsgWindowMode, 0); - WriteDecodeEffectProperty("decodeEffect", item); - - WriteListBoxProperties(item); - WriteEditFieldProperties(item); - WriteMultiProperties(item); - WriteEnumDvarProperties(item); - WriteTickerProperties(item); -} - -void MenuDumper::WriteItemDefs(const itemDef_s* const* itemDefs, size_t itemCount) -{ - for (auto i = 0u; i < itemCount; i++) - { - StartItemDefScope(); - - WriteItemData(itemDefs[i]); - - EndScope(); - } + m_stream << "{"; + for (auto i = 0; i < multiDef->count; i++) { + if (multiDef->dvarList[i] == nullptr || multiDef->strDef && multiDef->dvarStr[i] == nullptr) + continue; + + m_stream << " \"" << multiDef->dvarList[i] << "\""; + + if (multiDef->strDef) + m_stream << " \"" << multiDef->dvarStr[i] << "\""; + else + m_stream << " " << multiDef->dvarValue[i] << ""; + } + m_stream << " }\n"; } -void MenuDumper::WriteMenuData(const menuDef_t* menu) -{ - WriteStringProperty("name", menu->window.name); - WriteBoolProperty("fullscreen", menu->data->fullScreen, false); - WriteKeywordProperty("screenSpace", menu->window.staticFlags & WINDOW_FLAG_SCREEN_SPACE); - WriteKeywordProperty("decoration", menu->window.staticFlags & WINDOW_FLAG_DECORATION); - WriteRectProperty("rect", menu->window.rect); - WriteIntProperty("style", menu->window.style, 0); - WriteIntProperty("border", menu->window.border, 0); - WriteFloatProperty("borderSize", menu->window.borderSize, 0.0f); - WriteColorProperty("backcolor", menu->window.backColor, COLOR_0000); - WriteColorProperty("forecolor", menu->window.foreColor, COLOR_1111); - WriteColorProperty("bordercolor", menu->window.borderColor, COLOR_0000); - WriteColorProperty("focuscolor", menu->data->focusColor, COLOR_0000); - WriteColorProperty("outlinecolor", menu->window.outlineColor, COLOR_0000); - WriteMaterialProperty("background", menu->window.background); - WriteIntProperty("ownerdraw", menu->window.ownerDraw, 0); - WriteFlagsProperty("ownerdrawFlag", menu->window.ownerDrawFlags); - WriteKeywordProperty("outOfBoundsClick", menu->window.staticFlags & WINDOW_FLAG_OUT_OF_BOUNDS_CLICK); - WriteStringProperty("soundLoop", menu->data->soundName); - WriteKeywordProperty("popup", menu->window.staticFlags & WINDOW_FLAG_POPUP); - WriteFloatProperty("fadeClamp", menu->data->fadeClamp, 0.0f); - WriteIntProperty("fadeCycle", menu->data->fadeCycle, 0); - WriteFloatProperty("fadeAmount", menu->data->fadeAmount, 0.0f); - WriteFloatProperty("fadeInAmount", menu->data->fadeInAmount, 0.0f); - WriteFloatProperty("blurWorld", menu->data->blurRadius, 0.0f); - WriteKeywordProperty("legacySplitScreenScale", menu->window.staticFlags & WINDOW_FLAG_LEGACY_SPLIT_SCREEN_SCALE); - WriteKeywordProperty("hiddenDuringScope", menu->window.staticFlags & WINDOW_FLAG_HIDDEN_DURING_SCOPE); - WriteKeywordProperty("hiddenDuringFlashbang", menu->window.staticFlags & WINDOW_FLAG_HIDDEN_DURING_FLASH_BANG); - WriteKeywordProperty("hiddenDuringUI", menu->window.staticFlags & WINDOW_FLAG_HIDDEN_DURING_UI); - WriteStringProperty("allowedBinding", menu->data->allowedBinding); - WriteKeywordProperty("textOnlyFocus", menu->window.staticFlags & WINDOW_FLAG_TEXT_ONLY_FOCUS); - - if (menu->data->visibleExp) - WriteStatementProperty("visible", menu->data->visibleExp, true); - else if (menu->window.dynamicFlags[0] & WINDOW_FLAG_VISIBLE) - WriteIntProperty("visible", 1, 0); - - WriteStatementProperty("exp rect X", menu->data->rectXExp, false); - WriteStatementProperty("exp rect Y", menu->data->rectYExp, false); - WriteStatementProperty("exp rect W", menu->data->rectWExp, false); - WriteStatementProperty("exp rect H", menu->data->rectHExp, false); - WriteStatementProperty("exp openSound", menu->data->openSoundExp, false); - WriteStatementProperty("exp closeSound", menu->data->closeSoundExp, false); - WriteStatementProperty("exp soundLoop", menu->data->soundLoopExp, false); - WriteMenuEventHandlerSetProperty("onOpen", menu->data->onOpen); - WriteMenuEventHandlerSetProperty("onClose", menu->data->onClose); - WriteMenuEventHandlerSetProperty("onRequestClose", menu->data->onCloseRequest); - WriteMenuEventHandlerSetProperty("onESC", menu->data->onESC); - WriteMenuEventHandlerSetProperty("onFocusDueToClose", menu->data->onFocusDueToClose); - WriteItemKeyHandlerProperty(menu->data->onKey); - WriteItemDefs(menu->items, menu->itemCount); -} - -MenuDumper::MenuDumper(std::ostream& stream) - : AbstractMenuDumper(stream) -{ -} - -void MenuDumper::WriteFunctionDef(const std::string& functionName, const Statement_s* statement) -{ - StartFunctionDefScope(); - - WriteStringProperty("name", functionName); - WriteStatementProperty("value", statement, false); +void MenuDumper::WriteMultiProperties(const itemDef_s *item) const { + if (item->type != ITEM_TYPE_MULTI || item->typeData.multi == nullptr) + return; + + const auto *multiDef = item->typeData.multi; - EndScope(); + if (multiDef->count <= 0) + return; + + WriteStringProperty("dvar", item->dvar); + WriteStringProperty("localvar", item->localVar); + WriteMultiValueProperty(multiDef); } -void MenuDumper::WriteMenu(const menuDef_t* menu) -{ - StartMenuDefScope(); +void MenuDumper::WriteEnumDvarProperties(const itemDef_s *item) const { + if (item->type != ITEM_TYPE_DVARENUM) + return; + + WriteStringProperty("dvar", item->dvar); + WriteStringProperty("localvar", item->localVar); + WriteStringProperty("dvarEnumList", item->typeData.enumDvarName); +} + +void MenuDumper::WriteTickerProperties(const itemDef_s *item) const { + if (item->type != ITEM_TYPE_NEWS_TICKER || item->typeData.ticker == nullptr) + return; - WriteMenuData(menu); + const auto *newsTickerDef = item->typeData.ticker; + WriteIntProperty("spacing", newsTickerDef->spacing, 0); + WriteIntProperty("speed", newsTickerDef->speed, 0); + WriteIntProperty("newsfeed", newsTickerDef->feedId, 0); +} + +void MenuDumper::WriteItemData(const itemDef_s *item) { + WriteStringProperty("name", item->window.name); + WriteStringProperty("text", item->text); + WriteKeywordProperty("textsavegame", item->itemFlags & ITEM_FLAG_SAVE_GAME_INFO); + WriteKeywordProperty("textcinematicsubtitle", item->itemFlags & ITEM_FLAG_CINEMATIC_SUBTITLE); + WriteStringProperty("group", item->window.group); + WriteRectProperty("rect", item->window.rectClient); + WriteIntProperty("style", item->window.style, 0); + WriteKeywordProperty("decoration", item->window.staticFlags & WINDOW_FLAG_DECORATION); + WriteKeywordProperty("autowrapped", item->window.staticFlags & WINDOW_FLAG_AUTO_WRAPPED); + WriteKeywordProperty("horizontalscroll", item->window.staticFlags & WINDOW_FLAG_HORIZONTAL_SCROLL); + WriteIntProperty("type", item->type, ITEM_TYPE_TEXT); + WriteIntProperty("border", item->window.border, 0); + WriteFloatProperty("borderSize", item->window.borderSize, 0.0f); + + if (item->visibleExp) + WriteStatementProperty("visible", item->visibleExp, true); + else if (item->window.dynamicFlags[0] & WINDOW_FLAG_VISIBLE) + WriteIntProperty("visible", 1, 0); + + WriteStatementProperty("disabled", item->disabledExp, true); + WriteIntProperty("ownerdraw", item->window.ownerDraw, 0); + WriteFlagsProperty("ownerdrawFlag", item->window.ownerDrawFlags); + WriteIntProperty("align", item->alignment, 0); + WriteIntProperty("textalign", item->textAlignMode, 0); + WriteFloatProperty("textalignx", item->textalignx, 0.0f); + WriteFloatProperty("textaligny", item->textaligny, 0.0f); + WriteFloatProperty("textscale", item->textscale, 0.0f); + WriteIntProperty("textstyle", item->textStyle, 0); + WriteIntProperty("textfont", item->fontEnum, 0); + WriteColorProperty("backcolor", item->window.backColor, COLOR_0000); + WriteColorProperty("forecolor", item->window.foreColor, COLOR_1111); + WriteColorProperty("bordercolor", item->window.borderColor, COLOR_0000); + WriteColorProperty("outlinecolor", item->window.outlineColor, COLOR_0000); + WriteColorProperty("disablecolor", item->window.disableColor, COLOR_0000); + WriteColorProperty("glowcolor", item->glowColor, COLOR_0000); + WriteMaterialProperty("background", item->window.background); + WriteMenuEventHandlerSetProperty("onFocus", item->onFocus); + WriteMenuEventHandlerSetProperty("hasFocus", item->hasFocus); + WriteMenuEventHandlerSetProperty("leaveFocus", item->leaveFocus); + WriteMenuEventHandlerSetProperty("mouseEnter", item->mouseEnter); + WriteMenuEventHandlerSetProperty("mouseExit", item->mouseExit); + WriteMenuEventHandlerSetProperty("mouseEnterText", item->mouseEnterText); + WriteMenuEventHandlerSetProperty("mouseExitText", item->mouseExitText); + WriteMenuEventHandlerSetProperty("action", item->action); + WriteMenuEventHandlerSetProperty("accept", item->accept); + // WriteFloatProperty("special", item->special, 0.0f); + WriteSoundAliasProperty("focusSound", item->focusSound); + WriteStringProperty("dvarTest", item->dvarTest); + + if (item->dvarFlags & ITEM_DVAR_FLAG_ENABLE) + WriteMultiTokenStringProperty("enableDvar", item->enableDvar); + else if (item->dvarFlags & ITEM_DVAR_FLAG_DISABLE) + WriteMultiTokenStringProperty("disableDvar", item->enableDvar); + else if (item->dvarFlags & ITEM_DVAR_FLAG_SHOW) + WriteMultiTokenStringProperty("showDvar", item->enableDvar); + else if (item->dvarFlags & ITEM_DVAR_FLAG_HIDE) + WriteMultiTokenStringProperty("hideDvar", item->enableDvar); + else if (item->dvarFlags & ITEM_DVAR_FLAG_FOCUS) + WriteMultiTokenStringProperty("focusDvar", item->enableDvar); + + WriteItemKeyHandlerProperty(item->onKey); + WriteStatementProperty("exp text", item->textExp, false); + WriteStatementProperty("exp textaligny", item->textAlignYExp, false); + WriteStatementProperty("exp material", item->materialExp, false); + WriteStatementProperty("exp disabled", item->disabledExp, false); + WriteFloatExpressionsProperty(item->floatExpressions, item->floatExpressionCount); + WriteIntProperty("gamemsgwindowindex", item->gameMsgWindowIndex, 0); + WriteIntProperty("gamemsgwindowmode", item->gameMsgWindowMode, 0); + WriteDecodeEffectProperty("decodeEffect", item); + + WriteListBoxProperties(item); + WriteEditFieldProperties(item); + WriteMultiProperties(item); + WriteEnumDvarProperties(item); + WriteTickerProperties(item); +} + +void MenuDumper::WriteItemDefs(const itemDef_s *const *itemDefs, size_t itemCount) { + for (auto i = 0u; i < itemCount; i++) { + StartItemDefScope(); + + WriteItemData(itemDefs[i]); EndScope(); + } +} + +void MenuDumper::WriteMenuData(const menuDef_t *menu) { + WriteStringProperty("name", menu->window.name); + WriteBoolProperty("fullscreen", menu->data->fullScreen, false); + WriteKeywordProperty("screenSpace", menu->window.staticFlags & WINDOW_FLAG_SCREEN_SPACE); + WriteKeywordProperty("decoration", menu->window.staticFlags & WINDOW_FLAG_DECORATION); + WriteRectProperty("rect", menu->window.rect); + WriteIntProperty("style", menu->window.style, 0); + WriteIntProperty("border", menu->window.border, 0); + WriteFloatProperty("borderSize", menu->window.borderSize, 0.0f); + WriteColorProperty("backcolor", menu->window.backColor, COLOR_0000); + WriteColorProperty("forecolor", menu->window.foreColor, COLOR_1111); + WriteColorProperty("bordercolor", menu->window.borderColor, COLOR_0000); + WriteColorProperty("focuscolor", menu->data->focusColor, COLOR_0000); + WriteColorProperty("outlinecolor", menu->window.outlineColor, COLOR_0000); + WriteMaterialProperty("background", menu->window.background); + WriteIntProperty("ownerdraw", menu->window.ownerDraw, 0); + WriteFlagsProperty("ownerdrawFlag", menu->window.ownerDrawFlags); + WriteKeywordProperty("outOfBoundsClick", menu->window.staticFlags & WINDOW_FLAG_OUT_OF_BOUNDS_CLICK); + WriteStringProperty("soundLoop", menu->data->soundName); + WriteKeywordProperty("popup", menu->window.staticFlags & WINDOW_FLAG_POPUP); + WriteFloatProperty("fadeClamp", menu->data->fadeClamp, 0.0f); + WriteIntProperty("fadeCycle", menu->data->fadeCycle, 0); + WriteFloatProperty("fadeAmount", menu->data->fadeAmount, 0.0f); + WriteFloatProperty("fadeInAmount", menu->data->fadeInAmount, 0.0f); + WriteFloatProperty("blurWorld", menu->data->blurRadius, 0.0f); + WriteKeywordProperty("legacySplitScreenScale", menu->window.staticFlags & WINDOW_FLAG_LEGACY_SPLIT_SCREEN_SCALE); + WriteKeywordProperty("hiddenDuringScope", menu->window.staticFlags & WINDOW_FLAG_HIDDEN_DURING_SCOPE); + WriteKeywordProperty("hiddenDuringFlashbang", menu->window.staticFlags & WINDOW_FLAG_HIDDEN_DURING_FLASH_BANG); + WriteKeywordProperty("hiddenDuringUI", menu->window.staticFlags & WINDOW_FLAG_HIDDEN_DURING_UI); + WriteStringProperty("allowedBinding", menu->data->allowedBinding); + WriteKeywordProperty("textOnlyFocus", menu->window.staticFlags & WINDOW_FLAG_TEXT_ONLY_FOCUS); + + if (menu->data->visibleExp) + WriteStatementProperty("visible", menu->data->visibleExp, true); + else if (menu->window.dynamicFlags[0] & WINDOW_FLAG_VISIBLE) + WriteIntProperty("visible", 1, 0); + + WriteStatementProperty("exp rect X", menu->data->rectXExp, false); + WriteStatementProperty("exp rect Y", menu->data->rectYExp, false); + WriteStatementProperty("exp rect W", menu->data->rectWExp, false); + WriteStatementProperty("exp rect H", menu->data->rectHExp, false); + WriteStatementProperty("exp openSound", menu->data->openSoundExp, false); + WriteStatementProperty("exp closeSound", menu->data->closeSoundExp, false); + WriteStatementProperty("exp soundLoop", menu->data->soundLoopExp, false); + WriteMenuEventHandlerSetProperty("onOpen", menu->data->onOpen); + WriteMenuEventHandlerSetProperty("onClose", menu->data->onClose); + WriteMenuEventHandlerSetProperty("onRequestClose", menu->data->onCloseRequest); + WriteMenuEventHandlerSetProperty("onESC", menu->data->onESC); + WriteMenuEventHandlerSetProperty("onFocusDueToClose", menu->data->onFocusDueToClose); + WriteItemKeyHandlerProperty(menu->data->onKey); + WriteItemDefs(menu->items, menu->itemCount); +} + +MenuDumper::MenuDumper(std::ostream &stream) : AbstractMenuDumper(stream) {} + +void MenuDumper::WriteFunctionDef(const std::string &functionName, const Statement_s *statement) { + StartFunctionDefScope(); + + WriteStringProperty("name", functionName); + WriteStatementProperty("value", statement, false); + + EndScope(); +} + +void MenuDumper::WriteMenu(const menuDef_t *menu) { + StartMenuDefScope(); + + WriteMenuData(menu); + + EndScope(); } diff --git a/src/ObjWriting/Game/IW5/Menu/MenuDumperIW5.h b/src/ObjWriting/Game/IW5/Menu/MenuDumperIW5.h index b9fe76a88..898d89024 100644 --- a/src/ObjWriting/Game/IW5/Menu/MenuDumperIW5.h +++ b/src/ObjWriting/Game/IW5/Menu/MenuDumperIW5.h @@ -2,54 +2,52 @@ #include <string> -#include "Menu/AbstractMenuDumper.h" #include "Game/IW5/IW5.h" +#include "Menu/AbstractMenuDumper.h" -namespace IW5 -{ - class MenuDumper : public AbstractMenuDumper - { - static size_t FindStatementClosingParenthesis(const Statement_s* statement, size_t openingParenthesisPosition); - - void WriteStatementOperator(const Statement_s* statement, size_t& currentPos, bool& spaceNext) const; - void WriteStatementOperandFunction(const Statement_s* statement, size_t currentPos) const; - void WriteStatementOperand(const Statement_s* statement, size_t& currentPos, bool& spaceNext) const; - void WriteStatementEntryRange(const Statement_s* statement, size_t startOffset, size_t endOffset) const; - void WriteStatement(const Statement_s* statement) const; - void WriteStatementSkipInitialUnnecessaryParenthesis(const Statement_s* statementValue) const; - void WriteStatementProperty(const std::string& propertyKey, const Statement_s* statementValue, bool isBooleanStatement) const; - - void WriteSetLocalVarData(const std::string& setFunction, const SetLocalVarData* setLocalVarData) const; - void WriteUnconditionalScript(const char* script) const; - void WriteMenuEventHandlerSet(const MenuEventHandlerSet* eventHandlerSet); - void WriteMenuEventHandlerSetProperty(const std::string& propertyKey, const MenuEventHandlerSet* eventHandlerSetValue); - - void WriteRectProperty(const std::string& propertyKey, const rectDef_s& rect) const; - void WriteMaterialProperty(const std::string& propertyKey, const Material* materialValue) const; - void WriteSoundAliasProperty(const std::string& propertyKey, const snd_alias_list_t* soundAliasValue) const; - void WriteDecodeEffectProperty(const std::string& propertyKey, const itemDef_s* item) const; - void WriteItemKeyHandlerProperty(const ItemKeyHandler* itemKeyHandlerValue); - void WriteMultiTokenStringProperty(const std::string& propertyKey, const char* value) const; - void WriteFloatExpressionsProperty(const ItemFloatExpression* floatExpressions, int floatExpressionCount) const; - void WriteColumnProperty(const std::string& propertyKey, const listBoxDef_s* listBox) const; - - void WriteListBoxProperties(const itemDef_s* item); - void WriteDvarFloatProperty(const std::string& propertyKey, const itemDef_s* item, const editFieldDef_s* editField) const; - void WriteEditFieldProperties(const itemDef_s* item) const; - void WriteMultiValueProperty(const multiDef_s* multiDef) const; - void WriteMultiProperties(const itemDef_s* item) const; - void WriteEnumDvarProperties(const itemDef_s* item) const; - void WriteTickerProperties(const itemDef_s* item) const; - - void WriteItemData(const itemDef_s* item); - void WriteItemDefs(const itemDef_s* const* itemDefs, size_t itemCount); - - void WriteMenuData(const menuDef_t* menu); - - public: - explicit MenuDumper(std::ostream& stream); - - void WriteFunctionDef(const std::string& functionName, const Statement_s* statement); - void WriteMenu(const menuDef_t* menu); - }; -} +namespace IW5 { +class MenuDumper : public AbstractMenuDumper { + static size_t FindStatementClosingParenthesis(const Statement_s *statement, size_t openingParenthesisPosition); + + void WriteStatementOperator(const Statement_s *statement, size_t ¤tPos, bool &spaceNext) const; + void WriteStatementOperandFunction(const Statement_s *statement, size_t currentPos) const; + void WriteStatementOperand(const Statement_s *statement, size_t ¤tPos, bool &spaceNext) const; + void WriteStatementEntryRange(const Statement_s *statement, size_t startOffset, size_t endOffset) const; + void WriteStatement(const Statement_s *statement) const; + void WriteStatementSkipInitialUnnecessaryParenthesis(const Statement_s *statementValue) const; + void WriteStatementProperty(const std::string &propertyKey, const Statement_s *statementValue, bool isBooleanStatement) const; + + void WriteSetLocalVarData(const std::string &setFunction, const SetLocalVarData *setLocalVarData) const; + void WriteUnconditionalScript(const char *script) const; + void WriteMenuEventHandlerSet(const MenuEventHandlerSet *eventHandlerSet); + void WriteMenuEventHandlerSetProperty(const std::string &propertyKey, const MenuEventHandlerSet *eventHandlerSetValue); + + void WriteRectProperty(const std::string &propertyKey, const rectDef_s &rect) const; + void WriteMaterialProperty(const std::string &propertyKey, const Material *materialValue) const; + void WriteSoundAliasProperty(const std::string &propertyKey, const snd_alias_list_t *soundAliasValue) const; + void WriteDecodeEffectProperty(const std::string &propertyKey, const itemDef_s *item) const; + void WriteItemKeyHandlerProperty(const ItemKeyHandler *itemKeyHandlerValue); + void WriteMultiTokenStringProperty(const std::string &propertyKey, const char *value) const; + void WriteFloatExpressionsProperty(const ItemFloatExpression *floatExpressions, int floatExpressionCount) const; + void WriteColumnProperty(const std::string &propertyKey, const listBoxDef_s *listBox) const; + + void WriteListBoxProperties(const itemDef_s *item); + void WriteDvarFloatProperty(const std::string &propertyKey, const itemDef_s *item, const editFieldDef_s *editField) const; + void WriteEditFieldProperties(const itemDef_s *item) const; + void WriteMultiValueProperty(const multiDef_s *multiDef) const; + void WriteMultiProperties(const itemDef_s *item) const; + void WriteEnumDvarProperties(const itemDef_s *item) const; + void WriteTickerProperties(const itemDef_s *item) const; + + void WriteItemData(const itemDef_s *item); + void WriteItemDefs(const itemDef_s *const *itemDefs, size_t itemCount); + + void WriteMenuData(const menuDef_t *menu); + +public: + explicit MenuDumper(std::ostream &stream); + + void WriteFunctionDef(const std::string &functionName, const Statement_s *statement); + void WriteMenu(const menuDef_t *menu); +}; +} // namespace IW5 diff --git a/src/ObjWriting/Game/IW5/ZoneDumperIW5.cpp b/src/ObjWriting/Game/IW5/ZoneDumperIW5.cpp index 32f4579b6..385f71ee0 100644 --- a/src/ObjWriting/Game/IW5/ZoneDumperIW5.cpp +++ b/src/ObjWriting/Game/IW5/ZoneDumperIW5.cpp @@ -1,8 +1,8 @@ #include "ZoneDumperIW5.h" -#include "ObjWriting.h" -#include "Game/IW5/GameIW5.h" #include "Game/IW5/GameAssetPoolIW5.h" +#include "Game/IW5/GameIW5.h" +#include "ObjWriting.h" #include "AssetDumpers/AssetDumperAddonMapEnts.h" #include "AssetDumpers/AssetDumperGfxImage.h" @@ -16,63 +16,58 @@ using namespace IW5; -bool ZoneDumper::CanHandleZone(AssetDumpingContext& context) const -{ - return context.m_zone->m_game == &g_GameIW5; -} +bool ZoneDumper::CanHandleZone(AssetDumpingContext &context) const { return context.m_zone->m_game == &g_GameIW5; } -bool ZoneDumper::DumpZone(AssetDumpingContext& context) const -{ -#define DUMP_ASSET_POOL(dumperType, poolName, assetType) \ - if(assetPools->poolName && ObjWriting::ShouldHandleAssetType(assetType)) \ - { \ - dumperType dumper; \ - dumper.DumpPool(context, assetPools->poolName.get()); \ - } +bool ZoneDumper::DumpZone(AssetDumpingContext &context) const { +#define DUMP_ASSET_POOL(dumperType, poolName, assetType) \ + if (assetPools->poolName && ObjWriting::ShouldHandleAssetType(assetType)) { \ + dumperType dumper; \ + dumper.DumpPool(context, assetPools->poolName.get()); \ + } - const auto* assetPools = dynamic_cast<GameAssetPoolIW5*>(context.m_zone->m_pools.get()); - // DUMP_ASSET_POOL(AssetDumperPhysPreset, m_phys_preset, ASSET_TYPE_PHYSPRESET) - // DUMP_ASSET_POOL(AssetDumperPhysCollmap, m_phys_collmap, ASSET_TYPE_PHYSCOLLMAP) - // DUMP_ASSET_POOL(AssetDumperXAnimParts, m_xanim_parts, ASSET_TYPE_XANIMPARTS) - // DUMP_ASSET_POOL(AssetDumperXModelSurfs, m_xmodel_surfs, ASSET_TYPE_XMODEL_SURFS) - DUMP_ASSET_POOL(AssetDumperXModel, m_xmodel, ASSET_TYPE_XMODEL) - // DUMP_ASSET_POOL(AssetDumperMaterial, m_material, ASSET_TYPE_MATERIAL) - // DUMP_ASSET_POOL(AssetDumperMaterialPixelShader, m_material_pixel_shader, ASSET_TYPE_PIXELSHADER) - // DUMP_ASSET_POOL(AssetDumperMaterialVertexShader, m_material_vertex_shader, ASSET_TYPE_VERTEXSHADER) - // DUMP_ASSET_POOL(AssetDumperMaterialVertexDeclaration, m_material_vertex_decl, ASSET_TYPE_VERTEXDECL) - // DUMP_ASSET_POOL(AssetDumperMaterialTechniqueSet, m_technique_set, ASSET_TYPE_TECHNIQUE_SET) - DUMP_ASSET_POOL(AssetDumperGfxImage, m_image, ASSET_TYPE_IMAGE) - // DUMP_ASSET_POOL(AssetDumpersnd_alias_list_t, m_sound, ASSET_TYPE_SOUND) - // DUMP_ASSET_POOL(AssetDumperSndCurve, m_sound_curve, ASSET_TYPE_SOUND_CURVE) - DUMP_ASSET_POOL(AssetDumperLoadedSound, m_loaded_sound, ASSET_TYPE_LOADED_SOUND) - // DUMP_ASSET_POOL(AssetDumperclipMap_t, m_clip_map, ASSET_TYPE_CLIPMAP) - // DUMP_ASSET_POOL(AssetDumperComWorld, m_com_world, ASSET_TYPE_COMWORLD) - // DUMP_ASSET_POOL(AssetDumperGlassWorld, m_glass_world, ASSET_TYPE_GLASSWORLD) - // DUMP_ASSET_POOL(AssetDumperPathData, m_path_data, ASSET_TYPE_PATHDATA) - // DUMP_ASSET_POOL(AssetDumperVehicleTrack, m_vehicle_track, ASSET_TYPE_VEHICLE_TRACK) - // DUMP_ASSET_POOL(AssetDumperMapEnts, m_map_ents, ASSET_TYPE_MAP_ENTS) - // DUMP_ASSET_POOL(AssetDumperFxWorld, m_fx_world, ASSET_TYPE_FXWORLD) - // DUMP_ASSET_POOL(AssetDumperGfxWorld, m_gfx_world, ASSET_TYPE_GFXWORLD) - // DUMP_ASSET_POOL(AssetDumperGfxLightDef, m_gfx_light_def, ASSET_TYPE_LIGHT_DEF) - // DUMP_ASSET_POOL(AssetDumperFont_s, m_font, ASSET_TYPE_FONT) - DUMP_ASSET_POOL(AssetDumperMenuList, m_menu_list, ASSET_TYPE_MENULIST) - DUMP_ASSET_POOL(AssetDumperMenuDef, m_menu_def, ASSET_TYPE_MENU) - DUMP_ASSET_POOL(AssetDumperLocalizeEntry, m_localize, ASSET_TYPE_LOCALIZE_ENTRY) - // DUMP_ASSET_POOL(AssetDumperWeaponAttachment, m_attachment, ASSET_TYPE_ATTACHMENT) - // DUMP_ASSET_POOL(AssetDumperWeaponCompleteDef, m_weapon, ASSET_TYPE_WEAPON) - // DUMP_ASSET_POOL(AssetDumperFxEffectDef, m_fx, ASSET_TYPE_FX) - // DUMP_ASSET_POOL(AssetDumperFxImpactTable, m_fx_impact_table, ASSET_TYPE_IMPACT_FX) - // DUMP_ASSET_POOL(AssetDumperSurfaceFxTable, m_surface_fx_table, ASSET_TYPE_SURFACE_FX) - DUMP_ASSET_POOL(AssetDumperRawFile, m_raw_file, ASSET_TYPE_RAWFILE) - // DUMP_ASSET_POOL(AssetDumperScriptFile, m_script_file, ASSET_TYPE_SCRIPTFILE) - DUMP_ASSET_POOL(AssetDumperStringTable, m_string_table, ASSET_TYPE_STRINGTABLE) - // DUMP_ASSET_POOL(AssetDumperLeaderboardDef, m_leaderboard, ASSET_TYPE_LEADERBOARD) - // DUMP_ASSET_POOL(AssetDumperStructuredDataDefSet, m_structed_data_def_set, ASSET_TYPE_STRUCTURED_DATA_DEF) - // DUMP_ASSET_POOL(AssetDumperTracerDef, m_tracer, ASSET_TYPE_TRACER) - // DUMP_ASSET_POOL(AssetDumperVehicleDef, m_vehicle, ASSET_TYPE_VEHICLE) - DUMP_ASSET_POOL(AssetDumperAddonMapEnts, m_addon_map_ents, ASSET_TYPE_ADDON_MAP_ENTS) + const auto *assetPools = dynamic_cast<GameAssetPoolIW5 *>(context.m_zone->m_pools.get()); + // DUMP_ASSET_POOL(AssetDumperPhysPreset, m_phys_preset, ASSET_TYPE_PHYSPRESET) + // DUMP_ASSET_POOL(AssetDumperPhysCollmap, m_phys_collmap, ASSET_TYPE_PHYSCOLLMAP) + // DUMP_ASSET_POOL(AssetDumperXAnimParts, m_xanim_parts, ASSET_TYPE_XANIMPARTS) + // DUMP_ASSET_POOL(AssetDumperXModelSurfs, m_xmodel_surfs, ASSET_TYPE_XMODEL_SURFS) + DUMP_ASSET_POOL(AssetDumperXModel, m_xmodel, ASSET_TYPE_XMODEL) + // DUMP_ASSET_POOL(AssetDumperMaterial, m_material, ASSET_TYPE_MATERIAL) + // DUMP_ASSET_POOL(AssetDumperMaterialPixelShader, m_material_pixel_shader, ASSET_TYPE_PIXELSHADER) + // DUMP_ASSET_POOL(AssetDumperMaterialVertexShader, m_material_vertex_shader, ASSET_TYPE_VERTEXSHADER) + // DUMP_ASSET_POOL(AssetDumperMaterialVertexDeclaration, m_material_vertex_decl, ASSET_TYPE_VERTEXDECL) + // DUMP_ASSET_POOL(AssetDumperMaterialTechniqueSet, m_technique_set, ASSET_TYPE_TECHNIQUE_SET) + DUMP_ASSET_POOL(AssetDumperGfxImage, m_image, ASSET_TYPE_IMAGE) + // DUMP_ASSET_POOL(AssetDumpersnd_alias_list_t, m_sound, ASSET_TYPE_SOUND) + // DUMP_ASSET_POOL(AssetDumperSndCurve, m_sound_curve, ASSET_TYPE_SOUND_CURVE) + DUMP_ASSET_POOL(AssetDumperLoadedSound, m_loaded_sound, ASSET_TYPE_LOADED_SOUND) + // DUMP_ASSET_POOL(AssetDumperclipMap_t, m_clip_map, ASSET_TYPE_CLIPMAP) + // DUMP_ASSET_POOL(AssetDumperComWorld, m_com_world, ASSET_TYPE_COMWORLD) + // DUMP_ASSET_POOL(AssetDumperGlassWorld, m_glass_world, ASSET_TYPE_GLASSWORLD) + // DUMP_ASSET_POOL(AssetDumperPathData, m_path_data, ASSET_TYPE_PATHDATA) + // DUMP_ASSET_POOL(AssetDumperVehicleTrack, m_vehicle_track, ASSET_TYPE_VEHICLE_TRACK) + // DUMP_ASSET_POOL(AssetDumperMapEnts, m_map_ents, ASSET_TYPE_MAP_ENTS) + // DUMP_ASSET_POOL(AssetDumperFxWorld, m_fx_world, ASSET_TYPE_FXWORLD) + // DUMP_ASSET_POOL(AssetDumperGfxWorld, m_gfx_world, ASSET_TYPE_GFXWORLD) + // DUMP_ASSET_POOL(AssetDumperGfxLightDef, m_gfx_light_def, ASSET_TYPE_LIGHT_DEF) + // DUMP_ASSET_POOL(AssetDumperFont_s, m_font, ASSET_TYPE_FONT) + DUMP_ASSET_POOL(AssetDumperMenuList, m_menu_list, ASSET_TYPE_MENULIST) + DUMP_ASSET_POOL(AssetDumperMenuDef, m_menu_def, ASSET_TYPE_MENU) + DUMP_ASSET_POOL(AssetDumperLocalizeEntry, m_localize, ASSET_TYPE_LOCALIZE_ENTRY) + // DUMP_ASSET_POOL(AssetDumperWeaponAttachment, m_attachment, ASSET_TYPE_ATTACHMENT) + // DUMP_ASSET_POOL(AssetDumperWeaponCompleteDef, m_weapon, ASSET_TYPE_WEAPON) + // DUMP_ASSET_POOL(AssetDumperFxEffectDef, m_fx, ASSET_TYPE_FX) + // DUMP_ASSET_POOL(AssetDumperFxImpactTable, m_fx_impact_table, ASSET_TYPE_IMPACT_FX) + // DUMP_ASSET_POOL(AssetDumperSurfaceFxTable, m_surface_fx_table, ASSET_TYPE_SURFACE_FX) + DUMP_ASSET_POOL(AssetDumperRawFile, m_raw_file, ASSET_TYPE_RAWFILE) + // DUMP_ASSET_POOL(AssetDumperScriptFile, m_script_file, ASSET_TYPE_SCRIPTFILE) + DUMP_ASSET_POOL(AssetDumperStringTable, m_string_table, ASSET_TYPE_STRINGTABLE) + // DUMP_ASSET_POOL(AssetDumperLeaderboardDef, m_leaderboard, ASSET_TYPE_LEADERBOARD) + // DUMP_ASSET_POOL(AssetDumperStructuredDataDefSet, m_structed_data_def_set, ASSET_TYPE_STRUCTURED_DATA_DEF) + // DUMP_ASSET_POOL(AssetDumperTracerDef, m_tracer, ASSET_TYPE_TRACER) + // DUMP_ASSET_POOL(AssetDumperVehicleDef, m_vehicle, ASSET_TYPE_VEHICLE) + DUMP_ASSET_POOL(AssetDumperAddonMapEnts, m_addon_map_ents, ASSET_TYPE_ADDON_MAP_ENTS) - return true; + return true; #undef DUMP_ASSET_POOL } diff --git a/src/ObjWriting/Game/IW5/ZoneDumperIW5.h b/src/ObjWriting/Game/IW5/ZoneDumperIW5.h index 6291a5a94..eceec4474 100644 --- a/src/ObjWriting/Game/IW5/ZoneDumperIW5.h +++ b/src/ObjWriting/Game/IW5/ZoneDumperIW5.h @@ -1,12 +1,10 @@ #pragma once #include "Dumping/IZoneDumper.h" -namespace IW5 -{ - class ZoneDumper final : public IZoneDumper - { - public: - bool CanHandleZone(AssetDumpingContext& context) const override; - bool DumpZone(AssetDumpingContext& context) const override; - }; -} +namespace IW5 { +class ZoneDumper final : public IZoneDumper { +public: + bool CanHandleZone(AssetDumpingContext &context) const override; + bool DumpZone(AssetDumpingContext &context) const override; +}; +} // namespace IW5 diff --git a/src/ObjWriting/Game/T5/AssetDumpers/AssetDumperGfxImage.cpp b/src/ObjWriting/Game/T5/AssetDumpers/AssetDumperGfxImage.cpp index 745784d10..5966f3516 100644 --- a/src/ObjWriting/Game/T5/AssetDumpers/AssetDumperGfxImage.cpp +++ b/src/ObjWriting/Game/T5/AssetDumpers/AssetDumperGfxImage.cpp @@ -2,62 +2,55 @@ #include <cassert> -#include "ObjWriting.h" -#include "Image/IwiWriter27.h" #include "Image/DdsWriter.h" +#include "Image/IwiWriter27.h" +#include "ObjWriting.h" using namespace T5; -AssetDumperGfxImage::AssetDumperGfxImage() -{ - switch (ObjWriting::Configuration.ImageOutputFormat) - { - case ObjWriting::Configuration_t::ImageOutputFormat_e::DDS: - m_writer = std::make_unique<DdsWriter>(); - break; - case ObjWriting::Configuration_t::ImageOutputFormat_e::IWI: - m_writer = std::make_unique<iwi27::IwiWriter>(); - break; - default: - assert(false); - m_writer = nullptr; - break; - } +AssetDumperGfxImage::AssetDumperGfxImage() { + switch (ObjWriting::Configuration.ImageOutputFormat) { + case ObjWriting::Configuration_t::ImageOutputFormat_e::DDS: + m_writer = std::make_unique<DdsWriter>(); + break; + case ObjWriting::Configuration_t::ImageOutputFormat_e::IWI: + m_writer = std::make_unique<iwi27::IwiWriter>(); + break; + default: + assert(false); + m_writer = nullptr; + break; + } } -bool AssetDumperGfxImage::ShouldDump(XAssetInfo<GfxImage>* asset) -{ - const auto* image = asset->Asset(); - return image->loadedSize > 0; +bool AssetDumperGfxImage::ShouldDump(XAssetInfo<GfxImage> *asset) { + const auto *image = asset->Asset(); + return image->loadedSize > 0; } -std::string AssetDumperGfxImage::GetAssetFileName(XAssetInfo<GfxImage>* asset) const -{ - std::string cleanAssetName = asset->m_name; - for (auto& c : cleanAssetName) - { - switch (c) - { - case '*': - c = '_'; - break; - - default: - break; - } +std::string AssetDumperGfxImage::GetAssetFileName(XAssetInfo<GfxImage> *asset) const { + std::string cleanAssetName = asset->m_name; + for (auto &c : cleanAssetName) { + switch (c) { + case '*': + c = '_'; + break; + + default: + break; } + } - return "images/" + cleanAssetName + m_writer->GetFileExtension(); + return "images/" + cleanAssetName + m_writer->GetFileExtension(); } -void AssetDumperGfxImage::DumpAsset(AssetDumpingContext& context, XAssetInfo<GfxImage>* asset) -{ - const auto* image = asset->Asset(); - const auto assetFile = context.OpenAssetFile(GetAssetFileName(asset)); +void AssetDumperGfxImage::DumpAsset(AssetDumpingContext &context, XAssetInfo<GfxImage> *asset) { + const auto *image = asset->Asset(); + const auto assetFile = context.OpenAssetFile(GetAssetFileName(asset)); - if (!assetFile) - return; + if (!assetFile) + return; - auto& stream = *assetFile; - m_writer->DumpImage(stream, image->texture.texture); + auto &stream = *assetFile; + m_writer->DumpImage(stream, image->texture.texture); } diff --git a/src/ObjWriting/Game/T5/AssetDumpers/AssetDumperGfxImage.h b/src/ObjWriting/Game/T5/AssetDumpers/AssetDumperGfxImage.h index 4bbe63a88..2ea9fa0b3 100644 --- a/src/ObjWriting/Game/T5/AssetDumpers/AssetDumperGfxImage.h +++ b/src/ObjWriting/Game/T5/AssetDumpers/AssetDumperGfxImage.h @@ -6,19 +6,17 @@ #include "Game/T5/T5.h" #include "Image/IImageWriter.h" -namespace T5 -{ - class AssetDumperGfxImage final : public AbstractAssetDumper<GfxImage> - { - std::unique_ptr<IImageWriter> m_writer; +namespace T5 { +class AssetDumperGfxImage final : public AbstractAssetDumper<GfxImage> { + std::unique_ptr<IImageWriter> m_writer; - std::string GetAssetFileName(XAssetInfo<GfxImage>* asset) const; + std::string GetAssetFileName(XAssetInfo<GfxImage> *asset) const; - protected: - bool ShouldDump(XAssetInfo<GfxImage>* asset) override; - void DumpAsset(AssetDumpingContext& context, XAssetInfo<GfxImage>* asset) override; +protected: + bool ShouldDump(XAssetInfo<GfxImage> *asset) override; + void DumpAsset(AssetDumpingContext &context, XAssetInfo<GfxImage> *asset) override; - public: - AssetDumperGfxImage(); - }; -} +public: + AssetDumperGfxImage(); +}; +} // namespace T5 diff --git a/src/ObjWriting/Game/T5/AssetDumpers/AssetDumperLocalizeEntry.cpp b/src/ObjWriting/Game/T5/AssetDumpers/AssetDumperLocalizeEntry.cpp index 0d7d6717a..707376de2 100644 --- a/src/ObjWriting/Game/T5/AssetDumpers/AssetDumperLocalizeEntry.cpp +++ b/src/ObjWriting/Game/T5/AssetDumpers/AssetDumperLocalizeEntry.cpp @@ -2,42 +2,37 @@ #include <sstream> -#include "Localize/LocalizeCommon.h" #include "Dumping/Localize/StringFileDumper.h" +#include "Localize/LocalizeCommon.h" using namespace T5; -void AssetDumperLocalizeEntry::DumpPool(AssetDumpingContext& context, AssetPool<LocalizeEntry>* pool) -{ - if (pool->m_asset_lookup.empty()) - return; - - const auto language = LocalizeCommon::GetNameOfLanguage(context.m_zone->m_language); +void AssetDumperLocalizeEntry::DumpPool(AssetDumpingContext &context, AssetPool<LocalizeEntry> *pool) { + if (pool->m_asset_lookup.empty()) + return; - std::ostringstream ss; - ss << language << "/localizedstrings/" << context.m_zone->m_name << ".str"; - const auto assetFile = context.OpenAssetFile(ss.str()); + const auto language = LocalizeCommon::GetNameOfLanguage(context.m_zone->m_language); - if (assetFile) - { - StringFileDumper stringFileDumper(context.m_zone, *assetFile); + std::ostringstream ss; + ss << language << "/localizedstrings/" << context.m_zone->m_name << ".str"; + const auto assetFile = context.OpenAssetFile(ss.str()); - stringFileDumper.SetLanguageName(language); + if (assetFile) { + StringFileDumper stringFileDumper(context.m_zone, *assetFile); - // Magic string. Original string files do have this config file. The purpose of the config file is unknown though. - stringFileDumper.SetConfigFile(R"(C:/projects/cod/t5/bin/StringEd.cfg)"); + stringFileDumper.SetLanguageName(language); - stringFileDumper.SetNotes(""); + // Magic string. Original string files do have this config file. The purpose of the config file is unknown though. + stringFileDumper.SetConfigFile(R"(C:/projects/cod/t5/bin/StringEd.cfg)"); - for (auto* localizeEntry : *pool) - { - stringFileDumper.WriteLocalizeEntry(localizeEntry->m_name, localizeEntry->Asset()->value); - } + stringFileDumper.SetNotes(""); - stringFileDumper.Finalize(); - } - else - { - printf("Could not create string file for dumping localized strings of zone '%s'\n", context.m_zone->m_name.c_str()); + for (auto *localizeEntry : *pool) { + stringFileDumper.WriteLocalizeEntry(localizeEntry->m_name, localizeEntry->Asset()->value); } + + stringFileDumper.Finalize(); + } else { + printf("Could not create string file for dumping localized strings of zone '%s'\n", context.m_zone->m_name.c_str()); + } } \ No newline at end of file diff --git a/src/ObjWriting/Game/T5/AssetDumpers/AssetDumperLocalizeEntry.h b/src/ObjWriting/Game/T5/AssetDumpers/AssetDumperLocalizeEntry.h index 03d4e99f2..281624b39 100644 --- a/src/ObjWriting/Game/T5/AssetDumpers/AssetDumperLocalizeEntry.h +++ b/src/ObjWriting/Game/T5/AssetDumpers/AssetDumperLocalizeEntry.h @@ -3,11 +3,9 @@ #include "Dumping/AbstractAssetDumper.h" #include "Game/T5/T5.h" -namespace T5 -{ - class AssetDumperLocalizeEntry final : public IAssetDumper<LocalizeEntry> - { - public: - void DumpPool(AssetDumpingContext& context, AssetPool<LocalizeEntry>* pool) override; - }; -} +namespace T5 { +class AssetDumperLocalizeEntry final : public IAssetDumper<LocalizeEntry> { +public: + void DumpPool(AssetDumpingContext &context, AssetPool<LocalizeEntry> *pool) override; +}; +} // namespace T5 diff --git a/src/ObjWriting/Game/T5/AssetDumpers/AssetDumperRawFile.cpp b/src/ObjWriting/Game/T5/AssetDumpers/AssetDumperRawFile.cpp index 0c1d883ed..75738541a 100644 --- a/src/ObjWriting/Game/T5/AssetDumpers/AssetDumperRawFile.cpp +++ b/src/ObjWriting/Game/T5/AssetDumpers/AssetDumperRawFile.cpp @@ -8,107 +8,90 @@ using namespace T5; namespace fs = std::filesystem; -void AssetDumperRawFile::DumpGsc(AssetDumpingContext& context, XAssetInfo<RawFile>* asset, std::ostream& stream) -{ - const auto* rawFile = asset->Asset(); - - if (rawFile->len <= 8) - { - std::cout << "Invalid len of gsc file \"" << rawFile->name << "\"" << std::endl; - return; - } +void AssetDumperRawFile::DumpGsc(AssetDumpingContext &context, XAssetInfo<RawFile> *asset, std::ostream &stream) { + const auto *rawFile = asset->Asset(); - const auto outLen = reinterpret_cast<const uint32_t*>(rawFile->buffer)[0]; - const auto inLen = reinterpret_cast<const uint32_t*>(rawFile->buffer)[1]; + if (rawFile->len <= 8) { + std::cout << "Invalid len of gsc file \"" << rawFile->name << "\"" << std::endl; + return; + } - assert(inLen == static_cast<unsigned>(rawFile->len) - 8); + const auto outLen = reinterpret_cast<const uint32_t *>(rawFile->buffer)[0]; + const auto inLen = reinterpret_cast<const uint32_t *>(rawFile->buffer)[1]; - if(inLen > static_cast<unsigned>(rawFile->len - 8) + 1) - { - std::cout << "Invalid compression of gsc file \"" << rawFile->name << "\": " << inLen << std::endl; - return; - } + assert(inLen == static_cast<unsigned>(rawFile->len) - 8); - if(outLen > GSC_MAX_SIZE) - { - std::cout << "Invalid size of gsc file \"" << rawFile->name << "\": " << outLen << std::endl; - return; - } + if (inLen > static_cast<unsigned>(rawFile->len - 8) + 1) { + std::cout << "Invalid compression of gsc file \"" << rawFile->name << "\": " << inLen << std::endl; + return; + } + + if (outLen > GSC_MAX_SIZE) { + std::cout << "Invalid size of gsc file \"" << rawFile->name << "\": " << outLen << std::endl; + return; + } + + z_stream_s zs{}; + + zs.zalloc = Z_NULL; + zs.zfree = Z_NULL; + zs.opaque = Z_NULL; + zs.avail_in = 0; + zs.next_in = Z_NULL; - z_stream_s zs{}; + int ret = inflateInit(&zs); - zs.zalloc = Z_NULL; - zs.zfree = Z_NULL; - zs.opaque = Z_NULL; - zs.avail_in = 0; - zs.next_in = Z_NULL; + if (ret != Z_OK) { + throw std::runtime_error("Initializing inflate failed"); + } - int ret = inflateInit(&zs); + zs.next_in = reinterpret_cast<const Bytef *>(&rawFile->buffer[8]); + zs.avail_in = inLen; - if (ret != Z_OK) - { - throw std::runtime_error("Initializing inflate failed"); + Bytef buffer[0x1000]; + + size_t writtenSize = 0; + while (zs.avail_in > 0) { + zs.next_out = buffer; + zs.avail_out = sizeof buffer; + ret = inflate(&zs, Z_SYNC_FLUSH); + + if (ret < 0) { + std::cout << "Inflate failed for dumping gsc file \"" << rawFile->name << "\"" << std::endl; + inflateEnd(&zs); + return; } - zs.next_in = reinterpret_cast<const Bytef*>(&rawFile->buffer[8]); - zs.avail_in = inLen; - - Bytef buffer[0x1000]; - - size_t writtenSize = 0; - while (zs.avail_in > 0) - { - zs.next_out = buffer; - zs.avail_out = sizeof buffer; - ret = inflate(&zs, Z_SYNC_FLUSH); - - if (ret < 0) - { - std::cout << "Inflate failed for dumping gsc file \"" << rawFile->name << "\"" << std::endl; - inflateEnd(&zs); - return; - } - - const auto inflateOutSize = sizeof buffer - zs.avail_out; - - if(writtenSize + inflateOutSize >= outLen) - { - // Last byte is a \0 byte. Skip it. - stream.write(reinterpret_cast<char*>(buffer), inflateOutSize - 1); - } - else - { - stream.write(reinterpret_cast<char*>(buffer), inflateOutSize); - } - writtenSize += inflateOutSize; + const auto inflateOutSize = sizeof buffer - zs.avail_out; + + if (writtenSize + inflateOutSize >= outLen) { + // Last byte is a \0 byte. Skip it. + stream.write(reinterpret_cast<char *>(buffer), inflateOutSize - 1); + } else { + stream.write(reinterpret_cast<char *>(buffer), inflateOutSize); } + writtenSize += inflateOutSize; + } - inflateEnd(&zs); + inflateEnd(&zs); } -bool AssetDumperRawFile::ShouldDump(XAssetInfo<RawFile>* asset) -{ - return true; -} +bool AssetDumperRawFile::ShouldDump(XAssetInfo<RawFile> *asset) { return true; } -void AssetDumperRawFile::DumpAsset(AssetDumpingContext& context, XAssetInfo<RawFile>* asset) -{ - const auto* rawFile = asset->Asset(); - const auto assetFile = context.OpenAssetFile(asset->m_name); +void AssetDumperRawFile::DumpAsset(AssetDumpingContext &context, XAssetInfo<RawFile> *asset) { + const auto *rawFile = asset->Asset(); + const auto assetFile = context.OpenAssetFile(asset->m_name); - if (!assetFile) - return; + if (!assetFile) + return; - auto& stream = *assetFile; - const fs::path rawFilePath(rawFile->name); - const auto extension = rawFilePath.extension().string(); + auto &stream = *assetFile; + const fs::path rawFilePath(rawFile->name); + const auto extension = rawFilePath.extension().string(); - if (extension == ".gsc" || extension == ".csc") - { - DumpGsc(context, asset, stream); - } - else - { - stream.write(rawFile->buffer, rawFile->len); - } + if (extension == ".gsc" || extension == ".csc") { + DumpGsc(context, asset, stream); + } else { + stream.write(rawFile->buffer, rawFile->len); + } } \ No newline at end of file diff --git a/src/ObjWriting/Game/T5/AssetDumpers/AssetDumperRawFile.h b/src/ObjWriting/Game/T5/AssetDumpers/AssetDumperRawFile.h index de3e8ddc1..758152f8c 100644 --- a/src/ObjWriting/Game/T5/AssetDumpers/AssetDumperRawFile.h +++ b/src/ObjWriting/Game/T5/AssetDumpers/AssetDumperRawFile.h @@ -3,16 +3,14 @@ #include "Dumping/AbstractAssetDumper.h" #include "Game/T5/T5.h" -namespace T5 -{ - class AssetDumperRawFile final : public AbstractAssetDumper<RawFile> - { - constexpr static size_t GSC_MAX_SIZE = 0xC000000; +namespace T5 { +class AssetDumperRawFile final : public AbstractAssetDumper<RawFile> { + constexpr static size_t GSC_MAX_SIZE = 0xC000000; - static void DumpGsc(AssetDumpingContext& context, XAssetInfo<RawFile>* asset, std::ostream& stream); + static void DumpGsc(AssetDumpingContext &context, XAssetInfo<RawFile> *asset, std::ostream &stream); - protected: - bool ShouldDump(XAssetInfo<RawFile>* asset) override; - void DumpAsset(AssetDumpingContext& context, XAssetInfo<RawFile>* asset) override; - }; -} +protected: + bool ShouldDump(XAssetInfo<RawFile> *asset) override; + void DumpAsset(AssetDumpingContext &context, XAssetInfo<RawFile> *asset) override; +}; +} // namespace T5 diff --git a/src/ObjWriting/Game/T5/AssetDumpers/AssetDumperStringTable.cpp b/src/ObjWriting/Game/T5/AssetDumpers/AssetDumperStringTable.cpp index ba164c801..12e97507c 100644 --- a/src/ObjWriting/Game/T5/AssetDumpers/AssetDumperStringTable.cpp +++ b/src/ObjWriting/Game/T5/AssetDumpers/AssetDumperStringTable.cpp @@ -4,29 +4,23 @@ using namespace T5; -bool AssetDumperStringTable::ShouldDump(XAssetInfo<StringTable>* asset) -{ - return true; -} - -void AssetDumperStringTable::DumpAsset(AssetDumpingContext& context, XAssetInfo<StringTable>* asset) -{ - const auto* stringTable = asset->Asset(); - const auto assetFile = context.OpenAssetFile(asset->m_name); - - if (!assetFile) - return; - - CsvOutputStream csv(*assetFile); - - for (auto row = 0; row < stringTable->rowCount; row++) - { - for (auto column = 0; column < stringTable->columnCount; column++) - { - const auto* cell = &stringTable->values[column + row * stringTable->columnCount]; - csv.WriteColumn(cell->string); - } - - csv.NextRow(); +bool AssetDumperStringTable::ShouldDump(XAssetInfo<StringTable> *asset) { return true; } + +void AssetDumperStringTable::DumpAsset(AssetDumpingContext &context, XAssetInfo<StringTable> *asset) { + const auto *stringTable = asset->Asset(); + const auto assetFile = context.OpenAssetFile(asset->m_name); + + if (!assetFile) + return; + + CsvOutputStream csv(*assetFile); + + for (auto row = 0; row < stringTable->rowCount; row++) { + for (auto column = 0; column < stringTable->columnCount; column++) { + const auto *cell = &stringTable->values[column + row * stringTable->columnCount]; + csv.WriteColumn(cell->string); } + + csv.NextRow(); + } } \ No newline at end of file diff --git a/src/ObjWriting/Game/T5/AssetDumpers/AssetDumperStringTable.h b/src/ObjWriting/Game/T5/AssetDumpers/AssetDumperStringTable.h index cbbd86ea9..324b9e047 100644 --- a/src/ObjWriting/Game/T5/AssetDumpers/AssetDumperStringTable.h +++ b/src/ObjWriting/Game/T5/AssetDumpers/AssetDumperStringTable.h @@ -3,12 +3,10 @@ #include "Dumping/AbstractAssetDumper.h" #include "Game/T5/T5.h" -namespace T5 -{ - class AssetDumperStringTable final : public AbstractAssetDumper<StringTable> - { - protected: - bool ShouldDump(XAssetInfo<StringTable>* asset) override; - void DumpAsset(AssetDumpingContext& context, XAssetInfo<StringTable>* asset) override; - }; -} +namespace T5 { +class AssetDumperStringTable final : public AbstractAssetDumper<StringTable> { +protected: + bool ShouldDump(XAssetInfo<StringTable> *asset) override; + void DumpAsset(AssetDumpingContext &context, XAssetInfo<StringTable> *asset) override; +}; +} // namespace T5 diff --git a/src/ObjWriting/Game/T5/AssetDumpers/AssetDumperXModel.cpp b/src/ObjWriting/Game/T5/AssetDumpers/AssetDumperXModel.cpp index 5f41c5702..ea3eb4b9c 100644 --- a/src/ObjWriting/Game/T5/AssetDumpers/AssetDumperXModel.cpp +++ b/src/ObjWriting/Game/T5/AssetDumpers/AssetDumperXModel.cpp @@ -3,640 +3,527 @@ #include <cassert> #include <sstream> -#include "ObjWriting.h" #include "Game/T5/CommonT5.h" #include "Math/Quaternion.h" #include "Model/XModel/XModelExportWriter.h" +#include "ObjWriting.h" #include "Utils/HalfFloat.h" #include "Utils/QuatInt16.h" using namespace T5; -bool AssetDumperXModel::ShouldDump(XAssetInfo<XModel>* asset) -{ - return !asset->m_name.empty() && asset->m_name[0] != ','; -} +bool AssetDumperXModel::ShouldDump(XAssetInfo<XModel> *asset) { return !asset->m_name.empty() && asset->m_name[0] != ','; } -GfxImage* AssetDumperXModel::GetMaterialColorMap(const Material* material) -{ - std::vector<MaterialTextureDef*> potentialTextureDefs; +GfxImage *AssetDumperXModel::GetMaterialColorMap(const Material *material) { + std::vector<MaterialTextureDef *> potentialTextureDefs; - for(auto textureIndex = 0u; textureIndex < material->textureCount; textureIndex++) - { - MaterialTextureDef* def = &material->textureTable[textureIndex]; + for (auto textureIndex = 0u; textureIndex < material->textureCount; textureIndex++) { + MaterialTextureDef *def = &material->textureTable[textureIndex]; - if (def->semantic == TS_COLOR_MAP || def->semantic >= TS_COLOR0_MAP && def->semantic <= TS_COLOR15_MAP) - potentialTextureDefs.push_back(def); - } + if (def->semantic == TS_COLOR_MAP || def->semantic >= TS_COLOR0_MAP && def->semantic <= TS_COLOR15_MAP) + potentialTextureDefs.push_back(def); + } - if (potentialTextureDefs.empty()) - return nullptr; - if (potentialTextureDefs.size() == 1) - return potentialTextureDefs[0]->u.image; + if (potentialTextureDefs.empty()) + return nullptr; + if (potentialTextureDefs.size() == 1) + return potentialTextureDefs[0]->u.image; - for(const auto* def : potentialTextureDefs) - { - if (def->nameStart == 'c' && def->nameEnd == 'p') - return def->u.image; - } + for (const auto *def : potentialTextureDefs) { + if (def->nameStart == 'c' && def->nameEnd == 'p') + return def->u.image; + } - return potentialTextureDefs[0]->u.image; + return potentialTextureDefs[0]->u.image; } -GfxImage* AssetDumperXModel::GetMaterialNormalMap(const Material* material) -{ - std::vector<MaterialTextureDef*> potentialTextureDefs; +GfxImage *AssetDumperXModel::GetMaterialNormalMap(const Material *material) { + std::vector<MaterialTextureDef *> potentialTextureDefs; - for (auto textureIndex = 0u; textureIndex < material->textureCount; textureIndex++) - { - MaterialTextureDef* def = &material->textureTable[textureIndex]; + for (auto textureIndex = 0u; textureIndex < material->textureCount; textureIndex++) { + MaterialTextureDef *def = &material->textureTable[textureIndex]; - if (def->semantic == TS_NORMAL_MAP) - potentialTextureDefs.push_back(def); - } + if (def->semantic == TS_NORMAL_MAP) + potentialTextureDefs.push_back(def); + } - if (potentialTextureDefs.empty()) - return nullptr; - if (potentialTextureDefs.size() == 1) - return potentialTextureDefs[0]->u.image; + if (potentialTextureDefs.empty()) + return nullptr; + if (potentialTextureDefs.size() == 1) + return potentialTextureDefs[0]->u.image; - for (const auto* def : potentialTextureDefs) - { - if (def->nameStart == 'n' && def->nameEnd == 'p') - return def->u.image; - } + for (const auto *def : potentialTextureDefs) { + if (def->nameStart == 'n' && def->nameEnd == 'p') + return def->u.image; + } - return potentialTextureDefs[0]->u.image; + return potentialTextureDefs[0]->u.image; } -GfxImage* AssetDumperXModel::GetMaterialSpecularMap(const Material* material) -{ - std::vector<MaterialTextureDef*> potentialTextureDefs; +GfxImage *AssetDumperXModel::GetMaterialSpecularMap(const Material *material) { + std::vector<MaterialTextureDef *> potentialTextureDefs; - for (auto textureIndex = 0u; textureIndex < material->textureCount; textureIndex++) - { - MaterialTextureDef* def = &material->textureTable[textureIndex]; + for (auto textureIndex = 0u; textureIndex < material->textureCount; textureIndex++) { + MaterialTextureDef *def = &material->textureTable[textureIndex]; - if (def->semantic == TS_SPECULAR_MAP) - potentialTextureDefs.push_back(def); - } + if (def->semantic == TS_SPECULAR_MAP) + potentialTextureDefs.push_back(def); + } - if (potentialTextureDefs.empty()) - return nullptr; - if (potentialTextureDefs.size() == 1) - return potentialTextureDefs[0]->u.image; + if (potentialTextureDefs.empty()) + return nullptr; + if (potentialTextureDefs.size() == 1) + return potentialTextureDefs[0]->u.image; - for (const auto* def : potentialTextureDefs) - { - if (def->nameStart == 's' && def->nameEnd == 'p') - return def->u.image; - } + for (const auto *def : potentialTextureDefs) { + if (def->nameStart == 's' && def->nameEnd == 'p') + return def->u.image; + } - return potentialTextureDefs[0]->u.image; + return potentialTextureDefs[0]->u.image; } -void AssetDumperXModel::AddObjMaterials(ObjWriter& writer, DistinctMapper<Material*>& materialMapper, const XModel* model) -{ - if (!model->materialHandles) - return; +void AssetDumperXModel::AddObjMaterials(ObjWriter &writer, DistinctMapper<Material *> &materialMapper, const XModel *model) { + if (!model->materialHandles) + return; - for (auto surfIndex = 0u; surfIndex < model->numsurfs; surfIndex++) - { - Material* material = model->materialHandles[surfIndex]; - if (!materialMapper.Add(material)) - continue; + for (auto surfIndex = 0u; surfIndex < model->numsurfs; surfIndex++) { + Material *material = model->materialHandles[surfIndex]; + if (!materialMapper.Add(material)) + continue; - MtlMaterial mtl; - mtl.materialName = std::string(material->info.name); + MtlMaterial mtl; + mtl.materialName = std::string(material->info.name); - GfxImage* colorMap = GetMaterialColorMap(material); - GfxImage* normalMap = GetMaterialNormalMap(material); - GfxImage* specularMap = GetMaterialSpecularMap(material); + GfxImage *colorMap = GetMaterialColorMap(material); + GfxImage *normalMap = GetMaterialNormalMap(material); + GfxImage *specularMap = GetMaterialSpecularMap(material); - if (colorMap != nullptr) - mtl.colorMapName = colorMap->name; - if (normalMap != nullptr) - mtl.normalMapName = normalMap->name; - if (specularMap != nullptr) - mtl.specularMapName = specularMap->name; + if (colorMap != nullptr) + mtl.colorMapName = colorMap->name; + if (normalMap != nullptr) + mtl.normalMapName = normalMap->name; + if (specularMap != nullptr) + mtl.specularMapName = specularMap->name; - writer.AddMaterial(std::move(mtl)); - } + writer.AddMaterial(std::move(mtl)); + } } -void AssetDumperXModel::AddObjObjects(ObjWriter& writer, const DistinctMapper<Material*>& materialMapper, const XModel* model, const unsigned lod) -{ - const auto surfCount = model->lodInfo[lod].numsurfs; - const auto baseSurfIndex = model->lodInfo[lod].surfIndex; +void AssetDumperXModel::AddObjObjects(ObjWriter &writer, const DistinctMapper<Material *> &materialMapper, const XModel *model, const unsigned lod) { + const auto surfCount = model->lodInfo[lod].numsurfs; + const auto baseSurfIndex = model->lodInfo[lod].surfIndex; - for (auto surfIndex = 0u; surfIndex < surfCount; surfIndex++) - { - ObjObject object; - object.name = "surf" + std::to_string(surfIndex); - object.materialIndex = static_cast<int>(materialMapper.GetDistinctPositionByInputPosition(surfIndex + baseSurfIndex)); + for (auto surfIndex = 0u; surfIndex < surfCount; surfIndex++) { + ObjObject object; + object.name = "surf" + std::to_string(surfIndex); + object.materialIndex = static_cast<int>(materialMapper.GetDistinctPositionByInputPosition(surfIndex + baseSurfIndex)); - writer.AddObject(std::move(object)); - } + writer.AddObject(std::move(object)); + } } -void AssetDumperXModel::AddObjVertices(ObjWriter& writer, const XModel* model, const unsigned lod) -{ - const auto* surfs = &model->surfs[model->lodInfo[lod].surfIndex]; - const auto surfCount = model->lodInfo[lod].numsurfs; - - for (auto surfIndex = 0u; surfIndex < surfCount; surfIndex++) - { - const auto& surface = surfs[surfIndex]; - - for (auto vertexIndex = 0u; vertexIndex < surface.vertCount; vertexIndex++) - { - const auto& v = surface.verts0[vertexIndex]; - vec2_t uv; - vec3_t normalVec; - - Common::Vec2UnpackTexCoords(v.texCoord, &uv); - Common::Vec3UnpackUnitVec(v.normal, &normalVec); - - ObjVertex objVertex{}; - ObjNormal objNormal{}; - ObjUv objUv{}; - objVertex.coordinates[0] = v.xyz[0]; - objVertex.coordinates[1] = v.xyz[2]; - objVertex.coordinates[2] = -v.xyz[1]; - objNormal.normal[0] = normalVec[0]; - objNormal.normal[1] = normalVec[2]; - objNormal.normal[2] = -normalVec[1]; - objUv.uv[0] = uv[0]; - objUv.uv[1] = 1.0f - uv[1]; - - writer.AddVertex(static_cast<int>(surfIndex), objVertex); - writer.AddNormal(static_cast<int>(surfIndex), objNormal); - writer.AddUv(static_cast<int>(surfIndex), objUv); - } +void AssetDumperXModel::AddObjVertices(ObjWriter &writer, const XModel *model, const unsigned lod) { + const auto *surfs = &model->surfs[model->lodInfo[lod].surfIndex]; + const auto surfCount = model->lodInfo[lod].numsurfs; + + for (auto surfIndex = 0u; surfIndex < surfCount; surfIndex++) { + const auto &surface = surfs[surfIndex]; + + for (auto vertexIndex = 0u; vertexIndex < surface.vertCount; vertexIndex++) { + const auto &v = surface.verts0[vertexIndex]; + vec2_t uv; + vec3_t normalVec; + + Common::Vec2UnpackTexCoords(v.texCoord, &uv); + Common::Vec3UnpackUnitVec(v.normal, &normalVec); + + ObjVertex objVertex{}; + ObjNormal objNormal{}; + ObjUv objUv{}; + objVertex.coordinates[0] = v.xyz[0]; + objVertex.coordinates[1] = v.xyz[2]; + objVertex.coordinates[2] = -v.xyz[1]; + objNormal.normal[0] = normalVec[0]; + objNormal.normal[1] = normalVec[2]; + objNormal.normal[2] = -normalVec[1]; + objUv.uv[0] = uv[0]; + objUv.uv[1] = 1.0f - uv[1]; + + writer.AddVertex(static_cast<int>(surfIndex), objVertex); + writer.AddNormal(static_cast<int>(surfIndex), objNormal); + writer.AddUv(static_cast<int>(surfIndex), objUv); } + } } -void AssetDumperXModel::AddObjFaces(ObjWriter& writer, const XModel* model, const unsigned lod) -{ - const auto* surfs = &model->surfs[model->lodInfo[lod].surfIndex]; - const auto surfCount = model->lodInfo[lod].numsurfs; - - for (auto surfIndex = 0u; surfIndex < surfCount; surfIndex++) - { - const auto& surface = surfs[surfIndex]; - for (auto triIndex = 0u; triIndex < surface.triCount; triIndex++) - { - const auto& tri = surface.triIndices[triIndex]; - - ObjFace face{}; - face.vertexIndex[0] = tri[2] + surface.baseVertIndex; - face.vertexIndex[1] = tri[1] + surface.baseVertIndex; - face.vertexIndex[2] = tri[0] + surface.baseVertIndex; - face.normalIndex[0] = face.vertexIndex[0]; - face.normalIndex[1] = face.vertexIndex[1]; - face.normalIndex[2] = face.vertexIndex[2]; - face.uvIndex[0] = face.vertexIndex[0]; - face.uvIndex[1] = face.vertexIndex[1]; - face.uvIndex[2] = face.vertexIndex[2]; - writer.AddFace(static_cast<int>(surfIndex), face); - } +void AssetDumperXModel::AddObjFaces(ObjWriter &writer, const XModel *model, const unsigned lod) { + const auto *surfs = &model->surfs[model->lodInfo[lod].surfIndex]; + const auto surfCount = model->lodInfo[lod].numsurfs; + + for (auto surfIndex = 0u; surfIndex < surfCount; surfIndex++) { + const auto &surface = surfs[surfIndex]; + for (auto triIndex = 0u; triIndex < surface.triCount; triIndex++) { + const auto &tri = surface.triIndices[triIndex]; + + ObjFace face{}; + face.vertexIndex[0] = tri[2] + surface.baseVertIndex; + face.vertexIndex[1] = tri[1] + surface.baseVertIndex; + face.vertexIndex[2] = tri[0] + surface.baseVertIndex; + face.normalIndex[0] = face.vertexIndex[0]; + face.normalIndex[1] = face.vertexIndex[1]; + face.normalIndex[2] = face.vertexIndex[2]; + face.uvIndex[0] = face.vertexIndex[0]; + face.uvIndex[1] = face.vertexIndex[1]; + face.uvIndex[2] = face.vertexIndex[2]; + writer.AddFace(static_cast<int>(surfIndex), face); } + } } -void AssetDumperXModel::DumpObjMat(const AssetDumpingContext& context, XAssetInfo<XModel>* asset) -{ - const auto* model = asset->Asset(); - const auto matFile = context.OpenAssetFile("model_export/" + std::string(model->name) + ".mtl"); +void AssetDumperXModel::DumpObjMat(const AssetDumpingContext &context, XAssetInfo<XModel> *asset) { + const auto *model = asset->Asset(); + const auto matFile = context.OpenAssetFile("model_export/" + std::string(model->name) + ".mtl"); - if (!matFile) - return; + if (!matFile) + return; - ObjWriter writer(context.m_zone->m_game->GetShortName(), context.m_zone->m_name); - DistinctMapper<Material*> materialMapper(model->numsurfs); + ObjWriter writer(context.m_zone->m_game->GetShortName(), context.m_zone->m_name); + DistinctMapper<Material *> materialMapper(model->numsurfs); - AddObjMaterials(writer, materialMapper, model); - writer.WriteMtl(*matFile); + AddObjMaterials(writer, materialMapper, model); + writer.WriteMtl(*matFile); } -void AssetDumperXModel::DumpObjLod(AssetDumpingContext& context, XAssetInfo<XModel>* asset, const unsigned lod) -{ - const auto* model = asset->Asset(); - std::ostringstream ss; - ss << "model_export/" << model->name << "_lod" << lod << ".OBJ"; +void AssetDumperXModel::DumpObjLod(AssetDumpingContext &context, XAssetInfo<XModel> *asset, const unsigned lod) { + const auto *model = asset->Asset(); + std::ostringstream ss; + ss << "model_export/" << model->name << "_lod" << lod << ".OBJ"; - const auto assetFile = context.OpenAssetFile(ss.str()); + const auto assetFile = context.OpenAssetFile(ss.str()); - if (!assetFile) - return; + if (!assetFile) + return; - ObjWriter writer(context.m_zone->m_game->GetShortName(), context.m_zone->m_name); - DistinctMapper<Material*> materialMapper(model->numsurfs); + ObjWriter writer(context.m_zone->m_game->GetShortName(), context.m_zone->m_name); + DistinctMapper<Material *> materialMapper(model->numsurfs); - AddObjMaterials(writer, materialMapper, model); - AddObjObjects(writer, materialMapper, model, lod); - AddObjVertices(writer, model, lod); - AddObjFaces(writer, model, lod); + AddObjMaterials(writer, materialMapper, model); + AddObjObjects(writer, materialMapper, model, lod); + AddObjVertices(writer, model, lod); + AddObjFaces(writer, model, lod); - writer.WriteObj(*assetFile, std::string(model->name) + ".mtl"); + writer.WriteObj(*assetFile, std::string(model->name) + ".mtl"); } -void AssetDumperXModel::DumpObj(AssetDumpingContext& context, XAssetInfo<XModel>* asset) -{ - const auto* model = asset->Asset(); +void AssetDumperXModel::DumpObj(AssetDumpingContext &context, XAssetInfo<XModel> *asset) { + const auto *model = asset->Asset(); - DumpObjMat(context, asset); - for (auto currentLod = 0u; currentLod < model->numLods; currentLod++) - { - DumpObjLod(context, asset, currentLod); - } + DumpObjMat(context, asset); + for (auto currentLod = 0u; currentLod < model->numLods; currentLod++) { + DumpObjLod(context, asset, currentLod); + } } -void AssetDumperXModel::AddXModelBones(const AssetDumpingContext& context, AbstractXModelWriter& writer, const XModel* model) -{ - for (auto boneNum = 0u; boneNum < model->numBones; boneNum++) - { - XModelBone bone; - if (model->boneNames[boneNum] < context.m_zone->m_script_strings.Count()) - bone.name = context.m_zone->m_script_strings[model->boneNames[boneNum]]; - else - bone.name = "INVALID_BONE_NAME"; - - if (boneNum < model->numRootBones) - bone.parentIndex = -1; - else - bone.parentIndex = static_cast<int>(boneNum - static_cast<unsigned int>(model->parentList[boneNum - model->numRootBones])); - - bone.scale[0] = 1.0f; - bone.scale[1] = 1.0f; - bone.scale[2] = 1.0f; - - bone.globalOffset[0] = model->baseMat[boneNum].trans[0]; - bone.globalOffset[1] = model->baseMat[boneNum].trans[1]; - bone.globalOffset[2] = model->baseMat[boneNum].trans[2]; - bone.globalRotation = Quaternion32(model->baseMat[boneNum].quat[0], model->baseMat[boneNum].quat[1], model->baseMat[boneNum].quat[2], model->baseMat[boneNum].quat[3]); - - if (boneNum < model->numRootBones) - { - bone.localOffset[0] = 0; - bone.localOffset[1] = 0; - bone.localOffset[2] = 0; - bone.localRotation = Quaternion32(0, 0, 0, 1); - } - else - { - bone.localOffset[0] = model->trans[boneNum - model->numRootBones][0]; - bone.localOffset[1] = model->trans[boneNum - model->numRootBones][1]; - bone.localOffset[2] = model->trans[boneNum - model->numRootBones][2]; - bone.localRotation = Quaternion32( - QuatInt16::ToFloat(model->quats[boneNum - model->numRootBones][0]), - QuatInt16::ToFloat(model->quats[boneNum - model->numRootBones][1]), - QuatInt16::ToFloat(model->quats[boneNum - model->numRootBones][2]), - QuatInt16::ToFloat(model->quats[boneNum - model->numRootBones][3]) - ); - } - - writer.AddBone(std::move(bone)); +void AssetDumperXModel::AddXModelBones(const AssetDumpingContext &context, AbstractXModelWriter &writer, const XModel *model) { + for (auto boneNum = 0u; boneNum < model->numBones; boneNum++) { + XModelBone bone; + if (model->boneNames[boneNum] < context.m_zone->m_script_strings.Count()) + bone.name = context.m_zone->m_script_strings[model->boneNames[boneNum]]; + else + bone.name = "INVALID_BONE_NAME"; + + if (boneNum < model->numRootBones) + bone.parentIndex = -1; + else + bone.parentIndex = static_cast<int>(boneNum - static_cast<unsigned int>(model->parentList[boneNum - model->numRootBones])); + + bone.scale[0] = 1.0f; + bone.scale[1] = 1.0f; + bone.scale[2] = 1.0f; + + bone.globalOffset[0] = model->baseMat[boneNum].trans[0]; + bone.globalOffset[1] = model->baseMat[boneNum].trans[1]; + bone.globalOffset[2] = model->baseMat[boneNum].trans[2]; + bone.globalRotation = + Quaternion32(model->baseMat[boneNum].quat[0], model->baseMat[boneNum].quat[1], model->baseMat[boneNum].quat[2], model->baseMat[boneNum].quat[3]); + + if (boneNum < model->numRootBones) { + bone.localOffset[0] = 0; + bone.localOffset[1] = 0; + bone.localOffset[2] = 0; + bone.localRotation = Quaternion32(0, 0, 0, 1); + } else { + bone.localOffset[0] = model->trans[boneNum - model->numRootBones][0]; + bone.localOffset[1] = model->trans[boneNum - model->numRootBones][1]; + bone.localOffset[2] = model->trans[boneNum - model->numRootBones][2]; + bone.localRotation = + Quaternion32(QuatInt16::ToFloat(model->quats[boneNum - model->numRootBones][0]), QuatInt16::ToFloat(model->quats[boneNum - model->numRootBones][1]), + QuatInt16::ToFloat(model->quats[boneNum - model->numRootBones][2]), QuatInt16::ToFloat(model->quats[boneNum - model->numRootBones][3])); } + + writer.AddBone(std::move(bone)); + } } -void AssetDumperXModel::AddXModelMaterials(AbstractXModelWriter& writer, DistinctMapper<Material*>& materialMapper, const XModel* model) -{ - for (auto surfaceMaterialNum = 0; surfaceMaterialNum < model->numsurfs; surfaceMaterialNum++) - { - Material* material = model->materialHandles[surfaceMaterialNum]; - if (materialMapper.Add(material)) - { - XModelMaterial xMaterial; - xMaterial.ApplyDefaults(); - - xMaterial.name = material->info.name; - const auto* colorMap = GetMaterialColorMap(material); - if (colorMap) - xMaterial.colorMapName = std::string(colorMap->name); - - writer.AddMaterial(std::move(xMaterial)); - } +void AssetDumperXModel::AddXModelMaterials(AbstractXModelWriter &writer, DistinctMapper<Material *> &materialMapper, const XModel *model) { + for (auto surfaceMaterialNum = 0; surfaceMaterialNum < model->numsurfs; surfaceMaterialNum++) { + Material *material = model->materialHandles[surfaceMaterialNum]; + if (materialMapper.Add(material)) { + XModelMaterial xMaterial; + xMaterial.ApplyDefaults(); + + xMaterial.name = material->info.name; + const auto *colorMap = GetMaterialColorMap(material); + if (colorMap) + xMaterial.colorMapName = std::string(colorMap->name); + + writer.AddMaterial(std::move(xMaterial)); } + } } -void AssetDumperXModel::AddXModelObjects(AbstractXModelWriter& writer, const XModel* model, const unsigned lod) -{ - const auto surfCount = model->lodInfo[lod].numsurfs; +void AssetDumperXModel::AddXModelObjects(AbstractXModelWriter &writer, const XModel *model, const unsigned lod) { + const auto surfCount = model->lodInfo[lod].numsurfs; - for (auto surfIndex = 0u; surfIndex < surfCount; surfIndex++) - { - XModelObject object; - object.name = "surf" + std::to_string(surfIndex); + for (auto surfIndex = 0u; surfIndex < surfCount; surfIndex++) { + XModelObject object; + object.name = "surf" + std::to_string(surfIndex); - writer.AddObject(std::move(object)); - } + writer.AddObject(std::move(object)); + } } -void AssetDumperXModel::AddXModelVertices(AbstractXModelWriter& writer, const XModel* model, const unsigned lod) -{ - const auto* surfs = &model->surfs[model->lodInfo[lod].surfIndex]; - const auto surfCount = model->lodInfo[lod].numsurfs; - - for (auto surfIndex = 0u; surfIndex < surfCount; surfIndex++) - { - const auto& surface = surfs[surfIndex]; - - for (auto vertexIndex = 0u; vertexIndex < surface.vertCount; vertexIndex++) - { - const auto& v = surface.verts0[vertexIndex]; - vec2_t uv; - vec3_t normalVec; - vec4_t color; - - Common::Vec2UnpackTexCoords(v.texCoord, &uv); - Common::Vec3UnpackUnitVec(v.normal, &normalVec); - Common::Vec4UnpackGfxColor(v.color, &color); - - XModelVertex vertex{}; - vertex.coordinates[0] = v.xyz[0]; - vertex.coordinates[1] = v.xyz[1]; - vertex.coordinates[2] = v.xyz[2]; - vertex.normal[0] = normalVec[0]; - vertex.normal[1] = normalVec[1]; - vertex.normal[2] = normalVec[2]; - vertex.color[0] = color[0]; - vertex.color[1] = color[1]; - vertex.color[2] = color[2]; - vertex.color[3] = color[3]; - vertex.uv[0] = uv[0]; - vertex.uv[1] = uv[1]; - - writer.AddVertex(vertex); - } +void AssetDumperXModel::AddXModelVertices(AbstractXModelWriter &writer, const XModel *model, const unsigned lod) { + const auto *surfs = &model->surfs[model->lodInfo[lod].surfIndex]; + const auto surfCount = model->lodInfo[lod].numsurfs; + + for (auto surfIndex = 0u; surfIndex < surfCount; surfIndex++) { + const auto &surface = surfs[surfIndex]; + + for (auto vertexIndex = 0u; vertexIndex < surface.vertCount; vertexIndex++) { + const auto &v = surface.verts0[vertexIndex]; + vec2_t uv; + vec3_t normalVec; + vec4_t color; + + Common::Vec2UnpackTexCoords(v.texCoord, &uv); + Common::Vec3UnpackUnitVec(v.normal, &normalVec); + Common::Vec4UnpackGfxColor(v.color, &color); + + XModelVertex vertex{}; + vertex.coordinates[0] = v.xyz[0]; + vertex.coordinates[1] = v.xyz[1]; + vertex.coordinates[2] = v.xyz[2]; + vertex.normal[0] = normalVec[0]; + vertex.normal[1] = normalVec[1]; + vertex.normal[2] = normalVec[2]; + vertex.color[0] = color[0]; + vertex.color[1] = color[1]; + vertex.color[2] = color[2]; + vertex.color[3] = color[3]; + vertex.uv[0] = uv[0]; + vertex.uv[1] = uv[1]; + + writer.AddVertex(vertex); } + } } -void AssetDumperXModel::AllocateXModelBoneWeights(const XModel* model, const unsigned lod, XModelVertexBoneWeightCollection& weightCollection) -{ - const auto* surfs = &model->surfs[model->lodInfo[lod].surfIndex]; - const auto surfCount = model->lodInfo[lod].numsurfs; +void AssetDumperXModel::AllocateXModelBoneWeights(const XModel *model, const unsigned lod, XModelVertexBoneWeightCollection &weightCollection) { + const auto *surfs = &model->surfs[model->lodInfo[lod].surfIndex]; + const auto surfCount = model->lodInfo[lod].numsurfs; - weightCollection.totalWeightCount = 0u; - for (auto surfIndex = 0u; surfIndex < surfCount; surfIndex++) - { - const auto& surface = surfs[surfIndex]; + weightCollection.totalWeightCount = 0u; + for (auto surfIndex = 0u; surfIndex < surfCount; surfIndex++) { + const auto &surface = surfs[surfIndex]; - if (surface.vertList) - { - weightCollection.totalWeightCount += surface.vertListCount; - } + if (surface.vertList) { + weightCollection.totalWeightCount += surface.vertListCount; + } - if (surface.vertInfo.vertsBlend) - { - weightCollection.totalWeightCount += surface.vertInfo.vertCount[0] * 1; - weightCollection.totalWeightCount += surface.vertInfo.vertCount[1] * 2; - weightCollection.totalWeightCount += surface.vertInfo.vertCount[2] * 3; - weightCollection.totalWeightCount += surface.vertInfo.vertCount[3] * 4; - } + if (surface.vertInfo.vertsBlend) { + weightCollection.totalWeightCount += surface.vertInfo.vertCount[0] * 1; + weightCollection.totalWeightCount += surface.vertInfo.vertCount[1] * 2; + weightCollection.totalWeightCount += surface.vertInfo.vertCount[2] * 3; + weightCollection.totalWeightCount += surface.vertInfo.vertCount[3] * 4; } + } - weightCollection.weights = std::make_unique<XModelBoneWeight[]>(weightCollection.totalWeightCount); + weightCollection.weights = std::make_unique<XModelBoneWeight[]>(weightCollection.totalWeightCount); } -void AssetDumperXModel::AddXModelVertexBoneWeights(AbstractXModelWriter& writer, const XModel* model, const unsigned lod, XModelVertexBoneWeightCollection& weightCollection) -{ - const auto* surfs = &model->surfs[model->lodInfo[lod].surfIndex]; - const auto surfCount = model->lodInfo[lod].numsurfs; - - size_t weightOffset = 0u; - - for (auto surfIndex = 0u; surfIndex < surfCount; surfIndex++) - { - const auto& surface = surfs[surfIndex]; - auto handledVertices = 0u; - - if (surface.vertList) - { - for (auto vertListIndex = 0u; vertListIndex < surface.vertListCount; vertListIndex++) - { - const auto& vertList = surface.vertList[vertListIndex]; - const auto* boneWeightOffset = &weightCollection.weights[weightOffset]; - - weightCollection.weights[weightOffset++] = XModelBoneWeight{ - static_cast<int>(vertList.boneOffset / sizeof(DObjSkelMat)), - 1.0f - }; - - for (auto vertListVertexOffset = 0u; vertListVertexOffset < vertList.vertCount; vertListVertexOffset++) - { - writer.AddVertexBoneWeights(XModelVertexBoneWeights{ - boneWeightOffset, - 1 - }); - } - handledVertices += vertList.vertCount; - } - } +void AssetDumperXModel::AddXModelVertexBoneWeights(AbstractXModelWriter &writer, const XModel *model, const unsigned lod, + XModelVertexBoneWeightCollection &weightCollection) { + const auto *surfs = &model->surfs[model->lodInfo[lod].surfIndex]; + const auto surfCount = model->lodInfo[lod].numsurfs; - auto vertsBlendOffset = 0u; - if (surface.vertInfo.vertsBlend) - { - // 1 bone weight - for (auto vertIndex = 0; vertIndex < surface.vertInfo.vertCount[0]; vertIndex++) - { - const auto* boneWeightOffset = &weightCollection.weights[weightOffset]; - const auto boneIndex0 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 0] / sizeof(DObjSkelMat)); - weightCollection.weights[weightOffset++] = XModelBoneWeight{ - boneIndex0, - 1.0f - }; - - vertsBlendOffset += 1; - - writer.AddVertexBoneWeights(XModelVertexBoneWeights{ - boneWeightOffset, - 1 - }); - } - - // 2 bone weights - for (auto vertIndex = 0; vertIndex < surface.vertInfo.vertCount[1]; vertIndex++) - { - const auto* boneWeightOffset = &weightCollection.weights[weightOffset]; - const auto boneIndex0 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 0] / sizeof(DObjSkelMat)); - const auto boneIndex1 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 1] / sizeof(DObjSkelMat)); - const auto boneWeight1 = HalfFloat::ToFloat(surface.vertInfo.vertsBlend[vertsBlendOffset + 2]); - const auto boneWeight0 = 1.0f - boneWeight1; - - weightCollection.weights[weightOffset++] = XModelBoneWeight{ - boneIndex0, - boneWeight0 - }; - weightCollection.weights[weightOffset++] = XModelBoneWeight{ - boneIndex1, - boneWeight1 - }; - - vertsBlendOffset += 3; - - writer.AddVertexBoneWeights(XModelVertexBoneWeights{ - boneWeightOffset, - 2 - }); - } - - // 3 bone weights - for (auto vertIndex = 0; vertIndex < surface.vertInfo.vertCount[2]; vertIndex++) - { - const auto* boneWeightOffset = &weightCollection.weights[weightOffset]; - const auto boneIndex0 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 0] / sizeof(DObjSkelMat)); - const auto boneIndex1 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 1] / sizeof(DObjSkelMat)); - const auto boneWeight1 = HalfFloat::ToFloat(surface.vertInfo.vertsBlend[vertsBlendOffset + 2]); - const auto boneIndex2 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 3] / sizeof(DObjSkelMat)); - const auto boneWeight2 = HalfFloat::ToFloat(surface.vertInfo.vertsBlend[vertsBlendOffset + 4]); - const auto boneWeight0 = 1.0f - boneWeight1 - boneWeight2; - - weightCollection.weights[weightOffset++] = XModelBoneWeight{ - boneIndex0, - boneWeight0 - }; - weightCollection.weights[weightOffset++] = XModelBoneWeight{ - boneIndex1, - boneWeight1 - }; - weightCollection.weights[weightOffset++] = XModelBoneWeight{ - boneIndex2, - boneWeight2 - }; - - vertsBlendOffset += 5; - - writer.AddVertexBoneWeights(XModelVertexBoneWeights{ - boneWeightOffset, - 3 - }); - } - - // 4 bone weights - for (auto vertIndex = 0; vertIndex < surface.vertInfo.vertCount[3]; vertIndex++) - { - const auto* boneWeightOffset = &weightCollection.weights[weightOffset]; - const auto boneIndex0 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 0] / sizeof(DObjSkelMat)); - const auto boneIndex1 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 1] / sizeof(DObjSkelMat)); - const auto boneWeight1 = HalfFloat::ToFloat(surface.vertInfo.vertsBlend[vertsBlendOffset + 2]); - const auto boneIndex2 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 3] / sizeof(DObjSkelMat)); - const auto boneWeight2 = HalfFloat::ToFloat(surface.vertInfo.vertsBlend[vertsBlendOffset + 4]); - const auto boneIndex3 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 5] / sizeof(DObjSkelMat)); - const auto boneWeight3 = HalfFloat::ToFloat(surface.vertInfo.vertsBlend[vertsBlendOffset + 6]); - const auto boneWeight0 = 1.0f - boneWeight1 - boneWeight2 - boneWeight3; - - weightCollection.weights[weightOffset++] = XModelBoneWeight{ - boneIndex0, - boneWeight0 - }; - weightCollection.weights[weightOffset++] = XModelBoneWeight{ - boneIndex1, - boneWeight1 - }; - weightCollection.weights[weightOffset++] = XModelBoneWeight{ - boneIndex2, - boneWeight2 - }; - weightCollection.weights[weightOffset++] = XModelBoneWeight{ - boneIndex3, - boneWeight3 - }; - - vertsBlendOffset += 7; - - writer.AddVertexBoneWeights(XModelVertexBoneWeights{ - boneWeightOffset, - 4 - }); - } - - handledVertices += surface.vertInfo.vertCount[0] + surface.vertInfo.vertCount[1] + surface.vertInfo.vertCount[2] + surface.vertInfo.vertCount[3]; - } + size_t weightOffset = 0u; + + for (auto surfIndex = 0u; surfIndex < surfCount; surfIndex++) { + const auto &surface = surfs[surfIndex]; + auto handledVertices = 0u; - for (; handledVertices < surface.vertCount; handledVertices++) - { - writer.AddVertexBoneWeights(XModelVertexBoneWeights{ - nullptr, - 0 - }); + if (surface.vertList) { + for (auto vertListIndex = 0u; vertListIndex < surface.vertListCount; vertListIndex++) { + const auto &vertList = surface.vertList[vertListIndex]; + const auto *boneWeightOffset = &weightCollection.weights[weightOffset]; + + weightCollection.weights[weightOffset++] = XModelBoneWeight{static_cast<int>(vertList.boneOffset / sizeof(DObjSkelMat)), 1.0f}; + + for (auto vertListVertexOffset = 0u; vertListVertexOffset < vertList.vertCount; vertListVertexOffset++) { + writer.AddVertexBoneWeights(XModelVertexBoneWeights{boneWeightOffset, 1}); } + handledVertices += vertList.vertCount; + } + } + + auto vertsBlendOffset = 0u; + if (surface.vertInfo.vertsBlend) { + // 1 bone weight + for (auto vertIndex = 0; vertIndex < surface.vertInfo.vertCount[0]; vertIndex++) { + const auto *boneWeightOffset = &weightCollection.weights[weightOffset]; + const auto boneIndex0 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 0] / sizeof(DObjSkelMat)); + weightCollection.weights[weightOffset++] = XModelBoneWeight{boneIndex0, 1.0f}; + + vertsBlendOffset += 1; + + writer.AddVertexBoneWeights(XModelVertexBoneWeights{boneWeightOffset, 1}); + } + + // 2 bone weights + for (auto vertIndex = 0; vertIndex < surface.vertInfo.vertCount[1]; vertIndex++) { + const auto *boneWeightOffset = &weightCollection.weights[weightOffset]; + const auto boneIndex0 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 0] / sizeof(DObjSkelMat)); + const auto boneIndex1 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 1] / sizeof(DObjSkelMat)); + const auto boneWeight1 = HalfFloat::ToFloat(surface.vertInfo.vertsBlend[vertsBlendOffset + 2]); + const auto boneWeight0 = 1.0f - boneWeight1; + + weightCollection.weights[weightOffset++] = XModelBoneWeight{boneIndex0, boneWeight0}; + weightCollection.weights[weightOffset++] = XModelBoneWeight{boneIndex1, boneWeight1}; + + vertsBlendOffset += 3; + + writer.AddVertexBoneWeights(XModelVertexBoneWeights{boneWeightOffset, 2}); + } + + // 3 bone weights + for (auto vertIndex = 0; vertIndex < surface.vertInfo.vertCount[2]; vertIndex++) { + const auto *boneWeightOffset = &weightCollection.weights[weightOffset]; + const auto boneIndex0 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 0] / sizeof(DObjSkelMat)); + const auto boneIndex1 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 1] / sizeof(DObjSkelMat)); + const auto boneWeight1 = HalfFloat::ToFloat(surface.vertInfo.vertsBlend[vertsBlendOffset + 2]); + const auto boneIndex2 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 3] / sizeof(DObjSkelMat)); + const auto boneWeight2 = HalfFloat::ToFloat(surface.vertInfo.vertsBlend[vertsBlendOffset + 4]); + const auto boneWeight0 = 1.0f - boneWeight1 - boneWeight2; + + weightCollection.weights[weightOffset++] = XModelBoneWeight{boneIndex0, boneWeight0}; + weightCollection.weights[weightOffset++] = XModelBoneWeight{boneIndex1, boneWeight1}; + weightCollection.weights[weightOffset++] = XModelBoneWeight{boneIndex2, boneWeight2}; + + vertsBlendOffset += 5; + + writer.AddVertexBoneWeights(XModelVertexBoneWeights{boneWeightOffset, 3}); + } + + // 4 bone weights + for (auto vertIndex = 0; vertIndex < surface.vertInfo.vertCount[3]; vertIndex++) { + const auto *boneWeightOffset = &weightCollection.weights[weightOffset]; + const auto boneIndex0 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 0] / sizeof(DObjSkelMat)); + const auto boneIndex1 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 1] / sizeof(DObjSkelMat)); + const auto boneWeight1 = HalfFloat::ToFloat(surface.vertInfo.vertsBlend[vertsBlendOffset + 2]); + const auto boneIndex2 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 3] / sizeof(DObjSkelMat)); + const auto boneWeight2 = HalfFloat::ToFloat(surface.vertInfo.vertsBlend[vertsBlendOffset + 4]); + const auto boneIndex3 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 5] / sizeof(DObjSkelMat)); + const auto boneWeight3 = HalfFloat::ToFloat(surface.vertInfo.vertsBlend[vertsBlendOffset + 6]); + const auto boneWeight0 = 1.0f - boneWeight1 - boneWeight2 - boneWeight3; + + weightCollection.weights[weightOffset++] = XModelBoneWeight{boneIndex0, boneWeight0}; + weightCollection.weights[weightOffset++] = XModelBoneWeight{boneIndex1, boneWeight1}; + weightCollection.weights[weightOffset++] = XModelBoneWeight{boneIndex2, boneWeight2}; + weightCollection.weights[weightOffset++] = XModelBoneWeight{boneIndex3, boneWeight3}; + + vertsBlendOffset += 7; + + writer.AddVertexBoneWeights(XModelVertexBoneWeights{boneWeightOffset, 4}); + } + + handledVertices += surface.vertInfo.vertCount[0] + surface.vertInfo.vertCount[1] + surface.vertInfo.vertCount[2] + surface.vertInfo.vertCount[3]; + } + + for (; handledVertices < surface.vertCount; handledVertices++) { + writer.AddVertexBoneWeights(XModelVertexBoneWeights{nullptr, 0}); } + } } -void AssetDumperXModel::AddXModelFaces(AbstractXModelWriter& writer, const DistinctMapper<Material*>& materialMapper, const XModel* model, const unsigned lod) -{ - const auto* surfs = &model->surfs[model->lodInfo[lod].surfIndex]; - const auto surfCount = model->lodInfo[lod].numsurfs; - const auto baseSurfIndex = model->lodInfo[lod].surfIndex; - - for (auto surfIndex = 0u; surfIndex < surfCount; surfIndex++) - { - const auto& surface = surfs[surfIndex]; - for (auto triIndex = 0u; triIndex < surface.triCount; triIndex++) - { - const auto& tri = surface.triIndices[triIndex]; - - XModelFace face{}; - face.vertexIndex[0] = tri[0] + surface.baseVertIndex; - face.vertexIndex[1] = tri[1] + surface.baseVertIndex; - face.vertexIndex[2] = tri[2] + surface.baseVertIndex; - face.objectIndex = static_cast<int>(surfIndex); - face.materialIndex = static_cast<int>(materialMapper.GetDistinctPositionByInputPosition(surfIndex + baseSurfIndex)); - writer.AddFace(face); - } +void AssetDumperXModel::AddXModelFaces(AbstractXModelWriter &writer, const DistinctMapper<Material *> &materialMapper, const XModel *model, + const unsigned lod) { + const auto *surfs = &model->surfs[model->lodInfo[lod].surfIndex]; + const auto surfCount = model->lodInfo[lod].numsurfs; + const auto baseSurfIndex = model->lodInfo[lod].surfIndex; + + for (auto surfIndex = 0u; surfIndex < surfCount; surfIndex++) { + const auto &surface = surfs[surfIndex]; + for (auto triIndex = 0u; triIndex < surface.triCount; triIndex++) { + const auto &tri = surface.triIndices[triIndex]; + + XModelFace face{}; + face.vertexIndex[0] = tri[0] + surface.baseVertIndex; + face.vertexIndex[1] = tri[1] + surface.baseVertIndex; + face.vertexIndex[2] = tri[2] + surface.baseVertIndex; + face.objectIndex = static_cast<int>(surfIndex); + face.materialIndex = static_cast<int>(materialMapper.GetDistinctPositionByInputPosition(surfIndex + baseSurfIndex)); + writer.AddFace(face); } + } } -void AssetDumperXModel::DumpXModelExportLod(const AssetDumpingContext& context, XAssetInfo<XModel>* asset, const unsigned lod) -{ - const auto* model = asset->Asset(); +void AssetDumperXModel::DumpXModelExportLod(const AssetDumpingContext &context, XAssetInfo<XModel> *asset, const unsigned lod) { + const auto *model = asset->Asset(); - std::ostringstream ss; - ss << "model_export/" << model->name << "_lod" << lod << ".XMODEL_EXPORT"; + std::ostringstream ss; + ss << "model_export/" << model->name << "_lod" << lod << ".XMODEL_EXPORT"; - const auto assetFile = context.OpenAssetFile(ss.str()); + const auto assetFile = context.OpenAssetFile(ss.str()); - if (!assetFile) - return; + if (!assetFile) + return; - const auto writer = XModelExportWriter::CreateWriterForVersion6(context.m_zone->m_game->GetShortName(), context.m_zone->m_name); - DistinctMapper<Material*> materialMapper(model->numsurfs); - XModelVertexBoneWeightCollection boneWeightCollection; - AllocateXModelBoneWeights(model, lod, boneWeightCollection); + const auto writer = XModelExportWriter::CreateWriterForVersion6(context.m_zone->m_game->GetShortName(), context.m_zone->m_name); + DistinctMapper<Material *> materialMapper(model->numsurfs); + XModelVertexBoneWeightCollection boneWeightCollection; + AllocateXModelBoneWeights(model, lod, boneWeightCollection); - AddXModelBones(context, *writer, model); - AddXModelMaterials(*writer, materialMapper, model); - AddXModelObjects(*writer, model, lod); - AddXModelVertices(*writer, model, lod); - AddXModelVertexBoneWeights(*writer, model, lod, boneWeightCollection); - AddXModelFaces(*writer, materialMapper, model, lod); + AddXModelBones(context, *writer, model); + AddXModelMaterials(*writer, materialMapper, model); + AddXModelObjects(*writer, model, lod); + AddXModelVertices(*writer, model, lod); + AddXModelVertexBoneWeights(*writer, model, lod, boneWeightCollection); + AddXModelFaces(*writer, materialMapper, model, lod); - writer->Write(*assetFile); + writer->Write(*assetFile); } -void AssetDumperXModel::DumpXModelExport(const AssetDumpingContext& context, XAssetInfo<XModel>* asset) -{ - const auto* model = asset->Asset(); - for (auto currentLod = 0u; currentLod < model->numLods; currentLod++) - { - DumpXModelExportLod(context, asset, currentLod); - } +void AssetDumperXModel::DumpXModelExport(const AssetDumpingContext &context, XAssetInfo<XModel> *asset) { + const auto *model = asset->Asset(); + for (auto currentLod = 0u; currentLod < model->numLods; currentLod++) { + DumpXModelExportLod(context, asset, currentLod); + } } -void AssetDumperXModel::DumpAsset(AssetDumpingContext& context, XAssetInfo<XModel>* asset) -{ - switch (ObjWriting::Configuration.ModelOutputFormat) - { - case ObjWriting::Configuration_t::ModelOutputFormat_e::OBJ: - DumpObj(context, asset); - break; - - case ObjWriting::Configuration_t::ModelOutputFormat_e::XMODEL_EXPORT: - DumpXModelExport(context, asset); - break; - - default: - assert(false); - break; - } +void AssetDumperXModel::DumpAsset(AssetDumpingContext &context, XAssetInfo<XModel> *asset) { + switch (ObjWriting::Configuration.ModelOutputFormat) { + case ObjWriting::Configuration_t::ModelOutputFormat_e::OBJ: + DumpObj(context, asset); + break; + + case ObjWriting::Configuration_t::ModelOutputFormat_e::XMODEL_EXPORT: + DumpXModelExport(context, asset); + break; + + default: + assert(false); + break; + } } diff --git a/src/ObjWriting/Game/T5/AssetDumpers/AssetDumperXModel.h b/src/ObjWriting/Game/T5/AssetDumpers/AssetDumperXModel.h index 41f16b536..cd151a7ef 100644 --- a/src/ObjWriting/Game/T5/AssetDumpers/AssetDumperXModel.h +++ b/src/ObjWriting/Game/T5/AssetDumpers/AssetDumperXModel.h @@ -2,38 +2,36 @@ #include "Dumping/AbstractAssetDumper.h" #include "Game/T5/T5.h" -#include "Utils/DistinctMapper.h" -#include "Model/XModel/AbstractXModelWriter.h" #include "Model/Obj/ObjWriter.h" +#include "Model/XModel/AbstractXModelWriter.h" +#include "Utils/DistinctMapper.h" -namespace T5 -{ - class AssetDumperXModel final : public AbstractAssetDumper<XModel> - { - static GfxImage* GetMaterialColorMap(const Material* material); - static GfxImage* GetMaterialNormalMap(const Material* material); - static GfxImage* GetMaterialSpecularMap(const Material* material); +namespace T5 { +class AssetDumperXModel final : public AbstractAssetDumper<XModel> { + static GfxImage *GetMaterialColorMap(const Material *material); + static GfxImage *GetMaterialNormalMap(const Material *material); + static GfxImage *GetMaterialSpecularMap(const Material *material); - static void AddObjMaterials(ObjWriter& writer, DistinctMapper<Material*>& materialMapper, const XModel* model); - static void AddObjObjects(ObjWriter& writer, const DistinctMapper<Material*>& materialMapper, const XModel* model, unsigned lod); - static void AddObjVertices(ObjWriter& writer, const XModel* model, unsigned lod); - static void AddObjFaces(ObjWriter& writer, const XModel* model, unsigned lod); - static void DumpObjLod(AssetDumpingContext& context, XAssetInfo<XModel>* asset, unsigned lod); - static void DumpObjMat(const AssetDumpingContext& context, XAssetInfo<XModel>* asset); - static void DumpObj(AssetDumpingContext& context, XAssetInfo<XModel>* asset); + static void AddObjMaterials(ObjWriter &writer, DistinctMapper<Material *> &materialMapper, const XModel *model); + static void AddObjObjects(ObjWriter &writer, const DistinctMapper<Material *> &materialMapper, const XModel *model, unsigned lod); + static void AddObjVertices(ObjWriter &writer, const XModel *model, unsigned lod); + static void AddObjFaces(ObjWriter &writer, const XModel *model, unsigned lod); + static void DumpObjLod(AssetDumpingContext &context, XAssetInfo<XModel> *asset, unsigned lod); + static void DumpObjMat(const AssetDumpingContext &context, XAssetInfo<XModel> *asset); + static void DumpObj(AssetDumpingContext &context, XAssetInfo<XModel> *asset); - static void AddXModelBones(const AssetDumpingContext& context, AbstractXModelWriter& writer, const XModel* model); - static void AddXModelMaterials(AbstractXModelWriter& writer, DistinctMapper<Material*>& materialMapper, const XModel* model); - static void AddXModelObjects(AbstractXModelWriter& writer, const XModel* model, unsigned lod); - static void AddXModelVertices(AbstractXModelWriter& writer, const XModel* model, unsigned lod); - static void AllocateXModelBoneWeights(const XModel* model, unsigned lod, XModelVertexBoneWeightCollection& weightCollection); - static void AddXModelVertexBoneWeights(AbstractXModelWriter& writer, const XModel* model, unsigned lod, XModelVertexBoneWeightCollection& weightCollection); - static void AddXModelFaces(AbstractXModelWriter& writer, const DistinctMapper<Material*>& materialMapper, const XModel* model, unsigned lod); - static void DumpXModelExportLod(const AssetDumpingContext& context, XAssetInfo<XModel>* asset, unsigned lod); - static void DumpXModelExport(const AssetDumpingContext& context, XAssetInfo<XModel>* asset); + static void AddXModelBones(const AssetDumpingContext &context, AbstractXModelWriter &writer, const XModel *model); + static void AddXModelMaterials(AbstractXModelWriter &writer, DistinctMapper<Material *> &materialMapper, const XModel *model); + static void AddXModelObjects(AbstractXModelWriter &writer, const XModel *model, unsigned lod); + static void AddXModelVertices(AbstractXModelWriter &writer, const XModel *model, unsigned lod); + static void AllocateXModelBoneWeights(const XModel *model, unsigned lod, XModelVertexBoneWeightCollection &weightCollection); + static void AddXModelVertexBoneWeights(AbstractXModelWriter &writer, const XModel *model, unsigned lod, XModelVertexBoneWeightCollection &weightCollection); + static void AddXModelFaces(AbstractXModelWriter &writer, const DistinctMapper<Material *> &materialMapper, const XModel *model, unsigned lod); + static void DumpXModelExportLod(const AssetDumpingContext &context, XAssetInfo<XModel> *asset, unsigned lod); + static void DumpXModelExport(const AssetDumpingContext &context, XAssetInfo<XModel> *asset); - protected: - bool ShouldDump(XAssetInfo<XModel>* asset) override; - void DumpAsset(AssetDumpingContext& context, XAssetInfo<XModel>* asset) override; - }; -} +protected: + bool ShouldDump(XAssetInfo<XModel> *asset) override; + void DumpAsset(AssetDumpingContext &context, XAssetInfo<XModel> *asset) override; +}; +} // namespace T5 diff --git a/src/ObjWriting/Game/T5/ZoneDumperT5.cpp b/src/ObjWriting/Game/T5/ZoneDumperT5.cpp index 3d8fd3c56..cadcef956 100644 --- a/src/ObjWriting/Game/T5/ZoneDumperT5.cpp +++ b/src/ObjWriting/Game/T5/ZoneDumperT5.cpp @@ -1,71 +1,66 @@ #include "ZoneDumperT5.h" -#include "ObjWriting.h" -#include "Game/T5/GameT5.h" #include "Game/T5/GameAssetPoolT5.h" +#include "Game/T5/GameT5.h" +#include "ObjWriting.h" -#include "AssetDumpers/AssetDumperRawFile.h" -#include "AssetDumpers/AssetDumperStringTable.h" -#include "AssetDumpers/AssetDumperLocalizeEntry.h" #include "AssetDumpers/AssetDumperGfxImage.h" +#include "AssetDumpers/AssetDumperLocalizeEntry.h" #include "AssetDumpers/AssetDumperPhysConstraints.h" #include "AssetDumpers/AssetDumperPhysPreset.h" +#include "AssetDumpers/AssetDumperRawFile.h" #include "AssetDumpers/AssetDumperSndBank.h" +#include "AssetDumpers/AssetDumperStringTable.h" #include "AssetDumpers/AssetDumperWeapon.h" #include "AssetDumpers/AssetDumperXModel.h" using namespace T5; -bool ZoneDumper::CanHandleZone(AssetDumpingContext& context) const -{ - return context.m_zone->m_game == &g_GameT5; -} +bool ZoneDumper::CanHandleZone(AssetDumpingContext &context) const { return context.m_zone->m_game == &g_GameT5; } -bool ZoneDumper::DumpZone(AssetDumpingContext& context) const -{ -#define DUMP_ASSET_POOL(dumperType, poolName, assetType) \ - if(assetPools->poolName && ObjWriting::ShouldHandleAssetType(assetType)) \ - { \ - dumperType dumper; \ - dumper.DumpPool(context, assetPools->poolName.get()); \ - } +bool ZoneDumper::DumpZone(AssetDumpingContext &context) const { +#define DUMP_ASSET_POOL(dumperType, poolName, assetType) \ + if (assetPools->poolName && ObjWriting::ShouldHandleAssetType(assetType)) { \ + dumperType dumper; \ + dumper.DumpPool(context, assetPools->poolName.get()); \ + } - const auto* assetPools = dynamic_cast<GameAssetPoolT5*>(context.m_zone->m_pools.get()); + const auto *assetPools = dynamic_cast<GameAssetPoolT5 *>(context.m_zone->m_pools.get()); - // DUMP_ASSET_POOL(AssetDumperPhysPreset, m_phys_preset, ASSET_TYPE_PHYSPRESET) - // DUMP_ASSET_POOL(AssetDumperPhysConstraints, m_phys_constraints, ASSET_TYPE_PHYSCONSTRAINTS) - // DUMP_ASSET_POOL(AssetDumperDestructibleDef, m_destructible_def, ASSET_TYPE_DESTRUCTIBLEDEF) - // DUMP_ASSET_POOL(AssetDumperXAnimParts, m_xanim_parts, ASSET_TYPE_XANIMPARTS) - DUMP_ASSET_POOL(AssetDumperXModel, m_xmodel, ASSET_TYPE_XMODEL) - // DUMP_ASSET_POOL(AssetDumperMaterial, m_material, ASSET_TYPE_MATERIAL) - // DUMP_ASSET_POOL(AssetDumperTechniqueSet, m_technique_set, ASSET_TYPE_TECHNIQUE_SET) - DUMP_ASSET_POOL(AssetDumperGfxImage, m_image, ASSET_TYPE_IMAGE) - // DUMP_ASSET_POOL(AssetDumperSndBank, m_sound_bank, ASSET_TYPE_SOUND) - // DUMP_ASSET_POOL(AssetDumperSndPatch, m_sound_patch, ASSET_TYPE_SOUND_PATCH) - // DUMP_ASSET_POOL(AssetDumperClipMap, m_clip_map, ASSET_TYPE_CLIPMAP) - // DUMP_ASSET_POOL(AssetDumperComWorld, m_com_world, ASSET_TYPE_COMWORLD) - // DUMP_ASSET_POOL(AssetDumperGameWorldSp, m_game_world_sp, ASSET_TYPE_GAMEWORLD_SP) - // DUMP_ASSET_POOL(AssetDumperGameWorldMp, m_game_world_mp, ASSET_TYPE_GAMEWORLD_MP) - // DUMP_ASSET_POOL(AssetDumperMapEnts, m_map_ents, ASSET_TYPE_MAP_ENTS) - // DUMP_ASSET_POOL(AssetDumperGfxWorld, m_gfx_world, ASSET_TYPE_GFXWORLD) - // DUMP_ASSET_POOL(AssetDumperGfxLightDef, m_gfx_light_def, ASSET_TYPE_LIGHT_DEF) - // DUMP_ASSET_POOL(AssetDumperFont, m_font, ASSET_TYPE_FONT) - // DUMP_ASSET_POOL(AssetDumperMenuList, m_menu_list, ASSET_TYPE_MENULIST) - // DUMP_ASSET_POOL(AssetDumperMenuDef, m_menu_def, ASSET_TYPE_MENU) - DUMP_ASSET_POOL(AssetDumperLocalizeEntry, m_localize, ASSET_TYPE_LOCALIZE_ENTRY) - // DUMP_ASSET_POOL(AssetDumperWeapon, m_weapon, ASSET_TYPE_WEAPON) - // DUMP_ASSET_POOL(AssetDumperSndDriverGlobals, m_snd_driver_globals, ASSET_TYPE_SNDDRIVER_GLOBALS) - // DUMP_ASSET_POOL(AssetDumperFxEffectDef, m_fx, ASSET_TYPE_FX) - // DUMP_ASSET_POOL(AssetDumperFxImpactTable, m_fx_impact_table, ASSET_TYPE_IMPACT_FX) - DUMP_ASSET_POOL(AssetDumperRawFile, m_raw_file, ASSET_TYPE_RAWFILE) - DUMP_ASSET_POOL(AssetDumperStringTable, m_string_table, ASSET_TYPE_STRINGTABLE) - // DUMP_ASSET_POOL(AssetDumperPackIndex, m_pack_index, ASSET_TYPE_PACK_INDEX) - // DUMP_ASSET_POOL(AssetDumperXGlobals, m_xglobals, ASSET_TYPE_XGLOBALS) - // DUMP_ASSET_POOL(AssetDumperDDLRoot, m_ddl, ASSET_TYPE_DDL) - // DUMP_ASSET_POOL(AssetDumperGlasses, m_glasses, ASSET_TYPE_GLASSES) - // DUMP_ASSET_POOL(AssetDumperEmblemSet, m_emblem_set, ASSET_TYPE_EMBLEMSET) + // DUMP_ASSET_POOL(AssetDumperPhysPreset, m_phys_preset, ASSET_TYPE_PHYSPRESET) + // DUMP_ASSET_POOL(AssetDumperPhysConstraints, m_phys_constraints, ASSET_TYPE_PHYSCONSTRAINTS) + // DUMP_ASSET_POOL(AssetDumperDestructibleDef, m_destructible_def, ASSET_TYPE_DESTRUCTIBLEDEF) + // DUMP_ASSET_POOL(AssetDumperXAnimParts, m_xanim_parts, ASSET_TYPE_XANIMPARTS) + DUMP_ASSET_POOL(AssetDumperXModel, m_xmodel, ASSET_TYPE_XMODEL) + // DUMP_ASSET_POOL(AssetDumperMaterial, m_material, ASSET_TYPE_MATERIAL) + // DUMP_ASSET_POOL(AssetDumperTechniqueSet, m_technique_set, ASSET_TYPE_TECHNIQUE_SET) + DUMP_ASSET_POOL(AssetDumperGfxImage, m_image, ASSET_TYPE_IMAGE) + // DUMP_ASSET_POOL(AssetDumperSndBank, m_sound_bank, ASSET_TYPE_SOUND) + // DUMP_ASSET_POOL(AssetDumperSndPatch, m_sound_patch, ASSET_TYPE_SOUND_PATCH) + // DUMP_ASSET_POOL(AssetDumperClipMap, m_clip_map, ASSET_TYPE_CLIPMAP) + // DUMP_ASSET_POOL(AssetDumperComWorld, m_com_world, ASSET_TYPE_COMWORLD) + // DUMP_ASSET_POOL(AssetDumperGameWorldSp, m_game_world_sp, ASSET_TYPE_GAMEWORLD_SP) + // DUMP_ASSET_POOL(AssetDumperGameWorldMp, m_game_world_mp, ASSET_TYPE_GAMEWORLD_MP) + // DUMP_ASSET_POOL(AssetDumperMapEnts, m_map_ents, ASSET_TYPE_MAP_ENTS) + // DUMP_ASSET_POOL(AssetDumperGfxWorld, m_gfx_world, ASSET_TYPE_GFXWORLD) + // DUMP_ASSET_POOL(AssetDumperGfxLightDef, m_gfx_light_def, ASSET_TYPE_LIGHT_DEF) + // DUMP_ASSET_POOL(AssetDumperFont, m_font, ASSET_TYPE_FONT) + // DUMP_ASSET_POOL(AssetDumperMenuList, m_menu_list, ASSET_TYPE_MENULIST) + // DUMP_ASSET_POOL(AssetDumperMenuDef, m_menu_def, ASSET_TYPE_MENU) + DUMP_ASSET_POOL(AssetDumperLocalizeEntry, m_localize, ASSET_TYPE_LOCALIZE_ENTRY) + // DUMP_ASSET_POOL(AssetDumperWeapon, m_weapon, ASSET_TYPE_WEAPON) + // DUMP_ASSET_POOL(AssetDumperSndDriverGlobals, m_snd_driver_globals, ASSET_TYPE_SNDDRIVER_GLOBALS) + // DUMP_ASSET_POOL(AssetDumperFxEffectDef, m_fx, ASSET_TYPE_FX) + // DUMP_ASSET_POOL(AssetDumperFxImpactTable, m_fx_impact_table, ASSET_TYPE_IMPACT_FX) + DUMP_ASSET_POOL(AssetDumperRawFile, m_raw_file, ASSET_TYPE_RAWFILE) + DUMP_ASSET_POOL(AssetDumperStringTable, m_string_table, ASSET_TYPE_STRINGTABLE) + // DUMP_ASSET_POOL(AssetDumperPackIndex, m_pack_index, ASSET_TYPE_PACK_INDEX) + // DUMP_ASSET_POOL(AssetDumperXGlobals, m_xglobals, ASSET_TYPE_XGLOBALS) + // DUMP_ASSET_POOL(AssetDumperDDLRoot, m_ddl, ASSET_TYPE_DDL) + // DUMP_ASSET_POOL(AssetDumperGlasses, m_glasses, ASSET_TYPE_GLASSES) + // DUMP_ASSET_POOL(AssetDumperEmblemSet, m_emblem_set, ASSET_TYPE_EMBLEMSET) - return true; + return true; #undef DUMP_ASSET_POOL } diff --git a/src/ObjWriting/Game/T5/ZoneDumperT5.h b/src/ObjWriting/Game/T5/ZoneDumperT5.h index 5d90906f8..dadad5b85 100644 --- a/src/ObjWriting/Game/T5/ZoneDumperT5.h +++ b/src/ObjWriting/Game/T5/ZoneDumperT5.h @@ -1,12 +1,10 @@ #pragma once #include "Dumping/IZoneDumper.h" -namespace T5 -{ - class ZoneDumper final : public IZoneDumper - { - public: - bool CanHandleZone(AssetDumpingContext& context) const override; - bool DumpZone(AssetDumpingContext& context) const override; - }; -} +namespace T5 { +class ZoneDumper final : public IZoneDumper { +public: + bool CanHandleZone(AssetDumpingContext &context) const override; + bool DumpZone(AssetDumpingContext &context) const override; +}; +} // namespace T5 diff --git a/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperFontIcon.cpp b/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperFontIcon.cpp index cbb02436f..82d343db9 100644 --- a/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperFontIcon.cpp +++ b/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperFontIcon.cpp @@ -7,266 +7,225 @@ using namespace T6; -class AssetDumperFontIconInternal -{ - class KnownAlias - { - public: - std::string m_name; - int m_hash; - - explicit KnownAlias(std::string aliasName) - : m_name(std::move(aliasName)) - { - m_hash = Common::Com_HashString(m_name.c_str(), 0); - } - }; - - inline static const std::string TYPE_ICON = "icon"; - inline static const std::string ICON_HEADERS[] - { - "# index", - "# type", - "# name", - "# material", - "# size", - "# xScale", - "# yScale" - }; - - inline static const std::string TYPE_ALIAS = "alias"; - inline static const std::string ALIAS_HEADERS[] - { - "# index", - "# type", - "# alias", - "# button" - }; - - inline static const KnownAlias KNOWN_ALIASES[] - { - KnownAlias("BUTTON_ADS"), - KnownAlias("BUTTON_CAC_NEXT"), - KnownAlias("BUTTON_CAC_PREV"), - KnownAlias("BUTTON_CANCEL"), - KnownAlias("BUTTON_CAROUSEL_STICK"), - KnownAlias("BUTTON_CREATE"), - KnownAlias("BUTTON_CYCLE_LEFT"), - KnownAlias("BUTTON_CYCLE_LEFT_ACTIVE"), - KnownAlias("BUTTON_CYCLE_RIGHT"), - KnownAlias("BUTTON_CYCLE_RIGHT_ACTIVE"), - KnownAlias("BUTTON_DELETE"), - KnownAlias("BUTTON_EDIT"), - KnownAlias("BUTTON_EMBLEM_BACKWARD"), - KnownAlias("BUTTON_EMBLEM_FLIP"), - KnownAlias("BUTTON_EMBLEM_FORWARD"), - KnownAlias("BUTTON_EMBLEM_FORWARD_BACKWARD"), - KnownAlias("BUTTON_EMBLEM_MOVE"), - KnownAlias("BUTTON_EMBLEM_OUTLINE"), - KnownAlias("BUTTON_EMBLEM_PALETTE_CYCLE"), - KnownAlias("BUTTON_EMBLEM_PALETTE_NEXT"), - KnownAlias("BUTTON_EMBLEM_PALETTE_PREV"), - KnownAlias("BUTTON_EMBLEM_RESET"), - KnownAlias("BUTTON_EMBLEM_ROTATE_LEFT"), - KnownAlias("BUTTON_EMBLEM_ROTATE_RIGHT"), - KnownAlias("BUTTON_EMBLEM_SCALE"), - KnownAlias("BUTTON_FIRE"), - KnownAlias("BUTTON_FRIENDSLIST"), - KnownAlias("BUTTON_INTERACT"), - KnownAlias("BUTTON_LOOKSTICK"), - KnownAlias("BUTTON_LOOK"), - KnownAlias("BUTTON_LUI_ALT1"), - KnownAlias("BUTTON_LUI_ALT2"), - KnownAlias("BUTTON_LUI_DPAD_ALL"), - KnownAlias("BUTTON_LUI_DPAD_D"), - KnownAlias("BUTTON_LUI_DPAD_L"), - KnownAlias("BUTTON_LUI_DPAD_RL"), - KnownAlias("BUTTON_LUI_DPAD_R"), - KnownAlias("BUTTON_LUI_DPAD_UD"), - KnownAlias("BUTTON_LUI_DPAD_U"), - KnownAlias("BUTTON_LUI_LEFT_STICK_UP"), - KnownAlias("BUTTON_LUI_LEFT_TRIGGER"), - KnownAlias("BUTTON_LUI_PRIMARY"), - KnownAlias("BUTTON_LUI_RIGHT_STICK"), - KnownAlias("BUTTON_LUI_RIGHT_TRIGGER"), - KnownAlias("BUTTON_LUI_SECONDARY"), - KnownAlias("BUTTON_LUI_SELECT"), - KnownAlias("BUTTON_LUI_SHOULDERL"), - KnownAlias("BUTTON_LUI_SHOULDERR"), - KnownAlias("BUTTON_LUI_START"), - KnownAlias("BUTTON_MOUSE_CLICK"), - KnownAlias("BUTTON_MOUSE_CLICK_ACTIVE"), - KnownAlias("BUTTON_MOUSE_EDIT"), - KnownAlias("BUTTON_MOUSE_EDIT_ACTIVE"), - KnownAlias("BUTTON_MOUSE_LEFT"), - KnownAlias("BUTTON_MOUSE_MIDDLE"), - KnownAlias("BUTTON_MOUSE_RIGHT"), - KnownAlias("BUTTON_MOVESTICK"), - KnownAlias("BUTTON_MOVE"), - KnownAlias("BUTTON_MP_CANCELCOMMAND"), - KnownAlias("BUTTON_MP_CHANGESETTINGS"), - KnownAlias("BUTTON_MP_GAMERCARD"), - KnownAlias("BUTTON_MP_GAMERREVIEW"), - KnownAlias("BUTTON_MP_JOINGAME"), - KnownAlias("BUTTON_MP_KICKPLAYER"), - KnownAlias("BUTTON_MP_LEAVEGAME"), - KnownAlias("BUTTON_MP_LOBBY_GAMERCARD"), - KnownAlias("BUTTON_MP_NOTREADY"), - KnownAlias("BUTTON_MP_PGDOWN"), - KnownAlias("BUTTON_MP_PGUP"), - KnownAlias("BUTTON_MP_READY"), - KnownAlias("BUTTON_MP_REFRESH"), - KnownAlias("BUTTON_MP_SCOREBOARD"), - KnownAlias("BUTTON_MP_SIGNIN"), - KnownAlias("BUTTON_MP_SPECNEXT"), - KnownAlias("BUTTON_MP_SPECPREV"), - KnownAlias("BUTTON_MP_STARTGAME"), - KnownAlias("BUTTON_MP_TOGGLECHASECAM"), - KnownAlias("BUTTON_MP_TOGGLEVIEW"), - KnownAlias("BUTTON_NO"), - KnownAlias("BUTTON_RECORD_VIEW_NEXT"), - KnownAlias("BUTTON_RECORD_VIEW_PREV"), - KnownAlias("BUTTON_SELECTCHOICE"), - KnownAlias("BUTTON_SP_TOGGLEMENU"), - KnownAlias("BUTTON_YES"), - KnownAlias("CP"), - KnownAlias("FONT_CAPITAL_I"), - KnownAlias("FONT_NUMBER_ZERO"), - KnownAlias("KEY_DOWN_ARROW"), - KnownAlias("KEY_LEFT_ARROW"), - KnownAlias("KEY_RIGHT_ARROW"), - KnownAlias("KEY_UP_ARROW"), - KnownAlias("MOUSE_WHEEL_DOWN"), - KnownAlias("MOUSE_WHEEL_UP"), - KnownAlias("Remote_LStick") - }; - - CsvOutputStream m_csv; - - static FontIconEntry* FindEntryByHash(FontIcon* fontIcon, const int hash) - { - int lowerBound = 0; - int upperBound = fontIcon->numEntries; - - while (true) - { - const int entryIndex = (lowerBound + upperBound) / 2; - auto* entry = &fontIcon->fontIconEntry[entryIndex]; - - if (entry->fontIconName.hash == hash) - return entry; - - if (lowerBound == upperBound) - return nullptr; - - if (entry->fontIconName.hash < hash) - lowerBound = entryIndex + 1; - else - upperBound = entryIndex - 1; - } - } - - static const KnownAlias* FindKnownAliasByHash(const int hash) - { - for (const auto& i : KNOWN_ALIASES) - { - if (i.m_hash == hash) - return &i; - } - +class AssetDumperFontIconInternal { + class KnownAlias { + public: + std::string m_name; + int m_hash; + + explicit KnownAlias(std::string aliasName) : m_name(std::move(aliasName)) { m_hash = Common::Com_HashString(m_name.c_str(), 0); } + }; + + inline static const std::string TYPE_ICON = "icon"; + inline static const std::string ICON_HEADERS[]{"# index", "# type", "# name", "# material", "# size", "# xScale", "# yScale"}; + + inline static const std::string TYPE_ALIAS = "alias"; + inline static const std::string ALIAS_HEADERS[]{"# index", "# type", "# alias", "# button"}; + + inline static const KnownAlias KNOWN_ALIASES[]{KnownAlias("BUTTON_ADS"), + KnownAlias("BUTTON_CAC_NEXT"), + KnownAlias("BUTTON_CAC_PREV"), + KnownAlias("BUTTON_CANCEL"), + KnownAlias("BUTTON_CAROUSEL_STICK"), + KnownAlias("BUTTON_CREATE"), + KnownAlias("BUTTON_CYCLE_LEFT"), + KnownAlias("BUTTON_CYCLE_LEFT_ACTIVE"), + KnownAlias("BUTTON_CYCLE_RIGHT"), + KnownAlias("BUTTON_CYCLE_RIGHT_ACTIVE"), + KnownAlias("BUTTON_DELETE"), + KnownAlias("BUTTON_EDIT"), + KnownAlias("BUTTON_EMBLEM_BACKWARD"), + KnownAlias("BUTTON_EMBLEM_FLIP"), + KnownAlias("BUTTON_EMBLEM_FORWARD"), + KnownAlias("BUTTON_EMBLEM_FORWARD_BACKWARD"), + KnownAlias("BUTTON_EMBLEM_MOVE"), + KnownAlias("BUTTON_EMBLEM_OUTLINE"), + KnownAlias("BUTTON_EMBLEM_PALETTE_CYCLE"), + KnownAlias("BUTTON_EMBLEM_PALETTE_NEXT"), + KnownAlias("BUTTON_EMBLEM_PALETTE_PREV"), + KnownAlias("BUTTON_EMBLEM_RESET"), + KnownAlias("BUTTON_EMBLEM_ROTATE_LEFT"), + KnownAlias("BUTTON_EMBLEM_ROTATE_RIGHT"), + KnownAlias("BUTTON_EMBLEM_SCALE"), + KnownAlias("BUTTON_FIRE"), + KnownAlias("BUTTON_FRIENDSLIST"), + KnownAlias("BUTTON_INTERACT"), + KnownAlias("BUTTON_LOOKSTICK"), + KnownAlias("BUTTON_LOOK"), + KnownAlias("BUTTON_LUI_ALT1"), + KnownAlias("BUTTON_LUI_ALT2"), + KnownAlias("BUTTON_LUI_DPAD_ALL"), + KnownAlias("BUTTON_LUI_DPAD_D"), + KnownAlias("BUTTON_LUI_DPAD_L"), + KnownAlias("BUTTON_LUI_DPAD_RL"), + KnownAlias("BUTTON_LUI_DPAD_R"), + KnownAlias("BUTTON_LUI_DPAD_UD"), + KnownAlias("BUTTON_LUI_DPAD_U"), + KnownAlias("BUTTON_LUI_LEFT_STICK_UP"), + KnownAlias("BUTTON_LUI_LEFT_TRIGGER"), + KnownAlias("BUTTON_LUI_PRIMARY"), + KnownAlias("BUTTON_LUI_RIGHT_STICK"), + KnownAlias("BUTTON_LUI_RIGHT_TRIGGER"), + KnownAlias("BUTTON_LUI_SECONDARY"), + KnownAlias("BUTTON_LUI_SELECT"), + KnownAlias("BUTTON_LUI_SHOULDERL"), + KnownAlias("BUTTON_LUI_SHOULDERR"), + KnownAlias("BUTTON_LUI_START"), + KnownAlias("BUTTON_MOUSE_CLICK"), + KnownAlias("BUTTON_MOUSE_CLICK_ACTIVE"), + KnownAlias("BUTTON_MOUSE_EDIT"), + KnownAlias("BUTTON_MOUSE_EDIT_ACTIVE"), + KnownAlias("BUTTON_MOUSE_LEFT"), + KnownAlias("BUTTON_MOUSE_MIDDLE"), + KnownAlias("BUTTON_MOUSE_RIGHT"), + KnownAlias("BUTTON_MOVESTICK"), + KnownAlias("BUTTON_MOVE"), + KnownAlias("BUTTON_MP_CANCELCOMMAND"), + KnownAlias("BUTTON_MP_CHANGESETTINGS"), + KnownAlias("BUTTON_MP_GAMERCARD"), + KnownAlias("BUTTON_MP_GAMERREVIEW"), + KnownAlias("BUTTON_MP_JOINGAME"), + KnownAlias("BUTTON_MP_KICKPLAYER"), + KnownAlias("BUTTON_MP_LEAVEGAME"), + KnownAlias("BUTTON_MP_LOBBY_GAMERCARD"), + KnownAlias("BUTTON_MP_NOTREADY"), + KnownAlias("BUTTON_MP_PGDOWN"), + KnownAlias("BUTTON_MP_PGUP"), + KnownAlias("BUTTON_MP_READY"), + KnownAlias("BUTTON_MP_REFRESH"), + KnownAlias("BUTTON_MP_SCOREBOARD"), + KnownAlias("BUTTON_MP_SIGNIN"), + KnownAlias("BUTTON_MP_SPECNEXT"), + KnownAlias("BUTTON_MP_SPECPREV"), + KnownAlias("BUTTON_MP_STARTGAME"), + KnownAlias("BUTTON_MP_TOGGLECHASECAM"), + KnownAlias("BUTTON_MP_TOGGLEVIEW"), + KnownAlias("BUTTON_NO"), + KnownAlias("BUTTON_RECORD_VIEW_NEXT"), + KnownAlias("BUTTON_RECORD_VIEW_PREV"), + KnownAlias("BUTTON_SELECTCHOICE"), + KnownAlias("BUTTON_SP_TOGGLEMENU"), + KnownAlias("BUTTON_YES"), + KnownAlias("CP"), + KnownAlias("FONT_CAPITAL_I"), + KnownAlias("FONT_NUMBER_ZERO"), + KnownAlias("KEY_DOWN_ARROW"), + KnownAlias("KEY_LEFT_ARROW"), + KnownAlias("KEY_RIGHT_ARROW"), + KnownAlias("KEY_UP_ARROW"), + KnownAlias("MOUSE_WHEEL_DOWN"), + KnownAlias("MOUSE_WHEEL_UP"), + KnownAlias("Remote_LStick")}; + + CsvOutputStream m_csv; + + static FontIconEntry *FindEntryByHash(FontIcon *fontIcon, const int hash) { + int lowerBound = 0; + int upperBound = fontIcon->numEntries; + + while (true) { + const int entryIndex = (lowerBound + upperBound) / 2; + auto *entry = &fontIcon->fontIconEntry[entryIndex]; + + if (entry->fontIconName.hash == hash) + return entry; + + if (lowerBound == upperBound) return nullptr; + + if (entry->fontIconName.hash < hash) + lowerBound = entryIndex + 1; + else + upperBound = entryIndex - 1; } + } - void WriteFontIconEntries(FontIcon* fontIcon) - { - for (const auto& header : ICON_HEADERS) - m_csv.WriteColumn(header); - m_csv.NextRow(); - - for (int iconIndex = 0; iconIndex < fontIcon->numEntries; iconIndex++) - { - auto* entry = &fontIcon->fontIconEntry[iconIndex]; - m_csv.WriteColumn(std::to_string(iconIndex)); - m_csv.WriteColumn(TYPE_ICON); - - if (entry->fontIconName.string) - m_csv.WriteColumn(entry->fontIconName.string); - else - m_csv.WriteColumn(""); - - if (entry->fontIconMaterialHandle && entry->fontIconMaterialHandle->info.name) - m_csv.WriteColumn(entry->fontIconMaterialHandle->info.name); - else - m_csv.WriteColumn(""); - - m_csv.WriteColumn(std::to_string(entry->fontIconSize)); - m_csv.WriteColumn(std::to_string(entry->xScale)); - m_csv.WriteColumn(std::to_string(entry->yScale)); - - m_csv.NextRow(); - } + static const KnownAlias *FindKnownAliasByHash(const int hash) { + for (const auto &i : KNOWN_ALIASES) { + if (i.m_hash == hash) + return &i; } - void WriteFontIconAliases(FontIcon* fontIcon) - { - for (const auto& header : ALIAS_HEADERS) - m_csv.WriteColumn(header); - m_csv.NextRow(); - - for (int aliasIndex = 0; aliasIndex < fontIcon->numAliasEntries; aliasIndex++) - { - auto* alias = &fontIcon->fontIconAlias[aliasIndex]; - m_csv.WriteColumn(std::to_string(aliasIndex)); - m_csv.WriteColumn(TYPE_ALIAS); - - auto* knownAlias = FindKnownAliasByHash(alias->aliasHash); - if (knownAlias) - m_csv.WriteColumn(knownAlias->m_name); - else - { - std::ostringstream str; - str << '@' << std::hex << alias->aliasHash; - - m_csv.WriteColumn(str.str()); - } - - auto* referencedEntry = FindEntryByHash(fontIcon, alias->buttonHash); - if (referencedEntry && referencedEntry->fontIconName.string) - m_csv.WriteColumn(referencedEntry->fontIconName.string); - else - m_csv.WriteColumn(""); - - m_csv.NextRow(); - } + return nullptr; + } + + void WriteFontIconEntries(FontIcon *fontIcon) { + for (const auto &header : ICON_HEADERS) + m_csv.WriteColumn(header); + m_csv.NextRow(); + + for (int iconIndex = 0; iconIndex < fontIcon->numEntries; iconIndex++) { + auto *entry = &fontIcon->fontIconEntry[iconIndex]; + m_csv.WriteColumn(std::to_string(iconIndex)); + m_csv.WriteColumn(TYPE_ICON); + + if (entry->fontIconName.string) + m_csv.WriteColumn(entry->fontIconName.string); + else + m_csv.WriteColumn(""); + + if (entry->fontIconMaterialHandle && entry->fontIconMaterialHandle->info.name) + m_csv.WriteColumn(entry->fontIconMaterialHandle->info.name); + else + m_csv.WriteColumn(""); + + m_csv.WriteColumn(std::to_string(entry->fontIconSize)); + m_csv.WriteColumn(std::to_string(entry->xScale)); + m_csv.WriteColumn(std::to_string(entry->yScale)); + + m_csv.NextRow(); + } + } + + void WriteFontIconAliases(FontIcon *fontIcon) { + for (const auto &header : ALIAS_HEADERS) + m_csv.WriteColumn(header); + m_csv.NextRow(); + + for (int aliasIndex = 0; aliasIndex < fontIcon->numAliasEntries; aliasIndex++) { + auto *alias = &fontIcon->fontIconAlias[aliasIndex]; + m_csv.WriteColumn(std::to_string(aliasIndex)); + m_csv.WriteColumn(TYPE_ALIAS); + + auto *knownAlias = FindKnownAliasByHash(alias->aliasHash); + if (knownAlias) + m_csv.WriteColumn(knownAlias->m_name); + else { + std::ostringstream str; + str << '@' << std::hex << alias->aliasHash; + + m_csv.WriteColumn(str.str()); + } + + auto *referencedEntry = FindEntryByHash(fontIcon, alias->buttonHash); + if (referencedEntry && referencedEntry->fontIconName.string) + m_csv.WriteColumn(referencedEntry->fontIconName.string); + else + m_csv.WriteColumn(""); + + m_csv.NextRow(); } + } public: - explicit AssetDumperFontIconInternal(std::ostream& stream) - : m_csv(stream) - { - } + explicit AssetDumperFontIconInternal(std::ostream &stream) : m_csv(stream) {} - void DumpFontIcon(FontIcon* fontIcon) - { - WriteFontIconEntries(fontIcon); - m_csv.NextRow(); + void DumpFontIcon(FontIcon *fontIcon) { + WriteFontIconEntries(fontIcon); + m_csv.NextRow(); - WriteFontIconAliases(fontIcon); - } + WriteFontIconAliases(fontIcon); + } }; -bool AssetDumperFontIcon::ShouldDump(XAssetInfo<FontIcon>* asset) -{ - return true; -} +bool AssetDumperFontIcon::ShouldDump(XAssetInfo<FontIcon> *asset) { return true; } -void AssetDumperFontIcon::DumpAsset(AssetDumpingContext& context, XAssetInfo<FontIcon>* asset) -{ - const auto assetFile = context.OpenAssetFile(asset->m_name); +void AssetDumperFontIcon::DumpAsset(AssetDumpingContext &context, XAssetInfo<FontIcon> *asset) { + const auto assetFile = context.OpenAssetFile(asset->m_name); - if (!assetFile) - return; + if (!assetFile) + return; - AssetDumperFontIconInternal dumper(*assetFile); - dumper.DumpFontIcon(asset->Asset()); + AssetDumperFontIconInternal dumper(*assetFile); + dumper.DumpFontIcon(asset->Asset()); } diff --git a/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperFontIcon.h b/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperFontIcon.h index 23f1d54f7..2285cd24b 100644 --- a/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperFontIcon.h +++ b/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperFontIcon.h @@ -3,12 +3,10 @@ #include "Dumping/AbstractAssetDumper.h" #include "Game/T6/T6.h" -namespace T6 -{ - class AssetDumperFontIcon final : public AbstractAssetDumper<FontIcon> - { - protected: - bool ShouldDump(XAssetInfo<FontIcon>* asset) override; - void DumpAsset(AssetDumpingContext& context, XAssetInfo<FontIcon>* asset) override; - }; -} +namespace T6 { +class AssetDumperFontIcon final : public AbstractAssetDumper<FontIcon> { +protected: + bool ShouldDump(XAssetInfo<FontIcon> *asset) override; + void DumpAsset(AssetDumpingContext &context, XAssetInfo<FontIcon> *asset) override; +}; +} // namespace T6 diff --git a/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperGfxImage.cpp b/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperGfxImage.cpp index a205c05d8..49198c1bf 100644 --- a/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperGfxImage.cpp +++ b/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperGfxImage.cpp @@ -2,62 +2,55 @@ #include <cassert> -#include "ObjWriting.h" -#include "Image/IwiWriter27.h" #include "Image/DdsWriter.h" +#include "Image/IwiWriter27.h" +#include "ObjWriting.h" using namespace T6; -AssetDumperGfxImage::AssetDumperGfxImage() -{ - switch (ObjWriting::Configuration.ImageOutputFormat) - { - case ObjWriting::Configuration_t::ImageOutputFormat_e::DDS: - m_writer = std::make_unique<DdsWriter>(); - break; - case ObjWriting::Configuration_t::ImageOutputFormat_e::IWI: - m_writer = std::make_unique<iwi27::IwiWriter>(); - break; - default: - assert(false); - m_writer = nullptr; - break; - } +AssetDumperGfxImage::AssetDumperGfxImage() { + switch (ObjWriting::Configuration.ImageOutputFormat) { + case ObjWriting::Configuration_t::ImageOutputFormat_e::DDS: + m_writer = std::make_unique<DdsWriter>(); + break; + case ObjWriting::Configuration_t::ImageOutputFormat_e::IWI: + m_writer = std::make_unique<iwi27::IwiWriter>(); + break; + default: + assert(false); + m_writer = nullptr; + break; + } } -bool AssetDumperGfxImage::ShouldDump(XAssetInfo<GfxImage>* asset) -{ - const auto* image = asset->Asset(); - return image->loadedSize > 0; +bool AssetDumperGfxImage::ShouldDump(XAssetInfo<GfxImage> *asset) { + const auto *image = asset->Asset(); + return image->loadedSize > 0; } -std::string AssetDumperGfxImage::GetAssetFileName(XAssetInfo<GfxImage>* asset) const -{ - std::string cleanAssetName = asset->m_name; - for (auto& c : cleanAssetName) - { - switch (c) - { - case '*': - c = '_'; - break; - - default: - break; - } +std::string AssetDumperGfxImage::GetAssetFileName(XAssetInfo<GfxImage> *asset) const { + std::string cleanAssetName = asset->m_name; + for (auto &c : cleanAssetName) { + switch (c) { + case '*': + c = '_'; + break; + + default: + break; } + } - return "images/" + cleanAssetName + m_writer->GetFileExtension(); + return "images/" + cleanAssetName + m_writer->GetFileExtension(); } -void AssetDumperGfxImage::DumpAsset(AssetDumpingContext& context, XAssetInfo<GfxImage>* asset) -{ - const auto* image = asset->Asset(); - const auto assetFile = context.OpenAssetFile(GetAssetFileName(asset)); +void AssetDumperGfxImage::DumpAsset(AssetDumpingContext &context, XAssetInfo<GfxImage> *asset) { + const auto *image = asset->Asset(); + const auto assetFile = context.OpenAssetFile(GetAssetFileName(asset)); - if (!assetFile) - return; + if (!assetFile) + return; - auto& stream = *assetFile; - m_writer->DumpImage(stream, image->texture.texture); + auto &stream = *assetFile; + m_writer->DumpImage(stream, image->texture.texture); } diff --git a/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperGfxImage.h b/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperGfxImage.h index 456dd84b8..0d9660fea 100644 --- a/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperGfxImage.h +++ b/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperGfxImage.h @@ -6,19 +6,17 @@ #include "Game/T6/T6.h" #include "Image/IImageWriter.h" -namespace T6 -{ - class AssetDumperGfxImage final : public AbstractAssetDumper<GfxImage> - { - std::unique_ptr<IImageWriter> m_writer; +namespace T6 { +class AssetDumperGfxImage final : public AbstractAssetDumper<GfxImage> { + std::unique_ptr<IImageWriter> m_writer; - std::string GetAssetFileName(XAssetInfo<GfxImage>* asset) const; + std::string GetAssetFileName(XAssetInfo<GfxImage> *asset) const; - protected: - bool ShouldDump(XAssetInfo<GfxImage>* asset) override; - void DumpAsset(AssetDumpingContext& context, XAssetInfo<GfxImage>* asset) override; +protected: + bool ShouldDump(XAssetInfo<GfxImage> *asset) override; + void DumpAsset(AssetDumpingContext &context, XAssetInfo<GfxImage> *asset) override; - public: - AssetDumperGfxImage(); - }; -} +public: + AssetDumperGfxImage(); +}; +} // namespace T6 diff --git a/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperLocalizeEntry.cpp b/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperLocalizeEntry.cpp index 212ff1900..7636f831c 100644 --- a/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperLocalizeEntry.cpp +++ b/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperLocalizeEntry.cpp @@ -2,42 +2,37 @@ #include <sstream> -#include "Localize/LocalizeCommon.h" #include "Dumping/Localize/StringFileDumper.h" +#include "Localize/LocalizeCommon.h" using namespace T6; -void AssetDumperLocalizeEntry::DumpPool(AssetDumpingContext& context, AssetPool<LocalizeEntry>* pool) -{ - if (pool->m_asset_lookup.empty()) - return; - - const auto language = LocalizeCommon::GetNameOfLanguage(context.m_zone->m_language); +void AssetDumperLocalizeEntry::DumpPool(AssetDumpingContext &context, AssetPool<LocalizeEntry> *pool) { + if (pool->m_asset_lookup.empty()) + return; - std::ostringstream ss; - ss << language << "/localizedstrings/" << context.m_zone->m_name << ".str"; - const auto assetFile = context.OpenAssetFile(ss.str()); + const auto language = LocalizeCommon::GetNameOfLanguage(context.m_zone->m_language); - if (assetFile) - { - StringFileDumper stringFileDumper(context.m_zone, *assetFile); + std::ostringstream ss; + ss << language << "/localizedstrings/" << context.m_zone->m_name << ".str"; + const auto assetFile = context.OpenAssetFile(ss.str()); - stringFileDumper.SetLanguageName(language); + if (assetFile) { + StringFileDumper stringFileDumper(context.m_zone, *assetFile); - // Magic string. Original string files do have this config file. The purpose of the config file is unknown though. - stringFileDumper.SetConfigFile(R"(C:/projects/cod/t6/bin/StringEd.cfg)"); + stringFileDumper.SetLanguageName(language); - stringFileDumper.SetNotes(""); + // Magic string. Original string files do have this config file. The purpose of the config file is unknown though. + stringFileDumper.SetConfigFile(R"(C:/projects/cod/t6/bin/StringEd.cfg)"); - for(auto* localizeEntry : *pool) - { - stringFileDumper.WriteLocalizeEntry(localizeEntry->m_name, localizeEntry->Asset()->value); - } + stringFileDumper.SetNotes(""); - stringFileDumper.Finalize(); - } - else - { - printf("Could not create string file for dumping localized strings of zone '%s'\n", context.m_zone->m_name.c_str()); + for (auto *localizeEntry : *pool) { + stringFileDumper.WriteLocalizeEntry(localizeEntry->m_name, localizeEntry->Asset()->value); } + + stringFileDumper.Finalize(); + } else { + printf("Could not create string file for dumping localized strings of zone '%s'\n", context.m_zone->m_name.c_str()); + } } \ No newline at end of file diff --git a/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperLocalizeEntry.h b/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperLocalizeEntry.h index 06d7cfe2c..2ef9e185d 100644 --- a/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperLocalizeEntry.h +++ b/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperLocalizeEntry.h @@ -3,11 +3,9 @@ #include "Dumping/AbstractAssetDumper.h" #include "Game/T6/T6.h" -namespace T6 -{ - class AssetDumperLocalizeEntry final : public IAssetDumper<LocalizeEntry> - { - public: - void DumpPool(AssetDumpingContext& context, AssetPool<LocalizeEntry>* pool) override; - }; -} +namespace T6 { +class AssetDumperLocalizeEntry final : public IAssetDumper<LocalizeEntry> { +public: + void DumpPool(AssetDumpingContext &context, AssetPool<LocalizeEntry> *pool) override; +}; +} // namespace T6 diff --git a/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperPhysConstraints.cpp b/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperPhysConstraints.cpp index 7568ef9e4..8578b70ea 100644 --- a/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperPhysConstraints.cpp +++ b/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperPhysConstraints.cpp @@ -3,81 +3,68 @@ #include <cassert> #include <type_traits> -#include "Game/T6/ObjConstantsT6.h" #include "Game/T6/InfoString/EnumStrings.h" #include "Game/T6/InfoString/InfoStringFromStructConverter.h" #include "Game/T6/InfoString/PhysConstraintsFields.h" +#include "Game/T6/ObjConstantsT6.h" using namespace T6; -namespace T6 -{ - class InfoStringFromPhysConstraintsConverter final : public InfoStringFromStructConverter - { - protected: - void FillFromExtensionField(const cspField_t& field) override - { - switch (static_cast<constraintsFieldType_t>(field.iFieldType)) - { - case CFT_TYPE: - FillFromEnumInt(std::string(field.szName), field.iOffset, s_constraintTypeNames, std::extent<decltype(s_constraintTypeNames)>::value); - break; - - default: - assert(false); - break; - } - } +namespace T6 { +class InfoStringFromPhysConstraintsConverter final : public InfoStringFromStructConverter { +protected: + void FillFromExtensionField(const cspField_t &field) override { + switch (static_cast<constraintsFieldType_t>(field.iFieldType)) { + case CFT_TYPE: + FillFromEnumInt(std::string(field.szName), field.iOffset, s_constraintTypeNames, std::extent<decltype(s_constraintTypeNames)>::value); + break; - public: - InfoStringFromPhysConstraintsConverter(const PhysConstraints* structure, const cspField_t* fields, const size_t fieldCount, std::function<std::string(scr_string_t)> scriptStringValueCallback) - : InfoStringFromStructConverter(structure, fields, fieldCount, std::move(scriptStringValueCallback)) - { - } - }; -} + default: + assert(false); + break; + } + } -InfoString AssetDumperPhysConstraints::CreateInfoString(XAssetInfo<PhysConstraints>* asset) -{ - assert(asset->Asset()->count <= 4); +public: + InfoStringFromPhysConstraintsConverter(const PhysConstraints *structure, const cspField_t *fields, const size_t fieldCount, + std::function<std::string(scr_string_t)> scriptStringValueCallback) + : InfoStringFromStructConverter(structure, fields, fieldCount, std::move(scriptStringValueCallback)) {} +}; +} // namespace T6 - InfoStringFromPhysConstraintsConverter converter(asset->Asset(), phys_constraints_fields, std::extent<decltype(phys_constraints_fields)>::value, [asset](const scr_string_t scrStr) -> std::string - { - assert(scrStr < asset->m_zone->m_script_strings.Count()); - if (scrStr >= asset->m_zone->m_script_strings.Count()) - return ""; +InfoString AssetDumperPhysConstraints::CreateInfoString(XAssetInfo<PhysConstraints> *asset) { + assert(asset->Asset()->count <= 4); - return asset->m_zone->m_script_strings[scrStr]; - }); + InfoStringFromPhysConstraintsConverter converter(asset->Asset(), phys_constraints_fields, std::extent<decltype(phys_constraints_fields)>::value, + [asset](const scr_string_t scrStr) -> std::string { + assert(scrStr < asset->m_zone->m_script_strings.Count()); + if (scrStr >= asset->m_zone->m_script_strings.Count()) + return ""; - return converter.Convert(); -} + return asset->m_zone->m_script_strings[scrStr]; + }); -bool AssetDumperPhysConstraints::ShouldDump(XAssetInfo<PhysConstraints>* asset) -{ - return true; + return converter.Convert(); } -void AssetDumperPhysConstraints::DumpAsset(AssetDumpingContext& context, XAssetInfo<PhysConstraints>* asset) -{ - // Only dump raw when no gdt available - if (context.m_gdt) - { - const auto infoString = CreateInfoString(asset); - GdtEntry gdtEntry(asset->m_name, ObjConstants::GDF_FILENAME_PHYS_CONSTRAINTS); - infoString.ToGdtProperties(ObjConstants::INFO_STRING_PREFIX_PHYS_CONSTRAINTS, gdtEntry); - context.m_gdt->WriteEntry(gdtEntry); - } - else - { - const auto assetFile = context.OpenAssetFile("physconstraints/" + asset->m_name); +bool AssetDumperPhysConstraints::ShouldDump(XAssetInfo<PhysConstraints> *asset) { return true; } - if (!assetFile) - return; +void AssetDumperPhysConstraints::DumpAsset(AssetDumpingContext &context, XAssetInfo<PhysConstraints> *asset) { + // Only dump raw when no gdt available + if (context.m_gdt) { + const auto infoString = CreateInfoString(asset); + GdtEntry gdtEntry(asset->m_name, ObjConstants::GDF_FILENAME_PHYS_CONSTRAINTS); + infoString.ToGdtProperties(ObjConstants::INFO_STRING_PREFIX_PHYS_CONSTRAINTS, gdtEntry); + context.m_gdt->WriteEntry(gdtEntry); + } else { + const auto assetFile = context.OpenAssetFile("physconstraints/" + asset->m_name); - auto& stream = *assetFile; - const auto infoString = CreateInfoString(asset); - const auto stringValue = infoString.ToString(ObjConstants::INFO_STRING_PREFIX_PHYS_CONSTRAINTS); - stream.write(stringValue.c_str(), stringValue.size()); - } + if (!assetFile) + return; + + auto &stream = *assetFile; + const auto infoString = CreateInfoString(asset); + const auto stringValue = infoString.ToString(ObjConstants::INFO_STRING_PREFIX_PHYS_CONSTRAINTS); + stream.write(stringValue.c_str(), stringValue.size()); + } } \ No newline at end of file diff --git a/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperPhysConstraints.h b/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperPhysConstraints.h index e94bfdd98..e3edc204c 100644 --- a/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperPhysConstraints.h +++ b/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperPhysConstraints.h @@ -4,14 +4,12 @@ #include "Game/T6/T6.h" #include "InfoString/InfoString.h" -namespace T6 -{ - class AssetDumperPhysConstraints final : public AbstractAssetDumper<PhysConstraints> - { - static InfoString CreateInfoString(XAssetInfo<PhysConstraints>* asset); +namespace T6 { +class AssetDumperPhysConstraints final : public AbstractAssetDumper<PhysConstraints> { + static InfoString CreateInfoString(XAssetInfo<PhysConstraints> *asset); - protected: - bool ShouldDump(XAssetInfo<PhysConstraints>* asset) override; - void DumpAsset(AssetDumpingContext& context, XAssetInfo<PhysConstraints>* asset) override; - }; -} +protected: + bool ShouldDump(XAssetInfo<PhysConstraints> *asset) override; + void DumpAsset(AssetDumpingContext &context, XAssetInfo<PhysConstraints> *asset) override; +}; +} // namespace T6 diff --git a/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperPhysPreset.cpp b/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperPhysPreset.cpp index 2db9c7abc..c76691f07 100644 --- a/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperPhysPreset.cpp +++ b/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperPhysPreset.cpp @@ -5,99 +5,81 @@ #include <cmath> #include <type_traits> -#include "Game/T6/ObjConstantsT6.h" #include "Game/T6/InfoString/InfoStringFromStructConverter.h" #include "Game/T6/InfoString/PhysPresetFields.h" +#include "Game/T6/ObjConstantsT6.h" using namespace T6; -namespace T6 -{ - class InfoStringFromPhysPresetConverter final : public InfoStringFromStructConverter - { - protected: - void FillFromExtensionField(const cspField_t& field) override - { - assert(false); - } - - public: - InfoStringFromPhysPresetConverter(const PhysPresetInfo* structure, const cspField_t* fields, const size_t fieldCount, std::function<std::string(scr_string_t)> scriptStringValueCallback) - : InfoStringFromStructConverter(structure, fields, fieldCount, std::move(scriptStringValueCallback)) - { - } - }; -} - -void AssetDumperPhysPreset::CopyToPhysPresetInfo(const PhysPreset* physPreset, PhysPresetInfo* physPresetInfo) -{ - physPresetInfo->mass = std::clamp(physPreset->mass * 1000.0f, 1.0f, 2000.0f); - physPresetInfo->bounce = physPreset->bounce; - - if(std::isinf(physPreset->friction)) - { - physPresetInfo->isFrictionInfinity = 1; - physPresetInfo->friction = 0; - } - else - { - physPresetInfo->isFrictionInfinity = 0; - physPresetInfo->friction = physPreset->friction; - } - - physPresetInfo->bulletForceScale = physPreset->bulletForceScale; - physPresetInfo->explosiveForceScale = physPreset->explosiveForceScale; - physPresetInfo->piecesSpreadFraction = physPreset->piecesSpreadFraction; - physPresetInfo->piecesUpwardVelocity = physPreset->piecesUpwardVelocity; - physPresetInfo->canFloat = physPreset->canFloat; - physPresetInfo->gravityScale = std::clamp(physPreset->gravityScale, 0.01f, 10.0f); - physPresetInfo->centerOfMassOffset = physPreset->centerOfMassOffset; - physPresetInfo->buoyancyBoxMin = physPreset->buoyancyBoxMin; - physPresetInfo->buoyancyBoxMax = physPreset->buoyancyBoxMax; +namespace T6 { +class InfoStringFromPhysPresetConverter final : public InfoStringFromStructConverter { +protected: + void FillFromExtensionField(const cspField_t &field) override { assert(false); } + +public: + InfoStringFromPhysPresetConverter(const PhysPresetInfo *structure, const cspField_t *fields, const size_t fieldCount, + std::function<std::string(scr_string_t)> scriptStringValueCallback) + : InfoStringFromStructConverter(structure, fields, fieldCount, std::move(scriptStringValueCallback)) {} +}; +} // namespace T6 + +void AssetDumperPhysPreset::CopyToPhysPresetInfo(const PhysPreset *physPreset, PhysPresetInfo *physPresetInfo) { + physPresetInfo->mass = std::clamp(physPreset->mass * 1000.0f, 1.0f, 2000.0f); + physPresetInfo->bounce = physPreset->bounce; + + if (std::isinf(physPreset->friction)) { + physPresetInfo->isFrictionInfinity = 1; + physPresetInfo->friction = 0; + } else { + physPresetInfo->isFrictionInfinity = 0; + physPresetInfo->friction = physPreset->friction; + } + + physPresetInfo->bulletForceScale = physPreset->bulletForceScale; + physPresetInfo->explosiveForceScale = physPreset->explosiveForceScale; + physPresetInfo->piecesSpreadFraction = physPreset->piecesSpreadFraction; + physPresetInfo->piecesUpwardVelocity = physPreset->piecesUpwardVelocity; + physPresetInfo->canFloat = physPreset->canFloat; + physPresetInfo->gravityScale = std::clamp(physPreset->gravityScale, 0.01f, 10.0f); + physPresetInfo->centerOfMassOffset = physPreset->centerOfMassOffset; + physPresetInfo->buoyancyBoxMin = physPreset->buoyancyBoxMin; + physPresetInfo->buoyancyBoxMax = physPreset->buoyancyBoxMax; } -InfoString AssetDumperPhysPreset::CreateInfoString(XAssetInfo<PhysPreset>* asset) -{ - auto* physPresetInfo = new PhysPresetInfo; - CopyToPhysPresetInfo(asset->Asset(), physPresetInfo); - - InfoStringFromPhysPresetConverter converter(physPresetInfo, phys_preset_fields, std::extent<decltype(phys_preset_fields)>::value, [asset](const scr_string_t scrStr) -> std::string - { - assert(scrStr < asset->m_zone->m_script_strings.Count()); - if (scrStr >= asset->m_zone->m_script_strings.Count()) - return ""; +InfoString AssetDumperPhysPreset::CreateInfoString(XAssetInfo<PhysPreset> *asset) { + auto *physPresetInfo = new PhysPresetInfo; + CopyToPhysPresetInfo(asset->Asset(), physPresetInfo); - return asset->m_zone->m_script_strings[scrStr]; - }); + InfoStringFromPhysPresetConverter converter(physPresetInfo, phys_preset_fields, std::extent<decltype(phys_preset_fields)>::value, + [asset](const scr_string_t scrStr) -> std::string { + assert(scrStr < asset->m_zone->m_script_strings.Count()); + if (scrStr >= asset->m_zone->m_script_strings.Count()) + return ""; - return converter.Convert(); -} + return asset->m_zone->m_script_strings[scrStr]; + }); -bool AssetDumperPhysPreset::ShouldDump(XAssetInfo<PhysPreset>* asset) -{ - return true; + return converter.Convert(); } -void AssetDumperPhysPreset::DumpAsset(AssetDumpingContext& context, XAssetInfo<PhysPreset>* asset) -{ - // Only dump raw when no gdt available - if (context.m_gdt) - { - const auto infoString = CreateInfoString(asset); - GdtEntry gdtEntry(asset->m_name, ObjConstants::GDF_FILENAME_PHYS_PRESET); - infoString.ToGdtProperties(ObjConstants::INFO_STRING_PREFIX_PHYS_PRESET, gdtEntry); - context.m_gdt->WriteEntry(gdtEntry); - } - else - { - const auto assetFile = context.OpenAssetFile("physic/" + asset->m_name); - - if (!assetFile) - return; - - auto& stream = *assetFile; - const auto infoString = CreateInfoString(asset); - const auto stringValue = infoString.ToString(ObjConstants::INFO_STRING_PREFIX_PHYS_PRESET); - stream.write(stringValue.c_str(), stringValue.size()); - } +bool AssetDumperPhysPreset::ShouldDump(XAssetInfo<PhysPreset> *asset) { return true; } + +void AssetDumperPhysPreset::DumpAsset(AssetDumpingContext &context, XAssetInfo<PhysPreset> *asset) { + // Only dump raw when no gdt available + if (context.m_gdt) { + const auto infoString = CreateInfoString(asset); + GdtEntry gdtEntry(asset->m_name, ObjConstants::GDF_FILENAME_PHYS_PRESET); + infoString.ToGdtProperties(ObjConstants::INFO_STRING_PREFIX_PHYS_PRESET, gdtEntry); + context.m_gdt->WriteEntry(gdtEntry); + } else { + const auto assetFile = context.OpenAssetFile("physic/" + asset->m_name); + + if (!assetFile) + return; + + auto &stream = *assetFile; + const auto infoString = CreateInfoString(asset); + const auto stringValue = infoString.ToString(ObjConstants::INFO_STRING_PREFIX_PHYS_PRESET); + stream.write(stringValue.c_str(), stringValue.size()); + } } \ No newline at end of file diff --git a/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperPhysPreset.h b/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperPhysPreset.h index 3dcb9445b..1b45450da 100644 --- a/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperPhysPreset.h +++ b/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperPhysPreset.h @@ -4,15 +4,13 @@ #include "Game/T6/T6.h" #include "InfoString/InfoString.h" -namespace T6 -{ - class AssetDumperPhysPreset final : public AbstractAssetDumper<PhysPreset> - { - static void CopyToPhysPresetInfo(const PhysPreset* physPreset, PhysPresetInfo* physPresetInfo); - static InfoString CreateInfoString(XAssetInfo<PhysPreset>* asset); +namespace T6 { +class AssetDumperPhysPreset final : public AbstractAssetDumper<PhysPreset> { + static void CopyToPhysPresetInfo(const PhysPreset *physPreset, PhysPresetInfo *physPresetInfo); + static InfoString CreateInfoString(XAssetInfo<PhysPreset> *asset); - protected: - bool ShouldDump(XAssetInfo<PhysPreset>* asset) override; - void DumpAsset(AssetDumpingContext& context, XAssetInfo<PhysPreset>* asset) override; - }; -} +protected: + bool ShouldDump(XAssetInfo<PhysPreset> *asset) override; + void DumpAsset(AssetDumpingContext &context, XAssetInfo<PhysPreset> *asset) override; +}; +} // namespace T6 diff --git a/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperQdb.cpp b/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperQdb.cpp index d847be17d..2ed69b9b8 100644 --- a/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperQdb.cpp +++ b/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperQdb.cpp @@ -2,19 +2,15 @@ using namespace T6; -bool AssetDumperQdb::ShouldDump(XAssetInfo<Qdb>* asset) -{ - return true; -} +bool AssetDumperQdb::ShouldDump(XAssetInfo<Qdb> *asset) { return true; } -void AssetDumperQdb::DumpAsset(AssetDumpingContext& context, XAssetInfo<Qdb>* asset) -{ - const auto* qdb = asset->Asset(); - const auto assetFile = context.OpenAssetFile(asset->m_name); +void AssetDumperQdb::DumpAsset(AssetDumpingContext &context, XAssetInfo<Qdb> *asset) { + const auto *qdb = asset->Asset(); + const auto assetFile = context.OpenAssetFile(asset->m_name); - if (!assetFile) - return; + if (!assetFile) + return; - auto& stream = *assetFile; - stream.write(qdb->buffer, qdb->len); + auto &stream = *assetFile; + stream.write(qdb->buffer, qdb->len); } \ No newline at end of file diff --git a/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperQdb.h b/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperQdb.h index 7d253a4f5..4ce27eb41 100644 --- a/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperQdb.h +++ b/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperQdb.h @@ -3,12 +3,10 @@ #include "Dumping/AbstractAssetDumper.h" #include "Game/T6/T6.h" -namespace T6 -{ - class AssetDumperQdb final : public AbstractAssetDumper<Qdb> - { - protected: - bool ShouldDump(XAssetInfo<Qdb>* asset) override; - void DumpAsset(AssetDumpingContext& context, XAssetInfo<Qdb>* asset) override; - }; -} +namespace T6 { +class AssetDumperQdb final : public AbstractAssetDumper<Qdb> { +protected: + bool ShouldDump(XAssetInfo<Qdb> *asset) override; + void DumpAsset(AssetDumpingContext &context, XAssetInfo<Qdb> *asset) override; +}; +} // namespace T6 diff --git a/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperRawFile.cpp b/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperRawFile.cpp index 5c5b2357e..3c68568ca 100644 --- a/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperRawFile.cpp +++ b/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperRawFile.cpp @@ -2,19 +2,15 @@ using namespace T6; -bool AssetDumperRawFile::ShouldDump(XAssetInfo<RawFile>* asset) -{ - return true; -} +bool AssetDumperRawFile::ShouldDump(XAssetInfo<RawFile> *asset) { return true; } -void AssetDumperRawFile::DumpAsset(AssetDumpingContext& context, XAssetInfo<RawFile>* asset) -{ - const auto* rawFile = asset->Asset(); - const auto assetFile = context.OpenAssetFile(asset->m_name); +void AssetDumperRawFile::DumpAsset(AssetDumpingContext &context, XAssetInfo<RawFile> *asset) { + const auto *rawFile = asset->Asset(); + const auto assetFile = context.OpenAssetFile(asset->m_name); - if (!assetFile) - return; + if (!assetFile) + return; - auto& stream = *assetFile; - stream.write(rawFile->buffer, rawFile->len); + auto &stream = *assetFile; + stream.write(rawFile->buffer, rawFile->len); } \ No newline at end of file diff --git a/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperRawFile.h b/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperRawFile.h index 8916419dd..69e75f1c7 100644 --- a/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperRawFile.h +++ b/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperRawFile.h @@ -3,12 +3,10 @@ #include "Dumping/AbstractAssetDumper.h" #include "Game/T6/T6.h" -namespace T6 -{ - class AssetDumperRawFile final : public AbstractAssetDumper<RawFile> - { - protected: - bool ShouldDump(XAssetInfo<RawFile>* asset) override; - void DumpAsset(AssetDumpingContext& context, XAssetInfo<RawFile>* asset) override; - }; -} +namespace T6 { +class AssetDumperRawFile final : public AbstractAssetDumper<RawFile> { +protected: + bool ShouldDump(XAssetInfo<RawFile> *asset) override; + void DumpAsset(AssetDumpingContext &context, XAssetInfo<RawFile> *asset) override; +}; +} // namespace T6 diff --git a/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperScriptParseTree.cpp b/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperScriptParseTree.cpp index dc87009de..a48c8c72c 100644 --- a/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperScriptParseTree.cpp +++ b/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperScriptParseTree.cpp @@ -2,19 +2,15 @@ using namespace T6; -bool AssetDumperScriptParseTree::ShouldDump(XAssetInfo<ScriptParseTree>* asset) -{ - return true; -} +bool AssetDumperScriptParseTree::ShouldDump(XAssetInfo<ScriptParseTree> *asset) { return true; } -void AssetDumperScriptParseTree::DumpAsset(AssetDumpingContext& context, XAssetInfo<ScriptParseTree>* asset) -{ - const auto* scriptParseTree = asset->Asset(); - const auto assetFile = context.OpenAssetFile(asset->m_name); +void AssetDumperScriptParseTree::DumpAsset(AssetDumpingContext &context, XAssetInfo<ScriptParseTree> *asset) { + const auto *scriptParseTree = asset->Asset(); + const auto assetFile = context.OpenAssetFile(asset->m_name); - if (!assetFile) - return; + if (!assetFile) + return; - auto& stream = *assetFile; - stream.write(scriptParseTree->buffer, scriptParseTree->len); + auto &stream = *assetFile; + stream.write(scriptParseTree->buffer, scriptParseTree->len); } \ No newline at end of file diff --git a/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperScriptParseTree.h b/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperScriptParseTree.h index 396100b0e..a1c5a9cb4 100644 --- a/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperScriptParseTree.h +++ b/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperScriptParseTree.h @@ -3,12 +3,10 @@ #include "Dumping/AbstractAssetDumper.h" #include "Game/T6/T6.h" -namespace T6 -{ - class AssetDumperScriptParseTree final : public AbstractAssetDumper<ScriptParseTree> - { - protected: - bool ShouldDump(XAssetInfo<ScriptParseTree>* asset) override; - void DumpAsset(AssetDumpingContext& context, XAssetInfo<ScriptParseTree>* asset) override; - }; -} +namespace T6 { +class AssetDumperScriptParseTree final : public AbstractAssetDumper<ScriptParseTree> { +protected: + bool ShouldDump(XAssetInfo<ScriptParseTree> *asset) override; + void DumpAsset(AssetDumpingContext &context, XAssetInfo<ScriptParseTree> *asset) override; +}; +} // namespace T6 diff --git a/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperSlug.cpp b/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperSlug.cpp index 0be7b081a..293ed045a 100644 --- a/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperSlug.cpp +++ b/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperSlug.cpp @@ -2,19 +2,15 @@ using namespace T6; -bool AssetDumperSlug::ShouldDump(XAssetInfo<Slug>* asset) -{ - return true; -} +bool AssetDumperSlug::ShouldDump(XAssetInfo<Slug> *asset) { return true; } -void AssetDumperSlug::DumpAsset(AssetDumpingContext& context, XAssetInfo<Slug>* asset) -{ - const auto* slug = asset->Asset(); - const auto assetFile = context.OpenAssetFile(asset->m_name); +void AssetDumperSlug::DumpAsset(AssetDumpingContext &context, XAssetInfo<Slug> *asset) { + const auto *slug = asset->Asset(); + const auto assetFile = context.OpenAssetFile(asset->m_name); - if (!assetFile) - return; + if (!assetFile) + return; - auto& stream = *assetFile; - stream.write(slug->buffer, slug->len); + auto &stream = *assetFile; + stream.write(slug->buffer, slug->len); } \ No newline at end of file diff --git a/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperSlug.h b/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperSlug.h index f84fa9935..4345b4c35 100644 --- a/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperSlug.h +++ b/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperSlug.h @@ -3,12 +3,10 @@ #include "Dumping/AbstractAssetDumper.h" #include "Game/T6/T6.h" -namespace T6 -{ - class AssetDumperSlug final : public AbstractAssetDumper<Slug> - { - protected: - bool ShouldDump(XAssetInfo<Slug>* asset) override; - void DumpAsset(AssetDumpingContext& context, XAssetInfo<Slug>* asset) override; - }; -} +namespace T6 { +class AssetDumperSlug final : public AbstractAssetDumper<Slug> { +protected: + bool ShouldDump(XAssetInfo<Slug> *asset) override; + void DumpAsset(AssetDumpingContext &context, XAssetInfo<Slug> *asset) override; +}; +} // namespace T6 diff --git a/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperSndBank.cpp b/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperSndBank.cpp index af3a41707..4f804101b 100644 --- a/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperSndBank.cpp +++ b/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperSndBank.cpp @@ -1,345 +1,311 @@ #include "AssetDumperSndBank.h" -#include <fstream> #include <filesystem> +#include <fstream> #include <unordered_map> -#include "Utils/ClassUtils.h" #include "Csv/CsvStream.h" #include "ObjContainer/SoundBank/SoundBank.h" +#include "Utils/ClassUtils.h" using namespace T6; namespace fs = std::filesystem; -class AssetDumperSndBank::Internal -{ - inline static const std::string ALIAS_HEADERS[] - { - "# name", - "# file", - "# template", - "# loadspec", - "# secondary", - "# group", - "# vol_min", - "# vol_max", - "# team_vol_mod", - "# dist_min", - "# dist_max", - "# dist_reverb_max", - "# volume_falloff_curve", - "# reverb_falloff_curve", - "# volume_min_falloff_curve", - "# reverb_min_falloff_curve", - "# limit_count", - "# limit_type", - "# entity_limit_count", - "# entity_limit_type", - "# pitch_min", - "# pitch_max", - "# team_pitch_mod", - "# min_priority", - "# max_priority", - "# min_priority_threshold", - "# max_priority_threshold", - "# spatialized", - "# type", - "# loop", - "# randomize_type", - "# probability", - "# start_delay", - "# reverb_send", - "# duck", - "# pan", - "# center_send", - "# envelop_min", - "# envelop_max", - "# envelop_percentage", - "# occlusion_level", - "# occlusion_wet_dry", - "# is_big", - "# distance_lpf", - "# move_type", - "# move_time", - "# real_delay", - "# subtitle", - "# mature", - "# doppler", - "# futz", - "# context_type", - "# context_value", - "# compression", - "# timescale", - "# music", - "# fade_in", - "# fade_out", - "# pc_format", - "# pause", - "# stop_on_death", - "# bus", - "# snapshot", - }; - - AssetDumpingContext& m_context; - - static std::string GetExtensionForFormat(const snd_asset_format format) - { - switch (format) - { - case SND_ASSET_FORMAT_MP3: - return ".mp3"; - - case SND_ASSET_FORMAT_FLAC: - return ".flac"; - - case SND_ASSET_FORMAT_PCMS16: - case SND_ASSET_FORMAT_PCMS24: - case SND_ASSET_FORMAT_PCMS32: - case SND_ASSET_FORMAT_IEEE: - case SND_ASSET_FORMAT_XMA4: - case SND_ASSET_FORMAT_MSADPCM: - case SND_ASSET_FORMAT_WMA: - case SND_ASSET_FORMAT_WIIUADPCM: - case SND_ASSET_FORMAT_MPC: - std::cout << "Unsupported sound format " << format << std::endl; - return std::string(); - - default: - assert(false); - std::cout << "Unknown sound format " << format << std::endl; - return std::string(); - } +class AssetDumperSndBank::Internal { + inline static const std::string ALIAS_HEADERS[]{ + "# name", + "# file", + "# template", + "# loadspec", + "# secondary", + "# group", + "# vol_min", + "# vol_max", + "# team_vol_mod", + "# dist_min", + "# dist_max", + "# dist_reverb_max", + "# volume_falloff_curve", + "# reverb_falloff_curve", + "# volume_min_falloff_curve", + "# reverb_min_falloff_curve", + "# limit_count", + "# limit_type", + "# entity_limit_count", + "# entity_limit_type", + "# pitch_min", + "# pitch_max", + "# team_pitch_mod", + "# min_priority", + "# max_priority", + "# min_priority_threshold", + "# max_priority_threshold", + "# spatialized", + "# type", + "# loop", + "# randomize_type", + "# probability", + "# start_delay", + "# reverb_send", + "# duck", + "# pan", + "# center_send", + "# envelop_min", + "# envelop_max", + "# envelop_percentage", + "# occlusion_level", + "# occlusion_wet_dry", + "# is_big", + "# distance_lpf", + "# move_type", + "# move_time", + "# real_delay", + "# subtitle", + "# mature", + "# doppler", + "# futz", + "# context_type", + "# context_value", + "# compression", + "# timescale", + "# music", + "# fade_in", + "# fade_out", + "# pc_format", + "# pause", + "# stop_on_death", + "# bus", + "# snapshot", + }; + + AssetDumpingContext &m_context; + + static std::string GetExtensionForFormat(const snd_asset_format format) { + switch (format) { + case SND_ASSET_FORMAT_MP3: + return ".mp3"; + + case SND_ASSET_FORMAT_FLAC: + return ".flac"; + + case SND_ASSET_FORMAT_PCMS16: + case SND_ASSET_FORMAT_PCMS24: + case SND_ASSET_FORMAT_PCMS32: + case SND_ASSET_FORMAT_IEEE: + case SND_ASSET_FORMAT_XMA4: + case SND_ASSET_FORMAT_MSADPCM: + case SND_ASSET_FORMAT_WMA: + case SND_ASSET_FORMAT_WIIUADPCM: + case SND_ASSET_FORMAT_MPC: + std::cout << "Unsupported sound format " << format << std::endl; + return std::string(); + + default: + assert(false); + std::cout << "Unknown sound format " << format << std::endl; + return std::string(); } + } - _NODISCARD std::string GetAssetFilename(const std::string& outputFileName, const SoundAssetBankEntry& entry) const - { - fs::path assetPath(m_context.m_base_path); - - fs::path assetName(outputFileName); - auto firstPart = true; - for (const auto& part : assetName) - { - if (firstPart) - { - firstPart = false; - if (part.string() == "raw" - || part.string() == "devraw") - continue; - } - - assetPath.append(part.string()); - } + _NODISCARD std::string GetAssetFilename(const std::string &outputFileName, const SoundAssetBankEntry &entry) const { + fs::path assetPath(m_context.m_base_path); - const auto extension = GetExtensionForFormat(static_cast<snd_asset_format>(entry.format)); - if (!extension.empty()) - assetPath.concat(extension); + fs::path assetName(outputFileName); + auto firstPart = true; + for (const auto &part : assetName) { + if (firstPart) { + firstPart = false; + if (part.string() == "raw" || part.string() == "devraw") + continue; + } - return assetPath.string(); + assetPath.append(part.string()); } - _NODISCARD std::unique_ptr<std::ostream> OpenAssetOutputFile(const std::string& outputFileName, const SoundAssetBankEntry& entry) const - { - fs::path assetPath(GetAssetFilename(outputFileName, entry)); + const auto extension = GetExtensionForFormat(static_cast<snd_asset_format>(entry.format)); + if (!extension.empty()) + assetPath.concat(extension); - auto assetDir(assetPath); - assetDir.remove_filename(); + return assetPath.string(); + } - create_directories(assetDir); + _NODISCARD std::unique_ptr<std::ostream> OpenAssetOutputFile(const std::string &outputFileName, const SoundAssetBankEntry &entry) const { + fs::path assetPath(GetAssetFilename(outputFileName, entry)); - auto outputStream = std::make_unique<std::ofstream>(assetPath, std::ios_base::out | std::ios_base::binary); + auto assetDir(assetPath); + assetDir.remove_filename(); - if (outputStream->is_open()) - { - return std::move(outputStream); - } + create_directories(assetDir); - return nullptr; - } + auto outputStream = std::make_unique<std::ofstream>(assetPath, std::ios_base::out | std::ios_base::binary); - std::unique_ptr<std::ostream> OpenAliasOutputFile(const SndBank* sndBank) const - { - return nullptr; + if (outputStream->is_open()) { + return std::move(outputStream); } - static void WriteAliasFileHeader(CsvOutputStream& stream) - { - for (const auto& headerField : ALIAS_HEADERS) - { - stream.WriteColumn(headerField); - } + return nullptr; + } - stream.NextRow(); - } + std::unique_ptr<std::ostream> OpenAliasOutputFile(const SndBank *sndBank) const { return nullptr; } - void WriteAliasToFile(CsvOutputStream& stream, const SndAlias* alias) - { - // name - stream.WriteColumn(alias->name); - - // file - stream.WriteColumn(alias->assetFileName); - - // "# template", - // template - stream.WriteColumn(""); - - // loadspec - stream.WriteColumn(""); - - // "# secondary", - // "# group", - // "# vol_min", - // "# vol_max", - // "# team_vol_mod", - // "# dist_min", - // "# dist_max", - // "# dist_reverb_max", - // "# volume_falloff_curve", - // "# reverb_falloff_curve", - // "# volume_min_falloff_curve", - // "# reverb_min_falloff_curve", - // "# limit_count", - // "# limit_type", - // "# entity_limit_count", - // "# entity_limit_type", - // "# pitch_min", - // "# pitch_max", - // "# team_pitch_mod", - // "# min_priority", - // "# max_priority", - // "# min_priority_threshold", - // "# max_priority_threshold", - // "# spatialized", - // "# type", - // "# loop", - // "# randomize_type", - // "# probability", - // "# start_delay", - // "# reverb_send", - // "# duck", - // "# pan", - // "# center_send", - // "# envelop_min", - // "# envelop_max", - // "# envelop_percentage", - // "# occlusion_level", - // "# occlusion_wet_dry", - // "# is_big", - // "# distance_lpf", - // "# move_type", - // "# move_time", - // "# real_delay", - // "# subtitle", - // "# mature", - // "# doppler", - // "# futz", - // "# context_type", - // "# context_value", - // "# compression", - // "# timescale", - // "# music", - // "# fade_in", - // "# fade_out", - // "# pc_format", - // "# pause", - // "# stop_on_death", - // "# bus", - // "# snapshot", + static void WriteAliasFileHeader(CsvOutputStream &stream) { + for (const auto &headerField : ALIAS_HEADERS) { + stream.WriteColumn(headerField); } - void DumpSndBankAliases(const SndBank* sndBank, std::unordered_map<unsigned, std::string>& aliasFiles) - { - const auto outputFile = OpenAliasOutputFile(sndBank); - - if (outputFile == nullptr) - { - std::cout << "Failed to open sound alias output file for: \"" << sndBank->name << "\"" << std::endl; - return; - } - - CsvOutputStream csvStream(*outputFile); - WriteAliasFileHeader(csvStream); - - for (auto i = 0u; i < sndBank->aliasCount; i++) - { - const auto& aliasList = sndBank->alias[i]; - for (auto j = 0; j < aliasList.count; j++) - { - const auto& alias = aliasList.head[j]; - WriteAliasToFile(csvStream, &alias); - if (alias.assetId && alias.assetFileName) - aliasFiles[alias.assetId] = alias.assetFileName; - } - } + stream.NextRow(); + } + + void WriteAliasToFile(CsvOutputStream &stream, const SndAlias *alias) { + // name + stream.WriteColumn(alias->name); + + // file + stream.WriteColumn(alias->assetFileName); + + // "# template", + // template + stream.WriteColumn(""); + + // loadspec + stream.WriteColumn(""); + + // "# secondary", + // "# group", + // "# vol_min", + // "# vol_max", + // "# team_vol_mod", + // "# dist_min", + // "# dist_max", + // "# dist_reverb_max", + // "# volume_falloff_curve", + // "# reverb_falloff_curve", + // "# volume_min_falloff_curve", + // "# reverb_min_falloff_curve", + // "# limit_count", + // "# limit_type", + // "# entity_limit_count", + // "# entity_limit_type", + // "# pitch_min", + // "# pitch_max", + // "# team_pitch_mod", + // "# min_priority", + // "# max_priority", + // "# min_priority_threshold", + // "# max_priority_threshold", + // "# spatialized", + // "# type", + // "# loop", + // "# randomize_type", + // "# probability", + // "# start_delay", + // "# reverb_send", + // "# duck", + // "# pan", + // "# center_send", + // "# envelop_min", + // "# envelop_max", + // "# envelop_percentage", + // "# occlusion_level", + // "# occlusion_wet_dry", + // "# is_big", + // "# distance_lpf", + // "# move_type", + // "# move_time", + // "# real_delay", + // "# subtitle", + // "# mature", + // "# doppler", + // "# futz", + // "# context_type", + // "# context_value", + // "# compression", + // "# timescale", + // "# music", + // "# fade_in", + // "# fade_out", + // "# pc_format", + // "# pause", + // "# stop_on_death", + // "# bus", + // "# snapshot", + } + + void DumpSndBankAliases(const SndBank *sndBank, std::unordered_map<unsigned, std::string> &aliasFiles) { + const auto outputFile = OpenAliasOutputFile(sndBank); + + if (outputFile == nullptr) { + std::cout << "Failed to open sound alias output file for: \"" << sndBank->name << "\"" << std::endl; + return; } - void DumpSoundData(std::unordered_map<unsigned, std::string>& aliasFiles) const - { - for (const auto& [id, filename] : aliasFiles) - { - auto foundEntry = false; - - for (const auto* soundBank : SoundBank::Repository) - { - auto soundFile = soundBank->GetEntryStream(id); - if (soundFile.IsOpen()) - { - auto outFile = OpenAssetOutputFile(filename, soundFile.m_entry); - if (!outFile) - { - std::cout << "Failed to open sound outputfile: \"" << filename << "\"" << std::endl; - break; - } - - while (!soundFile.m_stream->eof()) - { - char buffer[2048]; - soundFile.m_stream->read(buffer, sizeof(buffer)); - const auto readSize = soundFile.m_stream->gcount(); - outFile->write(buffer, readSize); - } - - foundEntry = true; - break; - } - } - - if (!foundEntry) - { - std::cout << "Could not find data for sound \"" << filename << "\"" << std::endl; - } + CsvOutputStream csvStream(*outputFile); + WriteAliasFileHeader(csvStream); + + for (auto i = 0u; i < sndBank->aliasCount; i++) { + const auto &aliasList = sndBank->alias[i]; + for (auto j = 0; j < aliasList.count; j++) { + const auto &alias = aliasList.head[j]; + WriteAliasToFile(csvStream, &alias); + if (alias.assetId && alias.assetFileName) + aliasFiles[alias.assetId] = alias.assetFileName; + } + } + } + + void DumpSoundData(std::unordered_map<unsigned, std::string> &aliasFiles) const { + for (const auto &[id, filename] : aliasFiles) { + auto foundEntry = false; + + for (const auto *soundBank : SoundBank::Repository) { + auto soundFile = soundBank->GetEntryStream(id); + if (soundFile.IsOpen()) { + auto outFile = OpenAssetOutputFile(filename, soundFile.m_entry); + if (!outFile) { + std::cout << "Failed to open sound outputfile: \"" << filename << "\"" << std::endl; + break; + } + + while (!soundFile.m_stream->eof()) { + char buffer[2048]; + soundFile.m_stream->read(buffer, sizeof(buffer)); + const auto readSize = soundFile.m_stream->gcount(); + outFile->write(buffer, readSize); + } + + foundEntry = true; + break; } + } + + if (!foundEntry) { + std::cout << "Could not find data for sound \"" << filename << "\"" << std::endl; + } } + } - void DumpSndBank(const XAssetInfo<SndBank>* sndBankInfo) - { - const auto* sndBank = sndBankInfo->Asset(); + void DumpSndBank(const XAssetInfo<SndBank> *sndBankInfo) { + const auto *sndBank = sndBankInfo->Asset(); - std::unordered_map<unsigned int, std::string> aliasMappings; - DumpSndBankAliases(sndBank, aliasMappings); - DumpSoundData(aliasMappings); - } + std::unordered_map<unsigned int, std::string> aliasMappings; + DumpSndBankAliases(sndBank, aliasMappings); + DumpSoundData(aliasMappings); + } public: - explicit Internal(AssetDumpingContext& context) - : m_context(context) - { - } + explicit Internal(AssetDumpingContext &context) : m_context(context) {} - void DumpPool(AssetPool<SndBank>* pool) - { - for (const auto* assetInfo : *pool) - { - if (!assetInfo->m_name.empty() && assetInfo->m_name[0] == ',') - continue; + void DumpPool(AssetPool<SndBank> *pool) { + for (const auto *assetInfo : *pool) { + if (!assetInfo->m_name.empty() && assetInfo->m_name[0] == ',') + continue; - DumpSndBank(assetInfo); - } + DumpSndBank(assetInfo); } + } }; -void AssetDumperSndBank::DumpPool(AssetDumpingContext& context, AssetPool<SndBank>* pool) -{ - Internal internal(context); - internal.DumpPool(pool); +void AssetDumperSndBank::DumpPool(AssetDumpingContext &context, AssetPool<SndBank> *pool) { + Internal internal(context); + internal.DumpPool(pool); } diff --git a/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperSndBank.h b/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperSndBank.h index 923eed516..11756a70b 100644 --- a/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperSndBank.h +++ b/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperSndBank.h @@ -3,13 +3,11 @@ #include "Dumping/AbstractAssetDumper.h" #include "Game/T6/T6.h" -namespace T6 -{ - class AssetDumperSndBank final : public IAssetDumper<SndBank> - { - class Internal; +namespace T6 { +class AssetDumperSndBank final : public IAssetDumper<SndBank> { + class Internal; - public: - void DumpPool(AssetDumpingContext& context, AssetPool<SndBank>* pool) override; - }; -} +public: + void DumpPool(AssetDumpingContext &context, AssetPool<SndBank> *pool) override; +}; +} // namespace T6 diff --git a/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperStringTable.cpp b/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperStringTable.cpp index 1116559b0..5b804471c 100644 --- a/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperStringTable.cpp +++ b/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperStringTable.cpp @@ -4,29 +4,23 @@ using namespace T6; -bool AssetDumperStringTable::ShouldDump(XAssetInfo<StringTable>* asset) -{ - return true; -} - -void AssetDumperStringTable::DumpAsset(AssetDumpingContext& context, XAssetInfo<StringTable>* asset) -{ - const auto* stringTable = asset->Asset(); - const auto assetFile = context.OpenAssetFile(asset->m_name); - - if (!assetFile) - return; - - CsvOutputStream csv(*assetFile); - - for (auto row = 0; row < stringTable->rowCount; row++) - { - for (auto column = 0; column < stringTable->columnCount; column++) - { - const auto* cell = &stringTable->values[column + row * stringTable->columnCount]; - csv.WriteColumn(cell->string); - } - - csv.NextRow(); +bool AssetDumperStringTable::ShouldDump(XAssetInfo<StringTable> *asset) { return true; } + +void AssetDumperStringTable::DumpAsset(AssetDumpingContext &context, XAssetInfo<StringTable> *asset) { + const auto *stringTable = asset->Asset(); + const auto assetFile = context.OpenAssetFile(asset->m_name); + + if (!assetFile) + return; + + CsvOutputStream csv(*assetFile); + + for (auto row = 0; row < stringTable->rowCount; row++) { + for (auto column = 0; column < stringTable->columnCount; column++) { + const auto *cell = &stringTable->values[column + row * stringTable->columnCount]; + csv.WriteColumn(cell->string); } + + csv.NextRow(); + } } \ No newline at end of file diff --git a/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperStringTable.h b/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperStringTable.h index d175e8120..5763f8ee1 100644 --- a/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperStringTable.h +++ b/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperStringTable.h @@ -3,12 +3,10 @@ #include "Dumping/AbstractAssetDumper.h" #include "Game/T6/T6.h" -namespace T6 -{ - class AssetDumperStringTable final : public AbstractAssetDumper<StringTable> - { - protected: - bool ShouldDump(XAssetInfo<StringTable>* asset) override; - void DumpAsset(AssetDumpingContext& context, XAssetInfo<StringTable>* asset) override; - }; -} +namespace T6 { +class AssetDumperStringTable final : public AbstractAssetDumper<StringTable> { +protected: + bool ShouldDump(XAssetInfo<StringTable> *asset) override; + void DumpAsset(AssetDumpingContext &context, XAssetInfo<StringTable> *asset) override; +}; +} // namespace T6 diff --git a/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperTracer.cpp b/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperTracer.cpp index ccafb90c6..d5f67ff1b 100644 --- a/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperTracer.cpp +++ b/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperTracer.cpp @@ -3,80 +3,67 @@ #include <cassert> #include <type_traits> -#include "Game/T6/ObjConstantsT6.h" #include "Game/T6/InfoString/EnumStrings.h" #include "Game/T6/InfoString/InfoStringFromStructConverter.h" #include "Game/T6/InfoString/TracerFields.h" +#include "Game/T6/ObjConstantsT6.h" using namespace T6; -namespace T6 -{ - class InfoStringFromTracerConverter final : public InfoStringFromStructConverter - { - protected: - void FillFromExtensionField(const cspField_t& field) override - { - switch (static_cast<tracerFieldType_t>(field.iFieldType)) - { - case TFT_TRACERTYPE: - FillFromEnumInt(std::string(field.szName), field.iOffset, tracerTypeNames, std::extent<decltype(tracerTypeNames)>::value); - break; +namespace T6 { +class InfoStringFromTracerConverter final : public InfoStringFromStructConverter { +protected: + void FillFromExtensionField(const cspField_t &field) override { + switch (static_cast<tracerFieldType_t>(field.iFieldType)) { + case TFT_TRACERTYPE: + FillFromEnumInt(std::string(field.szName), field.iOffset, tracerTypeNames, std::extent<decltype(tracerTypeNames)>::value); + break; - case TFT_NUM_FIELD_TYPES: - default: - assert(false); - break; - } - } + case TFT_NUM_FIELD_TYPES: + default: + assert(false); + break; + } + } - public: - InfoStringFromTracerConverter(const TracerDef* structure, const cspField_t* fields, const size_t fieldCount, std::function<std::string(scr_string_t)> scriptStringValueCallback) - : InfoStringFromStructConverter(structure, fields, fieldCount, std::move(scriptStringValueCallback)) - { - } - }; -} +public: + InfoStringFromTracerConverter(const TracerDef *structure, const cspField_t *fields, const size_t fieldCount, + std::function<std::string(scr_string_t)> scriptStringValueCallback) + : InfoStringFromStructConverter(structure, fields, fieldCount, std::move(scriptStringValueCallback)) {} +}; +} // namespace T6 -InfoString AssetDumperTracer::CreateInfoString(XAssetInfo<TracerDef>* asset) -{ - InfoStringFromTracerConverter converter(asset->Asset(), tracer_fields, std::extent<decltype(tracer_fields)>::value, [asset](const scr_string_t scrStr) -> std::string - { - assert(scrStr < asset->m_zone->m_script_strings.Count()); - if (scrStr >= asset->m_zone->m_script_strings.Count()) - return ""; +InfoString AssetDumperTracer::CreateInfoString(XAssetInfo<TracerDef> *asset) { + InfoStringFromTracerConverter converter(asset->Asset(), tracer_fields, std::extent<decltype(tracer_fields)>::value, + [asset](const scr_string_t scrStr) -> std::string { + assert(scrStr < asset->m_zone->m_script_strings.Count()); + if (scrStr >= asset->m_zone->m_script_strings.Count()) + return ""; - return asset->m_zone->m_script_strings[scrStr]; - }); + return asset->m_zone->m_script_strings[scrStr]; + }); - return converter.Convert(); + return converter.Convert(); } -bool AssetDumperTracer::ShouldDump(XAssetInfo<TracerDef>* asset) -{ - return true; -} +bool AssetDumperTracer::ShouldDump(XAssetInfo<TracerDef> *asset) { return true; } -void AssetDumperTracer::DumpAsset(AssetDumpingContext& context, XAssetInfo<TracerDef>* asset) -{ - // Only dump raw when no gdt available - if (context.m_gdt) - { - const auto infoString = CreateInfoString(asset); - GdtEntry gdtEntry(asset->m_name, ObjConstants::GDF_FILENAME_TRACER); - infoString.ToGdtProperties(ObjConstants::INFO_STRING_PREFIX_TRACER, gdtEntry); - context.m_gdt->WriteEntry(gdtEntry); - } - else - { - const auto assetFile = context.OpenAssetFile("tracer/" + asset->m_name); +void AssetDumperTracer::DumpAsset(AssetDumpingContext &context, XAssetInfo<TracerDef> *asset) { + // Only dump raw when no gdt available + if (context.m_gdt) { + const auto infoString = CreateInfoString(asset); + GdtEntry gdtEntry(asset->m_name, ObjConstants::GDF_FILENAME_TRACER); + infoString.ToGdtProperties(ObjConstants::INFO_STRING_PREFIX_TRACER, gdtEntry); + context.m_gdt->WriteEntry(gdtEntry); + } else { + const auto assetFile = context.OpenAssetFile("tracer/" + asset->m_name); - if (!assetFile) - return; + if (!assetFile) + return; - auto& stream = *assetFile; - const auto infoString = CreateInfoString(asset); - const auto stringValue = infoString.ToString(ObjConstants::INFO_STRING_PREFIX_TRACER); - stream.write(stringValue.c_str(), stringValue.size()); - } + auto &stream = *assetFile; + const auto infoString = CreateInfoString(asset); + const auto stringValue = infoString.ToString(ObjConstants::INFO_STRING_PREFIX_TRACER); + stream.write(stringValue.c_str(), stringValue.size()); + } } diff --git a/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperTracer.h b/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperTracer.h index 36f6e7b6f..5c6b30244 100644 --- a/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperTracer.h +++ b/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperTracer.h @@ -4,14 +4,12 @@ #include "Game/T6/T6.h" #include "InfoString/InfoString.h" -namespace T6 -{ - class AssetDumperTracer final : public AbstractAssetDumper<TracerDef> - { - static InfoString CreateInfoString(XAssetInfo<TracerDef>* asset); +namespace T6 { +class AssetDumperTracer final : public AbstractAssetDumper<TracerDef> { + static InfoString CreateInfoString(XAssetInfo<TracerDef> *asset); - protected: - bool ShouldDump(XAssetInfo<TracerDef>* asset) override; - void DumpAsset(AssetDumpingContext& context, XAssetInfo<TracerDef>* asset) override; - }; -} +protected: + bool ShouldDump(XAssetInfo<TracerDef> *asset) override; + void DumpAsset(AssetDumpingContext &context, XAssetInfo<TracerDef> *asset) override; +}; +} // namespace T6 diff --git a/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperVehicle.cpp b/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperVehicle.cpp index c998bce9b..47c97e3a2 100644 --- a/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperVehicle.cpp +++ b/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperVehicle.cpp @@ -3,130 +3,113 @@ #include <cassert> #include <type_traits> -#include "Game/T6/ObjConstantsT6.h" #include "Game/T6/InfoString/EnumStrings.h" #include "Game/T6/InfoString/InfoStringFromStructConverter.h" #include "Game/T6/InfoString/VehicleFields.h" +#include "Game/T6/ObjConstantsT6.h" using namespace T6; -namespace T6 -{ - class InfoStringFromVehicleConverter final : public InfoStringFromStructConverter - { - protected: - void FillFromExtensionField(const cspField_t& field) override - { - switch (static_cast<VehicleFieldType>(field.iFieldType)) - { - case VFT_TYPE: - FillFromEnumInt(std::string(field.szName), field.iOffset, s_vehicleClassNames, std::extent<decltype(s_vehicleClassNames)>::value); - break; - - case VFT_CAMERAMODE: - FillFromEnumInt(std::string(field.szName), field.iOffset, s_vehicleCameraModes, std::extent<decltype(s_vehicleCameraModes)>::value); - break; - - case VFT_TRACTION_TYPE: - FillFromEnumInt(std::string(field.szName), field.iOffset, s_tractionTypeNames, std::extent<decltype(s_tractionTypeNames)>::value); - break; - - case VFT_MPH_TO_INCHES_PER_SECOND: - { - const auto* num = reinterpret_cast<float*>(reinterpret_cast<uintptr_t>(m_structure) + field.iOffset); - m_info_string.SetValueForKey(std::string(field.szName), std::to_string(*num / 17.6f)); - break; - } - - case VFT_POUNDS_TO_GAME_MASS: - { - const auto* num = reinterpret_cast<float*>(reinterpret_cast<uintptr_t>(m_structure) + field.iOffset); - m_info_string.SetValueForKey(std::string(field.szName), std::to_string(*num / 0.001f)); - break; - } - - case VFT_TEAM: - { - const auto* num = reinterpret_cast<int*>(reinterpret_cast<uintptr_t>(m_structure) + field.iOffset); - switch (*num) - { - case TEAM_AXIS: - m_info_string.SetValueForKey(std::string(field.szName), "axis"); - break; - - case TEAM_ALLIES: - m_info_string.SetValueForKey(std::string(field.szName), "allies"); - break; - - case TEAM_FOUR: - m_info_string.SetValueForKey(std::string(field.szName), "neutral"); - break; - - default: - assert(false); - m_info_string.SetValueForKey(std::string(field.szName), ""); - break; - } - break; - } - - case VFT_KEY_BINDING: - case VFT_GRAPH: - case VFT_WIIUCONTROLOVERRIDE: - case VFT_NUM: - default: - assert(false); - break; - } - } - - public: - InfoStringFromVehicleConverter(const VehicleDef* structure, const cspField_t* fields, const size_t fieldCount, std::function<std::string(scr_string_t)> scriptStringValueCallback) - : InfoStringFromStructConverter(structure, fields, fieldCount, std::move(scriptStringValueCallback)) - { - } - }; -} - -InfoString AssetDumperVehicle::CreateInfoString(XAssetInfo<VehicleDef>* asset) -{ - InfoStringFromVehicleConverter converter(asset->Asset(), vehicle_fields, std::extent<decltype(vehicle_fields)>::value, [asset](const scr_string_t scrStr) -> std::string - { - assert(scrStr < asset->m_zone->m_script_strings.Count()); - if (scrStr >= asset->m_zone->m_script_strings.Count()) - return ""; - - return asset->m_zone->m_script_strings[scrStr]; - }); - - return converter.Convert(); -} - -bool AssetDumperVehicle::ShouldDump(XAssetInfo<VehicleDef>* asset) -{ - return true; -} +namespace T6 { +class InfoStringFromVehicleConverter final : public InfoStringFromStructConverter { +protected: + void FillFromExtensionField(const cspField_t &field) override { + switch (static_cast<VehicleFieldType>(field.iFieldType)) { + case VFT_TYPE: + FillFromEnumInt(std::string(field.szName), field.iOffset, s_vehicleClassNames, std::extent<decltype(s_vehicleClassNames)>::value); + break; + + case VFT_CAMERAMODE: + FillFromEnumInt(std::string(field.szName), field.iOffset, s_vehicleCameraModes, std::extent<decltype(s_vehicleCameraModes)>::value); + break; + + case VFT_TRACTION_TYPE: + FillFromEnumInt(std::string(field.szName), field.iOffset, s_tractionTypeNames, std::extent<decltype(s_tractionTypeNames)>::value); + break; + + case VFT_MPH_TO_INCHES_PER_SECOND: { + const auto *num = reinterpret_cast<float *>(reinterpret_cast<uintptr_t>(m_structure) + field.iOffset); + m_info_string.SetValueForKey(std::string(field.szName), std::to_string(*num / 17.6f)); + break; + } -void AssetDumperVehicle::DumpAsset(AssetDumpingContext& context, XAssetInfo<VehicleDef>* asset) -{ - // Only dump raw when no gdt available - if (context.m_gdt) - { - const auto infoString = CreateInfoString(asset); - GdtEntry gdtEntry(asset->m_name, ObjConstants::GDF_FILENAME_VEHICLE); - infoString.ToGdtProperties(ObjConstants::INFO_STRING_PREFIX_VEHICLE, gdtEntry); - context.m_gdt->WriteEntry(gdtEntry); + case VFT_POUNDS_TO_GAME_MASS: { + const auto *num = reinterpret_cast<float *>(reinterpret_cast<uintptr_t>(m_structure) + field.iOffset); + m_info_string.SetValueForKey(std::string(field.szName), std::to_string(*num / 0.001f)); + break; } - else - { - const auto assetFile = context.OpenAssetFile("vehicles/" + asset->m_name); - if (!assetFile) - return; + case VFT_TEAM: { + const auto *num = reinterpret_cast<int *>(reinterpret_cast<uintptr_t>(m_structure) + field.iOffset); + switch (*num) { + case TEAM_AXIS: + m_info_string.SetValueForKey(std::string(field.szName), "axis"); + break; + + case TEAM_ALLIES: + m_info_string.SetValueForKey(std::string(field.szName), "allies"); + break; + + case TEAM_FOUR: + m_info_string.SetValueForKey(std::string(field.szName), "neutral"); + break; + + default: + assert(false); + m_info_string.SetValueForKey(std::string(field.szName), ""); + break; + } + break; + } - auto& stream = *assetFile; - const auto infoString = CreateInfoString(asset); - const auto stringValue = infoString.ToString(ObjConstants::INFO_STRING_PREFIX_VEHICLE); - stream.write(stringValue.c_str(), stringValue.size()); + case VFT_KEY_BINDING: + case VFT_GRAPH: + case VFT_WIIUCONTROLOVERRIDE: + case VFT_NUM: + default: + assert(false); + break; } + } + +public: + InfoStringFromVehicleConverter(const VehicleDef *structure, const cspField_t *fields, const size_t fieldCount, + std::function<std::string(scr_string_t)> scriptStringValueCallback) + : InfoStringFromStructConverter(structure, fields, fieldCount, std::move(scriptStringValueCallback)) {} +}; +} // namespace T6 + +InfoString AssetDumperVehicle::CreateInfoString(XAssetInfo<VehicleDef> *asset) { + InfoStringFromVehicleConverter converter(asset->Asset(), vehicle_fields, std::extent<decltype(vehicle_fields)>::value, + [asset](const scr_string_t scrStr) -> std::string { + assert(scrStr < asset->m_zone->m_script_strings.Count()); + if (scrStr >= asset->m_zone->m_script_strings.Count()) + return ""; + + return asset->m_zone->m_script_strings[scrStr]; + }); + + return converter.Convert(); +} + +bool AssetDumperVehicle::ShouldDump(XAssetInfo<VehicleDef> *asset) { return true; } + +void AssetDumperVehicle::DumpAsset(AssetDumpingContext &context, XAssetInfo<VehicleDef> *asset) { + // Only dump raw when no gdt available + if (context.m_gdt) { + const auto infoString = CreateInfoString(asset); + GdtEntry gdtEntry(asset->m_name, ObjConstants::GDF_FILENAME_VEHICLE); + infoString.ToGdtProperties(ObjConstants::INFO_STRING_PREFIX_VEHICLE, gdtEntry); + context.m_gdt->WriteEntry(gdtEntry); + } else { + const auto assetFile = context.OpenAssetFile("vehicles/" + asset->m_name); + + if (!assetFile) + return; + + auto &stream = *assetFile; + const auto infoString = CreateInfoString(asset); + const auto stringValue = infoString.ToString(ObjConstants::INFO_STRING_PREFIX_VEHICLE); + stream.write(stringValue.c_str(), stringValue.size()); + } } diff --git a/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperVehicle.h b/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperVehicle.h index 499181e49..39f4af802 100644 --- a/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperVehicle.h +++ b/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperVehicle.h @@ -4,14 +4,12 @@ #include "Game/T6/T6.h" #include "InfoString/InfoString.h" -namespace T6 -{ - class AssetDumperVehicle final : public AbstractAssetDumper<VehicleDef> - { - static InfoString CreateInfoString(XAssetInfo<VehicleDef>* asset); +namespace T6 { +class AssetDumperVehicle final : public AbstractAssetDumper<VehicleDef> { + static InfoString CreateInfoString(XAssetInfo<VehicleDef> *asset); - protected: - bool ShouldDump(XAssetInfo<VehicleDef>* asset) override; - void DumpAsset(AssetDumpingContext& context, XAssetInfo<VehicleDef>* asset) override; - }; -} +protected: + bool ShouldDump(XAssetInfo<VehicleDef> *asset) override; + void DumpAsset(AssetDumpingContext &context, XAssetInfo<VehicleDef> *asset) override; +}; +} // namespace T6 diff --git a/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperWeapon.cpp b/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperWeapon.cpp index 0870e33ac..1bd100c08 100644 --- a/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperWeapon.cpp +++ b/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperWeapon.cpp @@ -1,442 +1,380 @@ #include "AssetDumperWeapon.h" #include <cassert> +#include <cstring> #include <sstream> #include <type_traits> -#include <cstring> -#include "Game/T6/ObjConstantsT6.h" #include "Game/T6/InfoString/EnumStrings.h" #include "Game/T6/InfoString/InfoStringFromStructConverter.h" #include "Game/T6/InfoString/WeaponFields.h" +#include "Game/T6/ObjConstantsT6.h" using namespace T6; -namespace T6 -{ - class InfoStringFromWeaponConverter final : public InfoStringFromStructConverter - { - protected: - void FillFromExtensionField(const cspField_t& field) override - { - switch (static_cast<weapFieldType_t>(field.iFieldType)) - { - case WFT_WEAPONTYPE: - FillFromEnumInt(std::string(field.szName), field.iOffset, szWeapTypeNames, std::extent<decltype(szWeapTypeNames)>::value); - break; - - case WFT_WEAPONCLASS: - FillFromEnumInt(std::string(field.szName), field.iOffset, szWeapClassNames, std::extent<decltype(szWeapClassNames)>::value); - break; - case WFT_OVERLAYRETICLE: - FillFromEnumInt(std::string(field.szName), field.iOffset, szWeapOverlayReticleNames, std::extent<decltype(szWeapOverlayReticleNames)>::value); - break; - - case WFT_PENETRATE_TYPE: - FillFromEnumInt(std::string(field.szName), field.iOffset, penetrateTypeNames, std::extent<decltype(penetrateTypeNames)>::value); - break; - - case WFT_IMPACT_TYPE: - FillFromEnumInt(std::string(field.szName), field.iOffset, impactTypeNames, std::extent<decltype(impactTypeNames)>::value); - break; - - case WFT_STANCE: - FillFromEnumInt(std::string(field.szName), field.iOffset, szWeapStanceNames, - std::extent<decltype(szWeapStanceNames)>::value); - break; - - case WFT_PROJ_EXPLOSION: - FillFromEnumInt(std::string(field.szName), field.iOffset, szProjectileExplosionNames, - std::extent<decltype(szProjectileExplosionNames)>::value); - break; - - case WFT_OFFHAND_CLASS: - FillFromEnumInt(std::string(field.szName), field.iOffset, offhandClassNames, - std::extent<decltype(offhandClassNames)>::value); - break; - - case WFT_OFFHAND_SLOT: - FillFromEnumInt(std::string(field.szName), field.iOffset, offhandSlotNames, std::extent<decltype(offhandSlotNames)>::value); - break; - - case WFT_ANIMTYPE: - FillFromEnumInt(std::string(field.szName), field.iOffset, playerAnimTypeNames, - std::extent<decltype(playerAnimTypeNames)>::value); - break; - - case WFT_ACTIVE_RETICLE_TYPE: - FillFromEnumInt(std::string(field.szName), field.iOffset, activeReticleNames, - std::extent<decltype(activeReticleNames)>::value); - break; - - case WFT_GUIDED_MISSILE_TYPE: - FillFromEnumInt(std::string(field.szName), field.iOffset, guidedMissileNames, - std::extent<decltype(guidedMissileNames)>::value); - break; - - case WFT_BOUNCE_SOUND: - { - const auto* bounceSound = *reinterpret_cast<const char***>(reinterpret_cast<uintptr_t>(m_structure) - + field.iOffset); - - if (bounceSound && bounceSound[0]) - { - const std::string firstBounceSound(bounceSound[0]); - const auto endOfBouncePrefix = firstBounceSound.rfind("_default"); - assert(endOfBouncePrefix != std::string::npos); - - if (endOfBouncePrefix != std::string::npos) - { - m_info_string.SetValueForKey(std::string(field.szName), - firstBounceSound.substr(0, endOfBouncePrefix)); - } - else - m_info_string.SetValueForKey(std::string(field.szName), ""); - } - else - m_info_string.SetValueForKey(std::string(field.szName), ""); - - break; - } - - case WFT_STICKINESS: - FillFromEnumInt(std::string(field.szName), field.iOffset, stickinessNames, std::extent<decltype(stickinessNames)>::value); - break; - - case WFT_ROTATETYPE: - FillFromEnumInt(std::string(field.szName), field.iOffset, rotateTypeNames, std::extent<decltype(rotateTypeNames)>::value); - break; - - case WFT_OVERLAYINTERFACE: - FillFromEnumInt(std::string(field.szName), field.iOffset, overlayInterfaceNames, - std::extent<decltype(overlayInterfaceNames)>::value); - break; - - case WFT_INVENTORYTYPE: - FillFromEnumInt(std::string(field.szName), field.iOffset, szWeapInventoryTypeNames, - std::extent<decltype(szWeapInventoryTypeNames)>::value); - break; - - case WFT_FIRETYPE: - FillFromEnumInt(std::string(field.szName), field.iOffset, szWeapFireTypeNames, - std::extent<decltype(szWeapFireTypeNames)>::value); - break; - - case WFT_CLIPTYPE: - FillFromEnumInt(std::string(field.szName), field.iOffset, szWeapClipTypeNames, - std::extent<decltype(szWeapClipTypeNames)>::value); - break; - - case WFT_AMMOCOUNTER_CLIPTYPE: - FillFromEnumInt(std::string(field.szName), field.iOffset, ammoCounterClipNames, - std::extent<decltype(ammoCounterClipNames)>::value); - break; - - case WFT_ICONRATIO_HUD: - case WFT_ICONRATIO_AMMOCOUNTER: - case WFT_ICONRATIO_KILL: - case WFT_ICONRATIO_DPAD: - case WFT_ICONRATIO_INDICATOR: - FillFromEnumInt(std::string(field.szName), field.iOffset, weapIconRatioNames, - std::extent<decltype(weapIconRatioNames)>::value); - break; - - case WFT_BARRELTYPE: - FillFromEnumInt(std::string(field.szName), field.iOffset, barrelTypeNames, std::extent<decltype(barrelTypeNames)>::value); - break; - - case WFT_HIDETAGS: - { - const auto* hideTags = reinterpret_cast<scr_string_t*>(reinterpret_cast<uintptr_t>(m_structure) + field.iOffset); - std::stringstream ss; - bool first = true; - - for (auto i = 0u; i < std::extent<decltype(WeaponFullDef::hideTags)>::value; i++) - { - const auto& str = m_get_scr_string(hideTags[i]); - if (!str.empty()) - { - if (!first) - ss << "\n"; - else - first = false; - - ss << str; - } - } - - m_info_string.SetValueForKey(std::string(field.szName), ss.str()); - break; - } - - case WFT_EXPLOSION_TAG: - FillFromScriptString(std::string(field.szName), field.iOffset); - break; - - case WFT_NOTETRACKSOUNDMAP: - { - const auto* keys = reinterpret_cast<scr_string_t*>(reinterpret_cast<uintptr_t>(m_structure) + field.iOffset); - const auto* values = &keys[std::extent<decltype(WeaponFullDef::notetrackSoundMapKeys)>::value]; - std::stringstream ss; - bool first = true; - - for (auto i = 0u; i < std::extent<decltype(WeaponFullDef::notetrackSoundMapKeys)>::value; i++) - { - const auto& key = m_get_scr_string(keys[i]); - const auto& value = m_get_scr_string(values[i]); - if (!key.empty()) - { - if (!first) - ss << "\n"; - else - first = false; - - ss << key; - - if (!value.empty()) - ss << " " << value; - } - } - - m_info_string.SetValueForKey(std::string(field.szName), ss.str()); - break; - } - - case WFT_WEAPON_CAMO: - { - const auto* camo = *reinterpret_cast<WeaponCamo**>(reinterpret_cast<uintptr_t>(m_structure) + field - .iOffset); - - if (camo) - m_info_string.SetValueForKey(std::string(field.szName), std::string(AssetName(camo->name))); - else - m_info_string.SetValueForKey(std::string(field.szName), ""); - break; - } - - case WFT_ATTACHMENTS: - { - const auto* attachments = reinterpret_cast<WeaponAttachment**>(reinterpret_cast<uintptr_t>(m_structure) + field.iOffset); - std::stringstream ss; - auto first = true; - - for (auto i = 0u; i < std::extent<decltype(WeaponFullDef::attachments)>::value; i++) - { - if (attachments[i]) - { - if (!first) - ss << "\n"; - else - first = false; - ss << AssetName(attachments[i]->szInternalName); - } - } - - m_info_string.SetValueForKey(std::string(field.szName), ss.str()); - break; - } - - case WFT_ATTACHMENT_UNIQUES: - { - const auto* attachmentUniques = reinterpret_cast<WeaponAttachmentUnique**>(reinterpret_cast<uintptr_t>(m_structure) + field.iOffset); - std::stringstream ss; - auto first = true; - - for (auto i = 0u; i < std::extent<decltype(WeaponFullDef::attachmentUniques)>::value; i++) - { - if (attachmentUniques[i]) - { - if (!first) - ss << "\n"; - else - first = false; - ss << AssetName(attachmentUniques[i]->szInternalName); - } - } - - m_info_string.SetValueForKey(std::string(field.szName), ss.str()); - break; - } - - case WFT_NUM_FIELD_TYPES: - default: - assert(false); - break; - } - } - - public: - InfoStringFromWeaponConverter(const WeaponFullDef* structure, const cspField_t* fields, const size_t fieldCount, std::function<std::string(scr_string_t)> scriptStringValueCallback) - : InfoStringFromStructConverter(structure, fields, fieldCount, std::move(scriptStringValueCallback)) - { - } - }; -} - -void AssetDumperWeapon::CopyToFullDef(const WeaponVariantDef* weapon, WeaponFullDef* fullDef) -{ - fullDef->weapVariantDef = *weapon; - - if (weapon->weapDef) - { - fullDef->weapDef = *weapon->weapDef; - fullDef->weapVariantDef.weapDef = &fullDef->weapDef; - } - - if (weapon->attachments) - { - assert(sizeof(WeaponFullDef::attachments) >= sizeof(void*) * std::extent<decltype(WeaponFullDef::attachments)>::value); - memcpy(fullDef->attachments, weapon->attachments, sizeof(void*) * std::extent<decltype(WeaponFullDef::attachments)>::value); - fullDef->weapVariantDef.attachments = fullDef->attachments; - } - - if (weapon->attachmentUniques) - { - assert(sizeof(WeaponFullDef::attachmentUniques) >= sizeof(void*) * std::extent<decltype(WeaponFullDef::attachmentUniques)>::value); - memcpy(fullDef->attachmentUniques, weapon->attachmentUniques, sizeof(void*) * std::extent<decltype(WeaponFullDef::attachmentUniques)>::value); - fullDef->weapVariantDef.attachmentUniques = fullDef->attachmentUniques; - } - - if (fullDef->weapDef.gunXModel) - { - assert(sizeof(WeaponFullDef::gunXModel) >= sizeof(void*) * std::extent<decltype(WeaponFullDef::gunXModel)>::value); - memcpy(fullDef->gunXModel, fullDef->weapDef.gunXModel, sizeof(void*) * std::extent<decltype(WeaponFullDef::gunXModel)>::value); - fullDef->weapDef.gunXModel = fullDef->gunXModel; - } - - if (weapon->szXAnims) - { - assert(sizeof(WeaponFullDef::szXAnims) >= sizeof(void*) * NUM_WEAP_ANIMS); - memcpy(fullDef->szXAnims, weapon->szXAnims, sizeof(void*) * NUM_WEAP_ANIMS); - fullDef->weapVariantDef.szXAnims = fullDef->szXAnims; +namespace T6 { +class InfoStringFromWeaponConverter final : public InfoStringFromStructConverter { +protected: + void FillFromExtensionField(const cspField_t &field) override { + switch (static_cast<weapFieldType_t>(field.iFieldType)) { + case WFT_WEAPONTYPE: + FillFromEnumInt(std::string(field.szName), field.iOffset, szWeapTypeNames, std::extent<decltype(szWeapTypeNames)>::value); + break; + + case WFT_WEAPONCLASS: + FillFromEnumInt(std::string(field.szName), field.iOffset, szWeapClassNames, std::extent<decltype(szWeapClassNames)>::value); + break; + case WFT_OVERLAYRETICLE: + FillFromEnumInt(std::string(field.szName), field.iOffset, szWeapOverlayReticleNames, std::extent<decltype(szWeapOverlayReticleNames)>::value); + break; + + case WFT_PENETRATE_TYPE: + FillFromEnumInt(std::string(field.szName), field.iOffset, penetrateTypeNames, std::extent<decltype(penetrateTypeNames)>::value); + break; + + case WFT_IMPACT_TYPE: + FillFromEnumInt(std::string(field.szName), field.iOffset, impactTypeNames, std::extent<decltype(impactTypeNames)>::value); + break; + + case WFT_STANCE: + FillFromEnumInt(std::string(field.szName), field.iOffset, szWeapStanceNames, std::extent<decltype(szWeapStanceNames)>::value); + break; + + case WFT_PROJ_EXPLOSION: + FillFromEnumInt(std::string(field.szName), field.iOffset, szProjectileExplosionNames, std::extent<decltype(szProjectileExplosionNames)>::value); + break; + + case WFT_OFFHAND_CLASS: + FillFromEnumInt(std::string(field.szName), field.iOffset, offhandClassNames, std::extent<decltype(offhandClassNames)>::value); + break; + + case WFT_OFFHAND_SLOT: + FillFromEnumInt(std::string(field.szName), field.iOffset, offhandSlotNames, std::extent<decltype(offhandSlotNames)>::value); + break; + + case WFT_ANIMTYPE: + FillFromEnumInt(std::string(field.szName), field.iOffset, playerAnimTypeNames, std::extent<decltype(playerAnimTypeNames)>::value); + break; + + case WFT_ACTIVE_RETICLE_TYPE: + FillFromEnumInt(std::string(field.szName), field.iOffset, activeReticleNames, std::extent<decltype(activeReticleNames)>::value); + break; + + case WFT_GUIDED_MISSILE_TYPE: + FillFromEnumInt(std::string(field.szName), field.iOffset, guidedMissileNames, std::extent<decltype(guidedMissileNames)>::value); + break; + + case WFT_BOUNCE_SOUND: { + const auto *bounceSound = *reinterpret_cast<const char ***>(reinterpret_cast<uintptr_t>(m_structure) + field.iOffset); + + if (bounceSound && bounceSound[0]) { + const std::string firstBounceSound(bounceSound[0]); + const auto endOfBouncePrefix = firstBounceSound.rfind("_default"); + assert(endOfBouncePrefix != std::string::npos); + + if (endOfBouncePrefix != std::string::npos) { + m_info_string.SetValueForKey(std::string(field.szName), firstBounceSound.substr(0, endOfBouncePrefix)); + } else + m_info_string.SetValueForKey(std::string(field.szName), ""); + } else + m_info_string.SetValueForKey(std::string(field.szName), ""); + + break; } - if (weapon->hideTags) - { - assert(sizeof(WeaponFullDef::hideTags) >= sizeof(scr_string_t) * std::extent<decltype(WeaponFullDef::hideTags)>::value); - memcpy(fullDef->hideTags, weapon->hideTags, sizeof(scr_string_t) * std::extent<decltype(WeaponFullDef::hideTags)>::value); - fullDef->weapVariantDef.hideTags = fullDef->hideTags; - } - - if (fullDef->weapDef.notetrackSoundMapKeys) - { - assert(sizeof(WeaponFullDef::notetrackSoundMapKeys) >= sizeof(scr_string_t) * std::extent<decltype(WeaponFullDef::notetrackSoundMapKeys)>::value); - memcpy(fullDef->notetrackSoundMapKeys, fullDef->weapDef.notetrackSoundMapKeys, sizeof(scr_string_t) * std::extent<decltype(WeaponFullDef::notetrackSoundMapKeys)>::value); - fullDef->weapDef.notetrackSoundMapKeys = fullDef->notetrackSoundMapKeys; - } + case WFT_STICKINESS: + FillFromEnumInt(std::string(field.szName), field.iOffset, stickinessNames, std::extent<decltype(stickinessNames)>::value); + break; + + case WFT_ROTATETYPE: + FillFromEnumInt(std::string(field.szName), field.iOffset, rotateTypeNames, std::extent<decltype(rotateTypeNames)>::value); + break; + + case WFT_OVERLAYINTERFACE: + FillFromEnumInt(std::string(field.szName), field.iOffset, overlayInterfaceNames, std::extent<decltype(overlayInterfaceNames)>::value); + break; + + case WFT_INVENTORYTYPE: + FillFromEnumInt(std::string(field.szName), field.iOffset, szWeapInventoryTypeNames, std::extent<decltype(szWeapInventoryTypeNames)>::value); + break; + + case WFT_FIRETYPE: + FillFromEnumInt(std::string(field.szName), field.iOffset, szWeapFireTypeNames, std::extent<decltype(szWeapFireTypeNames)>::value); + break; + + case WFT_CLIPTYPE: + FillFromEnumInt(std::string(field.szName), field.iOffset, szWeapClipTypeNames, std::extent<decltype(szWeapClipTypeNames)>::value); + break; + + case WFT_AMMOCOUNTER_CLIPTYPE: + FillFromEnumInt(std::string(field.szName), field.iOffset, ammoCounterClipNames, std::extent<decltype(ammoCounterClipNames)>::value); + break; + + case WFT_ICONRATIO_HUD: + case WFT_ICONRATIO_AMMOCOUNTER: + case WFT_ICONRATIO_KILL: + case WFT_ICONRATIO_DPAD: + case WFT_ICONRATIO_INDICATOR: + FillFromEnumInt(std::string(field.szName), field.iOffset, weapIconRatioNames, std::extent<decltype(weapIconRatioNames)>::value); + break; + + case WFT_BARRELTYPE: + FillFromEnumInt(std::string(field.szName), field.iOffset, barrelTypeNames, std::extent<decltype(barrelTypeNames)>::value); + break; + + case WFT_HIDETAGS: { + const auto *hideTags = reinterpret_cast<scr_string_t *>(reinterpret_cast<uintptr_t>(m_structure) + field.iOffset); + std::stringstream ss; + bool first = true; + + for (auto i = 0u; i < std::extent<decltype(WeaponFullDef::hideTags)>::value; i++) { + const auto &str = m_get_scr_string(hideTags[i]); + if (!str.empty()) { + if (!first) + ss << "\n"; + else + first = false; + + ss << str; + } + } - if (fullDef->weapDef.notetrackSoundMapValues) - { - assert(sizeof(WeaponFullDef::notetrackSoundMapValues) >= sizeof(scr_string_t) * std::extent<decltype(WeaponFullDef::notetrackSoundMapValues)>::value); - memcpy(fullDef->notetrackSoundMapValues, fullDef->weapDef.notetrackSoundMapValues, sizeof(scr_string_t) * std::extent<decltype(WeaponFullDef::notetrackSoundMapValues)>::value); - fullDef->weapDef.notetrackSoundMapValues = fullDef->notetrackSoundMapValues; + m_info_string.SetValueForKey(std::string(field.szName), ss.str()); + break; } - if (fullDef->weapDef.worldModel) - { - assert(sizeof(WeaponFullDef::worldModel) >= sizeof(void*) * std::extent<decltype(WeaponFullDef::worldModel)>::value); - memcpy(fullDef->worldModel, fullDef->weapDef.worldModel, sizeof(void*) * std::extent<decltype(WeaponFullDef::worldModel)>::value); - fullDef->weapDef.worldModel = fullDef->worldModel; - } + case WFT_EXPLOSION_TAG: + FillFromScriptString(std::string(field.szName), field.iOffset); + break; + + case WFT_NOTETRACKSOUNDMAP: { + const auto *keys = reinterpret_cast<scr_string_t *>(reinterpret_cast<uintptr_t>(m_structure) + field.iOffset); + const auto *values = &keys[std::extent<decltype(WeaponFullDef::notetrackSoundMapKeys)>::value]; + std::stringstream ss; + bool first = true; + + for (auto i = 0u; i < std::extent<decltype(WeaponFullDef::notetrackSoundMapKeys)>::value; i++) { + const auto &key = m_get_scr_string(keys[i]); + const auto &value = m_get_scr_string(values[i]); + if (!key.empty()) { + if (!first) + ss << "\n"; + else + first = false; + + ss << key; + + if (!value.empty()) + ss << " " << value; + } + } - if (weapon->attachViewModel) - { - assert(sizeof(WeaponFullDef::attachViewModel) >= sizeof(void*) * std::extent<decltype(WeaponFullDef::attachViewModel)>::value); - memcpy(fullDef->attachViewModel, weapon->attachViewModel, sizeof(void*) * std::extent<decltype(WeaponFullDef::attachViewModel)>::value); - fullDef->weapVariantDef.attachViewModel = fullDef->attachViewModel; + m_info_string.SetValueForKey(std::string(field.szName), ss.str()); + break; } - if (weapon->attachWorldModel) - { - assert(sizeof(WeaponFullDef::attachWorldModel) >= sizeof(void*) * std::extent<decltype(WeaponFullDef::attachWorldModel)>::value); - memcpy(fullDef->attachWorldModel, weapon->attachWorldModel, sizeof(void*) * std::extent<decltype(WeaponFullDef::attachWorldModel)>::value); - fullDef->weapVariantDef.attachWorldModel = fullDef->attachWorldModel; - } + case WFT_WEAPON_CAMO: { + const auto *camo = *reinterpret_cast<WeaponCamo **>(reinterpret_cast<uintptr_t>(m_structure) + field.iOffset); - if (weapon->attachViewModelTag) - { - assert(sizeof(WeaponFullDef::attachViewModelTag) >= sizeof(void*) * std::extent<decltype(WeaponFullDef::attachViewModelTag)>::value); - memcpy(fullDef->attachViewModelTag, weapon->attachViewModelTag, sizeof(void*) * std::extent<decltype(WeaponFullDef::attachViewModelTag)>::value); - fullDef->weapVariantDef.attachViewModelTag = fullDef->attachViewModelTag; + if (camo) + m_info_string.SetValueForKey(std::string(field.szName), std::string(AssetName(camo->name))); + else + m_info_string.SetValueForKey(std::string(field.szName), ""); + break; } - if (weapon->attachWorldModelTag) - { - assert(sizeof(WeaponFullDef::attachWorldModelTag) >= sizeof(void*) * std::extent<decltype(WeaponFullDef::attachWorldModelTag)>::value); - memcpy(fullDef->attachWorldModelTag, weapon->attachWorldModelTag, sizeof(void*) * std::extent<decltype(WeaponFullDef::attachWorldModelTag)>::value); - fullDef->weapVariantDef.attachWorldModelTag = fullDef->attachWorldModelTag; - } + case WFT_ATTACHMENTS: { + const auto *attachments = reinterpret_cast<WeaponAttachment **>(reinterpret_cast<uintptr_t>(m_structure) + field.iOffset); + std::stringstream ss; + auto first = true; + + for (auto i = 0u; i < std::extent<decltype(WeaponFullDef::attachments)>::value; i++) { + if (attachments[i]) { + if (!first) + ss << "\n"; + else + first = false; + ss << AssetName(attachments[i]->szInternalName); + } + } - if (fullDef->weapDef.parallelBounce) - { - assert(sizeof(WeaponFullDef::parallelBounce) >= sizeof(float) * SURF_TYPE_NUM); - memcpy(fullDef->parallelBounce, fullDef->weapDef.parallelBounce, sizeof(float) * SURF_TYPE_NUM); - fullDef->weapDef.parallelBounce = fullDef->parallelBounce; + m_info_string.SetValueForKey(std::string(field.szName), ss.str()); + break; } - if (fullDef->weapDef.perpendicularBounce) - { - assert(sizeof(WeaponFullDef::perpendicularBounce) >= sizeof(float) * SURF_TYPE_NUM); - memcpy(fullDef->perpendicularBounce, fullDef->weapDef.perpendicularBounce, sizeof(float) * SURF_TYPE_NUM); - fullDef->weapDef.perpendicularBounce = fullDef->perpendicularBounce; - } + case WFT_ATTACHMENT_UNIQUES: { + const auto *attachmentUniques = reinterpret_cast<WeaponAttachmentUnique **>(reinterpret_cast<uintptr_t>(m_structure) + field.iOffset); + std::stringstream ss; + auto first = true; + + for (auto i = 0u; i < std::extent<decltype(WeaponFullDef::attachmentUniques)>::value; i++) { + if (attachmentUniques[i]) { + if (!first) + ss << "\n"; + else + first = false; + ss << AssetName(attachmentUniques[i]->szInternalName); + } + } - if (fullDef->weapDef.locationDamageMultipliers) - { - assert(sizeof(WeaponFullDef::locationDamageMultipliers) >= sizeof(float) * HITLOC_NUM); - memcpy(fullDef->locationDamageMultipliers, fullDef->weapDef.locationDamageMultipliers, sizeof(float) * HITLOC_NUM); - fullDef->weapDef.locationDamageMultipliers = fullDef->locationDamageMultipliers; + m_info_string.SetValueForKey(std::string(field.szName), ss.str()); + break; } - if (fullDef->weapDef.weaponCamo && fullDef->weapDef.weaponCamo->name) - { - strncpy(fullDef->weaponCamo, fullDef->weapDef.weaponCamo->name, std::extent<decltype(WeaponFullDef::weaponCamo)>::value); + case WFT_NUM_FIELD_TYPES: + default: + assert(false); + break; } + } + +public: + InfoStringFromWeaponConverter(const WeaponFullDef *structure, const cspField_t *fields, const size_t fieldCount, + std::function<std::string(scr_string_t)> scriptStringValueCallback) + : InfoStringFromStructConverter(structure, fields, fieldCount, std::move(scriptStringValueCallback)) {} +}; +} // namespace T6 + +void AssetDumperWeapon::CopyToFullDef(const WeaponVariantDef *weapon, WeaponFullDef *fullDef) { + fullDef->weapVariantDef = *weapon; + + if (weapon->weapDef) { + fullDef->weapDef = *weapon->weapDef; + fullDef->weapVariantDef.weapDef = &fullDef->weapDef; + } + + if (weapon->attachments) { + assert(sizeof(WeaponFullDef::attachments) >= sizeof(void *) * std::extent<decltype(WeaponFullDef::attachments)>::value); + memcpy(fullDef->attachments, weapon->attachments, sizeof(void *) * std::extent<decltype(WeaponFullDef::attachments)>::value); + fullDef->weapVariantDef.attachments = fullDef->attachments; + } + + if (weapon->attachmentUniques) { + assert(sizeof(WeaponFullDef::attachmentUniques) >= sizeof(void *) * std::extent<decltype(WeaponFullDef::attachmentUniques)>::value); + memcpy(fullDef->attachmentUniques, weapon->attachmentUniques, sizeof(void *) * std::extent<decltype(WeaponFullDef::attachmentUniques)>::value); + fullDef->weapVariantDef.attachmentUniques = fullDef->attachmentUniques; + } + + if (fullDef->weapDef.gunXModel) { + assert(sizeof(WeaponFullDef::gunXModel) >= sizeof(void *) * std::extent<decltype(WeaponFullDef::gunXModel)>::value); + memcpy(fullDef->gunXModel, fullDef->weapDef.gunXModel, sizeof(void *) * std::extent<decltype(WeaponFullDef::gunXModel)>::value); + fullDef->weapDef.gunXModel = fullDef->gunXModel; + } + + if (weapon->szXAnims) { + assert(sizeof(WeaponFullDef::szXAnims) >= sizeof(void *) * NUM_WEAP_ANIMS); + memcpy(fullDef->szXAnims, weapon->szXAnims, sizeof(void *) * NUM_WEAP_ANIMS); + fullDef->weapVariantDef.szXAnims = fullDef->szXAnims; + } + + if (weapon->hideTags) { + assert(sizeof(WeaponFullDef::hideTags) >= sizeof(scr_string_t) * std::extent<decltype(WeaponFullDef::hideTags)>::value); + memcpy(fullDef->hideTags, weapon->hideTags, sizeof(scr_string_t) * std::extent<decltype(WeaponFullDef::hideTags)>::value); + fullDef->weapVariantDef.hideTags = fullDef->hideTags; + } + + if (fullDef->weapDef.notetrackSoundMapKeys) { + assert(sizeof(WeaponFullDef::notetrackSoundMapKeys) >= sizeof(scr_string_t) * std::extent<decltype(WeaponFullDef::notetrackSoundMapKeys)>::value); + memcpy(fullDef->notetrackSoundMapKeys, fullDef->weapDef.notetrackSoundMapKeys, + sizeof(scr_string_t) * std::extent<decltype(WeaponFullDef::notetrackSoundMapKeys)>::value); + fullDef->weapDef.notetrackSoundMapKeys = fullDef->notetrackSoundMapKeys; + } + + if (fullDef->weapDef.notetrackSoundMapValues) { + assert(sizeof(WeaponFullDef::notetrackSoundMapValues) >= sizeof(scr_string_t) * std::extent<decltype(WeaponFullDef::notetrackSoundMapValues)>::value); + memcpy(fullDef->notetrackSoundMapValues, fullDef->weapDef.notetrackSoundMapValues, + sizeof(scr_string_t) * std::extent<decltype(WeaponFullDef::notetrackSoundMapValues)>::value); + fullDef->weapDef.notetrackSoundMapValues = fullDef->notetrackSoundMapValues; + } + + if (fullDef->weapDef.worldModel) { + assert(sizeof(WeaponFullDef::worldModel) >= sizeof(void *) * std::extent<decltype(WeaponFullDef::worldModel)>::value); + memcpy(fullDef->worldModel, fullDef->weapDef.worldModel, sizeof(void *) * std::extent<decltype(WeaponFullDef::worldModel)>::value); + fullDef->weapDef.worldModel = fullDef->worldModel; + } + + if (weapon->attachViewModel) { + assert(sizeof(WeaponFullDef::attachViewModel) >= sizeof(void *) * std::extent<decltype(WeaponFullDef::attachViewModel)>::value); + memcpy(fullDef->attachViewModel, weapon->attachViewModel, sizeof(void *) * std::extent<decltype(WeaponFullDef::attachViewModel)>::value); + fullDef->weapVariantDef.attachViewModel = fullDef->attachViewModel; + } + + if (weapon->attachWorldModel) { + assert(sizeof(WeaponFullDef::attachWorldModel) >= sizeof(void *) * std::extent<decltype(WeaponFullDef::attachWorldModel)>::value); + memcpy(fullDef->attachWorldModel, weapon->attachWorldModel, sizeof(void *) * std::extent<decltype(WeaponFullDef::attachWorldModel)>::value); + fullDef->weapVariantDef.attachWorldModel = fullDef->attachWorldModel; + } + + if (weapon->attachViewModelTag) { + assert(sizeof(WeaponFullDef::attachViewModelTag) >= sizeof(void *) * std::extent<decltype(WeaponFullDef::attachViewModelTag)>::value); + memcpy(fullDef->attachViewModelTag, weapon->attachViewModelTag, sizeof(void *) * std::extent<decltype(WeaponFullDef::attachViewModelTag)>::value); + fullDef->weapVariantDef.attachViewModelTag = fullDef->attachViewModelTag; + } + + if (weapon->attachWorldModelTag) { + assert(sizeof(WeaponFullDef::attachWorldModelTag) >= sizeof(void *) * std::extent<decltype(WeaponFullDef::attachWorldModelTag)>::value); + memcpy(fullDef->attachWorldModelTag, weapon->attachWorldModelTag, sizeof(void *) * std::extent<decltype(WeaponFullDef::attachWorldModelTag)>::value); + fullDef->weapVariantDef.attachWorldModelTag = fullDef->attachWorldModelTag; + } + + if (fullDef->weapDef.parallelBounce) { + assert(sizeof(WeaponFullDef::parallelBounce) >= sizeof(float) * SURF_TYPE_NUM); + memcpy(fullDef->parallelBounce, fullDef->weapDef.parallelBounce, sizeof(float) * SURF_TYPE_NUM); + fullDef->weapDef.parallelBounce = fullDef->parallelBounce; + } + + if (fullDef->weapDef.perpendicularBounce) { + assert(sizeof(WeaponFullDef::perpendicularBounce) >= sizeof(float) * SURF_TYPE_NUM); + memcpy(fullDef->perpendicularBounce, fullDef->weapDef.perpendicularBounce, sizeof(float) * SURF_TYPE_NUM); + fullDef->weapDef.perpendicularBounce = fullDef->perpendicularBounce; + } + + if (fullDef->weapDef.locationDamageMultipliers) { + assert(sizeof(WeaponFullDef::locationDamageMultipliers) >= sizeof(float) * HITLOC_NUM); + memcpy(fullDef->locationDamageMultipliers, fullDef->weapDef.locationDamageMultipliers, sizeof(float) * HITLOC_NUM); + fullDef->weapDef.locationDamageMultipliers = fullDef->locationDamageMultipliers; + } + + if (fullDef->weapDef.weaponCamo && fullDef->weapDef.weaponCamo->name) { + strncpy(fullDef->weaponCamo, fullDef->weapDef.weaponCamo->name, std::extent<decltype(WeaponFullDef::weaponCamo)>::value); + } } -InfoString AssetDumperWeapon::CreateInfoString(XAssetInfo<WeaponVariantDef>* asset) -{ - const auto fullDef = std::make_unique<WeaponFullDef>(); - memset(fullDef.get(), 0, sizeof(WeaponFullDef)); - CopyToFullDef(asset->Asset(), fullDef.get()); +InfoString AssetDumperWeapon::CreateInfoString(XAssetInfo<WeaponVariantDef> *asset) { + const auto fullDef = std::make_unique<WeaponFullDef>(); + memset(fullDef.get(), 0, sizeof(WeaponFullDef)); + CopyToFullDef(asset->Asset(), fullDef.get()); - InfoStringFromWeaponConverter converter(fullDef.get(), weapon_fields, std::extent<decltype(weapon_fields)>::value, [asset](const scr_string_t scrStr) -> std::string - { - assert(scrStr < asset->m_zone->m_script_strings.Count()); - if (scrStr >= asset->m_zone->m_script_strings.Count()) - return ""; + InfoStringFromWeaponConverter converter(fullDef.get(), weapon_fields, std::extent<decltype(weapon_fields)>::value, + [asset](const scr_string_t scrStr) -> std::string { + assert(scrStr < asset->m_zone->m_script_strings.Count()); + if (scrStr >= asset->m_zone->m_script_strings.Count()) + return ""; - return asset->m_zone->m_script_strings[scrStr]; - }); - - return converter.Convert(); -} + return asset->m_zone->m_script_strings[scrStr]; + }); -bool AssetDumperWeapon::ShouldDump(XAssetInfo<WeaponVariantDef>* asset) -{ - return true; + return converter.Convert(); } -void AssetDumperWeapon::DumpAsset(AssetDumpingContext& context, XAssetInfo<WeaponVariantDef>* asset) -{ - // Only dump raw when no gdt available - if (context.m_gdt) - { - const auto infoString = CreateInfoString(asset); - GdtEntry gdtEntry(asset->m_name, ObjConstants::GDF_FILENAME_WEAPON); - infoString.ToGdtProperties(ObjConstants::INFO_STRING_PREFIX_WEAPON, gdtEntry); - context.m_gdt->WriteEntry(gdtEntry); - } - else - { - const auto assetFile = context.OpenAssetFile("weapons/" + asset->m_name); - - if (!assetFile) - return; - - auto& stream = *assetFile; - const auto infoString = CreateInfoString(asset); - const auto stringValue = infoString.ToString(ObjConstants::INFO_STRING_PREFIX_WEAPON); - stream.write(stringValue.c_str(), stringValue.size()); - } +bool AssetDumperWeapon::ShouldDump(XAssetInfo<WeaponVariantDef> *asset) { return true; } + +void AssetDumperWeapon::DumpAsset(AssetDumpingContext &context, XAssetInfo<WeaponVariantDef> *asset) { + // Only dump raw when no gdt available + if (context.m_gdt) { + const auto infoString = CreateInfoString(asset); + GdtEntry gdtEntry(asset->m_name, ObjConstants::GDF_FILENAME_WEAPON); + infoString.ToGdtProperties(ObjConstants::INFO_STRING_PREFIX_WEAPON, gdtEntry); + context.m_gdt->WriteEntry(gdtEntry); + } else { + const auto assetFile = context.OpenAssetFile("weapons/" + asset->m_name); + + if (!assetFile) + return; + + auto &stream = *assetFile; + const auto infoString = CreateInfoString(asset); + const auto stringValue = infoString.ToString(ObjConstants::INFO_STRING_PREFIX_WEAPON); + stream.write(stringValue.c_str(), stringValue.size()); + } } diff --git a/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperWeapon.h b/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperWeapon.h index 1e89f189e..6ff787629 100644 --- a/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperWeapon.h +++ b/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperWeapon.h @@ -4,15 +4,13 @@ #include "Game/T6/T6.h" #include "InfoString/InfoString.h" -namespace T6 -{ - class AssetDumperWeapon final : public AbstractAssetDumper<WeaponVariantDef> - { - static void CopyToFullDef(const WeaponVariantDef* weapon, WeaponFullDef* fullDef); - static InfoString CreateInfoString(XAssetInfo<WeaponVariantDef>* asset); +namespace T6 { +class AssetDumperWeapon final : public AbstractAssetDumper<WeaponVariantDef> { + static void CopyToFullDef(const WeaponVariantDef *weapon, WeaponFullDef *fullDef); + static InfoString CreateInfoString(XAssetInfo<WeaponVariantDef> *asset); - protected: - bool ShouldDump(XAssetInfo<WeaponVariantDef>* asset) override; - void DumpAsset(AssetDumpingContext& context, XAssetInfo<WeaponVariantDef>* asset) override; - }; -} +protected: + bool ShouldDump(XAssetInfo<WeaponVariantDef> *asset) override; + void DumpAsset(AssetDumpingContext &context, XAssetInfo<WeaponVariantDef> *asset) override; +}; +} // namespace T6 diff --git a/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperWeaponAttachment.cpp b/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperWeaponAttachment.cpp index adb665e80..418331a57 100644 --- a/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperWeaponAttachment.cpp +++ b/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperWeaponAttachment.cpp @@ -3,86 +3,73 @@ #include <cassert> #include <type_traits> -#include "Game/T6/ObjConstantsT6.h" #include "Game/T6/InfoString/EnumStrings.h" #include "Game/T6/InfoString/InfoStringFromStructConverter.h" #include "Game/T6/InfoString/WeaponAttachmentFields.h" +#include "Game/T6/ObjConstantsT6.h" using namespace T6; -namespace T6 -{ - class InfoStringFromAttachmentConverter final : public InfoStringFromStructConverter - { - protected: - void FillFromExtensionField(const cspField_t& field) override - { - switch (static_cast<attachmentFieldType_t>(field.iFieldType)) - { - case AFT_ATTACHMENTTYPE: - FillFromEnumInt(std::string(field.szName), field.iOffset, szAttachmentTypeNames, std::extent<decltype(szAttachmentTypeNames)>::value); - break; +namespace T6 { +class InfoStringFromAttachmentConverter final : public InfoStringFromStructConverter { +protected: + void FillFromExtensionField(const cspField_t &field) override { + switch (static_cast<attachmentFieldType_t>(field.iFieldType)) { + case AFT_ATTACHMENTTYPE: + FillFromEnumInt(std::string(field.szName), field.iOffset, szAttachmentTypeNames, std::extent<decltype(szAttachmentTypeNames)>::value); + break; - case AFT_PENETRATE_TYPE: - FillFromEnumInt(std::string(field.szName), field.iOffset, penetrateTypeNames, std::extent<decltype(penetrateTypeNames)>::value); - break; + case AFT_PENETRATE_TYPE: + FillFromEnumInt(std::string(field.szName), field.iOffset, penetrateTypeNames, std::extent<decltype(penetrateTypeNames)>::value); + break; - case AFT_FIRETYPE: - FillFromEnumInt(std::string(field.szName), field.iOffset, szWeapFireTypeNames, std::extent<decltype(szWeapFireTypeNames)>::value); - break; + case AFT_FIRETYPE: + FillFromEnumInt(std::string(field.szName), field.iOffset, szWeapFireTypeNames, std::extent<decltype(szWeapFireTypeNames)>::value); + break; - default: - break; - } - } + default: + break; + } + } - public: - InfoStringFromAttachmentConverter(const WeaponAttachment* structure, const cspField_t* fields, const size_t fieldCount, std::function<std::string(scr_string_t)> scriptStringValueCallback) - : InfoStringFromStructConverter(structure, fields, fieldCount, std::move(scriptStringValueCallback)) - { - } - }; -} +public: + InfoStringFromAttachmentConverter(const WeaponAttachment *structure, const cspField_t *fields, const size_t fieldCount, + std::function<std::string(scr_string_t)> scriptStringValueCallback) + : InfoStringFromStructConverter(structure, fields, fieldCount, std::move(scriptStringValueCallback)) {} +}; +} // namespace T6 -InfoString AssetDumperWeaponAttachment::CreateInfoString(XAssetInfo<WeaponAttachment>* asset) -{ - InfoStringFromAttachmentConverter converter(asset->Asset(), attachment_fields, std::extent<decltype(attachment_fields)>::value, [asset](const scr_string_t scrStr) -> std::string - { - assert(scrStr < asset->m_zone->m_script_strings.Count()); - if (scrStr >= asset->m_zone->m_script_strings.Count()) - return ""; +InfoString AssetDumperWeaponAttachment::CreateInfoString(XAssetInfo<WeaponAttachment> *asset) { + InfoStringFromAttachmentConverter converter(asset->Asset(), attachment_fields, std::extent<decltype(attachment_fields)>::value, + [asset](const scr_string_t scrStr) -> std::string { + assert(scrStr < asset->m_zone->m_script_strings.Count()); + if (scrStr >= asset->m_zone->m_script_strings.Count()) + return ""; - return asset->m_zone->m_script_strings[scrStr]; - }); + return asset->m_zone->m_script_strings[scrStr]; + }); - return converter.Convert(); + return converter.Convert(); } -bool AssetDumperWeaponAttachment::ShouldDump(XAssetInfo<WeaponAttachment>* asset) -{ - return true; -} +bool AssetDumperWeaponAttachment::ShouldDump(XAssetInfo<WeaponAttachment> *asset) { return true; } -void AssetDumperWeaponAttachment::DumpAsset(AssetDumpingContext& context, XAssetInfo<WeaponAttachment>* asset) -{ - // Only dump raw when no gdt available - if (context.m_gdt) - { - const auto infoString = CreateInfoString(asset); - GdtEntry gdtEntry(asset->m_name, ObjConstants::GDF_FILENAME_WEAPON_ATTACHMENT); - infoString.ToGdtProperties(ObjConstants::INFO_STRING_PREFIX_WEAPON_ATTACHMENT, gdtEntry); - context.m_gdt->WriteEntry(gdtEntry); - } - else - { - const auto assetFile = context.OpenAssetFile("attachment/" + asset->m_name); +void AssetDumperWeaponAttachment::DumpAsset(AssetDumpingContext &context, XAssetInfo<WeaponAttachment> *asset) { + // Only dump raw when no gdt available + if (context.m_gdt) { + const auto infoString = CreateInfoString(asset); + GdtEntry gdtEntry(asset->m_name, ObjConstants::GDF_FILENAME_WEAPON_ATTACHMENT); + infoString.ToGdtProperties(ObjConstants::INFO_STRING_PREFIX_WEAPON_ATTACHMENT, gdtEntry); + context.m_gdt->WriteEntry(gdtEntry); + } else { + const auto assetFile = context.OpenAssetFile("attachment/" + asset->m_name); - if (!assetFile) - return; + if (!assetFile) + return; - auto& stream = *assetFile; - const auto infoString = CreateInfoString(asset); - const auto stringValue = infoString.ToString(ObjConstants::INFO_STRING_PREFIX_WEAPON_ATTACHMENT); - stream.write(stringValue.c_str(), stringValue.size()); - } + auto &stream = *assetFile; + const auto infoString = CreateInfoString(asset); + const auto stringValue = infoString.ToString(ObjConstants::INFO_STRING_PREFIX_WEAPON_ATTACHMENT); + stream.write(stringValue.c_str(), stringValue.size()); + } } diff --git a/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperWeaponAttachment.h b/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperWeaponAttachment.h index 25158627a..4ffbf0d0e 100644 --- a/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperWeaponAttachment.h +++ b/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperWeaponAttachment.h @@ -4,14 +4,12 @@ #include "Game/T6/T6.h" #include "InfoString/InfoString.h" -namespace T6 -{ - class AssetDumperWeaponAttachment final : public AbstractAssetDumper<WeaponAttachment> - { - static InfoString CreateInfoString(XAssetInfo<WeaponAttachment>* asset); +namespace T6 { +class AssetDumperWeaponAttachment final : public AbstractAssetDumper<WeaponAttachment> { + static InfoString CreateInfoString(XAssetInfo<WeaponAttachment> *asset); - protected: - bool ShouldDump(XAssetInfo<WeaponAttachment>* asset) override; - void DumpAsset(AssetDumpingContext& context, XAssetInfo<WeaponAttachment>* asset) override; - }; -} +protected: + bool ShouldDump(XAssetInfo<WeaponAttachment> *asset) override; + void DumpAsset(AssetDumpingContext &context, XAssetInfo<WeaponAttachment> *asset) override; +}; +} // namespace T6 diff --git a/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperWeaponAttachmentUnique.cpp b/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperWeaponAttachmentUnique.cpp index 85e62da5d..b20424a72 100644 --- a/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperWeaponAttachmentUnique.cpp +++ b/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperWeaponAttachmentUnique.cpp @@ -1,156 +1,131 @@ #include "AssetDumperWeaponAttachmentUnique.h" #include <cassert> +#include <cstring> #include <sstream> #include <type_traits> -#include <cstring> -#include "Game/T6/ObjConstantsT6.h" #include "Game/T6/InfoString/EnumStrings.h" #include "Game/T6/InfoString/InfoStringFromStructConverter.h" #include "Game/T6/InfoString/WeaponAttachmentUniqueFields.h" +#include "Game/T6/ObjConstantsT6.h" using namespace T6; -namespace T6 -{ - class InfoStringFromWeaponAttachmentUniqueConverter final : public InfoStringFromStructConverter - { - protected: - void FillFromExtensionField(const cspField_t& field) override - { - switch (static_cast<attachmentUniqueFieldType_t>(field.iFieldType)) - { - case AUFT_ATTACHMENTTYPE: - FillFromEnumInt(std::string(field.szName), field.iOffset, szAttachmentTypeNames, std::extent<decltype(szAttachmentTypeNames)>::value); - break; - - case AUFT_HIDETAGS: - { - const auto* hideTags = reinterpret_cast<scr_string_t*>(reinterpret_cast<uintptr_t>(m_structure) + field.iOffset); - std::stringstream ss; - auto first = true; - - for (auto i = 0u; i < std::extent<decltype(WeaponFullDef::hideTags)>::value; i++) - { - const auto& str = m_get_scr_string(hideTags[i]); - if (!str.empty()) - { - if (!first) - ss << "\n"; - else - first = false; - - ss << str; - } - } - - m_info_string.SetValueForKey(std::string(field.szName), ss.str()); - break; - } - - case AUFT_OVERLAYRETICLE: - FillFromEnumInt(std::string(field.szName), field.iOffset, szWeapOverlayReticleNames, std::extent<decltype(szWeapOverlayReticleNames)>::value); - break; - - case AUFT_CAMO: - { - const auto* camo = *reinterpret_cast<WeaponCamo**>(reinterpret_cast<uintptr_t>(m_structure) + field - .iOffset); - - if (camo) - m_info_string.SetValueForKey(std::string(field.szName), std::string(AssetName(camo->name))); - else - m_info_string.SetValueForKey(std::string(field.szName), ""); - break; - } - - default: - assert(false); - break; - } +namespace T6 { +class InfoStringFromWeaponAttachmentUniqueConverter final : public InfoStringFromStructConverter { +protected: + void FillFromExtensionField(const cspField_t &field) override { + switch (static_cast<attachmentUniqueFieldType_t>(field.iFieldType)) { + case AUFT_ATTACHMENTTYPE: + FillFromEnumInt(std::string(field.szName), field.iOffset, szAttachmentTypeNames, std::extent<decltype(szAttachmentTypeNames)>::value); + break; + + case AUFT_HIDETAGS: { + const auto *hideTags = reinterpret_cast<scr_string_t *>(reinterpret_cast<uintptr_t>(m_structure) + field.iOffset); + std::stringstream ss; + auto first = true; + + for (auto i = 0u; i < std::extent<decltype(WeaponFullDef::hideTags)>::value; i++) { + const auto &str = m_get_scr_string(hideTags[i]); + if (!str.empty()) { + if (!first) + ss << "\n"; + else + first = false; + + ss << str; } + } - public: - InfoStringFromWeaponAttachmentUniqueConverter(const WeaponAttachmentUniqueFull* structure, const cspField_t* fields, const size_t fieldCount, - std::function<std::string(scr_string_t)> scriptStringValueCallback) - : InfoStringFromStructConverter(structure, fields, fieldCount, std::move(scriptStringValueCallback)) - { - } - }; -} + m_info_string.SetValueForKey(std::string(field.szName), ss.str()); + break; + } -void AssetDumperWeaponAttachmentUnique::CopyToFullDef(const WeaponAttachmentUnique* attachment, WeaponAttachmentUniqueFull* fullDef) -{ - fullDef->attachment = *attachment; + case AUFT_OVERLAYRETICLE: + FillFromEnumInt(std::string(field.szName), field.iOffset, szWeapOverlayReticleNames, std::extent<decltype(szWeapOverlayReticleNames)>::value); + break; - if (attachment->szXAnims) - { - assert(sizeof(WeaponAttachmentUniqueFull::szXAnims) >= sizeof(void*) * NUM_WEAP_ANIMS); - memcpy(fullDef->szXAnims, attachment->szXAnims, sizeof(void*) * NUM_WEAP_ANIMS); - fullDef->attachment.szXAnims = fullDef->szXAnims; - } + case AUFT_CAMO: { + const auto *camo = *reinterpret_cast<WeaponCamo **>(reinterpret_cast<uintptr_t>(m_structure) + field.iOffset); - if (attachment->hideTags) - { - assert(sizeof(WeaponAttachmentUniqueFull::hideTags) >= sizeof(scr_string_t) * std::extent<decltype(WeaponAttachmentUniqueFull::hideTags)>::value); - memcpy(fullDef->hideTags, attachment->hideTags, sizeof(scr_string_t) * std::extent<decltype(WeaponAttachmentUniqueFull::hideTags)>::value); - fullDef->attachment.hideTags = fullDef->hideTags; + if (camo) + m_info_string.SetValueForKey(std::string(field.szName), std::string(AssetName(camo->name))); + else + m_info_string.SetValueForKey(std::string(field.szName), ""); + break; } - if (attachment->locationDamageMultipliers) - { - assert(sizeof(WeaponAttachmentUniqueFull::locationDamageMultipliers) >= sizeof(float) * HITLOC_NUM); - memcpy(fullDef->locationDamageMultipliers, attachment->locationDamageMultipliers, sizeof(float) * HITLOC_NUM); - fullDef->attachment.locationDamageMultipliers = fullDef->locationDamageMultipliers; + default: + assert(false); + break; } + } + +public: + InfoStringFromWeaponAttachmentUniqueConverter(const WeaponAttachmentUniqueFull *structure, const cspField_t *fields, const size_t fieldCount, + std::function<std::string(scr_string_t)> scriptStringValueCallback) + : InfoStringFromStructConverter(structure, fields, fieldCount, std::move(scriptStringValueCallback)) {} +}; +} // namespace T6 + +void AssetDumperWeaponAttachmentUnique::CopyToFullDef(const WeaponAttachmentUnique *attachment, WeaponAttachmentUniqueFull *fullDef) { + fullDef->attachment = *attachment; + + if (attachment->szXAnims) { + assert(sizeof(WeaponAttachmentUniqueFull::szXAnims) >= sizeof(void *) * NUM_WEAP_ANIMS); + memcpy(fullDef->szXAnims, attachment->szXAnims, sizeof(void *) * NUM_WEAP_ANIMS); + fullDef->attachment.szXAnims = fullDef->szXAnims; + } + + if (attachment->hideTags) { + assert(sizeof(WeaponAttachmentUniqueFull::hideTags) >= sizeof(scr_string_t) * std::extent<decltype(WeaponAttachmentUniqueFull::hideTags)>::value); + memcpy(fullDef->hideTags, attachment->hideTags, sizeof(scr_string_t) * std::extent<decltype(WeaponAttachmentUniqueFull::hideTags)>::value); + fullDef->attachment.hideTags = fullDef->hideTags; + } + + if (attachment->locationDamageMultipliers) { + assert(sizeof(WeaponAttachmentUniqueFull::locationDamageMultipliers) >= sizeof(float) * HITLOC_NUM); + memcpy(fullDef->locationDamageMultipliers, attachment->locationDamageMultipliers, sizeof(float) * HITLOC_NUM); + fullDef->attachment.locationDamageMultipliers = fullDef->locationDamageMultipliers; + } } -InfoString AssetDumperWeaponAttachmentUnique::CreateInfoString(XAssetInfo<WeaponAttachmentUnique>* asset) -{ - const auto fullDef = std::make_unique<WeaponAttachmentUniqueFull>(); - memset(fullDef.get(), 0, sizeof(WeaponAttachmentUniqueFull)); - CopyToFullDef(asset->Asset(), fullDef.get()); - - InfoStringFromWeaponAttachmentUniqueConverter converter( - fullDef.get(), attachment_unique_fields, std::extent<decltype(attachment_unique_fields)>::value, - [asset](const scr_string_t scrStr) -> std::string - { - assert(scrStr < asset->m_zone->m_script_strings.Count()); - if (scrStr >= asset->m_zone->m_script_strings.Count()) - return ""; +InfoString AssetDumperWeaponAttachmentUnique::CreateInfoString(XAssetInfo<WeaponAttachmentUnique> *asset) { + const auto fullDef = std::make_unique<WeaponAttachmentUniqueFull>(); + memset(fullDef.get(), 0, sizeof(WeaponAttachmentUniqueFull)); + CopyToFullDef(asset->Asset(), fullDef.get()); - return asset->m_zone->m_script_strings[scrStr]; - }); + InfoStringFromWeaponAttachmentUniqueConverter converter(fullDef.get(), attachment_unique_fields, std::extent<decltype(attachment_unique_fields)>::value, + [asset](const scr_string_t scrStr) -> std::string { + assert(scrStr < asset->m_zone->m_script_strings.Count()); + if (scrStr >= asset->m_zone->m_script_strings.Count()) + return ""; - return converter.Convert(); -} + return asset->m_zone->m_script_strings[scrStr]; + }); -bool AssetDumperWeaponAttachmentUnique::ShouldDump(XAssetInfo<WeaponAttachmentUnique>* asset) -{ - return true; + return converter.Convert(); } -void AssetDumperWeaponAttachmentUnique::DumpAsset(AssetDumpingContext& context, XAssetInfo<WeaponAttachmentUnique>* asset) -{ - // Only dump raw when no gdt available - if (context.m_gdt) - { - const auto infoString = CreateInfoString(asset); - GdtEntry gdtEntry(asset->m_name, ObjConstants::GDF_FILENAME_WEAPON_ATTACHMENT_UNIQUE); - infoString.ToGdtProperties(ObjConstants::INFO_STRING_PREFIX_WEAPON_ATTACHMENT_UNIQUE, gdtEntry); - context.m_gdt->WriteEntry(gdtEntry); - } - else - { - const auto assetFile = context.OpenAssetFile("attachmentunique/" + asset->m_name); - - if (!assetFile) - return; - - auto& stream = *assetFile; - const auto infoString = CreateInfoString(asset); - const auto stringValue = infoString.ToString(ObjConstants::INFO_STRING_PREFIX_WEAPON_ATTACHMENT_UNIQUE); - stream.write(stringValue.c_str(), stringValue.size()); - } +bool AssetDumperWeaponAttachmentUnique::ShouldDump(XAssetInfo<WeaponAttachmentUnique> *asset) { return true; } + +void AssetDumperWeaponAttachmentUnique::DumpAsset(AssetDumpingContext &context, XAssetInfo<WeaponAttachmentUnique> *asset) { + // Only dump raw when no gdt available + if (context.m_gdt) { + const auto infoString = CreateInfoString(asset); + GdtEntry gdtEntry(asset->m_name, ObjConstants::GDF_FILENAME_WEAPON_ATTACHMENT_UNIQUE); + infoString.ToGdtProperties(ObjConstants::INFO_STRING_PREFIX_WEAPON_ATTACHMENT_UNIQUE, gdtEntry); + context.m_gdt->WriteEntry(gdtEntry); + } else { + const auto assetFile = context.OpenAssetFile("attachmentunique/" + asset->m_name); + + if (!assetFile) + return; + + auto &stream = *assetFile; + const auto infoString = CreateInfoString(asset); + const auto stringValue = infoString.ToString(ObjConstants::INFO_STRING_PREFIX_WEAPON_ATTACHMENT_UNIQUE); + stream.write(stringValue.c_str(), stringValue.size()); + } } diff --git a/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperWeaponAttachmentUnique.h b/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperWeaponAttachmentUnique.h index 39d4f7d96..154bc03de 100644 --- a/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperWeaponAttachmentUnique.h +++ b/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperWeaponAttachmentUnique.h @@ -4,15 +4,13 @@ #include "Game/T6/T6.h" #include "InfoString/InfoString.h" -namespace T6 -{ - class AssetDumperWeaponAttachmentUnique final : public AbstractAssetDumper<WeaponAttachmentUnique> - { - static void CopyToFullDef(const WeaponAttachmentUnique* attachment, WeaponAttachmentUniqueFull* fullDef); - static InfoString CreateInfoString(XAssetInfo<WeaponAttachmentUnique>* asset); +namespace T6 { +class AssetDumperWeaponAttachmentUnique final : public AbstractAssetDumper<WeaponAttachmentUnique> { + static void CopyToFullDef(const WeaponAttachmentUnique *attachment, WeaponAttachmentUniqueFull *fullDef); + static InfoString CreateInfoString(XAssetInfo<WeaponAttachmentUnique> *asset); - protected: - bool ShouldDump(XAssetInfo<WeaponAttachmentUnique>* asset) override; - void DumpAsset(AssetDumpingContext& context, XAssetInfo<WeaponAttachmentUnique>* asset) override; - }; -} +protected: + bool ShouldDump(XAssetInfo<WeaponAttachmentUnique> *asset) override; + void DumpAsset(AssetDumpingContext &context, XAssetInfo<WeaponAttachmentUnique> *asset) override; +}; +} // namespace T6 diff --git a/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperXModel.cpp b/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperXModel.cpp index 8281ac593..ad973313b 100644 --- a/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperXModel.cpp +++ b/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperXModel.cpp @@ -3,664 +3,549 @@ #include <cassert> #include <sstream> -#include "ObjWriting.h" #include "Game/T6/CommonT6.h" #include "Math/Quaternion.h" #include "Model/XModel/XModelExportWriter.h" +#include "ObjWriting.h" #include "Utils/HalfFloat.h" #include "Utils/QuatInt16.h" using namespace T6; -bool AssetDumperXModel::ShouldDump(XAssetInfo<XModel>* asset) -{ - return !asset->m_name.empty() && asset->m_name[0] != ','; -} +bool AssetDumperXModel::ShouldDump(XAssetInfo<XModel> *asset) { return !asset->m_name.empty() && asset->m_name[0] != ','; } -GfxImage* AssetDumperXModel::GetMaterialColorMap(const Material* material) -{ - std::vector<MaterialTextureDef*> potentialTextureDefs; +GfxImage *AssetDumperXModel::GetMaterialColorMap(const Material *material) { + std::vector<MaterialTextureDef *> potentialTextureDefs; - for(auto textureIndex = 0u; textureIndex < material->textureCount; textureIndex++) - { - MaterialTextureDef* def = &material->textureTable[textureIndex]; + for (auto textureIndex = 0u; textureIndex < material->textureCount; textureIndex++) { + MaterialTextureDef *def = &material->textureTable[textureIndex]; - if (def->semantic == TS_COLOR_MAP || def->semantic >= TS_COLOR0_MAP && def->semantic <= TS_COLOR15_MAP) - potentialTextureDefs.push_back(def); - } + if (def->semantic == TS_COLOR_MAP || def->semantic >= TS_COLOR0_MAP && def->semantic <= TS_COLOR15_MAP) + potentialTextureDefs.push_back(def); + } - if (potentialTextureDefs.empty()) - return nullptr; - if (potentialTextureDefs.size() == 1) - return potentialTextureDefs[0]->image; + if (potentialTextureDefs.empty()) + return nullptr; + if (potentialTextureDefs.size() == 1) + return potentialTextureDefs[0]->image; - for(const auto* def : potentialTextureDefs) - { - if (tolower(def->nameStart) == 'c' && tolower(def->nameEnd) == 'p') - return def->image; - } + for (const auto *def : potentialTextureDefs) { + if (tolower(def->nameStart) == 'c' && tolower(def->nameEnd) == 'p') + return def->image; + } - for(const auto* def : potentialTextureDefs) - { - if (tolower(def->nameStart) == 'r' && tolower(def->nameEnd) == 'k') - return def->image; - } + for (const auto *def : potentialTextureDefs) { + if (tolower(def->nameStart) == 'r' && tolower(def->nameEnd) == 'k') + return def->image; + } - for(const auto* def : potentialTextureDefs) - { - if (tolower(def->nameStart) == 'd' && tolower(def->nameEnd) == 'p') - return def->image; - } + for (const auto *def : potentialTextureDefs) { + if (tolower(def->nameStart) == 'd' && tolower(def->nameEnd) == 'p') + return def->image; + } - return potentialTextureDefs[0]->image; + return potentialTextureDefs[0]->image; } -GfxImage* AssetDumperXModel::GetMaterialNormalMap(const Material* material) -{ - std::vector<MaterialTextureDef*> potentialTextureDefs; +GfxImage *AssetDumperXModel::GetMaterialNormalMap(const Material *material) { + std::vector<MaterialTextureDef *> potentialTextureDefs; - for (auto textureIndex = 0u; textureIndex < material->textureCount; textureIndex++) - { - MaterialTextureDef* def = &material->textureTable[textureIndex]; + for (auto textureIndex = 0u; textureIndex < material->textureCount; textureIndex++) { + MaterialTextureDef *def = &material->textureTable[textureIndex]; - if (def->semantic == TS_NORMAL_MAP) - potentialTextureDefs.push_back(def); - } + if (def->semantic == TS_NORMAL_MAP) + potentialTextureDefs.push_back(def); + } - if (potentialTextureDefs.empty()) - return nullptr; - if (potentialTextureDefs.size() == 1) - return potentialTextureDefs[0]->image; + if (potentialTextureDefs.empty()) + return nullptr; + if (potentialTextureDefs.size() == 1) + return potentialTextureDefs[0]->image; - for (const auto* def : potentialTextureDefs) - { - if (def->nameStart == 'n' && def->nameEnd == 'p') - return def->image; - } + for (const auto *def : potentialTextureDefs) { + if (def->nameStart == 'n' && def->nameEnd == 'p') + return def->image; + } - return potentialTextureDefs[0]->image; + return potentialTextureDefs[0]->image; } -GfxImage* AssetDumperXModel::GetMaterialSpecularMap(const Material* material) -{ - std::vector<MaterialTextureDef*> potentialTextureDefs; +GfxImage *AssetDumperXModel::GetMaterialSpecularMap(const Material *material) { + std::vector<MaterialTextureDef *> potentialTextureDefs; - for (auto textureIndex = 0u; textureIndex < material->textureCount; textureIndex++) - { - MaterialTextureDef* def = &material->textureTable[textureIndex]; + for (auto textureIndex = 0u; textureIndex < material->textureCount; textureIndex++) { + MaterialTextureDef *def = &material->textureTable[textureIndex]; - if (def->semantic == TS_SPECULAR_MAP) - potentialTextureDefs.push_back(def); - } + if (def->semantic == TS_SPECULAR_MAP) + potentialTextureDefs.push_back(def); + } - if (potentialTextureDefs.empty()) - return nullptr; - if (potentialTextureDefs.size() == 1) - return potentialTextureDefs[0]->image; + if (potentialTextureDefs.empty()) + return nullptr; + if (potentialTextureDefs.size() == 1) + return potentialTextureDefs[0]->image; - for (const auto* def : potentialTextureDefs) - { - if (def->nameStart == 's' && def->nameEnd == 'p') - return def->image; - } + for (const auto *def : potentialTextureDefs) { + if (def->nameStart == 's' && def->nameEnd == 'p') + return def->image; + } - return potentialTextureDefs[0]->image; + return potentialTextureDefs[0]->image; } -void AssetDumperXModel::AddObjMaterials(ObjWriter& writer, DistinctMapper<Material*>& materialMapper, const XModel* model) -{ - if (!model->materialHandles) - return; +void AssetDumperXModel::AddObjMaterials(ObjWriter &writer, DistinctMapper<Material *> &materialMapper, const XModel *model) { + if (!model->materialHandles) + return; - for (auto surfIndex = 0u; surfIndex < model->numsurfs; surfIndex++) - { - Material* material = model->materialHandles[surfIndex]; - if (!materialMapper.Add(material)) - continue; + for (auto surfIndex = 0u; surfIndex < model->numsurfs; surfIndex++) { + Material *material = model->materialHandles[surfIndex]; + if (!materialMapper.Add(material)) + continue; - MtlMaterial mtl; - mtl.materialName = std::string(material->info.name); + MtlMaterial mtl; + mtl.materialName = std::string(material->info.name); - GfxImage* colorMap = GetMaterialColorMap(material); - GfxImage* normalMap = GetMaterialNormalMap(material); - GfxImage* specularMap = GetMaterialSpecularMap(material); + GfxImage *colorMap = GetMaterialColorMap(material); + GfxImage *normalMap = GetMaterialNormalMap(material); + GfxImage *specularMap = GetMaterialSpecularMap(material); - if (colorMap != nullptr) - mtl.colorMapName = colorMap->name; - if (normalMap != nullptr) - mtl.normalMapName = normalMap->name; - if (specularMap != nullptr) - mtl.specularMapName = specularMap->name; + if (colorMap != nullptr) + mtl.colorMapName = colorMap->name; + if (normalMap != nullptr) + mtl.normalMapName = normalMap->name; + if (specularMap != nullptr) + mtl.specularMapName = specularMap->name; - writer.AddMaterial(std::move(mtl)); - } + writer.AddMaterial(std::move(mtl)); + } } -void AssetDumperXModel::AddObjObjects(ObjWriter& writer, const DistinctMapper<Material*>& materialMapper, const XModel* model, const unsigned lod) -{ - const auto surfCount = model->lodInfo[lod].numsurfs; - const auto baseSurfIndex = model->lodInfo[lod].surfIndex; +void AssetDumperXModel::AddObjObjects(ObjWriter &writer, const DistinctMapper<Material *> &materialMapper, const XModel *model, const unsigned lod) { + const auto surfCount = model->lodInfo[lod].numsurfs; + const auto baseSurfIndex = model->lodInfo[lod].surfIndex; - for (auto surfIndex = 0u; surfIndex < surfCount; surfIndex++) - { - ObjObject object; - object.name = "surf" + std::to_string(surfIndex); - object.materialIndex = static_cast<int>(materialMapper.GetDistinctPositionByInputPosition(surfIndex + baseSurfIndex)); + for (auto surfIndex = 0u; surfIndex < surfCount; surfIndex++) { + ObjObject object; + object.name = "surf" + std::to_string(surfIndex); + object.materialIndex = static_cast<int>(materialMapper.GetDistinctPositionByInputPosition(surfIndex + baseSurfIndex)); - writer.AddObject(std::move(object)); - } + writer.AddObject(std::move(object)); + } } -void AssetDumperXModel::AddObjVertices(ObjWriter& writer, const XModel* model, const unsigned lod) -{ - const auto* surfs = &model->surfs[model->lodInfo[lod].surfIndex]; - const auto surfCount = model->lodInfo[lod].numsurfs; - - for (auto surfIndex = 0u; surfIndex < surfCount; surfIndex++) - { - const auto& surface = surfs[surfIndex]; - - for (auto vertexIndex = 0u; vertexIndex < surface.vertCount; vertexIndex++) - { - const auto& v = surface.verts0[vertexIndex]; - vec2_t uv{}; - vec3_t normalVec{}; - - Common::Vec2UnpackTexCoords(v.texCoord, &uv); - Common::Vec3UnpackUnitVec(v.normal, &normalVec); - - ObjVertex objVertex{}; - ObjNormal objNormal{}; - ObjUv objUv{}; - objVertex.coordinates[0] = v.xyz.x; - objVertex.coordinates[1] = v.xyz.z; - objVertex.coordinates[2] = -v.xyz.y; - objNormal.normal[0] = normalVec.x; - objNormal.normal[1] = normalVec.z; - objNormal.normal[2] = -normalVec.y; - objUv.uv[0] = uv.x; - objUv.uv[1] = 1.0f - uv.y; - - writer.AddVertex(static_cast<int>(surfIndex), objVertex); - writer.AddNormal(static_cast<int>(surfIndex), objNormal); - writer.AddUv(static_cast<int>(surfIndex), objUv); - } +void AssetDumperXModel::AddObjVertices(ObjWriter &writer, const XModel *model, const unsigned lod) { + const auto *surfs = &model->surfs[model->lodInfo[lod].surfIndex]; + const auto surfCount = model->lodInfo[lod].numsurfs; + + for (auto surfIndex = 0u; surfIndex < surfCount; surfIndex++) { + const auto &surface = surfs[surfIndex]; + + for (auto vertexIndex = 0u; vertexIndex < surface.vertCount; vertexIndex++) { + const auto &v = surface.verts0[vertexIndex]; + vec2_t uv{}; + vec3_t normalVec{}; + + Common::Vec2UnpackTexCoords(v.texCoord, &uv); + Common::Vec3UnpackUnitVec(v.normal, &normalVec); + + ObjVertex objVertex{}; + ObjNormal objNormal{}; + ObjUv objUv{}; + objVertex.coordinates[0] = v.xyz.x; + objVertex.coordinates[1] = v.xyz.z; + objVertex.coordinates[2] = -v.xyz.y; + objNormal.normal[0] = normalVec.x; + objNormal.normal[1] = normalVec.z; + objNormal.normal[2] = -normalVec.y; + objUv.uv[0] = uv.x; + objUv.uv[1] = 1.0f - uv.y; + + writer.AddVertex(static_cast<int>(surfIndex), objVertex); + writer.AddNormal(static_cast<int>(surfIndex), objNormal); + writer.AddUv(static_cast<int>(surfIndex), objUv); } + } } -void AssetDumperXModel::AddObjFaces(ObjWriter& writer, const XModel* model, const unsigned lod) -{ - const auto* surfs = &model->surfs[model->lodInfo[lod].surfIndex]; - const auto surfCount = model->lodInfo[lod].numsurfs; - - for (auto surfIndex = 0u; surfIndex < surfCount; surfIndex++) - { - const auto& surface = surfs[surfIndex]; - for (auto triIndex = 0u; triIndex < surface.triCount; triIndex++) - { - const auto& tri = surface.triIndices[triIndex]; - - ObjFace face{}; - face.vertexIndex[0] = tri[2] + surface.baseVertIndex; - face.vertexIndex[1] = tri[1] + surface.baseVertIndex; - face.vertexIndex[2] = tri[0] + surface.baseVertIndex; - face.normalIndex[0] = face.vertexIndex[0]; - face.normalIndex[1] = face.vertexIndex[1]; - face.normalIndex[2] = face.vertexIndex[2]; - face.uvIndex[0] = face.vertexIndex[0]; - face.uvIndex[1] = face.vertexIndex[1]; - face.uvIndex[2] = face.vertexIndex[2]; - writer.AddFace(static_cast<int>(surfIndex), face); - } +void AssetDumperXModel::AddObjFaces(ObjWriter &writer, const XModel *model, const unsigned lod) { + const auto *surfs = &model->surfs[model->lodInfo[lod].surfIndex]; + const auto surfCount = model->lodInfo[lod].numsurfs; + + for (auto surfIndex = 0u; surfIndex < surfCount; surfIndex++) { + const auto &surface = surfs[surfIndex]; + for (auto triIndex = 0u; triIndex < surface.triCount; triIndex++) { + const auto &tri = surface.triIndices[triIndex]; + + ObjFace face{}; + face.vertexIndex[0] = tri[2] + surface.baseVertIndex; + face.vertexIndex[1] = tri[1] + surface.baseVertIndex; + face.vertexIndex[2] = tri[0] + surface.baseVertIndex; + face.normalIndex[0] = face.vertexIndex[0]; + face.normalIndex[1] = face.vertexIndex[1]; + face.normalIndex[2] = face.vertexIndex[2]; + face.uvIndex[0] = face.vertexIndex[0]; + face.uvIndex[1] = face.vertexIndex[1]; + face.uvIndex[2] = face.vertexIndex[2]; + writer.AddFace(static_cast<int>(surfIndex), face); } + } } -void AssetDumperXModel::DumpObjMat(const AssetDumpingContext& context, XAssetInfo<XModel>* asset) -{ - const auto* model = asset->Asset(); - const auto matFile = context.OpenAssetFile("model_export/" + std::string(model->name) + ".mtl"); +void AssetDumperXModel::DumpObjMat(const AssetDumpingContext &context, XAssetInfo<XModel> *asset) { + const auto *model = asset->Asset(); + const auto matFile = context.OpenAssetFile("model_export/" + std::string(model->name) + ".mtl"); - if (!matFile) - return; + if (!matFile) + return; - ObjWriter writer(context.m_zone->m_game->GetShortName(), context.m_zone->m_name); - DistinctMapper<Material*> materialMapper(model->numsurfs); + ObjWriter writer(context.m_zone->m_game->GetShortName(), context.m_zone->m_name); + DistinctMapper<Material *> materialMapper(model->numsurfs); - AddObjMaterials(writer, materialMapper, model); - writer.WriteMtl(*matFile); + AddObjMaterials(writer, materialMapper, model); + writer.WriteMtl(*matFile); } -void AssetDumperXModel::DumpObjLod(AssetDumpingContext& context, XAssetInfo<XModel>* asset, const unsigned lod) -{ - const auto* model = asset->Asset(); - std::ostringstream ss; - ss << "model_export/" << model->name << "_lod" << lod << ".OBJ"; +void AssetDumperXModel::DumpObjLod(AssetDumpingContext &context, XAssetInfo<XModel> *asset, const unsigned lod) { + const auto *model = asset->Asset(); + std::ostringstream ss; + ss << "model_export/" << model->name << "_lod" << lod << ".OBJ"; - const auto assetFile = context.OpenAssetFile(ss.str()); + const auto assetFile = context.OpenAssetFile(ss.str()); - if (!assetFile) - return; + if (!assetFile) + return; - ObjWriter writer(context.m_zone->m_game->GetShortName(), context.m_zone->m_name); - DistinctMapper<Material*> materialMapper(model->numsurfs); + ObjWriter writer(context.m_zone->m_game->GetShortName(), context.m_zone->m_name); + DistinctMapper<Material *> materialMapper(model->numsurfs); - AddObjMaterials(writer, materialMapper, model); - AddObjObjects(writer, materialMapper, model, lod); - AddObjVertices(writer, model, lod); - AddObjFaces(writer, model, lod); + AddObjMaterials(writer, materialMapper, model); + AddObjObjects(writer, materialMapper, model, lod); + AddObjVertices(writer, model, lod); + AddObjFaces(writer, model, lod); - writer.WriteObj(*assetFile, std::string(model->name) + ".mtl"); + writer.WriteObj(*assetFile, std::string(model->name) + ".mtl"); } -void AssetDumperXModel::DumpObj(AssetDumpingContext& context, XAssetInfo<XModel>* asset) -{ - const auto* model = asset->Asset(); +void AssetDumperXModel::DumpObj(AssetDumpingContext &context, XAssetInfo<XModel> *asset) { + const auto *model = asset->Asset(); - DumpObjMat(context, asset); - for (auto currentLod = 0u; currentLod < model->numLods; currentLod++) - { - DumpObjLod(context, asset, currentLod); - } + DumpObjMat(context, asset); + for (auto currentLod = 0u; currentLod < model->numLods; currentLod++) { + DumpObjLod(context, asset, currentLod); + } } -void AssetDumperXModel::AddXModelBones(const AssetDumpingContext& context, AbstractXModelWriter& writer, const XModel* model) -{ - for (auto boneNum = 0u; boneNum < model->numBones; boneNum++) - { - XModelBone bone; - if (model->boneNames[boneNum] < context.m_zone->m_script_strings.Count()) - bone.name = context.m_zone->m_script_strings[model->boneNames[boneNum]]; - else - bone.name = "INVALID_BONE_NAME"; - - if (boneNum < model->numRootBones) - bone.parentIndex = -1; - else - bone.parentIndex = static_cast<int>(boneNum - static_cast<unsigned int>(model->parentList[boneNum - model->numRootBones])); - - bone.scale[0] = 1.0f; - bone.scale[1] = 1.0f; - bone.scale[2] = 1.0f; - - bone.globalOffset[0] = model->baseMat[boneNum].trans.x; - bone.globalOffset[1] = model->baseMat[boneNum].trans.y; - bone.globalOffset[2] = model->baseMat[boneNum].trans.z; - bone.globalRotation = Quaternion32(model->baseMat[boneNum].quat.x, model->baseMat[boneNum].quat.y, model->baseMat[boneNum].quat.z, model->baseMat[boneNum].quat.w); - - if (boneNum < model->numRootBones) - { - bone.localOffset[0] = 0; - bone.localOffset[1] = 0; - bone.localOffset[2] = 0; - bone.localRotation = Quaternion32(0, 0, 0, 1); - } - else - { - bone.localOffset[0] = model->trans[boneNum - model->numRootBones][0]; - bone.localOffset[1] = model->trans[boneNum - model->numRootBones][1]; - bone.localOffset[2] = model->trans[boneNum - model->numRootBones][2]; - bone.localRotation = Quaternion32( - QuatInt16::ToFloat(model->quats[boneNum - model->numRootBones][0]), - QuatInt16::ToFloat(model->quats[boneNum - model->numRootBones][1]), - QuatInt16::ToFloat(model->quats[boneNum - model->numRootBones][2]), - QuatInt16::ToFloat(model->quats[boneNum - model->numRootBones][3]) - ); - } - - writer.AddBone(std::move(bone)); +void AssetDumperXModel::AddXModelBones(const AssetDumpingContext &context, AbstractXModelWriter &writer, const XModel *model) { + for (auto boneNum = 0u; boneNum < model->numBones; boneNum++) { + XModelBone bone; + if (model->boneNames[boneNum] < context.m_zone->m_script_strings.Count()) + bone.name = context.m_zone->m_script_strings[model->boneNames[boneNum]]; + else + bone.name = "INVALID_BONE_NAME"; + + if (boneNum < model->numRootBones) + bone.parentIndex = -1; + else + bone.parentIndex = static_cast<int>(boneNum - static_cast<unsigned int>(model->parentList[boneNum - model->numRootBones])); + + bone.scale[0] = 1.0f; + bone.scale[1] = 1.0f; + bone.scale[2] = 1.0f; + + bone.globalOffset[0] = model->baseMat[boneNum].trans.x; + bone.globalOffset[1] = model->baseMat[boneNum].trans.y; + bone.globalOffset[2] = model->baseMat[boneNum].trans.z; + bone.globalRotation = + Quaternion32(model->baseMat[boneNum].quat.x, model->baseMat[boneNum].quat.y, model->baseMat[boneNum].quat.z, model->baseMat[boneNum].quat.w); + + if (boneNum < model->numRootBones) { + bone.localOffset[0] = 0; + bone.localOffset[1] = 0; + bone.localOffset[2] = 0; + bone.localRotation = Quaternion32(0, 0, 0, 1); + } else { + bone.localOffset[0] = model->trans[boneNum - model->numRootBones][0]; + bone.localOffset[1] = model->trans[boneNum - model->numRootBones][1]; + bone.localOffset[2] = model->trans[boneNum - model->numRootBones][2]; + bone.localRotation = + Quaternion32(QuatInt16::ToFloat(model->quats[boneNum - model->numRootBones][0]), QuatInt16::ToFloat(model->quats[boneNum - model->numRootBones][1]), + QuatInt16::ToFloat(model->quats[boneNum - model->numRootBones][2]), QuatInt16::ToFloat(model->quats[boneNum - model->numRootBones][3])); } + + writer.AddBone(std::move(bone)); + } } -void AssetDumperXModel::AddXModelMaterials(AbstractXModelWriter& writer, DistinctMapper<Material*>& materialMapper, const XModel* model) -{ - for (auto surfaceMaterialNum = 0; surfaceMaterialNum < model->numsurfs; surfaceMaterialNum++) - { - Material* material = model->materialHandles[surfaceMaterialNum]; - if (materialMapper.Add(material)) - { - XModelMaterial xMaterial; - xMaterial.ApplyDefaults(); - - xMaterial.name = material->info.name; - const auto* colorMap = GetMaterialColorMap(material); - if (colorMap) - xMaterial.colorMapName = std::string(colorMap->name); - - writer.AddMaterial(std::move(xMaterial)); - } +void AssetDumperXModel::AddXModelMaterials(AbstractXModelWriter &writer, DistinctMapper<Material *> &materialMapper, const XModel *model) { + for (auto surfaceMaterialNum = 0; surfaceMaterialNum < model->numsurfs; surfaceMaterialNum++) { + Material *material = model->materialHandles[surfaceMaterialNum]; + if (materialMapper.Add(material)) { + XModelMaterial xMaterial; + xMaterial.ApplyDefaults(); + + xMaterial.name = material->info.name; + const auto *colorMap = GetMaterialColorMap(material); + if (colorMap) + xMaterial.colorMapName = std::string(colorMap->name); + + writer.AddMaterial(std::move(xMaterial)); } + } } -void AssetDumperXModel::AddXModelObjects(AbstractXModelWriter& writer, const XModel* model, const unsigned lod) -{ - const auto surfCount = model->lodInfo[lod].numsurfs; +void AssetDumperXModel::AddXModelObjects(AbstractXModelWriter &writer, const XModel *model, const unsigned lod) { + const auto surfCount = model->lodInfo[lod].numsurfs; - for (auto surfIndex = 0u; surfIndex < surfCount; surfIndex++) - { - XModelObject object; - object.name = "surf" + std::to_string(surfIndex); + for (auto surfIndex = 0u; surfIndex < surfCount; surfIndex++) { + XModelObject object; + object.name = "surf" + std::to_string(surfIndex); - writer.AddObject(std::move(object)); - } + writer.AddObject(std::move(object)); + } } -void AssetDumperXModel::AddXModelVertices(AbstractXModelWriter& writer, const XModel* model, const unsigned lod) -{ - const auto* surfs = &model->surfs[model->lodInfo[lod].surfIndex]; - const auto surfCount = model->lodInfo[lod].numsurfs; - - if (!surfs) - return; - - for (auto surfIndex = 0u; surfIndex < surfCount; surfIndex++) - { - const auto& surface = surfs[surfIndex]; - - for (auto vertexIndex = 0u; vertexIndex < surface.vertCount; vertexIndex++) - { - const auto& v = surface.verts0[vertexIndex]; - vec2_t uv{}; - vec3_t normalVec{}; - vec4_t color{}; - - Common::Vec2UnpackTexCoords(v.texCoord, &uv); - Common::Vec3UnpackUnitVec(v.normal, &normalVec); - Common::Vec4UnpackGfxColor(v.color, &color); - - XModelVertex vertex{}; - vertex.coordinates[0] = v.xyz.x; - vertex.coordinates[1] = v.xyz.y; - vertex.coordinates[2] = v.xyz.z; - vertex.normal[0] = normalVec.x; - vertex.normal[1] = normalVec.y; - vertex.normal[2] = normalVec.z; - vertex.color[0] = color.x; - vertex.color[1] = color.y; - vertex.color[2] = color.z; - vertex.color[3] = color.w; - vertex.uv[0] = uv.x; - vertex.uv[1] = uv.y; - - writer.AddVertex(vertex); - } +void AssetDumperXModel::AddXModelVertices(AbstractXModelWriter &writer, const XModel *model, const unsigned lod) { + const auto *surfs = &model->surfs[model->lodInfo[lod].surfIndex]; + const auto surfCount = model->lodInfo[lod].numsurfs; + + if (!surfs) + return; + + for (auto surfIndex = 0u; surfIndex < surfCount; surfIndex++) { + const auto &surface = surfs[surfIndex]; + + for (auto vertexIndex = 0u; vertexIndex < surface.vertCount; vertexIndex++) { + const auto &v = surface.verts0[vertexIndex]; + vec2_t uv{}; + vec3_t normalVec{}; + vec4_t color{}; + + Common::Vec2UnpackTexCoords(v.texCoord, &uv); + Common::Vec3UnpackUnitVec(v.normal, &normalVec); + Common::Vec4UnpackGfxColor(v.color, &color); + + XModelVertex vertex{}; + vertex.coordinates[0] = v.xyz.x; + vertex.coordinates[1] = v.xyz.y; + vertex.coordinates[2] = v.xyz.z; + vertex.normal[0] = normalVec.x; + vertex.normal[1] = normalVec.y; + vertex.normal[2] = normalVec.z; + vertex.color[0] = color.x; + vertex.color[1] = color.y; + vertex.color[2] = color.z; + vertex.color[3] = color.w; + vertex.uv[0] = uv.x; + vertex.uv[1] = uv.y; + + writer.AddVertex(vertex); } + } } -void AssetDumperXModel::AllocateXModelBoneWeights(const XModel* model, const unsigned lod, XModelVertexBoneWeightCollection& weightCollection) -{ - const auto* surfs = &model->surfs[model->lodInfo[lod].surfIndex]; - const auto surfCount = model->lodInfo[lod].numsurfs; +void AssetDumperXModel::AllocateXModelBoneWeights(const XModel *model, const unsigned lod, XModelVertexBoneWeightCollection &weightCollection) { + const auto *surfs = &model->surfs[model->lodInfo[lod].surfIndex]; + const auto surfCount = model->lodInfo[lod].numsurfs; - if (!surfs) - return; + if (!surfs) + return; - weightCollection.totalWeightCount = 0u; - for (auto surfIndex = 0u; surfIndex < surfCount; surfIndex++) - { - const auto& surface = surfs[surfIndex]; + weightCollection.totalWeightCount = 0u; + for (auto surfIndex = 0u; surfIndex < surfCount; surfIndex++) { + const auto &surface = surfs[surfIndex]; - if (surface.vertList) - { - weightCollection.totalWeightCount += surface.vertListCount; - } + if (surface.vertList) { + weightCollection.totalWeightCount += surface.vertListCount; + } - if (surface.vertInfo.vertsBlend) - { - weightCollection.totalWeightCount += surface.vertInfo.vertCount[0] * 1; - weightCollection.totalWeightCount += surface.vertInfo.vertCount[1] * 2; - weightCollection.totalWeightCount += surface.vertInfo.vertCount[2] * 3; - weightCollection.totalWeightCount += surface.vertInfo.vertCount[3] * 4; - } + if (surface.vertInfo.vertsBlend) { + weightCollection.totalWeightCount += surface.vertInfo.vertCount[0] * 1; + weightCollection.totalWeightCount += surface.vertInfo.vertCount[1] * 2; + weightCollection.totalWeightCount += surface.vertInfo.vertCount[2] * 3; + weightCollection.totalWeightCount += surface.vertInfo.vertCount[3] * 4; } + } - weightCollection.weights = std::make_unique<XModelBoneWeight[]>(weightCollection.totalWeightCount); + weightCollection.weights = std::make_unique<XModelBoneWeight[]>(weightCollection.totalWeightCount); } -void AssetDumperXModel::AddXModelVertexBoneWeights(AbstractXModelWriter& writer, const XModel* model, const unsigned lod, XModelVertexBoneWeightCollection& weightCollection) -{ - const auto* surfs = &model->surfs[model->lodInfo[lod].surfIndex]; - const auto surfCount = model->lodInfo[lod].numsurfs; - - if (!surfs) - return; - - size_t weightOffset = 0u; - - for (auto surfIndex = 0u; surfIndex < surfCount; surfIndex++) - { - const auto& surface = surfs[surfIndex]; - auto handledVertices = 0u; - - if (surface.vertList) - { - for (auto vertListIndex = 0u; vertListIndex < surface.vertListCount; vertListIndex++) - { - const auto& vertList = surface.vertList[vertListIndex]; - const auto* boneWeightOffset = &weightCollection.weights[weightOffset]; - - weightCollection.weights[weightOffset++] = XModelBoneWeight{ - static_cast<int>(vertList.boneOffset / sizeof(DObjSkelMat)), - 1.0f - }; - - for (auto vertListVertexOffset = 0u; vertListVertexOffset < vertList.vertCount; vertListVertexOffset++) - { - writer.AddVertexBoneWeights(XModelVertexBoneWeights{ - boneWeightOffset, - 1 - }); - } - handledVertices += vertList.vertCount; - } - } +void AssetDumperXModel::AddXModelVertexBoneWeights(AbstractXModelWriter &writer, const XModel *model, const unsigned lod, + XModelVertexBoneWeightCollection &weightCollection) { + const auto *surfs = &model->surfs[model->lodInfo[lod].surfIndex]; + const auto surfCount = model->lodInfo[lod].numsurfs; - auto vertsBlendOffset = 0u; - if (surface.vertInfo.vertsBlend) - { - // 1 bone weight - for (auto vertIndex = 0; vertIndex < surface.vertInfo.vertCount[0]; vertIndex++) - { - const auto* boneWeightOffset = &weightCollection.weights[weightOffset]; - const auto boneIndex0 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 0] / sizeof(DObjSkelMat)); - weightCollection.weights[weightOffset++] = XModelBoneWeight{ - boneIndex0, - 1.0f - }; - - vertsBlendOffset += 1; - - writer.AddVertexBoneWeights(XModelVertexBoneWeights{ - boneWeightOffset, - 1 - }); - } - - // 2 bone weights - for (auto vertIndex = 0; vertIndex < surface.vertInfo.vertCount[1]; vertIndex++) - { - const auto* boneWeightOffset = &weightCollection.weights[weightOffset]; - const auto boneIndex0 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 0] / sizeof(DObjSkelMat)); - const auto boneIndex1 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 1] / sizeof(DObjSkelMat)); - const auto boneWeight1 = HalfFloat::ToFloat(surface.vertInfo.vertsBlend[vertsBlendOffset + 2]); - const auto boneWeight0 = 1.0f - boneWeight1; - - weightCollection.weights[weightOffset++] = XModelBoneWeight{ - boneIndex0, - boneWeight0 - }; - weightCollection.weights[weightOffset++] = XModelBoneWeight{ - boneIndex1, - boneWeight1 - }; - - vertsBlendOffset += 3; - - writer.AddVertexBoneWeights(XModelVertexBoneWeights{ - boneWeightOffset, - 2 - }); - } - - // 3 bone weights - for (auto vertIndex = 0; vertIndex < surface.vertInfo.vertCount[2]; vertIndex++) - { - const auto* boneWeightOffset = &weightCollection.weights[weightOffset]; - const auto boneIndex0 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 0] / sizeof(DObjSkelMat)); - const auto boneIndex1 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 1] / sizeof(DObjSkelMat)); - const auto boneWeight1 = HalfFloat::ToFloat(surface.vertInfo.vertsBlend[vertsBlendOffset + 2]); - const auto boneIndex2 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 3] / sizeof(DObjSkelMat)); - const auto boneWeight2 = HalfFloat::ToFloat(surface.vertInfo.vertsBlend[vertsBlendOffset + 4]); - const auto boneWeight0 = 1.0f - boneWeight1 - boneWeight2; - - weightCollection.weights[weightOffset++] = XModelBoneWeight{ - boneIndex0, - boneWeight0 - }; - weightCollection.weights[weightOffset++] = XModelBoneWeight{ - boneIndex1, - boneWeight1 - }; - weightCollection.weights[weightOffset++] = XModelBoneWeight{ - boneIndex2, - boneWeight2 - }; - - vertsBlendOffset += 5; - - writer.AddVertexBoneWeights(XModelVertexBoneWeights{ - boneWeightOffset, - 3 - }); - } - - // 4 bone weights - for (auto vertIndex = 0; vertIndex < surface.vertInfo.vertCount[3]; vertIndex++) - { - const auto* boneWeightOffset = &weightCollection.weights[weightOffset]; - const auto boneIndex0 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 0] / sizeof(DObjSkelMat)); - const auto boneIndex1 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 1] / sizeof(DObjSkelMat)); - const auto boneWeight1 = HalfFloat::ToFloat(surface.vertInfo.vertsBlend[vertsBlendOffset + 2]); - const auto boneIndex2 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 3] / sizeof(DObjSkelMat)); - const auto boneWeight2 = HalfFloat::ToFloat(surface.vertInfo.vertsBlend[vertsBlendOffset + 4]); - const auto boneIndex3 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 5] / sizeof(DObjSkelMat)); - const auto boneWeight3 = HalfFloat::ToFloat(surface.vertInfo.vertsBlend[vertsBlendOffset + 6]); - const auto boneWeight0 = 1.0f - boneWeight1 - boneWeight2 - boneWeight3; - - weightCollection.weights[weightOffset++] = XModelBoneWeight{ - boneIndex0, - boneWeight0 - }; - weightCollection.weights[weightOffset++] = XModelBoneWeight{ - boneIndex1, - boneWeight1 - }; - weightCollection.weights[weightOffset++] = XModelBoneWeight{ - boneIndex2, - boneWeight2 - }; - weightCollection.weights[weightOffset++] = XModelBoneWeight{ - boneIndex3, - boneWeight3 - }; - - vertsBlendOffset += 7; - - writer.AddVertexBoneWeights(XModelVertexBoneWeights{ - boneWeightOffset, - 4 - }); - } - - handledVertices += surface.vertInfo.vertCount[0] + surface.vertInfo.vertCount[1] + surface.vertInfo.vertCount[2] + surface.vertInfo.vertCount[3]; - } + if (!surfs) + return; + + size_t weightOffset = 0u; - for (; handledVertices < surface.vertCount; handledVertices++) - { - writer.AddVertexBoneWeights(XModelVertexBoneWeights{ - nullptr, - 0 - }); + for (auto surfIndex = 0u; surfIndex < surfCount; surfIndex++) { + const auto &surface = surfs[surfIndex]; + auto handledVertices = 0u; + + if (surface.vertList) { + for (auto vertListIndex = 0u; vertListIndex < surface.vertListCount; vertListIndex++) { + const auto &vertList = surface.vertList[vertListIndex]; + const auto *boneWeightOffset = &weightCollection.weights[weightOffset]; + + weightCollection.weights[weightOffset++] = XModelBoneWeight{static_cast<int>(vertList.boneOffset / sizeof(DObjSkelMat)), 1.0f}; + + for (auto vertListVertexOffset = 0u; vertListVertexOffset < vertList.vertCount; vertListVertexOffset++) { + writer.AddVertexBoneWeights(XModelVertexBoneWeights{boneWeightOffset, 1}); } + handledVertices += vertList.vertCount; + } + } + + auto vertsBlendOffset = 0u; + if (surface.vertInfo.vertsBlend) { + // 1 bone weight + for (auto vertIndex = 0; vertIndex < surface.vertInfo.vertCount[0]; vertIndex++) { + const auto *boneWeightOffset = &weightCollection.weights[weightOffset]; + const auto boneIndex0 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 0] / sizeof(DObjSkelMat)); + weightCollection.weights[weightOffset++] = XModelBoneWeight{boneIndex0, 1.0f}; + + vertsBlendOffset += 1; + + writer.AddVertexBoneWeights(XModelVertexBoneWeights{boneWeightOffset, 1}); + } + + // 2 bone weights + for (auto vertIndex = 0; vertIndex < surface.vertInfo.vertCount[1]; vertIndex++) { + const auto *boneWeightOffset = &weightCollection.weights[weightOffset]; + const auto boneIndex0 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 0] / sizeof(DObjSkelMat)); + const auto boneIndex1 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 1] / sizeof(DObjSkelMat)); + const auto boneWeight1 = HalfFloat::ToFloat(surface.vertInfo.vertsBlend[vertsBlendOffset + 2]); + const auto boneWeight0 = 1.0f - boneWeight1; + + weightCollection.weights[weightOffset++] = XModelBoneWeight{boneIndex0, boneWeight0}; + weightCollection.weights[weightOffset++] = XModelBoneWeight{boneIndex1, boneWeight1}; + + vertsBlendOffset += 3; + + writer.AddVertexBoneWeights(XModelVertexBoneWeights{boneWeightOffset, 2}); + } + + // 3 bone weights + for (auto vertIndex = 0; vertIndex < surface.vertInfo.vertCount[2]; vertIndex++) { + const auto *boneWeightOffset = &weightCollection.weights[weightOffset]; + const auto boneIndex0 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 0] / sizeof(DObjSkelMat)); + const auto boneIndex1 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 1] / sizeof(DObjSkelMat)); + const auto boneWeight1 = HalfFloat::ToFloat(surface.vertInfo.vertsBlend[vertsBlendOffset + 2]); + const auto boneIndex2 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 3] / sizeof(DObjSkelMat)); + const auto boneWeight2 = HalfFloat::ToFloat(surface.vertInfo.vertsBlend[vertsBlendOffset + 4]); + const auto boneWeight0 = 1.0f - boneWeight1 - boneWeight2; + + weightCollection.weights[weightOffset++] = XModelBoneWeight{boneIndex0, boneWeight0}; + weightCollection.weights[weightOffset++] = XModelBoneWeight{boneIndex1, boneWeight1}; + weightCollection.weights[weightOffset++] = XModelBoneWeight{boneIndex2, boneWeight2}; + + vertsBlendOffset += 5; + + writer.AddVertexBoneWeights(XModelVertexBoneWeights{boneWeightOffset, 3}); + } + + // 4 bone weights + for (auto vertIndex = 0; vertIndex < surface.vertInfo.vertCount[3]; vertIndex++) { + const auto *boneWeightOffset = &weightCollection.weights[weightOffset]; + const auto boneIndex0 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 0] / sizeof(DObjSkelMat)); + const auto boneIndex1 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 1] / sizeof(DObjSkelMat)); + const auto boneWeight1 = HalfFloat::ToFloat(surface.vertInfo.vertsBlend[vertsBlendOffset + 2]); + const auto boneIndex2 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 3] / sizeof(DObjSkelMat)); + const auto boneWeight2 = HalfFloat::ToFloat(surface.vertInfo.vertsBlend[vertsBlendOffset + 4]); + const auto boneIndex3 = static_cast<int>(surface.vertInfo.vertsBlend[vertsBlendOffset + 5] / sizeof(DObjSkelMat)); + const auto boneWeight3 = HalfFloat::ToFloat(surface.vertInfo.vertsBlend[vertsBlendOffset + 6]); + const auto boneWeight0 = 1.0f - boneWeight1 - boneWeight2 - boneWeight3; + + weightCollection.weights[weightOffset++] = XModelBoneWeight{boneIndex0, boneWeight0}; + weightCollection.weights[weightOffset++] = XModelBoneWeight{boneIndex1, boneWeight1}; + weightCollection.weights[weightOffset++] = XModelBoneWeight{boneIndex2, boneWeight2}; + weightCollection.weights[weightOffset++] = XModelBoneWeight{boneIndex3, boneWeight3}; + + vertsBlendOffset += 7; + + writer.AddVertexBoneWeights(XModelVertexBoneWeights{boneWeightOffset, 4}); + } + + handledVertices += surface.vertInfo.vertCount[0] + surface.vertInfo.vertCount[1] + surface.vertInfo.vertCount[2] + surface.vertInfo.vertCount[3]; + } + + for (; handledVertices < surface.vertCount; handledVertices++) { + writer.AddVertexBoneWeights(XModelVertexBoneWeights{nullptr, 0}); } + } } -void AssetDumperXModel::AddXModelFaces(AbstractXModelWriter& writer, const DistinctMapper<Material*>& materialMapper, const XModel* model, const unsigned lod) -{ - const auto* surfs = &model->surfs[model->lodInfo[lod].surfIndex]; - const auto surfCount = model->lodInfo[lod].numsurfs; - const auto baseSurfIndex = model->lodInfo[lod].surfIndex; - - if (!surfs) - return; - - for (auto surfIndex = 0u; surfIndex < surfCount; surfIndex++) - { - const auto& surface = surfs[surfIndex]; - for (auto triIndex = 0u; triIndex < surface.triCount; triIndex++) - { - const auto& tri = surface.triIndices[triIndex]; - - XModelFace face{}; - face.vertexIndex[0] = tri[0] + surface.baseVertIndex; - face.vertexIndex[1] = tri[1] + surface.baseVertIndex; - face.vertexIndex[2] = tri[2] + surface.baseVertIndex; - face.objectIndex = static_cast<int>(surfIndex); - face.materialIndex = static_cast<int>(materialMapper.GetDistinctPositionByInputPosition(surfIndex + baseSurfIndex)); - writer.AddFace(face); - } +void AssetDumperXModel::AddXModelFaces(AbstractXModelWriter &writer, const DistinctMapper<Material *> &materialMapper, const XModel *model, + const unsigned lod) { + const auto *surfs = &model->surfs[model->lodInfo[lod].surfIndex]; + const auto surfCount = model->lodInfo[lod].numsurfs; + const auto baseSurfIndex = model->lodInfo[lod].surfIndex; + + if (!surfs) + return; + + for (auto surfIndex = 0u; surfIndex < surfCount; surfIndex++) { + const auto &surface = surfs[surfIndex]; + for (auto triIndex = 0u; triIndex < surface.triCount; triIndex++) { + const auto &tri = surface.triIndices[triIndex]; + + XModelFace face{}; + face.vertexIndex[0] = tri[0] + surface.baseVertIndex; + face.vertexIndex[1] = tri[1] + surface.baseVertIndex; + face.vertexIndex[2] = tri[2] + surface.baseVertIndex; + face.objectIndex = static_cast<int>(surfIndex); + face.materialIndex = static_cast<int>(materialMapper.GetDistinctPositionByInputPosition(surfIndex + baseSurfIndex)); + writer.AddFace(face); } + } } -void AssetDumperXModel::DumpXModelExportLod(const AssetDumpingContext& context, XAssetInfo<XModel>* asset, const unsigned lod) -{ - const auto* model = asset->Asset(); +void AssetDumperXModel::DumpXModelExportLod(const AssetDumpingContext &context, XAssetInfo<XModel> *asset, const unsigned lod) { + const auto *model = asset->Asset(); - std::ostringstream ss; - ss << "model_export/" << model->name << "_lod" << lod << ".XMODEL_EXPORT"; + std::ostringstream ss; + ss << "model_export/" << model->name << "_lod" << lod << ".XMODEL_EXPORT"; - const auto assetFile = context.OpenAssetFile(ss.str()); + const auto assetFile = context.OpenAssetFile(ss.str()); - if (!assetFile) - return; + if (!assetFile) + return; - const auto writer = XModelExportWriter::CreateWriterForVersion6(context.m_zone->m_game->GetShortName(), context.m_zone->m_name); - DistinctMapper<Material*> materialMapper(model->numsurfs); - XModelVertexBoneWeightCollection boneWeightCollection; - AllocateXModelBoneWeights(model, lod, boneWeightCollection); + const auto writer = XModelExportWriter::CreateWriterForVersion6(context.m_zone->m_game->GetShortName(), context.m_zone->m_name); + DistinctMapper<Material *> materialMapper(model->numsurfs); + XModelVertexBoneWeightCollection boneWeightCollection; + AllocateXModelBoneWeights(model, lod, boneWeightCollection); - AddXModelBones(context, *writer, model); - AddXModelMaterials(*writer, materialMapper, model); - AddXModelObjects(*writer, model, lod); - AddXModelVertices(*writer, model, lod); - AddXModelVertexBoneWeights(*writer, model, lod, boneWeightCollection); - AddXModelFaces(*writer, materialMapper, model, lod); + AddXModelBones(context, *writer, model); + AddXModelMaterials(*writer, materialMapper, model); + AddXModelObjects(*writer, model, lod); + AddXModelVertices(*writer, model, lod); + AddXModelVertexBoneWeights(*writer, model, lod, boneWeightCollection); + AddXModelFaces(*writer, materialMapper, model, lod); - writer->Write(*assetFile); + writer->Write(*assetFile); } -void AssetDumperXModel::DumpXModelExport(const AssetDumpingContext& context, XAssetInfo<XModel>* asset) -{ - const auto* model = asset->Asset(); - for (auto currentLod = 0u; currentLod < model->numLods; currentLod++) - { - DumpXModelExportLod(context, asset, currentLod); - } +void AssetDumperXModel::DumpXModelExport(const AssetDumpingContext &context, XAssetInfo<XModel> *asset) { + const auto *model = asset->Asset(); + for (auto currentLod = 0u; currentLod < model->numLods; currentLod++) { + DumpXModelExportLod(context, asset, currentLod); + } } -void AssetDumperXModel::DumpAsset(AssetDumpingContext& context, XAssetInfo<XModel>* asset) -{ - switch (ObjWriting::Configuration.ModelOutputFormat) - { - case ObjWriting::Configuration_t::ModelOutputFormat_e::OBJ: - DumpObj(context, asset); - break; - - case ObjWriting::Configuration_t::ModelOutputFormat_e::XMODEL_EXPORT: - DumpXModelExport(context, asset); - break; - - default: - assert(false); - break; - } +void AssetDumperXModel::DumpAsset(AssetDumpingContext &context, XAssetInfo<XModel> *asset) { + switch (ObjWriting::Configuration.ModelOutputFormat) { + case ObjWriting::Configuration_t::ModelOutputFormat_e::OBJ: + DumpObj(context, asset); + break; + + case ObjWriting::Configuration_t::ModelOutputFormat_e::XMODEL_EXPORT: + DumpXModelExport(context, asset); + break; + + default: + assert(false); + break; + } } diff --git a/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperXModel.h b/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperXModel.h index 1cb673790..0da78599f 100644 --- a/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperXModel.h +++ b/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperXModel.h @@ -2,38 +2,36 @@ #include "Dumping/AbstractAssetDumper.h" #include "Game/T6/T6.h" -#include "Utils/DistinctMapper.h" -#include "Model/XModel/AbstractXModelWriter.h" #include "Model/Obj/ObjWriter.h" +#include "Model/XModel/AbstractXModelWriter.h" +#include "Utils/DistinctMapper.h" -namespace T6 -{ - class AssetDumperXModel final : public AbstractAssetDumper<XModel> - { - static GfxImage* GetMaterialColorMap(const Material* material); - static GfxImage* GetMaterialNormalMap(const Material* material); - static GfxImage* GetMaterialSpecularMap(const Material* material); +namespace T6 { +class AssetDumperXModel final : public AbstractAssetDumper<XModel> { + static GfxImage *GetMaterialColorMap(const Material *material); + static GfxImage *GetMaterialNormalMap(const Material *material); + static GfxImage *GetMaterialSpecularMap(const Material *material); - static void AddObjMaterials(ObjWriter& writer, DistinctMapper<Material*>& materialMapper, const XModel* model); - static void AddObjObjects(ObjWriter& writer, const DistinctMapper<Material*>& materialMapper, const XModel* model, unsigned lod); - static void AddObjVertices(ObjWriter& writer, const XModel* model, unsigned lod); - static void AddObjFaces(ObjWriter& writer, const XModel* model, unsigned lod); - static void DumpObjLod(AssetDumpingContext& context, XAssetInfo<XModel>* asset, unsigned lod); - static void DumpObjMat(const AssetDumpingContext& context, XAssetInfo<XModel>* asset); - static void DumpObj(AssetDumpingContext& context, XAssetInfo<XModel>* asset); + static void AddObjMaterials(ObjWriter &writer, DistinctMapper<Material *> &materialMapper, const XModel *model); + static void AddObjObjects(ObjWriter &writer, const DistinctMapper<Material *> &materialMapper, const XModel *model, unsigned lod); + static void AddObjVertices(ObjWriter &writer, const XModel *model, unsigned lod); + static void AddObjFaces(ObjWriter &writer, const XModel *model, unsigned lod); + static void DumpObjLod(AssetDumpingContext &context, XAssetInfo<XModel> *asset, unsigned lod); + static void DumpObjMat(const AssetDumpingContext &context, XAssetInfo<XModel> *asset); + static void DumpObj(AssetDumpingContext &context, XAssetInfo<XModel> *asset); - static void AddXModelBones(const AssetDumpingContext& context, AbstractXModelWriter& writer, const XModel* model); - static void AddXModelMaterials(AbstractXModelWriter& writer, DistinctMapper<Material*>& materialMapper, const XModel* model); - static void AddXModelObjects(AbstractXModelWriter& writer, const XModel* model, unsigned lod); - static void AddXModelVertices(AbstractXModelWriter& writer, const XModel* model, unsigned lod); - static void AllocateXModelBoneWeights(const XModel* model, unsigned lod, XModelVertexBoneWeightCollection& weightCollection); - static void AddXModelVertexBoneWeights(AbstractXModelWriter& writer, const XModel* model, unsigned lod, XModelVertexBoneWeightCollection& weightCollection); - static void AddXModelFaces(AbstractXModelWriter& writer, const DistinctMapper<Material*>& materialMapper, const XModel* model, unsigned lod); - static void DumpXModelExportLod(const AssetDumpingContext& context, XAssetInfo<XModel>* asset, unsigned lod); - static void DumpXModelExport(const AssetDumpingContext& context, XAssetInfo<XModel>* asset); + static void AddXModelBones(const AssetDumpingContext &context, AbstractXModelWriter &writer, const XModel *model); + static void AddXModelMaterials(AbstractXModelWriter &writer, DistinctMapper<Material *> &materialMapper, const XModel *model); + static void AddXModelObjects(AbstractXModelWriter &writer, const XModel *model, unsigned lod); + static void AddXModelVertices(AbstractXModelWriter &writer, const XModel *model, unsigned lod); + static void AllocateXModelBoneWeights(const XModel *model, unsigned lod, XModelVertexBoneWeightCollection &weightCollection); + static void AddXModelVertexBoneWeights(AbstractXModelWriter &writer, const XModel *model, unsigned lod, XModelVertexBoneWeightCollection &weightCollection); + static void AddXModelFaces(AbstractXModelWriter &writer, const DistinctMapper<Material *> &materialMapper, const XModel *model, unsigned lod); + static void DumpXModelExportLod(const AssetDumpingContext &context, XAssetInfo<XModel> *asset, unsigned lod); + static void DumpXModelExport(const AssetDumpingContext &context, XAssetInfo<XModel> *asset); - protected: - bool ShouldDump(XAssetInfo<XModel>* asset) override; - void DumpAsset(AssetDumpingContext& context, XAssetInfo<XModel>* asset) override; - }; -} +protected: + bool ShouldDump(XAssetInfo<XModel> *asset) override; + void DumpAsset(AssetDumpingContext &context, XAssetInfo<XModel> *asset) override; +}; +} // namespace T6 diff --git a/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperZBarrier.cpp b/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperZBarrier.cpp index c9cb00fad..39714e340 100644 --- a/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperZBarrier.cpp +++ b/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperZBarrier.cpp @@ -3,69 +3,55 @@ #include <cassert> #include <type_traits> -#include "Game/T6/ObjConstantsT6.h" #include "Game/T6/InfoString/InfoStringFromStructConverter.h" #include "Game/T6/InfoString/ZBarrierFields.h" +#include "Game/T6/ObjConstantsT6.h" using namespace T6; -namespace T6 -{ - class InfoStringFromZBarrierConverter final : public InfoStringFromStructConverter - { - protected: - void FillFromExtensionField(const cspField_t& field) override - { - assert(false); - } - - public: - InfoStringFromZBarrierConverter(const ZBarrierDef* structure, const cspField_t* fields, const size_t fieldCount, std::function<std::string(scr_string_t)> scriptStringValueCallback) - : InfoStringFromStructConverter(structure, fields, fieldCount, std::move(scriptStringValueCallback)) - { - } - }; +namespace T6 { +class InfoStringFromZBarrierConverter final : public InfoStringFromStructConverter { +protected: + void FillFromExtensionField(const cspField_t &field) override { assert(false); } + +public: + InfoStringFromZBarrierConverter(const ZBarrierDef *structure, const cspField_t *fields, const size_t fieldCount, + std::function<std::string(scr_string_t)> scriptStringValueCallback) + : InfoStringFromStructConverter(structure, fields, fieldCount, std::move(scriptStringValueCallback)) {} +}; +} // namespace T6 + +InfoString AssetDumperZBarrier::CreateInfoString(XAssetInfo<ZBarrierDef> *asset) { + InfoStringFromZBarrierConverter converter(asset->Asset(), zbarrier_fields, std::extent<decltype(zbarrier_fields)>::value, + [asset](const scr_string_t scrStr) -> std::string { + assert(scrStr < asset->m_zone->m_script_strings.Count()); + if (scrStr >= asset->m_zone->m_script_strings.Count()) + return ""; + + return asset->m_zone->m_script_strings[scrStr]; + }); + + return converter.Convert(); } -InfoString AssetDumperZBarrier::CreateInfoString(XAssetInfo<ZBarrierDef>* asset) -{ - InfoStringFromZBarrierConverter converter(asset->Asset(), zbarrier_fields, std::extent<decltype(zbarrier_fields)>::value, [asset](const scr_string_t scrStr) -> std::string - { - assert(scrStr < asset->m_zone->m_script_strings.Count()); - if (scrStr >= asset->m_zone->m_script_strings.Count()) - return ""; - - return asset->m_zone->m_script_strings[scrStr]; - }); - - return converter.Convert(); -} - -bool AssetDumperZBarrier::ShouldDump(XAssetInfo<ZBarrierDef>* asset) -{ - return true; -} - -void AssetDumperZBarrier::DumpAsset(AssetDumpingContext& context, XAssetInfo<ZBarrierDef>* asset) -{ - // Only dump raw when no gdt available - if (context.m_gdt) - { - const auto infoString = CreateInfoString(asset); - GdtEntry gdtEntry(asset->m_name, ObjConstants::GDF_FILENAME_ZBARRIER); - infoString.ToGdtProperties(ObjConstants::INFO_STRING_PREFIX_ZBARRIER, gdtEntry); - context.m_gdt->WriteEntry(gdtEntry); - } - else - { - const auto assetFile = context.OpenAssetFile("zbarrier/" + asset->m_name); - - if (!assetFile) - return; - - auto& stream = *assetFile; - const auto infoString = CreateInfoString(asset); - const auto stringValue = infoString.ToString(ObjConstants::INFO_STRING_PREFIX_ZBARRIER); - stream.write(stringValue.c_str(), stringValue.size()); - } +bool AssetDumperZBarrier::ShouldDump(XAssetInfo<ZBarrierDef> *asset) { return true; } + +void AssetDumperZBarrier::DumpAsset(AssetDumpingContext &context, XAssetInfo<ZBarrierDef> *asset) { + // Only dump raw when no gdt available + if (context.m_gdt) { + const auto infoString = CreateInfoString(asset); + GdtEntry gdtEntry(asset->m_name, ObjConstants::GDF_FILENAME_ZBARRIER); + infoString.ToGdtProperties(ObjConstants::INFO_STRING_PREFIX_ZBARRIER, gdtEntry); + context.m_gdt->WriteEntry(gdtEntry); + } else { + const auto assetFile = context.OpenAssetFile("zbarrier/" + asset->m_name); + + if (!assetFile) + return; + + auto &stream = *assetFile; + const auto infoString = CreateInfoString(asset); + const auto stringValue = infoString.ToString(ObjConstants::INFO_STRING_PREFIX_ZBARRIER); + stream.write(stringValue.c_str(), stringValue.size()); + } } diff --git a/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperZBarrier.h b/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperZBarrier.h index 8dd46e545..e83945a0a 100644 --- a/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperZBarrier.h +++ b/src/ObjWriting/Game/T6/AssetDumpers/AssetDumperZBarrier.h @@ -4,14 +4,12 @@ #include "Game/T6/T6.h" #include "InfoString/InfoString.h" -namespace T6 -{ - class AssetDumperZBarrier final : public AbstractAssetDumper<ZBarrierDef> - { - static InfoString CreateInfoString(XAssetInfo<ZBarrierDef>* asset); +namespace T6 { +class AssetDumperZBarrier final : public AbstractAssetDumper<ZBarrierDef> { + static InfoString CreateInfoString(XAssetInfo<ZBarrierDef> *asset); - protected: - bool ShouldDump(XAssetInfo<ZBarrierDef>* asset) override; - void DumpAsset(AssetDumpingContext& context, XAssetInfo<ZBarrierDef>* asset) override; - }; -} +protected: + bool ShouldDump(XAssetInfo<ZBarrierDef> *asset) override; + void DumpAsset(AssetDumpingContext &context, XAssetInfo<ZBarrierDef> *asset) override; +}; +} // namespace T6 diff --git a/src/ObjWriting/Game/T6/InfoString/InfoStringFromStructConverter.cpp b/src/ObjWriting/Game/T6/InfoString/InfoStringFromStructConverter.cpp index afa762ff8..30406ac9e 100644 --- a/src/ObjWriting/Game/T6/InfoString/InfoStringFromStructConverter.cpp +++ b/src/ObjWriting/Game/T6/InfoString/InfoStringFromStructConverter.cpp @@ -5,155 +5,134 @@ using namespace T6; -void InfoStringFromStructConverter::FillFromBaseField(const cspField_t& field) -{ - switch (static_cast<csParseFieldType_t>(field.iFieldType)) - { - case CSPFT_STRING: - FillFromString(std::string(field.szName), field.iOffset); - break; - - case CSPFT_STRING_MAX_STRING_CHARS: - FillFromStringBuffer(std::string(field.szName), field.iOffset, 1024); - break; - - case CSPFT_STRING_MAX_QPATH: - FillFromStringBuffer(std::string(field.szName), field.iOffset, 64); - break; - - case CSPFT_STRING_MAX_OSPATH: - FillFromStringBuffer(std::string(field.szName), field.iOffset, 256); - break; - - case CSPFT_INT: - FillFromInt(std::string(field.szName), field.iOffset); - break; - - case CSPFT_UINT: - FillFromUint(std::string(field.szName), field.iOffset); - break; - - case CSPFT_BOOL: - FillFromBool(std::string(field.szName), field.iOffset); - break; - - case CSPFT_QBOOLEAN: - FillFromQBoolean(std::string(field.szName), field.iOffset); - break; - - case CSPFT_FLOAT: - FillFromFloat(std::string(field.szName), field.iOffset); - break; - - case CSPFT_MILLISECONDS: - FillFromMilliseconds(std::string(field.szName), field.iOffset); - break; - - case CSPFT_FX: - { - const auto* fx = *reinterpret_cast<FxEffectDef**>(reinterpret_cast<uintptr_t>(m_structure) + field.iOffset); - - if (fx) - m_info_string.SetValueForKey(std::string(field.szName), std::string(AssetName(fx->name))); - else - m_info_string.SetValueForKey(std::string(field.szName), ""); - break; - } - - case CSPFT_XMODEL: - { - const auto* model = *reinterpret_cast<XModel**>(reinterpret_cast<uintptr_t>(m_structure) + field.iOffset); - - if (model) - m_info_string.SetValueForKey(std::string(field.szName), std::string(AssetName(model->name))); - else - m_info_string.SetValueForKey(std::string(field.szName), ""); - break; - } - - case CSPFT_MATERIAL: - case CSPFT_MATERIAL_STREAM: - { - const auto* material = *reinterpret_cast<Material**>(reinterpret_cast<uintptr_t>(m_structure) + field. - iOffset); - - if (material) - m_info_string.SetValueForKey(std::string(field.szName), std::string(AssetName(material->info.name))); - else - m_info_string.SetValueForKey(std::string(field.szName), ""); - break; - } - - case CSPFT_PHYS_PRESET: - { - const auto* physPreset = *reinterpret_cast<PhysPreset**>(reinterpret_cast<uintptr_t>(m_structure) + field. - iOffset); - - if (physPreset) - m_info_string.SetValueForKey(std::string(field.szName), std::string(AssetName(physPreset->name))); - else - m_info_string.SetValueForKey(std::string(field.szName), ""); - break; - } - - case CSPFT_SCRIPT_STRING: - FillFromScriptString(std::string(field.szName), field.iOffset); - break; - - case CSPFT_TRACER: - { - const auto* tracer = *reinterpret_cast<TracerDef**>(reinterpret_cast<uintptr_t>(m_structure) + field.iOffset); - - if (tracer) - m_info_string.SetValueForKey(std::string(field.szName), std::string(AssetName(tracer->name))); - else - m_info_string.SetValueForKey(std::string(field.szName), ""); - break; - } - - case CSPFT_SOUND_ALIAS_ID: - { - // TODO: Search sound files for files matching the hash - const auto* hash = reinterpret_cast<unsigned*>(reinterpret_cast<uintptr_t>(m_structure) + field.iOffset); - std::ostringstream str; - str << '@' << std::hex << *hash; - m_info_string.SetValueForKey(std::string(field.szName), str.str()); - break; - } - - case CSPFT_NUM_BASE_FIELD_TYPES: - default: - assert(false); - break; - } +void InfoStringFromStructConverter::FillFromBaseField(const cspField_t &field) { + switch (static_cast<csParseFieldType_t>(field.iFieldType)) { + case CSPFT_STRING: + FillFromString(std::string(field.szName), field.iOffset); + break; + + case CSPFT_STRING_MAX_STRING_CHARS: + FillFromStringBuffer(std::string(field.szName), field.iOffset, 1024); + break; + + case CSPFT_STRING_MAX_QPATH: + FillFromStringBuffer(std::string(field.szName), field.iOffset, 64); + break; + + case CSPFT_STRING_MAX_OSPATH: + FillFromStringBuffer(std::string(field.szName), field.iOffset, 256); + break; + + case CSPFT_INT: + FillFromInt(std::string(field.szName), field.iOffset); + break; + + case CSPFT_UINT: + FillFromUint(std::string(field.szName), field.iOffset); + break; + + case CSPFT_BOOL: + FillFromBool(std::string(field.szName), field.iOffset); + break; + + case CSPFT_QBOOLEAN: + FillFromQBoolean(std::string(field.szName), field.iOffset); + break; + + case CSPFT_FLOAT: + FillFromFloat(std::string(field.szName), field.iOffset); + break; + + case CSPFT_MILLISECONDS: + FillFromMilliseconds(std::string(field.szName), field.iOffset); + break; + + case CSPFT_FX: { + const auto *fx = *reinterpret_cast<FxEffectDef **>(reinterpret_cast<uintptr_t>(m_structure) + field.iOffset); + + if (fx) + m_info_string.SetValueForKey(std::string(field.szName), std::string(AssetName(fx->name))); + else + m_info_string.SetValueForKey(std::string(field.szName), ""); + break; + } + + case CSPFT_XMODEL: { + const auto *model = *reinterpret_cast<XModel **>(reinterpret_cast<uintptr_t>(m_structure) + field.iOffset); + + if (model) + m_info_string.SetValueForKey(std::string(field.szName), std::string(AssetName(model->name))); + else + m_info_string.SetValueForKey(std::string(field.szName), ""); + break; + } + + case CSPFT_MATERIAL: + case CSPFT_MATERIAL_STREAM: { + const auto *material = *reinterpret_cast<Material **>(reinterpret_cast<uintptr_t>(m_structure) + field.iOffset); + + if (material) + m_info_string.SetValueForKey(std::string(field.szName), std::string(AssetName(material->info.name))); + else + m_info_string.SetValueForKey(std::string(field.szName), ""); + break; + } + + case CSPFT_PHYS_PRESET: { + const auto *physPreset = *reinterpret_cast<PhysPreset **>(reinterpret_cast<uintptr_t>(m_structure) + field.iOffset); + + if (physPreset) + m_info_string.SetValueForKey(std::string(field.szName), std::string(AssetName(physPreset->name))); + else + m_info_string.SetValueForKey(std::string(field.szName), ""); + break; + } + + case CSPFT_SCRIPT_STRING: + FillFromScriptString(std::string(field.szName), field.iOffset); + break; + + case CSPFT_TRACER: { + const auto *tracer = *reinterpret_cast<TracerDef **>(reinterpret_cast<uintptr_t>(m_structure) + field.iOffset); + + if (tracer) + m_info_string.SetValueForKey(std::string(field.szName), std::string(AssetName(tracer->name))); + else + m_info_string.SetValueForKey(std::string(field.szName), ""); + break; + } + + case CSPFT_SOUND_ALIAS_ID: { + // TODO: Search sound files for files matching the hash + const auto *hash = reinterpret_cast<unsigned *>(reinterpret_cast<uintptr_t>(m_structure) + field.iOffset); + std::ostringstream str; + str << '@' << std::hex << *hash; + m_info_string.SetValueForKey(std::string(field.szName), str.str()); + break; + } + + case CSPFT_NUM_BASE_FIELD_TYPES: + default: + assert(false); + break; + } } -void InfoStringFromStructConverter::FillInfoString() -{ - for (auto fieldIndex = 0u; fieldIndex < m_field_count; fieldIndex++) - { - const auto& field = m_fields[fieldIndex]; - assert(field.iFieldType >= 0); - - if (field.iFieldType < CSPFT_NUM_BASE_FIELD_TYPES) - FillFromBaseField(field); - else - FillFromExtensionField(field); - } -} +void InfoStringFromStructConverter::FillInfoString() { + for (auto fieldIndex = 0u; fieldIndex < m_field_count; fieldIndex++) { + const auto &field = m_fields[fieldIndex]; + assert(field.iFieldType >= 0); -InfoStringFromStructConverter::InfoStringFromStructConverter(const void* structure, const cspField_t* fields, - const size_t fieldCount) - : InfoStringFromStructConverterBase(structure), - m_fields(fields), - m_field_count(fieldCount) -{ + if (field.iFieldType < CSPFT_NUM_BASE_FIELD_TYPES) + FillFromBaseField(field); + else + FillFromExtensionField(field); + } } -InfoStringFromStructConverter::InfoStringFromStructConverter(const void* structure, const cspField_t* fields, const size_t fieldCount, - std::function<std::string(scr_string_t)> scriptStringValueCallback) - : InfoStringFromStructConverterBase(structure, std::move(scriptStringValueCallback)), - m_fields(fields), - m_field_count(fieldCount) -{ -} +InfoStringFromStructConverter::InfoStringFromStructConverter(const void *structure, const cspField_t *fields, const size_t fieldCount) + : InfoStringFromStructConverterBase(structure), m_fields(fields), m_field_count(fieldCount) {} + +InfoStringFromStructConverter::InfoStringFromStructConverter(const void *structure, const cspField_t *fields, const size_t fieldCount, + std::function<std::string(scr_string_t)> scriptStringValueCallback) + : InfoStringFromStructConverterBase(structure, std::move(scriptStringValueCallback)), m_fields(fields), m_field_count(fieldCount) {} diff --git a/src/ObjWriting/Game/T6/InfoString/InfoStringFromStructConverter.h b/src/ObjWriting/Game/T6/InfoString/InfoStringFromStructConverter.h index 9a8b79562..67a22e133 100644 --- a/src/ObjWriting/Game/T6/InfoString/InfoStringFromStructConverter.h +++ b/src/ObjWriting/Game/T6/InfoString/InfoStringFromStructConverter.h @@ -1,21 +1,20 @@ #pragma once -#include "InfoString/InfoStringFromStructConverterBase.h" #include "Game/T6/T6.h" +#include "InfoString/InfoStringFromStructConverterBase.h" -namespace T6 -{ - class InfoStringFromStructConverter : public InfoStringFromStructConverterBase - { - protected: - const cspField_t* m_fields; - size_t m_field_count; +namespace T6 { +class InfoStringFromStructConverter : public InfoStringFromStructConverterBase { +protected: + const cspField_t *m_fields; + size_t m_field_count; - virtual void FillFromExtensionField(const cspField_t& field) = 0; - void FillFromBaseField(const cspField_t& field); - void FillInfoString() override; + virtual void FillFromExtensionField(const cspField_t &field) = 0; + void FillFromBaseField(const cspField_t &field); + void FillInfoString() override; - public: - InfoStringFromStructConverter(const void* structure, const cspField_t* fields, size_t fieldCount); - InfoStringFromStructConverter(const void* structure, const cspField_t* fields, size_t fieldCount, std::function<std::string(scr_string_t)> scriptStringValueCallback); - }; -} \ No newline at end of file +public: + InfoStringFromStructConverter(const void *structure, const cspField_t *fields, size_t fieldCount); + InfoStringFromStructConverter(const void *structure, const cspField_t *fields, size_t fieldCount, + std::function<std::string(scr_string_t)> scriptStringValueCallback); +}; +} // namespace T6 \ No newline at end of file diff --git a/src/ObjWriting/Game/T6/ZoneDumperT6.cpp b/src/ObjWriting/Game/T6/ZoneDumperT6.cpp index 4a7349b51..ef3038195 100644 --- a/src/ObjWriting/Game/T6/ZoneDumperT6.cpp +++ b/src/ObjWriting/Game/T6/ZoneDumperT6.cpp @@ -1,20 +1,20 @@ #include "ZoneDumperT6.h" -#include "ObjWriting.h" -#include "Game/T6/GameT6.h" #include "Game/T6/GameAssetPoolT6.h" +#include "Game/T6/GameT6.h" +#include "ObjWriting.h" -#include "AssetDumpers/AssetDumperRawFile.h" -#include "AssetDumpers/AssetDumperSlug.h" -#include "AssetDumpers/AssetDumperQdb.h" -#include "AssetDumpers/AssetDumperScriptParseTree.h" -#include "AssetDumpers/AssetDumperStringTable.h" -#include "AssetDumpers/AssetDumperLocalizeEntry.h" -#include "AssetDumpers/AssetDumperGfxImage.h" #include "AssetDumpers/AssetDumperFontIcon.h" +#include "AssetDumpers/AssetDumperGfxImage.h" +#include "AssetDumpers/AssetDumperLocalizeEntry.h" #include "AssetDumpers/AssetDumperPhysConstraints.h" #include "AssetDumpers/AssetDumperPhysPreset.h" +#include "AssetDumpers/AssetDumperQdb.h" +#include "AssetDumpers/AssetDumperRawFile.h" +#include "AssetDumpers/AssetDumperScriptParseTree.h" +#include "AssetDumpers/AssetDumperSlug.h" #include "AssetDumpers/AssetDumperSndBank.h" +#include "AssetDumpers/AssetDumperStringTable.h" #include "AssetDumpers/AssetDumperTracer.h" #include "AssetDumpers/AssetDumperVehicle.h" #include "AssetDumpers/AssetDumperWeapon.h" @@ -25,72 +25,67 @@ using namespace T6; -bool ZoneDumper::CanHandleZone(AssetDumpingContext& context) const -{ - return context.m_zone->m_game == &g_GameT6; -} +bool ZoneDumper::CanHandleZone(AssetDumpingContext &context) const { return context.m_zone->m_game == &g_GameT6; } -bool ZoneDumper::DumpZone(AssetDumpingContext& context) const -{ -#define DUMP_ASSET_POOL(dumperType, poolName, assetType) \ - if(assetPools->poolName && ObjWriting::ShouldHandleAssetType(assetType)) \ - { \ - dumperType dumper; \ - dumper.DumpPool(context, assetPools->poolName.get()); \ - } +bool ZoneDumper::DumpZone(AssetDumpingContext &context) const { +#define DUMP_ASSET_POOL(dumperType, poolName, assetType) \ + if (assetPools->poolName && ObjWriting::ShouldHandleAssetType(assetType)) { \ + dumperType dumper; \ + dumper.DumpPool(context, assetPools->poolName.get()); \ + } - const auto* assetPools = dynamic_cast<GameAssetPoolT6*>(context.m_zone->m_pools.get()); + const auto *assetPools = dynamic_cast<GameAssetPoolT6 *>(context.m_zone->m_pools.get()); - DUMP_ASSET_POOL(AssetDumperPhysPreset, m_phys_preset, ASSET_TYPE_PHYSPRESET) - DUMP_ASSET_POOL(AssetDumperPhysConstraints, m_phys_constraints, ASSET_TYPE_PHYSCONSTRAINTS) - // DUMP_ASSET_POOL(AssetDumperDestructibleDef, m_destructible_def, ASSET_TYPE_DESTRUCTIBLEDEF) - // DUMP_ASSET_POOL(AssetDumperXAnimParts, m_xanim_parts, ASSET_TYPE_XANIMPARTS) - DUMP_ASSET_POOL(AssetDumperXModel, m_xmodel, ASSET_TYPE_XMODEL) - // DUMP_ASSET_POOL(AssetDumperMaterial, m_material, ASSET_TYPE_MATERIAL) - // DUMP_ASSET_POOL(AssetDumperTechniqueSet, m_technique_set, ASSET_TYPE_TECHNIQUE_SET) - DUMP_ASSET_POOL(AssetDumperGfxImage, m_image, ASSET_TYPE_IMAGE) - DUMP_ASSET_POOL(AssetDumperSndBank, m_sound_bank, ASSET_TYPE_SOUND) - // DUMP_ASSET_POOL(AssetDumperSndPatch, m_sound_patch, ASSET_TYPE_SOUND_PATCH) - // DUMP_ASSET_POOL(AssetDumperClipMap, m_clip_map, ASSET_TYPE_CLIPMAP) - // DUMP_ASSET_POOL(AssetDumperComWorld, m_com_world, ASSET_TYPE_COMWORLD) - // DUMP_ASSET_POOL(AssetDumperGameWorldSp, m_game_world_sp, ASSET_TYPE_GAMEWORLD_SP) - // DUMP_ASSET_POOL(AssetDumperGameWorldMp, m_game_world_mp, ASSET_TYPE_GAMEWORLD_MP) - // DUMP_ASSET_POOL(AssetDumperMapEnts, m_map_ents, ASSET_TYPE_MAP_ENTS) - // DUMP_ASSET_POOL(AssetDumperGfxWorld, m_gfx_world, ASSET_TYPE_GFXWORLD) - // DUMP_ASSET_POOL(AssetDumperGfxLightDef, m_gfx_light_def, ASSET_TYPE_LIGHT_DEF) - // DUMP_ASSET_POOL(AssetDumperFont, m_font, ASSET_TYPE_FONT) - DUMP_ASSET_POOL(AssetDumperFontIcon, m_font_icon, ASSET_TYPE_FONTICON) - // DUMP_ASSET_POOL(AssetDumperMenuList, m_menu_list, ASSET_TYPE_MENULIST) - // DUMP_ASSET_POOL(AssetDumperMenuDef, m_menu_def, ASSET_TYPE_MENU) - DUMP_ASSET_POOL(AssetDumperLocalizeEntry, m_localize, ASSET_TYPE_LOCALIZE_ENTRY) - DUMP_ASSET_POOL(AssetDumperWeapon, m_weapon, ASSET_TYPE_WEAPON) - DUMP_ASSET_POOL(AssetDumperWeaponAttachment, m_attachment, ASSET_TYPE_ATTACHMENT) - DUMP_ASSET_POOL(AssetDumperWeaponAttachmentUnique, m_attachment_unique, ASSET_TYPE_ATTACHMENT_UNIQUE) - // DUMP_ASSET_POOL(AssetDumperWeaponCamo, m_camo, ASSET_TYPE_WEAPON_CAMO) - // DUMP_ASSET_POOL(AssetDumperSndDriverGlobals, m_snd_driver_globals, ASSET_TYPE_SNDDRIVER_GLOBALS) - // DUMP_ASSET_POOL(AssetDumperFxEffectDef, m_fx, ASSET_TYPE_FX) - // DUMP_ASSET_POOL(AssetDumperFxImpactTable, m_fx_impact_table, ASSET_TYPE_IMPACT_FX) - DUMP_ASSET_POOL(AssetDumperRawFile, m_raw_file, ASSET_TYPE_RAWFILE) - DUMP_ASSET_POOL(AssetDumperStringTable, m_string_table, ASSET_TYPE_STRINGTABLE) - // DUMP_ASSET_POOL(AssetDumperLeaderboardDef, m_leaderboard, ASSET_TYPE_LEADERBOARD) - // DUMP_ASSET_POOL(AssetDumperXGlobals, m_xglobals, ASSET_TYPE_XGLOBALS) - // DUMP_ASSET_POOL(AssetDumperDDLRoot, m_ddl, ASSET_TYPE_DDL) - // DUMP_ASSET_POOL(AssetDumperGlasses, m_glasses, ASSET_TYPE_GLASSES) - // DUMP_ASSET_POOL(AssetDumperEmblemSet, m_emblem_set, ASSET_TYPE_EMBLEMSET) - DUMP_ASSET_POOL(AssetDumperScriptParseTree, m_script, ASSET_TYPE_SCRIPTPARSETREE) - // DUMP_ASSET_POOL(AssetDumperKeyValuePairs, m_key_value_pairs, ASSET_TYPE_KEYVALUEPAIRS) - DUMP_ASSET_POOL(AssetDumperVehicle, m_vehicle, ASSET_TYPE_VEHICLEDEF) - // DUMP_ASSET_POOL(AssetDumperMemoryBlock, m_memory_block, ASSET_TYPE_MEMORYBLOCK) - // DUMP_ASSET_POOL(AssetDumperAddonMapEnts, m_addon_map_ents, ASSET_TYPE_ADDON_MAP_ENTS) - DUMP_ASSET_POOL(AssetDumperTracer, m_tracer, ASSET_TYPE_TRACER) - // DUMP_ASSET_POOL(AssetDumperSkinnedVertsDef, m_skinned_verts, ASSET_TYPE_SKINNEDVERTS) - DUMP_ASSET_POOL(AssetDumperQdb, m_qdb, ASSET_TYPE_QDB) - DUMP_ASSET_POOL(AssetDumperSlug, m_slug, ASSET_TYPE_SLUG) - // DUMP_ASSET_POOL(AssetDumperFootstepTableDef, m_footstep_table, ASSET_TYPE_FOOTSTEP_TABLE) - // DUMP_ASSET_POOL(AssetDumperFootstepFXTableDef, m_footstep_fx_table, ASSET_TYPE_FOOTSTEPFX_TABLE) - DUMP_ASSET_POOL(AssetDumperZBarrier, m_zbarrier, ASSET_TYPE_ZBARRIER) + DUMP_ASSET_POOL(AssetDumperPhysPreset, m_phys_preset, ASSET_TYPE_PHYSPRESET) + DUMP_ASSET_POOL(AssetDumperPhysConstraints, m_phys_constraints, ASSET_TYPE_PHYSCONSTRAINTS) + // DUMP_ASSET_POOL(AssetDumperDestructibleDef, m_destructible_def, ASSET_TYPE_DESTRUCTIBLEDEF) + // DUMP_ASSET_POOL(AssetDumperXAnimParts, m_xanim_parts, ASSET_TYPE_XANIMPARTS) + DUMP_ASSET_POOL(AssetDumperXModel, m_xmodel, ASSET_TYPE_XMODEL) + // DUMP_ASSET_POOL(AssetDumperMaterial, m_material, ASSET_TYPE_MATERIAL) + // DUMP_ASSET_POOL(AssetDumperTechniqueSet, m_technique_set, ASSET_TYPE_TECHNIQUE_SET) + DUMP_ASSET_POOL(AssetDumperGfxImage, m_image, ASSET_TYPE_IMAGE) + DUMP_ASSET_POOL(AssetDumperSndBank, m_sound_bank, ASSET_TYPE_SOUND) + // DUMP_ASSET_POOL(AssetDumperSndPatch, m_sound_patch, ASSET_TYPE_SOUND_PATCH) + // DUMP_ASSET_POOL(AssetDumperClipMap, m_clip_map, ASSET_TYPE_CLIPMAP) + // DUMP_ASSET_POOL(AssetDumperComWorld, m_com_world, ASSET_TYPE_COMWORLD) + // DUMP_ASSET_POOL(AssetDumperGameWorldSp, m_game_world_sp, ASSET_TYPE_GAMEWORLD_SP) + // DUMP_ASSET_POOL(AssetDumperGameWorldMp, m_game_world_mp, ASSET_TYPE_GAMEWORLD_MP) + // DUMP_ASSET_POOL(AssetDumperMapEnts, m_map_ents, ASSET_TYPE_MAP_ENTS) + // DUMP_ASSET_POOL(AssetDumperGfxWorld, m_gfx_world, ASSET_TYPE_GFXWORLD) + // DUMP_ASSET_POOL(AssetDumperGfxLightDef, m_gfx_light_def, ASSET_TYPE_LIGHT_DEF) + // DUMP_ASSET_POOL(AssetDumperFont, m_font, ASSET_TYPE_FONT) + DUMP_ASSET_POOL(AssetDumperFontIcon, m_font_icon, ASSET_TYPE_FONTICON) + // DUMP_ASSET_POOL(AssetDumperMenuList, m_menu_list, ASSET_TYPE_MENULIST) + // DUMP_ASSET_POOL(AssetDumperMenuDef, m_menu_def, ASSET_TYPE_MENU) + DUMP_ASSET_POOL(AssetDumperLocalizeEntry, m_localize, ASSET_TYPE_LOCALIZE_ENTRY) + DUMP_ASSET_POOL(AssetDumperWeapon, m_weapon, ASSET_TYPE_WEAPON) + DUMP_ASSET_POOL(AssetDumperWeaponAttachment, m_attachment, ASSET_TYPE_ATTACHMENT) + DUMP_ASSET_POOL(AssetDumperWeaponAttachmentUnique, m_attachment_unique, ASSET_TYPE_ATTACHMENT_UNIQUE) + // DUMP_ASSET_POOL(AssetDumperWeaponCamo, m_camo, ASSET_TYPE_WEAPON_CAMO) + // DUMP_ASSET_POOL(AssetDumperSndDriverGlobals, m_snd_driver_globals, ASSET_TYPE_SNDDRIVER_GLOBALS) + // DUMP_ASSET_POOL(AssetDumperFxEffectDef, m_fx, ASSET_TYPE_FX) + // DUMP_ASSET_POOL(AssetDumperFxImpactTable, m_fx_impact_table, ASSET_TYPE_IMPACT_FX) + DUMP_ASSET_POOL(AssetDumperRawFile, m_raw_file, ASSET_TYPE_RAWFILE) + DUMP_ASSET_POOL(AssetDumperStringTable, m_string_table, ASSET_TYPE_STRINGTABLE) + // DUMP_ASSET_POOL(AssetDumperLeaderboardDef, m_leaderboard, ASSET_TYPE_LEADERBOARD) + // DUMP_ASSET_POOL(AssetDumperXGlobals, m_xglobals, ASSET_TYPE_XGLOBALS) + // DUMP_ASSET_POOL(AssetDumperDDLRoot, m_ddl, ASSET_TYPE_DDL) + // DUMP_ASSET_POOL(AssetDumperGlasses, m_glasses, ASSET_TYPE_GLASSES) + // DUMP_ASSET_POOL(AssetDumperEmblemSet, m_emblem_set, ASSET_TYPE_EMBLEMSET) + DUMP_ASSET_POOL(AssetDumperScriptParseTree, m_script, ASSET_TYPE_SCRIPTPARSETREE) + // DUMP_ASSET_POOL(AssetDumperKeyValuePairs, m_key_value_pairs, ASSET_TYPE_KEYVALUEPAIRS) + DUMP_ASSET_POOL(AssetDumperVehicle, m_vehicle, ASSET_TYPE_VEHICLEDEF) + // DUMP_ASSET_POOL(AssetDumperMemoryBlock, m_memory_block, ASSET_TYPE_MEMORYBLOCK) + // DUMP_ASSET_POOL(AssetDumperAddonMapEnts, m_addon_map_ents, ASSET_TYPE_ADDON_MAP_ENTS) + DUMP_ASSET_POOL(AssetDumperTracer, m_tracer, ASSET_TYPE_TRACER) + // DUMP_ASSET_POOL(AssetDumperSkinnedVertsDef, m_skinned_verts, ASSET_TYPE_SKINNEDVERTS) + DUMP_ASSET_POOL(AssetDumperQdb, m_qdb, ASSET_TYPE_QDB) + DUMP_ASSET_POOL(AssetDumperSlug, m_slug, ASSET_TYPE_SLUG) + // DUMP_ASSET_POOL(AssetDumperFootstepTableDef, m_footstep_table, ASSET_TYPE_FOOTSTEP_TABLE) + // DUMP_ASSET_POOL(AssetDumperFootstepFXTableDef, m_footstep_fx_table, ASSET_TYPE_FOOTSTEPFX_TABLE) + DUMP_ASSET_POOL(AssetDumperZBarrier, m_zbarrier, ASSET_TYPE_ZBARRIER) - return true; + return true; #undef DUMP_ASSET_POOL } diff --git a/src/ObjWriting/Game/T6/ZoneDumperT6.h b/src/ObjWriting/Game/T6/ZoneDumperT6.h index 7c0ed40d4..a0093134a 100644 --- a/src/ObjWriting/Game/T6/ZoneDumperT6.h +++ b/src/ObjWriting/Game/T6/ZoneDumperT6.h @@ -1,12 +1,10 @@ #pragma once #include "Dumping/IZoneDumper.h" -namespace T6 -{ - class ZoneDumper final : public IZoneDumper - { - public: - bool CanHandleZone(AssetDumpingContext& context) const override; - bool DumpZone(AssetDumpingContext& context) const override; - }; -} +namespace T6 { +class ZoneDumper final : public IZoneDumper { +public: + bool CanHandleZone(AssetDumpingContext &context) const override; + bool DumpZone(AssetDumpingContext &context) const override; +}; +} // namespace T6 diff --git a/src/ObjWriting/Image/DdsWriter.cpp b/src/ObjWriting/Image/DdsWriter.cpp index fef3429c2..1b5fdb8af 100644 --- a/src/ObjWriting/Image/DdsWriter.cpp +++ b/src/ObjWriting/Image/DdsWriter.cpp @@ -7,239 +7,200 @@ #include "Image/DdsTypes.h" #include "Image/TextureConverter.h" -const std::map<ImageFormatId, ImageFormatId> DDS_CONVERSION_TABLE -{ +const std::map<ImageFormatId, ImageFormatId> DDS_CONVERSION_TABLE{ {ImageFormatId::R8_G8_B8, ImageFormatId::B8_G8_R8_X8}, }; -class DdsWriterInternal -{ - std::ostream& m_stream; - Texture* m_texture; - std::unique_ptr<Texture> m_converted_texture; - bool m_use_dx10_extension; - - static constexpr unsigned Mask1(const unsigned length) - { - if (length >= sizeof(unsigned) * 8) - return UINT32_MAX; - - return UINT32_MAX >> (sizeof(unsigned) * 8 - length); - } - - void PopulatePixelFormatBlockCompressed(DDS_PIXELFORMAT& pf, const ImageFormatBlockCompressed* format) - { - pf.dwSize = sizeof(DDS_PIXELFORMAT); - pf.dwFlags = DDPF_FOURCC; - pf.dwRGBBitCount = 0; - pf.dwRBitMask = 0; - pf.dwGBitMask = 0; - pf.dwBBitMask = 0; - pf.dwABitMask = 0; - - // Use standard pixel format for DXT1-5 for maximum compatibility and only otherwise use DX10 extension - switch (format->GetDxgiFormat()) - { - case DXGI_FORMAT_BC1_UNORM: - pf.dwFourCC = MakeFourCc('D', 'X', 'T', '1'); - break; - case DXGI_FORMAT_BC2_UNORM: - pf.dwFourCC = MakeFourCc('D', 'X', 'T', '3'); - break; - case DXGI_FORMAT_BC3_UNORM: - pf.dwFourCC = MakeFourCc('D', 'X', 'T', '5'); - break; - default: - m_use_dx10_extension = true; - pf.dwFourCC = MakeFourCc('D', 'X', '1', '0'); - break; - } +class DdsWriterInternal { + std::ostream &m_stream; + Texture *m_texture; + std::unique_ptr<Texture> m_converted_texture; + bool m_use_dx10_extension; + + static constexpr unsigned Mask1(const unsigned length) { + if (length >= sizeof(unsigned) * 8) + return UINT32_MAX; + + return UINT32_MAX >> (sizeof(unsigned) * 8 - length); + } + + void PopulatePixelFormatBlockCompressed(DDS_PIXELFORMAT &pf, const ImageFormatBlockCompressed *format) { + pf.dwSize = sizeof(DDS_PIXELFORMAT); + pf.dwFlags = DDPF_FOURCC; + pf.dwRGBBitCount = 0; + pf.dwRBitMask = 0; + pf.dwGBitMask = 0; + pf.dwBBitMask = 0; + pf.dwABitMask = 0; + + // Use standard pixel format for DXT1-5 for maximum compatibility and only otherwise use DX10 extension + switch (format->GetDxgiFormat()) { + case DXGI_FORMAT_BC1_UNORM: + pf.dwFourCC = MakeFourCc('D', 'X', 'T', '1'); + break; + case DXGI_FORMAT_BC2_UNORM: + pf.dwFourCC = MakeFourCc('D', 'X', 'T', '3'); + break; + case DXGI_FORMAT_BC3_UNORM: + pf.dwFourCC = MakeFourCc('D', 'X', 'T', '5'); + break; + default: + m_use_dx10_extension = true; + pf.dwFourCC = MakeFourCc('D', 'X', '1', '0'); + break; } - - static void PopulatePixelFormatUnsigned(DDS_PIXELFORMAT& pf, const ImageFormatUnsigned* format) - { - pf.dwSize = sizeof(DDS_PIXELFORMAT); - pf.dwFourCC = 0; - pf.dwRGBBitCount = format->m_bits_per_pixel; - pf.dwRBitMask = format->HasR() ? Mask1(format->m_r_size) << format->m_r_offset : 0; - pf.dwGBitMask = format->HasG() ? Mask1(format->m_g_size) << format->m_g_offset : 0; - pf.dwBBitMask = format->HasB() ? Mask1(format->m_b_size) << format->m_b_offset : 0; - pf.dwABitMask = format->HasA() ? Mask1(format->m_a_size) << format->m_a_offset : 0; - - pf.dwFlags = 0; - if (format->HasA()) - pf.dwFlags |= DDPF_ALPHAPIXELS; - - if (format->HasR() && !format->HasG() && !format->HasB()) - pf.dwFlags |= DDPF_LUMINANCE; - else - pf.dwFlags |= DDPF_RGB; - } - - void PopulatePixelFormat(DDS_PIXELFORMAT& pf) - { - const auto* format = m_texture->GetFormat(); - - switch (format->GetType()) - { - case ImageFormatType::BLOCK_COMPRESSED: - PopulatePixelFormatBlockCompressed(pf, dynamic_cast<const ImageFormatBlockCompressed*>(format)); - break; - case ImageFormatType::UNSIGNED: - PopulatePixelFormatUnsigned(pf, dynamic_cast<const ImageFormatUnsigned*>(format)); - break; - default: - assert(false); - break; - } + } + + static void PopulatePixelFormatUnsigned(DDS_PIXELFORMAT &pf, const ImageFormatUnsigned *format) { + pf.dwSize = sizeof(DDS_PIXELFORMAT); + pf.dwFourCC = 0; + pf.dwRGBBitCount = format->m_bits_per_pixel; + pf.dwRBitMask = format->HasR() ? Mask1(format->m_r_size) << format->m_r_offset : 0; + pf.dwGBitMask = format->HasG() ? Mask1(format->m_g_size) << format->m_g_offset : 0; + pf.dwBBitMask = format->HasB() ? Mask1(format->m_b_size) << format->m_b_offset : 0; + pf.dwABitMask = format->HasA() ? Mask1(format->m_a_size) << format->m_a_offset : 0; + + pf.dwFlags = 0; + if (format->HasA()) + pf.dwFlags |= DDPF_ALPHAPIXELS; + + if (format->HasR() && !format->HasG() && !format->HasB()) + pf.dwFlags |= DDPF_LUMINANCE; + else + pf.dwFlags |= DDPF_RGB; + } + + void PopulatePixelFormat(DDS_PIXELFORMAT &pf) { + const auto *format = m_texture->GetFormat(); + + switch (format->GetType()) { + case ImageFormatType::BLOCK_COMPRESSED: + PopulatePixelFormatBlockCompressed(pf, dynamic_cast<const ImageFormatBlockCompressed *>(format)); + break; + case ImageFormatType::UNSIGNED: + PopulatePixelFormatUnsigned(pf, dynamic_cast<const ImageFormatUnsigned *>(format)); + break; + default: + assert(false); + break; } + } - void PopulateDdsHeader(DDS_HEADER& header) - { - header.dwSize = sizeof header; - header.dwFlags = DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH | DDSD_PIXELFORMAT; + void PopulateDdsHeader(DDS_HEADER &header) { + header.dwSize = sizeof header; + header.dwFlags = DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH | DDSD_PIXELFORMAT; - if (m_texture->HasMipMaps()) - header.dwFlags |= DDSD_MIPMAPCOUNT; + if (m_texture->HasMipMaps()) + header.dwFlags |= DDSD_MIPMAPCOUNT; - if (m_texture->GetFormat()->GetType() == ImageFormatType::BLOCK_COMPRESSED) - header.dwFlags |= DDSD_LINEARSIZE; - else - header.dwFlags |= DDSD_PITCH; + if (m_texture->GetFormat()->GetType() == ImageFormatType::BLOCK_COMPRESSED) + header.dwFlags |= DDSD_LINEARSIZE; + else + header.dwFlags |= DDSD_PITCH; - if (m_texture->GetDepth() > 1) - header.dwFlags |= DDSD_DEPTH; + if (m_texture->GetDepth() > 1) + header.dwFlags |= DDSD_DEPTH; - header.dwHeight = m_texture->GetHeight(); - header.dwWidth = m_texture->GetWidth(); - header.dwDepth = m_texture->GetDepth(); - header.dwPitchOrLinearSize = m_texture->GetFormat()->GetPitch(0, m_texture->GetWidth()); - header.dwMipMapCount = m_texture->HasMipMaps() ? m_texture->GetMipMapCount() : 1; + header.dwHeight = m_texture->GetHeight(); + header.dwWidth = m_texture->GetWidth(); + header.dwDepth = m_texture->GetDepth(); + header.dwPitchOrLinearSize = m_texture->GetFormat()->GetPitch(0, m_texture->GetWidth()); + header.dwMipMapCount = m_texture->HasMipMaps() ? m_texture->GetMipMapCount() : 1; - PopulatePixelFormat(header.ddspf); + PopulatePixelFormat(header.ddspf); - header.dwCaps = DDSCAPS_TEXTURE; + header.dwCaps = DDSCAPS_TEXTURE; - if (m_texture->HasMipMaps()) - header.dwCaps |= DDSCAPS_COMPLEX | DDSCAPS_MIPMAP; + if (m_texture->HasMipMaps()) + header.dwCaps |= DDSCAPS_COMPLEX | DDSCAPS_MIPMAP; - if (m_texture->GetTextureType() == TextureType::T_CUBE) - header.dwCaps |= DDSCAPS_COMPLEX; + if (m_texture->GetTextureType() == TextureType::T_CUBE) + header.dwCaps |= DDSCAPS_COMPLEX; - header.dwCaps2 = 0; + header.dwCaps2 = 0; - if (m_texture->GetTextureType() == TextureType::T_CUBE) - { - header.dwCaps2 |= - DDSCAPS2_CUBEMAP - | DDSCAPS2_CUBEMAP_POSITIVEX | DDSCAPS2_CUBEMAP_NEGATIVEX - | DDSCAPS2_CUBEMAP_POSITIVEY | DDSCAPS2_CUBEMAP_NEGATIVEY - | DDSCAPS2_CUBEMAP_POSITIVEZ | DDSCAPS2_CUBEMAP_NEGATIVEZ; - } - - header.dwCaps3 = 0; - header.dwCaps4 = 0; - header.dwReserved2 = 0; + if (m_texture->GetTextureType() == TextureType::T_CUBE) { + header.dwCaps2 |= DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_POSITIVEX | DDSCAPS2_CUBEMAP_NEGATIVEX | DDSCAPS2_CUBEMAP_POSITIVEY | DDSCAPS2_CUBEMAP_NEGATIVEY | + DDSCAPS2_CUBEMAP_POSITIVEZ | DDSCAPS2_CUBEMAP_NEGATIVEZ; } - void PopulateDxt10Header(DDS_HEADER_DXT10& header) const - { - header.dxgiFormat = m_texture->GetFormat()->GetDxgiFormat(); - header.miscFlag = 0; - header.miscFlags2 = 0; - - switch (m_texture->GetTextureType()) - { - case TextureType::T_2D: - header.resourceDimension = D3D10_RESOURCE_DIMENSION_TEXTURE2D; - header.arraySize = 1; - break; - case TextureType::T_CUBE: - header.resourceDimension = D3D10_RESOURCE_DIMENSION_TEXTURE2D; - header.arraySize = 6; - header.miscFlag |= DDS_RESOURCE_MISC_TEXTURECUBE; - break; - case TextureType::T_3D: - header.resourceDimension = D3D10_RESOURCE_DIMENSION_TEXTURE3D; - header.arraySize = 1; - break; - } + header.dwCaps3 = 0; + header.dwCaps4 = 0; + header.dwReserved2 = 0; + } + + void PopulateDxt10Header(DDS_HEADER_DXT10 &header) const { + header.dxgiFormat = m_texture->GetFormat()->GetDxgiFormat(); + header.miscFlag = 0; + header.miscFlags2 = 0; + + switch (m_texture->GetTextureType()) { + case TextureType::T_2D: + header.resourceDimension = D3D10_RESOURCE_DIMENSION_TEXTURE2D; + header.arraySize = 1; + break; + case TextureType::T_CUBE: + header.resourceDimension = D3D10_RESOURCE_DIMENSION_TEXTURE2D; + header.arraySize = 6; + header.miscFlag |= DDS_RESOURCE_MISC_TEXTURECUBE; + break; + case TextureType::T_3D: + header.resourceDimension = D3D10_RESOURCE_DIMENSION_TEXTURE3D; + header.arraySize = 1; + break; } + } - void ConvertTextureIfNecessary() - { - auto entry = DDS_CONVERSION_TABLE.find(m_texture->GetFormat()->GetId()); + void ConvertTextureIfNecessary() { + auto entry = DDS_CONVERSION_TABLE.find(m_texture->GetFormat()->GetId()); - if(entry != DDS_CONVERSION_TABLE.end()) - { - TextureConverter converter(m_texture, ImageFormat::ALL_FORMATS[static_cast<unsigned>(entry->second)]); - m_converted_texture = std::unique_ptr<Texture>(converter.Convert()); - m_texture = m_converted_texture.get(); - } + if (entry != DDS_CONVERSION_TABLE.end()) { + TextureConverter converter(m_texture, ImageFormat::ALL_FORMATS[static_cast<unsigned>(entry->second)]); + m_converted_texture = std::unique_ptr<Texture>(converter.Convert()); + m_texture = m_converted_texture.get(); } + } public: - static bool SupportsImageFormat(const ImageFormat* imageFormat) - { - return true; - } + static bool SupportsImageFormat(const ImageFormat *imageFormat) { return true; } - static std::string GetFileExtension() - { - return ".dds"; - } + static std::string GetFileExtension() { return ".dds"; } - DdsWriterInternal(std::ostream& stream, Texture* texture) - : m_stream(stream), - m_texture(texture), - m_use_dx10_extension(false) - { - } + DdsWriterInternal(std::ostream &stream, Texture *texture) : m_stream(stream), m_texture(texture), m_use_dx10_extension(false) {} - void DumpImage() - { - ConvertTextureIfNecessary(); + void DumpImage() { + ConvertTextureIfNecessary(); - DDS_HEADER header{}; - PopulateDdsHeader(header); + DDS_HEADER header{}; + PopulateDdsHeader(header); - constexpr auto magic = MakeFourCc('D', 'D', 'S', ' '); + constexpr auto magic = MakeFourCc('D', 'D', 'S', ' '); - m_stream.write(reinterpret_cast<const char*>(&magic), sizeof magic); - m_stream.write(reinterpret_cast<const char*>(&header), sizeof header); + m_stream.write(reinterpret_cast<const char *>(&magic), sizeof magic); + m_stream.write(reinterpret_cast<const char *>(&header), sizeof header); - if (m_use_dx10_extension) - { - DDS_HEADER_DXT10 dxt10{}; - PopulateDxt10Header(dxt10); - m_stream.write(reinterpret_cast<const char*>(&dxt10), sizeof dxt10); - } + if (m_use_dx10_extension) { + DDS_HEADER_DXT10 dxt10{}; + PopulateDxt10Header(dxt10); + m_stream.write(reinterpret_cast<const char *>(&dxt10), sizeof dxt10); + } - const auto mipCount = m_texture->HasMipMaps() ? m_texture->GetMipMapCount() : 1; - for (auto mipLevel = 0; mipLevel < mipCount; mipLevel++) - { - const auto* buffer = m_texture->GetBufferForMipLevel(mipLevel); - const auto mipLevelSize = m_texture->GetSizeOfMipLevel(mipLevel) * m_texture->GetFaceCount(); - m_stream.write(reinterpret_cast<const char*>(buffer), mipLevelSize); - } + const auto mipCount = m_texture->HasMipMaps() ? m_texture->GetMipMapCount() : 1; + for (auto mipLevel = 0; mipLevel < mipCount; mipLevel++) { + const auto *buffer = m_texture->GetBufferForMipLevel(mipLevel); + const auto mipLevelSize = m_texture->GetSizeOfMipLevel(mipLevel) * m_texture->GetFaceCount(); + m_stream.write(reinterpret_cast<const char *>(buffer), mipLevelSize); } + } }; -DdsWriter::~DdsWriter() -= default; +DdsWriter::~DdsWriter() = default; -bool DdsWriter::SupportsImageFormat(const ImageFormat* imageFormat) -{ - return DdsWriterInternal::SupportsImageFormat(imageFormat); -} +bool DdsWriter::SupportsImageFormat(const ImageFormat *imageFormat) { return DdsWriterInternal::SupportsImageFormat(imageFormat); } -std::string DdsWriter::GetFileExtension() -{ - return DdsWriterInternal::GetFileExtension(); -} +std::string DdsWriter::GetFileExtension() { return DdsWriterInternal::GetFileExtension(); } -void DdsWriter::DumpImage(std::ostream& stream, Texture* texture) -{ - DdsWriterInternal internal(stream, texture); - internal.DumpImage(); +void DdsWriter::DumpImage(std::ostream &stream, Texture *texture) { + DdsWriterInternal internal(stream, texture); + internal.DumpImage(); } diff --git a/src/ObjWriting/Image/DdsWriter.h b/src/ObjWriting/Image/DdsWriter.h index a2a010017..5b33f83f0 100644 --- a/src/ObjWriting/Image/DdsWriter.h +++ b/src/ObjWriting/Image/DdsWriter.h @@ -1,12 +1,11 @@ #pragma once #include "IImageWriter.h" -class DdsWriter final : public IImageWriter -{ +class DdsWriter final : public IImageWriter { public: - ~DdsWriter() override; + ~DdsWriter() override; - bool SupportsImageFormat(const ImageFormat * imageFormat) override; - std::string GetFileExtension() override; - void DumpImage(std::ostream& stream, Texture* texture) override; + bool SupportsImageFormat(const ImageFormat *imageFormat) override; + std::string GetFileExtension() override; + void DumpImage(std::ostream &stream, Texture *texture) override; }; diff --git a/src/ObjWriting/Image/IImageWriter.h b/src/ObjWriting/Image/IImageWriter.h index 1886b9e4e..0b296839a 100644 --- a/src/ObjWriting/Image/IImageWriter.h +++ b/src/ObjWriting/Image/IImageWriter.h @@ -5,12 +5,11 @@ #include "Image/Texture.h" -class IImageWriter -{ +class IImageWriter { public: - virtual ~IImageWriter() = default; + virtual ~IImageWriter() = default; - virtual bool SupportsImageFormat(const ImageFormat* imageFormat) = 0; - virtual std::string GetFileExtension() = 0; - virtual void DumpImage(std::ostream& stream, Texture* texture) = 0; + virtual bool SupportsImageFormat(const ImageFormat *imageFormat) = 0; + virtual std::string GetFileExtension() = 0; + virtual void DumpImage(std::ostream &stream, Texture *texture) = 0; }; \ No newline at end of file diff --git a/src/ObjWriting/Image/IwiWriter27.cpp b/src/ObjWriting/Image/IwiWriter27.cpp index f10fd8a3d..d15472b4b 100644 --- a/src/ObjWriting/Image/IwiWriter27.cpp +++ b/src/ObjWriting/Image/IwiWriter27.cpp @@ -4,142 +4,118 @@ using namespace iwi27; -IwiWriter::IwiWriter() -= default; +IwiWriter::IwiWriter() = default; -IwiWriter::~IwiWriter() -= default; +IwiWriter::~IwiWriter() = default; -IwiFormat IwiWriter::GetIwiFormatForImageFormat(const ImageFormat* imageFormat) -{ - switch (imageFormat->GetId()) - { - case ImageFormatId::R8_G8_B8: - return IwiFormat::IMG_FORMAT_BITMAP_RGB; +IwiFormat IwiWriter::GetIwiFormatForImageFormat(const ImageFormat *imageFormat) { + switch (imageFormat->GetId()) { + case ImageFormatId::R8_G8_B8: + return IwiFormat::IMG_FORMAT_BITMAP_RGB; - case ImageFormatId::R8_G8_B8_A8: - return IwiFormat::IMG_FORMAT_BITMAP_RGBA; + case ImageFormatId::R8_G8_B8_A8: + return IwiFormat::IMG_FORMAT_BITMAP_RGBA; - case ImageFormatId::A8: - return IwiFormat::IMG_FORMAT_BITMAP_ALPHA; + case ImageFormatId::A8: + return IwiFormat::IMG_FORMAT_BITMAP_ALPHA; - case ImageFormatId::R16_G16_B16_A16_FLOAT: - return IwiFormat::IMG_FORMAT_A16B16G16R16F; + case ImageFormatId::R16_G16_B16_A16_FLOAT: + return IwiFormat::IMG_FORMAT_A16B16G16R16F; - case ImageFormatId::BC1: - return IwiFormat::IMG_FORMAT_DXT1; + case ImageFormatId::BC1: + return IwiFormat::IMG_FORMAT_DXT1; - case ImageFormatId::BC2: - return IwiFormat::IMG_FORMAT_DXT3; + case ImageFormatId::BC2: + return IwiFormat::IMG_FORMAT_DXT3; - case ImageFormatId::BC3: - return IwiFormat::IMG_FORMAT_DXT5; + case ImageFormatId::BC3: + return IwiFormat::IMG_FORMAT_DXT5; - case ImageFormatId::BC5: - return IwiFormat::IMG_FORMAT_DXN; + case ImageFormatId::BC5: + return IwiFormat::IMG_FORMAT_DXN; - default: - return IwiFormat::IMG_FORMAT_INVALID; - } + default: + return IwiFormat::IMG_FORMAT_INVALID; + } } -bool IwiWriter::SupportsImageFormat(const ImageFormat* imageFormat) -{ - return GetIwiFormatForImageFormat(imageFormat) != IwiFormat::IMG_FORMAT_INVALID; -} +bool IwiWriter::SupportsImageFormat(const ImageFormat *imageFormat) { return GetIwiFormatForImageFormat(imageFormat) != IwiFormat::IMG_FORMAT_INVALID; } -std::string IwiWriter::GetFileExtension() -{ - return ".iwi"; -} +std::string IwiWriter::GetFileExtension() { return ".iwi"; } -void IwiWriter::WriteVersion(std::ostream& stream) -{ - IwiVersion version{}; - version.tag[0] = 'I'; - version.tag[1] = 'W'; - version.tag[2] = 'i'; - version.version = 27; +void IwiWriter::WriteVersion(std::ostream &stream) { + IwiVersion version{}; + version.tag[0] = 'I'; + version.tag[1] = 'W'; + version.tag[2] = 'i'; + version.version = 27; - stream.write(reinterpret_cast<char*>(&version), sizeof(IwiVersion)); + stream.write(reinterpret_cast<char *>(&version), sizeof(IwiVersion)); } -void IwiWriter::FillHeader2D(IwiHeader* header, Texture2D* texture) -{ - header->dimensions[0] = static_cast<uint16_t>(texture->GetWidth()); - header->dimensions[1] = static_cast<uint16_t>(texture->GetHeight()); - header->dimensions[2] = 1; +void IwiWriter::FillHeader2D(IwiHeader *header, Texture2D *texture) { + header->dimensions[0] = static_cast<uint16_t>(texture->GetWidth()); + header->dimensions[1] = static_cast<uint16_t>(texture->GetHeight()); + header->dimensions[2] = 1; } -void IwiWriter::FillHeaderCube(IwiHeader* header, TextureCube* texture) -{ - header->dimensions[0] = static_cast<uint16_t>(texture->GetWidth()); - header->dimensions[1] = static_cast<uint16_t>(texture->GetHeight()); - header->dimensions[2] = 1; - header->flags |= IMG_FLAG_CUBEMAP; +void IwiWriter::FillHeaderCube(IwiHeader *header, TextureCube *texture) { + header->dimensions[0] = static_cast<uint16_t>(texture->GetWidth()); + header->dimensions[1] = static_cast<uint16_t>(texture->GetHeight()); + header->dimensions[2] = 1; + header->flags |= IMG_FLAG_CUBEMAP; } -void IwiWriter::FillHeader3D(IwiHeader* header, Texture3D* texture) -{ - header->dimensions[0] = static_cast<uint16_t>(texture->GetWidth()); - header->dimensions[1] = static_cast<uint16_t>(texture->GetHeight()); - header->dimensions[2] = static_cast<uint16_t>(texture->GetDepth()); - header->flags |= IMG_FLAG_VOLMAP; +void IwiWriter::FillHeader3D(IwiHeader *header, Texture3D *texture) { + header->dimensions[0] = static_cast<uint16_t>(texture->GetWidth()); + header->dimensions[1] = static_cast<uint16_t>(texture->GetHeight()); + header->dimensions[2] = static_cast<uint16_t>(texture->GetDepth()); + header->flags |= IMG_FLAG_VOLMAP; } -void IwiWriter::DumpImage(std::ostream& stream, Texture* texture) -{ - assert(texture != nullptr); - - WriteVersion(stream); - - IwiHeader header{}; - header.flags = 0; - header.gamma = 0.0f; - - header.format = static_cast<int8_t>(GetIwiFormatForImageFormat(texture->GetFormat())); - - if (!texture->HasMipMaps()) - header.flags |= IMG_FLAG_NOMIPMAPS; - - for (auto& i : header.maxGlossForMip) - i = 0; - - auto currentFileSize = sizeof(IwiVersion) + sizeof(IwiHeader); - - const auto textureMipCount = texture->HasMipMaps() ? texture->GetMipMapCount() : 1; - for (auto currentMipLevel = textureMipCount - 1; currentMipLevel >= 0; currentMipLevel--) - { - const auto mipLevelSize = texture->GetSizeOfMipLevel(currentMipLevel) * texture->GetFaceCount(); - currentFileSize += mipLevelSize; - - if (currentMipLevel < static_cast<int>(std::extent<decltype(iwi27::IwiHeader::fileSizeForPicmip)>::value)) - header.fileSizeForPicmip[currentMipLevel] = currentFileSize; - } - - if (auto* texture2D = dynamic_cast<Texture2D*>(texture)) - { - FillHeader2D(&header, texture2D); - } - else if (auto* textureCube = dynamic_cast<TextureCube*>(texture)) - { - FillHeaderCube(&header, textureCube); - } - else if (auto* texture3D = dynamic_cast<Texture3D*>(texture)) - { - FillHeader3D(&header, texture3D); - } - else - { - assert(false); - return; - } - - stream.write(reinterpret_cast<char*>(&header), sizeof(IwiHeader)); - - for (auto currentMipLevel = textureMipCount - 1; currentMipLevel >= 0; currentMipLevel--) - { - const auto mipLevelSize = texture->GetSizeOfMipLevel(currentMipLevel) * texture->GetFaceCount(); - stream.write(reinterpret_cast<char*>(texture->GetBufferForMipLevel(currentMipLevel)), mipLevelSize); - } +void IwiWriter::DumpImage(std::ostream &stream, Texture *texture) { + assert(texture != nullptr); + + WriteVersion(stream); + + IwiHeader header{}; + header.flags = 0; + header.gamma = 0.0f; + + header.format = static_cast<int8_t>(GetIwiFormatForImageFormat(texture->GetFormat())); + + if (!texture->HasMipMaps()) + header.flags |= IMG_FLAG_NOMIPMAPS; + + for (auto &i : header.maxGlossForMip) + i = 0; + + auto currentFileSize = sizeof(IwiVersion) + sizeof(IwiHeader); + + const auto textureMipCount = texture->HasMipMaps() ? texture->GetMipMapCount() : 1; + for (auto currentMipLevel = textureMipCount - 1; currentMipLevel >= 0; currentMipLevel--) { + const auto mipLevelSize = texture->GetSizeOfMipLevel(currentMipLevel) * texture->GetFaceCount(); + currentFileSize += mipLevelSize; + + if (currentMipLevel < static_cast<int>(std::extent<decltype(iwi27::IwiHeader::fileSizeForPicmip)>::value)) + header.fileSizeForPicmip[currentMipLevel] = currentFileSize; + } + + if (auto *texture2D = dynamic_cast<Texture2D *>(texture)) { + FillHeader2D(&header, texture2D); + } else if (auto *textureCube = dynamic_cast<TextureCube *>(texture)) { + FillHeaderCube(&header, textureCube); + } else if (auto *texture3D = dynamic_cast<Texture3D *>(texture)) { + FillHeader3D(&header, texture3D); + } else { + assert(false); + return; + } + + stream.write(reinterpret_cast<char *>(&header), sizeof(IwiHeader)); + + for (auto currentMipLevel = textureMipCount - 1; currentMipLevel >= 0; currentMipLevel--) { + const auto mipLevelSize = texture->GetSizeOfMipLevel(currentMipLevel) * texture->GetFaceCount(); + stream.write(reinterpret_cast<char *>(texture->GetBufferForMipLevel(currentMipLevel)), mipLevelSize); + } } diff --git a/src/ObjWriting/Image/IwiWriter27.h b/src/ObjWriting/Image/IwiWriter27.h index 88bbc834a..0870ca95b 100644 --- a/src/ObjWriting/Image/IwiWriter27.h +++ b/src/ObjWriting/Image/IwiWriter27.h @@ -3,28 +3,26 @@ #include "IImageWriter.h" #include "Image/IwiTypes.h" -namespace iwi27 -{ - class IwiWriter final : public IImageWriter - { - static IwiFormat GetIwiFormatForImageFormat(const ImageFormat* imageFormat); +namespace iwi27 { +class IwiWriter final : public IImageWriter { + static IwiFormat GetIwiFormatForImageFormat(const ImageFormat *imageFormat); - static void WriteVersion(std::ostream& stream); - static void FillHeader2D(IwiHeader* header, Texture2D* texture); - static void FillHeaderCube(IwiHeader* header, TextureCube* texture); - static void FillHeader3D(IwiHeader* header, Texture3D* texture); + static void WriteVersion(std::ostream &stream); + static void FillHeader2D(IwiHeader *header, Texture2D *texture); + static void FillHeaderCube(IwiHeader *header, TextureCube *texture); + static void FillHeader3D(IwiHeader *header, Texture3D *texture); - public: - IwiWriter(); - IwiWriter(const IwiWriter& other) = delete; - IwiWriter(IwiWriter&& other) noexcept = delete; - ~IwiWriter() override; +public: + IwiWriter(); + IwiWriter(const IwiWriter &other) = delete; + IwiWriter(IwiWriter &&other) noexcept = delete; + ~IwiWriter() override; - IwiWriter& operator=(const IwiWriter& other) = delete; - IwiWriter& operator=(IwiWriter&& other) noexcept = delete; + IwiWriter &operator=(const IwiWriter &other) = delete; + IwiWriter &operator=(IwiWriter &&other) noexcept = delete; - bool SupportsImageFormat(const ImageFormat* imageFormat) override; - std::string GetFileExtension() override; - void DumpImage(std::ostream& stream, Texture* texture) override; - }; -} + bool SupportsImageFormat(const ImageFormat *imageFormat) override; + std::string GetFileExtension() override; + void DumpImage(std::ostream &stream, Texture *texture) override; +}; +} // namespace iwi27 diff --git a/src/ObjWriting/Image/IwiWriter6.cpp b/src/ObjWriting/Image/IwiWriter6.cpp index adc12f5e6..1388ec53f 100644 --- a/src/ObjWriting/Image/IwiWriter6.cpp +++ b/src/ObjWriting/Image/IwiWriter6.cpp @@ -4,135 +4,111 @@ using namespace iwi6; -IwiWriter::IwiWriter() -= default; +IwiWriter::IwiWriter() = default; -IwiWriter::~IwiWriter() -= default; +IwiWriter::~IwiWriter() = default; -IwiFormat IwiWriter::GetIwiFormatForImageFormat(const ImageFormat * imageFormat) -{ - switch (imageFormat->GetId()) - { - case ImageFormatId::R8_G8_B8: - return IwiFormat::IMG_FORMAT_BITMAP_RGB; +IwiFormat IwiWriter::GetIwiFormatForImageFormat(const ImageFormat *imageFormat) { + switch (imageFormat->GetId()) { + case ImageFormatId::R8_G8_B8: + return IwiFormat::IMG_FORMAT_BITMAP_RGB; - case ImageFormatId::R8_G8_B8_A8: - return IwiFormat::IMG_FORMAT_BITMAP_RGBA; + case ImageFormatId::R8_G8_B8_A8: + return IwiFormat::IMG_FORMAT_BITMAP_RGBA; - case ImageFormatId::A8: - return IwiFormat::IMG_FORMAT_BITMAP_ALPHA; + case ImageFormatId::A8: + return IwiFormat::IMG_FORMAT_BITMAP_ALPHA; - case ImageFormatId::BC1: - return IwiFormat::IMG_FORMAT_DXT1; + case ImageFormatId::BC1: + return IwiFormat::IMG_FORMAT_DXT1; - case ImageFormatId::BC2: - return IwiFormat::IMG_FORMAT_DXT3; + case ImageFormatId::BC2: + return IwiFormat::IMG_FORMAT_DXT3; - case ImageFormatId::BC3: - return IwiFormat::IMG_FORMAT_DXT5; + case ImageFormatId::BC3: + return IwiFormat::IMG_FORMAT_DXT5; - case ImageFormatId::BC5: - return IwiFormat::IMG_FORMAT_DXN; + case ImageFormatId::BC5: + return IwiFormat::IMG_FORMAT_DXN; - default: - return IwiFormat::IMG_FORMAT_INVALID; - } + default: + return IwiFormat::IMG_FORMAT_INVALID; + } } -void IwiWriter::WriteVersion(std::ostream & stream) -{ - IwiVersion version{}; - version.tag[0] = 'I'; - version.tag[1] = 'W'; - version.tag[2] = 'i'; - version.version = 6; +void IwiWriter::WriteVersion(std::ostream &stream) { + IwiVersion version{}; + version.tag[0] = 'I'; + version.tag[1] = 'W'; + version.tag[2] = 'i'; + version.version = 6; - stream.write(reinterpret_cast<char*>(&version), sizeof(IwiVersion)); + stream.write(reinterpret_cast<char *>(&version), sizeof(IwiVersion)); } -void IwiWriter::FillHeader2D(IwiHeader * header, Texture2D * texture) -{ - header->dimensions[0] = static_cast<uint16_t>(texture->GetWidth()); - header->dimensions[1] = static_cast<uint16_t>(texture->GetHeight()); - header->dimensions[2] = 1u; +void IwiWriter::FillHeader2D(IwiHeader *header, Texture2D *texture) { + header->dimensions[0] = static_cast<uint16_t>(texture->GetWidth()); + header->dimensions[1] = static_cast<uint16_t>(texture->GetHeight()); + header->dimensions[2] = 1u; } -void IwiWriter::FillHeaderCube(IwiHeader * header, TextureCube * texture) -{ - header->dimensions[0] = static_cast<uint16_t>(texture->GetWidth()); - header->dimensions[1] = static_cast<uint16_t>(texture->GetHeight()); - header->dimensions[2] = 1u; - header->flags |= IMG_FLAG_CUBEMAP; +void IwiWriter::FillHeaderCube(IwiHeader *header, TextureCube *texture) { + header->dimensions[0] = static_cast<uint16_t>(texture->GetWidth()); + header->dimensions[1] = static_cast<uint16_t>(texture->GetHeight()); + header->dimensions[2] = 1u; + header->flags |= IMG_FLAG_CUBEMAP; } -void IwiWriter::FillHeader3D(IwiHeader * header, Texture3D * texture) -{ - header->dimensions[0] = static_cast<uint16_t>(texture->GetWidth()); - header->dimensions[1] = static_cast<uint16_t>(texture->GetHeight()); - header->dimensions[2] = static_cast<uint16_t>(texture->GetDepth()); - header->flags |= IMG_FLAG_VOLMAP; +void IwiWriter::FillHeader3D(IwiHeader *header, Texture3D *texture) { + header->dimensions[0] = static_cast<uint16_t>(texture->GetWidth()); + header->dimensions[1] = static_cast<uint16_t>(texture->GetHeight()); + header->dimensions[2] = static_cast<uint16_t>(texture->GetDepth()); + header->flags |= IMG_FLAG_VOLMAP; } -bool IwiWriter::SupportsImageFormat(const ImageFormat * imageFormat) -{ - return GetIwiFormatForImageFormat(imageFormat) != IwiFormat::IMG_FORMAT_INVALID; -} +bool IwiWriter::SupportsImageFormat(const ImageFormat *imageFormat) { return GetIwiFormatForImageFormat(imageFormat) != IwiFormat::IMG_FORMAT_INVALID; } -std::string IwiWriter::GetFileExtension() -{ - return ".iwi"; -} +std::string IwiWriter::GetFileExtension() { return ".iwi"; } + +void IwiWriter::DumpImage(std::ostream &stream, Texture *texture) { + assert(texture != nullptr); + + WriteVersion(stream); + + IwiHeader header{}; + header.flags = 0; + + header.format = static_cast<int8_t>(GetIwiFormatForImageFormat(texture->GetFormat())); + + if (!texture->HasMipMaps()) + header.flags |= IMG_FLAG_NOMIPMAPS; + + auto currentFileSize = sizeof(IwiVersion) + sizeof(IwiHeader); + + const auto textureMipCount = texture->HasMipMaps() ? texture->GetMipMapCount() : 1; + for (auto currentMipLevel = textureMipCount - 1; currentMipLevel >= 0; currentMipLevel--) { + const auto mipLevelSize = texture->GetSizeOfMipLevel(currentMipLevel) * texture->GetFaceCount(); + currentFileSize += mipLevelSize; + + if (currentMipLevel < static_cast<int>(std::extent<decltype(IwiHeader::fileSizeForPicmip)>::value)) + header.fileSizeForPicmip[currentMipLevel] = currentFileSize; + } + + if (auto *texture2D = dynamic_cast<Texture2D *>(texture)) { + FillHeader2D(&header, texture2D); + } else if (auto *textureCube = dynamic_cast<TextureCube *>(texture)) { + FillHeaderCube(&header, textureCube); + } else if (auto *texture3D = dynamic_cast<Texture3D *>(texture)) { + FillHeader3D(&header, texture3D); + } else { + assert(false); + return; + } + + stream.write(reinterpret_cast<char *>(&header), sizeof(IwiHeader)); -void IwiWriter::DumpImage(std::ostream & stream, Texture * texture) -{ - assert(texture != nullptr); - - WriteVersion(stream); - - IwiHeader header{}; - header.flags = 0; - - header.format = static_cast<int8_t>(GetIwiFormatForImageFormat(texture->GetFormat())); - - if (!texture->HasMipMaps()) - header.flags |= IMG_FLAG_NOMIPMAPS; - - auto currentFileSize = sizeof(IwiVersion) + sizeof(IwiHeader); - - const auto textureMipCount = texture->HasMipMaps() ? texture->GetMipMapCount() : 1; - for (auto currentMipLevel = textureMipCount - 1; currentMipLevel >= 0; currentMipLevel--) - { - const auto mipLevelSize = texture->GetSizeOfMipLevel(currentMipLevel) * texture->GetFaceCount(); - currentFileSize += mipLevelSize; - - if (currentMipLevel < static_cast<int>(std::extent<decltype(IwiHeader::fileSizeForPicmip)>::value)) - header.fileSizeForPicmip[currentMipLevel] = currentFileSize; - } - - if (auto* texture2D = dynamic_cast<Texture2D*>(texture)) - { - FillHeader2D(&header, texture2D); - } - else if (auto* textureCube = dynamic_cast<TextureCube*>(texture)) - { - FillHeaderCube(&header, textureCube); - } - else if (auto* texture3D = dynamic_cast<Texture3D*>(texture)) - { - FillHeader3D(&header, texture3D); - } - else - { - assert(false); - return; - } - - stream.write(reinterpret_cast<char*>(&header), sizeof(IwiHeader)); - - for (auto currentMipLevel = textureMipCount - 1; currentMipLevel >= 0; currentMipLevel--) - { - const auto mipLevelSize = texture->GetSizeOfMipLevel(currentMipLevel) * texture->GetFaceCount(); - stream.write(reinterpret_cast<char*>(texture->GetBufferForMipLevel(currentMipLevel)), mipLevelSize); - } + for (auto currentMipLevel = textureMipCount - 1; currentMipLevel >= 0; currentMipLevel--) { + const auto mipLevelSize = texture->GetSizeOfMipLevel(currentMipLevel) * texture->GetFaceCount(); + stream.write(reinterpret_cast<char *>(texture->GetBufferForMipLevel(currentMipLevel)), mipLevelSize); + } } diff --git a/src/ObjWriting/Image/IwiWriter6.h b/src/ObjWriting/Image/IwiWriter6.h index 2ca178d11..8b5d55510 100644 --- a/src/ObjWriting/Image/IwiWriter6.h +++ b/src/ObjWriting/Image/IwiWriter6.h @@ -3,28 +3,26 @@ #include "IImageWriter.h" #include "Image/IwiTypes.h" -namespace iwi6 -{ - class IwiWriter final : public IImageWriter - { - static IwiFormat GetIwiFormatForImageFormat(const ImageFormat* imageFormat); +namespace iwi6 { +class IwiWriter final : public IImageWriter { + static IwiFormat GetIwiFormatForImageFormat(const ImageFormat *imageFormat); - static void WriteVersion(std::ostream& stream); - static void FillHeader2D(IwiHeader* header, Texture2D* texture); - static void FillHeaderCube(IwiHeader* header, TextureCube* texture); - static void FillHeader3D(IwiHeader* header, Texture3D* texture); + static void WriteVersion(std::ostream &stream); + static void FillHeader2D(IwiHeader *header, Texture2D *texture); + static void FillHeaderCube(IwiHeader *header, TextureCube *texture); + static void FillHeader3D(IwiHeader *header, Texture3D *texture); - public: - IwiWriter(); - IwiWriter(const IwiWriter& other) = delete; - IwiWriter(IwiWriter&& other) noexcept = delete; - ~IwiWriter() override; +public: + IwiWriter(); + IwiWriter(const IwiWriter &other) = delete; + IwiWriter(IwiWriter &&other) noexcept = delete; + ~IwiWriter() override; - IwiWriter& operator=(const IwiWriter& other) = delete; - IwiWriter& operator=(IwiWriter&& other) noexcept = delete; + IwiWriter &operator=(const IwiWriter &other) = delete; + IwiWriter &operator=(IwiWriter &&other) noexcept = delete; - bool SupportsImageFormat(const ImageFormat* imageFormat) override; - std::string GetFileExtension() override; - void DumpImage(std::ostream& stream, Texture* texture) override; - }; -} + bool SupportsImageFormat(const ImageFormat *imageFormat) override; + std::string GetFileExtension() override; + void DumpImage(std::ostream &stream, Texture *texture) override; +}; +} // namespace iwi6 diff --git a/src/ObjWriting/Image/IwiWriter8.cpp b/src/ObjWriting/Image/IwiWriter8.cpp index 028a86b5c..5a7426d1f 100644 --- a/src/ObjWriting/Image/IwiWriter8.cpp +++ b/src/ObjWriting/Image/IwiWriter8.cpp @@ -4,135 +4,111 @@ using namespace iwi8; -IwiWriter::IwiWriter() -= default; +IwiWriter::IwiWriter() = default; -IwiWriter::~IwiWriter() -= default; +IwiWriter::~IwiWriter() = default; -IwiFormat IwiWriter::GetIwiFormatForImageFormat(const ImageFormat* imageFormat) -{ - switch (imageFormat->GetId()) - { - case ImageFormatId::R8_G8_B8: - return IwiFormat::IMG_FORMAT_BITMAP_RGB; +IwiFormat IwiWriter::GetIwiFormatForImageFormat(const ImageFormat *imageFormat) { + switch (imageFormat->GetId()) { + case ImageFormatId::R8_G8_B8: + return IwiFormat::IMG_FORMAT_BITMAP_RGB; - case ImageFormatId::R8_G8_B8_A8: - return IwiFormat::IMG_FORMAT_BITMAP_RGBA; + case ImageFormatId::R8_G8_B8_A8: + return IwiFormat::IMG_FORMAT_BITMAP_RGBA; - case ImageFormatId::A8: - return IwiFormat::IMG_FORMAT_BITMAP_ALPHA; + case ImageFormatId::A8: + return IwiFormat::IMG_FORMAT_BITMAP_ALPHA; - case ImageFormatId::BC1: - return IwiFormat::IMG_FORMAT_DXT1; + case ImageFormatId::BC1: + return IwiFormat::IMG_FORMAT_DXT1; - case ImageFormatId::BC2: - return IwiFormat::IMG_FORMAT_DXT3; + case ImageFormatId::BC2: + return IwiFormat::IMG_FORMAT_DXT3; - case ImageFormatId::BC3: - return IwiFormat::IMG_FORMAT_DXT5; + case ImageFormatId::BC3: + return IwiFormat::IMG_FORMAT_DXT5; - case ImageFormatId::BC5: - return IwiFormat::IMG_FORMAT_DXN; + case ImageFormatId::BC5: + return IwiFormat::IMG_FORMAT_DXN; - default: - return IwiFormat::IMG_FORMAT_INVALID; - } + default: + return IwiFormat::IMG_FORMAT_INVALID; + } } -void IwiWriter::WriteVersion(std::ostream& stream) -{ - IwiVersion version{}; - version.tag[0] = 'I'; - version.tag[1] = 'W'; - version.tag[2] = 'i'; - version.version = 8; +void IwiWriter::WriteVersion(std::ostream &stream) { + IwiVersion version{}; + version.tag[0] = 'I'; + version.tag[1] = 'W'; + version.tag[2] = 'i'; + version.version = 8; - stream.write(reinterpret_cast<char*>(&version), sizeof(IwiVersion)); + stream.write(reinterpret_cast<char *>(&version), sizeof(IwiVersion)); } -void IwiWriter::FillHeader2D(IwiHeader* header, Texture2D* texture) -{ - header->dimensions[0] = static_cast<uint16_t>(texture->GetWidth()); - header->dimensions[1] = static_cast<uint16_t>(texture->GetHeight()); - header->dimensions[2] = 1u; +void IwiWriter::FillHeader2D(IwiHeader *header, Texture2D *texture) { + header->dimensions[0] = static_cast<uint16_t>(texture->GetWidth()); + header->dimensions[1] = static_cast<uint16_t>(texture->GetHeight()); + header->dimensions[2] = 1u; } -void IwiWriter::FillHeaderCube(IwiHeader* header, TextureCube* texture) -{ - header->dimensions[0] = static_cast<uint16_t>(texture->GetWidth()); - header->dimensions[1] = static_cast<uint16_t>(texture->GetHeight()); - header->dimensions[2] = 1u; - header->flags |= IMG_FLAG_MAPTYPE_CUBE; +void IwiWriter::FillHeaderCube(IwiHeader *header, TextureCube *texture) { + header->dimensions[0] = static_cast<uint16_t>(texture->GetWidth()); + header->dimensions[1] = static_cast<uint16_t>(texture->GetHeight()); + header->dimensions[2] = 1u; + header->flags |= IMG_FLAG_MAPTYPE_CUBE; } -void IwiWriter::FillHeader3D(IwiHeader* header, Texture3D* texture) -{ - header->dimensions[0] = static_cast<uint16_t>(texture->GetWidth()); - header->dimensions[1] = static_cast<uint16_t>(texture->GetHeight()); - header->dimensions[2] = static_cast<uint16_t>(texture->GetDepth()); - header->flags |= IMG_FLAG_MAPTYPE_3D; +void IwiWriter::FillHeader3D(IwiHeader *header, Texture3D *texture) { + header->dimensions[0] = static_cast<uint16_t>(texture->GetWidth()); + header->dimensions[1] = static_cast<uint16_t>(texture->GetHeight()); + header->dimensions[2] = static_cast<uint16_t>(texture->GetDepth()); + header->flags |= IMG_FLAG_MAPTYPE_3D; } -bool IwiWriter::SupportsImageFormat(const ImageFormat* imageFormat) -{ - return GetIwiFormatForImageFormat(imageFormat) != IwiFormat::IMG_FORMAT_INVALID; -} +bool IwiWriter::SupportsImageFormat(const ImageFormat *imageFormat) { return GetIwiFormatForImageFormat(imageFormat) != IwiFormat::IMG_FORMAT_INVALID; } -std::string IwiWriter::GetFileExtension() -{ - return ".iwi"; -} +std::string IwiWriter::GetFileExtension() { return ".iwi"; } + +void IwiWriter::DumpImage(std::ostream &stream, Texture *texture) { + assert(texture != nullptr); + + WriteVersion(stream); + + IwiHeader header{}; + header.flags = 0; + + header.format = static_cast<int8_t>(GetIwiFormatForImageFormat(texture->GetFormat())); + + if (!texture->HasMipMaps()) + header.flags |= IMG_FLAG_NOMIPMAPS; + + auto currentFileSize = sizeof(IwiVersion) + sizeof(IwiHeader); + + const auto textureMipCount = texture->HasMipMaps() ? texture->GetMipMapCount() : 1; + for (auto currentMipLevel = textureMipCount - 1; currentMipLevel >= 0; currentMipLevel--) { + const auto mipLevelSize = texture->GetSizeOfMipLevel(currentMipLevel) * texture->GetFaceCount(); + currentFileSize += mipLevelSize; + + if (currentMipLevel < static_cast<int>(std::extent<decltype(IwiHeader::fileSizeForPicmip)>::value)) + header.fileSizeForPicmip[currentMipLevel] = currentFileSize; + } + + if (auto *texture2D = dynamic_cast<Texture2D *>(texture)) { + FillHeader2D(&header, texture2D); + } else if (auto *textureCube = dynamic_cast<TextureCube *>(texture)) { + FillHeaderCube(&header, textureCube); + } else if (auto *texture3D = dynamic_cast<Texture3D *>(texture)) { + FillHeader3D(&header, texture3D); + } else { + assert(false); + return; + } + + stream.write(reinterpret_cast<char *>(&header), sizeof(IwiHeader)); -void IwiWriter::DumpImage(std::ostream& stream, Texture* texture) -{ - assert(texture != nullptr); - - WriteVersion(stream); - - IwiHeader header{}; - header.flags = 0; - - header.format = static_cast<int8_t>(GetIwiFormatForImageFormat(texture->GetFormat())); - - if (!texture->HasMipMaps()) - header.flags |= IMG_FLAG_NOMIPMAPS; - - auto currentFileSize = sizeof(IwiVersion) + sizeof(IwiHeader); - - const auto textureMipCount = texture->HasMipMaps() ? texture->GetMipMapCount() : 1; - for (auto currentMipLevel = textureMipCount - 1; currentMipLevel >= 0; currentMipLevel--) - { - const auto mipLevelSize = texture->GetSizeOfMipLevel(currentMipLevel) * texture->GetFaceCount(); - currentFileSize += mipLevelSize; - - if (currentMipLevel < static_cast<int>(std::extent<decltype(IwiHeader::fileSizeForPicmip)>::value)) - header.fileSizeForPicmip[currentMipLevel] = currentFileSize; - } - - if (auto* texture2D = dynamic_cast<Texture2D*>(texture)) - { - FillHeader2D(&header, texture2D); - } - else if (auto* textureCube = dynamic_cast<TextureCube*>(texture)) - { - FillHeaderCube(&header, textureCube); - } - else if (auto* texture3D = dynamic_cast<Texture3D*>(texture)) - { - FillHeader3D(&header, texture3D); - } - else - { - assert(false); - return; - } - - stream.write(reinterpret_cast<char*>(&header), sizeof(IwiHeader)); - - for (auto currentMipLevel = textureMipCount - 1; currentMipLevel >= 0; currentMipLevel--) - { - const auto mipLevelSize = texture->GetSizeOfMipLevel(currentMipLevel) * texture->GetFaceCount(); - stream.write(reinterpret_cast<char*>(texture->GetBufferForMipLevel(currentMipLevel)), mipLevelSize); - } + for (auto currentMipLevel = textureMipCount - 1; currentMipLevel >= 0; currentMipLevel--) { + const auto mipLevelSize = texture->GetSizeOfMipLevel(currentMipLevel) * texture->GetFaceCount(); + stream.write(reinterpret_cast<char *>(texture->GetBufferForMipLevel(currentMipLevel)), mipLevelSize); + } } diff --git a/src/ObjWriting/Image/IwiWriter8.h b/src/ObjWriting/Image/IwiWriter8.h index 1d3542932..bfc5daef9 100644 --- a/src/ObjWriting/Image/IwiWriter8.h +++ b/src/ObjWriting/Image/IwiWriter8.h @@ -3,28 +3,26 @@ #include "IImageWriter.h" #include "Image/IwiTypes.h" -namespace iwi8 -{ - class IwiWriter final : public IImageWriter - { - static IwiFormat GetIwiFormatForImageFormat(const ImageFormat* imageFormat); +namespace iwi8 { +class IwiWriter final : public IImageWriter { + static IwiFormat GetIwiFormatForImageFormat(const ImageFormat *imageFormat); - static void WriteVersion(std::ostream& stream); - static void FillHeader2D(IwiHeader* header, Texture2D* texture); - static void FillHeaderCube(IwiHeader* header, TextureCube* texture); - static void FillHeader3D(IwiHeader* header, Texture3D* texture); + static void WriteVersion(std::ostream &stream); + static void FillHeader2D(IwiHeader *header, Texture2D *texture); + static void FillHeaderCube(IwiHeader *header, TextureCube *texture); + static void FillHeader3D(IwiHeader *header, Texture3D *texture); - public: - IwiWriter(); - IwiWriter(const IwiWriter& other) = delete; - IwiWriter(IwiWriter&& other) noexcept = delete; - ~IwiWriter() override; +public: + IwiWriter(); + IwiWriter(const IwiWriter &other) = delete; + IwiWriter(IwiWriter &&other) noexcept = delete; + ~IwiWriter() override; - IwiWriter& operator=(const IwiWriter& other) = delete; - IwiWriter& operator=(IwiWriter&& other) noexcept = delete; + IwiWriter &operator=(const IwiWriter &other) = delete; + IwiWriter &operator=(IwiWriter &&other) noexcept = delete; - bool SupportsImageFormat(const ImageFormat* imageFormat) override; - std::string GetFileExtension() override; - void DumpImage(std::ostream& stream, Texture* texture) override; - }; -} + bool SupportsImageFormat(const ImageFormat *imageFormat) override; + std::string GetFileExtension() override; + void DumpImage(std::ostream &stream, Texture *texture) override; +}; +} // namespace iwi8 diff --git a/src/ObjWriting/InfoString/InfoStringFromStructConverterBase.cpp b/src/ObjWriting/InfoString/InfoStringFromStructConverterBase.cpp index c06adaf9b..93e9b1966 100644 --- a/src/ObjWriting/InfoString/InfoStringFromStructConverterBase.cpp +++ b/src/ObjWriting/InfoString/InfoStringFromStructConverterBase.cpp @@ -4,115 +4,94 @@ #include <cstring> #include <sstream> -InfoStringFromStructConverterBase::InfoStringFromStructConverterBase(const void* structure) - : m_structure(structure), - m_get_scr_string([](scr_string_t) - { - assert(false); - return ""; - }) -{ +InfoStringFromStructConverterBase::InfoStringFromStructConverterBase(const void *structure) + : m_structure(structure), m_get_scr_string([](scr_string_t) { + assert(false); + return ""; + }) {} + +InfoStringFromStructConverterBase::InfoStringFromStructConverterBase(const void *structure, std::function<std::string(scr_string_t)> scriptStringValueCallback) + : m_structure(structure), m_get_scr_string(std::move(scriptStringValueCallback)) {} + +InfoString InfoStringFromStructConverterBase::Convert() { + FillInfoString(); + return std::move(m_info_string); } -InfoStringFromStructConverterBase::InfoStringFromStructConverterBase(const void* structure, std::function<std::string(scr_string_t)> scriptStringValueCallback) - : m_structure(structure), - m_get_scr_string(std::move(scriptStringValueCallback)) -{ -} - -InfoString InfoStringFromStructConverterBase::Convert() -{ - FillInfoString(); - return std::move(m_info_string); -} - -const char* InfoStringFromStructConverterBase::AssetName(const char* name) -{ - if (name && name[0] == ',') - return &name[1]; +const char *InfoStringFromStructConverterBase::AssetName(const char *name) { + if (name && name[0] == ',') + return &name[1]; - return name; + return name; } -void InfoStringFromStructConverterBase::FillFromString(const std::string& key, const size_t offset) -{ - const auto* str = *reinterpret_cast<const char**>(reinterpret_cast<uintptr_t>(m_structure) + offset); +void InfoStringFromStructConverterBase::FillFromString(const std::string &key, const size_t offset) { + const auto *str = *reinterpret_cast<const char **>(reinterpret_cast<uintptr_t>(m_structure) + offset); - if (str) - m_info_string.SetValueForKey(key, std::string(str)); - else - m_info_string.SetValueForKey(key, ""); + if (str) + m_info_string.SetValueForKey(key, std::string(str)); + else + m_info_string.SetValueForKey(key, ""); } -void InfoStringFromStructConverterBase::FillFromStringBuffer(const std::string& key, const size_t offset, - const size_t bufferSize) -{ - const auto* str = reinterpret_cast<const char*>(reinterpret_cast<uintptr_t>(m_structure) + offset); - const auto strLen = strnlen(str, bufferSize); - m_info_string.SetValueForKey(key, std::string(str, strLen)); +void InfoStringFromStructConverterBase::FillFromStringBuffer(const std::string &key, const size_t offset, const size_t bufferSize) { + const auto *str = reinterpret_cast<const char *>(reinterpret_cast<uintptr_t>(m_structure) + offset); + const auto strLen = strnlen(str, bufferSize); + m_info_string.SetValueForKey(key, std::string(str, strLen)); } -void InfoStringFromStructConverterBase::FillFromInt(const std::string& key, const size_t offset) -{ - const auto* num = reinterpret_cast<int*>(reinterpret_cast<uintptr_t>(m_structure) + offset); - m_info_string.SetValueForKey(key, std::to_string(*num)); +void InfoStringFromStructConverterBase::FillFromInt(const std::string &key, const size_t offset) { + const auto *num = reinterpret_cast<int *>(reinterpret_cast<uintptr_t>(m_structure) + offset); + m_info_string.SetValueForKey(key, std::to_string(*num)); } -void InfoStringFromStructConverterBase::FillFromUint(const std::string& key, const size_t offset) -{ - const auto* num = reinterpret_cast<unsigned int*>(reinterpret_cast<uintptr_t>(m_structure) + offset); - m_info_string.SetValueForKey(key, std::to_string(*num)); +void InfoStringFromStructConverterBase::FillFromUint(const std::string &key, const size_t offset) { + const auto *num = reinterpret_cast<unsigned int *>(reinterpret_cast<uintptr_t>(m_structure) + offset); + m_info_string.SetValueForKey(key, std::to_string(*num)); } -void InfoStringFromStructConverterBase::FillFromBool(const std::string& key, const size_t offset) -{ - const auto* bBool = reinterpret_cast<bool*>(reinterpret_cast<uintptr_t>(m_structure) + offset); - m_info_string.SetValueForKey(key, *bBool ? "1" : "0"); +void InfoStringFromStructConverterBase::FillFromBool(const std::string &key, const size_t offset) { + const auto *bBool = reinterpret_cast<bool *>(reinterpret_cast<uintptr_t>(m_structure) + offset); + m_info_string.SetValueForKey(key, *bBool ? "1" : "0"); } -void InfoStringFromStructConverterBase::FillFromQBoolean(const std::string& key, const size_t offset) -{ - const auto* iBool = reinterpret_cast<int*>(reinterpret_cast<uintptr_t>(m_structure) + offset); - m_info_string.SetValueForKey(key, *iBool != 0 ? "1" : "0"); +void InfoStringFromStructConverterBase::FillFromQBoolean(const std::string &key, const size_t offset) { + const auto *iBool = reinterpret_cast<int *>(reinterpret_cast<uintptr_t>(m_structure) + offset); + m_info_string.SetValueForKey(key, *iBool != 0 ? "1" : "0"); } -void InfoStringFromStructConverterBase::FillFromFloat(const std::string& key, const size_t offset) -{ - const auto* num = reinterpret_cast<float*>(reinterpret_cast<uintptr_t>(m_structure) + offset); +void InfoStringFromStructConverterBase::FillFromFloat(const std::string &key, const size_t offset) { + const auto *num = reinterpret_cast<float *>(reinterpret_cast<uintptr_t>(m_structure) + offset); - std::ostringstream ss; - ss << *num; + std::ostringstream ss; + ss << *num; - m_info_string.SetValueForKey(key, ss.str()); + m_info_string.SetValueForKey(key, ss.str()); } -void InfoStringFromStructConverterBase::FillFromMilliseconds(const std::string& key, const size_t offset) -{ - const auto* millis = reinterpret_cast<unsigned int*>(reinterpret_cast<uintptr_t>(m_structure) + offset); +void InfoStringFromStructConverterBase::FillFromMilliseconds(const std::string &key, const size_t offset) { + const auto *millis = reinterpret_cast<unsigned int *>(reinterpret_cast<uintptr_t>(m_structure) + offset); - const auto value = static_cast<float>(*millis) / 1000.0f; + const auto value = static_cast<float>(*millis) / 1000.0f; - std::ostringstream ss; - ss << value; + std::ostringstream ss; + ss << value; - m_info_string.SetValueForKey(key, ss.str()); + m_info_string.SetValueForKey(key, ss.str()); } -void InfoStringFromStructConverterBase::FillFromScriptString(const std::string& key, const size_t offset) -{ - const auto* scrStr = reinterpret_cast<scr_string_t*>(reinterpret_cast<uintptr_t>(m_structure) + offset); - m_info_string.SetValueForKey(key, m_get_scr_string(*scrStr)); +void InfoStringFromStructConverterBase::FillFromScriptString(const std::string &key, const size_t offset) { + const auto *scrStr = reinterpret_cast<scr_string_t *>(reinterpret_cast<uintptr_t>(m_structure) + offset); + m_info_string.SetValueForKey(key, m_get_scr_string(*scrStr)); } -void InfoStringFromStructConverterBase::FillFromEnumInt(const std::string& key, const size_t offset, - const char** enumValues, const size_t enumSize) -{ - const auto num = *reinterpret_cast<int*>(reinterpret_cast<uintptr_t>(m_structure) + offset); +void InfoStringFromStructConverterBase::FillFromEnumInt(const std::string &key, const size_t offset, const char **enumValues, const size_t enumSize) { + const auto num = *reinterpret_cast<int *>(reinterpret_cast<uintptr_t>(m_structure) + offset); - assert(num >= 0 && num < static_cast<int>(enumSize)); + assert(num >= 0 && num < static_cast<int>(enumSize)); - if (num >= 0 && num < static_cast<int>(enumSize)) - m_info_string.SetValueForKey(key, std::string(enumValues[num])); - else - m_info_string.SetValueForKey(key, ""); + if (num >= 0 && num < static_cast<int>(enumSize)) + m_info_string.SetValueForKey(key, std::string(enumValues[num])); + else + m_info_string.SetValueForKey(key, ""); } diff --git a/src/ObjWriting/InfoString/InfoStringFromStructConverterBase.h b/src/ObjWriting/InfoString/InfoStringFromStructConverterBase.h index f918083e6..9c60e3687 100644 --- a/src/ObjWriting/InfoString/InfoStringFromStructConverterBase.h +++ b/src/ObjWriting/InfoString/InfoStringFromStructConverterBase.h @@ -4,35 +4,34 @@ #include "InfoString/InfoString.h" #include "Zone/ZoneTypes.h" -class InfoStringFromStructConverterBase -{ +class InfoStringFromStructConverterBase { protected: - InfoString m_info_string; - const void* m_structure; - const std::function<std::string(scr_string_t)> m_get_scr_string; + InfoString m_info_string; + const void *m_structure; + const std::function<std::string(scr_string_t)> m_get_scr_string; - static const char* AssetName(const char* name); - void FillFromString(const std::string& key, size_t offset); - void FillFromStringBuffer(const std::string& key, size_t offset, size_t bufferSize); - void FillFromInt(const std::string& key, size_t offset); - void FillFromUint(const std::string&, size_t offset); - void FillFromBool(const std::string&, size_t offset); - void FillFromQBoolean(const std::string& key, size_t offset); - void FillFromFloat(const std::string& key, size_t offset); - void FillFromMilliseconds(const std::string& key, size_t offset); - void FillFromScriptString(const std::string& key, size_t offset); - void FillFromEnumInt(const std::string& key, size_t offset, const char** enumValues, size_t enumSize); + static const char *AssetName(const char *name); + void FillFromString(const std::string &key, size_t offset); + void FillFromStringBuffer(const std::string &key, size_t offset, size_t bufferSize); + void FillFromInt(const std::string &key, size_t offset); + void FillFromUint(const std::string &, size_t offset); + void FillFromBool(const std::string &, size_t offset); + void FillFromQBoolean(const std::string &key, size_t offset); + void FillFromFloat(const std::string &key, size_t offset); + void FillFromMilliseconds(const std::string &key, size_t offset); + void FillFromScriptString(const std::string &key, size_t offset); + void FillFromEnumInt(const std::string &key, size_t offset, const char **enumValues, size_t enumSize); - virtual void FillInfoString() = 0; + virtual void FillInfoString() = 0; public: - explicit InfoStringFromStructConverterBase(const void* structure); - InfoStringFromStructConverterBase(const void* structure, std::function<std::string(scr_string_t)> scriptStringValueCallback); - virtual ~InfoStringFromStructConverterBase() = default; - InfoStringFromStructConverterBase(const InfoStringFromStructConverterBase& other) = delete; - InfoStringFromStructConverterBase(InfoStringFromStructConverterBase&& other) noexcept = delete; - InfoStringFromStructConverterBase& operator=(const InfoStringFromStructConverterBase& other) = delete; - InfoStringFromStructConverterBase& operator=(InfoStringFromStructConverterBase&& other) noexcept = delete; + explicit InfoStringFromStructConverterBase(const void *structure); + InfoStringFromStructConverterBase(const void *structure, std::function<std::string(scr_string_t)> scriptStringValueCallback); + virtual ~InfoStringFromStructConverterBase() = default; + InfoStringFromStructConverterBase(const InfoStringFromStructConverterBase &other) = delete; + InfoStringFromStructConverterBase(InfoStringFromStructConverterBase &&other) noexcept = delete; + InfoStringFromStructConverterBase &operator=(const InfoStringFromStructConverterBase &other) = delete; + InfoStringFromStructConverterBase &operator=(InfoStringFromStructConverterBase &&other) noexcept = delete; - InfoString Convert(); + InfoString Convert(); }; \ No newline at end of file diff --git a/src/ObjWriting/Menu/AbstractMenuDumper.cpp b/src/ObjWriting/Menu/AbstractMenuDumper.cpp index 6f02352ed..e47de8b03 100644 --- a/src/ObjWriting/Menu/AbstractMenuDumper.cpp +++ b/src/ObjWriting/Menu/AbstractMenuDumper.cpp @@ -1,296 +1,243 @@ #include "AbstractMenuDumper.h" #include <algorithm> -#include <sstream> #include <cmath> +#include <sstream> #include "Parsing/Impl/ParserSingleInputStream.h" #include "Parsing/Simple/SimpleLexer.h" -AbstractMenuDumper::AbstractMenuDumper(std::ostream& stream) - : m_stream(stream), - m_indent(0u) -{ -} +AbstractMenuDumper::AbstractMenuDumper(std::ostream &stream) : m_stream(stream), m_indent(0u) {} -void AbstractMenuDumper::IncIndent() -{ - m_indent++; -} +void AbstractMenuDumper::IncIndent() { m_indent++; } -void AbstractMenuDumper::DecIndent() -{ - if (m_indent > 0) - m_indent--; +void AbstractMenuDumper::DecIndent() { + if (m_indent > 0) + m_indent--; } -void AbstractMenuDumper::Indent() const -{ - for (auto i = 0u; i < m_indent; i++) - m_stream << " "; +void AbstractMenuDumper::Indent() const { + for (auto i = 0u; i < m_indent; i++) + m_stream << " "; } -void AbstractMenuDumper::StartScope(const std::string& scopeName) -{ - Indent(); - m_stream << scopeName << "\n"; - Indent(); - m_stream << "{\n"; - IncIndent(); +void AbstractMenuDumper::StartScope(const std::string &scopeName) { + Indent(); + m_stream << scopeName << "\n"; + Indent(); + m_stream << "{\n"; + IncIndent(); } -void AbstractMenuDumper::StartMenuDefScope() -{ - StartScope("menuDef"); -} +void AbstractMenuDumper::StartMenuDefScope() { StartScope("menuDef"); } -void AbstractMenuDumper::StartItemDefScope() -{ - StartScope("itemDef"); -} +void AbstractMenuDumper::StartItemDefScope() { StartScope("itemDef"); } -void AbstractMenuDumper::StartFunctionDefScope() -{ - StartScope("functionDef"); -} +void AbstractMenuDumper::StartFunctionDefScope() { StartScope("functionDef"); } -void AbstractMenuDumper::EndScope() -{ - DecIndent(); - Indent(); - m_stream << "}\n"; +void AbstractMenuDumper::EndScope() { + DecIndent(); + Indent(); + m_stream << "}\n"; } -std::vector<std::string> AbstractMenuDumper::CreateScriptTokenList(const char* script) -{ - const std::string scriptString(script); - std::istringstream stringStream(scriptString); - ParserSingleInputStream inputStream(stringStream, "MenuScript"); - - SimpleLexer::Config lexerConfig; - lexerConfig.m_emit_new_line_tokens = false; - lexerConfig.m_read_strings = true; - lexerConfig.m_string_escape_sequences = true; - lexerConfig.m_read_integer_numbers = false; - lexerConfig.m_read_floating_point_numbers = false; - SimpleLexer lexer(&inputStream, std::move(lexerConfig)); - - std::vector<std::string> result; - auto hasLexerTokens = true; - while (hasLexerTokens) - { - const auto& token = lexer.GetToken(0); - switch (token.m_type) - { - case SimpleParserValueType::IDENTIFIER: - result.emplace_back(token.IdentifierValue()); - break; - - case SimpleParserValueType::STRING: - result.emplace_back(token.StringValue()); - break; - - case SimpleParserValueType::CHARACTER: - result.emplace_back(1, token.CharacterValue()); - break; - - case SimpleParserValueType::INVALID: - case SimpleParserValueType::END_OF_FILE: - hasLexerTokens = false; - break; - - default: - assert(false); - break; - } - - lexer.PopTokens(1); +std::vector<std::string> AbstractMenuDumper::CreateScriptTokenList(const char *script) { + const std::string scriptString(script); + std::istringstream stringStream(scriptString); + ParserSingleInputStream inputStream(stringStream, "MenuScript"); + + SimpleLexer::Config lexerConfig; + lexerConfig.m_emit_new_line_tokens = false; + lexerConfig.m_read_strings = true; + lexerConfig.m_string_escape_sequences = true; + lexerConfig.m_read_integer_numbers = false; + lexerConfig.m_read_floating_point_numbers = false; + SimpleLexer lexer(&inputStream, std::move(lexerConfig)); + + std::vector<std::string> result; + auto hasLexerTokens = true; + while (hasLexerTokens) { + const auto &token = lexer.GetToken(0); + switch (token.m_type) { + case SimpleParserValueType::IDENTIFIER: + result.emplace_back(token.IdentifierValue()); + break; + + case SimpleParserValueType::STRING: + result.emplace_back(token.StringValue()); + break; + + case SimpleParserValueType::CHARACTER: + result.emplace_back(1, token.CharacterValue()); + break; + + case SimpleParserValueType::INVALID: + case SimpleParserValueType::END_OF_FILE: + hasLexerTokens = false; + break; + + default: + assert(false); + break; } - return result; + lexer.PopTokens(1); + } + + return result; } -bool AbstractMenuDumper::DoesTokenNeedQuotationMarks(const std::string& token) -{ - if (token.empty()) - return true; +bool AbstractMenuDumper::DoesTokenNeedQuotationMarks(const std::string &token) { + if (token.empty()) + return true; - const auto hasAlNumCharacter = std::any_of(token.begin(), token.end(), [](const char& c) - { - return isalnum(c); - }); + const auto hasAlNumCharacter = std::any_of(token.begin(), token.end(), [](const char &c) { return isalnum(c); }); - if (!hasAlNumCharacter) - return false; + if (!hasAlNumCharacter) + return false; - const auto hasNonIdentifierCharacter = std::any_of(token.begin(), token.end(), [](const char& c) - { - return !isalnum(c) && c != '_'; - }); + const auto hasNonIdentifierCharacter = std::any_of(token.begin(), token.end(), [](const char &c) { return !isalnum(c) && c != '_'; }); - return hasNonIdentifierCharacter; + return hasNonIdentifierCharacter; } -void AbstractMenuDumper::WriteEscapedString(const std::string_view& str) const -{ - m_stream << "\""; - - for (const auto& c : str) - { - switch (c) - { - case '\r': - m_stream << "\\r"; - break; - case '\n': - m_stream << "\\n"; - break; - case '\t': - m_stream << "\\t"; - break; - case '\f': - m_stream << "\\f"; - break; - case '"': - m_stream << "\\\""; - break; - default: - m_stream << c; - break; - } +void AbstractMenuDumper::WriteEscapedString(const std::string_view &str) const { + m_stream << "\""; + + for (const auto &c : str) { + switch (c) { + case '\r': + m_stream << "\\r"; + break; + case '\n': + m_stream << "\\n"; + break; + case '\t': + m_stream << "\\t"; + break; + case '\f': + m_stream << "\\f"; + break; + case '"': + m_stream << "\\\""; + break; + default: + m_stream << c; + break; } + } - m_stream << "\""; + m_stream << "\""; } -const std::string& AbstractMenuDumper::BoolValue(const bool value) -{ - return value ? BOOL_VALUE_TRUE : BOOL_VALUE_FALSE; -} +const std::string &AbstractMenuDumper::BoolValue(const bool value) { return value ? BOOL_VALUE_TRUE : BOOL_VALUE_FALSE; } -void AbstractMenuDumper::WriteKey(const std::string& keyName) const -{ - m_stream << keyName; +void AbstractMenuDumper::WriteKey(const std::string &keyName) const { + m_stream << keyName; - if (keyName.size() < MENU_KEY_SPACING) - { - const auto spacingLength = MENU_KEY_SPACING - keyName.size(); - for (auto i = 0u; i < spacingLength; i++) - m_stream << " "; - } + if (keyName.size() < MENU_KEY_SPACING) { + const auto spacingLength = MENU_KEY_SPACING - keyName.size(); + for (auto i = 0u; i < spacingLength; i++) + m_stream << " "; + } } -void AbstractMenuDumper::WriteStringProperty(const std::string& propertyKey, const std::string& propertyValue) const -{ - if (propertyValue.empty()) - return; +void AbstractMenuDumper::WriteStringProperty(const std::string &propertyKey, const std::string &propertyValue) const { + if (propertyValue.empty()) + return; - Indent(); - WriteKey(propertyKey); + Indent(); + WriteKey(propertyKey); - WriteEscapedString(propertyValue); - m_stream << "\n"; + WriteEscapedString(propertyValue); + m_stream << "\n"; } -void AbstractMenuDumper::WriteStringProperty(const std::string& propertyKey, const char* propertyValue) const -{ - if (propertyValue == nullptr || propertyValue[0] == '\0') - return; +void AbstractMenuDumper::WriteStringProperty(const std::string &propertyKey, const char *propertyValue) const { + if (propertyValue == nullptr || propertyValue[0] == '\0') + return; - Indent(); - WriteKey(propertyKey); + Indent(); + WriteKey(propertyKey); - WriteEscapedString(propertyValue); - m_stream << "\n"; + WriteEscapedString(propertyValue); + m_stream << "\n"; } -void AbstractMenuDumper::WriteBoolProperty(const std::string& propertyKey, const bool propertyValue, const bool defaultValue) const -{ - if (propertyValue == defaultValue) - return; +void AbstractMenuDumper::WriteBoolProperty(const std::string &propertyKey, const bool propertyValue, const bool defaultValue) const { + if (propertyValue == defaultValue) + return; - Indent(); - WriteKey(propertyKey); - m_stream << BoolValue(propertyValue) << "\n"; + Indent(); + WriteKey(propertyKey); + m_stream << BoolValue(propertyValue) << "\n"; } -void AbstractMenuDumper::WriteIntProperty(const std::string& propertyKey, const int propertyValue, const int defaultValue) const -{ - if (propertyValue == defaultValue) - return; +void AbstractMenuDumper::WriteIntProperty(const std::string &propertyKey, const int propertyValue, const int defaultValue) const { + if (propertyValue == defaultValue) + return; - Indent(); - WriteKey(propertyKey); - m_stream << propertyValue << "\n"; + Indent(); + WriteKey(propertyKey); + m_stream << propertyValue << "\n"; } -void AbstractMenuDumper::WriteFloatProperty(const std::string& propertyKey, const float propertyValue, const float defaultValue) const -{ - if (std::fabs(propertyValue - defaultValue) < std::numeric_limits<float>::epsilon()) - return; +void AbstractMenuDumper::WriteFloatProperty(const std::string &propertyKey, const float propertyValue, const float defaultValue) const { + if (std::fabs(propertyValue - defaultValue) < std::numeric_limits<float>::epsilon()) + return; - Indent(); - WriteKey(propertyKey); - m_stream << propertyValue << "\n"; + Indent(); + WriteKey(propertyKey); + m_stream << propertyValue << "\n"; } -void AbstractMenuDumper::WriteColorProperty(const std::string& propertyKey, const float (&propertyValue)[4], const float (&defaultValue)[4]) const -{ - if (std::fabs(propertyValue[0] - defaultValue[0]) < std::numeric_limits<float>::epsilon() - && std::fabs(propertyValue[1] - defaultValue[1]) < std::numeric_limits<float>::epsilon() - && std::fabs(propertyValue[2] - defaultValue[2]) < std::numeric_limits<float>::epsilon() - && std::fabs(propertyValue[3] - defaultValue[3]) < std::numeric_limits<float>::epsilon()) - { - return; - } +void AbstractMenuDumper::WriteColorProperty(const std::string &propertyKey, const float (&propertyValue)[4], const float (&defaultValue)[4]) const { + if (std::fabs(propertyValue[0] - defaultValue[0]) < std::numeric_limits<float>::epsilon() && + std::fabs(propertyValue[1] - defaultValue[1]) < std::numeric_limits<float>::epsilon() && + std::fabs(propertyValue[2] - defaultValue[2]) < std::numeric_limits<float>::epsilon() && + std::fabs(propertyValue[3] - defaultValue[3]) < std::numeric_limits<float>::epsilon()) { + return; + } - Indent(); - WriteKey(propertyKey); - m_stream << propertyValue[0] << " " << propertyValue[1] << " " << propertyValue[2] << " " << propertyValue[3] << "\n"; + Indent(); + WriteKey(propertyKey); + m_stream << propertyValue[0] << " " << propertyValue[1] << " " << propertyValue[2] << " " << propertyValue[3] << "\n"; } -void AbstractMenuDumper::WriteKeywordProperty(const std::string& propertyKey, const bool shouldWrite) const -{ - if (!shouldWrite) - return; +void AbstractMenuDumper::WriteKeywordProperty(const std::string &propertyKey, const bool shouldWrite) const { + if (!shouldWrite) + return; - Indent(); - WriteKey(propertyKey); - m_stream << "\n"; + Indent(); + WriteKey(propertyKey); + m_stream << "\n"; } -void AbstractMenuDumper::WriteFlagsProperty(const std::string& propertyKey, const int flagsValue) const -{ - for (auto i = 0u; i < sizeof(flagsValue) * 8; i++) - { - if (flagsValue & (1 << i)) - { - Indent(); - WriteKey(propertyKey); - m_stream << i << "\n"; - } +void AbstractMenuDumper::WriteFlagsProperty(const std::string &propertyKey, const int flagsValue) const { + for (auto i = 0u; i < sizeof(flagsValue) * 8; i++) { + if (flagsValue & (1 << i)) { + Indent(); + WriteKey(propertyKey); + m_stream << i << "\n"; } + } } -void AbstractMenuDumper::Start() -{ - Indent(); - m_stream << "{\n"; - IncIndent(); +void AbstractMenuDumper::Start() { + Indent(); + m_stream << "{\n"; + IncIndent(); } -void AbstractMenuDumper::End() -{ - for (auto i = 0u; i < m_indent; i++) - { - DecIndent(); - Indent(); - m_stream << "}\n"; - } +void AbstractMenuDumper::End() { + for (auto i = 0u; i < m_indent; i++) { + DecIndent(); + Indent(); + m_stream << "}\n"; + } } -void AbstractMenuDumper::IncludeMenu(const std::string& menuPath) const -{ - Indent(); - m_stream << "loadMenu { \"" << menuPath << "\" }\n"; +void AbstractMenuDumper::IncludeMenu(const std::string &menuPath) const { + Indent(); + m_stream << "loadMenu { \"" << menuPath << "\" }\n"; } diff --git a/src/ObjWriting/Menu/AbstractMenuDumper.h b/src/ObjWriting/Menu/AbstractMenuDumper.h index 5a826d057..b7dea6dbd 100644 --- a/src/ObjWriting/Menu/AbstractMenuDumper.h +++ b/src/ObjWriting/Menu/AbstractMenuDumper.h @@ -1,53 +1,52 @@ #pragma once -#include <string> #include <cstddef> #include <ostream> +#include <string> #include <vector> -class AbstractMenuDumper -{ +class AbstractMenuDumper { protected: - static constexpr auto MENU_KEY_SPACING = 28u; - static const inline std::string BOOL_VALUE_TRUE = "1"; - static const inline std::string BOOL_VALUE_FALSE = "0"; - static constexpr inline float COLOR_0000[4]{ 0.0f, 0.0f, 0.0f, 0.0f }; - static constexpr inline float COLOR_1111[4]{ 1.0f, 1.0f, 1.0f, 1.0f }; - - std::ostream& m_stream; - size_t m_indent; - - void IncIndent(); - void DecIndent(); - void Indent() const; - - void StartScope(const std::string& scopeName); - void StartMenuDefScope(); - void StartItemDefScope(); - void StartFunctionDefScope(); - void EndScope(); - - static std::vector<std::string> CreateScriptTokenList(const char* script); - static bool DoesTokenNeedQuotationMarks(const std::string& token); - - void WriteEscapedString(const std::string_view& str) const; - - static const std::string& BoolValue(bool value); - void WriteKey(const std::string& keyName) const; - void WriteStringProperty(const std::string& propertyKey, const std::string& propertyValue) const; - void WriteStringProperty(const std::string& propertyKey, const char* propertyValue) const; - void WriteBoolProperty(const std::string& propertyKey, bool propertyValue, bool defaultValue) const; - void WriteIntProperty(const std::string& propertyKey, int propertyValue, int defaultValue) const; - void WriteFloatProperty(const std::string& propertyKey, float propertyValue, float defaultValue) const; - void WriteColorProperty(const std::string& propertyKey, const float(&propertyValue)[4], const float(&defaultValue)[4]) const; - void WriteKeywordProperty(const std::string& propertyKey, bool shouldWrite) const; - void WriteFlagsProperty(const std::string& propertyKey, int flagsValue) const; - - explicit AbstractMenuDumper(std::ostream& stream); + static constexpr auto MENU_KEY_SPACING = 28u; + static const inline std::string BOOL_VALUE_TRUE = "1"; + static const inline std::string BOOL_VALUE_FALSE = "0"; + static constexpr inline float COLOR_0000[4]{0.0f, 0.0f, 0.0f, 0.0f}; + static constexpr inline float COLOR_1111[4]{1.0f, 1.0f, 1.0f, 1.0f}; + + std::ostream &m_stream; + size_t m_indent; + + void IncIndent(); + void DecIndent(); + void Indent() const; + + void StartScope(const std::string &scopeName); + void StartMenuDefScope(); + void StartItemDefScope(); + void StartFunctionDefScope(); + void EndScope(); + + static std::vector<std::string> CreateScriptTokenList(const char *script); + static bool DoesTokenNeedQuotationMarks(const std::string &token); + + void WriteEscapedString(const std::string_view &str) const; + + static const std::string &BoolValue(bool value); + void WriteKey(const std::string &keyName) const; + void WriteStringProperty(const std::string &propertyKey, const std::string &propertyValue) const; + void WriteStringProperty(const std::string &propertyKey, const char *propertyValue) const; + void WriteBoolProperty(const std::string &propertyKey, bool propertyValue, bool defaultValue) const; + void WriteIntProperty(const std::string &propertyKey, int propertyValue, int defaultValue) const; + void WriteFloatProperty(const std::string &propertyKey, float propertyValue, float defaultValue) const; + void WriteColorProperty(const std::string &propertyKey, const float (&propertyValue)[4], const float (&defaultValue)[4]) const; + void WriteKeywordProperty(const std::string &propertyKey, bool shouldWrite) const; + void WriteFlagsProperty(const std::string &propertyKey, int flagsValue) const; + + explicit AbstractMenuDumper(std::ostream &stream); public: - void Start(); - void End(); + void Start(); + void End(); - void IncludeMenu(const std::string& menuPath) const; + void IncludeMenu(const std::string &menuPath) const; }; \ No newline at end of file diff --git a/src/ObjWriting/Menu/MenuDumpingZoneState.cpp b/src/ObjWriting/Menu/MenuDumpingZoneState.cpp index 318bc7eb9..e962b6b6c 100644 --- a/src/ObjWriting/Menu/MenuDumpingZoneState.cpp +++ b/src/ObjWriting/Menu/MenuDumpingZoneState.cpp @@ -2,13 +2,9 @@ using namespace menu; -MenuDumpingZoneState::MenuDumpingState::MenuDumpingState(std::string path, const void* aliasMenuList) - : m_path(std::move(path)), - m_alias_menu_list(aliasMenuList) -{ -} +MenuDumpingZoneState::MenuDumpingState::MenuDumpingState(std::string path, const void *aliasMenuList) + : m_path(std::move(path)), m_alias_menu_list(aliasMenuList) {} -void MenuDumpingZoneState::CreateMenuDumpingState(const void* menuDef, std::string path, const void* aliasMenuList) -{ - m_menu_dumping_state_map.emplace(std::make_pair(menuDef, MenuDumpingState(std::move(path), aliasMenuList))); +void MenuDumpingZoneState::CreateMenuDumpingState(const void *menuDef, std::string path, const void *aliasMenuList) { + m_menu_dumping_state_map.emplace(std::make_pair(menuDef, MenuDumpingState(std::move(path), aliasMenuList))); } diff --git a/src/ObjWriting/Menu/MenuDumpingZoneState.h b/src/ObjWriting/Menu/MenuDumpingZoneState.h index 677891fda..415c0ec2d 100644 --- a/src/ObjWriting/Menu/MenuDumpingZoneState.h +++ b/src/ObjWriting/Menu/MenuDumpingZoneState.h @@ -3,22 +3,19 @@ #include "Dumping/IZoneAssetDumperState.h" -namespace menu -{ - class MenuDumpingZoneState final : public IZoneAssetDumperState - { - public: - class MenuDumpingState - { - public: - std::string m_path; - const void* m_alias_menu_list; +namespace menu { +class MenuDumpingZoneState final : public IZoneAssetDumperState { +public: + class MenuDumpingState { + public: + std::string m_path; + const void *m_alias_menu_list; - MenuDumpingState(std::string path, const void* aliasMenuList); - }; + MenuDumpingState(std::string path, const void *aliasMenuList); + }; - std::map<const void*, MenuDumpingState> m_menu_dumping_state_map; + std::map<const void *, MenuDumpingState> m_menu_dumping_state_map; - void CreateMenuDumpingState(const void* menuDef, std::string path, const void* aliasMenuList); - }; -} + void CreateMenuDumpingState(const void *menuDef, std::string path, const void *aliasMenuList); +}; +} // namespace menu diff --git a/src/ObjWriting/Model/Obj/ObjWriter.cpp b/src/ObjWriting/Model/Obj/ObjWriter.cpp index c476244d4..ff33e9216 100644 --- a/src/ObjWriting/Model/Obj/ObjWriter.cpp +++ b/src/ObjWriting/Model/Obj/ObjWriter.cpp @@ -2,158 +2,133 @@ #include "Game/IW4/CommonIW4.h" -ObjWriter::ObjWriter(std::string gameName, std::string zoneName) - : m_game_name(std::move(gameName)), - m_zone_name(std::move(zoneName)) -{ -} +ObjWriter::ObjWriter(std::string gameName, std::string zoneName) : m_game_name(std::move(gameName)), m_zone_name(std::move(zoneName)) {} -void ObjWriter::AddObject(ObjObject object) -{ - m_objects.emplace_back(std::move(object)); - m_object_data.emplace_back(); +void ObjWriter::AddObject(ObjObject object) { + m_objects.emplace_back(std::move(object)); + m_object_data.emplace_back(); } -void ObjWriter::AddMaterial(MtlMaterial material) -{ - m_materials.emplace_back(std::move(material)); -} +void ObjWriter::AddMaterial(MtlMaterial material) { m_materials.emplace_back(std::move(material)); } -void ObjWriter::AddVertex(const int objectId, const ObjVertex vertex) -{ - if (objectId < 0 || static_cast<unsigned>(objectId) >= m_object_data.size()) - return; +void ObjWriter::AddVertex(const int objectId, const ObjVertex vertex) { + if (objectId < 0 || static_cast<unsigned>(objectId) >= m_object_data.size()) + return; - m_object_data[objectId].m_vertices.Add(vertex); + m_object_data[objectId].m_vertices.Add(vertex); } -void ObjWriter::AddNormal(const int objectId, const ObjNormal normal) -{ - if (objectId < 0 || static_cast<unsigned>(objectId) >= m_object_data.size()) - return; +void ObjWriter::AddNormal(const int objectId, const ObjNormal normal) { + if (objectId < 0 || static_cast<unsigned>(objectId) >= m_object_data.size()) + return; - m_object_data[objectId].m_normals.Add(normal); + m_object_data[objectId].m_normals.Add(normal); } -void ObjWriter::AddUv(const int objectId, const ObjUv uv) -{ - if (objectId < 0 || static_cast<unsigned>(objectId) >= m_object_data.size()) - return; +void ObjWriter::AddUv(const int objectId, const ObjUv uv) { + if (objectId < 0 || static_cast<unsigned>(objectId) >= m_object_data.size()) + return; - m_object_data[objectId].m_uvs.Add(uv); + m_object_data[objectId].m_uvs.Add(uv); } -void ObjWriter::AddFace(const int objectId, const ObjFace face) -{ - if (objectId < 0 || static_cast<unsigned>(objectId) >= m_object_data.size()) - return; +void ObjWriter::AddFace(const int objectId, const ObjFace face) { + if (objectId < 0 || static_cast<unsigned>(objectId) >= m_object_data.size()) + return; - m_object_data[objectId].m_faces.push_back(face); + m_object_data[objectId].m_faces.push_back(face); } -void ObjWriter::GetObjObjectDataOffsets(std::vector<ObjObjectDataOffsets>& inputOffsets, std::vector<ObjObjectDataOffsets>& distinctOffsets) -{ - ObjObjectDataOffsets currentInputOffsets{}; - ObjObjectDataOffsets currentDistinctOffsets{}; - - for (const auto& objectData : m_object_data) - { - inputOffsets.push_back(currentInputOffsets); - distinctOffsets.push_back(currentDistinctOffsets); - - currentInputOffsets.vertexOffset += objectData.m_vertices.GetInputValueCount(); - currentInputOffsets.normalOffset += objectData.m_normals.GetInputValueCount(); - currentInputOffsets.uvOffset += objectData.m_uvs.GetInputValueCount(); - currentDistinctOffsets.vertexOffset += objectData.m_vertices.GetDistinctValueCount(); - currentDistinctOffsets.normalOffset += objectData.m_normals.GetDistinctValueCount(); - currentDistinctOffsets.uvOffset += objectData.m_uvs.GetDistinctValueCount(); - } +void ObjWriter::GetObjObjectDataOffsets(std::vector<ObjObjectDataOffsets> &inputOffsets, std::vector<ObjObjectDataOffsets> &distinctOffsets) { + ObjObjectDataOffsets currentInputOffsets{}; + ObjObjectDataOffsets currentDistinctOffsets{}; + + for (const auto &objectData : m_object_data) { + inputOffsets.push_back(currentInputOffsets); + distinctOffsets.push_back(currentDistinctOffsets); + + currentInputOffsets.vertexOffset += objectData.m_vertices.GetInputValueCount(); + currentInputOffsets.normalOffset += objectData.m_normals.GetInputValueCount(); + currentInputOffsets.uvOffset += objectData.m_uvs.GetInputValueCount(); + currentDistinctOffsets.vertexOffset += objectData.m_vertices.GetDistinctValueCount(); + currentDistinctOffsets.normalOffset += objectData.m_normals.GetDistinctValueCount(); + currentDistinctOffsets.uvOffset += objectData.m_uvs.GetDistinctValueCount(); + } } -void ObjWriter::WriteObj(std::ostream& stream) -{ - WriteObj(stream, std::string()); -} - -void ObjWriter::WriteObj(std::ostream& stream, const std::string& mtlName) -{ - stream << "# OpenAssetTools OBJ File ( " << m_game_name << ")\n"; - stream << "# Game Origin: " << m_game_name << "\n"; - stream << "# Zone Origin: " << m_zone_name << "\n"; - - if (!mtlName.empty()) - stream << "mtllib " << mtlName << "\n"; - - std::vector<ObjObjectDataOffsets> inputOffsetsByObject; - std::vector<ObjObjectDataOffsets> distinctOffsetsByObject; - GetObjObjectDataOffsets(inputOffsetsByObject, distinctOffsetsByObject); - - auto objectIndex = 0; - for (const auto& object : m_objects) - { - const auto& objectData = m_object_data[objectIndex]; - stream << "o " << object.name << "\n"; - - for (const auto& v : objectData.m_vertices.GetDistinctValues()) - stream << "v " << v.coordinates[0] << " " << v.coordinates[1] << " " << v.coordinates[2] << "\n"; - for (const auto& uv : objectData.m_uvs.GetDistinctValues()) - stream << "vt " << uv.uv[0] << " " << uv.uv[1] << "\n"; - for (const auto& n : objectData.m_normals.GetDistinctValues()) - stream << "vn " << n.normal[0] << " " << n.normal[1] << " " << n.normal[2] << "\n"; - - if (object.materialIndex >= 0 && static_cast<unsigned>(object.materialIndex) < m_materials.size()) - stream << "usemtl " << m_materials[object.materialIndex].materialName << "\n"; - - for (const auto& f : objectData.m_faces) - { - const size_t v[3] - { - objectData.m_vertices.GetDistinctPositionByInputPosition(f.vertexIndex[0] - inputOffsetsByObject[objectIndex].vertexOffset) + distinctOffsetsByObject[objectIndex].vertexOffset + 1, - objectData.m_vertices.GetDistinctPositionByInputPosition(f.vertexIndex[1] - inputOffsetsByObject[objectIndex].vertexOffset) + distinctOffsetsByObject[objectIndex].vertexOffset + 1, - objectData.m_vertices.GetDistinctPositionByInputPosition(f.vertexIndex[2] - inputOffsetsByObject[objectIndex].vertexOffset) + distinctOffsetsByObject[objectIndex].vertexOffset + 1 - }; - const size_t n[3] - { - objectData.m_normals.GetDistinctPositionByInputPosition(f.normalIndex[0] - inputOffsetsByObject[objectIndex].normalOffset) + distinctOffsetsByObject[objectIndex].normalOffset + 1, - objectData.m_normals.GetDistinctPositionByInputPosition(f.normalIndex[1] - inputOffsetsByObject[objectIndex].normalOffset) + distinctOffsetsByObject[objectIndex].normalOffset + 1, - objectData.m_normals.GetDistinctPositionByInputPosition(f.normalIndex[2] - inputOffsetsByObject[objectIndex].normalOffset) + distinctOffsetsByObject[objectIndex].normalOffset + 1 - }; - const size_t uv[3] - { - objectData.m_uvs.GetDistinctPositionByInputPosition(f.uvIndex[0] - inputOffsetsByObject[objectIndex].uvOffset) + distinctOffsetsByObject[objectIndex].uvOffset + 1, - objectData.m_uvs.GetDistinctPositionByInputPosition(f.uvIndex[1] - inputOffsetsByObject[objectIndex].uvOffset) + distinctOffsetsByObject[objectIndex].uvOffset + 1, - objectData.m_uvs.GetDistinctPositionByInputPosition(f.uvIndex[2] - inputOffsetsByObject[objectIndex].uvOffset) + distinctOffsetsByObject[objectIndex].uvOffset + 1 - }; - - stream << "f " << v[0] << "/" << uv[0] << "/" << n[0] - << " " << v[1] << "/" << uv[1] << "/" << n[1] - << " " << v[2] << "/" << uv[2] << "/" << n[2] - << "\n"; - } - - objectIndex++; +void ObjWriter::WriteObj(std::ostream &stream) { WriteObj(stream, std::string()); } + +void ObjWriter::WriteObj(std::ostream &stream, const std::string &mtlName) { + stream << "# OpenAssetTools OBJ File ( " << m_game_name << ")\n"; + stream << "# Game Origin: " << m_game_name << "\n"; + stream << "# Zone Origin: " << m_zone_name << "\n"; + + if (!mtlName.empty()) + stream << "mtllib " << mtlName << "\n"; + + std::vector<ObjObjectDataOffsets> inputOffsetsByObject; + std::vector<ObjObjectDataOffsets> distinctOffsetsByObject; + GetObjObjectDataOffsets(inputOffsetsByObject, distinctOffsetsByObject); + + auto objectIndex = 0; + for (const auto &object : m_objects) { + const auto &objectData = m_object_data[objectIndex]; + stream << "o " << object.name << "\n"; + + for (const auto &v : objectData.m_vertices.GetDistinctValues()) + stream << "v " << v.coordinates[0] << " " << v.coordinates[1] << " " << v.coordinates[2] << "\n"; + for (const auto &uv : objectData.m_uvs.GetDistinctValues()) + stream << "vt " << uv.uv[0] << " " << uv.uv[1] << "\n"; + for (const auto &n : objectData.m_normals.GetDistinctValues()) + stream << "vn " << n.normal[0] << " " << n.normal[1] << " " << n.normal[2] << "\n"; + + if (object.materialIndex >= 0 && static_cast<unsigned>(object.materialIndex) < m_materials.size()) + stream << "usemtl " << m_materials[object.materialIndex].materialName << "\n"; + + for (const auto &f : objectData.m_faces) { + const size_t v[3]{objectData.m_vertices.GetDistinctPositionByInputPosition(f.vertexIndex[0] - inputOffsetsByObject[objectIndex].vertexOffset) + + distinctOffsetsByObject[objectIndex].vertexOffset + 1, + objectData.m_vertices.GetDistinctPositionByInputPosition(f.vertexIndex[1] - inputOffsetsByObject[objectIndex].vertexOffset) + + distinctOffsetsByObject[objectIndex].vertexOffset + 1, + objectData.m_vertices.GetDistinctPositionByInputPosition(f.vertexIndex[2] - inputOffsetsByObject[objectIndex].vertexOffset) + + distinctOffsetsByObject[objectIndex].vertexOffset + 1}; + const size_t n[3]{objectData.m_normals.GetDistinctPositionByInputPosition(f.normalIndex[0] - inputOffsetsByObject[objectIndex].normalOffset) + + distinctOffsetsByObject[objectIndex].normalOffset + 1, + objectData.m_normals.GetDistinctPositionByInputPosition(f.normalIndex[1] - inputOffsetsByObject[objectIndex].normalOffset) + + distinctOffsetsByObject[objectIndex].normalOffset + 1, + objectData.m_normals.GetDistinctPositionByInputPosition(f.normalIndex[2] - inputOffsetsByObject[objectIndex].normalOffset) + + distinctOffsetsByObject[objectIndex].normalOffset + 1}; + const size_t uv[3]{objectData.m_uvs.GetDistinctPositionByInputPosition(f.uvIndex[0] - inputOffsetsByObject[objectIndex].uvOffset) + + distinctOffsetsByObject[objectIndex].uvOffset + 1, + objectData.m_uvs.GetDistinctPositionByInputPosition(f.uvIndex[1] - inputOffsetsByObject[objectIndex].uvOffset) + + distinctOffsetsByObject[objectIndex].uvOffset + 1, + objectData.m_uvs.GetDistinctPositionByInputPosition(f.uvIndex[2] - inputOffsetsByObject[objectIndex].uvOffset) + + distinctOffsetsByObject[objectIndex].uvOffset + 1}; + + stream << "f " << v[0] << "/" << uv[0] << "/" << n[0] << " " << v[1] << "/" << uv[1] << "/" << n[1] << " " << v[2] << "/" << uv[2] << "/" << n[2] << "\n"; } + + objectIndex++; + } } -void ObjWriter::WriteMtl(std::ostream& stream) -{ - stream << "# OpenAssetTools MAT File ( " << m_game_name << ")\n"; - stream << "# Game Origin: " << m_game_name << "\n"; - stream << "# Zone Origin: " << m_zone_name << "\n"; - stream << "# Material count: " << m_materials.size() << "\n"; +void ObjWriter::WriteMtl(std::ostream &stream) { + stream << "# OpenAssetTools MAT File ( " << m_game_name << ")\n"; + stream << "# Game Origin: " << m_game_name << "\n"; + stream << "# Zone Origin: " << m_zone_name << "\n"; + stream << "# Material count: " << m_materials.size() << "\n"; - for (const auto& material : m_materials) - { - stream << "\n"; - stream << "newmtl " << material.materialName << "\n"; + for (const auto &material : m_materials) { + stream << "\n"; + stream << "newmtl " << material.materialName << "\n"; - if (!material.colorMapName.empty()) - stream << "map_Kd ../images/" << material.colorMapName << ".dds\n"; + if (!material.colorMapName.empty()) + stream << "map_Kd ../images/" << material.colorMapName << ".dds\n"; - if (!material.normalMapName.empty()) - stream << "map_bump ../images/" << material.normalMapName << ".dds\n"; + if (!material.normalMapName.empty()) + stream << "map_bump ../images/" << material.normalMapName << ".dds\n"; - if (!material.specularMapName.empty()) - stream << "map_Ks ../images/" << material.specularMapName << ".dds\n"; - } + if (!material.specularMapName.empty()) + stream << "map_Ks ../images/" << material.specularMapName << ".dds\n"; + } } diff --git a/src/ObjWriting/Model/Obj/ObjWriter.h b/src/ObjWriting/Model/Obj/ObjWriter.h index 5cb1660a6..915bd86a0 100644 --- a/src/ObjWriting/Model/Obj/ObjWriter.h +++ b/src/ObjWriting/Model/Obj/ObjWriter.h @@ -1,48 +1,45 @@ #pragma once -#include <vector> #include <ostream> +#include <vector> #include "Model/Obj/ObjCommon.h" #include "Utils/DistinctMapper.h" -class ObjWriter -{ +class ObjWriter { protected: - struct ObjObjectData - { - DistinctMapper<ObjVertex> m_vertices; - DistinctMapper<ObjNormal> m_normals; - DistinctMapper<ObjUv> m_uvs; - std::vector<ObjFace> m_faces; - }; - - struct ObjObjectDataOffsets - { - size_t vertexOffset; - size_t normalOffset; - size_t uvOffset; - }; - - std::string m_game_name; - std::string m_zone_name; - std::vector<ObjObject> m_objects; - std::vector<ObjObjectData> m_object_data; - std::vector<MtlMaterial> m_materials; - - void GetObjObjectDataOffsets(std::vector<ObjObjectDataOffsets>& inputOffsets, std::vector<ObjObjectDataOffsets>& distinctOffsets); + struct ObjObjectData { + DistinctMapper<ObjVertex> m_vertices; + DistinctMapper<ObjNormal> m_normals; + DistinctMapper<ObjUv> m_uvs; + std::vector<ObjFace> m_faces; + }; + + struct ObjObjectDataOffsets { + size_t vertexOffset; + size_t normalOffset; + size_t uvOffset; + }; + + std::string m_game_name; + std::string m_zone_name; + std::vector<ObjObject> m_objects; + std::vector<ObjObjectData> m_object_data; + std::vector<MtlMaterial> m_materials; + + void GetObjObjectDataOffsets(std::vector<ObjObjectDataOffsets> &inputOffsets, std::vector<ObjObjectDataOffsets> &distinctOffsets); public: - ObjWriter(std::string gameName, std::string zoneName); - - void AddObject(ObjObject object); - void AddMaterial(MtlMaterial material); - void AddVertex(int objectId, ObjVertex vertex); - void AddNormal(int objectId, ObjNormal normal); - void AddUv(int objectId, ObjUv uv); - void AddFace(int objectId, ObjFace face); - - void WriteObj(std::ostream& stream); - void WriteObj(std::ostream& stream, const std::string& mtlName); - void WriteMtl(std::ostream& stream); + ObjWriter(std::string gameName, std::string zoneName); + + void AddObject(ObjObject object); + void AddMaterial(MtlMaterial material); + void AddVertex(int objectId, ObjVertex vertex); + void AddNormal(int objectId, ObjNormal normal); + void AddUv(int objectId, ObjUv uv); + void AddFace(int objectId, ObjFace face); + + void WriteObj(std::ostream &stream); + void WriteObj(std::ostream &stream, const std::string &mtlName); + void WriteMtl(std::ostream &stream); }; diff --git a/src/ObjWriting/Model/XModel/AbstractXModelWriter.cpp b/src/ObjWriting/Model/XModel/AbstractXModelWriter.cpp index 1575b471e..a733c171d 100644 --- a/src/ObjWriting/Model/XModel/AbstractXModelWriter.cpp +++ b/src/ObjWriting/Model/XModel/AbstractXModelWriter.cpp @@ -1,34 +1,15 @@ #include "AbstractXModelWriter.h" -AbstractXModelWriter::AbstractXModelWriter() -= default; +AbstractXModelWriter::AbstractXModelWriter() = default; -void AbstractXModelWriter::AddObject(XModelObject object) -{ - m_objects.emplace_back(std::move(object)); -} +void AbstractXModelWriter::AddObject(XModelObject object) { m_objects.emplace_back(std::move(object)); } -void AbstractXModelWriter::AddBone(XModelBone bone) -{ - m_bones.emplace_back(std::move(bone)); -} +void AbstractXModelWriter::AddBone(XModelBone bone) { m_bones.emplace_back(std::move(bone)); } -void AbstractXModelWriter::AddMaterial(XModelMaterial material) -{ - m_materials.emplace_back(std::move(material)); -} +void AbstractXModelWriter::AddMaterial(XModelMaterial material) { m_materials.emplace_back(std::move(material)); } -void AbstractXModelWriter::AddVertex(XModelVertex vertex) -{ - m_vertices.emplace_back(vertex); -} +void AbstractXModelWriter::AddVertex(XModelVertex vertex) { m_vertices.emplace_back(vertex); } -void AbstractXModelWriter::AddVertexBoneWeights(XModelVertexBoneWeights vertexBoneWeights) -{ - m_vertex_bone_weights.emplace_back(vertexBoneWeights); -} +void AbstractXModelWriter::AddVertexBoneWeights(XModelVertexBoneWeights vertexBoneWeights) { m_vertex_bone_weights.emplace_back(vertexBoneWeights); } -void AbstractXModelWriter::AddFace(XModelFace face) -{ - m_faces.emplace_back(face); -} +void AbstractXModelWriter::AddFace(XModelFace face) { m_faces.emplace_back(face); } diff --git a/src/ObjWriting/Model/XModel/AbstractXModelWriter.h b/src/ObjWriting/Model/XModel/AbstractXModelWriter.h index ab2c30e3a..93e4f7a83 100644 --- a/src/ObjWriting/Model/XModel/AbstractXModelWriter.h +++ b/src/ObjWriting/Model/XModel/AbstractXModelWriter.h @@ -4,23 +4,22 @@ #include "Model/XModel/XModelCommon.h" -class AbstractXModelWriter -{ +class AbstractXModelWriter { protected: - std::vector<XModelObject> m_objects; - std::vector<XModelBone> m_bones; - std::vector<XModelMaterial> m_materials; - std::vector<XModelVertex> m_vertices; - std::vector<XModelVertexBoneWeights> m_vertex_bone_weights; - std::vector<XModelFace> m_faces; + std::vector<XModelObject> m_objects; + std::vector<XModelBone> m_bones; + std::vector<XModelMaterial> m_materials; + std::vector<XModelVertex> m_vertices; + std::vector<XModelVertexBoneWeights> m_vertex_bone_weights; + std::vector<XModelFace> m_faces; public: - AbstractXModelWriter(); + AbstractXModelWriter(); - void AddObject(XModelObject object); - void AddBone(XModelBone bone); - void AddMaterial(XModelMaterial material); - void AddVertex(XModelVertex vertex); - void AddVertexBoneWeights(XModelVertexBoneWeights vertexBoneWeights); - void AddFace(XModelFace face); + void AddObject(XModelObject object); + void AddBone(XModelBone bone); + void AddMaterial(XModelMaterial material); + void AddVertex(XModelVertex vertex); + void AddVertexBoneWeights(XModelVertexBoneWeights vertexBoneWeights); + void AddFace(XModelFace face); }; diff --git a/src/ObjWriting/Model/XModel/XModelExportWriter.cpp b/src/ObjWriting/Model/XModel/XModelExportWriter.cpp index b85d46852..f663ac04c 100644 --- a/src/ObjWriting/Model/XModel/XModelExportWriter.cpp +++ b/src/ObjWriting/Model/XModel/XModelExportWriter.cpp @@ -5,247 +5,187 @@ #include "Math/Quaternion.h" -class XModelExportWriterBase : public XModelExportWriter -{ +class XModelExportWriterBase : public XModelExportWriter { protected: - std::string m_game_name; - std::string m_zone_name; - - VertexMerger m_vertex_merger; - - void PrepareVertexMerger() - { - m_vertex_merger = VertexMerger(m_vertices.size()); - - auto vertexOffset = 0u; - for (const auto& vertex : m_vertices) - { - XModelVertexBoneWeights weights{ - nullptr, - 0 - }; - - if(vertexOffset < m_vertex_bone_weights.size()) - weights = m_vertex_bone_weights[vertexOffset]; - - m_vertex_merger.Add(VertexMergerPos{ - vertex.coordinates[0], - vertex.coordinates[1], - vertex.coordinates[2], - weights.weights, - weights.weightCount - }); - - vertexOffset++; - } - } + std::string m_game_name; + std::string m_zone_name; - void WriteHeader(std::ostream& stream, const int version) const - { - stream << "// OpenAssetTools XMODEL_EXPORT File\n"; - stream << "// Game Origin: " << m_game_name << "\n"; - stream << "// Zone Origin: " << m_zone_name << "\n"; - stream << "MODEL\n"; - stream << "VERSION " << version << "\n"; - stream << "\n"; - } + VertexMerger m_vertex_merger; - void WriteBones(std::ostream& stream) const - { - stream << "NUMBONES " << m_bones.size() << "\n"; - size_t boneNum = 0u; - for (const auto& bone : m_bones) - { - stream << "BONE " << boneNum << " "; - if (bone.parentIndex < 0) - stream << "-1"; - else - stream << bone.parentIndex; - - stream << " \"" << bone.name << "\"\n"; - boneNum++; - } - stream << "\n"; - - boneNum = 0u; - for (const auto& bone : m_bones) - { - stream << "BONE " << boneNum << "\n"; - stream << "OFFSET "; - stream << std::setprecision(6) << std::fixed << bone.globalOffset[0] - << ", " << std::setprecision(6) << std::fixed << bone.globalOffset[1] - << ", " << std::setprecision(6) << std::fixed << bone.globalOffset[2] << "\n"; - - stream << "SCALE "; - stream << std::setprecision(6) << std::fixed << bone.scale[0] - << ", " << std::setprecision(6) << std::fixed << bone.scale[1] - << ", " << std::setprecision(6) << std::fixed << bone.scale[2] << "\n"; - - const Matrix32 mat = bone.globalRotation.ToMatrix(); - stream << "X " << std::setprecision(6) << std::fixed << mat.m_data[0][0] - << ", " << std::setprecision(6) << std::fixed << mat.m_data[1][0] - << ", " << std::setprecision(6) << std::fixed << mat.m_data[2][0] << "\n"; - stream << "Y " << std::setprecision(6) << std::fixed << mat.m_data[0][1] - << ", " << std::setprecision(6) << std::fixed << mat.m_data[1][1] - << ", " << std::setprecision(6) << std::fixed << mat.m_data[2][1] << "\n"; - stream << "Z " << std::setprecision(6) << std::fixed << mat.m_data[0][2] - << ", " << std::setprecision(6) << std::fixed << mat.m_data[1][2] - << ", " << std::setprecision(6) << std::fixed << mat.m_data[2][2] << "\n"; - stream << "\n"; - boneNum++; - } - } + void PrepareVertexMerger() { + m_vertex_merger = VertexMerger(m_vertices.size()); - XModelExportWriterBase(std::string gameName, std::string zoneName) - : m_game_name(std::move(gameName)), - m_zone_name(std::move(zoneName)) - { - } -}; + auto vertexOffset = 0u; + for (const auto &vertex : m_vertices) { + XModelVertexBoneWeights weights{nullptr, 0}; -class XModelExportWriter6 final : public XModelExportWriterBase -{ - void WriteVertices(std::ostream& stream) const - { - const auto& distinctVertexValues = m_vertex_merger.GetDistinctValues(); - stream << "NUMVERTS " << distinctVertexValues.size() << "\n"; - size_t vertexNum = 0u; - for (const auto& vertexPos : distinctVertexValues) - { - stream << "VERT " << vertexNum << "\n"; - stream << "OFFSET "; - stream << std::setprecision(6) << std::fixed << vertexPos.x - << ", " << std::setprecision(6) << std::fixed << vertexPos.y - << ", " << std::setprecision(6) << std::fixed << vertexPos.z << "\n"; - stream << "BONES " << vertexPos.weightCount << "\n"; - - for (auto weightIndex = 0u; weightIndex < vertexPos.weightCount; weightIndex++) - { - stream << "BONE " << vertexPos.weights[weightIndex].boneIndex - << " " << std::setprecision(6) << std::fixed << vertexPos.weights[weightIndex].weight << "\n"; - } - stream << "\n"; - vertexNum++; - } - } + if (vertexOffset < m_vertex_bone_weights.size()) + weights = m_vertex_bone_weights[vertexOffset]; - static void WriteFaceVertex(std::ostream& stream, const size_t index, const XModelVertex& vertex) - { - stream << "VERT " << index << "\n"; - stream << "NORMAL " << std::setprecision(6) << std::fixed << vertex.normal[0] - << " " << std::setprecision(6) << std::fixed << vertex.normal[1] - << " " << std::setprecision(6) << std::fixed << vertex.normal[2] << "\n"; - stream << "COLOR " << std::setprecision(6) << std::fixed << vertex.color[0] - << " " << std::setprecision(6) << std::fixed << vertex.color[1] - << " " << std::setprecision(6) << std::fixed << vertex.color[2] - << " " << std::setprecision(6) << std::fixed << vertex.color[3] << "\n"; - stream << "UV 1 " << std::setprecision(6) << std::fixed << vertex.uv[0] - << " " << std::setprecision(6) << std::fixed << vertex.uv[1] << "\n"; - } + m_vertex_merger.Add(VertexMergerPos{vertex.coordinates[0], vertex.coordinates[1], vertex.coordinates[2], weights.weights, weights.weightCount}); - void WriteFaces(std::ostream& stream) const - { - stream << "NUMFACES " << m_faces.size() << "\n"; - for (const auto& face : m_faces) - { - const size_t distinctPositions[3] - { - m_vertex_merger.GetDistinctPositionByInputPosition(face.vertexIndex[0]), - m_vertex_merger.GetDistinctPositionByInputPosition(face.vertexIndex[1]), - m_vertex_merger.GetDistinctPositionByInputPosition(face.vertexIndex[2]) - }; - - const XModelVertex& v0 = m_vertices[face.vertexIndex[0]]; - const XModelVertex& v1 = m_vertices[face.vertexIndex[1]]; - const XModelVertex& v2 = m_vertices[face.vertexIndex[2]]; - - stream << "TRI " << face.objectIndex << " " << face.materialIndex << " 0 0\n"; - WriteFaceVertex(stream, distinctPositions[0], v0); - WriteFaceVertex(stream, distinctPositions[1], v1); - WriteFaceVertex(stream, distinctPositions[2], v2); - stream << "\n"; - } + vertexOffset++; } - - void WriteObjects(std::ostream& stream) const - { - stream << "NUMOBJECTS " << m_objects.size() << "\n"; - size_t objectNum = 0u; - for (const auto& object : m_objects) - { - stream << "OBJECT " << objectNum << " \"" << object.name << "\"\n"; - objectNum++; - } - stream << "\n"; + } + + void WriteHeader(std::ostream &stream, const int version) const { + stream << "// OpenAssetTools XMODEL_EXPORT File\n"; + stream << "// Game Origin: " << m_game_name << "\n"; + stream << "// Zone Origin: " << m_zone_name << "\n"; + stream << "MODEL\n"; + stream << "VERSION " << version << "\n"; + stream << "\n"; + } + + void WriteBones(std::ostream &stream) const { + stream << "NUMBONES " << m_bones.size() << "\n"; + size_t boneNum = 0u; + for (const auto &bone : m_bones) { + stream << "BONE " << boneNum << " "; + if (bone.parentIndex < 0) + stream << "-1"; + else + stream << bone.parentIndex; + + stream << " \"" << bone.name << "\"\n"; + boneNum++; } - - void WriteMaterials(std::ostream& stream) const - { - stream << "NUMMATERIALS " << m_materials.size() << "\n"; - size_t materialNum = 0u; - for (const auto& material : m_materials) - { - const auto colorMapPath = "../images/" + material.colorMapName + ".dds"; - stream << "MATERIAL " << materialNum << " \"" << material.name << "\" \"" << material.materialTypeName << "\" \"" << colorMapPath << "\"\n"; - stream << "COLOR " << std::setprecision(6) << std::fixed << material.color[0] - << " " << std::setprecision(6) << std::fixed << material.color[1] - << " " << std::setprecision(6) << std::fixed << material.color[2] - << " " << std::setprecision(6) << std::fixed << material.color[3] << "\n"; - stream << "TRANSPARENCY " << std::setprecision(6) << std::fixed << material.transparency[0] - << " " << std::setprecision(6) << std::fixed << material.transparency[1] - << " " << std::setprecision(6) << std::fixed << material.transparency[2] - << " " << std::setprecision(6) << std::fixed << material.transparency[3] << "\n"; - stream << "AMBIENTCOLOR " << std::setprecision(6) << std::fixed << material.ambientColor[0] - << " " << std::setprecision(6) << std::fixed << material.ambientColor[1] - << " " << std::setprecision(6) << std::fixed << material.ambientColor[2] - << " " << std::setprecision(6) << std::fixed << material.ambientColor[3] << "\n"; - stream << "INCANDESCENCE " << std::setprecision(6) << std::fixed << material.incandescence[0] - << " " << std::setprecision(6) << std::fixed << material.incandescence[1] - << " " << std::setprecision(6) << std::fixed << material.incandescence[2] - << " " << std::setprecision(6) << std::fixed << material.incandescence[3] << "\n"; - stream << "COEFFS " << std::setprecision(6) << std::fixed << material.coeffs[0] - << " " << std::setprecision(6) << std::fixed << material.coeffs[1] << "\n"; - stream << "GLOW " << std::setprecision(6) << std::fixed << material.glow.x - << " " << material.glow.y << "\n"; - stream << "REFRACTIVE " << material.refractive.x - << " " << std::setprecision(6) << std::fixed << material.refractive.y << "\n"; - stream << "SPECULARCOLOR " << std::setprecision(6) << std::fixed << material.specularColor[0] - << " " << std::setprecision(6) << std::fixed << material.specularColor[1] - << " " << std::setprecision(6) << std::fixed << material.specularColor[2] - << " " << std::setprecision(6) << std::fixed << material.specularColor[3] << "\n"; - stream << "REFLECTIVECOLOR " << std::setprecision(6) << std::fixed << material.reflectiveColor[0] - << " " << std::setprecision(6) << std::fixed << material.reflectiveColor[1] - << " " << std::setprecision(6) << std::fixed << material.reflectiveColor[2] - << " " << std::setprecision(6) << std::fixed << material.reflectiveColor[3] << "\n"; - stream << "REFLECTIVE " << material.reflective.x - << " " << std::setprecision(6) << std::fixed << material.reflective.y << "\n"; - stream << "BLINN " << std::setprecision(6) << std::fixed << material.blinn[0] - << " " << std::setprecision(6) << std::fixed << material.blinn[1] << "\n"; - stream << "PHONG " << std::setprecision(6) << std::fixed << material.phong << "\n"; - stream << "\n"; - materialNum++; - } + stream << "\n"; + + boneNum = 0u; + for (const auto &bone : m_bones) { + stream << "BONE " << boneNum << "\n"; + stream << "OFFSET "; + stream << std::setprecision(6) << std::fixed << bone.globalOffset[0] << ", " << std::setprecision(6) << std::fixed << bone.globalOffset[1] << ", " + << std::setprecision(6) << std::fixed << bone.globalOffset[2] << "\n"; + + stream << "SCALE "; + stream << std::setprecision(6) << std::fixed << bone.scale[0] << ", " << std::setprecision(6) << std::fixed << bone.scale[1] << ", " + << std::setprecision(6) << std::fixed << bone.scale[2] << "\n"; + + const Matrix32 mat = bone.globalRotation.ToMatrix(); + stream << "X " << std::setprecision(6) << std::fixed << mat.m_data[0][0] << ", " << std::setprecision(6) << std::fixed << mat.m_data[1][0] << ", " + << std::setprecision(6) << std::fixed << mat.m_data[2][0] << "\n"; + stream << "Y " << std::setprecision(6) << std::fixed << mat.m_data[0][1] << ", " << std::setprecision(6) << std::fixed << mat.m_data[1][1] << ", " + << std::setprecision(6) << std::fixed << mat.m_data[2][1] << "\n"; + stream << "Z " << std::setprecision(6) << std::fixed << mat.m_data[0][2] << ", " << std::setprecision(6) << std::fixed << mat.m_data[1][2] << ", " + << std::setprecision(6) << std::fixed << mat.m_data[2][2] << "\n"; + stream << "\n"; + boneNum++; } + } -public: - XModelExportWriter6(std::string gameName, std::string zoneName) - : XModelExportWriterBase(std::move(gameName), std::move(zoneName)) - { - } + XModelExportWriterBase(std::string gameName, std::string zoneName) : m_game_name(std::move(gameName)), m_zone_name(std::move(zoneName)) {} +}; - void Write(std::ostream& stream) override - { - PrepareVertexMerger(); - WriteHeader(stream, 6); - WriteBones(stream); - WriteVertices(stream); - WriteFaces(stream); - WriteObjects(stream); - WriteMaterials(stream); +class XModelExportWriter6 final : public XModelExportWriterBase { + void WriteVertices(std::ostream &stream) const { + const auto &distinctVertexValues = m_vertex_merger.GetDistinctValues(); + stream << "NUMVERTS " << distinctVertexValues.size() << "\n"; + size_t vertexNum = 0u; + for (const auto &vertexPos : distinctVertexValues) { + stream << "VERT " << vertexNum << "\n"; + stream << "OFFSET "; + stream << std::setprecision(6) << std::fixed << vertexPos.x << ", " << std::setprecision(6) << std::fixed << vertexPos.y << ", " << std::setprecision(6) + << std::fixed << vertexPos.z << "\n"; + stream << "BONES " << vertexPos.weightCount << "\n"; + + for (auto weightIndex = 0u; weightIndex < vertexPos.weightCount; weightIndex++) { + stream << "BONE " << vertexPos.weights[weightIndex].boneIndex << " " << std::setprecision(6) << std::fixed << vertexPos.weights[weightIndex].weight + << "\n"; + } + stream << "\n"; + vertexNum++; + } + } + + static void WriteFaceVertex(std::ostream &stream, const size_t index, const XModelVertex &vertex) { + stream << "VERT " << index << "\n"; + stream << "NORMAL " << std::setprecision(6) << std::fixed << vertex.normal[0] << " " << std::setprecision(6) << std::fixed << vertex.normal[1] << " " + << std::setprecision(6) << std::fixed << vertex.normal[2] << "\n"; + stream << "COLOR " << std::setprecision(6) << std::fixed << vertex.color[0] << " " << std::setprecision(6) << std::fixed << vertex.color[1] << " " + << std::setprecision(6) << std::fixed << vertex.color[2] << " " << std::setprecision(6) << std::fixed << vertex.color[3] << "\n"; + stream << "UV 1 " << std::setprecision(6) << std::fixed << vertex.uv[0] << " " << std::setprecision(6) << std::fixed << vertex.uv[1] << "\n"; + } + + void WriteFaces(std::ostream &stream) const { + stream << "NUMFACES " << m_faces.size() << "\n"; + for (const auto &face : m_faces) { + const size_t distinctPositions[3]{m_vertex_merger.GetDistinctPositionByInputPosition(face.vertexIndex[0]), + m_vertex_merger.GetDistinctPositionByInputPosition(face.vertexIndex[1]), + m_vertex_merger.GetDistinctPositionByInputPosition(face.vertexIndex[2])}; + + const XModelVertex &v0 = m_vertices[face.vertexIndex[0]]; + const XModelVertex &v1 = m_vertices[face.vertexIndex[1]]; + const XModelVertex &v2 = m_vertices[face.vertexIndex[2]]; + + stream << "TRI " << face.objectIndex << " " << face.materialIndex << " 0 0\n"; + WriteFaceVertex(stream, distinctPositions[0], v0); + WriteFaceVertex(stream, distinctPositions[1], v1); + WriteFaceVertex(stream, distinctPositions[2], v2); + stream << "\n"; } + } + + void WriteObjects(std::ostream &stream) const { + stream << "NUMOBJECTS " << m_objects.size() << "\n"; + size_t objectNum = 0u; + for (const auto &object : m_objects) { + stream << "OBJECT " << objectNum << " \"" << object.name << "\"\n"; + objectNum++; + } + stream << "\n"; + } + + void WriteMaterials(std::ostream &stream) const { + stream << "NUMMATERIALS " << m_materials.size() << "\n"; + size_t materialNum = 0u; + for (const auto &material : m_materials) { + const auto colorMapPath = "../images/" + material.colorMapName + ".dds"; + stream << "MATERIAL " << materialNum << " \"" << material.name << "\" \"" << material.materialTypeName << "\" \"" << colorMapPath << "\"\n"; + stream << "COLOR " << std::setprecision(6) << std::fixed << material.color[0] << " " << std::setprecision(6) << std::fixed << material.color[1] << " " + << std::setprecision(6) << std::fixed << material.color[2] << " " << std::setprecision(6) << std::fixed << material.color[3] << "\n"; + stream << "TRANSPARENCY " << std::setprecision(6) << std::fixed << material.transparency[0] << " " << std::setprecision(6) << std::fixed + << material.transparency[1] << " " << std::setprecision(6) << std::fixed << material.transparency[2] << " " << std::setprecision(6) << std::fixed + << material.transparency[3] << "\n"; + stream << "AMBIENTCOLOR " << std::setprecision(6) << std::fixed << material.ambientColor[0] << " " << std::setprecision(6) << std::fixed + << material.ambientColor[1] << " " << std::setprecision(6) << std::fixed << material.ambientColor[2] << " " << std::setprecision(6) << std::fixed + << material.ambientColor[3] << "\n"; + stream << "INCANDESCENCE " << std::setprecision(6) << std::fixed << material.incandescence[0] << " " << std::setprecision(6) << std::fixed + << material.incandescence[1] << " " << std::setprecision(6) << std::fixed << material.incandescence[2] << " " << std::setprecision(6) << std::fixed + << material.incandescence[3] << "\n"; + stream << "COEFFS " << std::setprecision(6) << std::fixed << material.coeffs[0] << " " << std::setprecision(6) << std::fixed << material.coeffs[1] + << "\n"; + stream << "GLOW " << std::setprecision(6) << std::fixed << material.glow.x << " " << material.glow.y << "\n"; + stream << "REFRACTIVE " << material.refractive.x << " " << std::setprecision(6) << std::fixed << material.refractive.y << "\n"; + stream << "SPECULARCOLOR " << std::setprecision(6) << std::fixed << material.specularColor[0] << " " << std::setprecision(6) << std::fixed + << material.specularColor[1] << " " << std::setprecision(6) << std::fixed << material.specularColor[2] << " " << std::setprecision(6) << std::fixed + << material.specularColor[3] << "\n"; + stream << "REFLECTIVECOLOR " << std::setprecision(6) << std::fixed << material.reflectiveColor[0] << " " << std::setprecision(6) << std::fixed + << material.reflectiveColor[1] << " " << std::setprecision(6) << std::fixed << material.reflectiveColor[2] << " " << std::setprecision(6) + << std::fixed << material.reflectiveColor[3] << "\n"; + stream << "REFLECTIVE " << material.reflective.x << " " << std::setprecision(6) << std::fixed << material.reflective.y << "\n"; + stream << "BLINN " << std::setprecision(6) << std::fixed << material.blinn[0] << " " << std::setprecision(6) << std::fixed << material.blinn[1] << "\n"; + stream << "PHONG " << std::setprecision(6) << std::fixed << material.phong << "\n"; + stream << "\n"; + materialNum++; + } + } + +public: + XModelExportWriter6(std::string gameName, std::string zoneName) : XModelExportWriterBase(std::move(gameName), std::move(zoneName)) {} + + void Write(std::ostream &stream) override { + PrepareVertexMerger(); + WriteHeader(stream, 6); + WriteBones(stream); + WriteVertices(stream); + WriteFaces(stream); + WriteObjects(stream); + WriteMaterials(stream); + } }; -std::unique_ptr<XModelExportWriter> XModelExportWriter::CreateWriterForVersion6(std::string gameName, std::string zoneName) -{ - return std::make_unique<XModelExportWriter6>(std::move(gameName), std::move(zoneName)); +std::unique_ptr<XModelExportWriter> XModelExportWriter::CreateWriterForVersion6(std::string gameName, std::string zoneName) { + return std::make_unique<XModelExportWriter6>(std::move(gameName), std::move(zoneName)); } diff --git a/src/ObjWriting/Model/XModel/XModelExportWriter.h b/src/ObjWriting/Model/XModel/XModelExportWriter.h index 0d4d217d4..48a482bce 100644 --- a/src/ObjWriting/Model/XModel/XModelExportWriter.h +++ b/src/ObjWriting/Model/XModel/XModelExportWriter.h @@ -1,21 +1,20 @@ #pragma once -#include <ostream> #include <memory> +#include <ostream> #include "AbstractXModelWriter.h" -class XModelExportWriter : public AbstractXModelWriter -{ +class XModelExportWriter : public AbstractXModelWriter { public: - XModelExportWriter() = default; - virtual ~XModelExportWriter() = default; - XModelExportWriter(const XModelExportWriter& other) = default; - XModelExportWriter(XModelExportWriter&& other) noexcept = default; - XModelExportWriter& operator=(const XModelExportWriter& other) = default; - XModelExportWriter& operator=(XModelExportWriter&& other) noexcept = default; + XModelExportWriter() = default; + virtual ~XModelExportWriter() = default; + XModelExportWriter(const XModelExportWriter &other) = default; + XModelExportWriter(XModelExportWriter &&other) noexcept = default; + XModelExportWriter &operator=(const XModelExportWriter &other) = default; + XModelExportWriter &operator=(XModelExportWriter &&other) noexcept = default; - virtual void Write(std::ostream& stream) = 0; + virtual void Write(std::ostream &stream) = 0; - static std::unique_ptr<XModelExportWriter> CreateWriterForVersion6(std::string gameName, std::string zoneName); + static std::unique_ptr<XModelExportWriter> CreateWriterForVersion6(std::string gameName, std::string zoneName); }; diff --git a/src/ObjWriting/ObjWriting.cpp b/src/ObjWriting/ObjWriting.cpp index 90dda09a8..0060981db 100644 --- a/src/ObjWriting/ObjWriting.cpp +++ b/src/ObjWriting/ObjWriting.cpp @@ -8,40 +8,28 @@ ObjWriting::Configuration_t ObjWriting::Configuration; -const IZoneDumper* const ZONE_DUMPER[] -{ - new IW3::ZoneDumper(), - new IW4::ZoneDumper(), - new IW5::ZoneDumper(), - new T5::ZoneDumper(), - new T6::ZoneDumper() -}; +const IZoneDumper *const ZONE_DUMPER[]{new IW3::ZoneDumper(), new IW4::ZoneDumper(), new IW5::ZoneDumper(), new T5::ZoneDumper(), new T6::ZoneDumper()}; -bool ObjWriting::DumpZone(AssetDumpingContext& context) -{ - for (const auto* dumper : ZONE_DUMPER) - { - if (dumper->CanHandleZone(context)) - { - if (dumper->DumpZone(context)) - { - return true; - } +bool ObjWriting::DumpZone(AssetDumpingContext &context) { + for (const auto *dumper : ZONE_DUMPER) { + if (dumper->CanHandleZone(context)) { + if (dumper->DumpZone(context)) { + return true; + } - printf("Dumper for zone '%s' failed!\n", context.m_zone->m_name.c_str()); - return false; - } + printf("Dumper for zone '%s' failed!\n", context.m_zone->m_name.c_str()); + return false; } + } - return false; + return false; } -bool ObjWriting::ShouldHandleAssetType(const asset_type_t assetType) -{ - if (assetType < 0) - return false; - if (static_cast<size_t>(assetType) >= Configuration.AssetTypesToHandleBitfield.size()) - return true; +bool ObjWriting::ShouldHandleAssetType(const asset_type_t assetType) { + if (assetType < 0) + return false; + if (static_cast<size_t>(assetType) >= Configuration.AssetTypesToHandleBitfield.size()) + return true; - return Configuration.AssetTypesToHandleBitfield[assetType]; + return Configuration.AssetTypesToHandleBitfield[assetType]; } diff --git a/src/ObjWriting/ObjWriting.h b/src/ObjWriting/ObjWriting.h index beacbf7a7..e2a1234b8 100644 --- a/src/ObjWriting/ObjWriting.h +++ b/src/ObjWriting/ObjWriting.h @@ -5,33 +5,23 @@ #include "Dumping/AssetDumpingContext.h" #include "Zone/ZoneTypes.h" -class ObjWriting -{ +class ObjWriting { public: - static class Configuration_t - { - public: - enum class ImageOutputFormat_e - { - DDS, - IWI - }; - - enum class ModelOutputFormat_e - { - XMODEL_EXPORT, - OBJ - }; - - bool Verbose = false; - std::vector<bool> AssetTypesToHandleBitfield; - - ImageOutputFormat_e ImageOutputFormat = ImageOutputFormat_e::DDS; - ModelOutputFormat_e ModelOutputFormat = ModelOutputFormat_e::XMODEL_EXPORT; - bool MenuLegacyMode = false; - - } Configuration; - - static bool DumpZone(AssetDumpingContext& context); - static bool ShouldHandleAssetType(asset_type_t assetType); + static class Configuration_t { + public: + enum class ImageOutputFormat_e { DDS, IWI }; + + enum class ModelOutputFormat_e { XMODEL_EXPORT, OBJ }; + + bool Verbose = false; + std::vector<bool> AssetTypesToHandleBitfield; + + ImageOutputFormat_e ImageOutputFormat = ImageOutputFormat_e::DDS; + ModelOutputFormat_e ModelOutputFormat = ModelOutputFormat_e::XMODEL_EXPORT; + bool MenuLegacyMode = false; + + } Configuration; + + static bool DumpZone(AssetDumpingContext &context); + static bool ShouldHandleAssetType(asset_type_t assetType); }; diff --git a/src/ObjWriting/StructuredDataDef/StructuredDataDefDumper.cpp b/src/ObjWriting/StructuredDataDef/StructuredDataDefDumper.cpp index a8fed89f2..ebe98f89c 100644 --- a/src/ObjWriting/StructuredDataDef/StructuredDataDefDumper.cpp +++ b/src/ObjWriting/StructuredDataDef/StructuredDataDefDumper.cpp @@ -6,270 +6,249 @@ #include "Utils/Alignment.h" #include "Utils/StringUtils.h" -StructuredDataDefDumper::StructuredDataDefDumper(std::ostream& stream) - : AbstractTextDumper(stream), - m_flags{} -{ -} +StructuredDataDefDumper::StructuredDataDefDumper(std::ostream &stream) : AbstractTextDumper(stream), m_flags{} {} -void StructuredDataDefDumper::WriteLineComment(const std::string& comment) const -{ - Indent(); - m_stream << "// " << comment << "\n"; +void StructuredDataDefDumper::WriteLineComment(const std::string &comment) const { + Indent(); + m_stream << "// " << comment << "\n"; } -void StructuredDataDefDumper::DumpEnum(const CommonStructuredDataEnum& _enum) -{ - Indent(); +void StructuredDataDefDumper::DumpEnum(const CommonStructuredDataEnum &_enum) { + Indent(); - if (_enum.m_reserved_entry_count > static_cast<int>(_enum.m_entries.size())) - m_stream << "enum(" << _enum.m_reserved_entry_count << ") "; - else - m_stream << "enum "; - - m_stream << _enum.m_name << "\n"; - - Indent(); - m_stream << "{\n"; + if (_enum.m_reserved_entry_count > static_cast<int>(_enum.m_entries.size())) + m_stream << "enum(" << _enum.m_reserved_entry_count << ") "; + else + m_stream << "enum "; - IncIndent(); + m_stream << _enum.m_name << "\n"; - const auto entryCount = _enum.m_entries.size(); - for (auto i = 0u; i < entryCount; i++) - { - Indent(); - m_stream << "\""; - utils::EscapeStringForQuotationMarks(m_stream, _enum.m_entries[i].m_name); - m_stream << "\""; + Indent(); + m_stream << "{\n"; - if (i + 1 < entryCount) - m_stream << ","; - m_stream << "\n"; - } + IncIndent(); - DecIndent(); + const auto entryCount = _enum.m_entries.size(); + for (auto i = 0u; i < entryCount; i++) { Indent(); - m_stream << "};\n"; // end enum + m_stream << "\""; + utils::EscapeStringForQuotationMarks(m_stream, _enum.m_entries[i].m_name); + m_stream << "\""; + + if (i + 1 < entryCount) + m_stream << ","; + m_stream << "\n"; + } + + DecIndent(); + Indent(); + m_stream << "};\n"; // end enum } -void StructuredDataDefDumper::DumpType(const CommonStructuredDataDef& def, CommonStructuredDataType type, std::string& typeName, std::vector<std::string>& arraySpecifiers) const -{ - while (type.m_category != CommonStructuredDataTypeCategory::UNKNOWN) - { - switch (type.m_category) - { - case CommonStructuredDataTypeCategory::INT: - typeName = "int"; - type = CommonStructuredDataType(CommonStructuredDataTypeCategory::UNKNOWN); - break; - case CommonStructuredDataTypeCategory::BYTE: - typeName = "byte"; - type = CommonStructuredDataType(CommonStructuredDataTypeCategory::UNKNOWN); - break; - case CommonStructuredDataTypeCategory::BOOL: - typeName = "bool"; - type = CommonStructuredDataType(CommonStructuredDataTypeCategory::UNKNOWN); - break; - case CommonStructuredDataTypeCategory::FLOAT: - typeName = "float"; - type = CommonStructuredDataType(CommonStructuredDataTypeCategory::UNKNOWN); - break; - case CommonStructuredDataTypeCategory::SHORT: - typeName = "short"; - type = CommonStructuredDataType(CommonStructuredDataTypeCategory::UNKNOWN); - break; - case CommonStructuredDataTypeCategory::STRING: - { - std::ostringstream ss; - ss << "string(" << type.m_info.string_length << ')'; - typeName = ss.str(); - type = CommonStructuredDataType(CommonStructuredDataTypeCategory::UNKNOWN); - } - break; - case CommonStructuredDataTypeCategory::ENUM: - assert(type.m_info.type_index < def.m_enums.size()); - if (type.m_info.type_index < def.m_enums.size()) - typeName = def.m_enums[type.m_info.type_index]->m_name; - else - typeName = "unknown"; - type = CommonStructuredDataType(CommonStructuredDataTypeCategory::UNKNOWN); - break; - case CommonStructuredDataTypeCategory::STRUCT: - assert(type.m_info.type_index < def.m_structs.size()); - if (type.m_info.type_index < def.m_structs.size()) - typeName = def.m_structs[type.m_info.type_index]->m_name; - else - typeName = "unknown"; - type = CommonStructuredDataType(CommonStructuredDataTypeCategory::UNKNOWN); - break; - case CommonStructuredDataTypeCategory::INDEXED_ARRAY: - assert(type.m_info.type_index < def.m_indexed_arrays.size()); - if (type.m_info.type_index < def.m_indexed_arrays.size()) - { - const auto& indexArray = def.m_indexed_arrays[type.m_info.type_index]; - arraySpecifiers.push_back(std::to_string(indexArray.m_element_count)); - type = indexArray.m_array_type; - } - else - type = CommonStructuredDataType(CommonStructuredDataTypeCategory::UNKNOWN); - break; - case CommonStructuredDataTypeCategory::ENUM_ARRAY: - assert(type.m_info.type_index < def.m_enumed_arrays.size()); - if (type.m_info.type_index < def.m_enumed_arrays.size()) - { - const auto& enumedArray = def.m_enumed_arrays[type.m_info.type_index]; - - assert(enumedArray.m_enum_index < def.m_enums.size()); - if (enumedArray.m_enum_index < def.m_enums.size()) - arraySpecifiers.push_back(def.m_enums[enumedArray.m_enum_index]->m_name); - type = enumedArray.m_array_type; - } - else - type = CommonStructuredDataType(CommonStructuredDataTypeCategory::UNKNOWN); - break; - default: - type = CommonStructuredDataType(CommonStructuredDataTypeCategory::UNKNOWN); - break; - } +void StructuredDataDefDumper::DumpType(const CommonStructuredDataDef &def, CommonStructuredDataType type, std::string &typeName, + std::vector<std::string> &arraySpecifiers) const { + while (type.m_category != CommonStructuredDataTypeCategory::UNKNOWN) { + switch (type.m_category) { + case CommonStructuredDataTypeCategory::INT: + typeName = "int"; + type = CommonStructuredDataType(CommonStructuredDataTypeCategory::UNKNOWN); + break; + case CommonStructuredDataTypeCategory::BYTE: + typeName = "byte"; + type = CommonStructuredDataType(CommonStructuredDataTypeCategory::UNKNOWN); + break; + case CommonStructuredDataTypeCategory::BOOL: + typeName = "bool"; + type = CommonStructuredDataType(CommonStructuredDataTypeCategory::UNKNOWN); + break; + case CommonStructuredDataTypeCategory::FLOAT: + typeName = "float"; + type = CommonStructuredDataType(CommonStructuredDataTypeCategory::UNKNOWN); + break; + case CommonStructuredDataTypeCategory::SHORT: + typeName = "short"; + type = CommonStructuredDataType(CommonStructuredDataTypeCategory::UNKNOWN); + break; + case CommonStructuredDataTypeCategory::STRING: { + std::ostringstream ss; + ss << "string(" << type.m_info.string_length << ')'; + typeName = ss.str(); + type = CommonStructuredDataType(CommonStructuredDataTypeCategory::UNKNOWN); + } break; + case CommonStructuredDataTypeCategory::ENUM: + assert(type.m_info.type_index < def.m_enums.size()); + if (type.m_info.type_index < def.m_enums.size()) + typeName = def.m_enums[type.m_info.type_index]->m_name; + else + typeName = "unknown"; + type = CommonStructuredDataType(CommonStructuredDataTypeCategory::UNKNOWN); + break; + case CommonStructuredDataTypeCategory::STRUCT: + assert(type.m_info.type_index < def.m_structs.size()); + if (type.m_info.type_index < def.m_structs.size()) + typeName = def.m_structs[type.m_info.type_index]->m_name; + else + typeName = "unknown"; + type = CommonStructuredDataType(CommonStructuredDataTypeCategory::UNKNOWN); + break; + case CommonStructuredDataTypeCategory::INDEXED_ARRAY: + assert(type.m_info.type_index < def.m_indexed_arrays.size()); + if (type.m_info.type_index < def.m_indexed_arrays.size()) { + const auto &indexArray = def.m_indexed_arrays[type.m_info.type_index]; + arraySpecifiers.push_back(std::to_string(indexArray.m_element_count)); + type = indexArray.m_array_type; + } else + type = CommonStructuredDataType(CommonStructuredDataTypeCategory::UNKNOWN); + break; + case CommonStructuredDataTypeCategory::ENUM_ARRAY: + assert(type.m_info.type_index < def.m_enumed_arrays.size()); + if (type.m_info.type_index < def.m_enumed_arrays.size()) { + const auto &enumedArray = def.m_enumed_arrays[type.m_info.type_index]; + + assert(enumedArray.m_enum_index < def.m_enums.size()); + if (enumedArray.m_enum_index < def.m_enums.size()) + arraySpecifiers.push_back(def.m_enums[enumedArray.m_enum_index]->m_name); + type = enumedArray.m_array_type; + } else + type = CommonStructuredDataType(CommonStructuredDataTypeCategory::UNKNOWN); + break; + default: + type = CommonStructuredDataType(CommonStructuredDataTypeCategory::UNKNOWN); + break; } + } } -void StructuredDataDefDumper::DumpProperty(const CommonStructuredDataDef& def, const CommonStructuredDataStructProperty& property, unsigned& currentOffsetInBit) const -{ - std::string typeName; - std::vector<std::string> arraySpecifiers; - - currentOffsetInBit = utils::Align(currentOffsetInBit, property.m_type.GetAlignmentInBits()); - assert(currentOffsetInBit <= property.m_offset_in_bits); - if (currentOffsetInBit < property.m_offset_in_bits) - { - assert((property.m_offset_in_bits - currentOffsetInBit) % 8 == 0); - Indent(); - m_stream << "pad(" << ((property.m_offset_in_bits - currentOffsetInBit) / 8) << ");\n"; - currentOffsetInBit = property.m_offset_in_bits; - } - - DumpType(def, property.m_type, typeName, arraySpecifiers); +void StructuredDataDefDumper::DumpProperty(const CommonStructuredDataDef &def, const CommonStructuredDataStructProperty &property, + unsigned ¤tOffsetInBit) const { + std::string typeName; + std::vector<std::string> arraySpecifiers; + currentOffsetInBit = utils::Align(currentOffsetInBit, property.m_type.GetAlignmentInBits()); + assert(currentOffsetInBit <= property.m_offset_in_bits); + if (currentOffsetInBit < property.m_offset_in_bits) { + assert((property.m_offset_in_bits - currentOffsetInBit) % 8 == 0); Indent(); - m_stream << typeName << ' ' << property.m_name; + m_stream << "pad(" << ((property.m_offset_in_bits - currentOffsetInBit) / 8) << ");\n"; + currentOffsetInBit = property.m_offset_in_bits; + } - for (auto ri = arraySpecifiers.begin(); ri != arraySpecifiers.end(); ++ri) - m_stream << '[' << *ri << ']'; + DumpType(def, property.m_type, typeName, arraySpecifiers); -#ifdef STRUCTUREDDATADEF_DEBUG - m_stream << "; // Offset: " << (property.m_offset_in_bits / 8) << " byte"; - if (property.m_offset_in_bits % 8 > 0) - m_stream << " + " << (property.m_offset_in_bits % 8) << " bit"; + Indent(); + m_stream << typeName << ' ' << property.m_name; - const auto sizeInBits = property.m_type.GetSizeInBits(def); - m_stream << " | Size: "; + for (auto ri = arraySpecifiers.begin(); ri != arraySpecifiers.end(); ++ri) + m_stream << '[' << *ri << ']'; - if (sizeInBits % 8 == 0) - m_stream << (sizeInBits / 8) << " byte"; - else if (sizeInBits > 8) - m_stream << (sizeInBits / 8) << " byte + " << (sizeInBits % 8) << " bit"; - else - m_stream << sizeInBits << " bit"; - - m_stream << " | Alignment: " << property.m_type.GetAlignmentInBits() << " bit"; - m_stream << '\n'; +#ifdef STRUCTUREDDATADEF_DEBUG + m_stream << "; // Offset: " << (property.m_offset_in_bits / 8) << " byte"; + if (property.m_offset_in_bits % 8 > 0) + m_stream << " + " << (property.m_offset_in_bits % 8) << " bit"; + + const auto sizeInBits = property.m_type.GetSizeInBits(def); + m_stream << " | Size: "; + + if (sizeInBits % 8 == 0) + m_stream << (sizeInBits / 8) << " byte"; + else if (sizeInBits > 8) + m_stream << (sizeInBits / 8) << " byte + " << (sizeInBits % 8) << " bit"; + else + m_stream << sizeInBits << " bit"; + + m_stream << " | Alignment: " << property.m_type.GetAlignmentInBits() << " bit"; + m_stream << '\n'; #else - m_stream << ";\n"; + m_stream << ";\n"; #endif - currentOffsetInBit += property.m_type.GetSizeInBits(def); + currentOffsetInBit += property.m_type.GetSizeInBits(def); } -void StructuredDataDefDumper::DumpStruct(const CommonStructuredDataDef& def, const CommonStructuredDataStruct& _struct, const size_t structIndex) -{ +void StructuredDataDefDumper::DumpStruct(const CommonStructuredDataDef &def, const CommonStructuredDataStruct &_struct, const size_t structIndex) { #ifdef STRUCTUREDDATADEF_DEBUG - Indent(); - m_stream << "// BitOffset: " << _struct.m_bit_offset << "\n"; - Indent(); - m_stream << "// Size (Byte): " << _struct.m_size_in_byte << "\n"; + Indent(); + m_stream << "// BitOffset: " << _struct.m_bit_offset << "\n"; + Indent(); + m_stream << "// Size (Byte): " << _struct.m_size_in_byte << "\n"; #endif - Indent(); + Indent(); - m_stream << "struct " << _struct.m_name << "\n"; + m_stream << "struct " << _struct.m_name << "\n"; - Indent(); - m_stream << "{\n"; + Indent(); + m_stream << "{\n"; - IncIndent(); + IncIndent(); - auto currentOffsetInBit = def.m_root_type.m_category == CommonStructuredDataTypeCategory::STRUCT && def.m_root_type.m_info.type_index == structIndex ? 64u : 0u; - for (const auto& property : _struct.m_properties) - DumpProperty(def, property, currentOffsetInBit); + auto currentOffsetInBit = + def.m_root_type.m_category == CommonStructuredDataTypeCategory::STRUCT && def.m_root_type.m_info.type_index == structIndex ? 64u : 0u; + for (const auto &property : _struct.m_properties) + DumpProperty(def, property, currentOffsetInBit); - currentOffsetInBit = utils::Align(currentOffsetInBit, 8u); - if ((currentOffsetInBit / 8) < _struct.m_size_in_byte) - { - Indent(); - m_stream << "pad(" << (_struct.m_size_in_byte - (currentOffsetInBit / 8)) << ");\n"; - } - - DecIndent(); + currentOffsetInBit = utils::Align(currentOffsetInBit, 8u); + if ((currentOffsetInBit / 8) < _struct.m_size_in_byte) { Indent(); - m_stream << "};\n"; // end struct + m_stream << "pad(" << (_struct.m_size_in_byte - (currentOffsetInBit / 8)) << ");\n"; + } + + DecIndent(); + Indent(); + m_stream << "};\n"; // end struct } -void StructuredDataDefDumper::DumpDef(const CommonStructuredDataDef& def) -{ - if (m_flags.m_empty_line_before_definition) - m_stream << "\n\n"; - else - m_flags.m_empty_line_before_definition = true; +void StructuredDataDefDumper::DumpDef(const CommonStructuredDataDef &def) { + if (m_flags.m_empty_line_before_definition) + m_stream << "\n\n"; + else + m_flags.m_empty_line_before_definition = true; - const auto calculatedChecksum = def.CalculateChecksum(); + const auto calculatedChecksum = def.CalculateChecksum(); - m_stream << "// ====================\n"; - m_stream << "// Version " << def.m_version << "\n"; + m_stream << "// ====================\n"; + m_stream << "// Version " << def.m_version << "\n"; - if (calculatedChecksum != def.m_checksum) - m_stream << "// Calculated checksum did not match checksum in file\n// Overriding checksum to match original value\n"; + if (calculatedChecksum != def.m_checksum) + m_stream << "// Calculated checksum did not match checksum in file\n// Overriding checksum to match original value\n"; - m_stream << "// ====================\n"; + m_stream << "// ====================\n"; #ifdef STRUCTUREDDATADEF_DEBUG - m_stream << "// Size (Byte): " << def.m_size_in_byte << "\n"; - m_stream << "// Checksum: " << def.m_checksum << "\n"; + m_stream << "// Size (Byte): " << def.m_size_in_byte << "\n"; + m_stream << "// Checksum: " << def.m_checksum << "\n"; #endif - m_stream << "version " << def.m_version << "\n{\n"; - IncIndent(); + m_stream << "version " << def.m_version << "\n{\n"; + IncIndent(); - auto insertEmptyLine = false; + auto insertEmptyLine = false; - if (calculatedChecksum != def.m_checksum) - { - Indent(); - m_stream << "checksumoverride " << def.m_checksum << ";\n"; - insertEmptyLine = true; - } + if (calculatedChecksum != def.m_checksum) { + Indent(); + m_stream << "checksumoverride " << def.m_checksum << ";\n"; + insertEmptyLine = true; + } - for (const auto& _enum : def.m_enums) - { - if (insertEmptyLine) - m_stream << "\n"; - else - insertEmptyLine = true; + for (const auto &_enum : def.m_enums) { + if (insertEmptyLine) + m_stream << "\n"; + else + insertEmptyLine = true; - DumpEnum(*_enum); - } + DumpEnum(*_enum); + } - auto structIndex = 0u; - for (const auto& _struct : def.m_structs) - { - if (insertEmptyLine) - m_stream << "\n"; - else - insertEmptyLine = true; + auto structIndex = 0u; + for (const auto &_struct : def.m_structs) { + if (insertEmptyLine) + m_stream << "\n"; + else + insertEmptyLine = true; - DumpStruct(def, *_struct, structIndex++); - } + DumpStruct(def, *_struct, structIndex++); + } - DecIndent(); - m_stream << "}\n"; // end version + DecIndent(); + m_stream << "}\n"; // end version } diff --git a/src/ObjWriting/StructuredDataDef/StructuredDataDefDumper.h b/src/ObjWriting/StructuredDataDef/StructuredDataDefDumper.h index 5195f2235..3a86ebb24 100644 --- a/src/ObjWriting/StructuredDataDef/StructuredDataDefDumper.h +++ b/src/ObjWriting/StructuredDataDef/StructuredDataDefDumper.h @@ -6,22 +6,20 @@ #include "Dumping/AbstractTextDumper.h" #include "StructuredDataDef/CommonStructuredDataDef.h" -class StructuredDataDefDumper : AbstractTextDumper -{ - struct - { - bool m_empty_line_before_definition : 1; - } m_flags; +class StructuredDataDefDumper : AbstractTextDumper { + struct { + bool m_empty_line_before_definition : 1; + } m_flags; - void WriteLineComment(const std::string& comment) const; + void WriteLineComment(const std::string &comment) const; - void DumpEnum(const CommonStructuredDataEnum& _enum); - void DumpType(const CommonStructuredDataDef& def, CommonStructuredDataType type, std::string& typeName, std::vector<std::string>& arraySpecifiers) const; - void DumpProperty(const CommonStructuredDataDef& def, const CommonStructuredDataStructProperty& property, unsigned& currentOffsetInBit) const; - void DumpStruct(const CommonStructuredDataDef& def, const CommonStructuredDataStruct& _struct, size_t structIndex); + void DumpEnum(const CommonStructuredDataEnum &_enum); + void DumpType(const CommonStructuredDataDef &def, CommonStructuredDataType type, std::string &typeName, std::vector<std::string> &arraySpecifiers) const; + void DumpProperty(const CommonStructuredDataDef &def, const CommonStructuredDataStructProperty &property, unsigned ¤tOffsetInBit) const; + void DumpStruct(const CommonStructuredDataDef &def, const CommonStructuredDataStruct &_struct, size_t structIndex); public: - explicit StructuredDataDefDumper(std::ostream& stream); + explicit StructuredDataDefDumper(std::ostream &stream); - void DumpDef(const CommonStructuredDataDef& def); + void DumpDef(const CommonStructuredDataDef &def); }; diff --git a/src/Parser/Parsing/ILexer.h b/src/Parser/Parsing/ILexer.h index e84249fe4..b6ea8d1c5 100644 --- a/src/Parser/Parsing/ILexer.h +++ b/src/Parser/Parsing/ILexer.h @@ -3,24 +3,22 @@ #include "IParserLineStream.h" #include "Parsing/IParserValue.h" -template<typename TokenType> -class ILexer -{ - // TokenType must inherit IParserValue - static_assert(std::is_base_of<IParserValue, TokenType>::value); +template <typename TokenType> class ILexer { + // TokenType must inherit IParserValue + static_assert(std::is_base_of<IParserValue, TokenType>::value); public: - ILexer() = default; - virtual ~ILexer() = default; - ILexer(const ILexer& other) = default; - ILexer(ILexer&& other) noexcept = default; - ILexer& operator=(const ILexer& other) = default; - ILexer& operator=(ILexer&& other) noexcept = default; + ILexer() = default; + virtual ~ILexer() = default; + ILexer(const ILexer &other) = default; + ILexer(ILexer &&other) noexcept = default; + ILexer &operator=(const ILexer &other) = default; + ILexer &operator=(ILexer &&other) noexcept = default; - virtual const TokenType& GetToken(unsigned index) = 0; - virtual void PopTokens(int amount) = 0; + virtual const TokenType &GetToken(unsigned index) = 0; + virtual void PopTokens(int amount) = 0; - _NODISCARD virtual bool IsEof() = 0; - _NODISCARD virtual const TokenPos& GetPos() = 0; - _NODISCARD virtual ParserLine GetLineForPos(const TokenPos& pos) const = 0; + _NODISCARD virtual bool IsEof() = 0; + _NODISCARD virtual const TokenPos &GetPos() = 0; + _NODISCARD virtual ParserLine GetLineForPos(const TokenPos &pos) const = 0; }; diff --git a/src/Parser/Parsing/IPackValueSupplier.h b/src/Parser/Parsing/IPackValueSupplier.h index d023011c8..375babfe1 100644 --- a/src/Parser/Parsing/IPackValueSupplier.h +++ b/src/Parser/Parsing/IPackValueSupplier.h @@ -1,14 +1,13 @@ #pragma once -class IPackValueSupplier -{ +class IPackValueSupplier { public: - IPackValueSupplier() = default; - virtual ~IPackValueSupplier() = default; - IPackValueSupplier(const IPackValueSupplier& other) = default; - IPackValueSupplier(IPackValueSupplier&& other) noexcept = default; - IPackValueSupplier& operator=(const IPackValueSupplier& other) = default; - IPackValueSupplier& operator=(IPackValueSupplier&& other) noexcept = default; + IPackValueSupplier() = default; + virtual ~IPackValueSupplier() = default; + IPackValueSupplier(const IPackValueSupplier &other) = default; + IPackValueSupplier(IPackValueSupplier &&other) noexcept = default; + IPackValueSupplier &operator=(const IPackValueSupplier &other) = default; + IPackValueSupplier &operator=(IPackValueSupplier &&other) noexcept = default; - virtual int GetCurrentPack() const = 0; + virtual int GetCurrentPack() const = 0; }; \ No newline at end of file diff --git a/src/Parser/Parsing/IParser.h b/src/Parser/Parsing/IParser.h index b2c3ac039..dedf290d7 100644 --- a/src/Parser/Parsing/IParser.h +++ b/src/Parser/Parsing/IParser.h @@ -1,14 +1,13 @@ #pragma once -class IParser -{ +class IParser { public: - IParser() = default; - virtual ~IParser() = default; - IParser(const IParser& other) = default; - IParser(IParser&& other) noexcept = default; - IParser& operator=(const IParser& other) = default; - IParser& operator=(IParser&& other) noexcept = default; + IParser() = default; + virtual ~IParser() = default; + IParser(const IParser &other) = default; + IParser(IParser &&other) noexcept = default; + IParser &operator=(const IParser &other) = default; + IParser &operator=(IParser &&other) noexcept = default; - virtual bool Parse() = 0; + virtual bool Parse() = 0; }; diff --git a/src/Parser/Parsing/IParserLineStream.cpp b/src/Parser/Parsing/IParserLineStream.cpp index 60ba91c09..ba8fc5ea1 100644 --- a/src/Parser/Parsing/IParserLineStream.cpp +++ b/src/Parser/Parsing/IParserLineStream.cpp @@ -1,18 +1,8 @@ #include "IParserLineStream.h" -ParserLine::ParserLine() - : m_line_number(0) -{ -} +ParserLine::ParserLine() : m_line_number(0) {} ParserLine::ParserLine(std::shared_ptr<std::string> filename, const int lineNumber, std::string line) - : m_filename(std::move(filename)), - m_line_number(lineNumber), - m_line(std::move(line)) -{ -} + : m_filename(std::move(filename)), m_line_number(lineNumber), m_line(std::move(line)) {} -bool ParserLine::IsEof() const -{ - return m_line_number <= 0; -} +bool ParserLine::IsEof() const { return m_line_number <= 0; } diff --git a/src/Parser/Parsing/IParserLineStream.h b/src/Parser/Parsing/IParserLineStream.h index f00a3432a..8ff5fc49b 100644 --- a/src/Parser/Parsing/IParserLineStream.h +++ b/src/Parser/Parsing/IParserLineStream.h @@ -1,38 +1,36 @@ #pragma once -#include <string> #include <functional> #include <memory> +#include <string> #include "Utils/ClassUtils.h" -class ParserLine -{ +class ParserLine { public: - std::shared_ptr<std::string> m_filename; - int m_line_number; - std::string m_line; + std::shared_ptr<std::string> m_filename; + int m_line_number; + std::string m_line; - ParserLine(); - ParserLine(std::shared_ptr<std::string> filename, int lineNumber, std::string line); + ParserLine(); + ParserLine(std::shared_ptr<std::string> filename, int lineNumber, std::string line); - _NODISCARD bool IsEof() const; + _NODISCARD bool IsEof() const; }; -class IParserLineStream -{ +class IParserLineStream { public: - IParserLineStream() = default; - virtual ~IParserLineStream() = default; - - IParserLineStream(const IParserLineStream& other) = default; - IParserLineStream(IParserLineStream&& other) noexcept = default; - IParserLineStream& operator=(const IParserLineStream& other) = default; - IParserLineStream& operator=(IParserLineStream&& other) noexcept = default; - - virtual ParserLine NextLine() = 0; - virtual bool IncludeFile(const std::string& filename) = 0; - virtual void PopCurrentFile() = 0; - _NODISCARD virtual bool IsOpen() const = 0; - _NODISCARD virtual bool Eof() const = 0; + IParserLineStream() = default; + virtual ~IParserLineStream() = default; + + IParserLineStream(const IParserLineStream &other) = default; + IParserLineStream(IParserLineStream &&other) noexcept = default; + IParserLineStream &operator=(const IParserLineStream &other) = default; + IParserLineStream &operator=(IParserLineStream &&other) noexcept = default; + + virtual ParserLine NextLine() = 0; + virtual bool IncludeFile(const std::string &filename) = 0; + virtual void PopCurrentFile() = 0; + _NODISCARD virtual bool IsOpen() const = 0; + _NODISCARD virtual bool Eof() const = 0; }; diff --git a/src/Parser/Parsing/IParserValue.h b/src/Parser/Parsing/IParserValue.h index 3dfd4c4c9..9f5aef753 100644 --- a/src/Parser/Parsing/IParserValue.h +++ b/src/Parser/Parsing/IParserValue.h @@ -1,20 +1,19 @@ #pragma once -#include "Utils/ClassUtils.h" #include "TokenPos.h" +#include "Utils/ClassUtils.h" -class IParserValue -{ +class IParserValue { protected: - IParserValue() = default; + IParserValue() = default; public: - virtual ~IParserValue() = default; - IParserValue(const IParserValue& other) = default; - IParserValue(IParserValue&& other) noexcept = default; - IParserValue& operator=(const IParserValue& other) = default; - IParserValue& operator=(IParserValue&& other) noexcept = default; + virtual ~IParserValue() = default; + IParserValue(const IParserValue &other) = default; + IParserValue(IParserValue &&other) noexcept = default; + IParserValue &operator=(const IParserValue &other) = default; + IParserValue &operator=(IParserValue &&other) noexcept = default; - _NODISCARD virtual bool IsEof() const = 0; - _NODISCARD virtual const TokenPos& GetPos() const = 0; + _NODISCARD virtual bool IsEof() const = 0; + _NODISCARD virtual const TokenPos &GetPos() const = 0; }; diff --git a/src/Parser/Parsing/Impl/AbstractDirectiveStreamProxy.cpp b/src/Parser/Parsing/Impl/AbstractDirectiveStreamProxy.cpp index 492ecbd96..bcf5cb678 100644 --- a/src/Parser/Parsing/Impl/AbstractDirectiveStreamProxy.cpp +++ b/src/Parser/Parsing/Impl/AbstractDirectiveStreamProxy.cpp @@ -1,123 +1,103 @@ #include "AbstractDirectiveStreamProxy.h" -TokenPos AbstractDirectiveStreamProxy::CreatePos(const ParserLine& line, const unsigned position) -{ - return TokenPos(*line.m_filename, line.m_line_number, static_cast<int>(position + 1)); +TokenPos AbstractDirectiveStreamProxy::CreatePos(const ParserLine &line, const unsigned position) { + return TokenPos(*line.m_filename, line.m_line_number, static_cast<int>(position + 1)); } -bool AbstractDirectiveStreamProxy::SkipWhitespace(const ParserLine& line, unsigned& position) -{ - while(true) - { - if (position >= line.m_line.size()) - return false; - - if (isspace(line.m_line[position])) - position++; - else - break; - } +bool AbstractDirectiveStreamProxy::SkipWhitespace(const ParserLine &line, unsigned &position) { + while (true) { + if (position >= line.m_line.size()) + return false; - return true; + if (isspace(line.m_line[position])) + position++; + else + break; + } + + return true; } -bool AbstractDirectiveStreamProxy::ExtractInteger(const ParserLine& line, unsigned& position, int& value) -{ - if (position >= line.m_line.size()) - return false; +bool AbstractDirectiveStreamProxy::ExtractInteger(const ParserLine &line, unsigned &position, int &value) { + if (position >= line.m_line.size()) + return false; - const auto* startPosition = &line.m_line[position]; - char* endPosition; - value = strtol(startPosition, &endPosition, 0); - const auto len = endPosition - startPosition; + const auto *startPosition = &line.m_line[position]; + char *endPosition; + value = strtol(startPosition, &endPosition, 0); + const auto len = endPosition - startPosition; - if(len > 0) - { - position += len; - return true; - } + if (len > 0) { + position += len; + return true; + } - return false; + return false; } -bool AbstractDirectiveStreamProxy::ExtractIdentifier(const ParserLine& line, unsigned& position) -{ - auto firstChar = true; - while (true) - { - if (position >= line.m_line.size()) - return !firstChar; - - const auto c = line.m_line[position]; - if (isalpha(c) - || c == '_' - || !firstChar && isdigit(c)) - { - position++; - } - else - return !firstChar; - - firstChar = false; - } +bool AbstractDirectiveStreamProxy::ExtractIdentifier(const ParserLine &line, unsigned &position) { + auto firstChar = true; + while (true) { + if (position >= line.m_line.size()) + return !firstChar; + + const auto c = line.m_line[position]; + if (isalpha(c) || c == '_' || !firstChar && isdigit(c)) { + position++; + } else + return !firstChar; + + firstChar = false; + } } -bool AbstractDirectiveStreamProxy::MatchCharacter(const ParserLine& line, unsigned& position, char c) -{ - if (position < line.m_line.size() && line.m_line[position] == c) - { - position++; - return true; - } +bool AbstractDirectiveStreamProxy::MatchCharacter(const ParserLine &line, unsigned &position, char c) { + if (position < line.m_line.size() && line.m_line[position] == c) { + position++; + return true; + } - return false; + return false; } -bool AbstractDirectiveStreamProxy::MatchNextCharacter(const ParserLine& line, unsigned& position, char c) -{ - return SkipWhitespace(line, position) && MatchCharacter(line, position, c); +bool AbstractDirectiveStreamProxy::MatchNextCharacter(const ParserLine &line, unsigned &position, char c) { + return SkipWhitespace(line, position) && MatchCharacter(line, position, c); } -bool AbstractDirectiveStreamProxy::MatchString(const ParserLine& line, unsigned& position, const char* str, unsigned len) -{ - if (line.m_line.compare(position, len, str) == 0) - { - position += len; - return true; - } +bool AbstractDirectiveStreamProxy::MatchString(const ParserLine &line, unsigned &position, const char *str, unsigned len) { + if (line.m_line.compare(position, len, str) == 0) { + position += len; + return true; + } - return false; + return false; } -bool AbstractDirectiveStreamProxy::MatchNextString(const ParserLine& line, unsigned& position, const char* str, unsigned len) -{ - return SkipWhitespace(line, position) && MatchString(line, position, str, len); +bool AbstractDirectiveStreamProxy::MatchNextString(const ParserLine &line, unsigned &position, const char *str, unsigned len) { + return SkipWhitespace(line, position) && MatchString(line, position, str, len); } -bool AbstractDirectiveStreamProxy::FindDirective(const ParserLine& line, unsigned& directiveStartPosition, unsigned& directiveEndPos) -{ - directiveStartPosition = 0; - for (; directiveStartPosition < line.m_line.size(); directiveStartPosition++) - { - const auto c = line.m_line[directiveStartPosition]; - - if (isspace(c)) - continue; - - if (c != '#') - continue; - - directiveEndPos = directiveStartPosition + 1; - for(; directiveEndPos < line.m_line.size(); directiveEndPos++) - { - const auto c2 = line.m_line[directiveEndPos]; - - if (isspace(c2)) - break; - } - - return true; +bool AbstractDirectiveStreamProxy::FindDirective(const ParserLine &line, unsigned &directiveStartPosition, unsigned &directiveEndPos) { + directiveStartPosition = 0; + for (; directiveStartPosition < line.m_line.size(); directiveStartPosition++) { + const auto c = line.m_line[directiveStartPosition]; + + if (isspace(c)) + continue; + + if (c != '#') + continue; + + directiveEndPos = directiveStartPosition + 1; + for (; directiveEndPos < line.m_line.size(); directiveEndPos++) { + const auto c2 = line.m_line[directiveEndPos]; + + if (isspace(c2)) + break; } - return false; + return true; + } + + return false; } diff --git a/src/Parser/Parsing/Impl/AbstractDirectiveStreamProxy.h b/src/Parser/Parsing/Impl/AbstractDirectiveStreamProxy.h index 513f2f06c..a9ddfcf9e 100644 --- a/src/Parser/Parsing/Impl/AbstractDirectiveStreamProxy.h +++ b/src/Parser/Parsing/Impl/AbstractDirectiveStreamProxy.h @@ -3,20 +3,19 @@ #include "Parsing/IParserLineStream.h" #include "Parsing/TokenPos.h" -class AbstractDirectiveStreamProxy : public IParserLineStream -{ +class AbstractDirectiveStreamProxy : public IParserLineStream { protected: - AbstractDirectiveStreamProxy() = default; + AbstractDirectiveStreamProxy() = default; - static TokenPos CreatePos(const ParserLine& line, unsigned position); + static TokenPos CreatePos(const ParserLine &line, unsigned position); - static bool SkipWhitespace(const ParserLine& line, unsigned& position); - static bool ExtractInteger(const ParserLine& line, unsigned& position, int& value); - static bool ExtractIdentifier(const ParserLine& line, unsigned& position); - static bool MatchCharacter(const ParserLine& line, unsigned& position, char c); - static bool MatchNextCharacter(const ParserLine& line, unsigned& position, char c); - static bool MatchString(const ParserLine& line, unsigned& position, const char* str, unsigned len); - static bool MatchNextString(const ParserLine& line, unsigned& position, const char* str, unsigned len); + static bool SkipWhitespace(const ParserLine &line, unsigned &position); + static bool ExtractInteger(const ParserLine &line, unsigned &position, int &value); + static bool ExtractIdentifier(const ParserLine &line, unsigned &position); + static bool MatchCharacter(const ParserLine &line, unsigned &position, char c); + static bool MatchNextCharacter(const ParserLine &line, unsigned &position, char c); + static bool MatchString(const ParserLine &line, unsigned &position, const char *str, unsigned len); + static bool MatchNextString(const ParserLine &line, unsigned &position, const char *str, unsigned len); - static bool FindDirective(const ParserLine& line, unsigned& directiveStartPosition, unsigned& directiveEndPos); + static bool FindDirective(const ParserLine &line, unsigned &directiveStartPosition, unsigned &directiveEndPos); }; diff --git a/src/Parser/Parsing/Impl/AbstractLexer.h b/src/Parser/Parsing/Impl/AbstractLexer.h index dfbb91c8f..6c76ad45d 100644 --- a/src/Parser/Parsing/Impl/AbstractLexer.h +++ b/src/Parser/Parsing/Impl/AbstractLexer.h @@ -4,423 +4,334 @@ #include <deque> #include <sstream> -#include "Utils/ClassUtils.h" #include "Parsing/ILexer.h" #include "Parsing/IParserLineStream.h" #include "Parsing/ParsingException.h" +#include "Utils/ClassUtils.h" #include "Utils/StringUtils.h" -template <typename TokenType> -class AbstractLexer : public ILexer<TokenType> -{ - // TokenType must inherit IParserValue - static_assert(std::is_base_of<IParserValue, TokenType>::value); +template <typename TokenType> class AbstractLexer : public ILexer<TokenType> { + // TokenType must inherit IParserValue + static_assert(std::is_base_of<IParserValue, TokenType>::value); protected: - std::deque<TokenType> m_token_cache; - std::deque<ParserLine> m_line_cache; - IParserLineStream* const m_stream; - - unsigned m_line_index; - unsigned m_current_line_offset; - - explicit AbstractLexer(IParserLineStream* stream) - : m_stream(stream), - m_line_index(0u), - m_current_line_offset(0u) - { - } + std::deque<TokenType> m_token_cache; + std::deque<ParserLine> m_line_cache; + IParserLineStream *const m_stream; - virtual TokenType GetNextToken() = 0; - - int NextChar() - { - while (true) - { - while (m_line_index >= m_line_cache.size()) - { - if (!m_line_cache.empty() && m_line_cache.back().IsEof()) - return EOF; - - m_line_cache.push_back(m_stream->NextLine()); - } - - if (m_current_line_offset >= m_line_cache[m_line_index].m_line.size()) - { - m_line_index++; - m_current_line_offset = 0; - } - else - break; - } - - return m_line_cache[m_line_index].m_line[m_current_line_offset++]; - } + unsigned m_line_index; + unsigned m_current_line_offset; - int PeekChar() - { - auto peekLineOffset = m_current_line_offset; - auto peekLine = m_line_index; - - while (true) - { - while (peekLine >= m_line_cache.size()) - { - if (!m_line_cache.empty() && m_line_cache.back().IsEof()) - return EOF; - - m_line_cache.push_back(m_stream->NextLine()); - } - - if (peekLineOffset >= m_line_cache[peekLine].m_line.size()) - { - peekLine++; - peekLineOffset = 0; - } - else - break; - } - - return m_line_cache[peekLine].m_line[peekLineOffset]; - } + explicit AbstractLexer(IParserLineStream *stream) : m_stream(stream), m_line_index(0u), m_current_line_offset(0u) {} - _NODISCARD const ParserLine& CurrentLine() const - { - return m_line_cache[m_line_index]; - } + virtual TokenType GetNextToken() = 0; - _NODISCARD bool IsLineEnd() const - { - return m_current_line_offset >= CurrentLine().m_line.size(); - } + int NextChar() { + while (true) { + while (m_line_index >= m_line_cache.size()) { + if (!m_line_cache.empty() && m_line_cache.back().IsEof()) + return EOF; - _NODISCARD bool NextCharInLineIs(const char c) - { - return !IsLineEnd() && PeekChar() == c; - } + m_line_cache.push_back(m_stream->NextLine()); + } - _NODISCARD TokenPos GetPreviousCharacterPos() const - { - const auto& currentLine = CurrentLine(); - return TokenPos(*currentLine.m_filename, currentLine.m_line_number, m_current_line_offset); + if (m_current_line_offset >= m_line_cache[m_line_index].m_line.size()) { + m_line_index++; + m_current_line_offset = 0; + } else + break; } - _NODISCARD TokenPos GetNextCharacterPos() - { - const auto& currentLine = CurrentLine(); - if (m_current_line_offset + 1 >= currentLine.m_line.size()) - { - PeekChar(); - return TokenPos(*m_line_cache.back().m_filename, m_line_cache.back().m_line_number, 1); - } + return m_line_cache[m_line_index].m_line[m_current_line_offset++]; + } - return TokenPos(*currentLine.m_filename, currentLine.m_line_number, m_current_line_offset + 1); - } + int PeekChar() { + auto peekLineOffset = m_current_line_offset; + auto peekLine = m_line_index; - /** - * \brief Reads an identifier from the current position - * \return The value of the read identifier - */ - std::string ReadIdentifier() - { - const auto& currentLine = CurrentLine(); - assert(m_current_line_offset >= 1); - assert(isalpha(currentLine.m_line[m_current_line_offset - 1]) || currentLine.m_line[m_current_line_offset - 1] == '_'); - - const auto startPos = m_current_line_offset - 1; - const auto lineSize = currentLine.m_line.size(); - while (m_current_line_offset < lineSize) - { - const auto c = currentLine.m_line[m_current_line_offset]; - - if (!isalnum(c) && c != '_') - break; - - m_current_line_offset++; - } - - return std::string(currentLine.m_line, startPos, m_current_line_offset - startPos); - } + while (true) { + while (peekLine >= m_line_cache.size()) { + if (!m_line_cache.empty() && m_line_cache.back().IsEof()) + return EOF; - /** - * \brief Reads an identifier from the current position - * \return The value of the read identifier - */ - std::string ReadStringWithEscapeSequences() - { - const auto& currentLine = CurrentLine(); - assert(m_current_line_offset >= 1); - assert(currentLine.m_line[m_current_line_offset - 1] == '"'); - - const auto startPos = m_current_line_offset; - const auto lineSize = currentLine.m_line.size(); - auto isEscaped = false; - auto inEscape = false; - while (true) - { - if (m_current_line_offset >= lineSize) - throw ParsingException(TokenPos(*currentLine.m_filename, currentLine.m_line_number, m_current_line_offset), "Unclosed string"); - - const auto c = currentLine.m_line[m_current_line_offset]; - - if (c == '\"' && !inEscape) - break; - - if (c == '\\' && !inEscape) - { - isEscaped = true; - inEscape = true; - } - else - { - inEscape = false; - } - - m_current_line_offset++; - } - - std::string str(currentLine.m_line, startPos, m_current_line_offset++ - startPos); - if (!isEscaped) - return str; - - std::ostringstream ss; - utils::UnescapeStringFromQuotationMarks(ss, std::move(str)); - return ss.str(); - } + m_line_cache.push_back(m_stream->NextLine()); + } - /** - * \brief Reads an identifier from the current position - * \return The value of the read identifier - */ - std::string ReadString() - { - const auto& currentLine = CurrentLine(); - assert(m_current_line_offset >= 1); - assert(currentLine.m_line[m_current_line_offset - 1] == '"'); - - const auto startPos = m_current_line_offset; - const auto lineSize = currentLine.m_line.size(); - while (true) - { - if (m_current_line_offset >= lineSize) - throw ParsingException(TokenPos(*currentLine.m_filename, currentLine.m_line_number, m_current_line_offset), "Unclosed string"); - - if (currentLine.m_line[m_current_line_offset] == '\"') - break; - - m_current_line_offset++; - } - - return std::string(currentLine.m_line, startPos, m_current_line_offset++ - startPos); + if (peekLineOffset >= m_line_cache[peekLine].m_line.size()) { + peekLine++; + peekLineOffset = 0; + } else + break; } - void ReadHexNumber(int& integerValue) - { - const auto& currentLine = CurrentLine(); - const auto* start = ¤tLine.m_line.c_str()[m_current_line_offset - 1]; - char* end; + return m_line_cache[peekLine].m_line[peekLineOffset]; + } - integerValue = static_cast<int>(std::strtoul(start, &end, 16)); - const auto numberLength = static_cast<unsigned>(end - start); - if (numberLength == 0 || isalnum(*end) || *end == '_') - throw ParsingException(GetPreviousCharacterPos(), "Invalid hex number"); + _NODISCARD const ParserLine &CurrentLine() const { return m_line_cache[m_line_index]; } - m_current_line_offset += numberLength - 1; - } + _NODISCARD bool IsLineEnd() const { return m_current_line_offset >= CurrentLine().m_line.size(); } - _NODISCARD bool IsIntegerNumber() const - { - const auto& currentLine = CurrentLine(); - const auto* currentCharacter = ¤tLine.m_line.c_str()[m_current_line_offset - 1]; - auto isInteger = true; - auto dot = false; - auto exponent = false; - - if (*currentCharacter == '-' || *currentCharacter == '+') - ++currentCharacter; - - while (*currentCharacter) - { - if (isdigit(*currentCharacter)) - { - } - else if (*currentCharacter == '.') - { - if (dot) - throw ParsingException(GetPreviousCharacterPos(), "Invalid number"); - dot = true; - isInteger = false; - } - else if (*currentCharacter == 'e' || *currentCharacter == 'E') - { - if (exponent) - throw ParsingException(GetPreviousCharacterPos(), "Invalid number"); - if (currentCharacter[1] == '-') - ++currentCharacter; - exponent = true; - isInteger = false; - } - else if (isalpha(*currentCharacter)) - { - throw ParsingException(GetPreviousCharacterPos(), "Invalid number"); - } - else - { - break; - } - - ++currentCharacter; - } - - return isInteger; - } - - int ReadInteger() - { - const auto& currentLine = CurrentLine(); - const auto* start = ¤tLine.m_line.c_str()[m_current_line_offset - 1]; - char* end; - const auto integerValue = std::strtol(start, &end, 10); - const auto numberLength = static_cast<unsigned>(end - start); - - if (numberLength == 0) - throw ParsingException(GetPreviousCharacterPos(), "Invalid number"); + _NODISCARD bool NextCharInLineIs(const char c) { return !IsLineEnd() && PeekChar() == c; } - m_current_line_offset += numberLength - 1; + _NODISCARD TokenPos GetPreviousCharacterPos() const { + const auto ¤tLine = CurrentLine(); + return TokenPos(*currentLine.m_filename, currentLine.m_line_number, m_current_line_offset); + } - return integerValue; + _NODISCARD TokenPos GetNextCharacterPos() { + const auto ¤tLine = CurrentLine(); + if (m_current_line_offset + 1 >= currentLine.m_line.size()) { + PeekChar(); + return TokenPos(*m_line_cache.back().m_filename, m_line_cache.back().m_line_number, 1); } - double ReadFloatingPoint() - { - const auto& currentLine = CurrentLine(); - const auto* start = ¤tLine.m_line.c_str()[m_current_line_offset - 1]; - char* end; - const auto floatingPointValue = std::strtod(start, &end); - const auto numberLength = static_cast<unsigned>(end - start); + return TokenPos(*currentLine.m_filename, currentLine.m_line_number, m_current_line_offset + 1); + } - if (numberLength == 0) - throw ParsingException(GetPreviousCharacterPos(), "Invalid number"); + /** + * \brief Reads an identifier from the current position + * \return The value of the read identifier + */ + std::string ReadIdentifier() { + const auto ¤tLine = CurrentLine(); + assert(m_current_line_offset >= 1); + assert(isalpha(currentLine.m_line[m_current_line_offset - 1]) || currentLine.m_line[m_current_line_offset - 1] == '_'); - m_current_line_offset += numberLength - 1; + const auto startPos = m_current_line_offset - 1; + const auto lineSize = currentLine.m_line.size(); + while (m_current_line_offset < lineSize) { + const auto c = currentLine.m_line[m_current_line_offset]; - return floatingPointValue; - } + if (!isalnum(c) && c != '_') + break; - void ReadNumber(bool& isFloatingPoint, bool& hasSignPrefix, double& floatingPointValue, int& integerValue) - { - const auto& currentLine = CurrentLine(); - assert(m_current_line_offset >= 1); - assert(isdigit(currentLine.m_line[m_current_line_offset - 1]) - || currentLine.m_line[m_current_line_offset - 1] == '.' - || currentLine.m_line[m_current_line_offset - 1] == '+' - || currentLine.m_line[m_current_line_offset - 1] == '-'); - hasSignPrefix = currentLine.m_line[m_current_line_offset - 1] == '+' || currentLine.m_line[m_current_line_offset - 1] == '-'; - - const auto lineLength = currentLine.m_line.size(); - if (lineLength - m_current_line_offset >= 1 - && currentLine.m_line[m_current_line_offset - 1] == '0' - && currentLine.m_line[m_current_line_offset] == 'x') - { - isFloatingPoint = false; - ReadHexNumber(integerValue); - } - else if (IsIntegerNumber()) - { - isFloatingPoint = false; - integerValue = ReadInteger(); - } - else - { - isFloatingPoint = true; - floatingPointValue = ReadFloatingPoint(); - } + m_current_line_offset++; } - void ReadNumber(bool& hasSignPrefix, int& integerValue) - { - const auto& currentLine = CurrentLine(); - assert(m_current_line_offset >= 1); - assert(isdigit(currentLine.m_line[m_current_line_offset - 1]) - || currentLine.m_line[m_current_line_offset - 1] == '+' - || currentLine.m_line[m_current_line_offset - 1] == '-'); - hasSignPrefix = currentLine.m_line[m_current_line_offset - 1] == '+' || currentLine.m_line[m_current_line_offset - 1] == '-'; - - const auto lineLength = currentLine.m_line.size(); - if (lineLength - m_current_line_offset >= 1 - && currentLine.m_line[m_current_line_offset - 1] == '0' - && currentLine.m_line[m_current_line_offset] == 'x') - { - ReadHexNumber(integerValue); - } - else - { - integerValue = ReadInteger(); - } + return std::string(currentLine.m_line, startPos, m_current_line_offset - startPos); + } + + /** + * \brief Reads an identifier from the current position + * \return The value of the read identifier + */ + std::string ReadStringWithEscapeSequences() { + const auto ¤tLine = CurrentLine(); + assert(m_current_line_offset >= 1); + assert(currentLine.m_line[m_current_line_offset - 1] == '"'); + + const auto startPos = m_current_line_offset; + const auto lineSize = currentLine.m_line.size(); + auto isEscaped = false; + auto inEscape = false; + while (true) { + if (m_current_line_offset >= lineSize) + throw ParsingException(TokenPos(*currentLine.m_filename, currentLine.m_line_number, m_current_line_offset), "Unclosed string"); + + const auto c = currentLine.m_line[m_current_line_offset]; + + if (c == '\"' && !inEscape) + break; + + if (c == '\\' && !inEscape) { + isEscaped = true; + inEscape = true; + } else { + inEscape = false; + } + + m_current_line_offset++; } -public: - const TokenType& GetToken(unsigned index) override - { - while (index >= m_token_cache.size()) - m_token_cache.emplace_back(GetNextToken()); - - return m_token_cache[index]; + std::string str(currentLine.m_line, startPos, m_current_line_offset++ - startPos); + if (!isEscaped) + return str; + + std::ostringstream ss; + utils::UnescapeStringFromQuotationMarks(ss, std::move(str)); + return ss.str(); + } + + /** + * \brief Reads an identifier from the current position + * \return The value of the read identifier + */ + std::string ReadString() { + const auto ¤tLine = CurrentLine(); + assert(m_current_line_offset >= 1); + assert(currentLine.m_line[m_current_line_offset - 1] == '"'); + + const auto startPos = m_current_line_offset; + const auto lineSize = currentLine.m_line.size(); + while (true) { + if (m_current_line_offset >= lineSize) + throw ParsingException(TokenPos(*currentLine.m_filename, currentLine.m_line_number, m_current_line_offset), "Unclosed string"); + + if (currentLine.m_line[m_current_line_offset] == '\"') + break; + + m_current_line_offset++; } - void PopTokens(int amount) override - { - if (amount <= 0 || m_token_cache.empty()) - return; - - if (static_cast<int>(m_token_cache.size()) <= amount) - { - const auto& lastToken = m_token_cache.back(); - while (!m_line_cache.empty() - && (m_line_cache.front().m_line_number != lastToken.GetPos().m_line - || *m_line_cache.front().m_filename != lastToken.GetPos().m_filename.get())) - { - m_line_cache.pop_front(); - m_line_index--; - } - m_token_cache.clear(); - } - else - { - m_token_cache.erase(m_token_cache.begin(), m_token_cache.begin() + amount); - const auto& firstToken = m_token_cache.front(); - while (!m_line_cache.empty() - && (m_line_cache.front().m_line_number != firstToken.GetPos().m_line - || *m_line_cache.front().m_filename != firstToken.GetPos().m_filename.get())) - { - m_line_cache.pop_front(); - m_line_index--; - } - } + return std::string(currentLine.m_line, startPos, m_current_line_offset++ - startPos); + } + + void ReadHexNumber(int &integerValue) { + const auto ¤tLine = CurrentLine(); + const auto *start = ¤tLine.m_line.c_str()[m_current_line_offset - 1]; + char *end; + + integerValue = static_cast<int>(std::strtoul(start, &end, 16)); + const auto numberLength = static_cast<unsigned>(end - start); + if (numberLength == 0 || isalnum(*end) || *end == '_') + throw ParsingException(GetPreviousCharacterPos(), "Invalid hex number"); + + m_current_line_offset += numberLength - 1; + } + + _NODISCARD bool IsIntegerNumber() const { + const auto ¤tLine = CurrentLine(); + const auto *currentCharacter = ¤tLine.m_line.c_str()[m_current_line_offset - 1]; + auto isInteger = true; + auto dot = false; + auto exponent = false; + + if (*currentCharacter == '-' || *currentCharacter == '+') + ++currentCharacter; + + while (*currentCharacter) { + if (isdigit(*currentCharacter)) { + } else if (*currentCharacter == '.') { + if (dot) + throw ParsingException(GetPreviousCharacterPos(), "Invalid number"); + dot = true; + isInteger = false; + } else if (*currentCharacter == 'e' || *currentCharacter == 'E') { + if (exponent) + throw ParsingException(GetPreviousCharacterPos(), "Invalid number"); + if (currentCharacter[1] == '-') + ++currentCharacter; + exponent = true; + isInteger = false; + } else if (isalpha(*currentCharacter)) { + throw ParsingException(GetPreviousCharacterPos(), "Invalid number"); + } else { + break; + } + + ++currentCharacter; } - _NODISCARD bool IsEof() override - { - return GetToken(0).IsEof(); + return isInteger; + } + + int ReadInteger() { + const auto ¤tLine = CurrentLine(); + const auto *start = ¤tLine.m_line.c_str()[m_current_line_offset - 1]; + char *end; + const auto integerValue = std::strtol(start, &end, 10); + const auto numberLength = static_cast<unsigned>(end - start); + + if (numberLength == 0) + throw ParsingException(GetPreviousCharacterPos(), "Invalid number"); + + m_current_line_offset += numberLength - 1; + + return integerValue; + } + + double ReadFloatingPoint() { + const auto ¤tLine = CurrentLine(); + const auto *start = ¤tLine.m_line.c_str()[m_current_line_offset - 1]; + char *end; + const auto floatingPointValue = std::strtod(start, &end); + const auto numberLength = static_cast<unsigned>(end - start); + + if (numberLength == 0) + throw ParsingException(GetPreviousCharacterPos(), "Invalid number"); + + m_current_line_offset += numberLength - 1; + + return floatingPointValue; + } + + void ReadNumber(bool &isFloatingPoint, bool &hasSignPrefix, double &floatingPointValue, int &integerValue) { + const auto ¤tLine = CurrentLine(); + assert(m_current_line_offset >= 1); + assert(isdigit(currentLine.m_line[m_current_line_offset - 1]) || currentLine.m_line[m_current_line_offset - 1] == '.' || + currentLine.m_line[m_current_line_offset - 1] == '+' || currentLine.m_line[m_current_line_offset - 1] == '-'); + hasSignPrefix = currentLine.m_line[m_current_line_offset - 1] == '+' || currentLine.m_line[m_current_line_offset - 1] == '-'; + + const auto lineLength = currentLine.m_line.size(); + if (lineLength - m_current_line_offset >= 1 && currentLine.m_line[m_current_line_offset - 1] == '0' && currentLine.m_line[m_current_line_offset] == 'x') { + isFloatingPoint = false; + ReadHexNumber(integerValue); + } else if (IsIntegerNumber()) { + isFloatingPoint = false; + integerValue = ReadInteger(); + } else { + isFloatingPoint = true; + floatingPointValue = ReadFloatingPoint(); } + } + + void ReadNumber(bool &hasSignPrefix, int &integerValue) { + const auto ¤tLine = CurrentLine(); + assert(m_current_line_offset >= 1); + assert(isdigit(currentLine.m_line[m_current_line_offset - 1]) || currentLine.m_line[m_current_line_offset - 1] == '+' || + currentLine.m_line[m_current_line_offset - 1] == '-'); + hasSignPrefix = currentLine.m_line[m_current_line_offset - 1] == '+' || currentLine.m_line[m_current_line_offset - 1] == '-'; + + const auto lineLength = currentLine.m_line.size(); + if (lineLength - m_current_line_offset >= 1 && currentLine.m_line[m_current_line_offset - 1] == '0' && currentLine.m_line[m_current_line_offset] == 'x') { + ReadHexNumber(integerValue); + } else { + integerValue = ReadInteger(); + } + } - _NODISCARD const TokenPos& GetPos() override - { - return GetToken(0).GetPos(); +public: + const TokenType &GetToken(unsigned index) override { + while (index >= m_token_cache.size()) + m_token_cache.emplace_back(GetNextToken()); + + return m_token_cache[index]; + } + + void PopTokens(int amount) override { + if (amount <= 0 || m_token_cache.empty()) + return; + + if (static_cast<int>(m_token_cache.size()) <= amount) { + const auto &lastToken = m_token_cache.back(); + while (!m_line_cache.empty() && + (m_line_cache.front().m_line_number != lastToken.GetPos().m_line || *m_line_cache.front().m_filename != lastToken.GetPos().m_filename.get())) { + m_line_cache.pop_front(); + m_line_index--; + } + m_token_cache.clear(); + } else { + m_token_cache.erase(m_token_cache.begin(), m_token_cache.begin() + amount); + const auto &firstToken = m_token_cache.front(); + while (!m_line_cache.empty() && + (m_line_cache.front().m_line_number != firstToken.GetPos().m_line || *m_line_cache.front().m_filename != firstToken.GetPos().m_filename.get())) { + m_line_cache.pop_front(); + m_line_index--; + } } + } + + _NODISCARD bool IsEof() override { return GetToken(0).IsEof(); } - _NODISCARD ParserLine GetLineForPos(const TokenPos& pos) const override - { - for (const auto& line : m_line_cache) - { - if (line.m_filename - && *line.m_filename == pos.m_filename.get() - && line.m_line_number == pos.m_line) - { - return line; - } - } - - return ParserLine(); + _NODISCARD const TokenPos &GetPos() override { return GetToken(0).GetPos(); } + + _NODISCARD ParserLine GetLineForPos(const TokenPos &pos) const override { + for (const auto &line : m_line_cache) { + if (line.m_filename && *line.m_filename == pos.m_filename.get() && line.m_line_number == pos.m_line) { + return line; + } } + + return ParserLine(); + } }; diff --git a/src/Parser/Parsing/Impl/AbstractParser.h b/src/Parser/Parsing/Impl/AbstractParser.h index ba83b4818..b47b5ceb2 100644 --- a/src/Parser/Parsing/Impl/AbstractParser.h +++ b/src/Parser/Parsing/Impl/AbstractParser.h @@ -3,95 +3,75 @@ #include <iostream> #include <vector> -#include "Parsing/IParser.h" #include "Parsing/ILexer.h" -#include "Parsing/Sequence/AbstractSequence.h" +#include "Parsing/IParser.h" #include "Parsing/ParsingException.h" +#include "Parsing/Sequence/AbstractSequence.h" -template <typename TokenType, typename ParserState> -class AbstractParser : public IParser -{ - // TokenType must inherit IParserValue - static_assert(std::is_base_of<IParserValue, TokenType>::value); +template <typename TokenType, typename ParserState> class AbstractParser : public IParser { + // TokenType must inherit IParserValue + static_assert(std::is_base_of<IParserValue, TokenType>::value); public: - typedef AbstractSequence<TokenType, ParserState> sequence_t; + typedef AbstractSequence<TokenType, ParserState> sequence_t; protected: - ILexer<TokenType>* m_lexer; - std::unique_ptr<ParserState> m_state; + ILexer<TokenType> *m_lexer; + std::unique_ptr<ParserState> m_state; - explicit AbstractParser(ILexer<TokenType>* lexer, std::unique_ptr<ParserState> state) - : m_lexer(lexer), - m_state(std::move(state)) - { - } + explicit AbstractParser(ILexer<TokenType> *lexer, std::unique_ptr<ParserState> state) : m_lexer(lexer), m_state(std::move(state)) {} - virtual const std::vector<sequence_t*>& GetTestsForState() = 0; + virtual const std::vector<sequence_t *> &GetTestsForState() = 0; public: - ~AbstractParser() override = default; - AbstractParser(const AbstractParser& other) = default; - AbstractParser(AbstractParser&& other) noexcept = default; - AbstractParser& operator=(const AbstractParser& other) = default; - AbstractParser& operator=(AbstractParser&& other) noexcept = default; - - bool Parse() override - { - try - { - while (!m_lexer->IsEof()) - { - auto testSuccessful = false; - const auto& availableTests = GetTestsForState(); - - for (const sequence_t* test : availableTests) - { - unsigned consumedTokenCount; - - if (test->MatchSequence(m_lexer, m_state.get(), consumedTokenCount)) - { - m_lexer->PopTokens(consumedTokenCount); - testSuccessful = true; - break; - } - } - - if (!testSuccessful) - { - const TokenPos& pos = m_lexer->GetPos(); - const ParserLine line = m_lexer->GetLineForPos(pos); - - if (!line.IsEof()) - { - std::cerr << "Error: " << pos.m_filename.get() << " L" << pos.m_line << ':' << pos.m_column << " Could not parse expression:\n" - << line.m_line.substr(pos.m_column - 1) << std::endl; - } - else - { - std::cerr << "Error: " << pos.m_filename.get() << " L" << pos.m_line << ':' << pos.m_column << " Could not parse expression." << std::endl; - } - return false; - } - } - } - catch (const ParsingException& e) - { - const auto pos = e.Position(); - const auto line = m_lexer->GetLineForPos(pos); - - if (!line.IsEof() && line.m_line.size() > static_cast<unsigned>(pos.m_column - 1)) - { - std::cerr << "Error: " << e.FullMessage() << "\n" << line.m_line.substr(pos.m_column - 1) << std::endl; - } - else - { - std::cerr << "Error: " << e.FullMessage() << std::endl; - } - - return false; + ~AbstractParser() override = default; + AbstractParser(const AbstractParser &other) = default; + AbstractParser(AbstractParser &&other) noexcept = default; + AbstractParser &operator=(const AbstractParser &other) = default; + AbstractParser &operator=(AbstractParser &&other) noexcept = default; + + bool Parse() override { + try { + while (!m_lexer->IsEof()) { + auto testSuccessful = false; + const auto &availableTests = GetTestsForState(); + + for (const sequence_t *test : availableTests) { + unsigned consumedTokenCount; + + if (test->MatchSequence(m_lexer, m_state.get(), consumedTokenCount)) { + m_lexer->PopTokens(consumedTokenCount); + testSuccessful = true; + break; + } } - return true; + if (!testSuccessful) { + const TokenPos &pos = m_lexer->GetPos(); + const ParserLine line = m_lexer->GetLineForPos(pos); + + if (!line.IsEof()) { + std::cerr << "Error: " << pos.m_filename.get() << " L" << pos.m_line << ':' << pos.m_column << " Could not parse expression:\n" + << line.m_line.substr(pos.m_column - 1) << std::endl; + } else { + std::cerr << "Error: " << pos.m_filename.get() << " L" << pos.m_line << ':' << pos.m_column << " Could not parse expression." << std::endl; + } + return false; + } + } + } catch (const ParsingException &e) { + const auto pos = e.Position(); + const auto line = m_lexer->GetLineForPos(pos); + + if (!line.IsEof() && line.m_line.size() > static_cast<unsigned>(pos.m_column - 1)) { + std::cerr << "Error: " << e.FullMessage() << "\n" << line.m_line.substr(pos.m_column - 1) << std::endl; + } else { + std::cerr << "Error: " << e.FullMessage() << std::endl; + } + + return false; } + + return true; + } }; diff --git a/src/Parser/Parsing/Impl/CommentRemovingStreamProxy.cpp b/src/Parser/Parsing/Impl/CommentRemovingStreamProxy.cpp index b4bf76940..36284a7c7 100644 --- a/src/Parser/Parsing/Impl/CommentRemovingStreamProxy.cpp +++ b/src/Parser/Parsing/Impl/CommentRemovingStreamProxy.cpp @@ -1,95 +1,64 @@ #include "CommentRemovingStreamProxy.h" -CommentRemovingStreamProxy::CommentRemovingStreamProxy(IParserLineStream* stream) - : m_stream(stream), - m_inside_multi_line_comment(false), - m_next_line_is_comment(false) -{ -} +CommentRemovingStreamProxy::CommentRemovingStreamProxy(IParserLineStream *stream) + : m_stream(stream), m_inside_multi_line_comment(false), m_next_line_is_comment(false) {} -ParserLine CommentRemovingStreamProxy::NextLine() -{ - auto line = m_stream->NextLine(); +ParserLine CommentRemovingStreamProxy::NextLine() { + auto line = m_stream->NextLine(); - if (m_next_line_is_comment) - { - m_next_line_is_comment = !line.m_line.empty() && line.m_line[line.m_line.size() - 1] == '\\'; - return ParserLine(line.m_filename, line.m_line_number, std::string()); - } + if (m_next_line_is_comment) { + m_next_line_is_comment = !line.m_line.empty() && line.m_line[line.m_line.size() - 1] == '\\'; + return ParserLine(line.m_filename, line.m_line_number, std::string()); + } - auto multiLineCommentStart = 0u; - auto inString = false; - auto isEscaped = false; - for (auto i = 0u; i < line.m_line.size(); i++) - { - const auto c = line.m_line[i]; + auto multiLineCommentStart = 0u; + auto inString = false; + auto isEscaped = false; + for (auto i = 0u; i < line.m_line.size(); i++) { + const auto c = line.m_line[i]; - if (m_inside_multi_line_comment) - { - if (c == '*' && i + 1 < line.m_line.size() && line.m_line[i + 1] == '/') - { - line.m_line.erase(multiLineCommentStart, i + 2 - multiLineCommentStart); - i = multiLineCommentStart - 1; - multiLineCommentStart = 0; - m_inside_multi_line_comment = false; - } - } - else if(inString) - { - if (isEscaped) - isEscaped = false; - else if (c == '\\') - isEscaped = true; - else if (c == '"') - inString = false; - } - else - { - if(c == '"') - { - inString = true; - } - else if(c == '/' && i + 1 < line.m_line.size()) - { - const auto c1 = line.m_line[i + 1]; + if (m_inside_multi_line_comment) { + if (c == '*' && i + 1 < line.m_line.size() && line.m_line[i + 1] == '/') { + line.m_line.erase(multiLineCommentStart, i + 2 - multiLineCommentStart); + i = multiLineCommentStart - 1; + multiLineCommentStart = 0; + m_inside_multi_line_comment = false; + } + } else if (inString) { + if (isEscaped) + isEscaped = false; + else if (c == '\\') + isEscaped = true; + else if (c == '"') + inString = false; + } else { + if (c == '"') { + inString = true; + } else if (c == '/' && i + 1 < line.m_line.size()) { + const auto c1 = line.m_line[i + 1]; - if (c1 == '*') - { - multiLineCommentStart = i; - m_inside_multi_line_comment = true; - } - else if(c1 == '/') - { - m_next_line_is_comment = line.m_line[line.m_line.size() - 1] == '\\'; - line.m_line.erase(i); - return line; - } - } + if (c1 == '*') { + multiLineCommentStart = i; + m_inside_multi_line_comment = true; + } else if (c1 == '/') { + m_next_line_is_comment = line.m_line[line.m_line.size() - 1] == '\\'; + line.m_line.erase(i); + return line; } + } } + } - if(m_inside_multi_line_comment) - line.m_line.erase(multiLineCommentStart); + if (m_inside_multi_line_comment) + line.m_line.erase(multiLineCommentStart); - return line; + return line; } -bool CommentRemovingStreamProxy::IncludeFile(const std::string& filename) -{ - return m_stream->IncludeFile(filename); -} +bool CommentRemovingStreamProxy::IncludeFile(const std::string &filename) { return m_stream->IncludeFile(filename); } -void CommentRemovingStreamProxy::PopCurrentFile() -{ - m_stream->PopCurrentFile(); -} +void CommentRemovingStreamProxy::PopCurrentFile() { m_stream->PopCurrentFile(); } -bool CommentRemovingStreamProxy::IsOpen() const -{ - return m_stream->IsOpen(); -} +bool CommentRemovingStreamProxy::IsOpen() const { return m_stream->IsOpen(); } -bool CommentRemovingStreamProxy::Eof() const -{ - return m_stream->Eof(); -} +bool CommentRemovingStreamProxy::Eof() const { return m_stream->Eof(); } diff --git a/src/Parser/Parsing/Impl/CommentRemovingStreamProxy.h b/src/Parser/Parsing/Impl/CommentRemovingStreamProxy.h index d9d9bfc5f..4fce28b1e 100644 --- a/src/Parser/Parsing/Impl/CommentRemovingStreamProxy.h +++ b/src/Parser/Parsing/Impl/CommentRemovingStreamProxy.h @@ -2,18 +2,17 @@ #include "Parsing/IParserLineStream.h" -class CommentRemovingStreamProxy final : public IParserLineStream -{ - IParserLineStream* const m_stream; - bool m_inside_multi_line_comment; - bool m_next_line_is_comment; +class CommentRemovingStreamProxy final : public IParserLineStream { + IParserLineStream *const m_stream; + bool m_inside_multi_line_comment; + bool m_next_line_is_comment; public: - explicit CommentRemovingStreamProxy(IParserLineStream* stream); + explicit CommentRemovingStreamProxy(IParserLineStream *stream); - ParserLine NextLine() override; - bool IncludeFile(const std::string& filename) override; - void PopCurrentFile() override; - _NODISCARD bool IsOpen() const override; - _NODISCARD bool Eof() const override; + ParserLine NextLine() override; + bool IncludeFile(const std::string &filename) override; + void PopCurrentFile() override; + _NODISCARD bool IsOpen() const override; + _NODISCARD bool Eof() const override; }; diff --git a/src/Parser/Parsing/Impl/DefinesStreamProxy.cpp b/src/Parser/Parsing/Impl/DefinesStreamProxy.cpp index 4e6f7deaf..72e8a0747 100644 --- a/src/Parser/Parsing/Impl/DefinesStreamProxy.cpp +++ b/src/Parser/Parsing/Impl/DefinesStreamProxy.cpp @@ -4,754 +4,622 @@ #include <sstream> #include <utility> -#include "Utils/ClassUtils.h" #include "ParserSingleInputStream.h" #include "Parsing/ParsingException.h" -#include "Parsing/Simple/SimpleExpressionInterpreter.h" #include "Parsing/Simple/Expression/ISimpleExpression.h" #include "Parsing/Simple/Expression/SimpleExpressionMatchers.h" +#include "Parsing/Simple/SimpleExpressionInterpreter.h" +#include "Utils/ClassUtils.h" -DefinesStreamProxy::DefineParameterPosition::DefineParameterPosition() - : m_parameter_index(0u), - m_parameter_position(0u) -{ -} +DefinesStreamProxy::DefineParameterPosition::DefineParameterPosition() : m_parameter_index(0u), m_parameter_position(0u) {} DefinesStreamProxy::DefineParameterPosition::DefineParameterPosition(const unsigned index, const unsigned position) - : m_parameter_index(index), - m_parameter_position(position) -{ -} + : m_parameter_index(index), m_parameter_position(position) {} -DefinesStreamProxy::Define::Define() -= default; +DefinesStreamProxy::Define::Define() = default; -DefinesStreamProxy::Define::Define(std::string name, std::string value) - : m_name(std::move(name)), - m_value(std::move(value)) -{ -} +DefinesStreamProxy::Define::Define(std::string name, std::string value) : m_name(std::move(name)), m_value(std::move(value)) {} -std::string DefinesStreamProxy::Define::Render(const std::vector<std::string>& parameterValues) const -{ - if (parameterValues.empty() || m_parameter_positions.empty()) - return m_value; +std::string DefinesStreamProxy::Define::Render(const std::vector<std::string> ¶meterValues) const { + if (parameterValues.empty() || m_parameter_positions.empty()) + return m_value; - std::ostringstream str; - auto lastPos = 0u; - for (const auto& parameterPosition : m_parameter_positions) - { - if (lastPos < parameterPosition.m_parameter_position) - str << std::string(m_value, lastPos, parameterPosition.m_parameter_position - lastPos); - - if (parameterPosition.m_parameter_index < parameterValues.size()) - { - str << parameterValues[parameterPosition.m_parameter_index]; - } + std::ostringstream str; + auto lastPos = 0u; + for (const auto ¶meterPosition : m_parameter_positions) { + if (lastPos < parameterPosition.m_parameter_position) + str << std::string(m_value, lastPos, parameterPosition.m_parameter_position - lastPos); - lastPos = parameterPosition.m_parameter_position; + if (parameterPosition.m_parameter_index < parameterValues.size()) { + str << parameterValues[parameterPosition.m_parameter_index]; } - if (lastPos < m_value.size()) - str << std::string(m_value, lastPos, m_value.size() - lastPos); + lastPos = parameterPosition.m_parameter_position; + } + + if (lastPos < m_value.size()) + str << std::string(m_value, lastPos, m_value.size() - lastPos); - return str.str(); + return str.str(); } -void DefinesStreamProxy::Define::IdentifyParameters(const std::vector<std::string>& parameterNames) -{ - if (parameterNames.empty()) - return; +void DefinesStreamProxy::Define::IdentifyParameters(const std::vector<std::string> ¶meterNames) { + if (parameterNames.empty()) + return; - auto inWord = false; - auto wordStart = 0u; - for (auto i = 0u; i < m_value.size(); i++) - { - const auto c = m_value[i]; - if (!isalnum(c) && c != '_') - { - if (inWord) - { - const std::string word(m_value, wordStart, i - wordStart); - - auto parameterIndex = 0u; - for (; parameterIndex < parameterNames.size(); parameterIndex++) - { - if (word == parameterNames[parameterIndex]) - break; - } - - if (parameterIndex < parameterNames.size()) - { - m_value.erase(wordStart, i - wordStart); - m_parameter_positions.emplace_back(parameterIndex, wordStart); - i = wordStart; - } - - inWord = false; - } + auto inWord = false; + auto wordStart = 0u; + for (auto i = 0u; i < m_value.size(); i++) { + const auto c = m_value[i]; + if (!isalnum(c) && c != '_') { + if (inWord) { + const std::string word(m_value, wordStart, i - wordStart); + + auto parameterIndex = 0u; + for (; parameterIndex < parameterNames.size(); parameterIndex++) { + if (word == parameterNames[parameterIndex]) + break; } - else - { - if (!inWord && (isalpha(c) || c == '_')) - { - inWord = true; - wordStart = i; - } + + if (parameterIndex < parameterNames.size()) { + m_value.erase(wordStart, i - wordStart); + m_parameter_positions.emplace_back(parameterIndex, wordStart); + i = wordStart; } + + inWord = false; + } + } else { + if (!inWord && (isalpha(c) || c == '_')) { + inWord = true; + wordStart = i; + } } + } - if (inWord) - { - const std::string word(m_value, wordStart, m_value.size() - wordStart); + if (inWord) { + const std::string word(m_value, wordStart, m_value.size() - wordStart); - auto parameterIndex = 0u; - for (; parameterIndex < parameterNames.size(); parameterIndex++) - { - if (word == parameterNames[parameterIndex]) - break; - } + auto parameterIndex = 0u; + for (; parameterIndex < parameterNames.size(); parameterIndex++) { + if (word == parameterNames[parameterIndex]) + break; + } - if (parameterIndex < parameterNames.size()) - { - m_value.erase(wordStart, m_value.size() - wordStart); - m_parameter_positions.emplace_back(parameterIndex, wordStart); - } + if (parameterIndex < parameterNames.size()) { + m_value.erase(wordStart, m_value.size() - wordStart); + m_parameter_positions.emplace_back(parameterIndex, wordStart); } + } } -DefinesStreamProxy::DefinesStreamProxy(IParserLineStream* stream, const bool skipDirectiveLines) - : m_stream(stream), - m_skip_directive_lines(skipDirectiveLines), - m_ignore_depth(0), - m_in_define(false) -{ -} +DefinesStreamProxy::DefinesStreamProxy(IParserLineStream *stream, const bool skipDirectiveLines) + : m_stream(stream), m_skip_directive_lines(skipDirectiveLines), m_ignore_depth(0), m_in_define(false) {} -int DefinesStreamProxy::GetLineEndEscapePos(const ParserLine& line) -{ - for (auto linePos = line.m_line.size(); linePos > 0; linePos--) - { - const auto c = line.m_line[linePos - 1]; - if (c == '\\') - return static_cast<int>(linePos) - 1; +int DefinesStreamProxy::GetLineEndEscapePos(const ParserLine &line) { + for (auto linePos = line.m_line.size(); linePos > 0; linePos--) { + const auto c = line.m_line[linePos - 1]; + if (c == '\\') + return static_cast<int>(linePos) - 1; - if (!isspace(c)) - return -1; - } + if (!isspace(c)) + return -1; + } - return -1; + return -1; } -void DefinesStreamProxy::ContinueDefine(const ParserLine& line) -{ - const auto lineEndEscapePos = GetLineEndEscapePos(line); - if (lineEndEscapePos < 0) - { - m_current_define_value << line.m_line; - m_current_define.m_value = m_current_define_value.str(); - m_current_define.IdentifyParameters(m_current_define_parameters); - AddDefine(std::move(m_current_define)); - - m_in_define = false; - m_current_define = Define(); - m_current_define_value.str(std::string()); - m_current_define_parameters.clear(); - } - else - { - if (line.m_line.size() > static_cast<unsigned>(lineEndEscapePos)) - m_current_define_value << line.m_line.substr(0, static_cast<unsigned>(lineEndEscapePos)); - } +void DefinesStreamProxy::ContinueDefine(const ParserLine &line) { + const auto lineEndEscapePos = GetLineEndEscapePos(line); + if (lineEndEscapePos < 0) { + m_current_define_value << line.m_line; + m_current_define.m_value = m_current_define_value.str(); + m_current_define.IdentifyParameters(m_current_define_parameters); + AddDefine(std::move(m_current_define)); + + m_in_define = false; + m_current_define = Define(); + m_current_define_value.str(std::string()); + m_current_define_parameters.clear(); + } else { + if (line.m_line.size() > static_cast<unsigned>(lineEndEscapePos)) + m_current_define_value << line.m_line.substr(0, static_cast<unsigned>(lineEndEscapePos)); + } } -std::vector<std::string> DefinesStreamProxy::MatchDefineParameters(const ParserLine& line, unsigned& parameterPosition) -{ - if (line.m_line[parameterPosition] != '(') - return std::vector<std::string>(); +std::vector<std::string> DefinesStreamProxy::MatchDefineParameters(const ParserLine &line, unsigned ¶meterPosition) { + if (line.m_line[parameterPosition] != '(') + return std::vector<std::string>(); - parameterPosition++; - std::vector<std::string> parameters; + parameterPosition++; + std::vector<std::string> parameters; - while (true) - { - if (!SkipWhitespace(line, parameterPosition) || parameterPosition >= line.m_line.size()) - throw ParsingException(CreatePos(line, parameterPosition), "Invalid define parameter list"); + while (true) { + if (!SkipWhitespace(line, parameterPosition) || parameterPosition >= line.m_line.size()) + throw ParsingException(CreatePos(line, parameterPosition), "Invalid define parameter list"); - const auto nameStartPos = parameterPosition; - if (!ExtractIdentifier(line, parameterPosition)) - throw ParsingException(CreatePos(line, parameterPosition), "Cannot extract name of parameter of define"); + const auto nameStartPos = parameterPosition; + if (!ExtractIdentifier(line, parameterPosition)) + throw ParsingException(CreatePos(line, parameterPosition), "Cannot extract name of parameter of define"); - parameters.emplace_back(std::string(line.m_line, nameStartPos, parameterPosition - nameStartPos)); + parameters.emplace_back(std::string(line.m_line, nameStartPos, parameterPosition - nameStartPos)); - if (!SkipWhitespace(line, parameterPosition)) - throw ParsingException(CreatePos(line, parameterPosition), "Unclosed define parameters"); + if (!SkipWhitespace(line, parameterPosition)) + throw ParsingException(CreatePos(line, parameterPosition), "Unclosed define parameters"); - if (parameterPosition >= line.m_line.size()) - throw ParsingException(CreatePos(line, parameterPosition), "Unclosed define parameters"); + if (parameterPosition >= line.m_line.size()) + throw ParsingException(CreatePos(line, parameterPosition), "Unclosed define parameters"); - if (line.m_line[parameterPosition] == ')') - { - parameterPosition++; - break; - } + if (line.m_line[parameterPosition] == ')') { + parameterPosition++; + break; + } - if (line.m_line[parameterPosition] != ',') - throw ParsingException(CreatePos(line, parameterPosition), "Unknown symbol in define parameter list"); + if (line.m_line[parameterPosition] != ',') + throw ParsingException(CreatePos(line, parameterPosition), "Unknown symbol in define parameter list"); - parameterPosition++; - } + parameterPosition++; + } - return parameters; + return parameters; } -bool DefinesStreamProxy::MatchDefineDirective(const ParserLine& line, const unsigned directiveStartPosition, const unsigned directiveEndPosition) -{ - auto currentPos = directiveStartPosition; +bool DefinesStreamProxy::MatchDefineDirective(const ParserLine &line, const unsigned directiveStartPosition, const unsigned directiveEndPosition) { + auto currentPos = directiveStartPosition; - if (directiveEndPosition - directiveStartPosition != std::char_traits<char>::length(DEFINE_DIRECTIVE) - || !MatchString(line, currentPos, DEFINE_DIRECTIVE, std::char_traits<char>::length(DEFINE_DIRECTIVE))) - { - return false; - } + if (directiveEndPosition - directiveStartPosition != std::char_traits<char>::length(DEFINE_DIRECTIVE) || + !MatchString(line, currentPos, DEFINE_DIRECTIVE, std::char_traits<char>::length(DEFINE_DIRECTIVE))) { + return false; + } - if (!SkipWhitespace(line, currentPos)) - throw ParsingException(CreatePos(line, currentPos), "Cannot define without a name."); + if (!SkipWhitespace(line, currentPos)) + throw ParsingException(CreatePos(line, currentPos), "Cannot define without a name."); - const auto nameStartPos = currentPos; - if (!ExtractIdentifier(line, currentPos)) - throw ParsingException(CreatePos(line, currentPos), "Cannot define without a name."); + const auto nameStartPos = currentPos; + if (!ExtractIdentifier(line, currentPos)) + throw ParsingException(CreatePos(line, currentPos), "Cannot define without a name."); - const auto name = line.m_line.substr(nameStartPos, currentPos - nameStartPos); + const auto name = line.m_line.substr(nameStartPos, currentPos - nameStartPos); - auto parameters = MatchDefineParameters(line, currentPos); + auto parameters = MatchDefineParameters(line, currentPos); - const auto lineEndEscapePos = GetLineEndEscapePos(line); - if (lineEndEscapePos < 0) - { - std::string value; - if (currentPos < line.m_line.size()) - value = line.m_line.substr(currentPos + 1); + const auto lineEndEscapePos = GetLineEndEscapePos(line); + if (lineEndEscapePos < 0) { + std::string value; + if (currentPos < line.m_line.size()) + value = line.m_line.substr(currentPos + 1); - Define define(name, value); - define.IdentifyParameters(parameters); - AddDefine(std::move(define)); - } - else - { - m_in_define = true; - m_current_define = Define(name, std::string()); - m_current_define_value.str(std::string()); - m_current_define_parameters = std::move(parameters); - - if (currentPos < line.m_line.size() && (currentPos + 1) < static_cast<unsigned>(lineEndEscapePos)) - m_current_define_value << line.m_line.substr(currentPos + 1, static_cast<unsigned>(lineEndEscapePos) - (currentPos + 1)); - } + Define define(name, value); + define.IdentifyParameters(parameters); + AddDefine(std::move(define)); + } else { + m_in_define = true; + m_current_define = Define(name, std::string()); + m_current_define_value.str(std::string()); + m_current_define_parameters = std::move(parameters); - return true; + if (currentPos < line.m_line.size() && (currentPos + 1) < static_cast<unsigned>(lineEndEscapePos)) + m_current_define_value << line.m_line.substr(currentPos + 1, static_cast<unsigned>(lineEndEscapePos) - (currentPos + 1)); + } + + return true; } -bool DefinesStreamProxy::MatchUndefDirective(const ParserLine& line, const unsigned directiveStartPosition, const unsigned directiveEndPosition) -{ - auto currentPos = directiveStartPosition; +bool DefinesStreamProxy::MatchUndefDirective(const ParserLine &line, const unsigned directiveStartPosition, const unsigned directiveEndPosition) { + auto currentPos = directiveStartPosition; - if (directiveEndPosition - directiveStartPosition != std::char_traits<char>::length(UNDEF_DIRECTIVE) - || !MatchString(line, currentPos, UNDEF_DIRECTIVE, std::char_traits<char>::length(UNDEF_DIRECTIVE))) - { - return false; - } + if (directiveEndPosition - directiveStartPosition != std::char_traits<char>::length(UNDEF_DIRECTIVE) || + !MatchString(line, currentPos, UNDEF_DIRECTIVE, std::char_traits<char>::length(UNDEF_DIRECTIVE))) { + return false; + } - if (!SkipWhitespace(line, currentPos)) - throw ParsingException(CreatePos(line, currentPos), "Cannot undef without a name."); + if (!SkipWhitespace(line, currentPos)) + throw ParsingException(CreatePos(line, currentPos), "Cannot undef without a name."); - const auto nameStartPos = currentPos; - if (!ExtractIdentifier(line, currentPos)) - throw ParsingException(CreatePos(line, currentPos), "Cannot undef without a name."); + const auto nameStartPos = currentPos; + if (!ExtractIdentifier(line, currentPos)) + throw ParsingException(CreatePos(line, currentPos), "Cannot undef without a name."); - const auto name = line.m_line.substr(nameStartPos, currentPos - nameStartPos); - const auto entry = m_defines.find(name); + const auto name = line.m_line.substr(nameStartPos, currentPos - nameStartPos); + const auto entry = m_defines.find(name); - if (entry != m_defines.end()) - m_defines.erase(entry); + if (entry != m_defines.end()) + m_defines.erase(entry); - return true; + return true; } -std::unique_ptr<ISimpleExpression> DefinesStreamProxy::ParseExpression(std::shared_ptr<std::string> fileName, int lineNumber, std::string expressionString) const -{ - ParserLine pseudoLine(std::move(fileName), lineNumber, std::move(expressionString)); - ExpandDefinedExpressions(pseudoLine); - ExpandDefines(pseudoLine); +std::unique_ptr<ISimpleExpression> DefinesStreamProxy::ParseExpression(std::shared_ptr<std::string> fileName, int lineNumber, + std::string expressionString) const { + ParserLine pseudoLine(std::move(fileName), lineNumber, std::move(expressionString)); + ExpandDefinedExpressions(pseudoLine); + ExpandDefines(pseudoLine); - std::istringstream ss(pseudoLine.m_line); - ParserSingleInputStream inputStream(ss, "defines directive expression"); + std::istringstream ss(pseudoLine.m_line); + ParserSingleInputStream inputStream(ss, "defines directive expression"); - const SimpleExpressionInterpreter expressionInterpreter(&inputStream); - return expressionInterpreter.Evaluate(); + const SimpleExpressionInterpreter expressionInterpreter(&inputStream); + return expressionInterpreter.Evaluate(); } -bool DefinesStreamProxy::MatchIfDirective(const ParserLine& line, const unsigned directiveStartPosition, const unsigned directiveEndPosition) -{ - auto currentPos = directiveStartPosition; +bool DefinesStreamProxy::MatchIfDirective(const ParserLine &line, const unsigned directiveStartPosition, const unsigned directiveEndPosition) { + auto currentPos = directiveStartPosition; - if (directiveEndPosition - directiveStartPosition != std::char_traits<char>::length(IF_DIRECTIVE) - || !MatchString(line, currentPos, IF_DIRECTIVE, std::char_traits<char>::length(IF_DIRECTIVE))) - { - return false; - } + if (directiveEndPosition - directiveStartPosition != std::char_traits<char>::length(IF_DIRECTIVE) || + !MatchString(line, currentPos, IF_DIRECTIVE, std::char_traits<char>::length(IF_DIRECTIVE))) { + return false; + } - if (!m_modes.empty() && m_modes.top() != BlockMode::IN_BLOCK) - { - m_ignore_depth++; - return true; - } + if (!m_modes.empty() && m_modes.top() != BlockMode::IN_BLOCK) { + m_ignore_depth++; + return true; + } - if (!SkipWhitespace(line, currentPos)) - throw ParsingException(CreatePos(line, currentPos), "Cannot if without an expression."); + if (!SkipWhitespace(line, currentPos)) + throw ParsingException(CreatePos(line, currentPos), "Cannot if without an expression."); - const auto expressionString = line.m_line.substr(currentPos, line.m_line.size() - currentPos); + const auto expressionString = line.m_line.substr(currentPos, line.m_line.size() - currentPos); - if (expressionString.empty()) - throw ParsingException(CreatePos(line, currentPos), "Cannot if without an expression."); + if (expressionString.empty()) + throw ParsingException(CreatePos(line, currentPos), "Cannot if without an expression."); - const auto expression = ParseExpression(line.m_filename, line.m_line_number, expressionString); - if (!expression) - throw ParsingException(CreatePos(line, currentPos), "Failed to parse if expression"); + const auto expression = ParseExpression(line.m_filename, line.m_line_number, expressionString); + if (!expression) + throw ParsingException(CreatePos(line, currentPos), "Failed to parse if expression"); - m_modes.push(expression->EvaluateStatic().IsTruthy() ? BlockMode::IN_BLOCK : BlockMode::NOT_IN_BLOCK); + m_modes.push(expression->EvaluateStatic().IsTruthy() ? BlockMode::IN_BLOCK : BlockMode::NOT_IN_BLOCK); - return true; + return true; } -bool DefinesStreamProxy::MatchElIfDirective(const ParserLine& line, const unsigned directiveStartPosition, const unsigned directiveEndPosition) -{ - auto currentPos = directiveStartPosition; +bool DefinesStreamProxy::MatchElIfDirective(const ParserLine &line, const unsigned directiveStartPosition, const unsigned directiveEndPosition) { + auto currentPos = directiveStartPosition; - if (directiveEndPosition - directiveStartPosition != std::char_traits<char>::length(ELIF_DIRECTIVE) - || !MatchString(line, currentPos, ELIF_DIRECTIVE, std::char_traits<char>::length(ELIF_DIRECTIVE))) - { - return false; - } + if (directiveEndPosition - directiveStartPosition != std::char_traits<char>::length(ELIF_DIRECTIVE) || + !MatchString(line, currentPos, ELIF_DIRECTIVE, std::char_traits<char>::length(ELIF_DIRECTIVE))) { + return false; + } - if (m_ignore_depth > 0) - return true; + if (m_ignore_depth > 0) + return true; - if (m_modes.empty()) - throw ParsingException(CreatePos(line, currentPos), "Cannot use elif without if"); + if (m_modes.empty()) + throw ParsingException(CreatePos(line, currentPos), "Cannot use elif without if"); - if (m_modes.top() == BlockMode::BLOCK_BLOCKED) - return true; + if (m_modes.top() == BlockMode::BLOCK_BLOCKED) + return true; - if (m_modes.top() == BlockMode::IN_BLOCK) - { - m_modes.top() = BlockMode::BLOCK_BLOCKED; - return true; - } + if (m_modes.top() == BlockMode::IN_BLOCK) { + m_modes.top() = BlockMode::BLOCK_BLOCKED; + return true; + } - if (!SkipWhitespace(line, currentPos)) - throw ParsingException(CreatePos(line, currentPos), "Cannot elif without an expression."); + if (!SkipWhitespace(line, currentPos)) + throw ParsingException(CreatePos(line, currentPos), "Cannot elif without an expression."); - const auto expressionString = line.m_line.substr(currentPos, line.m_line.size() - currentPos); + const auto expressionString = line.m_line.substr(currentPos, line.m_line.size() - currentPos); - if (expressionString.empty()) - throw ParsingException(CreatePos(line, currentPos), "Cannot elif without an expression."); + if (expressionString.empty()) + throw ParsingException(CreatePos(line, currentPos), "Cannot elif without an expression."); - const auto expression = ParseExpression(line.m_filename, line.m_line_number, expressionString); - if (!expression) - throw ParsingException(CreatePos(line, currentPos), "Failed to parse elif expression"); + const auto expression = ParseExpression(line.m_filename, line.m_line_number, expressionString); + if (!expression) + throw ParsingException(CreatePos(line, currentPos), "Failed to parse elif expression"); - m_modes.top() = expression->EvaluateStatic().IsTruthy() ? BlockMode::IN_BLOCK : BlockMode::NOT_IN_BLOCK; + m_modes.top() = expression->EvaluateStatic().IsTruthy() ? BlockMode::IN_BLOCK : BlockMode::NOT_IN_BLOCK; - return true; + return true; } -bool DefinesStreamProxy::MatchIfdefDirective(const ParserLine& line, const unsigned directiveStartPosition, const unsigned directiveEndPosition) -{ - auto currentPos = directiveStartPosition; - - auto reverse = false; - if (directiveEndPosition - directiveStartPosition != std::char_traits<char>::length(IFDEF_DIRECTIVE) - || !MatchString(line, currentPos, IFDEF_DIRECTIVE, std::char_traits<char>::length(IFDEF_DIRECTIVE))) - { - if (directiveEndPosition - directiveStartPosition != std::char_traits<char>::length(IFNDEF_DIRECTIVE) - || !MatchString(line, currentPos, IFNDEF_DIRECTIVE, std::char_traits<char>::length(IFNDEF_DIRECTIVE))) - { - return false; - } +bool DefinesStreamProxy::MatchIfdefDirective(const ParserLine &line, const unsigned directiveStartPosition, const unsigned directiveEndPosition) { + auto currentPos = directiveStartPosition; - reverse = true; + auto reverse = false; + if (directiveEndPosition - directiveStartPosition != std::char_traits<char>::length(IFDEF_DIRECTIVE) || + !MatchString(line, currentPos, IFDEF_DIRECTIVE, std::char_traits<char>::length(IFDEF_DIRECTIVE))) { + if (directiveEndPosition - directiveStartPosition != std::char_traits<char>::length(IFNDEF_DIRECTIVE) || + !MatchString(line, currentPos, IFNDEF_DIRECTIVE, std::char_traits<char>::length(IFNDEF_DIRECTIVE))) { + return false; } - if (!m_modes.empty() && m_modes.top() != BlockMode::IN_BLOCK) - { - m_ignore_depth++; - return true; - } + reverse = true; + } - if (!SkipWhitespace(line, currentPos)) - throw ParsingException(CreatePos(line, currentPos), "Cannot ifdef without a name."); + if (!m_modes.empty() && m_modes.top() != BlockMode::IN_BLOCK) { + m_ignore_depth++; + return true; + } - const auto nameStartPos = currentPos; - if (!ExtractIdentifier(line, currentPos)) - throw ParsingException(CreatePos(line, currentPos), "Cannot ifdef without a name."); + if (!SkipWhitespace(line, currentPos)) + throw ParsingException(CreatePos(line, currentPos), "Cannot ifdef without a name."); - const auto name = line.m_line.substr(nameStartPos, currentPos - nameStartPos); - const auto entry = m_defines.find(name); + const auto nameStartPos = currentPos; + if (!ExtractIdentifier(line, currentPos)) + throw ParsingException(CreatePos(line, currentPos), "Cannot ifdef without a name."); - if (entry != m_defines.end()) - m_modes.push(!reverse ? BlockMode::IN_BLOCK : BlockMode::NOT_IN_BLOCK); - else - m_modes.push(reverse ? BlockMode::IN_BLOCK : BlockMode::NOT_IN_BLOCK); + const auto name = line.m_line.substr(nameStartPos, currentPos - nameStartPos); + const auto entry = m_defines.find(name); - return true; + if (entry != m_defines.end()) + m_modes.push(!reverse ? BlockMode::IN_BLOCK : BlockMode::NOT_IN_BLOCK); + else + m_modes.push(reverse ? BlockMode::IN_BLOCK : BlockMode::NOT_IN_BLOCK); + + return true; } -bool DefinesStreamProxy::MatchElseDirective(const ParserLine& line, const unsigned directiveStartPosition, const unsigned directiveEndPosition) -{ - auto currentPos = directiveStartPosition; +bool DefinesStreamProxy::MatchElseDirective(const ParserLine &line, const unsigned directiveStartPosition, const unsigned directiveEndPosition) { + auto currentPos = directiveStartPosition; - if (directiveEndPosition - directiveStartPosition != std::char_traits<char>::length(ELSE_DIRECTIVE) - || !MatchString(line, currentPos, ELSE_DIRECTIVE, std::char_traits<char>::length(ELSE_DIRECTIVE))) - { - return false; - } + if (directiveEndPosition - directiveStartPosition != std::char_traits<char>::length(ELSE_DIRECTIVE) || + !MatchString(line, currentPos, ELSE_DIRECTIVE, std::char_traits<char>::length(ELSE_DIRECTIVE))) { + return false; + } - if (m_ignore_depth > 0) - return true; + if (m_ignore_depth > 0) + return true; - if (m_modes.empty()) - throw ParsingException(CreatePos(line, currentPos), "Cannot use else without ifdef"); + if (m_modes.empty()) + throw ParsingException(CreatePos(line, currentPos), "Cannot use else without ifdef"); - m_modes.top() = m_modes.top() == BlockMode::NOT_IN_BLOCK ? BlockMode::IN_BLOCK : BlockMode::BLOCK_BLOCKED; + m_modes.top() = m_modes.top() == BlockMode::NOT_IN_BLOCK ? BlockMode::IN_BLOCK : BlockMode::BLOCK_BLOCKED; - return true; + return true; } -bool DefinesStreamProxy::MatchEndifDirective(const ParserLine& line, const unsigned directiveStartPosition, const unsigned directiveEndPosition) -{ - auto currentPos = directiveStartPosition; +bool DefinesStreamProxy::MatchEndifDirective(const ParserLine &line, const unsigned directiveStartPosition, const unsigned directiveEndPosition) { + auto currentPos = directiveStartPosition; - if (directiveEndPosition - directiveStartPosition != std::char_traits<char>::length(ENDIF_DIRECTIVE) - || !MatchString(line, currentPos, ENDIF_DIRECTIVE, std::char_traits<char>::length(ENDIF_DIRECTIVE))) - { - return false; - } + if (directiveEndPosition - directiveStartPosition != std::char_traits<char>::length(ENDIF_DIRECTIVE) || + !MatchString(line, currentPos, ENDIF_DIRECTIVE, std::char_traits<char>::length(ENDIF_DIRECTIVE))) { + return false; + } - if (m_ignore_depth > 0) - { - m_ignore_depth--; - return true; - } + if (m_ignore_depth > 0) { + m_ignore_depth--; + return true; + } - if (!m_modes.empty()) - m_modes.pop(); - else - throw ParsingException(CreatePos(line, currentPos), "Cannot use endif without ifdef"); + if (!m_modes.empty()) + m_modes.pop(); + else + throw ParsingException(CreatePos(line, currentPos), "Cannot use endif without ifdef"); - return true; + return true; } -bool DefinesStreamProxy::MatchDirectives(const ParserLine& line) -{ - unsigned directiveStartPos; - unsigned directiveEndPos; +bool DefinesStreamProxy::MatchDirectives(const ParserLine &line) { + unsigned directiveStartPos; + unsigned directiveEndPos; - if (!FindDirective(line, directiveStartPos, directiveEndPos)) - return false; + if (!FindDirective(line, directiveStartPos, directiveEndPos)) + return false; - directiveStartPos++; + directiveStartPos++; - if (m_modes.empty() || m_modes.top() == BlockMode::IN_BLOCK) - { - if (MatchDefineDirective(line, directiveStartPos, directiveEndPos) - || MatchUndefDirective(line, directiveStartPos, directiveEndPos)) - return true; - } + if (m_modes.empty() || m_modes.top() == BlockMode::IN_BLOCK) { + if (MatchDefineDirective(line, directiveStartPos, directiveEndPos) || MatchUndefDirective(line, directiveStartPos, directiveEndPos)) + return true; + } - return MatchIfdefDirective(line, directiveStartPos, directiveEndPos) - || MatchIfDirective(line, directiveStartPos, directiveEndPos) - || MatchElIfDirective(line, directiveStartPos, directiveEndPos) - || MatchElseDirective(line, directiveStartPos, directiveEndPos) - || MatchEndifDirective(line, directiveStartPos, directiveEndPos); + return MatchIfdefDirective(line, directiveStartPos, directiveEndPos) || MatchIfDirective(line, directiveStartPos, directiveEndPos) || + MatchElIfDirective(line, directiveStartPos, directiveEndPos) || MatchElseDirective(line, directiveStartPos, directiveEndPos) || + MatchEndifDirective(line, directiveStartPos, directiveEndPos); } -bool DefinesStreamProxy::FindDefineForWord(const ParserLine& line, const unsigned wordStart, const unsigned wordEnd, const Define*& value) const -{ - const std::string word(line.m_line, wordStart, wordEnd - wordStart); - const auto foundEntry = m_defines.find(word); - if (foundEntry != m_defines.end()) - { - value = &foundEntry->second; - return true; - } +bool DefinesStreamProxy::FindDefineForWord(const ParserLine &line, const unsigned wordStart, const unsigned wordEnd, const Define *&value) const { + const std::string word(line.m_line, wordStart, wordEnd - wordStart); + const auto foundEntry = m_defines.find(word); + if (foundEntry != m_defines.end()) { + value = &foundEntry->second; + return true; + } - return false; + return false; } -void DefinesStreamProxy::ExtractParametersFromDefineUsage(const ParserLine& line, const unsigned parameterStart, unsigned& parameterEnd, std::vector<std::string>& parameterValues) -{ - if (line.m_line[parameterStart] != '(') - return; - - std::ostringstream currentValue; - auto pos = parameterStart + 1; - auto valueHasStarted = false; - auto parenthesisDepth = 0; - while (true) - { - if (pos >= line.m_line.size()) - throw ParsingException(CreatePos(line, pos), "Invalid use of define"); - - const auto c = line.m_line[pos]; - - if (c == ',') - { - if (parenthesisDepth > 0) - { - valueHasStarted = true; - currentValue << c; - } - else - { - parameterValues.emplace_back(currentValue.str()); - currentValue.clear(); - currentValue.str(std::string()); - valueHasStarted = false; - } - } - else if (c == '(') - { - valueHasStarted = true; - parenthesisDepth++; - currentValue << c; - } - else if (c == ')') - { - if (parenthesisDepth > 0) - { - valueHasStarted = true; - parenthesisDepth--; - currentValue << c; - } - else - { - parameterValues.emplace_back(currentValue.str()); - parameterEnd = pos + 1; - break; - } - } - else if (valueHasStarted || !isspace(c)) - { - valueHasStarted = true; - currentValue << c; - } - - pos++; +void DefinesStreamProxy::ExtractParametersFromDefineUsage(const ParserLine &line, const unsigned parameterStart, unsigned ¶meterEnd, + std::vector<std::string> ¶meterValues) { + if (line.m_line[parameterStart] != '(') + return; + + std::ostringstream currentValue; + auto pos = parameterStart + 1; + auto valueHasStarted = false; + auto parenthesisDepth = 0; + while (true) { + if (pos >= line.m_line.size()) + throw ParsingException(CreatePos(line, pos), "Invalid use of define"); + + const auto c = line.m_line[pos]; + + if (c == ',') { + if (parenthesisDepth > 0) { + valueHasStarted = true; + currentValue << c; + } else { + parameterValues.emplace_back(currentValue.str()); + currentValue.clear(); + currentValue.str(std::string()); + valueHasStarted = false; + } + } else if (c == '(') { + valueHasStarted = true; + parenthesisDepth++; + currentValue << c; + } else if (c == ')') { + if (parenthesisDepth > 0) { + valueHasStarted = true; + parenthesisDepth--; + currentValue << c; + } else { + parameterValues.emplace_back(currentValue.str()); + parameterEnd = pos + 1; + break; + } + } else if (valueHasStarted || !isspace(c)) { + valueHasStarted = true; + currentValue << c; } + + pos++; + } } -bool DefinesStreamProxy::MatchDefinedExpression(const ParserLine& line, unsigned& pos, std::string& definitionName) -{ - unsigned currentPos = pos; - - if (!MatchNextCharacter(line, currentPos, '(')) - return false; +bool DefinesStreamProxy::MatchDefinedExpression(const ParserLine &line, unsigned &pos, std::string &definitionName) { + unsigned currentPos = pos; - const auto nameStartPos = currentPos; - if (!ExtractIdentifier(line, currentPos)) - return false; + if (!MatchNextCharacter(line, currentPos, '(')) + return false; - const auto nameEndPos = currentPos; - if (!MatchNextCharacter(line, currentPos, ')')) - return false; + const auto nameStartPos = currentPos; + if (!ExtractIdentifier(line, currentPos)) + return false; - pos = currentPos; - definitionName = line.m_line.substr(nameStartPos, nameEndPos - nameStartPos); - return true; -} + const auto nameEndPos = currentPos; + if (!MatchNextCharacter(line, currentPos, ')')) + return false; -void DefinesStreamProxy::ExpandDefinedExpressions(ParserLine& line) const -{ - auto currentPos = 0u; + pos = currentPos; + definitionName = line.m_line.substr(nameStartPos, nameEndPos - nameStartPos); + return true; +} - while (true) - { - const auto definedPos = line.m_line.find(DEFINED_KEYWORD, currentPos); - if (definedPos == std::string::npos) - break; +void DefinesStreamProxy::ExpandDefinedExpressions(ParserLine &line) const { + auto currentPos = 0u; - currentPos = definedPos; + while (true) { + const auto definedPos = line.m_line.find(DEFINED_KEYWORD, currentPos); + if (definedPos == std::string::npos) + break; - if (definedPos > 0 && !isspace(line.m_line[definedPos - 1])) - { - currentPos += std::char_traits<char>::length(DEFINED_KEYWORD); - continue; - } + currentPos = definedPos; - auto definitionEndPos = currentPos + std::char_traits<char>::length(DEFINED_KEYWORD); - std::string definitionName; - if (!MatchDefinedExpression(line, definitionEndPos, definitionName)) - { - currentPos += std::char_traits<char>::length(DEFINED_KEYWORD); - continue; - } + if (definedPos > 0 && !isspace(line.m_line[definedPos - 1])) { + currentPos += std::char_traits<char>::length(DEFINED_KEYWORD); + continue; + } - const auto entry = m_defines.find(definitionName); - line.m_line.replace(currentPos, definitionEndPos - currentPos, entry != m_defines.end() ? "1" : "0"); + auto definitionEndPos = currentPos + std::char_traits<char>::length(DEFINED_KEYWORD); + std::string definitionName; + if (!MatchDefinedExpression(line, definitionEndPos, definitionName)) { + currentPos += std::char_traits<char>::length(DEFINED_KEYWORD); + continue; } + + const auto entry = m_defines.find(definitionName); + line.m_line.replace(currentPos, definitionEndPos - currentPos, entry != m_defines.end() ? "1" : "0"); + } } -void DefinesStreamProxy::ExpandDefines(ParserLine& line) const -{ - bool usesDefines; - auto defineIterations = 0u; - - do - { - if (defineIterations > MAX_DEFINE_ITERATIONS) - throw ParsingException(CreatePos(line, 1), "Potential define loop? Exceeded max define iterations of " + std::to_string(MAX_DEFINE_ITERATIONS) + " iterations."); - - usesDefines = false; - - auto wordStart = 0u; - auto lastWordEnd = 0u; - auto inWord = false; - const Define* value; - std::ostringstream str; - - for (auto i = 0u; i < line.m_line.size(); i++) - { - const auto c = line.m_line[i]; - if (!inWord) - { - if (isalpha(c) || c == '_') - { - wordStart = i; - inWord = true; - } - } - else - { - if (!isalnum(c) && c != '_') - { - if (FindDefineForWord(line, wordStart, i, value)) - { - std::vector<std::string> parameterValues; - ExtractParametersFromDefineUsage(line, i, i, parameterValues); - const auto defineValue = value->Render(parameterValues); - - if (!usesDefines) - { - str << std::string(line.m_line, 0, wordStart) << defineValue; - usesDefines = true; - } - else - { - str << std::string(line.m_line, lastWordEnd, wordStart - lastWordEnd) << defineValue; - } - lastWordEnd = i; - } - inWord = false; - } - } - } +void DefinesStreamProxy::ExpandDefines(ParserLine &line) const { + bool usesDefines; + auto defineIterations = 0u; + + do { + if (defineIterations > MAX_DEFINE_ITERATIONS) + throw ParsingException(CreatePos(line, 1), + "Potential define loop? Exceeded max define iterations of " + std::to_string(MAX_DEFINE_ITERATIONS) + " iterations."); - if (inWord) - { - if (FindDefineForWord(line, wordStart, line.m_line.size(), value)) - { - const std::vector<std::string> parameterValues; - const auto defineValue = value->Render(parameterValues); - - if (!usesDefines) - { - str << std::string(line.m_line, 0, wordStart) << defineValue; - usesDefines = true; - } - else - { - str << std::string(line.m_line, lastWordEnd, wordStart - lastWordEnd) << defineValue; - } - lastWordEnd = line.m_line.size(); + usesDefines = false; + + auto wordStart = 0u; + auto lastWordEnd = 0u; + auto inWord = false; + const Define *value; + std::ostringstream str; + + for (auto i = 0u; i < line.m_line.size(); i++) { + const auto c = line.m_line[i]; + if (!inWord) { + if (isalpha(c) || c == '_') { + wordStart = i; + inWord = true; + } + } else { + if (!isalnum(c) && c != '_') { + if (FindDefineForWord(line, wordStart, i, value)) { + std::vector<std::string> parameterValues; + ExtractParametersFromDefineUsage(line, i, i, parameterValues); + const auto defineValue = value->Render(parameterValues); + + if (!usesDefines) { + str << std::string(line.m_line, 0, wordStart) << defineValue; + usesDefines = true; + } else { + str << std::string(line.m_line, lastWordEnd, wordStart - lastWordEnd) << defineValue; } + lastWordEnd = i; + } + inWord = false; } + } + } - if (usesDefines) - { - if (lastWordEnd < line.m_line.size()) - str << std::string(line.m_line, lastWordEnd, line.m_line.size() - lastWordEnd); - line.m_line = str.str(); + if (inWord) { + if (FindDefineForWord(line, wordStart, line.m_line.size(), value)) { + const std::vector<std::string> parameterValues; + const auto defineValue = value->Render(parameterValues); + + if (!usesDefines) { + str << std::string(line.m_line, 0, wordStart) << defineValue; + usesDefines = true; + } else { + str << std::string(line.m_line, lastWordEnd, wordStart - lastWordEnd) << defineValue; } + lastWordEnd = line.m_line.size(); + } + } - defineIterations++; + if (usesDefines) { + if (lastWordEnd < line.m_line.size()) + str << std::string(line.m_line, lastWordEnd, line.m_line.size() - lastWordEnd); + line.m_line = str.str(); } - while (usesDefines); -} -void DefinesStreamProxy::AddDefine(Define define) -{ - m_defines[define.m_name] = std::move(define); + defineIterations++; + } while (usesDefines); } -void DefinesStreamProxy::Undefine(const std::string& name) -{ - const auto entry = m_defines.find(name); - - if (entry != m_defines.end()) - m_defines.erase(entry); -} +void DefinesStreamProxy::AddDefine(Define define) { m_defines[define.m_name] = std::move(define); } -ParserLine DefinesStreamProxy::NextLine() -{ - auto line = m_stream->NextLine(); - - while (true) - { - if (m_in_define) - { - ContinueDefine(line); - if (!m_skip_directive_lines) - { - line.m_line = std::string(); - return line; - } +void DefinesStreamProxy::Undefine(const std::string &name) { + const auto entry = m_defines.find(name); - line = m_stream->NextLine(); - } - else if (MatchDirectives(line) || !m_modes.empty() && m_modes.top() != BlockMode::IN_BLOCK) - { - if (!m_skip_directive_lines) - { - line.m_line = std::string(); - return line; - } + if (entry != m_defines.end()) + m_defines.erase(entry); +} - line = m_stream->NextLine(); - } - else - { - ExpandDefines(line); - return line; - } +ParserLine DefinesStreamProxy::NextLine() { + auto line = m_stream->NextLine(); + + while (true) { + if (m_in_define) { + ContinueDefine(line); + if (!m_skip_directive_lines) { + line.m_line = std::string(); + return line; + } + + line = m_stream->NextLine(); + } else if (MatchDirectives(line) || !m_modes.empty() && m_modes.top() != BlockMode::IN_BLOCK) { + if (!m_skip_directive_lines) { + line.m_line = std::string(); + return line; + } + + line = m_stream->NextLine(); + } else { + ExpandDefines(line); + return line; } + } } -bool DefinesStreamProxy::IncludeFile(const std::string& filename) -{ - return m_stream->IncludeFile(filename); -} +bool DefinesStreamProxy::IncludeFile(const std::string &filename) { return m_stream->IncludeFile(filename); } -void DefinesStreamProxy::PopCurrentFile() -{ - m_stream->PopCurrentFile(); -} +void DefinesStreamProxy::PopCurrentFile() { m_stream->PopCurrentFile(); } -bool DefinesStreamProxy::IsOpen() const -{ - return m_stream->IsOpen(); -} +bool DefinesStreamProxy::IsOpen() const { return m_stream->IsOpen(); } -bool DefinesStreamProxy::Eof() const -{ - return m_stream->Eof(); -} +bool DefinesStreamProxy::Eof() const { return m_stream->Eof(); } diff --git a/src/Parser/Parsing/Impl/DefinesStreamProxy.h b/src/Parser/Parsing/Impl/DefinesStreamProxy.h index 77188981b..3061fc0fb 100644 --- a/src/Parser/Parsing/Impl/DefinesStreamProxy.h +++ b/src/Parser/Parsing/Impl/DefinesStreamProxy.h @@ -1,101 +1,94 @@ #pragma once #include <map> -#include <stack> #include <sstream> +#include <stack> #include "AbstractDirectiveStreamProxy.h" #include "Parsing/IParserLineStream.h" #include "Parsing/Simple/Expression/ISimpleExpression.h" -class DefinesStreamProxy final : public AbstractDirectiveStreamProxy -{ - static constexpr const char* DEFINE_DIRECTIVE = "define"; - static constexpr const char* UNDEF_DIRECTIVE = "undef"; - static constexpr const char* IF_DIRECTIVE = "if"; - static constexpr const char* ELIF_DIRECTIVE = "elif"; - static constexpr const char* IFDEF_DIRECTIVE = "ifdef"; - static constexpr const char* IFNDEF_DIRECTIVE = "ifndef"; - static constexpr const char* ELSE_DIRECTIVE = "else"; - static constexpr const char* ENDIF_DIRECTIVE = "endif"; - static constexpr const char* DEFINED_KEYWORD = "defined"; +class DefinesStreamProxy final : public AbstractDirectiveStreamProxy { + static constexpr const char *DEFINE_DIRECTIVE = "define"; + static constexpr const char *UNDEF_DIRECTIVE = "undef"; + static constexpr const char *IF_DIRECTIVE = "if"; + static constexpr const char *ELIF_DIRECTIVE = "elif"; + static constexpr const char *IFDEF_DIRECTIVE = "ifdef"; + static constexpr const char *IFNDEF_DIRECTIVE = "ifndef"; + static constexpr const char *ELSE_DIRECTIVE = "else"; + static constexpr const char *ENDIF_DIRECTIVE = "endif"; + static constexpr const char *DEFINED_KEYWORD = "defined"; - static constexpr auto MAX_DEFINE_ITERATIONS = 128u; + static constexpr auto MAX_DEFINE_ITERATIONS = 128u; public: - class DefineParameterPosition - { - public: - unsigned m_parameter_index; - unsigned m_parameter_position; - - DefineParameterPosition(); - DefineParameterPosition(unsigned index, unsigned position); - }; - - class Define - { - public: - std::string m_name; - std::string m_value; - std::vector<DefineParameterPosition> m_parameter_positions; - - Define(); - Define(std::string name, std::string value); - void IdentifyParameters(const std::vector<std::string>& parameterNames); - _NODISCARD std::string Render(const std::vector<std::string>& parameterValues) const; - }; + class DefineParameterPosition { + public: + unsigned m_parameter_index; + unsigned m_parameter_position; + + DefineParameterPosition(); + DefineParameterPosition(unsigned index, unsigned position); + }; + + class Define { + public: + std::string m_name; + std::string m_value; + std::vector<DefineParameterPosition> m_parameter_positions; + + Define(); + Define(std::string name, std::string value); + void IdentifyParameters(const std::vector<std::string> ¶meterNames); + _NODISCARD std::string Render(const std::vector<std::string> ¶meterValues) const; + }; private: - enum class BlockMode - { - NOT_IN_BLOCK, - IN_BLOCK, - BLOCK_BLOCKED - }; - - IParserLineStream* const m_stream; - const bool m_skip_directive_lines; - std::map<std::string, Define> m_defines; - std::stack<BlockMode> m_modes; - unsigned m_ignore_depth; - - bool m_in_define; - Define m_current_define; - std::ostringstream m_current_define_value; - std::vector<std::string> m_current_define_parameters; - - static int GetLineEndEscapePos(const ParserLine& line); - static std::vector<std::string> MatchDefineParameters(const ParserLine& line, unsigned& parameterPosition); - void ContinueDefine(const ParserLine& line); - _NODISCARD bool MatchDefineDirective(const ParserLine& line, unsigned directiveStartPosition, unsigned directiveEndPosition); - _NODISCARD bool MatchUndefDirective(const ParserLine& line, unsigned directiveStartPosition, unsigned directiveEndPosition); - _NODISCARD bool MatchIfDirective(const ParserLine& line, unsigned directiveStartPosition, unsigned directiveEndPosition); - _NODISCARD bool MatchElIfDirective(const ParserLine& line, unsigned directiveStartPosition, unsigned directiveEndPosition); - _NODISCARD bool MatchIfdefDirective(const ParserLine& line, unsigned directiveStartPosition, unsigned directiveEndPosition); - _NODISCARD bool MatchElseDirective(const ParserLine& line, unsigned directiveStartPosition, unsigned directiveEndPosition); - _NODISCARD bool MatchEndifDirective(const ParserLine& line, unsigned directiveStartPosition, unsigned directiveEndPosition); - _NODISCARD bool MatchDirectives(const ParserLine& line); - - static void ExtractParametersFromDefineUsage(const ParserLine& line, unsigned parameterStart, unsigned& parameterEnd, std::vector<std::string>& parameterValues); - bool FindDefineForWord(const ParserLine& line, unsigned wordStart, unsigned wordEnd, const Define*& value) const; - - static bool MatchDefinedExpression(const ParserLine& line, unsigned& pos, std::string& definitionName); - void ExpandDefinedExpressions(ParserLine& line) const; + enum class BlockMode { NOT_IN_BLOCK, IN_BLOCK, BLOCK_BLOCKED }; + + IParserLineStream *const m_stream; + const bool m_skip_directive_lines; + std::map<std::string, Define> m_defines; + std::stack<BlockMode> m_modes; + unsigned m_ignore_depth; + + bool m_in_define; + Define m_current_define; + std::ostringstream m_current_define_value; + std::vector<std::string> m_current_define_parameters; + + static int GetLineEndEscapePos(const ParserLine &line); + static std::vector<std::string> MatchDefineParameters(const ParserLine &line, unsigned ¶meterPosition); + void ContinueDefine(const ParserLine &line); + _NODISCARD bool MatchDefineDirective(const ParserLine &line, unsigned directiveStartPosition, unsigned directiveEndPosition); + _NODISCARD bool MatchUndefDirective(const ParserLine &line, unsigned directiveStartPosition, unsigned directiveEndPosition); + _NODISCARD bool MatchIfDirective(const ParserLine &line, unsigned directiveStartPosition, unsigned directiveEndPosition); + _NODISCARD bool MatchElIfDirective(const ParserLine &line, unsigned directiveStartPosition, unsigned directiveEndPosition); + _NODISCARD bool MatchIfdefDirective(const ParserLine &line, unsigned directiveStartPosition, unsigned directiveEndPosition); + _NODISCARD bool MatchElseDirective(const ParserLine &line, unsigned directiveStartPosition, unsigned directiveEndPosition); + _NODISCARD bool MatchEndifDirective(const ParserLine &line, unsigned directiveStartPosition, unsigned directiveEndPosition); + _NODISCARD bool MatchDirectives(const ParserLine &line); + + static void ExtractParametersFromDefineUsage(const ParserLine &line, unsigned parameterStart, unsigned ¶meterEnd, + std::vector<std::string> ¶meterValues); + bool FindDefineForWord(const ParserLine &line, unsigned wordStart, unsigned wordEnd, const Define *&value) const; + + static bool MatchDefinedExpression(const ParserLine &line, unsigned &pos, std::string &definitionName); + void ExpandDefinedExpressions(ParserLine &line) const; public: - explicit DefinesStreamProxy(IParserLineStream* stream, bool skipDirectiveLines = false); + explicit DefinesStreamProxy(IParserLineStream *stream, bool skipDirectiveLines = false); - void AddDefine(Define define); - void Undefine(const std::string& name); + void AddDefine(Define define); + void Undefine(const std::string &name); - void ExpandDefines(ParserLine& line) const; + void ExpandDefines(ParserLine &line) const; - _NODISCARD std::unique_ptr<ISimpleExpression> ParseExpression(std::shared_ptr<std::string> fileName, int lineNumber, std::string expressionString) const; + _NODISCARD std::unique_ptr<ISimpleExpression> ParseExpression(std::shared_ptr<std::string> fileName, int lineNumber, std::string expressionString) const; - ParserLine NextLine() override; - bool IncludeFile(const std::string& filename) override; - void PopCurrentFile() override; - _NODISCARD bool IsOpen() const override; - _NODISCARD bool Eof() const override; + ParserLine NextLine() override; + bool IncludeFile(const std::string &filename) override; + void PopCurrentFile() override; + _NODISCARD bool IsOpen() const override; + _NODISCARD bool Eof() const override; }; diff --git a/src/Parser/Parsing/Impl/IncludingStreamProxy.cpp b/src/Parser/Parsing/Impl/IncludingStreamProxy.cpp index bd1b38c8c..39007137b 100644 --- a/src/Parser/Parsing/Impl/IncludingStreamProxy.cpp +++ b/src/Parser/Parsing/Impl/IncludingStreamProxy.cpp @@ -1,158 +1,131 @@ #include "IncludingStreamProxy.h" -#include <sstream> #include <filesystem> +#include <sstream> #include "Parsing/ParsingException.h" namespace fs = std::filesystem; -IncludingStreamProxy::IncludingStreamProxy(IParserLineStream* stream) - : m_stream(stream) -{ -} +IncludingStreamProxy::IncludingStreamProxy(IParserLineStream *stream) : m_stream(stream) {} + +bool IncludingStreamProxy::ExtractIncludeFilename(const ParserLine &line, const unsigned includeDirectivePosition, unsigned &filenameStartPosition, + unsigned &filenameEndPosition) { + auto currentPos = includeDirectivePosition; + bool isDoubleQuotes; + + while (isspace(line.m_line[currentPos])) { + if (currentPos++ >= line.m_line.size()) + throw ParsingException(CreatePos(line, currentPos - 1), INCLUDE_QUOTES_ERROR); + } + + if (line.m_line[currentPos] == '"') + isDoubleQuotes = true; + else if (line.m_line[currentPos] == '<') + isDoubleQuotes = false; + else + throw ParsingException(CreatePos(line, currentPos - 1), INCLUDE_QUOTES_ERROR); -bool IncludingStreamProxy::ExtractIncludeFilename(const ParserLine& line, const unsigned includeDirectivePosition, unsigned& filenameStartPosition, unsigned& filenameEndPosition) -{ - auto currentPos = includeDirectivePosition; - bool isDoubleQuotes; + filenameStartPosition = ++currentPos; + filenameEndPosition = 0; - while (isspace(line.m_line[currentPos])) - { - if (currentPos++ >= line.m_line.size()) - throw ParsingException(CreatePos(line, currentPos - 1), INCLUDE_QUOTES_ERROR); + for (; currentPos < line.m_line.size(); currentPos++) { + const auto c = line.m_line[currentPos]; + + if (c == '"') { + if (!isDoubleQuotes) + throw ParsingException(CreatePos(line, currentPos - 1), ""); + filenameEndPosition = currentPos; + return true; } - if (line.m_line[currentPos] == '"') - isDoubleQuotes = true; - else if (line.m_line[currentPos] == '<') - isDoubleQuotes = false; - else + if (c == '>') { + if (isDoubleQuotes) throw ParsingException(CreatePos(line, currentPos - 1), INCLUDE_QUOTES_ERROR); - - filenameStartPosition = ++currentPos; - filenameEndPosition = 0; - - for (; currentPos < line.m_line.size(); currentPos++) - { - const auto c = line.m_line[currentPos]; - - if (c == '"') - { - if (!isDoubleQuotes) - throw ParsingException(CreatePos(line, currentPos - 1), ""); - filenameEndPosition = currentPos; - return true; - } - - if (c == '>') - { - if (isDoubleQuotes) - throw ParsingException(CreatePos(line, currentPos - 1), INCLUDE_QUOTES_ERROR); - filenameEndPosition = currentPos; - return true; - } + filenameEndPosition = currentPos; + return true; } + } - return false; + return false; } -bool IncludingStreamProxy::MatchIncludeDirective(const ParserLine& line, const unsigned directiveStartPos, const unsigned directiveEndPos) const -{ - auto currentPos = directiveStartPos; +bool IncludingStreamProxy::MatchIncludeDirective(const ParserLine &line, const unsigned directiveStartPos, const unsigned directiveEndPos) const { + auto currentPos = directiveStartPos; - if (directiveEndPos - directiveStartPos != std::char_traits<char>::length(INCLUDE_DIRECTIVE) - || !MatchString(line, currentPos, INCLUDE_DIRECTIVE, std::char_traits<char>::length(INCLUDE_DIRECTIVE))) - { - return false; - } - - unsigned filenameStart, filenameEnd; + if (directiveEndPos - directiveStartPos != std::char_traits<char>::length(INCLUDE_DIRECTIVE) || + !MatchString(line, currentPos, INCLUDE_DIRECTIVE, std::char_traits<char>::length(INCLUDE_DIRECTIVE))) { + return false; + } - if (!ExtractIncludeFilename(line, currentPos, filenameStart, filenameEnd)) - throw ParsingException(TokenPos(*line.m_filename, line.m_line_number, static_cast<int>(currentPos)), INCLUDE_QUOTES_ERROR); + unsigned filenameStart, filenameEnd; - if (filenameEnd <= filenameStart) - throw ParsingException(CreatePos(line, currentPos), "No filename specified"); + if (!ExtractIncludeFilename(line, currentPos, filenameStart, filenameEnd)) + throw ParsingException(TokenPos(*line.m_filename, line.m_line_number, static_cast<int>(currentPos)), INCLUDE_QUOTES_ERROR); - const auto filename = line.m_line.substr(filenameStart, filenameEnd - filenameStart); + if (filenameEnd <= filenameStart) + throw ParsingException(CreatePos(line, currentPos), "No filename specified"); - if (!m_stream->IncludeFile(filename)) - { - std::ostringstream errorStr; - errorStr << "Could not include file \"" << filename << "\""; - throw ParsingException(CreatePos(line, currentPos), errorStr.str()); - } + const auto filename = line.m_line.substr(filenameStart, filenameEnd - filenameStart); - return true; + if (!m_stream->IncludeFile(filename)) { + std::ostringstream errorStr; + errorStr << "Could not include file \"" << filename << "\""; + throw ParsingException(CreatePos(line, currentPos), errorStr.str()); + } + + return true; } -bool IncludingStreamProxy::MatchPragmaOnceDirective(const ParserLine& line, const unsigned directiveStartPos, const unsigned directiveEndPos) -{ - auto currentPos = directiveStartPos; +bool IncludingStreamProxy::MatchPragmaOnceDirective(const ParserLine &line, const unsigned directiveStartPos, const unsigned directiveEndPos) { + auto currentPos = directiveStartPos; - if(directiveEndPos - directiveStartPos != std::char_traits<char>::length(PRAGMA_DIRECTIVE) - || !MatchString(line, currentPos, PRAGMA_DIRECTIVE, std::char_traits<char>::length(PRAGMA_DIRECTIVE))) - { - return false; - } + if (directiveEndPos - directiveStartPos != std::char_traits<char>::length(PRAGMA_DIRECTIVE) || + !MatchString(line, currentPos, PRAGMA_DIRECTIVE, std::char_traits<char>::length(PRAGMA_DIRECTIVE))) { + return false; + } - if (!SkipWhitespace(line, currentPos)) - return false; + if (!SkipWhitespace(line, currentPos)) + return false; - if (!MatchString(line, currentPos, ONCE_PRAGMA_COMMAND, std::char_traits<char>::length(ONCE_PRAGMA_COMMAND))) - return false; + if (!MatchString(line, currentPos, ONCE_PRAGMA_COMMAND, std::char_traits<char>::length(ONCE_PRAGMA_COMMAND))) + return false; - const auto absolutePath = absolute(fs::path(*line.m_filename)); - const auto absolutePathStr = absolutePath.string(); + const auto absolutePath = absolute(fs::path(*line.m_filename)); + const auto absolutePathStr = absolutePath.string(); - const auto existingPath = m_included_files.find(absolutePathStr); - if (existingPath != m_included_files.end()) - m_stream->PopCurrentFile(); - else - m_included_files.emplace(absolutePathStr); + const auto existingPath = m_included_files.find(absolutePathStr); + if (existingPath != m_included_files.end()) + m_stream->PopCurrentFile(); + else + m_included_files.emplace(absolutePathStr); - return true; + return true; } -bool IncludingStreamProxy::MatchDirectives(const ParserLine& line) -{ - unsigned directiveStartPos, directiveEndPos; +bool IncludingStreamProxy::MatchDirectives(const ParserLine &line) { + unsigned directiveStartPos, directiveEndPos; - if (!FindDirective(line, directiveStartPos, directiveEndPos)) - return false; + if (!FindDirective(line, directiveStartPos, directiveEndPos)) + return false; - directiveStartPos++; - return MatchIncludeDirective(line, directiveStartPos, directiveEndPos) - || MatchPragmaOnceDirective(line, directiveStartPos, directiveEndPos); + directiveStartPos++; + return MatchIncludeDirective(line, directiveStartPos, directiveEndPos) || MatchPragmaOnceDirective(line, directiveStartPos, directiveEndPos); } -ParserLine IncludingStreamProxy::NextLine() -{ - auto line = m_stream->NextLine(); +ParserLine IncludingStreamProxy::NextLine() { + auto line = m_stream->NextLine(); - while(MatchDirectives(line)) - line = m_stream->NextLine(); + while (MatchDirectives(line)) + line = m_stream->NextLine(); - return line; + return line; } -bool IncludingStreamProxy::IncludeFile(const std::string& filename) -{ - return m_stream->IncludeFile(filename); -} +bool IncludingStreamProxy::IncludeFile(const std::string &filename) { return m_stream->IncludeFile(filename); } -void IncludingStreamProxy::PopCurrentFile() -{ - m_stream->PopCurrentFile(); -} +void IncludingStreamProxy::PopCurrentFile() { m_stream->PopCurrentFile(); } -bool IncludingStreamProxy::IsOpen() const -{ - return m_stream->IsOpen(); -} +bool IncludingStreamProxy::IsOpen() const { return m_stream->IsOpen(); } -bool IncludingStreamProxy::Eof() const -{ - return m_stream->Eof(); -} +bool IncludingStreamProxy::Eof() const { return m_stream->Eof(); } diff --git a/src/Parser/Parsing/Impl/IncludingStreamProxy.h b/src/Parser/Parsing/Impl/IncludingStreamProxy.h index 6fb64587c..948bd2f3d 100644 --- a/src/Parser/Parsing/Impl/IncludingStreamProxy.h +++ b/src/Parser/Parsing/Impl/IncludingStreamProxy.h @@ -5,27 +5,27 @@ #include "AbstractDirectiveStreamProxy.h" #include "Parsing/IParserLineStream.h" -class IncludingStreamProxy final : public AbstractDirectiveStreamProxy -{ - static constexpr const char* INCLUDE_QUOTES_ERROR = "Invalid include directive. Expected \"\" or <>"; - static constexpr const char* INCLUDE_DIRECTIVE = "include"; - static constexpr const char* PRAGMA_DIRECTIVE = "pragma"; - static constexpr const char* ONCE_PRAGMA_COMMAND = "once"; +class IncludingStreamProxy final : public AbstractDirectiveStreamProxy { + static constexpr const char *INCLUDE_QUOTES_ERROR = "Invalid include directive. Expected \"\" or <>"; + static constexpr const char *INCLUDE_DIRECTIVE = "include"; + static constexpr const char *PRAGMA_DIRECTIVE = "pragma"; + static constexpr const char *ONCE_PRAGMA_COMMAND = "once"; - IParserLineStream* const m_stream; - std::set<std::string> m_included_files; - - _NODISCARD static bool ExtractIncludeFilename(const ParserLine& line, unsigned includeDirectivePosition, unsigned& filenameStartPosition, unsigned& filenameEndPosition); - _NODISCARD bool MatchIncludeDirective(const ParserLine& line, unsigned directiveStartPos, unsigned directiveEndPos) const; - _NODISCARD bool MatchPragmaOnceDirective(const ParserLine& line, unsigned directiveStartPos, unsigned directiveEndPos); - _NODISCARD bool MatchDirectives(const ParserLine& line); + IParserLineStream *const m_stream; + std::set<std::string> m_included_files; + + _NODISCARD static bool ExtractIncludeFilename(const ParserLine &line, unsigned includeDirectivePosition, unsigned &filenameStartPosition, + unsigned &filenameEndPosition); + _NODISCARD bool MatchIncludeDirective(const ParserLine &line, unsigned directiveStartPos, unsigned directiveEndPos) const; + _NODISCARD bool MatchPragmaOnceDirective(const ParserLine &line, unsigned directiveStartPos, unsigned directiveEndPos); + _NODISCARD bool MatchDirectives(const ParserLine &line); public: - explicit IncludingStreamProxy(IParserLineStream* stream); + explicit IncludingStreamProxy(IParserLineStream *stream); - ParserLine NextLine() override; - bool IncludeFile(const std::string& filename) override; - void PopCurrentFile() override; - _NODISCARD bool IsOpen() const override; - _NODISCARD bool Eof() const override; + ParserLine NextLine() override; + bool IncludeFile(const std::string &filename) override; + void PopCurrentFile() override; + _NODISCARD bool IsOpen() const override; + _NODISCARD bool Eof() const override; }; diff --git a/src/Parser/Parsing/Impl/PackDefinitionStreamProxy.cpp b/src/Parser/Parsing/Impl/PackDefinitionStreamProxy.cpp index 85bfc424c..31710b3c4 100644 --- a/src/Parser/Parsing/Impl/PackDefinitionStreamProxy.cpp +++ b/src/Parser/Parsing/Impl/PackDefinitionStreamProxy.cpp @@ -2,104 +2,81 @@ #include "Parsing/ParsingException.h" -PackDefinitionStreamProxy::PackDefinitionStreamProxy(IParserLineStream* stream) - : m_stream(stream) -{ -} +PackDefinitionStreamProxy::PackDefinitionStreamProxy(IParserLineStream *stream) : m_stream(stream) {} -bool PackDefinitionStreamProxy::MatchPackDirective(const ParserLine& line, const unsigned directiveStartPosition, const unsigned directiveEndPosition) -{ - auto packValue = 0; - auto currentPosition = directiveStartPosition; +bool PackDefinitionStreamProxy::MatchPackDirective(const ParserLine &line, const unsigned directiveStartPosition, const unsigned directiveEndPosition) { + auto packValue = 0; + auto currentPosition = directiveStartPosition; - if (directiveEndPosition - directiveStartPosition != std::char_traits<char>::length(PRAGMA_DIRECTIVE) - || !MatchString(line, currentPosition, PRAGMA_DIRECTIVE, std::char_traits<char>::length(PRAGMA_DIRECTIVE))) - { - return false; - } + if (directiveEndPosition - directiveStartPosition != std::char_traits<char>::length(PRAGMA_DIRECTIVE) || + !MatchString(line, currentPosition, PRAGMA_DIRECTIVE, std::char_traits<char>::length(PRAGMA_DIRECTIVE))) { + return false; + } - if (!SkipWhitespace(line, currentPosition)) - return false; + if (!SkipWhitespace(line, currentPosition)) + return false; - if (!MatchString(line, currentPosition, PACK_PRAGMA_COMMAND, std::char_traits<char>::length(PACK_PRAGMA_COMMAND))) - return false; + if (!MatchString(line, currentPosition, PACK_PRAGMA_COMMAND, std::char_traits<char>::length(PACK_PRAGMA_COMMAND))) + return false; - if (!SkipWhitespace(line, currentPosition)) - throw ParsingException(CreatePos(line, currentPosition), "Invalid pack directive."); + if (!SkipWhitespace(line, currentPosition)) + throw ParsingException(CreatePos(line, currentPosition), "Invalid pack directive."); - if (!MatchNextCharacter(line, currentPosition, '(')) - throw ParsingException(CreatePos(line, currentPosition), "Invalid pack directive."); + if (!MatchNextCharacter(line, currentPosition, '(')) + throw ParsingException(CreatePos(line, currentPosition), "Invalid pack directive."); - bool isPush; - if (MatchNextString(line, currentPosition, PUSH_KEYWORD, std::char_traits<char>::length(PUSH_KEYWORD))) - isPush = true; - else if (MatchNextString(line, currentPosition, POP_KEYWORD, std::char_traits<char>::length(POP_KEYWORD))) - isPush = false; - else - throw ParsingException(CreatePos(line, currentPosition), "Unknown pack directive command."); + bool isPush; + if (MatchNextString(line, currentPosition, PUSH_KEYWORD, std::char_traits<char>::length(PUSH_KEYWORD))) + isPush = true; + else if (MatchNextString(line, currentPosition, POP_KEYWORD, std::char_traits<char>::length(POP_KEYWORD))) + isPush = false; + else + throw ParsingException(CreatePos(line, currentPosition), "Unknown pack directive command."); - if (isPush) - { - if (!MatchNextCharacter(line, currentPosition, ',')) - throw ParsingException(CreatePos(line, currentPosition), "Invalid pack directive."); + if (isPush) { + if (!MatchNextCharacter(line, currentPosition, ',')) + throw ParsingException(CreatePos(line, currentPosition), "Invalid pack directive."); - if (!ExtractInteger(line, currentPosition, packValue)) - throw ParsingException(CreatePos(line, currentPosition), "Invalid pack value."); - } + if (!ExtractInteger(line, currentPosition, packValue)) + throw ParsingException(CreatePos(line, currentPosition), "Invalid pack value."); + } - if (!MatchNextCharacter(line, currentPosition, ')')) - throw ParsingException(CreatePos(line, currentPosition), "Invalid pack directive."); + if (!MatchNextCharacter(line, currentPosition, ')')) + throw ParsingException(CreatePos(line, currentPosition), "Invalid pack directive."); - if (isPush) - m_current_pack.push(packValue); - else if (!m_current_pack.empty()) - m_current_pack.pop(); + if (isPush) + m_current_pack.push(packValue); + else if (!m_current_pack.empty()) + m_current_pack.pop(); - return true; + return true; } -bool PackDefinitionStreamProxy::MatchDirectives(const ParserLine& line) -{ - unsigned directiveStartPos, directiveEndPos; +bool PackDefinitionStreamProxy::MatchDirectives(const ParserLine &line) { + unsigned directiveStartPos, directiveEndPos; - if (!FindDirective(line, directiveStartPos, directiveEndPos)) - return false; + if (!FindDirective(line, directiveStartPos, directiveEndPos)) + return false; - directiveStartPos++; - return MatchPackDirective(line, directiveStartPos, directiveEndPos); + directiveStartPos++; + return MatchPackDirective(line, directiveStartPos, directiveEndPos); } -ParserLine PackDefinitionStreamProxy::NextLine() -{ - auto line = m_stream->NextLine(); +ParserLine PackDefinitionStreamProxy::NextLine() { + auto line = m_stream->NextLine(); - while (MatchDirectives(line)) - line = m_stream->NextLine(); + while (MatchDirectives(line)) + line = m_stream->NextLine(); - return line; + return line; } -bool PackDefinitionStreamProxy::IncludeFile(const std::string& filename) -{ - return m_stream->IncludeFile(filename); -} +bool PackDefinitionStreamProxy::IncludeFile(const std::string &filename) { return m_stream->IncludeFile(filename); } -void PackDefinitionStreamProxy::PopCurrentFile() -{ - m_stream->PopCurrentFile(); -} +void PackDefinitionStreamProxy::PopCurrentFile() { m_stream->PopCurrentFile(); } -bool PackDefinitionStreamProxy::IsOpen() const -{ - return m_stream->IsOpen(); -} +bool PackDefinitionStreamProxy::IsOpen() const { return m_stream->IsOpen(); } -bool PackDefinitionStreamProxy::Eof() const -{ - return m_stream->Eof(); -} +bool PackDefinitionStreamProxy::Eof() const { return m_stream->Eof(); } -int PackDefinitionStreamProxy::GetCurrentPack() const -{ - return m_current_pack.empty() ? DEFAULT_PACK : m_current_pack.top(); -} +int PackDefinitionStreamProxy::GetCurrentPack() const { return m_current_pack.empty() ? DEFAULT_PACK : m_current_pack.top(); } diff --git a/src/Parser/Parsing/Impl/PackDefinitionStreamProxy.h b/src/Parser/Parsing/Impl/PackDefinitionStreamProxy.h index 9dce21eb7..48f80e62b 100644 --- a/src/Parser/Parsing/Impl/PackDefinitionStreamProxy.h +++ b/src/Parser/Parsing/Impl/PackDefinitionStreamProxy.h @@ -2,36 +2,35 @@ #include <stack> -#include "Utils/ClassUtils.h" #include "AbstractDirectiveStreamProxy.h" #include "Parsing/IPackValueSupplier.h" #include "Parsing/IParserLineStream.h" +#include "Utils/ClassUtils.h" -class PackDefinitionStreamProxy final : public AbstractDirectiveStreamProxy, public IPackValueSupplier -{ +class PackDefinitionStreamProxy final : public AbstractDirectiveStreamProxy, public IPackValueSupplier { public: - static constexpr int DEFAULT_PACK = 8; + static constexpr int DEFAULT_PACK = 8; private: - static constexpr const char* PRAGMA_DIRECTIVE = "pragma"; - static constexpr const char* PACK_PRAGMA_COMMAND = "pack"; - static constexpr const char* PUSH_KEYWORD = "push"; - static constexpr const char* POP_KEYWORD = "pop"; + static constexpr const char *PRAGMA_DIRECTIVE = "pragma"; + static constexpr const char *PACK_PRAGMA_COMMAND = "pack"; + static constexpr const char *PUSH_KEYWORD = "push"; + static constexpr const char *POP_KEYWORD = "pop"; - IParserLineStream* const m_stream; - std::stack<int> m_current_pack; + IParserLineStream *const m_stream; + std::stack<int> m_current_pack; - _NODISCARD bool MatchPackDirective(const ParserLine& line, unsigned directiveStartPosition, unsigned directiveEndPosition); - _NODISCARD bool MatchDirectives(const ParserLine& line); + _NODISCARD bool MatchPackDirective(const ParserLine &line, unsigned directiveStartPosition, unsigned directiveEndPosition); + _NODISCARD bool MatchDirectives(const ParserLine &line); public: - explicit PackDefinitionStreamProxy(IParserLineStream* stream); + explicit PackDefinitionStreamProxy(IParserLineStream *stream); - ParserLine NextLine() override; - bool IncludeFile(const std::string& filename) override; - void PopCurrentFile() override; - _NODISCARD bool IsOpen() const override; - _NODISCARD bool Eof() const override; + ParserLine NextLine() override; + bool IncludeFile(const std::string &filename) override; + void PopCurrentFile() override; + _NODISCARD bool IsOpen() const override; + _NODISCARD bool Eof() const override; - _NODISCARD int GetCurrentPack() const override; + _NODISCARD int GetCurrentPack() const override; }; diff --git a/src/Parser/Parsing/Impl/ParserFilesystemStream.cpp b/src/Parser/Parsing/Impl/ParserFilesystemStream.cpp index 8192533ee..9d6fbb3b9 100644 --- a/src/Parser/Parsing/Impl/ParserFilesystemStream.cpp +++ b/src/Parser/Parsing/Impl/ParserFilesystemStream.cpp @@ -1,100 +1,81 @@ #include "ParserFilesystemStream.h" -#include <sstream> #include <filesystem> +#include <sstream> namespace fs = std::filesystem; ParserFilesystemStream::FileInfo::FileInfo(std::string filePath) - : m_file_path(std::make_shared<std::string>(std::move(filePath))), - m_stream(*m_file_path), - m_line_number(1) -{ -} + : m_file_path(std::make_shared<std::string>(std::move(filePath))), m_stream(*m_file_path), m_line_number(1) {} -ParserFilesystemStream::ParserFilesystemStream(const std::string& path) -{ - const auto absolutePath = absolute(fs::path(path)); - m_files.emplace(FileInfo(absolutePath.string())); +ParserFilesystemStream::ParserFilesystemStream(const std::string &path) { + const auto absolutePath = absolute(fs::path(path)); + m_files.emplace(FileInfo(absolutePath.string())); } -bool ParserFilesystemStream::IsOpen() const -{ - return !m_files.empty() - && m_files.top().m_stream.is_open(); -} +bool ParserFilesystemStream::IsOpen() const { return !m_files.empty() && m_files.top().m_stream.is_open(); } -ParserLine ParserFilesystemStream::NextLine() -{ - std::ostringstream str; - auto hasLength = false; - - if (m_files.empty()) - return ParserLine(); - - while(!m_files.empty()) - { - auto& fileInfo = m_files.top(); - - auto c = fileInfo.m_stream.get(); - while (c != EOF) - { - switch (c) - { - case '\r': - c = fileInfo.m_stream.get(); - if (c == '\n') - return ParserLine(fileInfo.m_file_path, fileInfo.m_line_number++, str.str()); - str << '\r'; - hasLength = true; - continue; - - case '\n': - return ParserLine(fileInfo.m_file_path, fileInfo.m_line_number++, str.str()); - - default: - str << static_cast<char>(c); - hasLength = true; - break; - } - - c = fileInfo.m_stream.get(); - } - - if(hasLength) - return ParserLine(fileInfo.m_file_path, fileInfo.m_line_number, str.str()); - m_files.pop(); - } +ParserLine ParserFilesystemStream::NextLine() { + std::ostringstream str; + auto hasLength = false; + if (m_files.empty()) return ParserLine(); + + while (!m_files.empty()) { + auto &fileInfo = m_files.top(); + + auto c = fileInfo.m_stream.get(); + while (c != EOF) { + switch (c) { + case '\r': + c = fileInfo.m_stream.get(); + if (c == '\n') + return ParserLine(fileInfo.m_file_path, fileInfo.m_line_number++, str.str()); + str << '\r'; + hasLength = true; + continue; + + case '\n': + return ParserLine(fileInfo.m_file_path, fileInfo.m_line_number++, str.str()); + + default: + str << static_cast<char>(c); + hasLength = true; + break; + } + + c = fileInfo.m_stream.get(); + } + + if (hasLength) + return ParserLine(fileInfo.m_file_path, fileInfo.m_line_number, str.str()); + m_files.pop(); + } + + return ParserLine(); } -bool ParserFilesystemStream::IncludeFile(const std::string& filename) -{ - if (m_files.empty()) - return false; - - auto newFilePath = fs::path(*m_files.top().m_file_path); - newFilePath.remove_filename().concat(filename); - newFilePath = absolute(newFilePath); +bool ParserFilesystemStream::IncludeFile(const std::string &filename) { + if (m_files.empty()) + return false; - FileInfo fileInfo(newFilePath.string()); + auto newFilePath = fs::path(*m_files.top().m_file_path); + newFilePath.remove_filename().concat(filename); + newFilePath = absolute(newFilePath); - if (!fileInfo.m_stream.is_open()) - return false; + FileInfo fileInfo(newFilePath.string()); - m_files.emplace(std::move(fileInfo)); - return true; -} + if (!fileInfo.m_stream.is_open()) + return false; -void ParserFilesystemStream::PopCurrentFile() -{ - if(!m_files.empty()) - m_files.pop(); + m_files.emplace(std::move(fileInfo)); + return true; } -bool ParserFilesystemStream::Eof() const -{ - return m_files.empty() - || m_files.top().m_stream.eof(); +void ParserFilesystemStream::PopCurrentFile() { + if (!m_files.empty()) + m_files.pop(); } + +bool ParserFilesystemStream::Eof() const { return m_files.empty() || m_files.top().m_stream.eof(); } diff --git a/src/Parser/Parsing/Impl/ParserFilesystemStream.h b/src/Parser/Parsing/Impl/ParserFilesystemStream.h index 628708964..d5f133bf5 100644 --- a/src/Parser/Parsing/Impl/ParserFilesystemStream.h +++ b/src/Parser/Parsing/Impl/ParserFilesystemStream.h @@ -1,29 +1,27 @@ #pragma once -#include <stack> #include <fstream> +#include <stack> #include "Parsing/IParserLineStream.h" -class ParserFilesystemStream final : public IParserLineStream -{ - class FileInfo - { - public: - std::shared_ptr<std::string> m_file_path; - std::ifstream m_stream; - int m_line_number; +class ParserFilesystemStream final : public IParserLineStream { + class FileInfo { + public: + std::shared_ptr<std::string> m_file_path; + std::ifstream m_stream; + int m_line_number; - explicit FileInfo(std::string filePath); - }; - std::stack<FileInfo> m_files; + explicit FileInfo(std::string filePath); + }; + std::stack<FileInfo> m_files; public: - explicit ParserFilesystemStream(const std::string& path); + explicit ParserFilesystemStream(const std::string &path); - ParserLine NextLine() override; - bool IncludeFile(const std::string& filename) override; - void PopCurrentFile() override; - _NODISCARD bool IsOpen() const override; - _NODISCARD bool Eof() const override; + ParserLine NextLine() override; + bool IncludeFile(const std::string &filename) override; + void PopCurrentFile() override; + _NODISCARD bool IsOpen() const override; + _NODISCARD bool Eof() const override; }; diff --git a/src/Parser/Parsing/Impl/ParserMultiInputStream.cpp b/src/Parser/Parsing/Impl/ParserMultiInputStream.cpp index 78e2d5ee0..1e752d748 100644 --- a/src/Parser/Parsing/Impl/ParserMultiInputStream.cpp +++ b/src/Parser/Parsing/Impl/ParserMultiInputStream.cpp @@ -3,102 +3,79 @@ #include <sstream> ParserMultiInputStream::FileInfo::FileInfo(std::unique_ptr<std::istream> stream, std::string filePath) - : m_owned_stream(std::move(stream)), - m_stream(*m_owned_stream), - m_file_path(std::make_shared<std::string>(std::move(filePath))), - m_line_number(1) -{ -} + : m_owned_stream(std::move(stream)), m_stream(*m_owned_stream), m_file_path(std::make_shared<std::string>(std::move(filePath))), m_line_number(1) {} -ParserMultiInputStream::FileInfo::FileInfo(std::istream& stream, std::string filePath) - : m_stream(stream), - m_file_path(std::make_shared<std::string>(std::move(filePath))), - m_line_number(1) -{ -} +ParserMultiInputStream::FileInfo::FileInfo(std::istream &stream, std::string filePath) + : m_stream(stream), m_file_path(std::make_shared<std::string>(std::move(filePath))), m_line_number(1) {} ParserMultiInputStream::ParserMultiInputStream(std::unique_ptr<std::istream> stream, std::string fileName, include_callback_t includeCallback) - : m_include_callback(std::move(includeCallback)) -{ - m_files.emplace(std::move(stream), std::move(fileName)); + : m_include_callback(std::move(includeCallback)) { + m_files.emplace(std::move(stream), std::move(fileName)); } -ParserMultiInputStream::ParserMultiInputStream(std::istream& stream, std::string fileName, include_callback_t includeCallback) - : m_include_callback(std::move(includeCallback)) -{ - m_files.emplace(stream, std::move(fileName)); +ParserMultiInputStream::ParserMultiInputStream(std::istream &stream, std::string fileName, include_callback_t includeCallback) + : m_include_callback(std::move(includeCallback)) { + m_files.emplace(stream, std::move(fileName)); } -ParserLine ParserMultiInputStream::NextLine() -{ - std::ostringstream str; - auto hasLength = false; - - if (m_files.empty()) - return ParserLine(); - - while (!m_files.empty()) - { - auto& fileInfo = m_files.top(); - - auto c = fileInfo.m_stream.get(); - while (c != EOF) - { - switch (c) - { - case '\r': - c = fileInfo.m_stream.get(); - if (c == '\n') - return ParserLine(fileInfo.m_file_path, fileInfo.m_line_number++, str.str()); - str << '\r'; - hasLength = true; - continue; - - case '\n': - return ParserLine(fileInfo.m_file_path, fileInfo.m_line_number++, str.str()); - - default: - str << static_cast<char>(c); - hasLength = true; - break; - } - - c = fileInfo.m_stream.get(); - } - - if (hasLength) - return ParserLine(fileInfo.m_file_path, fileInfo.m_line_number, str.str()); - m_files.pop(); - } +ParserLine ParserMultiInputStream::NextLine() { + std::ostringstream str; + auto hasLength = false; + if (m_files.empty()) return ParserLine(); -} -bool ParserMultiInputStream::IncludeFile(const std::string& filename) -{ - if (!m_include_callback) - return false; + while (!m_files.empty()) { + auto &fileInfo = m_files.top(); + + auto c = fileInfo.m_stream.get(); + while (c != EOF) { + switch (c) { + case '\r': + c = fileInfo.m_stream.get(); + if (c == '\n') + return ParserLine(fileInfo.m_file_path, fileInfo.m_line_number++, str.str()); + str << '\r'; + hasLength = true; + continue; + + case '\n': + return ParserLine(fileInfo.m_file_path, fileInfo.m_line_number++, str.str()); + + default: + str << static_cast<char>(c); + hasLength = true; + break; + } + + c = fileInfo.m_stream.get(); + } - auto newFile = m_include_callback(filename, m_files.empty() ? "" : *m_files.top().m_file_path); - if (!newFile) - return false; + if (hasLength) + return ParserLine(fileInfo.m_file_path, fileInfo.m_line_number, str.str()); + m_files.pop(); + } - m_files.emplace(std::move(newFile), filename); - return true; + return ParserLine(); } -void ParserMultiInputStream::PopCurrentFile() -{ - if (!m_files.empty()) - m_files.pop(); -} +bool ParserMultiInputStream::IncludeFile(const std::string &filename) { + if (!m_include_callback) + return false; + + auto newFile = m_include_callback(filename, m_files.empty() ? "" : *m_files.top().m_file_path); + if (!newFile) + return false; -bool ParserMultiInputStream::IsOpen() const -{ - return !m_files.empty(); + m_files.emplace(std::move(newFile), filename); + return true; } -bool ParserMultiInputStream::Eof() const -{ - return m_files.empty(); +void ParserMultiInputStream::PopCurrentFile() { + if (!m_files.empty()) + m_files.pop(); } + +bool ParserMultiInputStream::IsOpen() const { return !m_files.empty(); } + +bool ParserMultiInputStream::Eof() const { return m_files.empty(); } diff --git a/src/Parser/Parsing/Impl/ParserMultiInputStream.h b/src/Parser/Parsing/Impl/ParserMultiInputStream.h index bd6ee7cb4..26d742e66 100644 --- a/src/Parser/Parsing/Impl/ParserMultiInputStream.h +++ b/src/Parser/Parsing/Impl/ParserMultiInputStream.h @@ -1,40 +1,38 @@ #pragma once +#include <functional> #include <istream> -#include <stack> #include <memory> -#include <functional> +#include <stack> #include "Parsing/IParserLineStream.h" -class ParserMultiInputStream final : public IParserLineStream -{ +class ParserMultiInputStream final : public IParserLineStream { public: - using include_callback_t = std::function<std::unique_ptr<std::istream>(const std::string& filename, const std::string& sourceFile)>; + using include_callback_t = std::function<std::unique_ptr<std::istream>(const std::string &filename, const std::string &sourceFile)>; private: - class FileInfo - { - public: - std::unique_ptr<std::istream> m_owned_stream; - std::istream& m_stream; - std::shared_ptr<std::string> m_file_path; - int m_line_number; + class FileInfo { + public: + std::unique_ptr<std::istream> m_owned_stream; + std::istream &m_stream; + std::shared_ptr<std::string> m_file_path; + int m_line_number; - FileInfo(std::unique_ptr<std::istream> stream, std::string filePath); - FileInfo(std::istream& stream, std::string filePath); - }; + FileInfo(std::unique_ptr<std::istream> stream, std::string filePath); + FileInfo(std::istream &stream, std::string filePath); + }; - const include_callback_t m_include_callback; - std::stack<FileInfo> m_files; + const include_callback_t m_include_callback; + std::stack<FileInfo> m_files; public: - ParserMultiInputStream(std::unique_ptr<std::istream> stream, std::string fileName, include_callback_t includeCallback); - ParserMultiInputStream(std::istream& stream, std::string fileName, include_callback_t includeCallback); - - ParserLine NextLine() override; - bool IncludeFile(const std::string& filename) override; - void PopCurrentFile() override; - _NODISCARD bool IsOpen() const override; - _NODISCARD bool Eof() const override; + ParserMultiInputStream(std::unique_ptr<std::istream> stream, std::string fileName, include_callback_t includeCallback); + ParserMultiInputStream(std::istream &stream, std::string fileName, include_callback_t includeCallback); + + ParserLine NextLine() override; + bool IncludeFile(const std::string &filename) override; + void PopCurrentFile() override; + _NODISCARD bool IsOpen() const override; + _NODISCARD bool Eof() const override; }; \ No newline at end of file diff --git a/src/Parser/Parsing/Impl/ParserSingleInputStream.cpp b/src/Parser/Parsing/Impl/ParserSingleInputStream.cpp index e561b2c24..590a5bab9 100644 --- a/src/Parser/Parsing/Impl/ParserSingleInputStream.cpp +++ b/src/Parser/Parsing/Impl/ParserSingleInputStream.cpp @@ -2,64 +2,46 @@ #include <sstream> -ParserSingleInputStream::ParserSingleInputStream(std::istream& stream, std::string fileName) - : m_stream(stream), - m_file_name(std::make_shared<std::string>(std::move(fileName))), - m_line_number(1) -{ -} - -ParserLine ParserSingleInputStream::NextLine() -{ - std::ostringstream str; - auto hasLength = false; - - auto c = m_stream.get(); - while (c != EOF) - { - switch (c) - { - case '\r': - c = m_stream.get(); - if (c == '\n') - return ParserLine(m_file_name, m_line_number++, str.str()); - str << '\r'; - hasLength = true; - continue; - - case '\n': - return ParserLine(m_file_name, m_line_number++, str.str()); - - default: - str << static_cast<char>(c); - hasLength = true; - break; - } - - c = m_stream.get(); +ParserSingleInputStream::ParserSingleInputStream(std::istream &stream, std::string fileName) + : m_stream(stream), m_file_name(std::make_shared<std::string>(std::move(fileName))), m_line_number(1) {} + +ParserLine ParserSingleInputStream::NextLine() { + std::ostringstream str; + auto hasLength = false; + + auto c = m_stream.get(); + while (c != EOF) { + switch (c) { + case '\r': + c = m_stream.get(); + if (c == '\n') + return ParserLine(m_file_name, m_line_number++, str.str()); + str << '\r'; + hasLength = true; + continue; + + case '\n': + return ParserLine(m_file_name, m_line_number++, str.str()); + + default: + str << static_cast<char>(c); + hasLength = true; + break; } - if (hasLength) - return ParserLine(m_file_name, m_line_number, str.str()); + c = m_stream.get(); + } - return ParserLine(); -} + if (hasLength) + return ParserLine(m_file_name, m_line_number, str.str()); -bool ParserSingleInputStream::IncludeFile(const std::string& filename) -{ - return false; + return ParserLine(); } -void ParserSingleInputStream::PopCurrentFile() -{ -} +bool ParserSingleInputStream::IncludeFile(const std::string &filename) { return false; } -bool ParserSingleInputStream::IsOpen() const -{ - return !m_stream.eof(); -} +void ParserSingleInputStream::PopCurrentFile() {} -bool ParserSingleInputStream::Eof() const -{ - return m_stream.eof(); -} +bool ParserSingleInputStream::IsOpen() const { return !m_stream.eof(); } + +bool ParserSingleInputStream::Eof() const { return m_stream.eof(); } diff --git a/src/Parser/Parsing/Impl/ParserSingleInputStream.h b/src/Parser/Parsing/Impl/ParserSingleInputStream.h index 4a60adbc8..e17bd7a36 100644 --- a/src/Parser/Parsing/Impl/ParserSingleInputStream.h +++ b/src/Parser/Parsing/Impl/ParserSingleInputStream.h @@ -5,18 +5,17 @@ #include "Parsing/IParserLineStream.h" -class ParserSingleInputStream final : public IParserLineStream -{ - std::istream& m_stream; - std::shared_ptr<std::string> m_file_name; - int m_line_number; +class ParserSingleInputStream final : public IParserLineStream { + std::istream &m_stream; + std::shared_ptr<std::string> m_file_name; + int m_line_number; public: - ParserSingleInputStream(std::istream& stream, std::string fileName); + ParserSingleInputStream(std::istream &stream, std::string fileName); - ParserLine NextLine() override; - bool IncludeFile(const std::string& filename) override; - void PopCurrentFile() override; - _NODISCARD bool IsOpen() const override; - _NODISCARD bool Eof() const override; + ParserLine NextLine() override; + bool IncludeFile(const std::string &filename) override; + void PopCurrentFile() override; + _NODISCARD bool IsOpen() const override; + _NODISCARD bool Eof() const override; }; \ No newline at end of file diff --git a/src/Parser/Parsing/Impl/SkipUntilFirstNonEmptyProxy.cpp b/src/Parser/Parsing/Impl/SkipUntilFirstNonEmptyProxy.cpp index 19b3d7dbb..a0344962e 100644 --- a/src/Parser/Parsing/Impl/SkipUntilFirstNonEmptyProxy.cpp +++ b/src/Parser/Parsing/Impl/SkipUntilFirstNonEmptyProxy.cpp @@ -1,40 +1,22 @@ #include "SkipUntilFirstNonEmptyProxy.h" -SkipUntilFirstNonEmptyProxy::SkipUntilFirstNonEmptyProxy(IParserLineStream* stream) - : m_stream(stream), - m_had_non_empty(false) -{ -} +SkipUntilFirstNonEmptyProxy::SkipUntilFirstNonEmptyProxy(IParserLineStream *stream) : m_stream(stream), m_had_non_empty(false) {} -ParserLine SkipUntilFirstNonEmptyProxy::NextLine() -{ - auto line = m_stream->NextLine(); - if (!m_had_non_empty) - { - while (line.m_line.empty() && !m_stream->Eof()) - line = m_stream->NextLine(); - m_had_non_empty = true; - } +ParserLine SkipUntilFirstNonEmptyProxy::NextLine() { + auto line = m_stream->NextLine(); + if (!m_had_non_empty) { + while (line.m_line.empty() && !m_stream->Eof()) + line = m_stream->NextLine(); + m_had_non_empty = true; + } - return line; + return line; } -bool SkipUntilFirstNonEmptyProxy::IncludeFile(const std::string& filename) -{ - return m_stream->IncludeFile(filename); -} +bool SkipUntilFirstNonEmptyProxy::IncludeFile(const std::string &filename) { return m_stream->IncludeFile(filename); } -void SkipUntilFirstNonEmptyProxy::PopCurrentFile() -{ - m_stream->PopCurrentFile(); -} +void SkipUntilFirstNonEmptyProxy::PopCurrentFile() { m_stream->PopCurrentFile(); } -bool SkipUntilFirstNonEmptyProxy::IsOpen() const -{ - return m_stream->IsOpen(); -} +bool SkipUntilFirstNonEmptyProxy::IsOpen() const { return m_stream->IsOpen(); } -bool SkipUntilFirstNonEmptyProxy::Eof() const -{ - return m_stream->Eof(); -} +bool SkipUntilFirstNonEmptyProxy::Eof() const { return m_stream->Eof(); } diff --git a/src/Parser/Parsing/Impl/SkipUntilFirstNonEmptyProxy.h b/src/Parser/Parsing/Impl/SkipUntilFirstNonEmptyProxy.h index b4f5a7537..29ecd1796 100644 --- a/src/Parser/Parsing/Impl/SkipUntilFirstNonEmptyProxy.h +++ b/src/Parser/Parsing/Impl/SkipUntilFirstNonEmptyProxy.h @@ -2,18 +2,17 @@ #include "Parsing/IParserLineStream.h" -class SkipUntilFirstNonEmptyProxy final : public IParserLineStream -{ +class SkipUntilFirstNonEmptyProxy final : public IParserLineStream { public: - explicit SkipUntilFirstNonEmptyProxy(IParserLineStream* stream); + explicit SkipUntilFirstNonEmptyProxy(IParserLineStream *stream); - ParserLine NextLine() override; - bool IncludeFile(const std::string& filename) override; - void PopCurrentFile() override; - _NODISCARD bool IsOpen() const override; - _NODISCARD bool Eof() const override; + ParserLine NextLine() override; + bool IncludeFile(const std::string &filename) override; + void PopCurrentFile() override; + _NODISCARD bool IsOpen() const override; + _NODISCARD bool Eof() const override; private: - IParserLineStream* const m_stream; - bool m_had_non_empty; + IParserLineStream *const m_stream; + bool m_had_non_empty; }; diff --git a/src/Parser/Parsing/Matcher/AbstractMatcher.h b/src/Parser/Parsing/Matcher/AbstractMatcher.h index f6e4d797a..bb73e42a7 100644 --- a/src/Parser/Parsing/Matcher/AbstractMatcher.h +++ b/src/Parser/Parsing/Matcher/AbstractMatcher.h @@ -2,102 +2,78 @@ #include <functional> -#include "Parsing/IParserValue.h" #include "Parsing/ILexer.h" +#include "Parsing/IParserValue.h" #include "Parsing/Matcher/MatcherResult.h" -template <typename TokenType> -class AbstractMatcher -{ - // TokenType must inherit IParserValue - static_assert(std::is_base_of<IParserValue, TokenType>::value); +template <typename TokenType> class AbstractMatcher { + // TokenType must inherit IParserValue + static_assert(std::is_base_of<IParserValue, TokenType>::value); public: - static constexpr int NO_ID = -1; + static constexpr int NO_ID = -1; - typedef std::vector<std::reference_wrapper<const TokenType>> token_list_t; + typedef std::vector<std::reference_wrapper<const TokenType>> token_list_t; private: - int m_tag_id; - int m_capture_id; - bool m_no_consume; - std::function<TokenType(token_list_t&)> m_transform_func; + int m_tag_id; + int m_capture_id; + bool m_no_consume; + std::function<TokenType(token_list_t &)> m_transform_func; protected: - AbstractMatcher() - : m_tag_id(NO_ID), - m_capture_id(NO_ID), - m_no_consume(false) - { - } + AbstractMatcher() : m_tag_id(NO_ID), m_capture_id(NO_ID), m_no_consume(false) {} - virtual MatcherResult<TokenType> CanMatch(ILexer<TokenType>* lexer, unsigned tokenOffset) = 0; + virtual MatcherResult<TokenType> CanMatch(ILexer<TokenType> *lexer, unsigned tokenOffset) = 0; public: - virtual ~AbstractMatcher() = default; - AbstractMatcher(const AbstractMatcher& other) = default; - AbstractMatcher(AbstractMatcher&& other) noexcept = default; - AbstractMatcher& operator=(const AbstractMatcher& other) = default; - AbstractMatcher& operator=(AbstractMatcher&& other) noexcept = default; - - void SetTag(const int tagId) - { - m_tag_id = tagId; - } + virtual ~AbstractMatcher() = default; + AbstractMatcher(const AbstractMatcher &other) = default; + AbstractMatcher(AbstractMatcher &&other) noexcept = default; + AbstractMatcher &operator=(const AbstractMatcher &other) = default; + AbstractMatcher &operator=(AbstractMatcher &&other) noexcept = default; - void SetCapture(const int captureId) - { - m_capture_id = captureId; - } + void SetTag(const int tagId) { m_tag_id = tagId; } - void SetConsume(const bool value) - { - m_no_consume = !value; - } + void SetCapture(const int captureId) { m_capture_id = captureId; } - void SetTransform(std::function<TokenType(std::vector<std::reference_wrapper<const TokenType>>&)> transform) - { - m_transform_func = std::move(transform); - } - - MatcherResult<TokenType> Match(ILexer<TokenType>* lexer, const unsigned tokenOffset) - { - MatcherResult<TokenType> result = CanMatch(lexer, tokenOffset); + void SetConsume(const bool value) { m_no_consume = !value; } - if (!result.m_matches) - return result; + void SetTransform(std::function<TokenType(std::vector<std::reference_wrapper<const TokenType>> &)> transform) { m_transform_func = std::move(transform); } - if (m_tag_id != NO_ID) - result.m_tags.insert(result.m_tags.begin(), m_tag_id); + MatcherResult<TokenType> Match(ILexer<TokenType> *lexer, const unsigned tokenOffset) { + MatcherResult<TokenType> result = CanMatch(lexer, tokenOffset); - if (m_transform_func) - { - std::vector<std::reference_wrapper<const TokenType>> tokens; - tokens.reserve(result.m_consumed_token_count); + if (!result.m_matches) + return result; - for (auto i = 0u; i < result.m_consumed_token_count; i++) - tokens.emplace_back(lexer->GetToken(tokenOffset + i)); + if (m_tag_id != NO_ID) + result.m_tags.insert(result.m_tags.begin(), m_tag_id); - result.m_fabricated_tokens.push_back(m_transform_func(tokens)); + if (m_transform_func) { + std::vector<std::reference_wrapper<const TokenType>> tokens; + tokens.reserve(result.m_consumed_token_count); - result.m_matched_tokens.clear(); - result.m_matched_tokens.emplace_back(result.m_fabricated_tokens.size() - 1, true); - } - else if(result.m_matched_tokens.empty()) - { - for (auto i = 0u; i < result.m_consumed_token_count; i++) - result.m_matched_tokens.emplace_back(tokenOffset + i, false); - } + for (auto i = 0u; i < result.m_consumed_token_count; i++) + tokens.emplace_back(lexer->GetToken(tokenOffset + i)); - if (m_capture_id != NO_ID) - { - for (const auto& match : result.m_matched_tokens) - result.m_captures.emplace_back(m_capture_id, match); - } + result.m_fabricated_tokens.push_back(m_transform_func(tokens)); - if (m_no_consume) - result.m_consumed_token_count = 0; + result.m_matched_tokens.clear(); + result.m_matched_tokens.emplace_back(result.m_fabricated_tokens.size() - 1, true); + } else if (result.m_matched_tokens.empty()) { + for (auto i = 0u; i < result.m_consumed_token_count; i++) + result.m_matched_tokens.emplace_back(tokenOffset + i, false); + } - return result; + if (m_capture_id != NO_ID) { + for (const auto &match : result.m_matched_tokens) + result.m_captures.emplace_back(m_capture_id, match); } + + if (m_no_consume) + result.m_consumed_token_count = 0; + + return result; + } }; diff --git a/src/Parser/Parsing/Matcher/AbstractMatcherFactory.h b/src/Parser/Parsing/Matcher/AbstractMatcherFactory.h index 39535cc4b..6c166996f 100644 --- a/src/Parser/Parsing/Matcher/AbstractMatcherFactory.h +++ b/src/Parser/Parsing/Matcher/AbstractMatcherFactory.h @@ -2,138 +2,101 @@ #include <memory> -#include "Utils/ClassUtils.h" #include "AbstractMatcher.h" #include "MatcherAnd.h" +#include "MatcherFalse.h" #include "MatcherLabel.h" #include "MatcherLoop.h" -#include "MatcherFalse.h" -#include "MatcherTrue.h" #include "MatcherOptional.h" #include "MatcherOr.h" +#include "MatcherTrue.h" #include "Parsing/IParserValue.h" +#include "Utils/ClassUtils.h" -template <typename TokenType> -class MatcherFactoryWrapper -{ - // TokenType must inherit IParserValue - static_assert(std::is_base_of<IParserValue, TokenType>::value); +template <typename TokenType> class MatcherFactoryWrapper { + // TokenType must inherit IParserValue + static_assert(std::is_base_of<IParserValue, TokenType>::value); - std::unique_ptr<AbstractMatcher<TokenType>> m_matcher; + std::unique_ptr<AbstractMatcher<TokenType>> m_matcher; public: - typedef typename AbstractMatcher<TokenType>::token_list_t token_list_t; - - explicit MatcherFactoryWrapper(std::unique_ptr<AbstractMatcher<TokenType>> matcher) - : m_matcher(std::move(matcher)) - { - } - - MatcherFactoryWrapper<TokenType>& Tag(const int tagId) - { - m_matcher->SetTag(tagId); - return *this; - } - - MatcherFactoryWrapper<TokenType>& Capture(const int captureId) - { - m_matcher->SetCapture(captureId); - return *this; - } - - MatcherFactoryWrapper<TokenType>& NoConsume() - { - m_matcher->SetConsume(false); - return *this; - } - - MatcherFactoryWrapper<TokenType>& Transform(std::function<TokenType(token_list_t&)> transform) - { - m_matcher->SetTransform(std::move(transform)); - return *this; - } - - std::unique_ptr<AbstractMatcher<TokenType>> Build() - { - return std::move(m_matcher); - } - - // ReSharper disable once CppNonExplicitConversionOperator - operator std::unique_ptr<AbstractMatcher<TokenType>>() - { - return Build(); - } - - // ReSharper disable once CppNonExplicitConversionOperator - operator Movable<std::unique_ptr<AbstractMatcher<TokenType>>>() - { - return Build(); - } + typedef typename AbstractMatcher<TokenType>::token_list_t token_list_t; + + explicit MatcherFactoryWrapper(std::unique_ptr<AbstractMatcher<TokenType>> matcher) : m_matcher(std::move(matcher)) {} + + MatcherFactoryWrapper<TokenType> &Tag(const int tagId) { + m_matcher->SetTag(tagId); + return *this; + } + + MatcherFactoryWrapper<TokenType> &Capture(const int captureId) { + m_matcher->SetCapture(captureId); + return *this; + } + + MatcherFactoryWrapper<TokenType> &NoConsume() { + m_matcher->SetConsume(false); + return *this; + } + + MatcherFactoryWrapper<TokenType> &Transform(std::function<TokenType(token_list_t &)> transform) { + m_matcher->SetTransform(std::move(transform)); + return *this; + } + + std::unique_ptr<AbstractMatcher<TokenType>> Build() { return std::move(m_matcher); } + + // ReSharper disable once CppNonExplicitConversionOperator + operator std::unique_ptr<AbstractMatcher<TokenType>>() { return Build(); } + + // ReSharper disable once CppNonExplicitConversionOperator + operator Movable<std::unique_ptr<AbstractMatcher<TokenType>>>() { return Build(); } }; -template <typename TokenType> -class AbstractMatcherFactory -{ - // TokenType must inherit IParserValue - static_assert(std::is_base_of<IParserValue, TokenType>::value); +template <typename TokenType> class AbstractMatcherFactory { + // TokenType must inherit IParserValue + static_assert(std::is_base_of<IParserValue, TokenType>::value); - const IMatcherForLabelSupplier<TokenType>* m_label_supplier; + const IMatcherForLabelSupplier<TokenType> *m_label_supplier; public: - typedef typename AbstractMatcher<TokenType>::token_list_t token_list_t; - - explicit AbstractMatcherFactory(const IMatcherForLabelSupplier<TokenType>* labelSupplier) - : m_label_supplier(labelSupplier) - { - } - - _NODISCARD MatcherFactoryWrapper<TokenType> False() const - { - return MatcherFactoryWrapper<TokenType>(std::make_unique<MatcherFalse<TokenType>>()); - } - - _NODISCARD MatcherFactoryWrapper<TokenType> True() const - { - return MatcherFactoryWrapper<TokenType>(std::make_unique<MatcherTrue<TokenType>>()); - } - - _NODISCARD MatcherFactoryWrapper<TokenType> And(std::initializer_list<Movable<std::unique_ptr<AbstractMatcher<TokenType>>>> matchers) const - { - return MatcherFactoryWrapper<TokenType>(std::make_unique<MatcherAnd<TokenType>>(matchers)); - } - - _NODISCARD MatcherFactoryWrapper<TokenType> And(std::vector<std::unique_ptr<AbstractMatcher<TokenType>>> matchers) const - { - return MatcherFactoryWrapper<TokenType>(std::make_unique<MatcherAnd<TokenType>>(std::move(matchers))); - } - - _NODISCARD MatcherFactoryWrapper<TokenType> Or(std::initializer_list<Movable<std::unique_ptr<AbstractMatcher<TokenType>>>> matchers) const - { - return MatcherFactoryWrapper<TokenType>(std::make_unique<MatcherOr<TokenType>>(matchers)); - } - - _NODISCARD MatcherFactoryWrapper<TokenType> Or(std::vector<std::unique_ptr<AbstractMatcher<TokenType>>> matchers) const - { - return MatcherFactoryWrapper<TokenType>(std::make_unique<MatcherOr<TokenType>>(std::move(matchers))); - } - - _NODISCARD MatcherFactoryWrapper<TokenType> Loop(std::unique_ptr<AbstractMatcher<TokenType>> matcher) const - { - return MatcherFactoryWrapper<TokenType>(std::make_unique<MatcherLoop<TokenType>>(std::move(matcher))); - } - - _NODISCARD MatcherFactoryWrapper<TokenType> OptionalLoop(std::unique_ptr<AbstractMatcher<TokenType>> matcher) const - { - return MatcherFactoryWrapper<TokenType>(std::make_unique<MatcherOptional<TokenType>>(std::make_unique<MatcherLoop<TokenType>>(std::move(matcher)))); - } - - _NODISCARD MatcherFactoryWrapper<TokenType> Optional(std::unique_ptr<AbstractMatcher<TokenType>> matcher) const - { - return MatcherFactoryWrapper<TokenType>(std::make_unique<MatcherOptional<TokenType>>(std::move(matcher))); - } - - _NODISCARD MatcherFactoryWrapper<TokenType> Label(const int label) const - { - return MatcherFactoryWrapper<TokenType>(std::make_unique<MatcherLabel<TokenType>>(m_label_supplier, label)); - } + typedef typename AbstractMatcher<TokenType>::token_list_t token_list_t; + + explicit AbstractMatcherFactory(const IMatcherForLabelSupplier<TokenType> *labelSupplier) : m_label_supplier(labelSupplier) {} + + _NODISCARD MatcherFactoryWrapper<TokenType> False() const { return MatcherFactoryWrapper<TokenType>(std::make_unique<MatcherFalse<TokenType>>()); } + + _NODISCARD MatcherFactoryWrapper<TokenType> True() const { return MatcherFactoryWrapper<TokenType>(std::make_unique<MatcherTrue<TokenType>>()); } + + _NODISCARD MatcherFactoryWrapper<TokenType> And(std::initializer_list<Movable<std::unique_ptr<AbstractMatcher<TokenType>>>> matchers) const { + return MatcherFactoryWrapper<TokenType>(std::make_unique<MatcherAnd<TokenType>>(matchers)); + } + + _NODISCARD MatcherFactoryWrapper<TokenType> And(std::vector<std::unique_ptr<AbstractMatcher<TokenType>>> matchers) const { + return MatcherFactoryWrapper<TokenType>(std::make_unique<MatcherAnd<TokenType>>(std::move(matchers))); + } + + _NODISCARD MatcherFactoryWrapper<TokenType> Or(std::initializer_list<Movable<std::unique_ptr<AbstractMatcher<TokenType>>>> matchers) const { + return MatcherFactoryWrapper<TokenType>(std::make_unique<MatcherOr<TokenType>>(matchers)); + } + + _NODISCARD MatcherFactoryWrapper<TokenType> Or(std::vector<std::unique_ptr<AbstractMatcher<TokenType>>> matchers) const { + return MatcherFactoryWrapper<TokenType>(std::make_unique<MatcherOr<TokenType>>(std::move(matchers))); + } + + _NODISCARD MatcherFactoryWrapper<TokenType> Loop(std::unique_ptr<AbstractMatcher<TokenType>> matcher) const { + return MatcherFactoryWrapper<TokenType>(std::make_unique<MatcherLoop<TokenType>>(std::move(matcher))); + } + + _NODISCARD MatcherFactoryWrapper<TokenType> OptionalLoop(std::unique_ptr<AbstractMatcher<TokenType>> matcher) const { + return MatcherFactoryWrapper<TokenType>(std::make_unique<MatcherOptional<TokenType>>(std::make_unique<MatcherLoop<TokenType>>(std::move(matcher)))); + } + + _NODISCARD MatcherFactoryWrapper<TokenType> Optional(std::unique_ptr<AbstractMatcher<TokenType>> matcher) const { + return MatcherFactoryWrapper<TokenType>(std::make_unique<MatcherOptional<TokenType>>(std::move(matcher))); + } + + _NODISCARD MatcherFactoryWrapper<TokenType> Label(const int label) const { + return MatcherFactoryWrapper<TokenType>(std::make_unique<MatcherLabel<TokenType>>(m_label_supplier, label)); + } }; diff --git a/src/Parser/Parsing/Matcher/MatcherAnd.h b/src/Parser/Parsing/Matcher/MatcherAnd.h index 740c36b17..0edc8170c 100644 --- a/src/Parser/Parsing/Matcher/MatcherAnd.h +++ b/src/Parser/Parsing/Matcher/MatcherAnd.h @@ -3,43 +3,34 @@ #include <iterator> #include <memory> -#include "Parsing/IParserValue.h" #include "AbstractMatcher.h" +#include "Parsing/IParserValue.h" -template <typename TokenType> -class MatcherAnd final : public AbstractMatcher<TokenType> -{ - // TokenType must inherit IParserValue - static_assert(std::is_base_of<IParserValue, TokenType>::value); +template <typename TokenType> class MatcherAnd final : public AbstractMatcher<TokenType> { + // TokenType must inherit IParserValue + static_assert(std::is_base_of<IParserValue, TokenType>::value); - std::vector<std::unique_ptr<AbstractMatcher<TokenType>>> m_matchers; + std::vector<std::unique_ptr<AbstractMatcher<TokenType>>> m_matchers; protected: - MatcherResult<TokenType> CanMatch(ILexer<TokenType>* lexer, const unsigned tokenOffset) override - { - auto matchResult = MatcherResult<TokenType>::Match(0); - - for (const std::unique_ptr<AbstractMatcher<TokenType>>& matcher : m_matchers) - { - MatcherResult<TokenType> result = matcher->Match(lexer, tokenOffset + matchResult.m_consumed_token_count); - - if (!result.m_matches) - return MatcherResult<TokenType>::NoMatch(); - - matchResult.Absorb(std::move(result)); - } - - return matchResult; + MatcherResult<TokenType> CanMatch(ILexer<TokenType> *lexer, const unsigned tokenOffset) override { + auto matchResult = MatcherResult<TokenType>::Match(0); + + for (const std::unique_ptr<AbstractMatcher<TokenType>> &matcher : m_matchers) { + MatcherResult<TokenType> result = matcher->Match(lexer, tokenOffset + matchResult.m_consumed_token_count); + + if (!result.m_matches) + return MatcherResult<TokenType>::NoMatch(); + + matchResult.Absorb(std::move(result)); } + return matchResult; + } + public: - MatcherAnd(std::initializer_list<Movable<std::unique_ptr<AbstractMatcher<TokenType>>>> matchers) - : m_matchers(std::make_move_iterator(matchers.begin()), std::make_move_iterator(matchers.end())) - { - } + MatcherAnd(std::initializer_list<Movable<std::unique_ptr<AbstractMatcher<TokenType>>>> matchers) + : m_matchers(std::make_move_iterator(matchers.begin()), std::make_move_iterator(matchers.end())) {} - explicit MatcherAnd(std::vector<std::unique_ptr<AbstractMatcher<TokenType>>> matchers) - : m_matchers(std::move(matchers)) - { - } + explicit MatcherAnd(std::vector<std::unique_ptr<AbstractMatcher<TokenType>>> matchers) : m_matchers(std::move(matchers)) {} }; diff --git a/src/Parser/Parsing/Matcher/MatcherFalse.h b/src/Parser/Parsing/Matcher/MatcherFalse.h index 3834c223d..608f16b6c 100644 --- a/src/Parser/Parsing/Matcher/MatcherFalse.h +++ b/src/Parser/Parsing/Matcher/MatcherFalse.h @@ -2,22 +2,16 @@ #include <memory> -#include "Parsing/IParserValue.h" #include "AbstractMatcher.h" +#include "Parsing/IParserValue.h" -template <typename TokenType> -class MatcherFalse final : public AbstractMatcher<TokenType> -{ - // TokenType must inherit IParserValue - static_assert(std::is_base_of<IParserValue, TokenType>::value); +template <typename TokenType> class MatcherFalse final : public AbstractMatcher<TokenType> { + // TokenType must inherit IParserValue + static_assert(std::is_base_of<IParserValue, TokenType>::value); protected: - MatcherResult<TokenType> CanMatch(ILexer<TokenType>* lexer, unsigned tokenOffset) override - { - return MatcherResult<TokenType>::NoMatch(); - } + MatcherResult<TokenType> CanMatch(ILexer<TokenType> *lexer, unsigned tokenOffset) override { return MatcherResult<TokenType>::NoMatch(); } public: - MatcherFalse() - = default; + MatcherFalse() = default; }; diff --git a/src/Parser/Parsing/Matcher/MatcherLabel.h b/src/Parser/Parsing/Matcher/MatcherLabel.h index 1dff01a31..3445ba2de 100644 --- a/src/Parser/Parsing/Matcher/MatcherLabel.h +++ b/src/Parser/Parsing/Matcher/MatcherLabel.h @@ -2,52 +2,43 @@ #include <cassert> -#include "Utils/ClassUtils.h" -#include "Parsing/IParserValue.h" #include "AbstractMatcher.h" +#include "Parsing/IParserValue.h" +#include "Utils/ClassUtils.h" -template <typename TokenType> -class IMatcherForLabelSupplier -{ - // TokenType must inherit IParserValue - static_assert(std::is_base_of<IParserValue, TokenType>::value); +template <typename TokenType> class IMatcherForLabelSupplier { + // TokenType must inherit IParserValue + static_assert(std::is_base_of<IParserValue, TokenType>::value); public: - IMatcherForLabelSupplier() = default; - virtual ~IMatcherForLabelSupplier() = default; - IMatcherForLabelSupplier(const IMatcherForLabelSupplier& other) = default; - IMatcherForLabelSupplier(IMatcherForLabelSupplier&& other) noexcept = default; - IMatcherForLabelSupplier& operator=(const IMatcherForLabelSupplier& other) = default; - IMatcherForLabelSupplier& operator=(IMatcherForLabelSupplier&& other) noexcept = default; - - _NODISCARD virtual AbstractMatcher<TokenType>* GetMatcherForLabel(int label) const = 0; + IMatcherForLabelSupplier() = default; + virtual ~IMatcherForLabelSupplier() = default; + IMatcherForLabelSupplier(const IMatcherForLabelSupplier &other) = default; + IMatcherForLabelSupplier(IMatcherForLabelSupplier &&other) noexcept = default; + IMatcherForLabelSupplier &operator=(const IMatcherForLabelSupplier &other) = default; + IMatcherForLabelSupplier &operator=(IMatcherForLabelSupplier &&other) noexcept = default; + + _NODISCARD virtual AbstractMatcher<TokenType> *GetMatcherForLabel(int label) const = 0; }; -template <typename TokenType> -class MatcherLabel final : public AbstractMatcher<TokenType> -{ - // TokenType must inherit IParserValue - static_assert(std::is_base_of<IParserValue, TokenType>::value); +template <typename TokenType> class MatcherLabel final : public AbstractMatcher<TokenType> { + // TokenType must inherit IParserValue + static_assert(std::is_base_of<IParserValue, TokenType>::value); - const IMatcherForLabelSupplier<TokenType>* m_supplier; - int m_label; + const IMatcherForLabelSupplier<TokenType> *m_supplier; + int m_label; protected: - MatcherResult<TokenType> CanMatch(ILexer<TokenType>* lexer, unsigned tokenOffset) override - { - AbstractMatcher<TokenType>* matcher = m_supplier->GetMatcherForLabel(m_label); + MatcherResult<TokenType> CanMatch(ILexer<TokenType> *lexer, unsigned tokenOffset) override { + AbstractMatcher<TokenType> *matcher = m_supplier->GetMatcherForLabel(m_label); - assert(matcher); - if (matcher) - return matcher->Match(lexer, tokenOffset); + assert(matcher); + if (matcher) + return matcher->Match(lexer, tokenOffset); - return MatcherResult<TokenType>::NoMatch(); - } + return MatcherResult<TokenType>::NoMatch(); + } public: - MatcherLabel(const IMatcherForLabelSupplier<TokenType>* supplier, const int label) - : m_supplier(supplier), - m_label(label) - { - } + MatcherLabel(const IMatcherForLabelSupplier<TokenType> *supplier, const int label) : m_supplier(supplier), m_label(label) {} }; diff --git a/src/Parser/Parsing/Matcher/MatcherLoop.h b/src/Parser/Parsing/Matcher/MatcherLoop.h index 2ef415072..df60a45df 100644 --- a/src/Parser/Parsing/Matcher/MatcherLoop.h +++ b/src/Parser/Parsing/Matcher/MatcherLoop.h @@ -2,43 +2,35 @@ #include <memory> -#include "Parsing/IParserValue.h" #include "AbstractMatcher.h" +#include "Parsing/IParserValue.h" -template <typename TokenType> -class MatcherLoop final : public AbstractMatcher<TokenType> -{ - // TokenType must inherit IParserValue - static_assert(std::is_base_of<IParserValue, TokenType>::value); +template <typename TokenType> class MatcherLoop final : public AbstractMatcher<TokenType> { + // TokenType must inherit IParserValue + static_assert(std::is_base_of<IParserValue, TokenType>::value); - std::unique_ptr<AbstractMatcher<TokenType>> m_matcher; + std::unique_ptr<AbstractMatcher<TokenType>> m_matcher; protected: - MatcherResult<TokenType> CanMatch(ILexer<TokenType>* lexer, const unsigned tokenOffset) override - { - auto matchResult = MatcherResult<TokenType>::Match(0); - auto loopedAtLeastOnce = false; - - while(true) - { - auto result = m_matcher->Match(lexer, tokenOffset + matchResult.m_consumed_token_count); - - if(!result.m_matches) - { - if (loopedAtLeastOnce) - return matchResult; - - return MatcherResult<TokenType>::NoMatch(); - } - - loopedAtLeastOnce = true; - matchResult.Absorb(std::move(result)); - } + MatcherResult<TokenType> CanMatch(ILexer<TokenType> *lexer, const unsigned tokenOffset) override { + auto matchResult = MatcherResult<TokenType>::Match(0); + auto loopedAtLeastOnce = false; + + while (true) { + auto result = m_matcher->Match(lexer, tokenOffset + matchResult.m_consumed_token_count); + + if (!result.m_matches) { + if (loopedAtLeastOnce) + return matchResult; + + return MatcherResult<TokenType>::NoMatch(); + } + + loopedAtLeastOnce = true; + matchResult.Absorb(std::move(result)); } + } public: - explicit MatcherLoop(std::unique_ptr<AbstractMatcher<TokenType>> matcher) - : m_matcher(std::move(matcher)) - { - } + explicit MatcherLoop(std::unique_ptr<AbstractMatcher<TokenType>> matcher) : m_matcher(std::move(matcher)) {} }; diff --git a/src/Parser/Parsing/Matcher/MatcherOptional.h b/src/Parser/Parsing/Matcher/MatcherOptional.h index 1360fd6b3..df1052bf6 100644 --- a/src/Parser/Parsing/Matcher/MatcherOptional.h +++ b/src/Parser/Parsing/Matcher/MatcherOptional.h @@ -2,31 +2,25 @@ #include <memory> -#include "Parsing/IParserValue.h" #include "AbstractMatcher.h" +#include "Parsing/IParserValue.h" -template <typename TokenType> -class MatcherOptional final : public AbstractMatcher<TokenType> -{ - // TokenType must inherit IParserValue - static_assert(std::is_base_of<IParserValue, TokenType>::value); +template <typename TokenType> class MatcherOptional final : public AbstractMatcher<TokenType> { + // TokenType must inherit IParserValue + static_assert(std::is_base_of<IParserValue, TokenType>::value); - std::unique_ptr<AbstractMatcher<TokenType>> m_matcher; + std::unique_ptr<AbstractMatcher<TokenType>> m_matcher; protected: - MatcherResult<TokenType> CanMatch(ILexer<TokenType>* lexer, unsigned tokenOffset) override - { - auto result = m_matcher->Match(lexer, tokenOffset); + MatcherResult<TokenType> CanMatch(ILexer<TokenType> *lexer, unsigned tokenOffset) override { + auto result = m_matcher->Match(lexer, tokenOffset); - if (result.m_matches) - return result; + if (result.m_matches) + return result; - return MatcherResult<TokenType>::Match(0); - } + return MatcherResult<TokenType>::Match(0); + } public: - explicit MatcherOptional(std::unique_ptr<AbstractMatcher<TokenType>> matcher) - : m_matcher(std::move(matcher)) - { - } + explicit MatcherOptional(std::unique_ptr<AbstractMatcher<TokenType>> matcher) : m_matcher(std::move(matcher)) {} }; diff --git a/src/Parser/Parsing/Matcher/MatcherOr.h b/src/Parser/Parsing/Matcher/MatcherOr.h index 993073ac5..4aa76be76 100644 --- a/src/Parser/Parsing/Matcher/MatcherOr.h +++ b/src/Parser/Parsing/Matcher/MatcherOr.h @@ -3,41 +3,32 @@ #include <iterator> #include <memory> -#include "Parsing/IParserValue.h" #include "AbstractMatcher.h" +#include "Parsing/IParserValue.h" -template <typename TokenType> -class MatcherOr final : public AbstractMatcher<TokenType> -{ - // TokenType must inherit IParserValue - static_assert(std::is_base_of<IParserValue, TokenType>::value); +template <typename TokenType> class MatcherOr final : public AbstractMatcher<TokenType> { + // TokenType must inherit IParserValue + static_assert(std::is_base_of<IParserValue, TokenType>::value); - std::vector<std::unique_ptr<AbstractMatcher<TokenType>>> m_matchers; + std::vector<std::unique_ptr<AbstractMatcher<TokenType>>> m_matchers; protected: - MatcherResult<TokenType> CanMatch(ILexer<TokenType>* lexer, unsigned tokenOffset) override - { - for (const std::unique_ptr<AbstractMatcher<TokenType>>& matcher : m_matchers) - { - MatcherResult<TokenType> result = matcher->Match(lexer, tokenOffset); - - if (!result.m_matches) - continue; + MatcherResult<TokenType> CanMatch(ILexer<TokenType> *lexer, unsigned tokenOffset) override { + for (const std::unique_ptr<AbstractMatcher<TokenType>> &matcher : m_matchers) { + MatcherResult<TokenType> result = matcher->Match(lexer, tokenOffset); - return result; - } + if (!result.m_matches) + continue; - return MatcherResult<TokenType>::NoMatch(); + return result; } + return MatcherResult<TokenType>::NoMatch(); + } + public: - MatcherOr(std::initializer_list<Movable<std::unique_ptr<AbstractMatcher<TokenType>>>> matchers) - : m_matchers(std::make_move_iterator(matchers.begin()), std::make_move_iterator(matchers.end())) - { - } + MatcherOr(std::initializer_list<Movable<std::unique_ptr<AbstractMatcher<TokenType>>>> matchers) + : m_matchers(std::make_move_iterator(matchers.begin()), std::make_move_iterator(matchers.end())) {} - explicit MatcherOr(std::vector<std::unique_ptr<AbstractMatcher<TokenType>>> matchers) - : m_matchers(std::move(matchers)) - { - } + explicit MatcherOr(std::vector<std::unique_ptr<AbstractMatcher<TokenType>>> matchers) : m_matchers(std::move(matchers)) {} }; diff --git a/src/Parser/Parsing/Matcher/MatcherResult.h b/src/Parser/Parsing/Matcher/MatcherResult.h index 925904a5f..c7df9d7d5 100644 --- a/src/Parser/Parsing/Matcher/MatcherResult.h +++ b/src/Parser/Parsing/Matcher/MatcherResult.h @@ -4,122 +4,83 @@ #include <limits> #include <vector> -#include "Utils/ClassUtils.h" #include "Parsing/IParserValue.h" +#include "Utils/ClassUtils.h" -template <typename TokenType> -class MatcherResult -{ - // TokenType must inherit IParserValue - static_assert(std::is_base_of<IParserValue, TokenType>::value); +template <typename TokenType> class MatcherResult { + // TokenType must inherit IParserValue + static_assert(std::is_base_of<IParserValue, TokenType>::value); public: - class TokenIndex - { - static constexpr unsigned FABRICATED_FLAG_MASK = std::numeric_limits<unsigned>::max() ^ std::numeric_limits<int>::max(); - static constexpr unsigned TOKEN_INDEX_MASK = ~FABRICATED_FLAG_MASK; - - unsigned m_token_index; - - public: - TokenIndex(const unsigned index, const bool isFabricated) - { - m_token_index = index & TOKEN_INDEX_MASK; - if (isFabricated) - m_token_index |= FABRICATED_FLAG_MASK; - } - - _NODISCARD bool IsFabricated() const - { - return m_token_index & FABRICATED_FLAG_MASK; - } - - _NODISCARD unsigned GetTokenIndex() const - { - return m_token_index & TOKEN_INDEX_MASK; - } - }; - - class Capture - { - public: - int m_capture_id; - TokenIndex m_token_index; - - Capture(const int captureId, const unsigned tokenIndex) - : Capture(captureId, tokenIndex, false) - { - } - - Capture(const int captureId, const unsigned tokenIndex, const bool isFabricated) - : m_capture_id(captureId), - m_token_index(tokenIndex, isFabricated) - { - } - - Capture(const int captureId, const TokenIndex index) - : m_capture_id(captureId), - m_token_index(index) - { - } - - _NODISCARD int GetCaptureId() const - { - return m_capture_id; - } - }; - - bool m_matches; - unsigned m_consumed_token_count; - std::vector<int> m_tags; - std::vector<Capture> m_captures; - std::vector<TokenIndex> m_matched_tokens; - std::vector<TokenType> m_fabricated_tokens; + class TokenIndex { + static constexpr unsigned FABRICATED_FLAG_MASK = std::numeric_limits<unsigned>::max() ^ std::numeric_limits<int>::max(); + static constexpr unsigned TOKEN_INDEX_MASK = ~FABRICATED_FLAG_MASK; -private: - MatcherResult(const bool matches, const unsigned consumedTokenCount) - : m_matches(matches), - m_consumed_token_count(consumedTokenCount) - { + unsigned m_token_index; + + public: + TokenIndex(const unsigned index, const bool isFabricated) { + m_token_index = index & TOKEN_INDEX_MASK; + if (isFabricated) + m_token_index |= FABRICATED_FLAG_MASK; } + _NODISCARD bool IsFabricated() const { return m_token_index & FABRICATED_FLAG_MASK; } + + _NODISCARD unsigned GetTokenIndex() const { return m_token_index & TOKEN_INDEX_MASK; } + }; + + class Capture { + public: + int m_capture_id; + TokenIndex m_token_index; + + Capture(const int captureId, const unsigned tokenIndex) : Capture(captureId, tokenIndex, false) {} + + Capture(const int captureId, const unsigned tokenIndex, const bool isFabricated) : m_capture_id(captureId), m_token_index(tokenIndex, isFabricated) {} + + Capture(const int captureId, const TokenIndex index) : m_capture_id(captureId), m_token_index(index) {} + + _NODISCARD int GetCaptureId() const { return m_capture_id; } + }; + + bool m_matches; + unsigned m_consumed_token_count; + std::vector<int> m_tags; + std::vector<Capture> m_captures; + std::vector<TokenIndex> m_matched_tokens; + std::vector<TokenType> m_fabricated_tokens; + +private: + MatcherResult(const bool matches, const unsigned consumedTokenCount) : m_matches(matches), m_consumed_token_count(consumedTokenCount) {} + public: - static MatcherResult Match(unsigned consumedTokenCount) - { - return MatcherResult(true, consumedTokenCount); + static MatcherResult Match(unsigned consumedTokenCount) { return MatcherResult(true, consumedTokenCount); } + + static MatcherResult NoMatch() { return MatcherResult(false, 0); } + + void Absorb(MatcherResult<TokenType> &&other) { + m_consumed_token_count += other.m_consumed_token_count; + + if (!other.m_tags.empty()) + std::copy(other.m_tags.begin(), other.m_tags.end(), std::back_inserter(m_tags)); + + for (const auto &capture : other.m_captures) { + if (capture.m_token_index.IsFabricated()) + m_captures.emplace_back(capture.GetCaptureId(), TokenIndex(m_fabricated_tokens.size() + capture.m_token_index.GetTokenIndex(), true)); + else + m_captures.emplace_back(capture.GetCaptureId(), capture.m_token_index); } - static MatcherResult NoMatch() - { - return MatcherResult(false, 0); + for (const auto &token : other.m_matched_tokens) { + if (token.IsFabricated()) + m_matched_tokens.emplace_back(m_fabricated_tokens.size() + token.GetTokenIndex(), true); + else + m_matched_tokens.emplace_back(token.GetTokenIndex(), false); } - void Absorb(MatcherResult<TokenType>&& other) - { - m_consumed_token_count += other.m_consumed_token_count; - - if (!other.m_tags.empty()) - std::copy(other.m_tags.begin(), other.m_tags.end(), std::back_inserter(m_tags)); - - for (const auto& capture : other.m_captures) - { - if (capture.m_token_index.IsFabricated()) - m_captures.emplace_back(capture.GetCaptureId(), TokenIndex(m_fabricated_tokens.size() + capture.m_token_index.GetTokenIndex(), true)); - else - m_captures.emplace_back(capture.GetCaptureId(), capture.m_token_index); - } - - for (const auto& token : other.m_matched_tokens) - { - if (token.IsFabricated()) - m_matched_tokens.emplace_back(m_fabricated_tokens.size() + token.GetTokenIndex(), true); - else - m_matched_tokens.emplace_back(token.GetTokenIndex(), false); - } - - for (auto& fabricated : other.m_fabricated_tokens) - { - m_fabricated_tokens.emplace_back(std::move(fabricated)); - } + for (auto &fabricated : other.m_fabricated_tokens) { + m_fabricated_tokens.emplace_back(std::move(fabricated)); } + } }; diff --git a/src/Parser/Parsing/Matcher/MatcherTrue.h b/src/Parser/Parsing/Matcher/MatcherTrue.h index 7dd6375cc..83267ba32 100644 --- a/src/Parser/Parsing/Matcher/MatcherTrue.h +++ b/src/Parser/Parsing/Matcher/MatcherTrue.h @@ -2,22 +2,16 @@ #include <memory> -#include "Parsing/IParserValue.h" #include "AbstractMatcher.h" +#include "Parsing/IParserValue.h" -template <typename TokenType> -class MatcherTrue final : public AbstractMatcher<TokenType> -{ - // TokenType must inherit IParserValue - static_assert(std::is_base_of<IParserValue, TokenType>::value); +template <typename TokenType> class MatcherTrue final : public AbstractMatcher<TokenType> { + // TokenType must inherit IParserValue + static_assert(std::is_base_of<IParserValue, TokenType>::value); protected: - MatcherResult<TokenType> CanMatch(ILexer<TokenType>* lexer, unsigned tokenOffset) override - { - return MatcherResult<TokenType>::Match(0); - } + MatcherResult<TokenType> CanMatch(ILexer<TokenType> *lexer, unsigned tokenOffset) override { return MatcherResult<TokenType>::Match(0); } public: - MatcherTrue() - = default; + MatcherTrue() = default; }; diff --git a/src/Parser/Parsing/ParsingException.cpp b/src/Parser/Parsing/ParsingException.cpp index eeab8ab77..17cceca7f 100644 --- a/src/Parser/Parsing/ParsingException.cpp +++ b/src/Parser/Parsing/ParsingException.cpp @@ -2,31 +2,16 @@ #include <sstream> -ParsingException::ParsingException(const TokenPos position, std::string message) - : m_pos(position), - m_message(std::move(message)) -{ - std::ostringstream str; - str << position.m_filename.get() << " L" << m_pos.m_line << ':' << m_pos.m_column << ' ' << m_message; - m_full_message = str.str(); +ParsingException::ParsingException(const TokenPos position, std::string message) : m_pos(position), m_message(std::move(message)) { + std::ostringstream str; + str << position.m_filename.get() << " L" << m_pos.m_line << ':' << m_pos.m_column << ' ' << m_message; + m_full_message = str.str(); } -TokenPos ParsingException::Position() const -{ - return m_pos; -} +TokenPos ParsingException::Position() const { return m_pos; } -const std::string& ParsingException::Message() const -{ - return m_message; -} +const std::string &ParsingException::Message() const { return m_message; } -std::string ParsingException::FullMessage() const -{ - return m_full_message; -} +std::string ParsingException::FullMessage() const { return m_full_message; } -char const* ParsingException::what() const noexcept -{ - return m_full_message.c_str(); -} +char const *ParsingException::what() const noexcept { return m_full_message.c_str(); } diff --git a/src/Parser/Parsing/ParsingException.h b/src/Parser/Parsing/ParsingException.h index 400b92341..40a9ac657 100644 --- a/src/Parser/Parsing/ParsingException.h +++ b/src/Parser/Parsing/ParsingException.h @@ -6,17 +6,16 @@ #include "TokenPos.h" #include "Utils/ClassUtils.h" -class ParsingException final : std::exception -{ - TokenPos m_pos; - std::string m_message; - std::string m_full_message; +class ParsingException final : std::exception { + TokenPos m_pos; + std::string m_message; + std::string m_full_message; public: - ParsingException(TokenPos position, std::string message); + ParsingException(TokenPos position, std::string message); - _NODISCARD TokenPos Position() const; - _NODISCARD const std::string& Message() const; - _NODISCARD std::string FullMessage() const; - _NODISCARD char const* what() const noexcept override; + _NODISCARD TokenPos Position() const; + _NODISCARD const std::string &Message() const; + _NODISCARD std::string FullMessage() const; + _NODISCARD char const *what() const noexcept override; }; diff --git a/src/Parser/Parsing/Sequence/AbstractScopeSequenceHolder.h b/src/Parser/Parsing/Sequence/AbstractScopeSequenceHolder.h index 24403005e..4e9ed39ce 100644 --- a/src/Parser/Parsing/Sequence/AbstractScopeSequenceHolder.h +++ b/src/Parser/Parsing/Sequence/AbstractScopeSequenceHolder.h @@ -3,29 +3,24 @@ #include <memory> #include <vector> -template <typename ParserType> -class AbstractScopeSequenceHolder -{ - std::vector<std::unique_ptr<typename ParserType::sequence_t>>& m_all_sequences; - std::vector<typename ParserType::sequence_t*>& m_scope_sequences; +template <typename ParserType> class AbstractScopeSequenceHolder { + std::vector<std::unique_ptr<typename ParserType::sequence_t>> &m_all_sequences; + std::vector<typename ParserType::sequence_t *> &m_scope_sequences; protected: - AbstractScopeSequenceHolder(std::vector<std::unique_ptr<typename ParserType::sequence_t>>& allSequences, std::vector<typename ParserType::sequence_t*>& scopeSequences) - : m_all_sequences(allSequences), - m_scope_sequences(scopeSequences) - { - } + AbstractScopeSequenceHolder(std::vector<std::unique_ptr<typename ParserType::sequence_t>> &allSequences, + std::vector<typename ParserType::sequence_t *> &scopeSequences) + : m_all_sequences(allSequences), m_scope_sequences(scopeSequences) {} - void AddSequence(std::unique_ptr<typename ParserType::sequence_t> test) const - { - m_scope_sequences.push_back(test.get()); - m_all_sequences.emplace_back(std::move(test)); - } + void AddSequence(std::unique_ptr<typename ParserType::sequence_t> test) const { + m_scope_sequences.push_back(test.get()); + m_all_sequences.emplace_back(std::move(test)); + } public: - virtual ~AbstractScopeSequenceHolder() = default; - AbstractScopeSequenceHolder(const AbstractScopeSequenceHolder& other) = delete; - AbstractScopeSequenceHolder(AbstractScopeSequenceHolder&& other) noexcept = default; - AbstractScopeSequenceHolder& operator=(const AbstractScopeSequenceHolder& other) = delete; - AbstractScopeSequenceHolder& operator=(AbstractScopeSequenceHolder&& other) noexcept = delete; + virtual ~AbstractScopeSequenceHolder() = default; + AbstractScopeSequenceHolder(const AbstractScopeSequenceHolder &other) = delete; + AbstractScopeSequenceHolder(AbstractScopeSequenceHolder &&other) noexcept = default; + AbstractScopeSequenceHolder &operator=(const AbstractScopeSequenceHolder &other) = delete; + AbstractScopeSequenceHolder &operator=(AbstractScopeSequenceHolder &&other) noexcept = delete; }; diff --git a/src/Parser/Parsing/Sequence/AbstractSequence.h b/src/Parser/Parsing/Sequence/AbstractSequence.h index b61fd06fb..8147e53dc 100644 --- a/src/Parser/Parsing/Sequence/AbstractSequence.h +++ b/src/Parser/Parsing/Sequence/AbstractSequence.h @@ -1,93 +1,83 @@ #pragma once -#include <unordered_map> #include <cassert> +#include <unordered_map> -#include "SequenceResult.h" -#include "Utils/ClassUtils.h" #include "Parsing/Matcher/AbstractMatcher.h" #include "Parsing/Matcher/MatcherAnd.h" #include "Parsing/Matcher/MatcherLabel.h" +#include "SequenceResult.h" +#include "Utils/ClassUtils.h" -template<typename TokenType, typename ParserState> -class AbstractSequence : protected IMatcherForLabelSupplier<TokenType> -{ - // TokenType must inherit IParserValue - static_assert(std::is_base_of<IParserValue, TokenType>::value); +template <typename TokenType, typename ParserState> class AbstractSequence : protected IMatcherForLabelSupplier<TokenType> { + // TokenType must inherit IParserValue + static_assert(std::is_base_of<IParserValue, TokenType>::value); public: - typedef AbstractMatcher<TokenType> matcher_t; + typedef AbstractMatcher<TokenType> matcher_t; private: - - std::unique_ptr<matcher_t> m_entry; - std::unordered_map<int, std::unique_ptr<matcher_t>> m_matchers; + std::unique_ptr<matcher_t> m_entry; + std::unordered_map<int, std::unique_ptr<matcher_t>> m_matchers; protected: - static constexpr int ENTRY_LABEL = 0; + static constexpr int ENTRY_LABEL = 0; - AbstractSequence() = default; + AbstractSequence() = default; - virtual void ProcessMatch(ParserState* state, SequenceResult<TokenType>& result) const = 0; + virtual void ProcessMatch(ParserState *state, SequenceResult<TokenType> &result) const = 0; - void AddMatchers(std::unique_ptr<matcher_t> matcher) - { - assert(!m_entry); - m_entry = std::move(matcher); - } + void AddMatchers(std::unique_ptr<matcher_t> matcher) { + assert(!m_entry); + m_entry = std::move(matcher); + } - void AddMatchers(std::initializer_list<Movable<std::unique_ptr<matcher_t>>> matchers) - { - assert(!m_entry); - m_entry = std::make_unique<MatcherAnd<TokenType>>(matchers); - } + void AddMatchers(std::initializer_list<Movable<std::unique_ptr<matcher_t>>> matchers) { + assert(!m_entry); + m_entry = std::make_unique<MatcherAnd<TokenType>>(matchers); + } - void AddLabeledMatchers(std::unique_ptr<matcher_t> matcher, const int label) - { - assert(m_matchers.find(label) == m_matchers.end()); - m_matchers.emplace(label, std::move(matcher)); - } + void AddLabeledMatchers(std::unique_ptr<matcher_t> matcher, const int label) { + assert(m_matchers.find(label) == m_matchers.end()); + m_matchers.emplace(label, std::move(matcher)); + } - void AddLabeledMatchers(std::initializer_list<Movable<std::unique_ptr<matcher_t>>> matchers, const int label) - { - assert(m_matchers.find(label) == m_matchers.end()); - m_matchers.emplace(label, std::make_unique<MatcherAnd<TokenType>>(matchers)); - } + void AddLabeledMatchers(std::initializer_list<Movable<std::unique_ptr<matcher_t>>> matchers, const int label) { + assert(m_matchers.find(label) == m_matchers.end()); + m_matchers.emplace(label, std::make_unique<MatcherAnd<TokenType>>(matchers)); + } public: - ~AbstractSequence() override = default; - AbstractSequence(const AbstractSequence& other) = default; - AbstractSequence(AbstractSequence&& other) noexcept = default; - AbstractSequence& operator=(const AbstractSequence& other) = default; - AbstractSequence& operator=(AbstractSequence&& other) noexcept = default; + ~AbstractSequence() override = default; + AbstractSequence(const AbstractSequence &other) = default; + AbstractSequence(AbstractSequence &&other) noexcept = default; + AbstractSequence &operator=(const AbstractSequence &other) = default; + AbstractSequence &operator=(AbstractSequence &&other) noexcept = default; - _NODISCARD matcher_t* GetMatcherForLabel(const int label) const override - { - if (label == 0) - return m_entry.get(); + _NODISCARD matcher_t *GetMatcherForLabel(const int label) const override { + if (label == 0) + return m_entry.get(); - const auto foundEntry = m_matchers.find(label); + const auto foundEntry = m_matchers.find(label); - if (foundEntry != m_matchers.end()) - return foundEntry->second.get(); + if (foundEntry != m_matchers.end()) + return foundEntry->second.get(); - return nullptr; - } + return nullptr; + } - _NODISCARD bool MatchSequence(ILexer<TokenType>* lexer, ParserState* state, unsigned& consumedTokenCount) const - { - if (!m_entry) - return false; - - auto result = m_entry->Match(lexer, 0); - - if (result.m_matches) - { - SequenceResult<TokenType> sequenceResult(lexer, result); - ProcessMatch(state, sequenceResult); - consumedTokenCount = result.m_consumed_token_count; - } - - return result.m_matches; + _NODISCARD bool MatchSequence(ILexer<TokenType> *lexer, ParserState *state, unsigned &consumedTokenCount) const { + if (!m_entry) + return false; + + auto result = m_entry->Match(lexer, 0); + + if (result.m_matches) { + SequenceResult<TokenType> sequenceResult(lexer, result); + ProcessMatch(state, sequenceResult); + consumedTokenCount = result.m_consumed_token_count; } + + return result.m_matches; + } }; diff --git a/src/Parser/Parsing/Sequence/SequenceResult.h b/src/Parser/Parsing/Sequence/SequenceResult.h index 8c7ae076a..3ebdfea1a 100644 --- a/src/Parser/Parsing/Sequence/SequenceResult.h +++ b/src/Parser/Parsing/Sequence/SequenceResult.h @@ -2,99 +2,83 @@ #include <unordered_map> -#include "Utils/ClassUtils.h" #include "Parsing/Matcher/AbstractMatcher.h" #include "Parsing/Matcher/MatcherResult.h" #include "Parsing/ParsingException.h" +#include "Utils/ClassUtils.h" -template <typename TokenType> -class SequenceResult -{ - class Capture - { - public: - unsigned m_offset; - std::vector<std::reference_wrapper<const TokenType>> m_tokens; +template <typename TokenType> class SequenceResult { + class Capture { + public: + unsigned m_offset; + std::vector<std::reference_wrapper<const TokenType>> m_tokens; - Capture() - : m_offset(0) - { - } - }; + Capture() : m_offset(0) {} + }; - // TokenType must inherit IParserValue - static_assert(std::is_base_of<IParserValue, TokenType>::value); + // TokenType must inherit IParserValue + static_assert(std::is_base_of<IParserValue, TokenType>::value); - std::vector<int> m_tags; - std::unordered_map<int, Capture> m_captures; + std::vector<int> m_tags; + std::unordered_map<int, Capture> m_captures; - unsigned m_tag_offset; + unsigned m_tag_offset; public: - SequenceResult(ILexer<TokenType>* lexer, const MatcherResult<TokenType>& result) - : m_tags(result.m_tags), - m_tag_offset(0) - { - for (const typename MatcherResult<TokenType>::Capture& capture : result.m_captures) - { - if (capture.m_token_index.IsFabricated()) - m_captures[capture.GetCaptureId()].m_tokens.push_back(result.m_fabricated_tokens[capture.m_token_index.GetTokenIndex()]); - else - m_captures[capture.GetCaptureId()].m_tokens.push_back(lexer->GetToken(capture.m_token_index.GetTokenIndex())); - } + SequenceResult(ILexer<TokenType> *lexer, const MatcherResult<TokenType> &result) : m_tags(result.m_tags), m_tag_offset(0) { + for (const typename MatcherResult<TokenType>::Capture &capture : result.m_captures) { + if (capture.m_token_index.IsFabricated()) + m_captures[capture.GetCaptureId()].m_tokens.push_back(result.m_fabricated_tokens[capture.m_token_index.GetTokenIndex()]); + else + m_captures[capture.GetCaptureId()].m_tokens.push_back(lexer->GetToken(capture.m_token_index.GetTokenIndex())); } + } - _NODISCARD int PeekTag() const - { - if (m_tag_offset < m_tags.size()) - return m_tags[m_tag_offset]; + _NODISCARD int PeekTag() const { + if (m_tag_offset < m_tags.size()) + return m_tags[m_tag_offset]; - return AbstractMatcher<TokenType>::NO_ID; - } + return AbstractMatcher<TokenType>::NO_ID; + } - int PeekAndRemoveIfTag(const int tag) - { - if (m_tag_offset < m_tags.size()) - { - const auto result = m_tags[m_tag_offset]; - - if (result == tag) - m_tag_offset++; + int PeekAndRemoveIfTag(const int tag) { + if (m_tag_offset < m_tags.size()) { + const auto result = m_tags[m_tag_offset]; - return result; - } + if (result == tag) + m_tag_offset++; - return AbstractMatcher<TokenType>::NO_ID; + return result; } - int NextTag() - { - if (m_tag_offset < m_tags.size()) - return m_tags[m_tag_offset++]; + return AbstractMatcher<TokenType>::NO_ID; + } - return AbstractMatcher<TokenType>::NO_ID; - } + int NextTag() { + if (m_tag_offset < m_tags.size()) + return m_tags[m_tag_offset++]; - _NODISCARD bool HasNextCapture(int captureId) - { - auto foundEntry = m_captures.find(captureId); + return AbstractMatcher<TokenType>::NO_ID; + } - if (foundEntry == m_captures.end()) - return false; + _NODISCARD bool HasNextCapture(int captureId) { + auto foundEntry = m_captures.find(captureId); - return foundEntry->second.m_offset < foundEntry->second.m_tokens.size(); - } + if (foundEntry == m_captures.end()) + return false; - const TokenType& NextCapture(int captureId) - { - auto foundEntry = m_captures.find(captureId); + return foundEntry->second.m_offset < foundEntry->second.m_tokens.size(); + } - if (foundEntry == m_captures.end()) - throw ParsingException(TokenPos(), "Tried to access next capture even though no captures exists!"); + const TokenType &NextCapture(int captureId) { + auto foundEntry = m_captures.find(captureId); - if(foundEntry->second.m_offset >= foundEntry->second.m_tokens.size()) - throw ParsingException(TokenPos(), "Tried to access next capture even though none exists!"); + if (foundEntry == m_captures.end()) + throw ParsingException(TokenPos(), "Tried to access next capture even though no captures exists!"); - return foundEntry->second.m_tokens[foundEntry->second.m_offset++]; - } + if (foundEntry->second.m_offset >= foundEntry->second.m_tokens.size()) + throw ParsingException(TokenPos(), "Tried to access next capture even though none exists!"); + + return foundEntry->second.m_tokens[foundEntry->second.m_offset++]; + } }; diff --git a/src/Parser/Parsing/Simple/Expression/ISimpleExpression.h b/src/Parser/Parsing/Simple/Expression/ISimpleExpression.h index 97c026b00..ffd783bbd 100644 --- a/src/Parser/Parsing/Simple/Expression/ISimpleExpression.h +++ b/src/Parser/Parsing/Simple/Expression/ISimpleExpression.h @@ -5,35 +5,35 @@ #include "Utils/ClassUtils.h" class SimpleExpressionValue; -class ISimpleExpressionScopeValues -{ +class ISimpleExpressionScopeValues { protected: - ISimpleExpressionScopeValues() = default; + ISimpleExpressionScopeValues() = default; + public: - virtual ~ISimpleExpressionScopeValues() = default; - ISimpleExpressionScopeValues(const ISimpleExpressionScopeValues& other) = default; - ISimpleExpressionScopeValues(ISimpleExpressionScopeValues&& other) noexcept = default; - ISimpleExpressionScopeValues& operator=(const ISimpleExpressionScopeValues& other) = default; - ISimpleExpressionScopeValues& operator=(ISimpleExpressionScopeValues&& other) noexcept = default; + virtual ~ISimpleExpressionScopeValues() = default; + ISimpleExpressionScopeValues(const ISimpleExpressionScopeValues &other) = default; + ISimpleExpressionScopeValues(ISimpleExpressionScopeValues &&other) noexcept = default; + ISimpleExpressionScopeValues &operator=(const ISimpleExpressionScopeValues &other) = default; + ISimpleExpressionScopeValues &operator=(ISimpleExpressionScopeValues &&other) noexcept = default; - _NODISCARD virtual SimpleExpressionValue ValueByName(const std::string& name) const = 0; + _NODISCARD virtual SimpleExpressionValue ValueByName(const std::string &name) const = 0; }; -class ISimpleExpression -{ +class ISimpleExpression { protected: - ISimpleExpression() = default; + ISimpleExpression() = default; + public: - virtual ~ISimpleExpression() = default; - ISimpleExpression(const ISimpleExpression& other) = default; - ISimpleExpression(ISimpleExpression&& other) noexcept = default; - ISimpleExpression& operator=(const ISimpleExpression& other) = default; - ISimpleExpression& operator=(ISimpleExpression&& other) noexcept = default; - - _NODISCARD virtual bool Equals(const ISimpleExpression* other) const = 0; - _NODISCARD virtual bool IsStatic() const = 0; - _NODISCARD virtual SimpleExpressionValue EvaluateStatic() const = 0; - _NODISCARD virtual SimpleExpressionValue EvaluateNonStatic(const ISimpleExpressionScopeValues* scopeValues) const = 0; + virtual ~ISimpleExpression() = default; + ISimpleExpression(const ISimpleExpression &other) = default; + ISimpleExpression(ISimpleExpression &&other) noexcept = default; + ISimpleExpression &operator=(const ISimpleExpression &other) = default; + ISimpleExpression &operator=(ISimpleExpression &&other) noexcept = default; + + _NODISCARD virtual bool Equals(const ISimpleExpression *other) const = 0; + _NODISCARD virtual bool IsStatic() const = 0; + _NODISCARD virtual SimpleExpressionValue EvaluateStatic() const = 0; + _NODISCARD virtual SimpleExpressionValue EvaluateNonStatic(const ISimpleExpressionScopeValues *scopeValues) const = 0; }; // Include SimpleExpressionValue after definition to avoid "base class not defined" diff --git a/src/Parser/Parsing/Simple/Expression/SimpleExpressionBinaryOperation.cpp b/src/Parser/Parsing/Simple/Expression/SimpleExpressionBinaryOperation.cpp index 8b4131b73..d907e4bd6 100644 --- a/src/Parser/Parsing/Simple/Expression/SimpleExpressionBinaryOperation.cpp +++ b/src/Parser/Parsing/Simple/Expression/SimpleExpressionBinaryOperation.cpp @@ -3,407 +3,302 @@ #include <cassert> #include <cmath> -SimpleExpressionBinaryOperationType::SimpleExpressionBinaryOperationType(const SimpleBinaryOperationId id, std::string syntax, const SimpleOperationPrecedence precedence, - evaluation_function_t evaluationFunction) - : m_id(id), - m_syntax(std::move(syntax)), - m_precedence(precedence), - m_evaluation_function(std::move(evaluationFunction)) -{ -} +SimpleExpressionBinaryOperationType::SimpleExpressionBinaryOperationType(const SimpleBinaryOperationId id, std::string syntax, + const SimpleOperationPrecedence precedence, evaluation_function_t evaluationFunction) + : m_id(id), m_syntax(std::move(syntax)), m_precedence(precedence), m_evaluation_function(std::move(evaluationFunction)) {} const SimpleExpressionBinaryOperationType SimpleExpressionBinaryOperationType::OPERATION_ADD( - SimpleBinaryOperationId::ADD, - "+", - SimpleOperationPrecedence::ADDITION_SUBTRACTION, - [](const SimpleExpressionValue& operand1, const SimpleExpressionValue& operand2) -> SimpleExpressionValue - { - if (operand1.m_type == SimpleExpressionValue::Type::DOUBLE) - { - if (operand2.m_type == SimpleExpressionValue::Type::DOUBLE) - return SimpleExpressionValue(operand1.m_double_value + operand2.m_double_value); - if (operand2.m_type == SimpleExpressionValue::Type::INT) - return SimpleExpressionValue(operand1.m_double_value + static_cast<double>(operand2.m_int_value)); - if (operand2.m_type == SimpleExpressionValue::Type::STRING) - return SimpleExpressionValue(std::to_string(operand1.m_double_value) + *operand2.m_string_value); - } - else if (operand1.m_type == SimpleExpressionValue::Type::INT) - { - if (operand2.m_type == SimpleExpressionValue::Type::DOUBLE) - return SimpleExpressionValue(static_cast<double>(operand1.m_int_value) + operand2.m_double_value); - if (operand2.m_type == SimpleExpressionValue::Type::INT) - return SimpleExpressionValue(operand1.m_int_value + operand2.m_int_value); - if (operand2.m_type == SimpleExpressionValue::Type::STRING) - return SimpleExpressionValue(std::to_string(operand1.m_int_value) + *operand2.m_string_value); - } - else if (operand1.m_type == SimpleExpressionValue::Type::STRING) - { - if (operand2.m_type == SimpleExpressionValue::Type::DOUBLE) - return SimpleExpressionValue(*operand1.m_string_value + std::to_string(operand2.m_double_value)); - if (operand2.m_type == SimpleExpressionValue::Type::INT) - return SimpleExpressionValue(*operand1.m_string_value + std::to_string(operand2.m_int_value)); - if (operand2.m_type == SimpleExpressionValue::Type::STRING) - return SimpleExpressionValue(*operand1.m_string_value + *operand2.m_string_value); - } - - return SimpleExpressionValue(0); - } -); + SimpleBinaryOperationId::ADD, "+", SimpleOperationPrecedence::ADDITION_SUBTRACTION, + [](const SimpleExpressionValue &operand1, const SimpleExpressionValue &operand2) -> SimpleExpressionValue { + if (operand1.m_type == SimpleExpressionValue::Type::DOUBLE) { + if (operand2.m_type == SimpleExpressionValue::Type::DOUBLE) + return SimpleExpressionValue(operand1.m_double_value + operand2.m_double_value); + if (operand2.m_type == SimpleExpressionValue::Type::INT) + return SimpleExpressionValue(operand1.m_double_value + static_cast<double>(operand2.m_int_value)); + if (operand2.m_type == SimpleExpressionValue::Type::STRING) + return SimpleExpressionValue(std::to_string(operand1.m_double_value) + *operand2.m_string_value); + } else if (operand1.m_type == SimpleExpressionValue::Type::INT) { + if (operand2.m_type == SimpleExpressionValue::Type::DOUBLE) + return SimpleExpressionValue(static_cast<double>(operand1.m_int_value) + operand2.m_double_value); + if (operand2.m_type == SimpleExpressionValue::Type::INT) + return SimpleExpressionValue(operand1.m_int_value + operand2.m_int_value); + if (operand2.m_type == SimpleExpressionValue::Type::STRING) + return SimpleExpressionValue(std::to_string(operand1.m_int_value) + *operand2.m_string_value); + } else if (operand1.m_type == SimpleExpressionValue::Type::STRING) { + if (operand2.m_type == SimpleExpressionValue::Type::DOUBLE) + return SimpleExpressionValue(*operand1.m_string_value + std::to_string(operand2.m_double_value)); + if (operand2.m_type == SimpleExpressionValue::Type::INT) + return SimpleExpressionValue(*operand1.m_string_value + std::to_string(operand2.m_int_value)); + if (operand2.m_type == SimpleExpressionValue::Type::STRING) + return SimpleExpressionValue(*operand1.m_string_value + *operand2.m_string_value); + } + + return SimpleExpressionValue(0); + }); const SimpleExpressionBinaryOperationType SimpleExpressionBinaryOperationType::OPERATION_SUBTRACT( - SimpleBinaryOperationId::SUBTRACT, - "-", - SimpleOperationPrecedence::ADDITION_SUBTRACTION, - [](const SimpleExpressionValue& operand1, const SimpleExpressionValue& operand2) -> SimpleExpressionValue - { - if (operand1.m_type == SimpleExpressionValue::Type::DOUBLE) - { - if (operand2.m_type == SimpleExpressionValue::Type::DOUBLE) - return SimpleExpressionValue(operand1.m_double_value - operand2.m_double_value); - if (operand2.m_type == SimpleExpressionValue::Type::INT) - return SimpleExpressionValue(operand1.m_double_value - static_cast<double>(operand2.m_int_value)); - } - else if (operand1.m_type == SimpleExpressionValue::Type::INT) - { - if (operand2.m_type == SimpleExpressionValue::Type::DOUBLE) - return SimpleExpressionValue(static_cast<double>(operand1.m_int_value) - operand2.m_double_value); - if (operand2.m_type == SimpleExpressionValue::Type::INT) - return SimpleExpressionValue(operand1.m_int_value - operand2.m_int_value); - } - - return SimpleExpressionValue(0); - } -); + SimpleBinaryOperationId::SUBTRACT, "-", SimpleOperationPrecedence::ADDITION_SUBTRACTION, + [](const SimpleExpressionValue &operand1, const SimpleExpressionValue &operand2) -> SimpleExpressionValue { + if (operand1.m_type == SimpleExpressionValue::Type::DOUBLE) { + if (operand2.m_type == SimpleExpressionValue::Type::DOUBLE) + return SimpleExpressionValue(operand1.m_double_value - operand2.m_double_value); + if (operand2.m_type == SimpleExpressionValue::Type::INT) + return SimpleExpressionValue(operand1.m_double_value - static_cast<double>(operand2.m_int_value)); + } else if (operand1.m_type == SimpleExpressionValue::Type::INT) { + if (operand2.m_type == SimpleExpressionValue::Type::DOUBLE) + return SimpleExpressionValue(static_cast<double>(operand1.m_int_value) - operand2.m_double_value); + if (operand2.m_type == SimpleExpressionValue::Type::INT) + return SimpleExpressionValue(operand1.m_int_value - operand2.m_int_value); + } + + return SimpleExpressionValue(0); + }); const SimpleExpressionBinaryOperationType SimpleExpressionBinaryOperationType::OPERATION_MULTIPLY( - SimpleBinaryOperationId::MULTIPLY, - "*", - SimpleOperationPrecedence::MULTIPLICATION_DIVISION_REMAINDER, - [](const SimpleExpressionValue& operand1, const SimpleExpressionValue& operand2) -> SimpleExpressionValue - { - if (operand1.m_type == SimpleExpressionValue::Type::DOUBLE) - { - if (operand2.m_type == SimpleExpressionValue::Type::DOUBLE) - return SimpleExpressionValue(operand1.m_double_value * operand2.m_double_value); - if (operand2.m_type == SimpleExpressionValue::Type::INT) - return SimpleExpressionValue(operand1.m_double_value * static_cast<double>(operand2.m_int_value)); - } - else if (operand1.m_type == SimpleExpressionValue::Type::INT) - { - if (operand2.m_type == SimpleExpressionValue::Type::DOUBLE) - return SimpleExpressionValue(static_cast<double>(operand1.m_int_value) * operand2.m_double_value); - if (operand2.m_type == SimpleExpressionValue::Type::INT) - return SimpleExpressionValue(operand1.m_int_value * operand2.m_int_value); - } - - return SimpleExpressionValue(0); - } -); + SimpleBinaryOperationId::MULTIPLY, "*", SimpleOperationPrecedence::MULTIPLICATION_DIVISION_REMAINDER, + [](const SimpleExpressionValue &operand1, const SimpleExpressionValue &operand2) -> SimpleExpressionValue { + if (operand1.m_type == SimpleExpressionValue::Type::DOUBLE) { + if (operand2.m_type == SimpleExpressionValue::Type::DOUBLE) + return SimpleExpressionValue(operand1.m_double_value * operand2.m_double_value); + if (operand2.m_type == SimpleExpressionValue::Type::INT) + return SimpleExpressionValue(operand1.m_double_value * static_cast<double>(operand2.m_int_value)); + } else if (operand1.m_type == SimpleExpressionValue::Type::INT) { + if (operand2.m_type == SimpleExpressionValue::Type::DOUBLE) + return SimpleExpressionValue(static_cast<double>(operand1.m_int_value) * operand2.m_double_value); + if (operand2.m_type == SimpleExpressionValue::Type::INT) + return SimpleExpressionValue(operand1.m_int_value * operand2.m_int_value); + } + + return SimpleExpressionValue(0); + }); const SimpleExpressionBinaryOperationType SimpleExpressionBinaryOperationType::OPERATION_DIVIDE( - SimpleBinaryOperationId::DIVIDE, - "/", - SimpleOperationPrecedence::MULTIPLICATION_DIVISION_REMAINDER, - [](const SimpleExpressionValue& operand1, const SimpleExpressionValue& operand2) -> SimpleExpressionValue - { - if (operand1.m_type == SimpleExpressionValue::Type::DOUBLE) - { - if (operand2.m_type == SimpleExpressionValue::Type::DOUBLE) - return SimpleExpressionValue(operand1.m_double_value / operand2.m_double_value); - if (operand2.m_type == SimpleExpressionValue::Type::INT) - return SimpleExpressionValue(operand1.m_double_value / static_cast<double>(operand2.m_int_value)); - } - else if (operand1.m_type == SimpleExpressionValue::Type::INT) - { - if (operand2.m_type == SimpleExpressionValue::Type::DOUBLE) - return SimpleExpressionValue(static_cast<double>(operand1.m_int_value) / operand2.m_double_value); - if (operand2.m_type == SimpleExpressionValue::Type::INT) - return SimpleExpressionValue(operand1.m_int_value / operand2.m_int_value); - } - - return SimpleExpressionValue(0); - } -); + SimpleBinaryOperationId::DIVIDE, "/", SimpleOperationPrecedence::MULTIPLICATION_DIVISION_REMAINDER, + [](const SimpleExpressionValue &operand1, const SimpleExpressionValue &operand2) -> SimpleExpressionValue { + if (operand1.m_type == SimpleExpressionValue::Type::DOUBLE) { + if (operand2.m_type == SimpleExpressionValue::Type::DOUBLE) + return SimpleExpressionValue(operand1.m_double_value / operand2.m_double_value); + if (operand2.m_type == SimpleExpressionValue::Type::INT) + return SimpleExpressionValue(operand1.m_double_value / static_cast<double>(operand2.m_int_value)); + } else if (operand1.m_type == SimpleExpressionValue::Type::INT) { + if (operand2.m_type == SimpleExpressionValue::Type::DOUBLE) + return SimpleExpressionValue(static_cast<double>(operand1.m_int_value) / operand2.m_double_value); + if (operand2.m_type == SimpleExpressionValue::Type::INT) + return SimpleExpressionValue(operand1.m_int_value / operand2.m_int_value); + } + + return SimpleExpressionValue(0); + }); const SimpleExpressionBinaryOperationType SimpleExpressionBinaryOperationType::OPERATION_REMAINDER( - SimpleBinaryOperationId::REMAINDER, - "%", - SimpleOperationPrecedence::MULTIPLICATION_DIVISION_REMAINDER, - [](const SimpleExpressionValue& operand1, const SimpleExpressionValue& operand2) -> SimpleExpressionValue - { - if (operand1.m_type == SimpleExpressionValue::Type::INT && operand2.m_type == SimpleExpressionValue::Type::INT) - return SimpleExpressionValue(operand1.m_int_value % operand2.m_int_value); + SimpleBinaryOperationId::REMAINDER, "%", SimpleOperationPrecedence::MULTIPLICATION_DIVISION_REMAINDER, + [](const SimpleExpressionValue &operand1, const SimpleExpressionValue &operand2) -> SimpleExpressionValue { + if (operand1.m_type == SimpleExpressionValue::Type::INT && operand2.m_type == SimpleExpressionValue::Type::INT) + return SimpleExpressionValue(operand1.m_int_value % operand2.m_int_value); - return SimpleExpressionValue(0); - } -); + return SimpleExpressionValue(0); + }); const SimpleExpressionBinaryOperationType SimpleExpressionBinaryOperationType::OPERATION_BITWISE_AND( - SimpleBinaryOperationId::BITWISE_AND, - "&", - SimpleOperationPrecedence::BITWISE_AND, - [](const SimpleExpressionValue& operand1, const SimpleExpressionValue& operand2) -> SimpleExpressionValue - { - if (operand1.m_type == SimpleExpressionValue::Type::INT && operand2.m_type == SimpleExpressionValue::Type::INT) - return SimpleExpressionValue(operand1.m_int_value & operand2.m_int_value); + SimpleBinaryOperationId::BITWISE_AND, "&", SimpleOperationPrecedence::BITWISE_AND, + [](const SimpleExpressionValue &operand1, const SimpleExpressionValue &operand2) -> SimpleExpressionValue { + if (operand1.m_type == SimpleExpressionValue::Type::INT && operand2.m_type == SimpleExpressionValue::Type::INT) + return SimpleExpressionValue(operand1.m_int_value & operand2.m_int_value); - return SimpleExpressionValue(0); - } -); + return SimpleExpressionValue(0); + }); const SimpleExpressionBinaryOperationType SimpleExpressionBinaryOperationType::OPERATION_BITWISE_OR( - SimpleBinaryOperationId::BITWISE_OR, - "|", - SimpleOperationPrecedence::BITWISE_OR, - [](const SimpleExpressionValue& operand1, const SimpleExpressionValue& operand2) -> SimpleExpressionValue - { - if (operand1.m_type == SimpleExpressionValue::Type::INT && operand2.m_type == SimpleExpressionValue::Type::INT) - return SimpleExpressionValue(operand1.m_int_value | operand2.m_int_value); + SimpleBinaryOperationId::BITWISE_OR, "|", SimpleOperationPrecedence::BITWISE_OR, + [](const SimpleExpressionValue &operand1, const SimpleExpressionValue &operand2) -> SimpleExpressionValue { + if (operand1.m_type == SimpleExpressionValue::Type::INT && operand2.m_type == SimpleExpressionValue::Type::INT) + return SimpleExpressionValue(operand1.m_int_value | operand2.m_int_value); - return SimpleExpressionValue(0); - } -); + return SimpleExpressionValue(0); + }); const SimpleExpressionBinaryOperationType SimpleExpressionBinaryOperationType::OPERATION_SHIFT_LEFT( - SimpleBinaryOperationId::SHIFT_LEFT, - "<<", - SimpleOperationPrecedence::BITWISE_SHIFT, - [](const SimpleExpressionValue& operand1, const SimpleExpressionValue& operand2) -> SimpleExpressionValue - { - if (operand1.m_type == SimpleExpressionValue::Type::INT && operand2.m_type == SimpleExpressionValue::Type::INT) - return SimpleExpressionValue(operand1.m_int_value << operand2.m_int_value); + SimpleBinaryOperationId::SHIFT_LEFT, "<<", SimpleOperationPrecedence::BITWISE_SHIFT, + [](const SimpleExpressionValue &operand1, const SimpleExpressionValue &operand2) -> SimpleExpressionValue { + if (operand1.m_type == SimpleExpressionValue::Type::INT && operand2.m_type == SimpleExpressionValue::Type::INT) + return SimpleExpressionValue(operand1.m_int_value << operand2.m_int_value); - return SimpleExpressionValue(0); - } -); + return SimpleExpressionValue(0); + }); const SimpleExpressionBinaryOperationType SimpleExpressionBinaryOperationType::OPERATION_SHIFT_RIGHT( - SimpleBinaryOperationId::SHIFT_RIGHT, - ">>", - SimpleOperationPrecedence::BITWISE_SHIFT, - [](const SimpleExpressionValue& operand1, const SimpleExpressionValue& operand2) -> SimpleExpressionValue - { - if (operand1.m_type == SimpleExpressionValue::Type::INT && operand2.m_type == SimpleExpressionValue::Type::INT) - return SimpleExpressionValue(operand1.m_int_value >> operand2.m_int_value); + SimpleBinaryOperationId::SHIFT_RIGHT, ">>", SimpleOperationPrecedence::BITWISE_SHIFT, + [](const SimpleExpressionValue &operand1, const SimpleExpressionValue &operand2) -> SimpleExpressionValue { + if (operand1.m_type == SimpleExpressionValue::Type::INT && operand2.m_type == SimpleExpressionValue::Type::INT) + return SimpleExpressionValue(operand1.m_int_value >> operand2.m_int_value); - return SimpleExpressionValue(0); - } -); + return SimpleExpressionValue(0); + }); const SimpleExpressionBinaryOperationType SimpleExpressionBinaryOperationType::OPERATION_GREATER_THAN( - SimpleBinaryOperationId::GREATER_THAN, - ">", - SimpleOperationPrecedence::RELATIONAL_GREATER_LESS_THAN, - [](const SimpleExpressionValue& operand1, const SimpleExpressionValue& operand2) -> SimpleExpressionValue - { - if (operand1.m_type == SimpleExpressionValue::Type::STRING || operand2.m_type == SimpleExpressionValue::Type::STRING) - return SimpleExpressionValue(operand1.IsTruthy() > operand2.IsTruthy()); - - if (operand1.m_type == SimpleExpressionValue::Type::DOUBLE) - { - if (operand2.m_type == SimpleExpressionValue::Type::DOUBLE) - return SimpleExpressionValue(operand1.m_double_value > operand2.m_double_value); - if (operand2.m_type == SimpleExpressionValue::Type::INT) - return SimpleExpressionValue(operand1.m_double_value > operand2.m_int_value); - } - else if (operand1.m_type == SimpleExpressionValue::Type::INT) - { - if (operand2.m_type == SimpleExpressionValue::Type::DOUBLE) - return SimpleExpressionValue(operand1.m_int_value > operand2.m_double_value); - if (operand2.m_type == SimpleExpressionValue::Type::INT) - return SimpleExpressionValue(operand1.m_int_value > operand2.m_int_value); - } + SimpleBinaryOperationId::GREATER_THAN, ">", SimpleOperationPrecedence::RELATIONAL_GREATER_LESS_THAN, + [](const SimpleExpressionValue &operand1, const SimpleExpressionValue &operand2) -> SimpleExpressionValue { + if (operand1.m_type == SimpleExpressionValue::Type::STRING || operand2.m_type == SimpleExpressionValue::Type::STRING) + return SimpleExpressionValue(operand1.IsTruthy() > operand2.IsTruthy()); + + if (operand1.m_type == SimpleExpressionValue::Type::DOUBLE) { + if (operand2.m_type == SimpleExpressionValue::Type::DOUBLE) + return SimpleExpressionValue(operand1.m_double_value > operand2.m_double_value); + if (operand2.m_type == SimpleExpressionValue::Type::INT) + return SimpleExpressionValue(operand1.m_double_value > operand2.m_int_value); + } else if (operand1.m_type == SimpleExpressionValue::Type::INT) { + if (operand2.m_type == SimpleExpressionValue::Type::DOUBLE) + return SimpleExpressionValue(operand1.m_int_value > operand2.m_double_value); + if (operand2.m_type == SimpleExpressionValue::Type::INT) + return SimpleExpressionValue(operand1.m_int_value > operand2.m_int_value); + } + + return SimpleExpressionValue(0); + }); + +const SimpleExpressionBinaryOperationType SimpleExpressionBinaryOperationType::OPERATION_GREATER_EQUAL_THAN( + SimpleBinaryOperationId::GREATER_EQUAL_THAN, ">=", SimpleOperationPrecedence::RELATIONAL_GREATER_LESS_THAN, + [](const SimpleExpressionValue &operand1, const SimpleExpressionValue &operand2) -> SimpleExpressionValue { + if (operand1.m_type == SimpleExpressionValue::Type::STRING || operand2.m_type == SimpleExpressionValue::Type::STRING) + return SimpleExpressionValue(operand1.IsTruthy() >= operand2.IsTruthy()); + + if (operand1.m_type == SimpleExpressionValue::Type::DOUBLE) { + if (operand2.m_type == SimpleExpressionValue::Type::DOUBLE) + return SimpleExpressionValue(operand1.m_double_value >= operand2.m_double_value); + if (operand2.m_type == SimpleExpressionValue::Type::INT) + return SimpleExpressionValue(operand1.m_double_value >= operand2.m_int_value); + } else if (operand1.m_type == SimpleExpressionValue::Type::INT) { + if (operand2.m_type == SimpleExpressionValue::Type::DOUBLE) + return SimpleExpressionValue(operand1.m_int_value >= operand2.m_double_value); + if (operand2.m_type == SimpleExpressionValue::Type::INT) + return SimpleExpressionValue(operand1.m_int_value >= operand2.m_int_value); + } + + return SimpleExpressionValue(0); + }); + +const SimpleExpressionBinaryOperationType SimpleExpressionBinaryOperationType::OPERATION_LESS_THAN( + SimpleBinaryOperationId::LESS_THAN, "<", SimpleOperationPrecedence::RELATIONAL_GREATER_LESS_THAN, + [](const SimpleExpressionValue &operand1, const SimpleExpressionValue &operand2) -> SimpleExpressionValue { + if (operand1.m_type == SimpleExpressionValue::Type::STRING || operand2.m_type == SimpleExpressionValue::Type::STRING) + return SimpleExpressionValue(operand1.IsTruthy() < operand2.IsTruthy()); + + if (operand1.m_type == SimpleExpressionValue::Type::DOUBLE) { + if (operand2.m_type == SimpleExpressionValue::Type::DOUBLE) + return SimpleExpressionValue(operand1.m_double_value < operand2.m_double_value); + if (operand2.m_type == SimpleExpressionValue::Type::INT) + return SimpleExpressionValue(operand1.m_double_value < operand2.m_int_value); + } else if (operand1.m_type == SimpleExpressionValue::Type::INT) { + if (operand2.m_type == SimpleExpressionValue::Type::DOUBLE) + return SimpleExpressionValue(operand1.m_int_value < operand2.m_double_value); + if (operand2.m_type == SimpleExpressionValue::Type::INT) + return SimpleExpressionValue(operand1.m_int_value < operand2.m_int_value); + } + + return SimpleExpressionValue(0); + }); + +const SimpleExpressionBinaryOperationType SimpleExpressionBinaryOperationType::OPERATION_LESS_EQUAL_THAN( + SimpleBinaryOperationId::LESS_EQUAL_THAN, "<=", SimpleOperationPrecedence::RELATIONAL_GREATER_LESS_THAN, + [](const SimpleExpressionValue &operand1, const SimpleExpressionValue &operand2) -> SimpleExpressionValue { + if (operand1.m_type == SimpleExpressionValue::Type::STRING || operand2.m_type == SimpleExpressionValue::Type::STRING) + return SimpleExpressionValue(operand1.IsTruthy() <= operand2.IsTruthy()); + + if (operand1.m_type == SimpleExpressionValue::Type::DOUBLE) { + if (operand2.m_type == SimpleExpressionValue::Type::DOUBLE) + return SimpleExpressionValue(operand1.m_double_value <= operand2.m_double_value); + if (operand2.m_type == SimpleExpressionValue::Type::INT) + return SimpleExpressionValue(operand1.m_double_value <= operand2.m_int_value); + } else if (operand1.m_type == SimpleExpressionValue::Type::INT) { + if (operand2.m_type == SimpleExpressionValue::Type::DOUBLE) + return SimpleExpressionValue(operand1.m_int_value <= operand2.m_double_value); + if (operand2.m_type == SimpleExpressionValue::Type::INT) + return SimpleExpressionValue(operand1.m_int_value <= operand2.m_int_value); + } + + return SimpleExpressionValue(0); + }); + +const SimpleExpressionBinaryOperationType SimpleExpressionBinaryOperationType::OPERATION_EQUALS( + SimpleBinaryOperationId::EQUALS, "==", SimpleOperationPrecedence::RELATIONAL_EQUALS, + [](const SimpleExpressionValue &operand1, const SimpleExpressionValue &operand2) -> SimpleExpressionValue { + if (operand1.m_type == SimpleExpressionValue::Type::DOUBLE) { + if (operand2.m_type == SimpleExpressionValue::Type::DOUBLE) + return SimpleExpressionValue(std::fpclassify(operand1.m_double_value - operand2.m_double_value) == FP_ZERO); + if (operand2.m_type == SimpleExpressionValue::Type::INT) + return SimpleExpressionValue(std::fpclassify(operand1.m_double_value - static_cast<double>(operand2.m_int_value)) == FP_ZERO); return SimpleExpressionValue(0); - } -); + } -const SimpleExpressionBinaryOperationType SimpleExpressionBinaryOperationType::OPERATION_GREATER_EQUAL_THAN( - SimpleBinaryOperationId::GREATER_EQUAL_THAN, - ">=", - SimpleOperationPrecedence::RELATIONAL_GREATER_LESS_THAN, - [](const SimpleExpressionValue& operand1, const SimpleExpressionValue& operand2) -> SimpleExpressionValue - { - if (operand1.m_type == SimpleExpressionValue::Type::STRING || operand2.m_type == SimpleExpressionValue::Type::STRING) - return SimpleExpressionValue(operand1.IsTruthy() >= operand2.IsTruthy()); - - if (operand1.m_type == SimpleExpressionValue::Type::DOUBLE) - { - if (operand2.m_type == SimpleExpressionValue::Type::DOUBLE) - return SimpleExpressionValue(operand1.m_double_value >= operand2.m_double_value); - if (operand2.m_type == SimpleExpressionValue::Type::INT) - return SimpleExpressionValue(operand1.m_double_value >= operand2.m_int_value); - } - else if (operand1.m_type == SimpleExpressionValue::Type::INT) - { - if (operand2.m_type == SimpleExpressionValue::Type::DOUBLE) - return SimpleExpressionValue(operand1.m_int_value >= operand2.m_double_value); - if (operand2.m_type == SimpleExpressionValue::Type::INT) - return SimpleExpressionValue(operand1.m_int_value >= operand2.m_int_value); - } + if (operand1.m_type == SimpleExpressionValue::Type::INT) { + if (operand2.m_type == SimpleExpressionValue::Type::DOUBLE) + return SimpleExpressionValue(std::fpclassify(operand1.m_double_value - operand2.m_double_value) == FP_ZERO); + if (operand2.m_type == SimpleExpressionValue::Type::INT) + return SimpleExpressionValue(operand1.m_int_value == operand2.m_int_value); return SimpleExpressionValue(0); - } -); + } -const SimpleExpressionBinaryOperationType SimpleExpressionBinaryOperationType::OPERATION_LESS_THAN( - SimpleBinaryOperationId::LESS_THAN, - "<", - SimpleOperationPrecedence::RELATIONAL_GREATER_LESS_THAN, - [](const SimpleExpressionValue& operand1, const SimpleExpressionValue& operand2) -> SimpleExpressionValue - { - if (operand1.m_type == SimpleExpressionValue::Type::STRING || operand2.m_type == SimpleExpressionValue::Type::STRING) - return SimpleExpressionValue(operand1.IsTruthy() < operand2.IsTruthy()); - - if (operand1.m_type == SimpleExpressionValue::Type::DOUBLE) - { - if (operand2.m_type == SimpleExpressionValue::Type::DOUBLE) - return SimpleExpressionValue(operand1.m_double_value < operand2.m_double_value); - if (operand2.m_type == SimpleExpressionValue::Type::INT) - return SimpleExpressionValue(operand1.m_double_value < operand2.m_int_value); - } - else if (operand1.m_type == SimpleExpressionValue::Type::INT) - { - if (operand2.m_type == SimpleExpressionValue::Type::DOUBLE) - return SimpleExpressionValue(operand1.m_int_value < operand2.m_double_value); - if (operand2.m_type == SimpleExpressionValue::Type::INT) - return SimpleExpressionValue(operand1.m_int_value < operand2.m_int_value); - } + if (operand1.m_type == SimpleExpressionValue::Type::STRING) { + if (operand2.m_type == SimpleExpressionValue::Type::STRING) + return SimpleExpressionValue(*operand1.m_string_value == *operand2.m_string_value); return SimpleExpressionValue(0); - } -); + } -const SimpleExpressionBinaryOperationType SimpleExpressionBinaryOperationType::OPERATION_LESS_EQUAL_THAN( - SimpleBinaryOperationId::LESS_EQUAL_THAN, - "<=", - SimpleOperationPrecedence::RELATIONAL_GREATER_LESS_THAN, - [](const SimpleExpressionValue& operand1, const SimpleExpressionValue& operand2) -> SimpleExpressionValue - { - if (operand1.m_type == SimpleExpressionValue::Type::STRING || operand2.m_type == SimpleExpressionValue::Type::STRING) - return SimpleExpressionValue(operand1.IsTruthy() <= operand2.IsTruthy()); - - if (operand1.m_type == SimpleExpressionValue::Type::DOUBLE) - { - if (operand2.m_type == SimpleExpressionValue::Type::DOUBLE) - return SimpleExpressionValue(operand1.m_double_value <= operand2.m_double_value); - if (operand2.m_type == SimpleExpressionValue::Type::INT) - return SimpleExpressionValue(operand1.m_double_value <= operand2.m_int_value); - } - else if (operand1.m_type == SimpleExpressionValue::Type::INT) - { - if (operand2.m_type == SimpleExpressionValue::Type::DOUBLE) - return SimpleExpressionValue(operand1.m_int_value <= operand2.m_double_value); - if (operand2.m_type == SimpleExpressionValue::Type::INT) - return SimpleExpressionValue(operand1.m_int_value <= operand2.m_int_value); - } + return SimpleExpressionValue(0); + }); + +const SimpleExpressionBinaryOperationType SimpleExpressionBinaryOperationType::OPERATION_NOT_EQUAL( + SimpleBinaryOperationId::NOT_EQUAL, "!=", SimpleOperationPrecedence::RELATIONAL_EQUALS, + [](const SimpleExpressionValue &operand1, const SimpleExpressionValue &operand2) -> SimpleExpressionValue { + if (operand1.m_type == SimpleExpressionValue::Type::DOUBLE) { + if (operand2.m_type == SimpleExpressionValue::Type::DOUBLE) + return SimpleExpressionValue(std::fpclassify(operand1.m_double_value - operand2.m_double_value) != FP_ZERO); + if (operand2.m_type == SimpleExpressionValue::Type::INT) + return SimpleExpressionValue(std::fpclassify(operand1.m_double_value - static_cast<double>(operand2.m_int_value)) != FP_ZERO); return SimpleExpressionValue(0); - } -); + } -const SimpleExpressionBinaryOperationType SimpleExpressionBinaryOperationType::OPERATION_EQUALS( - SimpleBinaryOperationId::EQUALS, - "==", - SimpleOperationPrecedence::RELATIONAL_EQUALS, - [](const SimpleExpressionValue& operand1, const SimpleExpressionValue& operand2) -> SimpleExpressionValue - { - if (operand1.m_type == SimpleExpressionValue::Type::DOUBLE) - { - if (operand2.m_type == SimpleExpressionValue::Type::DOUBLE) - return SimpleExpressionValue(std::fpclassify(operand1.m_double_value - operand2.m_double_value) == FP_ZERO); - if (operand2.m_type == SimpleExpressionValue::Type::INT) - return SimpleExpressionValue(std::fpclassify(operand1.m_double_value - static_cast<double>(operand2.m_int_value)) == FP_ZERO); - - return SimpleExpressionValue(0); - } - - if (operand1.m_type == SimpleExpressionValue::Type::INT) - { - if (operand2.m_type == SimpleExpressionValue::Type::DOUBLE) - return SimpleExpressionValue(std::fpclassify(operand1.m_double_value - operand2.m_double_value) == FP_ZERO); - if (operand2.m_type == SimpleExpressionValue::Type::INT) - return SimpleExpressionValue(operand1.m_int_value == operand2.m_int_value); - - return SimpleExpressionValue(0); - } - - if (operand1.m_type == SimpleExpressionValue::Type::STRING) - { - if (operand2.m_type == SimpleExpressionValue::Type::STRING) - return SimpleExpressionValue(*operand1.m_string_value == *operand2.m_string_value); - - return SimpleExpressionValue(0); - } + if (operand1.m_type == SimpleExpressionValue::Type::INT) { + if (operand2.m_type == SimpleExpressionValue::Type::DOUBLE) + return SimpleExpressionValue(std::fpclassify(operand1.m_double_value - operand2.m_double_value) != FP_ZERO); + if (operand2.m_type == SimpleExpressionValue::Type::INT) + return SimpleExpressionValue(operand1.m_int_value != operand2.m_int_value); return SimpleExpressionValue(0); - } -); + } -const SimpleExpressionBinaryOperationType SimpleExpressionBinaryOperationType::OPERATION_NOT_EQUAL( - SimpleBinaryOperationId::NOT_EQUAL, - "!=", - SimpleOperationPrecedence::RELATIONAL_EQUALS, - [](const SimpleExpressionValue& operand1, const SimpleExpressionValue& operand2) -> SimpleExpressionValue - { - if (operand1.m_type == SimpleExpressionValue::Type::DOUBLE) - { - if (operand2.m_type == SimpleExpressionValue::Type::DOUBLE) - return SimpleExpressionValue(std::fpclassify(operand1.m_double_value - operand2.m_double_value) != FP_ZERO); - if (operand2.m_type == SimpleExpressionValue::Type::INT) - return SimpleExpressionValue(std::fpclassify(operand1.m_double_value - static_cast<double>(operand2.m_int_value)) != FP_ZERO); - - return SimpleExpressionValue(0); - } - - if (operand1.m_type == SimpleExpressionValue::Type::INT) - { - if (operand2.m_type == SimpleExpressionValue::Type::DOUBLE) - return SimpleExpressionValue(std::fpclassify(operand1.m_double_value - operand2.m_double_value) != FP_ZERO); - if (operand2.m_type == SimpleExpressionValue::Type::INT) - return SimpleExpressionValue(operand1.m_int_value != operand2.m_int_value); - - return SimpleExpressionValue(0); - } - - if (operand1.m_type == SimpleExpressionValue::Type::STRING) - { - if (operand2.m_type == SimpleExpressionValue::Type::STRING) - return SimpleExpressionValue(*operand1.m_string_value != *operand2.m_string_value); - - return SimpleExpressionValue(0); - } + if (operand1.m_type == SimpleExpressionValue::Type::STRING) { + if (operand2.m_type == SimpleExpressionValue::Type::STRING) + return SimpleExpressionValue(*operand1.m_string_value != *operand2.m_string_value); return SimpleExpressionValue(0); - } -); + } + + return SimpleExpressionValue(0); + }); const SimpleExpressionBinaryOperationType SimpleExpressionBinaryOperationType::OPERATION_AND( - SimpleBinaryOperationId::AND, - "&&", - SimpleOperationPrecedence::LOGICAL_AND, - [](const SimpleExpressionValue& operand1, const SimpleExpressionValue& operand2) -> SimpleExpressionValue - { - if (operand1.IsTruthy()) - return operand2; - return operand1; - } -); - -const SimpleExpressionBinaryOperationType SimpleExpressionBinaryOperationType::OPERATION_OR( - SimpleBinaryOperationId::OR, - "||", - SimpleOperationPrecedence::LOGICAL_OR, - [](const SimpleExpressionValue& operand1, const SimpleExpressionValue& operand2) -> SimpleExpressionValue - { - if (operand1.IsTruthy()) - return operand1; + SimpleBinaryOperationId::AND, "&&", SimpleOperationPrecedence::LOGICAL_AND, + [](const SimpleExpressionValue &operand1, const SimpleExpressionValue &operand2) -> SimpleExpressionValue { + if (operand1.IsTruthy()) return operand2; - } -); - -const SimpleExpressionBinaryOperationType* const SimpleExpressionBinaryOperationType::ALL_OPERATION_TYPES[static_cast<int>(SimpleBinaryOperationId::COUNT)] -{ + return operand1; + }); + +const SimpleExpressionBinaryOperationType SimpleExpressionBinaryOperationType::OPERATION_OR(SimpleBinaryOperationId::OR, "||", + SimpleOperationPrecedence::LOGICAL_OR, + [](const SimpleExpressionValue &operand1, + const SimpleExpressionValue &operand2) -> SimpleExpressionValue { + if (operand1.IsTruthy()) + return operand1; + return operand2; + }); + +const SimpleExpressionBinaryOperationType *const SimpleExpressionBinaryOperationType::ALL_OPERATION_TYPES[static_cast<int>(SimpleBinaryOperationId::COUNT)]{ &OPERATION_ADD, &OPERATION_SUBTRACT, &OPERATION_MULTIPLY, @@ -420,52 +315,39 @@ const SimpleExpressionBinaryOperationType* const SimpleExpressionBinaryOperation &OPERATION_EQUALS, &OPERATION_NOT_EQUAL, &OPERATION_AND, - &OPERATION_OR -}; - -SimpleExpressionBinaryOperation::SimpleExpressionBinaryOperation(const SimpleExpressionBinaryOperationType* operationType, std::unique_ptr<ISimpleExpression> operand1, - std::unique_ptr<ISimpleExpression> operand2) - : m_operation_type(operationType), - m_operand1(std::move(operand1)), - m_operand2(std::move(operand2)) -{ -} + &OPERATION_OR}; + +SimpleExpressionBinaryOperation::SimpleExpressionBinaryOperation(const SimpleExpressionBinaryOperationType *operationType, + std::unique_ptr<ISimpleExpression> operand1, std::unique_ptr<ISimpleExpression> operand2) + : m_operation_type(operationType), m_operand1(std::move(operand1)), m_operand2(std::move(operand2)) {} -bool SimpleExpressionBinaryOperation::Operand1NeedsParenthesis() const -{ - const auto* operation = dynamic_cast<const SimpleExpressionBinaryOperation*>(m_operand1.get()); - return operation && operation->m_operation_type->m_precedence > m_operation_type->m_precedence; +bool SimpleExpressionBinaryOperation::Operand1NeedsParenthesis() const { + const auto *operation = dynamic_cast<const SimpleExpressionBinaryOperation *>(m_operand1.get()); + return operation && operation->m_operation_type->m_precedence > m_operation_type->m_precedence; } -bool SimpleExpressionBinaryOperation::Operand2NeedsParenthesis() const -{ - const auto* operation = dynamic_cast<const SimpleExpressionBinaryOperation*>(m_operand2.get()); - return operation && operation->m_operation_type->m_precedence > m_operation_type->m_precedence; +bool SimpleExpressionBinaryOperation::Operand2NeedsParenthesis() const { + const auto *operation = dynamic_cast<const SimpleExpressionBinaryOperation *>(m_operand2.get()); + return operation && operation->m_operation_type->m_precedence > m_operation_type->m_precedence; } -bool SimpleExpressionBinaryOperation::Equals(const ISimpleExpression* other) const -{ - const auto* otherBinaryOperation = dynamic_cast<const SimpleExpressionBinaryOperation*>(other); +bool SimpleExpressionBinaryOperation::Equals(const ISimpleExpression *other) const { + const auto *otherBinaryOperation = dynamic_cast<const SimpleExpressionBinaryOperation *>(other); - return otherBinaryOperation - && m_operation_type->m_id == otherBinaryOperation->m_operation_type->m_id - && m_operand1->Equals(otherBinaryOperation->m_operand1.get()) - && m_operand2->Equals(otherBinaryOperation->m_operand2.get()); + return otherBinaryOperation && m_operation_type->m_id == otherBinaryOperation->m_operation_type->m_id && + m_operand1->Equals(otherBinaryOperation->m_operand1.get()) && m_operand2->Equals(otherBinaryOperation->m_operand2.get()); } -bool SimpleExpressionBinaryOperation::IsStatic() const -{ - assert(m_operand1 && m_operand2); +bool SimpleExpressionBinaryOperation::IsStatic() const { + assert(m_operand1 && m_operand2); - return m_operand1->IsStatic() && m_operand2->IsStatic(); + return m_operand1->IsStatic() && m_operand2->IsStatic(); } -SimpleExpressionValue SimpleExpressionBinaryOperation::EvaluateStatic() const -{ - return m_operation_type->m_evaluation_function(m_operand1->EvaluateStatic(), m_operand2->EvaluateStatic()); +SimpleExpressionValue SimpleExpressionBinaryOperation::EvaluateStatic() const { + return m_operation_type->m_evaluation_function(m_operand1->EvaluateStatic(), m_operand2->EvaluateStatic()); } -SimpleExpressionValue SimpleExpressionBinaryOperation::EvaluateNonStatic(const ISimpleExpressionScopeValues* scopeValues) const -{ - return m_operation_type->m_evaluation_function(m_operand1->EvaluateNonStatic(scopeValues), m_operand2->EvaluateNonStatic(scopeValues)); +SimpleExpressionValue SimpleExpressionBinaryOperation::EvaluateNonStatic(const ISimpleExpressionScopeValues *scopeValues) const { + return m_operation_type->m_evaluation_function(m_operand1->EvaluateNonStatic(scopeValues), m_operand2->EvaluateNonStatic(scopeValues)); } diff --git a/src/Parser/Parsing/Simple/Expression/SimpleExpressionBinaryOperation.h b/src/Parser/Parsing/Simple/Expression/SimpleExpressionBinaryOperation.h index 210c1cb93..1405c7adf 100644 --- a/src/Parser/Parsing/Simple/Expression/SimpleExpressionBinaryOperation.h +++ b/src/Parser/Parsing/Simple/Expression/SimpleExpressionBinaryOperation.h @@ -1,100 +1,96 @@ #pragma once -#include <string> -#include <memory> #include <functional> +#include <memory> +#include <string> #include "ISimpleExpression.h" #include "SimpleExpressionValue.h" // https://en.cppreference.com/w/cpp/language/operator_precedence -enum class SimpleOperationPrecedence -{ - MULTIPLICATION_DIVISION_REMAINDER = 1, - ADDITION_SUBTRACTION = 2, - BITWISE_SHIFT = 3, - RELATIONAL_GREATER_LESS_THAN = 4, - RELATIONAL_EQUALS = 5, - BITWISE_AND = 6, - BITWISE_OR = 8, - LOGICAL_AND = 9, - LOGICAL_OR = 10 +enum class SimpleOperationPrecedence { + MULTIPLICATION_DIVISION_REMAINDER = 1, + ADDITION_SUBTRACTION = 2, + BITWISE_SHIFT = 3, + RELATIONAL_GREATER_LESS_THAN = 4, + RELATIONAL_EQUALS = 5, + BITWISE_AND = 6, + BITWISE_OR = 8, + LOGICAL_AND = 9, + LOGICAL_OR = 10 }; -enum class SimpleBinaryOperationId -{ - ADD, - SUBTRACT, - MULTIPLY, - DIVIDE, - REMAINDER, - BITWISE_AND, - BITWISE_OR, - SHIFT_LEFT, - SHIFT_RIGHT, - GREATER_THAN, - GREATER_EQUAL_THAN, - LESS_THAN, - LESS_EQUAL_THAN, - EQUALS, - NOT_EQUAL, - AND, - OR, +enum class SimpleBinaryOperationId { + ADD, + SUBTRACT, + MULTIPLY, + DIVIDE, + REMAINDER, + BITWISE_AND, + BITWISE_OR, + SHIFT_LEFT, + SHIFT_RIGHT, + GREATER_THAN, + GREATER_EQUAL_THAN, + LESS_THAN, + LESS_EQUAL_THAN, + EQUALS, + NOT_EQUAL, + AND, + OR, - COUNT + COUNT }; -class SimpleExpressionBinaryOperationType -{ +class SimpleExpressionBinaryOperationType { public: - using evaluation_function_t = std::function<SimpleExpressionValue(const SimpleExpressionValue& operand1, const SimpleExpressionValue& operand2)>; + using evaluation_function_t = std::function<SimpleExpressionValue(const SimpleExpressionValue &operand1, const SimpleExpressionValue &operand2)>; - SimpleBinaryOperationId m_id; - std::string m_syntax; - SimpleOperationPrecedence m_precedence; - evaluation_function_t m_evaluation_function; + SimpleBinaryOperationId m_id; + std::string m_syntax; + SimpleOperationPrecedence m_precedence; + evaluation_function_t m_evaluation_function; private: - SimpleExpressionBinaryOperationType(SimpleBinaryOperationId id, std::string syntax, SimpleOperationPrecedence precedence, evaluation_function_t evaluationFunction); + SimpleExpressionBinaryOperationType(SimpleBinaryOperationId id, std::string syntax, SimpleOperationPrecedence precedence, + evaluation_function_t evaluationFunction); public: - static const SimpleExpressionBinaryOperationType OPERATION_ADD; - static const SimpleExpressionBinaryOperationType OPERATION_SUBTRACT; - static const SimpleExpressionBinaryOperationType OPERATION_MULTIPLY; - static const SimpleExpressionBinaryOperationType OPERATION_DIVIDE; - static const SimpleExpressionBinaryOperationType OPERATION_REMAINDER; - static const SimpleExpressionBinaryOperationType OPERATION_BITWISE_AND; - static const SimpleExpressionBinaryOperationType OPERATION_BITWISE_OR; - static const SimpleExpressionBinaryOperationType OPERATION_SHIFT_LEFT; - static const SimpleExpressionBinaryOperationType OPERATION_SHIFT_RIGHT; - static const SimpleExpressionBinaryOperationType OPERATION_GREATER_THAN; - static const SimpleExpressionBinaryOperationType OPERATION_GREATER_EQUAL_THAN; - static const SimpleExpressionBinaryOperationType OPERATION_LESS_THAN; - static const SimpleExpressionBinaryOperationType OPERATION_LESS_EQUAL_THAN; - static const SimpleExpressionBinaryOperationType OPERATION_EQUALS; - static const SimpleExpressionBinaryOperationType OPERATION_NOT_EQUAL; - static const SimpleExpressionBinaryOperationType OPERATION_AND; - static const SimpleExpressionBinaryOperationType OPERATION_OR; + static const SimpleExpressionBinaryOperationType OPERATION_ADD; + static const SimpleExpressionBinaryOperationType OPERATION_SUBTRACT; + static const SimpleExpressionBinaryOperationType OPERATION_MULTIPLY; + static const SimpleExpressionBinaryOperationType OPERATION_DIVIDE; + static const SimpleExpressionBinaryOperationType OPERATION_REMAINDER; + static const SimpleExpressionBinaryOperationType OPERATION_BITWISE_AND; + static const SimpleExpressionBinaryOperationType OPERATION_BITWISE_OR; + static const SimpleExpressionBinaryOperationType OPERATION_SHIFT_LEFT; + static const SimpleExpressionBinaryOperationType OPERATION_SHIFT_RIGHT; + static const SimpleExpressionBinaryOperationType OPERATION_GREATER_THAN; + static const SimpleExpressionBinaryOperationType OPERATION_GREATER_EQUAL_THAN; + static const SimpleExpressionBinaryOperationType OPERATION_LESS_THAN; + static const SimpleExpressionBinaryOperationType OPERATION_LESS_EQUAL_THAN; + static const SimpleExpressionBinaryOperationType OPERATION_EQUALS; + static const SimpleExpressionBinaryOperationType OPERATION_NOT_EQUAL; + static const SimpleExpressionBinaryOperationType OPERATION_AND; + static const SimpleExpressionBinaryOperationType OPERATION_OR; - static const SimpleExpressionBinaryOperationType* const ALL_OPERATION_TYPES[static_cast<int>(SimpleBinaryOperationId::COUNT)]; + static const SimpleExpressionBinaryOperationType *const ALL_OPERATION_TYPES[static_cast<int>(SimpleBinaryOperationId::COUNT)]; }; -class SimpleExpressionBinaryOperation final : public ISimpleExpression -{ +class SimpleExpressionBinaryOperation final : public ISimpleExpression { public: - const SimpleExpressionBinaryOperationType* m_operation_type; - std::unique_ptr<ISimpleExpression> m_operand1; - std::unique_ptr<ISimpleExpression> m_operand2; + const SimpleExpressionBinaryOperationType *m_operation_type; + std::unique_ptr<ISimpleExpression> m_operand1; + std::unique_ptr<ISimpleExpression> m_operand2; - SimpleExpressionBinaryOperation(const SimpleExpressionBinaryOperationType* operationType, - std::unique_ptr<ISimpleExpression> operand1, - std::unique_ptr<ISimpleExpression> operand2); + SimpleExpressionBinaryOperation(const SimpleExpressionBinaryOperationType *operationType, std::unique_ptr<ISimpleExpression> operand1, + std::unique_ptr<ISimpleExpression> operand2); - _NODISCARD bool Operand1NeedsParenthesis() const; - _NODISCARD bool Operand2NeedsParenthesis() const; + _NODISCARD bool Operand1NeedsParenthesis() const; + _NODISCARD bool Operand2NeedsParenthesis() const; - _NODISCARD bool Equals(const ISimpleExpression* other) const override; - _NODISCARD bool IsStatic() const override; - _NODISCARD SimpleExpressionValue EvaluateStatic() const override; - _NODISCARD SimpleExpressionValue EvaluateNonStatic(const ISimpleExpressionScopeValues* scopeValues) const override; + _NODISCARD bool Equals(const ISimpleExpression *other) const override; + _NODISCARD bool IsStatic() const override; + _NODISCARD SimpleExpressionValue EvaluateStatic() const override; + _NODISCARD SimpleExpressionValue EvaluateNonStatic(const ISimpleExpressionScopeValues *scopeValues) const override; }; diff --git a/src/Parser/Parsing/Simple/Expression/SimpleExpressionConditionalOperator.cpp b/src/Parser/Parsing/Simple/Expression/SimpleExpressionConditionalOperator.cpp index b945b8b4c..654255d10 100644 --- a/src/Parser/Parsing/Simple/Expression/SimpleExpressionConditionalOperator.cpp +++ b/src/Parser/Parsing/Simple/Expression/SimpleExpressionConditionalOperator.cpp @@ -1,39 +1,25 @@ #include "SimpleExpressionConditionalOperator.h" -SimpleExpressionConditionalOperator::SimpleExpressionConditionalOperator() -= default; +SimpleExpressionConditionalOperator::SimpleExpressionConditionalOperator() = default; -SimpleExpressionConditionalOperator::SimpleExpressionConditionalOperator(std::unique_ptr<ISimpleExpression> condition, std::unique_ptr<ISimpleExpression> trueExpression, +SimpleExpressionConditionalOperator::SimpleExpressionConditionalOperator(std::unique_ptr<ISimpleExpression> condition, + std::unique_ptr<ISimpleExpression> trueExpression, std::unique_ptr<ISimpleExpression> falseExpression) - : m_condition(std::move(condition)), - m_true_value(std::move(trueExpression)), - m_false_value(std::move(falseExpression)) -{ -} + : m_condition(std::move(condition)), m_true_value(std::move(trueExpression)), m_false_value(std::move(falseExpression)) {} -bool SimpleExpressionConditionalOperator::Equals(const ISimpleExpression* other) const -{ - const auto* otherConditionalOperator = dynamic_cast<const SimpleExpressionConditionalOperator*>(other); +bool SimpleExpressionConditionalOperator::Equals(const ISimpleExpression *other) const { + const auto *otherConditionalOperator = dynamic_cast<const SimpleExpressionConditionalOperator *>(other); - return otherConditionalOperator - && m_condition->Equals(otherConditionalOperator->m_condition.get()) - && m_true_value->Equals(otherConditionalOperator->m_true_value.get()) - && m_false_value->Equals(otherConditionalOperator->m_false_value.get()); + return otherConditionalOperator && m_condition->Equals(otherConditionalOperator->m_condition.get()) && + m_true_value->Equals(otherConditionalOperator->m_true_value.get()) && m_false_value->Equals(otherConditionalOperator->m_false_value.get()); } -bool SimpleExpressionConditionalOperator::IsStatic() const -{ - return m_condition->IsStatic() && m_true_value->IsStatic() && m_false_value->IsStatic(); -} +bool SimpleExpressionConditionalOperator::IsStatic() const { return m_condition->IsStatic() && m_true_value->IsStatic() && m_false_value->IsStatic(); } -SimpleExpressionValue SimpleExpressionConditionalOperator::EvaluateStatic() const -{ - return m_condition->EvaluateStatic().IsTruthy() ? m_true_value->EvaluateStatic() : m_false_value->EvaluateStatic(); +SimpleExpressionValue SimpleExpressionConditionalOperator::EvaluateStatic() const { + return m_condition->EvaluateStatic().IsTruthy() ? m_true_value->EvaluateStatic() : m_false_value->EvaluateStatic(); } -SimpleExpressionValue SimpleExpressionConditionalOperator::EvaluateNonStatic(const ISimpleExpressionScopeValues* scopeValues) const -{ - return m_condition->EvaluateNonStatic(scopeValues).IsTruthy() - ? m_true_value->EvaluateNonStatic(scopeValues) - : m_false_value->EvaluateNonStatic(scopeValues); +SimpleExpressionValue SimpleExpressionConditionalOperator::EvaluateNonStatic(const ISimpleExpressionScopeValues *scopeValues) const { + return m_condition->EvaluateNonStatic(scopeValues).IsTruthy() ? m_true_value->EvaluateNonStatic(scopeValues) : m_false_value->EvaluateNonStatic(scopeValues); } diff --git a/src/Parser/Parsing/Simple/Expression/SimpleExpressionConditionalOperator.h b/src/Parser/Parsing/Simple/Expression/SimpleExpressionConditionalOperator.h index 3a43483e1..e5d4107bf 100644 --- a/src/Parser/Parsing/Simple/Expression/SimpleExpressionConditionalOperator.h +++ b/src/Parser/Parsing/Simple/Expression/SimpleExpressionConditionalOperator.h @@ -1,18 +1,18 @@ #pragma once #include "ISimpleExpression.h" -class SimpleExpressionConditionalOperator final : public ISimpleExpression -{ +class SimpleExpressionConditionalOperator final : public ISimpleExpression { public: - std::unique_ptr<ISimpleExpression> m_condition; - std::unique_ptr<ISimpleExpression> m_true_value; - std::unique_ptr<ISimpleExpression> m_false_value; + std::unique_ptr<ISimpleExpression> m_condition; + std::unique_ptr<ISimpleExpression> m_true_value; + std::unique_ptr<ISimpleExpression> m_false_value; - _NODISCARD bool Equals(const ISimpleExpression* other) const override; - _NODISCARD bool IsStatic() const override; - _NODISCARD SimpleExpressionValue EvaluateStatic() const override; - _NODISCARD SimpleExpressionValue EvaluateNonStatic(const ISimpleExpressionScopeValues* scopeValues) const override; + _NODISCARD bool Equals(const ISimpleExpression *other) const override; + _NODISCARD bool IsStatic() const override; + _NODISCARD SimpleExpressionValue EvaluateStatic() const override; + _NODISCARD SimpleExpressionValue EvaluateNonStatic(const ISimpleExpressionScopeValues *scopeValues) const override; - SimpleExpressionConditionalOperator(); - SimpleExpressionConditionalOperator(std::unique_ptr<ISimpleExpression> condition, std::unique_ptr<ISimpleExpression> trueExpression, std::unique_ptr<ISimpleExpression> falseExpression); + SimpleExpressionConditionalOperator(); + SimpleExpressionConditionalOperator(std::unique_ptr<ISimpleExpression> condition, std::unique_ptr<ISimpleExpression> trueExpression, + std::unique_ptr<ISimpleExpression> falseExpression); }; diff --git a/src/Parser/Parsing/Simple/Expression/SimpleExpressionMatchers.cpp b/src/Parser/Parsing/Simple/Expression/SimpleExpressionMatchers.cpp index dae82f950..832d14c66 100644 --- a/src/Parser/Parsing/Simple/Expression/SimpleExpressionMatchers.cpp +++ b/src/Parser/Parsing/Simple/Expression/SimpleExpressionMatchers.cpp @@ -3,10 +3,10 @@ #include <algorithm> #include <list> -#include "SimpleExpressionConditionalOperator.h" -#include "Parsing/Simple/Matcher/SimpleMatcherFactory.h" #include "Parsing/Simple/Expression/SimpleExpressionBinaryOperation.h" #include "Parsing/Simple/Expression/SimpleExpressionUnaryOperation.h" +#include "Parsing/Simple/Matcher/SimpleMatcherFactory.h" +#include "SimpleExpressionConditionalOperator.h" static constexpr int TAG_EXPRESSION = SimpleExpressionMatchers::TAG_OFFSET_EXPRESSION + 1; static constexpr int TAG_OPERAND = SimpleExpressionMatchers::TAG_OFFSET_EXPRESSION + 2; @@ -24,364 +24,286 @@ static constexpr int CAPTURE_OPERAND = SimpleExpressionMatchers::CAPTURE_OFFSET_ static constexpr int CAPTURE_UNARY_OPERATION_TYPE = SimpleExpressionMatchers::CAPTURE_OFFSET_EXPRESSION + 2; static constexpr int CAPTURE_BINARY_OPERATION_TYPE = SimpleExpressionMatchers::CAPTURE_OFFSET_EXPRESSION + 3; -SimpleExpressionMatchers::SimpleExpressionMatchers() - : SimpleExpressionMatchers(true, true, true, true, false) -{ -} +SimpleExpressionMatchers::SimpleExpressionMatchers() : SimpleExpressionMatchers(true, true, true, true, false) {} -SimpleExpressionMatchers::SimpleExpressionMatchers(const bool enableStringOperands, const bool enableIdentifierOperands, const bool enableFloatingPointOperands, const bool enableIntOperands, - const bool enableConditionalOperator) - : m_enable_string_operands(enableStringOperands), - m_enable_identifier_operands(enableIdentifierOperands), - m_enable_floating_point_operands(enableFloatingPointOperands), - m_enable_int_operands(enableIntOperands), - m_enable_conditional_operator(enableConditionalOperator) -{ -} +SimpleExpressionMatchers::SimpleExpressionMatchers(const bool enableStringOperands, const bool enableIdentifierOperands, const bool enableFloatingPointOperands, + const bool enableIntOperands, const bool enableConditionalOperator) + : m_enable_string_operands(enableStringOperands), m_enable_identifier_operands(enableIdentifierOperands), + m_enable_floating_point_operands(enableFloatingPointOperands), m_enable_int_operands(enableIntOperands), + m_enable_conditional_operator(enableConditionalOperator) {} -SimpleExpressionMatchers::~SimpleExpressionMatchers() -= default; +SimpleExpressionMatchers::~SimpleExpressionMatchers() = default; -void SimpleExpressionMatchers::ApplyTokensToLexerConfig(SimpleLexer::Config& lexerConfig) -{ - for (const auto* unaryOperation : SimpleExpressionUnaryOperationType::ALL_OPERATION_TYPES) - { - if (unaryOperation->m_syntax.size() <= 1) - continue; +void SimpleExpressionMatchers::ApplyTokensToLexerConfig(SimpleLexer::Config &lexerConfig) { + for (const auto *unaryOperation : SimpleExpressionUnaryOperationType::ALL_OPERATION_TYPES) { + if (unaryOperation->m_syntax.size() <= 1) + continue; - lexerConfig.m_multi_character_tokens.emplace_back(MULTI_TOKEN_OFFSET_UNARY + static_cast<int>(unaryOperation->m_id), unaryOperation->m_syntax); - } + lexerConfig.m_multi_character_tokens.emplace_back(MULTI_TOKEN_OFFSET_UNARY + static_cast<int>(unaryOperation->m_id), unaryOperation->m_syntax); + } - for (const auto* binaryOperation : SimpleExpressionBinaryOperationType::ALL_OPERATION_TYPES) - { - if (binaryOperation->m_syntax.size() <= 1) - continue; + for (const auto *binaryOperation : SimpleExpressionBinaryOperationType::ALL_OPERATION_TYPES) { + if (binaryOperation->m_syntax.size() <= 1) + continue; - lexerConfig.m_multi_character_tokens.emplace_back(MULTI_TOKEN_OFFSET_BINARY + static_cast<int>(binaryOperation->m_id), binaryOperation->m_syntax); - } + lexerConfig.m_multi_character_tokens.emplace_back(MULTI_TOKEN_OFFSET_BINARY + static_cast<int>(binaryOperation->m_id), binaryOperation->m_syntax); + } } -std::vector<const SimpleExpressionUnaryOperationType*> SimpleExpressionMatchers::EnabledUnaryOperations() const -{ - return std::vector(&SimpleExpressionUnaryOperationType::ALL_OPERATION_TYPES[0], - &SimpleExpressionUnaryOperationType::ALL_OPERATION_TYPES[std::extent_v<decltype(SimpleExpressionUnaryOperationType::ALL_OPERATION_TYPES)>]); +std::vector<const SimpleExpressionUnaryOperationType *> SimpleExpressionMatchers::EnabledUnaryOperations() const { + return std::vector( + &SimpleExpressionUnaryOperationType::ALL_OPERATION_TYPES[0], + &SimpleExpressionUnaryOperationType::ALL_OPERATION_TYPES[std::extent_v<decltype(SimpleExpressionUnaryOperationType::ALL_OPERATION_TYPES)>]); } -std::vector<const SimpleExpressionBinaryOperationType*> SimpleExpressionMatchers::EnabledBinaryOperations() const -{ - return std::vector(&SimpleExpressionBinaryOperationType::ALL_OPERATION_TYPES[0], - &SimpleExpressionBinaryOperationType::ALL_OPERATION_TYPES[std::extent_v<decltype(SimpleExpressionBinaryOperationType::ALL_OPERATION_TYPES)>]); +std::vector<const SimpleExpressionBinaryOperationType *> SimpleExpressionMatchers::EnabledBinaryOperations() const { + return std::vector( + &SimpleExpressionBinaryOperationType::ALL_OPERATION_TYPES[0], + &SimpleExpressionBinaryOperationType::ALL_OPERATION_TYPES[std::extent_v<decltype(SimpleExpressionBinaryOperationType::ALL_OPERATION_TYPES)>]); } -std::unique_ptr<ISimpleExpression> SimpleExpressionMatchers::ProcessExpressionInParenthesis(SequenceResult<SimpleParserValue>& result) const -{ - auto processedEvaluation = ProcessExpression(result); +std::unique_ptr<ISimpleExpression> SimpleExpressionMatchers::ProcessExpressionInParenthesis(SequenceResult<SimpleParserValue> &result) const { + auto processedEvaluation = ProcessExpression(result); - if (result.PeekAndRemoveIfTag(TAG_PARENTHESIS_END) != TAG_PARENTHESIS_END) - throw ParsingException(TokenPos(), "Expected parenthesis end tag @ ExpressionInParenthesis"); + if (result.PeekAndRemoveIfTag(TAG_PARENTHESIS_END) != TAG_PARENTHESIS_END) + throw ParsingException(TokenPos(), "Expected parenthesis end tag @ ExpressionInParenthesis"); - return processedEvaluation; + return processedEvaluation; } -std::unique_ptr<ISimpleExpression> SimpleExpressionMatchers::ProcessConditionalOperation(std::unique_ptr<ISimpleExpression> condition, SequenceResult<SimpleParserValue>& result) const -{ - auto trueExpression = ProcessExpression(result); +std::unique_ptr<ISimpleExpression> SimpleExpressionMatchers::ProcessConditionalOperation(std::unique_ptr<ISimpleExpression> condition, + SequenceResult<SimpleParserValue> &result) const { + auto trueExpression = ProcessExpression(result); - if (result.PeekAndRemoveIfTag(TAG_CONDITIONAL_OPERATOR_SEPARATOR) != TAG_CONDITIONAL_OPERATOR_SEPARATOR) - throw ParsingException(TokenPos(), "Expected conditional separator tag @ ProcessConditionalOperation"); + if (result.PeekAndRemoveIfTag(TAG_CONDITIONAL_OPERATOR_SEPARATOR) != TAG_CONDITIONAL_OPERATOR_SEPARATOR) + throw ParsingException(TokenPos(), "Expected conditional separator tag @ ProcessConditionalOperation"); - auto falseExpression = ProcessExpression(result); + auto falseExpression = ProcessExpression(result); - if (result.PeekAndRemoveIfTag(TAG_CONDITIONAL_OPERATOR_END) != TAG_CONDITIONAL_OPERATOR_END) - throw ParsingException(TokenPos(), "Expected conditional end tag @ ProcessConditionalOperation"); + if (result.PeekAndRemoveIfTag(TAG_CONDITIONAL_OPERATOR_END) != TAG_CONDITIONAL_OPERATOR_END) + throw ParsingException(TokenPos(), "Expected conditional end tag @ ProcessConditionalOperation"); - return std::make_unique<SimpleExpressionConditionalOperator>(std::move(condition), std::move(trueExpression), std::move(falseExpression)); + return std::make_unique<SimpleExpressionConditionalOperator>(std::move(condition), std::move(trueExpression), std::move(falseExpression)); } -std::unique_ptr<ISimpleExpression> SimpleExpressionMatchers::ProcessOperand(SequenceResult<SimpleParserValue>& result) const -{ - const auto& operandToken = result.NextCapture(CAPTURE_OPERAND); - - switch (operandToken.m_type) - { - case SimpleParserValueType::INTEGER: - return std::make_unique<SimpleExpressionValue>(operandToken.IntegerValue()); - case SimpleParserValueType::FLOATING_POINT: - return std::make_unique<SimpleExpressionValue>(operandToken.FloatingPointValue()); - case SimpleParserValueType::STRING: - return std::make_unique<SimpleExpressionValue>(operandToken.StringValue()); - case SimpleParserValueType::IDENTIFIER: - return std::make_unique<SimpleExpressionValue>(operandToken.IdentifierValue()); - default: - throw ParsingException(TokenPos(), "Unknown operand type @ Operand"); - } +std::unique_ptr<ISimpleExpression> SimpleExpressionMatchers::ProcessOperand(SequenceResult<SimpleParserValue> &result) const { + const auto &operandToken = result.NextCapture(CAPTURE_OPERAND); + + switch (operandToken.m_type) { + case SimpleParserValueType::INTEGER: + return std::make_unique<SimpleExpressionValue>(operandToken.IntegerValue()); + case SimpleParserValueType::FLOATING_POINT: + return std::make_unique<SimpleExpressionValue>(operandToken.FloatingPointValue()); + case SimpleParserValueType::STRING: + return std::make_unique<SimpleExpressionValue>(operandToken.StringValue()); + case SimpleParserValueType::IDENTIFIER: + return std::make_unique<SimpleExpressionValue>(operandToken.IdentifierValue()); + default: + throw ParsingException(TokenPos(), "Unknown operand type @ Operand"); + } } -std::unique_ptr<ISimpleExpression> SimpleExpressionMatchers::ProcessOperandExtension(SequenceResult<SimpleParserValue>& result) const -{ +std::unique_ptr<ISimpleExpression> SimpleExpressionMatchers::ProcessOperandExtension(SequenceResult<SimpleParserValue> &result) const { return nullptr; } + +std::unique_ptr<ISimpleExpression> SimpleExpressionMatchers::ProcessExpression(SequenceResult<SimpleParserValue> &result) const { + if (result.PeekAndRemoveIfTag(TAG_EXPRESSION) != TAG_EXPRESSION) return nullptr; -} -std::unique_ptr<ISimpleExpression> SimpleExpressionMatchers::ProcessExpression(SequenceResult<SimpleParserValue>& result) const -{ - if (result.PeekAndRemoveIfTag(TAG_EXPRESSION) != TAG_EXPRESSION) - return nullptr; - - std::vector<std::unique_ptr<ISimpleExpression>> operands; - std::list<std::pair<unsigned, const SimpleExpressionBinaryOperationType*>> operators; - - while (true) - { - std::unique_ptr<ISimpleExpression> firstStatementPart; - std::vector<int> unaryOperations; - auto nextTag = result.NextTag(); - - while (nextTag == TAG_UNARY_OPERATION) - { - unaryOperations.push_back(result.NextCapture(CAPTURE_UNARY_OPERATION_TYPE).IntegerValue()); - nextTag = result.NextTag(); - } - - switch (nextTag) - { - case TAG_PARENTHESIS: - firstStatementPart = ProcessExpressionInParenthesis(result); - break; - - case TAG_OPERAND: - firstStatementPart = ProcessOperand(result); - break; - - case TAG_OPERAND_EXT: - firstStatementPart = ProcessOperandExtension(result); - if (result.PeekAndRemoveIfTag(TAG_OPERAND_EXT_END) != TAG_OPERAND_EXT_END) - throw ParsingException(TokenPos(), "Unclosed operand extension @ Expression"); - break; - - default: - throw ParsingException(TokenPos(), "Invalid followup tag @ Expression"); - } - - for (auto i = unaryOperations.size(); i > 0; i--) - { - const auto operationIndex = unaryOperations[i - 1]; - if (operationIndex < 0 || operationIndex >= static_cast<int>(SimpleUnaryOperationId::COUNT)) - throw ParsingException(TokenPos(), "Invalid unary operation id @ Expression"); - firstStatementPart = std::make_unique<SimpleExpressionUnaryOperation>(SimpleExpressionUnaryOperationType::ALL_OPERATION_TYPES[operationIndex], - std::move(firstStatementPart)); - } - - if (result.PeekAndRemoveIfTag(TAG_CONDITIONAL_OPERATOR) == TAG_CONDITIONAL_OPERATOR) - { - operands.emplace_back(ProcessConditionalOperation(std::move(firstStatementPart), result)); - break; - } - - operands.emplace_back(std::move(firstStatementPart)); - - if (result.PeekAndRemoveIfTag(TAG_BINARY_OPERATION) == TAG_BINARY_OPERATION) - { - const auto operationIndex = result.NextCapture(CAPTURE_BINARY_OPERATION_TYPE).IntegerValue(); - if (operationIndex < 0 || operationIndex >= static_cast<int>(SimpleBinaryOperationId::COUNT)) - throw ParsingException(TokenPos(), "Invalid binary operation id @ Expression"); - - operators.emplace_back(operators.size(), SimpleExpressionBinaryOperationType::ALL_OPERATION_TYPES[operationIndex]); - } - else - break; - - if (result.PeekAndRemoveIfTag(TAG_EXPRESSION) != TAG_EXPRESSION) - throw ParsingException(TokenPos(), "Expected EvaluationTag @ Evaluation"); + std::vector<std::unique_ptr<ISimpleExpression>> operands; + std::list<std::pair<unsigned, const SimpleExpressionBinaryOperationType *>> operators; + + while (true) { + std::unique_ptr<ISimpleExpression> firstStatementPart; + std::vector<int> unaryOperations; + auto nextTag = result.NextTag(); + + while (nextTag == TAG_UNARY_OPERATION) { + unaryOperations.push_back(result.NextCapture(CAPTURE_UNARY_OPERATION_TYPE).IntegerValue()); + nextTag = result.NextTag(); } - operators.sort([](const std::pair<unsigned, const SimpleExpressionBinaryOperationType*>& p1, const std::pair<unsigned, const SimpleExpressionBinaryOperationType*>& p2) - { - if (p1.second->m_precedence != p2.second->m_precedence) - return p1.second->m_precedence > p2.second->m_precedence; + switch (nextTag) { + case TAG_PARENTHESIS: + firstStatementPart = ProcessExpressionInParenthesis(result); + break; - return p1.first > p2.first; - }); + case TAG_OPERAND: + firstStatementPart = ProcessOperand(result); + break; - while (!operators.empty()) - { - const auto [operatorIndex, operatorType] = operators.back(); // This must not be a reference + case TAG_OPERAND_EXT: + firstStatementPart = ProcessOperandExtension(result); + if (result.PeekAndRemoveIfTag(TAG_OPERAND_EXT_END) != TAG_OPERAND_EXT_END) + throw ParsingException(TokenPos(), "Unclosed operand extension @ Expression"); + break; - auto operation = std::make_unique<SimpleExpressionBinaryOperation>(operatorType, std::move(operands[operatorIndex]), std::move(operands[operatorIndex + 1])); - operands.erase(operands.begin() + static_cast<int>(operatorIndex)); - operands[operatorIndex] = std::move(operation); + default: + throw ParsingException(TokenPos(), "Invalid followup tag @ Expression"); + } - operators.pop_back(); + for (auto i = unaryOperations.size(); i > 0; i--) { + const auto operationIndex = unaryOperations[i - 1]; + if (operationIndex < 0 || operationIndex >= static_cast<int>(SimpleUnaryOperationId::COUNT)) + throw ParsingException(TokenPos(), "Invalid unary operation id @ Expression"); + firstStatementPart = std::make_unique<SimpleExpressionUnaryOperation>(SimpleExpressionUnaryOperationType::ALL_OPERATION_TYPES[operationIndex], + std::move(firstStatementPart)); + } - for (auto& [opIndex, _] : operators) - { - if (opIndex > operatorIndex) - opIndex--; - } + if (result.PeekAndRemoveIfTag(TAG_CONDITIONAL_OPERATOR) == TAG_CONDITIONAL_OPERATOR) { + operands.emplace_back(ProcessConditionalOperation(std::move(firstStatementPart), result)); + break; } - return std::move(operands.front()); -} + operands.emplace_back(std::move(firstStatementPart)); -std::unique_ptr<SimpleExpressionMatchers::matcher_t> SimpleExpressionMatchers::ParseOperand(const supplier_t* labelSupplier) const -{ - const SimpleMatcherFactory create(labelSupplier); + if (result.PeekAndRemoveIfTag(TAG_BINARY_OPERATION) == TAG_BINARY_OPERATION) { + const auto operationIndex = result.NextCapture(CAPTURE_BINARY_OPERATION_TYPE).IntegerValue(); + if (operationIndex < 0 || operationIndex >= static_cast<int>(SimpleBinaryOperationId::COUNT)) + throw ParsingException(TokenPos(), "Invalid binary operation id @ Expression"); - std::vector<std::unique_ptr<matcher_t>> operandMatchers; - operandMatchers.reserve(4); + operators.emplace_back(operators.size(), SimpleExpressionBinaryOperationType::ALL_OPERATION_TYPES[operationIndex]); + } else + break; - if (m_enable_string_operands) - operandMatchers.emplace_back(create.String()); + if (result.PeekAndRemoveIfTag(TAG_EXPRESSION) != TAG_EXPRESSION) + throw ParsingException(TokenPos(), "Expected EvaluationTag @ Evaluation"); + } - if (m_enable_identifier_operands) - operandMatchers.emplace_back(create.Identifier()); + operators.sort([](const std::pair<unsigned, const SimpleExpressionBinaryOperationType *> &p1, + const std::pair<unsigned, const SimpleExpressionBinaryOperationType *> &p2) { + if (p1.second->m_precedence != p2.second->m_precedence) + return p1.second->m_precedence > p2.second->m_precedence; - if (m_enable_floating_point_operands) - operandMatchers.emplace_back(create.FloatingPoint()); + return p1.first > p2.first; + }); - if (m_enable_int_operands) - operandMatchers.emplace_back(create.Integer()); + while (!operators.empty()) { + const auto [operatorIndex, operatorType] = operators.back(); // This must not be a reference - return create.Or(std::move(operandMatchers)).Tag(TAG_OPERAND).Capture(CAPTURE_OPERAND); -} + auto operation = + std::make_unique<SimpleExpressionBinaryOperation>(operatorType, std::move(operands[operatorIndex]), std::move(operands[operatorIndex + 1])); + operands.erase(operands.begin() + static_cast<int>(operatorIndex)); + operands[operatorIndex] = std::move(operation); -std::unique_ptr<SimpleExpressionMatchers::matcher_t> SimpleExpressionMatchers::ParseBinaryOperationType(const supplier_t* labelSupplier) const -{ - const SimpleMatcherFactory create(labelSupplier); - - const auto enabledBinaryOperations = EnabledBinaryOperations(); - std::vector<std::unique_ptr<matcher_t>> binaryOperationsMatchers; - binaryOperationsMatchers.reserve(enabledBinaryOperations.size()); - - for (const auto* enabledBinaryOperation : enabledBinaryOperations) - { - if (enabledBinaryOperation->m_syntax.size() > 1) - { - binaryOperationsMatchers.emplace_back( - create.MultiChar(MULTI_TOKEN_OFFSET_BINARY + static_cast<int>(enabledBinaryOperation->m_id)) - .Transform([enabledBinaryOperation](const SimpleMatcherFactory::token_list_t& values) - { - return SimpleParserValue::Integer(values[0].get().GetPos(), static_cast<int>(enabledBinaryOperation->m_id)); - })); - } - else if (!enabledBinaryOperation->m_syntax.empty()) - { - binaryOperationsMatchers.emplace_back( - create.Char(enabledBinaryOperation->m_syntax[0]) - .Transform([enabledBinaryOperation](const SimpleMatcherFactory::token_list_t& values) - { - return SimpleParserValue::Integer(values[0].get().GetPos(), static_cast<int>(enabledBinaryOperation->m_id)); - })); - } - } + operators.pop_back(); - const auto hasAddOperation = std::any_of(enabledBinaryOperations.begin(), enabledBinaryOperations.end(), [](const SimpleExpressionBinaryOperationType* type) - { - return type == &SimpleExpressionBinaryOperationType::OPERATION_ADD; - }); - const auto hasSubtractOperation = std::any_of(enabledBinaryOperations.begin(), enabledBinaryOperations.end(), [](const SimpleExpressionBinaryOperationType* type) - { - return type == &SimpleExpressionBinaryOperationType::OPERATION_SUBTRACT; - }); - - if (hasAddOperation && hasSubtractOperation) - { - binaryOperationsMatchers.emplace_back( - create.Or({ - create.IntegerWithSign(), - create.FloatingPointWithSign() - }) - .NoConsume() - .Transform([](const SimpleMatcherFactory::token_list_t& values) - { - return SimpleParserValue::Integer(values[0].get().GetPos(), static_cast<int>(SimpleBinaryOperationId::ADD)); - })); + for (auto &[opIndex, _] : operators) { + if (opIndex > operatorIndex) + opIndex--; } + } + + return std::move(operands.front()); +} + +std::unique_ptr<SimpleExpressionMatchers::matcher_t> SimpleExpressionMatchers::ParseOperand(const supplier_t *labelSupplier) const { + const SimpleMatcherFactory create(labelSupplier); + + std::vector<std::unique_ptr<matcher_t>> operandMatchers; + operandMatchers.reserve(4); + if (m_enable_string_operands) + operandMatchers.emplace_back(create.String()); - return create.Or(std::move(binaryOperationsMatchers)).Capture(CAPTURE_BINARY_OPERATION_TYPE); + if (m_enable_identifier_operands) + operandMatchers.emplace_back(create.Identifier()); + + if (m_enable_floating_point_operands) + operandMatchers.emplace_back(create.FloatingPoint()); + + if (m_enable_int_operands) + operandMatchers.emplace_back(create.Integer()); + + return create.Or(std::move(operandMatchers)).Tag(TAG_OPERAND).Capture(CAPTURE_OPERAND); +} + +std::unique_ptr<SimpleExpressionMatchers::matcher_t> SimpleExpressionMatchers::ParseBinaryOperationType(const supplier_t *labelSupplier) const { + const SimpleMatcherFactory create(labelSupplier); + + const auto enabledBinaryOperations = EnabledBinaryOperations(); + std::vector<std::unique_ptr<matcher_t>> binaryOperationsMatchers; + binaryOperationsMatchers.reserve(enabledBinaryOperations.size()); + + for (const auto *enabledBinaryOperation : enabledBinaryOperations) { + if (enabledBinaryOperation->m_syntax.size() > 1) { + binaryOperationsMatchers.emplace_back(create.MultiChar(MULTI_TOKEN_OFFSET_BINARY + static_cast<int>(enabledBinaryOperation->m_id)) + .Transform([enabledBinaryOperation](const SimpleMatcherFactory::token_list_t &values) { + return SimpleParserValue::Integer(values[0].get().GetPos(), static_cast<int>(enabledBinaryOperation->m_id)); + })); + } else if (!enabledBinaryOperation->m_syntax.empty()) { + binaryOperationsMatchers.emplace_back( + create.Char(enabledBinaryOperation->m_syntax[0]).Transform([enabledBinaryOperation](const SimpleMatcherFactory::token_list_t &values) { + return SimpleParserValue::Integer(values[0].get().GetPos(), static_cast<int>(enabledBinaryOperation->m_id)); + })); + } + } + + const auto hasAddOperation = std::any_of(enabledBinaryOperations.begin(), enabledBinaryOperations.end(), [](const SimpleExpressionBinaryOperationType *type) { + return type == &SimpleExpressionBinaryOperationType::OPERATION_ADD; + }); + const auto hasSubtractOperation = + std::any_of(enabledBinaryOperations.begin(), enabledBinaryOperations.end(), + [](const SimpleExpressionBinaryOperationType *type) { return type == &SimpleExpressionBinaryOperationType::OPERATION_SUBTRACT; }); + + if (hasAddOperation && hasSubtractOperation) { + binaryOperationsMatchers.emplace_back( + create.Or({create.IntegerWithSign(), create.FloatingPointWithSign()}).NoConsume().Transform([](const SimpleMatcherFactory::token_list_t &values) { + return SimpleParserValue::Integer(values[0].get().GetPos(), static_cast<int>(SimpleBinaryOperationId::ADD)); + })); + } + + return create.Or(std::move(binaryOperationsMatchers)).Capture(CAPTURE_BINARY_OPERATION_TYPE); } -std::unique_ptr<SimpleExpressionMatchers::matcher_t> SimpleExpressionMatchers::ParseOperandExtension(const supplier_t* labelSupplier) const -{ - const SimpleMatcherFactory create(labelSupplier); +std::unique_ptr<SimpleExpressionMatchers::matcher_t> SimpleExpressionMatchers::ParseOperandExtension(const supplier_t *labelSupplier) const { + const SimpleMatcherFactory create(labelSupplier); - return create.False(); + return create.False(); } -std::unique_ptr<SimpleExpressionMatchers::matcher_t> SimpleExpressionMatchers::ParseUnaryOperationType(const supplier_t* labelSupplier) const -{ - const SimpleMatcherFactory create(labelSupplier); - - const auto enabledUnaryOperations = EnabledUnaryOperations(); - std::vector<std::unique_ptr<matcher_t>> unaryOperationsMatchers; - unaryOperationsMatchers.reserve(enabledUnaryOperations.size()); - - for (const auto* enabledUnaryOperation : enabledUnaryOperations) - { - if (enabledUnaryOperation->m_syntax.size() > 1) - { - unaryOperationsMatchers.emplace_back( - create.MultiChar(MULTI_TOKEN_OFFSET_UNARY + static_cast<int>(enabledUnaryOperation->m_id)) - .Transform([enabledUnaryOperation](const SimpleMatcherFactory::token_list_t& values) - { - return SimpleParserValue::Integer(values[0].get().GetPos(), static_cast<int>(enabledUnaryOperation->m_id)); - })); - } - else if (!enabledUnaryOperation->m_syntax.empty()) - { - unaryOperationsMatchers.emplace_back( - create.Char(enabledUnaryOperation->m_syntax[0]) - .Transform([enabledUnaryOperation](const SimpleMatcherFactory::token_list_t& values) - { - return SimpleParserValue::Integer(values[0].get().GetPos(), static_cast<int>(enabledUnaryOperation->m_id)); - })); - } +std::unique_ptr<SimpleExpressionMatchers::matcher_t> SimpleExpressionMatchers::ParseUnaryOperationType(const supplier_t *labelSupplier) const { + const SimpleMatcherFactory create(labelSupplier); + + const auto enabledUnaryOperations = EnabledUnaryOperations(); + std::vector<std::unique_ptr<matcher_t>> unaryOperationsMatchers; + unaryOperationsMatchers.reserve(enabledUnaryOperations.size()); + + for (const auto *enabledUnaryOperation : enabledUnaryOperations) { + if (enabledUnaryOperation->m_syntax.size() > 1) { + unaryOperationsMatchers.emplace_back(create.MultiChar(MULTI_TOKEN_OFFSET_UNARY + static_cast<int>(enabledUnaryOperation->m_id)) + .Transform([enabledUnaryOperation](const SimpleMatcherFactory::token_list_t &values) { + return SimpleParserValue::Integer(values[0].get().GetPos(), static_cast<int>(enabledUnaryOperation->m_id)); + })); + } else if (!enabledUnaryOperation->m_syntax.empty()) { + unaryOperationsMatchers.emplace_back( + create.Char(enabledUnaryOperation->m_syntax[0]).Transform([enabledUnaryOperation](const SimpleMatcherFactory::token_list_t &values) { + return SimpleParserValue::Integer(values[0].get().GetPos(), static_cast<int>(enabledUnaryOperation->m_id)); + })); } + } - return create.Or(std::move(unaryOperationsMatchers)).Tag(TAG_UNARY_OPERATION).Capture(CAPTURE_UNARY_OPERATION_TYPE); + return create.Or(std::move(unaryOperationsMatchers)).Tag(TAG_UNARY_OPERATION).Capture(CAPTURE_UNARY_OPERATION_TYPE); } -std::unique_ptr<SimpleExpressionMatchers::matcher_t> SimpleExpressionMatchers::ParseConditionalOperator(const supplier_t* labelSupplier) const -{ - const SimpleMatcherFactory create(labelSupplier); +std::unique_ptr<SimpleExpressionMatchers::matcher_t> SimpleExpressionMatchers::ParseConditionalOperator(const supplier_t *labelSupplier) const { + const SimpleMatcherFactory create(labelSupplier); - if (!m_enable_conditional_operator) - return create.False(); + if (!m_enable_conditional_operator) + return create.False(); - return create.And({ - create.Char('?').Tag(TAG_CONDITIONAL_OPERATOR), - create.Label(LABEL_EXPRESSION), - create.Char(':').Tag(TAG_CONDITIONAL_OPERATOR_SEPARATOR), - create.Label(LABEL_EXPRESSION), - create.True().Tag(TAG_CONDITIONAL_OPERATOR_END) - }); + return create.And({create.Char('?').Tag(TAG_CONDITIONAL_OPERATOR), create.Label(LABEL_EXPRESSION), create.Char(':').Tag(TAG_CONDITIONAL_OPERATOR_SEPARATOR), + create.Label(LABEL_EXPRESSION), create.True().Tag(TAG_CONDITIONAL_OPERATOR_END)}); } -std::unique_ptr<SimpleExpressionMatchers::matcher_t> SimpleExpressionMatchers::Expression(const supplier_t* labelSupplier) const -{ - const SimpleMatcherFactory create(labelSupplier); - - return create.And({ - create.OptionalLoop(ParseUnaryOperationType(labelSupplier)), - create.Or({ - create.And({ - create.Char('('), - create.Label(LABEL_EXPRESSION), - create.Char(')').Tag(TAG_PARENTHESIS_END) - }).Tag(TAG_PARENTHESIS), - create.And({ - create.True().Tag(TAG_OPERAND_EXT), - ParseOperandExtension(labelSupplier), - create.True().Tag(TAG_OPERAND_EXT_END) - }), - ParseOperand(labelSupplier) - }), - create.Optional(create.Or({ - ParseConditionalOperator(labelSupplier), - create.And({ - ParseBinaryOperationType(labelSupplier), - create.Label(LABEL_EXPRESSION) - }).Tag(TAG_BINARY_OPERATION) - })) - }).Tag(TAG_EXPRESSION); +std::unique_ptr<SimpleExpressionMatchers::matcher_t> SimpleExpressionMatchers::Expression(const supplier_t *labelSupplier) const { + const SimpleMatcherFactory create(labelSupplier); + + return create + .And({create.OptionalLoop(ParseUnaryOperationType(labelSupplier)), + create.Or({create.And({create.Char('('), create.Label(LABEL_EXPRESSION), create.Char(')').Tag(TAG_PARENTHESIS_END)}).Tag(TAG_PARENTHESIS), + create.And({create.True().Tag(TAG_OPERAND_EXT), ParseOperandExtension(labelSupplier), create.True().Tag(TAG_OPERAND_EXT_END)}), + ParseOperand(labelSupplier)}), + create.Optional(create.Or({ParseConditionalOperator(labelSupplier), + create.And({ParseBinaryOperationType(labelSupplier), create.Label(LABEL_EXPRESSION)}).Tag(TAG_BINARY_OPERATION)}))}) + .Tag(TAG_EXPRESSION); } diff --git a/src/Parser/Parsing/Simple/Expression/SimpleExpressionMatchers.h b/src/Parser/Parsing/Simple/Expression/SimpleExpressionMatchers.h index edb98876c..e783fd06f 100644 --- a/src/Parser/Parsing/Simple/Expression/SimpleExpressionMatchers.h +++ b/src/Parser/Parsing/Simple/Expression/SimpleExpressionMatchers.h @@ -2,66 +2,66 @@ #include <memory> -#include "SimpleExpressionBinaryOperation.h" -#include "SimpleExpressionUnaryOperation.h" -#include "Utils/ClassUtils.h" #include "Parsing/Matcher/AbstractMatcher.h" #include "Parsing/Matcher/MatcherLabel.h" -#include "Parsing/Simple/Expression/ISimpleExpression.h" #include "Parsing/Sequence/SequenceResult.h" +#include "Parsing/Simple/Expression/ISimpleExpression.h" #include "Parsing/Simple/SimpleParserValue.h" +#include "SimpleExpressionBinaryOperation.h" +#include "SimpleExpressionUnaryOperation.h" +#include "Utils/ClassUtils.h" #include <Parsing/Simple/SimpleLexer.h> -class SimpleExpressionMatchers -{ +class SimpleExpressionMatchers { public: - using matcher_t = AbstractMatcher<SimpleParserValue>; - typedef IMatcherForLabelSupplier<SimpleParserValue> supplier_t; + using matcher_t = AbstractMatcher<SimpleParserValue>; + typedef IMatcherForLabelSupplier<SimpleParserValue> supplier_t; - static constexpr auto CAPTURE_OFFSET_EXPRESSION = 7000; - static constexpr auto TAG_OFFSET_EXPRESSION = 7000; - static constexpr auto CAPTURE_OFFSET_EXPRESSION_EXT = 8000; - static constexpr auto TAG_OFFSET_EXPRESSION_EXT = 8000; - static constexpr auto LABEL_EXPRESSION = 7000; - static constexpr auto MULTI_TOKEN_OFFSET_UNARY = 700; - static constexpr auto MULTI_TOKEN_OFFSET_BINARY = 720; + static constexpr auto CAPTURE_OFFSET_EXPRESSION = 7000; + static constexpr auto TAG_OFFSET_EXPRESSION = 7000; + static constexpr auto CAPTURE_OFFSET_EXPRESSION_EXT = 8000; + static constexpr auto TAG_OFFSET_EXPRESSION_EXT = 8000; + static constexpr auto LABEL_EXPRESSION = 7000; + static constexpr auto MULTI_TOKEN_OFFSET_UNARY = 700; + static constexpr auto MULTI_TOKEN_OFFSET_BINARY = 720; private: - bool m_enable_string_operands; - bool m_enable_identifier_operands; - bool m_enable_floating_point_operands; - bool m_enable_int_operands; - bool m_enable_conditional_operator; + bool m_enable_string_operands; + bool m_enable_identifier_operands; + bool m_enable_floating_point_operands; + bool m_enable_int_operands; + bool m_enable_conditional_operator; public: - SimpleExpressionMatchers(); - SimpleExpressionMatchers(bool enableStringOperands, bool enableIdentifierOperands, bool enableFloatingPointOperands, bool enableIntOperands, bool enableConditionalOperator); - virtual ~SimpleExpressionMatchers(); - SimpleExpressionMatchers(const SimpleExpressionMatchers& other) = default; - SimpleExpressionMatchers(SimpleExpressionMatchers&& other) noexcept = default; - SimpleExpressionMatchers& operator=(const SimpleExpressionMatchers& other) = default; - SimpleExpressionMatchers& operator=(SimpleExpressionMatchers&& other) noexcept = default; + SimpleExpressionMatchers(); + SimpleExpressionMatchers(bool enableStringOperands, bool enableIdentifierOperands, bool enableFloatingPointOperands, bool enableIntOperands, + bool enableConditionalOperator); + virtual ~SimpleExpressionMatchers(); + SimpleExpressionMatchers(const SimpleExpressionMatchers &other) = default; + SimpleExpressionMatchers(SimpleExpressionMatchers &&other) noexcept = default; + SimpleExpressionMatchers &operator=(const SimpleExpressionMatchers &other) = default; + SimpleExpressionMatchers &operator=(SimpleExpressionMatchers &&other) noexcept = default; protected: - virtual std::unique_ptr<matcher_t> ParseOperandExtension(const supplier_t* labelSupplier) const; - virtual std::unique_ptr<ISimpleExpression> ProcessOperandExtension(SequenceResult<SimpleParserValue>& result) const; + virtual std::unique_ptr<matcher_t> ParseOperandExtension(const supplier_t *labelSupplier) const; + virtual std::unique_ptr<ISimpleExpression> ProcessOperandExtension(SequenceResult<SimpleParserValue> &result) const; - _NODISCARD virtual std::vector<const SimpleExpressionUnaryOperationType*> EnabledUnaryOperations() const; - _NODISCARD virtual std::vector<const SimpleExpressionBinaryOperationType*> EnabledBinaryOperations() const; + _NODISCARD virtual std::vector<const SimpleExpressionUnaryOperationType *> EnabledUnaryOperations() const; + _NODISCARD virtual std::vector<const SimpleExpressionBinaryOperationType *> EnabledBinaryOperations() const; private: - std::unique_ptr<matcher_t> ParseBinaryOperationType(const supplier_t* labelSupplier) const; - std::unique_ptr<matcher_t> ParseOperand(const supplier_t* labelSupplier) const; - std::unique_ptr<matcher_t> ParseUnaryOperationType(const supplier_t* labelSupplier) const; - std::unique_ptr<matcher_t> ParseConditionalOperator(const supplier_t* labelSupplier) const; + std::unique_ptr<matcher_t> ParseBinaryOperationType(const supplier_t *labelSupplier) const; + std::unique_ptr<matcher_t> ParseOperand(const supplier_t *labelSupplier) const; + std::unique_ptr<matcher_t> ParseUnaryOperationType(const supplier_t *labelSupplier) const; + std::unique_ptr<matcher_t> ParseConditionalOperator(const supplier_t *labelSupplier) const; - std::unique_ptr<ISimpleExpression> ProcessExpressionInParenthesis(SequenceResult<SimpleParserValue>& result) const; - std::unique_ptr<ISimpleExpression> ProcessConditionalOperation(std::unique_ptr<ISimpleExpression> condition, SequenceResult<SimpleParserValue>& result) const; - std::unique_ptr<ISimpleExpression> ProcessOperand(SequenceResult<SimpleParserValue>& result) const; + std::unique_ptr<ISimpleExpression> ProcessExpressionInParenthesis(SequenceResult<SimpleParserValue> &result) const; + std::unique_ptr<ISimpleExpression> ProcessConditionalOperation(std::unique_ptr<ISimpleExpression> condition, SequenceResult<SimpleParserValue> &result) const; + std::unique_ptr<ISimpleExpression> ProcessOperand(SequenceResult<SimpleParserValue> &result) const; public: - std::unique_ptr<matcher_t> Expression(const supplier_t* labelSupplier) const; - std::unique_ptr<ISimpleExpression> ProcessExpression(SequenceResult<SimpleParserValue>& result) const; + std::unique_ptr<matcher_t> Expression(const supplier_t *labelSupplier) const; + std::unique_ptr<ISimpleExpression> ProcessExpression(SequenceResult<SimpleParserValue> &result) const; - virtual void ApplyTokensToLexerConfig(SimpleLexer::Config& lexerConfig); + virtual void ApplyTokensToLexerConfig(SimpleLexer::Config &lexerConfig); }; \ No newline at end of file diff --git a/src/Parser/Parsing/Simple/Expression/SimpleExpressionScopeValue.cpp b/src/Parser/Parsing/Simple/Expression/SimpleExpressionScopeValue.cpp index 215ea4e95..d0f17eb2f 100644 --- a/src/Parser/Parsing/Simple/Expression/SimpleExpressionScopeValue.cpp +++ b/src/Parser/Parsing/Simple/Expression/SimpleExpressionScopeValue.cpp @@ -1,28 +1,17 @@ #include "SimpleExpressionScopeValue.h" -SimpleExpressionScopeValue::SimpleExpressionScopeValue(std::string valueName) - : m_value_name(std::move(valueName)) -{ -} +SimpleExpressionScopeValue::SimpleExpressionScopeValue(std::string valueName) : m_value_name(std::move(valueName)) {} -bool SimpleExpressionScopeValue::Equals(const ISimpleExpression* other) const -{ - const auto* otherScopeValue = dynamic_cast<const SimpleExpressionScopeValue*>(other); +bool SimpleExpressionScopeValue::Equals(const ISimpleExpression *other) const { + const auto *otherScopeValue = dynamic_cast<const SimpleExpressionScopeValue *>(other); - return otherScopeValue && otherScopeValue->m_value_name == m_value_name; + return otherScopeValue && otherScopeValue->m_value_name == m_value_name; } -bool SimpleExpressionScopeValue::IsStatic() const -{ - return false; -} +bool SimpleExpressionScopeValue::IsStatic() const { return false; } -SimpleExpressionValue SimpleExpressionScopeValue::EvaluateStatic() const -{ - return SimpleExpressionValue(0); -} +SimpleExpressionValue SimpleExpressionScopeValue::EvaluateStatic() const { return SimpleExpressionValue(0); } -SimpleExpressionValue SimpleExpressionScopeValue::EvaluateNonStatic(const ISimpleExpressionScopeValues* scopeValues) const -{ - return scopeValues->ValueByName(m_value_name); +SimpleExpressionValue SimpleExpressionScopeValue::EvaluateNonStatic(const ISimpleExpressionScopeValues *scopeValues) const { + return scopeValues->ValueByName(m_value_name); } diff --git a/src/Parser/Parsing/Simple/Expression/SimpleExpressionScopeValue.h b/src/Parser/Parsing/Simple/Expression/SimpleExpressionScopeValue.h index 2d4c78d34..60863c337 100644 --- a/src/Parser/Parsing/Simple/Expression/SimpleExpressionScopeValue.h +++ b/src/Parser/Parsing/Simple/Expression/SimpleExpressionScopeValue.h @@ -5,15 +5,14 @@ #include "ISimpleExpression.h" #include "SimpleExpressionValue.h" -class SimpleExpressionScopeValue final : public ISimpleExpression -{ +class SimpleExpressionScopeValue final : public ISimpleExpression { public: - std::string m_value_name; + std::string m_value_name; - explicit SimpleExpressionScopeValue(std::string valueName); + explicit SimpleExpressionScopeValue(std::string valueName); - _NODISCARD bool Equals(const ISimpleExpression* other) const override; - _NODISCARD bool IsStatic() const override; - _NODISCARD SimpleExpressionValue EvaluateStatic() const override; - _NODISCARD SimpleExpressionValue EvaluateNonStatic(const ISimpleExpressionScopeValues* scopeValues) const override; + _NODISCARD bool Equals(const ISimpleExpression *other) const override; + _NODISCARD bool IsStatic() const override; + _NODISCARD SimpleExpressionValue EvaluateStatic() const override; + _NODISCARD SimpleExpressionValue EvaluateNonStatic(const ISimpleExpressionScopeValues *scopeValues) const override; }; diff --git a/src/Parser/Parsing/Simple/Expression/SimpleExpressionUnaryOperation.cpp b/src/Parser/Parsing/Simple/Expression/SimpleExpressionUnaryOperation.cpp index 4f9081717..591a64e87 100644 --- a/src/Parser/Parsing/Simple/Expression/SimpleExpressionUnaryOperation.cpp +++ b/src/Parser/Parsing/Simple/Expression/SimpleExpressionUnaryOperation.cpp @@ -4,86 +4,64 @@ #include "SimpleExpressionBinaryOperation.h" -SimpleExpressionUnaryOperationType::SimpleExpressionUnaryOperationType(const SimpleUnaryOperationId id, std::string syntax, evaluation_function_t evaluationFunction) - : m_id(id), - m_syntax(std::move(syntax)), - m_evaluation_function(std::move(evaluationFunction)) -{ -} - -const SimpleExpressionUnaryOperationType SimpleExpressionUnaryOperationType::OPERATION_NOT( - SimpleUnaryOperationId::NOT, - "!", - [](const SimpleExpressionValue& operand) -> SimpleExpressionValue - { - return SimpleExpressionValue(!operand.IsTruthy()); - } -); - -const SimpleExpressionUnaryOperationType SimpleExpressionUnaryOperationType::OPERATION_BITWISE_NOT( - SimpleUnaryOperationId::BITWISE_NOT, - "~", - [](const SimpleExpressionValue& operand) -> SimpleExpressionValue - { - if (operand.m_type == SimpleExpressionValue::Type::INT) - return SimpleExpressionValue(~operand.m_int_value); - - return SimpleExpressionValue(0); - } -); - -const SimpleExpressionUnaryOperationType SimpleExpressionUnaryOperationType::OPERATION_NEGATIVE( - SimpleUnaryOperationId::NEGATIVE, - "-", - [](const SimpleExpressionValue& operand) -> SimpleExpressionValue - { - if (operand.m_type == SimpleExpressionValue::Type::INT) - return SimpleExpressionValue(-operand.m_int_value); - if (operand.m_type == SimpleExpressionValue::Type::DOUBLE) - return SimpleExpressionValue(-operand.m_double_value); - - return SimpleExpressionValue(0); - } -); - -const SimpleExpressionUnaryOperationType* const SimpleExpressionUnaryOperationType::ALL_OPERATION_TYPES[static_cast<int>(SimpleUnaryOperationId::COUNT)] -{ +SimpleExpressionUnaryOperationType::SimpleExpressionUnaryOperationType(const SimpleUnaryOperationId id, std::string syntax, + evaluation_function_t evaluationFunction) + : m_id(id), m_syntax(std::move(syntax)), m_evaluation_function(std::move(evaluationFunction)) {} + +const SimpleExpressionUnaryOperationType SimpleExpressionUnaryOperationType::OPERATION_NOT(SimpleUnaryOperationId::NOT, "!", + [](const SimpleExpressionValue &operand) -> SimpleExpressionValue { + return SimpleExpressionValue(!operand.IsTruthy()); + }); + +const SimpleExpressionUnaryOperationType + SimpleExpressionUnaryOperationType::OPERATION_BITWISE_NOT(SimpleUnaryOperationId::BITWISE_NOT, "~", + [](const SimpleExpressionValue &operand) -> SimpleExpressionValue { + if (operand.m_type == SimpleExpressionValue::Type::INT) + return SimpleExpressionValue(~operand.m_int_value); + + return SimpleExpressionValue(0); + }); + +const SimpleExpressionUnaryOperationType + SimpleExpressionUnaryOperationType::OPERATION_NEGATIVE(SimpleUnaryOperationId::NEGATIVE, "-", + [](const SimpleExpressionValue &operand) -> SimpleExpressionValue { + if (operand.m_type == SimpleExpressionValue::Type::INT) + return SimpleExpressionValue(-operand.m_int_value); + if (operand.m_type == SimpleExpressionValue::Type::DOUBLE) + return SimpleExpressionValue(-operand.m_double_value); + + return SimpleExpressionValue(0); + }); + +const SimpleExpressionUnaryOperationType *const SimpleExpressionUnaryOperationType::ALL_OPERATION_TYPES[static_cast<int>(SimpleUnaryOperationId::COUNT)]{ &OPERATION_NOT, &OPERATION_BITWISE_NOT, &OPERATION_NEGATIVE, }; -SimpleExpressionUnaryOperation::SimpleExpressionUnaryOperation(const SimpleExpressionUnaryOperationType* operationType, std::unique_ptr<ISimpleExpression> operand) - : m_operation_type(operationType), - m_operand(std::move(operand)) -{ -} +SimpleExpressionUnaryOperation::SimpleExpressionUnaryOperation(const SimpleExpressionUnaryOperationType *operationType, + std::unique_ptr<ISimpleExpression> operand) + : m_operation_type(operationType), m_operand(std::move(operand)) {} -bool SimpleExpressionUnaryOperation::OperandNeedsParenthesis() const -{ - return dynamic_cast<const SimpleExpressionBinaryOperation*>(m_operand.get()) != nullptr; +bool SimpleExpressionUnaryOperation::OperandNeedsParenthesis() const { + return dynamic_cast<const SimpleExpressionBinaryOperation *>(m_operand.get()) != nullptr; } -bool SimpleExpressionUnaryOperation::Equals(const ISimpleExpression* other) const -{ - const auto* otherUnaryOperation = dynamic_cast<const SimpleExpressionUnaryOperation*>(other); +bool SimpleExpressionUnaryOperation::Equals(const ISimpleExpression *other) const { + const auto *otherUnaryOperation = dynamic_cast<const SimpleExpressionUnaryOperation *>(other); - return otherUnaryOperation && m_operation_type->m_id == otherUnaryOperation->m_operation_type->m_id && m_operand->Equals(otherUnaryOperation->m_operand.get()); + return otherUnaryOperation && m_operation_type->m_id == otherUnaryOperation->m_operation_type->m_id && + m_operand->Equals(otherUnaryOperation->m_operand.get()); } -bool SimpleExpressionUnaryOperation::IsStatic() const -{ - assert(m_operand); +bool SimpleExpressionUnaryOperation::IsStatic() const { + assert(m_operand); - return m_operand->IsStatic(); + return m_operand->IsStatic(); } -SimpleExpressionValue SimpleExpressionUnaryOperation::EvaluateStatic() const -{ - return m_operation_type->m_evaluation_function(m_operand->EvaluateStatic()); -} +SimpleExpressionValue SimpleExpressionUnaryOperation::EvaluateStatic() const { return m_operation_type->m_evaluation_function(m_operand->EvaluateStatic()); } -SimpleExpressionValue SimpleExpressionUnaryOperation::EvaluateNonStatic(const ISimpleExpressionScopeValues* scopeValues) const -{ - return m_operation_type->m_evaluation_function(m_operand->EvaluateNonStatic(scopeValues)); +SimpleExpressionValue SimpleExpressionUnaryOperation::EvaluateNonStatic(const ISimpleExpressionScopeValues *scopeValues) const { + return m_operation_type->m_evaluation_function(m_operand->EvaluateNonStatic(scopeValues)); } diff --git a/src/Parser/Parsing/Simple/Expression/SimpleExpressionUnaryOperation.h b/src/Parser/Parsing/Simple/Expression/SimpleExpressionUnaryOperation.h index 18e0dcc65..d36028864 100644 --- a/src/Parser/Parsing/Simple/Expression/SimpleExpressionUnaryOperation.h +++ b/src/Parser/Parsing/Simple/Expression/SimpleExpressionUnaryOperation.h @@ -1,53 +1,50 @@ #pragma once -#include <string> -#include <memory> #include <functional> +#include <memory> +#include <string> #include "ISimpleExpression.h" #include "SimpleExpressionValue.h" -enum class SimpleUnaryOperationId -{ - NOT, - BITWISE_NOT, - NEGATIVE, +enum class SimpleUnaryOperationId { + NOT, + BITWISE_NOT, + NEGATIVE, - COUNT + COUNT }; -class SimpleExpressionUnaryOperationType -{ +class SimpleExpressionUnaryOperationType { public: - using evaluation_function_t = std::function<SimpleExpressionValue(const SimpleExpressionValue& operand)>; + using evaluation_function_t = std::function<SimpleExpressionValue(const SimpleExpressionValue &operand)>; - SimpleUnaryOperationId m_id; - std::string m_syntax; - evaluation_function_t m_evaluation_function; + SimpleUnaryOperationId m_id; + std::string m_syntax; + evaluation_function_t m_evaluation_function; private: - SimpleExpressionUnaryOperationType(SimpleUnaryOperationId id, std::string syntax, evaluation_function_t evaluationFunction); + SimpleExpressionUnaryOperationType(SimpleUnaryOperationId id, std::string syntax, evaluation_function_t evaluationFunction); public: - static const SimpleExpressionUnaryOperationType OPERATION_NOT; - static const SimpleExpressionUnaryOperationType OPERATION_BITWISE_NOT; - static const SimpleExpressionUnaryOperationType OPERATION_NEGATIVE; + static const SimpleExpressionUnaryOperationType OPERATION_NOT; + static const SimpleExpressionUnaryOperationType OPERATION_BITWISE_NOT; + static const SimpleExpressionUnaryOperationType OPERATION_NEGATIVE; - static const SimpleExpressionUnaryOperationType* const ALL_OPERATION_TYPES[static_cast<int>(SimpleUnaryOperationId::COUNT)]; + static const SimpleExpressionUnaryOperationType *const ALL_OPERATION_TYPES[static_cast<int>(SimpleUnaryOperationId::COUNT)]; }; -class SimpleExpressionUnaryOperation final : public ISimpleExpression -{ +class SimpleExpressionUnaryOperation final : public ISimpleExpression { public: - const SimpleExpressionUnaryOperationType* m_operation_type; - std::unique_ptr<ISimpleExpression> m_operand; + const SimpleExpressionUnaryOperationType *m_operation_type; + std::unique_ptr<ISimpleExpression> m_operand; - SimpleExpressionUnaryOperation(const SimpleExpressionUnaryOperationType* operationType, std::unique_ptr<ISimpleExpression> operand); + SimpleExpressionUnaryOperation(const SimpleExpressionUnaryOperationType *operationType, std::unique_ptr<ISimpleExpression> operand); - _NODISCARD bool OperandNeedsParenthesis() const; + _NODISCARD bool OperandNeedsParenthesis() const; - _NODISCARD bool Equals(const ISimpleExpression* other) const override; - _NODISCARD bool IsStatic() const override; - _NODISCARD SimpleExpressionValue EvaluateStatic() const override; - _NODISCARD SimpleExpressionValue EvaluateNonStatic(const ISimpleExpressionScopeValues* scopeValues) const override; + _NODISCARD bool Equals(const ISimpleExpression *other) const override; + _NODISCARD bool IsStatic() const override; + _NODISCARD SimpleExpressionValue EvaluateStatic() const override; + _NODISCARD SimpleExpressionValue EvaluateNonStatic(const ISimpleExpressionScopeValues *scopeValues) const override; }; diff --git a/src/Parser/Parsing/Simple/Expression/SimpleExpressionValue.cpp b/src/Parser/Parsing/Simple/Expression/SimpleExpressionValue.cpp index 14a9431cd..e54552c36 100644 --- a/src/Parser/Parsing/Simple/Expression/SimpleExpressionValue.cpp +++ b/src/Parser/Parsing/Simple/Expression/SimpleExpressionValue.cpp @@ -3,66 +3,49 @@ #include <cmath> SimpleExpressionValue::SimpleExpressionValue(std::string stringValue) - : m_type(Type::STRING), - m_string_value(std::make_shared<std::string>(std::move(stringValue))) -{ - m_double_value = 0; - m_int_value = 0; + : m_type(Type::STRING), m_string_value(std::make_shared<std::string>(std::move(stringValue))) { + m_double_value = 0; + m_int_value = 0; } -SimpleExpressionValue::SimpleExpressionValue(const double doubleValue) - : m_type(Type::DOUBLE) -{ - m_int_value = 0; - m_double_value = doubleValue; +SimpleExpressionValue::SimpleExpressionValue(const double doubleValue) : m_type(Type::DOUBLE) { + m_int_value = 0; + m_double_value = doubleValue; } -SimpleExpressionValue::SimpleExpressionValue(const int intValue) - : m_type(Type::INT) -{ - m_double_value = 0; - m_int_value = intValue; +SimpleExpressionValue::SimpleExpressionValue(const int intValue) : m_type(Type::INT) { + m_double_value = 0; + m_int_value = intValue; } -bool SimpleExpressionValue::Equals(const ISimpleExpression* other) const -{ - const auto* otherExpressionValue = dynamic_cast<const SimpleExpressionValue*>(other); +bool SimpleExpressionValue::Equals(const ISimpleExpression *other) const { + const auto *otherExpressionValue = dynamic_cast<const SimpleExpressionValue *>(other); - if (!otherExpressionValue || m_type != otherExpressionValue->m_type) - return false; + if (!otherExpressionValue || m_type != otherExpressionValue->m_type) + return false; - if (m_type == Type::INT) - return m_int_value == otherExpressionValue->m_int_value; - if (m_type == Type::DOUBLE) - return std::fabs(m_double_value - otherExpressionValue->m_double_value) < std::numeric_limits<double>::epsilon(); - if (m_type == Type::STRING) - return *m_string_value == *otherExpressionValue->m_string_value; + if (m_type == Type::INT) + return m_int_value == otherExpressionValue->m_int_value; + if (m_type == Type::DOUBLE) + return std::fabs(m_double_value - otherExpressionValue->m_double_value) < std::numeric_limits<double>::epsilon(); + if (m_type == Type::STRING) + return *m_string_value == *otherExpressionValue->m_string_value; - return true; + return true; } -bool SimpleExpressionValue::IsStatic() const -{ - return true; -} +bool SimpleExpressionValue::IsStatic() const { return true; } -SimpleExpressionValue SimpleExpressionValue::EvaluateStatic() const -{ - return *this; -} +SimpleExpressionValue SimpleExpressionValue::EvaluateStatic() const { return *this; } -SimpleExpressionValue SimpleExpressionValue::EvaluateNonStatic(const ISimpleExpressionScopeValues* scopeValues) const -{ - return *this; -} +SimpleExpressionValue SimpleExpressionValue::EvaluateNonStatic(const ISimpleExpressionScopeValues *scopeValues) const { return *this; } -bool SimpleExpressionValue::IsTruthy() const -{ - if (m_type == Type::DOUBLE) - return std::fpclassify(m_double_value) != FP_ZERO; - if (m_type == Type::INT) - return m_int_value != 0; - if (m_type == Type::STRING) - return m_string_value && !m_string_value->empty(); - return false; +bool SimpleExpressionValue::IsTruthy() const { + if (m_type == Type::DOUBLE) + return std::fpclassify(m_double_value) != FP_ZERO; + if (m_type == Type::INT) + return m_int_value != 0; + if (m_type == Type::STRING) + return m_string_value && !m_string_value->empty(); + return false; } diff --git a/src/Parser/Parsing/Simple/Expression/SimpleExpressionValue.h b/src/Parser/Parsing/Simple/Expression/SimpleExpressionValue.h index a99d137d5..1b4fe10f3 100644 --- a/src/Parser/Parsing/Simple/Expression/SimpleExpressionValue.h +++ b/src/Parser/Parsing/Simple/Expression/SimpleExpressionValue.h @@ -7,31 +7,24 @@ #include "Utils/ClassUtils.h" class ISimpleExpression; -class SimpleExpressionValue final : public ISimpleExpression -{ +class SimpleExpressionValue final : public ISimpleExpression { public: - enum class Type - { - STRING, - DOUBLE, - INT - }; + enum class Type { STRING, DOUBLE, INT }; - Type m_type; - std::shared_ptr<std::string> m_string_value; - union - { - double m_double_value; - int m_int_value; - }; + Type m_type; + std::shared_ptr<std::string> m_string_value; + union { + double m_double_value; + int m_int_value; + }; - explicit SimpleExpressionValue(std::string stringValue); - explicit SimpleExpressionValue(double doubleValue); - explicit SimpleExpressionValue(int intValue); + explicit SimpleExpressionValue(std::string stringValue); + explicit SimpleExpressionValue(double doubleValue); + explicit SimpleExpressionValue(int intValue); - _NODISCARD bool Equals(const ISimpleExpression* other) const override; - _NODISCARD bool IsStatic() const override; - _NODISCARD SimpleExpressionValue EvaluateStatic() const override; - _NODISCARD SimpleExpressionValue EvaluateNonStatic(const ISimpleExpressionScopeValues* scopeValues) const override; - _NODISCARD bool IsTruthy() const; + _NODISCARD bool Equals(const ISimpleExpression *other) const override; + _NODISCARD bool IsStatic() const override; + _NODISCARD SimpleExpressionValue EvaluateStatic() const override; + _NODISCARD SimpleExpressionValue EvaluateNonStatic(const ISimpleExpressionScopeValues *scopeValues) const override; + _NODISCARD bool IsTruthy() const; }; diff --git a/src/Parser/Parsing/Simple/Matcher/SimpleMatcherAnyCharacterBesides.cpp b/src/Parser/Parsing/Simple/Matcher/SimpleMatcherAnyCharacterBesides.cpp index 0208ffcfd..55deabf94 100644 --- a/src/Parser/Parsing/Simple/Matcher/SimpleMatcherAnyCharacterBesides.cpp +++ b/src/Parser/Parsing/Simple/Matcher/SimpleMatcherAnyCharacterBesides.cpp @@ -1,14 +1,10 @@ #include "SimpleMatcherAnyCharacterBesides.h" -SimpleMatcherAnyCharacterBesides::SimpleMatcherAnyCharacterBesides(std::vector<char> chars) - : m_chars(std::move(chars)) -{ -} +SimpleMatcherAnyCharacterBesides::SimpleMatcherAnyCharacterBesides(std::vector<char> chars) : m_chars(std::move(chars)) {} -MatcherResult<SimpleParserValue> SimpleMatcherAnyCharacterBesides::CanMatch(ILexer<SimpleParserValue>* lexer, const unsigned tokenOffset) -{ - const auto& token = lexer->GetToken(tokenOffset); - return token.m_type == SimpleParserValueType::CHARACTER && std::find(m_chars.begin(), m_chars.end(), token.CharacterValue()) == m_chars.end() - ? MatcherResult<SimpleParserValue>::Match(1) - : MatcherResult<SimpleParserValue>::NoMatch(); +MatcherResult<SimpleParserValue> SimpleMatcherAnyCharacterBesides::CanMatch(ILexer<SimpleParserValue> *lexer, const unsigned tokenOffset) { + const auto &token = lexer->GetToken(tokenOffset); + return token.m_type == SimpleParserValueType::CHARACTER && std::find(m_chars.begin(), m_chars.end(), token.CharacterValue()) == m_chars.end() + ? MatcherResult<SimpleParserValue>::Match(1) + : MatcherResult<SimpleParserValue>::NoMatch(); } diff --git a/src/Parser/Parsing/Simple/Matcher/SimpleMatcherAnyCharacterBesides.h b/src/Parser/Parsing/Simple/Matcher/SimpleMatcherAnyCharacterBesides.h index 46e254080..484cd69a3 100644 --- a/src/Parser/Parsing/Simple/Matcher/SimpleMatcherAnyCharacterBesides.h +++ b/src/Parser/Parsing/Simple/Matcher/SimpleMatcherAnyCharacterBesides.h @@ -2,16 +2,15 @@ #include <vector> -#include "Parsing/Simple/SimpleParserValue.h" #include "Parsing/Matcher/AbstractMatcher.h" +#include "Parsing/Simple/SimpleParserValue.h" -class SimpleMatcherAnyCharacterBesides final : public AbstractMatcher<SimpleParserValue> -{ - std::vector<char> m_chars; +class SimpleMatcherAnyCharacterBesides final : public AbstractMatcher<SimpleParserValue> { + std::vector<char> m_chars; protected: - MatcherResult<SimpleParserValue> CanMatch(ILexer<SimpleParserValue>* lexer, unsigned tokenOffset) override; + MatcherResult<SimpleParserValue> CanMatch(ILexer<SimpleParserValue> *lexer, unsigned tokenOffset) override; public: - explicit SimpleMatcherAnyCharacterBesides(std::vector<char> chars); + explicit SimpleMatcherAnyCharacterBesides(std::vector<char> chars); }; diff --git a/src/Parser/Parsing/Simple/Matcher/SimpleMatcherCharacter.cpp b/src/Parser/Parsing/Simple/Matcher/SimpleMatcherCharacter.cpp index 19531b305..ef38201fd 100644 --- a/src/Parser/Parsing/Simple/Matcher/SimpleMatcherCharacter.cpp +++ b/src/Parser/Parsing/Simple/Matcher/SimpleMatcherCharacter.cpp @@ -1,14 +1,9 @@ #include "SimpleMatcherCharacter.h" -SimpleMatcherCharacter::SimpleMatcherCharacter(const char c) - : m_char(c) -{ -} +SimpleMatcherCharacter::SimpleMatcherCharacter(const char c) : m_char(c) {} -MatcherResult<SimpleParserValue> SimpleMatcherCharacter::CanMatch(ILexer<SimpleParserValue>* lexer, const unsigned tokenOffset) -{ - const auto& token = lexer->GetToken(tokenOffset); - return token.m_type == SimpleParserValueType::CHARACTER && token.CharacterValue() == m_char - ? MatcherResult<SimpleParserValue>::Match(1) - : MatcherResult<SimpleParserValue>::NoMatch(); +MatcherResult<SimpleParserValue> SimpleMatcherCharacter::CanMatch(ILexer<SimpleParserValue> *lexer, const unsigned tokenOffset) { + const auto &token = lexer->GetToken(tokenOffset); + return token.m_type == SimpleParserValueType::CHARACTER && token.CharacterValue() == m_char ? MatcherResult<SimpleParserValue>::Match(1) + : MatcherResult<SimpleParserValue>::NoMatch(); } diff --git a/src/Parser/Parsing/Simple/Matcher/SimpleMatcherCharacter.h b/src/Parser/Parsing/Simple/Matcher/SimpleMatcherCharacter.h index c795061f7..e44f62115 100644 --- a/src/Parser/Parsing/Simple/Matcher/SimpleMatcherCharacter.h +++ b/src/Parser/Parsing/Simple/Matcher/SimpleMatcherCharacter.h @@ -1,15 +1,14 @@ #pragma once -#include "Parsing/Simple/SimpleParserValue.h" #include "Parsing/Matcher/AbstractMatcher.h" +#include "Parsing/Simple/SimpleParserValue.h" -class SimpleMatcherCharacter final : public AbstractMatcher<SimpleParserValue> -{ - char m_char; +class SimpleMatcherCharacter final : public AbstractMatcher<SimpleParserValue> { + char m_char; protected: - MatcherResult<SimpleParserValue> CanMatch(ILexer<SimpleParserValue>* lexer, unsigned tokenOffset) override; + MatcherResult<SimpleParserValue> CanMatch(ILexer<SimpleParserValue> *lexer, unsigned tokenOffset) override; public: - explicit SimpleMatcherCharacter(char c); + explicit SimpleMatcherCharacter(char c); }; diff --git a/src/Parser/Parsing/Simple/Matcher/SimpleMatcherFactory.cpp b/src/Parser/Parsing/Simple/Matcher/SimpleMatcherFactory.cpp index 4d062e32e..00bde231d 100644 --- a/src/Parser/Parsing/Simple/Matcher/SimpleMatcherFactory.cpp +++ b/src/Parser/Parsing/Simple/Matcher/SimpleMatcherFactory.cpp @@ -9,72 +9,56 @@ #include "SimpleMatcherValueType.h" #include "SimpleMatcherValueTypeAndHasSignPrefix.h" -SimpleMatcherFactory::SimpleMatcherFactory(const IMatcherForLabelSupplier<SimpleParserValue>* labelSupplier) - : AbstractMatcherFactory(labelSupplier) -{ -} +SimpleMatcherFactory::SimpleMatcherFactory(const IMatcherForLabelSupplier<SimpleParserValue> *labelSupplier) : AbstractMatcherFactory(labelSupplier) {} -MatcherFactoryWrapper<SimpleParserValue> SimpleMatcherFactory::Type(SimpleParserValueType type) const -{ - return MatcherFactoryWrapper<SimpleParserValue>(std::make_unique<SimpleMatcherValueType>(type)); +MatcherFactoryWrapper<SimpleParserValue> SimpleMatcherFactory::Type(SimpleParserValueType type) const { + return MatcherFactoryWrapper<SimpleParserValue>(std::make_unique<SimpleMatcherValueType>(type)); } -MatcherFactoryWrapper<SimpleParserValue> SimpleMatcherFactory::Keyword(std::string value) const -{ - return MatcherFactoryWrapper<SimpleParserValue>(std::make_unique<SimpleMatcherKeyword>(std::move(value))); +MatcherFactoryWrapper<SimpleParserValue> SimpleMatcherFactory::Keyword(std::string value) const { + return MatcherFactoryWrapper<SimpleParserValue>(std::make_unique<SimpleMatcherKeyword>(std::move(value))); } -MatcherFactoryWrapper<SimpleParserValue> SimpleMatcherFactory::KeywordIgnoreCase(std::string value) const -{ - return MatcherFactoryWrapper<SimpleParserValue>(std::make_unique<SimpleMatcherKeywordIgnoreCase>(std::move(value))); +MatcherFactoryWrapper<SimpleParserValue> SimpleMatcherFactory::KeywordIgnoreCase(std::string value) const { + return MatcherFactoryWrapper<SimpleParserValue>(std::make_unique<SimpleMatcherKeywordIgnoreCase>(std::move(value))); } -MatcherFactoryWrapper<SimpleParserValue> SimpleMatcherFactory::KeywordPrefix(std::string value) const -{ - return MatcherFactoryWrapper<SimpleParserValue>(std::make_unique<SimpleMatcherKeywordPrefix>(std::move(value))); +MatcherFactoryWrapper<SimpleParserValue> SimpleMatcherFactory::KeywordPrefix(std::string value) const { + return MatcherFactoryWrapper<SimpleParserValue>(std::make_unique<SimpleMatcherKeywordPrefix>(std::move(value))); } -MatcherFactoryWrapper<SimpleParserValue> SimpleMatcherFactory::Identifier() const -{ - return MatcherFactoryWrapper<SimpleParserValue>(std::make_unique<SimpleMatcherValueType>(SimpleParserValueType::IDENTIFIER)); +MatcherFactoryWrapper<SimpleParserValue> SimpleMatcherFactory::Identifier() const { + return MatcherFactoryWrapper<SimpleParserValue>(std::make_unique<SimpleMatcherValueType>(SimpleParserValueType::IDENTIFIER)); } -MatcherFactoryWrapper<SimpleParserValue> SimpleMatcherFactory::String() const -{ - return MatcherFactoryWrapper<SimpleParserValue>(std::make_unique<SimpleMatcherValueType>(SimpleParserValueType::STRING)); +MatcherFactoryWrapper<SimpleParserValue> SimpleMatcherFactory::String() const { + return MatcherFactoryWrapper<SimpleParserValue>(std::make_unique<SimpleMatcherValueType>(SimpleParserValueType::STRING)); } -MatcherFactoryWrapper<SimpleParserValue> SimpleMatcherFactory::Integer() const -{ - return MatcherFactoryWrapper<SimpleParserValue>(std::make_unique<SimpleMatcherValueType>(SimpleParserValueType::INTEGER)); +MatcherFactoryWrapper<SimpleParserValue> SimpleMatcherFactory::Integer() const { + return MatcherFactoryWrapper<SimpleParserValue>(std::make_unique<SimpleMatcherValueType>(SimpleParserValueType::INTEGER)); } -MatcherFactoryWrapper<SimpleParserValue> SimpleMatcherFactory::IntegerWithSign() const -{ - return MatcherFactoryWrapper<SimpleParserValue>(std::make_unique<SimpleMatcherValueTypeAndHasSignPrefix>(SimpleParserValueType::INTEGER, true)); +MatcherFactoryWrapper<SimpleParserValue> SimpleMatcherFactory::IntegerWithSign() const { + return MatcherFactoryWrapper<SimpleParserValue>(std::make_unique<SimpleMatcherValueTypeAndHasSignPrefix>(SimpleParserValueType::INTEGER, true)); } -MatcherFactoryWrapper<SimpleParserValue> SimpleMatcherFactory::FloatingPoint() const -{ - return MatcherFactoryWrapper<SimpleParserValue>(std::make_unique<SimpleMatcherValueType>(SimpleParserValueType::FLOATING_POINT)); +MatcherFactoryWrapper<SimpleParserValue> SimpleMatcherFactory::FloatingPoint() const { + return MatcherFactoryWrapper<SimpleParserValue>(std::make_unique<SimpleMatcherValueType>(SimpleParserValueType::FLOATING_POINT)); } -MatcherFactoryWrapper<SimpleParserValue> SimpleMatcherFactory::FloatingPointWithSign() const -{ - return MatcherFactoryWrapper<SimpleParserValue>(std::make_unique<SimpleMatcherValueTypeAndHasSignPrefix>(SimpleParserValueType::FLOATING_POINT, true)); +MatcherFactoryWrapper<SimpleParserValue> SimpleMatcherFactory::FloatingPointWithSign() const { + return MatcherFactoryWrapper<SimpleParserValue>(std::make_unique<SimpleMatcherValueTypeAndHasSignPrefix>(SimpleParserValueType::FLOATING_POINT, true)); } -MatcherFactoryWrapper<SimpleParserValue> SimpleMatcherFactory::Char(char c) const -{ - return MatcherFactoryWrapper<SimpleParserValue>(std::make_unique<SimpleMatcherCharacter>(c)); +MatcherFactoryWrapper<SimpleParserValue> SimpleMatcherFactory::Char(char c) const { + return MatcherFactoryWrapper<SimpleParserValue>(std::make_unique<SimpleMatcherCharacter>(c)); } -MatcherFactoryWrapper<SimpleParserValue> SimpleMatcherFactory::MultiChar(int multiCharacterSequenceId) const -{ - return MatcherFactoryWrapper<SimpleParserValue>(std::make_unique<SimpleMatcherMultiCharacter>(multiCharacterSequenceId)); +MatcherFactoryWrapper<SimpleParserValue> SimpleMatcherFactory::MultiChar(int multiCharacterSequenceId) const { + return MatcherFactoryWrapper<SimpleParserValue>(std::make_unique<SimpleMatcherMultiCharacter>(multiCharacterSequenceId)); } -MatcherFactoryWrapper<SimpleParserValue> SimpleMatcherFactory::AnyCharBesides(std::vector<char> chars) const -{ - return MatcherFactoryWrapper<SimpleParserValue>(std::make_unique<SimpleMatcherAnyCharacterBesides>(std::move(chars))); +MatcherFactoryWrapper<SimpleParserValue> SimpleMatcherFactory::AnyCharBesides(std::vector<char> chars) const { + return MatcherFactoryWrapper<SimpleParserValue>(std::make_unique<SimpleMatcherAnyCharacterBesides>(std::move(chars))); } diff --git a/src/Parser/Parsing/Simple/Matcher/SimpleMatcherFactory.h b/src/Parser/Parsing/Simple/Matcher/SimpleMatcherFactory.h index 5831a4fc7..1d7c21534 100644 --- a/src/Parser/Parsing/Simple/Matcher/SimpleMatcherFactory.h +++ b/src/Parser/Parsing/Simple/Matcher/SimpleMatcherFactory.h @@ -2,25 +2,24 @@ #include <string> -#include "Parsing/Simple/SimpleParserValue.h" #include "Parsing/Matcher/AbstractMatcherFactory.h" +#include "Parsing/Simple/SimpleParserValue.h" -class SimpleMatcherFactory : public AbstractMatcherFactory<SimpleParserValue> -{ +class SimpleMatcherFactory : public AbstractMatcherFactory<SimpleParserValue> { public: - explicit SimpleMatcherFactory(const IMatcherForLabelSupplier<SimpleParserValue>* labelSupplier); - - _NODISCARD MatcherFactoryWrapper<SimpleParserValue> Type(SimpleParserValueType type) const; - _NODISCARD MatcherFactoryWrapper<SimpleParserValue> Keyword(std::string value) const; - _NODISCARD MatcherFactoryWrapper<SimpleParserValue> KeywordIgnoreCase(std::string value) const; - _NODISCARD MatcherFactoryWrapper<SimpleParserValue> KeywordPrefix(std::string value) const; - _NODISCARD MatcherFactoryWrapper<SimpleParserValue> Identifier() const; - _NODISCARD MatcherFactoryWrapper<SimpleParserValue> String() const; - _NODISCARD MatcherFactoryWrapper<SimpleParserValue> Integer() const; - _NODISCARD MatcherFactoryWrapper<SimpleParserValue> IntegerWithSign() const; - _NODISCARD MatcherFactoryWrapper<SimpleParserValue> FloatingPoint() const; - _NODISCARD MatcherFactoryWrapper<SimpleParserValue> FloatingPointWithSign() const; - _NODISCARD MatcherFactoryWrapper<SimpleParserValue> Char(char c) const; - _NODISCARD MatcherFactoryWrapper<SimpleParserValue> MultiChar(int multiCharacterSequenceId) const; - _NODISCARD MatcherFactoryWrapper<SimpleParserValue> AnyCharBesides(std::vector<char> chars) const; + explicit SimpleMatcherFactory(const IMatcherForLabelSupplier<SimpleParserValue> *labelSupplier); + + _NODISCARD MatcherFactoryWrapper<SimpleParserValue> Type(SimpleParserValueType type) const; + _NODISCARD MatcherFactoryWrapper<SimpleParserValue> Keyword(std::string value) const; + _NODISCARD MatcherFactoryWrapper<SimpleParserValue> KeywordIgnoreCase(std::string value) const; + _NODISCARD MatcherFactoryWrapper<SimpleParserValue> KeywordPrefix(std::string value) const; + _NODISCARD MatcherFactoryWrapper<SimpleParserValue> Identifier() const; + _NODISCARD MatcherFactoryWrapper<SimpleParserValue> String() const; + _NODISCARD MatcherFactoryWrapper<SimpleParserValue> Integer() const; + _NODISCARD MatcherFactoryWrapper<SimpleParserValue> IntegerWithSign() const; + _NODISCARD MatcherFactoryWrapper<SimpleParserValue> FloatingPoint() const; + _NODISCARD MatcherFactoryWrapper<SimpleParserValue> FloatingPointWithSign() const; + _NODISCARD MatcherFactoryWrapper<SimpleParserValue> Char(char c) const; + _NODISCARD MatcherFactoryWrapper<SimpleParserValue> MultiChar(int multiCharacterSequenceId) const; + _NODISCARD MatcherFactoryWrapper<SimpleParserValue> AnyCharBesides(std::vector<char> chars) const; }; diff --git a/src/Parser/Parsing/Simple/Matcher/SimpleMatcherKeyword.cpp b/src/Parser/Parsing/Simple/Matcher/SimpleMatcherKeyword.cpp index b29e00211..ef7096499 100644 --- a/src/Parser/Parsing/Simple/Matcher/SimpleMatcherKeyword.cpp +++ b/src/Parser/Parsing/Simple/Matcher/SimpleMatcherKeyword.cpp @@ -1,16 +1,13 @@ #include "SimpleMatcherKeyword.h" -SimpleMatcherKeyword::SimpleMatcherKeyword(std::string value) - : m_value(std::move(value)) -{ - const std::hash<std::string> hash; - m_hash = hash(m_value); +SimpleMatcherKeyword::SimpleMatcherKeyword(std::string value) : m_value(std::move(value)) { + const std::hash<std::string> hash; + m_hash = hash(m_value); } -MatcherResult<SimpleParserValue> SimpleMatcherKeyword::CanMatch(ILexer<SimpleParserValue>* lexer, const unsigned tokenOffset) -{ - const auto& token = lexer->GetToken(tokenOffset); - return token.m_type == SimpleParserValueType::IDENTIFIER && token.IdentifierHash() == m_hash && token.IdentifierValue() == m_value - ? MatcherResult<SimpleParserValue>::Match(1) - : MatcherResult<SimpleParserValue>::NoMatch(); +MatcherResult<SimpleParserValue> SimpleMatcherKeyword::CanMatch(ILexer<SimpleParserValue> *lexer, const unsigned tokenOffset) { + const auto &token = lexer->GetToken(tokenOffset); + return token.m_type == SimpleParserValueType::IDENTIFIER && token.IdentifierHash() == m_hash && token.IdentifierValue() == m_value + ? MatcherResult<SimpleParserValue>::Match(1) + : MatcherResult<SimpleParserValue>::NoMatch(); } diff --git a/src/Parser/Parsing/Simple/Matcher/SimpleMatcherKeyword.h b/src/Parser/Parsing/Simple/Matcher/SimpleMatcherKeyword.h index 40183667c..0a239c0c0 100644 --- a/src/Parser/Parsing/Simple/Matcher/SimpleMatcherKeyword.h +++ b/src/Parser/Parsing/Simple/Matcher/SimpleMatcherKeyword.h @@ -2,17 +2,16 @@ #include <string> -#include "Parsing/Simple/SimpleParserValue.h" #include "Parsing/Matcher/AbstractMatcher.h" +#include "Parsing/Simple/SimpleParserValue.h" -class SimpleMatcherKeyword final : public AbstractMatcher<SimpleParserValue> -{ - size_t m_hash; - std::string m_value; +class SimpleMatcherKeyword final : public AbstractMatcher<SimpleParserValue> { + size_t m_hash; + std::string m_value; protected: - MatcherResult<SimpleParserValue> CanMatch(ILexer<SimpleParserValue>* lexer, unsigned tokenOffset) override; + MatcherResult<SimpleParserValue> CanMatch(ILexer<SimpleParserValue> *lexer, unsigned tokenOffset) override; public: - explicit SimpleMatcherKeyword(std::string value); + explicit SimpleMatcherKeyword(std::string value); }; diff --git a/src/Parser/Parsing/Simple/Matcher/SimpleMatcherKeywordIgnoreCase.cpp b/src/Parser/Parsing/Simple/Matcher/SimpleMatcherKeywordIgnoreCase.cpp index 3c241d160..9e4776f4d 100644 --- a/src/Parser/Parsing/Simple/Matcher/SimpleMatcherKeywordIgnoreCase.cpp +++ b/src/Parser/Parsing/Simple/Matcher/SimpleMatcherKeywordIgnoreCase.cpp @@ -2,28 +2,23 @@ #include <algorithm> -SimpleMatcherKeywordIgnoreCase::SimpleMatcherKeywordIgnoreCase(std::string value) - : m_value(std::move(value)) -{ - for (auto& c : m_value) - c = static_cast<char>(tolower(c)); +SimpleMatcherKeywordIgnoreCase::SimpleMatcherKeywordIgnoreCase(std::string value) : m_value(std::move(value)) { + for (auto &c : m_value) + c = static_cast<char>(tolower(c)); } -MatcherResult<SimpleParserValue> SimpleMatcherKeywordIgnoreCase::CanMatch(ILexer<SimpleParserValue>* lexer, const unsigned tokenOffset) -{ - const auto& token = lexer->GetToken(tokenOffset); +MatcherResult<SimpleParserValue> SimpleMatcherKeywordIgnoreCase::CanMatch(ILexer<SimpleParserValue> *lexer, const unsigned tokenOffset) { + const auto &token = lexer->GetToken(tokenOffset); - if (token.m_type != SimpleParserValueType::IDENTIFIER) - return MatcherResult<SimpleParserValue>::NoMatch(); + if (token.m_type != SimpleParserValueType::IDENTIFIER) + return MatcherResult<SimpleParserValue>::NoMatch(); - const auto& identifierValue = token.IdentifierValue(); - const auto isEqual = std::equal(identifierValue.begin(), identifierValue.end(), m_value.begin(), m_value.end(), [](const char a, const char b) - { - return tolower(a) == b; - }); + const auto &identifierValue = token.IdentifierValue(); + const auto isEqual = + std::equal(identifierValue.begin(), identifierValue.end(), m_value.begin(), m_value.end(), [](const char a, const char b) { return tolower(a) == b; }); - if (isEqual) - return MatcherResult<SimpleParserValue>::Match(1); + if (isEqual) + return MatcherResult<SimpleParserValue>::Match(1); - return MatcherResult<SimpleParserValue>::NoMatch(); + return MatcherResult<SimpleParserValue>::NoMatch(); } diff --git a/src/Parser/Parsing/Simple/Matcher/SimpleMatcherKeywordIgnoreCase.h b/src/Parser/Parsing/Simple/Matcher/SimpleMatcherKeywordIgnoreCase.h index 3b52aca8a..b796c8938 100644 --- a/src/Parser/Parsing/Simple/Matcher/SimpleMatcherKeywordIgnoreCase.h +++ b/src/Parser/Parsing/Simple/Matcher/SimpleMatcherKeywordIgnoreCase.h @@ -2,16 +2,15 @@ #include <string> -#include "Parsing/Simple/SimpleParserValue.h" #include "Parsing/Matcher/AbstractMatcher.h" +#include "Parsing/Simple/SimpleParserValue.h" -class SimpleMatcherKeywordIgnoreCase final : public AbstractMatcher<SimpleParserValue> -{ - std::string m_value; +class SimpleMatcherKeywordIgnoreCase final : public AbstractMatcher<SimpleParserValue> { + std::string m_value; protected: - MatcherResult<SimpleParserValue> CanMatch(ILexer<SimpleParserValue>* lexer, unsigned tokenOffset) override; + MatcherResult<SimpleParserValue> CanMatch(ILexer<SimpleParserValue> *lexer, unsigned tokenOffset) override; public: - explicit SimpleMatcherKeywordIgnoreCase(std::string value); + explicit SimpleMatcherKeywordIgnoreCase(std::string value); }; diff --git a/src/Parser/Parsing/Simple/Matcher/SimpleMatcherKeywordPrefix.cpp b/src/Parser/Parsing/Simple/Matcher/SimpleMatcherKeywordPrefix.cpp index 303ddaf64..6fd27524f 100644 --- a/src/Parser/Parsing/Simple/Matcher/SimpleMatcherKeywordPrefix.cpp +++ b/src/Parser/Parsing/Simple/Matcher/SimpleMatcherKeywordPrefix.cpp @@ -1,14 +1,10 @@ #include "SimpleMatcherKeywordPrefix.h" -SimpleMatcherKeywordPrefix::SimpleMatcherKeywordPrefix(std::string value) - : m_value(std::move(value)) -{ -} +SimpleMatcherKeywordPrefix::SimpleMatcherKeywordPrefix(std::string value) : m_value(std::move(value)) {} -MatcherResult<SimpleParserValue> SimpleMatcherKeywordPrefix::CanMatch(ILexer<SimpleParserValue>* lexer, const unsigned tokenOffset) -{ - const auto& token = lexer->GetToken(tokenOffset); - return token.m_type == SimpleParserValueType::IDENTIFIER && token.IdentifierValue().compare(0, m_value.size(), m_value) == 0 - ? MatcherResult<SimpleParserValue>::Match(1) - : MatcherResult<SimpleParserValue>::NoMatch(); +MatcherResult<SimpleParserValue> SimpleMatcherKeywordPrefix::CanMatch(ILexer<SimpleParserValue> *lexer, const unsigned tokenOffset) { + const auto &token = lexer->GetToken(tokenOffset); + return token.m_type == SimpleParserValueType::IDENTIFIER && token.IdentifierValue().compare(0, m_value.size(), m_value) == 0 + ? MatcherResult<SimpleParserValue>::Match(1) + : MatcherResult<SimpleParserValue>::NoMatch(); } diff --git a/src/Parser/Parsing/Simple/Matcher/SimpleMatcherKeywordPrefix.h b/src/Parser/Parsing/Simple/Matcher/SimpleMatcherKeywordPrefix.h index 29bc19413..013bb63a3 100644 --- a/src/Parser/Parsing/Simple/Matcher/SimpleMatcherKeywordPrefix.h +++ b/src/Parser/Parsing/Simple/Matcher/SimpleMatcherKeywordPrefix.h @@ -2,16 +2,15 @@ #include <string> -#include "Parsing/Simple/SimpleParserValue.h" #include "Parsing/Matcher/AbstractMatcher.h" +#include "Parsing/Simple/SimpleParserValue.h" -class SimpleMatcherKeywordPrefix final : public AbstractMatcher<SimpleParserValue> -{ - std::string m_value; +class SimpleMatcherKeywordPrefix final : public AbstractMatcher<SimpleParserValue> { + std::string m_value; protected: - MatcherResult<SimpleParserValue> CanMatch(ILexer<SimpleParserValue>* lexer, unsigned tokenOffset) override; + MatcherResult<SimpleParserValue> CanMatch(ILexer<SimpleParserValue> *lexer, unsigned tokenOffset) override; public: - explicit SimpleMatcherKeywordPrefix(std::string value); + explicit SimpleMatcherKeywordPrefix(std::string value); }; diff --git a/src/Parser/Parsing/Simple/Matcher/SimpleMatcherMultiCharacter.cpp b/src/Parser/Parsing/Simple/Matcher/SimpleMatcherMultiCharacter.cpp index 8cbcc9665..843d54e2d 100644 --- a/src/Parser/Parsing/Simple/Matcher/SimpleMatcherMultiCharacter.cpp +++ b/src/Parser/Parsing/Simple/Matcher/SimpleMatcherMultiCharacter.cpp @@ -1,14 +1,10 @@ #include "SimpleMatcherMultiCharacter.h" -SimpleMatcherMultiCharacter::SimpleMatcherMultiCharacter(const int multiCharacterSequenceId) - : m_multi_character_sequence_id(multiCharacterSequenceId) -{ -} +SimpleMatcherMultiCharacter::SimpleMatcherMultiCharacter(const int multiCharacterSequenceId) : m_multi_character_sequence_id(multiCharacterSequenceId) {} -MatcherResult<SimpleParserValue> SimpleMatcherMultiCharacter::CanMatch(ILexer<SimpleParserValue>* lexer, const unsigned tokenOffset) -{ - const auto& token = lexer->GetToken(tokenOffset); - return token.m_type == SimpleParserValueType::MULTI_CHARACTER && token.MultiCharacterValue() == m_multi_character_sequence_id - ? MatcherResult<SimpleParserValue>::Match(1) - : MatcherResult<SimpleParserValue>::NoMatch(); +MatcherResult<SimpleParserValue> SimpleMatcherMultiCharacter::CanMatch(ILexer<SimpleParserValue> *lexer, const unsigned tokenOffset) { + const auto &token = lexer->GetToken(tokenOffset); + return token.m_type == SimpleParserValueType::MULTI_CHARACTER && token.MultiCharacterValue() == m_multi_character_sequence_id + ? MatcherResult<SimpleParserValue>::Match(1) + : MatcherResult<SimpleParserValue>::NoMatch(); } diff --git a/src/Parser/Parsing/Simple/Matcher/SimpleMatcherMultiCharacter.h b/src/Parser/Parsing/Simple/Matcher/SimpleMatcherMultiCharacter.h index cb68fe6ea..093da1adf 100644 --- a/src/Parser/Parsing/Simple/Matcher/SimpleMatcherMultiCharacter.h +++ b/src/Parser/Parsing/Simple/Matcher/SimpleMatcherMultiCharacter.h @@ -1,15 +1,14 @@ #pragma once -#include "Parsing/Simple/SimpleParserValue.h" #include "Parsing/Matcher/AbstractMatcher.h" +#include "Parsing/Simple/SimpleParserValue.h" -class SimpleMatcherMultiCharacter final : public AbstractMatcher<SimpleParserValue> -{ - int m_multi_character_sequence_id; +class SimpleMatcherMultiCharacter final : public AbstractMatcher<SimpleParserValue> { + int m_multi_character_sequence_id; protected: - MatcherResult<SimpleParserValue> CanMatch(ILexer<SimpleParserValue>* lexer, unsigned tokenOffset) override; + MatcherResult<SimpleParserValue> CanMatch(ILexer<SimpleParserValue> *lexer, unsigned tokenOffset) override; public: - explicit SimpleMatcherMultiCharacter(int multiCharacterSequenceId); + explicit SimpleMatcherMultiCharacter(int multiCharacterSequenceId); }; diff --git a/src/Parser/Parsing/Simple/Matcher/SimpleMatcherValueType.cpp b/src/Parser/Parsing/Simple/Matcher/SimpleMatcherValueType.cpp index c71a50f21..802ee9895 100644 --- a/src/Parser/Parsing/Simple/Matcher/SimpleMatcherValueType.cpp +++ b/src/Parser/Parsing/Simple/Matcher/SimpleMatcherValueType.cpp @@ -1,13 +1,7 @@ #include "SimpleMatcherValueType.h" -SimpleMatcherValueType::SimpleMatcherValueType(const SimpleParserValueType type) - : m_type(type) -{ -} +SimpleMatcherValueType::SimpleMatcherValueType(const SimpleParserValueType type) : m_type(type) {} -MatcherResult<SimpleParserValue> SimpleMatcherValueType::CanMatch(ILexer<SimpleParserValue>* lexer, const unsigned tokenOffset) -{ - return lexer->GetToken(tokenOffset).m_type == m_type - ? MatcherResult<SimpleParserValue>::Match(1) - : MatcherResult<SimpleParserValue>::NoMatch(); +MatcherResult<SimpleParserValue> SimpleMatcherValueType::CanMatch(ILexer<SimpleParserValue> *lexer, const unsigned tokenOffset) { + return lexer->GetToken(tokenOffset).m_type == m_type ? MatcherResult<SimpleParserValue>::Match(1) : MatcherResult<SimpleParserValue>::NoMatch(); } diff --git a/src/Parser/Parsing/Simple/Matcher/SimpleMatcherValueType.h b/src/Parser/Parsing/Simple/Matcher/SimpleMatcherValueType.h index 9bb6669cf..101965951 100644 --- a/src/Parser/Parsing/Simple/Matcher/SimpleMatcherValueType.h +++ b/src/Parser/Parsing/Simple/Matcher/SimpleMatcherValueType.h @@ -1,15 +1,14 @@ #pragma once -#include "Parsing/Simple/SimpleParserValue.h" #include "Parsing/Matcher/AbstractMatcher.h" +#include "Parsing/Simple/SimpleParserValue.h" -class SimpleMatcherValueType final : public AbstractMatcher<SimpleParserValue> -{ - SimpleParserValueType m_type; +class SimpleMatcherValueType final : public AbstractMatcher<SimpleParserValue> { + SimpleParserValueType m_type; protected: - MatcherResult<SimpleParserValue> CanMatch(ILexer<SimpleParserValue>* lexer, unsigned tokenOffset) override; + MatcherResult<SimpleParserValue> CanMatch(ILexer<SimpleParserValue> *lexer, unsigned tokenOffset) override; public: - explicit SimpleMatcherValueType(SimpleParserValueType type); + explicit SimpleMatcherValueType(SimpleParserValueType type); }; diff --git a/src/Parser/Parsing/Simple/Matcher/SimpleMatcherValueTypeAndHasPrefix.cpp b/src/Parser/Parsing/Simple/Matcher/SimpleMatcherValueTypeAndHasPrefix.cpp index 4378a0e4c..66833d49c 100644 --- a/src/Parser/Parsing/Simple/Matcher/SimpleMatcherValueTypeAndHasPrefix.cpp +++ b/src/Parser/Parsing/Simple/Matcher/SimpleMatcherValueTypeAndHasPrefix.cpp @@ -1,15 +1,10 @@ #include "SimpleMatcherValueTypeAndHasSignPrefix.h" SimpleMatcherValueTypeAndHasSignPrefix::SimpleMatcherValueTypeAndHasSignPrefix(const SimpleParserValueType type, bool hasSignPrefix) - : m_type(type), - m_has_sign_prefix(hasSignPrefix) -{ -} + : m_type(type), m_has_sign_prefix(hasSignPrefix) {} -MatcherResult<SimpleParserValue> SimpleMatcherValueTypeAndHasSignPrefix::CanMatch(ILexer<SimpleParserValue>* lexer, const unsigned tokenOffset) -{ - const auto& token = lexer->GetToken(tokenOffset); - return token.m_type == m_type && token.m_has_sign_prefix == m_has_sign_prefix - ? MatcherResult<SimpleParserValue>::Match(1) - : MatcherResult<SimpleParserValue>::NoMatch(); +MatcherResult<SimpleParserValue> SimpleMatcherValueTypeAndHasSignPrefix::CanMatch(ILexer<SimpleParserValue> *lexer, const unsigned tokenOffset) { + const auto &token = lexer->GetToken(tokenOffset); + return token.m_type == m_type && token.m_has_sign_prefix == m_has_sign_prefix ? MatcherResult<SimpleParserValue>::Match(1) + : MatcherResult<SimpleParserValue>::NoMatch(); } diff --git a/src/Parser/Parsing/Simple/Matcher/SimpleMatcherValueTypeAndHasSignPrefix.h b/src/Parser/Parsing/Simple/Matcher/SimpleMatcherValueTypeAndHasSignPrefix.h index b5564a9c8..ee90dfafb 100644 --- a/src/Parser/Parsing/Simple/Matcher/SimpleMatcherValueTypeAndHasSignPrefix.h +++ b/src/Parser/Parsing/Simple/Matcher/SimpleMatcherValueTypeAndHasSignPrefix.h @@ -1,16 +1,15 @@ #pragma once -#include "Parsing/Simple/SimpleParserValue.h" #include "Parsing/Matcher/AbstractMatcher.h" +#include "Parsing/Simple/SimpleParserValue.h" -class SimpleMatcherValueTypeAndHasSignPrefix final : public AbstractMatcher<SimpleParserValue> -{ - SimpleParserValueType m_type; - bool m_has_sign_prefix; +class SimpleMatcherValueTypeAndHasSignPrefix final : public AbstractMatcher<SimpleParserValue> { + SimpleParserValueType m_type; + bool m_has_sign_prefix; protected: - MatcherResult<SimpleParserValue> CanMatch(ILexer<SimpleParserValue>* lexer, unsigned tokenOffset) override; + MatcherResult<SimpleParserValue> CanMatch(ILexer<SimpleParserValue> *lexer, unsigned tokenOffset) override; public: - explicit SimpleMatcherValueTypeAndHasSignPrefix(SimpleParserValueType type, bool hasSignPrefix); + explicit SimpleMatcherValueTypeAndHasSignPrefix(SimpleParserValueType type, bool hasSignPrefix); }; diff --git a/src/Parser/Parsing/Simple/SimpleExpressionInterpreter.cpp b/src/Parser/Parsing/Simple/SimpleExpressionInterpreter.cpp index f4975734c..9a97ea3a4 100644 --- a/src/Parser/Parsing/Simple/SimpleExpressionInterpreter.cpp +++ b/src/Parser/Parsing/Simple/SimpleExpressionInterpreter.cpp @@ -1,80 +1,62 @@ #include "SimpleExpressionInterpreter.h" -#include "Utils/ClassUtils.h" #include "Expression/SimpleExpressionMatchers.h" #include "Matcher/SimpleMatcherFactory.h" #include "Parsing/Impl/AbstractParser.h" +#include "Utils/ClassUtils.h" -class SimpleExpressionInterpreterParserState -{ +class SimpleExpressionInterpreterParserState { public: - std::unique_ptr<ISimpleExpression> m_expression; + std::unique_ptr<ISimpleExpression> m_expression; }; -class SimpleExpressionInterpreterExpressionSequence final : public AbstractSequence<SimpleParserValue, SimpleExpressionInterpreterParserState> -{ +class SimpleExpressionInterpreterExpressionSequence final : public AbstractSequence<SimpleParserValue, SimpleExpressionInterpreterParserState> { public: - SimpleExpressionInterpreterExpressionSequence() - { - const SimpleMatcherFactory create(this); - AddLabeledMatchers(m_expression_matchers.Expression(this), SimpleExpressionMatchers::LABEL_EXPRESSION); - AddMatchers(create.Label(SimpleExpressionMatchers::LABEL_EXPRESSION)); - } + SimpleExpressionInterpreterExpressionSequence() { + const SimpleMatcherFactory create(this); + AddLabeledMatchers(m_expression_matchers.Expression(this), SimpleExpressionMatchers::LABEL_EXPRESSION); + AddMatchers(create.Label(SimpleExpressionMatchers::LABEL_EXPRESSION)); + } protected: - void ProcessMatch(SimpleExpressionInterpreterParserState* state, SequenceResult<SimpleParserValue>& result) const override - { - state->m_expression = m_expression_matchers.ProcessExpression(result); - } + void ProcessMatch(SimpleExpressionInterpreterParserState *state, SequenceResult<SimpleParserValue> &result) const override { + state->m_expression = m_expression_matchers.ProcessExpression(result); + } private: - SimpleExpressionMatchers m_expression_matchers; + SimpleExpressionMatchers m_expression_matchers; }; -class SimpleExpressionInterpreterParser final : public AbstractParser<SimpleParserValue, SimpleExpressionInterpreterParserState> -{ +class SimpleExpressionInterpreterParser final : public AbstractParser<SimpleParserValue, SimpleExpressionInterpreterParserState> { public: - explicit SimpleExpressionInterpreterParser(ILexer<SimpleParserValue>* lexer) - : AbstractParser<SimpleParserValue, SimpleExpressionInterpreterParserState>(lexer, std::make_unique<SimpleExpressionInterpreterParserState>()) - { - } + explicit SimpleExpressionInterpreterParser(ILexer<SimpleParserValue> *lexer) + : AbstractParser<SimpleParserValue, SimpleExpressionInterpreterParserState>(lexer, std::make_unique<SimpleExpressionInterpreterParserState>()) {} - _NODISCARD std::unique_ptr<ISimpleExpression> GetParsedExpression() const - { - return std::move(m_state->m_expression); - } + _NODISCARD std::unique_ptr<ISimpleExpression> GetParsedExpression() const { return std::move(m_state->m_expression); } protected: - const std::vector<sequence_t*>& GetTestsForState() override - { - static std::vector<sequence_t*> sequences - { - new SimpleExpressionInterpreterExpressionSequence() - }; - return sequences; - } + const std::vector<sequence_t *> &GetTestsForState() override { + static std::vector<sequence_t *> sequences{new SimpleExpressionInterpreterExpressionSequence()}; + return sequences; + } }; -SimpleExpressionInterpreter::SimpleExpressionInterpreter(IParserLineStream* input) - : m_input(input) -{ -} +SimpleExpressionInterpreter::SimpleExpressionInterpreter(IParserLineStream *input) : m_input(input) {} -std::unique_ptr<ISimpleExpression> SimpleExpressionInterpreter::Evaluate() const -{ - SimpleLexer::Config lexerConfig; - lexerConfig.m_emit_new_line_tokens = false; - lexerConfig.m_read_integer_numbers = true; - lexerConfig.m_read_floating_point_numbers = true; - lexerConfig.m_read_strings = true; - lexerConfig.m_string_escape_sequences = true; - SimpleExpressionMatchers().ApplyTokensToLexerConfig(lexerConfig); +std::unique_ptr<ISimpleExpression> SimpleExpressionInterpreter::Evaluate() const { + SimpleLexer::Config lexerConfig; + lexerConfig.m_emit_new_line_tokens = false; + lexerConfig.m_read_integer_numbers = true; + lexerConfig.m_read_floating_point_numbers = true; + lexerConfig.m_read_strings = true; + lexerConfig.m_string_escape_sequences = true; + SimpleExpressionMatchers().ApplyTokensToLexerConfig(lexerConfig); - SimpleLexer lexer(m_input, std::move(lexerConfig)); - SimpleExpressionInterpreterParser parser(&lexer); + SimpleLexer lexer(m_input, std::move(lexerConfig)); + SimpleExpressionInterpreterParser parser(&lexer); - if (!parser.Parse()) - return nullptr; + if (!parser.Parse()) + return nullptr; - return parser.GetParsedExpression(); + return parser.GetParsedExpression(); } diff --git a/src/Parser/Parsing/Simple/SimpleExpressionInterpreter.h b/src/Parser/Parsing/Simple/SimpleExpressionInterpreter.h index 5494cb6f3..da9cfb7d2 100644 --- a/src/Parser/Parsing/Simple/SimpleExpressionInterpreter.h +++ b/src/Parser/Parsing/Simple/SimpleExpressionInterpreter.h @@ -2,13 +2,12 @@ #include "Expression/ISimpleExpression.h" #include "Parsing/IParserLineStream.h" -class SimpleExpressionInterpreter -{ +class SimpleExpressionInterpreter { public: - explicit SimpleExpressionInterpreter(IParserLineStream* input); + explicit SimpleExpressionInterpreter(IParserLineStream *input); - std::unique_ptr<ISimpleExpression> Evaluate() const; + std::unique_ptr<ISimpleExpression> Evaluate() const; private: - IParserLineStream* m_input; + IParserLineStream *m_input; }; diff --git a/src/Parser/Parsing/Simple/SimpleLexer.cpp b/src/Parser/Parsing/Simple/SimpleLexer.cpp index 719bad83c..d0ae9940c 100644 --- a/src/Parser/Parsing/Simple/SimpleLexer.cpp +++ b/src/Parser/Parsing/Simple/SimpleLexer.cpp @@ -1,156 +1,125 @@ #include "SimpleLexer.h" -SimpleLexer::Config::MultiCharacterToken::MultiCharacterToken(const int id, std::string value) - : m_id(id), - m_value(std::move(value)) -{ -} +SimpleLexer::Config::MultiCharacterToken::MultiCharacterToken(const int id, std::string value) : m_id(id), m_value(std::move(value)) {} -SimpleLexer::MultiCharacterTokenLookupEntry::MultiCharacterTokenLookupEntry(const int id, std::string value) - : m_id(id), - m_value(std::move(value)) -{ -} +SimpleLexer::MultiCharacterTokenLookupEntry::MultiCharacterTokenLookupEntry(const int id, std::string value) : m_id(id), m_value(std::move(value)) {} -SimpleLexer::SimpleLexer(IParserLineStream* stream) - : AbstractLexer(stream), - m_config{false, true, false, true, true, {}}, - m_check_for_multi_character_tokens(false), - m_last_line(1) -{ -} +SimpleLexer::SimpleLexer(IParserLineStream *stream) + : AbstractLexer(stream), m_config{false, true, false, true, true, {}}, m_check_for_multi_character_tokens(false), m_last_line(1) {} + +SimpleLexer::SimpleLexer(IParserLineStream *stream, Config config) + : AbstractLexer(stream), m_config(std::move(config)), m_check_for_multi_character_tokens(false), m_last_line(1) { + for (auto tokenConfig : m_config.m_multi_character_tokens) + AddMultiCharacterTokenConfigToLookup(std::move(tokenConfig)); + m_config.m_multi_character_tokens.clear(); -SimpleLexer::SimpleLexer(IParserLineStream* stream, Config config) - : AbstractLexer(stream), - m_config(std::move(config)), - m_check_for_multi_character_tokens(false), - m_last_line(1) -{ - for (auto tokenConfig : m_config.m_multi_character_tokens) - AddMultiCharacterTokenConfigToLookup(std::move(tokenConfig)); - m_config.m_multi_character_tokens.clear(); - - // If reading floating point numbers then must be reading integers - assert(m_config.m_read_floating_point_numbers == false || m_config.m_read_floating_point_numbers == m_config.m_read_integer_numbers); + // If reading floating point numbers then must be reading integers + assert(m_config.m_read_floating_point_numbers == false || m_config.m_read_floating_point_numbers == m_config.m_read_integer_numbers); } -void SimpleLexer::AddMultiCharacterTokenConfigToLookup(Config::MultiCharacterToken tokenConfig) -{ - if (tokenConfig.m_value.empty()) - return; +void SimpleLexer::AddMultiCharacterTokenConfigToLookup(Config::MultiCharacterToken tokenConfig) { + if (tokenConfig.m_value.empty()) + return; - m_check_for_multi_character_tokens = true; - const auto firstCharacterValue = static_cast<uint8_t>(tokenConfig.m_value[0]); + m_check_for_multi_character_tokens = true; + const auto firstCharacterValue = static_cast<uint8_t>(tokenConfig.m_value[0]); - if (m_multi_character_token_lookup[firstCharacterValue]) - { - auto* currentEntry = m_multi_character_token_lookup[firstCharacterValue].get(); - while (currentEntry->m_next) - currentEntry = currentEntry->m_next.get(); + if (m_multi_character_token_lookup[firstCharacterValue]) { + auto *currentEntry = m_multi_character_token_lookup[firstCharacterValue].get(); + while (currentEntry->m_next) + currentEntry = currentEntry->m_next.get(); - currentEntry->m_next = std::make_unique<MultiCharacterTokenLookupEntry>(tokenConfig.m_id, std::move(tokenConfig.m_value)); - } - else - { - m_multi_character_token_lookup[firstCharacterValue] = std::make_unique<MultiCharacterTokenLookupEntry>(tokenConfig.m_id, std::move(tokenConfig.m_value)); - } + currentEntry->m_next = std::make_unique<MultiCharacterTokenLookupEntry>(tokenConfig.m_id, std::move(tokenConfig.m_value)); + } else { + m_multi_character_token_lookup[firstCharacterValue] = std::make_unique<MultiCharacterTokenLookupEntry>(tokenConfig.m_id, std::move(tokenConfig.m_value)); + } } -bool SimpleLexer::ReadMultiCharacterToken(const MultiCharacterTokenLookupEntry* multiTokenLookup) -{ - const auto& currentLine = CurrentLine(); - assert(m_current_line_offset >= 1); - assert(multiTokenLookup); - assert(!multiTokenLookup->m_value.empty()); - assert(currentLine.m_line[m_current_line_offset - 1] == multiTokenLookup->m_value[0]); - - const char* linePos = ¤tLine.m_line[m_current_line_offset - 1]; - - for (const auto c : multiTokenLookup->m_value) - { - if (!*linePos || *linePos != c) - return false; - linePos++; - } +bool SimpleLexer::ReadMultiCharacterToken(const MultiCharacterTokenLookupEntry *multiTokenLookup) { + const auto ¤tLine = CurrentLine(); + assert(m_current_line_offset >= 1); + assert(multiTokenLookup); + assert(!multiTokenLookup->m_value.empty()); + assert(currentLine.m_line[m_current_line_offset - 1] == multiTokenLookup->m_value[0]); + + const char *linePos = ¤tLine.m_line[m_current_line_offset - 1]; - m_current_line_offset = m_current_line_offset - 1 + multiTokenLookup->m_value.size(); - return true; + for (const auto c : multiTokenLookup->m_value) { + if (!*linePos || *linePos != c) + return false; + linePos++; + } + + m_current_line_offset = m_current_line_offset - 1 + multiTokenLookup->m_value.size(); + return true; } -SimpleParserValue SimpleLexer::GetNextToken() -{ - auto c = PeekChar(); - const auto nextCharPos = GetNextCharacterPos(); - if (m_config.m_emit_new_line_tokens && nextCharPos.m_line > m_last_line) - { - m_last_line++; - return SimpleParserValue::NewLine(GetPreviousCharacterPos()); - } +SimpleParserValue SimpleLexer::GetNextToken() { + auto c = PeekChar(); + const auto nextCharPos = GetNextCharacterPos(); + if (m_config.m_emit_new_line_tokens && nextCharPos.m_line > m_last_line) { + m_last_line++; + return SimpleParserValue::NewLine(GetPreviousCharacterPos()); + } - while (isspace(c)) - { - if (m_config.m_emit_new_line_tokens && c == '\n') - return SimpleParserValue::NewLine(GetPreviousCharacterPos()); + while (isspace(c)) { + if (m_config.m_emit_new_line_tokens && c == '\n') + return SimpleParserValue::NewLine(GetPreviousCharacterPos()); - NextChar(); - c = PeekChar(); - } + NextChar(); + c = PeekChar(); + } - const auto pos = GetNextCharacterPos(); - if (m_config.m_emit_new_line_tokens && pos.m_line > m_last_line) - { - m_last_line++; - return SimpleParserValue::NewLine(GetPreviousCharacterPos()); - } + const auto pos = GetNextCharacterPos(); + if (m_config.m_emit_new_line_tokens && pos.m_line > m_last_line) { + m_last_line++; + return SimpleParserValue::NewLine(GetPreviousCharacterPos()); + } - c = NextChar(); + c = NextChar(); - if (c == EOF) - return SimpleParserValue::EndOfFile(TokenPos()); + if (c == EOF) + return SimpleParserValue::EndOfFile(TokenPos()); - if (m_check_for_multi_character_tokens) - { - const auto* multiTokenLookup = m_multi_character_token_lookup[static_cast<uint8_t>(c)].get(); - while (multiTokenLookup) - { - if (ReadMultiCharacterToken(multiTokenLookup)) - return SimpleParserValue::MultiCharacter(pos, multiTokenLookup->m_id); + if (m_check_for_multi_character_tokens) { + const auto *multiTokenLookup = m_multi_character_token_lookup[static_cast<uint8_t>(c)].get(); + while (multiTokenLookup) { + if (ReadMultiCharacterToken(multiTokenLookup)) + return SimpleParserValue::MultiCharacter(pos, multiTokenLookup->m_id); - multiTokenLookup = multiTokenLookup->m_next.get(); - } + multiTokenLookup = multiTokenLookup->m_next.get(); } + } - if (m_config.m_read_strings && c == '\"') - return SimpleParserValue::String(pos, new std::string(m_config.m_string_escape_sequences ? ReadStringWithEscapeSequences() : ReadString())); + if (m_config.m_read_strings && c == '\"') + return SimpleParserValue::String(pos, new std::string(m_config.m_string_escape_sequences ? ReadStringWithEscapeSequences() : ReadString())); - if (m_config.m_read_integer_numbers && (isdigit(c) || (c == '+' || c == '-' || (m_config.m_read_floating_point_numbers && c == '.')) && isdigit(PeekChar()))) - { - bool hasSignPrefix; - int integerValue; + if (m_config.m_read_integer_numbers && + (isdigit(c) || (c == '+' || c == '-' || (m_config.m_read_floating_point_numbers && c == '.')) && isdigit(PeekChar()))) { + bool hasSignPrefix; + int integerValue; - if(m_config.m_read_floating_point_numbers) - { - bool isFloatingPointValue; - double floatingPointValue; + if (m_config.m_read_floating_point_numbers) { + bool isFloatingPointValue; + double floatingPointValue; - ReadNumber(isFloatingPointValue, hasSignPrefix, floatingPointValue, integerValue); + ReadNumber(isFloatingPointValue, hasSignPrefix, floatingPointValue, integerValue); - if (isFloatingPointValue) - return SimpleParserValue::FloatingPoint(pos, floatingPointValue, hasSignPrefix); + if (isFloatingPointValue) + return SimpleParserValue::FloatingPoint(pos, floatingPointValue, hasSignPrefix); - return SimpleParserValue::Integer(pos, integerValue, hasSignPrefix); - } - - ReadNumber(hasSignPrefix, integerValue); - return SimpleParserValue::Integer(pos, integerValue, hasSignPrefix); + return SimpleParserValue::Integer(pos, integerValue, hasSignPrefix); } - if (isalpha(c) || c == '_') - { - auto identifier = ReadIdentifier(); + ReadNumber(hasSignPrefix, integerValue); + return SimpleParserValue::Integer(pos, integerValue, hasSignPrefix); + } - return SimpleParserValue::Identifier(pos, new std::string(std::move(identifier))); - } + if (isalpha(c) || c == '_') { + auto identifier = ReadIdentifier(); + + return SimpleParserValue::Identifier(pos, new std::string(std::move(identifier))); + } - return SimpleParserValue::Character(pos, static_cast<char>(c)); + return SimpleParserValue::Character(pos, static_cast<char>(c)); } diff --git a/src/Parser/Parsing/Simple/SimpleLexer.h b/src/Parser/Parsing/Simple/SimpleLexer.h index fd051f2d4..77b0eae69 100644 --- a/src/Parser/Parsing/Simple/SimpleLexer.h +++ b/src/Parser/Parsing/Simple/SimpleLexer.h @@ -4,55 +4,51 @@ #include <limits> #include <memory> -#include "SimpleParserValue.h" #include "Parsing/Impl/AbstractLexer.h" +#include "SimpleParserValue.h" -class SimpleLexer : public AbstractLexer<SimpleParserValue> -{ +class SimpleLexer : public AbstractLexer<SimpleParserValue> { public: - class Config - { + class Config { + public: + class MultiCharacterToken { public: - class MultiCharacterToken - { - public: - int m_id; - std::string m_value; - - MultiCharacterToken(int id, std::string value); - }; - - bool m_emit_new_line_tokens = false; - bool m_read_strings = true; - bool m_string_escape_sequences = false; - bool m_read_integer_numbers = true; - bool m_read_floating_point_numbers = true; - std::vector<MultiCharacterToken> m_multi_character_tokens; + int m_id; + std::string m_value; + + MultiCharacterToken(int id, std::string value); }; + bool m_emit_new_line_tokens = false; + bool m_read_strings = true; + bool m_string_escape_sequences = false; + bool m_read_integer_numbers = true; + bool m_read_floating_point_numbers = true; + std::vector<MultiCharacterToken> m_multi_character_tokens; + }; + protected: - class MultiCharacterTokenLookupEntry - { - public: - int m_id; - std::string m_value; - std::unique_ptr<MultiCharacterTokenLookupEntry> m_next; + class MultiCharacterTokenLookupEntry { + public: + int m_id; + std::string m_value; + std::unique_ptr<MultiCharacterTokenLookupEntry> m_next; - MultiCharacterTokenLookupEntry(int id, std::string value); - }; + MultiCharacterTokenLookupEntry(int id, std::string value); + }; - Config m_config; - bool m_check_for_multi_character_tokens; - int m_last_line; + Config m_config; + bool m_check_for_multi_character_tokens; + int m_last_line; - std::unique_ptr<MultiCharacterTokenLookupEntry> m_multi_character_token_lookup[std::numeric_limits<uint8_t>::max() + 1]; + std::unique_ptr<MultiCharacterTokenLookupEntry> m_multi_character_token_lookup[std::numeric_limits<uint8_t>::max() + 1]; - void AddMultiCharacterTokenConfigToLookup(Config::MultiCharacterToken tokenConfig); - bool ReadMultiCharacterToken(const MultiCharacterTokenLookupEntry* multiTokenLookup); + void AddMultiCharacterTokenConfigToLookup(Config::MultiCharacterToken tokenConfig); + bool ReadMultiCharacterToken(const MultiCharacterTokenLookupEntry *multiTokenLookup); - SimpleParserValue GetNextToken() override; + SimpleParserValue GetNextToken() override; public: - explicit SimpleLexer(IParserLineStream* stream); - SimpleLexer(IParserLineStream* stream, Config config); + explicit SimpleLexer(IParserLineStream *stream); + SimpleLexer(IParserLineStream *stream, Config config); }; \ No newline at end of file diff --git a/src/Parser/Parsing/Simple/SimpleParserValue.cpp b/src/Parser/Parsing/Simple/SimpleParserValue.cpp index 3acdac5f0..930d74f4f 100644 --- a/src/Parser/Parsing/Simple/SimpleParserValue.cpp +++ b/src/Parser/Parsing/Simple/SimpleParserValue.cpp @@ -2,178 +2,140 @@ #include <cassert> -SimpleParserValue SimpleParserValue::Invalid(const TokenPos pos) -{ - SimpleParserValue pv(pos, SimpleParserValueType::INVALID); - return pv; +SimpleParserValue SimpleParserValue::Invalid(const TokenPos pos) { + SimpleParserValue pv(pos, SimpleParserValueType::INVALID); + return pv; } -SimpleParserValue SimpleParserValue::EndOfFile(const TokenPos pos) -{ - SimpleParserValue pv(pos, SimpleParserValueType::END_OF_FILE); - return pv; +SimpleParserValue SimpleParserValue::EndOfFile(const TokenPos pos) { + SimpleParserValue pv(pos, SimpleParserValueType::END_OF_FILE); + return pv; } -SimpleParserValue SimpleParserValue::NewLine(const TokenPos pos) -{ - SimpleParserValue pv(pos, SimpleParserValueType::NEW_LINE); - return pv; +SimpleParserValue SimpleParserValue::NewLine(const TokenPos pos) { + SimpleParserValue pv(pos, SimpleParserValueType::NEW_LINE); + return pv; } -SimpleParserValue SimpleParserValue::Character(const TokenPos pos, const char c) -{ - SimpleParserValue pv(pos, SimpleParserValueType::CHARACTER); - pv.m_value.char_value = c; - return pv; +SimpleParserValue SimpleParserValue::Character(const TokenPos pos, const char c) { + SimpleParserValue pv(pos, SimpleParserValueType::CHARACTER); + pv.m_value.char_value = c; + return pv; } -SimpleParserValue SimpleParserValue::MultiCharacter(const TokenPos pos, const int multiCharacterSequenceId) -{ - SimpleParserValue pv(pos, SimpleParserValueType::MULTI_CHARACTER); - pv.m_value.multi_character_sequence_id = multiCharacterSequenceId; - return pv; +SimpleParserValue SimpleParserValue::MultiCharacter(const TokenPos pos, const int multiCharacterSequenceId) { + SimpleParserValue pv(pos, SimpleParserValueType::MULTI_CHARACTER); + pv.m_value.multi_character_sequence_id = multiCharacterSequenceId; + return pv; } -SimpleParserValue SimpleParserValue::Integer(const TokenPos pos, const int value) -{ - SimpleParserValue pv(pos, SimpleParserValueType::INTEGER); - pv.m_value.int_value = value; - return pv; +SimpleParserValue SimpleParserValue::Integer(const TokenPos pos, const int value) { + SimpleParserValue pv(pos, SimpleParserValueType::INTEGER); + pv.m_value.int_value = value; + return pv; } -SimpleParserValue SimpleParserValue::Integer(const TokenPos pos, const int value, const bool hasSignPrefix) -{ - SimpleParserValue pv(pos, SimpleParserValueType::INTEGER); - pv.m_value.int_value = value; - pv.m_has_sign_prefix = hasSignPrefix; - return pv; +SimpleParserValue SimpleParserValue::Integer(const TokenPos pos, const int value, const bool hasSignPrefix) { + SimpleParserValue pv(pos, SimpleParserValueType::INTEGER); + pv.m_value.int_value = value; + pv.m_has_sign_prefix = hasSignPrefix; + return pv; } -SimpleParserValue SimpleParserValue::FloatingPoint(const TokenPos pos, const double value) -{ - SimpleParserValue pv(pos, SimpleParserValueType::FLOATING_POINT); - pv.m_value.double_value = value; - return pv; +SimpleParserValue SimpleParserValue::FloatingPoint(const TokenPos pos, const double value) { + SimpleParserValue pv(pos, SimpleParserValueType::FLOATING_POINT); + pv.m_value.double_value = value; + return pv; } -SimpleParserValue SimpleParserValue::FloatingPoint(const TokenPos pos, const double value, const bool hasSignPrefix) -{ - SimpleParserValue pv(pos, SimpleParserValueType::FLOATING_POINT); - pv.m_value.double_value = value; - pv.m_has_sign_prefix = hasSignPrefix; - return pv; +SimpleParserValue SimpleParserValue::FloatingPoint(const TokenPos pos, const double value, const bool hasSignPrefix) { + SimpleParserValue pv(pos, SimpleParserValueType::FLOATING_POINT); + pv.m_value.double_value = value; + pv.m_has_sign_prefix = hasSignPrefix; + return pv; } -SimpleParserValue SimpleParserValue::String(const TokenPos pos, std::string* stringValue) -{ - SimpleParserValue pv(pos, SimpleParserValueType::STRING); - pv.m_value.string_value = stringValue; - return pv; +SimpleParserValue SimpleParserValue::String(const TokenPos pos, std::string *stringValue) { + SimpleParserValue pv(pos, SimpleParserValueType::STRING); + pv.m_value.string_value = stringValue; + return pv; } -SimpleParserValue SimpleParserValue::Identifier(const TokenPos pos, std::string* identifier) -{ - SimpleParserValue pv(pos, SimpleParserValueType::IDENTIFIER); - pv.m_value.string_value = identifier; - pv.m_hash = std::hash<std::string>()(*identifier); - return pv; +SimpleParserValue SimpleParserValue::Identifier(const TokenPos pos, std::string *identifier) { + SimpleParserValue pv(pos, SimpleParserValueType::IDENTIFIER); + pv.m_value.string_value = identifier; + pv.m_hash = std::hash<std::string>()(*identifier); + return pv; } SimpleParserValue::SimpleParserValue(const TokenPos pos, const SimpleParserValueType type) - : m_pos(pos), - m_type(type), - m_hash(0), - m_has_sign_prefix(false), - m_value{} -{ -} + : m_pos(pos), m_type(type), m_hash(0), m_has_sign_prefix(false), m_value{} {} -SimpleParserValue::~SimpleParserValue() -{ - switch (m_type) - { - case SimpleParserValueType::STRING: - case SimpleParserValueType::IDENTIFIER: - delete m_value.string_value; - break; +SimpleParserValue::~SimpleParserValue() { + switch (m_type) { + case SimpleParserValueType::STRING: + case SimpleParserValueType::IDENTIFIER: + delete m_value.string_value; + break; - default: - break; - } + default: + break; + } - m_value = ValueType(); + m_value = ValueType(); } -SimpleParserValue::SimpleParserValue(SimpleParserValue&& other) noexcept - : m_pos(other.m_pos), - m_type(other.m_type), - m_hash(other.m_hash), - m_has_sign_prefix(other.m_has_sign_prefix), - m_value(other.m_value) -{ - other.m_value = ValueType(); +SimpleParserValue::SimpleParserValue(SimpleParserValue &&other) noexcept + : m_pos(other.m_pos), m_type(other.m_type), m_hash(other.m_hash), m_has_sign_prefix(other.m_has_sign_prefix), m_value(other.m_value) { + other.m_value = ValueType(); } -SimpleParserValue& SimpleParserValue::operator=(SimpleParserValue&& other) noexcept -{ - m_pos = other.m_pos; - m_type = other.m_type; - m_value = other.m_value; - m_hash = other.m_hash; - m_has_sign_prefix = other.m_has_sign_prefix; - other.m_value = ValueType(); +SimpleParserValue &SimpleParserValue::operator=(SimpleParserValue &&other) noexcept { + m_pos = other.m_pos; + m_type = other.m_type; + m_value = other.m_value; + m_hash = other.m_hash; + m_has_sign_prefix = other.m_has_sign_prefix; + other.m_value = ValueType(); - return *this; + return *this; } -bool SimpleParserValue::IsEof() const -{ - return m_type == SimpleParserValueType::END_OF_FILE; -} +bool SimpleParserValue::IsEof() const { return m_type == SimpleParserValueType::END_OF_FILE; } -const TokenPos& SimpleParserValue::GetPos() const -{ - return m_pos; -} +const TokenPos &SimpleParserValue::GetPos() const { return m_pos; } -char SimpleParserValue::CharacterValue() const -{ - assert(m_type == SimpleParserValueType::CHARACTER); - return m_value.char_value; +char SimpleParserValue::CharacterValue() const { + assert(m_type == SimpleParserValueType::CHARACTER); + return m_value.char_value; } -int SimpleParserValue::MultiCharacterValue() const -{ - assert(m_type == SimpleParserValueType::MULTI_CHARACTER); - return m_value.multi_character_sequence_id; +int SimpleParserValue::MultiCharacterValue() const { + assert(m_type == SimpleParserValueType::MULTI_CHARACTER); + return m_value.multi_character_sequence_id; } -int SimpleParserValue::IntegerValue() const -{ - assert(m_type == SimpleParserValueType::INTEGER); - return m_value.int_value; +int SimpleParserValue::IntegerValue() const { + assert(m_type == SimpleParserValueType::INTEGER); + return m_value.int_value; } -double SimpleParserValue::FloatingPointValue() const -{ - assert(m_type == SimpleParserValueType::FLOATING_POINT); - return m_value.double_value; +double SimpleParserValue::FloatingPointValue() const { + assert(m_type == SimpleParserValueType::FLOATING_POINT); + return m_value.double_value; } -std::string& SimpleParserValue::StringValue() const -{ - assert(m_type == SimpleParserValueType::STRING); - return *m_value.string_value; +std::string &SimpleParserValue::StringValue() const { + assert(m_type == SimpleParserValueType::STRING); + return *m_value.string_value; } -std::string& SimpleParserValue::IdentifierValue() const -{ - assert(m_type == SimpleParserValueType::IDENTIFIER); - return *m_value.string_value; +std::string &SimpleParserValue::IdentifierValue() const { + assert(m_type == SimpleParserValueType::IDENTIFIER); + return *m_value.string_value; } -size_t SimpleParserValue::IdentifierHash() const -{ - assert(m_type == SimpleParserValueType::IDENTIFIER); - return m_hash; +size_t SimpleParserValue::IdentifierHash() const { + assert(m_type == SimpleParserValueType::IDENTIFIER); + return m_hash; } diff --git a/src/Parser/Parsing/Simple/SimpleParserValue.h b/src/Parser/Parsing/Simple/SimpleParserValue.h index 79cd3d408..731d40e45 100644 --- a/src/Parser/Parsing/Simple/SimpleParserValue.h +++ b/src/Parser/Parsing/Simple/SimpleParserValue.h @@ -3,76 +3,73 @@ #include <string> #include "Parsing/IParserValue.h" -#include "Utils/ClassUtils.h" #include "Parsing/TokenPos.h" +#include "Utils/ClassUtils.h" -enum class SimpleParserValueType -{ - // Meta tokens - INVALID, - END_OF_FILE, - NEW_LINE, +enum class SimpleParserValueType { + // Meta tokens + INVALID, + END_OF_FILE, + NEW_LINE, - // Character sequences - CHARACTER, - MULTI_CHARACTER, + // Character sequences + CHARACTER, + MULTI_CHARACTER, - // Generic token types - INTEGER, - FLOATING_POINT, - STRING, - IDENTIFIER, + // Generic token types + INTEGER, + FLOATING_POINT, + STRING, + IDENTIFIER, - // End - MAX + // End + MAX }; -class SimpleParserValue final : public IParserValue -{ +class SimpleParserValue final : public IParserValue { public: - TokenPos m_pos; - SimpleParserValueType m_type; - size_t m_hash; - bool m_has_sign_prefix; - union ValueType - { - char char_value; - int int_value; - int multi_character_sequence_id; - double double_value; - std::string* string_value; - } m_value; + TokenPos m_pos; + SimpleParserValueType m_type; + size_t m_hash; + bool m_has_sign_prefix; + union ValueType { + char char_value; + int int_value; + int multi_character_sequence_id; + double double_value; + std::string *string_value; + } m_value; - static SimpleParserValue Invalid(TokenPos pos); - static SimpleParserValue EndOfFile(TokenPos pos); - static SimpleParserValue NewLine(TokenPos pos); - static SimpleParserValue Character(TokenPos pos, char c); - static SimpleParserValue MultiCharacter(TokenPos pos, int multiCharacterSequenceId); - static SimpleParserValue Integer(TokenPos pos, int value); - static SimpleParserValue Integer(TokenPos pos, int value, bool hasSignPrefix); - static SimpleParserValue FloatingPoint(TokenPos pos, double value); - static SimpleParserValue FloatingPoint(TokenPos pos, double value, bool hasSignPrefix); - static SimpleParserValue String(TokenPos pos, std::string* stringValue); - static SimpleParserValue Identifier(TokenPos pos, std::string* identifier); + static SimpleParserValue Invalid(TokenPos pos); + static SimpleParserValue EndOfFile(TokenPos pos); + static SimpleParserValue NewLine(TokenPos pos); + static SimpleParserValue Character(TokenPos pos, char c); + static SimpleParserValue MultiCharacter(TokenPos pos, int multiCharacterSequenceId); + static SimpleParserValue Integer(TokenPos pos, int value); + static SimpleParserValue Integer(TokenPos pos, int value, bool hasSignPrefix); + static SimpleParserValue FloatingPoint(TokenPos pos, double value); + static SimpleParserValue FloatingPoint(TokenPos pos, double value, bool hasSignPrefix); + static SimpleParserValue String(TokenPos pos, std::string *stringValue); + static SimpleParserValue Identifier(TokenPos pos, std::string *identifier); private: - SimpleParserValue(TokenPos pos, SimpleParserValueType type); + SimpleParserValue(TokenPos pos, SimpleParserValueType type); public: - ~SimpleParserValue() override; - SimpleParserValue(const SimpleParserValue& other) = delete; - SimpleParserValue(SimpleParserValue&& other) noexcept; - SimpleParserValue& operator=(const SimpleParserValue& other) = delete; - SimpleParserValue& operator=(SimpleParserValue&& other) noexcept; + ~SimpleParserValue() override; + SimpleParserValue(const SimpleParserValue &other) = delete; + SimpleParserValue(SimpleParserValue &&other) noexcept; + SimpleParserValue &operator=(const SimpleParserValue &other) = delete; + SimpleParserValue &operator=(SimpleParserValue &&other) noexcept; - _NODISCARD bool IsEof() const override; - _NODISCARD const TokenPos& GetPos() const override; + _NODISCARD bool IsEof() const override; + _NODISCARD const TokenPos &GetPos() const override; - _NODISCARD char CharacterValue() const; - _NODISCARD int MultiCharacterValue() const; - _NODISCARD int IntegerValue() const; - _NODISCARD double FloatingPointValue() const; - _NODISCARD std::string& StringValue() const; - _NODISCARD std::string& IdentifierValue() const; - _NODISCARD size_t IdentifierHash() const; + _NODISCARD char CharacterValue() const; + _NODISCARD int MultiCharacterValue() const; + _NODISCARD int IntegerValue() const; + _NODISCARD double FloatingPointValue() const; + _NODISCARD std::string &StringValue() const; + _NODISCARD std::string &IdentifierValue() const; + _NODISCARD size_t IdentifierHash() const; }; diff --git a/src/Parser/Parsing/TokenPos.cpp b/src/Parser/Parsing/TokenPos.cpp index fe9d9c5dd..efef223e0 100644 --- a/src/Parser/Parsing/TokenPos.cpp +++ b/src/Parser/Parsing/TokenPos.cpp @@ -2,16 +2,6 @@ const std::string TokenPos::EMPTY_FILENAME; -TokenPos::TokenPos() - : m_filename(EMPTY_FILENAME), - m_line(1), - m_column(1) -{ -} +TokenPos::TokenPos() : m_filename(EMPTY_FILENAME), m_line(1), m_column(1) {} -TokenPos::TokenPos(const std::string& filename, const int line, const int column) - : m_filename(filename), - m_line(line), - m_column(column) -{ -} +TokenPos::TokenPos(const std::string &filename, const int line, const int column) : m_filename(filename), m_line(line), m_column(column) {} diff --git a/src/Parser/Parsing/TokenPos.h b/src/Parser/Parsing/TokenPos.h index 6035cc982..b35b69b12 100644 --- a/src/Parser/Parsing/TokenPos.h +++ b/src/Parser/Parsing/TokenPos.h @@ -1,17 +1,16 @@ #pragma once -#include <string> #include <functional> +#include <string> -class TokenPos -{ - static const std::string EMPTY_FILENAME; +class TokenPos { + static const std::string EMPTY_FILENAME; public: - std::reference_wrapper<const std::string> m_filename; - int m_line; - int m_column; + std::reference_wrapper<const std::string> m_filename; + int m_line; + int m_column; - TokenPos(); - TokenPos(const std::string& filename, int line, int column); + TokenPos(); + TokenPos(const std::string &filename, int line, int column); }; diff --git a/src/RawTemplater/RawTemplater.cpp b/src/RawTemplater/RawTemplater.cpp index 1f7300394..9c8d4aef9 100644 --- a/src/RawTemplater/RawTemplater.cpp +++ b/src/RawTemplater/RawTemplater.cpp @@ -1,90 +1,73 @@ #include "RawTemplater.h" +#include <filesystem> #include <fstream> #include <iostream> -#include <filesystem> #include "RawTemplaterArguments.h" #include "Templating/Templater.h" namespace fs = std::filesystem; -class RawTemplater::Impl -{ - RawTemplaterArguments m_args; +class RawTemplater::Impl { + RawTemplaterArguments m_args; - bool m_write_build_log; - std::ofstream m_build_log_file; + bool m_write_build_log; + std::ofstream m_build_log_file; - _NODISCARD bool GenerateCode(const std::string& filename) - { - std::ifstream file(filename, std::ios::in | std::ios::binary); - if (!file.is_open()) - { - std::cerr << "Failed to open file \"" << filename << "\"\n"; - return false; - } + _NODISCARD bool GenerateCode(const std::string &filename) { + std::ifstream file(filename, std::ios::in | std::ios::binary); + if (!file.is_open()) { + std::cerr << "Failed to open file \"" << filename << "\"\n"; + return false; + } - templating::Templater templater(file, filename); - if (m_write_build_log) - templater.SetBuildLogFile(&m_build_log_file); - if (!m_args.m_output_directory.empty()) - return templater.TemplateToDirectory(m_args.m_output_directory); + templating::Templater templater(file, filename); + if (m_write_build_log) + templater.SetBuildLogFile(&m_build_log_file); + if (!m_args.m_output_directory.empty()) + return templater.TemplateToDirectory(m_args.m_output_directory); - const fs::path filePath(filename); - const auto parentPath = filePath.parent_path(); + const fs::path filePath(filename); + const auto parentPath = filePath.parent_path(); - return templater.TemplateToDirectory(parentPath.string()); - } + return templater.TemplateToDirectory(parentPath.string()); + } public: - Impl() - : m_write_build_log(false) - { + Impl() : m_write_build_log(false) {} + + int Run(const int argc, const char **argv) { + if (!m_args.Parse(argc, argv)) + return 1; + + if (!m_args.m_build_log_file.empty()) { + fs::path p = fs::path(m_args.m_build_log_file).parent_path(); + if (!p.empty()) + fs::create_directories(p); + + m_build_log_file = std::ofstream(m_args.m_build_log_file, std::ios::out | std::ios::binary); + if (!m_build_log_file.is_open()) { + std::cerr << "Failed to open build log file \"" << m_args.m_build_log_file << "\"\n"; + return false; + } + m_write_build_log = true; } - int Run(const int argc, const char** argv) - { - if (!m_args.Parse(argc, argv)) - return 1; - - if (!m_args.m_build_log_file.empty()) - { - fs::path p = fs::path(m_args.m_build_log_file).parent_path(); - if (!p.empty()) - fs::create_directories(p); - - m_build_log_file = std::ofstream(m_args.m_build_log_file, std::ios::out | std::ios::binary); - if (!m_build_log_file.is_open()) - { - std::cerr << "Failed to open build log file \"" << m_args.m_build_log_file << "\"\n"; - return false; - } - m_write_build_log = true; - } - - for (const auto& inputFile : m_args.m_input_files) - { - if (!GenerateCode(inputFile)) - return 1; - } - - return 0; + for (const auto &inputFile : m_args.m_input_files) { + if (!GenerateCode(inputFile)) + return 1; } + + return 0; + } }; -RawTemplater::RawTemplater() -{ - m_impl = new Impl(); -} +RawTemplater::RawTemplater() { m_impl = new Impl(); } -RawTemplater::~RawTemplater() -{ - delete m_impl; - m_impl = nullptr; +RawTemplater::~RawTemplater() { + delete m_impl; + m_impl = nullptr; } -int RawTemplater::Run(const int argc, const char** argv) const -{ - return m_impl->Run(argc, argv); -} +int RawTemplater::Run(const int argc, const char **argv) const { return m_impl->Run(argc, argv); } diff --git a/src/RawTemplater/RawTemplater.h b/src/RawTemplater/RawTemplater.h index c068f3c9f..85846c2a3 100644 --- a/src/RawTemplater/RawTemplater.h +++ b/src/RawTemplater/RawTemplater.h @@ -1,17 +1,16 @@ #pragma once -class RawTemplater -{ - class Impl; - Impl* m_impl; +class RawTemplater { + class Impl; + Impl *m_impl; public: - RawTemplater(); - ~RawTemplater(); - RawTemplater(const RawTemplater& other) = delete; - RawTemplater(RawTemplater&& other) noexcept = default; - RawTemplater& operator=(const RawTemplater& other) = delete; - RawTemplater& operator=(RawTemplater&& other) noexcept = default; + RawTemplater(); + ~RawTemplater(); + RawTemplater(const RawTemplater &other) = delete; + RawTemplater(RawTemplater &&other) noexcept = default; + RawTemplater &operator=(const RawTemplater &other) = delete; + RawTemplater &operator=(RawTemplater &&other) noexcept = default; - int Run(int argc, const char** argv) const; + int Run(int argc, const char **argv) const; }; diff --git a/src/RawTemplater/RawTemplaterArguments.cpp b/src/RawTemplater/RawTemplaterArguments.cpp index 2ad5b6f48..b076ff498 100644 --- a/src/RawTemplater/RawTemplaterArguments.cpp +++ b/src/RawTemplater/RawTemplaterArguments.cpp @@ -3,114 +3,89 @@ #include "Utils/Arguments/CommandLineOption.h" #include "Utils/Arguments/UsageInformation.h" -const CommandLineOption* const OPTION_HELP = CommandLineOption::Builder::Create() - .WithShortName("?") - .WithLongName("help") - .WithDescription("Displays usage information.") - .Build(); - -const CommandLineOption* const OPTION_VERBOSE = CommandLineOption::Builder::Create() - .WithShortName("v") - .WithLongName("verbose") - .WithDescription("Outputs a lot more and more detailed messages.") - .Build(); - -const CommandLineOption* const OPTION_OUTPUT_FOLDER = CommandLineOption::Builder::Create() - .WithShortName("o") - .WithLongName("output") - .WithDescription("Specify the folder to save the generated files. Defaults to the current directory.") - .WithParameter("outputPath") - .Build(); +const CommandLineOption *const OPTION_HELP = + CommandLineOption::Builder::Create().WithShortName("?").WithLongName("help").WithDescription("Displays usage information.").Build(); + +const CommandLineOption *const OPTION_VERBOSE = + CommandLineOption::Builder::Create().WithShortName("v").WithLongName("verbose").WithDescription("Outputs a lot more and more detailed messages.").Build(); + +const CommandLineOption *const OPTION_OUTPUT_FOLDER = CommandLineOption::Builder::Create() + .WithShortName("o") + .WithLongName("output") + .WithDescription("Specify the folder to save the generated files. Defaults to the current directory.") + .WithParameter("outputPath") + .Build(); -const CommandLineOption* const OPTION_BUILD_LOG = CommandLineOption::Builder::Create() +const CommandLineOption *const OPTION_BUILD_LOG = CommandLineOption::Builder::Create() .WithLongName("build-log") .WithDescription("Specify a file to write a build log to.") .WithParameter("logFilePath") .Build(); -const CommandLineOption* const OPTION_DEFINE = CommandLineOption::Builder::Create() - .WithShortName("d") - .WithLongName("define") - .WithDescription("Adds a define for the templating process. Can be of format define or define=value.") - .WithParameter("defineValue") - .Reusable() - .Build(); - -const CommandLineOption* const COMMAND_LINE_OPTIONS[] -{ - OPTION_HELP, - OPTION_VERBOSE, - OPTION_OUTPUT_FOLDER, - OPTION_BUILD_LOG, - OPTION_DEFINE -}; - -RawTemplaterArguments::RawTemplaterArguments() - : m_argument_parser(COMMAND_LINE_OPTIONS, std::extent_v<decltype(COMMAND_LINE_OPTIONS)>), - m_verbose(false) -{ -} +const CommandLineOption *const OPTION_DEFINE = CommandLineOption::Builder::Create() + .WithShortName("d") + .WithLongName("define") + .WithDescription("Adds a define for the templating process. Can be of format define or define=value.") + .WithParameter("defineValue") + .Reusable() + .Build(); -void RawTemplaterArguments::PrintUsage() -{ - UsageInformation usage("RawTemplater.exe"); +const CommandLineOption *const COMMAND_LINE_OPTIONS[]{OPTION_HELP, OPTION_VERBOSE, OPTION_OUTPUT_FOLDER, OPTION_BUILD_LOG, OPTION_DEFINE}; - for (const auto* commandLineOption : COMMAND_LINE_OPTIONS) - { - usage.AddCommandLineOption(commandLineOption); - } +RawTemplaterArguments::RawTemplaterArguments() : m_argument_parser(COMMAND_LINE_OPTIONS, std::extent_v<decltype(COMMAND_LINE_OPTIONS)>), m_verbose(false) {} - usage.Print(); -} +void RawTemplaterArguments::PrintUsage() { + UsageInformation usage("RawTemplater.exe"); -bool RawTemplaterArguments::Parse(const int argc, const char** argv) -{ - if (!m_argument_parser.ParseArguments(argc - 1, &argv[1])) - { - PrintUsage(); - return false; - } - - // Check if the user requested help - if (m_argument_parser.IsOptionSpecified(OPTION_HELP)) - { - PrintUsage(); - return false; - } + for (const auto *commandLineOption : COMMAND_LINE_OPTIONS) { + usage.AddCommandLineOption(commandLineOption); + } - m_input_files = m_argument_parser.GetArguments(); - if (m_input_files.empty()) - { - PrintUsage(); - return false; - } + usage.Print(); +} - // -v; --verbose - m_verbose = m_argument_parser.IsOptionSpecified(OPTION_VERBOSE); - - // -o; --output - if (m_argument_parser.IsOptionSpecified(OPTION_OUTPUT_FOLDER)) - m_output_directory = m_argument_parser.GetValueForOption(OPTION_OUTPUT_FOLDER); - else - m_output_directory = "."; - - // --build-log - if (m_argument_parser.IsOptionSpecified(OPTION_BUILD_LOG)) - m_build_log_file = m_argument_parser.GetValueForOption(OPTION_BUILD_LOG); - - // -d; --define - if (m_argument_parser.IsOptionSpecified(OPTION_DEFINE)) - { - for (const auto& arg : m_argument_parser.GetParametersForOption(OPTION_DEFINE)) - { - const auto separator = arg.find('='); - - if (separator != std::string::npos) - m_defines.emplace_back(std::make_pair(arg.substr(0, separator), arg.substr(separator + 1))); - else - m_defines.emplace_back(std::make_pair(arg, std::string())); - } +bool RawTemplaterArguments::Parse(const int argc, const char **argv) { + if (!m_argument_parser.ParseArguments(argc - 1, &argv[1])) { + PrintUsage(); + return false; + } + + // Check if the user requested help + if (m_argument_parser.IsOptionSpecified(OPTION_HELP)) { + PrintUsage(); + return false; + } + + m_input_files = m_argument_parser.GetArguments(); + if (m_input_files.empty()) { + PrintUsage(); + return false; + } + + // -v; --verbose + m_verbose = m_argument_parser.IsOptionSpecified(OPTION_VERBOSE); + + // -o; --output + if (m_argument_parser.IsOptionSpecified(OPTION_OUTPUT_FOLDER)) + m_output_directory = m_argument_parser.GetValueForOption(OPTION_OUTPUT_FOLDER); + else + m_output_directory = "."; + + // --build-log + if (m_argument_parser.IsOptionSpecified(OPTION_BUILD_LOG)) + m_build_log_file = m_argument_parser.GetValueForOption(OPTION_BUILD_LOG); + + // -d; --define + if (m_argument_parser.IsOptionSpecified(OPTION_DEFINE)) { + for (const auto &arg : m_argument_parser.GetParametersForOption(OPTION_DEFINE)) { + const auto separator = arg.find('='); + + if (separator != std::string::npos) + m_defines.emplace_back(std::make_pair(arg.substr(0, separator), arg.substr(separator + 1))); + else + m_defines.emplace_back(std::make_pair(arg, std::string())); } + } - return true; + return true; } diff --git a/src/RawTemplater/RawTemplaterArguments.h b/src/RawTemplater/RawTemplaterArguments.h index 25fc3158c..3b40798d8 100644 --- a/src/RawTemplater/RawTemplaterArguments.h +++ b/src/RawTemplater/RawTemplaterArguments.h @@ -6,26 +6,25 @@ #include "Utils/Arguments/ArgumentParser.h" -class RawTemplaterArguments -{ - ArgumentParser m_argument_parser; +class RawTemplaterArguments { + ArgumentParser m_argument_parser; - /** - * \brief Prints a command line usage help text for the RawTemplater tool to stdout. - */ - static void PrintUsage(); + /** + * \brief Prints a command line usage help text for the RawTemplater tool to stdout. + */ + static void PrintUsage(); public: - bool m_verbose; + bool m_verbose; - std::vector<std::string> m_input_files; - std::string m_output_directory; + std::vector<std::string> m_input_files; + std::string m_output_directory; - std::string m_build_log_file; + std::string m_build_log_file; - std::vector<std::pair<std::string, std::string>> m_defines; + std::vector<std::pair<std::string, std::string>> m_defines; - RawTemplaterArguments(); + RawTemplaterArguments(); - bool Parse(int argc, const char** argv); + bool Parse(int argc, const char **argv); }; \ No newline at end of file diff --git a/src/RawTemplater/Templating/DirectiveEscapeStreamProxy.cpp b/src/RawTemplater/Templating/DirectiveEscapeStreamProxy.cpp index 04fbbeca0..578938a4d 100644 --- a/src/RawTemplater/Templating/DirectiveEscapeStreamProxy.cpp +++ b/src/RawTemplater/Templating/DirectiveEscapeStreamProxy.cpp @@ -2,37 +2,21 @@ using namespace templating; -DirectiveEscapeStreamProxy::DirectiveEscapeStreamProxy(IParserLineStream* stream) - : m_stream(stream) -{ -} +DirectiveEscapeStreamProxy::DirectiveEscapeStreamProxy(IParserLineStream *stream) : m_stream(stream) {} -ParserLine DirectiveEscapeStreamProxy::NextLine() -{ - auto line = m_stream->NextLine(); +ParserLine DirectiveEscapeStreamProxy::NextLine() { + auto line = m_stream->NextLine(); - if (line.m_line.size() >= 2 && line.m_line[0] == '#' && line.m_line[1] == '#') - line.m_line = line.m_line.substr(1); + if (line.m_line.size() >= 2 && line.m_line[0] == '#' && line.m_line[1] == '#') + line.m_line = line.m_line.substr(1); - return line; + return line; } -bool DirectiveEscapeStreamProxy::IncludeFile(const std::string& filename) -{ - return m_stream->IncludeFile(filename); -} +bool DirectiveEscapeStreamProxy::IncludeFile(const std::string &filename) { return m_stream->IncludeFile(filename); } -void DirectiveEscapeStreamProxy::PopCurrentFile() -{ - m_stream->PopCurrentFile(); -} +void DirectiveEscapeStreamProxy::PopCurrentFile() { m_stream->PopCurrentFile(); } -bool DirectiveEscapeStreamProxy::IsOpen() const -{ - return m_stream->IsOpen(); -} +bool DirectiveEscapeStreamProxy::IsOpen() const { return m_stream->IsOpen(); } -bool DirectiveEscapeStreamProxy::Eof() const -{ - return m_stream->Eof(); -} +bool DirectiveEscapeStreamProxy::Eof() const { return m_stream->Eof(); } diff --git a/src/RawTemplater/Templating/DirectiveEscapeStreamProxy.h b/src/RawTemplater/Templating/DirectiveEscapeStreamProxy.h index 1a2ada984..028e91394 100644 --- a/src/RawTemplater/Templating/DirectiveEscapeStreamProxy.h +++ b/src/RawTemplater/Templating/DirectiveEscapeStreamProxy.h @@ -1,20 +1,18 @@ #pragma once #include "Parsing/Impl/AbstractDirectiveStreamProxy.h" -namespace templating -{ - class DirectiveEscapeStreamProxy final : public AbstractDirectiveStreamProxy - { - public: - explicit DirectiveEscapeStreamProxy(IParserLineStream* stream); +namespace templating { +class DirectiveEscapeStreamProxy final : public AbstractDirectiveStreamProxy { +public: + explicit DirectiveEscapeStreamProxy(IParserLineStream *stream); - ParserLine NextLine() override; - bool IncludeFile(const std::string& filename) override; - void PopCurrentFile() override; - _NODISCARD bool IsOpen() const override; - _NODISCARD bool Eof() const override; + ParserLine NextLine() override; + bool IncludeFile(const std::string &filename) override; + void PopCurrentFile() override; + _NODISCARD bool IsOpen() const override; + _NODISCARD bool Eof() const override; - private: - IParserLineStream* const m_stream; - }; -} +private: + IParserLineStream *const m_stream; +}; +} // namespace templating diff --git a/src/RawTemplater/Templating/SetDefineStreamProxy.cpp b/src/RawTemplater/Templating/SetDefineStreamProxy.cpp index 5c459e0f1..5a6e71877 100644 --- a/src/RawTemplater/Templating/SetDefineStreamProxy.cpp +++ b/src/RawTemplater/Templating/SetDefineStreamProxy.cpp @@ -4,97 +4,74 @@ using namespace templating; -SetDefineStreamProxy::SetDefineStreamProxy(IParserLineStream* stream) - : m_stream(stream), - m_defines_proxy(nullptr) -{ -} +SetDefineStreamProxy::SetDefineStreamProxy(IParserLineStream *stream) : m_stream(stream), m_defines_proxy(nullptr) {} -void SetDefineStreamProxy::SetDefinesProxy(DefinesStreamProxy* definesProxy) -{ - m_defines_proxy = definesProxy; -} +void SetDefineStreamProxy::SetDefinesProxy(DefinesStreamProxy *definesProxy) { m_defines_proxy = definesProxy; } -bool SetDefineStreamProxy::MatchSetDirective(const ParserLine& line, const unsigned directiveStartPosition, const unsigned directiveEndPosition) const -{ - auto currentPosition = directiveStartPosition; +bool SetDefineStreamProxy::MatchSetDirective(const ParserLine &line, const unsigned directiveStartPosition, const unsigned directiveEndPosition) const { + auto currentPosition = directiveStartPosition; - if (directiveEndPosition - directiveStartPosition != std::char_traits<char>::length(SET_DIRECTIVE) - || !MatchString(line, currentPosition, SET_DIRECTIVE, std::char_traits<char>::length(SET_DIRECTIVE))) - { - return false; - } + if (directiveEndPosition - directiveStartPosition != std::char_traits<char>::length(SET_DIRECTIVE) || + !MatchString(line, currentPosition, SET_DIRECTIVE, std::char_traits<char>::length(SET_DIRECTIVE))) { + return false; + } - if (!SkipWhitespace(line, currentPosition)) - return false; + if (!SkipWhitespace(line, currentPosition)) + return false; - const auto nameStartPosition = currentPosition; - if (!ExtractIdentifier(line, currentPosition)) - throw ParsingException(CreatePos(line, currentPosition), "Invalid set directive."); + const auto nameStartPosition = currentPosition; + if (!ExtractIdentifier(line, currentPosition)) + throw ParsingException(CreatePos(line, currentPosition), "Invalid set directive."); - auto name = line.m_line.substr(nameStartPosition, currentPosition - nameStartPosition); + auto name = line.m_line.substr(nameStartPosition, currentPosition - nameStartPosition); - if (!SkipWhitespace(line, currentPosition)) - throw ParsingException(CreatePos(line, currentPosition), "Invalid set directive."); + if (!SkipWhitespace(line, currentPosition)) + throw ParsingException(CreatePos(line, currentPosition), "Invalid set directive."); - const auto expressionString = line.m_line.substr(currentPosition, line.m_line.size() - currentPosition); - if (expressionString.empty()) - throw ParsingException(CreatePos(line, currentPosition), "Cannot set without an expression."); + const auto expressionString = line.m_line.substr(currentPosition, line.m_line.size() - currentPosition); + if (expressionString.empty()) + throw ParsingException(CreatePos(line, currentPosition), "Cannot set without an expression."); - const auto expression = m_defines_proxy->ParseExpression(line.m_filename, line.m_line_number, expressionString); - if (!expression) - throw ParsingException(CreatePos(line, currentPosition), "Failed to parse set expression"); + const auto expression = m_defines_proxy->ParseExpression(line.m_filename, line.m_line_number, expressionString); + if (!expression) + throw ParsingException(CreatePos(line, currentPosition), "Failed to parse set expression"); - if (!expression->IsStatic()) - throw ParsingException(CreatePos(line, currentPosition), "set expression must be static"); + if (!expression->IsStatic()) + throw ParsingException(CreatePos(line, currentPosition), "set expression must be static"); - const auto value = expression->EvaluateStatic(); + const auto value = expression->EvaluateStatic(); - if (value.m_type != SimpleExpressionValue::Type::STRING) - throw ParsingException(CreatePos(line, currentPosition), "set expression must evaluate to string"); + if (value.m_type != SimpleExpressionValue::Type::STRING) + throw ParsingException(CreatePos(line, currentPosition), "set expression must evaluate to string"); - m_defines_proxy->AddDefine(DefinesStreamProxy::Define(std::move(name), *value.m_string_value)); - return true; + m_defines_proxy->AddDefine(DefinesStreamProxy::Define(std::move(name), *value.m_string_value)); + return true; } -bool SetDefineStreamProxy::MatchDirectives(const ParserLine& line) const -{ - unsigned directiveStartPos, directiveEndPos; +bool SetDefineStreamProxy::MatchDirectives(const ParserLine &line) const { + unsigned directiveStartPos, directiveEndPos; - if (!FindDirective(line, directiveStartPos, directiveEndPos)) - return false; + if (!FindDirective(line, directiveStartPos, directiveEndPos)) + return false; - directiveStartPos++; + directiveStartPos++; - return MatchSetDirective(line, directiveStartPos, directiveEndPos); + return MatchSetDirective(line, directiveStartPos, directiveEndPos); } -ParserLine SetDefineStreamProxy::NextLine() -{ - auto line = m_stream->NextLine(); +ParserLine SetDefineStreamProxy::NextLine() { + auto line = m_stream->NextLine(); - while (MatchDirectives(line)) - line = m_stream->NextLine(); + while (MatchDirectives(line)) + line = m_stream->NextLine(); - return line; + return line; } -bool SetDefineStreamProxy::IncludeFile(const std::string& filename) -{ - return m_stream->IncludeFile(filename); -} +bool SetDefineStreamProxy::IncludeFile(const std::string &filename) { return m_stream->IncludeFile(filename); } -void SetDefineStreamProxy::PopCurrentFile() -{ - m_stream->PopCurrentFile(); -} +void SetDefineStreamProxy::PopCurrentFile() { m_stream->PopCurrentFile(); } -bool SetDefineStreamProxy::IsOpen() const -{ - return m_stream->IsOpen(); -} +bool SetDefineStreamProxy::IsOpen() const { return m_stream->IsOpen(); } -bool SetDefineStreamProxy::Eof() const -{ - return m_stream->Eof(); -} +bool SetDefineStreamProxy::Eof() const { return m_stream->Eof(); } diff --git a/src/RawTemplater/Templating/SetDefineStreamProxy.h b/src/RawTemplater/Templating/SetDefineStreamProxy.h index 70315a684..b8812937c 100644 --- a/src/RawTemplater/Templating/SetDefineStreamProxy.h +++ b/src/RawTemplater/Templating/SetDefineStreamProxy.h @@ -1,31 +1,29 @@ #pragma once -#include "Utils/ClassUtils.h" #include "Parsing/Impl/AbstractDirectiveStreamProxy.h" #include "Parsing/Impl/DefinesStreamProxy.h" +#include "Utils/ClassUtils.h" -namespace templating -{ - class SetDefineStreamProxy final : public AbstractDirectiveStreamProxy - { - public: - explicit SetDefineStreamProxy(IParserLineStream* stream); +namespace templating { +class SetDefineStreamProxy final : public AbstractDirectiveStreamProxy { +public: + explicit SetDefineStreamProxy(IParserLineStream *stream); - void SetDefinesProxy(DefinesStreamProxy* definesProxy); + void SetDefinesProxy(DefinesStreamProxy *definesProxy); - ParserLine NextLine() override; - bool IncludeFile(const std::string& filename) override; - void PopCurrentFile() override; - _NODISCARD bool IsOpen() const override; - _NODISCARD bool Eof() const override; + ParserLine NextLine() override; + bool IncludeFile(const std::string &filename) override; + void PopCurrentFile() override; + _NODISCARD bool IsOpen() const override; + _NODISCARD bool Eof() const override; - private: - static constexpr const char* SET_DIRECTIVE = "set"; +private: + static constexpr const char *SET_DIRECTIVE = "set"; - _NODISCARD bool MatchSetDirective(const ParserLine& line, unsigned directiveStartPosition, unsigned directiveEndPosition) const; - _NODISCARD bool MatchDirectives(const ParserLine& line) const; + _NODISCARD bool MatchSetDirective(const ParserLine &line, unsigned directiveStartPosition, unsigned directiveEndPosition) const; + _NODISCARD bool MatchDirectives(const ParserLine &line) const; - IParserLineStream* const m_stream; - DefinesStreamProxy* m_defines_proxy; - }; -} + IParserLineStream *const m_stream; + DefinesStreamProxy *m_defines_proxy; +}; +} // namespace templating diff --git a/src/RawTemplater/Templating/Templater.cpp b/src/RawTemplater/Templating/Templater.cpp index 91fea331d..3885b9d65 100644 --- a/src/RawTemplater/Templating/Templater.cpp +++ b/src/RawTemplater/Templating/Templater.cpp @@ -1,421 +1,332 @@ #include "Templater.h" -#include <unordered_map> -#include <vector> #include <filesystem> #include <fstream> #include <iostream> +#include <unordered_map> +#include <vector> -#include "Utils/ClassUtils.h" #include "DirectiveEscapeStreamProxy.h" -#include "SetDefineStreamProxy.h" -#include "TemplatingStreamProxy.h" -#include "Parsing/ParsingException.h" #include "Parsing/Impl/DefinesStreamProxy.h" #include "Parsing/Impl/ParserSingleInputStream.h" #include "Parsing/Impl/SkipUntilFirstNonEmptyProxy.h" +#include "Parsing/ParsingException.h" +#include "SetDefineStreamProxy.h" +#include "TemplatingStreamProxy.h" +#include "Utils/ClassUtils.h" using namespace templating; namespace fs = std::filesystem; -namespace templating -{ - class TemplatingPass - { - public: - TemplatingPass() - : m_stream(nullptr) - { - } - - TemplatingPass(std::istream& stream, const std::string& fileName, ITemplaterControl* templaterControl) - { - m_base_stream = std::make_unique<ParserSingleInputStream>(stream, fileName); - - m_templating_proxy = std::make_unique<TemplatingStreamProxy>(m_base_stream.get(), templaterControl); - m_set_define_proxy = std::make_unique<SetDefineStreamProxy>(m_templating_proxy.get()); - m_defines_proxy = std::make_unique<DefinesStreamProxy>(m_set_define_proxy.get(), true); - m_directive_escape_proxy = std::make_unique<DirectiveEscapeStreamProxy>(m_defines_proxy.get()); - m_skip_until_first_non_empty_proxy = std::make_unique<SkipUntilFirstNonEmptyProxy>(m_directive_escape_proxy.get()); - - m_templating_proxy->SetDefinesProxy(m_defines_proxy.get()); - m_set_define_proxy->SetDefinesProxy(m_defines_proxy.get()); - m_stream = m_skip_until_first_non_empty_proxy.get(); - } - - std::unique_ptr<IParserLineStream> m_base_stream; - std::unique_ptr<TemplatingStreamProxy> m_templating_proxy; - std::unique_ptr<SetDefineStreamProxy> m_set_define_proxy; - std::unique_ptr<DefinesStreamProxy> m_defines_proxy; - std::unique_ptr<DirectiveEscapeStreamProxy> m_directive_escape_proxy; - std::unique_ptr<SkipUntilFirstNonEmptyProxy> m_skip_until_first_non_empty_proxy; - IParserLineStream* m_stream; - }; - - enum class TemplatingVariationType - { - OPTIONS, - SWITCH - }; - - class ITemplatingVariation - { - protected: - ITemplatingVariation() = default; - - public: - virtual ~ITemplatingVariation() = default; - ITemplatingVariation(const ITemplatingVariation& other) = default; - ITemplatingVariation(ITemplatingVariation&& other) noexcept = default; - ITemplatingVariation& operator=(const ITemplatingVariation& other) = default; - ITemplatingVariation& operator=(ITemplatingVariation&& other) noexcept = default; - - virtual const std::string& GetName() = 0; - virtual void Advance() = 0; - virtual void Apply(DefinesStreamProxy* definesProxy) = 0; - _NODISCARD virtual bool IsFinished() const = 0; - _NODISCARD virtual TemplatingVariationType GetVariationType() const = 0; - }; - - class SwitchVariation final : public ITemplatingVariation - { - public: - explicit SwitchVariation(std::string name) - : m_name(std::move(name)), - m_should_define(true), - m_finished(false) - { - } - - const std::string& GetName() override - { - return m_name; - } - - void Advance() override - { - if (!m_should_define) - m_finished = true; - else - m_should_define = false; - } - - void Apply(DefinesStreamProxy* definesProxy) override - { - if (m_should_define) - definesProxy->AddDefine(DefinesStreamProxy::Define(m_name, "1")); - } - - _NODISCARD bool IsFinished() const override - { - return m_finished; - } - - _NODISCARD TemplatingVariationType GetVariationType() const override - { - return TemplatingVariationType::SWITCH; - } - - std::string m_name; - bool m_should_define; - bool m_finished; - }; - - class OptionsVariation final : public ITemplatingVariation - { - public: - OptionsVariation(std::string name, std::vector<std::string> values) - : m_name(std::move(name)), - m_values(std::move(values)), - m_value_offset(0u) - { - } - - const std::string& GetName() override - { - return m_name; - } - - void Advance() override - { - m_value_offset++; - } - - void Apply(DefinesStreamProxy* definesProxy) override - { - if (m_value_offset < m_values.size()) - definesProxy->AddDefine(DefinesStreamProxy::Define(m_name, m_values[m_value_offset])); - } - - _NODISCARD bool IsFinished() const override - { - return m_value_offset >= m_values.size(); - } - - _NODISCARD TemplatingVariationType GetVariationType() const override - { - return TemplatingVariationType::OPTIONS; - } - - std::string m_name; - std::vector<std::string> m_values; - size_t m_value_offset; - }; - - class TemplaterControlImpl final : ITemplaterControl - { - public: - TemplaterControlImpl(std::istream& stream, std::string filename, const std::string& outputDirectory) - : m_stream(stream), - m_filename(std::move(filename)), - m_output_directory(outputDirectory), - m_first_line(true), - m_skip_pass(false), - m_write_output_to_file(false) - { - const fs::path filenamePath(m_filename); - m_default_output_file = (m_output_directory / filenamePath.filename().replace_extension()).string(); - } - - bool RunNextPass(std::ostream* buildLogFile) - { - m_stream.clear(); - m_stream.seekg(0, std::ios::beg); - - m_output_file = m_default_output_file; - m_current_pass = TemplatingPass(m_stream, m_filename, this); - - for (const auto& activeVariation : m_active_variations) - activeVariation->Apply(m_current_pass.m_defines_proxy.get()); - - while (!m_skip_pass && !m_current_pass.m_stream->Eof()) - { - auto nextLine = m_current_pass.m_stream->NextLine(); - - if (m_write_output_to_file) - { - if (m_first_line) - m_first_line = false; - else - m_output_stream << '\n'; - - m_output_stream << nextLine.m_line; - } - else - { - if (m_first_line) - m_first_line = false; - else - m_output_cache << '\n'; - - m_output_cache << nextLine.m_line; - } - } - - if (m_skip_pass) - return true; - - if (!m_write_output_to_file) - { - if (!m_active_variations.empty()) - { - std::cerr << "Template with variations must specify a filename\n"; - return false; - } - - if (!OpenOutputStream()) - return false; - - const auto cachedData = m_output_cache.str(); - if (!cachedData.empty()) - m_output_stream << cachedData; - } - - std::cout << "Templated file \"" << m_output_file << "\"\n"; - - if (buildLogFile) - *buildLogFile << "Templated file \"" << m_output_file << "\"\n"; - - m_first_line = true; - m_write_output_to_file = false; - m_output_cache.clear(); - m_output_cache.str(std::string()); - m_output_stream.close(); - - return true; - } - - void AdvanceActiveVariations() - { - while (!m_active_variations.empty()) - { - const auto& lastVariation = m_active_variations[m_active_variations.size() - 1]; - lastVariation->Advance(); - - if (lastVariation->IsFinished()) - { - m_active_variations_by_name.erase(lastVariation->GetName()); - m_active_variations.pop_back(); - } - else - break; - } - } - - _NODISCARD bool HasActiveVariations() const - { - return !m_active_variations.empty(); - } - - protected: - bool AddSwitch(std::string switchName) override - { - const auto existingVariation = m_active_variations_by_name.find(switchName); - if (existingVariation != m_active_variations_by_name.end()) - { - const auto isValidRedefinition = existingVariation->second->GetVariationType() == TemplatingVariationType::SWITCH; - - if (!isValidRedefinition) - std::cerr << "Redefinition of \"" << switchName << "\" as switch is invalid\n"; - - return isValidRedefinition; - } - - auto switchVariation = std::make_unique<SwitchVariation>(std::move(switchName)); - if (m_current_pass.m_defines_proxy) - switchVariation->Apply(m_current_pass.m_defines_proxy.get()); - - m_active_variations_by_name.emplace(switchVariation->m_name, switchVariation.get()); - m_active_variations.emplace_back(std::move(switchVariation)); - - return true; - } - - bool AddOptions(std::string optionsName, std::vector<std::string> optionValues) override - { - const auto existingVariation = m_active_variations_by_name.find(optionsName); - if (existingVariation != m_active_variations_by_name.end()) - { - const auto isValidRedefinition = existingVariation->second->GetVariationType() == TemplatingVariationType::OPTIONS; - - if (!isValidRedefinition) - std::cerr << "Redefinition of \"" << optionsName << "\" as options is invalid\n"; - - return isValidRedefinition; - } - - auto optionsVariation = std::make_unique<OptionsVariation>(std::move(optionsName), std::move(optionValues)); - if (m_current_pass.m_defines_proxy) - optionsVariation->Apply(m_current_pass.m_defines_proxy.get()); - - m_active_variations_by_name.emplace(optionsVariation->m_name, optionsVariation.get()); - m_active_variations.emplace_back(std::move(optionsVariation)); - - return true; - } - - bool SetFileName(const std::string& fileName) override - { - if (m_write_output_to_file) - return false; - - m_output_file = (m_output_directory / fileName).string(); - if (!OpenOutputStream()) - return false; - - m_write_output_to_file = true; - const auto cachedData = m_output_cache.str(); - if (!cachedData.empty()) - m_output_stream << cachedData; - m_output_cache.clear(); - m_output_cache.str(std::string()); - - return true; - } - - bool SkipPass() override - { - if (m_write_output_to_file) - { - std::cerr << "Cannot skip when already writing to file\n"; - return false; - } - - m_skip_pass = true; - return true; - } - - private: - bool OpenOutputStream() - { - const auto parentDir = fs::path(m_output_file).parent_path(); - if (!parentDir.empty()) - create_directories(parentDir); - - m_output_stream = std::ofstream(m_output_file, std::ios::out | std::ios::binary); - if (!m_output_stream.is_open()) - { - std::cerr << "Failed to open output file \"" << m_output_file << "\"\n"; - return false; - } - - return true; - } - - std::vector<std::unique_ptr<ITemplatingVariation>> m_active_variations; - std::unordered_map<std::string, ITemplatingVariation*> m_active_variations_by_name; - TemplatingPass m_current_pass; - - std::istream& m_stream; - std::string m_filename; - std::string m_output_file; - std::string m_default_output_file; - const fs::path m_output_directory; - - bool m_first_line; - bool m_skip_pass; - bool m_write_output_to_file; - std::ofstream m_output_stream; - std::ostringstream m_output_cache; - }; -} +namespace templating { +class TemplatingPass { +public: + TemplatingPass() : m_stream(nullptr) {} + + TemplatingPass(std::istream &stream, const std::string &fileName, ITemplaterControl *templaterControl) { + m_base_stream = std::make_unique<ParserSingleInputStream>(stream, fileName); + + m_templating_proxy = std::make_unique<TemplatingStreamProxy>(m_base_stream.get(), templaterControl); + m_set_define_proxy = std::make_unique<SetDefineStreamProxy>(m_templating_proxy.get()); + m_defines_proxy = std::make_unique<DefinesStreamProxy>(m_set_define_proxy.get(), true); + m_directive_escape_proxy = std::make_unique<DirectiveEscapeStreamProxy>(m_defines_proxy.get()); + m_skip_until_first_non_empty_proxy = std::make_unique<SkipUntilFirstNonEmptyProxy>(m_directive_escape_proxy.get()); + + m_templating_proxy->SetDefinesProxy(m_defines_proxy.get()); + m_set_define_proxy->SetDefinesProxy(m_defines_proxy.get()); + m_stream = m_skip_until_first_non_empty_proxy.get(); + } + + std::unique_ptr<IParserLineStream> m_base_stream; + std::unique_ptr<TemplatingStreamProxy> m_templating_proxy; + std::unique_ptr<SetDefineStreamProxy> m_set_define_proxy; + std::unique_ptr<DefinesStreamProxy> m_defines_proxy; + std::unique_ptr<DirectiveEscapeStreamProxy> m_directive_escape_proxy; + std::unique_ptr<SkipUntilFirstNonEmptyProxy> m_skip_until_first_non_empty_proxy; + IParserLineStream *m_stream; +}; + +enum class TemplatingVariationType { OPTIONS, SWITCH }; + +class ITemplatingVariation { +protected: + ITemplatingVariation() = default; + +public: + virtual ~ITemplatingVariation() = default; + ITemplatingVariation(const ITemplatingVariation &other) = default; + ITemplatingVariation(ITemplatingVariation &&other) noexcept = default; + ITemplatingVariation &operator=(const ITemplatingVariation &other) = default; + ITemplatingVariation &operator=(ITemplatingVariation &&other) noexcept = default; + + virtual const std::string &GetName() = 0; + virtual void Advance() = 0; + virtual void Apply(DefinesStreamProxy *definesProxy) = 0; + _NODISCARD virtual bool IsFinished() const = 0; + _NODISCARD virtual TemplatingVariationType GetVariationType() const = 0; +}; + +class SwitchVariation final : public ITemplatingVariation { +public: + explicit SwitchVariation(std::string name) : m_name(std::move(name)), m_should_define(true), m_finished(false) {} + + const std::string &GetName() override { return m_name; } + + void Advance() override { + if (!m_should_define) + m_finished = true; + else + m_should_define = false; + } + + void Apply(DefinesStreamProxy *definesProxy) override { + if (m_should_define) + definesProxy->AddDefine(DefinesStreamProxy::Define(m_name, "1")); + } + + _NODISCARD bool IsFinished() const override { return m_finished; } + + _NODISCARD TemplatingVariationType GetVariationType() const override { return TemplatingVariationType::SWITCH; } + + std::string m_name; + bool m_should_define; + bool m_finished; +}; + +class OptionsVariation final : public ITemplatingVariation { +public: + OptionsVariation(std::string name, std::vector<std::string> values) : m_name(std::move(name)), m_values(std::move(values)), m_value_offset(0u) {} + + const std::string &GetName() override { return m_name; } + + void Advance() override { m_value_offset++; } + + void Apply(DefinesStreamProxy *definesProxy) override { + if (m_value_offset < m_values.size()) + definesProxy->AddDefine(DefinesStreamProxy::Define(m_name, m_values[m_value_offset])); + } + + _NODISCARD bool IsFinished() const override { return m_value_offset >= m_values.size(); } + + _NODISCARD TemplatingVariationType GetVariationType() const override { return TemplatingVariationType::OPTIONS; } + + std::string m_name; + std::vector<std::string> m_values; + size_t m_value_offset; +}; + +class TemplaterControlImpl final : ITemplaterControl { +public: + TemplaterControlImpl(std::istream &stream, std::string filename, const std::string &outputDirectory) + : m_stream(stream), m_filename(std::move(filename)), m_output_directory(outputDirectory), m_first_line(true), m_skip_pass(false), + m_write_output_to_file(false) { + const fs::path filenamePath(m_filename); + m_default_output_file = (m_output_directory / filenamePath.filename().replace_extension()).string(); + } + + bool RunNextPass(std::ostream *buildLogFile) { + m_stream.clear(); + m_stream.seekg(0, std::ios::beg); + + m_output_file = m_default_output_file; + m_current_pass = TemplatingPass(m_stream, m_filename, this); + + for (const auto &activeVariation : m_active_variations) + activeVariation->Apply(m_current_pass.m_defines_proxy.get()); + + while (!m_skip_pass && !m_current_pass.m_stream->Eof()) { + auto nextLine = m_current_pass.m_stream->NextLine(); + + if (m_write_output_to_file) { + if (m_first_line) + m_first_line = false; + else + m_output_stream << '\n'; + + m_output_stream << nextLine.m_line; + } else { + if (m_first_line) + m_first_line = false; + else + m_output_cache << '\n'; + + m_output_cache << nextLine.m_line; + } + } -Templater::Templater(std::istream& stream, std::string fileName) - : m_stream(stream), - m_build_log(nullptr), - m_file_name(std::move(fileName)) -{ -} + if (m_skip_pass) + return true; -void Templater::SetBuildLogFile(std::ostream* buildLogFile) -{ - m_build_log = buildLogFile; -} + if (!m_write_output_to_file) { + if (!m_active_variations.empty()) { + std::cerr << "Template with variations must specify a filename\n"; + return false; + } + + if (!OpenOutputStream()) + return false; + + const auto cachedData = m_output_cache.str(); + if (!cachedData.empty()) + m_output_stream << cachedData; + } -bool Templater::TemplateToDirectory(const std::string& outputDirectory) const -{ - TemplaterControlImpl control(m_stream, m_file_name, outputDirectory); + std::cout << "Templated file \"" << m_output_file << "\"\n"; - try - { - if (!control.RunNextPass(m_build_log)) - return false; + if (buildLogFile) + *buildLogFile << "Templated file \"" << m_output_file << "\"\n"; - control.AdvanceActiveVariations(); - while (control.HasActiveVariations()) - { - if (!control.RunNextPass(m_build_log)) - return false; + m_first_line = true; + m_write_output_to_file = false; + m_output_cache.clear(); + m_output_cache.str(std::string()); + m_output_stream.close(); - control.AdvanceActiveVariations(); - } + return true; + } + + void AdvanceActiveVariations() { + while (!m_active_variations.empty()) { + const auto &lastVariation = m_active_variations[m_active_variations.size() - 1]; + lastVariation->Advance(); + + if (lastVariation->IsFinished()) { + m_active_variations_by_name.erase(lastVariation->GetName()); + m_active_variations.pop_back(); + } else + break; } - catch (ParsingException& e) - { - std::cerr << "Error: " << e.FullMessage() << std::endl; + } - return false; + _NODISCARD bool HasActiveVariations() const { return !m_active_variations.empty(); } + +protected: + bool AddSwitch(std::string switchName) override { + const auto existingVariation = m_active_variations_by_name.find(switchName); + if (existingVariation != m_active_variations_by_name.end()) { + const auto isValidRedefinition = existingVariation->second->GetVariationType() == TemplatingVariationType::SWITCH; + + if (!isValidRedefinition) + std::cerr << "Redefinition of \"" << switchName << "\" as switch is invalid\n"; + + return isValidRedefinition; } + auto switchVariation = std::make_unique<SwitchVariation>(std::move(switchName)); + if (m_current_pass.m_defines_proxy) + switchVariation->Apply(m_current_pass.m_defines_proxy.get()); + + m_active_variations_by_name.emplace(switchVariation->m_name, switchVariation.get()); + m_active_variations.emplace_back(std::move(switchVariation)); + return true; + } + + bool AddOptions(std::string optionsName, std::vector<std::string> optionValues) override { + const auto existingVariation = m_active_variations_by_name.find(optionsName); + if (existingVariation != m_active_variations_by_name.end()) { + const auto isValidRedefinition = existingVariation->second->GetVariationType() == TemplatingVariationType::OPTIONS; + + if (!isValidRedefinition) + std::cerr << "Redefinition of \"" << optionsName << "\" as options is invalid\n"; + + return isValidRedefinition; + } + + auto optionsVariation = std::make_unique<OptionsVariation>(std::move(optionsName), std::move(optionValues)); + if (m_current_pass.m_defines_proxy) + optionsVariation->Apply(m_current_pass.m_defines_proxy.get()); + + m_active_variations_by_name.emplace(optionsVariation->m_name, optionsVariation.get()); + m_active_variations.emplace_back(std::move(optionsVariation)); + + return true; + } + + bool SetFileName(const std::string &fileName) override { + if (m_write_output_to_file) + return false; + + m_output_file = (m_output_directory / fileName).string(); + if (!OpenOutputStream()) + return false; + + m_write_output_to_file = true; + const auto cachedData = m_output_cache.str(); + if (!cachedData.empty()) + m_output_stream << cachedData; + m_output_cache.clear(); + m_output_cache.str(std::string()); + + return true; + } + + bool SkipPass() override { + if (m_write_output_to_file) { + std::cerr << "Cannot skip when already writing to file\n"; + return false; + } + + m_skip_pass = true; + return true; + } + +private: + bool OpenOutputStream() { + const auto parentDir = fs::path(m_output_file).parent_path(); + if (!parentDir.empty()) + create_directories(parentDir); + + m_output_stream = std::ofstream(m_output_file, std::ios::out | std::ios::binary); + if (!m_output_stream.is_open()) { + std::cerr << "Failed to open output file \"" << m_output_file << "\"\n"; + return false; + } + + return true; + } + + std::vector<std::unique_ptr<ITemplatingVariation>> m_active_variations; + std::unordered_map<std::string, ITemplatingVariation *> m_active_variations_by_name; + TemplatingPass m_current_pass; + + std::istream &m_stream; + std::string m_filename; + std::string m_output_file; + std::string m_default_output_file; + const fs::path m_output_directory; + + bool m_first_line; + bool m_skip_pass; + bool m_write_output_to_file; + std::ofstream m_output_stream; + std::ostringstream m_output_cache; +}; +} // namespace templating + +Templater::Templater(std::istream &stream, std::string fileName) : m_stream(stream), m_build_log(nullptr), m_file_name(std::move(fileName)) {} + +void Templater::SetBuildLogFile(std::ostream *buildLogFile) { m_build_log = buildLogFile; } + +bool Templater::TemplateToDirectory(const std::string &outputDirectory) const { + TemplaterControlImpl control(m_stream, m_file_name, outputDirectory); + + try { + if (!control.RunNextPass(m_build_log)) + return false; + + control.AdvanceActiveVariations(); + while (control.HasActiveVariations()) { + if (!control.RunNextPass(m_build_log)) + return false; + + control.AdvanceActiveVariations(); + } + } catch (ParsingException &e) { + std::cerr << "Error: " << e.FullMessage() << std::endl; + + return false; + } + + return true; } diff --git a/src/RawTemplater/Templating/Templater.h b/src/RawTemplater/Templating/Templater.h index 1b2ff73d9..a0b16ec0d 100644 --- a/src/RawTemplater/Templating/Templater.h +++ b/src/RawTemplater/Templating/Templater.h @@ -1,22 +1,20 @@ #pragma once #include <string> -#include "Utils/ClassUtils.h" #include "Parsing/IParserLineStream.h" +#include "Utils/ClassUtils.h" -namespace templating -{ - class Templater - { - public: - Templater(std::istream& stream, std::string fileName); +namespace templating { +class Templater { +public: + Templater(std::istream &stream, std::string fileName); - void SetBuildLogFile(std::ostream* buildLogFile); - _NODISCARD bool TemplateToDirectory(const std::string& outputDirectory) const; + void SetBuildLogFile(std::ostream *buildLogFile); + _NODISCARD bool TemplateToDirectory(const std::string &outputDirectory) const; - private: - std::istream& m_stream; - std::ostream* m_build_log; - std::string m_file_name; - }; -} +private: + std::istream &m_stream; + std::ostream *m_build_log; + std::string m_file_name; +}; +} // namespace templating diff --git a/src/RawTemplater/Templating/TemplatingStreamProxy.cpp b/src/RawTemplater/Templating/TemplatingStreamProxy.cpp index 5cddd5743..f54300657 100644 --- a/src/RawTemplater/Templating/TemplatingStreamProxy.cpp +++ b/src/RawTemplater/Templating/TemplatingStreamProxy.cpp @@ -6,185 +6,153 @@ using namespace templating; -TemplatingStreamProxy::TemplatingStreamProxy(IParserLineStream* stream, ITemplaterControl* templaterControl) - : m_stream(stream), - m_templater_control(templaterControl), - m_defines_proxy(nullptr) -{ -} +TemplatingStreamProxy::TemplatingStreamProxy(IParserLineStream *stream, ITemplaterControl *templaterControl) + : m_stream(stream), m_templater_control(templaterControl), m_defines_proxy(nullptr) {} -void TemplatingStreamProxy::SetDefinesProxy(DefinesStreamProxy* definesProxy) -{ - m_defines_proxy = definesProxy; -} +void TemplatingStreamProxy::SetDefinesProxy(DefinesStreamProxy *definesProxy) { m_defines_proxy = definesProxy; } -bool TemplatingStreamProxy::MatchSwitchDirective(const ParserLine& line, const unsigned directiveStartPosition, const unsigned directiveEndPosition) const -{ - auto currentPosition = directiveStartPosition; +bool TemplatingStreamProxy::MatchSwitchDirective(const ParserLine &line, const unsigned directiveStartPosition, const unsigned directiveEndPosition) const { + auto currentPosition = directiveStartPosition; - if (directiveEndPosition - directiveStartPosition != std::char_traits<char>::length(SWITCH_DIRECTIVE) - || !MatchString(line, currentPosition, SWITCH_DIRECTIVE, std::char_traits<char>::length(SWITCH_DIRECTIVE))) - { - return false; - } + if (directiveEndPosition - directiveStartPosition != std::char_traits<char>::length(SWITCH_DIRECTIVE) || + !MatchString(line, currentPosition, SWITCH_DIRECTIVE, std::char_traits<char>::length(SWITCH_DIRECTIVE))) { + return false; + } - if (!SkipWhitespace(line, currentPosition)) - throw ParsingException(CreatePos(line, currentPosition), "Invalid switch directive."); + if (!SkipWhitespace(line, currentPosition)) + throw ParsingException(CreatePos(line, currentPosition), "Invalid switch directive."); - const auto nameStartPosition = currentPosition; - if (!ExtractIdentifier(line, currentPosition)) - throw ParsingException(CreatePos(line, currentPosition), "Invalid switch directive."); + const auto nameStartPosition = currentPosition; + if (!ExtractIdentifier(line, currentPosition)) + throw ParsingException(CreatePos(line, currentPosition), "Invalid switch directive."); - auto name = line.m_line.substr(nameStartPosition, currentPosition - nameStartPosition); + auto name = line.m_line.substr(nameStartPosition, currentPosition - nameStartPosition); - if (!m_templater_control->AddSwitch(std::move(name))) - throw ParsingException(TokenPos(*line.m_filename, line.m_line_number, 1), "switch directive failed"); + if (!m_templater_control->AddSwitch(std::move(name))) + throw ParsingException(TokenPos(*line.m_filename, line.m_line_number, 1), "switch directive failed"); - return true; + return true; } -bool TemplatingStreamProxy::MatchOptionsDirective(const ParserLine& line, const unsigned directiveStartPosition, const unsigned directiveEndPosition) const -{ - auto currentPosition = directiveStartPosition; +bool TemplatingStreamProxy::MatchOptionsDirective(const ParserLine &line, const unsigned directiveStartPosition, const unsigned directiveEndPosition) const { + auto currentPosition = directiveStartPosition; - if (directiveEndPosition - directiveStartPosition != std::char_traits<char>::length(OPTIONS_DIRECTIVE) - || !MatchString(line, currentPosition, OPTIONS_DIRECTIVE, std::char_traits<char>::length(OPTIONS_DIRECTIVE))) - { - return false; - } + if (directiveEndPosition - directiveStartPosition != std::char_traits<char>::length(OPTIONS_DIRECTIVE) || + !MatchString(line, currentPosition, OPTIONS_DIRECTIVE, std::char_traits<char>::length(OPTIONS_DIRECTIVE))) { + return false; + } - if (!SkipWhitespace(line, currentPosition)) - throw ParsingException(CreatePos(line, currentPosition), "Invalid options directive."); + if (!SkipWhitespace(line, currentPosition)) + throw ParsingException(CreatePos(line, currentPosition), "Invalid options directive."); - const auto nameStartPosition = currentPosition; - if (!ExtractIdentifier(line, currentPosition)) - throw ParsingException(CreatePos(line, currentPosition), "Invalid options directive."); + const auto nameStartPosition = currentPosition; + if (!ExtractIdentifier(line, currentPosition)) + throw ParsingException(CreatePos(line, currentPosition), "Invalid options directive."); - auto name = line.m_line.substr(nameStartPosition, currentPosition - nameStartPosition); + auto name = line.m_line.substr(nameStartPosition, currentPosition - nameStartPosition); - if (!MatchNextCharacter(line, currentPosition, '(')) - throw ParsingException(CreatePos(line, currentPosition), "Invalid options directive."); + if (!MatchNextCharacter(line, currentPosition, '(')) + throw ParsingException(CreatePos(line, currentPosition), "Invalid options directive."); - std::vector<std::string> options; + std::vector<std::string> options; - if (!SkipWhitespace(line, currentPosition)) - throw ParsingException(CreatePos(line, currentPosition), "Invalid options directive."); + if (!SkipWhitespace(line, currentPosition)) + throw ParsingException(CreatePos(line, currentPosition), "Invalid options directive."); - bool firstArg = true; - while (!MatchNextCharacter(line, currentPosition, ')')) - { - if (!firstArg && !MatchNextCharacter(line, currentPosition, ',')) - throw ParsingException(CreatePos(line, currentPosition), "Invalid options directive."); - if (!SkipWhitespace(line, currentPosition)) - throw ParsingException(CreatePos(line, currentPosition), "Invalid options directive."); + bool firstArg = true; + while (!MatchNextCharacter(line, currentPosition, ')')) { + if (!firstArg && !MatchNextCharacter(line, currentPosition, ',')) + throw ParsingException(CreatePos(line, currentPosition), "Invalid options directive."); + if (!SkipWhitespace(line, currentPosition)) + throw ParsingException(CreatePos(line, currentPosition), "Invalid options directive."); - const auto optionStartPosition = currentPosition; - if (!ExtractIdentifier(line, currentPosition)) - throw ParsingException(CreatePos(line, currentPosition), "Invalid options directive."); + const auto optionStartPosition = currentPosition; + if (!ExtractIdentifier(line, currentPosition)) + throw ParsingException(CreatePos(line, currentPosition), "Invalid options directive."); - options.emplace_back(line.m_line.substr(optionStartPosition, currentPosition - optionStartPosition)); + options.emplace_back(line.m_line.substr(optionStartPosition, currentPosition - optionStartPosition)); - firstArg = false; - } + firstArg = false; + } - if (!m_templater_control->AddOptions(std::move(name), std::move(options))) - throw ParsingException(TokenPos(*line.m_filename, line.m_line_number, 1), "options directive failed"); + if (!m_templater_control->AddOptions(std::move(name), std::move(options))) + throw ParsingException(TokenPos(*line.m_filename, line.m_line_number, 1), "options directive failed"); - return true; + return true; } -bool TemplatingStreamProxy::MatchFilenameDirective(const ParserLine& line, const unsigned directiveStartPosition, const unsigned directiveEndPosition) const -{ - auto currentPosition = directiveStartPosition; +bool TemplatingStreamProxy::MatchFilenameDirective(const ParserLine &line, const unsigned directiveStartPosition, const unsigned directiveEndPosition) const { + auto currentPosition = directiveStartPosition; - if (directiveEndPosition - directiveStartPosition != std::char_traits<char>::length(FILENAME_DIRECTIVE) - || !MatchString(line, currentPosition, FILENAME_DIRECTIVE, std::char_traits<char>::length(FILENAME_DIRECTIVE))) - { - return false; - } + if (directiveEndPosition - directiveStartPosition != std::char_traits<char>::length(FILENAME_DIRECTIVE) || + !MatchString(line, currentPosition, FILENAME_DIRECTIVE, std::char_traits<char>::length(FILENAME_DIRECTIVE))) { + return false; + } - if (!SkipWhitespace(line, currentPosition)) - throw ParsingException(CreatePos(line, currentPosition), "Invalid options directive."); + if (!SkipWhitespace(line, currentPosition)) + throw ParsingException(CreatePos(line, currentPosition), "Invalid options directive."); - const auto expressionString = line.m_line.substr(currentPosition, line.m_line.size() - currentPosition); - if (expressionString.empty()) - throw ParsingException(CreatePos(line, currentPosition), "Cannot pragma filename without an expression."); + const auto expressionString = line.m_line.substr(currentPosition, line.m_line.size() - currentPosition); + if (expressionString.empty()) + throw ParsingException(CreatePos(line, currentPosition), "Cannot pragma filename without an expression."); - const auto expression = m_defines_proxy->ParseExpression(line.m_filename, line.m_line_number, expressionString); - if (!expression) - throw ParsingException(CreatePos(line, currentPosition), "Failed to parse pragma filename expression"); + const auto expression = m_defines_proxy->ParseExpression(line.m_filename, line.m_line_number, expressionString); + if (!expression) + throw ParsingException(CreatePos(line, currentPosition), "Failed to parse pragma filename expression"); - if (!expression->IsStatic()) - throw ParsingException(CreatePos(line, currentPosition), "pragma filename expression must be static"); + if (!expression->IsStatic()) + throw ParsingException(CreatePos(line, currentPosition), "pragma filename expression must be static"); - const auto value = expression->EvaluateStatic(); + const auto value = expression->EvaluateStatic(); - if (value.m_type != SimpleExpressionValue::Type::STRING) - throw ParsingException(CreatePos(line, currentPosition), "pragma filename expression must evaluate to string"); + if (value.m_type != SimpleExpressionValue::Type::STRING) + throw ParsingException(CreatePos(line, currentPosition), "pragma filename expression must evaluate to string"); - if (!m_templater_control->SetFileName(*value.m_string_value)) - throw ParsingException(TokenPos(*line.m_filename, line.m_line_number, 1), "filename directive failed"); + if (!m_templater_control->SetFileName(*value.m_string_value)) + throw ParsingException(TokenPos(*line.m_filename, line.m_line_number, 1), "filename directive failed"); - return true; + return true; } -bool TemplatingStreamProxy::MatchSkipDirective(const ParserLine& line, const unsigned directiveStartPosition, const unsigned directiveEndPosition) const -{ - auto currentPosition = directiveStartPosition; +bool TemplatingStreamProxy::MatchSkipDirective(const ParserLine &line, const unsigned directiveStartPosition, const unsigned directiveEndPosition) const { + auto currentPosition = directiveStartPosition; - if (directiveEndPosition - directiveStartPosition != std::char_traits<char>::length(SKIP_DIRECTIVE) - || !MatchString(line, currentPosition, SKIP_DIRECTIVE, std::char_traits<char>::length(SKIP_DIRECTIVE))) - { - return false; - } + if (directiveEndPosition - directiveStartPosition != std::char_traits<char>::length(SKIP_DIRECTIVE) || + !MatchString(line, currentPosition, SKIP_DIRECTIVE, std::char_traits<char>::length(SKIP_DIRECTIVE))) { + return false; + } - if (!m_templater_control->SkipPass()) - throw ParsingException(TokenPos(*line.m_filename, line.m_line_number, 1), "skip directive failed"); + if (!m_templater_control->SkipPass()) + throw ParsingException(TokenPos(*line.m_filename, line.m_line_number, 1), "skip directive failed"); - return true; + return true; } -bool TemplatingStreamProxy::MatchDirectives(const ParserLine& line) const -{ - unsigned directiveStartPos, directiveEndPos; +bool TemplatingStreamProxy::MatchDirectives(const ParserLine &line) const { + unsigned directiveStartPos, directiveEndPos; - if (!FindDirective(line, directiveStartPos, directiveEndPos)) - return false; + if (!FindDirective(line, directiveStartPos, directiveEndPos)) + return false; - directiveStartPos++; + directiveStartPos++; - return MatchSwitchDirective(line, directiveStartPos, directiveEndPos) - || MatchOptionsDirective(line, directiveStartPos, directiveEndPos) - || MatchFilenameDirective(line, directiveStartPos, directiveEndPos) - || MatchSkipDirective(line, directiveStartPos, directiveEndPos); + return MatchSwitchDirective(line, directiveStartPos, directiveEndPos) || MatchOptionsDirective(line, directiveStartPos, directiveEndPos) || + MatchFilenameDirective(line, directiveStartPos, directiveEndPos) || MatchSkipDirective(line, directiveStartPos, directiveEndPos); } -ParserLine TemplatingStreamProxy::NextLine() -{ - auto line = m_stream->NextLine(); +ParserLine TemplatingStreamProxy::NextLine() { + auto line = m_stream->NextLine(); - while (MatchDirectives(line)) - line = m_stream->NextLine(); + while (MatchDirectives(line)) + line = m_stream->NextLine(); - return line; + return line; } -bool TemplatingStreamProxy::IncludeFile(const std::string& filename) -{ - return m_stream->IncludeFile(filename); -} +bool TemplatingStreamProxy::IncludeFile(const std::string &filename) { return m_stream->IncludeFile(filename); } -void TemplatingStreamProxy::PopCurrentFile() -{ - m_stream->PopCurrentFile(); -} +void TemplatingStreamProxy::PopCurrentFile() { m_stream->PopCurrentFile(); } -bool TemplatingStreamProxy::IsOpen() const -{ - return m_stream->IsOpen(); -} +bool TemplatingStreamProxy::IsOpen() const { return m_stream->IsOpen(); } -bool TemplatingStreamProxy::Eof() const -{ - return m_stream->Eof(); -} +bool TemplatingStreamProxy::Eof() const { return m_stream->Eof(); } diff --git a/src/RawTemplater/Templating/TemplatingStreamProxy.h b/src/RawTemplater/Templating/TemplatingStreamProxy.h index 36676dc1f..8dc6001b6 100644 --- a/src/RawTemplater/Templating/TemplatingStreamProxy.h +++ b/src/RawTemplater/Templating/TemplatingStreamProxy.h @@ -1,56 +1,53 @@ #pragma once -#include "Utils/ClassUtils.h" #include "Parsing/Impl/AbstractDirectiveStreamProxy.h" #include "Parsing/Impl/DefinesStreamProxy.h" +#include "Utils/ClassUtils.h" -namespace templating -{ - class ITemplaterControl - { - protected: - ITemplaterControl() = default; - - public: - virtual ~ITemplaterControl() = default; - ITemplaterControl(const ITemplaterControl& other) = default; - ITemplaterControl(ITemplaterControl&& other) noexcept = default; - ITemplaterControl& operator=(const ITemplaterControl& other) = default; - ITemplaterControl& operator=(ITemplaterControl&& other) noexcept = default; - - virtual bool AddSwitch(std::string switchName) = 0; - virtual bool AddOptions(std::string optionsName, std::vector<std::string> optionValues) = 0; - virtual bool SetFileName(const std::string& fileName) = 0; - virtual bool SkipPass() = 0; - }; - - class TemplatingStreamProxy final : public AbstractDirectiveStreamProxy - { - public: - TemplatingStreamProxy(IParserLineStream* stream, ITemplaterControl* templaterControl); - - void SetDefinesProxy(DefinesStreamProxy* definesProxy); - - ParserLine NextLine() override; - bool IncludeFile(const std::string& filename) override; - void PopCurrentFile() override; - _NODISCARD bool IsOpen() const override; - _NODISCARD bool Eof() const override; - - private: - static constexpr const char* SWITCH_DIRECTIVE = "switch"; - static constexpr const char* OPTIONS_DIRECTIVE = "options"; - static constexpr const char* FILENAME_DIRECTIVE = "filename"; - static constexpr const char* SKIP_DIRECTIVE = "skip"; - - _NODISCARD bool MatchSwitchDirective(const ParserLine& line, unsigned directiveStartPosition, unsigned directiveEndPosition) const; - _NODISCARD bool MatchOptionsDirective(const ParserLine& line, unsigned directiveStartPosition, unsigned directiveEndPosition) const; - _NODISCARD bool MatchFilenameDirective(const ParserLine& line, unsigned directiveStartPosition, unsigned directiveEndPosition) const; - _NODISCARD bool MatchSkipDirective(const ParserLine& line, unsigned directiveStartPosition, unsigned directiveEndPosition) const; - _NODISCARD bool MatchDirectives(const ParserLine& line) const; - - IParserLineStream* const m_stream; - ITemplaterControl* const m_templater_control; - DefinesStreamProxy* m_defines_proxy; - }; -} +namespace templating { +class ITemplaterControl { +protected: + ITemplaterControl() = default; + +public: + virtual ~ITemplaterControl() = default; + ITemplaterControl(const ITemplaterControl &other) = default; + ITemplaterControl(ITemplaterControl &&other) noexcept = default; + ITemplaterControl &operator=(const ITemplaterControl &other) = default; + ITemplaterControl &operator=(ITemplaterControl &&other) noexcept = default; + + virtual bool AddSwitch(std::string switchName) = 0; + virtual bool AddOptions(std::string optionsName, std::vector<std::string> optionValues) = 0; + virtual bool SetFileName(const std::string &fileName) = 0; + virtual bool SkipPass() = 0; +}; + +class TemplatingStreamProxy final : public AbstractDirectiveStreamProxy { +public: + TemplatingStreamProxy(IParserLineStream *stream, ITemplaterControl *templaterControl); + + void SetDefinesProxy(DefinesStreamProxy *definesProxy); + + ParserLine NextLine() override; + bool IncludeFile(const std::string &filename) override; + void PopCurrentFile() override; + _NODISCARD bool IsOpen() const override; + _NODISCARD bool Eof() const override; + +private: + static constexpr const char *SWITCH_DIRECTIVE = "switch"; + static constexpr const char *OPTIONS_DIRECTIVE = "options"; + static constexpr const char *FILENAME_DIRECTIVE = "filename"; + static constexpr const char *SKIP_DIRECTIVE = "skip"; + + _NODISCARD bool MatchSwitchDirective(const ParserLine &line, unsigned directiveStartPosition, unsigned directiveEndPosition) const; + _NODISCARD bool MatchOptionsDirective(const ParserLine &line, unsigned directiveStartPosition, unsigned directiveEndPosition) const; + _NODISCARD bool MatchFilenameDirective(const ParserLine &line, unsigned directiveStartPosition, unsigned directiveEndPosition) const; + _NODISCARD bool MatchSkipDirective(const ParserLine &line, unsigned directiveStartPosition, unsigned directiveEndPosition) const; + _NODISCARD bool MatchDirectives(const ParserLine &line) const; + + IParserLineStream *const m_stream; + ITemplaterControl *const m_templater_control; + DefinesStreamProxy *m_defines_proxy; +}; +} // namespace templating diff --git a/src/RawTemplater/main.cpp b/src/RawTemplater/main.cpp index afdf94b98..cf20e57c2 100644 --- a/src/RawTemplater/main.cpp +++ b/src/RawTemplater/main.cpp @@ -1,7 +1,6 @@ #include "RawTemplater.h" -int main(const int argc, const char** argv) -{ - const RawTemplater rawTemplater; - return rawTemplater.Run(argc, argv); +int main(const int argc, const char **argv) { + const RawTemplater rawTemplater; + return rawTemplater.Run(argc, argv); } diff --git a/src/Unlinker/ContentLister/ContentPrinter.cpp b/src/Unlinker/ContentLister/ContentPrinter.cpp index 5edfecef3..900dd72a0 100644 --- a/src/Unlinker/ContentLister/ContentPrinter.cpp +++ b/src/Unlinker/ContentLister/ContentPrinter.cpp @@ -1,20 +1,15 @@ #include "ContentPrinter.h" -ContentPrinter::ContentPrinter(Zone* zone) -{ - m_zone = zone; -} +ContentPrinter::ContentPrinter(Zone *zone) { m_zone = zone; } -void ContentPrinter::PrintContent() const -{ - const auto* pools = m_zone->m_pools.get(); - printf("Zone '%s' (%s)\n", m_zone->m_name.c_str(), m_zone->m_game->GetShortName().c_str()); - puts("Content:"); +void ContentPrinter::PrintContent() const { + const auto *pools = m_zone->m_pools.get(); + printf("Zone '%s' (%s)\n", m_zone->m_name.c_str(), m_zone->m_game->GetShortName().c_str()); + puts("Content:"); - for(const auto& asset : *pools) - { - printf("%s, %s\n", pools->GetAssetTypeName(asset->m_type), asset->m_name.c_str()); - } + for (const auto &asset : *pools) { + printf("%s, %s\n", pools->GetAssetTypeName(asset->m_type), asset->m_name.c_str()); + } - puts(""); + puts(""); } diff --git a/src/Unlinker/ContentLister/ContentPrinter.h b/src/Unlinker/ContentLister/ContentPrinter.h index 245095a53..500b20dfd 100644 --- a/src/Unlinker/ContentLister/ContentPrinter.h +++ b/src/Unlinker/ContentLister/ContentPrinter.h @@ -2,12 +2,11 @@ #include "Zone/Zone.h" -class ContentPrinter -{ - Zone* m_zone; +class ContentPrinter { + Zone *m_zone; public: - explicit ContentPrinter(Zone* zone); + explicit ContentPrinter(Zone *zone); - void PrintContent() const; + void PrintContent() const; }; \ No newline at end of file diff --git a/src/Unlinker/ContentLister/ZoneDefWriter.cpp b/src/Unlinker/ContentLister/ZoneDefWriter.cpp index a7627d5a6..5a4b11767 100644 --- a/src/Unlinker/ContentLister/ZoneDefWriter.cpp +++ b/src/Unlinker/ContentLister/ZoneDefWriter.cpp @@ -1,20 +1,18 @@ #include "ZoneDefWriter.h" -void AbstractZoneDefWriter::WriteZoneDef(std::ostream& stream, const UnlinkerArgs* args, Zone* zone) const -{ - ZoneDefinitionOutputStream out(stream); +void AbstractZoneDefWriter::WriteZoneDef(std::ostream &stream, const UnlinkerArgs *args, Zone *zone) const { + ZoneDefinitionOutputStream out(stream); - out.WriteComment(zone->m_game->GetFullName()); - out.WriteMetaData(META_DATA_KEY_GAME, zone->m_game->GetShortName()); - out.EmptyLine(); + out.WriteComment(zone->m_game->GetFullName()); + out.WriteMetaData(META_DATA_KEY_GAME, zone->m_game->GetShortName()); + out.EmptyLine(); - if(args->m_use_gdt) - { - out.WriteComment("Load asset gdt files"); - out.WriteMetaData(META_DATA_KEY_GDT, zone->m_name); - out.EmptyLine(); - } + if (args->m_use_gdt) { + out.WriteComment("Load asset gdt files"); + out.WriteMetaData(META_DATA_KEY_GDT, zone->m_name); + out.EmptyLine(); + } - WriteMetaData(out, args, zone); - WriteContent(out, args, zone); + WriteMetaData(out, args, zone); + WriteContent(out, args, zone); } \ No newline at end of file diff --git a/src/Unlinker/ContentLister/ZoneDefWriter.h b/src/Unlinker/ContentLister/ZoneDefWriter.h index a3e86557e..9b933b96c 100644 --- a/src/Unlinker/ContentLister/ZoneDefWriter.h +++ b/src/Unlinker/ContentLister/ZoneDefWriter.h @@ -1,32 +1,30 @@ #pragma once #include "UnlinkerArgs.h" -#include "Zone/Zone.h" #include "Zone/Definition/ZoneDefinitionStream.h" +#include "Zone/Zone.h" -class IZoneDefWriter -{ +class IZoneDefWriter { public: - IZoneDefWriter() = default; - virtual ~IZoneDefWriter() = default; - IZoneDefWriter(const IZoneDefWriter& other) = default; - IZoneDefWriter(IZoneDefWriter&& other) noexcept = default; - IZoneDefWriter& operator=(const IZoneDefWriter& other) = default; - IZoneDefWriter& operator=(IZoneDefWriter&& other) noexcept = default; + IZoneDefWriter() = default; + virtual ~IZoneDefWriter() = default; + IZoneDefWriter(const IZoneDefWriter &other) = default; + IZoneDefWriter(IZoneDefWriter &&other) noexcept = default; + IZoneDefWriter &operator=(const IZoneDefWriter &other) = default; + IZoneDefWriter &operator=(IZoneDefWriter &&other) noexcept = default; - virtual bool CanHandleZone(Zone* zone) const = 0; - virtual void WriteZoneDef(std::ostream& stream, const UnlinkerArgs* args, Zone* zone) const = 0; + virtual bool CanHandleZone(Zone *zone) const = 0; + virtual void WriteZoneDef(std::ostream &stream, const UnlinkerArgs *args, Zone *zone) const = 0; }; -class AbstractZoneDefWriter : public IZoneDefWriter -{ +class AbstractZoneDefWriter : public IZoneDefWriter { protected: - static constexpr const char* META_DATA_KEY_GAME = "game"; - static constexpr const char* META_DATA_KEY_GDT = "gdt"; - - virtual void WriteMetaData(ZoneDefinitionOutputStream& stream, const UnlinkerArgs* args, Zone* zone) const = 0; - virtual void WriteContent(ZoneDefinitionOutputStream& stream, const UnlinkerArgs* args, Zone* zone) const = 0; + static constexpr const char *META_DATA_KEY_GAME = "game"; + static constexpr const char *META_DATA_KEY_GDT = "gdt"; + + virtual void WriteMetaData(ZoneDefinitionOutputStream &stream, const UnlinkerArgs *args, Zone *zone) const = 0; + virtual void WriteContent(ZoneDefinitionOutputStream &stream, const UnlinkerArgs *args, Zone *zone) const = 0; public: - void WriteZoneDef(std::ostream& stream, const UnlinkerArgs* args, Zone* zone) const override; + void WriteZoneDef(std::ostream &stream, const UnlinkerArgs *args, Zone *zone) const override; }; \ No newline at end of file diff --git a/src/Unlinker/Game/IW3/ZoneDefWriterIW3.cpp b/src/Unlinker/Game/IW3/ZoneDefWriterIW3.cpp index b3ee1bb02..deba986a8 100644 --- a/src/Unlinker/Game/IW3/ZoneDefWriterIW3.cpp +++ b/src/Unlinker/Game/IW3/ZoneDefWriterIW3.cpp @@ -2,44 +2,35 @@ #include <cassert> -#include "Game/IW3/GameIW3.h" #include "Game/IW3/GameAssetPoolIW3.h" +#include "Game/IW3/GameIW3.h" using namespace IW3; -bool ZoneDefWriter::CanHandleZone(Zone* zone) const -{ - return zone->m_game == &g_GameIW3; -} +bool ZoneDefWriter::CanHandleZone(Zone *zone) const { return zone->m_game == &g_GameIW3; } -void ZoneDefWriter::WriteMetaData(ZoneDefinitionOutputStream& stream, const UnlinkerArgs* args, Zone* zone) const -{ -} +void ZoneDefWriter::WriteMetaData(ZoneDefinitionOutputStream &stream, const UnlinkerArgs *args, Zone *zone) const {} -void ZoneDefWriter::WriteContent(ZoneDefinitionOutputStream& stream, const UnlinkerArgs* args, Zone* zone) const -{ - const auto* pools = dynamic_cast<GameAssetPoolIW3*>(zone->m_pools.get()); +void ZoneDefWriter::WriteContent(ZoneDefinitionOutputStream &stream, const UnlinkerArgs *args, Zone *zone) const { + const auto *pools = dynamic_cast<GameAssetPoolIW3 *>(zone->m_pools.get()); - assert(pools); - if (!pools) - return; + assert(pools); + if (!pools) + return; - // Localized strings are all collected in one string file. So only add this to the zone file. - if (!pools->m_localize->m_asset_lookup.empty()) - { - stream.WriteEntry(pools->GetAssetTypeName(ASSET_TYPE_LOCALIZE_ENTRY), zone->m_name); - } + // Localized strings are all collected in one string file. So only add this to the zone file. + if (!pools->m_localize->m_asset_lookup.empty()) { + stream.WriteEntry(pools->GetAssetTypeName(ASSET_TYPE_LOCALIZE_ENTRY), zone->m_name); + } + + for (const auto &asset : *pools) { + switch (asset->m_type) { + case ASSET_TYPE_LOCALIZE_ENTRY: + break; - for (const auto& asset : *pools) - { - switch (asset->m_type) - { - case ASSET_TYPE_LOCALIZE_ENTRY: - break; - - default: - stream.WriteEntry(pools->GetAssetTypeName(asset->m_type), asset->m_name); - break; - } + default: + stream.WriteEntry(pools->GetAssetTypeName(asset->m_type), asset->m_name); + break; } + } } diff --git a/src/Unlinker/Game/IW3/ZoneDefWriterIW3.h b/src/Unlinker/Game/IW3/ZoneDefWriterIW3.h index b07e57d1b..c010e8332 100644 --- a/src/Unlinker/Game/IW3/ZoneDefWriterIW3.h +++ b/src/Unlinker/Game/IW3/ZoneDefWriterIW3.h @@ -2,15 +2,13 @@ #include "ContentLister/ZoneDefWriter.h" -namespace IW3 -{ - class ZoneDefWriter final : public AbstractZoneDefWriter - { - protected: - void WriteMetaData(ZoneDefinitionOutputStream& stream, const UnlinkerArgs* args, Zone* zone) const override; - void WriteContent(ZoneDefinitionOutputStream& stream, const UnlinkerArgs* args, Zone* zone) const override; +namespace IW3 { +class ZoneDefWriter final : public AbstractZoneDefWriter { +protected: + void WriteMetaData(ZoneDefinitionOutputStream &stream, const UnlinkerArgs *args, Zone *zone) const override; + void WriteContent(ZoneDefinitionOutputStream &stream, const UnlinkerArgs *args, Zone *zone) const override; - public: - bool CanHandleZone(Zone* zone) const override; - }; -} \ No newline at end of file +public: + bool CanHandleZone(Zone *zone) const override; +}; +} // namespace IW3 \ No newline at end of file diff --git a/src/Unlinker/Game/IW4/ZoneDefWriterIW4.cpp b/src/Unlinker/Game/IW4/ZoneDefWriterIW4.cpp index 76be5b7c4..fbd8321ae 100644 --- a/src/Unlinker/Game/IW4/ZoneDefWriterIW4.cpp +++ b/src/Unlinker/Game/IW4/ZoneDefWriterIW4.cpp @@ -2,44 +2,35 @@ #include <cassert> -#include "Game/IW4/GameIW4.h" #include "Game/IW4/GameAssetPoolIW4.h" +#include "Game/IW4/GameIW4.h" using namespace IW4; -bool ZoneDefWriter::CanHandleZone(Zone* zone) const -{ - return zone->m_game == &g_GameIW4; -} +bool ZoneDefWriter::CanHandleZone(Zone *zone) const { return zone->m_game == &g_GameIW4; } -void ZoneDefWriter::WriteMetaData(ZoneDefinitionOutputStream& stream, const UnlinkerArgs* args, Zone* zone) const -{ -} +void ZoneDefWriter::WriteMetaData(ZoneDefinitionOutputStream &stream, const UnlinkerArgs *args, Zone *zone) const {} -void ZoneDefWriter::WriteContent(ZoneDefinitionOutputStream& stream, const UnlinkerArgs* args, Zone* zone) const -{ - const auto* pools = dynamic_cast<GameAssetPoolIW4*>(zone->m_pools.get()); +void ZoneDefWriter::WriteContent(ZoneDefinitionOutputStream &stream, const UnlinkerArgs *args, Zone *zone) const { + const auto *pools = dynamic_cast<GameAssetPoolIW4 *>(zone->m_pools.get()); - assert(pools); - if (!pools) - return; + assert(pools); + if (!pools) + return; - // Localized strings are all collected in one string file. So only add this to the zone file. - if (!pools->m_localize->m_asset_lookup.empty()) - { - stream.WriteEntry(pools->GetAssetTypeName(ASSET_TYPE_LOCALIZE_ENTRY), zone->m_name); - } + // Localized strings are all collected in one string file. So only add this to the zone file. + if (!pools->m_localize->m_asset_lookup.empty()) { + stream.WriteEntry(pools->GetAssetTypeName(ASSET_TYPE_LOCALIZE_ENTRY), zone->m_name); + } + + for (const auto &asset : *pools) { + switch (asset->m_type) { + case ASSET_TYPE_LOCALIZE_ENTRY: + break; - for (const auto& asset : *pools) - { - switch (asset->m_type) - { - case ASSET_TYPE_LOCALIZE_ENTRY: - break; - - default: - stream.WriteEntry(pools->GetAssetTypeName(asset->m_type), asset->m_name); - break; - } + default: + stream.WriteEntry(pools->GetAssetTypeName(asset->m_type), asset->m_name); + break; } + } } diff --git a/src/Unlinker/Game/IW4/ZoneDefWriterIW4.h b/src/Unlinker/Game/IW4/ZoneDefWriterIW4.h index 6f9e1b82a..a5773e2cb 100644 --- a/src/Unlinker/Game/IW4/ZoneDefWriterIW4.h +++ b/src/Unlinker/Game/IW4/ZoneDefWriterIW4.h @@ -2,15 +2,13 @@ #include "ContentLister/ZoneDefWriter.h" -namespace IW4 -{ - class ZoneDefWriter final : public AbstractZoneDefWriter - { - protected: - void WriteMetaData(ZoneDefinitionOutputStream& stream, const UnlinkerArgs* args, Zone* zone) const override; - void WriteContent(ZoneDefinitionOutputStream& stream, const UnlinkerArgs* args, Zone* zone) const override; +namespace IW4 { +class ZoneDefWriter final : public AbstractZoneDefWriter { +protected: + void WriteMetaData(ZoneDefinitionOutputStream &stream, const UnlinkerArgs *args, Zone *zone) const override; + void WriteContent(ZoneDefinitionOutputStream &stream, const UnlinkerArgs *args, Zone *zone) const override; - public: - bool CanHandleZone(Zone* zone) const override; - }; -} \ No newline at end of file +public: + bool CanHandleZone(Zone *zone) const override; +}; +} // namespace IW4 \ No newline at end of file diff --git a/src/Unlinker/Game/IW5/ZoneDefWriterIW5.cpp b/src/Unlinker/Game/IW5/ZoneDefWriterIW5.cpp index 304a8019d..3b26c8067 100644 --- a/src/Unlinker/Game/IW5/ZoneDefWriterIW5.cpp +++ b/src/Unlinker/Game/IW5/ZoneDefWriterIW5.cpp @@ -2,44 +2,35 @@ #include <cassert> -#include "Game/IW5/GameIW5.h" #include "Game/IW5/GameAssetPoolIW5.h" +#include "Game/IW5/GameIW5.h" using namespace IW5; -bool ZoneDefWriter::CanHandleZone(Zone* zone) const -{ - return zone->m_game == &g_GameIW5; -} +bool ZoneDefWriter::CanHandleZone(Zone *zone) const { return zone->m_game == &g_GameIW5; } -void ZoneDefWriter::WriteMetaData(ZoneDefinitionOutputStream& stream, const UnlinkerArgs* args, Zone* zone) const -{ -} +void ZoneDefWriter::WriteMetaData(ZoneDefinitionOutputStream &stream, const UnlinkerArgs *args, Zone *zone) const {} -void ZoneDefWriter::WriteContent(ZoneDefinitionOutputStream& stream, const UnlinkerArgs* args, Zone* zone) const -{ - const auto* pools = dynamic_cast<GameAssetPoolIW5*>(zone->m_pools.get()); +void ZoneDefWriter::WriteContent(ZoneDefinitionOutputStream &stream, const UnlinkerArgs *args, Zone *zone) const { + const auto *pools = dynamic_cast<GameAssetPoolIW5 *>(zone->m_pools.get()); - assert(pools); - if (!pools) - return; + assert(pools); + if (!pools) + return; - // Localized strings are all collected in one string file. So only add this to the zone file. - if (!pools->m_localize->m_asset_lookup.empty()) - { - stream.WriteEntry(pools->GetAssetTypeName(ASSET_TYPE_LOCALIZE_ENTRY), zone->m_name); - } + // Localized strings are all collected in one string file. So only add this to the zone file. + if (!pools->m_localize->m_asset_lookup.empty()) { + stream.WriteEntry(pools->GetAssetTypeName(ASSET_TYPE_LOCALIZE_ENTRY), zone->m_name); + } + + for (const auto &asset : *pools) { + switch (asset->m_type) { + case ASSET_TYPE_LOCALIZE_ENTRY: + break; - for (const auto& asset : *pools) - { - switch (asset->m_type) - { - case ASSET_TYPE_LOCALIZE_ENTRY: - break; - - default: - stream.WriteEntry(pools->GetAssetTypeName(asset->m_type), asset->m_name); - break; - } + default: + stream.WriteEntry(pools->GetAssetTypeName(asset->m_type), asset->m_name); + break; } + } } diff --git a/src/Unlinker/Game/IW5/ZoneDefWriterIW5.h b/src/Unlinker/Game/IW5/ZoneDefWriterIW5.h index e68b942fd..6ab25c599 100644 --- a/src/Unlinker/Game/IW5/ZoneDefWriterIW5.h +++ b/src/Unlinker/Game/IW5/ZoneDefWriterIW5.h @@ -2,15 +2,13 @@ #include "ContentLister/ZoneDefWriter.h" -namespace IW5 -{ - class ZoneDefWriter final : public AbstractZoneDefWriter - { - protected: - void WriteMetaData(ZoneDefinitionOutputStream& stream, const UnlinkerArgs* args, Zone* zone) const override; - void WriteContent(ZoneDefinitionOutputStream& stream, const UnlinkerArgs* args, Zone* zone) const override; +namespace IW5 { +class ZoneDefWriter final : public AbstractZoneDefWriter { +protected: + void WriteMetaData(ZoneDefinitionOutputStream &stream, const UnlinkerArgs *args, Zone *zone) const override; + void WriteContent(ZoneDefinitionOutputStream &stream, const UnlinkerArgs *args, Zone *zone) const override; - public: - bool CanHandleZone(Zone* zone) const override; - }; -} \ No newline at end of file +public: + bool CanHandleZone(Zone *zone) const override; +}; +} // namespace IW5 \ No newline at end of file diff --git a/src/Unlinker/Game/T5/ZoneDefWriterT5.cpp b/src/Unlinker/Game/T5/ZoneDefWriterT5.cpp index 1cc9e1cf1..de9ff1bf8 100644 --- a/src/Unlinker/Game/T5/ZoneDefWriterT5.cpp +++ b/src/Unlinker/Game/T5/ZoneDefWriterT5.cpp @@ -2,44 +2,35 @@ #include <cassert> -#include "Game/T5/GameT5.h" #include "Game/T5/GameAssetPoolT5.h" +#include "Game/T5/GameT5.h" using namespace T5; -bool ZoneDefWriter::CanHandleZone(Zone* zone) const -{ - return zone->m_game == &g_GameT5; -} +bool ZoneDefWriter::CanHandleZone(Zone *zone) const { return zone->m_game == &g_GameT5; } -void ZoneDefWriter::WriteMetaData(ZoneDefinitionOutputStream& stream, const UnlinkerArgs* args, Zone* zone) const -{ -} +void ZoneDefWriter::WriteMetaData(ZoneDefinitionOutputStream &stream, const UnlinkerArgs *args, Zone *zone) const {} -void ZoneDefWriter::WriteContent(ZoneDefinitionOutputStream& stream, const UnlinkerArgs* args, Zone* zone) const -{ - const auto* pools = dynamic_cast<GameAssetPoolT5*>(zone->m_pools.get()); +void ZoneDefWriter::WriteContent(ZoneDefinitionOutputStream &stream, const UnlinkerArgs *args, Zone *zone) const { + const auto *pools = dynamic_cast<GameAssetPoolT5 *>(zone->m_pools.get()); - assert(pools); - if (!pools) - return; + assert(pools); + if (!pools) + return; - // Localized strings are all collected in one string file. So only add this to the zone file. - if (!pools->m_localize->m_asset_lookup.empty()) - { - stream.WriteEntry(pools->GetAssetTypeName(ASSET_TYPE_LOCALIZE_ENTRY), zone->m_name); - } + // Localized strings are all collected in one string file. So only add this to the zone file. + if (!pools->m_localize->m_asset_lookup.empty()) { + stream.WriteEntry(pools->GetAssetTypeName(ASSET_TYPE_LOCALIZE_ENTRY), zone->m_name); + } + + for (const auto &asset : *pools) { + switch (asset->m_type) { + case ASSET_TYPE_LOCALIZE_ENTRY: + break; - for (const auto& asset : *pools) - { - switch (asset->m_type) - { - case ASSET_TYPE_LOCALIZE_ENTRY: - break; - - default: - stream.WriteEntry(pools->GetAssetTypeName(asset->m_type), asset->m_name); - break; - } + default: + stream.WriteEntry(pools->GetAssetTypeName(asset->m_type), asset->m_name); + break; } + } } diff --git a/src/Unlinker/Game/T5/ZoneDefWriterT5.h b/src/Unlinker/Game/T5/ZoneDefWriterT5.h index bca2c2e33..945761a3f 100644 --- a/src/Unlinker/Game/T5/ZoneDefWriterT5.h +++ b/src/Unlinker/Game/T5/ZoneDefWriterT5.h @@ -2,15 +2,13 @@ #include "ContentLister/ZoneDefWriter.h" -namespace T5 -{ - class ZoneDefWriter final : public AbstractZoneDefWriter - { - protected: - void WriteMetaData(ZoneDefinitionOutputStream& stream, const UnlinkerArgs* args, Zone* zone) const override; - void WriteContent(ZoneDefinitionOutputStream& stream, const UnlinkerArgs* args, Zone* zone) const override; +namespace T5 { +class ZoneDefWriter final : public AbstractZoneDefWriter { +protected: + void WriteMetaData(ZoneDefinitionOutputStream &stream, const UnlinkerArgs *args, Zone *zone) const override; + void WriteContent(ZoneDefinitionOutputStream &stream, const UnlinkerArgs *args, Zone *zone) const override; - public: - bool CanHandleZone(Zone* zone) const override; - }; -} \ No newline at end of file +public: + bool CanHandleZone(Zone *zone) const override; +}; +} // namespace T5 \ No newline at end of file diff --git a/src/Unlinker/Game/T6/ZoneDefWriterT6.cpp b/src/Unlinker/Game/T6/ZoneDefWriterT6.cpp index 8f0ff78c8..12b09ce0a 100644 --- a/src/Unlinker/Game/T6/ZoneDefWriterT6.cpp +++ b/src/Unlinker/Game/T6/ZoneDefWriterT6.cpp @@ -1,102 +1,84 @@ #include "ZoneDefWriterT6.h" -#include "Game/T6/GameT6.h" #include "Game/T6/CommonT6.h" #include "Game/T6/GameAssetPoolT6.h" +#include "Game/T6/GameT6.h" -#include <sstream> -#include <iomanip> #include <cassert> +#include <iomanip> +#include <sstream> using namespace T6; -namespace T6 -{ - class KeyValuePairKnownKey - { - public: - std::string m_key; - int m_hash; +namespace T6 { +class KeyValuePairKnownKey { +public: + std::string m_key; + int m_hash; - explicit KeyValuePairKnownKey(std::string key) - { - m_key = std::move(key); - m_hash = Common::Com_HashKey(m_key.c_str(), 64); - } - }; + explicit KeyValuePairKnownKey(std::string key) { + m_key = std::move(key); + m_hash = Common::Com_HashKey(m_key.c_str(), 64); + } +}; - const KeyValuePairKnownKey KEY_VALUE_PAIR_KNOWN_KEYS[] - { - KeyValuePairKnownKey("ipak_read"), - KeyValuePairKnownKey("ipak_write"), - KeyValuePairKnownKey("initial_xmodels"), - KeyValuePairKnownKey("initial_materials"), - }; -} +const KeyValuePairKnownKey KEY_VALUE_PAIR_KNOWN_KEYS[]{ + KeyValuePairKnownKey("ipak_read"), + KeyValuePairKnownKey("ipak_write"), + KeyValuePairKnownKey("initial_xmodels"), + KeyValuePairKnownKey("initial_materials"), +}; +} // namespace T6 -bool ZoneDefWriter::CanHandleZone(Zone* zone) const -{ - return zone->m_game == &g_GameT6; -} +bool ZoneDefWriter::CanHandleZone(Zone *zone) const { return zone->m_game == &g_GameT6; } -void ZoneDefWriter::WriteKeyValuePair(ZoneDefinitionOutputStream& stream, KeyValuePair* kvp) -{ - for (const auto& knownKey : KEY_VALUE_PAIR_KNOWN_KEYS) - { - if (knownKey.m_hash == kvp->keyHash) - { - stream.WriteMetaData("level." + knownKey.m_key, kvp->value); - return; - } +void ZoneDefWriter::WriteKeyValuePair(ZoneDefinitionOutputStream &stream, KeyValuePair *kvp) { + for (const auto &knownKey : KEY_VALUE_PAIR_KNOWN_KEYS) { + if (knownKey.m_hash == kvp->keyHash) { + stream.WriteMetaData("level." + knownKey.m_key, kvp->value); + return; } + } - std::ostringstream str; - str << "level.@" << std::setfill('0') << std::setw(sizeof(int) * 2) << std::hex << kvp->keyHash; - stream.WriteMetaData(str.str(), kvp->value); + std::ostringstream str; + str << "level.@" << std::setfill('0') << std::setw(sizeof(int) * 2) << std::hex << kvp->keyHash; + stream.WriteMetaData(str.str(), kvp->value); } -void ZoneDefWriter::WriteMetaData(ZoneDefinitionOutputStream& stream, const UnlinkerArgs* args, Zone* zone) const -{ - auto* assetPoolT6 = dynamic_cast<GameAssetPoolT6*>(zone->m_pools.get()); - if (assetPoolT6 && !assetPoolT6->m_key_value_pairs->m_asset_lookup.empty()) - { - for (const auto* kvpAsset : *assetPoolT6->m_key_value_pairs) - { - const auto* keyValuePairs = kvpAsset->Asset(); - for (auto varIndex = 0; varIndex < keyValuePairs->numVariables; varIndex++) - { - WriteKeyValuePair(stream, &keyValuePairs->keyValuePairs[varIndex]); - } - } - - stream.EmptyLine(); +void ZoneDefWriter::WriteMetaData(ZoneDefinitionOutputStream &stream, const UnlinkerArgs *args, Zone *zone) const { + auto *assetPoolT6 = dynamic_cast<GameAssetPoolT6 *>(zone->m_pools.get()); + if (assetPoolT6 && !assetPoolT6->m_key_value_pairs->m_asset_lookup.empty()) { + for (const auto *kvpAsset : *assetPoolT6->m_key_value_pairs) { + const auto *keyValuePairs = kvpAsset->Asset(); + for (auto varIndex = 0; varIndex < keyValuePairs->numVariables; varIndex++) { + WriteKeyValuePair(stream, &keyValuePairs->keyValuePairs[varIndex]); + } } + + stream.EmptyLine(); + } } -void ZoneDefWriter::WriteContent(ZoneDefinitionOutputStream& stream, const UnlinkerArgs* args, Zone* zone) const -{ - const auto* pools = dynamic_cast<GameAssetPoolT6*>(zone->m_pools.get()); +void ZoneDefWriter::WriteContent(ZoneDefinitionOutputStream &stream, const UnlinkerArgs *args, Zone *zone) const { + const auto *pools = dynamic_cast<GameAssetPoolT6 *>(zone->m_pools.get()); - assert(pools); - if (!pools) - return; + assert(pools); + if (!pools) + return; - // Localized strings are all collected in one string file. So only add this to the zone file. - if (!pools->m_localize->m_asset_lookup.empty()) - { - stream.WriteEntry(pools->GetAssetTypeName(ASSET_TYPE_LOCALIZE_ENTRY), zone->m_name); - } + // Localized strings are all collected in one string file. So only add this to the zone file. + if (!pools->m_localize->m_asset_lookup.empty()) { + stream.WriteEntry(pools->GetAssetTypeName(ASSET_TYPE_LOCALIZE_ENTRY), zone->m_name); + } - for (const auto& asset : *pools) - { - switch (asset->m_type) - { - case ASSET_TYPE_LOCALIZE_ENTRY: - case ASSET_TYPE_KEYVALUEPAIRS: // KeyValuePairs should be included as zone file metadata and not as content - break; + for (const auto &asset : *pools) { + switch (asset->m_type) { + case ASSET_TYPE_LOCALIZE_ENTRY: + case ASSET_TYPE_KEYVALUEPAIRS: // KeyValuePairs should be included as zone file metadata and not as content + break; - default: - stream.WriteEntry(pools->GetAssetTypeName(asset->m_type), asset->m_name); - break; - } + default: + stream.WriteEntry(pools->GetAssetTypeName(asset->m_type), asset->m_name); + break; } + } } \ No newline at end of file diff --git a/src/Unlinker/Game/T6/ZoneDefWriterT6.h b/src/Unlinker/Game/T6/ZoneDefWriterT6.h index 73c247d80..cfb4e52f0 100644 --- a/src/Unlinker/Game/T6/ZoneDefWriterT6.h +++ b/src/Unlinker/Game/T6/ZoneDefWriterT6.h @@ -3,17 +3,15 @@ #include "ContentLister/ZoneDefWriter.h" #include "Game/T6/T6.h" -namespace T6 -{ - class ZoneDefWriter final : public AbstractZoneDefWriter - { - static void WriteKeyValuePair(ZoneDefinitionOutputStream& stream, KeyValuePair* kvp); +namespace T6 { +class ZoneDefWriter final : public AbstractZoneDefWriter { + static void WriteKeyValuePair(ZoneDefinitionOutputStream &stream, KeyValuePair *kvp); - protected: - void WriteMetaData(ZoneDefinitionOutputStream& stream, const UnlinkerArgs* args, Zone* zone) const override; - void WriteContent(ZoneDefinitionOutputStream& stream, const UnlinkerArgs* args, Zone* zone) const override; +protected: + void WriteMetaData(ZoneDefinitionOutputStream &stream, const UnlinkerArgs *args, Zone *zone) const override; + void WriteContent(ZoneDefinitionOutputStream &stream, const UnlinkerArgs *args, Zone *zone) const override; - public: - bool CanHandleZone(Zone* zone) const override; - }; -} +public: + bool CanHandleZone(Zone *zone) const override; +}; +} // namespace T6 diff --git a/src/Unlinker/Unlinker.cpp b/src/Unlinker/Unlinker.cpp index 043c7a679..5901269b3 100644 --- a/src/Unlinker/Unlinker.cpp +++ b/src/Unlinker/Unlinker.cpp @@ -1,464 +1,389 @@ #include "Unlinker.h" -#include <set> -#include <regex> #include <filesystem> #include <fstream> +#include <regex> +#include <set> -#include "Utils/ClassUtils.h" -#include "Utils/Arguments/ArgumentParser.h" -#include "ZoneLoading.h" -#include "ObjWriting.h" #include "ContentLister/ContentPrinter.h" -#include "ObjLoading.h" -#include "SearchPath/SearchPaths.h" -#include "SearchPath/SearchPathFilesystem.h" #include "ContentLister/ZoneDefWriter.h" -#include "ObjContainer/IWD/IWD.h" -#include "UnlinkerArgs.h" #include "Game/IW3/ZoneDefWriterIW3.h" #include "Game/IW4/ZoneDefWriterIW4.h" #include "Game/IW5/ZoneDefWriterIW5.h" #include "Game/T5/ZoneDefWriterT5.h" #include "Game/T6/ZoneDefWriterT6.h" +#include "ObjContainer/IWD/IWD.h" +#include "ObjLoading.h" +#include "ObjWriting.h" +#include "SearchPath/SearchPathFilesystem.h" +#include "SearchPath/SearchPaths.h" +#include "UnlinkerArgs.h" +#include "Utils/Arguments/ArgumentParser.h" +#include "Utils/ClassUtils.h" #include "Utils/ObjFileStream.h" +#include "ZoneLoading.h" namespace fs = std::filesystem; -const IZoneDefWriter* const ZONE_DEF_WRITERS[] -{ - new IW3::ZoneDefWriter(), - new IW4::ZoneDefWriter(), - new IW5::ZoneDefWriter(), - new T5::ZoneDefWriter(), - new T6::ZoneDefWriter() -}; +const IZoneDefWriter *const ZONE_DEF_WRITERS[]{new IW3::ZoneDefWriter(), new IW4::ZoneDefWriter(), new IW5::ZoneDefWriter(), new T5::ZoneDefWriter(), + new T6::ZoneDefWriter()}; -class Unlinker::Impl -{ - UnlinkerArgs m_args; - SearchPaths m_search_paths; - SearchPathFilesystem* m_last_zone_search_path; - std::set<std::string> m_absolute_search_paths; +class Unlinker::Impl { + UnlinkerArgs m_args; + SearchPaths m_search_paths; + SearchPathFilesystem *m_last_zone_search_path; + std::set<std::string> m_absolute_search_paths; - std::vector<std::unique_ptr<Zone>> m_loaded_zones; + std::vector<std::unique_ptr<Zone>> m_loaded_zones; - _NODISCARD bool ShouldLoadObj() const - { - return m_args.m_task != UnlinkerArgs::ProcessingTask::LIST && !m_args.m_skip_obj; + _NODISCARD bool ShouldLoadObj() const { return m_args.m_task != UnlinkerArgs::ProcessingTask::LIST && !m_args.m_skip_obj; } + + /** + * \brief Loads a search path. + * \param searchPath The search path to load. + */ + void LoadSearchPath(ISearchPath *searchPath) const { + if (ShouldLoadObj()) { + if (m_args.m_verbose) { + printf("Loading search path: \"%s\"\n", searchPath->GetPath().c_str()); + } + + ObjLoading::LoadIWDsInSearchPath(searchPath); + } + } + + /** + * \brief Unloads a search path. + * \param searchPath The search path to unload. + */ + void UnloadSearchPath(ISearchPath *searchPath) const { + if (ShouldLoadObj()) { + if (m_args.m_verbose) { + printf("Unloading search path: \"%s\"\n", searchPath->GetPath().c_str()); + } + + ObjLoading::UnloadIWDsInSearchPath(searchPath); + } + } + + /** + * \brief Loads all search paths that are valid for the specified zone and returns them. + * \param zonePath The path to the zone file that should be prepared for. + * \return A \c SearchPaths object that contains all search paths that should be considered when loading the specified zone. + */ + SearchPaths GetSearchPathsForZone(const std::string &zonePath) { + SearchPaths searchPathsForZone; + const auto absoluteZoneDirectory = fs::absolute(std::filesystem::path(zonePath).remove_filename()).string(); + + if (m_last_zone_search_path != nullptr && m_last_zone_search_path->GetPath() == absoluteZoneDirectory) { + searchPathsForZone.IncludeSearchPath(m_last_zone_search_path); + } else if (m_absolute_search_paths.find(absoluteZoneDirectory) == m_absolute_search_paths.end()) { + if (m_last_zone_search_path != nullptr) { + UnloadSearchPath(m_last_zone_search_path); + delete m_last_zone_search_path; + } + + m_last_zone_search_path = new SearchPathFilesystem(absoluteZoneDirectory); + searchPathsForZone.IncludeSearchPath(m_last_zone_search_path); + LoadSearchPath(m_last_zone_search_path); } - /** - * \brief Loads a search path. - * \param searchPath The search path to load. - */ - void LoadSearchPath(ISearchPath* searchPath) const - { - if (ShouldLoadObj()) - { - if (m_args.m_verbose) - { - printf("Loading search path: \"%s\"\n", searchPath->GetPath().c_str()); - } - - ObjLoading::LoadIWDsInSearchPath(searchPath); - } + for (auto *iwd : IWD::Repository) { + searchPathsForZone.IncludeSearchPath(iwd); } - /** - * \brief Unloads a search path. - * \param searchPath The search path to unload. - */ - void UnloadSearchPath(ISearchPath* searchPath) const - { - if (ShouldLoadObj()) - { - if (m_args.m_verbose) - { - printf("Unloading search path: \"%s\"\n", searchPath->GetPath().c_str()); - } - - ObjLoading::UnloadIWDsInSearchPath(searchPath); - } + return searchPathsForZone; + } + + /** + * \brief Initializes the Unlinker object's search paths based on the user's input. + * \return \c true if building the search paths was successful, otherwise \c false. + */ + bool BuildSearchPaths() { + for (const auto &path : m_args.m_user_search_paths) { + auto absolutePath = fs::absolute(path); + + if (!fs::is_directory(absolutePath)) { + printf("Could not find directory of search path: \"%s\"\n", path.c_str()); + return false; + } + + auto searchPath = std::make_unique<SearchPathFilesystem>(absolutePath.string()); + LoadSearchPath(searchPath.get()); + m_search_paths.CommitSearchPath(std::move(searchPath)); + + m_absolute_search_paths.insert(absolutePath.string()); } - /** - * \brief Loads all search paths that are valid for the specified zone and returns them. - * \param zonePath The path to the zone file that should be prepared for. - * \return A \c SearchPaths object that contains all search paths that should be considered when loading the specified zone. - */ - SearchPaths GetSearchPathsForZone(const std::string& zonePath) - { - SearchPaths searchPathsForZone; - const auto absoluteZoneDirectory = fs::absolute(std::filesystem::path(zonePath).remove_filename()).string(); - - if (m_last_zone_search_path != nullptr && m_last_zone_search_path->GetPath() == absoluteZoneDirectory) - { - searchPathsForZone.IncludeSearchPath(m_last_zone_search_path); - } - else if (m_absolute_search_paths.find(absoluteZoneDirectory) == m_absolute_search_paths.end()) - { - if (m_last_zone_search_path != nullptr) - { - UnloadSearchPath(m_last_zone_search_path); - delete m_last_zone_search_path; - } - - m_last_zone_search_path = new SearchPathFilesystem(absoluteZoneDirectory); - searchPathsForZone.IncludeSearchPath(m_last_zone_search_path); - LoadSearchPath(m_last_zone_search_path); - } - - for (auto* iwd : IWD::Repository) - { - searchPathsForZone.IncludeSearchPath(iwd); - } - - return searchPathsForZone; + if (m_args.m_verbose) { + printf("%u SearchPaths%s\n", m_absolute_search_paths.size(), !m_absolute_search_paths.empty() ? ":" : ""); + for (const auto &absoluteSearchPath : m_absolute_search_paths) { + printf(" \"%s\"\n", absoluteSearchPath.c_str()); + } + + if (!m_absolute_search_paths.empty()) { + puts(""); + } } - /** - * \brief Initializes the Unlinker object's search paths based on the user's input. - * \return \c true if building the search paths was successful, otherwise \c false. - */ - bool BuildSearchPaths() - { - for (const auto& path : m_args.m_user_search_paths) - { - auto absolutePath = fs::absolute(path); - - if (!fs::is_directory(absolutePath)) - { - printf("Could not find directory of search path: \"%s\"\n", path.c_str()); - return false; - } - - auto searchPath = std::make_unique<SearchPathFilesystem>(absolutePath.string()); - LoadSearchPath(searchPath.get()); - m_search_paths.CommitSearchPath(std::move(searchPath)); - - m_absolute_search_paths.insert(absolutePath.string()); - } - - if (m_args.m_verbose) - { - printf("%u SearchPaths%s\n", m_absolute_search_paths.size(), !m_absolute_search_paths.empty() ? ":" : ""); - for (const auto& absoluteSearchPath : m_absolute_search_paths) - { - printf(" \"%s\"\n", absoluteSearchPath.c_str()); - } - - if (!m_absolute_search_paths.empty()) - { - puts(""); - } - } - - return true; + return true; + } + + bool WriteZoneDefinitionFile(Zone *zone, const fs::path &zoneDefinitionFileFolder) const { + auto zoneDefinitionFilePath(zoneDefinitionFileFolder); + zoneDefinitionFilePath.append(zone->m_name); + zoneDefinitionFilePath.replace_extension(".zone"); + + std::ofstream zoneDefinitionFile(zoneDefinitionFilePath, std::fstream::out | std::fstream::binary); + if (!zoneDefinitionFile.is_open()) { + printf("Failed to open file for zone definition file of zone \"%s\".\n", zone->m_name.c_str()); + return false; + } + + auto result = false; + for (const auto *zoneDefWriter : ZONE_DEF_WRITERS) { + if (zoneDefWriter->CanHandleZone(zone)) { + zoneDefWriter->WriteZoneDef(zoneDefinitionFile, &m_args, zone); + result = true; + break; + } } - bool WriteZoneDefinitionFile(Zone* zone, const fs::path& zoneDefinitionFileFolder) const - { - auto zoneDefinitionFilePath(zoneDefinitionFileFolder); - zoneDefinitionFilePath.append(zone->m_name); - zoneDefinitionFilePath.replace_extension(".zone"); - - std::ofstream zoneDefinitionFile(zoneDefinitionFilePath, std::fstream::out | std::fstream::binary); - if (!zoneDefinitionFile.is_open()) - { - printf("Failed to open file for zone definition file of zone \"%s\".\n", zone->m_name.c_str()); - return false; - } - - auto result = false; - for (const auto* zoneDefWriter : ZONE_DEF_WRITERS) - { - if (zoneDefWriter->CanHandleZone(zone)) - { - zoneDefWriter->WriteZoneDef(zoneDefinitionFile, &m_args, zone); - result = true; - break; - } - } - - if (!result) - { - printf("Failed to find writer for zone definition file of zone \"%s\".\n", zone->m_name.c_str()); - } - - zoneDefinitionFile.close(); - return result; + if (!result) { + printf("Failed to find writer for zone definition file of zone \"%s\".\n", zone->m_name.c_str()); } - static bool OpenGdtFile(Zone* zone, const fs::path& outputFolder, std::ofstream& stream) - { - auto gdtFilePath(outputFolder); - gdtFilePath.append("source_data"); + zoneDefinitionFile.close(); + return result; + } - fs::create_directories(gdtFilePath); + static bool OpenGdtFile(Zone *zone, const fs::path &outputFolder, std::ofstream &stream) { + auto gdtFilePath(outputFolder); + gdtFilePath.append("source_data"); - gdtFilePath.append(zone->m_name); - gdtFilePath.replace_extension(".gdt"); + fs::create_directories(gdtFilePath); - stream = std::ofstream(gdtFilePath, std::fstream::out | std::fstream::binary); - if (!stream.is_open()) - { - printf("Failed to open file for zone definition file of zone \"%s\".\n", zone->m_name.c_str()); - return false; - } + gdtFilePath.append(zone->m_name); + gdtFilePath.replace_extension(".gdt"); - return true; + stream = std::ofstream(gdtFilePath, std::fstream::out | std::fstream::binary); + if (!stream.is_open()) { + printf("Failed to open file for zone definition file of zone \"%s\".\n", zone->m_name.c_str()); + return false; } - void UpdateAssetIncludesAndExcludes(const AssetDumpingContext& context) const - { - const auto assetTypeCount = context.m_zone->m_pools->GetAssetTypeCount(); - - ObjWriting::Configuration.AssetTypesToHandleBitfield = std::vector<bool>(assetTypeCount); - - std::vector<bool> handledSpecifiedAssets(m_args.m_specified_asset_types.size()); - for (auto i = 0; i < assetTypeCount; i++) - { - const auto assetTypeName = std::string(context.m_zone->m_pools->GetAssetTypeName(i)); - - const auto foundSpecifiedEntry = m_args.m_specified_asset_type_map.find(assetTypeName); - if (foundSpecifiedEntry != m_args.m_specified_asset_type_map.end()) - { - ObjWriting::Configuration.AssetTypesToHandleBitfield[i] = m_args.m_asset_type_handling == UnlinkerArgs::AssetTypeHandling::INCLUDE; - assert(foundSpecifiedEntry->second < handledSpecifiedAssets.size()); - handledSpecifiedAssets[foundSpecifiedEntry->second] = true; - } - else - ObjWriting::Configuration.AssetTypesToHandleBitfield[i] = m_args.m_asset_type_handling == UnlinkerArgs::AssetTypeHandling::EXCLUDE; - } - - auto anySpecifiedValueInvalid = false; - for (auto i = 0u; i < handledSpecifiedAssets.size(); i++) - { - if (!handledSpecifiedAssets[i]) - { - std::cerr << "Unknown asset type \"" << m_args.m_specified_asset_types[i] << "\"\n"; - anySpecifiedValueInvalid = true; - } - } - - if (anySpecifiedValueInvalid) - { - std::cerr << "Valid asset types are:\n"; - - auto first = true; - for (auto i = 0; i < assetTypeCount; i++) - { - const auto assetTypeName = std::string(context.m_zone->m_pools->GetAssetTypeName(i)); - - if (first) - first = false; - else - std::cerr << ", "; - std::cerr << assetTypeName; - } - std::cerr << "\n"; - } + return true; + } + + void UpdateAssetIncludesAndExcludes(const AssetDumpingContext &context) const { + const auto assetTypeCount = context.m_zone->m_pools->GetAssetTypeCount(); + + ObjWriting::Configuration.AssetTypesToHandleBitfield = std::vector<bool>(assetTypeCount); + + std::vector<bool> handledSpecifiedAssets(m_args.m_specified_asset_types.size()); + for (auto i = 0; i < assetTypeCount; i++) { + const auto assetTypeName = std::string(context.m_zone->m_pools->GetAssetTypeName(i)); + + const auto foundSpecifiedEntry = m_args.m_specified_asset_type_map.find(assetTypeName); + if (foundSpecifiedEntry != m_args.m_specified_asset_type_map.end()) { + ObjWriting::Configuration.AssetTypesToHandleBitfield[i] = m_args.m_asset_type_handling == UnlinkerArgs::AssetTypeHandling::INCLUDE; + assert(foundSpecifiedEntry->second < handledSpecifiedAssets.size()); + handledSpecifiedAssets[foundSpecifiedEntry->second] = true; + } else + ObjWriting::Configuration.AssetTypesToHandleBitfield[i] = m_args.m_asset_type_handling == UnlinkerArgs::AssetTypeHandling::EXCLUDE; } - /** - * \brief Performs the tasks specified by the command line arguments on the specified zone. - * \param zone The zone to handle. - * \return \c true if handling the zone was successful, otherwise \c false. - */ - bool HandleZone(Zone* zone) const - { - if (m_args.m_task == UnlinkerArgs::ProcessingTask::LIST) - { - const ContentPrinter printer(zone); - printer.PrintContent(); - } - else if (m_args.m_task == UnlinkerArgs::ProcessingTask::DUMP) - { - const auto outputFolderPath = m_args.GetOutputFolderPathForZone(zone); - fs::create_directories(outputFolderPath); - - fs::path zoneDefinitionFileFolder(outputFolderPath); - zoneDefinitionFileFolder.append("zone_source"); - fs::create_directories(zoneDefinitionFileFolder); - - if (!WriteZoneDefinitionFile(zone, zoneDefinitionFileFolder)) - return false; - - std::ofstream gdtStream; - AssetDumpingContext context; - context.m_zone = zone; - context.m_base_path = outputFolderPath; - - if (m_args.m_use_gdt) - { - if (!OpenGdtFile(zone, outputFolderPath, gdtStream)) - return false; - auto gdt = std::make_unique<GdtOutputStream>(gdtStream); - gdt->BeginStream(); - gdt->WriteVersion(GdtVersion(zone->m_game->GetShortName(), 1)); - context.m_gdt = std::move(gdt); - } - - UpdateAssetIncludesAndExcludes(context); - ObjWriting::DumpZone(context); - - if (m_args.m_use_gdt) - { - context.m_gdt->EndStream(); - gdtStream.close(); - } - } - - return true; + auto anySpecifiedValueInvalid = false; + for (auto i = 0u; i < handledSpecifiedAssets.size(); i++) { + if (!handledSpecifiedAssets[i]) { + std::cerr << "Unknown asset type \"" << m_args.m_specified_asset_types[i] << "\"\n"; + anySpecifiedValueInvalid = true; + } } - bool LoadZones() - { - for (const auto& zonePath : m_args.m_zones_to_load) - { - if (!fs::is_regular_file(zonePath)) - { - printf("Could not find file \"%s\".\n", zonePath.c_str()); - continue; - } + if (anySpecifiedValueInvalid) { + std::cerr << "Valid asset types are:\n"; + + auto first = true; + for (auto i = 0; i < assetTypeCount; i++) { + const auto assetTypeName = std::string(context.m_zone->m_pools->GetAssetTypeName(i)); + + if (first) + first = false; + else + std::cerr << ", "; + std::cerr << assetTypeName; + } + std::cerr << "\n"; + } + } + + /** + * \brief Performs the tasks specified by the command line arguments on the specified zone. + * \param zone The zone to handle. + * \return \c true if handling the zone was successful, otherwise \c false. + */ + bool HandleZone(Zone *zone) const { + if (m_args.m_task == UnlinkerArgs::ProcessingTask::LIST) { + const ContentPrinter printer(zone); + printer.PrintContent(); + } else if (m_args.m_task == UnlinkerArgs::ProcessingTask::DUMP) { + const auto outputFolderPath = m_args.GetOutputFolderPathForZone(zone); + fs::create_directories(outputFolderPath); + + fs::path zoneDefinitionFileFolder(outputFolderPath); + zoneDefinitionFileFolder.append("zone_source"); + fs::create_directories(zoneDefinitionFileFolder); + + if (!WriteZoneDefinitionFile(zone, zoneDefinitionFileFolder)) + return false; + + std::ofstream gdtStream; + AssetDumpingContext context; + context.m_zone = zone; + context.m_base_path = outputFolderPath; + + if (m_args.m_use_gdt) { + if (!OpenGdtFile(zone, outputFolderPath, gdtStream)) + return false; + auto gdt = std::make_unique<GdtOutputStream>(gdtStream); + gdt->BeginStream(); + gdt->WriteVersion(GdtVersion(zone->m_game->GetShortName(), 1)); + context.m_gdt = std::move(gdt); + } + + UpdateAssetIncludesAndExcludes(context); + ObjWriting::DumpZone(context); + + if (m_args.m_use_gdt) { + context.m_gdt->EndStream(); + gdtStream.close(); + } + } - auto absoluteZoneDirectory = absolute(std::filesystem::path(zonePath).remove_filename()).string(); + return true; + } - auto searchPathsForZone = GetSearchPathsForZone(absoluteZoneDirectory); - searchPathsForZone.IncludeSearchPath(&m_search_paths); + bool LoadZones() { + for (const auto &zonePath : m_args.m_zones_to_load) { + if (!fs::is_regular_file(zonePath)) { + printf("Could not find file \"%s\".\n", zonePath.c_str()); + continue; + } - auto zone = ZoneLoading::LoadZone(zonePath); - if (zone == nullptr) - { - printf("Failed to load zone \"%s\".\n", zonePath.c_str()); - return false; - } + auto absoluteZoneDirectory = absolute(std::filesystem::path(zonePath).remove_filename()).string(); - if (m_args.m_verbose) - { - printf("Loaded zone \"%s\"\n", zone->m_name.c_str()); - } + auto searchPathsForZone = GetSearchPathsForZone(absoluteZoneDirectory); + searchPathsForZone.IncludeSearchPath(&m_search_paths); - if (ShouldLoadObj()) - { - ObjLoading::LoadReferencedContainersForZone(&searchPathsForZone, zone.get()); - ObjLoading::LoadObjDataForZone(&searchPathsForZone, zone.get()); - } + auto zone = ZoneLoading::LoadZone(zonePath); + if (zone == nullptr) { + printf("Failed to load zone \"%s\".\n", zonePath.c_str()); + return false; + } + if (m_args.m_verbose) { + printf("Loaded zone \"%s\"\n", zone->m_name.c_str()); + } - m_loaded_zones.emplace_back(std::move(zone)); - } + if (ShouldLoadObj()) { + ObjLoading::LoadReferencedContainersForZone(&searchPathsForZone, zone.get()); + ObjLoading::LoadObjDataForZone(&searchPathsForZone, zone.get()); + } - return true; + m_loaded_zones.emplace_back(std::move(zone)); } - void UnloadZones() - { - for (auto i = m_loaded_zones.rbegin(); i != m_loaded_zones.rend(); ++i) - { - auto& loadedZone = *i; - std::string zoneName = loadedZone->m_name; + return true; + } - if (ShouldLoadObj()) - { - ObjLoading::UnloadContainersOfZone(loadedZone.get()); - } + void UnloadZones() { + for (auto i = m_loaded_zones.rbegin(); i != m_loaded_zones.rend(); ++i) { + auto &loadedZone = *i; + std::string zoneName = loadedZone->m_name; - loadedZone.reset(); + if (ShouldLoadObj()) { + ObjLoading::UnloadContainersOfZone(loadedZone.get()); + } - if (m_args.m_verbose) - std::cout << "Unloaded zone \"" << zoneName << "\"\n"; - } - m_loaded_zones.clear(); - } + loadedZone.reset(); - bool UnlinkZones() - { - for (const auto& zonePath : m_args.m_zones_to_unlink) - { - if (!fs::is_regular_file(zonePath)) - { - printf("Could not find file \"%s\".\n", zonePath.c_str()); - continue; - } - - auto absoluteZoneDirectory = absolute(std::filesystem::path(zonePath).remove_filename()).string(); - - auto searchPathsForZone = GetSearchPathsForZone(absoluteZoneDirectory); - searchPathsForZone.IncludeSearchPath(&m_search_paths); - - std::string zoneName; - auto zone = ZoneLoading::LoadZone(zonePath); - if (zone == nullptr) - { - printf("Failed to load zone \"%s\".\n", zonePath.c_str()); - return false; - } - - zoneName = zone->m_name; - if (m_args.m_verbose) - std::cout << "Loaded zone \"" << zoneName << "\"\n"; - - if (ShouldLoadObj()) - { - ObjLoading::LoadReferencedContainersForZone(&searchPathsForZone, zone.get()); - ObjLoading::LoadObjDataForZone(&searchPathsForZone, zone.get()); - } - - if (!HandleZone(zone.get())) - return false; - - if (ShouldLoadObj()) - ObjLoading::UnloadContainersOfZone(zone.get()); - - zone.reset(); - if (m_args.m_verbose) - std::cout << "Unloaded zone \"" << zoneName << "\"\n"; - } - - return true; + if (m_args.m_verbose) + std::cout << "Unloaded zone \"" << zoneName << "\"\n"; } + m_loaded_zones.clear(); + } + + bool UnlinkZones() { + for (const auto &zonePath : m_args.m_zones_to_unlink) { + if (!fs::is_regular_file(zonePath)) { + printf("Could not find file \"%s\".\n", zonePath.c_str()); + continue; + } + + auto absoluteZoneDirectory = absolute(std::filesystem::path(zonePath).remove_filename()).string(); + + auto searchPathsForZone = GetSearchPathsForZone(absoluteZoneDirectory); + searchPathsForZone.IncludeSearchPath(&m_search_paths); + + std::string zoneName; + auto zone = ZoneLoading::LoadZone(zonePath); + if (zone == nullptr) { + printf("Failed to load zone \"%s\".\n", zonePath.c_str()); + return false; + } + + zoneName = zone->m_name; + if (m_args.m_verbose) + std::cout << "Loaded zone \"" << zoneName << "\"\n"; + + if (ShouldLoadObj()) { + ObjLoading::LoadReferencedContainersForZone(&searchPathsForZone, zone.get()); + ObjLoading::LoadObjDataForZone(&searchPathsForZone, zone.get()); + } + + if (!HandleZone(zone.get())) + return false; + + if (ShouldLoadObj()) + ObjLoading::UnloadContainersOfZone(zone.get()); + + zone.reset(); + if (m_args.m_verbose) + std::cout << "Unloaded zone \"" << zoneName << "\"\n"; + } + + return true; + } public: - Impl() - { - m_last_zone_search_path = nullptr; - } + Impl() { m_last_zone_search_path = nullptr; } - /** - * \copydoc Unlinker::Start - */ - bool Start(const int argc, const char** argv) - { - if (!m_args.ParseArgs(argc, argv)) - return false; + /** + * \copydoc Unlinker::Start + */ + bool Start(const int argc, const char **argv) { + if (!m_args.ParseArgs(argc, argv)) + return false; - if (!BuildSearchPaths()) - return false; + if (!BuildSearchPaths()) + return false; - if (!LoadZones()) - return false; + if (!LoadZones()) + return false; - const auto result = UnlinkZones(); + const auto result = UnlinkZones(); - UnloadZones(); - return result; - } + UnloadZones(); + return result; + } }; -Unlinker::Unlinker() -{ - m_impl = new Impl(); -} +Unlinker::Unlinker() { m_impl = new Impl(); } -Unlinker::~Unlinker() -{ - delete m_impl; - m_impl = nullptr; +Unlinker::~Unlinker() { + delete m_impl; + m_impl = nullptr; } -bool Unlinker::Start(const int argc, const char** argv) const -{ - return m_impl->Start(argc, argv); -} +bool Unlinker::Start(const int argc, const char **argv) const { return m_impl->Start(argc, argv); } diff --git a/src/Unlinker/Unlinker.h b/src/Unlinker/Unlinker.h index 21653e76c..b4e81ce4f 100644 --- a/src/Unlinker/Unlinker.h +++ b/src/Unlinker/Unlinker.h @@ -1,24 +1,23 @@ #pragma once -class Unlinker -{ - class Impl; - Impl* m_impl; +class Unlinker { + class Impl; + Impl *m_impl; public: - Unlinker(); - ~Unlinker(); + Unlinker(); + ~Unlinker(); - Unlinker(const Unlinker& other) = delete; - Unlinker(Unlinker&& other) noexcept = delete; - Unlinker& operator=(const Unlinker& other) = delete; - Unlinker& operator=(Unlinker&& other) noexcept = delete; + Unlinker(const Unlinker &other) = delete; + Unlinker(Unlinker &&other) noexcept = delete; + Unlinker &operator=(const Unlinker &other) = delete; + Unlinker &operator=(Unlinker &&other) noexcept = delete; - /** - * \brief Starts the Unlinker application logic. - * \param argc The amount of command line arguments specified. - * \param argv The command line arguments. - * \return \c true if the application was successful or \c false if an error occurred. - */ - bool Start(int argc, const char** argv) const; + /** + * \brief Starts the Unlinker application logic. + * \param argc The amount of command line arguments specified. + * \param argv The command line arguments. + * \return \c true if the application was successful or \c false if an error occurred. + */ + bool Start(int argc, const char **argv) const; }; \ No newline at end of file diff --git a/src/Unlinker/UnlinkerArgs.cpp b/src/Unlinker/UnlinkerArgs.cpp index 25caad324..7c180489e 100644 --- a/src/Unlinker/UnlinkerArgs.cpp +++ b/src/Unlinker/UnlinkerArgs.cpp @@ -3,344 +3,269 @@ #include <regex> #include <type_traits> -#include "Utils/Arguments/UsageInformation.h" #include "ObjLoading.h" #include "ObjWriting.h" +#include "Utils/Arguments/UsageInformation.h" #include "Utils/FileUtils.h" -const CommandLineOption* const OPTION_HELP = - CommandLineOption::Builder::Create() - .WithShortName("?") - .WithLongName("help") - .WithDescription("Displays usage information.") - .Build(); - -const CommandLineOption* const OPTION_VERBOSE = - CommandLineOption::Builder::Create() - .WithShortName("v") - .WithLongName("verbose") - .WithDescription("Outputs a lot more and more detailed messages.") - .Build(); - -const CommandLineOption* const OPTION_MINIMAL_ZONE_FILE = - CommandLineOption::Builder::Create() - .WithShortName("min") - .WithLongName("minimal-zone") - .WithDescription("Minimizes the size of the zone file output by only including assets that are not a dependency of another asset.") - .Build(); - -const CommandLineOption* const OPTION_LOAD = - CommandLineOption::Builder::Create() - .WithShortName("l") - .WithLongName("load") - .WithDescription("Loads an existing zone before trying to unlink any zone.") - .WithParameter("zonePath") - .Reusable() - .Build(); - -const CommandLineOption* const OPTION_LIST = - CommandLineOption::Builder::Create() - .WithLongName("list") - .WithDescription("Lists the contents of a zone instead of writing them to the disk.") - .Build(); - -const CommandLineOption* const OPTION_OUTPUT_FOLDER = - CommandLineOption::Builder::Create() - .WithShortName("o") - .WithLongName("output-folder") - .WithDescription("Specifies the output folder containing the contents of the unlinked zones. Defaults to \"" + std::string(UnlinkerArgs::DEFAULT_OUTPUT_FOLDER) + "\"") - .WithParameter("outputFolderPath") - .Build(); - -const CommandLineOption* const OPTION_SEARCH_PATH = - CommandLineOption::Builder::Create() - .WithLongName("search-path") - .WithDescription("Specifies a semi-colon separated list of paths to search for additional game files.") - .WithParameter("searchPathString") - .Build(); +const CommandLineOption *const OPTION_HELP = + CommandLineOption::Builder::Create().WithShortName("?").WithLongName("help").WithDescription("Displays usage information.").Build(); -const CommandLineOption* const OPTION_IMAGE_FORMAT = - CommandLineOption::Builder::Create() - .WithLongName("image-format") - .WithDescription("Specifies the format of dumped image files. Valid values are: DDS, IWI") - .WithParameter("imageFormatValue") - .Build(); +const CommandLineOption *const OPTION_VERBOSE = + CommandLineOption::Builder::Create().WithShortName("v").WithLongName("verbose").WithDescription("Outputs a lot more and more detailed messages.").Build(); -const CommandLineOption* const OPTION_MODEL_FORMAT = +const CommandLineOption *const OPTION_MINIMAL_ZONE_FILE = CommandLineOption::Builder::Create() - .WithLongName("model-format") - .WithDescription("Specifies the format of dumped model files. Valid values are: XMODEL_EXPORT, OBJ") - .WithParameter("modelFormatValue") - .Build(); - -const CommandLineOption* const OPTION_SKIP_OBJ = + .WithShortName("min") + .WithLongName("minimal-zone") + .WithDescription("Minimizes the size of the zone file output by only including assets that are not a dependency of another asset.") + .Build(); + +const CommandLineOption *const OPTION_LOAD = CommandLineOption::Builder::Create() + .WithShortName("l") + .WithLongName("load") + .WithDescription("Loads an existing zone before trying to unlink any zone.") + .WithParameter("zonePath") + .Reusable() + .Build(); + +const CommandLineOption *const OPTION_LIST = + CommandLineOption::Builder::Create().WithLongName("list").WithDescription("Lists the contents of a zone instead of writing them to the disk.").Build(); + +const CommandLineOption *const OPTION_OUTPUT_FOLDER = CommandLineOption::Builder::Create() - .WithLongName("skip-obj") - .WithDescription("Skips loading raw obj data.") - .Build(); - -const CommandLineOption* const OPTION_GDT = + .WithShortName("o") + .WithLongName("output-folder") + .WithDescription("Specifies the output folder containing the contents of the unlinked zones. Defaults to \"" + + std::string(UnlinkerArgs::DEFAULT_OUTPUT_FOLDER) + "\"") + .WithParameter("outputFolderPath") + .Build(); + +const CommandLineOption *const OPTION_SEARCH_PATH = CommandLineOption::Builder::Create() + .WithLongName("search-path") + .WithDescription("Specifies a semi-colon separated list of paths to search for additional game files.") + .WithParameter("searchPathString") + .Build(); + +const CommandLineOption *const OPTION_IMAGE_FORMAT = CommandLineOption::Builder::Create() + .WithLongName("image-format") + .WithDescription("Specifies the format of dumped image files. Valid values are: DDS, IWI") + .WithParameter("imageFormatValue") + .Build(); + +const CommandLineOption *const OPTION_MODEL_FORMAT = CommandLineOption::Builder::Create() + .WithLongName("model-format") + .WithDescription("Specifies the format of dumped model files. Valid values are: XMODEL_EXPORT, OBJ") + .WithParameter("modelFormatValue") + .Build(); + +const CommandLineOption *const OPTION_SKIP_OBJ = + CommandLineOption::Builder::Create().WithLongName("skip-obj").WithDescription("Skips loading raw obj data.").Build(); + +const CommandLineOption *const OPTION_GDT = + CommandLineOption::Builder::Create().WithLongName("gdt").WithDescription("Dumps assets in a GDT whenever possible.").Build(); + +const CommandLineOption *const OPTION_EXCLUDE_ASSETS = CommandLineOption::Builder::Create() + .WithLongName("exclude-assets") + .WithDescription("Specify all asset types that should be excluded.") + .WithParameter("assetTypeList") + .Reusable() + .Build(); + +const CommandLineOption *const OPTION_INCLUDE_ASSETS = CommandLineOption::Builder::Create() + .WithLongName("include-assets") + .WithDescription("Specify all asset types that should be included.") + .WithParameter("assetTypeList") + .Reusable() + .Build(); + +const CommandLineOption *const OPTION_LEGACY_MENUS = CommandLineOption::Builder::Create() - .WithLongName("gdt") - .WithDescription("Dumps assets in a GDT whenever possible.") - .Build(); + .WithLongName("legacy-menus") + .WithDescription("Dumps menus with a compatibility mode to work with applications not compatible with the newer dumping mode.") + .Build(); -const CommandLineOption* const OPTION_EXCLUDE_ASSETS = - CommandLineOption::Builder::Create() - .WithLongName("exclude-assets") - .WithDescription("Specify all asset types that should be excluded.") - .WithParameter("assetTypeList") - .Reusable() - .Build(); - -const CommandLineOption* const OPTION_INCLUDE_ASSETS = - CommandLineOption::Builder::Create() - .WithLongName("include-assets") - .WithDescription("Specify all asset types that should be included.") - .WithParameter("assetTypeList") - .Reusable() - .Build(); - -const CommandLineOption* const OPTION_LEGACY_MENUS = - CommandLineOption::Builder::Create() - .WithLongName("legacy-menus") - .WithDescription("Dumps menus with a compatibility mode to work with applications not compatible with the newer dumping mode.") - .Build(); - -const CommandLineOption* const COMMAND_LINE_OPTIONS[] -{ - OPTION_HELP, - OPTION_VERBOSE, - OPTION_MINIMAL_ZONE_FILE, - OPTION_LOAD, - OPTION_LIST, - OPTION_OUTPUT_FOLDER, - OPTION_SEARCH_PATH, - OPTION_IMAGE_FORMAT, - OPTION_MODEL_FORMAT, - OPTION_SKIP_OBJ, - OPTION_GDT, - OPTION_EXCLUDE_ASSETS, - OPTION_INCLUDE_ASSETS, - OPTION_LEGACY_MENUS -}; +const CommandLineOption *const COMMAND_LINE_OPTIONS[]{ + OPTION_HELP, OPTION_VERBOSE, OPTION_MINIMAL_ZONE_FILE, OPTION_LOAD, OPTION_LIST, OPTION_OUTPUT_FOLDER, OPTION_SEARCH_PATH, + OPTION_IMAGE_FORMAT, OPTION_MODEL_FORMAT, OPTION_SKIP_OBJ, OPTION_GDT, OPTION_EXCLUDE_ASSETS, OPTION_INCLUDE_ASSETS, OPTION_LEGACY_MENUS}; UnlinkerArgs::UnlinkerArgs() - : m_argument_parser(COMMAND_LINE_OPTIONS, std::extent_v<decltype(COMMAND_LINE_OPTIONS)>), - m_zone_pattern(R"(\?zone\?)"), - m_task(ProcessingTask::DUMP), - m_minimal_zone_def(false), - m_asset_type_handling(AssetTypeHandling::EXCLUDE), - m_skip_obj(false), - m_use_gdt(false), - m_verbose(false) -{ -} + : m_argument_parser(COMMAND_LINE_OPTIONS, std::extent_v<decltype(COMMAND_LINE_OPTIONS)>), m_zone_pattern(R"(\?zone\?)"), m_task(ProcessingTask::DUMP), + m_minimal_zone_def(false), m_asset_type_handling(AssetTypeHandling::EXCLUDE), m_skip_obj(false), m_use_gdt(false), m_verbose(false) {} -void UnlinkerArgs::PrintUsage() -{ - UsageInformation usage("Unlinker.exe"); +void UnlinkerArgs::PrintUsage() { + UsageInformation usage("Unlinker.exe"); - for (const auto* commandLineOption : COMMAND_LINE_OPTIONS) - { - usage.AddCommandLineOption(commandLineOption); - } + for (const auto *commandLineOption : COMMAND_LINE_OPTIONS) { + usage.AddCommandLineOption(commandLineOption); + } - usage.AddArgument("pathToZone"); - usage.SetVariableArguments(true); + usage.AddArgument("pathToZone"); + usage.SetVariableArguments(true); - usage.Print(); + usage.Print(); } -void UnlinkerArgs::SetVerbose(const bool isVerbose) -{ - m_verbose = isVerbose; - ObjLoading::Configuration.Verbose = isVerbose; - ObjWriting::Configuration.Verbose = isVerbose; +void UnlinkerArgs::SetVerbose(const bool isVerbose) { + m_verbose = isVerbose; + ObjLoading::Configuration.Verbose = isVerbose; + ObjWriting::Configuration.Verbose = isVerbose; } -bool UnlinkerArgs::SetImageDumpingMode() -{ - auto specifiedValue = m_argument_parser.GetValueForOption(OPTION_IMAGE_FORMAT); - for (auto& c : specifiedValue) - c = static_cast<char>(tolower(c)); +bool UnlinkerArgs::SetImageDumpingMode() { + auto specifiedValue = m_argument_parser.GetValueForOption(OPTION_IMAGE_FORMAT); + for (auto &c : specifiedValue) + c = static_cast<char>(tolower(c)); - if (specifiedValue == "dds") - { - ObjWriting::Configuration.ImageOutputFormat = ObjWriting::Configuration_t::ImageOutputFormat_e::DDS; - return true; - } + if (specifiedValue == "dds") { + ObjWriting::Configuration.ImageOutputFormat = ObjWriting::Configuration_t::ImageOutputFormat_e::DDS; + return true; + } - if (specifiedValue == "iwi") - { - ObjWriting::Configuration.ImageOutputFormat = ObjWriting::Configuration_t::ImageOutputFormat_e::IWI; - return true; - } + if (specifiedValue == "iwi") { + ObjWriting::Configuration.ImageOutputFormat = ObjWriting::Configuration_t::ImageOutputFormat_e::IWI; + return true; + } - const std::string originalValue = m_argument_parser.GetValueForOption(OPTION_IMAGE_FORMAT); - printf("Illegal value: \"%s\" is not a valid image output format. Use -? to see usage information.\n", originalValue.c_str()); - return false; + const std::string originalValue = m_argument_parser.GetValueForOption(OPTION_IMAGE_FORMAT); + printf("Illegal value: \"%s\" is not a valid image output format. Use -? to see usage information.\n", originalValue.c_str()); + return false; } -bool UnlinkerArgs::SetModelDumpingMode() -{ - auto specifiedValue = m_argument_parser.GetValueForOption(OPTION_MODEL_FORMAT); - for (auto& c : specifiedValue) - c = static_cast<char>(tolower(c)); +bool UnlinkerArgs::SetModelDumpingMode() { + auto specifiedValue = m_argument_parser.GetValueForOption(OPTION_MODEL_FORMAT); + for (auto &c : specifiedValue) + c = static_cast<char>(tolower(c)); - if (specifiedValue == "xmodel_export") - { - ObjWriting::Configuration.ModelOutputFormat = ObjWriting::Configuration_t::ModelOutputFormat_e::XMODEL_EXPORT; - return true; - } + if (specifiedValue == "xmodel_export") { + ObjWriting::Configuration.ModelOutputFormat = ObjWriting::Configuration_t::ModelOutputFormat_e::XMODEL_EXPORT; + return true; + } - if (specifiedValue == "obj") - { - ObjWriting::Configuration.ModelOutputFormat = ObjWriting::Configuration_t::ModelOutputFormat_e::OBJ; - return true; - } + if (specifiedValue == "obj") { + ObjWriting::Configuration.ModelOutputFormat = ObjWriting::Configuration_t::ModelOutputFormat_e::OBJ; + return true; + } - const std::string originalValue = m_argument_parser.GetValueForOption(OPTION_MODEL_FORMAT); - printf("Illegal value: \"%s\" is not a valid model output format. Use -? to see usage information.\n", originalValue.c_str()); - return false; + const std::string originalValue = m_argument_parser.GetValueForOption(OPTION_MODEL_FORMAT); + printf("Illegal value: \"%s\" is not a valid model output format. Use -? to see usage information.\n", originalValue.c_str()); + return false; } -void UnlinkerArgs::AddSpecifiedAssetType(std::string value) -{ - const auto alreadySpecifiedAssetType = m_specified_asset_type_map.find(value); - if (alreadySpecifiedAssetType == m_specified_asset_type_map.end()) - { - m_specified_asset_type_map.emplace(std::make_pair(value, m_specified_asset_types.size())); - m_specified_asset_types.emplace_back(std::move(value)); - } +void UnlinkerArgs::AddSpecifiedAssetType(std::string value) { + const auto alreadySpecifiedAssetType = m_specified_asset_type_map.find(value); + if (alreadySpecifiedAssetType == m_specified_asset_type_map.end()) { + m_specified_asset_type_map.emplace(std::make_pair(value, m_specified_asset_types.size())); + m_specified_asset_types.emplace_back(std::move(value)); + } } -void UnlinkerArgs::ParseCommaSeparatedAssetTypeString(const std::string& input) -{ - auto currentPos = 0u; - size_t endPos; +void UnlinkerArgs::ParseCommaSeparatedAssetTypeString(const std::string &input) { + auto currentPos = 0u; + size_t endPos; - std::string lowerInput(input); - for (auto& c : lowerInput) - c = static_cast<char>(tolower(c)); + std::string lowerInput(input); + for (auto &c : lowerInput) + c = static_cast<char>(tolower(c)); - while (currentPos < lowerInput.size() && (endPos = lowerInput.find_first_of(',', currentPos)) != std::string::npos) - { - AddSpecifiedAssetType(std::string(lowerInput, currentPos, endPos - currentPos)); - currentPos = endPos + 1; - } + while (currentPos < lowerInput.size() && (endPos = lowerInput.find_first_of(',', currentPos)) != std::string::npos) { + AddSpecifiedAssetType(std::string(lowerInput, currentPos, endPos - currentPos)); + currentPos = endPos + 1; + } - if (currentPos < lowerInput.size()) - AddSpecifiedAssetType(std::string(lowerInput, currentPos, lowerInput.size() - currentPos)); + if (currentPos < lowerInput.size()) + AddSpecifiedAssetType(std::string(lowerInput, currentPos, lowerInput.size() - currentPos)); } -bool UnlinkerArgs::ParseArgs(const int argc, const char** argv) -{ - if (!m_argument_parser.ParseArguments(argc - 1, &argv[1])) - { - PrintUsage(); - return false; - } - - // Check if the user requested help - if (m_argument_parser.IsOptionSpecified(OPTION_HELP)) - { - PrintUsage(); - return false; - } - - m_zones_to_unlink = m_argument_parser.GetArguments(); - const size_t zoneCount = m_zones_to_unlink.size(); - if (zoneCount < 1) - { - // No zones to load specified... - PrintUsage(); - return false; - } +bool UnlinkerArgs::ParseArgs(const int argc, const char **argv) { + if (!m_argument_parser.ParseArguments(argc - 1, &argv[1])) { + PrintUsage(); + return false; + } + // Check if the user requested help + if (m_argument_parser.IsOptionSpecified(OPTION_HELP)) { + PrintUsage(); + return false; + } - // -v; --verbose - SetVerbose(m_argument_parser.IsOptionSpecified(OPTION_VERBOSE)); + m_zones_to_unlink = m_argument_parser.GetArguments(); + const size_t zoneCount = m_zones_to_unlink.size(); + if (zoneCount < 1) { + // No zones to load specified... + PrintUsage(); + return false; + } - // -min; --minimal-zone - m_minimal_zone_def = m_argument_parser.IsOptionSpecified(OPTION_MINIMAL_ZONE_FILE); + // -v; --verbose + SetVerbose(m_argument_parser.IsOptionSpecified(OPTION_VERBOSE)); - // -l; --load - if (m_argument_parser.IsOptionSpecified(OPTION_LOAD)) - m_zones_to_load = m_argument_parser.GetParametersForOption(OPTION_LOAD); + // -min; --minimal-zone + m_minimal_zone_def = m_argument_parser.IsOptionSpecified(OPTION_MINIMAL_ZONE_FILE); - // --list - if (m_argument_parser.IsOptionSpecified(OPTION_LIST)) - m_task = ProcessingTask::LIST; + // -l; --load + if (m_argument_parser.IsOptionSpecified(OPTION_LOAD)) + m_zones_to_load = m_argument_parser.GetParametersForOption(OPTION_LOAD); - // -o; --output-folder - if (m_argument_parser.IsOptionSpecified(OPTION_OUTPUT_FOLDER)) - m_output_folder = m_argument_parser.GetValueForOption(OPTION_OUTPUT_FOLDER); - else - m_output_folder = DEFAULT_OUTPUT_FOLDER; + // --list + if (m_argument_parser.IsOptionSpecified(OPTION_LIST)) + m_task = ProcessingTask::LIST; - // --search-path - if (m_argument_parser.IsOptionSpecified(OPTION_SEARCH_PATH)) - { - if (!FileUtils::ParsePathsString(m_argument_parser.GetValueForOption(OPTION_SEARCH_PATH), m_user_search_paths)) - { - return false; - } - } + // -o; --output-folder + if (m_argument_parser.IsOptionSpecified(OPTION_OUTPUT_FOLDER)) + m_output_folder = m_argument_parser.GetValueForOption(OPTION_OUTPUT_FOLDER); + else + m_output_folder = DEFAULT_OUTPUT_FOLDER; - // --image-format - if (m_argument_parser.IsOptionSpecified(OPTION_IMAGE_FORMAT)) - { - if (!SetImageDumpingMode()) - { - return false; - } + // --search-path + if (m_argument_parser.IsOptionSpecified(OPTION_SEARCH_PATH)) { + if (!FileUtils::ParsePathsString(m_argument_parser.GetValueForOption(OPTION_SEARCH_PATH), m_user_search_paths)) { + return false; } + } - // --model-format - if (m_argument_parser.IsOptionSpecified(OPTION_MODEL_FORMAT)) - { - if (!SetModelDumpingMode()) - { - return false; - } + // --image-format + if (m_argument_parser.IsOptionSpecified(OPTION_IMAGE_FORMAT)) { + if (!SetImageDumpingMode()) { + return false; } + } - // --skip-obj - m_skip_obj = m_argument_parser.IsOptionSpecified(OPTION_SKIP_OBJ); - - // --gdt - m_use_gdt = m_argument_parser.IsOptionSpecified(OPTION_GDT); - - // --exclude-assets - // --include-assets - if (m_argument_parser.IsOptionSpecified(OPTION_EXCLUDE_ASSETS) && m_argument_parser.IsOptionSpecified(OPTION_INCLUDE_ASSETS)) - { - std::cout << "You can only asset types to either exclude or include, not both\n"; - return false; + // --model-format + if (m_argument_parser.IsOptionSpecified(OPTION_MODEL_FORMAT)) { + if (!SetModelDumpingMode()) { + return false; } + } - if (m_argument_parser.IsOptionSpecified(OPTION_EXCLUDE_ASSETS)) - { - m_asset_type_handling = AssetTypeHandling::EXCLUDE; - for (const auto& exclude : m_argument_parser.GetParametersForOption(OPTION_EXCLUDE_ASSETS)) - ParseCommaSeparatedAssetTypeString(exclude); - } - else if (m_argument_parser.IsOptionSpecified(OPTION_INCLUDE_ASSETS)) - { - m_asset_type_handling = AssetTypeHandling::INCLUDE; - for (const auto& include : m_argument_parser.GetParametersForOption(OPTION_INCLUDE_ASSETS)) - ParseCommaSeparatedAssetTypeString(include); - } + // --skip-obj + m_skip_obj = m_argument_parser.IsOptionSpecified(OPTION_SKIP_OBJ); - // --legacy-menus - if (m_argument_parser.IsOptionSpecified(OPTION_LEGACY_MENUS)) - ObjWriting::Configuration.MenuLegacyMode = true; + // --gdt + m_use_gdt = m_argument_parser.IsOptionSpecified(OPTION_GDT); - return true; + // --exclude-assets + // --include-assets + if (m_argument_parser.IsOptionSpecified(OPTION_EXCLUDE_ASSETS) && m_argument_parser.IsOptionSpecified(OPTION_INCLUDE_ASSETS)) { + std::cout << "You can only asset types to either exclude or include, not both\n"; + return false; + } + + if (m_argument_parser.IsOptionSpecified(OPTION_EXCLUDE_ASSETS)) { + m_asset_type_handling = AssetTypeHandling::EXCLUDE; + for (const auto &exclude : m_argument_parser.GetParametersForOption(OPTION_EXCLUDE_ASSETS)) + ParseCommaSeparatedAssetTypeString(exclude); + } else if (m_argument_parser.IsOptionSpecified(OPTION_INCLUDE_ASSETS)) { + m_asset_type_handling = AssetTypeHandling::INCLUDE; + for (const auto &include : m_argument_parser.GetParametersForOption(OPTION_INCLUDE_ASSETS)) + ParseCommaSeparatedAssetTypeString(include); + } + + // --legacy-menus + if (m_argument_parser.IsOptionSpecified(OPTION_LEGACY_MENUS)) + ObjWriting::Configuration.MenuLegacyMode = true; + + return true; } -std::string UnlinkerArgs::GetOutputFolderPathForZone(const Zone* zone) const -{ - return std::regex_replace(m_output_folder, m_zone_pattern, zone->m_name); -} +std::string UnlinkerArgs::GetOutputFolderPathForZone(const Zone *zone) const { return std::regex_replace(m_output_folder, m_zone_pattern, zone->m_name); } diff --git a/src/Unlinker/UnlinkerArgs.h b/src/Unlinker/UnlinkerArgs.h index 7a4d081f3..28b8a8ca5 100644 --- a/src/Unlinker/UnlinkerArgs.h +++ b/src/Unlinker/UnlinkerArgs.h @@ -1,71 +1,62 @@ #pragma once #include <regex> #include <set> -#include <vector> #include <string> #include <unordered_map> +#include <vector> #include "Utils/Arguments/ArgumentParser.h" #include "Zone/Zone.h" -class UnlinkerArgs -{ +class UnlinkerArgs { public: - static constexpr const char* DEFAULT_OUTPUT_FOLDER = "zone_dump/zone_raw/?zone?"; + static constexpr const char *DEFAULT_OUTPUT_FOLDER = "zone_dump/zone_raw/?zone?"; private: - ArgumentParser m_argument_parser; - std::regex m_zone_pattern; + ArgumentParser m_argument_parser; + std::regex m_zone_pattern; - /** - * \brief Prints a command line usage help text for the Unlinker tool to stdout. - */ - static void PrintUsage(); + /** + * \brief Prints a command line usage help text for the Unlinker tool to stdout. + */ + static void PrintUsage(); - void SetVerbose(bool isVerbose); - bool SetImageDumpingMode(); - bool SetModelDumpingMode(); + void SetVerbose(bool isVerbose); + bool SetImageDumpingMode(); + bool SetModelDumpingMode(); - void AddSpecifiedAssetType(std::string value); - void ParseCommaSeparatedAssetTypeString(const std::string& input); + void AddSpecifiedAssetType(std::string value); + void ParseCommaSeparatedAssetTypeString(const std::string &input); public: - enum class ProcessingTask - { - DUMP, - LIST - }; + enum class ProcessingTask { DUMP, LIST }; - enum class AssetTypeHandling - { - EXCLUDE, - INCLUDE - }; + enum class AssetTypeHandling { EXCLUDE, INCLUDE }; - std::vector<std::string> m_zones_to_load; - std::vector<std::string> m_zones_to_unlink; - std::set<std::string> m_user_search_paths; + std::vector<std::string> m_zones_to_load; + std::vector<std::string> m_zones_to_unlink; + std::set<std::string> m_user_search_paths; - ProcessingTask m_task; - std::string m_output_folder; - bool m_minimal_zone_def; + ProcessingTask m_task; + std::string m_output_folder; + bool m_minimal_zone_def; - std::vector<std::string> m_specified_asset_types; - std::unordered_map<std::string, size_t> m_specified_asset_type_map; - AssetTypeHandling m_asset_type_handling; + std::vector<std::string> m_specified_asset_types; + std::unordered_map<std::string, size_t> m_specified_asset_type_map; + AssetTypeHandling m_asset_type_handling; - bool m_skip_obj; - bool m_use_gdt; + bool m_skip_obj; + bool m_use_gdt; - bool m_verbose; + bool m_verbose; - UnlinkerArgs(); - bool ParseArgs(int argc, const char** argv); + UnlinkerArgs(); + bool ParseArgs(int argc, const char **argv); - /** - * \brief Converts the output path specified by command line arguments to a path applies for the specified zone. - * \param zone The zone to resolve the path input for. - * \return An output path for the zone based on the user input. - */ - std::string GetOutputFolderPathForZone(const Zone* zone) const; + /** + * \brief Converts the output path specified by command line arguments to a path applies for the specified zone. + * \param zone The zone to resolve the path input for. + * \return An output path for the zone based on the user input. + */ + std::string GetOutputFolderPathForZone(const Zone *zone) const; }; diff --git a/src/Unlinker/main.cpp b/src/Unlinker/main.cpp index 9a326acb9..0156665af 100644 --- a/src/Unlinker/main.cpp +++ b/src/Unlinker/main.cpp @@ -1,8 +1,7 @@ #include "Unlinker.h" -int main(const int argc, const char** argv) -{ - Unlinker unlinker; +int main(const int argc, const char **argv) { + Unlinker unlinker; - return unlinker.Start(argc, argv) ? 0 : 1; + return unlinker.Start(argc, argv) ? 0 : 1; } diff --git a/src/Utils/Math/Matrix.h b/src/Utils/Math/Matrix.h index 4f5006e77..e603ce8a4 100644 --- a/src/Utils/Math/Matrix.h +++ b/src/Utils/Math/Matrix.h @@ -1,38 +1,26 @@ #pragma once -template <typename T> -class Matrix -{ +template <typename T> class Matrix { public: - T m_data[4][4]; + T m_data[4][4]; - Matrix() - : m_data{ - {T(1.0), 0, 0, 0}, - {0, T(1.0), 0, 0}, - {0, 0, T(1.0), 0}, - {0, 0, 0, T(1.0)} - } - { - } + Matrix() + : m_data{ + {T(1.0), 0, 0, 0 }, + {0, T(1.0), 0, 0 }, + {0, 0, T(1.0), 0 }, + {0, 0, 0, T(1.0)} + } {} - Matrix(T d00, T d01, T d02, T d03, - T d10, T d11, T d12, T d13, - T d20, T d21, T d22, T d23, - T d30, T d31, T d32, T d33) - : m_data{ + Matrix(T d00, T d01, T d02, T d03, T d10, T d11, T d12, T d13, T d20, T d21, T d22, T d23, T d30, T d31, T d32, T d33) + : m_data{ {d00, d01, d02, d03}, {d10, d11, d12, d13}, {d20, d21, d22, d23}, {d30, d31, d32, d33} - } - { - } + } {} - static Matrix<T> Identity() - { - return Matrix(); - } + static Matrix<T> Identity() { return Matrix(); } }; typedef Matrix<float> Matrix32; diff --git a/src/Utils/Math/Quaternion.h b/src/Utils/Math/Quaternion.h index 2d0336ece..cc0743af6 100644 --- a/src/Utils/Math/Quaternion.h +++ b/src/Utils/Math/Quaternion.h @@ -1,62 +1,52 @@ #pragma once -#include "Utils/ClassUtils.h" #include "Matrix.h" +#include "Utils/ClassUtils.h" -template <typename T> -class Quaternion -{ +template <typename T> class Quaternion { public: - T m_x; - T m_y; - T m_z; - T m_w; - - Quaternion() - { - m_x = T(0); - m_y = T(0); - m_z = T(0); - m_w = T(1); - } - - Quaternion(T x, T y, T z, T w) - { - m_x = x; - m_y = y; - m_z = z; - m_w = w; - } - - _NODISCARD Matrix<T> ToMatrix() const - { - const T xx = m_x * m_x; - const T xy = m_x * m_y; - const T xz = m_x * m_z; - const T xw = m_x * m_w; - const T yy = m_y * m_y; - const T yz = m_y * m_z; - const T yw = m_y * m_w; - const T zz = m_z * m_z; - const T zw = m_z * m_w; - - const T m00 = 1 - 2 * yy - 2 * zz; - const T m01 = 2 * xy - 2 * zw; - const T m02 = 2 * xz + 2 * yw; - const T m10 = 2 * xy + 2 * zw; - const T m11 = 1 - 2 * xx - 2 * zz; - const T m12 = 2 * yz - 2 * xw; - const T m20 = 2 * xz - 2 * yw; - const T m21 = 2 * yz + 2 * xw; - const T m22 = 1 - 2 * xx - 2 * yy; - - return Matrix<T>( - m00, m01, m02, 0, - m10, m11, m12, 0, - m20, m21, m22, 0, - 0, 0, 0, T(1.0) - ); - } + T m_x; + T m_y; + T m_z; + T m_w; + + Quaternion() { + m_x = T(0); + m_y = T(0); + m_z = T(0); + m_w = T(1); + } + + Quaternion(T x, T y, T z, T w) { + m_x = x; + m_y = y; + m_z = z; + m_w = w; + } + + _NODISCARD Matrix<T> ToMatrix() const { + const T xx = m_x * m_x; + const T xy = m_x * m_y; + const T xz = m_x * m_z; + const T xw = m_x * m_w; + const T yy = m_y * m_y; + const T yz = m_y * m_z; + const T yw = m_y * m_w; + const T zz = m_z * m_z; + const T zw = m_z * m_w; + + const T m00 = 1 - 2 * yy - 2 * zz; + const T m01 = 2 * xy - 2 * zw; + const T m02 = 2 * xz + 2 * yw; + const T m10 = 2 * xy + 2 * zw; + const T m11 = 1 - 2 * xx - 2 * zz; + const T m12 = 2 * yz - 2 * xw; + const T m20 = 2 * xz - 2 * yw; + const T m21 = 2 * yz + 2 * xw; + const T m22 = 1 - 2 * xx - 2 * yy; + + return Matrix<T>(m00, m01, m02, 0, m10, m11, m12, 0, m20, m21, m22, 0, 0, 0, 0, T(1.0)); + } }; typedef Quaternion<float> Quaternion32; diff --git a/src/Utils/Math/Vector.h b/src/Utils/Math/Vector.h index 7fa9caac2..67c5181d3 100644 --- a/src/Utils/Math/Vector.h +++ b/src/Utils/Math/Vector.h @@ -3,149 +3,110 @@ #include "Utils/ClassUtils.h" -template <typename T> -class Vector2 -{ - T m_value[2]; +template <typename T> class Vector2 { + T m_value[2]; public: - Vector2() - : m_value{ T(0), T(0)} - { - } - - Vector2(T x, T y) - : m_value{ x, y } - { - } - - explicit Vector2(const T* value) - : m_value{ value[0], value[1] } - { - } - - _NODISCARD T& operator()(const size_t index) - { - assert(index < 2); - return m_value[index]; - } - - _NODISCARD const T& operator()(const size_t index) const - { - assert(index < 2); - return m_value[index]; - } - - _NODISCARD T& x() { return m_value[0]; } - _NODISCARD T& y() { return m_value[1]; } - _NODISCARD const T& x() const { return m_value[0]; } - _NODISCARD const T& y() const { return m_value[1]; } + Vector2() : m_value{T(0), T(0)} {} + + Vector2(T x, T y) : m_value{x, y} {} + + explicit Vector2(const T *value) : m_value{value[0], value[1]} {} + + _NODISCARD T &operator()(const size_t index) { + assert(index < 2); + return m_value[index]; + } + + _NODISCARD const T &operator()(const size_t index) const { + assert(index < 2); + return m_value[index]; + } + + _NODISCARD T &x() { return m_value[0]; } + _NODISCARD T &y() { return m_value[1]; } + _NODISCARD const T &x() const { return m_value[0]; } + _NODISCARD const T &y() const { return m_value[1]; } }; typedef Vector2<float> Vector2f; typedef Vector2<double> Vector2d; -template <typename T> -class Vector3 -{ - T m_value[3]; +template <typename T> class Vector3 { + T m_value[3]; public: - Vector3() - : m_value{ T(0), T(0), T(0) } - { - } - - Vector3(T x, T y, T z) - : m_value{ x, y, z } - { - } - - explicit Vector3(const T* value) - : m_value{ value[0], value[1], value[2] } - { - } - - _NODISCARD T& operator()(const size_t index) - { - assert(index < 3); - return m_value[index]; - } - - _NODISCARD const T& operator()(const size_t index) const - { - assert(index < 3); - return m_value[index]; - } - - _NODISCARD T& x() { return m_value[0]; } - _NODISCARD T& y() { return m_value[1]; } - _NODISCARD T& z() { return m_value[2]; } - _NODISCARD const T& x() const { return m_value[0]; } - _NODISCARD const T& y() const { return m_value[1]; } - _NODISCARD const T& z() const { return m_value[2]; } - - _NODISCARD T& r() { return m_value[0]; } - _NODISCARD T& g() { return m_value[1]; } - _NODISCARD T& b() { return m_value[2]; } - _NODISCARD const T& r() const { return m_value[0]; } - _NODISCARD const T& g() const { return m_value[1]; } - _NODISCARD const T& b() const { return m_value[2]; } + Vector3() : m_value{T(0), T(0), T(0)} {} + + Vector3(T x, T y, T z) : m_value{x, y, z} {} + + explicit Vector3(const T *value) : m_value{value[0], value[1], value[2]} {} + + _NODISCARD T &operator()(const size_t index) { + assert(index < 3); + return m_value[index]; + } + + _NODISCARD const T &operator()(const size_t index) const { + assert(index < 3); + return m_value[index]; + } + + _NODISCARD T &x() { return m_value[0]; } + _NODISCARD T &y() { return m_value[1]; } + _NODISCARD T &z() { return m_value[2]; } + _NODISCARD const T &x() const { return m_value[0]; } + _NODISCARD const T &y() const { return m_value[1]; } + _NODISCARD const T &z() const { return m_value[2]; } + + _NODISCARD T &r() { return m_value[0]; } + _NODISCARD T &g() { return m_value[1]; } + _NODISCARD T &b() { return m_value[2]; } + _NODISCARD const T &r() const { return m_value[0]; } + _NODISCARD const T &g() const { return m_value[1]; } + _NODISCARD const T &b() const { return m_value[2]; } }; typedef Vector3<float> Vector3f; typedef Vector3<double> Vector3d; -template <typename T> -class Vector4 -{ - T m_value[4]; +template <typename T> class Vector4 { + T m_value[4]; public: - Vector4() - : m_value{T(0), T(0), T(0), T(0)} - { - } - - Vector4(T x, T y, T z, T w) - : m_value{x, y, z, w} - { - } - - explicit Vector4(const T* value) - : m_value{ value[0], value[1], value[2], value[3] } - { - } - - _NODISCARD T& operator()(const size_t index) - { - assert(index < 4); - return m_value[index]; - } - - _NODISCARD const T& operator()(const size_t index) const - { - assert(index < 4); - return m_value[index]; - } - - _NODISCARD T& x() { return m_value[0]; } - _NODISCARD T& y() { return m_value[1]; } - _NODISCARD T& z() { return m_value[2]; } - _NODISCARD T& w() { return m_value[3]; } - _NODISCARD const T& x() const { return m_value[0]; } - _NODISCARD const T& y() const { return m_value[1]; } - _NODISCARD const T& z() const { return m_value[2]; } - _NODISCARD const T& w() const { return m_value[3]; } - - _NODISCARD T& r() { return m_value[0]; } - _NODISCARD T& g() { return m_value[1]; } - _NODISCARD T& b() { return m_value[2]; } - _NODISCARD T& a() { return m_value[3]; } - _NODISCARD const T& r() const { return m_value[0]; } - _NODISCARD const T& g() const { return m_value[1]; } - _NODISCARD const T& b() const { return m_value[2]; } - _NODISCARD const T& a() const { return m_value[3]; } + Vector4() : m_value{T(0), T(0), T(0), T(0)} {} + + Vector4(T x, T y, T z, T w) : m_value{x, y, z, w} {} + + explicit Vector4(const T *value) : m_value{value[0], value[1], value[2], value[3]} {} + + _NODISCARD T &operator()(const size_t index) { + assert(index < 4); + return m_value[index]; + } + + _NODISCARD const T &operator()(const size_t index) const { + assert(index < 4); + return m_value[index]; + } + + _NODISCARD T &x() { return m_value[0]; } + _NODISCARD T &y() { return m_value[1]; } + _NODISCARD T &z() { return m_value[2]; } + _NODISCARD T &w() { return m_value[3]; } + _NODISCARD const T &x() const { return m_value[0]; } + _NODISCARD const T &y() const { return m_value[1]; } + _NODISCARD const T &z() const { return m_value[2]; } + _NODISCARD const T &w() const { return m_value[3]; } + + _NODISCARD T &r() { return m_value[0]; } + _NODISCARD T &g() { return m_value[1]; } + _NODISCARD T &b() { return m_value[2]; } + _NODISCARD T &a() { return m_value[3]; } + _NODISCARD const T &r() const { return m_value[0]; } + _NODISCARD const T &g() const { return m_value[1]; } + _NODISCARD const T &b() const { return m_value[2]; } + _NODISCARD const T &a() const { return m_value[3]; } }; typedef Vector4<float> Vector4f; diff --git a/src/Utils/Utils/Alignment.h b/src/Utils/Utils/Alignment.h index 9b0ba20d1..ab7576c32 100644 --- a/src/Utils/Utils/Alignment.h +++ b/src/Utils/Utils/Alignment.h @@ -1,12 +1,9 @@ #pragma once -namespace utils -{ - template <typename T> - constexpr T Align(T value, T toNext) - { - if (toNext > 0) - return (value + toNext - 1) / toNext * toNext; - return value; - } +namespace utils { +template <typename T> constexpr T Align(T value, T toNext) { + if (toNext > 0) + return (value + toNext - 1) / toNext * toNext; + return value; } +} // namespace utils diff --git a/src/Utils/Utils/Arguments/ArgumentParser.cpp b/src/Utils/Utils/Arguments/ArgumentParser.cpp index fe3fabd16..6d088f813 100644 --- a/src/Utils/Utils/Arguments/ArgumentParser.cpp +++ b/src/Utils/Utils/Arguments/ArgumentParser.cpp @@ -4,161 +4,124 @@ const std::string PREFIX_LONG = "--"; const std::string PREFIX_SHORT = "-"; -ArgumentParser::ArgumentParser(const CommandLineOption* const* options, const size_t optionCount) -{ - for(unsigned optionIndex = 0; optionIndex < optionCount; optionIndex++) - { - m_command_line_options.push_back(options[optionIndex]); - } +ArgumentParser::ArgumentParser(const CommandLineOption *const *options, const size_t optionCount) { + for (unsigned optionIndex = 0; optionIndex < optionCount; optionIndex++) { + m_command_line_options.push_back(options[optionIndex]); + } } -bool ArgumentParser::ParseArguments(const int argc, const char** argv) -{ - std::vector<std::string> args(argc); - - for(int arg = 0; arg < argc; arg++) - { - args[arg] = argv[arg]; - } +bool ArgumentParser::ParseArguments(const int argc, const char **argv) { + std::vector<std::string> args(argc); - return ParseArguments(args); + for (int arg = 0; arg < argc; arg++) { + args[arg] = argv[arg]; + } + + return ParseArguments(args); } -bool ArgumentParser::ParseArguments(std::vector<std::string>& args) -{ - m_matched_arguments.clear(); - m_matched_options.clear(); - - const size_t argCount = args.size(); - for (unsigned argIndex = 0; argIndex < argCount; argIndex++) - { - std::string& arg = args[argIndex]; - - if(arg.compare(0, PREFIX_SHORT.size(), PREFIX_SHORT) == 0) - { - // Options should be case insensitive. So before comparing we make the argument lower case. - const size_t argStrLen = arg.size(); - for(unsigned argStrIndex = 0; argStrIndex < argStrLen; argStrIndex++) - { - arg[argStrIndex] = tolower(arg[argStrIndex]); - } - - const CommandLineOption* matchedOption = nullptr; - if(arg.compare(0, PREFIX_LONG.size(), PREFIX_LONG) == 0) - { - std::string longName = arg.substr(2); - - for (auto option : m_command_line_options) - { - if(option->m_long_name == longName) - { - matchedOption = option; - break; - } - } - } - else - { - std::string shortName = arg.substr(1); - - for (auto option : m_command_line_options) - { - if(option->m_short_name == shortName) - { - matchedOption = option; - break; - } - } - } - - if(matchedOption == nullptr) - { - printf("Unknown option '%s'.\n", arg.c_str()); - return false; - } - - if(m_matched_options.find(matchedOption) != m_matched_options.end()) - { - if(!matchedOption->m_multi_use) - { - printf("Option '%s' already specified.\n", arg.c_str()); - return false; - } - } - else - { - m_matched_options[matchedOption] = std::vector<std::string>(); - } - - const size_t parameterCount = matchedOption->m_parameters.size(); - if(argIndex + parameterCount >= argCount) - { - printf("Not enough parameters for option '%s'.\n", arg.c_str()); - return false; - } - - std::vector<std::string>& parameters = m_matched_options[matchedOption]; - for(unsigned parameterIndex = 0; parameterIndex < parameterCount; parameterIndex++) - { - std::string& param = args[argIndex + parameterIndex + 1]; - - if(param.compare(0, PREFIX_SHORT.size(), PREFIX_SHORT) == 0) - { - printf("Not enough parameters for option '%s'.\n", arg.c_str()); - return false; - } - - parameters.push_back(param); - } - - argIndex += parameterCount; +bool ArgumentParser::ParseArguments(std::vector<std::string> &args) { + m_matched_arguments.clear(); + m_matched_options.clear(); + + const size_t argCount = args.size(); + for (unsigned argIndex = 0; argIndex < argCount; argIndex++) { + std::string &arg = args[argIndex]; + + if (arg.compare(0, PREFIX_SHORT.size(), PREFIX_SHORT) == 0) { + // Options should be case insensitive. So before comparing we make the argument lower case. + const size_t argStrLen = arg.size(); + for (unsigned argStrIndex = 0; argStrIndex < argStrLen; argStrIndex++) { + arg[argStrIndex] = tolower(arg[argStrIndex]); + } + + const CommandLineOption *matchedOption = nullptr; + if (arg.compare(0, PREFIX_LONG.size(), PREFIX_LONG) == 0) { + std::string longName = arg.substr(2); + + for (auto option : m_command_line_options) { + if (option->m_long_name == longName) { + matchedOption = option; + break; + } + } + } else { + std::string shortName = arg.substr(1); + + for (auto option : m_command_line_options) { + if (option->m_short_name == shortName) { + matchedOption = option; + break; + } + } + } + + if (matchedOption == nullptr) { + printf("Unknown option '%s'.\n", arg.c_str()); + return false; + } + + if (m_matched_options.find(matchedOption) != m_matched_options.end()) { + if (!matchedOption->m_multi_use) { + printf("Option '%s' already specified.\n", arg.c_str()); + return false; } - else - { - m_matched_arguments.push_back(arg); + } else { + m_matched_options[matchedOption] = std::vector<std::string>(); + } + + const size_t parameterCount = matchedOption->m_parameters.size(); + if (argIndex + parameterCount >= argCount) { + printf("Not enough parameters for option '%s'.\n", arg.c_str()); + return false; + } + + std::vector<std::string> ¶meters = m_matched_options[matchedOption]; + for (unsigned parameterIndex = 0; parameterIndex < parameterCount; parameterIndex++) { + std::string ¶m = args[argIndex + parameterIndex + 1]; + + if (param.compare(0, PREFIX_SHORT.size(), PREFIX_SHORT) == 0) { + printf("Not enough parameters for option '%s'.\n", arg.c_str()); + return false; } + + parameters.push_back(param); + } + + argIndex += parameterCount; + } else { + m_matched_arguments.push_back(arg); } + } - return true; + return true; } -std::vector<std::string> ArgumentParser::GetArguments() const -{ - return m_matched_arguments; -} +std::vector<std::string> ArgumentParser::GetArguments() const { return m_matched_arguments; } -std::string ArgumentParser::GetValueForOption(const CommandLineOption* option) -{ - if(!IsOptionSpecified(option)) - return ""; - - std::stringstream value; - bool firstMatch = true; - for (const auto& match : m_matched_options[option]) - { - if(!firstMatch) - { - value << " " << match; - } - else - { - value << match; - firstMatch = false; - } +std::string ArgumentParser::GetValueForOption(const CommandLineOption *option) { + if (!IsOptionSpecified(option)) + return ""; + + std::stringstream value; + bool firstMatch = true; + for (const auto &match : m_matched_options[option]) { + if (!firstMatch) { + value << " " << match; + } else { + value << match; + firstMatch = false; } + } - return value.str(); + return value.str(); } -std::vector<std::string> ArgumentParser::GetParametersForOption(const CommandLineOption* option) -{ - if(!IsOptionSpecified(option)) - return std::vector<std::string>(); +std::vector<std::string> ArgumentParser::GetParametersForOption(const CommandLineOption *option) { + if (!IsOptionSpecified(option)) + return std::vector<std::string>(); - return m_matched_options[option]; + return m_matched_options[option]; } -bool ArgumentParser::IsOptionSpecified(const CommandLineOption* option) -{ - return m_matched_options.find(option) != m_matched_options.end(); -} \ No newline at end of file +bool ArgumentParser::IsOptionSpecified(const CommandLineOption *option) { return m_matched_options.find(option) != m_matched_options.end(); } \ No newline at end of file diff --git a/src/Utils/Utils/Arguments/ArgumentParser.h b/src/Utils/Utils/Arguments/ArgumentParser.h index 7e23d65de..d1df20901 100644 --- a/src/Utils/Utils/Arguments/ArgumentParser.h +++ b/src/Utils/Utils/Arguments/ArgumentParser.h @@ -1,24 +1,23 @@ #pragma once #include "CommandLineOption.h" +#include <map> #include <string> #include <vector> -#include <map> -class ArgumentParser -{ - std::vector<const CommandLineOption*> m_command_line_options; - std::map<const CommandLineOption*, std::vector<std::string>> m_matched_options; - std::vector<std::string> m_matched_arguments; +class ArgumentParser { + std::vector<const CommandLineOption *> m_command_line_options; + std::map<const CommandLineOption *, std::vector<std::string>> m_matched_options; + std::vector<std::string> m_matched_arguments; public: - ArgumentParser(const CommandLineOption* const* options, size_t optionCount); - - bool ParseArguments(std::vector<std::string>& args); - bool ParseArguments(int argc, const char** argv); + ArgumentParser(const CommandLineOption *const *options, size_t optionCount); + + bool ParseArguments(std::vector<std::string> &args); + bool ParseArguments(int argc, const char **argv); - std::vector<std::string> GetArguments() const; + std::vector<std::string> GetArguments() const; - bool IsOptionSpecified(const CommandLineOption* option); - std::string GetValueForOption(const CommandLineOption* option); - std::vector<std::string> GetParametersForOption(const CommandLineOption* option); + bool IsOptionSpecified(const CommandLineOption *option); + std::string GetValueForOption(const CommandLineOption *option); + std::vector<std::string> GetParametersForOption(const CommandLineOption *option); }; diff --git a/src/Utils/Utils/Arguments/CommandLineOption.cpp b/src/Utils/Utils/Arguments/CommandLineOption.cpp index d5f77fd61..0283ccc95 100644 --- a/src/Utils/Utils/Arguments/CommandLineOption.cpp +++ b/src/Utils/Utils/Arguments/CommandLineOption.cpp @@ -1,59 +1,48 @@ #include "CommandLineOption.h" -CommandLineOption::CommandLineOption() -{ - m_short_name = ""; - m_long_name = ""; - m_description = ""; - m_category = ""; - m_multi_use = false; +CommandLineOption::CommandLineOption() { + m_short_name = ""; + m_long_name = ""; + m_description = ""; + m_category = ""; + m_multi_use = false; } -CommandLineOption::Builder& CommandLineOption::Builder::Create() -{ - return *new Builder(); -} +CommandLineOption::Builder &CommandLineOption::Builder::Create() { return *new Builder(); } -CommandLineOption::Builder& CommandLineOption::Builder::WithShortName(std::string shortName) -{ - m_option.m_short_name = std::move(shortName); - return *this; +CommandLineOption::Builder &CommandLineOption::Builder::WithShortName(std::string shortName) { + m_option.m_short_name = std::move(shortName); + return *this; } -CommandLineOption::Builder& CommandLineOption::Builder::WithLongName(std::string longName) -{ - m_option.m_long_name = std::move(longName); - return *this; +CommandLineOption::Builder &CommandLineOption::Builder::WithLongName(std::string longName) { + m_option.m_long_name = std::move(longName); + return *this; } -CommandLineOption::Builder& CommandLineOption::Builder::WithDescription(std::string description) -{ - m_option.m_description = std::move(description); - return *this; +CommandLineOption::Builder &CommandLineOption::Builder::WithDescription(std::string description) { + m_option.m_description = std::move(description); + return *this; } -CommandLineOption::Builder& CommandLineOption::Builder::WithCategory(std::string category) -{ - m_option.m_category = std::move(category); - return *this; +CommandLineOption::Builder &CommandLineOption::Builder::WithCategory(std::string category) { + m_option.m_category = std::move(category); + return *this; } -CommandLineOption::Builder& CommandLineOption::Builder::WithParameter(std::string parameterName) -{ - m_option.m_parameters.push_back(std::move(parameterName)); - return *this; +CommandLineOption::Builder &CommandLineOption::Builder::WithParameter(std::string parameterName) { + m_option.m_parameters.push_back(std::move(parameterName)); + return *this; } -CommandLineOption::Builder& CommandLineOption::Builder::Reusable() -{ - m_option.m_multi_use = true; - return *this; +CommandLineOption::Builder &CommandLineOption::Builder::Reusable() { + m_option.m_multi_use = true; + return *this; } -CommandLineOption* CommandLineOption::Builder::Build() const -{ - auto* result = new CommandLineOption(m_option); - delete this; +CommandLineOption *CommandLineOption::Builder::Build() const { + auto *result = new CommandLineOption(m_option); + delete this; - return result; + return result; } diff --git a/src/Utils/Utils/Arguments/CommandLineOption.h b/src/Utils/Utils/Arguments/CommandLineOption.h index 1d915cb36..787056e05 100644 --- a/src/Utils/Utils/Arguments/CommandLineOption.h +++ b/src/Utils/Utils/Arguments/CommandLineOption.h @@ -2,34 +2,32 @@ #include <string> #include <vector> -class CommandLineOption -{ +class CommandLineOption { protected: - CommandLineOption(); + CommandLineOption(); public: - std::string m_short_name; - std::string m_long_name; - std::string m_description; - std::string m_category; - bool m_multi_use; - std::vector<std::string> m_parameters; + std::string m_short_name; + std::string m_long_name; + std::string m_description; + std::string m_category; + bool m_multi_use; + std::vector<std::string> m_parameters; - class Builder; + class Builder; }; -class CommandLineOption::Builder -{ - CommandLineOption m_option; +class CommandLineOption::Builder { + CommandLineOption m_option; public: - static Builder& Create(); + static Builder &Create(); - Builder& WithShortName(std::string shortName); - Builder& WithLongName(std::string longName); - Builder& WithDescription(std::string description); - Builder& WithCategory(std::string category); - Builder& WithParameter(std::string parameterName); - Builder& Reusable(); - CommandLineOption* Build() const; + Builder &WithShortName(std::string shortName); + Builder &WithLongName(std::string longName); + Builder &WithDescription(std::string description); + Builder &WithCategory(std::string category); + Builder &WithParameter(std::string parameterName); + Builder &Reusable(); + CommandLineOption *Build() const; }; \ No newline at end of file diff --git a/src/Utils/Utils/Arguments/UsageInformation.cpp b/src/Utils/Utils/Arguments/UsageInformation.cpp index c94d1381c..296faebe6 100644 --- a/src/Utils/Utils/Arguments/UsageInformation.cpp +++ b/src/Utils/Utils/Arguments/UsageInformation.cpp @@ -1,166 +1,131 @@ #include "UsageInformation.h" +#include <iomanip> #include <iostream> #include <map> -#include <iomanip> -UsageInformation::ArgumentUsage::ArgumentUsage(std::string name, const bool optional) -{ - m_name = std::move(name); - m_optional = optional; +UsageInformation::ArgumentUsage::ArgumentUsage(std::string name, const bool optional) { + m_name = std::move(name); + m_optional = optional; } -UsageInformation::UsageInformation(std::string applicationName) -{ - m_application_name = std::move(applicationName); - m_var_args = false; +UsageInformation::UsageInformation(std::string applicationName) { + m_application_name = std::move(applicationName); + m_var_args = false; } -void UsageInformation::AddCommandLineOption(const CommandLineOption* option) -{ - m_command_line_options.push_back(option); -} +void UsageInformation::AddCommandLineOption(const CommandLineOption *option) { m_command_line_options.push_back(option); } -void UsageInformation::AddArgument(std::string argumentName) -{ - m_arguments.emplace_back(std::move(argumentName), false); -} +void UsageInformation::AddArgument(std::string argumentName) { m_arguments.emplace_back(std::move(argumentName), false); } -void UsageInformation::AddOptionalArgument(std::string argumentName) -{ - m_arguments.emplace_back(std::move(argumentName), true); -} +void UsageInformation::AddOptionalArgument(std::string argumentName) { m_arguments.emplace_back(std::move(argumentName), true); } -void UsageInformation::SetVariableArguments(const bool enabled) -{ - m_var_args = enabled; -} +void UsageInformation::SetVariableArguments(const bool enabled) { m_var_args = enabled; } -void UsageInformation::Print() -{ - std::stringstream str; - std::map<std::string, std::vector<const CommandLineOption*>> categories; +void UsageInformation::Print() { + std::stringstream str; + std::map<std::string, std::vector<const CommandLineOption *>> categories; - str << "Usage:" << std::endl; + str << "Usage:" << std::endl; - PrintUsageOverview(str); + PrintUsageOverview(str); - str << "The following options are available:" << std::endl; + str << "The following options are available:" << std::endl; - str.fill(' '); + str.fill(' '); - for (auto commandLineOption : m_command_line_options) - { - if (categories.find(commandLineOption->m_category) == categories.end()) - categories[commandLineOption->m_category] = std::vector<const CommandLineOption*>(); + for (auto commandLineOption : m_command_line_options) { + if (categories.find(commandLineOption->m_category) == categories.end()) + categories[commandLineOption->m_category] = std::vector<const CommandLineOption *>(); - categories[commandLineOption->m_category].push_back(commandLineOption); - } + categories[commandLineOption->m_category].push_back(commandLineOption); + } + + size_t longestShortName = 0; + size_t longestLongName = 0; + size_t longestArgumentLength = 0; - size_t longestShortName = 0; - size_t longestLongName = 0; - size_t longestArgumentLength = 0; + for (auto option : m_command_line_options) { + if (option->m_short_name.length() > longestShortName) + longestShortName = option->m_short_name.length(); - for (auto option : m_command_line_options) - { - if (option->m_short_name.length() > longestShortName) - longestShortName = option->m_short_name.length(); + if (option->m_long_name.length() > longestLongName) + longestLongName = option->m_long_name.length(); - if (option->m_long_name.length() > longestLongName) - longestLongName = option->m_long_name.length(); + const size_t argumentLength = GetOptionArgumentLength(option); + if (argumentLength > longestArgumentLength) + longestArgumentLength = argumentLength; + } - const size_t argumentLength = GetOptionArgumentLength(option); - if (argumentLength > longestArgumentLength) - longestArgumentLength = argumentLength; + bool firstCategory = true; + for (auto &category : categories) { + if (!firstCategory) + str << std::endl; + else + firstCategory = false; + + if (!category.first.empty()) { + str << "== " << category.first << " ==" << std::endl; } - bool firstCategory = true; - for (auto& category : categories) - { - if (!firstCategory) - str << std::endl; - else - firstCategory = false; - - if (!category.first.empty()) - { - str << "== " << category.first << " ==" << std::endl; - } - - for (auto option : category.second) - { - str << std::setw(static_cast<std::streamsize>(longestShortName) + 1) << (!option->m_short_name.empty() - ? "-" + option->m_short_name - : ""); - - if (!option->m_short_name.empty() && !option->m_long_name.empty()) - str << ", "; - else - str << " "; - - str << std::setw(static_cast<std::streamsize>(longestLongName) + 2) << (!option->m_long_name.empty() - ? "--" + option->m_long_name - : ""); - - str << " "; - str << std::setw(longestArgumentLength) << GetOptionArgument(option); - - str << " " << option->m_description << std::endl; - } + for (auto option : category.second) { + str << std::setw(static_cast<std::streamsize>(longestShortName) + 1) << (!option->m_short_name.empty() ? "-" + option->m_short_name : ""); + + if (!option->m_short_name.empty() && !option->m_long_name.empty()) + str << ", "; + else + str << " "; + + str << std::setw(static_cast<std::streamsize>(longestLongName) + 2) << (!option->m_long_name.empty() ? "--" + option->m_long_name : ""); + + str << " "; + str << std::setw(longestArgumentLength) << GetOptionArgument(option); + + str << " " << option->m_description << std::endl; } + } - std::cout << str.str() << std::endl; + std::cout << str.str() << std::endl; } -void UsageInformation::PrintUsageOverview(std::stringstream& str) -{ - str << m_application_name << " [options]"; - for (ArgumentUsage& argument : m_arguments) - { - if (argument.m_optional) - { - str << " [" << argument.m_name << "]"; - } - else - { - str << " <" << argument.m_name << ">"; - } - } - if (m_var_args) - { - str << "..."; +void UsageInformation::PrintUsageOverview(std::stringstream &str) { + str << m_application_name << " [options]"; + for (ArgumentUsage &argument : m_arguments) { + if (argument.m_optional) { + str << " [" << argument.m_name << "]"; + } else { + str << " <" << argument.m_name << ">"; } - str << std::endl << std::endl; + } + if (m_var_args) { + str << "..."; + } + str << std::endl << std::endl; } -std::string UsageInformation::GetOptionArgument(const CommandLineOption* option) -{ - std::stringstream str; +std::string UsageInformation::GetOptionArgument(const CommandLineOption *option) { + std::stringstream str; - bool firstParam = true; - for (const std::string& param : option->m_parameters) - { - if (!firstParam) - str << " "; - else - firstParam = false; + bool firstParam = true; + for (const std::string ¶m : option->m_parameters) { + if (!firstParam) + str << " "; + else + firstParam = false; - str << "<" << param << ">"; - } + str << "<" << param << ">"; + } - return str.str(); + return str.str(); } -size_t UsageInformation::GetOptionArgumentLength(const CommandLineOption* option) -{ - const size_t parameterCount = option->m_parameters.size(); - size_t parameterCombinedStringLength = 0; +size_t UsageInformation::GetOptionArgumentLength(const CommandLineOption *option) { + const size_t parameterCount = option->m_parameters.size(); + size_t parameterCombinedStringLength = 0; - for (const std::string& param : option->m_parameters) - { - parameterCombinedStringLength += param.length(); - } + for (const std::string ¶m : option->m_parameters) { + parameterCombinedStringLength += param.length(); + } - return parameterCount * 2 // < and > - + parameterCombinedStringLength - + (parameterCount > 1 ? parameterCount - 1 : 0); // One space between each argument + return parameterCount * 2 // < and > + + parameterCombinedStringLength + (parameterCount > 1 ? parameterCount - 1 : 0); // One space between each argument } diff --git a/src/Utils/Utils/Arguments/UsageInformation.h b/src/Utils/Utils/Arguments/UsageInformation.h index 16f663495..4f5582a65 100644 --- a/src/Utils/Utils/Arguments/UsageInformation.h +++ b/src/Utils/Utils/Arguments/UsageInformation.h @@ -1,37 +1,35 @@ #pragma once #include "CommandLineOption.h" +#include <sstream> #include <string> #include <vector> -#include <sstream> -class UsageInformation -{ - class ArgumentUsage - { - public: - std::string m_name; - bool m_optional; +class UsageInformation { + class ArgumentUsage { + public: + std::string m_name; + bool m_optional; + + ArgumentUsage(std::string name, bool optional); + }; - ArgumentUsage(std::string name, bool optional); - }; + std::string m_application_name; + std::vector<const CommandLineOption *> m_command_line_options; + std::vector<ArgumentUsage> m_arguments; + bool m_var_args; - std::string m_application_name; - std::vector<const CommandLineOption*> m_command_line_options; - std::vector<ArgumentUsage> m_arguments; - bool m_var_args; + void PrintUsageOverview(std::stringstream &str); - void PrintUsageOverview(std::stringstream& str); - - static std::string GetOptionArgument(const CommandLineOption* option); - static size_t GetOptionArgumentLength(const CommandLineOption* option); + static std::string GetOptionArgument(const CommandLineOption *option); + static size_t GetOptionArgumentLength(const CommandLineOption *option); public: - UsageInformation(std::string applicationName); + UsageInformation(std::string applicationName); - void AddCommandLineOption(const CommandLineOption* option); - void AddArgument(std::string argumentName); - void AddOptionalArgument(std::string argumentName); - void SetVariableArguments(bool enabled); + void AddCommandLineOption(const CommandLineOption *option); + void AddArgument(std::string argumentName); + void AddOptionalArgument(std::string argumentName); + void SetVariableArguments(bool enabled); - void Print(); + void Print(); }; \ No newline at end of file diff --git a/src/Utils/Utils/ClassUtils.h b/src/Utils/Utils/ClassUtils.h index 8fd506454..a77928a90 100644 --- a/src/Utils/Utils/ClassUtils.h +++ b/src/Utils/Utils/ClassUtils.h @@ -28,20 +28,12 @@ #define _NORETURN #endif -template <class T> -struct Movable -{ - mutable T m_val; - - // ReSharper disable once CppNonExplicitConversionOperator - operator T() const && - { - return std::move(m_val); - } - - // ReSharper disable once CppNonExplicitConvertingConstructor - Movable(T&& in) - : m_val(std::move(in)) - { - } +template <class T> struct Movable { + mutable T m_val; + + // ReSharper disable once CppNonExplicitConversionOperator + operator T() const && { return std::move(m_val); } + + // ReSharper disable once CppNonExplicitConvertingConstructor + Movable(T &&in) : m_val(std::move(in)) {} }; diff --git a/src/Utils/Utils/Endianness.cpp b/src/Utils/Utils/Endianness.cpp index 4047984e8..6f1fcdc1c 100644 --- a/src/Utils/Utils/Endianness.cpp +++ b/src/Utils/Utils/Endianness.cpp @@ -2,218 +2,96 @@ #if defined(_WIN32) || defined(_WIN64) || defined(_MSC_VER) -namespace endianness -{ - constexpr uint16_t byteswap16u(const uint16_t in) - { - return static_cast<uint16_t>( - (in >> 8) | - (in << 8) - ); - } - - constexpr int16_t byteswap16s(const int16_t in) - { - return static_cast<int16_t>(byteswap16u(static_cast<uint16_t>(in))); - } - - constexpr uint32_t byteswap32u(const uint32_t in) - { - return static_cast<uint32_t>( - (in >> 24) | - ((in >> 8) & 0x0000FF00ui32) | - ((in << 8) & 0x00FF0000ui32) | - (in << 24) - ); - } - - constexpr int32_t byteswap32s(const int32_t in) - { - return static_cast<int32_t>(byteswap32u(static_cast<uint32_t>(in))); - } - - constexpr uint64_t byteswap64u(const uint64_t in) - { - return static_cast<uint32_t>( - (in >> 56) | - ((in >> 40) & 0x000000000000FF00ui64) | - ((in >> 24) & 0x0000000000FF0000ui64) | - ((in >> 8) & 0x00000000FF000000ui64) | - ((in << 8) & 0x000000FF00000000ui64) | - ((in << 24) & 0x0000FF0000000000ui64) | - ((in << 40) & 0x00FF000000000000ui64) | - (in << 56) - ); - } - - constexpr int64_t byteswap64s(const int64_t in) - { - return static_cast<int64_t>(byteswap64u(static_cast<uint64_t>(in))); - } +namespace endianness { +constexpr uint16_t byteswap16u(const uint16_t in) { return static_cast<uint16_t>((in >> 8) | (in << 8)); } + +constexpr int16_t byteswap16s(const int16_t in) { return static_cast<int16_t>(byteswap16u(static_cast<uint16_t>(in))); } + +constexpr uint32_t byteswap32u(const uint32_t in) { + return static_cast<uint32_t>((in >> 24) | ((in >> 8) & 0x0000FF00ui32) | ((in << 8) & 0x00FF0000ui32) | (in << 24)); } -#else +constexpr int32_t byteswap32s(const int32_t in) { return static_cast<int32_t>(byteswap32u(static_cast<uint32_t>(in))); } -namespace endianness -{ - constexpr int16_t byteswap16s(const int16_t in) - { - return static_cast<int16_t>(__builtin_bswap16(static_cast<uint16_t>(in))); - } - - constexpr uint16_t byteswap16u(const uint16_t in) - { - return __builtin_bswap16(in); - } - - constexpr int32_t byteswap32s(const int32_t in) - { - return static_cast<int32_t>(__builtin_bswap32(static_cast<uint32_t>(in))); - } - - constexpr uint32_t byteswap32u(const uint32_t in) - { - return __builtin_bswap32(in); - } - - constexpr int64_t byteswap64s(const int64_t in) - { - return static_cast<int64_t>(__builtin_bswap64(static_cast<uint64_t>(in))); - } - - constexpr uint64_t byteswap64u(const uint64_t in) - { - return __builtin_bswap64(in); - } +constexpr uint64_t byteswap64u(const uint64_t in) { + return static_cast<uint32_t>((in >> 56) | ((in >> 40) & 0x000000000000FF00ui64) | ((in >> 24) & 0x0000000000FF0000ui64) | + ((in >> 8) & 0x00000000FF000000ui64) | ((in << 8) & 0x000000FF00000000ui64) | ((in << 24) & 0x0000FF0000000000ui64) | + ((in << 40) & 0x00FF000000000000ui64) | (in << 56)); } +constexpr int64_t byteswap64s(const int64_t in) { return static_cast<int64_t>(byteswap64u(static_cast<uint64_t>(in))); } +} // namespace endianness + +#else + +namespace endianness { +constexpr int16_t byteswap16s(const int16_t in) { return static_cast<int16_t>(__builtin_bswap16(static_cast<uint16_t>(in))); } + +constexpr uint16_t byteswap16u(const uint16_t in) { return __builtin_bswap16(in); } + +constexpr int32_t byteswap32s(const int32_t in) { return static_cast<int32_t>(__builtin_bswap32(static_cast<uint32_t>(in))); } + +constexpr uint32_t byteswap32u(const uint32_t in) { return __builtin_bswap32(in); } + +constexpr int64_t byteswap64s(const int64_t in) { return static_cast<int64_t>(__builtin_bswap64(static_cast<uint64_t>(in))); } + +constexpr uint64_t byteswap64u(const uint64_t in) { return __builtin_bswap64(in); } +} // namespace endianness + #endif -namespace endianness -{ +namespace endianness { #if HOST_ENDIANNESS == LITTLE_ENDIAN_ENDIANNESS - int16_t ToBigEndian(const int16_t in) - { - return byteswap16s(in); - } - - uint16_t ToBigEndian(const uint16_t in) - { - return byteswap16u(in); - } - - int32_t ToBigEndian(const int32_t in) - { - return byteswap32s(in); - } - - uint32_t ToBigEndian(const uint32_t in) - { - return byteswap32u(in); - } - - int64_t ToBigEndian(const int64_t in) - { - return byteswap64s(in); - } - - uint64_t ToBigEndian(const uint64_t in) - { - return byteswap64u(in); - } - - int16_t FromBigEndian(const int16_t in) - { - return byteswap16s(in); - } - - uint16_t FromBigEndian(const uint16_t in) - { - return byteswap16u(in); - } - - int32_t FromBigEndian(const int32_t in) - { - return byteswap32s(in); - } - - uint32_t FromBigEndian(const uint32_t in) - { - return byteswap32u(in); - } - - int64_t FromBigEndian(const int64_t in) - { - return byteswap64s(in); - } - - uint64_t FromBigEndian(const uint64_t in) - { - return byteswap64u(in); - } +int16_t ToBigEndian(const int16_t in) { return byteswap16s(in); } + +uint16_t ToBigEndian(const uint16_t in) { return byteswap16u(in); } + +int32_t ToBigEndian(const int32_t in) { return byteswap32s(in); } + +uint32_t ToBigEndian(const uint32_t in) { return byteswap32u(in); } + +int64_t ToBigEndian(const int64_t in) { return byteswap64s(in); } + +uint64_t ToBigEndian(const uint64_t in) { return byteswap64u(in); } + +int16_t FromBigEndian(const int16_t in) { return byteswap16s(in); } + +uint16_t FromBigEndian(const uint16_t in) { return byteswap16u(in); } + +int32_t FromBigEndian(const int32_t in) { return byteswap32s(in); } + +uint32_t FromBigEndian(const uint32_t in) { return byteswap32u(in); } + +int64_t FromBigEndian(const int64_t in) { return byteswap64s(in); } + +uint64_t FromBigEndian(const uint64_t in) { return byteswap64u(in); } #else - int16_t ToLittleEndian(const int16_t in) - { - return byteswap16s(in); - } - - uint16_t ToLittleEndian(const uint16_t in) - { - return byteswap16u(in); - } - - int32_t ToLittleEndian(const int32_t in) - { - return byteswap32s(in); - } - - uint32_t ToLittleEndian(const uint32_t in) - { - return byteswap32u(in); - } - - int64_t ToLittleEndian(const int64_t in) - { - return byteswap64s(in); - } - - uint64_t ToLittleEndian(const uint64_t in) - { - return byteswap64u(in); - } - - int16_t FromLittleEndian(const int16_t in) - { - return byteswap16s(in); - } - - uint16_t FromLittleEndian(const uint16_t in) - { - return byteswap16u(in); - } - - int32_t FromLittleEndian(const int32_t in) - { - return byteswap32s(in); - } - - uint32_t FromLittleEndian(const uint32_t in) - { - return byteswap32u(in); - } - - int64_t FromLittleEndian(const int64_t in) - { - return byteswap64s(in); - } - - uint64_t FromLittleEndian(const uint64_t in) - { - return byteswap64u(in); - } +int16_t ToLittleEndian(const int16_t in) { return byteswap16s(in); } + +uint16_t ToLittleEndian(const uint16_t in) { return byteswap16u(in); } + +int32_t ToLittleEndian(const int32_t in) { return byteswap32s(in); } + +uint32_t ToLittleEndian(const uint32_t in) { return byteswap32u(in); } + +int64_t ToLittleEndian(const int64_t in) { return byteswap64s(in); } + +uint64_t ToLittleEndian(const uint64_t in) { return byteswap64u(in); } + +int16_t FromLittleEndian(const int16_t in) { return byteswap16s(in); } + +uint16_t FromLittleEndian(const uint16_t in) { return byteswap16u(in); } + +int32_t FromLittleEndian(const int32_t in) { return byteswap32s(in); } + +uint32_t FromLittleEndian(const uint32_t in) { return byteswap32u(in); } + +int64_t FromLittleEndian(const int64_t in) { return byteswap64s(in); } + +uint64_t FromLittleEndian(const uint64_t in) { return byteswap64u(in); } #endif -} +} // namespace endianness diff --git a/src/Utils/Utils/Endianness.h b/src/Utils/Utils/Endianness.h index 196ae7969..e2d5d7976 100644 --- a/src/Utils/Utils/Endianness.h +++ b/src/Utils/Utils/Endianness.h @@ -21,62 +21,60 @@ #endif -namespace endianness -{ +namespace endianness { #if HOST_ENDIANNESS == LITTLE_ENDIAN_ENDIANNESS - constexpr int16_t ToLittleEndian(const int16_t in) { return in; } - constexpr uint16_t ToLittleEndian(const uint16_t in) { return in; } - constexpr int32_t ToLittleEndian(const int32_t in) { return in; } - constexpr uint32_t ToLittleEndian(const uint32_t in) { return in; } - constexpr int64_t ToLittleEndian(const int64_t in) { return in; } - constexpr uint64_t ToLittleEndian(const uint64_t in) { return in; } - constexpr int16_t FromLittleEndian(const int16_t in) { return in; } - constexpr uint16_t FromLittleEndian(const uint16_t in) { return in; } - constexpr int32_t FromLittleEndian(const int32_t in) { return in; } - constexpr uint32_t FromLittleEndian(const uint32_t in) { return in; } - constexpr int64_t FromLittleEndian(const int64_t in) { return in; } - constexpr uint64_t FromLittleEndian(const uint64_t in) { return in; } +constexpr int16_t ToLittleEndian(const int16_t in) { return in; } +constexpr uint16_t ToLittleEndian(const uint16_t in) { return in; } +constexpr int32_t ToLittleEndian(const int32_t in) { return in; } +constexpr uint32_t ToLittleEndian(const uint32_t in) { return in; } +constexpr int64_t ToLittleEndian(const int64_t in) { return in; } +constexpr uint64_t ToLittleEndian(const uint64_t in) { return in; } +constexpr int16_t FromLittleEndian(const int16_t in) { return in; } +constexpr uint16_t FromLittleEndian(const uint16_t in) { return in; } +constexpr int32_t FromLittleEndian(const int32_t in) { return in; } +constexpr uint32_t FromLittleEndian(const uint32_t in) { return in; } +constexpr int64_t FromLittleEndian(const int64_t in) { return in; } +constexpr uint64_t FromLittleEndian(const uint64_t in) { return in; } #else - int16_t ToLittleEndian(int16_t in); - uint16_t ToLittleEndian(uint16_t in); - int32_t ToLittleEndian(int32_t in); - uint32_t ToLittleEndian(uint32_t in); - int64_t ToLittleEndian(int64_t in); - uint64_t ToLittleEndian(uint64_t in); - int16_t FromLittleEndian(int16_t in); - uint16_t FromLittleEndian(uint16_t in); - int32_t FromLittleEndian(int32_t in); - uint32_t FromLittleEndian(uint32_t in); - int64_t FromLittleEndian(int64_t in); - uint64_t FromLittleEndian(uint64_t in); +int16_t ToLittleEndian(int16_t in); +uint16_t ToLittleEndian(uint16_t in); +int32_t ToLittleEndian(int32_t in); +uint32_t ToLittleEndian(uint32_t in); +int64_t ToLittleEndian(int64_t in); +uint64_t ToLittleEndian(uint64_t in); +int16_t FromLittleEndian(int16_t in); +uint16_t FromLittleEndian(uint16_t in); +int32_t FromLittleEndian(int32_t in); +uint32_t FromLittleEndian(uint32_t in); +int64_t FromLittleEndian(int64_t in); +uint64_t FromLittleEndian(uint64_t in); #endif - #if HOST_ENDIANNESS == BIG_ENDIAN_ENDIANNESS - constexpr int16_t ToBigEndian(const int16_t in) { return in; } - constexpr uint16_t ToBigEndian(const uint16_t in) { return in; } - constexpr int32_t ToBigEndian(const int32_t in) { return in; } - constexpr uint32_t ToBigEndian(const uint32_t in) { return in; } - constexpr int64_t ToBigEndian(const int64_t in) { return in; } - constexpr uint64_t ToBigEndian(const uint64_t in) { return in; } - constexpr int16_t FromBigEndian(const int16_t in) { return in; } - constexpr uint16_t FromBigEndian(const uint16_t in) { return in; } - constexpr int32_t FromBigEndian(const int32_t in) { return in; } - constexpr uint32_t FromBigEndian(const uint32_t in) { return in; } - constexpr int64_t FromBigEndian(const int64_t in) { return in; } - constexpr uint64_t FromBigEndian(const uint64_t in) { return in; } +constexpr int16_t ToBigEndian(const int16_t in) { return in; } +constexpr uint16_t ToBigEndian(const uint16_t in) { return in; } +constexpr int32_t ToBigEndian(const int32_t in) { return in; } +constexpr uint32_t ToBigEndian(const uint32_t in) { return in; } +constexpr int64_t ToBigEndian(const int64_t in) { return in; } +constexpr uint64_t ToBigEndian(const uint64_t in) { return in; } +constexpr int16_t FromBigEndian(const int16_t in) { return in; } +constexpr uint16_t FromBigEndian(const uint16_t in) { return in; } +constexpr int32_t FromBigEndian(const int32_t in) { return in; } +constexpr uint32_t FromBigEndian(const uint32_t in) { return in; } +constexpr int64_t FromBigEndian(const int64_t in) { return in; } +constexpr uint64_t FromBigEndian(const uint64_t in) { return in; } #else - int16_t ToBigEndian(int16_t in); - uint16_t ToBigEndian(uint16_t in); - int32_t ToBigEndian(int32_t in); - uint32_t ToBigEndian(uint32_t in); - int64_t ToBigEndian(int64_t in); - uint64_t ToBigEndian(uint64_t in); - int16_t FromBigEndian(int16_t in); - uint16_t FromBigEndian(uint16_t in); - int32_t FromBigEndian(int32_t in); - uint32_t FromBigEndian(uint32_t in); - int64_t FromBigEndian(int64_t in); - uint64_t FromBigEndian(uint64_t in); +int16_t ToBigEndian(int16_t in); +uint16_t ToBigEndian(uint16_t in); +int32_t ToBigEndian(int32_t in); +uint32_t ToBigEndian(uint32_t in); +int64_t ToBigEndian(int64_t in); +uint64_t ToBigEndian(uint64_t in); +int16_t FromBigEndian(int16_t in); +uint16_t FromBigEndian(uint16_t in); +int32_t FromBigEndian(int32_t in); +uint32_t FromBigEndian(uint32_t in); +int64_t FromBigEndian(int64_t in); +uint64_t FromBigEndian(uint64_t in); #endif -} +} // namespace endianness diff --git a/src/Utils/Utils/FileUtils.cpp b/src/Utils/Utils/FileUtils.cpp index 24b8a612a..67a461eed 100644 --- a/src/Utils/Utils/FileUtils.cpp +++ b/src/Utils/Utils/FileUtils.cpp @@ -2,62 +2,49 @@ #include <sstream> -bool FileUtils::ParsePathsString(const std::string& pathsString, std::set<std::string>& output) -{ - std::ostringstream currentPath; - auto pathStart = true; - auto quotationPos = 0; // 0 = before quotations, 1 = in quotations, 2 = after quotations - - for (auto character : pathsString) - { - switch (character) - { - case '"': - if (quotationPos == 0 && pathStart) - { - quotationPos = 1; - } - else if (quotationPos == 1) - { - quotationPos = 2; - pathStart = false; - } - else - { - return false; - } - break; - - case ';': - if (quotationPos != 1) - { - auto path = currentPath.str(); - if (!path.empty()) - { - output.insert(path); - currentPath = std::ostringstream(); - } - - pathStart = true; - quotationPos = 0; - } - else - { - currentPath << character; - } - break; - - default: - currentPath << character; - pathStart = false; - break; +bool FileUtils::ParsePathsString(const std::string &pathsString, std::set<std::string> &output) { + std::ostringstream currentPath; + auto pathStart = true; + auto quotationPos = 0; // 0 = before quotations, 1 = in quotations, 2 = after quotations + + for (auto character : pathsString) { + switch (character) { + case '"': + if (quotationPos == 0 && pathStart) { + quotationPos = 1; + } else if (quotationPos == 1) { + quotationPos = 2; + pathStart = false; + } else { + return false; + } + break; + + case ';': + if (quotationPos != 1) { + auto path = currentPath.str(); + if (!path.empty()) { + output.insert(path); + currentPath = std::ostringstream(); } - } - if (currentPath.tellp() > 0) - { - output.insert(currentPath.str()); + pathStart = true; + quotationPos = 0; + } else { + currentPath << character; + } + break; + + default: + currentPath << character; + pathStart = false; + break; } + } + + if (currentPath.tellp() > 0) { + output.insert(currentPath.str()); + } - return true; + return true; } diff --git a/src/Utils/Utils/FileUtils.h b/src/Utils/Utils/FileUtils.h index e96178b6d..b59913b67 100644 --- a/src/Utils/Utils/FileUtils.h +++ b/src/Utils/Utils/FileUtils.h @@ -3,22 +3,17 @@ #include <set> #include <string> -class FileUtils -{ +class FileUtils { public: - static constexpr uint32_t MakeMagic32(const char ch0, const char ch1, const char ch2, const char ch3) - { - return static_cast<uint32_t>(ch0) - | static_cast<uint32_t>(ch1) << 8 - | static_cast<uint32_t>(ch2) << 16 - | static_cast<uint32_t>(ch3) << 24; - } + static constexpr uint32_t MakeMagic32(const char ch0, const char ch1, const char ch2, const char ch3) { + return static_cast<uint32_t>(ch0) | static_cast<uint32_t>(ch1) << 8 | static_cast<uint32_t>(ch2) << 16 | static_cast<uint32_t>(ch3) << 24; + } - /** - * \brief Splits a path string as user input into a list of paths. - * \param pathsString The path string that was taken as user input. - * \param output A set for strings to save the output to. - * \return \c true if the user input was valid and could be processed successfully, otherwise \c false. - */ - static bool ParsePathsString(const std::string& pathsString, std::set<std::string>& output); + /** + * \brief Splits a path string as user input into a list of paths. + * \param pathsString The path string that was taken as user input. + * \param output A set for strings to save the output to. + * \return \c true if the user input was valid and could be processed successfully, otherwise \c false. + */ + static bool ParsePathsString(const std::string &pathsString, std::set<std::string> &output); }; diff --git a/src/Utils/Utils/MemoryManager.cpp b/src/Utils/Utils/MemoryManager.cpp index 31582fb1e..a0119baa1 100644 --- a/src/Utils/Utils/MemoryManager.cpp +++ b/src/Utils/Utils/MemoryManager.cpp @@ -3,72 +3,59 @@ #include <cstdlib> #include <cstring> -MemoryManager::AllocationInfo::AllocationInfo(IDestructible* data, void* dataPtr) -{ - m_data = data; - m_data_ptr = dataPtr; +MemoryManager::AllocationInfo::AllocationInfo(IDestructible *data, void *dataPtr) { + m_data = data; + m_data_ptr = dataPtr; } -MemoryManager::MemoryManager() -= default; +MemoryManager::MemoryManager() = default; -MemoryManager::~MemoryManager() -{ - for (auto allocation : m_allocations) - { - free(allocation); - } - m_allocations.clear(); +MemoryManager::~MemoryManager() { + for (auto allocation : m_allocations) { + free(allocation); + } + m_allocations.clear(); - for (auto destructible : m_destructible) - { - delete destructible.m_data; - } - m_destructible.clear(); + for (auto destructible : m_destructible) { + delete destructible.m_data; + } + m_destructible.clear(); } -void* MemoryManager::Alloc(const size_t size) -{ - void* result = malloc(size); - m_allocations.push_back(result); +void *MemoryManager::Alloc(const size_t size) { + void *result = malloc(size); + m_allocations.push_back(result); - return result; + return result; } -char* MemoryManager::Dup(const char* str) -{ +char *MemoryManager::Dup(const char *str) { #ifdef _MSC_VER - auto* result = _strdup(str); + auto *result = _strdup(str); #else - auto* result = strdup(str); + auto *result = strdup(str); #endif - m_allocations.push_back(result); + m_allocations.push_back(result); - return result; + return result; } -void MemoryManager::Free(void* data) -{ - for (auto iAlloc = m_allocations.begin(); iAlloc != m_allocations.end(); ++iAlloc) - { - if (*iAlloc == data) - { - free(*iAlloc); - m_allocations.erase(iAlloc); - return; - } +void MemoryManager::Free(void *data) { + for (auto iAlloc = m_allocations.begin(); iAlloc != m_allocations.end(); ++iAlloc) { + if (*iAlloc == data) { + free(*iAlloc); + m_allocations.erase(iAlloc); + return; } + } } -void MemoryManager::Delete(void* data) -{ - for (auto iAlloc = m_destructible.begin(); iAlloc != m_destructible.end(); ++iAlloc) - { - if (iAlloc->m_data_ptr == data) - { - delete iAlloc->m_data; - m_destructible.erase(iAlloc); - return; - } +void MemoryManager::Delete(void *data) { + for (auto iAlloc = m_destructible.begin(); iAlloc != m_destructible.end(); ++iAlloc) { + if (iAlloc->m_data_ptr == data) { + delete iAlloc->m_data; + m_destructible.erase(iAlloc); + return; } + } } diff --git a/src/Utils/Utils/MemoryManager.h b/src/Utils/Utils/MemoryManager.h index 03ec0a4de..f74669803 100644 --- a/src/Utils/Utils/MemoryManager.h +++ b/src/Utils/Utils/MemoryManager.h @@ -3,61 +3,50 @@ #include <cstddef> #include <vector> -class MemoryManager -{ - class IDestructible - { - public: - virtual ~IDestructible() = default; - }; - - template <class T> - class Allocation final : public IDestructible - { - public: - T m_entry; - - template <class... _Valty> - explicit Allocation(_Valty&&... _Val) - : m_entry(std::forward<_Valty>(_Val)...) - { - } - - ~Allocation() override = default; - - Allocation(const Allocation& other) = delete; - Allocation(Allocation&& other) noexcept = delete; - Allocation& operator=(const Allocation& other) = delete; - Allocation& operator=(Allocation&& other) noexcept = delete; - }; - - class AllocationInfo - { - public: - IDestructible* m_data; - void* m_data_ptr; - - AllocationInfo(IDestructible* data, void* dataPtr); - }; - - std::vector<void*> m_allocations; - std::vector<AllocationInfo> m_destructible; +class MemoryManager { + class IDestructible { + public: + virtual ~IDestructible() = default; + }; + + template <class T> class Allocation final : public IDestructible { + public: + T m_entry; + + template <class... _Valty> explicit Allocation(_Valty &&..._Val) : m_entry(std::forward<_Valty>(_Val)...) {} + + ~Allocation() override = default; + + Allocation(const Allocation &other) = delete; + Allocation(Allocation &&other) noexcept = delete; + Allocation &operator=(const Allocation &other) = delete; + Allocation &operator=(Allocation &&other) noexcept = delete; + }; + + class AllocationInfo { + public: + IDestructible *m_data; + void *m_data_ptr; + + AllocationInfo(IDestructible *data, void *dataPtr); + }; + + std::vector<void *> m_allocations; + std::vector<AllocationInfo> m_destructible; public: - MemoryManager(); - virtual ~MemoryManager(); - - void* Alloc(size_t size); - char* Dup(const char* str); - - template <class T, class... _Valty> - T* Create(_Valty&&... _Val) - { - Allocation<T>* allocation = new Allocation<T>(std::forward<_Valty>(_Val)...); - m_destructible.emplace_back(allocation, &allocation->m_entry); - return &allocation->m_entry; - } - - void Free(void* data); - void Delete(void* data); + MemoryManager(); + virtual ~MemoryManager(); + + void *Alloc(size_t size); + char *Dup(const char *str); + + template <class T, class... _Valty> T *Create(_Valty &&..._Val) { + Allocation<T> *allocation = new Allocation<T>(std::forward<_Valty>(_Val)...); + m_destructible.emplace_back(allocation, &allocation->m_entry); + return &allocation->m_entry; + } + + void Free(void *data); + void Delete(void *data); }; \ No newline at end of file diff --git a/src/Utils/Utils/StringUtils.cpp b/src/Utils/Utils/StringUtils.cpp index e7f84d9a5..a312e1f3c 100644 --- a/src/Utils/Utils/StringUtils.cpp +++ b/src/Utils/Utils/StringUtils.cpp @@ -2,90 +2,79 @@ #include <sstream> -namespace utils -{ - std::string EscapeStringForQuotationMarks(const std::string_view& str) - { - std::ostringstream ss; - EscapeStringForQuotationMarks(ss, str); - return ss.str(); - } +namespace utils { +std::string EscapeStringForQuotationMarks(const std::string_view &str) { + std::ostringstream ss; + EscapeStringForQuotationMarks(ss, str); + return ss.str(); +} - void EscapeStringForQuotationMarks(std::ostream& stream, const std::string_view& str) - { - for (const auto& c : str) - { - switch (c) - { - case '\r': - stream << "\\r"; - break; - case '\n': - stream << "\\n"; - break; - case '\t': - stream << "\\t"; - break; - case '\f': - stream << "\\f"; - break; - case '"': - stream << "\\\""; - break; - case '\\': - stream << "\\\\"; - break; - default: - stream << c; - break; - } - } +void EscapeStringForQuotationMarks(std::ostream &stream, const std::string_view &str) { + for (const auto &c : str) { + switch (c) { + case '\r': + stream << "\\r"; + break; + case '\n': + stream << "\\n"; + break; + case '\t': + stream << "\\t"; + break; + case '\f': + stream << "\\f"; + break; + case '"': + stream << "\\\""; + break; + case '\\': + stream << "\\\\"; + break; + default: + stream << c; + break; } + } +} - std::string UnescapeStringFromQuotationMarks(const std::string_view& str) - { - std::ostringstream ss; - UnescapeStringFromQuotationMarks(ss, str); - return ss.str(); - } +std::string UnescapeStringFromQuotationMarks(const std::string_view &str) { + std::ostringstream ss; + UnescapeStringFromQuotationMarks(ss, str); + return ss.str(); +} - void UnescapeStringFromQuotationMarks(std::ostream& stream, const std::string_view& str) - { - auto inEscape = false; - for (const auto& c : str) - { - if (inEscape) - { - switch (c) - { - case 'r': - stream << "\r"; - break; - case 'n': - stream << "\n"; - break; - case 't': - stream << "\t"; - break; - case 'f': - stream << "\f"; - break; - case '"': - stream << "\""; - break; - case '\\': - stream << "\\"; - break; - default: - stream << c; - break; - } - inEscape = false; - } - else if (c != '\\') - stream << c; - else - inEscape = true; - } - } +void UnescapeStringFromQuotationMarks(std::ostream &stream, const std::string_view &str) { + auto inEscape = false; + for (const auto &c : str) { + if (inEscape) { + switch (c) { + case 'r': + stream << "\r"; + break; + case 'n': + stream << "\n"; + break; + case 't': + stream << "\t"; + break; + case 'f': + stream << "\f"; + break; + case '"': + stream << "\""; + break; + case '\\': + stream << "\\"; + break; + default: + stream << c; + break; + } + inEscape = false; + } else if (c != '\\') + stream << c; + else + inEscape = true; + } } +} // namespace utils diff --git a/src/Utils/Utils/StringUtils.h b/src/Utils/Utils/StringUtils.h index 860f8dbb2..11f80e82b 100644 --- a/src/Utils/Utils/StringUtils.h +++ b/src/Utils/Utils/StringUtils.h @@ -1,14 +1,13 @@ #pragma once #include <string> -namespace utils -{ +namespace utils { #define M_LETTERS_AL_NUM "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" - static constexpr const char* LETTERS_AL_NUM = M_LETTERS_AL_NUM; - static constexpr const char* LETTERS_AL_NUM_UNDERSCORE = M_LETTERS_AL_NUM "_"; +static constexpr const char *LETTERS_AL_NUM = M_LETTERS_AL_NUM; +static constexpr const char *LETTERS_AL_NUM_UNDERSCORE = M_LETTERS_AL_NUM "_"; - std::string EscapeStringForQuotationMarks(const std::string_view& str); - void EscapeStringForQuotationMarks(std::ostream& stream, const std::string_view& str); - std::string UnescapeStringFromQuotationMarks(const std::string_view& str); - void UnescapeStringFromQuotationMarks(std::ostream& stream, const std::string_view& str); -} +std::string EscapeStringForQuotationMarks(const std::string_view &str); +void EscapeStringForQuotationMarks(std::ostream &stream, const std::string_view &str); +std::string UnescapeStringFromQuotationMarks(const std::string_view &str); +void UnescapeStringFromQuotationMarks(std::ostream &stream, const std::string_view &str); +} // namespace utils diff --git a/src/Utils/Utils/TransformIterator.h b/src/Utils/Utils/TransformIterator.h index 619609af6..ffc4c5610 100644 --- a/src/Utils/Utils/TransformIterator.h +++ b/src/Utils/Utils/TransformIterator.h @@ -2,25 +2,19 @@ #include <functional> -template <typename BaseIteratorType, typename SourceType, typename TargetType> -class TransformIterator -{ - BaseIteratorType m_base; - std::function<TargetType(SourceType)> m_transform; +template <typename BaseIteratorType, typename SourceType, typename TargetType> class TransformIterator { + BaseIteratorType m_base; + std::function<TargetType(SourceType)> m_transform; public: - TransformIterator(BaseIteratorType base, std::function<TargetType(SourceType)> transform) - : m_base(base), m_transform(transform) - { - } + TransformIterator(BaseIteratorType base, std::function<TargetType(SourceType)> transform) : m_base(base), m_transform(transform) {} - TransformIterator& operator++() - { - ++m_base; - return *this; - } + TransformIterator &operator++() { + ++m_base; + return *this; + } - bool operator==(TransformIterator other) const { return m_base == other.m_base; } - bool operator!=(TransformIterator other) const { return !(m_base == other.m_base); } - TargetType operator*() { return m_transform(*m_base); } + bool operator==(TransformIterator other) const { return m_base == other.m_base; } + bool operator!=(TransformIterator other) const { return !(m_base == other.m_base); } + TargetType operator*() { return m_transform(*m_base); } }; diff --git a/src/ZoneCode/Game/Common.h b/src/ZoneCode/Game/Common.h index dd9fe65f3..a8570d705 100644 --- a/src/ZoneCode/Game/Common.h +++ b/src/ZoneCode/Game/Common.h @@ -6,23 +6,22 @@ // =========================================== // Windows Types -typedef unsigned long DWORD; -typedef int BOOL; -typedef unsigned char BYTE; -typedef unsigned short WORD; -typedef float FLOAT; - -namespace std -{ - typedef char int8_t; - typedef short int16_t; - typedef int int32_t; - typedef long long int64_t; - typedef unsigned char uint8_t; - typedef unsigned short uint16_t; - typedef unsigned int uint32_t; - typedef unsigned long long uint64_t; -} +typedef unsigned long DWORD; +typedef int BOOL; +typedef unsigned char BYTE; +typedef unsigned short WORD; +typedef float FLOAT; + +namespace std { +typedef char int8_t; +typedef short int16_t; +typedef int int32_t; +typedef long long int64_t; +typedef unsigned char uint8_t; +typedef unsigned short uint16_t; +typedef unsigned int uint32_t; +typedef unsigned long long uint64_t; +} // namespace std #define __int8 char #define __int16 short diff --git a/src/ZoneCode/Game/IW3/IW3.h b/src/ZoneCode/Game/IW3/IW3.h index 98e6e4aff..c0c0057d6 100644 --- a/src/ZoneCode/Game/IW3/IW3.h +++ b/src/ZoneCode/Game/IW3/IW3.h @@ -2,7 +2,7 @@ // Entry point for IW3 code generation -#include "../Common.h" #include "../../../Common/Game/IW3/IW3_Assets.h" +#include "../Common.h" // EOF \ No newline at end of file diff --git a/src/ZoneCode/Game/IW4/IW4.h b/src/ZoneCode/Game/IW4/IW4.h index da61db127..7ddec31ba 100644 --- a/src/ZoneCode/Game/IW4/IW4.h +++ b/src/ZoneCode/Game/IW4/IW4.h @@ -2,7 +2,7 @@ // Entry point for IW4 code generation -#include "../Common.h" #include "../../../Common/Game/IW4/IW4_Assets.h" +#include "../Common.h" // EOF \ No newline at end of file diff --git a/src/ZoneCode/Game/IW5/IW5.h b/src/ZoneCode/Game/IW5/IW5.h index 46fba6de1..f32514e17 100644 --- a/src/ZoneCode/Game/IW5/IW5.h +++ b/src/ZoneCode/Game/IW5/IW5.h @@ -2,7 +2,7 @@ // Entry point for IW5 code generation -#include "../Common.h" #include "../../../Common/Game/IW5/IW5_Assets.h" +#include "../Common.h" // EOF \ No newline at end of file diff --git a/src/ZoneCode/Game/T5/T5.h b/src/ZoneCode/Game/T5/T5.h index dfcd4342a..48653b502 100644 --- a/src/ZoneCode/Game/T5/T5.h +++ b/src/ZoneCode/Game/T5/T5.h @@ -2,7 +2,7 @@ // Entry point for T5 code generation -#include "../Common.h" #include "../../../Common/Game/T5/T5_Assets.h" +#include "../Common.h" // EOF \ No newline at end of file diff --git a/src/ZoneCode/Game/T6/T6.h b/src/ZoneCode/Game/T6/T6.h index eca6b0c01..e867cb398 100644 --- a/src/ZoneCode/Game/T6/T6.h +++ b/src/ZoneCode/Game/T6/T6.h @@ -2,7 +2,7 @@ // Entry point for T6 code generation -#include "../Common.h" #include "../../../Common/Game/T6/T6_Assets.h" +#include "../Common.h" // EOF \ No newline at end of file diff --git a/src/ZoneCodeGenerator/main.cpp b/src/ZoneCodeGenerator/main.cpp index 9025da720..86e127170 100644 --- a/src/ZoneCodeGenerator/main.cpp +++ b/src/ZoneCodeGenerator/main.cpp @@ -1,7 +1,6 @@ #include "ZoneCodeGenerator.h" -int main(const int argc, const char** argv) -{ - const ZoneCodeGenerator zoneCodeGenerator; - return zoneCodeGenerator.Run(argc, argv); +int main(const int argc, const char **argv) { + const ZoneCodeGenerator zoneCodeGenerator; + return zoneCodeGenerator.Run(argc, argv); } diff --git a/src/ZoneCodeGeneratorLib/Domain/Computations/MemberComputations.cpp b/src/ZoneCodeGeneratorLib/Domain/Computations/MemberComputations.cpp index 407ce18b7..746d1ba6f 100644 --- a/src/ZoneCodeGeneratorLib/Domain/Computations/MemberComputations.cpp +++ b/src/ZoneCodeGeneratorLib/Domain/Computations/MemberComputations.cpp @@ -3,226 +3,184 @@ #include <algorithm> #include <cassert> -#include "StructureComputations.h" #include "Domain/Definition/ArrayDeclarationModifier.h" #include "Domain/Definition/PointerDeclarationModifier.h" +#include "StructureComputations.h" -MemberComputations::MemberComputations(const MemberInformation* member) - : m_info(member) -{ - assert(m_info != nullptr); -} +MemberComputations::MemberComputations(const MemberInformation *member) : m_info(member) { assert(m_info != nullptr); } -bool MemberComputations::ShouldIgnore() const -{ - return m_info->m_condition && m_info->m_condition->IsStatic() && m_info->m_condition->EvaluateNumeric() == 0; -} +bool MemberComputations::ShouldIgnore() const { return m_info->m_condition && m_info->m_condition->IsStatic() && m_info->m_condition->EvaluateNumeric() == 0; } -bool MemberComputations::ContainsNonEmbeddedReference() const -{ - const auto& declarationModifiers = m_info->m_member->m_type_declaration->m_declaration_modifiers; - return std::any_of(declarationModifiers.begin(), declarationModifiers.end(), [](const std::unique_ptr<DeclarationModifier>& modifier) - { - return modifier->GetType() == DeclarationModifierType::POINTER; - }); +bool MemberComputations::ContainsNonEmbeddedReference() const { + const auto &declarationModifiers = m_info->m_member->m_type_declaration->m_declaration_modifiers; + return std::any_of(declarationModifiers.begin(), declarationModifiers.end(), + [](const std::unique_ptr<DeclarationModifier> &modifier) { return modifier->GetType() == DeclarationModifierType::POINTER; }); } -bool MemberComputations::ContainsSinglePointerReference() const -{ - const auto& declarationModifiers = m_info->m_member->m_type_declaration->m_declaration_modifiers; - if (declarationModifiers.empty()) - return false; +bool MemberComputations::ContainsSinglePointerReference() const { + const auto &declarationModifiers = m_info->m_member->m_type_declaration->m_declaration_modifiers; + if (declarationModifiers.empty()) + return false; - const auto* lastModifier = declarationModifiers[declarationModifiers.size() - 1].get(); - if (lastModifier->GetType() != DeclarationModifierType::POINTER) - return false; + const auto *lastModifier = declarationModifiers[declarationModifiers.size() - 1].get(); + if (lastModifier->GetType() != DeclarationModifierType::POINTER) + return false; - return !dynamic_cast<const PointerDeclarationModifier*>(lastModifier)->AnyCountEvaluationIsArray(); + return !dynamic_cast<const PointerDeclarationModifier *>(lastModifier)->AnyCountEvaluationIsArray(); } -bool MemberComputations::ContainsArrayPointerReference() const -{ - const auto& declarationModifiers = m_info->m_member->m_type_declaration->m_declaration_modifiers; - if (declarationModifiers.empty()) - return false; +bool MemberComputations::ContainsArrayPointerReference() const { + const auto &declarationModifiers = m_info->m_member->m_type_declaration->m_declaration_modifiers; + if (declarationModifiers.empty()) + return false; - const auto* lastModifier = declarationModifiers[declarationModifiers.size() - 1].get(); - if (lastModifier->GetType() != DeclarationModifierType::POINTER) - return false; + const auto *lastModifier = declarationModifiers[declarationModifiers.size() - 1].get(); + if (lastModifier->GetType() != DeclarationModifierType::POINTER) + return false; - return dynamic_cast<const PointerDeclarationModifier*>(lastModifier)->AnyCountEvaluationIsArray(); + return dynamic_cast<const PointerDeclarationModifier *>(lastModifier)->AnyCountEvaluationIsArray(); } -bool MemberComputations::ContainsPointerArrayReference() const -{ - if (!ContainsSinglePointerReference()) - return false; +bool MemberComputations::ContainsPointerArrayReference() const { + if (!ContainsSinglePointerReference()) + return false; - const auto pointerDepth = GetPointerDepth(); - const auto isArray = IsArray(); + const auto pointerDepth = GetPointerDepth(); + const auto isArray = IsArray(); - return isArray && pointerDepth == 1 || !isArray && pointerDepth == 2; + return isArray && pointerDepth == 1 || !isArray && pointerDepth == 2; } -bool MemberComputations::ContainsArrayReference() const -{ - const auto& declarationModifiers = m_info->m_member->m_type_declaration->m_declaration_modifiers; - if (declarationModifiers.empty()) - return false; +bool MemberComputations::ContainsArrayReference() const { + const auto &declarationModifiers = m_info->m_member->m_type_declaration->m_declaration_modifiers; + if (declarationModifiers.empty()) + return false; - const auto* lastModifier = declarationModifiers[declarationModifiers.size() - 1].get(); - return lastModifier->GetType() == DeclarationModifierType::ARRAY; + const auto *lastModifier = declarationModifiers[declarationModifiers.size() - 1].get(); + return lastModifier->GetType() == DeclarationModifierType::ARRAY; } -const IEvaluation* MemberComputations::GetArrayPointerCountEvaluation() const -{ - const auto& declarationModifiers = m_info->m_member->m_type_declaration->m_declaration_modifiers; - if (declarationModifiers.empty()) - return nullptr; +const IEvaluation *MemberComputations::GetArrayPointerCountEvaluation() const { + const auto &declarationModifiers = m_info->m_member->m_type_declaration->m_declaration_modifiers; + if (declarationModifiers.empty()) + return nullptr; - const auto* lastModifier = declarationModifiers[declarationModifiers.size() - 1].get(); - return lastModifier->GetType() == DeclarationModifierType::POINTER - ? dynamic_cast<const PointerDeclarationModifier*>(lastModifier)->GetCountEvaluation() - : nullptr; + const auto *lastModifier = declarationModifiers[declarationModifiers.size() - 1].get(); + return lastModifier->GetType() == DeclarationModifierType::POINTER ? dynamic_cast<const PointerDeclarationModifier *>(lastModifier)->GetCountEvaluation() + : nullptr; } -bool MemberComputations::IsArray() const -{ - const auto& declarationModifiers = m_info->m_member->m_type_declaration->m_declaration_modifiers; - if (declarationModifiers.empty()) - return false; +bool MemberComputations::IsArray() const { + const auto &declarationModifiers = m_info->m_member->m_type_declaration->m_declaration_modifiers; + if (declarationModifiers.empty()) + return false; - return declarationModifiers[0]->GetType() == DeclarationModifierType::ARRAY; + return declarationModifiers[0]->GetType() == DeclarationModifierType::ARRAY; } -std::vector<int> MemberComputations::GetArraySizes() const -{ - std::vector<int> sizes; - const auto& declarationModifiers = m_info->m_member->m_type_declaration->m_declaration_modifiers; - for (const auto& declarationModifier : declarationModifiers) - { - if (declarationModifier->GetType() != DeclarationModifierType::ARRAY) - break; +std::vector<int> MemberComputations::GetArraySizes() const { + std::vector<int> sizes; + const auto &declarationModifiers = m_info->m_member->m_type_declaration->m_declaration_modifiers; + for (const auto &declarationModifier : declarationModifiers) { + if (declarationModifier->GetType() != DeclarationModifierType::ARRAY) + break; - sizes.push_back(dynamic_cast<const ArrayDeclarationModifier*>(declarationModifier.get())->m_size); - } + sizes.push_back(dynamic_cast<const ArrayDeclarationModifier *>(declarationModifier.get())->m_size); + } - return sizes; + return sizes; } -int MemberComputations::GetArrayDimension() const -{ - auto dimension = 0; - const auto& declarationModifiers = m_info->m_member->m_type_declaration->m_declaration_modifiers; - for (const auto& declarationModifier : declarationModifiers) - { - if (declarationModifier->GetType() != DeclarationModifierType::ARRAY) - break; +int MemberComputations::GetArrayDimension() const { + auto dimension = 0; + const auto &declarationModifiers = m_info->m_member->m_type_declaration->m_declaration_modifiers; + for (const auto &declarationModifier : declarationModifiers) { + if (declarationModifier->GetType() != DeclarationModifierType::ARRAY) + break; - dimension++; - } + dimension++; + } - return dimension; -} - -bool MemberComputations::IsPointerToArray() const -{ - const auto& declarationModifiers = m_info->m_member->m_type_declaration->m_declaration_modifiers; - if (declarationModifiers.empty()) - return false; - - const auto* lastModifier = declarationModifiers[declarationModifiers.size() - 1].get(); - if (lastModifier->GetType() != DeclarationModifierType::ARRAY) - return false; - - return std::any_of(declarationModifiers.begin(), declarationModifiers.end(), [](const std::unique_ptr<DeclarationModifier>& modifier) - { - return modifier->GetType() == DeclarationModifierType::POINTER; - }); -} - -std::vector<int> MemberComputations::GetPointerToArraySizes() const -{ - std::vector<int> sizes; - const auto& declarationModifiers = m_info->m_member->m_type_declaration->m_declaration_modifiers; - for (const auto& declarationModifier : declarationModifiers) - { - if (declarationModifier->GetType() == DeclarationModifierType::ARRAY) - { - sizes.push_back(dynamic_cast<ArrayDeclarationModifier*>(declarationModifier.get())->m_size); - } - else - { - sizes.clear(); - } - } + return dimension; +} + +bool MemberComputations::IsPointerToArray() const { + const auto &declarationModifiers = m_info->m_member->m_type_declaration->m_declaration_modifiers; + if (declarationModifiers.empty()) + return false; - return sizes; + const auto *lastModifier = declarationModifiers[declarationModifiers.size() - 1].get(); + if (lastModifier->GetType() != DeclarationModifierType::ARRAY) + return false; + + return std::any_of(declarationModifiers.begin(), declarationModifiers.end(), + [](const std::unique_ptr<DeclarationModifier> &modifier) { return modifier->GetType() == DeclarationModifierType::POINTER; }); } -int MemberComputations::GetPointerDepth() const -{ - auto depth = 0; - const auto& declarationModifiers = m_info->m_member->m_type_declaration->m_declaration_modifiers; - for(const auto& declarationModifier : declarationModifiers) - { - if (declarationModifier->GetType() == DeclarationModifierType::POINTER) - depth++; +std::vector<int> MemberComputations::GetPointerToArraySizes() const { + std::vector<int> sizes; + const auto &declarationModifiers = m_info->m_member->m_type_declaration->m_declaration_modifiers; + for (const auto &declarationModifier : declarationModifiers) { + if (declarationModifier->GetType() == DeclarationModifierType::ARRAY) { + sizes.push_back(dynamic_cast<ArrayDeclarationModifier *>(declarationModifier.get())->m_size); + } else { + sizes.clear(); } + } - return depth; + return sizes; } -bool MemberComputations::IsNotInDefaultNormalBlock() const -{ - return m_info->m_fast_file_block != nullptr && !(m_info->m_fast_file_block->m_type == FastFileBlockType::NORMAL && m_info->m_fast_file_block->m_is_default); +int MemberComputations::GetPointerDepth() const { + auto depth = 0; + const auto &declarationModifiers = m_info->m_member->m_type_declaration->m_declaration_modifiers; + for (const auto &declarationModifier : declarationModifiers) { + if (declarationModifier->GetType() == DeclarationModifierType::POINTER) + depth++; + } + + return depth; } -bool MemberComputations::IsInTempBlock() const -{ - return m_info->m_fast_file_block != nullptr && m_info->m_fast_file_block->m_type == FastFileBlockType::TEMP; +bool MemberComputations::IsNotInDefaultNormalBlock() const { + return m_info->m_fast_file_block != nullptr && !(m_info->m_fast_file_block->m_type == FastFileBlockType::NORMAL && m_info->m_fast_file_block->m_is_default); } -bool MemberComputations::IsInRuntimeBlock() const -{ - return m_info->m_fast_file_block != nullptr && m_info->m_fast_file_block->m_type == FastFileBlockType::RUNTIME; +bool MemberComputations::IsInTempBlock() const { return m_info->m_fast_file_block != nullptr && m_info->m_fast_file_block->m_type == FastFileBlockType::TEMP; } + +bool MemberComputations::IsInRuntimeBlock() const { + return m_info->m_fast_file_block != nullptr && m_info->m_fast_file_block->m_type == FastFileBlockType::RUNTIME; } -bool MemberComputations::IsFirstMember() const -{ - const auto parentUsedMembers = StructureComputations(m_info->m_parent).GetUsedMembers(); - return !parentUsedMembers.empty() && parentUsedMembers[0] == m_info; +bool MemberComputations::IsFirstMember() const { + const auto parentUsedMembers = StructureComputations(m_info->m_parent).GetUsedMembers(); + return !parentUsedMembers.empty() && parentUsedMembers[0] == m_info; } -bool MemberComputations::IsLastMember() const -{ - const auto parentUsedMembers = StructureComputations(m_info->m_parent).GetUsedMembers(); - return !parentUsedMembers.empty() && parentUsedMembers[parentUsedMembers.size() - 1] == m_info; +bool MemberComputations::IsLastMember() const { + const auto parentUsedMembers = StructureComputations(m_info->m_parent).GetUsedMembers(); + return !parentUsedMembers.empty() && parentUsedMembers[parentUsedMembers.size() - 1] == m_info; } -bool MemberComputations::HasDynamicArraySize() const -{ - const auto& declarationModifiers = m_info->m_member->m_type_declaration->m_declaration_modifiers; +bool MemberComputations::HasDynamicArraySize() const { + const auto &declarationModifiers = m_info->m_member->m_type_declaration->m_declaration_modifiers; - return std::any_of(declarationModifiers.begin(), declarationModifiers.end(), [](const std::unique_ptr<DeclarationModifier>& declarationModifier) - { - return declarationModifier->GetType() == DeclarationModifierType::ARRAY - && dynamic_cast<ArrayDeclarationModifier*>(declarationModifier.get())->m_dynamic_size_evaluation; - }); + return std::any_of(declarationModifiers.begin(), declarationModifiers.end(), [](const std::unique_ptr<DeclarationModifier> &declarationModifier) { + return declarationModifier->GetType() == DeclarationModifierType::ARRAY && + dynamic_cast<ArrayDeclarationModifier *>(declarationModifier.get())->m_dynamic_size_evaluation; + }); } -bool MemberComputations::IsDynamicMember() const -{ - if (HasDynamicArraySize()) - return true; +bool MemberComputations::IsDynamicMember() const { + if (HasDynamicArraySize()) + return true; - return !ContainsNonEmbeddedReference() && m_info->m_type && StructureComputations(m_info->m_type).GetDynamicMember() != nullptr; + return !ContainsNonEmbeddedReference() && m_info->m_type && StructureComputations(m_info->m_type).GetDynamicMember() != nullptr; } -bool MemberComputations::IsAfterPartialLoad() const -{ - if (IsDynamicMember()) - return true; +bool MemberComputations::IsAfterPartialLoad() const { + if (IsDynamicMember()) + return true; - return m_info->m_parent->m_definition->GetType() == DataDefinitionType::UNION && StructureComputations(m_info->m_parent).GetDynamicMember() != nullptr; + return m_info->m_parent->m_definition->GetType() == DataDefinitionType::UNION && StructureComputations(m_info->m_parent).GetDynamicMember() != nullptr; } diff --git a/src/ZoneCodeGeneratorLib/Domain/Computations/MemberComputations.h b/src/ZoneCodeGeneratorLib/Domain/Computations/MemberComputations.h index 8a9fd8a13..b83419b8a 100644 --- a/src/ZoneCodeGeneratorLib/Domain/Computations/MemberComputations.h +++ b/src/ZoneCodeGeneratorLib/Domain/Computations/MemberComputations.h @@ -2,32 +2,31 @@ #include "Domain/Information/MemberInformation.h" -class MemberComputations -{ - const MemberInformation* const m_info; +class MemberComputations { + const MemberInformation *const m_info; public: - explicit MemberComputations(const MemberInformation* member); + explicit MemberComputations(const MemberInformation *member); - _NODISCARD bool ShouldIgnore() const; - _NODISCARD bool ContainsNonEmbeddedReference() const; - _NODISCARD bool ContainsSinglePointerReference() const; - _NODISCARD bool ContainsArrayPointerReference() const; - _NODISCARD bool ContainsPointerArrayReference() const; - _NODISCARD bool ContainsArrayReference() const; - _NODISCARD const IEvaluation* GetArrayPointerCountEvaluation() const; - _NODISCARD bool IsArray() const; - _NODISCARD std::vector<int> GetArraySizes() const; - _NODISCARD int GetArrayDimension() const; - _NODISCARD bool IsPointerToArray() const; - _NODISCARD std::vector<int> GetPointerToArraySizes() const; - _NODISCARD int GetPointerDepth() const; - _NODISCARD bool IsNotInDefaultNormalBlock() const; - _NODISCARD bool IsInTempBlock() const; - _NODISCARD bool IsInRuntimeBlock() const; - _NODISCARD bool IsFirstMember() const; - _NODISCARD bool IsLastMember() const; - _NODISCARD bool HasDynamicArraySize() const; - _NODISCARD bool IsDynamicMember() const; - _NODISCARD bool IsAfterPartialLoad() const; + _NODISCARD bool ShouldIgnore() const; + _NODISCARD bool ContainsNonEmbeddedReference() const; + _NODISCARD bool ContainsSinglePointerReference() const; + _NODISCARD bool ContainsArrayPointerReference() const; + _NODISCARD bool ContainsPointerArrayReference() const; + _NODISCARD bool ContainsArrayReference() const; + _NODISCARD const IEvaluation *GetArrayPointerCountEvaluation() const; + _NODISCARD bool IsArray() const; + _NODISCARD std::vector<int> GetArraySizes() const; + _NODISCARD int GetArrayDimension() const; + _NODISCARD bool IsPointerToArray() const; + _NODISCARD std::vector<int> GetPointerToArraySizes() const; + _NODISCARD int GetPointerDepth() const; + _NODISCARD bool IsNotInDefaultNormalBlock() const; + _NODISCARD bool IsInTempBlock() const; + _NODISCARD bool IsInRuntimeBlock() const; + _NODISCARD bool IsFirstMember() const; + _NODISCARD bool IsLastMember() const; + _NODISCARD bool HasDynamicArraySize() const; + _NODISCARD bool IsDynamicMember() const; + _NODISCARD bool IsAfterPartialLoad() const; }; diff --git a/src/ZoneCodeGeneratorLib/Domain/Computations/MemberDeclarationModifierComputations.cpp b/src/ZoneCodeGeneratorLib/Domain/Computations/MemberDeclarationModifierComputations.cpp index 6699322bf..b69c80266 100644 --- a/src/ZoneCodeGeneratorLib/Domain/Computations/MemberDeclarationModifierComputations.cpp +++ b/src/ZoneCodeGeneratorLib/Domain/Computations/MemberDeclarationModifierComputations.cpp @@ -3,251 +3,207 @@ #include <algorithm> #include <cassert> -#include "MemberComputations.h" #include "Domain/Definition/ArrayDeclarationModifier.h" #include "Domain/Definition/PointerDeclarationModifier.h" +#include "MemberComputations.h" -DeclarationModifierComputations::DeclarationModifierComputations(const MemberInformation* member, std::vector<int> modifierIndices) - : m_information(member), - m_modifier_indices(std::move(modifierIndices)) -{ - auto combinedIndex = 0; - auto arraySizes = MemberComputations(m_information).GetArraySizes(); - std::vector<int> sizePerDepth(arraySizes.size()); - - auto currentDepthSize = 1; - for (int i = arraySizes.size(); i > 0; i--) - { - sizePerDepth[i - 1] = currentDepthSize; - currentDepthSize *= arraySizes[i - 1]; - } +DeclarationModifierComputations::DeclarationModifierComputations(const MemberInformation *member, std::vector<int> modifierIndices) + : m_information(member), m_modifier_indices(std::move(modifierIndices)) { + auto combinedIndex = 0; + auto arraySizes = MemberComputations(m_information).GetArraySizes(); + std::vector<int> sizePerDepth(arraySizes.size()); - auto currentDepth = 0; - for (auto modifierIndex : m_modifier_indices) - { - combinedIndex += sizePerDepth[currentDepth++] * modifierIndex; - } + auto currentDepthSize = 1; + for (int i = arraySizes.size(); i > 0; i--) { + sizePerDepth[i - 1] = currentDepthSize; + currentDepthSize *= arraySizes[i - 1]; + } - m_combined_index = combinedIndex; -} + auto currentDepth = 0; + for (auto modifierIndex : m_modifier_indices) { + combinedIndex += sizePerDepth[currentDepth++] * modifierIndex; + } -DeclarationModifierComputations::DeclarationModifierComputations(const MemberInformation* member) - : m_information(member), - m_combined_index(0) -{ + m_combined_index = combinedIndex; } -DeclarationModifier* DeclarationModifierComputations::GetDeclarationModifier() const -{ - const auto& declarationModifiers = m_information->m_member->m_type_declaration->m_declaration_modifiers; - if (m_modifier_indices.size() < declarationModifiers.size()) - return declarationModifiers[m_modifier_indices.size()].get(); +DeclarationModifierComputations::DeclarationModifierComputations(const MemberInformation *member) : m_information(member), m_combined_index(0) {} - return nullptr; +DeclarationModifier *DeclarationModifierComputations::GetDeclarationModifier() const { + const auto &declarationModifiers = m_information->m_member->m_type_declaration->m_declaration_modifiers; + if (m_modifier_indices.size() < declarationModifiers.size()) + return declarationModifiers[m_modifier_indices.size()].get(); + + return nullptr; } -DeclarationModifier* DeclarationModifierComputations::GetNextDeclarationModifier() const -{ - const auto& declarationModifiers = m_information->m_member->m_type_declaration->m_declaration_modifiers; - if (m_modifier_indices.size() + 1 < declarationModifiers.size()) - return declarationModifiers[m_modifier_indices.size() + 1].get(); +DeclarationModifier *DeclarationModifierComputations::GetNextDeclarationModifier() const { + const auto &declarationModifiers = m_information->m_member->m_type_declaration->m_declaration_modifiers; + if (m_modifier_indices.size() + 1 < declarationModifiers.size()) + return declarationModifiers[m_modifier_indices.size() + 1].get(); - return nullptr; + return nullptr; } -std::vector<DeclarationModifier*> DeclarationModifierComputations::GetFollowingDeclarationModifiers() const -{ - std::vector<DeclarationModifier*> following; - const auto& declarationModifiers = m_information->m_member->m_type_declaration->m_declaration_modifiers; +std::vector<DeclarationModifier *> DeclarationModifierComputations::GetFollowingDeclarationModifiers() const { + std::vector<DeclarationModifier *> following; + const auto &declarationModifiers = m_information->m_member->m_type_declaration->m_declaration_modifiers; - if (m_modifier_indices.size() + 1 < declarationModifiers.size()) - { - for (auto i = declarationModifiers.begin() + m_modifier_indices.size() + 1; i != declarationModifiers.end(); ++i) - { - following.push_back(i->get()); - } + if (m_modifier_indices.size() + 1 < declarationModifiers.size()) { + for (auto i = declarationModifiers.begin() + m_modifier_indices.size() + 1; i != declarationModifiers.end(); ++i) { + following.push_back(i->get()); } + } - return following; + return following; } -std::vector<int> DeclarationModifierComputations::GetArrayIndices() const -{ - return m_modifier_indices; -} +std::vector<int> DeclarationModifierComputations::GetArrayIndices() const { return m_modifier_indices; } -bool DeclarationModifierComputations::IsArray() const -{ - auto* declarationModifier = GetDeclarationModifier(); - return declarationModifier != nullptr && declarationModifier->GetType() == DeclarationModifierType::ARRAY; +bool DeclarationModifierComputations::IsArray() const { + auto *declarationModifier = GetDeclarationModifier(); + return declarationModifier != nullptr && declarationModifier->GetType() == DeclarationModifierType::ARRAY; } -int DeclarationModifierComputations::GetArraySize() const -{ - auto* declarationModifier = GetDeclarationModifier(); - if (declarationModifier != nullptr && declarationModifier->GetType() == DeclarationModifierType::ARRAY) - { - return dynamic_cast<ArrayDeclarationModifier*>(declarationModifier)->m_size; - } +int DeclarationModifierComputations::GetArraySize() const { + auto *declarationModifier = GetDeclarationModifier(); + if (declarationModifier != nullptr && declarationModifier->GetType() == DeclarationModifierType::ARRAY) { + return dynamic_cast<ArrayDeclarationModifier *>(declarationModifier)->m_size; + } - return 0; + return 0; } -bool DeclarationModifierComputations::HasDynamicArrayCount() const -{ - auto* declarationModifier = GetDeclarationModifier(); - if (declarationModifier != nullptr && declarationModifier->GetType() == DeclarationModifierType::ARRAY) - { - return dynamic_cast<ArrayDeclarationModifier*>(declarationModifier)->m_dynamic_count_evaluation != nullptr; - } +bool DeclarationModifierComputations::HasDynamicArrayCount() const { + auto *declarationModifier = GetDeclarationModifier(); + if (declarationModifier != nullptr && declarationModifier->GetType() == DeclarationModifierType::ARRAY) { + return dynamic_cast<ArrayDeclarationModifier *>(declarationModifier)->m_dynamic_count_evaluation != nullptr; + } - return false; + return false; } -const IEvaluation* DeclarationModifierComputations::GetDynamicArrayCountEvaluation() const -{ - auto* declarationModifier = GetDeclarationModifier(); - if (declarationModifier != nullptr && declarationModifier->GetType() == DeclarationModifierType::ARRAY) - { - return dynamic_cast<ArrayDeclarationModifier*>(declarationModifier)->m_dynamic_count_evaluation.get(); - } +const IEvaluation *DeclarationModifierComputations::GetDynamicArrayCountEvaluation() const { + auto *declarationModifier = GetDeclarationModifier(); + if (declarationModifier != nullptr && declarationModifier->GetType() == DeclarationModifierType::ARRAY) { + return dynamic_cast<ArrayDeclarationModifier *>(declarationModifier)->m_dynamic_count_evaluation.get(); + } - return nullptr; + return nullptr; } -std::vector<DeclarationModifierComputations> DeclarationModifierComputations::GetArrayEntries() const -{ - std::vector<DeclarationModifierComputations> arrayEntries; +std::vector<DeclarationModifierComputations> DeclarationModifierComputations::GetArrayEntries() const { + std::vector<DeclarationModifierComputations> arrayEntries; - const auto arraySize = GetArraySize(); - for (auto i = 0; i < arraySize; i++) - { - std::vector<int> childModifierIndices(m_modifier_indices.size() + 1); - std::copy(m_modifier_indices.begin(), m_modifier_indices.end(), childModifierIndices.begin()); - childModifierIndices[childModifierIndices.size() - 1] = i; - arrayEntries.push_back(DeclarationModifierComputations(m_information, std::move(childModifierIndices))); - } + const auto arraySize = GetArraySize(); + for (auto i = 0; i < arraySize; i++) { + std::vector<int> childModifierIndices(m_modifier_indices.size() + 1); + std::copy(m_modifier_indices.begin(), m_modifier_indices.end(), childModifierIndices.begin()); + childModifierIndices[childModifierIndices.size() - 1] = i; + arrayEntries.push_back(DeclarationModifierComputations(m_information, std::move(childModifierIndices))); + } - return arrayEntries; + return arrayEntries; } -bool DeclarationModifierComputations::IsSinglePointer() const -{ - auto* declarationModifier = GetDeclarationModifier(); +bool DeclarationModifierComputations::IsSinglePointer() const { + auto *declarationModifier = GetDeclarationModifier(); - if (declarationModifier != nullptr - && declarationModifier->GetType() == DeclarationModifierType::POINTER - && !dynamic_cast<PointerDeclarationModifier*>(declarationModifier)->CountEvaluationIsArray(m_combined_index)) - { - const auto following = GetFollowingDeclarationModifiers(); + if (declarationModifier != nullptr && declarationModifier->GetType() == DeclarationModifierType::POINTER && + !dynamic_cast<PointerDeclarationModifier *>(declarationModifier)->CountEvaluationIsArray(m_combined_index)) { + const auto following = GetFollowingDeclarationModifiers(); - return !std::any_of(following.begin(), following.end(), [](const DeclarationModifier* modifier) - { - return modifier->GetType() == DeclarationModifierType::POINTER; - }); - } + return !std::any_of(following.begin(), following.end(), + [](const DeclarationModifier *modifier) { return modifier->GetType() == DeclarationModifierType::POINTER; }); + } - return false; + return false; } -bool DeclarationModifierComputations::IsArrayPointer() const -{ - auto* declarationModifier = GetDeclarationModifier(); +bool DeclarationModifierComputations::IsArrayPointer() const { + auto *declarationModifier = GetDeclarationModifier(); - if (declarationModifier != nullptr - && declarationModifier->GetType() == DeclarationModifierType::POINTER - && dynamic_cast<PointerDeclarationModifier*>(declarationModifier)->CountEvaluationIsArray(m_combined_index)) - { - const auto following = GetFollowingDeclarationModifiers(); + if (declarationModifier != nullptr && declarationModifier->GetType() == DeclarationModifierType::POINTER && + dynamic_cast<PointerDeclarationModifier *>(declarationModifier)->CountEvaluationIsArray(m_combined_index)) { + const auto following = GetFollowingDeclarationModifiers(); - return !std::any_of(following.begin(), following.end(), [](const DeclarationModifier* modifier) - { - return modifier->GetType() == DeclarationModifierType::POINTER; - }); - } + return !std::any_of(following.begin(), following.end(), + [](const DeclarationModifier *modifier) { return modifier->GetType() == DeclarationModifierType::POINTER; }); + } - return false; + return false; } -const IEvaluation* DeclarationModifierComputations::GetArrayPointerCountEvaluation() const -{ - auto* declarationModifier = GetDeclarationModifier(); - if (declarationModifier == nullptr || declarationModifier->GetType() != DeclarationModifierType::POINTER) - return nullptr; +const IEvaluation *DeclarationModifierComputations::GetArrayPointerCountEvaluation() const { + auto *declarationModifier = GetDeclarationModifier(); + if (declarationModifier == nullptr || declarationModifier->GetType() != DeclarationModifierType::POINTER) + return nullptr; - return dynamic_cast<PointerDeclarationModifier*>(declarationModifier)->GetCountEvaluationForArrayIndex(m_combined_index); + return dynamic_cast<PointerDeclarationModifier *>(declarationModifier)->GetCountEvaluationForArrayIndex(m_combined_index); } -bool DeclarationModifierComputations::IsPointerArray() const -{ - auto* declarationModifier = GetDeclarationModifier(); - if (declarationModifier == nullptr) - return false; +bool DeclarationModifierComputations::IsPointerArray() const { + auto *declarationModifier = GetDeclarationModifier(); + if (declarationModifier == nullptr) + return false; - auto* nextDeclarationModifier = GetNextDeclarationModifier(); - if (nextDeclarationModifier == nullptr) - return false; + auto *nextDeclarationModifier = GetNextDeclarationModifier(); + if (nextDeclarationModifier == nullptr) + return false; - const auto thisDeclModIsArray = declarationModifier->GetType() == DeclarationModifierType::POINTER - && dynamic_cast<PointerDeclarationModifier*>(declarationModifier)->CountEvaluationIsArray(m_combined_index) - || declarationModifier->GetType() == DeclarationModifierType::ARRAY; + const auto thisDeclModIsArray = declarationModifier->GetType() == DeclarationModifierType::POINTER && + dynamic_cast<PointerDeclarationModifier *>(declarationModifier)->CountEvaluationIsArray(m_combined_index) || + declarationModifier->GetType() == DeclarationModifierType::ARRAY; - if (!thisDeclModIsArray) - return false; + if (!thisDeclModIsArray) + return false; - const auto nextDeclModIsSinglePointer = nextDeclarationModifier->GetType() == DeclarationModifierType::POINTER - && !dynamic_cast<PointerDeclarationModifier*>(nextDeclarationModifier)->AnyCountEvaluationIsArray(); + const auto nextDeclModIsSinglePointer = nextDeclarationModifier->GetType() == DeclarationModifierType::POINTER && + !dynamic_cast<PointerDeclarationModifier *>(nextDeclarationModifier)->AnyCountEvaluationIsArray(); - return nextDeclModIsSinglePointer; + return nextDeclModIsSinglePointer; } -const IEvaluation* DeclarationModifierComputations::GetPointerArrayCountEvaluation() const -{ - auto* declarationModifier = GetDeclarationModifier(); - if (declarationModifier == nullptr) - return nullptr; +const IEvaluation *DeclarationModifierComputations::GetPointerArrayCountEvaluation() const { + auto *declarationModifier = GetDeclarationModifier(); + if (declarationModifier == nullptr) + return nullptr; - if (declarationModifier->GetType() == DeclarationModifierType::POINTER) - { - return dynamic_cast<PointerDeclarationModifier*>(declarationModifier)->GetCountEvaluationForArrayIndex(m_combined_index); - } + if (declarationModifier->GetType() == DeclarationModifierType::POINTER) { + return dynamic_cast<PointerDeclarationModifier *>(declarationModifier)->GetCountEvaluationForArrayIndex(m_combined_index); + } - if (declarationModifier->GetType() == DeclarationModifierType::ARRAY) - { - auto* arrayDeclarationModifier = dynamic_cast<ArrayDeclarationModifier*>(declarationModifier); - return arrayDeclarationModifier->m_dynamic_count_evaluation.get(); // This might be null in which case there is no evaluation but a static size - } + if (declarationModifier->GetType() == DeclarationModifierType::ARRAY) { + auto *arrayDeclarationModifier = dynamic_cast<ArrayDeclarationModifier *>(declarationModifier); + return arrayDeclarationModifier->m_dynamic_count_evaluation.get(); // This might be null in which case there is no evaluation but a static size + } - assert(false); - return nullptr; + assert(false); + return nullptr; } -bool DeclarationModifierComputations::IsDynamicArray() const -{ - auto* declarationModifier = GetDeclarationModifier(); - if (declarationModifier == nullptr) - return false; +bool DeclarationModifierComputations::IsDynamicArray() const { + auto *declarationModifier = GetDeclarationModifier(); + if (declarationModifier == nullptr) + return false; - return declarationModifier->GetType() == DeclarationModifierType::ARRAY - && dynamic_cast<ArrayDeclarationModifier*>(declarationModifier)->m_dynamic_size_evaluation != nullptr; + return declarationModifier->GetType() == DeclarationModifierType::ARRAY && + dynamic_cast<ArrayDeclarationModifier *>(declarationModifier)->m_dynamic_size_evaluation != nullptr; } -const IEvaluation* DeclarationModifierComputations::GetDynamicArraySizeEvaluation() const -{ - auto* declarationModifier = GetDeclarationModifier(); - if (declarationModifier == nullptr - || declarationModifier->GetType() != DeclarationModifierType::ARRAY) - return nullptr; +const IEvaluation *DeclarationModifierComputations::GetDynamicArraySizeEvaluation() const { + auto *declarationModifier = GetDeclarationModifier(); + if (declarationModifier == nullptr || declarationModifier->GetType() != DeclarationModifierType::ARRAY) + return nullptr; - return dynamic_cast<ArrayDeclarationModifier*>(declarationModifier)->m_dynamic_size_evaluation.get(); + return dynamic_cast<ArrayDeclarationModifier *>(declarationModifier)->m_dynamic_size_evaluation.get(); } -unsigned DeclarationModifierComputations::GetAlignment() const -{ - const auto following = GetFollowingDeclarationModifiers(); +unsigned DeclarationModifierComputations::GetAlignment() const { + const auto following = GetFollowingDeclarationModifiers(); - return std::any_of(following.begin(), following.end(), [](const DeclarationModifier* modifier) - { - return modifier->GetType() == DeclarationModifierType::POINTER; - }) ? m_information->m_member->GetAlignment() : m_information->m_member->m_type_declaration->m_type->GetAlignment(); + return std::any_of(following.begin(), following.end(), + [](const DeclarationModifier *modifier) { return modifier->GetType() == DeclarationModifierType::POINTER; }) + ? m_information->m_member->GetAlignment() + : m_information->m_member->m_type_declaration->m_type->GetAlignment(); } diff --git a/src/ZoneCodeGeneratorLib/Domain/Computations/MemberDeclarationModifierComputations.h b/src/ZoneCodeGeneratorLib/Domain/Computations/MemberDeclarationModifierComputations.h index 490697d36..19bd4542b 100644 --- a/src/ZoneCodeGeneratorLib/Domain/Computations/MemberDeclarationModifierComputations.h +++ b/src/ZoneCodeGeneratorLib/Domain/Computations/MemberDeclarationModifierComputations.h @@ -1,35 +1,34 @@ #pragma once -#include "Utils/ClassUtils.h" -#include "Domain/Information/MemberInformation.h" #include "Domain/Evaluation/IEvaluation.h" +#include "Domain/Information/MemberInformation.h" +#include "Utils/ClassUtils.h" -class DeclarationModifierComputations -{ - const MemberInformation* const m_information; - std::vector<int> m_modifier_indices; - int m_combined_index; +class DeclarationModifierComputations { + const MemberInformation *const m_information; + std::vector<int> m_modifier_indices; + int m_combined_index; - DeclarationModifierComputations(const MemberInformation* member, std::vector<int> modifierIndices); + DeclarationModifierComputations(const MemberInformation *member, std::vector<int> modifierIndices); public: - explicit DeclarationModifierComputations(const MemberInformation* member); + explicit DeclarationModifierComputations(const MemberInformation *member); - _NODISCARD DeclarationModifier* GetDeclarationModifier() const; - _NODISCARD DeclarationModifier* GetNextDeclarationModifier() const; - _NODISCARD std::vector<DeclarationModifier*> GetFollowingDeclarationModifiers() const; - _NODISCARD std::vector<int> GetArrayIndices() const; - _NODISCARD bool IsArray() const; - _NODISCARD int GetArraySize() const; - _NODISCARD bool HasDynamicArrayCount() const; - _NODISCARD const IEvaluation* GetDynamicArrayCountEvaluation() const; - _NODISCARD std::vector<DeclarationModifierComputations> GetArrayEntries() const; - _NODISCARD bool IsSinglePointer() const; - _NODISCARD bool IsArrayPointer() const; - _NODISCARD const IEvaluation* GetArrayPointerCountEvaluation() const; - _NODISCARD bool IsPointerArray() const; - _NODISCARD const IEvaluation* GetPointerArrayCountEvaluation() const; - _NODISCARD bool IsDynamicArray() const; - _NODISCARD const IEvaluation* GetDynamicArraySizeEvaluation() const; - _NODISCARD unsigned GetAlignment() const; + _NODISCARD DeclarationModifier *GetDeclarationModifier() const; + _NODISCARD DeclarationModifier *GetNextDeclarationModifier() const; + _NODISCARD std::vector<DeclarationModifier *> GetFollowingDeclarationModifiers() const; + _NODISCARD std::vector<int> GetArrayIndices() const; + _NODISCARD bool IsArray() const; + _NODISCARD int GetArraySize() const; + _NODISCARD bool HasDynamicArrayCount() const; + _NODISCARD const IEvaluation *GetDynamicArrayCountEvaluation() const; + _NODISCARD std::vector<DeclarationModifierComputations> GetArrayEntries() const; + _NODISCARD bool IsSinglePointer() const; + _NODISCARD bool IsArrayPointer() const; + _NODISCARD const IEvaluation *GetArrayPointerCountEvaluation() const; + _NODISCARD bool IsPointerArray() const; + _NODISCARD const IEvaluation *GetPointerArrayCountEvaluation() const; + _NODISCARD bool IsDynamicArray() const; + _NODISCARD const IEvaluation *GetDynamicArraySizeEvaluation() const; + _NODISCARD unsigned GetAlignment() const; }; diff --git a/src/ZoneCodeGeneratorLib/Domain/Computations/StructureComputations.cpp b/src/ZoneCodeGeneratorLib/Domain/Computations/StructureComputations.cpp index a6badb0ef..f07df7e2b 100644 --- a/src/ZoneCodeGeneratorLib/Domain/Computations/StructureComputations.cpp +++ b/src/ZoneCodeGeneratorLib/Domain/Computations/StructureComputations.cpp @@ -4,48 +4,33 @@ #include "MemberComputations.h" -StructureComputations::StructureComputations(const StructureInformation* structure) - : m_info(structure) -{ - assert(m_info != nullptr); -} +StructureComputations::StructureComputations(const StructureInformation *structure) : m_info(structure) { assert(m_info != nullptr); } -bool StructureComputations::IsAsset() const -{ - return m_info->m_asset_enum_entry != nullptr; -} +bool StructureComputations::IsAsset() const { return m_info->m_asset_enum_entry != nullptr; } -MemberInformation* StructureComputations::GetDynamicMember() const -{ - for (const auto& member : m_info->m_ordered_members) - { - if (MemberComputations(member.get()).IsDynamicMember()) - return member.get(); - } +MemberInformation *StructureComputations::GetDynamicMember() const { + for (const auto &member : m_info->m_ordered_members) { + if (MemberComputations(member.get()).IsDynamicMember()) + return member.get(); + } - return nullptr; + return nullptr; } -std::vector<MemberInformation*> StructureComputations::GetUsedMembers() const -{ - std::vector<MemberInformation*> members; - - if (m_info->m_definition->GetType() == DataDefinitionType::UNION && GetDynamicMember() != nullptr) - { - for (const auto& member : m_info->m_ordered_members) - { - if (!MemberComputations(member.get()).ShouldIgnore()) - members.push_back(member.get()); - } +std::vector<MemberInformation *> StructureComputations::GetUsedMembers() const { + std::vector<MemberInformation *> members; + + if (m_info->m_definition->GetType() == DataDefinitionType::UNION && GetDynamicMember() != nullptr) { + for (const auto &member : m_info->m_ordered_members) { + if (!MemberComputations(member.get()).ShouldIgnore()) + members.push_back(member.get()); } - else - { - for (const auto& member : m_info->m_ordered_members) - { - if (!member->m_is_leaf && !MemberComputations(member.get()).ShouldIgnore()) - members.push_back(member.get()); - } + } else { + for (const auto &member : m_info->m_ordered_members) { + if (!member->m_is_leaf && !MemberComputations(member.get()).ShouldIgnore()) + members.push_back(member.get()); } + } - return members; + return members; } \ No newline at end of file diff --git a/src/ZoneCodeGeneratorLib/Domain/Computations/StructureComputations.h b/src/ZoneCodeGeneratorLib/Domain/Computations/StructureComputations.h index d1bbe7d67..68950f668 100644 --- a/src/ZoneCodeGeneratorLib/Domain/Computations/StructureComputations.h +++ b/src/ZoneCodeGeneratorLib/Domain/Computations/StructureComputations.h @@ -2,14 +2,13 @@ #include "Domain/Information/StructureInformation.h" -class StructureComputations -{ - const StructureInformation* const m_info; +class StructureComputations { + const StructureInformation *const m_info; public: - explicit StructureComputations(const StructureInformation* structure); + explicit StructureComputations(const StructureInformation *structure); - _NODISCARD bool IsAsset() const; - _NODISCARD MemberInformation* GetDynamicMember() const; - _NODISCARD std::vector<MemberInformation*> GetUsedMembers() const; + _NODISCARD bool IsAsset() const; + _NODISCARD MemberInformation *GetDynamicMember() const; + _NODISCARD std::vector<MemberInformation *> GetUsedMembers() const; }; diff --git a/src/ZoneCodeGeneratorLib/Domain/Definition/ArrayDeclarationModifier.cpp b/src/ZoneCodeGeneratorLib/Domain/Definition/ArrayDeclarationModifier.cpp index cfe6e7868..0fb3f3f99 100644 --- a/src/ZoneCodeGeneratorLib/Domain/Definition/ArrayDeclarationModifier.cpp +++ b/src/ZoneCodeGeneratorLib/Domain/Definition/ArrayDeclarationModifier.cpp @@ -1,11 +1,5 @@ #include "ArrayDeclarationModifier.h" -ArrayDeclarationModifier::ArrayDeclarationModifier(const int size) - : m_size(size) -{ -} +ArrayDeclarationModifier::ArrayDeclarationModifier(const int size) : m_size(size) {} -DeclarationModifierType ArrayDeclarationModifier::GetType() const -{ - return DeclarationModifierType::ARRAY; -} +DeclarationModifierType ArrayDeclarationModifier::GetType() const { return DeclarationModifierType::ARRAY; } diff --git a/src/ZoneCodeGeneratorLib/Domain/Definition/ArrayDeclarationModifier.h b/src/ZoneCodeGeneratorLib/Domain/Definition/ArrayDeclarationModifier.h index 713e0c0e4..a9f1d3438 100644 --- a/src/ZoneCodeGeneratorLib/Domain/Definition/ArrayDeclarationModifier.h +++ b/src/ZoneCodeGeneratorLib/Domain/Definition/ArrayDeclarationModifier.h @@ -2,26 +2,25 @@ #include <memory> -#include "Utils/ClassUtils.h" #include "DeclarationModifier.h" #include "Domain/Evaluation/IEvaluation.h" +#include "Utils/ClassUtils.h" -class ArrayDeclarationModifier final : public DeclarationModifier -{ +class ArrayDeclarationModifier final : public DeclarationModifier { public: - int m_size; + int m_size; - /** - * \brief The array size is not actually given by \c m_size but instead is dynamic. - */ - std::unique_ptr<IEvaluation> m_dynamic_size_evaluation; + /** + * \brief The array size is not actually given by \c m_size but instead is dynamic. + */ + std::unique_ptr<IEvaluation> m_dynamic_size_evaluation; - /** - * \brief The array has a size that is given by \c m_size but only a certain dynamic amount is handled by generated count. - */ - std::unique_ptr<IEvaluation> m_dynamic_count_evaluation; + /** + * \brief The array has a size that is given by \c m_size but only a certain dynamic amount is handled by generated count. + */ + std::unique_ptr<IEvaluation> m_dynamic_count_evaluation; - explicit ArrayDeclarationModifier(int size); + explicit ArrayDeclarationModifier(int size); - _NODISCARD DeclarationModifierType GetType() const override; + _NODISCARD DeclarationModifierType GetType() const override; }; diff --git a/src/ZoneCodeGeneratorLib/Domain/Definition/BaseTypeDefinition.cpp b/src/ZoneCodeGeneratorLib/Domain/Definition/BaseTypeDefinition.cpp index 47716c050..31cf79d9b 100644 --- a/src/ZoneCodeGeneratorLib/Domain/Definition/BaseTypeDefinition.cpp +++ b/src/ZoneCodeGeneratorLib/Domain/Definition/BaseTypeDefinition.cpp @@ -2,61 +2,30 @@ #include <type_traits> -BaseTypeDefinition::BaseTypeDefinition(std::string name, const unsigned size) - : DataDefinition("", std::move(name)), - m_size(size) -{ -} +BaseTypeDefinition::BaseTypeDefinition(std::string name, const unsigned size) : DataDefinition("", std::move(name)), m_size(size) {} -DataDefinitionType BaseTypeDefinition::GetType() const -{ - return DataDefinitionType::BASE_TYPE; -} +DataDefinitionType BaseTypeDefinition::GetType() const { return DataDefinitionType::BASE_TYPE; } -unsigned BaseTypeDefinition::GetAlignment() const -{ - return m_size; -} +unsigned BaseTypeDefinition::GetAlignment() const { return m_size; } -bool BaseTypeDefinition::GetForceAlignment() const -{ - return false; -} +bool BaseTypeDefinition::GetForceAlignment() const { return false; } -unsigned BaseTypeDefinition::GetSize() const -{ - return m_size; -} +unsigned BaseTypeDefinition::GetSize() const { return m_size; } -const BaseTypeDefinition* const BaseTypeDefinition::FLOAT = new BaseTypeDefinition("float", 4); -const BaseTypeDefinition* const BaseTypeDefinition::DOUBLE = new BaseTypeDefinition("double", 8); -const BaseTypeDefinition* const BaseTypeDefinition::BOOL = new BaseTypeDefinition("bool", 1); -const BaseTypeDefinition* const BaseTypeDefinition::CHAR = new BaseTypeDefinition("char", 1); -const BaseTypeDefinition* const BaseTypeDefinition::UNSIGNED_CHAR = new BaseTypeDefinition("unsigned char", 1); -const BaseTypeDefinition* const BaseTypeDefinition::SHORT = new BaseTypeDefinition("short", 2); -const BaseTypeDefinition* const BaseTypeDefinition::UNSIGNED_SHORT = new BaseTypeDefinition("unsigned short", 2); -const BaseTypeDefinition* const BaseTypeDefinition::INT = new BaseTypeDefinition("int", 4); -const BaseTypeDefinition* const BaseTypeDefinition::UNSIGNED_INT = new BaseTypeDefinition("unsigned int", 4); -const BaseTypeDefinition* const BaseTypeDefinition::LONG = new BaseTypeDefinition("long", 4); -const BaseTypeDefinition* const BaseTypeDefinition::UNSIGNED_LONG = new BaseTypeDefinition("unsigned long", 4); -const BaseTypeDefinition* const BaseTypeDefinition::LONG_LONG = new BaseTypeDefinition("long long", 8); -const BaseTypeDefinition* const BaseTypeDefinition::UNSIGNED_LONG_LONG = new BaseTypeDefinition("unsigned long long", 8); -const BaseTypeDefinition* const BaseTypeDefinition::VOID = new BaseTypeDefinition("void", 0); -const BaseTypeDefinition* const BaseTypeDefinition::ALL_BASE_TYPES[] -{ - FLOAT, - DOUBLE, - BOOL, - CHAR, - UNSIGNED_CHAR, - SHORT, - UNSIGNED_SHORT, - INT, - UNSIGNED_INT, - LONG, - UNSIGNED_LONG, - LONG_LONG, - UNSIGNED_LONG_LONG, - VOID -}; +const BaseTypeDefinition *const BaseTypeDefinition::FLOAT = new BaseTypeDefinition("float", 4); +const BaseTypeDefinition *const BaseTypeDefinition::DOUBLE = new BaseTypeDefinition("double", 8); +const BaseTypeDefinition *const BaseTypeDefinition::BOOL = new BaseTypeDefinition("bool", 1); +const BaseTypeDefinition *const BaseTypeDefinition::CHAR = new BaseTypeDefinition("char", 1); +const BaseTypeDefinition *const BaseTypeDefinition::UNSIGNED_CHAR = new BaseTypeDefinition("unsigned char", 1); +const BaseTypeDefinition *const BaseTypeDefinition::SHORT = new BaseTypeDefinition("short", 2); +const BaseTypeDefinition *const BaseTypeDefinition::UNSIGNED_SHORT = new BaseTypeDefinition("unsigned short", 2); +const BaseTypeDefinition *const BaseTypeDefinition::INT = new BaseTypeDefinition("int", 4); +const BaseTypeDefinition *const BaseTypeDefinition::UNSIGNED_INT = new BaseTypeDefinition("unsigned int", 4); +const BaseTypeDefinition *const BaseTypeDefinition::LONG = new BaseTypeDefinition("long", 4); +const BaseTypeDefinition *const BaseTypeDefinition::UNSIGNED_LONG = new BaseTypeDefinition("unsigned long", 4); +const BaseTypeDefinition *const BaseTypeDefinition::LONG_LONG = new BaseTypeDefinition("long long", 8); +const BaseTypeDefinition *const BaseTypeDefinition::UNSIGNED_LONG_LONG = new BaseTypeDefinition("unsigned long long", 8); +const BaseTypeDefinition *const BaseTypeDefinition::VOID = new BaseTypeDefinition("void", 0); +const BaseTypeDefinition *const BaseTypeDefinition::ALL_BASE_TYPES[]{ + FLOAT, DOUBLE, BOOL, CHAR, UNSIGNED_CHAR, SHORT, UNSIGNED_SHORT, INT, UNSIGNED_INT, LONG, UNSIGNED_LONG, LONG_LONG, UNSIGNED_LONG_LONG, VOID}; const size_t BaseTypeDefinition::ALL_BASE_TYPES_COUNT = std::extent<decltype(ALL_BASE_TYPES)>::value; \ No newline at end of file diff --git a/src/ZoneCodeGeneratorLib/Domain/Definition/BaseTypeDefinition.h b/src/ZoneCodeGeneratorLib/Domain/Definition/BaseTypeDefinition.h index 7a10733f1..4d90b2de2 100644 --- a/src/ZoneCodeGeneratorLib/Domain/Definition/BaseTypeDefinition.h +++ b/src/ZoneCodeGeneratorLib/Domain/Definition/BaseTypeDefinition.h @@ -1,35 +1,34 @@ #pragma once #include "DataDefinition.h" -class BaseTypeDefinition final : public DataDefinition -{ +class BaseTypeDefinition final : public DataDefinition { public: - const unsigned m_size; + const unsigned m_size; private: - BaseTypeDefinition(std::string name, unsigned size); + BaseTypeDefinition(std::string name, unsigned size); public: - _NODISCARD DataDefinitionType GetType() const override; - _NODISCARD unsigned GetAlignment() const override; - _NODISCARD bool GetForceAlignment() const override; - _NODISCARD unsigned GetSize() const override; + _NODISCARD DataDefinitionType GetType() const override; + _NODISCARD unsigned GetAlignment() const override; + _NODISCARD bool GetForceAlignment() const override; + _NODISCARD unsigned GetSize() const override; - static const BaseTypeDefinition* const FLOAT; - static const BaseTypeDefinition* const DOUBLE; - static const BaseTypeDefinition* const BOOL; - static const BaseTypeDefinition* const CHAR; - static const BaseTypeDefinition* const UNSIGNED_CHAR; - static const BaseTypeDefinition* const SHORT; - static const BaseTypeDefinition* const UNSIGNED_SHORT; - static const BaseTypeDefinition* const INT; - static const BaseTypeDefinition* const UNSIGNED_INT; - static const BaseTypeDefinition* const LONG; - static const BaseTypeDefinition* const UNSIGNED_LONG; - static const BaseTypeDefinition* const LONG_LONG; - static const BaseTypeDefinition* const UNSIGNED_LONG_LONG; - static const BaseTypeDefinition* const VOID; + static const BaseTypeDefinition *const FLOAT; + static const BaseTypeDefinition *const DOUBLE; + static const BaseTypeDefinition *const BOOL; + static const BaseTypeDefinition *const CHAR; + static const BaseTypeDefinition *const UNSIGNED_CHAR; + static const BaseTypeDefinition *const SHORT; + static const BaseTypeDefinition *const UNSIGNED_SHORT; + static const BaseTypeDefinition *const INT; + static const BaseTypeDefinition *const UNSIGNED_INT; + static const BaseTypeDefinition *const LONG; + static const BaseTypeDefinition *const UNSIGNED_LONG; + static const BaseTypeDefinition *const LONG_LONG; + static const BaseTypeDefinition *const UNSIGNED_LONG_LONG; + static const BaseTypeDefinition *const VOID; - static const BaseTypeDefinition* const ALL_BASE_TYPES[]; - static const size_t ALL_BASE_TYPES_COUNT; + static const BaseTypeDefinition *const ALL_BASE_TYPES[]; + static const size_t ALL_BASE_TYPES_COUNT; }; diff --git a/src/ZoneCodeGeneratorLib/Domain/Definition/DataDefinition.cpp b/src/ZoneCodeGeneratorLib/Domain/Definition/DataDefinition.cpp index ac097f336..596431ad3 100644 --- a/src/ZoneCodeGeneratorLib/Domain/Definition/DataDefinition.cpp +++ b/src/ZoneCodeGeneratorLib/Domain/Definition/DataDefinition.cpp @@ -1,19 +1,12 @@ #include "DataDefinition.h" - #include <cassert> #include <sstream> #include "Utils/NamespaceBuilder.h" -DataDefinition::DataDefinition(std::string _namespace, std::string name) - : m_namespace(std::move(_namespace)), - m_name(std::move(name)) -{ - assert(!m_name.empty()); +DataDefinition::DataDefinition(std::string _namespace, std::string name) : m_namespace(std::move(_namespace)), m_name(std::move(name)) { + assert(!m_name.empty()); } -std::string DataDefinition::GetFullName() const -{ - return NamespaceBuilder::Combine(m_namespace, m_name); -} +std::string DataDefinition::GetFullName() const { return NamespaceBuilder::Combine(m_namespace, m_name); } diff --git a/src/ZoneCodeGeneratorLib/Domain/Definition/DataDefinition.h b/src/ZoneCodeGeneratorLib/Domain/Definition/DataDefinition.h index c3e0ba903..a856f0bc9 100644 --- a/src/ZoneCodeGeneratorLib/Domain/Definition/DataDefinition.h +++ b/src/ZoneCodeGeneratorLib/Domain/Definition/DataDefinition.h @@ -3,35 +3,26 @@ #include "Utils/ClassUtils.h" -enum class DataDefinitionType -{ - STRUCT, - UNION, - ENUM, - TYPEDEF, - BASE_TYPE, - FORWARD_DECLARATION -}; +enum class DataDefinitionType { STRUCT, UNION, ENUM, TYPEDEF, BASE_TYPE, FORWARD_DECLARATION }; -class DataDefinition -{ +class DataDefinition { public: - DataDefinition() = default; - DataDefinition(std::string _namespace, std::string name); + DataDefinition() = default; + DataDefinition(std::string _namespace, std::string name); + + virtual ~DataDefinition() = default; + DataDefinition(const DataDefinition &other) = default; + DataDefinition(DataDefinition &&other) noexcept = default; + DataDefinition &operator=(const DataDefinition &other) = default; + DataDefinition &operator=(DataDefinition &&other) noexcept = default; - virtual ~DataDefinition() = default; - DataDefinition(const DataDefinition& other) = default; - DataDefinition(DataDefinition&& other) noexcept = default; - DataDefinition& operator=(const DataDefinition& other) = default; - DataDefinition& operator=(DataDefinition&& other) noexcept = default; + std::string m_namespace; + std::string m_name; - std::string m_namespace; - std::string m_name; - - _NODISCARD virtual DataDefinitionType GetType() const = 0; - _NODISCARD virtual unsigned GetAlignment() const = 0; - _NODISCARD virtual bool GetForceAlignment() const = 0; - _NODISCARD virtual unsigned GetSize() const = 0; + _NODISCARD virtual DataDefinitionType GetType() const = 0; + _NODISCARD virtual unsigned GetAlignment() const = 0; + _NODISCARD virtual bool GetForceAlignment() const = 0; + _NODISCARD virtual unsigned GetSize() const = 0; - _NODISCARD std::string GetFullName() const; + _NODISCARD std::string GetFullName() const; }; diff --git a/src/ZoneCodeGeneratorLib/Domain/Definition/DeclarationModifier.h b/src/ZoneCodeGeneratorLib/Domain/Definition/DeclarationModifier.h index f34dda33a..6ececd365 100644 --- a/src/ZoneCodeGeneratorLib/Domain/Definition/DeclarationModifier.h +++ b/src/ZoneCodeGeneratorLib/Domain/Definition/DeclarationModifier.h @@ -2,21 +2,16 @@ #include "Utils/ClassUtils.h" -enum class DeclarationModifierType -{ - POINTER, - ARRAY -}; +enum class DeclarationModifierType { POINTER, ARRAY }; -class DeclarationModifier -{ +class DeclarationModifier { public: - DeclarationModifier() = default; - virtual ~DeclarationModifier() = default; - DeclarationModifier(const DeclarationModifier& other) = default; - DeclarationModifier(DeclarationModifier&& other) noexcept = default; - DeclarationModifier& operator=(const DeclarationModifier& other) = default; - DeclarationModifier& operator=(DeclarationModifier&& other) noexcept = default; + DeclarationModifier() = default; + virtual ~DeclarationModifier() = default; + DeclarationModifier(const DeclarationModifier &other) = default; + DeclarationModifier(DeclarationModifier &&other) noexcept = default; + DeclarationModifier &operator=(const DeclarationModifier &other) = default; + DeclarationModifier &operator=(DeclarationModifier &&other) noexcept = default; - _NODISCARD virtual DeclarationModifierType GetType() const = 0; + _NODISCARD virtual DeclarationModifierType GetType() const = 0; }; \ No newline at end of file diff --git a/src/ZoneCodeGeneratorLib/Domain/Definition/DefinitionWithMembers.cpp b/src/ZoneCodeGeneratorLib/Domain/Definition/DefinitionWithMembers.cpp index dade3c986..2b7569105 100644 --- a/src/ZoneCodeGeneratorLib/Domain/Definition/DefinitionWithMembers.cpp +++ b/src/ZoneCodeGeneratorLib/Domain/Definition/DefinitionWithMembers.cpp @@ -3,54 +3,43 @@ #include <cassert> DefinitionWithMembers::DefinitionWithMembers(std::string _namespace, std::string name, const unsigned pack) - : DataDefinition(std::move(_namespace), std::move(name)), - m_flags(0), - m_size(0), - m_alignment(0), - m_has_alignment_override(false), - m_anonymous(false), - m_pack(pack), - m_alignment_override(0) -{ -} + : DataDefinition(std::move(_namespace), std::move(name)), m_flags(0), m_size(0), m_alignment(0), m_has_alignment_override(false), m_anonymous(false), + m_pack(pack), m_alignment_override(0) {} -//void DefinitionWithMembers::CalculateAlignment() +// void DefinitionWithMembers::CalculateAlignment() //{ -// if (m_has_alignment_override) -// { -// m_flags |= FLAG_ALIGNMENT_FORCED; -// m_alignment = m_alignment_override; -// } -// else -// { -// m_alignment = 0; -// for (const auto& member : m_members) -// { -// const auto memberAlignment = member->GetAlignment(); -// if (memberAlignment > m_alignment) -// m_alignment = memberAlignment; -// } -// } -// m_flags |= FLAG_ALIGNMENT_CALCULATED; -//} - -unsigned DefinitionWithMembers::GetAlignment() const -{ - assert(m_flags & FLAG_FIELDS_CALCULATED); - - return m_alignment; +// if (m_has_alignment_override) +// { +// m_flags |= FLAG_ALIGNMENT_FORCED; +// m_alignment = m_alignment_override; +// } +// else +// { +// m_alignment = 0; +// for (const auto& member : m_members) +// { +// const auto memberAlignment = member->GetAlignment(); +// if (memberAlignment > m_alignment) +// m_alignment = memberAlignment; +// } +// } +// m_flags |= FLAG_ALIGNMENT_CALCULATED; +// } + +unsigned DefinitionWithMembers::GetAlignment() const { + assert(m_flags & FLAG_FIELDS_CALCULATED); + + return m_alignment; } -bool DefinitionWithMembers::GetForceAlignment() const -{ - assert(m_flags & FLAG_FIELDS_CALCULATED); +bool DefinitionWithMembers::GetForceAlignment() const { + assert(m_flags & FLAG_FIELDS_CALCULATED); - return m_flags & FLAG_ALIGNMENT_FORCED; + return m_flags & FLAG_ALIGNMENT_FORCED; } -unsigned DefinitionWithMembers::GetSize() const -{ - assert(m_flags & FLAG_FIELDS_CALCULATED); +unsigned DefinitionWithMembers::GetSize() const { + assert(m_flags & FLAG_FIELDS_CALCULATED); - return m_size; + return m_size; } diff --git a/src/ZoneCodeGeneratorLib/Domain/Definition/DefinitionWithMembers.h b/src/ZoneCodeGeneratorLib/Domain/Definition/DefinitionWithMembers.h index 658a25a74..6a041f229 100644 --- a/src/ZoneCodeGeneratorLib/Domain/Definition/DefinitionWithMembers.h +++ b/src/ZoneCodeGeneratorLib/Domain/Definition/DefinitionWithMembers.h @@ -6,28 +6,27 @@ #include "DataDefinition.h" #include "Variable.h" -class DefinitionWithMembers : public DataDefinition -{ +class DefinitionWithMembers : public DataDefinition { public: - static constexpr int FLAG_FIELDS_CALCULATED = 1 << 0; - static constexpr int FLAG_FIELDS_CALCULATING = 1 << 1; - static constexpr int FLAG_ALIGNMENT_FORCED = 1 << 2; + static constexpr int FLAG_FIELDS_CALCULATED = 1 << 0; + static constexpr int FLAG_FIELDS_CALCULATING = 1 << 1; + static constexpr int FLAG_ALIGNMENT_FORCED = 1 << 2; - unsigned m_flags; - unsigned m_size; - unsigned m_alignment; + unsigned m_flags; + unsigned m_size; + unsigned m_alignment; - bool m_has_alignment_override; - bool m_anonymous; + bool m_has_alignment_override; + bool m_anonymous; - const unsigned m_pack; - unsigned m_alignment_override; + const unsigned m_pack; + unsigned m_alignment_override; - std::vector<std::shared_ptr<Variable>> m_members; + std::vector<std::shared_ptr<Variable>> m_members; - DefinitionWithMembers(std::string _namespace, std::string name, unsigned pack); + DefinitionWithMembers(std::string _namespace, std::string name, unsigned pack); - _NODISCARD unsigned GetAlignment() const override; - _NODISCARD bool GetForceAlignment() const override; - _NODISCARD unsigned GetSize() const override; + _NODISCARD unsigned GetAlignment() const override; + _NODISCARD bool GetForceAlignment() const override; + _NODISCARD unsigned GetSize() const override; }; \ No newline at end of file diff --git a/src/ZoneCodeGeneratorLib/Domain/Definition/EnumDefinition.cpp b/src/ZoneCodeGeneratorLib/Domain/Definition/EnumDefinition.cpp index 283309aa7..038155e3a 100644 --- a/src/ZoneCodeGeneratorLib/Domain/Definition/EnumDefinition.cpp +++ b/src/ZoneCodeGeneratorLib/Domain/Definition/EnumDefinition.cpp @@ -2,34 +2,17 @@ #include <cassert> -EnumDefinition::EnumDefinition(std::string _namespace, std::string name, const BaseTypeDefinition* parentType) - : DataDefinition(std::move(_namespace), std::move(name)), - m_parent_type(parentType) -{ - assert(parentType != nullptr); +EnumDefinition::EnumDefinition(std::string _namespace, std::string name, const BaseTypeDefinition *parentType) + : DataDefinition(std::move(_namespace), std::move(name)), m_parent_type(parentType) { + assert(parentType != nullptr); } -DataDefinitionType EnumDefinition::GetType() const -{ - return DataDefinitionType::ENUM; -} +DataDefinitionType EnumDefinition::GetType() const { return DataDefinitionType::ENUM; } -unsigned EnumDefinition::GetAlignment() const -{ - return m_parent_type->GetAlignment(); -} +unsigned EnumDefinition::GetAlignment() const { return m_parent_type->GetAlignment(); } -bool EnumDefinition::GetForceAlignment() const -{ - return m_parent_type->GetForceAlignment(); -} +bool EnumDefinition::GetForceAlignment() const { return m_parent_type->GetForceAlignment(); } -unsigned EnumDefinition::GetSize() const -{ - return m_parent_type->GetSize(); -} +unsigned EnumDefinition::GetSize() const { return m_parent_type->GetSize(); } -void EnumDefinition::AddEnumMember(EnumMember enumMember) -{ - m_members.emplace_back(std::make_unique<EnumMember>(std::move(enumMember))); -} +void EnumDefinition::AddEnumMember(EnumMember enumMember) { m_members.emplace_back(std::make_unique<EnumMember>(std::move(enumMember))); } diff --git a/src/ZoneCodeGeneratorLib/Domain/Definition/EnumDefinition.h b/src/ZoneCodeGeneratorLib/Domain/Definition/EnumDefinition.h index f7104a106..36e3bfeb5 100644 --- a/src/ZoneCodeGeneratorLib/Domain/Definition/EnumDefinition.h +++ b/src/ZoneCodeGeneratorLib/Domain/Definition/EnumDefinition.h @@ -7,18 +7,17 @@ #include "DataDefinition.h" #include "EnumMember.h" -class EnumDefinition final : public DataDefinition -{ +class EnumDefinition final : public DataDefinition { public: - const BaseTypeDefinition* m_parent_type; - std::vector<std::unique_ptr<EnumMember>> m_members; + const BaseTypeDefinition *m_parent_type; + std::vector<std::unique_ptr<EnumMember>> m_members; - EnumDefinition(std::string _namespace, std::string name, const BaseTypeDefinition* parentType); + EnumDefinition(std::string _namespace, std::string name, const BaseTypeDefinition *parentType); - _NODISCARD DataDefinitionType GetType() const override; - _NODISCARD unsigned GetAlignment() const override; - _NODISCARD bool GetForceAlignment() const override; - _NODISCARD unsigned GetSize() const override; + _NODISCARD DataDefinitionType GetType() const override; + _NODISCARD unsigned GetAlignment() const override; + _NODISCARD bool GetForceAlignment() const override; + _NODISCARD unsigned GetSize() const override; - void AddEnumMember(EnumMember enumMember); + void AddEnumMember(EnumMember enumMember); }; diff --git a/src/ZoneCodeGeneratorLib/Domain/Definition/EnumMember.cpp b/src/ZoneCodeGeneratorLib/Domain/Definition/EnumMember.cpp index 6c5de70df..0b95c60ce 100644 --- a/src/ZoneCodeGeneratorLib/Domain/Definition/EnumMember.cpp +++ b/src/ZoneCodeGeneratorLib/Domain/Definition/EnumMember.cpp @@ -1,12 +1,5 @@ #include "EnumMember.h" -EnumMember::EnumMember() - : m_value(0) -{ -} +EnumMember::EnumMember() : m_value(0) {} -EnumMember::EnumMember(std::string name, const int value) - : m_name(std::move(name)), - m_value(value) -{ -} +EnumMember::EnumMember(std::string name, const int value) : m_name(std::move(name)), m_value(value) {} diff --git a/src/ZoneCodeGeneratorLib/Domain/Definition/EnumMember.h b/src/ZoneCodeGeneratorLib/Domain/Definition/EnumMember.h index d7336e5ee..b05299a91 100644 --- a/src/ZoneCodeGeneratorLib/Domain/Definition/EnumMember.h +++ b/src/ZoneCodeGeneratorLib/Domain/Definition/EnumMember.h @@ -2,12 +2,11 @@ #include <string> -class EnumMember -{ +class EnumMember { public: - std::string m_name; - int m_value; + std::string m_name; + int m_value; - EnumMember(); - EnumMember(std::string name, int value); + EnumMember(); + EnumMember(std::string name, int value); }; \ No newline at end of file diff --git a/src/ZoneCodeGeneratorLib/Domain/Definition/ForwardDeclaration.cpp b/src/ZoneCodeGeneratorLib/Domain/Definition/ForwardDeclaration.cpp index c5e472a74..d993bafc3 100644 --- a/src/ZoneCodeGeneratorLib/Domain/Definition/ForwardDeclaration.cpp +++ b/src/ZoneCodeGeneratorLib/Domain/Definition/ForwardDeclaration.cpp @@ -1,28 +1,12 @@ #include "ForwardDeclaration.h" ForwardDeclaration::ForwardDeclaration(std::string _namespace, std::string name, DataDefinitionType type) - : DataDefinition(std::move(_namespace), std::move(name)), - m_forwarded_type(type), - m_definition(nullptr) -{ -} + : DataDefinition(std::move(_namespace), std::move(name)), m_forwarded_type(type), m_definition(nullptr) {} -DataDefinitionType ForwardDeclaration::GetType() const -{ - return DataDefinitionType::FORWARD_DECLARATION; -} +DataDefinitionType ForwardDeclaration::GetType() const { return DataDefinitionType::FORWARD_DECLARATION; } -unsigned ForwardDeclaration::GetAlignment() const -{ - return 0; -} +unsigned ForwardDeclaration::GetAlignment() const { return 0; } -bool ForwardDeclaration::GetForceAlignment() const -{ - return false; -} +bool ForwardDeclaration::GetForceAlignment() const { return false; } -unsigned ForwardDeclaration::GetSize() const -{ - return 0; -} +unsigned ForwardDeclaration::GetSize() const { return 0; } diff --git a/src/ZoneCodeGeneratorLib/Domain/Definition/ForwardDeclaration.h b/src/ZoneCodeGeneratorLib/Domain/Definition/ForwardDeclaration.h index 89283ae7b..adeb4e9ba 100644 --- a/src/ZoneCodeGeneratorLib/Domain/Definition/ForwardDeclaration.h +++ b/src/ZoneCodeGeneratorLib/Domain/Definition/ForwardDeclaration.h @@ -2,16 +2,15 @@ #include "DataDefinition.h" -class ForwardDeclaration final : public DataDefinition -{ +class ForwardDeclaration final : public DataDefinition { public: - const DataDefinitionType m_forwarded_type; - const DataDefinition* m_definition; + const DataDefinitionType m_forwarded_type; + const DataDefinition *m_definition; - ForwardDeclaration(std::string _namespace, std::string name, DataDefinitionType type); + ForwardDeclaration(std::string _namespace, std::string name, DataDefinitionType type); - _NODISCARD DataDefinitionType GetType() const override; - _NODISCARD unsigned GetAlignment() const override; - _NODISCARD bool GetForceAlignment() const override; - _NODISCARD unsigned GetSize() const override; + _NODISCARD DataDefinitionType GetType() const override; + _NODISCARD unsigned GetAlignment() const override; + _NODISCARD bool GetForceAlignment() const override; + _NODISCARD unsigned GetSize() const override; }; diff --git a/src/ZoneCodeGeneratorLib/Domain/Definition/PointerDeclarationModifier.cpp b/src/ZoneCodeGeneratorLib/Domain/Definition/PointerDeclarationModifier.cpp index 44f1a1d20..63f5ddc78 100644 --- a/src/ZoneCodeGeneratorLib/Domain/Definition/PointerDeclarationModifier.cpp +++ b/src/ZoneCodeGeneratorLib/Domain/Definition/PointerDeclarationModifier.cpp @@ -2,71 +2,55 @@ #include "Domain/Evaluation/OperandStatic.h" -const IEvaluation* const PointerDeclarationModifier::DEFAULT_COUNT = new OperandStatic(1); +const IEvaluation *const PointerDeclarationModifier::DEFAULT_COUNT = new OperandStatic(1); -DeclarationModifierType PointerDeclarationModifier::GetType() const -{ - return DeclarationModifierType::POINTER; -} +DeclarationModifierType PointerDeclarationModifier::GetType() const { return DeclarationModifierType::POINTER; } -const IEvaluation* PointerDeclarationModifier::GetCountEvaluation() const -{ - if (m_count_evaluation) - return m_count_evaluation.get(); +const IEvaluation *PointerDeclarationModifier::GetCountEvaluation() const { + if (m_count_evaluation) + return m_count_evaluation.get(); - return DEFAULT_COUNT; + return DEFAULT_COUNT; } -const IEvaluation* PointerDeclarationModifier::GetCountEvaluationForArrayIndex(const int index) -{ - if (index >= 0 && m_count_evaluation_by_array_index.size() > static_cast<unsigned>(index)) - { - return m_count_evaluation_by_array_index[index].get(); - } +const IEvaluation *PointerDeclarationModifier::GetCountEvaluationForArrayIndex(const int index) { + if (index >= 0 && m_count_evaluation_by_array_index.size() > static_cast<unsigned>(index)) { + return m_count_evaluation_by_array_index[index].get(); + } - if (m_count_evaluation) - { - return m_count_evaluation.get(); - } + if (m_count_evaluation) { + return m_count_evaluation.get(); + } - return DEFAULT_COUNT; + return DEFAULT_COUNT; } -bool PointerDeclarationModifier::EvaluationIsArray(const IEvaluation* evaluation) -{ - return !evaluation->IsStatic() || evaluation->EvaluateNumeric() > 1; -} +bool PointerDeclarationModifier::EvaluationIsArray(const IEvaluation *evaluation) { return !evaluation->IsStatic() || evaluation->EvaluateNumeric() > 1; } -bool PointerDeclarationModifier::CountEvaluationIsArray() const -{ - if (m_count_evaluation) - { - return EvaluationIsArray(m_count_evaluation.get()); - } +bool PointerDeclarationModifier::CountEvaluationIsArray() const { + if (m_count_evaluation) { + return EvaluationIsArray(m_count_evaluation.get()); + } - return EvaluationIsArray(DEFAULT_COUNT); + return EvaluationIsArray(DEFAULT_COUNT); } -bool PointerDeclarationModifier::CountEvaluationIsArray(const int index) const -{ - if(index >= 0 && m_count_evaluation_by_array_index.size() > static_cast<unsigned>(index)) - { - return EvaluationIsArray(m_count_evaluation_by_array_index[index].get()); - } +bool PointerDeclarationModifier::CountEvaluationIsArray(const int index) const { + if (index >= 0 && m_count_evaluation_by_array_index.size() > static_cast<unsigned>(index)) { + return EvaluationIsArray(m_count_evaluation_by_array_index[index].get()); + } - return CountEvaluationIsArray(); + return CountEvaluationIsArray(); } -bool PointerDeclarationModifier::AnyCountEvaluationIsArray() const -{ - if (m_count_evaluation && EvaluationIsArray(m_count_evaluation.get())) - return true; +bool PointerDeclarationModifier::AnyCountEvaluationIsArray() const { + if (m_count_evaluation && EvaluationIsArray(m_count_evaluation.get())) + return true; - for(const auto& arrayCountEvaluation : m_count_evaluation_by_array_index) - { - if (EvaluationIsArray(arrayCountEvaluation.get())) - return true; - } + for (const auto &arrayCountEvaluation : m_count_evaluation_by_array_index) { + if (EvaluationIsArray(arrayCountEvaluation.get())) + return true; + } - return EvaluationIsArray(DEFAULT_COUNT); + return EvaluationIsArray(DEFAULT_COUNT); } diff --git a/src/ZoneCodeGeneratorLib/Domain/Definition/PointerDeclarationModifier.h b/src/ZoneCodeGeneratorLib/Domain/Definition/PointerDeclarationModifier.h index 06e60fa05..a785b3624 100644 --- a/src/ZoneCodeGeneratorLib/Domain/Definition/PointerDeclarationModifier.h +++ b/src/ZoneCodeGeneratorLib/Domain/Definition/PointerDeclarationModifier.h @@ -6,21 +6,20 @@ #include "DeclarationModifier.h" #include "Domain/Evaluation/IEvaluation.h" -class PointerDeclarationModifier final : public DeclarationModifier -{ - static const IEvaluation* const DEFAULT_COUNT; +class PointerDeclarationModifier final : public DeclarationModifier { + static const IEvaluation *const DEFAULT_COUNT; - static bool EvaluationIsArray(const IEvaluation* evaluation); + static bool EvaluationIsArray(const IEvaluation *evaluation); public: - std::unique_ptr<IEvaluation> m_count_evaluation; - std::vector<std::unique_ptr<IEvaluation>> m_count_evaluation_by_array_index; + std::unique_ptr<IEvaluation> m_count_evaluation; + std::vector<std::unique_ptr<IEvaluation>> m_count_evaluation_by_array_index; - _NODISCARD DeclarationModifierType GetType() const override; - _NODISCARD const IEvaluation* GetCountEvaluation() const; - _NODISCARD const IEvaluation* GetCountEvaluationForArrayIndex(int index); + _NODISCARD DeclarationModifierType GetType() const override; + _NODISCARD const IEvaluation *GetCountEvaluation() const; + _NODISCARD const IEvaluation *GetCountEvaluationForArrayIndex(int index); - _NODISCARD bool CountEvaluationIsArray() const; - _NODISCARD bool CountEvaluationIsArray(int index) const; - _NODISCARD bool AnyCountEvaluationIsArray() const; + _NODISCARD bool CountEvaluationIsArray() const; + _NODISCARD bool CountEvaluationIsArray(int index) const; + _NODISCARD bool AnyCountEvaluationIsArray() const; }; diff --git a/src/ZoneCodeGeneratorLib/Domain/Definition/StructDefinition.cpp b/src/ZoneCodeGeneratorLib/Domain/Definition/StructDefinition.cpp index 51a1557b2..bfa4e82bd 100644 --- a/src/ZoneCodeGeneratorLib/Domain/Definition/StructDefinition.cpp +++ b/src/ZoneCodeGeneratorLib/Domain/Definition/StructDefinition.cpp @@ -1,11 +1,6 @@ #include "StructDefinition.h" StructDefinition::StructDefinition(std::string _namespace, std::string name, const int pack) - : DefinitionWithMembers(std::move(_namespace), std::move(name), pack) -{ -} + : DefinitionWithMembers(std::move(_namespace), std::move(name), pack) {} -DataDefinitionType StructDefinition::GetType() const -{ - return DataDefinitionType::STRUCT; -} +DataDefinitionType StructDefinition::GetType() const { return DataDefinitionType::STRUCT; } diff --git a/src/ZoneCodeGeneratorLib/Domain/Definition/StructDefinition.h b/src/ZoneCodeGeneratorLib/Domain/Definition/StructDefinition.h index 41d89c619..b8ee61a9b 100644 --- a/src/ZoneCodeGeneratorLib/Domain/Definition/StructDefinition.h +++ b/src/ZoneCodeGeneratorLib/Domain/Definition/StructDefinition.h @@ -2,10 +2,9 @@ #include "DefinitionWithMembers.h" -class StructDefinition final : public DefinitionWithMembers -{ +class StructDefinition final : public DefinitionWithMembers { public: - StructDefinition(std::string _namespace, std::string name, int pack); + StructDefinition(std::string _namespace, std::string name, int pack); - _NODISCARD DataDefinitionType GetType() const override; + _NODISCARD DataDefinitionType GetType() const override; }; diff --git a/src/ZoneCodeGeneratorLib/Domain/Definition/TypeDeclaration.cpp b/src/ZoneCodeGeneratorLib/Domain/Definition/TypeDeclaration.cpp index 20243f169..273fd61d4 100644 --- a/src/ZoneCodeGeneratorLib/Domain/Definition/TypeDeclaration.cpp +++ b/src/ZoneCodeGeneratorLib/Domain/Definition/TypeDeclaration.cpp @@ -4,32 +4,22 @@ #include "ArrayDeclarationModifier.h" -TypeDeclaration::TypeDeclaration(const DataDefinition* type) - : m_flags(0), - m_size(0), - m_alignment(0), - m_is_const(false), - m_has_custom_bit_size(false), - m_type(type), - m_custom_bit_size(0) -{ - assert(m_type != nullptr); +TypeDeclaration::TypeDeclaration(const DataDefinition *type) + : m_flags(0), m_size(0), m_alignment(0), m_is_const(false), m_has_custom_bit_size(false), m_type(type), m_custom_bit_size(0) { + assert(m_type != nullptr); } -unsigned TypeDeclaration::GetSize() const -{ - assert(m_flags & FLAG_FIELDS_CALCULATED); - return m_size; +unsigned TypeDeclaration::GetSize() const { + assert(m_flags & FLAG_FIELDS_CALCULATED); + return m_size; } -unsigned TypeDeclaration::GetAlignment() const -{ - assert(m_flags & FLAG_FIELDS_CALCULATED); - return m_alignment; +unsigned TypeDeclaration::GetAlignment() const { + assert(m_flags & FLAG_FIELDS_CALCULATED); + return m_alignment; } -bool TypeDeclaration::GetForceAlignment() const -{ - assert(m_flags & FLAG_FIELDS_CALCULATED); - return m_flags & FLAG_ALIGNMENT_FORCED; +bool TypeDeclaration::GetForceAlignment() const { + assert(m_flags & FLAG_FIELDS_CALCULATED); + return m_flags & FLAG_ALIGNMENT_FORCED; } diff --git a/src/ZoneCodeGeneratorLib/Domain/Definition/TypeDeclaration.h b/src/ZoneCodeGeneratorLib/Domain/Definition/TypeDeclaration.h index 1d2b541f8..0e9192bdc 100644 --- a/src/ZoneCodeGeneratorLib/Domain/Definition/TypeDeclaration.h +++ b/src/ZoneCodeGeneratorLib/Domain/Definition/TypeDeclaration.h @@ -3,31 +3,30 @@ #include <memory> #include <vector> -#include "Utils/ClassUtils.h" #include "DataDefinition.h" #include "DeclarationModifier.h" +#include "Utils/ClassUtils.h" -class TypeDeclaration -{ +class TypeDeclaration { public: - static constexpr int FLAG_FIELDS_CALCULATED = 1 << 0; - static constexpr int FLAG_ALIGNMENT_FORCED = 1 << 1; + static constexpr int FLAG_FIELDS_CALCULATED = 1 << 0; + static constexpr int FLAG_ALIGNMENT_FORCED = 1 << 1; - unsigned m_flags; - unsigned m_size; - unsigned m_alignment; + unsigned m_flags; + unsigned m_size; + unsigned m_alignment; - explicit TypeDeclaration(const DataDefinition* type); + explicit TypeDeclaration(const DataDefinition *type); - bool m_is_const; - bool m_has_custom_bit_size; + bool m_is_const; + bool m_has_custom_bit_size; - const DataDefinition* m_type; - unsigned m_custom_bit_size; + const DataDefinition *m_type; + unsigned m_custom_bit_size; - std::vector<std::unique_ptr<DeclarationModifier>> m_declaration_modifiers; + std::vector<std::unique_ptr<DeclarationModifier>> m_declaration_modifiers; - _NODISCARD unsigned GetSize() const; - _NODISCARD unsigned GetAlignment() const; - _NODISCARD bool GetForceAlignment() const; + _NODISCARD unsigned GetSize() const; + _NODISCARD unsigned GetAlignment() const; + _NODISCARD bool GetForceAlignment() const; }; diff --git a/src/ZoneCodeGeneratorLib/Domain/Definition/TypedefDefinition.cpp b/src/ZoneCodeGeneratorLib/Domain/Definition/TypedefDefinition.cpp index 916082ec1..b7e1a3f7e 100644 --- a/src/ZoneCodeGeneratorLib/Domain/Definition/TypedefDefinition.cpp +++ b/src/ZoneCodeGeneratorLib/Domain/Definition/TypedefDefinition.cpp @@ -1,33 +1,18 @@ #include "TypedefDefinition.h" TypedefDefinition::TypedefDefinition(std::string _namespace, std::string name, std::unique_ptr<TypeDeclaration> typeDeclaration) - : DataDefinition(std::move(_namespace), std::move(name)), - m_has_alignment_override(false), - m_alignment_override(0), - m_type_declaration(std::move(typeDeclaration)) -{ -} + : DataDefinition(std::move(_namespace), std::move(name)), m_has_alignment_override(false), m_alignment_override(0), + m_type_declaration(std::move(typeDeclaration)) {} -DataDefinitionType TypedefDefinition::GetType() const -{ - return DataDefinitionType::TYPEDEF; -} +DataDefinitionType TypedefDefinition::GetType() const { return DataDefinitionType::TYPEDEF; } -unsigned TypedefDefinition::GetAlignment() const -{ - if (m_has_alignment_override) - { - return m_alignment_override; - } - return m_type_declaration->GetAlignment(); +unsigned TypedefDefinition::GetAlignment() const { + if (m_has_alignment_override) { + return m_alignment_override; + } + return m_type_declaration->GetAlignment(); } -bool TypedefDefinition::GetForceAlignment() const -{ - return m_has_alignment_override || m_type_declaration->GetForceAlignment(); -} +bool TypedefDefinition::GetForceAlignment() const { return m_has_alignment_override || m_type_declaration->GetForceAlignment(); } -unsigned TypedefDefinition::GetSize() const -{ - return m_type_declaration->GetSize(); -} +unsigned TypedefDefinition::GetSize() const { return m_type_declaration->GetSize(); } diff --git a/src/ZoneCodeGeneratorLib/Domain/Definition/TypedefDefinition.h b/src/ZoneCodeGeneratorLib/Domain/Definition/TypedefDefinition.h index 036fbd02a..35349c488 100644 --- a/src/ZoneCodeGeneratorLib/Domain/Definition/TypedefDefinition.h +++ b/src/ZoneCodeGeneratorLib/Domain/Definition/TypedefDefinition.h @@ -3,17 +3,16 @@ #include "DataDefinition.h" #include "TypeDeclaration.h" -class TypedefDefinition final : public DataDefinition -{ +class TypedefDefinition final : public DataDefinition { public: - bool m_has_alignment_override; - unsigned m_alignment_override; - std::unique_ptr<TypeDeclaration> m_type_declaration; + bool m_has_alignment_override; + unsigned m_alignment_override; + std::unique_ptr<TypeDeclaration> m_type_declaration; - TypedefDefinition(std::string _namespace, std::string name, std::unique_ptr<TypeDeclaration> typeDeclaration); + TypedefDefinition(std::string _namespace, std::string name, std::unique_ptr<TypeDeclaration> typeDeclaration); - _NODISCARD DataDefinitionType GetType() const override; - _NODISCARD unsigned GetAlignment() const override; - _NODISCARD bool GetForceAlignment() const override; - _NODISCARD unsigned GetSize() const override; + _NODISCARD DataDefinitionType GetType() const override; + _NODISCARD unsigned GetAlignment() const override; + _NODISCARD bool GetForceAlignment() const override; + _NODISCARD unsigned GetSize() const override; }; diff --git a/src/ZoneCodeGeneratorLib/Domain/Definition/UnionDefinition.cpp b/src/ZoneCodeGeneratorLib/Domain/Definition/UnionDefinition.cpp index ce7a10cba..737ef1634 100644 --- a/src/ZoneCodeGeneratorLib/Domain/Definition/UnionDefinition.cpp +++ b/src/ZoneCodeGeneratorLib/Domain/Definition/UnionDefinition.cpp @@ -1,11 +1,6 @@ #include "UnionDefinition.h" UnionDefinition::UnionDefinition(std::string _namespace, std::string name, const int pack) - : DefinitionWithMembers(std::move(_namespace), std::move(name), pack) -{ -} + : DefinitionWithMembers(std::move(_namespace), std::move(name), pack) {} -DataDefinitionType UnionDefinition::GetType() const -{ - return DataDefinitionType::UNION; -} +DataDefinitionType UnionDefinition::GetType() const { return DataDefinitionType::UNION; } diff --git a/src/ZoneCodeGeneratorLib/Domain/Definition/UnionDefinition.h b/src/ZoneCodeGeneratorLib/Domain/Definition/UnionDefinition.h index e841ad79c..2e8766352 100644 --- a/src/ZoneCodeGeneratorLib/Domain/Definition/UnionDefinition.h +++ b/src/ZoneCodeGeneratorLib/Domain/Definition/UnionDefinition.h @@ -2,13 +2,12 @@ #include "DefinitionWithMembers.h" -class UnionDefinition final : public DefinitionWithMembers -{ -//protected: -// void CalculateSize() override; +class UnionDefinition final : public DefinitionWithMembers { + // protected: + // void CalculateSize() override; public: - UnionDefinition(std::string _namespace, std::string name, int pack); + UnionDefinition(std::string _namespace, std::string name, int pack); - _NODISCARD DataDefinitionType GetType() const override; + _NODISCARD DataDefinitionType GetType() const override; }; diff --git a/src/ZoneCodeGeneratorLib/Domain/Definition/Variable.cpp b/src/ZoneCodeGeneratorLib/Domain/Definition/Variable.cpp index 526bba32e..591191364 100644 --- a/src/ZoneCodeGeneratorLib/Domain/Definition/Variable.cpp +++ b/src/ZoneCodeGeneratorLib/Domain/Definition/Variable.cpp @@ -1,23 +1,13 @@ #include "Variable.h" Variable::Variable(std::string name, std::unique_ptr<TypeDeclaration> typeDeclaration) - : m_name(std::move(name)), - m_has_alignment_override(false), - m_alignment_override(0), - m_offset(0), - m_type_declaration(std::move(typeDeclaration)) -{ -} + : m_name(std::move(name)), m_has_alignment_override(false), m_alignment_override(0), m_offset(0), m_type_declaration(std::move(typeDeclaration)) {} -unsigned Variable::GetAlignment() const -{ - if (m_has_alignment_override) - return m_alignment_override; +unsigned Variable::GetAlignment() const { + if (m_has_alignment_override) + return m_alignment_override; - return m_type_declaration->GetAlignment(); + return m_type_declaration->GetAlignment(); } -bool Variable::GetForceAlignment() const -{ - return m_has_alignment_override || m_type_declaration->GetForceAlignment(); -} +bool Variable::GetForceAlignment() const { return m_has_alignment_override || m_type_declaration->GetForceAlignment(); } diff --git a/src/ZoneCodeGeneratorLib/Domain/Definition/Variable.h b/src/ZoneCodeGeneratorLib/Domain/Definition/Variable.h index 77af2df30..3812f91ae 100644 --- a/src/ZoneCodeGeneratorLib/Domain/Definition/Variable.h +++ b/src/ZoneCodeGeneratorLib/Domain/Definition/Variable.h @@ -3,20 +3,19 @@ #include <memory> #include <string> -#include "Utils/ClassUtils.h" #include "TypeDeclaration.h" +#include "Utils/ClassUtils.h" -class Variable -{ +class Variable { public: - std::string m_name; - bool m_has_alignment_override; - unsigned m_alignment_override; - unsigned m_offset; - std::unique_ptr<TypeDeclaration> m_type_declaration; + std::string m_name; + bool m_has_alignment_override; + unsigned m_alignment_override; + unsigned m_offset; + std::unique_ptr<TypeDeclaration> m_type_declaration; - Variable(std::string name, std::unique_ptr<TypeDeclaration> typeDeclaration); + Variable(std::string name, std::unique_ptr<TypeDeclaration> typeDeclaration); - _NODISCARD unsigned GetAlignment() const; - _NODISCARD bool GetForceAlignment() const; + _NODISCARD unsigned GetAlignment() const; + _NODISCARD bool GetForceAlignment() const; }; diff --git a/src/ZoneCodeGeneratorLib/Domain/Environment/Architecture.h b/src/ZoneCodeGeneratorLib/Domain/Environment/Architecture.h index 0748fbfbc..2ca73b8c4 100644 --- a/src/ZoneCodeGeneratorLib/Domain/Environment/Architecture.h +++ b/src/ZoneCodeGeneratorLib/Domain/Environment/Architecture.h @@ -1,8 +1,3 @@ #pragma once -enum class Architecture -{ - UNKNOWN, - X86, - X64 -}; \ No newline at end of file +enum class Architecture { UNKNOWN, X86, X64 }; \ No newline at end of file diff --git a/src/ZoneCodeGeneratorLib/Domain/Evaluation/IEvaluation.h b/src/ZoneCodeGeneratorLib/Domain/Evaluation/IEvaluation.h index 5cd0ceb2d..e5990866a 100644 --- a/src/ZoneCodeGeneratorLib/Domain/Evaluation/IEvaluation.h +++ b/src/ZoneCodeGeneratorLib/Domain/Evaluation/IEvaluation.h @@ -2,25 +2,19 @@ #include "Utils/ClassUtils.h" -enum class EvaluationType -{ - OPERAND_DYNAMIC, - OPERAND_STATIC, - OPERATION -}; +enum class EvaluationType { OPERAND_DYNAMIC, OPERAND_STATIC, OPERATION }; -class IEvaluation -{ +class IEvaluation { public: - IEvaluation() = default; - virtual ~IEvaluation() = default; + IEvaluation() = default; + virtual ~IEvaluation() = default; - IEvaluation(const IEvaluation& other) = default; - IEvaluation(IEvaluation&& other) noexcept = default; - IEvaluation& operator=(const IEvaluation& other) = default; - IEvaluation& operator=(IEvaluation&& other) noexcept = default; + IEvaluation(const IEvaluation &other) = default; + IEvaluation(IEvaluation &&other) noexcept = default; + IEvaluation &operator=(const IEvaluation &other) = default; + IEvaluation &operator=(IEvaluation &&other) noexcept = default; - _NODISCARD virtual EvaluationType GetType() const = 0; - _NODISCARD virtual bool IsStatic() const = 0; - _NODISCARD virtual int EvaluateNumeric() const = 0; + _NODISCARD virtual EvaluationType GetType() const = 0; + _NODISCARD virtual bool IsStatic() const = 0; + _NODISCARD virtual int EvaluateNumeric() const = 0; }; \ No newline at end of file diff --git a/src/ZoneCodeGeneratorLib/Domain/Evaluation/OperandDynamic.cpp b/src/ZoneCodeGeneratorLib/Domain/Evaluation/OperandDynamic.cpp index 0a2817351..8784fee03 100644 --- a/src/ZoneCodeGeneratorLib/Domain/Evaluation/OperandDynamic.cpp +++ b/src/ZoneCodeGeneratorLib/Domain/Evaluation/OperandDynamic.cpp @@ -2,30 +2,17 @@ #include <cassert> -OperandDynamic::OperandDynamic(StructureInformation* structure) - : m_structure(structure) -{ -} +OperandDynamic::OperandDynamic(StructureInformation *structure) : m_structure(structure) {} -OperandDynamic::OperandDynamic(StructureInformation* structure, std::vector<MemberInformation*> referencedMemberChain, std::vector<std::unique_ptr<IEvaluation>> arrayIndices) - : m_structure(structure), - m_referenced_member_chain(std::move(referencedMemberChain)), - m_array_indices(std::move(arrayIndices)) -{ -} +OperandDynamic::OperandDynamic(StructureInformation *structure, std::vector<MemberInformation *> referencedMemberChain, + std::vector<std::unique_ptr<IEvaluation>> arrayIndices) + : m_structure(structure), m_referenced_member_chain(std::move(referencedMemberChain)), m_array_indices(std::move(arrayIndices)) {} -EvaluationType OperandDynamic::GetType() const -{ - return EvaluationType::OPERAND_DYNAMIC; -} +EvaluationType OperandDynamic::GetType() const { return EvaluationType::OPERAND_DYNAMIC; } -bool OperandDynamic::IsStatic() const -{ - return false; -} +bool OperandDynamic::IsStatic() const { return false; } -int OperandDynamic::EvaluateNumeric() const -{ - assert(false); - return 0; +int OperandDynamic::EvaluateNumeric() const { + assert(false); + return 0; } diff --git a/src/ZoneCodeGeneratorLib/Domain/Evaluation/OperandDynamic.h b/src/ZoneCodeGeneratorLib/Domain/Evaluation/OperandDynamic.h index 0ebf3b0db..1f207619c 100644 --- a/src/ZoneCodeGeneratorLib/Domain/Evaluation/OperandDynamic.h +++ b/src/ZoneCodeGeneratorLib/Domain/Evaluation/OperandDynamic.h @@ -2,21 +2,21 @@ #include <memory> #include <vector> -#include "IEvaluation.h" #include "Domain/Information/MemberInformation.h" #include "Domain/Information/StructureInformation.h" +#include "IEvaluation.h" -class OperandDynamic final : public IEvaluation -{ +class OperandDynamic final : public IEvaluation { public: - StructureInformation* const m_structure; - std::vector<MemberInformation*> m_referenced_member_chain; - std::vector<std::unique_ptr<IEvaluation>> m_array_indices; + StructureInformation *const m_structure; + std::vector<MemberInformation *> m_referenced_member_chain; + std::vector<std::unique_ptr<IEvaluation>> m_array_indices; - explicit OperandDynamic(StructureInformation* structure); - OperandDynamic(StructureInformation* structure, std::vector<MemberInformation*> referencedMemberChain, std::vector<std::unique_ptr<IEvaluation>> arrayIndices); + explicit OperandDynamic(StructureInformation *structure); + OperandDynamic(StructureInformation *structure, std::vector<MemberInformation *> referencedMemberChain, + std::vector<std::unique_ptr<IEvaluation>> arrayIndices); - _NODISCARD EvaluationType GetType() const override; - _NODISCARD bool IsStatic() const override; - _NODISCARD int EvaluateNumeric() const override; + _NODISCARD EvaluationType GetType() const override; + _NODISCARD bool IsStatic() const override; + _NODISCARD int EvaluateNumeric() const override; }; diff --git a/src/ZoneCodeGeneratorLib/Domain/Evaluation/OperandStatic.cpp b/src/ZoneCodeGeneratorLib/Domain/Evaluation/OperandStatic.cpp index 7d2de18c4..04ccfa002 100644 --- a/src/ZoneCodeGeneratorLib/Domain/Evaluation/OperandStatic.cpp +++ b/src/ZoneCodeGeneratorLib/Domain/Evaluation/OperandStatic.cpp @@ -1,28 +1,11 @@ #include "OperandStatic.h" -OperandStatic::OperandStatic(const int value) - : m_value(value), - m_enum_member(nullptr) -{ -} +OperandStatic::OperandStatic(const int value) : m_value(value), m_enum_member(nullptr) {} -OperandStatic::OperandStatic(EnumMember* enumMember) - : m_value(enumMember->m_value), - m_enum_member(enumMember) -{ -} +OperandStatic::OperandStatic(EnumMember *enumMember) : m_value(enumMember->m_value), m_enum_member(enumMember) {} -EvaluationType OperandStatic::GetType() const -{ - return EvaluationType::OPERAND_STATIC; -} +EvaluationType OperandStatic::GetType() const { return EvaluationType::OPERAND_STATIC; } -bool OperandStatic::IsStatic() const -{ - return true; -} +bool OperandStatic::IsStatic() const { return true; } -int OperandStatic::EvaluateNumeric() const -{ - return m_value; -} +int OperandStatic::EvaluateNumeric() const { return m_value; } diff --git a/src/ZoneCodeGeneratorLib/Domain/Evaluation/OperandStatic.h b/src/ZoneCodeGeneratorLib/Domain/Evaluation/OperandStatic.h index 7ea1150f9..f8d8253d0 100644 --- a/src/ZoneCodeGeneratorLib/Domain/Evaluation/OperandStatic.h +++ b/src/ZoneCodeGeneratorLib/Domain/Evaluation/OperandStatic.h @@ -1,18 +1,17 @@ #pragma once -#include "IEvaluation.h" #include "Domain/Definition/EnumMember.h" +#include "IEvaluation.h" -class OperandStatic final : public IEvaluation -{ +class OperandStatic final : public IEvaluation { public: - const int m_value; - EnumMember* const m_enum_member; + const int m_value; + EnumMember *const m_enum_member; - explicit OperandStatic(int value); - explicit OperandStatic(EnumMember* enumMember); + explicit OperandStatic(int value); + explicit OperandStatic(EnumMember *enumMember); - _NODISCARD EvaluationType GetType() const override; - _NODISCARD bool IsStatic() const override; - _NODISCARD int EvaluateNumeric() const override; + _NODISCARD EvaluationType GetType() const override; + _NODISCARD bool IsStatic() const override; + _NODISCARD int EvaluateNumeric() const override; }; diff --git a/src/ZoneCodeGeneratorLib/Domain/Evaluation/Operation.cpp b/src/ZoneCodeGeneratorLib/Domain/Evaluation/Operation.cpp index e1cfc07c4..880819a7a 100644 --- a/src/ZoneCodeGeneratorLib/Domain/Evaluation/Operation.cpp +++ b/src/ZoneCodeGeneratorLib/Domain/Evaluation/Operation.cpp @@ -1,40 +1,22 @@ #include "Operation.h" -Operation::Operation(const OperationType* type) - : m_operation_type(type) -{ -} +Operation::Operation(const OperationType *type) : m_operation_type(type) {} -Operation::Operation(const OperationType* type, std::unique_ptr<IEvaluation> operand1, std::unique_ptr<IEvaluation> operand2) - : m_operation_type(type), - m_operand1(std::move(operand1)), - m_operand2(std::move(operand2)) -{ -} +Operation::Operation(const OperationType *type, std::unique_ptr<IEvaluation> operand1, std::unique_ptr<IEvaluation> operand2) + : m_operation_type(type), m_operand1(std::move(operand1)), m_operand2(std::move(operand2)) {} -EvaluationType Operation::GetType() const -{ - return EvaluationType::OPERATION; -} +EvaluationType Operation::GetType() const { return EvaluationType::OPERATION; } -bool Operation::IsStatic() const -{ - return m_operand1->IsStatic() && m_operand2->IsStatic(); -} +bool Operation::IsStatic() const { return m_operand1->IsStatic() && m_operand2->IsStatic(); } -int Operation::EvaluateNumeric() const -{ - return m_operation_type->m_evaluation_function(m_operand1->EvaluateNumeric(), m_operand2->EvaluateNumeric()); -} +int Operation::EvaluateNumeric() const { return m_operation_type->m_evaluation_function(m_operand1->EvaluateNumeric(), m_operand2->EvaluateNumeric()); } -bool Operation::Operand1NeedsParenthesis() const -{ - return m_operand1->GetType() == EvaluationType::OPERATION - && dynamic_cast<Operation*>(m_operand1.get())->m_operation_type->m_precedence > m_operation_type->m_precedence; +bool Operation::Operand1NeedsParenthesis() const { + return m_operand1->GetType() == EvaluationType::OPERATION && + dynamic_cast<Operation *>(m_operand1.get())->m_operation_type->m_precedence > m_operation_type->m_precedence; } -bool Operation::Operand2NeedsParenthesis() const -{ - return m_operand2->GetType() == EvaluationType::OPERATION - && dynamic_cast<Operation*>(m_operand2.get())->m_operation_type->m_precedence >= m_operation_type->m_precedence; +bool Operation::Operand2NeedsParenthesis() const { + return m_operand2->GetType() == EvaluationType::OPERATION && + dynamic_cast<Operation *>(m_operand2.get())->m_operation_type->m_precedence >= m_operation_type->m_precedence; } diff --git a/src/ZoneCodeGeneratorLib/Domain/Evaluation/Operation.h b/src/ZoneCodeGeneratorLib/Domain/Evaluation/Operation.h index 6ff78d2a3..5b1e59bf9 100644 --- a/src/ZoneCodeGeneratorLib/Domain/Evaluation/Operation.h +++ b/src/ZoneCodeGeneratorLib/Domain/Evaluation/Operation.h @@ -2,24 +2,23 @@ #include <memory> -#include "Utils/ClassUtils.h" #include "IEvaluation.h" #include "OperationType.h" +#include "Utils/ClassUtils.h" -class Operation final : public IEvaluation -{ +class Operation final : public IEvaluation { public: - const OperationType* const m_operation_type; - std::unique_ptr<IEvaluation> m_operand1; - std::unique_ptr<IEvaluation> m_operand2; + const OperationType *const m_operation_type; + std::unique_ptr<IEvaluation> m_operand1; + std::unique_ptr<IEvaluation> m_operand2; - explicit Operation(const OperationType* type); - Operation(const OperationType* type, std::unique_ptr<IEvaluation> operand1, std::unique_ptr<IEvaluation> operand2); + explicit Operation(const OperationType *type); + Operation(const OperationType *type, std::unique_ptr<IEvaluation> operand1, std::unique_ptr<IEvaluation> operand2); - _NODISCARD EvaluationType GetType() const override; - _NODISCARD bool IsStatic() const override; - _NODISCARD int EvaluateNumeric() const override; + _NODISCARD EvaluationType GetType() const override; + _NODISCARD bool IsStatic() const override; + _NODISCARD int EvaluateNumeric() const override; - _NODISCARD bool Operand1NeedsParenthesis() const; - _NODISCARD bool Operand2NeedsParenthesis() const; + _NODISCARD bool Operand1NeedsParenthesis() const; + _NODISCARD bool Operand2NeedsParenthesis() const; }; diff --git a/src/ZoneCodeGeneratorLib/Domain/Evaluation/OperationType.cpp b/src/ZoneCodeGeneratorLib/Domain/Evaluation/OperationType.cpp index 3615f0d14..814be0d10 100644 --- a/src/ZoneCodeGeneratorLib/Domain/Evaluation/OperationType.cpp +++ b/src/ZoneCodeGeneratorLib/Domain/Evaluation/OperationType.cpp @@ -1,139 +1,63 @@ #include "OperationType.h" OperationType::OperationType(std::string syntax, const OperationPrecedence precedence, std::function<int(int, int)> evaluationFunction) - : m_syntax(std::move(syntax)), - m_precedence(precedence), - m_evaluation_function(std::move(evaluationFunction)) -{ -} - -const OperationType* const OperationType::OPERATION_ADD - = new OperationType("+", OperationPrecedence::ADDITION_SUBTRACTION, [](auto op1, auto op2) - { - return op1 + op2; - }); - -const OperationType* const OperationType::OPERATION_SUBTRACT - = new OperationType("-", OperationPrecedence::ADDITION_SUBTRACTION, [](auto op1, auto op2) - { - return op1 - op2; - }); - -const OperationType* const OperationType::OPERATION_MULTIPLY - = new OperationType("*", OperationPrecedence::MULTIPLICATION_DIVISION_REMAINDER, [](auto op1, auto op2) - { - return op1 * op2; - }); - -const OperationType* const OperationType::OPERATION_DIVIDE - = new OperationType("/", OperationPrecedence::MULTIPLICATION_DIVISION_REMAINDER, [](auto op1, auto op2) - { - return op1 / op2; - }); - -const OperationType* const OperationType::OPERATION_REMAINDER - = new OperationType("%", OperationPrecedence::MULTIPLICATION_DIVISION_REMAINDER, [](auto op1, auto op2) - { - return op1 % op2; - }); - -const OperationType* const OperationType::OPERATION_BITWISE_AND - = new OperationType("&", OperationPrecedence::BITWISE_AND, [](auto op1, auto op2) - { - return op1 & op2; - }); - -const OperationType* const OperationType::OPERATION_BITWISE_XOR - = new OperationType("^", OperationPrecedence::BITWISE_XOR, [](auto op1, auto op2) - { - return op1 ^ op2; - }); - -const OperationType* const OperationType::OPERATION_BITWISE_OR - = new OperationType("|", OperationPrecedence::BITWISE_OR, [](auto op1, auto op2) - { - return op1 | op2; - }); - -const OperationType* const OperationType::OPERATION_SHIFT_LEFT - = new OperationType("<<", OperationPrecedence::BITWISE_SHIFT, [](auto op1, auto op2) - { - return op1 << op2; - }); - -const OperationType* const OperationType::OPERATION_SHIFT_RIGHT - = new OperationType(">>", OperationPrecedence::BITWISE_SHIFT, [](auto op1, auto op2) - { - return op1 >> op2; - }); - -const OperationType* const OperationType::OPERATION_GREATER_THAN - = new OperationType(">", OperationPrecedence::RELATIONAL_GREATER_LESS_THAN, [](auto op1, auto op2) - { - return op1 > op2 ? 1 : 0; - }); - -const OperationType* const OperationType::OPERATION_GREATER_EQUAL_THAN - = new OperationType(">=", OperationPrecedence::RELATIONAL_GREATER_LESS_THAN, [](auto op1, auto op2) - { - return op1 >= op2 ? 1 : 0; - }); - -const OperationType* const OperationType::OPERATION_LESS_THAN - = new OperationType("<", OperationPrecedence::RELATIONAL_GREATER_LESS_THAN, [](auto op1, auto op2) - { - return op1 < op2 ? 1 : 0; - }); - -const OperationType* const OperationType::OPERATION_LESS_EQUAL_THAN - = new OperationType("<=", OperationPrecedence::RELATIONAL_GREATER_LESS_THAN, [](auto op1, auto op2) - { - return op1 <= op2 ? 1 : 0; - }); - -const OperationType* const OperationType::OPERATION_EQUALS - = new OperationType("==", OperationPrecedence::RELATIONAL_EQUALS, [](auto op1, auto op2) - { - return op1 == op2 ? 1 : 0; - }); - -const OperationType* const OperationType::OPERATION_NOT_EQUAL - = new OperationType("!=", OperationPrecedence::RELATIONAL_EQUALS, [](auto op1, auto op2) - { - return op1 != op2 ? 1 : 0; - }); - -const OperationType* const OperationType::OPERATION_AND - = new OperationType("&&", OperationPrecedence::LOGICAL_AND, [](auto op1, auto op2) - { - return op1 > 0 && op2 > 0 ? 1 : 0; - }); - -const OperationType* const OperationType::OPERATION_OR - = new OperationType("||", OperationPrecedence::LOGICAL_OR, [](auto op1, auto op2) - { - return op1 > 0 || op2 > 0 ? 1 : 0; - }); - - -const OperationType* const OperationType::ALL_OPERATION_TYPES[] -{ - OPERATION_ADD, - OPERATION_SUBTRACT, - OPERATION_MULTIPLY, - OPERATION_DIVIDE, - OPERATION_REMAINDER, - OPERATION_BITWISE_AND, - OPERATION_BITWISE_XOR, - OPERATION_BITWISE_OR, - OPERATION_SHIFT_LEFT, - OPERATION_SHIFT_RIGHT, - OPERATION_GREATER_THAN, - OPERATION_GREATER_EQUAL_THAN, - OPERATION_LESS_THAN, - OPERATION_LESS_EQUAL_THAN, - OPERATION_EQUALS, - OPERATION_NOT_EQUAL, - OPERATION_AND, - OPERATION_OR -}; + : m_syntax(std::move(syntax)), m_precedence(precedence), m_evaluation_function(std::move(evaluationFunction)) {} + +const OperationType *const OperationType::OPERATION_ADD = + new OperationType("+", OperationPrecedence::ADDITION_SUBTRACTION, [](auto op1, auto op2) { return op1 + op2; }); + +const OperationType *const OperationType::OPERATION_SUBTRACT = + new OperationType("-", OperationPrecedence::ADDITION_SUBTRACTION, [](auto op1, auto op2) { return op1 - op2; }); + +const OperationType *const OperationType::OPERATION_MULTIPLY = + new OperationType("*", OperationPrecedence::MULTIPLICATION_DIVISION_REMAINDER, [](auto op1, auto op2) { return op1 * op2; }); + +const OperationType *const OperationType::OPERATION_DIVIDE = + new OperationType("/", OperationPrecedence::MULTIPLICATION_DIVISION_REMAINDER, [](auto op1, auto op2) { return op1 / op2; }); + +const OperationType *const OperationType::OPERATION_REMAINDER = + new OperationType("%", OperationPrecedence::MULTIPLICATION_DIVISION_REMAINDER, [](auto op1, auto op2) { return op1 % op2; }); + +const OperationType *const OperationType::OPERATION_BITWISE_AND = + new OperationType("&", OperationPrecedence::BITWISE_AND, [](auto op1, auto op2) { return op1 & op2; }); + +const OperationType *const OperationType::OPERATION_BITWISE_XOR = + new OperationType("^", OperationPrecedence::BITWISE_XOR, [](auto op1, auto op2) { return op1 ^ op2; }); + +const OperationType *const OperationType::OPERATION_BITWISE_OR = + new OperationType("|", OperationPrecedence::BITWISE_OR, [](auto op1, auto op2) { return op1 | op2; }); + +const OperationType *const OperationType::OPERATION_SHIFT_LEFT = + new OperationType("<<", OperationPrecedence::BITWISE_SHIFT, [](auto op1, auto op2) { return op1 << op2; }); + +const OperationType *const OperationType::OPERATION_SHIFT_RIGHT = + new OperationType(">>", OperationPrecedence::BITWISE_SHIFT, [](auto op1, auto op2) { return op1 >> op2; }); + +const OperationType *const OperationType::OPERATION_GREATER_THAN = + new OperationType(">", OperationPrecedence::RELATIONAL_GREATER_LESS_THAN, [](auto op1, auto op2) { return op1 > op2 ? 1 : 0; }); + +const OperationType *const OperationType::OPERATION_GREATER_EQUAL_THAN = + new OperationType(">=", OperationPrecedence::RELATIONAL_GREATER_LESS_THAN, [](auto op1, auto op2) { return op1 >= op2 ? 1 : 0; }); + +const OperationType *const OperationType::OPERATION_LESS_THAN = + new OperationType("<", OperationPrecedence::RELATIONAL_GREATER_LESS_THAN, [](auto op1, auto op2) { return op1 < op2 ? 1 : 0; }); + +const OperationType *const OperationType::OPERATION_LESS_EQUAL_THAN = + new OperationType("<=", OperationPrecedence::RELATIONAL_GREATER_LESS_THAN, [](auto op1, auto op2) { return op1 <= op2 ? 1 : 0; }); + +const OperationType *const OperationType::OPERATION_EQUALS = + new OperationType("==", OperationPrecedence::RELATIONAL_EQUALS, [](auto op1, auto op2) { return op1 == op2 ? 1 : 0; }); + +const OperationType *const OperationType::OPERATION_NOT_EQUAL = + new OperationType("!=", OperationPrecedence::RELATIONAL_EQUALS, [](auto op1, auto op2) { return op1 != op2 ? 1 : 0; }); + +const OperationType *const OperationType::OPERATION_AND = + new OperationType("&&", OperationPrecedence::LOGICAL_AND, [](auto op1, auto op2) { return op1 > 0 && op2 > 0 ? 1 : 0; }); + +const OperationType *const OperationType::OPERATION_OR = + new OperationType("||", OperationPrecedence::LOGICAL_OR, [](auto op1, auto op2) { return op1 > 0 || op2 > 0 ? 1 : 0; }); + +const OperationType *const OperationType::ALL_OPERATION_TYPES[]{ + OPERATION_ADD, OPERATION_SUBTRACT, OPERATION_MULTIPLY, OPERATION_DIVIDE, OPERATION_REMAINDER, OPERATION_BITWISE_AND, + OPERATION_BITWISE_XOR, OPERATION_BITWISE_OR, OPERATION_SHIFT_LEFT, OPERATION_SHIFT_RIGHT, OPERATION_GREATER_THAN, OPERATION_GREATER_EQUAL_THAN, + OPERATION_LESS_THAN, OPERATION_LESS_EQUAL_THAN, OPERATION_EQUALS, OPERATION_NOT_EQUAL, OPERATION_AND, OPERATION_OR}; diff --git a/src/ZoneCodeGeneratorLib/Domain/Evaluation/OperationType.h b/src/ZoneCodeGeneratorLib/Domain/Evaluation/OperationType.h index f33cf3cca..ba12ad94f 100644 --- a/src/ZoneCodeGeneratorLib/Domain/Evaluation/OperationType.h +++ b/src/ZoneCodeGeneratorLib/Domain/Evaluation/OperationType.h @@ -4,49 +4,47 @@ #include <string> // https://en.cppreference.com/w/cpp/language/operator_precedence -enum class OperationPrecedence -{ - MULTIPLICATION_DIVISION_REMAINDER = 1, - ADDITION_SUBTRACTION = 2, - BITWISE_SHIFT = 3, - RELATIONAL_GREATER_LESS_THAN = 4, - RELATIONAL_EQUALS = 5, - BITWISE_AND = 6, - BITWISE_XOR = 7, - BITWISE_OR = 8, - LOGICAL_AND = 9, - LOGICAL_OR = 10 +enum class OperationPrecedence { + MULTIPLICATION_DIVISION_REMAINDER = 1, + ADDITION_SUBTRACTION = 2, + BITWISE_SHIFT = 3, + RELATIONAL_GREATER_LESS_THAN = 4, + RELATIONAL_EQUALS = 5, + BITWISE_AND = 6, + BITWISE_XOR = 7, + BITWISE_OR = 8, + LOGICAL_AND = 9, + LOGICAL_OR = 10 }; -class OperationType -{ +class OperationType { public: - std::string m_syntax; - OperationPrecedence m_precedence; - std::function<int(int operand1, int operand2)> m_evaluation_function; + std::string m_syntax; + OperationPrecedence m_precedence; + std::function<int(int operand1, int operand2)> m_evaluation_function; private: - OperationType(std::string syntax, OperationPrecedence precedence, std::function<int(int, int)> evaluationFunction); + OperationType(std::string syntax, OperationPrecedence precedence, std::function<int(int, int)> evaluationFunction); public: - static const OperationType* const OPERATION_ADD; - static const OperationType* const OPERATION_SUBTRACT; - static const OperationType* const OPERATION_MULTIPLY; - static const OperationType* const OPERATION_DIVIDE; - static const OperationType* const OPERATION_REMAINDER; - static const OperationType* const OPERATION_BITWISE_AND; - static const OperationType* const OPERATION_BITWISE_XOR; - static const OperationType* const OPERATION_BITWISE_OR; - static const OperationType* const OPERATION_SHIFT_LEFT; - static const OperationType* const OPERATION_SHIFT_RIGHT; - static const OperationType* const OPERATION_GREATER_THAN; - static const OperationType* const OPERATION_GREATER_EQUAL_THAN; - static const OperationType* const OPERATION_LESS_THAN; - static const OperationType* const OPERATION_LESS_EQUAL_THAN; - static const OperationType* const OPERATION_EQUALS; - static const OperationType* const OPERATION_NOT_EQUAL; - static const OperationType* const OPERATION_AND; - static const OperationType* const OPERATION_OR; + static const OperationType *const OPERATION_ADD; + static const OperationType *const OPERATION_SUBTRACT; + static const OperationType *const OPERATION_MULTIPLY; + static const OperationType *const OPERATION_DIVIDE; + static const OperationType *const OPERATION_REMAINDER; + static const OperationType *const OPERATION_BITWISE_AND; + static const OperationType *const OPERATION_BITWISE_XOR; + static const OperationType *const OPERATION_BITWISE_OR; + static const OperationType *const OPERATION_SHIFT_LEFT; + static const OperationType *const OPERATION_SHIFT_RIGHT; + static const OperationType *const OPERATION_GREATER_THAN; + static const OperationType *const OPERATION_GREATER_EQUAL_THAN; + static const OperationType *const OPERATION_LESS_THAN; + static const OperationType *const OPERATION_LESS_EQUAL_THAN; + static const OperationType *const OPERATION_EQUALS; + static const OperationType *const OPERATION_NOT_EQUAL; + static const OperationType *const OPERATION_AND; + static const OperationType *const OPERATION_OR; - static const OperationType* const ALL_OPERATION_TYPES[]; + static const OperationType *const ALL_OPERATION_TYPES[]; }; \ No newline at end of file diff --git a/src/ZoneCodeGeneratorLib/Domain/Extension/CustomAction.cpp b/src/ZoneCodeGeneratorLib/Domain/Extension/CustomAction.cpp index a433428b4..370628c64 100644 --- a/src/ZoneCodeGeneratorLib/Domain/Extension/CustomAction.cpp +++ b/src/ZoneCodeGeneratorLib/Domain/Extension/CustomAction.cpp @@ -1,7 +1,4 @@ #include "CustomAction.h" -CustomAction::CustomAction(std::string actionName, std::vector<DataDefinition*> parameterTypes) - : m_action_name(std::move(actionName)), - m_parameter_types(std::move(parameterTypes)) -{ -} +CustomAction::CustomAction(std::string actionName, std::vector<DataDefinition *> parameterTypes) + : m_action_name(std::move(actionName)), m_parameter_types(std::move(parameterTypes)) {} diff --git a/src/ZoneCodeGeneratorLib/Domain/Extension/CustomAction.h b/src/ZoneCodeGeneratorLib/Domain/Extension/CustomAction.h index b5fa5d791..55c8ef775 100644 --- a/src/ZoneCodeGeneratorLib/Domain/Extension/CustomAction.h +++ b/src/ZoneCodeGeneratorLib/Domain/Extension/CustomAction.h @@ -5,11 +5,10 @@ #include "Domain/Definition/DataDefinition.h" -class CustomAction -{ +class CustomAction { public: - std::string m_action_name; - std::vector<DataDefinition*> m_parameter_types; + std::string m_action_name; + std::vector<DataDefinition *> m_parameter_types; - CustomAction(std::string actionName, std::vector<DataDefinition*> parameterTypes); + CustomAction(std::string actionName, std::vector<DataDefinition *> parameterTypes); }; diff --git a/src/ZoneCodeGeneratorLib/Domain/FastFile/FastFileBlock.cpp b/src/ZoneCodeGeneratorLib/Domain/FastFile/FastFileBlock.cpp index fcf411d13..a23106ef8 100644 --- a/src/ZoneCodeGeneratorLib/Domain/FastFile/FastFileBlock.cpp +++ b/src/ZoneCodeGeneratorLib/Domain/FastFile/FastFileBlock.cpp @@ -1,9 +1,4 @@ #include "FastFileBlock.h" FastFileBlock::FastFileBlock(std::string name, const unsigned index, const FastFileBlockType type, const bool isDefault) - : m_name(std::move(name)), - m_index(index), - m_type(type), - m_is_default(isDefault) -{ -} + : m_name(std::move(name)), m_index(index), m_type(type), m_is_default(isDefault) {} diff --git a/src/ZoneCodeGeneratorLib/Domain/FastFile/FastFileBlock.h b/src/ZoneCodeGeneratorLib/Domain/FastFile/FastFileBlock.h index 11a9c6b06..9618c30da 100644 --- a/src/ZoneCodeGeneratorLib/Domain/FastFile/FastFileBlock.h +++ b/src/ZoneCodeGeneratorLib/Domain/FastFile/FastFileBlock.h @@ -2,21 +2,14 @@ #include <string> -enum class FastFileBlockType -{ - TEMP, - RUNTIME, - DELAY, - NORMAL -}; +enum class FastFileBlockType { TEMP, RUNTIME, DELAY, NORMAL }; -class FastFileBlock -{ +class FastFileBlock { public: - std::string m_name; - unsigned m_index; - FastFileBlockType m_type; - bool m_is_default; + std::string m_name; + unsigned m_index; + FastFileBlockType m_type; + bool m_is_default; - FastFileBlock(std::string name, unsigned index, FastFileBlockType type, bool isDefault); + FastFileBlock(std::string name, unsigned index, FastFileBlockType type, bool isDefault); }; \ No newline at end of file diff --git a/src/ZoneCodeGeneratorLib/Domain/Information/MemberInformation.cpp b/src/ZoneCodeGeneratorLib/Domain/Information/MemberInformation.cpp index a19fc05cf..b238e6aee 100644 --- a/src/ZoneCodeGeneratorLib/Domain/Information/MemberInformation.cpp +++ b/src/ZoneCodeGeneratorLib/Domain/Information/MemberInformation.cpp @@ -1,13 +1,5 @@ #include "MemberInformation.h" -MemberInformation::MemberInformation(StructureInformation* parent, StructureInformation* type, Variable* member) - : m_parent(parent), - m_type(type), - m_member(member), - m_is_string(false), - m_is_script_string(false), - m_is_reusable(false), - m_is_leaf(false), - m_fast_file_block(nullptr) -{ -} +MemberInformation::MemberInformation(StructureInformation *parent, StructureInformation *type, Variable *member) + : m_parent(parent), m_type(type), m_member(member), m_is_string(false), m_is_script_string(false), m_is_reusable(false), m_is_leaf(false), + m_fast_file_block(nullptr) {} diff --git a/src/ZoneCodeGeneratorLib/Domain/Information/MemberInformation.h b/src/ZoneCodeGeneratorLib/Domain/Information/MemberInformation.h index 857291ae7..39ba49508 100644 --- a/src/ZoneCodeGeneratorLib/Domain/Information/MemberInformation.h +++ b/src/ZoneCodeGeneratorLib/Domain/Information/MemberInformation.h @@ -2,26 +2,25 @@ #include <memory> -#include "Utils/ClassUtils.h" -#include "StructureInformation.h" #include "Domain/Definition/Variable.h" -#include "Domain/FastFile/FastFileBlock.h" #include "Domain/Evaluation/IEvaluation.h" +#include "Domain/FastFile/FastFileBlock.h" +#include "StructureInformation.h" +#include "Utils/ClassUtils.h" class StructureInformation; -class MemberInformation -{ +class MemberInformation { public: - StructureInformation* m_parent; - StructureInformation* m_type; - Variable* m_member; - bool m_is_string; - bool m_is_script_string; - bool m_is_reusable; - bool m_is_leaf; - std::unique_ptr<IEvaluation> m_condition; - std::unique_ptr<IEvaluation> m_alloc_alignment; - const FastFileBlock* m_fast_file_block; + StructureInformation *m_parent; + StructureInformation *m_type; + Variable *m_member; + bool m_is_string; + bool m_is_script_string; + bool m_is_reusable; + bool m_is_leaf; + std::unique_ptr<IEvaluation> m_condition; + std::unique_ptr<IEvaluation> m_alloc_alignment; + const FastFileBlock *m_fast_file_block; - MemberInformation(StructureInformation* parent, StructureInformation* type, Variable* member); + MemberInformation(StructureInformation *parent, StructureInformation *type, Variable *member); }; diff --git a/src/ZoneCodeGeneratorLib/Domain/Information/StructureInformation.cpp b/src/ZoneCodeGeneratorLib/Domain/Information/StructureInformation.cpp index cda4cba42..bad357b8f 100644 --- a/src/ZoneCodeGeneratorLib/Domain/Information/StructureInformation.cpp +++ b/src/ZoneCodeGeneratorLib/Domain/Information/StructureInformation.cpp @@ -1,16 +1,6 @@ #include "StructureInformation.h" -StructureInformation::StructureInformation(DefinitionWithMembers* definition) - : m_definition(definition), - m_asset_enum_entry(nullptr), - m_is_leaf(false), - m_non_embedded_reference_exists(false), - m_single_pointer_reference_exists(false), - m_array_pointer_reference_exists(false), - m_array_reference_exists(false), - m_reference_from_non_default_normal_block_exists(false), - m_reusable_reference_exists(false), - m_post_load_action(nullptr), - m_block(nullptr) -{ -} +StructureInformation::StructureInformation(DefinitionWithMembers *definition) + : m_definition(definition), m_asset_enum_entry(nullptr), m_is_leaf(false), m_non_embedded_reference_exists(false), m_single_pointer_reference_exists(false), + m_array_pointer_reference_exists(false), m_array_reference_exists(false), m_reference_from_non_default_normal_block_exists(false), + m_reusable_reference_exists(false), m_post_load_action(nullptr), m_block(nullptr) {} diff --git a/src/ZoneCodeGeneratorLib/Domain/Information/StructureInformation.h b/src/ZoneCodeGeneratorLib/Domain/Information/StructureInformation.h index 29c19e988..1fe07aa61 100644 --- a/src/ZoneCodeGeneratorLib/Domain/Information/StructureInformation.h +++ b/src/ZoneCodeGeneratorLib/Domain/Information/StructureInformation.h @@ -1,34 +1,33 @@ #pragma once -#include "Utils/ClassUtils.h" -#include "MemberInformation.h" #include "Domain/Definition/DefinitionWithMembers.h" #include "Domain/Definition/EnumMember.h" #include "Domain/Extension/CustomAction.h" #include "Domain/FastFile/FastFileBlock.h" +#include "MemberInformation.h" +#include "Utils/ClassUtils.h" class MemberInformation; -class StructureInformation -{ +class StructureInformation { public: - DefinitionWithMembers* const m_definition; - EnumMember* m_asset_enum_entry; + DefinitionWithMembers *const m_definition; + EnumMember *m_asset_enum_entry; - std::vector<StructureInformation*> m_usages; - std::vector<std::unique_ptr<MemberInformation>> m_ordered_members; + std::vector<StructureInformation *> m_usages; + std::vector<std::unique_ptr<MemberInformation>> m_ordered_members; - bool m_is_leaf; + bool m_is_leaf; - bool m_non_embedded_reference_exists; - bool m_single_pointer_reference_exists; - bool m_array_pointer_reference_exists; - bool m_array_reference_exists; - bool m_reference_from_non_default_normal_block_exists; - bool m_reusable_reference_exists; + bool m_non_embedded_reference_exists; + bool m_single_pointer_reference_exists; + bool m_array_pointer_reference_exists; + bool m_array_reference_exists; + bool m_reference_from_non_default_normal_block_exists; + bool m_reusable_reference_exists; - std::unique_ptr<CustomAction> m_post_load_action; - const FastFileBlock* m_block; - std::vector<MemberInformation*> m_name_chain; + std::unique_ptr<CustomAction> m_post_load_action; + const FastFileBlock *m_block; + std::vector<MemberInformation *> m_name_chain; - explicit StructureInformation(DefinitionWithMembers* definition); + explicit StructureInformation(DefinitionWithMembers *definition); }; diff --git a/src/ZoneCodeGeneratorLib/Generating/CodeGenerator.cpp b/src/ZoneCodeGeneratorLib/Generating/CodeGenerator.cpp index 41b766f67..b874fe28c 100644 --- a/src/ZoneCodeGeneratorLib/Generating/CodeGenerator.cpp +++ b/src/ZoneCodeGeneratorLib/Generating/CodeGenerator.cpp @@ -11,127 +11,105 @@ namespace fs = std::filesystem; -CodeGenerator::CodeGenerator(const ZoneCodeGeneratorArguments* args) - : m_args(args) -{ - SetupTemplates(); -} +CodeGenerator::CodeGenerator(const ZoneCodeGeneratorArguments *args) : m_args(args) { SetupTemplates(); } -void CodeGenerator::SetupTemplates() -{ - m_template_mapping["zoneload"] = std::make_unique<ZoneLoadTemplate>(); - m_template_mapping["zonewrite"] = std::make_unique<ZoneWriteTemplate>(); - m_template_mapping["assetstructtests"] = std::make_unique<AssetStructTestsTemplate>(); +void CodeGenerator::SetupTemplates() { + m_template_mapping["zoneload"] = std::make_unique<ZoneLoadTemplate>(); + m_template_mapping["zonewrite"] = std::make_unique<ZoneWriteTemplate>(); + m_template_mapping["assetstructtests"] = std::make_unique<AssetStructTestsTemplate>(); } -bool CodeGenerator::GenerateCodeForTemplate(RenderingContext* context, ICodeTemplate* codeTemplate) const -{ - for (const auto& codeFile : codeTemplate->GetFilesToRender(context)) - { - fs::path p(m_args->m_output_directory); - p.append(codeFile.m_file_name); - - auto parentFolder(p); - parentFolder.remove_filename(); - create_directories(parentFolder); - - std::ofstream stream(p, std::fstream::out | std::fstream::binary); - - if (!stream.is_open()) - { - std::cout << "Failed to open file '" << p.string() << "'" << std::endl; - return false; - } - - codeTemplate->RenderFile(stream, codeFile.m_tag, context); +bool CodeGenerator::GenerateCodeForTemplate(RenderingContext *context, ICodeTemplate *codeTemplate) const { + for (const auto &codeFile : codeTemplate->GetFilesToRender(context)) { + fs::path p(m_args->m_output_directory); + p.append(codeFile.m_file_name); - stream.close(); - } + auto parentFolder(p); + parentFolder.remove_filename(); + create_directories(parentFolder); - return true; -} + std::ofstream stream(p, std::fstream::out | std::fstream::binary); -bool CodeGenerator::GetAssetWithName(IDataRepository* repository, const std::string& name, StructureInformation*& asset) -{ - auto* def = repository->GetDataDefinitionByName(name); - if (def == nullptr) - { - std::cout << "Could not find type with name '" << name << "'" << std::endl; - return false; + if (!stream.is_open()) { + std::cout << "Failed to open file '" << p.string() << "'" << std::endl; + return false; } - auto* defWithMembers = dynamic_cast<DefinitionWithMembers*>(def); - auto* info = defWithMembers != nullptr ? repository->GetInformationFor(defWithMembers) : nullptr; - if (info == nullptr) - { - std::cout << "Could not find type with name '" << name << "'" << std::endl; - return false; - } + codeTemplate->RenderFile(stream, codeFile.m_tag, context); - if(!StructureComputations(info).IsAsset()) - { - std::cout << "Type is not an asset '" << name << "'" << std::endl; - return false; - } + stream.close(); + } - return true; + return true; } -bool CodeGenerator::GenerateCode(IDataRepository* repository) -{ - std::vector<StructureInformation*> assets; +bool CodeGenerator::GetAssetWithName(IDataRepository *repository, const std::string &name, StructureInformation *&asset) { + auto *def = repository->GetDataDefinitionByName(name); + if (def == nullptr) { + std::cout << "Could not find type with name '" << name << "'" << std::endl; + return false; + } + + auto *defWithMembers = dynamic_cast<DefinitionWithMembers *>(def); + auto *info = defWithMembers != nullptr ? repository->GetInformationFor(defWithMembers) : nullptr; + if (info == nullptr) { + std::cout << "Could not find type with name '" << name << "'" << std::endl; + return false; + } + + if (!StructureComputations(info).IsAsset()) { + std::cout << "Type is not an asset '" << name << "'" << std::endl; + return false; + } + + return true; +} - for (auto* info : repository->GetAllStructureInformation()) - { - StructureComputations computations(info); - if (computations.IsAsset()) - assets.push_back(info); +bool CodeGenerator::GenerateCode(IDataRepository *repository) { + std::vector<StructureInformation *> assets; + + for (auto *info : repository->GetAllStructureInformation()) { + StructureComputations computations(info); + if (computations.IsAsset()) + assets.push_back(info); + } + + const auto start = std::chrono::steady_clock::now(); + for (const auto &generationTask : m_args->m_generation_tasks) { + auto templateName = generationTask.m_template_name; + for (auto &c : templateName) + c = static_cast<char>(tolower(c)); + + const auto foundTemplate = m_template_mapping.find(templateName); + if (foundTemplate == m_template_mapping.end()) { + std::cout << "Unknown template '" << generationTask.m_template_name << "'." << std::endl; + return false; } - const auto start = std::chrono::steady_clock::now(); - for (const auto& generationTask : m_args->m_generation_tasks) - { - auto templateName = generationTask.m_template_name; - for (auto& c : templateName) - c = static_cast<char>(tolower(c)); - - const auto foundTemplate = m_template_mapping.find(templateName); - if (foundTemplate == m_template_mapping.end()) - { - std::cout << "Unknown template '" << generationTask.m_template_name << "'." << std::endl; - return false; + if (generationTask.m_all_assets) { + for (auto *asset : assets) { + auto context = RenderingContext::BuildContext(repository, asset); + if (!GenerateCodeForTemplate(context.get(), foundTemplate->second.get())) { + std::cout << "Failed to generate code for asset '" << asset->m_definition->GetFullName() << "' with preset '" << foundTemplate->first << "'\n"; + return false; } - if (generationTask.m_all_assets) - { - for (auto* asset : assets) - { - auto context = RenderingContext::BuildContext(repository, asset); - if (!GenerateCodeForTemplate(context.get(), foundTemplate->second.get())) - { - std::cout << "Failed to generate code for asset '" << asset->m_definition->GetFullName() << "' with preset '" << foundTemplate->first << "'\n"; - return false; - } - - std::cout << "Successfully generated code for asset '" << asset->m_definition->GetFullName() << "' with preset '" << foundTemplate->first << "'\n"; - } - } - else - { - StructureInformation* asset; - if (!GetAssetWithName(repository, generationTask.m_asset_name, asset)) - return false; - - auto context = RenderingContext::BuildContext(repository, asset); - if (!GenerateCodeForTemplate(context.get(), foundTemplate->second.get())) - return false; - } - } - const auto end = std::chrono::steady_clock::now(); - if (m_args->m_verbose) - { - std::cout << "Generating code took " << std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count() << "ms" << std::endl; + std::cout << "Successfully generated code for asset '" << asset->m_definition->GetFullName() << "' with preset '" << foundTemplate->first << "'\n"; + } + } else { + StructureInformation *asset; + if (!GetAssetWithName(repository, generationTask.m_asset_name, asset)) + return false; + + auto context = RenderingContext::BuildContext(repository, asset); + if (!GenerateCodeForTemplate(context.get(), foundTemplate->second.get())) + return false; } + } + const auto end = std::chrono::steady_clock::now(); + if (m_args->m_verbose) { + std::cout << "Generating code took " << std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count() << "ms" << std::endl; + } - return true; + return true; } diff --git a/src/ZoneCodeGeneratorLib/Generating/CodeGenerator.h b/src/ZoneCodeGeneratorLib/Generating/CodeGenerator.h index aee800238..b18f65ff2 100644 --- a/src/ZoneCodeGeneratorLib/Generating/CodeGenerator.h +++ b/src/ZoneCodeGeneratorLib/Generating/CodeGenerator.h @@ -5,19 +5,18 @@ #include "ICodeTemplate.h" #include "ZoneCodeGeneratorArguments.h" -class CodeGenerator -{ - const ZoneCodeGeneratorArguments* m_args; +class CodeGenerator { + const ZoneCodeGeneratorArguments *m_args; - std::unordered_map<std::string, std::unique_ptr<ICodeTemplate>> m_template_mapping; + std::unordered_map<std::string, std::unique_ptr<ICodeTemplate>> m_template_mapping; - void SetupTemplates(); + void SetupTemplates(); - bool GenerateCodeForTemplate(RenderingContext* context, ICodeTemplate* codeTemplate) const; - static bool GetAssetWithName(IDataRepository* repository, const std::string& name, StructureInformation*& asset); + bool GenerateCodeForTemplate(RenderingContext *context, ICodeTemplate *codeTemplate) const; + static bool GetAssetWithName(IDataRepository *repository, const std::string &name, StructureInformation *&asset); public: - explicit CodeGenerator(const ZoneCodeGeneratorArguments* args); + explicit CodeGenerator(const ZoneCodeGeneratorArguments *args); - bool GenerateCode(IDataRepository* repository); + bool GenerateCode(IDataRepository *repository); }; diff --git a/src/ZoneCodeGeneratorLib/Generating/ICodeTemplate.h b/src/ZoneCodeGeneratorLib/Generating/ICodeTemplate.h index 153b5c97a..88fdbd850 100644 --- a/src/ZoneCodeGeneratorLib/Generating/ICodeTemplate.h +++ b/src/ZoneCodeGeneratorLib/Generating/ICodeTemplate.h @@ -6,29 +6,23 @@ #include "RenderingContext.h" -class CodeTemplateFile -{ +class CodeTemplateFile { public: - std::string m_file_name; - int m_tag; + std::string m_file_name; + int m_tag; - CodeTemplateFile(std::string fileName, const int tag) - : m_file_name(std::move(fileName)), - m_tag(tag) - { - } + CodeTemplateFile(std::string fileName, const int tag) : m_file_name(std::move(fileName)), m_tag(tag) {} }; -class ICodeTemplate -{ +class ICodeTemplate { public: - ICodeTemplate() = default; - virtual ~ICodeTemplate() = default; - ICodeTemplate(const ICodeTemplate& other) = default; - ICodeTemplate(ICodeTemplate&& other) noexcept = default; - ICodeTemplate& operator=(const ICodeTemplate& other) = default; - ICodeTemplate& operator=(ICodeTemplate&& other) noexcept = default; - - virtual std::vector<CodeTemplateFile> GetFilesToRender(RenderingContext* context) = 0; - virtual void RenderFile(std::ostream& stream, int fileTag, RenderingContext* context) = 0; + ICodeTemplate() = default; + virtual ~ICodeTemplate() = default; + ICodeTemplate(const ICodeTemplate &other) = default; + ICodeTemplate(ICodeTemplate &&other) noexcept = default; + ICodeTemplate &operator=(const ICodeTemplate &other) = default; + ICodeTemplate &operator=(ICodeTemplate &&other) noexcept = default; + + virtual std::vector<CodeTemplateFile> GetFilesToRender(RenderingContext *context) = 0; + virtual void RenderFile(std::ostream &stream, int fileTag, RenderingContext *context) = 0; }; diff --git a/src/ZoneCodeGeneratorLib/Generating/RenderingContext.cpp b/src/ZoneCodeGeneratorLib/Generating/RenderingContext.cpp index 5e40e0a5e..2a42676ef 100644 --- a/src/ZoneCodeGeneratorLib/Generating/RenderingContext.cpp +++ b/src/ZoneCodeGeneratorLib/Generating/RenderingContext.cpp @@ -3,171 +3,136 @@ #include "Domain/Computations/MemberComputations.h" #include "Domain/Computations/StructureComputations.h" -RenderingUsedType::RenderingUsedType(const DataDefinition* type, StructureInformation* info) - : m_members_loaded(false), - m_type(type), - m_info(info), - m_is_context_asset(false), - m_non_runtime_reference_exists(false), - m_non_embedded_reference_exists(false), - m_array_reference_exists(false), - m_pointer_array_reference_exists(false), - m_pointer_array_reference_is_reusable(false) -{ -} - -RenderingContext::RenderingContext(std::string game, std::vector<const FastFileBlock*> fastFileBlocks) - : m_game(std::move(game)), - m_blocks(std::move(fastFileBlocks)), - m_asset(nullptr), - m_has_actions(false), - m_default_normal_block(nullptr), - m_default_temp_block(nullptr) -{ - for (const auto* block : m_blocks) - { - if (block->m_is_default) - { - if (block->m_type == FastFileBlockType::NORMAL && m_default_normal_block == nullptr) - m_default_normal_block = block; - else if (block->m_type == FastFileBlockType::TEMP && m_default_temp_block == nullptr) - m_default_temp_block = block; - } +RenderingUsedType::RenderingUsedType(const DataDefinition *type, StructureInformation *info) + : m_members_loaded(false), m_type(type), m_info(info), m_is_context_asset(false), m_non_runtime_reference_exists(false), + m_non_embedded_reference_exists(false), m_array_reference_exists(false), m_pointer_array_reference_exists(false), + m_pointer_array_reference_is_reusable(false) {} + +RenderingContext::RenderingContext(std::string game, std::vector<const FastFileBlock *> fastFileBlocks) + : m_game(std::move(game)), m_blocks(std::move(fastFileBlocks)), m_asset(nullptr), m_has_actions(false), m_default_normal_block(nullptr), + m_default_temp_block(nullptr) { + for (const auto *block : m_blocks) { + if (block->m_is_default) { + if (block->m_type == FastFileBlockType::NORMAL && m_default_normal_block == nullptr) + m_default_normal_block = block; + else if (block->m_type == FastFileBlockType::TEMP && m_default_temp_block == nullptr) + m_default_temp_block = block; } + } } -RenderingUsedType* RenderingContext::AddUsedType(std::unique_ptr<RenderingUsedType> usedType) -{ - auto* result = usedType.get(); - m_used_types.push_back(usedType.get()); - m_used_types_lookup.emplace(std::make_pair(usedType->m_type, std::move(usedType))); +RenderingUsedType *RenderingContext::AddUsedType(std::unique_ptr<RenderingUsedType> usedType) { + auto *result = usedType.get(); + m_used_types.push_back(usedType.get()); + m_used_types_lookup.emplace(std::make_pair(usedType->m_type, std::move(usedType))); - return result; + return result; } -RenderingUsedType* RenderingContext::GetBaseType(const IDataRepository* repository, MemberComputations* computations, RenderingUsedType* usedType) -{ - if(usedType->m_type->GetType() == DataDefinitionType::TYPEDEF) - { - const auto* typedefDefinition = dynamic_cast<const TypedefDefinition*>(usedType->m_type); - - while(typedefDefinition->m_type_declaration->m_type->GetType() == DataDefinitionType::TYPEDEF) - typedefDefinition = dynamic_cast<const TypedefDefinition*>(typedefDefinition->m_type_declaration->m_type); - - const auto foundUsedType = m_used_types_lookup.find(typedefDefinition->m_type_declaration->m_type); - if(foundUsedType == m_used_types_lookup.end()) - { - const auto* memberDef = dynamic_cast<const DefinitionWithMembers*>(typedefDefinition->m_type_declaration->m_type); - StructureInformation* info = nullptr; - if (memberDef) - info = repository->GetInformationFor(memberDef); - - auto* addedUsedType = AddUsedType(std::make_unique<RenderingUsedType>(typedefDefinition->m_type_declaration->m_type, info)); - ScanUsedTypeIfNeeded(repository, computations, usedType); - return addedUsedType; - } +RenderingUsedType *RenderingContext::GetBaseType(const IDataRepository *repository, MemberComputations *computations, RenderingUsedType *usedType) { + if (usedType->m_type->GetType() == DataDefinitionType::TYPEDEF) { + const auto *typedefDefinition = dynamic_cast<const TypedefDefinition *>(usedType->m_type); + + while (typedefDefinition->m_type_declaration->m_type->GetType() == DataDefinitionType::TYPEDEF) + typedefDefinition = dynamic_cast<const TypedefDefinition *>(typedefDefinition->m_type_declaration->m_type); - return foundUsedType->second.get(); + const auto foundUsedType = m_used_types_lookup.find(typedefDefinition->m_type_declaration->m_type); + if (foundUsedType == m_used_types_lookup.end()) { + const auto *memberDef = dynamic_cast<const DefinitionWithMembers *>(typedefDefinition->m_type_declaration->m_type); + StructureInformation *info = nullptr; + if (memberDef) + info = repository->GetInformationFor(memberDef); + + auto *addedUsedType = AddUsedType(std::make_unique<RenderingUsedType>(typedefDefinition->m_type_declaration->m_type, info)); + ScanUsedTypeIfNeeded(repository, computations, usedType); + return addedUsedType; } - return nullptr; -} + return foundUsedType->second.get(); + } -void RenderingContext::AddMembersToContext(const IDataRepository* repository, StructureInformation* info) -{ - for(const auto& member : info->m_ordered_members) - { - MemberComputations computations(member.get()); + return nullptr; +} - if(computations.ShouldIgnore()) - continue; +void RenderingContext::AddMembersToContext(const IDataRepository *repository, StructureInformation *info) { + for (const auto &member : info->m_ordered_members) { + MemberComputations computations(member.get()); - RenderingUsedType* usedType; - const auto existingUsedType = m_used_types_lookup.find(member->m_member->m_type_declaration->m_type); - if(existingUsedType == m_used_types_lookup.end()) - usedType = AddUsedType(std::make_unique<RenderingUsedType>(member->m_member->m_type_declaration->m_type, member->m_type)); - else - usedType = existingUsedType->second.get(); + if (computations.ShouldIgnore()) + continue; - auto* baseUsedType = GetBaseType(repository, &computations, usedType); + RenderingUsedType *usedType; + const auto existingUsedType = m_used_types_lookup.find(member->m_member->m_type_declaration->m_type); + if (existingUsedType == m_used_types_lookup.end()) + usedType = AddUsedType(std::make_unique<RenderingUsedType>(member->m_member->m_type_declaration->m_type, member->m_type)); + else + usedType = existingUsedType->second.get(); - if(!computations.IsInRuntimeBlock()) - { - usedType->m_non_runtime_reference_exists = true; + auto *baseUsedType = GetBaseType(repository, &computations, usedType); - if (baseUsedType != nullptr) - baseUsedType->m_non_runtime_reference_exists = true; - } + if (!computations.IsInRuntimeBlock()) { + usedType->m_non_runtime_reference_exists = true; - if (computations.ContainsNonEmbeddedReference()) - usedType->m_non_embedded_reference_exists = true; + if (baseUsedType != nullptr) + baseUsedType->m_non_runtime_reference_exists = true; + } - if (computations.ContainsArrayPointerReference() || computations.ContainsArrayReference()) - usedType->m_array_reference_exists = true; + if (computations.ContainsNonEmbeddedReference()) + usedType->m_non_embedded_reference_exists = true; - if(computations.ContainsPointerArrayReference() && !member->m_is_string) - { - usedType->m_pointer_array_reference_exists = true; + if (computations.ContainsArrayPointerReference() || computations.ContainsArrayReference()) + usedType->m_array_reference_exists = true; - if (member->m_is_reusable) - usedType->m_pointer_array_reference_is_reusable = true; - } + if (computations.ContainsPointerArrayReference() && !member->m_is_string) { + usedType->m_pointer_array_reference_exists = true; - ScanUsedTypeIfNeeded(repository, &computations, usedType); + if (member->m_is_reusable) + usedType->m_pointer_array_reference_is_reusable = true; } + + ScanUsedTypeIfNeeded(repository, &computations, usedType); + } } -void RenderingContext::ScanUsedTypeIfNeeded(const IDataRepository* repository, MemberComputations* computations, RenderingUsedType* usedType) -{ - if (usedType->m_info != nullptr && !StructureComputations(usedType->m_info).IsAsset() && !computations->IsInRuntimeBlock() && !usedType->m_members_loaded) - { - usedType->m_members_loaded = true; - AddMembersToContext(repository, usedType->m_info); - } +void RenderingContext::ScanUsedTypeIfNeeded(const IDataRepository *repository, MemberComputations *computations, RenderingUsedType *usedType) { + if (usedType->m_info != nullptr && !StructureComputations(usedType->m_info).IsAsset() && !computations->IsInRuntimeBlock() && !usedType->m_members_loaded) { + usedType->m_members_loaded = true; + AddMembersToContext(repository, usedType->m_info); + } } -void RenderingContext::MakeAsset(const IDataRepository* repository, StructureInformation* asset) -{ - m_asset = asset; - AddUsedType(std::make_unique<RenderingUsedType>(asset->m_definition, asset)); +void RenderingContext::MakeAsset(const IDataRepository *repository, StructureInformation *asset) { + m_asset = asset; + AddUsedType(std::make_unique<RenderingUsedType>(asset->m_definition, asset)); - AddMembersToContext(repository, asset); + AddMembersToContext(repository, asset); } -void RenderingContext::CreateUsedTypeCollections() -{ - for(auto* usedType : m_used_types) - { - if (usedType->m_info != nullptr) - { - StructureComputations computations(usedType->m_info); - - if(usedType->m_info->m_definition == usedType->m_type) - m_used_structures.push_back(usedType); - - if(computations.IsAsset() && usedType->m_info != m_asset) - m_referenced_assets.push_back(usedType); - - if (!m_has_actions) - { - if ((!computations.IsAsset() || usedType->m_is_context_asset) - && usedType->m_non_runtime_reference_exists - && usedType->m_info->m_post_load_action) - { - m_has_actions = true; - } - } - } +void RenderingContext::CreateUsedTypeCollections() { + for (auto *usedType : m_used_types) { + if (usedType->m_info != nullptr) { + StructureComputations computations(usedType->m_info); + + if (usedType->m_info->m_definition == usedType->m_type) + m_used_structures.push_back(usedType); + if (computations.IsAsset() && usedType->m_info != m_asset) + m_referenced_assets.push_back(usedType); + + if (!m_has_actions) { + if ((!computations.IsAsset() || usedType->m_is_context_asset) && usedType->m_non_runtime_reference_exists && usedType->m_info->m_post_load_action) { + m_has_actions = true; + } + } } + } } -std::unique_ptr<RenderingContext> RenderingContext::BuildContext(const IDataRepository* repository, StructureInformation* asset) -{ - auto context = std::make_unique<RenderingContext>(RenderingContext(repository->GetGameName(), repository->GetAllFastFileBlocks())); +std::unique_ptr<RenderingContext> RenderingContext::BuildContext(const IDataRepository *repository, StructureInformation *asset) { + auto context = std::make_unique<RenderingContext>(RenderingContext(repository->GetGameName(), repository->GetAllFastFileBlocks())); - context->MakeAsset(repository, asset); - context->CreateUsedTypeCollections(); + context->MakeAsset(repository, asset); + context->CreateUsedTypeCollections(); - return std::move(context); + return std::move(context); } diff --git a/src/ZoneCodeGeneratorLib/Generating/RenderingContext.h b/src/ZoneCodeGeneratorLib/Generating/RenderingContext.h index cf9edef5f..ddb29295a 100644 --- a/src/ZoneCodeGeneratorLib/Generating/RenderingContext.h +++ b/src/ZoneCodeGeneratorLib/Generating/RenderingContext.h @@ -7,49 +7,47 @@ #include "Domain/Information/StructureInformation.h" #include "Persistence/IDataRepository.h" -class RenderingUsedType -{ +class RenderingUsedType { public: - bool m_members_loaded; - const DataDefinition* m_type; - StructureInformation* m_info; - bool m_is_context_asset; - - bool m_non_runtime_reference_exists; - bool m_non_embedded_reference_exists; - bool m_array_reference_exists; - bool m_pointer_array_reference_exists; - bool m_pointer_array_reference_is_reusable; - - RenderingUsedType(const DataDefinition* type, StructureInformation* info); + bool m_members_loaded; + const DataDefinition *m_type; + StructureInformation *m_info; + bool m_is_context_asset; + + bool m_non_runtime_reference_exists; + bool m_non_embedded_reference_exists; + bool m_array_reference_exists; + bool m_pointer_array_reference_exists; + bool m_pointer_array_reference_is_reusable; + + RenderingUsedType(const DataDefinition *type, StructureInformation *info); }; -class RenderingContext -{ - std::unordered_map<const DataDefinition*, std::unique_ptr<RenderingUsedType>> m_used_types_lookup; +class RenderingContext { + std::unordered_map<const DataDefinition *, std::unique_ptr<RenderingUsedType>> m_used_types_lookup; - RenderingContext(std::string game, std::vector<const FastFileBlock*> fastFileBlocks); + RenderingContext(std::string game, std::vector<const FastFileBlock *> fastFileBlocks); - RenderingUsedType* AddUsedType(std::unique_ptr<RenderingUsedType> usedType); - RenderingUsedType* GetBaseType(const IDataRepository* repository, MemberComputations* computations, RenderingUsedType* usedType); - void AddMembersToContext(const IDataRepository* repository, StructureInformation* info); - void ScanUsedTypeIfNeeded(const IDataRepository* repository, MemberComputations* computations, RenderingUsedType* usedType); - void MakeAsset(const IDataRepository* repository, StructureInformation* asset); - void CreateUsedTypeCollections(); + RenderingUsedType *AddUsedType(std::unique_ptr<RenderingUsedType> usedType); + RenderingUsedType *GetBaseType(const IDataRepository *repository, MemberComputations *computations, RenderingUsedType *usedType); + void AddMembersToContext(const IDataRepository *repository, StructureInformation *info); + void ScanUsedTypeIfNeeded(const IDataRepository *repository, MemberComputations *computations, RenderingUsedType *usedType); + void MakeAsset(const IDataRepository *repository, StructureInformation *asset); + void CreateUsedTypeCollections(); public: - std::string m_game; - std::vector<const FastFileBlock*> m_blocks; + std::string m_game; + std::vector<const FastFileBlock *> m_blocks; - StructureInformation* m_asset; + StructureInformation *m_asset; - std::vector<RenderingUsedType*> m_used_types; - std::vector<RenderingUsedType*> m_used_structures; - std::vector<RenderingUsedType*> m_referenced_assets; - bool m_has_actions; + std::vector<RenderingUsedType *> m_used_types; + std::vector<RenderingUsedType *> m_used_structures; + std::vector<RenderingUsedType *> m_referenced_assets; + bool m_has_actions; - const FastFileBlock* m_default_normal_block; - const FastFileBlock* m_default_temp_block; + const FastFileBlock *m_default_normal_block; + const FastFileBlock *m_default_temp_block; - static std::unique_ptr<RenderingContext> BuildContext(const IDataRepository* repository, StructureInformation* asset); + static std::unique_ptr<RenderingContext> BuildContext(const IDataRepository *repository, StructureInformation *asset); }; diff --git a/src/ZoneCodeGeneratorLib/Generating/Templates/AssetStructTestsTemplate.cpp b/src/ZoneCodeGeneratorLib/Generating/Templates/AssetStructTestsTemplate.cpp index 2a98eef22..2858e0f15 100644 --- a/src/ZoneCodeGeneratorLib/Generating/Templates/AssetStructTestsTemplate.cpp +++ b/src/ZoneCodeGeneratorLib/Generating/Templates/AssetStructTestsTemplate.cpp @@ -6,91 +6,81 @@ #include "Domain/Computations/StructureComputations.h" #include "Internal/BaseTemplate.h" -class AssetStructTestsTemplate::Internal final : BaseTemplate -{ - void TestMethod(StructureInformation* structure) - { - LINE("TEST_CASE(\""<<m_env.m_game<<"::"<<m_env.m_asset->m_definition->GetFullName()<<": Tests for "<<structure->m_definition->GetFullName()<<"\", \"[assetstruct]\")") - LINE("{") - m_intendation++; - - for(const auto& member : structure->m_ordered_members) - { - if(!member->m_member->m_name.empty() && !member->m_member->m_type_declaration->m_has_custom_bit_size) - { - LINE("REQUIRE(offsetof(" << structure->m_definition->GetFullName() << ", " << member->m_member->m_name << ") == " << member->m_member->m_offset << ");") - } - } - - LINE("") - - LINE("REQUIRE("<<structure->m_definition->GetSize()<<"u == sizeof("<<structure->m_definition->GetFullName()<<"));") - LINE("REQUIRE("<<structure->m_definition->GetAlignment()<<"u == alignof("<<structure->m_definition->GetFullName()<<"));") - m_intendation--; - LINE("}") +class AssetStructTestsTemplate::Internal final : BaseTemplate { + void TestMethod(StructureInformation *structure) { + LINE("TEST_CASE(\"" << m_env.m_game << "::" << m_env.m_asset->m_definition->GetFullName() << ": Tests for " << structure->m_definition->GetFullName() + << "\", \"[assetstruct]\")") + LINE("{") + m_intendation++; + + for (const auto &member : structure->m_ordered_members) { + if (!member->m_member->m_name.empty() && !member->m_member->m_type_declaration->m_has_custom_bit_size) { + LINE("REQUIRE(offsetof(" << structure->m_definition->GetFullName() << ", " << member->m_member->m_name << ") == " << member->m_member->m_offset << ");") + } } + LINE("") + + LINE("REQUIRE(" << structure->m_definition->GetSize() << "u == sizeof(" << structure->m_definition->GetFullName() << "));") + LINE("REQUIRE(" << structure->m_definition->GetAlignment() << "u == alignof(" << structure->m_definition->GetFullName() << "));") + m_intendation--; + LINE("}") + } + public: - Internal(std::ostream& stream, RenderingContext* context) - : BaseTemplate(stream, context) - { + Internal(std::ostream &stream, RenderingContext *context) : BaseTemplate(stream, context) {} + + void Source() { + LINE("// ====================================================================") + LINE("// This file has been generated by ZoneCodeGenerator.") + LINE("// Do not modify.") + LINE("// Any changes will be discarded when regenerating.") + LINE("// ====================================================================") + LINE("") + LINE("#include <catch2/catch_test_macros.hpp>") + LINE("#include <catch2/generators/catch_generators.hpp>") + LINE("#include <cstddef>") + LINE("#include \"Game/" << m_env.m_game << "/" << m_env.m_game << ".h\"") + LINE("") + LINE("using namespace " << m_env.m_game << ";") + LINE("") + LINE("namespace game::" << m_env.m_game << "::xassets::asset_" << Lower(m_env.m_asset->m_definition->m_name)) + LINE("{") + m_intendation++; + + TestMethod(m_env.m_asset); + for (auto *structure : m_env.m_used_structures) { + StructureComputations computations(structure->m_info); + if (!structure->m_info->m_definition->m_anonymous && !computations.IsAsset()) + TestMethod(structure->m_info); } - void Source() - { - LINE("// ====================================================================") - LINE("// This file has been generated by ZoneCodeGenerator.") - LINE("// Do not modify.") - LINE("// Any changes will be discarded when regenerating.") - LINE("// ====================================================================") - LINE("") - LINE("#include <catch2/catch_test_macros.hpp>") - LINE("#include <catch2/generators/catch_generators.hpp>") - LINE("#include <cstddef>") - LINE("#include \"Game/" << m_env.m_game << "/" << m_env.m_game << ".h\"") - LINE("") - LINE("using namespace " << m_env.m_game << ";") - LINE("") - LINE("namespace game::"<<m_env.m_game<<"::xassets::asset_"<<Lower(m_env.m_asset->m_definition->m_name)) - LINE("{") - m_intendation++; - - TestMethod(m_env.m_asset); - for (auto* structure : m_env.m_used_structures) - { - StructureComputations computations(structure->m_info); - if (!structure->m_info->m_definition->m_anonymous && !computations.IsAsset()) - TestMethod(structure->m_info); - } - - m_intendation--; - LINE("}") - } + m_intendation--; + LINE("}") + } }; -std::vector<CodeTemplateFile> AssetStructTestsTemplate::GetFilesToRender(RenderingContext* context) -{ - std::vector<CodeTemplateFile> files; +std::vector<CodeTemplateFile> AssetStructTestsTemplate::GetFilesToRender(RenderingContext *context) { + std::vector<CodeTemplateFile> files; - auto assetName = context->m_asset->m_definition->m_name; - for (auto& c : assetName) - c = static_cast<char>(tolower(c)); + auto assetName = context->m_asset->m_definition->m_name; + for (auto &c : assetName) + c = static_cast<char>(tolower(c)); - { - std::ostringstream str; - str << assetName << '/' << assetName << "_struct_test.cpp"; - files.emplace_back(str.str(), TAG_SOURCE); - } + { + std::ostringstream str; + str << assetName << '/' << assetName << "_struct_test.cpp"; + files.emplace_back(str.str(), TAG_SOURCE); + } - return files; + return files; } -void AssetStructTestsTemplate::RenderFile(std::ostream& stream, const int fileTag, RenderingContext* context) -{ - Internal internal(stream, context); +void AssetStructTestsTemplate::RenderFile(std::ostream &stream, const int fileTag, RenderingContext *context) { + Internal internal(stream, context); - if (fileTag == TAG_SOURCE) - internal.Source(); - else - std::cout << "Invalid tag in AssetStructTestsTemplate\n"; + if (fileTag == TAG_SOURCE) + internal.Source(); + else + std::cout << "Invalid tag in AssetStructTestsTemplate\n"; } diff --git a/src/ZoneCodeGeneratorLib/Generating/Templates/AssetStructTestsTemplate.h b/src/ZoneCodeGeneratorLib/Generating/Templates/AssetStructTestsTemplate.h index d5d9ba845..9e518c4ce 100644 --- a/src/ZoneCodeGeneratorLib/Generating/Templates/AssetStructTestsTemplate.h +++ b/src/ZoneCodeGeneratorLib/Generating/Templates/AssetStructTestsTemplate.h @@ -1,13 +1,12 @@ #pragma once #include "Generating/ICodeTemplate.h" -class AssetStructTestsTemplate final : public ICodeTemplate -{ - static constexpr int TAG_SOURCE = 1; +class AssetStructTestsTemplate final : public ICodeTemplate { + static constexpr int TAG_SOURCE = 1; - class Internal; + class Internal; public: - std::vector<CodeTemplateFile> GetFilesToRender(RenderingContext* context) override; - void RenderFile(std::ostream& stream, int fileTag, RenderingContext* context) override; + std::vector<CodeTemplateFile> GetFilesToRender(RenderingContext *context) override; + void RenderFile(std::ostream &stream, int fileTag, RenderingContext *context) override; }; diff --git a/src/ZoneCodeGeneratorLib/Generating/Templates/Internal/BaseTemplate.cpp b/src/ZoneCodeGeneratorLib/Generating/Templates/Internal/BaseTemplate.cpp index 8c5a51f30..32e585597 100644 --- a/src/ZoneCodeGeneratorLib/Generating/Templates/Internal/BaseTemplate.cpp +++ b/src/ZoneCodeGeneratorLib/Generating/Templates/Internal/BaseTemplate.cpp @@ -2,300 +2,245 @@ #include <sstream> - #include "Domain/Computations/MemberComputations.h" #include "Domain/Definition/ArrayDeclarationModifier.h" -BaseTemplate::BaseTemplate(std::ostream& stream, RenderingContext* context) - : m_out(stream), - m_env(*context), - m_intendation(0u) -{ -} +BaseTemplate::BaseTemplate(std::ostream &stream, RenderingContext *context) : m_out(stream), m_env(*context), m_intendation(0u) {} -void BaseTemplate::DoIntendation() const -{ - for (auto i = 0u; i < m_intendation; i++) - m_out << INTENDATION; +void BaseTemplate::DoIntendation() const { + for (auto i = 0u; i < m_intendation; i++) + m_out << INTENDATION; } -std::string BaseTemplate::Upper(std::string str) -{ - for (auto& c : str) - c = static_cast<char>(toupper(c)); +std::string BaseTemplate::Upper(std::string str) { + for (auto &c : str) + c = static_cast<char>(toupper(c)); - return str; + return str; } -std::string BaseTemplate::Lower(std::string str) -{ - for (auto& c : str) - c = static_cast<char>(tolower(c)); +std::string BaseTemplate::Lower(std::string str) { + for (auto &c : str) + c = static_cast<char>(tolower(c)); - return str; + return str; } -void BaseTemplate::MakeSafeTypeNameInternal(const DataDefinition* def, std::ostringstream& str) -{ - for (const auto& c : def->m_name) - { - if (isspace(c)) - str << "_"; - else - str << c; - } +void BaseTemplate::MakeSafeTypeNameInternal(const DataDefinition *def, std::ostringstream &str) { + for (const auto &c : def->m_name) { + if (isspace(c)) + str << "_"; + else + str << c; + } } -void BaseTemplate::MakeTypeVarNameInternal(const DataDefinition* def, std::ostringstream& str) -{ - str << "var"; - MakeSafeTypeNameInternal(def, str); +void BaseTemplate::MakeTypeVarNameInternal(const DataDefinition *def, std::ostringstream &str) { + str << "var"; + MakeSafeTypeNameInternal(def, str); } -void BaseTemplate::MakeTypeWrittenVarNameInternal(const DataDefinition* def, std::ostringstream& str) -{ - str << "var"; - MakeSafeTypeNameInternal(def, str); - str << "Written"; +void BaseTemplate::MakeTypeWrittenVarNameInternal(const DataDefinition *def, std::ostringstream &str) { + str << "var"; + MakeSafeTypeNameInternal(def, str); + str << "Written"; } -void BaseTemplate::MakeTypePtrVarNameInternal(const DataDefinition* def, std::ostringstream& str) -{ - str << "var"; - MakeSafeTypeNameInternal(def, str); - str << "Ptr"; +void BaseTemplate::MakeTypePtrVarNameInternal(const DataDefinition *def, std::ostringstream &str) { + str << "var"; + MakeSafeTypeNameInternal(def, str); + str << "Ptr"; } -void BaseTemplate::MakeTypeWrittenPtrVarNameInternal(const DataDefinition* def, std::ostringstream& str) -{ - str << "var"; - MakeSafeTypeNameInternal(def, str); - str << "PtrWritten"; +void BaseTemplate::MakeTypeWrittenPtrVarNameInternal(const DataDefinition *def, std::ostringstream &str) { + str << "var"; + MakeSafeTypeNameInternal(def, str); + str << "PtrWritten"; } -void BaseTemplate::MakeArrayIndicesInternal(const DeclarationModifierComputations& modifierComputations, std::ostringstream& str) -{ - for (auto index : modifierComputations.GetArrayIndices()) - { - str << "[" << index << "]"; - } +void BaseTemplate::MakeArrayIndicesInternal(const DeclarationModifierComputations &modifierComputations, std::ostringstream &str) { + for (auto index : modifierComputations.GetArrayIndices()) { + str << "[" << index << "]"; + } } -std::string BaseTemplate::MakeTypeVarName(const DataDefinition* def) -{ - std::ostringstream str; - MakeTypeVarNameInternal(def, str); - return str.str(); +std::string BaseTemplate::MakeTypeVarName(const DataDefinition *def) { + std::ostringstream str; + MakeTypeVarNameInternal(def, str); + return str.str(); } - -std::string BaseTemplate::MakeTypeWrittenVarName(const DataDefinition* def) -{ - std::ostringstream str; - MakeTypeWrittenVarNameInternal(def, str); - return str.str(); +std::string BaseTemplate::MakeTypeWrittenVarName(const DataDefinition *def) { + std::ostringstream str; + MakeTypeWrittenVarNameInternal(def, str); + return str.str(); } -std::string BaseTemplate::MakeTypePtrVarName(const DataDefinition* def) -{ - std::ostringstream str; - MakeTypePtrVarNameInternal(def, str); - return str.str(); +std::string BaseTemplate::MakeTypePtrVarName(const DataDefinition *def) { + std::ostringstream str; + MakeTypePtrVarNameInternal(def, str); + return str.str(); } -std::string BaseTemplate::MakeTypeWrittenPtrVarName(const DataDefinition* def) -{ - std::ostringstream str; - MakeTypeWrittenPtrVarNameInternal(def, str); - return str.str(); +std::string BaseTemplate::MakeTypeWrittenPtrVarName(const DataDefinition *def) { + std::ostringstream str; + MakeTypeWrittenPtrVarNameInternal(def, str); + return str.str(); } -std::string BaseTemplate::MakeSafeTypeName(const DataDefinition* def) -{ - std::ostringstream str; - MakeSafeTypeNameInternal(def, str); - return str.str(); +std::string BaseTemplate::MakeSafeTypeName(const DataDefinition *def) { + std::ostringstream str; + MakeSafeTypeNameInternal(def, str); + return str.str(); } -std::string BaseTemplate::MakeMemberAccess(StructureInformation* info, MemberInformation* member, const DeclarationModifierComputations& modifier) -{ - std::ostringstream str; - MakeTypeVarNameInternal(info->m_definition, str); - str << "->" << member->m_member->m_name; - MakeArrayIndicesInternal(modifier, str); +std::string BaseTemplate::MakeMemberAccess(StructureInformation *info, MemberInformation *member, const DeclarationModifierComputations &modifier) { + std::ostringstream str; + MakeTypeVarNameInternal(info->m_definition, str); + str << "->" << member->m_member->m_name; + MakeArrayIndicesInternal(modifier, str); - return str.str(); + return str.str(); } -std::string BaseTemplate::MakeWrittenMemberAccess(StructureInformation* info, MemberInformation* member, const DeclarationModifierComputations& modifier) -{ - std::ostringstream str; - MakeTypeWrittenVarNameInternal(info->m_definition, str); - str << "->" << member->m_member->m_name; - MakeArrayIndicesInternal(modifier, str); +std::string BaseTemplate::MakeWrittenMemberAccess(StructureInformation *info, MemberInformation *member, const DeclarationModifierComputations &modifier) { + std::ostringstream str; + MakeTypeWrittenVarNameInternal(info->m_definition, str); + str << "->" << member->m_member->m_name; + MakeArrayIndicesInternal(modifier, str); - return str.str(); + return str.str(); } -std::string BaseTemplate::MakeMemberAccess(const std::string& variableName, StructureInformation* info, MemberInformation* member, const DeclarationModifierComputations& modifier) -{ - std::ostringstream str; - str << variableName << "->" << member->m_member->m_name; - MakeArrayIndicesInternal(modifier, str); +std::string BaseTemplate::MakeMemberAccess(const std::string &variableName, StructureInformation *info, MemberInformation *member, + const DeclarationModifierComputations &modifier) { + std::ostringstream str; + str << variableName << "->" << member->m_member->m_name; + MakeArrayIndicesInternal(modifier, str); - return str.str(); + return str.str(); } -std::string BaseTemplate::MakeTypeDecl(const TypeDeclaration* decl) -{ - std::ostringstream str; - if (decl->m_is_const) - { - str << "const "; - } +std::string BaseTemplate::MakeTypeDecl(const TypeDeclaration *decl) { + std::ostringstream str; + if (decl->m_is_const) { + str << "const "; + } - str << decl->m_type->GetFullName(); - return str.str(); + str << decl->m_type->GetFullName(); + return str.str(); } -std::string BaseTemplate::MakeFollowingReferences(const std::vector<DeclarationModifier*>& modifiers) -{ - std::ostringstream str; - for (const auto* modifier : modifiers) - { - if (modifier->GetType() == DeclarationModifierType::ARRAY) - { - const auto* array = dynamic_cast<const ArrayDeclarationModifier*>(modifier); - str << "[" << array->m_size << "]"; - } - else - { - str << "*"; - } +std::string BaseTemplate::MakeFollowingReferences(const std::vector<DeclarationModifier *> &modifiers) { + std::ostringstream str; + for (const auto *modifier : modifiers) { + if (modifier->GetType() == DeclarationModifierType::ARRAY) { + const auto *array = dynamic_cast<const ArrayDeclarationModifier *>(modifier); + str << "[" << array->m_size << "]"; + } else { + str << "*"; } + } - return str.str(); + return str.str(); } -std::string BaseTemplate::MakeArrayIndices(const DeclarationModifierComputations& modifierComputations) -{ - std::ostringstream str; - MakeArrayIndicesInternal(modifierComputations, str); - return str.str(); +std::string BaseTemplate::MakeArrayIndices(const DeclarationModifierComputations &modifierComputations) { + std::ostringstream str; + MakeArrayIndicesInternal(modifierComputations, str); + return str.str(); } -std::string BaseTemplate::MakeCustomActionCall(CustomAction* action) -{ - std::ostringstream str; - str << "m_actions." << action->m_action_name << "("; - - auto first = true; - for (auto* def : action->m_parameter_types) - { - if (first) - { - first = false; - } - else - { - str << ", "; - } - - MakeTypeVarNameInternal(def, str); +std::string BaseTemplate::MakeCustomActionCall(CustomAction *action) { + std::ostringstream str; + str << "m_actions." << action->m_action_name << "("; + + auto first = true; + for (auto *def : action->m_parameter_types) { + if (first) { + first = false; + } else { + str << ", "; } - str << ");"; - return str.str(); + MakeTypeVarNameInternal(def, str); + } + + str << ");"; + return str.str(); } -std::string BaseTemplate::MakeArrayCount(const ArrayDeclarationModifier* arrayModifier) -{ - if(arrayModifier->m_dynamic_count_evaluation) - { - return MakeEvaluation(arrayModifier->m_dynamic_count_evaluation.get()); - } +std::string BaseTemplate::MakeArrayCount(const ArrayDeclarationModifier *arrayModifier) { + if (arrayModifier->m_dynamic_count_evaluation) { + return MakeEvaluation(arrayModifier->m_dynamic_count_evaluation.get()); + } - return std::to_string(arrayModifier->m_size); + return std::to_string(arrayModifier->m_size); } -void BaseTemplate::MakeOperandStatic(const OperandStatic* op, std::ostringstream& str) -{ - if (op->m_enum_member != nullptr) - { - str << op->m_enum_member->m_name; - } - else - { - str << op->m_value; - } +void BaseTemplate::MakeOperandStatic(const OperandStatic *op, std::ostringstream &str) { + if (op->m_enum_member != nullptr) { + str << op->m_enum_member->m_name; + } else { + str << op->m_value; + } } -void BaseTemplate::MakeOperandDynamic(const OperandDynamic* op, std::ostringstream& str) -{ - MakeTypeVarNameInternal(op->m_structure->m_definition, str); +void BaseTemplate::MakeOperandDynamic(const OperandDynamic *op, std::ostringstream &str) { + MakeTypeVarNameInternal(op->m_structure->m_definition, str); + + if (!op->m_referenced_member_chain.empty()) { + str << "->"; + const auto lastEntry = op->m_referenced_member_chain.end() - 1; + for (auto i = op->m_referenced_member_chain.begin(); i != lastEntry; ++i) { + MemberComputations computations(*i); + str << (*i)->m_member->m_name; - if(!op->m_referenced_member_chain.empty()) - { + if (computations.ContainsNonEmbeddedReference()) str << "->"; - const auto lastEntry = op->m_referenced_member_chain.end() - 1; - for(auto i = op->m_referenced_member_chain.begin(); i != lastEntry; ++i) - { - MemberComputations computations(*i); - str << (*i)->m_member->m_name; - - if (computations.ContainsNonEmbeddedReference()) - str << "->"; - else - str << "."; - } - - str << (*lastEntry)->m_member->m_name; + else + str << "."; } - for (const auto& arrayIndex : op->m_array_indices) - { - str << "["; - MakeEvaluationInternal(arrayIndex.get(), str); - str << "]"; - } + str << (*lastEntry)->m_member->m_name; + } + + for (const auto &arrayIndex : op->m_array_indices) { + str << "["; + MakeEvaluationInternal(arrayIndex.get(), str); + str << "]"; + } } -void BaseTemplate::MakeOperation(const Operation* operation, std::ostringstream& str) -{ - if (operation->Operand1NeedsParenthesis()) - { - str << "("; - MakeEvaluationInternal(operation->m_operand1.get(), str); - str << ")"; - } - else - MakeEvaluationInternal(operation->m_operand1.get(), str); +void BaseTemplate::MakeOperation(const Operation *operation, std::ostringstream &str) { + if (operation->Operand1NeedsParenthesis()) { + str << "("; + MakeEvaluationInternal(operation->m_operand1.get(), str); + str << ")"; + } else + MakeEvaluationInternal(operation->m_operand1.get(), str); - str << " " << operation->m_operation_type->m_syntax << " "; + str << " " << operation->m_operation_type->m_syntax << " "; - if (operation->Operand2NeedsParenthesis()) - { - str << "("; - MakeEvaluationInternal(operation->m_operand2.get(), str); - str << ")"; - } - else - MakeEvaluationInternal(operation->m_operand2.get(), str); + if (operation->Operand2NeedsParenthesis()) { + str << "("; + MakeEvaluationInternal(operation->m_operand2.get(), str); + str << ")"; + } else + MakeEvaluationInternal(operation->m_operand2.get(), str); } -void BaseTemplate::MakeEvaluationInternal(const IEvaluation* evaluation, std::ostringstream& str) -{ - if (evaluation->GetType() == EvaluationType::OPERATION) - MakeOperation(dynamic_cast<const Operation*>(evaluation), str); - else if (evaluation->GetType() == EvaluationType::OPERAND_STATIC) - MakeOperandStatic(dynamic_cast<const OperandStatic*>(evaluation), str); - else if (evaluation->GetType() == EvaluationType::OPERAND_DYNAMIC) - MakeOperandDynamic(dynamic_cast<const OperandDynamic*>(evaluation), str); +void BaseTemplate::MakeEvaluationInternal(const IEvaluation *evaluation, std::ostringstream &str) { + if (evaluation->GetType() == EvaluationType::OPERATION) + MakeOperation(dynamic_cast<const Operation *>(evaluation), str); + else if (evaluation->GetType() == EvaluationType::OPERAND_STATIC) + MakeOperandStatic(dynamic_cast<const OperandStatic *>(evaluation), str); + else if (evaluation->GetType() == EvaluationType::OPERAND_DYNAMIC) + MakeOperandDynamic(dynamic_cast<const OperandDynamic *>(evaluation), str); } -std::string BaseTemplate::MakeEvaluation(const IEvaluation* evaluation) -{ - std::ostringstream str; - MakeEvaluationInternal(evaluation, str); - return str.str(); +std::string BaseTemplate::MakeEvaluation(const IEvaluation *evaluation) { + std::ostringstream str; + MakeEvaluationInternal(evaluation, str); + return str.str(); } diff --git a/src/ZoneCodeGeneratorLib/Generating/Templates/Internal/BaseTemplate.h b/src/ZoneCodeGeneratorLib/Generating/Templates/Internal/BaseTemplate.h index 074c3ddd1..40fe51761 100644 --- a/src/ZoneCodeGeneratorLib/Generating/Templates/Internal/BaseTemplate.h +++ b/src/ZoneCodeGeneratorLib/Generating/Templates/Internal/BaseTemplate.h @@ -10,51 +10,61 @@ #include "Domain/Evaluation/Operation.h" #include "Generating/RenderingContext.h" -class BaseTemplate -{ +class BaseTemplate { protected: - static constexpr const char* INTENDATION = " "; + static constexpr const char *INTENDATION = " "; - std::ostream& m_out; - RenderingContext& m_env; - unsigned m_intendation; + std::ostream &m_out; + RenderingContext &m_env; + unsigned m_intendation; - BaseTemplate(std::ostream& stream, RenderingContext* context); + BaseTemplate(std::ostream &stream, RenderingContext *context); - void DoIntendation() const; + void DoIntendation() const; private: - static void MakeSafeTypeNameInternal(const DataDefinition* def, std::ostringstream& str); - static void MakeTypeVarNameInternal(const DataDefinition* def, std::ostringstream& str); - static void MakeTypeWrittenVarNameInternal(const DataDefinition* def, std::ostringstream& str); - static void MakeTypePtrVarNameInternal(const DataDefinition* def, std::ostringstream& str); - static void MakeTypeWrittenPtrVarNameInternal(const DataDefinition* def, std::ostringstream& str); - static void MakeArrayIndicesInternal(const DeclarationModifierComputations& modifierComputations, std::ostringstream& str); - static void MakeOperandStatic(const OperandStatic* op, std::ostringstream& str); - static void MakeOperandDynamic(const OperandDynamic* op, std::ostringstream& str); - static void MakeOperation(const Operation* operation, std::ostringstream& str); - static void MakeEvaluationInternal(const IEvaluation* evaluation, std::ostringstream& str); + static void MakeSafeTypeNameInternal(const DataDefinition *def, std::ostringstream &str); + static void MakeTypeVarNameInternal(const DataDefinition *def, std::ostringstream &str); + static void MakeTypeWrittenVarNameInternal(const DataDefinition *def, std::ostringstream &str); + static void MakeTypePtrVarNameInternal(const DataDefinition *def, std::ostringstream &str); + static void MakeTypeWrittenPtrVarNameInternal(const DataDefinition *def, std::ostringstream &str); + static void MakeArrayIndicesInternal(const DeclarationModifierComputations &modifierComputations, std::ostringstream &str); + static void MakeOperandStatic(const OperandStatic *op, std::ostringstream &str); + static void MakeOperandDynamic(const OperandDynamic *op, std::ostringstream &str); + static void MakeOperation(const Operation *operation, std::ostringstream &str); + static void MakeEvaluationInternal(const IEvaluation *evaluation, std::ostringstream &str); protected: - static std::string Upper(std::string str); - static std::string Lower(std::string str); - static std::string MakeTypeVarName(const DataDefinition* def); - static std::string MakeTypeWrittenVarName(const DataDefinition* def); - static std::string MakeTypePtrVarName(const DataDefinition* def); - static std::string MakeTypeWrittenPtrVarName(const DataDefinition* def); - static std::string MakeSafeTypeName(const DataDefinition* def); - static std::string MakeMemberAccess(StructureInformation* info, MemberInformation* member, const DeclarationModifierComputations& modifier); - static std::string MakeWrittenMemberAccess(StructureInformation* info, MemberInformation* member, const DeclarationModifierComputations& modifier); - static std::string MakeMemberAccess(const std::string& variableName, StructureInformation* info, MemberInformation* member, const DeclarationModifierComputations& modifier); - static std::string MakeTypeDecl(const TypeDeclaration* decl); - static std::string MakeFollowingReferences(const std::vector<DeclarationModifier*>& modifiers); - static std::string MakeArrayIndices(const DeclarationModifierComputations& modifierComputations); - static std::string MakeCustomActionCall(CustomAction* action); - static std::string MakeArrayCount(const ArrayDeclarationModifier* arrayModifier); - static std::string MakeEvaluation(const IEvaluation* evaluation); + static std::string Upper(std::string str); + static std::string Lower(std::string str); + static std::string MakeTypeVarName(const DataDefinition *def); + static std::string MakeTypeWrittenVarName(const DataDefinition *def); + static std::string MakeTypePtrVarName(const DataDefinition *def); + static std::string MakeTypeWrittenPtrVarName(const DataDefinition *def); + static std::string MakeSafeTypeName(const DataDefinition *def); + static std::string MakeMemberAccess(StructureInformation *info, MemberInformation *member, const DeclarationModifierComputations &modifier); + static std::string MakeWrittenMemberAccess(StructureInformation *info, MemberInformation *member, const DeclarationModifierComputations &modifier); + static std::string MakeMemberAccess(const std::string &variableName, StructureInformation *info, MemberInformation *member, + const DeclarationModifierComputations &modifier); + static std::string MakeTypeDecl(const TypeDeclaration *decl); + static std::string MakeFollowingReferences(const std::vector<DeclarationModifier *> &modifiers); + static std::string MakeArrayIndices(const DeclarationModifierComputations &modifierComputations); + static std::string MakeCustomActionCall(CustomAction *action); + static std::string MakeArrayCount(const ArrayDeclarationModifier *arrayModifier); + static std::string MakeEvaluation(const IEvaluation *evaluation); }; -#define LINE(x) {DoIntendation(); m_out << x << "\n";} -#define LINE_START(x) {DoIntendation(); m_out << x;} -#define LINE_MIDDLE(x) {m_out << x;} -#define LINE_END(x) {m_out << x << "\n";} \ No newline at end of file +#define LINE(x) \ + { \ + DoIntendation(); \ + m_out << x << "\n"; \ + } +#define LINE_START(x) \ + { \ + DoIntendation(); \ + m_out << x; \ + } +#define LINE_MIDDLE(x) \ + { m_out << x; } +#define LINE_END(x) \ + { m_out << x << "\n"; } \ No newline at end of file diff --git a/src/ZoneCodeGeneratorLib/Generating/Templates/ZoneLoadTemplate.cpp b/src/ZoneCodeGeneratorLib/Generating/Templates/ZoneLoadTemplate.cpp index 682cd0b15..48e009121 100644 --- a/src/ZoneCodeGeneratorLib/Generating/Templates/ZoneLoadTemplate.cpp +++ b/src/ZoneCodeGeneratorLib/Generating/Templates/ZoneLoadTemplate.cpp @@ -8,1331 +8,1074 @@ #include "Domain/Computations/StructureComputations.h" #include "Internal/BaseTemplate.h" -class ZoneLoadTemplate::Internal final : BaseTemplate -{ - enum class MemberLoadType - { - ARRAY_POINTER, - DYNAMIC_ARRAY, - EMBEDDED, - EMBEDDED_ARRAY, - POINTER_ARRAY, - SINGLE_POINTER - }; +class ZoneLoadTemplate::Internal final : BaseTemplate { + enum class MemberLoadType { ARRAY_POINTER, DYNAMIC_ARRAY, EMBEDDED, EMBEDDED_ARRAY, POINTER_ARRAY, SINGLE_POINTER }; - static std::string LoaderClassName(StructureInformation* asset) - { - std::ostringstream str; - str << "Loader_" << asset->m_definition->m_name; - return str.str(); - } + static std::string LoaderClassName(StructureInformation *asset) { + std::ostringstream str; + str << "Loader_" << asset->m_definition->m_name; + return str.str(); + } - static std::string VariableDecl(const DataDefinition* def) - { - std::ostringstream str; - str << def->GetFullName() << "* var" << MakeSafeTypeName(def) << ";"; - return str.str(); - } + static std::string VariableDecl(const DataDefinition *def) { + std::ostringstream str; + str << def->GetFullName() << "* var" << MakeSafeTypeName(def) << ";"; + return str.str(); + } - static std::string PointerVariableDecl(const DataDefinition* def) - { - std::ostringstream str; - str << def->GetFullName() << "** var" << MakeSafeTypeName(def) << "Ptr;"; - return str.str(); - } + static std::string PointerVariableDecl(const DataDefinition *def) { + std::ostringstream str; + str << def->GetFullName() << "** var" << MakeSafeTypeName(def) << "Ptr;"; + return str.str(); + } - void PrintHeaderPtrArrayLoadMethodDeclaration(const DataDefinition* def) const - { - LINE("void LoadPtrArray_"<< MakeSafeTypeName(def)<<"(bool atStreamStart, size_t count);") - } + void PrintHeaderPtrArrayLoadMethodDeclaration(const DataDefinition *def) const { + LINE("void LoadPtrArray_" << MakeSafeTypeName(def) << "(bool atStreamStart, size_t count);") + } - void PrintHeaderArrayLoadMethodDeclaration(const DataDefinition* def) const - { - LINE("void LoadArray_"<< MakeSafeTypeName(def)<<"(bool atStreamStart, size_t count);") - } + void PrintHeaderArrayLoadMethodDeclaration(const DataDefinition *def) const { + LINE("void LoadArray_" << MakeSafeTypeName(def) << "(bool atStreamStart, size_t count);") + } - void PrintHeaderLoadMethodDeclaration(const StructureInformation* info) const - { - LINE("void Load_"<< MakeSafeTypeName(info->m_definition)<<"(bool atStreamStart);") - } - - void PrintHeaderTempPtrLoadMethodDeclaration(const StructureInformation* info) const - { - LINE("void LoadPtr_"<< MakeSafeTypeName(info->m_definition)<<"(bool atStreamStart);") - } + void PrintHeaderLoadMethodDeclaration(const StructureInformation *info) const { + LINE("void Load_" << MakeSafeTypeName(info->m_definition) << "(bool atStreamStart);") + } - void PrintHeaderAssetLoadMethodDeclaration(const StructureInformation* info) const - { - LINE("void LoadAsset_"<< MakeSafeTypeName(info->m_definition)<<"("<<info->m_definition->GetFullName()<<"** pAsset);") - } + void PrintHeaderTempPtrLoadMethodDeclaration(const StructureInformation *info) const { + LINE("void LoadPtr_" << MakeSafeTypeName(info->m_definition) << "(bool atStreamStart);") + } - void PrintHeaderGetNameMethodDeclaration(const StructureInformation* info) const - { - LINE("static std::string GetAssetName("<<info->m_definition->GetFullName()<<"* pAsset);") - } + void PrintHeaderAssetLoadMethodDeclaration(const StructureInformation *info) const { + LINE("void LoadAsset_" << MakeSafeTypeName(info->m_definition) << "(" << info->m_definition->GetFullName() << "** pAsset);") + } - void PrintHeaderMainLoadMethodDeclaration(const StructureInformation* info) const - { - LINE("XAssetInfo<"<<info->m_definition->GetFullName()<<">* Load("<<info->m_definition->GetFullName()<<"** pAsset);") - } + void PrintHeaderGetNameMethodDeclaration(const StructureInformation *info) const { + LINE("static std::string GetAssetName(" << info->m_definition->GetFullName() << "* pAsset);") + } - void PrintHeaderConstructor() const - { - LINE(LoaderClassName(m_env.m_asset)<<"(Zone* zone, IZoneInputStream* stream);") - } + void PrintHeaderMainLoadMethodDeclaration(const StructureInformation *info) const { + LINE("XAssetInfo<" << info->m_definition->GetFullName() << ">* Load(" << info->m_definition->GetFullName() << "** pAsset);") + } - void PrintVariableInitialization(const DataDefinition* def) const - { - LINE("var"<<def->m_name<<" = nullptr;") - } + void PrintHeaderConstructor() const { LINE(LoaderClassName(m_env.m_asset) << "(Zone* zone, IZoneInputStream* stream);") } - void PrintPointerVariableInitialization(const DataDefinition* def) const - { - LINE("var"<<def->m_name<<"Ptr = nullptr;") - } + void PrintVariableInitialization(const DataDefinition *def) const { LINE("var" << def->m_name << " = nullptr;") } - void PrintConstructorMethod() - { - LINE(LoaderClassName(m_env.m_asset) << "::" << LoaderClassName(m_env.m_asset) << "(Zone* zone, IZoneInputStream* stream)") + void PrintPointerVariableInitialization(const DataDefinition *def) const { LINE("var" << def->m_name << "Ptr = nullptr;") } - m_intendation++; - LINE_START(": AssetLoader("<<m_env.m_asset->m_asset_enum_entry->m_name<<", zone, stream)") - if (m_env.m_has_actions) - { - LINE_MIDDLE(", m_actions(zone)") - } - LINE_END("") - m_intendation--; + void PrintConstructorMethod() { + LINE(LoaderClassName(m_env.m_asset) << "::" << LoaderClassName(m_env.m_asset) << "(Zone* zone, IZoneInputStream* stream)") - LINE("{") - m_intendation++; + m_intendation++; + LINE_START(": AssetLoader(" << m_env.m_asset->m_asset_enum_entry->m_name << ", zone, stream)") + if (m_env.m_has_actions) { + LINE_MIDDLE(", m_actions(zone)") + } + LINE_END("") + m_intendation--; - LINE("m_asset_info = nullptr;") - PrintVariableInitialization(m_env.m_asset->m_definition); - PrintPointerVariableInitialization(m_env.m_asset->m_definition); - LINE("") + LINE("{") + m_intendation++; - for (auto* type : m_env.m_used_types) - { - if (type->m_info && !type->m_info->m_definition->m_anonymous && !type->m_info->m_is_leaf && !StructureComputations(type->m_info).IsAsset()) - { - PrintVariableInitialization(type->m_type); - } - } - for (auto* type : m_env.m_used_types) - { - if (type->m_info && type->m_pointer_array_reference_exists && !type->m_is_context_asset) - { - PrintPointerVariableInitialization(type->m_type); - } - } + LINE("m_asset_info = nullptr;") + PrintVariableInitialization(m_env.m_asset->m_definition); + PrintPointerVariableInitialization(m_env.m_asset->m_definition); + LINE("") - m_intendation--; - LINE("}") + for (auto *type : m_env.m_used_types) { + if (type->m_info && !type->m_info->m_definition->m_anonymous && !type->m_info->m_is_leaf && !StructureComputations(type->m_info).IsAsset()) { + PrintVariableInitialization(type->m_type); + } } - - void PrintLoadPtrArrayMethod_Loading(const DataDefinition* def, StructureInformation* info) const - { - LINE("*"<< MakeTypePtrVarName(def)<<" = m_stream->Alloc<"<<def->GetFullName()<<">("<< def->GetAlignment() <<");") - - if (info && !info->m_is_leaf) - { - LINE(MakeTypeVarName(info->m_definition)<<" = *"<< MakeTypePtrVarName(def)<<";") - LINE("Load_"<< MakeSafeTypeName(def)<<"(true);") - } - else - { - LINE("m_stream->Load<"<<def->GetFullName()<<">(*"<< MakeTypePtrVarName(def)<<");") - } + for (auto *type : m_env.m_used_types) { + if (type->m_info && type->m_pointer_array_reference_exists && !type->m_is_context_asset) { + PrintPointerVariableInitialization(type->m_type); + } } - void PrintLoadPtrArrayMethod_PointerCheck(const DataDefinition* def, StructureInformation* info, const bool reusable) - { - LINE("if (*" << MakeTypePtrVarName(def) << ")") - LINE("{") - m_intendation++; + m_intendation--; + LINE("}") + } - if (info && StructureComputations(info).IsAsset()) - { - LINE(LoaderClassName(info)<<" loader(m_zone, m_stream);") - LINE("AddDependency(loader.Load("<< MakeTypePtrVarName(def)<<"));") - } - else - { - if (reusable) - { - LINE("if(*" << MakeTypePtrVarName(def) << " == PTR_FOLLOWING)") - LINE("{") - m_intendation++; - - PrintLoadPtrArrayMethod_Loading(def, info); - - m_intendation--; - LINE("}") - LINE("else") - LINE("{") - m_intendation++; - - LINE("*"<< MakeTypePtrVarName(def)<<" = m_stream->ConvertOffsetToPointer(*"<< MakeTypePtrVarName(def)<<");") - - m_intendation--; - LINE("}") - } - else - { - PrintLoadPtrArrayMethod_Loading(def, info); - } - } + void PrintLoadPtrArrayMethod_Loading(const DataDefinition *def, StructureInformation *info) const { + LINE("*" << MakeTypePtrVarName(def) << " = m_stream->Alloc<" << def->GetFullName() << ">(" << def->GetAlignment() << ");") - m_intendation--; - LINE("}") + if (info && !info->m_is_leaf) { + LINE(MakeTypeVarName(info->m_definition) << " = *" << MakeTypePtrVarName(def) << ";") + LINE("Load_" << MakeSafeTypeName(def) << "(true);") + } else { + LINE("m_stream->Load<" << def->GetFullName() << ">(*" << MakeTypePtrVarName(def) << ");") } - - void PrintLoadPtrArrayMethod(const DataDefinition* def, StructureInformation* info, const bool reusable) - { - LINE("void "<<LoaderClassName(m_env.m_asset)<<"::LoadPtrArray_"<< MakeSafeTypeName(def)<<"(const bool atStreamStart, const size_t count)") + } + + void PrintLoadPtrArrayMethod_PointerCheck(const DataDefinition *def, StructureInformation *info, const bool reusable) { + LINE("if (*" << MakeTypePtrVarName(def) << ")") + LINE("{") + m_intendation++; + + if (info && StructureComputations(info).IsAsset()) { + LINE(LoaderClassName(info) << " loader(m_zone, m_stream);") + LINE("AddDependency(loader.Load(" << MakeTypePtrVarName(def) << "));") + } else { + if (reusable) { + LINE("if(*" << MakeTypePtrVarName(def) << " == PTR_FOLLOWING)") LINE("{") m_intendation++; - LINE("assert(" << MakeTypePtrVarName(def) << " != nullptr);") - LINE("") + PrintLoadPtrArrayMethod_Loading(def, info); - LINE("if(atStreamStart)") - m_intendation++; - LINE("m_stream->Load<"<<def->GetFullName()<<"*>("<< MakeTypePtrVarName(def)<<", count);") m_intendation--; - - LINE("") - LINE(def->GetFullName() << "** var = " << MakeTypePtrVarName(def) << ";") - LINE("for(size_t index = 0; index < count; index++)") + LINE("}") + LINE("else") LINE("{") m_intendation++; - LINE(MakeTypePtrVarName(def) << " = var;") - PrintLoadPtrArrayMethod_PointerCheck(def, info, reusable); - LINE("") - LINE("var++;") + LINE("*" << MakeTypePtrVarName(def) << " = m_stream->ConvertOffsetToPointer(*" << MakeTypePtrVarName(def) << ");") m_intendation--; LINE("}") - m_intendation--; - LINE("}") + } else { + PrintLoadPtrArrayMethod_Loading(def, info); + } } - void PrintLoadArrayMethod(const DataDefinition* def, StructureInformation* info) - { - LINE("void " << LoaderClassName(m_env.m_asset) << "::LoadArray_" << MakeSafeTypeName(def) << "(const bool atStreamStart, const size_t count)") - LINE("{") - m_intendation++; + m_intendation--; + LINE("}") + } + + void PrintLoadPtrArrayMethod(const DataDefinition *def, StructureInformation *info, const bool reusable) { + LINE("void " << LoaderClassName(m_env.m_asset) << "::LoadPtrArray_" << MakeSafeTypeName(def) << "(const bool atStreamStart, const size_t count)") + LINE("{") + m_intendation++; + + LINE("assert(" << MakeTypePtrVarName(def) << " != nullptr);") + LINE("") + + LINE("if(atStreamStart)") + m_intendation++; + LINE("m_stream->Load<" << def->GetFullName() << "*>(" << MakeTypePtrVarName(def) << ", count);") + m_intendation--; + + LINE("") + LINE(def->GetFullName() << "** var = " << MakeTypePtrVarName(def) << ";") + LINE("for(size_t index = 0; index < count; index++)") + LINE("{") + m_intendation++; + + LINE(MakeTypePtrVarName(def) << " = var;") + PrintLoadPtrArrayMethod_PointerCheck(def, info, reusable); + LINE("") + LINE("var++;") + + m_intendation--; + LINE("}") + m_intendation--; + LINE("}") + } + + void PrintLoadArrayMethod(const DataDefinition *def, StructureInformation *info) { + LINE("void " << LoaderClassName(m_env.m_asset) << "::LoadArray_" << MakeSafeTypeName(def) << "(const bool atStreamStart, const size_t count)") + LINE("{") + m_intendation++; + + LINE("assert(" << MakeTypeVarName(def) << " != nullptr);") + LINE("") + LINE("if(atStreamStart)") + m_intendation++; + LINE("m_stream->Load<" << def->GetFullName() << ">(" << MakeTypeVarName(def) << ", count);") + m_intendation--; + + LINE("") + LINE(def->GetFullName() << "* var = " << MakeTypeVarName(def) << ";") + LINE("for(size_t index = 0; index < count; index++)") + LINE("{") + m_intendation++; + + LINE(MakeTypeVarName(info->m_definition) << " = var;") + LINE("Load_" << info->m_definition->m_name << "(false);") + LINE("var++;") + + m_intendation--; + LINE("}") + + m_intendation--; + LINE("}") + } + + void LoadMember_ScriptString(StructureInformation *info, MemberInformation *member, const DeclarationModifierComputations &modifier, + const MemberLoadType loadType) const { + if (loadType == MemberLoadType::ARRAY_POINTER) { + LINE("varScriptString = " << MakeMemberAccess(info, member, modifier) << ";") + LINE("LoadScriptStringArray(true, " << MakeEvaluation(modifier.GetArrayPointerCountEvaluation()) << ");") + } else if (loadType == MemberLoadType::EMBEDDED_ARRAY) { + LINE("varScriptString = " << MakeMemberAccess(info, member, modifier) << ";") + LINE("LoadScriptStringArray(false, " << MakeArrayCount(dynamic_cast<ArrayDeclarationModifier *>(modifier.GetDeclarationModifier())) << ");") + } else if (loadType == MemberLoadType::EMBEDDED) { + LINE(MakeMemberAccess(info, member, modifier) << " = UseScriptString(" << MakeMemberAccess(info, member, modifier) << ");") + } else { + assert(false); + LINE("#error unsupported loadType " << static_cast<int>(loadType) << " for scripstring") + } + } + + void LoadMember_Asset(StructureInformation *info, MemberInformation *member, const DeclarationModifierComputations &modifier, + const MemberLoadType loadType) const { + if (loadType == MemberLoadType::SINGLE_POINTER) { + LINE(LoaderClassName(member->m_type) << " loader(m_zone, m_stream);") + LINE("AddDependency(loader.Load(&" << MakeMemberAccess(info, member, modifier) << "));") + } else if (loadType == MemberLoadType::POINTER_ARRAY) { + LoadMember_PointerArray(info, member, modifier); + } else { + assert(false); + LINE("#error unsupported loadType " << static_cast<int>(loadType) << " for asset") + } + } + + void LoadMember_String(StructureInformation *info, MemberInformation *member, const DeclarationModifierComputations &modifier, + const MemberLoadType loadType) const { + if (loadType == MemberLoadType::SINGLE_POINTER) { + if (member->m_member->m_type_declaration->m_is_const) { + LINE("varXString = &" << MakeMemberAccess(info, member, modifier) << ";") + } else { + LINE("varXString = const_cast<const char**>(&" << MakeMemberAccess(info, member, modifier) << ");") + } + LINE("LoadXString(false);") + } else if (loadType == MemberLoadType::POINTER_ARRAY) { + LINE("varXString = " << MakeMemberAccess(info, member, modifier) << ";") + if (modifier.IsArray()) { + LINE("LoadXStringArray(false, " << modifier.GetArraySize() << ");") + } else { + LINE("LoadXStringArray(true, " << MakeEvaluation(modifier.GetPointerArrayCountEvaluation()) << ");") + } + } else { + assert(false); + LINE("#error unsupported loadType " << static_cast<int>(loadType) << " for string") + } + } - LINE("assert(" << MakeTypeVarName(def) << " != nullptr);") - LINE("") - LINE("if(atStreamStart)") - m_intendation++; - LINE("m_stream->Load<"<<def->GetFullName()<<">("<<MakeTypeVarName(def)<<", count);") - m_intendation--; + void LoadMember_ArrayPointer(StructureInformation *info, MemberInformation *member, const DeclarationModifierComputations &modifier) const { + const MemberComputations computations(member); + if (member->m_type && !member->m_type->m_is_leaf && !computations.IsInRuntimeBlock()) { + LINE(MakeTypeVarName(member->m_member->m_type_declaration->m_type) << " = " << MakeMemberAccess(info, member, modifier) << ";") + LINE("LoadArray_" << MakeSafeTypeName(member->m_member->m_type_declaration->m_type) << "(true, " + << MakeEvaluation(modifier.GetArrayPointerCountEvaluation()) << ");") + if (member->m_type->m_post_load_action) { LINE("") - LINE(def->GetFullName() << "* var = " << MakeTypeVarName(def) << ";") - LINE("for(size_t index = 0; index < count; index++)") - LINE("{") - m_intendation++; + LINE(MakeCustomActionCall(member->m_type->m_post_load_action.get())) + } + } else { + LINE("m_stream->Load<" << MakeTypeDecl(member->m_member->m_type_declaration.get()) << MakeFollowingReferences(modifier.GetFollowingDeclarationModifiers()) + << ">(" << MakeMemberAccess(info, member, modifier) << ", " << MakeEvaluation(modifier.GetArrayPointerCountEvaluation()) << ");") + } + } + + void LoadMember_PointerArray(StructureInformation *info, MemberInformation *member, const DeclarationModifierComputations &modifier) const { + LINE(MakeTypePtrVarName(member->m_member->m_type_declaration->m_type) << " = " << MakeMemberAccess(info, member, modifier) << ";") + if (modifier.IsArray()) { + LINE("LoadPtrArray_" << MakeSafeTypeName(member->m_member->m_type_declaration->m_type) << "(false, " << modifier.GetArraySize() << ");") + } else { + LINE("LoadPtrArray_" << MakeSafeTypeName(member->m_member->m_type_declaration->m_type) << "(true, " + << MakeEvaluation(modifier.GetPointerArrayCountEvaluation()) << ");") + } + } - LINE(MakeTypeVarName(info->m_definition) << " = var;") - LINE("Load_"<<info->m_definition->m_name<<"(false);") - LINE("var++;") + void LoadMember_EmbeddedArray(StructureInformation *info, MemberInformation *member, const DeclarationModifierComputations &modifier) const { + const MemberComputations computations(member); + std::string arraySizeStr; - m_intendation--; - LINE("}") + if (modifier.HasDynamicArrayCount()) + arraySizeStr = MakeEvaluation(modifier.GetDynamicArrayCountEvaluation()); + else + arraySizeStr = std::to_string(modifier.GetArraySize()); - m_intendation--; - LINE("}") - } + if (!member->m_is_leaf) { + LINE(MakeTypeVarName(member->m_member->m_type_declaration->m_type) << " = " << MakeMemberAccess(info, member, modifier) << ";") - void LoadMember_ScriptString(StructureInformation* info, MemberInformation* member, const DeclarationModifierComputations& modifier, const MemberLoadType loadType) const - { - if (loadType == MemberLoadType::ARRAY_POINTER) - { - LINE("varScriptString = " << MakeMemberAccess(info, member, modifier) << ";") - LINE("LoadScriptStringArray(true, " << MakeEvaluation(modifier.GetArrayPointerCountEvaluation()) << ");") - } - else if (loadType == MemberLoadType::EMBEDDED_ARRAY) - { - LINE("varScriptString = " << MakeMemberAccess(info, member, modifier) << ";") - LINE("LoadScriptStringArray(false, " << MakeArrayCount(dynamic_cast<ArrayDeclarationModifier*>(modifier.GetDeclarationModifier())) << ");") - } - else if (loadType == MemberLoadType::EMBEDDED) - { - LINE(MakeMemberAccess(info, member, modifier) << " = UseScriptString(" << MakeMemberAccess(info, member, modifier) << ");") - } - else - { - assert(false); - LINE("#error unsupported loadType " << static_cast<int>(loadType) << " for scripstring") - } - } + if (computations.IsAfterPartialLoad()) { + LINE("LoadArray_" << MakeSafeTypeName(member->m_member->m_type_declaration->m_type) << "(true, " << arraySizeStr << ");") + } else { + LINE("LoadArray_" << MakeSafeTypeName(member->m_member->m_type_declaration->m_type) << "(false, " << arraySizeStr << ");") + } - void LoadMember_Asset(StructureInformation* info, MemberInformation* member, const DeclarationModifierComputations& modifier, const MemberLoadType loadType) const - { - if (loadType == MemberLoadType::SINGLE_POINTER) - { - LINE(LoaderClassName(member->m_type)<<" loader(m_zone, m_stream);") - LINE("AddDependency(loader.Load(&"<<MakeMemberAccess(info, member, modifier)<<"));") - } - else if (loadType == MemberLoadType::POINTER_ARRAY) - { - LoadMember_PointerArray(info, member, modifier); - } - else - { - assert(false); - LINE("#error unsupported loadType " << static_cast<int>(loadType) << " for asset") - } + if (member->m_type->m_post_load_action) { + LINE("") + LINE(MakeCustomActionCall(member->m_type->m_post_load_action.get())) + } + } else if (computations.IsAfterPartialLoad()) { + LINE("m_stream->Load<" << MakeTypeDecl(member->m_member->m_type_declaration.get()) << MakeFollowingReferences(modifier.GetFollowingDeclarationModifiers()) + << ">(" << MakeMemberAccess(info, member, modifier) << ", " << arraySizeStr << ");") } - - void LoadMember_String(StructureInformation* info, MemberInformation* member, const DeclarationModifierComputations& modifier, const MemberLoadType loadType) const - { - if (loadType == MemberLoadType::SINGLE_POINTER) - { - if (member->m_member->m_type_declaration->m_is_const) - { - LINE("varXString = &" << MakeMemberAccess(info, member, modifier) << ";") - } - else - { - LINE("varXString = const_cast<const char**>(&" << MakeMemberAccess(info, member, modifier) << ");") - } - LINE("LoadXString(false);") - } - else if (loadType == MemberLoadType::POINTER_ARRAY) - { - LINE("varXString = " << MakeMemberAccess(info, member, modifier) << ";") - if (modifier.IsArray()) - { - LINE("LoadXStringArray(false, "<<modifier.GetArraySize()<<");") - } - else - { - LINE("LoadXStringArray(true, "<<MakeEvaluation(modifier.GetPointerArrayCountEvaluation())<<");") - } - } - else - { - assert(false); - LINE("#error unsupported loadType "<<static_cast<int>(loadType)<<" for string") - } + } + + void LoadMember_DynamicArray(StructureInformation *info, MemberInformation *member, const DeclarationModifierComputations &modifier) const { + if (member->m_type && !member->m_type->m_is_leaf) { + LINE(MakeTypeVarName(member->m_member->m_type_declaration->m_type) << " = " << MakeMemberAccess(info, member, modifier) << ";") + LINE("LoadArray_" << MakeSafeTypeName(member->m_member->m_type_declaration->m_type) << "(true, " + << MakeEvaluation(modifier.GetDynamicArraySizeEvaluation()) << ");") + } else { + LINE("m_stream->Load<" << MakeTypeDecl(member->m_member->m_type_declaration.get()) << MakeFollowingReferences(modifier.GetFollowingDeclarationModifiers()) + << ">(" << MakeMemberAccess(info, member, modifier) << ", " << MakeEvaluation(modifier.GetDynamicArraySizeEvaluation()) << ");") } + } - void LoadMember_ArrayPointer(StructureInformation* info, MemberInformation* member, const DeclarationModifierComputations& modifier) const - { - const MemberComputations computations(member); - if (member->m_type && !member->m_type->m_is_leaf && !computations.IsInRuntimeBlock()) - { - LINE(MakeTypeVarName(member->m_member->m_type_declaration->m_type) << " = " << MakeMemberAccess(info, member, modifier) << ";") - LINE("LoadArray_" << MakeSafeTypeName(member->m_member->m_type_declaration->m_type) << "(true, " << MakeEvaluation(modifier.GetArrayPointerCountEvaluation()) << ");") + void LoadMember_Embedded(StructureInformation *info, MemberInformation *member, const DeclarationModifierComputations &modifier) const { + const MemberComputations computations(member); + if (!member->m_is_leaf) { + LINE(MakeTypeVarName(member->m_member->m_type_declaration->m_type) << " = &" << MakeMemberAccess(info, member, modifier) << ";") - if (member->m_type->m_post_load_action) - { - LINE("") - LINE(MakeCustomActionCall(member->m_type->m_post_load_action.get())) - } - } - else - { - LINE("m_stream->Load<" << MakeTypeDecl(member->m_member->m_type_declaration.get()) << MakeFollowingReferences(modifier.GetFollowingDeclarationModifiers()) - << ">(" << MakeMemberAccess(info, member, modifier) << ", " << MakeEvaluation(modifier.GetArrayPointerCountEvaluation()) << ");") - } - } + if (computations.IsAfterPartialLoad()) { + LINE("Load_" << MakeSafeTypeName(member->m_member->m_type_declaration->m_type) << "(true);") + } else { + LINE("Load_" << MakeSafeTypeName(member->m_member->m_type_declaration->m_type) << "(false);") + } - void LoadMember_PointerArray(StructureInformation* info, MemberInformation* member, const DeclarationModifierComputations& modifier) const - { - LINE(MakeTypePtrVarName(member->m_member->m_type_declaration->m_type) << " = " << MakeMemberAccess(info, member, modifier) << ";") - if (modifier.IsArray()) - { - LINE("LoadPtrArray_"<<MakeSafeTypeName(member->m_member->m_type_declaration->m_type)<<"(false, "<<modifier.GetArraySize()<<");") - } - else - { - LINE("LoadPtrArray_"<<MakeSafeTypeName(member->m_member->m_type_declaration->m_type)<<"(true, "<<MakeEvaluation(modifier.GetPointerArrayCountEvaluation())<<");") - } + if (member->m_type->m_post_load_action) { + LINE("") + LINE(MakeCustomActionCall(member->m_type->m_post_load_action.get())) + } + } else if (computations.IsAfterPartialLoad()) { + LINE("m_stream->Load<" << MakeTypeDecl(member->m_member->m_type_declaration.get()) << MakeFollowingReferences(modifier.GetFollowingDeclarationModifiers()) + << ">(&" << MakeMemberAccess(info, member, modifier) << ");") } + } - void LoadMember_EmbeddedArray(StructureInformation* info, MemberInformation* member, const DeclarationModifierComputations& modifier) const - { - const MemberComputations computations(member); - std::string arraySizeStr; - - if (modifier.HasDynamicArrayCount()) - arraySizeStr = MakeEvaluation(modifier.GetDynamicArrayCountEvaluation()); - else - arraySizeStr = std::to_string(modifier.GetArraySize()); - - if (!member->m_is_leaf) - { - LINE(MakeTypeVarName(member->m_member->m_type_declaration->m_type) << " = " << MakeMemberAccess(info, member, modifier) << ";") - - if (computations.IsAfterPartialLoad()) - { - LINE("LoadArray_" << MakeSafeTypeName(member->m_member->m_type_declaration->m_type) << "(true, "<<arraySizeStr <<");") - } - else - { - LINE("LoadArray_"<<MakeSafeTypeName(member->m_member->m_type_declaration->m_type)<<"(false, "<<arraySizeStr <<");") - } - - if (member->m_type->m_post_load_action) - { - LINE("") - LINE(MakeCustomActionCall(member->m_type->m_post_load_action.get())) - } - } - else if (computations.IsAfterPartialLoad()) - { - LINE("m_stream->Load<" << MakeTypeDecl(member->m_member->m_type_declaration.get()) << MakeFollowingReferences(modifier.GetFollowingDeclarationModifiers()) - << ">(" << MakeMemberAccess(info, member, modifier) <<", "<<arraySizeStr <<");") - } - } + void LoadMember_SinglePointer(StructureInformation *info, MemberInformation *member, const DeclarationModifierComputations &modifier) const { + const MemberComputations computations(member); + if (member->m_type && !member->m_type->m_is_leaf && !computations.IsInRuntimeBlock()) { + LINE(MakeTypeVarName(member->m_member->m_type_declaration->m_type) << " = " << MakeMemberAccess(info, member, modifier) << ";") + LINE("Load_" << MakeSafeTypeName(member->m_type->m_definition) << "(true);") - void LoadMember_DynamicArray(StructureInformation* info, MemberInformation* member, const DeclarationModifierComputations& modifier) const - { - if (member->m_type && !member->m_type->m_is_leaf) - { - LINE(MakeTypeVarName(member->m_member->m_type_declaration->m_type) << " = " << MakeMemberAccess(info, member, modifier) << ";") - LINE("LoadArray_"<<MakeSafeTypeName(member->m_member->m_type_declaration->m_type)<<"(true, "<<MakeEvaluation(modifier.GetDynamicArraySizeEvaluation())<<");") - } - else - { - LINE("m_stream->Load<"<<MakeTypeDecl(member->m_member->m_type_declaration.get())<<MakeFollowingReferences(modifier.GetFollowingDeclarationModifiers()) - <<">("<<MakeMemberAccess(info, member, modifier)<<", "<<MakeEvaluation(modifier.GetDynamicArraySizeEvaluation())<<");") - } + if (member->m_type->m_post_load_action) { + LINE("") + LINE(MakeCustomActionCall(member->m_type->m_post_load_action.get())) + } + } else { + LINE("m_stream->Load<" << MakeTypeDecl(member->m_member->m_type_declaration.get()) << MakeFollowingReferences(modifier.GetFollowingDeclarationModifiers()) + << ">(" << MakeMemberAccess(info, member, modifier) << ");") } - - void LoadMember_Embedded(StructureInformation* info, MemberInformation* member, const DeclarationModifierComputations& modifier) const - { - const MemberComputations computations(member); - if (!member->m_is_leaf) - { - LINE(MakeTypeVarName(member->m_member->m_type_declaration->m_type) << " = &" << MakeMemberAccess(info, member, modifier) << ";") - - if (computations.IsAfterPartialLoad()) - { - LINE("Load_" << MakeSafeTypeName(member->m_member->m_type_declaration->m_type) << "(true);") - } - else - { - LINE("Load_" << MakeSafeTypeName(member->m_member->m_type_declaration->m_type) << "(false);") - } - - if (member->m_type->m_post_load_action) - { - LINE("") - LINE(MakeCustomActionCall(member->m_type->m_post_load_action.get())) - } - } - else if (computations.IsAfterPartialLoad()) - { - LINE("m_stream->Load<"<<MakeTypeDecl(member->m_member->m_type_declaration.get()) << MakeFollowingReferences(modifier.GetFollowingDeclarationModifiers()) - << ">(&" << MakeMemberAccess(info, member, modifier)<<");") - } + } + + void LoadMember_TypeCheck(StructureInformation *info, MemberInformation *member, const DeclarationModifierComputations &modifier, + const MemberLoadType loadType) const { + if (member->m_is_string) { + LoadMember_String(info, member, modifier, loadType); + } else if (member->m_is_script_string) { + LoadMember_ScriptString(info, member, modifier, loadType); + } else if (member->m_type && StructureComputations(member->m_type).IsAsset()) { + LoadMember_Asset(info, member, modifier, loadType); + } else { + switch (loadType) { + case MemberLoadType::ARRAY_POINTER: + LoadMember_ArrayPointer(info, member, modifier); + break; + + case MemberLoadType::SINGLE_POINTER: + LoadMember_SinglePointer(info, member, modifier); + break; + + case MemberLoadType::EMBEDDED: + LoadMember_Embedded(info, member, modifier); + break; + + case MemberLoadType::POINTER_ARRAY: + LoadMember_PointerArray(info, member, modifier); + break; + + case MemberLoadType::DYNAMIC_ARRAY: + LoadMember_DynamicArray(info, member, modifier); + break; + + case MemberLoadType::EMBEDDED_ARRAY: + LoadMember_EmbeddedArray(info, member, modifier); + break; + + default: + LINE("// t=" << static_cast<int>(loadType)) + break; + } } + } - void LoadMember_SinglePointer(StructureInformation* info, MemberInformation* member, const DeclarationModifierComputations& modifier) const - { - const MemberComputations computations(member); - if (member->m_type && !member->m_type->m_is_leaf && !computations.IsInRuntimeBlock()) - { - LINE(MakeTypeVarName(member->m_member->m_type_declaration->m_type) << " = " << MakeMemberAccess(info, member, modifier) << ";") - LINE("Load_" << MakeSafeTypeName(member->m_type->m_definition) << "(true);") - - if (member->m_type->m_post_load_action) - { - LINE("") - LINE(MakeCustomActionCall(member->m_type->m_post_load_action.get())) - } - } - else - { - LINE("m_stream->Load<" << MakeTypeDecl(member->m_member->m_type_declaration.get()) << MakeFollowingReferences(modifier.GetFollowingDeclarationModifiers()) - << ">(" << MakeMemberAccess(info, member, modifier) << ");") - } + static bool LoadMember_ShouldMakeAlloc(StructureInformation *info, MemberInformation *member, const DeclarationModifierComputations &modifier, + const MemberLoadType loadType) { + if (loadType != MemberLoadType::ARRAY_POINTER && loadType != MemberLoadType::POINTER_ARRAY && loadType != MemberLoadType::SINGLE_POINTER) { + return false; } - void LoadMember_TypeCheck(StructureInformation* info, MemberInformation* member, const DeclarationModifierComputations& modifier, const MemberLoadType loadType) const - { - if (member->m_is_string) - { - LoadMember_String(info, member, modifier, loadType); - } - else if (member->m_is_script_string) - { - LoadMember_ScriptString(info, member, modifier, loadType); - } - else if (member->m_type && StructureComputations(member->m_type).IsAsset()) - { - LoadMember_Asset(info, member, modifier, loadType); - } - else - { - switch (loadType) - { - case MemberLoadType::ARRAY_POINTER: - LoadMember_ArrayPointer(info, member, modifier); - break; - - case MemberLoadType::SINGLE_POINTER: - LoadMember_SinglePointer(info, member, modifier); - break; - - case MemberLoadType::EMBEDDED: - LoadMember_Embedded(info, member, modifier); - break; - - case MemberLoadType::POINTER_ARRAY: - LoadMember_PointerArray(info, member, modifier); - break; - - case MemberLoadType::DYNAMIC_ARRAY: - LoadMember_DynamicArray(info, member, modifier); - break; - - case MemberLoadType::EMBEDDED_ARRAY: - LoadMember_EmbeddedArray(info, member, modifier); - break; - - default: - LINE("// t=" << static_cast<int>(loadType)) - break; - } - } + if (loadType == MemberLoadType::POINTER_ARRAY) { + return !modifier.IsArray(); } - static bool LoadMember_ShouldMakeAlloc(StructureInformation* info, MemberInformation* member, const DeclarationModifierComputations& modifier, const MemberLoadType loadType) - { - if (loadType != MemberLoadType::ARRAY_POINTER - && loadType != MemberLoadType::POINTER_ARRAY - && loadType != MemberLoadType::SINGLE_POINTER) - { - return false; - } - - if (loadType == MemberLoadType::POINTER_ARRAY) - { - return !modifier.IsArray(); - } + if (member->m_is_string) { + return false; + } - if (member->m_is_string) - { - return false; - } + if (member->m_type && StructureComputations(member->m_type).IsAsset()) { + return false; + } - if (member->m_type && StructureComputations(member->m_type).IsAsset()) - { - return false; - } + return true; + } - return true; + void LoadMember_Alloc(StructureInformation *info, MemberInformation *member, const DeclarationModifierComputations &modifier, const MemberLoadType loadType) { + if (!LoadMember_ShouldMakeAlloc(info, member, modifier, loadType)) { + LoadMember_TypeCheck(info, member, modifier, loadType); + return; } - void LoadMember_Alloc(StructureInformation* info, MemberInformation* member, const DeclarationModifierComputations& modifier, const MemberLoadType loadType) - { - if (!LoadMember_ShouldMakeAlloc(info, member, modifier, loadType)) - { - LoadMember_TypeCheck(info, member, modifier, loadType); - return; - } - - const MemberComputations computations(member); - if (computations.IsInTempBlock()) - { - LINE(member->m_member->m_type_declaration->m_type->GetFullName()<< "* ptr = "<<MakeMemberAccess(info, member, modifier)<<";") - } + const MemberComputations computations(member); + if (computations.IsInTempBlock()) { + LINE(member->m_member->m_type_declaration->m_type->GetFullName() << "* ptr = " << MakeMemberAccess(info, member, modifier) << ";") + } - const auto typeDecl = MakeTypeDecl(member->m_member->m_type_declaration.get()); - const auto followingReferences = MakeFollowingReferences(modifier.GetFollowingDeclarationModifiers()); + const auto typeDecl = MakeTypeDecl(member->m_member->m_type_declaration.get()); + const auto followingReferences = MakeFollowingReferences(modifier.GetFollowingDeclarationModifiers()); + + // This used to use `alignof()` to calculate alignment but due to inconsistencies between compilers and bugs discovered in MSVC + // (Alignment specified via `__declspec(align())` showing as correct via intellisense but is incorrect when compiled for types that have a larger alignment + // than the specified value) this was changed to make ZoneCodeGenerator calculate what is supposed to be used as alignment when allocating. This is more + // reliable when being used with different compilers and the value used can be seen in the source code directly + if (member->m_alloc_alignment) { + LINE(MakeMemberAccess(info, member, modifier) << " = m_stream->Alloc<" << typeDecl << followingReferences << ">(" + << MakeEvaluation(member->m_alloc_alignment.get()) << ");") + } else { + LINE(MakeMemberAccess(info, member, modifier) << " = m_stream->Alloc<" << typeDecl << followingReferences << ">(" << modifier.GetAlignment() << ");") + } - // This used to use `alignof()` to calculate alignment but due to inconsistencies between compilers and bugs discovered in MSVC - // (Alignment specified via `__declspec(align())` showing as correct via intellisense but is incorrect when compiled for types that have a larger alignment than the specified value) - // this was changed to make ZoneCodeGenerator calculate what is supposed to be used as alignment when allocating. - // This is more reliable when being used with different compilers and the value used can be seen in the source code directly - if (member->m_alloc_alignment) - { - LINE(MakeMemberAccess(info, member, modifier)<<" = m_stream->Alloc<"<<typeDecl<<followingReferences<<">("<<MakeEvaluation(member->m_alloc_alignment.get())<<");") - } - else - { - LINE(MakeMemberAccess(info, member, modifier)<<" = m_stream->Alloc<"<<typeDecl<<followingReferences<<">("<<modifier.GetAlignment()<<");") - } + if (computations.IsInTempBlock()) { + LINE("") + LINE(member->m_member->m_type_declaration->m_type->GetFullName() << "** toInsert = nullptr;") + LINE("if(ptr == PTR_INSERT)") + m_intendation++; + LINE("toInsert = m_stream->InsertPointer<" << member->m_member->m_type_declaration->m_type->GetFullName() << ">();") + m_intendation--; + LINE("") + } - if (computations.IsInTempBlock()) - { - LINE("") - LINE(member->m_member->m_type_declaration->m_type->GetFullName() << "** toInsert = nullptr;") - LINE("if(ptr == PTR_INSERT)") - m_intendation++; - LINE("toInsert = m_stream->InsertPointer<"<<member->m_member->m_type_declaration->m_type->GetFullName() << ">();") - m_intendation--; - LINE("") - } + LoadMember_TypeCheck(info, member, modifier, loadType); - LoadMember_TypeCheck(info, member, modifier, loadType); + if (computations.IsInTempBlock()) { + LINE("") + LINE("if(toInsert != nullptr)") + m_intendation++; + LINE("*toInsert = " << MakeTypeVarName(info->m_definition) << "->" << member->m_member->m_name << ";") + m_intendation--; + } + } - if (computations.IsInTempBlock()) - { - LINE("") - LINE("if(toInsert != nullptr)") - m_intendation++; - LINE("*toInsert = "<<MakeTypeVarName(info->m_definition)<<"->"<<member->m_member->m_name<<";") - m_intendation--; - } + static bool LoadMember_ShouldMakeReuse(StructureInformation *info, MemberInformation *member, const DeclarationModifierComputations &modifier, + const MemberLoadType loadType) { + if (loadType != MemberLoadType::ARRAY_POINTER && loadType != MemberLoadType::SINGLE_POINTER && loadType != MemberLoadType::POINTER_ARRAY) { + return false; } - static bool LoadMember_ShouldMakeReuse(StructureInformation* info, MemberInformation* member, const DeclarationModifierComputations& modifier, const MemberLoadType loadType) - { - if (loadType != MemberLoadType::ARRAY_POINTER - && loadType != MemberLoadType::SINGLE_POINTER - && loadType != MemberLoadType::POINTER_ARRAY) - { - return false; - } + if (loadType == MemberLoadType::POINTER_ARRAY && modifier.IsArray()) { + return false; + } - if (loadType == MemberLoadType::POINTER_ARRAY - && modifier.IsArray()) - { - return false; - } + return true; + } - return true; + void LoadMember_Reuse(StructureInformation *info, MemberInformation *member, const DeclarationModifierComputations &modifier, const MemberLoadType loadType) { + if (!LoadMember_ShouldMakeReuse(info, member, modifier, loadType) || !member->m_is_reusable) { + LoadMember_Alloc(info, member, modifier, loadType); + return; } - void LoadMember_Reuse(StructureInformation* info, MemberInformation* member, const DeclarationModifierComputations& modifier, const MemberLoadType loadType) - { - if (!LoadMember_ShouldMakeReuse(info, member, modifier, loadType) - || !member->m_is_reusable) - { - LoadMember_Alloc(info, member, modifier, loadType); - return; - } + const MemberComputations computations(member); + if (computations.IsInTempBlock()) { + LINE("if(" << MakeMemberAccess(info, member, modifier) << " == PTR_FOLLOWING || " << MakeMemberAccess(info, member, modifier) << " == PTR_INSERT)") + LINE("{") + m_intendation++; - const MemberComputations computations(member); - if (computations.IsInTempBlock()) - { - LINE("if("<<MakeMemberAccess(info, member, modifier)<<" == PTR_FOLLOWING || "<<MakeMemberAccess(info, member, modifier)<<" == PTR_INSERT)") - LINE("{") - m_intendation++; + LoadMember_Alloc(info, member, modifier, loadType); - LoadMember_Alloc(info, member, modifier, loadType); + m_intendation--; + LINE("}") + LINE("else") + LINE("{") + m_intendation++; - m_intendation--; - LINE("}") - LINE("else") - LINE("{") - m_intendation++; + LINE(MakeMemberAccess(info, member, modifier) << " = m_stream->ConvertOffsetToAlias(" << MakeMemberAccess(info, member, modifier) << ");") - LINE(MakeMemberAccess(info, member, modifier) << " = m_stream->ConvertOffsetToAlias(" << MakeMemberAccess(info, member, modifier) << ");") - - m_intendation--; - LINE("}") - } - else - { - LINE("if("<<MakeMemberAccess(info, member, modifier)<<" == PTR_FOLLOWING)") - LINE("{") - m_intendation++; + m_intendation--; + LINE("}") + } else { + LINE("if(" << MakeMemberAccess(info, member, modifier) << " == PTR_FOLLOWING)") + LINE("{") + m_intendation++; - LoadMember_Alloc(info, member, modifier, loadType); + LoadMember_Alloc(info, member, modifier, loadType); - m_intendation--; - LINE("}") - LINE("else") - LINE("{") - m_intendation++; + m_intendation--; + LINE("}") + LINE("else") + LINE("{") + m_intendation++; - LINE(MakeMemberAccess(info, member, modifier)<< " = m_stream->ConvertOffsetToPointer("<<MakeMemberAccess(info, member, modifier)<<");") + LINE(MakeMemberAccess(info, member, modifier) << " = m_stream->ConvertOffsetToPointer(" << MakeMemberAccess(info, member, modifier) << ");") - if (member->m_is_script_string && loadType == MemberLoadType::ARRAY_POINTER) - { - LINE("MarkScriptStringArrayAsUsed(" << MakeMemberAccess(info, member, modifier) << ", " << MakeEvaluation(modifier.GetArrayPointerCountEvaluation()) << ");") - } + if (member->m_is_script_string && loadType == MemberLoadType::ARRAY_POINTER) { + LINE("MarkScriptStringArrayAsUsed(" << MakeMemberAccess(info, member, modifier) << ", " << MakeEvaluation(modifier.GetArrayPointerCountEvaluation()) + << ");") + } - m_intendation--; - LINE("}") - } + m_intendation--; + LINE("}") } + } - static bool LoadMember_ShouldMakePointerCheck(StructureInformation* info, MemberInformation* member, const DeclarationModifierComputations& modifier, MemberLoadType loadType) - { - if (loadType != MemberLoadType::ARRAY_POINTER - && loadType != MemberLoadType::POINTER_ARRAY - && loadType != MemberLoadType::SINGLE_POINTER) - { - return false; - } - - if (loadType == MemberLoadType::POINTER_ARRAY) - { - return !modifier.IsArray(); - } + static bool LoadMember_ShouldMakePointerCheck(StructureInformation *info, MemberInformation *member, const DeclarationModifierComputations &modifier, + MemberLoadType loadType) { + if (loadType != MemberLoadType::ARRAY_POINTER && loadType != MemberLoadType::POINTER_ARRAY && loadType != MemberLoadType::SINGLE_POINTER) { + return false; + } - if (member->m_is_string) - { - return false; - } + if (loadType == MemberLoadType::POINTER_ARRAY) { + return !modifier.IsArray(); + } - return true; + if (member->m_is_string) { + return false; } - void LoadMember_PointerCheck(StructureInformation* info, MemberInformation* member, const DeclarationModifierComputations& modifier, const MemberLoadType loadType) - { - if (LoadMember_ShouldMakePointerCheck(info, member, modifier, loadType)) - { - LINE("if (" << MakeMemberAccess(info, member, modifier) << ")") - LINE("{") - m_intendation++; + return true; + } - LoadMember_Reuse(info, member, modifier, loadType); + void LoadMember_PointerCheck(StructureInformation *info, MemberInformation *member, const DeclarationModifierComputations &modifier, + const MemberLoadType loadType) { + if (LoadMember_ShouldMakePointerCheck(info, member, modifier, loadType)) { + LINE("if (" << MakeMemberAccess(info, member, modifier) << ")") + LINE("{") + m_intendation++; - m_intendation--; - LINE("}") - } - else - { - LoadMember_Reuse(info, member, modifier, loadType); - } + LoadMember_Reuse(info, member, modifier, loadType); + + m_intendation--; + LINE("}") + } else { + LoadMember_Reuse(info, member, modifier, loadType); } + } - void LoadMember_Block(StructureInformation* info, MemberInformation* member, const DeclarationModifierComputations& modifier, MemberLoadType loadType) - { - const MemberComputations computations(member); + void LoadMember_Block(StructureInformation *info, MemberInformation *member, const DeclarationModifierComputations &modifier, MemberLoadType loadType) { + const MemberComputations computations(member); - const auto notInDefaultNormalBlock = computations.IsNotInDefaultNormalBlock(); - if (notInDefaultNormalBlock) - { - LINE("m_stream->PushBlock(" << member->m_fast_file_block->m_name << ");") - } + const auto notInDefaultNormalBlock = computations.IsNotInDefaultNormalBlock(); + if (notInDefaultNormalBlock) { + LINE("m_stream->PushBlock(" << member->m_fast_file_block->m_name << ");") + } - LoadMember_PointerCheck(info, member, modifier, loadType); + LoadMember_PointerCheck(info, member, modifier, loadType); - if (notInDefaultNormalBlock) - { - LINE("m_stream->PopBlock();") - } + if (notInDefaultNormalBlock) { + LINE("m_stream->PopBlock();") } + } + + void LoadMember_ReferenceArray(StructureInformation *info, MemberInformation *member, const DeclarationModifierComputations &modifier) { + auto first = true; + for (const auto &entry : modifier.GetArrayEntries()) { + if (first) { + first = false; + } else { + LINE("") + } - void LoadMember_ReferenceArray(StructureInformation* info, MemberInformation* member, const DeclarationModifierComputations& modifier) - { - auto first = true; - for (const auto& entry : modifier.GetArrayEntries()) - { - if (first) - { - first = false; - } - else - { - LINE("") - } - - LoadMember_Reference(info, member, entry); - } + LoadMember_Reference(info, member, entry); } - - void LoadMember_Reference(StructureInformation* info, MemberInformation* member, const DeclarationModifierComputations& modifier) - { - if (modifier.IsDynamicArray()) - { - LoadMember_Block(info, member, modifier, MemberLoadType::DYNAMIC_ARRAY); - } - else if (modifier.IsSinglePointer()) - { - LoadMember_Block(info, member, modifier, MemberLoadType::SINGLE_POINTER); - } - else if (modifier.IsArrayPointer()) - { - LoadMember_Block(info, member, modifier, MemberLoadType::ARRAY_POINTER); - } - else if (modifier.IsPointerArray()) - { - LoadMember_Block(info, member, modifier, MemberLoadType::POINTER_ARRAY); - } - else if (modifier.IsArray() && modifier.GetNextDeclarationModifier() == nullptr) - { - LoadMember_Block(info, member, modifier, MemberLoadType::EMBEDDED_ARRAY); - } - else if (modifier.GetDeclarationModifier() == nullptr) - { - LoadMember_Block(info, member, modifier, MemberLoadType::EMBEDDED); - } - else if (modifier.IsArray()) - { - LoadMember_ReferenceArray(info, member, modifier); - } - else - { - assert(false); - LINE("#error LoadMemberReference failed @ "<<member->m_member->m_name) - } + } + + void LoadMember_Reference(StructureInformation *info, MemberInformation *member, const DeclarationModifierComputations &modifier) { + if (modifier.IsDynamicArray()) { + LoadMember_Block(info, member, modifier, MemberLoadType::DYNAMIC_ARRAY); + } else if (modifier.IsSinglePointer()) { + LoadMember_Block(info, member, modifier, MemberLoadType::SINGLE_POINTER); + } else if (modifier.IsArrayPointer()) { + LoadMember_Block(info, member, modifier, MemberLoadType::ARRAY_POINTER); + } else if (modifier.IsPointerArray()) { + LoadMember_Block(info, member, modifier, MemberLoadType::POINTER_ARRAY); + } else if (modifier.IsArray() && modifier.GetNextDeclarationModifier() == nullptr) { + LoadMember_Block(info, member, modifier, MemberLoadType::EMBEDDED_ARRAY); + } else if (modifier.GetDeclarationModifier() == nullptr) { + LoadMember_Block(info, member, modifier, MemberLoadType::EMBEDDED); + } else if (modifier.IsArray()) { + LoadMember_ReferenceArray(info, member, modifier); + } else { + assert(false); + LINE("#error LoadMemberReference failed @ " << member->m_member->m_name) } + } - void LoadMember_Condition_Struct(StructureInformation* info, MemberInformation* member) - { - LINE("") - if (member->m_condition) - { - LINE("if("<<MakeEvaluation(member->m_condition.get())<<")") - LINE("{") - m_intendation++; + void LoadMember_Condition_Struct(StructureInformation *info, MemberInformation *member) { + LINE("") + if (member->m_condition) { + LINE("if(" << MakeEvaluation(member->m_condition.get()) << ")") + LINE("{") + m_intendation++; - LoadMember_Reference(info, member, DeclarationModifierComputations(member)); + LoadMember_Reference(info, member, DeclarationModifierComputations(member)); - m_intendation--; - LINE("}") - } - else - { - LoadMember_Reference(info, member, DeclarationModifierComputations(member)); - } - } - - void LoadMember_Condition_Union(StructureInformation* info, MemberInformation* member) - { - const MemberComputations computations(member); - - if (computations.IsFirstMember()) - { - LINE("") - if (member->m_condition) - { - LINE("if("<<MakeEvaluation(member->m_condition.get())<<")") - LINE("{") - m_intendation++; - - LoadMember_Reference(info, member, DeclarationModifierComputations(member)); - - m_intendation--; - LINE("}") - } - else - { - LoadMember_Reference(info, member, DeclarationModifierComputations(member)); - } - } - else if (computations.IsLastMember()) - { - if (member->m_condition) - { - LINE("else if("<<MakeEvaluation(member->m_condition.get())<<")") - LINE("{") - m_intendation++; - - LoadMember_Reference(info, member, DeclarationModifierComputations(member)); - - m_intendation--; - LINE("}") - } - else - { - LINE("else") - LINE("{") - m_intendation++; - - LoadMember_Reference(info, member, DeclarationModifierComputations(member)); - - m_intendation--; - LINE("}") - } - } - else - { - if (member->m_condition) - { - LINE("else if("<<MakeEvaluation(member->m_condition.get())<<")") - LINE("{") - m_intendation++; - - LoadMember_Reference(info, member, DeclarationModifierComputations(member)); - - m_intendation--; - LINE("}") - } - else - { - LINE("#error Middle member of union must have condition ("<<member->m_member->m_name<<")") - } - } + m_intendation--; + LINE("}") + } else { + LoadMember_Reference(info, member, DeclarationModifierComputations(member)); } + } - void PrintLoadMemberIfNeedsTreatment(StructureInformation* info, MemberInformation* member) - { - const MemberComputations computations(member); - if (computations.ShouldIgnore()) - return; - - if (member->m_is_string - || member->m_is_script_string - || computations.ContainsNonEmbeddedReference() - || member->m_type && !member->m_type->m_is_leaf - || computations.IsAfterPartialLoad()) - { - if (info->m_definition->GetType() == DataDefinitionType::UNION) - LoadMember_Condition_Union(info, member); - else - LoadMember_Condition_Struct(info, member); - } - } + void LoadMember_Condition_Union(StructureInformation *info, MemberInformation *member) { + const MemberComputations computations(member); - void PrintLoadMethod(StructureInformation* info) - { - const StructureComputations computations(info); - LINE("void " << LoaderClassName(m_env.m_asset) << "::Load_" << info->m_definition->m_name << "(const bool atStreamStart)") + if (computations.IsFirstMember()) { + LINE("") + if (member->m_condition) { + LINE("if(" << MakeEvaluation(member->m_condition.get()) << ")") LINE("{") m_intendation++; - LINE("assert(" <<MakeTypeVarName(info->m_definition) << " != nullptr);") - - auto* dynamicMember = computations.GetDynamicMember(); - if (!(info->m_definition->GetType() == DataDefinitionType::UNION && dynamicMember)) - { - LINE("") - LINE("if(atStreamStart)") - m_intendation++; - - if (dynamicMember == nullptr) - { - LINE("m_stream->Load<"<<info->m_definition->GetFullName()<<">("<<MakeTypeVarName(info->m_definition)<<"); // Size: "<<info->m_definition->GetSize()) - } - else - { - LINE("m_stream->LoadPartial<"<<info->m_definition->GetFullName()<<">("<<MakeTypeVarName(info->m_definition)<<", offsetof("<<info->m_definition->GetFullName() - <<", "<<dynamicMember->m_member->m_name<<"));") - } - - m_intendation--; - } - else - { - LINE("assert(atStreamStart);") - } - - if (computations.IsAsset()) - { - LINE("") - LINE("m_stream->PushBlock(" << m_env.m_default_normal_block->m_name << ");") - } - else if (info->m_block) - { - LINE("") - LINE("m_stream->PushBlock("<<info->m_block->m_name<<");") - } - - for (const auto& member : info->m_ordered_members) - { - PrintLoadMemberIfNeedsTreatment(info, member.get()); - } - - if (info->m_block || computations.IsAsset()) - { - LINE("") - LINE("m_stream->PopBlock();") - } + LoadMember_Reference(info, member, DeclarationModifierComputations(member)); m_intendation--; LINE("}") - } - - void PrintLoadPtrMethod(StructureInformation* info) - { - const bool inTemp = info->m_block && info->m_block->m_type == FastFileBlockType::TEMP; - LINE("void "<<LoaderClassName(m_env.m_asset)<<"::LoadPtr_"<<MakeSafeTypeName(info->m_definition)<<"(const bool atStreamStart)") + } else { + LoadMember_Reference(info, member, DeclarationModifierComputations(member)); + } + } else if (computations.IsLastMember()) { + if (member->m_condition) { + LINE("else if(" << MakeEvaluation(member->m_condition.get()) << ")") LINE("{") m_intendation++; - LINE("assert("<<MakeTypePtrVarName(info->m_definition)<<" != nullptr);") - LINE("") + LoadMember_Reference(info, member, DeclarationModifierComputations(member)); - LINE("if(atStreamStart)") - m_intendation++; - LINE("m_stream->Load<"<<info->m_definition->GetFullName()<<"*>("<< MakeTypePtrVarName(info->m_definition)<<");") m_intendation--; - - LINE("") - if (inTemp) - { - LINE("m_stream->PushBlock(" << m_env.m_default_temp_block->m_name << ");") - LINE("") - } - - LINE("if(*"<< MakeTypePtrVarName(info->m_definition)<<" != nullptr)") - LINE("{") - m_intendation++; - - if (inTemp) - { - LINE("if(*" << MakeTypePtrVarName(info->m_definition) << " == PTR_FOLLOWING || *" << MakeTypePtrVarName(info->m_definition) << " == PTR_INSERT)") - } - else - { - LINE("if(*" << MakeTypePtrVarName(info->m_definition) << " == PTR_FOLLOWING)") - } + LINE("}") + } else { + LINE("else") LINE("{") m_intendation++; - if (inTemp) - { - LINE(info->m_definition->GetFullName() << "* ptr = *" << MakeTypePtrVarName(info->m_definition) << ";") - } - LINE("*" << MakeTypePtrVarName(info->m_definition) << " = m_stream->Alloc<" << info->m_definition->GetFullName() << ">("<< info->m_definition->GetAlignment() <<");") - - if (inTemp) - { - LINE("") - LINE(info->m_definition->GetFullName() << "** toInsert = nullptr;") - LINE("if(ptr == PTR_INSERT)") - m_intendation++; - LINE("toInsert = m_stream->InsertPointer<" << info->m_definition->GetFullName() << ">();") - m_intendation--; - } - - auto startLoadSection = true; - - if (!info->m_is_leaf) - { - if (startLoadSection) - { - startLoadSection = false; - LINE("") - } - LINE(MakeTypeVarName(info->m_definition)<<" = *"<< MakeTypePtrVarName(info->m_definition)<<";") - LINE("Load_"<<MakeSafeTypeName(info->m_definition)<<"(true);") - } - else - { - LINE("#error Ptr method cannot have leaf type") - } - - if (info->m_post_load_action) - { - LINE("") - LINE(MakeCustomActionCall(info->m_post_load_action.get())) - } - - if (StructureComputations(info).IsAsset()) - { - LINE("") - LINE("LoadAsset_"<<MakeSafeTypeName(info->m_definition)<<"("<<MakeTypePtrVarName(info->m_definition)<<");") - } - - if (inTemp) - { - if (!startLoadSection) - { - LINE("") - } - - LINE("if(toInsert != nullptr)") - m_intendation++; - LINE("*toInsert = *" << MakeTypePtrVarName(info->m_definition) << ";") - m_intendation--; - } + LoadMember_Reference(info, member, DeclarationModifierComputations(member)); m_intendation--; LINE("}") - LINE("else") + } + } else { + if (member->m_condition) { + LINE("else if(" << MakeEvaluation(member->m_condition.get()) << ")") LINE("{") m_intendation++; - if (inTemp) - { - LINE("*" << MakeTypePtrVarName(info->m_definition) << " = m_stream->ConvertOffsetToAlias(*" << MakeTypePtrVarName(info->m_definition) << ");") - } - else - { - LINE("*" << MakeTypePtrVarName(info->m_definition) << " = m_stream->ConvertOffsetToPointer(*" << MakeTypePtrVarName(info->m_definition) << ");") - } + LoadMember_Reference(info, member, DeclarationModifierComputations(member)); m_intendation--; LINE("}") + } else { + LINE("#error Middle member of union must have condition (" << member->m_member->m_name << ")") + } + } + } + + void PrintLoadMemberIfNeedsTreatment(StructureInformation *info, MemberInformation *member) { + const MemberComputations computations(member); + if (computations.ShouldIgnore()) + return; + + if (member->m_is_string || member->m_is_script_string || computations.ContainsNonEmbeddedReference() || member->m_type && !member->m_type->m_is_leaf || + computations.IsAfterPartialLoad()) { + if (info->m_definition->GetType() == DataDefinitionType::UNION) + LoadMember_Condition_Union(info, member); + else + LoadMember_Condition_Struct(info, member); + } + } + + void PrintLoadMethod(StructureInformation *info) { + const StructureComputations computations(info); + LINE("void " << LoaderClassName(m_env.m_asset) << "::Load_" << info->m_definition->m_name << "(const bool atStreamStart)") + LINE("{") + m_intendation++; + + LINE("assert(" << MakeTypeVarName(info->m_definition) << " != nullptr);") + + auto *dynamicMember = computations.GetDynamicMember(); + if (!(info->m_definition->GetType() == DataDefinitionType::UNION && dynamicMember)) { + LINE("") + LINE("if(atStreamStart)") + m_intendation++; + + if (dynamicMember == nullptr) { + LINE("m_stream->Load<" << info->m_definition->GetFullName() << ">(" << MakeTypeVarName(info->m_definition) + << "); // Size: " << info->m_definition->GetSize()) + } else { + LINE("m_stream->LoadPartial<" << info->m_definition->GetFullName() << ">(" << MakeTypeVarName(info->m_definition) << ", offsetof(" + << info->m_definition->GetFullName() << ", " << dynamicMember->m_member->m_name << "));") + } + + m_intendation--; + } else { + LINE("assert(atStreamStart);") + } - m_intendation--; - LINE("}") + if (computations.IsAsset()) { + LINE("") + LINE("m_stream->PushBlock(" << m_env.m_default_normal_block->m_name << ");") + } else if (info->m_block) { + LINE("") + LINE("m_stream->PushBlock(" << info->m_block->m_name << ");") + } - if (inTemp) - { - LINE("") - LINE("m_stream->PopBlock();") - } + for (const auto &member : info->m_ordered_members) { + PrintLoadMemberIfNeedsTreatment(info, member.get()); + } - m_intendation--; - LINE("}") + if (info->m_block || computations.IsAsset()) { + LINE("") + LINE("m_stream->PopBlock();") } - void PrintLoadAssetMethod(StructureInformation* info) - { - LINE("void " << LoaderClassName(m_env.m_asset) << "::LoadAsset_" << MakeSafeTypeName(info->m_definition) << "(" << info->m_definition->GetFullName() << "** pAsset)") - LINE("{") - m_intendation++; + m_intendation--; + LINE("}") + } - LINE("assert(pAsset != nullptr);") - LINE("m_asset_info = reinterpret_cast<XAssetInfo<"<<info->m_definition->GetFullName()<<">*>(LinkAsset(GetAssetName(*pAsset), *pAsset));") - LINE("*pAsset = m_asset_info->Asset();") + void PrintLoadPtrMethod(StructureInformation *info) { + const bool inTemp = info->m_block && info->m_block->m_type == FastFileBlockType::TEMP; + LINE("void " << LoaderClassName(m_env.m_asset) << "::LoadPtr_" << MakeSafeTypeName(info->m_definition) << "(const bool atStreamStart)") + LINE("{") + m_intendation++; - m_intendation--; - LINE("}") + LINE("assert(" << MakeTypePtrVarName(info->m_definition) << " != nullptr);") + LINE("") + + LINE("if(atStreamStart)") + m_intendation++; + LINE("m_stream->Load<" << info->m_definition->GetFullName() << "*>(" << MakeTypePtrVarName(info->m_definition) << ");") + m_intendation--; + + LINE("") + if (inTemp) { + LINE("m_stream->PushBlock(" << m_env.m_default_temp_block->m_name << ");") + LINE("") } - void PrintMainLoadMethod() - { - LINE("XAssetInfo<" << m_env.m_asset->m_definition->GetFullName() << ">* " << LoaderClassName(m_env.m_asset) << "::Load(" << m_env.m_asset->m_definition->GetFullName() << "** pAsset)") - LINE("{") - m_intendation++; + LINE("if(*" << MakeTypePtrVarName(info->m_definition) << " != nullptr)") + LINE("{") + m_intendation++; - LINE("assert(pAsset != nullptr);") - LINE("") - LINE("m_asset_info = nullptr;") - LINE("") - LINE(MakeTypePtrVarName(m_env.m_asset->m_definition) << " = pAsset;") - LINE("LoadPtr_" << MakeSafeTypeName(m_env.m_asset->m_definition) << "(false);") - LINE("") - LINE("if(m_asset_info == nullptr && *pAsset != nullptr)") - m_intendation++; - LINE("m_asset_info = reinterpret_cast<XAssetInfo<"<<m_env.m_asset->m_definition->GetFullName()<<">*>(GetAssetInfo(GetAssetName(*pAsset)));") - m_intendation--; - LINE("") - LINE("return m_asset_info;") + if (inTemp) { + LINE("if(*" << MakeTypePtrVarName(info->m_definition) << " == PTR_FOLLOWING || *" << MakeTypePtrVarName(info->m_definition) << " == PTR_INSERT)") + } else { + LINE("if(*" << MakeTypePtrVarName(info->m_definition) << " == PTR_FOLLOWING)") + } + LINE("{") + m_intendation++; - m_intendation--; - LINE("}") + if (inTemp) { + LINE(info->m_definition->GetFullName() << "* ptr = *" << MakeTypePtrVarName(info->m_definition) << ";") + } + LINE("*" << MakeTypePtrVarName(info->m_definition) << " = m_stream->Alloc<" << info->m_definition->GetFullName() << ">(" + << info->m_definition->GetAlignment() << ");") + + if (inTemp) { + LINE("") + LINE(info->m_definition->GetFullName() << "** toInsert = nullptr;") + LINE("if(ptr == PTR_INSERT)") + m_intendation++; + LINE("toInsert = m_stream->InsertPointer<" << info->m_definition->GetFullName() << ">();") + m_intendation--; } - void PrintGetNameMethod() - { - LINE("std::string " << LoaderClassName(m_env.m_asset) << "::GetAssetName(" << m_env.m_asset->m_definition->GetFullName() << "* pAsset)") - LINE("{") - m_intendation++; + auto startLoadSection = true; - if (!m_env.m_asset->m_name_chain.empty()) - { - LINE_START("return pAsset") - - auto first = true; - for (auto* member : m_env.m_asset->m_name_chain) - { - if (first) - { - first = false; - LINE_MIDDLE("->"<<member->m_member->m_name) - } - else - { - LINE_MIDDLE("." << member->m_member->m_name) - } - } - LINE_END(";") - } - else - { - LINE("return \""<<m_env.m_asset->m_definition->m_name<<"\";") - } + if (!info->m_is_leaf) { + if (startLoadSection) { + startLoadSection = false; + LINE("") + } + LINE(MakeTypeVarName(info->m_definition) << " = *" << MakeTypePtrVarName(info->m_definition) << ";") + LINE("Load_" << MakeSafeTypeName(info->m_definition) << "(true);") + } else { + LINE("#error Ptr method cannot have leaf type") + } - m_intendation--; - LINE("}") + if (info->m_post_load_action) { + LINE("") + LINE(MakeCustomActionCall(info->m_post_load_action.get())) } -public: - Internal(std::ostream& stream, RenderingContext* context) - : BaseTemplate(stream, context) - { - } - - void Header() - { - LINE("// ====================================================================") - LINE("// This file has been generated by ZoneCodeGenerator.") - LINE("// Do not modify. ") - LINE("// Any changes will be discarded when regenerating.") - LINE("// ====================================================================") - LINE("") - LINE("#pragma once") - LINE("") - LINE("#include \"Loading/AssetLoader.h\"") - LINE("#include \"Game/" << m_env.m_game << "/" << m_env.m_game << ".h\"") - if (m_env.m_has_actions) - { - LINE("#include \"Game/" << m_env.m_game << "/XAssets/" << Lower(m_env.m_asset->m_definition->m_name) << "/" << Lower(m_env.m_asset->m_definition->m_name) << "_actions.h\"") - } - LINE("#include <string>") - LINE("") - LINE("namespace " << m_env.m_game) - LINE("{") - m_intendation++; - LINE("class " << LoaderClassName(m_env.m_asset) << " final : public AssetLoader") - LINE("{") - m_intendation++; + if (StructureComputations(info).IsAsset()) { + LINE("") + LINE("LoadAsset_" << MakeSafeTypeName(info->m_definition) << "(" << MakeTypePtrVarName(info->m_definition) << ");") + } - LINE("XAssetInfo<"<<m_env.m_asset->m_definition->GetFullName()<<">* m_asset_info;") - if (m_env.m_has_actions) - { - LINE("Actions_"<<m_env.m_asset->m_definition->m_name<<" m_actions;") - } - LINE(VariableDecl(m_env.m_asset->m_definition)) - LINE(PointerVariableDecl(m_env.m_asset->m_definition)) + if (inTemp) { + if (!startLoadSection) { LINE("") + } - // Variable Declarations: type varType; - for (auto* type : m_env.m_used_types) - { - if (type->m_info && !type->m_info->m_definition->m_anonymous && !type->m_info->m_is_leaf && !StructureComputations(type->m_info).IsAsset()) - { - LINE(VariableDecl(type->m_type)) - } - } - for (auto* type : m_env.m_used_types) - { - if (type->m_pointer_array_reference_exists && !type->m_is_context_asset) - { - LINE(PointerVariableDecl(type->m_type)) - } - } + LINE("if(toInsert != nullptr)") + m_intendation++; + LINE("*toInsert = *" << MakeTypePtrVarName(info->m_definition) << ";") + m_intendation--; + } - LINE("") + m_intendation--; + LINE("}") + LINE("else") + LINE("{") + m_intendation++; - // Method Declarations - for (auto* type : m_env.m_used_types) - { - if (type->m_pointer_array_reference_exists) - { - PrintHeaderPtrArrayLoadMethodDeclaration(type->m_type); - } - } - for (auto* type : m_env.m_used_types) - { - if (type->m_array_reference_exists && type->m_info && !type->m_info->m_is_leaf && type->m_non_runtime_reference_exists) - { - PrintHeaderArrayLoadMethodDeclaration(type->m_type); - } - } - for (auto* type : m_env.m_used_structures) - { - if (type->m_non_runtime_reference_exists && !type->m_info->m_is_leaf && !StructureComputations(type->m_info).IsAsset()) - { - PrintHeaderLoadMethodDeclaration(type->m_info); - } - } - PrintHeaderLoadMethodDeclaration(m_env.m_asset); - PrintHeaderTempPtrLoadMethodDeclaration(m_env.m_asset); - PrintHeaderAssetLoadMethodDeclaration(m_env.m_asset); - LINE("") - m_intendation--; - LINE("public:") - m_intendation++; - PrintHeaderConstructor(); - PrintHeaderMainLoadMethodDeclaration(m_env.m_asset); - PrintHeaderGetNameMethodDeclaration(m_env.m_asset); + if (inTemp) { + LINE("*" << MakeTypePtrVarName(info->m_definition) << " = m_stream->ConvertOffsetToAlias(*" << MakeTypePtrVarName(info->m_definition) << ");") + } else { + LINE("*" << MakeTypePtrVarName(info->m_definition) << " = m_stream->ConvertOffsetToPointer(*" << MakeTypePtrVarName(info->m_definition) << ");") + } - m_intendation--; - LINE("};") - m_intendation--; - LINE("}") + m_intendation--; + LINE("}") + + m_intendation--; + LINE("}") + + if (inTemp) { + LINE("") + LINE("m_stream->PopBlock();") } - void Source() - { - LINE("// ====================================================================") - LINE("// This file has been generated by ZoneCodeGenerator.") - LINE("// Do not modify. ") - LINE("// Any changes will be discarded when regenerating.") - LINE("// ====================================================================") - LINE("") - LINE("#include \""<<Lower(m_env.m_asset->m_definition->m_name)<<"_load_db.h\"") - LINE("#include <cassert>") - LINE("") + m_intendation--; + LINE("}") + } + + void PrintLoadAssetMethod(StructureInformation *info) { + LINE("void " << LoaderClassName(m_env.m_asset) << "::LoadAsset_" << MakeSafeTypeName(info->m_definition) << "(" << info->m_definition->GetFullName() + << "** pAsset)") + LINE("{") + m_intendation++; + + LINE("assert(pAsset != nullptr);") + LINE("m_asset_info = reinterpret_cast<XAssetInfo<" << info->m_definition->GetFullName() << ">*>(LinkAsset(GetAssetName(*pAsset), *pAsset));") + LINE("*pAsset = m_asset_info->Asset();") + + m_intendation--; + LINE("}") + } + + void PrintMainLoadMethod() { + LINE("XAssetInfo<" << m_env.m_asset->m_definition->GetFullName() << ">* " << LoaderClassName(m_env.m_asset) << "::Load(" + << m_env.m_asset->m_definition->GetFullName() << "** pAsset)") + LINE("{") + m_intendation++; + + LINE("assert(pAsset != nullptr);") + LINE("") + LINE("m_asset_info = nullptr;") + LINE("") + LINE(MakeTypePtrVarName(m_env.m_asset->m_definition) << " = pAsset;") + LINE("LoadPtr_" << MakeSafeTypeName(m_env.m_asset->m_definition) << "(false);") + LINE("") + LINE("if(m_asset_info == nullptr && *pAsset != nullptr)") + m_intendation++; + LINE("m_asset_info = reinterpret_cast<XAssetInfo<" << m_env.m_asset->m_definition->GetFullName() << ">*>(GetAssetInfo(GetAssetName(*pAsset)));") + m_intendation--; + LINE("") + LINE("return m_asset_info;") + + m_intendation--; + LINE("}") + } + + void PrintGetNameMethod() { + LINE("std::string " << LoaderClassName(m_env.m_asset) << "::GetAssetName(" << m_env.m_asset->m_definition->GetFullName() << "* pAsset)") + LINE("{") + m_intendation++; + + if (!m_env.m_asset->m_name_chain.empty()) { + LINE_START("return pAsset") + + auto first = true; + for (auto *member : m_env.m_asset->m_name_chain) { + if (first) { + first = false; + LINE_MIDDLE("->" << member->m_member->m_name) + } else { + LINE_MIDDLE("." << member->m_member->m_name) + } + } + LINE_END(";") + } else { + LINE("return \"" << m_env.m_asset->m_definition->m_name << "\";") + } - if (!m_env.m_referenced_assets.empty()) - { - LINE("// Referenced Assets:") - for (auto* type : m_env.m_referenced_assets) - { - LINE("#include \"../"<<Lower(type->m_type->m_name)<<"/"<<Lower(type->m_type->m_name)<<"_load_db.h\"") - } - LINE("") - } - LINE("using namespace " << m_env.m_game << ";") - LINE("") - PrintConstructorMethod(); - - for (auto* type : m_env.m_used_types) - { - if (type->m_pointer_array_reference_exists) - { - LINE("") - PrintLoadPtrArrayMethod(type->m_type, type->m_info, type->m_pointer_array_reference_is_reusable); - } - } - for (auto* type : m_env.m_used_types) - { - if (type->m_array_reference_exists && type->m_info && !type->m_info->m_is_leaf && type->m_non_runtime_reference_exists) - { - LINE("") - PrintLoadArrayMethod(type->m_type, type->m_info); - } - } - for (auto* type : m_env.m_used_structures) - { - if (type->m_non_runtime_reference_exists && !type->m_info->m_is_leaf && !StructureComputations(type->m_info).IsAsset()) - { - LINE("") - PrintLoadMethod(type->m_info); - } - } - LINE("") - PrintLoadMethod(m_env.m_asset); - LINE("") - PrintLoadPtrMethod(m_env.m_asset); + m_intendation--; + LINE("}") + } + +public: + Internal(std::ostream &stream, RenderingContext *context) : BaseTemplate(stream, context) {} + + void Header() { + LINE("// ====================================================================") + LINE("// This file has been generated by ZoneCodeGenerator.") + LINE("// Do not modify. ") + LINE("// Any changes will be discarded when regenerating.") + LINE("// ====================================================================") + LINE("") + LINE("#pragma once") + LINE("") + LINE("#include \"Loading/AssetLoader.h\"") + LINE("#include \"Game/" << m_env.m_game << "/" << m_env.m_game << ".h\"") + if (m_env.m_has_actions) { + LINE("#include \"Game/" << m_env.m_game << "/XAssets/" << Lower(m_env.m_asset->m_definition->m_name) << "/" << Lower(m_env.m_asset->m_definition->m_name) + << "_actions.h\"") + } + LINE("#include <string>") + LINE("") + LINE("namespace " << m_env.m_game) + LINE("{") + m_intendation++; + LINE("class " << LoaderClassName(m_env.m_asset) << " final : public AssetLoader") + LINE("{") + m_intendation++; + + LINE("XAssetInfo<" << m_env.m_asset->m_definition->GetFullName() << ">* m_asset_info;") + if (m_env.m_has_actions) { + LINE("Actions_" << m_env.m_asset->m_definition->m_name << " m_actions;") + } + LINE(VariableDecl(m_env.m_asset->m_definition)) + LINE(PointerVariableDecl(m_env.m_asset->m_definition)) + LINE("") + + // Variable Declarations: type varType; + for (auto *type : m_env.m_used_types) { + if (type->m_info && !type->m_info->m_definition->m_anonymous && !type->m_info->m_is_leaf && !StructureComputations(type->m_info).IsAsset()) { + LINE(VariableDecl(type->m_type)) + } + } + for (auto *type : m_env.m_used_types) { + if (type->m_pointer_array_reference_exists && !type->m_is_context_asset) { + LINE(PointerVariableDecl(type->m_type)) + } + } + + LINE("") + + // Method Declarations + for (auto *type : m_env.m_used_types) { + if (type->m_pointer_array_reference_exists) { + PrintHeaderPtrArrayLoadMethodDeclaration(type->m_type); + } + } + for (auto *type : m_env.m_used_types) { + if (type->m_array_reference_exists && type->m_info && !type->m_info->m_is_leaf && type->m_non_runtime_reference_exists) { + PrintHeaderArrayLoadMethodDeclaration(type->m_type); + } + } + for (auto *type : m_env.m_used_structures) { + if (type->m_non_runtime_reference_exists && !type->m_info->m_is_leaf && !StructureComputations(type->m_info).IsAsset()) { + PrintHeaderLoadMethodDeclaration(type->m_info); + } + } + PrintHeaderLoadMethodDeclaration(m_env.m_asset); + PrintHeaderTempPtrLoadMethodDeclaration(m_env.m_asset); + PrintHeaderAssetLoadMethodDeclaration(m_env.m_asset); + LINE("") + m_intendation--; + LINE("public:") + m_intendation++; + PrintHeaderConstructor(); + PrintHeaderMainLoadMethodDeclaration(m_env.m_asset); + PrintHeaderGetNameMethodDeclaration(m_env.m_asset); + + m_intendation--; + LINE("};") + m_intendation--; + LINE("}") + } + + void Source() { + LINE("// ====================================================================") + LINE("// This file has been generated by ZoneCodeGenerator.") + LINE("// Do not modify. ") + LINE("// Any changes will be discarded when regenerating.") + LINE("// ====================================================================") + LINE("") + LINE("#include \"" << Lower(m_env.m_asset->m_definition->m_name) << "_load_db.h\"") + LINE("#include <cassert>") + LINE("") + + if (!m_env.m_referenced_assets.empty()) { + LINE("// Referenced Assets:") + for (auto *type : m_env.m_referenced_assets) { + LINE("#include \"../" << Lower(type->m_type->m_name) << "/" << Lower(type->m_type->m_name) << "_load_db.h\"") + } + LINE("") + } + LINE("using namespace " << m_env.m_game << ";") + LINE("") + PrintConstructorMethod(); + + for (auto *type : m_env.m_used_types) { + if (type->m_pointer_array_reference_exists) { LINE("") - PrintLoadAssetMethod(m_env.m_asset); + PrintLoadPtrArrayMethod(type->m_type, type->m_info, type->m_pointer_array_reference_is_reusable); + } + } + for (auto *type : m_env.m_used_types) { + if (type->m_array_reference_exists && type->m_info && !type->m_info->m_is_leaf && type->m_non_runtime_reference_exists) { LINE("") - PrintMainLoadMethod(); + PrintLoadArrayMethod(type->m_type, type->m_info); + } + } + for (auto *type : m_env.m_used_structures) { + if (type->m_non_runtime_reference_exists && !type->m_info->m_is_leaf && !StructureComputations(type->m_info).IsAsset()) { LINE("") - PrintGetNameMethod(); + PrintLoadMethod(type->m_info); + } } + LINE("") + PrintLoadMethod(m_env.m_asset); + LINE("") + PrintLoadPtrMethod(m_env.m_asset); + LINE("") + PrintLoadAssetMethod(m_env.m_asset); + LINE("") + PrintMainLoadMethod(); + LINE("") + PrintGetNameMethod(); + } }; -std::vector<CodeTemplateFile> ZoneLoadTemplate::GetFilesToRender(RenderingContext* context) -{ - std::vector<CodeTemplateFile> files; +std::vector<CodeTemplateFile> ZoneLoadTemplate::GetFilesToRender(RenderingContext *context) { + std::vector<CodeTemplateFile> files; - auto assetName = context->m_asset->m_definition->m_name; - for (auto& c : assetName) - c = static_cast<char>(tolower(c)); + auto assetName = context->m_asset->m_definition->m_name; + for (auto &c : assetName) + c = static_cast<char>(tolower(c)); - { - std::ostringstream str; - str << assetName << '/' << assetName << "_load_db.h"; - files.emplace_back(str.str(), TAG_HEADER); - } + { + std::ostringstream str; + str << assetName << '/' << assetName << "_load_db.h"; + files.emplace_back(str.str(), TAG_HEADER); + } - { - std::ostringstream str; - str << assetName << '/' << assetName << "_load_db.cpp"; - files.emplace_back(str.str(), TAG_SOURCE); - } + { + std::ostringstream str; + str << assetName << '/' << assetName << "_load_db.cpp"; + files.emplace_back(str.str(), TAG_SOURCE); + } - return files; + return files; } -void ZoneLoadTemplate::RenderFile(std::ostream& stream, const int fileTag, RenderingContext* context) -{ - Internal internal(stream, context); +void ZoneLoadTemplate::RenderFile(std::ostream &stream, const int fileTag, RenderingContext *context) { + Internal internal(stream, context); - if (fileTag == TAG_HEADER) - { - internal.Header(); - } - else if (fileTag == TAG_SOURCE) - { - internal.Source(); - } - else - { - std::cout << "Unknown tag for ZoneLoadTemplate: " << fileTag << "\n"; - } + if (fileTag == TAG_HEADER) { + internal.Header(); + } else if (fileTag == TAG_SOURCE) { + internal.Source(); + } else { + std::cout << "Unknown tag for ZoneLoadTemplate: " << fileTag << "\n"; + } } diff --git a/src/ZoneCodeGeneratorLib/Generating/Templates/ZoneLoadTemplate.h b/src/ZoneCodeGeneratorLib/Generating/Templates/ZoneLoadTemplate.h index b4c743a78..703a2252d 100644 --- a/src/ZoneCodeGeneratorLib/Generating/Templates/ZoneLoadTemplate.h +++ b/src/ZoneCodeGeneratorLib/Generating/Templates/ZoneLoadTemplate.h @@ -1,14 +1,13 @@ #pragma once #include "Generating/ICodeTemplate.h" -class ZoneLoadTemplate final : public ICodeTemplate -{ - static constexpr int TAG_HEADER = 1; - static constexpr int TAG_SOURCE = 2; +class ZoneLoadTemplate final : public ICodeTemplate { + static constexpr int TAG_HEADER = 1; + static constexpr int TAG_SOURCE = 2; - class Internal; + class Internal; public: - std::vector<CodeTemplateFile> GetFilesToRender(RenderingContext* context) override; - void RenderFile(std::ostream& stream, int fileTag, RenderingContext* context) override; + std::vector<CodeTemplateFile> GetFilesToRender(RenderingContext *context) override; + void RenderFile(std::ostream &stream, int fileTag, RenderingContext *context) override; }; diff --git a/src/ZoneCodeGeneratorLib/Generating/Templates/ZoneWriteTemplate.cpp b/src/ZoneCodeGeneratorLib/Generating/Templates/ZoneWriteTemplate.cpp index 95ed06840..1813084f0 100644 --- a/src/ZoneCodeGeneratorLib/Generating/Templates/ZoneWriteTemplate.cpp +++ b/src/ZoneCodeGeneratorLib/Generating/Templates/ZoneWriteTemplate.cpp @@ -7,1254 +7,1010 @@ #include "Domain/Computations/StructureComputations.h" #include "Internal/BaseTemplate.h" -class ZoneWriteTemplate::Internal final : BaseTemplate -{ - enum class MemberWriteType - { - ARRAY_POINTER, - DYNAMIC_ARRAY, - EMBEDDED, - EMBEDDED_ARRAY, - POINTER_ARRAY, - SINGLE_POINTER - }; - - static std::string WriterClassName(StructureInformation* asset) - { - std::ostringstream str; - str << "Writer_" << asset->m_definition->m_name; - return str.str(); - } +class ZoneWriteTemplate::Internal final : BaseTemplate { + enum class MemberWriteType { ARRAY_POINTER, DYNAMIC_ARRAY, EMBEDDED, EMBEDDED_ARRAY, POINTER_ARRAY, SINGLE_POINTER }; + + static std::string WriterClassName(StructureInformation *asset) { + std::ostringstream str; + str << "Writer_" << asset->m_definition->m_name; + return str.str(); + } + + static std::string VariableDecl(const DataDefinition *def) { + std::ostringstream str; + str << def->GetFullName() << "* var" << MakeSafeTypeName(def) << ";"; + return str.str(); + } + + static std::string WrittenVariableDecl(const DataDefinition *def) { + std::ostringstream str; + str << def->GetFullName() << "* var" << MakeSafeTypeName(def) << "Written;"; + return str.str(); + } + + static std::string PointerVariableDecl(const DataDefinition *def) { + std::ostringstream str; + str << def->GetFullName() << "** var" << MakeSafeTypeName(def) << "Ptr;"; + return str.str(); + } + + static std::string WrittenPointerVariableDecl(const DataDefinition *def) { + std::ostringstream str; + str << def->GetFullName() << "** var" << MakeSafeTypeName(def) << "PtrWritten;"; + return str.str(); + } + + void PrintHeaderPtrArrayWriteMethodDeclaration(const DataDefinition *def) const { + LINE("void WritePtrArray_" << MakeSafeTypeName(def) << "(bool atStreamStart, size_t count);") + } + + void PrintHeaderArrayWriteMethodDeclaration(const DataDefinition *def) const { + LINE("void WriteArray_" << MakeSafeTypeName(def) << "(bool atStreamStart, size_t count);") + } + + void PrintHeaderWriteMethodDeclaration(const StructureInformation *info) const { + LINE("void Write_" << MakeSafeTypeName(info->m_definition) << "(bool atStreamStart);") + } + + void PrintHeaderTempPtrWriteMethodDeclaration(const StructureInformation *info) const { + LINE("void WritePtr_" << MakeSafeTypeName(info->m_definition) << "(bool atStreamStart);") + } + + void PrintHeaderGetNameMethodDeclaration(const StructureInformation *info) const { + LINE("static std::string GetAssetName(" << info->m_definition->GetFullName() << "* pAsset);") + } + + void PrintHeaderMainWriteMethodDeclaration(const StructureInformation *info) const { + LINE("void Write(" << info->m_definition->GetFullName() << "** pAsset);") + } + + void PrintHeaderConstructor() const { + LINE(WriterClassName(m_env.m_asset) << "(" << m_env.m_asset->m_definition->GetFullName() << "* asset, Zone* zone, IZoneOutputStream* stream);") + } + + void PrintVariableInitialization(const DataDefinition *def) const { LINE("var" << def->m_name << " = nullptr;") } + + void PrintWrittenVariableInitialization(const DataDefinition *def) const { LINE("var" << def->m_name << "Written = nullptr;") } + + void PrintPointerVariableInitialization(const DataDefinition *def) const { LINE("var" << def->m_name << "Ptr = nullptr;") } + + void PrintWrittenPointerVariableInitialization(const DataDefinition *def) const { LINE("var" << def->m_name << "PtrWritten = nullptr;") } + + void PrintConstructorMethod() { + LINE(WriterClassName(m_env.m_asset) << "::" << WriterClassName(m_env.m_asset) << "(" << m_env.m_asset->m_definition->GetFullName() + << "* asset, Zone* zone, IZoneOutputStream* stream)") + + m_intendation++; + LINE_START(": AssetWriter(zone->m_pools->GetAsset(" << m_env.m_asset->m_asset_enum_entry->m_name << ", GetAssetName(asset))" + << ", zone, stream)") + LINE_END("") + m_intendation--; + + LINE("{") + m_intendation++; + + PrintVariableInitialization(m_env.m_asset->m_definition); + PrintWrittenVariableInitialization(m_env.m_asset->m_definition); + PrintPointerVariableInitialization(m_env.m_asset->m_definition); + PrintWrittenPointerVariableInitialization(m_env.m_asset->m_definition); + LINE("") + + for (auto *type : m_env.m_used_types) { + if (type->m_info && !type->m_info->m_definition->m_anonymous && !type->m_info->m_is_leaf && !StructureComputations(type->m_info).IsAsset()) { + PrintVariableInitialization(type->m_type); + PrintWrittenVariableInitialization(type->m_type); + } + } + for (auto *type : m_env.m_used_types) { + if (type->m_info && type->m_pointer_array_reference_exists && !type->m_is_context_asset) { + PrintPointerVariableInitialization(type->m_type); + PrintWrittenPointerVariableInitialization(type->m_type); + } + } + + m_intendation--; + LINE("}") + } + + void WriteMember_ScriptString(StructureInformation *info, MemberInformation *member, const DeclarationModifierComputations &modifier, + const MemberWriteType writeType) const { + if (writeType == MemberWriteType::ARRAY_POINTER) { + LINE("varScriptString = " << MakeMemberAccess(info, member, modifier) << ";") + LINE("m_stream->MarkFollowing(" << MakeWrittenMemberAccess(info, member, modifier) << ");") + LINE("WriteScriptStringArray(true, " << MakeEvaluation(modifier.GetArrayPointerCountEvaluation()) << ");") + } else if (writeType == MemberWriteType::EMBEDDED_ARRAY) { + LINE("varScriptStringWritten = " << MakeWrittenMemberAccess(info, member, modifier) << ";") + LINE("WriteScriptStringArray(false, " << MakeArrayCount(dynamic_cast<ArrayDeclarationModifier *>(modifier.GetDeclarationModifier())) << ");") + } else if (writeType == MemberWriteType::EMBEDDED) { + LINE(MakeWrittenMemberAccess(info, member, modifier) << " = UseScriptString(" << MakeMemberAccess(info, member, modifier) << ");") + } else { + assert(false); + LINE("#error unsupported writeType " << static_cast<int>(writeType) << " for scripstring") + } + } + + void WriteMember_Asset(StructureInformation *info, MemberInformation *member, const DeclarationModifierComputations &modifier, + const MemberWriteType writeType) const { + if (writeType == MemberWriteType::SINGLE_POINTER) { + LINE(WriterClassName(member->m_type) << " writer(" << MakeMemberAccess(info, member, modifier) << ", m_zone, m_stream);") + LINE("writer.Write(&" << MakeWrittenMemberAccess(info, member, modifier) << ");") + } else if (writeType == MemberWriteType::POINTER_ARRAY) { + WriteMember_PointerArray(info, member, modifier); + } else { + assert(false); + LINE("#error unsupported writeType " << static_cast<int>(writeType) << " for asset") + } + } + + void WriteMember_String(StructureInformation *info, MemberInformation *member, const DeclarationModifierComputations &modifier, + const MemberWriteType writeType) const { + if (writeType == MemberWriteType::SINGLE_POINTER) { + if (member->m_member->m_type_declaration->m_is_const) { + LINE("varXStringWritten = &" << MakeWrittenMemberAccess(info, member, modifier) << ";") + } else { + LINE("varXStringWritten = const_cast<const char**>(&" << MakeWrittenMemberAccess(info, member, modifier) << ");") + } + LINE("WriteXString(false);") + } else if (writeType == MemberWriteType::POINTER_ARRAY) { + if (modifier.IsArray()) { + LINE("varXStringWritten = " << MakeWrittenMemberAccess(info, member, modifier) << ";") + LINE("WriteXStringArray(false, " << modifier.GetArraySize() << ");") + } else { + LINE("varXString = " << MakeMemberAccess(info, member, modifier) << ";") + LINE("m_stream->MarkFollowing(" << MakeWrittenMemberAccess(info, member, modifier) << ");") + LINE("WriteXStringArray(true, " << MakeEvaluation(modifier.GetPointerArrayCountEvaluation()) << ");") + } + } else { + assert(false); + LINE("#error unsupported writeType " << static_cast<int>(writeType) << " for string") + } + } + + void WriteMember_ArrayPointer(StructureInformation *info, MemberInformation *member, const DeclarationModifierComputations &modifier) const { + const MemberComputations computations(member); + LINE("m_stream->MarkFollowing(" << MakeWrittenMemberAccess(info, member, modifier) << ");") + if (member->m_type && !member->m_type->m_is_leaf && !computations.IsInRuntimeBlock()) { + LINE(MakeTypeVarName(member->m_member->m_type_declaration->m_type) << " = " << MakeMemberAccess(info, member, modifier) << ";") + LINE("WriteArray_" << MakeSafeTypeName(member->m_member->m_type_declaration->m_type) << "(true, " + << MakeEvaluation(modifier.GetArrayPointerCountEvaluation()) << ");") + } else { + LINE("m_stream->Write<" << MakeTypeDecl(member->m_member->m_type_declaration.get()) + << MakeFollowingReferences(modifier.GetFollowingDeclarationModifiers()) << ">(" << MakeMemberAccess(info, member, modifier) + << ", " << MakeEvaluation(modifier.GetArrayPointerCountEvaluation()) << ");") + } + } + + void WriteMember_PointerArray(StructureInformation *info, MemberInformation *member, const DeclarationModifierComputations &modifier) const { + LINE(MakeTypePtrVarName(member->m_member->m_type_declaration->m_type) << " = " << MakeMemberAccess(info, member, modifier) << ";") + if (modifier.IsArray()) { + LINE(MakeTypeWrittenPtrVarName(member->m_member->m_type_declaration->m_type) << " = " << MakeWrittenMemberAccess(info, member, modifier) << ";") + LINE("WritePtrArray_" << MakeSafeTypeName(member->m_member->m_type_declaration->m_type) << "(false, " << modifier.GetArraySize() << ");") + } else { + LINE("m_stream->MarkFollowing(" << MakeWrittenMemberAccess(info, member, modifier) << ");") + LINE("WritePtrArray_" << MakeSafeTypeName(member->m_member->m_type_declaration->m_type) << "(true, " + << MakeEvaluation(modifier.GetPointerArrayCountEvaluation()) << ");") + } + } + + void WriteMember_EmbeddedArray(StructureInformation *info, MemberInformation *member, const DeclarationModifierComputations &modifier) const { + const MemberComputations computations(member); + std::string arraySizeStr; + + if (modifier.HasDynamicArrayCount()) + arraySizeStr = MakeEvaluation(modifier.GetDynamicArrayCountEvaluation()); + else + arraySizeStr = std::to_string(modifier.GetArraySize()); + + if (!member->m_is_leaf) { + if (computations.IsAfterPartialLoad()) { + LINE(MakeTypeVarName(member->m_member->m_type_declaration->m_type) << " = " << MakeMemberAccess(info, member, modifier) << ";") + LINE("WriteArray_" << MakeSafeTypeName(member->m_member->m_type_declaration->m_type) << "(true, " << arraySizeStr << ");") + } else { + LINE(MakeTypeVarName(member->m_member->m_type_declaration->m_type) << " = " << MakeMemberAccess(info, member, modifier) << ";") + LINE(MakeTypeWrittenVarName(member->m_member->m_type_declaration->m_type) << " = " << MakeWrittenMemberAccess(info, member, modifier) << ";") + LINE("WriteArray_" << MakeSafeTypeName(member->m_member->m_type_declaration->m_type) << "(false, " << arraySizeStr << ");") + } + } else if (computations.IsAfterPartialLoad()) { + LINE("m_stream->Write<" << MakeTypeDecl(member->m_member->m_type_declaration.get()) + << MakeFollowingReferences(modifier.GetFollowingDeclarationModifiers()) << ">(" << MakeMemberAccess(info, member, modifier) + << ", " << arraySizeStr << ");") + } + } + + void WriteMember_DynamicArray(StructureInformation *info, MemberInformation *member, const DeclarationModifierComputations &modifier) const { + if (member->m_type && !member->m_type->m_is_leaf) { + LINE(MakeTypeVarName(member->m_member->m_type_declaration->m_type) << " = " << MakeMemberAccess(info, member, modifier) << ";") + LINE("WriteArray_" << MakeSafeTypeName(member->m_member->m_type_declaration->m_type) << "(true, " + << MakeEvaluation(modifier.GetDynamicArraySizeEvaluation()) << ");") + } else { + LINE("m_stream->Write<" << MakeTypeDecl(member->m_member->m_type_declaration.get()) + << MakeFollowingReferences(modifier.GetFollowingDeclarationModifiers()) << ">(" << MakeMemberAccess(info, member, modifier) + << ", " << MakeEvaluation(modifier.GetDynamicArraySizeEvaluation()) << ");") + } + } + + void WriteMember_Embedded(StructureInformation *info, MemberInformation *member, const DeclarationModifierComputations &modifier) const { + const MemberComputations computations(member); + + if (!member->m_is_leaf) { + if (computations.IsAfterPartialLoad()) { + LINE(MakeTypeVarName(member->m_member->m_type_declaration->m_type) << " = &" << MakeMemberAccess(info, member, modifier) << ";") + LINE("Write_" << MakeSafeTypeName(member->m_member->m_type_declaration->m_type) << "(true);") + } else { + LINE(MakeTypeVarName(member->m_member->m_type_declaration->m_type) << " = &" << MakeMemberAccess(info, member, modifier) << ";") + LINE(MakeTypeWrittenVarName(member->m_member->m_type_declaration->m_type) << " = &" << MakeWrittenMemberAccess(info, member, modifier) << ";") + LINE("Write_" << MakeSafeTypeName(member->m_member->m_type_declaration->m_type) << "(false);") + } + } else if (computations.IsAfterPartialLoad()) { + LINE("m_stream->Write<" << MakeTypeDecl(member->m_member->m_type_declaration.get()) + << MakeFollowingReferences(modifier.GetFollowingDeclarationModifiers()) << ">(&" << MakeMemberAccess(info, member, modifier) + << ");") + } + } + + void WriteMember_SinglePointer(StructureInformation *info, MemberInformation *member, const DeclarationModifierComputations &modifier) const { + const MemberComputations computations(member); + LINE("m_stream->MarkFollowing(" << MakeWrittenMemberAccess(info, member, modifier) << ");") + if (member->m_type && !member->m_type->m_is_leaf && !computations.IsInRuntimeBlock()) { + LINE(MakeTypeVarName(member->m_member->m_type_declaration->m_type) << " = " << MakeMemberAccess(info, member, modifier) << ";") + LINE("Write_" << MakeSafeTypeName(member->m_type->m_definition) << "(true);") + } else { + LINE("m_stream->Write<" << MakeTypeDecl(member->m_member->m_type_declaration.get()) + << MakeFollowingReferences(modifier.GetFollowingDeclarationModifiers()) << ">(" << MakeMemberAccess(info, member, modifier) + << ");") + } + } + + void WriteMember_TypeCheck(StructureInformation *info, MemberInformation *member, const DeclarationModifierComputations &modifier, + const MemberWriteType writeType) const { + if (member->m_is_string) { + WriteMember_String(info, member, modifier, writeType); + } else if (member->m_is_script_string) { + WriteMember_ScriptString(info, member, modifier, writeType); + } else if (member->m_type && StructureComputations(member->m_type).IsAsset()) { + WriteMember_Asset(info, member, modifier, writeType); + } else { + switch (writeType) { + case MemberWriteType::ARRAY_POINTER: + WriteMember_ArrayPointer(info, member, modifier); + break; + + case MemberWriteType::SINGLE_POINTER: + WriteMember_SinglePointer(info, member, modifier); + break; + + case MemberWriteType::EMBEDDED: + WriteMember_Embedded(info, member, modifier); + break; - static std::string VariableDecl(const DataDefinition* def) - { - std::ostringstream str; - str << def->GetFullName() << "* var" << MakeSafeTypeName(def) << ";"; - return str.str(); - } + case MemberWriteType::POINTER_ARRAY: + WriteMember_PointerArray(info, member, modifier); + break; - static std::string WrittenVariableDecl(const DataDefinition* def) - { - std::ostringstream str; - str << def->GetFullName() << "* var" << MakeSafeTypeName(def) << "Written;"; - return str.str(); - } + case MemberWriteType::DYNAMIC_ARRAY: + WriteMember_DynamicArray(info, member, modifier); + break; - static std::string PointerVariableDecl(const DataDefinition* def) - { - std::ostringstream str; - str << def->GetFullName() << "** var" << MakeSafeTypeName(def) << "Ptr;"; - return str.str(); - } + case MemberWriteType::EMBEDDED_ARRAY: + WriteMember_EmbeddedArray(info, member, modifier); + break; - static std::string WrittenPointerVariableDecl(const DataDefinition* def) - { - std::ostringstream str; - str << def->GetFullName() << "** var" << MakeSafeTypeName(def) << "PtrWritten;"; - return str.str(); + default: + LINE("// t=" << static_cast<int>(writeType)) + break; + } } + } - void PrintHeaderPtrArrayWriteMethodDeclaration(const DataDefinition* def) const - { - LINE("void WritePtrArray_" << MakeSafeTypeName(def) << "(bool atStreamStart, size_t count);") + static bool WriteMember_ShouldMakeInsertReuse(StructureInformation *info, MemberInformation *member, const DeclarationModifierComputations &modifier, + const MemberWriteType writeType) { + if (writeType != MemberWriteType::ARRAY_POINTER && writeType != MemberWriteType::SINGLE_POINTER && writeType != MemberWriteType::POINTER_ARRAY) { + return false; } - void PrintHeaderArrayWriteMethodDeclaration(const DataDefinition* def) const - { - LINE("void WriteArray_" << MakeSafeTypeName(def) << "(bool atStreamStart, size_t count);") + if (writeType == MemberWriteType::POINTER_ARRAY && modifier.IsArray()) { + return false; } - void PrintHeaderWriteMethodDeclaration(const StructureInformation* info) const - { - LINE("void Write_" << MakeSafeTypeName(info->m_definition) << "(bool atStreamStart);") + if (member->m_is_string) { + return false; } - void PrintHeaderTempPtrWriteMethodDeclaration(const StructureInformation* info) const - { - LINE("void WritePtr_" << MakeSafeTypeName(info->m_definition) << "(bool atStreamStart);") + if (member->m_type && StructureComputations(member->m_type).IsAsset()) { + return false; } - void PrintHeaderGetNameMethodDeclaration(const StructureInformation* info) const - { - LINE("static std::string GetAssetName(" << info->m_definition->GetFullName() << "* pAsset);") - } + if (member->m_is_reusable) + return true; - void PrintHeaderMainWriteMethodDeclaration(const StructureInformation* info) const - { - LINE("void Write(" << info->m_definition->GetFullName() << "** pAsset);") - } + if (member->m_type == nullptr || !member->m_type->m_reusable_reference_exists) + return false; - void PrintHeaderConstructor() const - { - LINE(WriterClassName(m_env.m_asset) << "("<<m_env.m_asset->m_definition->GetFullName()<<"* asset, Zone* zone, IZoneOutputStream* stream);") - } + return true; + } - void PrintVariableInitialization(const DataDefinition* def) const - { - LINE("var" << def->m_name << " = nullptr;") + void WriteMember_InsertReuse(StructureInformation *info, MemberInformation *member, const DeclarationModifierComputations &modifier, + const MemberWriteType writeType) { + if (!WriteMember_ShouldMakeInsertReuse(info, member, modifier, writeType)) { + WriteMember_TypeCheck(info, member, modifier, writeType); + return; } - void PrintWrittenVariableInitialization(const DataDefinition* def) const - { - LINE("var" << def->m_name << "Written = nullptr;") - } - - void PrintPointerVariableInitialization(const DataDefinition* def) const - { - LINE("var" << def->m_name << "Ptr = nullptr;") - } - - void PrintWrittenPointerVariableInitialization(const DataDefinition* def) const - { - LINE("var" << def->m_name << "PtrWritten = nullptr;") - } - - void PrintConstructorMethod() - { - LINE(WriterClassName(m_env.m_asset) << "::" << WriterClassName(m_env.m_asset) << "("<<m_env.m_asset->m_definition->GetFullName()<<"* asset, Zone* zone, IZoneOutputStream* stream)") + if (writeType == MemberWriteType::ARRAY_POINTER) { + LINE("m_stream->ReusableAddOffset(" << MakeMemberAccess(info, member, modifier) << ", " << MakeEvaluation(modifier.GetArrayPointerCountEvaluation()) + << ");") + } else if (writeType == MemberWriteType::POINTER_ARRAY) { + const auto *evaluation = modifier.GetPointerArrayCountEvaluation(); - m_intendation++; - LINE_START(": AssetWriter(zone->m_pools->GetAsset("<<m_env.m_asset->m_asset_enum_entry->m_name<<", GetAssetName(asset))"<<", zone, stream)") - LINE_END("") - m_intendation--; - - LINE("{") - m_intendation++; - - PrintVariableInitialization(m_env.m_asset->m_definition); - PrintWrittenVariableInitialization(m_env.m_asset->m_definition); - PrintPointerVariableInitialization(m_env.m_asset->m_definition); - PrintWrittenPointerVariableInitialization(m_env.m_asset->m_definition); - LINE("") - - for (auto* type : m_env.m_used_types) - { - if (type->m_info && !type->m_info->m_definition->m_anonymous && !type->m_info->m_is_leaf && !StructureComputations(type->m_info).IsAsset()) - { - PrintVariableInitialization(type->m_type); - PrintWrittenVariableInitialization(type->m_type); - } - } - for (auto* type : m_env.m_used_types) - { - if (type->m_info && type->m_pointer_array_reference_exists && !type->m_is_context_asset) - { - PrintPointerVariableInitialization(type->m_type); - PrintWrittenPointerVariableInitialization(type->m_type); - } - } - - m_intendation--; - LINE("}") - } - - void WriteMember_ScriptString(StructureInformation* info, MemberInformation* member, const DeclarationModifierComputations& modifier, const MemberWriteType writeType) const - { - if (writeType == MemberWriteType::ARRAY_POINTER) - { - LINE("varScriptString = " << MakeMemberAccess(info, member, modifier) << ";") - LINE("m_stream->MarkFollowing("<<MakeWrittenMemberAccess(info, member, modifier)<<");") - LINE("WriteScriptStringArray(true, " << MakeEvaluation(modifier.GetArrayPointerCountEvaluation()) << ");") - } - else if (writeType == MemberWriteType::EMBEDDED_ARRAY) - { - LINE("varScriptStringWritten = " << MakeWrittenMemberAccess(info, member, modifier) << ";") - LINE("WriteScriptStringArray(false, " << MakeArrayCount(dynamic_cast<ArrayDeclarationModifier*>(modifier.GetDeclarationModifier())) << ");") - } - else if (writeType == MemberWriteType::EMBEDDED) - { - LINE(MakeWrittenMemberAccess(info, member, modifier) << " = UseScriptString(" << MakeMemberAccess(info, member, modifier) << ");") - } - else - { - assert(false); - LINE("#error unsupported writeType " << static_cast<int>(writeType) << " for scripstring") - } + if (evaluation) { + LINE("m_stream->ReusableAddOffset(" << MakeMemberAccess(info, member, modifier) << ", " << MakeEvaluation(modifier.GetPointerArrayCountEvaluation()) + << ");") + } else { + LINE("m_stream->ReusableAddOffset(" << MakeMemberAccess(info, member, modifier) << ", " << modifier.GetArraySize() << ");") + } + } else { + LINE("m_stream->ReusableAddOffset(" << MakeMemberAccess(info, member, modifier) << ");") } - void WriteMember_Asset(StructureInformation* info, MemberInformation* member, const DeclarationModifierComputations& modifier, const MemberWriteType writeType) const - { - if (writeType == MemberWriteType::SINGLE_POINTER) - { - LINE(WriterClassName(member->m_type) << " writer("<<MakeMemberAccess(info, member, modifier)<<", m_zone, m_stream);") - LINE("writer.Write(&" << MakeWrittenMemberAccess(info, member, modifier) << ");") - } - else if (writeType == MemberWriteType::POINTER_ARRAY) - { - WriteMember_PointerArray(info, member, modifier); - } - else - { - assert(false); - LINE("#error unsupported writeType " << static_cast<int>(writeType) << " for asset") - } - } + WriteMember_TypeCheck(info, member, modifier, writeType); + } - void WriteMember_String(StructureInformation* info, MemberInformation* member, const DeclarationModifierComputations& modifier, const MemberWriteType writeType) const - { - if (writeType == MemberWriteType::SINGLE_POINTER) - { - if (member->m_member->m_type_declaration->m_is_const) - { - LINE("varXStringWritten = &" << MakeWrittenMemberAccess(info, member, modifier) << ";") - } - else - { - LINE("varXStringWritten = const_cast<const char**>(&" << MakeWrittenMemberAccess(info, member, modifier) << ");") - } - LINE("WriteXString(false);") - } - else if (writeType == MemberWriteType::POINTER_ARRAY) - { - if (modifier.IsArray()) - { - LINE("varXStringWritten = " << MakeWrittenMemberAccess(info, member, modifier) << ";") - LINE("WriteXStringArray(false, " << modifier.GetArraySize() << ");") - } - else - { - LINE("varXString = " << MakeMemberAccess(info, member, modifier) << ";") - LINE("m_stream->MarkFollowing(" << MakeWrittenMemberAccess(info, member, modifier) << ");") - LINE("WriteXStringArray(true, " << MakeEvaluation(modifier.GetPointerArrayCountEvaluation()) << ");") - } - } - else - { - assert(false); - LINE("#error unsupported writeType " << static_cast<int>(writeType) << " for string") - } + static bool WriteMember_ShouldMakeAlign(StructureInformation *info, MemberInformation *member, const DeclarationModifierComputations &modifier, + const MemberWriteType writeType) { + if (writeType != MemberWriteType::ARRAY_POINTER && writeType != MemberWriteType::POINTER_ARRAY && writeType != MemberWriteType::SINGLE_POINTER) { + return false; } - void WriteMember_ArrayPointer(StructureInformation* info, MemberInformation* member, const DeclarationModifierComputations& modifier) const - { - const MemberComputations computations(member); - LINE("m_stream->MarkFollowing(" << MakeWrittenMemberAccess(info, member, modifier) << ");") - if (member->m_type && !member->m_type->m_is_leaf && !computations.IsInRuntimeBlock()) - { - LINE(MakeTypeVarName(member->m_member->m_type_declaration->m_type) << " = " << MakeMemberAccess(info, member, modifier) << ";") - LINE("WriteArray_" << MakeSafeTypeName(member->m_member->m_type_declaration->m_type) << "(true, " << MakeEvaluation(modifier.GetArrayPointerCountEvaluation()) << ");") - } - else - { - LINE("m_stream->Write<" << MakeTypeDecl(member->m_member->m_type_declaration.get()) << MakeFollowingReferences(modifier.GetFollowingDeclarationModifiers()) - << ">(" << MakeMemberAccess(info, member, modifier) << ", " << MakeEvaluation(modifier.GetArrayPointerCountEvaluation()) << ");") - } + if (writeType == MemberWriteType::POINTER_ARRAY) { + return !modifier.IsArray(); } - void WriteMember_PointerArray(StructureInformation* info, MemberInformation* member, const DeclarationModifierComputations& modifier) const - { - LINE(MakeTypePtrVarName(member->m_member->m_type_declaration->m_type) << " = " << MakeMemberAccess(info, member, modifier) << ";") - if (modifier.IsArray()) - { - LINE(MakeTypeWrittenPtrVarName(member->m_member->m_type_declaration->m_type) << " = " << MakeWrittenMemberAccess(info, member, modifier) << ";") - LINE("WritePtrArray_" << MakeSafeTypeName(member->m_member->m_type_declaration->m_type) << "(false, " << modifier.GetArraySize() << ");") - } - else - { - LINE("m_stream->MarkFollowing(" << MakeWrittenMemberAccess(info, member, modifier) << ");") - LINE("WritePtrArray_" << MakeSafeTypeName(member->m_member->m_type_declaration->m_type) << "(true, " << MakeEvaluation(modifier.GetPointerArrayCountEvaluation()) << ");") - } + if (member->m_is_string) { + return false; } - void WriteMember_EmbeddedArray(StructureInformation* info, MemberInformation* member, const DeclarationModifierComputations& modifier) const - { - const MemberComputations computations(member); - std::string arraySizeStr; - - if (modifier.HasDynamicArrayCount()) - arraySizeStr = MakeEvaluation(modifier.GetDynamicArrayCountEvaluation()); - else - arraySizeStr = std::to_string(modifier.GetArraySize()); - - if (!member->m_is_leaf) - { - if (computations.IsAfterPartialLoad()) - { - LINE(MakeTypeVarName(member->m_member->m_type_declaration->m_type)<<" = "<< MakeMemberAccess(info, member, modifier) <<";") - LINE("WriteArray_" << MakeSafeTypeName(member->m_member->m_type_declaration->m_type) << "(true, " << arraySizeStr << ");") - } - else - { - LINE(MakeTypeVarName(member->m_member->m_type_declaration->m_type) << " = " << MakeMemberAccess(info, member, modifier) << ";") - LINE(MakeTypeWrittenVarName(member->m_member->m_type_declaration->m_type) << " = " << MakeWrittenMemberAccess(info, member, modifier) << ";") - LINE("WriteArray_" << MakeSafeTypeName(member->m_member->m_type_declaration->m_type) << "(false, " << arraySizeStr << ");") - } - } - else if (computations.IsAfterPartialLoad()) - { - LINE("m_stream->Write<" << MakeTypeDecl(member->m_member->m_type_declaration.get()) << MakeFollowingReferences(modifier.GetFollowingDeclarationModifiers()) - << ">(" << MakeMemberAccess(info, member, modifier) << ", " << arraySizeStr << ");") - } + if (member->m_type && StructureComputations(member->m_type).IsAsset()) { + return false; } - void WriteMember_DynamicArray(StructureInformation* info, MemberInformation* member, const DeclarationModifierComputations& modifier) const - { - if (member->m_type && !member->m_type->m_is_leaf) - { - LINE(MakeTypeVarName(member->m_member->m_type_declaration->m_type) << " = " << MakeMemberAccess(info, member, modifier) << ";") - LINE("WriteArray_" << MakeSafeTypeName(member->m_member->m_type_declaration->m_type) << "(true, " << MakeEvaluation(modifier.GetDynamicArraySizeEvaluation()) << ");") - } - else - { - LINE("m_stream->Write<" << MakeTypeDecl(member->m_member->m_type_declaration.get()) << MakeFollowingReferences(modifier.GetFollowingDeclarationModifiers()) - << ">(" << MakeMemberAccess(info, member, modifier) << ", " << MakeEvaluation(modifier.GetDynamicArraySizeEvaluation()) << ");") - } - } + return true; + } - void WriteMember_Embedded(StructureInformation* info, MemberInformation* member, const DeclarationModifierComputations& modifier) const - { - const MemberComputations computations(member); - - if (!member->m_is_leaf) - { - if (computations.IsAfterPartialLoad()) - { - LINE(MakeTypeVarName(member->m_member->m_type_declaration->m_type) << " = &" << MakeMemberAccess(info, member, modifier) << ";") - LINE("Write_" << MakeSafeTypeName(member->m_member->m_type_declaration->m_type) << "(true);") - } - else - { - LINE(MakeTypeVarName(member->m_member->m_type_declaration->m_type) << " = &" << MakeMemberAccess(info, member, modifier) << ";") - LINE(MakeTypeWrittenVarName(member->m_member->m_type_declaration->m_type) << " = &" << MakeWrittenMemberAccess(info, member, modifier) << ";") - LINE("Write_" << MakeSafeTypeName(member->m_member->m_type_declaration->m_type) << "(false);") - } - } - else if (computations.IsAfterPartialLoad()) - { - LINE("m_stream->Write<" << MakeTypeDecl(member->m_member->m_type_declaration.get()) << MakeFollowingReferences(modifier.GetFollowingDeclarationModifiers()) - << ">(&" << MakeMemberAccess(info, member, modifier) << ");") - } + void WriteMember_Align(StructureInformation *info, MemberInformation *member, const DeclarationModifierComputations &modifier, + const MemberWriteType writeType) { + if (!WriteMember_ShouldMakeAlign(info, member, modifier, writeType)) { + WriteMember_InsertReuse(info, member, modifier, writeType); + return; } - void WriteMember_SinglePointer(StructureInformation* info, MemberInformation* member, const DeclarationModifierComputations& modifier) const - { - const MemberComputations computations(member); - LINE("m_stream->MarkFollowing(" << MakeWrittenMemberAccess(info, member, modifier) << ");") - if (member->m_type && !member->m_type->m_is_leaf && !computations.IsInRuntimeBlock()) - { - LINE(MakeTypeVarName(member->m_member->m_type_declaration->m_type) << " = " << MakeMemberAccess(info, member, modifier) << ";") - LINE("Write_" << MakeSafeTypeName(member->m_type->m_definition) << "(true);") - } - else - { - LINE("m_stream->Write<" << MakeTypeDecl(member->m_member->m_type_declaration.get()) << MakeFollowingReferences(modifier.GetFollowingDeclarationModifiers()) - << ">(" << MakeMemberAccess(info, member, modifier) << ");") - } - } + const auto typeDecl = MakeTypeDecl(member->m_member->m_type_declaration.get()); + const auto followingReferences = MakeFollowingReferences(modifier.GetFollowingDeclarationModifiers()); - void WriteMember_TypeCheck(StructureInformation* info, MemberInformation* member, const DeclarationModifierComputations& modifier, const MemberWriteType writeType) const - { - if (member->m_is_string) - { - WriteMember_String(info, member, modifier, writeType); - } - else if (member->m_is_script_string) - { - WriteMember_ScriptString(info, member, modifier, writeType); - } - else if (member->m_type && StructureComputations(member->m_type).IsAsset()) - { - WriteMember_Asset(info, member, modifier, writeType); - } - else - { - switch (writeType) - { - case MemberWriteType::ARRAY_POINTER: - WriteMember_ArrayPointer(info, member, modifier); - break; - - case MemberWriteType::SINGLE_POINTER: - WriteMember_SinglePointer(info, member, modifier); - break; - - case MemberWriteType::EMBEDDED: - WriteMember_Embedded(info, member, modifier); - break; - - case MemberWriteType::POINTER_ARRAY: - WriteMember_PointerArray(info, member, modifier); - break; - - case MemberWriteType::DYNAMIC_ARRAY: - WriteMember_DynamicArray(info, member, modifier); - break; - - case MemberWriteType::EMBEDDED_ARRAY: - WriteMember_EmbeddedArray(info, member, modifier); - break; - - default: - LINE("// t=" << static_cast<int>(writeType)) - break; - } - } + if (member->m_alloc_alignment) { + LINE("m_stream->Align(" << MakeEvaluation(member->m_alloc_alignment.get()) << ");") + } else { + LINE("m_stream->Align(" << modifier.GetAlignment() << ");") } - static bool WriteMember_ShouldMakeInsertReuse(StructureInformation* info, MemberInformation* member, const DeclarationModifierComputations& modifier, const MemberWriteType writeType) - { - if (writeType != MemberWriteType::ARRAY_POINTER - && writeType != MemberWriteType::SINGLE_POINTER - && writeType != MemberWriteType::POINTER_ARRAY) - { - return false; - } - - if (writeType == MemberWriteType::POINTER_ARRAY - && modifier.IsArray()) - { - return false; - } - - if (member->m_is_string) - { - return false; - } - - if (member->m_type && StructureComputations(member->m_type).IsAsset()) - { - return false; - } - - if (member->m_is_reusable) - return true; + WriteMember_InsertReuse(info, member, modifier, writeType); + } - if (member->m_type == nullptr || !member->m_type->m_reusable_reference_exists) - return false; - - return true; + static bool WriteMember_ShouldMakeReuse(StructureInformation *info, MemberInformation *member, const DeclarationModifierComputations &modifier, + const MemberWriteType writeType) { + if (writeType != MemberWriteType::ARRAY_POINTER && writeType != MemberWriteType::SINGLE_POINTER && writeType != MemberWriteType::POINTER_ARRAY) { + return false; } - void WriteMember_InsertReuse(StructureInformation* info, MemberInformation* member, const DeclarationModifierComputations& modifier, const MemberWriteType writeType) - { - if (!WriteMember_ShouldMakeInsertReuse(info, member, modifier, writeType)) - { - WriteMember_TypeCheck(info, member, modifier, writeType); - return; - } - - if (writeType == MemberWriteType::ARRAY_POINTER) - { - LINE("m_stream->ReusableAddOffset("<<MakeMemberAccess(info, member, modifier)<<", "<<MakeEvaluation(modifier.GetArrayPointerCountEvaluation())<<");") - } - else if (writeType == MemberWriteType::POINTER_ARRAY) - { - const auto* evaluation = modifier.GetPointerArrayCountEvaluation(); - - if (evaluation) - { - LINE("m_stream->ReusableAddOffset(" << MakeMemberAccess(info, member, modifier) << ", " << MakeEvaluation(modifier.GetPointerArrayCountEvaluation()) << ");") - } - else - { - LINE("m_stream->ReusableAddOffset(" << MakeMemberAccess(info, member, modifier) << ", " << modifier.GetArraySize() << ");") - } - } - else - { - LINE("m_stream->ReusableAddOffset("<<MakeMemberAccess(info, member, modifier)<<");") - } - - WriteMember_TypeCheck(info, member, modifier, writeType); + if (writeType == MemberWriteType::POINTER_ARRAY && modifier.IsArray()) { + return false; } - static bool WriteMember_ShouldMakeAlign(StructureInformation* info, MemberInformation* member, const DeclarationModifierComputations& modifier, const MemberWriteType writeType) - { - if (writeType != MemberWriteType::ARRAY_POINTER - && writeType != MemberWriteType::POINTER_ARRAY - && writeType != MemberWriteType::SINGLE_POINTER) - { - return false; - } - - if (writeType == MemberWriteType::POINTER_ARRAY) - { - return !modifier.IsArray(); - } - - if (member->m_is_string) - { - return false; - } - - if (member->m_type && StructureComputations(member->m_type).IsAsset()) - { - return false; - } + return member->m_is_reusable; + } - return true; + void WriteMember_Reuse(StructureInformation *info, MemberInformation *member, const DeclarationModifierComputations &modifier, + const MemberWriteType writeType) { + if (!WriteMember_ShouldMakeReuse(info, member, modifier, writeType)) { + WriteMember_Align(info, member, modifier, writeType); + return; } - void WriteMember_Align(StructureInformation* info, MemberInformation* member, const DeclarationModifierComputations& modifier, const MemberWriteType writeType) - { - if (!WriteMember_ShouldMakeAlign(info, member, modifier, writeType)) - { - WriteMember_InsertReuse(info, member, modifier, writeType); - return; - } + LINE("if(m_stream->ReusableShouldWrite(&" << MakeWrittenMemberAccess(info, member, modifier) << "))") + LINE("{") + m_intendation++; - const auto typeDecl = MakeTypeDecl(member->m_member->m_type_declaration.get()); - const auto followingReferences = MakeFollowingReferences(modifier.GetFollowingDeclarationModifiers()); + WriteMember_Align(info, member, modifier, writeType); - if (member->m_alloc_alignment) - { - LINE("m_stream->Align("<<MakeEvaluation(member->m_alloc_alignment.get())<<");") - } - else - { - LINE("m_stream->Align("<<modifier.GetAlignment()<<");") - } + m_intendation--; + LINE("}") + } - WriteMember_InsertReuse(info, member, modifier, writeType); + static bool WriteMember_ShouldMakePointerCheck(StructureInformation *info, MemberInformation *member, const DeclarationModifierComputations &modifier, + const MemberWriteType writeType) { + if (writeType != MemberWriteType::ARRAY_POINTER && writeType != MemberWriteType::POINTER_ARRAY && writeType != MemberWriteType::SINGLE_POINTER) { + return false; } - static bool WriteMember_ShouldMakeReuse(StructureInformation* info, MemberInformation* member, const DeclarationModifierComputations& modifier, const MemberWriteType writeType) - { - if (writeType != MemberWriteType::ARRAY_POINTER - && writeType != MemberWriteType::SINGLE_POINTER - && writeType != MemberWriteType::POINTER_ARRAY) - { - return false; - } - - if (writeType == MemberWriteType::POINTER_ARRAY - && modifier.IsArray()) - { - return false; - } - - return member->m_is_reusable; + if (writeType == MemberWriteType::POINTER_ARRAY) { + return !modifier.IsArray(); } - void WriteMember_Reuse(StructureInformation* info, MemberInformation* member, const DeclarationModifierComputations& modifier, const MemberWriteType writeType) - { - if (!WriteMember_ShouldMakeReuse(info, member, modifier, writeType)) - { - WriteMember_Align(info, member, modifier, writeType); - return; - } - - LINE("if(m_stream->ReusableShouldWrite(&" << MakeWrittenMemberAccess(info, member, modifier) << "))") - LINE("{") - m_intendation++; - - WriteMember_Align(info, member, modifier, writeType); - - m_intendation--; - LINE("}") + if (member->m_is_string) { + return false; } - static bool WriteMember_ShouldMakePointerCheck(StructureInformation* info, MemberInformation* member, const DeclarationModifierComputations& modifier, const MemberWriteType writeType) - { - if (writeType != MemberWriteType::ARRAY_POINTER - && writeType != MemberWriteType::POINTER_ARRAY - && writeType != MemberWriteType::SINGLE_POINTER) - { - return false; - } - - if (writeType == MemberWriteType::POINTER_ARRAY) - { - return !modifier.IsArray(); - } + return true; + } - if (member->m_is_string) - { - return false; - } - - return true; - } + void WriteMember_PointerCheck(StructureInformation *info, MemberInformation *member, const DeclarationModifierComputations &modifier, + const MemberWriteType writeType) { + if (WriteMember_ShouldMakePointerCheck(info, member, modifier, writeType)) { + LINE("if (" << MakeMemberAccess(info, member, modifier) << ")") + LINE("{") + m_intendation++; - void WriteMember_PointerCheck(StructureInformation* info, MemberInformation* member, const DeclarationModifierComputations& modifier, const MemberWriteType writeType) - { - if (WriteMember_ShouldMakePointerCheck(info, member, modifier, writeType)) - { - LINE("if (" << MakeMemberAccess(info, member, modifier) << ")") - LINE("{") - m_intendation++; + WriteMember_Reuse(info, member, modifier, writeType); - WriteMember_Reuse(info, member, modifier, writeType); - - m_intendation--; - LINE("}") - } - else - { - WriteMember_Reuse(info, member, modifier, writeType); - } + m_intendation--; + LINE("}") + } else { + WriteMember_Reuse(info, member, modifier, writeType); } + } - void WriteMember_Block(StructureInformation* info, MemberInformation* member, const DeclarationModifierComputations& modifier, MemberWriteType writeType) - { - const MemberComputations computations(member); + void WriteMember_Block(StructureInformation *info, MemberInformation *member, const DeclarationModifierComputations &modifier, MemberWriteType writeType) { + const MemberComputations computations(member); - const auto notInDefaultNormalBlock = computations.IsNotInDefaultNormalBlock(); - if (notInDefaultNormalBlock) - { - LINE("m_stream->PushBlock(" << member->m_fast_file_block->m_name << ");") - } - - WriteMember_PointerCheck(info, member, modifier, writeType); - - if (notInDefaultNormalBlock) - { - LINE("m_stream->PopBlock();") - } + const auto notInDefaultNormalBlock = computations.IsNotInDefaultNormalBlock(); + if (notInDefaultNormalBlock) { + LINE("m_stream->PushBlock(" << member->m_fast_file_block->m_name << ");") } - void WriteMember_ReferenceArray(StructureInformation* info, MemberInformation* member, const DeclarationModifierComputations& modifier) - { - auto first = true; - for (const auto& entry : modifier.GetArrayEntries()) - { - if (first) - { - first = false; - } - else - { - LINE("") - } - - WriteMember_Reference(info, member, entry); - } - } + WriteMember_PointerCheck(info, member, modifier, writeType); - void WriteMember_Reference(StructureInformation* info, MemberInformation* member, const DeclarationModifierComputations& modifier) - { - if (modifier.IsDynamicArray()) - { - WriteMember_Block(info, member, modifier, MemberWriteType::DYNAMIC_ARRAY); - } - else if (modifier.IsSinglePointer()) - { - WriteMember_Block(info, member, modifier, MemberWriteType::SINGLE_POINTER); - } - else if (modifier.IsArrayPointer()) - { - WriteMember_Block(info, member, modifier, MemberWriteType::ARRAY_POINTER); - } - else if (modifier.IsPointerArray()) - { - WriteMember_Block(info, member, modifier, MemberWriteType::POINTER_ARRAY); - } - else if (modifier.IsArray() && modifier.GetNextDeclarationModifier() == nullptr) - { - WriteMember_Block(info, member, modifier, MemberWriteType::EMBEDDED_ARRAY); - } - else if (modifier.GetDeclarationModifier() == nullptr) - { - WriteMember_Block(info, member, modifier, MemberWriteType::EMBEDDED); - } - else if (modifier.IsArray()) - { - WriteMember_ReferenceArray(info, member, modifier); - } - else - { - assert(false); - LINE("#error WriteMemberReference failed @ " << member->m_member->m_name) - } + if (notInDefaultNormalBlock) { + LINE("m_stream->PopBlock();") } + } - void WriteMember_Condition_Struct(StructureInformation* info, MemberInformation* member) - { + void WriteMember_ReferenceArray(StructureInformation *info, MemberInformation *member, const DeclarationModifierComputations &modifier) { + auto first = true; + for (const auto &entry : modifier.GetArrayEntries()) { + if (first) { + first = false; + } else { LINE("") - if (member->m_condition) - { - LINE("if(" << MakeEvaluation(member->m_condition.get()) << ")") - LINE("{") - m_intendation++; - - WriteMember_Reference(info, member, DeclarationModifierComputations(member)); - - m_intendation--; - LINE("}") - } - else - { - WriteMember_Reference(info, member, DeclarationModifierComputations(member)); - } - } - - void WriteMember_Condition_Union(StructureInformation* info, MemberInformation* member) - { - const MemberComputations computations(member); - - if (computations.IsFirstMember()) - { - LINE("") - if (member->m_condition) - { - LINE("if(" << MakeEvaluation(member->m_condition.get()) << ")") - LINE("{") - m_intendation++; - - WriteMember_Reference(info, member, DeclarationModifierComputations(member)); - - m_intendation--; - LINE("}") - } - else - { - WriteMember_Reference(info, member, DeclarationModifierComputations(member)); - } - } - else if (computations.IsLastMember()) - { - if (member->m_condition) - { - LINE("else if(" << MakeEvaluation(member->m_condition.get()) << ")") - LINE("{") - m_intendation++; - - WriteMember_Reference(info, member, DeclarationModifierComputations(member)); - - m_intendation--; - LINE("}") - } - else - { - LINE("else") - LINE("{") - m_intendation++; - - WriteMember_Reference(info, member, DeclarationModifierComputations(member)); - - m_intendation--; - LINE("}") - } - } - else - { - if (member->m_condition) - { - LINE("else if(" << MakeEvaluation(member->m_condition.get()) << ")") - LINE("{") - m_intendation++; - - WriteMember_Reference(info, member, DeclarationModifierComputations(member)); - - m_intendation--; - LINE("}") - } - else - { - LINE("#error Middle member of union must have condition (" << member->m_member->m_name << ")") - } - } - } - - void PrintWriteMemberIfNeedsTreatment(StructureInformation* info, MemberInformation* member) - { - const MemberComputations computations(member); - if (computations.ShouldIgnore()) - return; - - if (member->m_is_string - || member->m_is_script_string - || computations.ContainsNonEmbeddedReference() - || member->m_type && !member->m_type->m_is_leaf - || computations.IsAfterPartialLoad()) - { - if (info->m_definition->GetType() == DataDefinitionType::UNION) - WriteMember_Condition_Union(info, member); - else - WriteMember_Condition_Struct(info, member); - } - } - - void PrintWriteMethod(StructureInformation* info) - { - const StructureComputations computations(info); - LINE("void " << WriterClassName(m_env.m_asset) << "::Write_" << info->m_definition->m_name << "(const bool atStreamStart)") + } + + WriteMember_Reference(info, member, entry); + } + } + + void WriteMember_Reference(StructureInformation *info, MemberInformation *member, const DeclarationModifierComputations &modifier) { + if (modifier.IsDynamicArray()) { + WriteMember_Block(info, member, modifier, MemberWriteType::DYNAMIC_ARRAY); + } else if (modifier.IsSinglePointer()) { + WriteMember_Block(info, member, modifier, MemberWriteType::SINGLE_POINTER); + } else if (modifier.IsArrayPointer()) { + WriteMember_Block(info, member, modifier, MemberWriteType::ARRAY_POINTER); + } else if (modifier.IsPointerArray()) { + WriteMember_Block(info, member, modifier, MemberWriteType::POINTER_ARRAY); + } else if (modifier.IsArray() && modifier.GetNextDeclarationModifier() == nullptr) { + WriteMember_Block(info, member, modifier, MemberWriteType::EMBEDDED_ARRAY); + } else if (modifier.GetDeclarationModifier() == nullptr) { + WriteMember_Block(info, member, modifier, MemberWriteType::EMBEDDED); + } else if (modifier.IsArray()) { + WriteMember_ReferenceArray(info, member, modifier); + } else { + assert(false); + LINE("#error WriteMemberReference failed @ " << member->m_member->m_name) + } + } + + void WriteMember_Condition_Struct(StructureInformation *info, MemberInformation *member) { + LINE("") + if (member->m_condition) { + LINE("if(" << MakeEvaluation(member->m_condition.get()) << ")") + LINE("{") + m_intendation++; + + WriteMember_Reference(info, member, DeclarationModifierComputations(member)); + + m_intendation--; + LINE("}") + } else { + WriteMember_Reference(info, member, DeclarationModifierComputations(member)); + } + } + + void WriteMember_Condition_Union(StructureInformation *info, MemberInformation *member) { + const MemberComputations computations(member); + + if (computations.IsFirstMember()) { + LINE("") + if (member->m_condition) { + LINE("if(" << MakeEvaluation(member->m_condition.get()) << ")") LINE("{") m_intendation++; - LINE("assert(" << MakeTypeVarName(info->m_definition) << " != nullptr);") - LINE("") - - auto* dynamicMember = computations.GetDynamicMember(); - if (!(info->m_definition->GetType() == DataDefinitionType::UNION && dynamicMember)) - { - LINE("if(atStreamStart)") - m_intendation++; - - if (dynamicMember == nullptr) - { - LINE(MakeTypeWrittenVarName(info->m_definition)<<" = m_stream->Write<" << info->m_definition->GetFullName() << ">(" << MakeTypeVarName(info->m_definition) << "); // Size: " - << info->m_definition->GetSize()) - } - else - { - LINE(MakeTypeWrittenVarName(info->m_definition) << " = m_stream->WritePartial<" << info->m_definition->GetFullName() << ">(" << MakeTypeVarName(info->m_definition) << ", offsetof(" << - info->m_definition->GetFullName() << ", " << dynamicMember->m_member->m_name << "));") - } - - m_intendation--; - - LINE("") - LINE("assert(" << MakeTypeWrittenVarName(info->m_definition) << " != nullptr);") - } - else - { - LINE("assert(atStreamStart);") - } - - if (computations.IsAsset()) - { - LINE("") - LINE("m_stream->PushBlock(" << m_env.m_default_normal_block->m_name << ");") - } - else if (info->m_block) - { - LINE("") - LINE("m_stream->PushBlock(" << info->m_block->m_name << ");") - } - - for (const auto& member : info->m_ordered_members) - { - PrintWriteMemberIfNeedsTreatment(info, member.get()); - } - - if (info->m_block || computations.IsAsset()) - { - LINE("") - LINE("m_stream->PopBlock();") - } + WriteMember_Reference(info, member, DeclarationModifierComputations(member)); m_intendation--; LINE("}") - } - - void PrintWritePtrMethod(StructureInformation* info) - { - const bool inTemp = info->m_block && info->m_block->m_type == FastFileBlockType::TEMP; - LINE("void " << WriterClassName(m_env.m_asset) << "::WritePtr_" << MakeSafeTypeName(info->m_definition) << "(const bool atStreamStart)") + } else { + WriteMember_Reference(info, member, DeclarationModifierComputations(member)); + } + } else if (computations.IsLastMember()) { + if (member->m_condition) { + LINE("else if(" << MakeEvaluation(member->m_condition.get()) << ")") LINE("{") m_intendation++; - LINE("assert(" << MakeTypePtrVarName(info->m_definition) << " != nullptr);") - LINE("") - - LINE("if(atStreamStart)") - m_intendation++; - LINE(MakeTypeWrittenPtrVarName(info->m_definition)<<" = m_stream->Write<" << info->m_definition->GetFullName() << "*>(" << MakeTypePtrVarName(info->m_definition) << ");") - m_intendation--; - - LINE("") - LINE("assert(" << MakeTypeWrittenPtrVarName(info->m_definition) << " != nullptr);") - - LINE("") - if (inTemp) - { - LINE("m_stream->PushBlock(" << m_env.m_default_temp_block->m_name << ");") - LINE("") - } - LINE("if(m_stream->ReusableShouldWrite(" << MakeTypeWrittenPtrVarName(info->m_definition) << "))") - LINE("{") - m_intendation++; - - LINE("m_stream->Align(" << info->m_definition->GetAlignment() << ");") - LINE("m_stream->ReusableAddOffset(*"<<MakeTypePtrVarName(info->m_definition)<<");") - LINE("") - if (!info->m_is_leaf) - { - LINE(MakeTypeVarName(info->m_definition) << " = *" << MakeTypePtrVarName(info->m_definition) << ";") - LINE("Write_" << MakeSafeTypeName(info->m_definition) << "(true);") - } - else - { - LINE("#error Ptr method cannot have leaf type") - } - - LINE("") - LINE("m_stream->MarkFollowing(*"<<MakeTypeWrittenPtrVarName(info->m_definition)<<");") - - m_intendation--; - LINE("}") - - if (inTemp) - { - LINE("") - LINE("m_stream->PopBlock();") - } + WriteMember_Reference(info, member, DeclarationModifierComputations(member)); m_intendation--; LINE("}") - } - - void PrintMainWriteMethod() - { - LINE("void " << WriterClassName(m_env.m_asset) << "::Write(" << m_env.m_asset->m_definition->GetFullName() << "** pAsset)") + } else { + LINE("else") LINE("{") m_intendation++; - LINE("assert(pAsset != nullptr);") - LINE("assert(m_asset != nullptr);") - LINE("assert(m_asset->m_ptr != nullptr);") - LINE("") - LINE("auto* zoneAsset = static_cast<"<<m_env.m_asset->m_definition->GetFullName()<<"*>(m_asset->m_ptr);") - LINE(MakeTypePtrVarName(m_env.m_asset->m_definition) << " = &zoneAsset;") - LINE(MakeTypeWrittenPtrVarName(m_env.m_asset->m_definition) << " = &zoneAsset;") - LINE("WritePtr_" << MakeSafeTypeName(m_env.m_asset->m_definition) << "(false);") - LINE("*pAsset = zoneAsset;") + WriteMember_Reference(info, member, DeclarationModifierComputations(member)); m_intendation--; LINE("}") - } - - void PrintGetNameMethod() - { - LINE("std::string " << WriterClassName(m_env.m_asset) << "::GetAssetName(" << m_env.m_asset->m_definition->GetFullName() << "* pAsset)") + } + } else { + if (member->m_condition) { + LINE("else if(" << MakeEvaluation(member->m_condition.get()) << ")") LINE("{") m_intendation++; - if (!m_env.m_asset->m_name_chain.empty()) - { - LINE_START("return pAsset") - - auto first = true; - for (auto* member : m_env.m_asset->m_name_chain) - { - if (first) - { - first = false; - LINE_MIDDLE("->" << member->m_member->m_name) - } - else - { - LINE_MIDDLE("." << member->m_member->m_name) - } - } - LINE_END(";") - } - else - { - LINE("return \"" << m_env.m_asset->m_definition->m_name << "\";") - } + WriteMember_Reference(info, member, DeclarationModifierComputations(member)); m_intendation--; LINE("}") - } + } else { + LINE("#error Middle member of union must have condition (" << member->m_member->m_name << ")") + } + } + } + + void PrintWriteMemberIfNeedsTreatment(StructureInformation *info, MemberInformation *member) { + const MemberComputations computations(member); + if (computations.ShouldIgnore()) + return; - void PrintWritePtrArrayMethod_Loading(const DataDefinition* def, StructureInformation* info, const bool reusable) const - { - LINE("m_stream->Align("<<def->GetAlignment()<<");") - - if (reusable) - { - LINE("m_stream->ReusableAddOffset(*"<<MakeTypePtrVarName(def)<< ");") - } - - if (info && !info->m_is_leaf) - { - LINE(MakeTypeVarName(info->m_definition) << " = *" << MakeTypePtrVarName(def) << ";") - LINE("Write_" << MakeSafeTypeName(def) << "(true);") - } - else - { - LINE("m_stream->Write<" << def->GetFullName() << ">(*" << MakeTypePtrVarName(def) << ");") - } - LINE("m_stream->MarkFollowing(*"<< MakeTypeWrittenPtrVarName(def)<<");") + if (member->m_is_string || member->m_is_script_string || computations.ContainsNonEmbeddedReference() || member->m_type && !member->m_type->m_is_leaf || + computations.IsAfterPartialLoad()) { + if (info->m_definition->GetType() == DataDefinitionType::UNION) + WriteMember_Condition_Union(info, member); + else + WriteMember_Condition_Struct(info, member); } + } - void PrintWritePtrArrayMethod_PointerCheck(const DataDefinition* def, StructureInformation* info, const bool reusable) - { - LINE("if (*" << MakeTypePtrVarName(def) << ")") - LINE("{") - m_intendation++; + void PrintWriteMethod(StructureInformation *info) { + const StructureComputations computations(info); + LINE("void " << WriterClassName(m_env.m_asset) << "::Write_" << info->m_definition->m_name << "(const bool atStreamStart)") + LINE("{") + m_intendation++; - if (info && StructureComputations(info).IsAsset()) - { - LINE(WriterClassName(info) << " writer(*"<< MakeTypePtrVarName(def)<<", m_zone, m_stream);") - LINE("writer.Write(" << MakeTypeWrittenPtrVarName(def) << ");") - } - else - { - if (reusable) - { - LINE("if(m_stream->ReusableShouldWrite(" << MakeTypeWrittenPtrVarName(def) << "))") - LINE("{") - m_intendation++; - - PrintWritePtrArrayMethod_Loading(def, info, reusable); - - m_intendation--; - LINE("}") - } - else - { - PrintWritePtrArrayMethod_Loading(def, info, reusable); - } - } + LINE("assert(" << MakeTypeVarName(info->m_definition) << " != nullptr);") + LINE("") - m_intendation--; - LINE("}") - } + auto *dynamicMember = computations.GetDynamicMember(); + if (!(info->m_definition->GetType() == DataDefinitionType::UNION && dynamicMember)) { + LINE("if(atStreamStart)") + m_intendation++; - void PrintWritePtrArrayMethod(const DataDefinition* def, StructureInformation* info, const bool reusable) - { - LINE("void " << WriterClassName(m_env.m_asset) << "::WritePtrArray_" << MakeSafeTypeName(def) << "(const bool atStreamStart, const size_t count)") - LINE("{") - m_intendation++; + if (dynamicMember == nullptr) { + LINE(MakeTypeWrittenVarName(info->m_definition) << " = m_stream->Write<" << info->m_definition->GetFullName() << ">(" + << MakeTypeVarName(info->m_definition) << "); // Size: " << info->m_definition->GetSize()) + } else { + LINE(MakeTypeWrittenVarName(info->m_definition) + << " = m_stream->WritePartial<" << info->m_definition->GetFullName() << ">(" << MakeTypeVarName(info->m_definition) << ", offsetof(" + << info->m_definition->GetFullName() << ", " << dynamicMember->m_member->m_name << "));") + } - LINE("assert(" << MakeTypePtrVarName(def) << " != nullptr);") - LINE("") + m_intendation--; + + LINE("") + LINE("assert(" << MakeTypeWrittenVarName(info->m_definition) << " != nullptr);") + } else { + LINE("assert(atStreamStart);") + } - LINE("if(atStreamStart)") - m_intendation++; - LINE(MakeTypeWrittenPtrVarName(def)<<" = m_stream->Write<" << def->GetFullName() << "*>(" << MakeTypePtrVarName(def) << ", count);") - m_intendation--; + if (computations.IsAsset()) { + LINE("") + LINE("m_stream->PushBlock(" << m_env.m_default_normal_block->m_name << ");") + } else if (info->m_block) { + LINE("") + LINE("m_stream->PushBlock(" << info->m_block->m_name << ");") + } + + for (const auto &member : info->m_ordered_members) { + PrintWriteMemberIfNeedsTreatment(info, member.get()); + } + + if (info->m_block || computations.IsAsset()) { + LINE("") + LINE("m_stream->PopBlock();") + } + + m_intendation--; + LINE("}") + } + + void PrintWritePtrMethod(StructureInformation *info) { + const bool inTemp = info->m_block && info->m_block->m_type == FastFileBlockType::TEMP; + LINE("void " << WriterClassName(m_env.m_asset) << "::WritePtr_" << MakeSafeTypeName(info->m_definition) << "(const bool atStreamStart)") + LINE("{") + m_intendation++; - LINE("") - LINE("assert(" << MakeTypeWrittenPtrVarName(def) << " != nullptr);") + LINE("assert(" << MakeTypePtrVarName(info->m_definition) << " != nullptr);") + LINE("") + + LINE("if(atStreamStart)") + m_intendation++; + LINE(MakeTypeWrittenPtrVarName(info->m_definition) + << " = m_stream->Write<" << info->m_definition->GetFullName() << "*>(" << MakeTypePtrVarName(info->m_definition) << ");") + m_intendation--; - LINE("") - LINE(def->GetFullName() << "** var = " << MakeTypePtrVarName(def) << ";") - LINE(def->GetFullName() << "** varWritten = " << MakeTypeWrittenPtrVarName(def) << ";") - LINE("for(size_t index = 0; index < count; index++)") - LINE("{") - m_intendation++; + LINE("") + LINE("assert(" << MakeTypeWrittenPtrVarName(info->m_definition) << " != nullptr);") - LINE(MakeTypePtrVarName(def) << " = var;") - LINE(MakeTypeWrittenPtrVarName(def) << " = varWritten;") - PrintWritePtrArrayMethod_PointerCheck(def, info, reusable); - LINE("") - LINE("var++;") - LINE("varWritten++;") + LINE("") + if (inTemp) { + LINE("m_stream->PushBlock(" << m_env.m_default_temp_block->m_name << ");") + LINE("") + } + LINE("if(m_stream->ReusableShouldWrite(" << MakeTypeWrittenPtrVarName(info->m_definition) << "))") + LINE("{") + m_intendation++; + + LINE("m_stream->Align(" << info->m_definition->GetAlignment() << ");") + LINE("m_stream->ReusableAddOffset(*" << MakeTypePtrVarName(info->m_definition) << ");") + LINE("") + if (!info->m_is_leaf) { + LINE(MakeTypeVarName(info->m_definition) << " = *" << MakeTypePtrVarName(info->m_definition) << ";") + LINE("Write_" << MakeSafeTypeName(info->m_definition) << "(true);") + } else { + LINE("#error Ptr method cannot have leaf type") + } + + LINE("") + LINE("m_stream->MarkFollowing(*" << MakeTypeWrittenPtrVarName(info->m_definition) << ");") + + m_intendation--; + LINE("}") + + if (inTemp) { + LINE("") + LINE("m_stream->PopBlock();") + } + + m_intendation--; + LINE("}") + } + + void PrintMainWriteMethod() { + LINE("void " << WriterClassName(m_env.m_asset) << "::Write(" << m_env.m_asset->m_definition->GetFullName() << "** pAsset)") + LINE("{") + m_intendation++; + + LINE("assert(pAsset != nullptr);") + LINE("assert(m_asset != nullptr);") + LINE("assert(m_asset->m_ptr != nullptr);") + LINE("") + LINE("auto* zoneAsset = static_cast<" << m_env.m_asset->m_definition->GetFullName() << "*>(m_asset->m_ptr);") + LINE(MakeTypePtrVarName(m_env.m_asset->m_definition) << " = &zoneAsset;") + LINE(MakeTypeWrittenPtrVarName(m_env.m_asset->m_definition) << " = &zoneAsset;") + LINE("WritePtr_" << MakeSafeTypeName(m_env.m_asset->m_definition) << "(false);") + LINE("*pAsset = zoneAsset;") - m_intendation--; - LINE("}") - m_intendation--; - LINE("}") - } + m_intendation--; + LINE("}") + } - void PrintWriteArrayMethod(const DataDefinition* def, StructureInformation* info) - { - LINE("void " << WriterClassName(m_env.m_asset) << "::WriteArray_" << MakeSafeTypeName(def) << "(const bool atStreamStart, const size_t count)") - LINE("{") - m_intendation++; + void PrintGetNameMethod() { + LINE("std::string " << WriterClassName(m_env.m_asset) << "::GetAssetName(" << m_env.m_asset->m_definition->GetFullName() << "* pAsset)") + LINE("{") + m_intendation++; - LINE("assert(" << MakeTypeVarName(def) << " != nullptr);") - LINE("") - LINE("if(atStreamStart)") - m_intendation++; - LINE(MakeTypeWrittenVarName(def)<<" = m_stream->Write<" << def->GetFullName() << ">(" << MakeTypeVarName(def) << ", count);") - m_intendation--; - - LINE("") - LINE("assert(" << MakeTypeWrittenVarName(def) << " != nullptr);") + if (!m_env.m_asset->m_name_chain.empty()) { + LINE_START("return pAsset") - LINE("") - LINE(def->GetFullName() << "* var = " << MakeTypeVarName(def) << ";") - LINE(def->GetFullName() << "* varWritten = " << MakeTypeWrittenVarName(def) << ";") - LINE("for(size_t index = 0; index < count; index++)") + auto first = true; + for (auto *member : m_env.m_asset->m_name_chain) { + if (first) { + first = false; + LINE_MIDDLE("->" << member->m_member->m_name) + } else { + LINE_MIDDLE("." << member->m_member->m_name) + } + } + LINE_END(";") + } else { + LINE("return \"" << m_env.m_asset->m_definition->m_name << "\";") + } + + m_intendation--; + LINE("}") + } + + void PrintWritePtrArrayMethod_Loading(const DataDefinition *def, StructureInformation *info, const bool reusable) const { + LINE("m_stream->Align(" << def->GetAlignment() << ");") + + if (reusable) { + LINE("m_stream->ReusableAddOffset(*" << MakeTypePtrVarName(def) << ");") + } + + if (info && !info->m_is_leaf) { + LINE(MakeTypeVarName(info->m_definition) << " = *" << MakeTypePtrVarName(def) << ";") + LINE("Write_" << MakeSafeTypeName(def) << "(true);") + } else { + LINE("m_stream->Write<" << def->GetFullName() << ">(*" << MakeTypePtrVarName(def) << ");") + } + LINE("m_stream->MarkFollowing(*" << MakeTypeWrittenPtrVarName(def) << ");") + } + + void PrintWritePtrArrayMethod_PointerCheck(const DataDefinition *def, StructureInformation *info, const bool reusable) { + LINE("if (*" << MakeTypePtrVarName(def) << ")") + LINE("{") + m_intendation++; + + if (info && StructureComputations(info).IsAsset()) { + LINE(WriterClassName(info) << " writer(*" << MakeTypePtrVarName(def) << ", m_zone, m_stream);") + LINE("writer.Write(" << MakeTypeWrittenPtrVarName(def) << ");") + } else { + if (reusable) { + LINE("if(m_stream->ReusableShouldWrite(" << MakeTypeWrittenPtrVarName(def) << "))") LINE("{") m_intendation++; - LINE(MakeTypeVarName(info->m_definition) << " = var;") - LINE(MakeTypeWrittenVarName(info->m_definition) << " = varWritten;") - LINE("Write_" << info->m_definition->m_name << "(false);") - LINE("var++;") - LINE("varWritten++;") + PrintWritePtrArrayMethod_Loading(def, info, reusable); m_intendation--; LINE("}") - - m_intendation--; - LINE("}") - } + } else { + PrintWritePtrArrayMethod_Loading(def, info, reusable); + } + } + + m_intendation--; + LINE("}") + } + + void PrintWritePtrArrayMethod(const DataDefinition *def, StructureInformation *info, const bool reusable) { + LINE("void " << WriterClassName(m_env.m_asset) << "::WritePtrArray_" << MakeSafeTypeName(def) << "(const bool atStreamStart, const size_t count)") + LINE("{") + m_intendation++; + + LINE("assert(" << MakeTypePtrVarName(def) << " != nullptr);") + LINE("") + + LINE("if(atStreamStart)") + m_intendation++; + LINE(MakeTypeWrittenPtrVarName(def) << " = m_stream->Write<" << def->GetFullName() << "*>(" << MakeTypePtrVarName(def) << ", count);") + m_intendation--; + + LINE("") + LINE("assert(" << MakeTypeWrittenPtrVarName(def) << " != nullptr);") + + LINE("") + LINE(def->GetFullName() << "** var = " << MakeTypePtrVarName(def) << ";") + LINE(def->GetFullName() << "** varWritten = " << MakeTypeWrittenPtrVarName(def) << ";") + LINE("for(size_t index = 0; index < count; index++)") + LINE("{") + m_intendation++; + + LINE(MakeTypePtrVarName(def) << " = var;") + LINE(MakeTypeWrittenPtrVarName(def) << " = varWritten;") + PrintWritePtrArrayMethod_PointerCheck(def, info, reusable); + LINE("") + LINE("var++;") + LINE("varWritten++;") + + m_intendation--; + LINE("}") + m_intendation--; + LINE("}") + } + + void PrintWriteArrayMethod(const DataDefinition *def, StructureInformation *info) { + LINE("void " << WriterClassName(m_env.m_asset) << "::WriteArray_" << MakeSafeTypeName(def) << "(const bool atStreamStart, const size_t count)") + LINE("{") + m_intendation++; + + LINE("assert(" << MakeTypeVarName(def) << " != nullptr);") + LINE("") + LINE("if(atStreamStart)") + m_intendation++; + LINE(MakeTypeWrittenVarName(def) << " = m_stream->Write<" << def->GetFullName() << ">(" << MakeTypeVarName(def) << ", count);") + m_intendation--; + + LINE("") + LINE("assert(" << MakeTypeWrittenVarName(def) << " != nullptr);") + + LINE("") + LINE(def->GetFullName() << "* var = " << MakeTypeVarName(def) << ";") + LINE(def->GetFullName() << "* varWritten = " << MakeTypeWrittenVarName(def) << ";") + LINE("for(size_t index = 0; index < count; index++)") + LINE("{") + m_intendation++; + + LINE(MakeTypeVarName(info->m_definition) << " = var;") + LINE(MakeTypeWrittenVarName(info->m_definition) << " = varWritten;") + LINE("Write_" << info->m_definition->m_name << "(false);") + LINE("var++;") + LINE("varWritten++;") + + m_intendation--; + LINE("}") + + m_intendation--; + LINE("}") + } public: - Internal(std::ostream& stream, RenderingContext* context) - : BaseTemplate(stream, context) - { - } - - void Header() - { - LINE("// ====================================================================") - LINE("// This file has been generated by ZoneCodeGenerator.") - LINE("// Do not modify. ") - LINE("// Any changes will be discarded when regenerating.") - LINE("// ====================================================================") - LINE("") - LINE("#pragma once") - LINE("") - LINE("#include \"Writing/AssetWriter.h\"") - LINE("#include \"Game/" << m_env.m_game << "/" << m_env.m_game << ".h\"") - LINE("#include <string>") - LINE("") - LINE("namespace " << m_env.m_game) - LINE("{") - m_intendation++; - LINE("class " << WriterClassName(m_env.m_asset) << " final : public AssetWriter") - LINE("{") - m_intendation++; - - LINE(VariableDecl(m_env.m_asset->m_definition)) - LINE(WrittenVariableDecl(m_env.m_asset->m_definition)) - LINE(PointerVariableDecl(m_env.m_asset->m_definition)) - LINE(WrittenPointerVariableDecl(m_env.m_asset->m_definition)) + Internal(std::ostream &stream, RenderingContext *context) : BaseTemplate(stream, context) {} + + void Header() { + LINE("// ====================================================================") + LINE("// This file has been generated by ZoneCodeGenerator.") + LINE("// Do not modify. ") + LINE("// Any changes will be discarded when regenerating.") + LINE("// ====================================================================") + LINE("") + LINE("#pragma once") + LINE("") + LINE("#include \"Writing/AssetWriter.h\"") + LINE("#include \"Game/" << m_env.m_game << "/" << m_env.m_game << ".h\"") + LINE("#include <string>") + LINE("") + LINE("namespace " << m_env.m_game) + LINE("{") + m_intendation++; + LINE("class " << WriterClassName(m_env.m_asset) << " final : public AssetWriter") + LINE("{") + m_intendation++; + + LINE(VariableDecl(m_env.m_asset->m_definition)) + LINE(WrittenVariableDecl(m_env.m_asset->m_definition)) + LINE(PointerVariableDecl(m_env.m_asset->m_definition)) + LINE(WrittenPointerVariableDecl(m_env.m_asset->m_definition)) + LINE("") + + // Variable Declarations: type varType; + for (auto *type : m_env.m_used_types) { + if (type->m_info && !type->m_info->m_definition->m_anonymous && !type->m_info->m_is_leaf && !StructureComputations(type->m_info).IsAsset()) { + LINE(VariableDecl(type->m_type)) + LINE(WrittenVariableDecl(type->m_type)) + } + } + for (auto *type : m_env.m_used_types) { + if (type->m_pointer_array_reference_exists && !type->m_is_context_asset) { + LINE(PointerVariableDecl(type->m_type)) + LINE(WrittenPointerVariableDecl(type->m_type)) + } + } + + LINE("") + + // Method Declarations + for (auto *type : m_env.m_used_types) { + if (type->m_pointer_array_reference_exists) { + PrintHeaderPtrArrayWriteMethodDeclaration(type->m_type); + } + } + for (auto *type : m_env.m_used_types) { + if (type->m_array_reference_exists && type->m_info && !type->m_info->m_is_leaf && type->m_non_runtime_reference_exists) { + PrintHeaderArrayWriteMethodDeclaration(type->m_type); + } + } + for (auto *type : m_env.m_used_structures) { + if (type->m_non_runtime_reference_exists && !type->m_info->m_is_leaf && !StructureComputations(type->m_info).IsAsset()) { + PrintHeaderWriteMethodDeclaration(type->m_info); + } + } + PrintHeaderWriteMethodDeclaration(m_env.m_asset); + PrintHeaderTempPtrWriteMethodDeclaration(m_env.m_asset); + LINE("") + m_intendation--; + LINE("public:") + m_intendation++; + PrintHeaderConstructor(); + PrintHeaderMainWriteMethodDeclaration(m_env.m_asset); + PrintHeaderGetNameMethodDeclaration(m_env.m_asset); + + m_intendation--; + LINE("};") + m_intendation--; + LINE("}") + } + + void Source() { + LINE("// ====================================================================") + LINE("// This file has been generated by ZoneCodeGenerator.") + LINE("// Do not modify. ") + LINE("// Any changes will be discarded when regenerating.") + LINE("// ====================================================================") + LINE("") + LINE("#include \"" << Lower(m_env.m_asset->m_definition->m_name) << "_write_db.h\"") + LINE("#include <cassert>") + LINE("") + + if (!m_env.m_referenced_assets.empty()) { + LINE("// Referenced Assets:") + for (auto *type : m_env.m_referenced_assets) { + LINE("#include \"../" << Lower(type->m_type->m_name) << "/" << Lower(type->m_type->m_name) << "_write_db.h\"") + } + LINE("") + } + LINE("using namespace " << m_env.m_game << ";") + LINE("") + PrintConstructorMethod(); + + for (auto *type : m_env.m_used_types) { + if (type->m_pointer_array_reference_exists) { LINE("") - - // Variable Declarations: type varType; - for (auto* type : m_env.m_used_types) - { - if (type->m_info && !type->m_info->m_definition->m_anonymous && !type->m_info->m_is_leaf && !StructureComputations(type->m_info).IsAsset()) - { - LINE(VariableDecl(type->m_type)) - LINE(WrittenVariableDecl(type->m_type)) - } - } - for (auto* type : m_env.m_used_types) - { - if (type->m_pointer_array_reference_exists && !type->m_is_context_asset) - { - LINE(PointerVariableDecl(type->m_type)) - LINE(WrittenPointerVariableDecl(type->m_type)) - } - } - - LINE("") - - // Method Declarations - for (auto* type : m_env.m_used_types) - { - if (type->m_pointer_array_reference_exists) - { - PrintHeaderPtrArrayWriteMethodDeclaration(type->m_type); - } - } - for (auto* type : m_env.m_used_types) - { - if (type->m_array_reference_exists && type->m_info && !type->m_info->m_is_leaf && type->m_non_runtime_reference_exists) - { - PrintHeaderArrayWriteMethodDeclaration(type->m_type); - } - } - for (auto* type : m_env.m_used_structures) - { - if (type->m_non_runtime_reference_exists && !type->m_info->m_is_leaf && !StructureComputations(type->m_info).IsAsset()) - { - PrintHeaderWriteMethodDeclaration(type->m_info); - } - } - PrintHeaderWriteMethodDeclaration(m_env.m_asset); - PrintHeaderTempPtrWriteMethodDeclaration(m_env.m_asset); - LINE("") - m_intendation--; - LINE("public:") - m_intendation++; - PrintHeaderConstructor(); - PrintHeaderMainWriteMethodDeclaration(m_env.m_asset); - PrintHeaderGetNameMethodDeclaration(m_env.m_asset); - - m_intendation--; - LINE("};") - m_intendation--; - LINE("}") + PrintWritePtrArrayMethod(type->m_type, type->m_info, type->m_pointer_array_reference_is_reusable); + } } - - void Source() - { - LINE("// ====================================================================") - LINE("// This file has been generated by ZoneCodeGenerator.") - LINE("// Do not modify. ") - LINE("// Any changes will be discarded when regenerating.") - LINE("// ====================================================================") - LINE("") - LINE("#include \"" << Lower(m_env.m_asset->m_definition->m_name) << "_write_db.h\"") - LINE("#include <cassert>") - LINE("") - - if (!m_env.m_referenced_assets.empty()) - { - LINE("// Referenced Assets:") - for (auto* type : m_env.m_referenced_assets) - { - LINE("#include \"../" << Lower(type->m_type->m_name) << "/" << Lower(type->m_type->m_name) << "_write_db.h\"") - } - LINE("") - } - LINE("using namespace " << m_env.m_game << ";") - LINE("") - PrintConstructorMethod(); - - for (auto* type : m_env.m_used_types) - { - if (type->m_pointer_array_reference_exists) - { - LINE("") - PrintWritePtrArrayMethod(type->m_type, type->m_info, type->m_pointer_array_reference_is_reusable); - } - } - for (auto* type : m_env.m_used_types) - { - if (type->m_array_reference_exists && type->m_info && !type->m_info->m_is_leaf && type->m_non_runtime_reference_exists) - { - LINE("") - PrintWriteArrayMethod(type->m_type, type->m_info); - } - } - for (auto* type : m_env.m_used_structures) - { - if (type->m_non_runtime_reference_exists && !type->m_info->m_is_leaf && !StructureComputations(type->m_info).IsAsset()) - { - LINE("") - PrintWriteMethod(type->m_info); - } - } - LINE("") - PrintWriteMethod(m_env.m_asset); - LINE("") - PrintWritePtrMethod(m_env.m_asset); + for (auto *type : m_env.m_used_types) { + if (type->m_array_reference_exists && type->m_info && !type->m_info->m_is_leaf && type->m_non_runtime_reference_exists) { LINE("") - PrintMainWriteMethod(); - LINE("") - PrintGetNameMethod(); + PrintWriteArrayMethod(type->m_type, type->m_info); + } } + for (auto *type : m_env.m_used_structures) { + if (type->m_non_runtime_reference_exists && !type->m_info->m_is_leaf && !StructureComputations(type->m_info).IsAsset()) { + LINE("") + PrintWriteMethod(type->m_info); + } + } + LINE("") + PrintWriteMethod(m_env.m_asset); + LINE("") + PrintWritePtrMethod(m_env.m_asset); + LINE("") + PrintMainWriteMethod(); + LINE("") + PrintGetNameMethod(); + } }; -std::vector<CodeTemplateFile> ZoneWriteTemplate::GetFilesToRender(RenderingContext* context) -{ - std::vector<CodeTemplateFile> files; +std::vector<CodeTemplateFile> ZoneWriteTemplate::GetFilesToRender(RenderingContext *context) { + std::vector<CodeTemplateFile> files; - auto assetName = context->m_asset->m_definition->m_name; - for (auto& c : assetName) - c = static_cast<char>(tolower(c)); + auto assetName = context->m_asset->m_definition->m_name; + for (auto &c : assetName) + c = static_cast<char>(tolower(c)); - { - std::ostringstream str; - str << assetName << '/' << assetName << "_write_db.h"; - files.emplace_back(str.str(), TAG_HEADER); - } + { + std::ostringstream str; + str << assetName << '/' << assetName << "_write_db.h"; + files.emplace_back(str.str(), TAG_HEADER); + } - { - std::ostringstream str; - str << assetName << '/' << assetName << "_write_db.cpp"; - files.emplace_back(str.str(), TAG_SOURCE); - } + { + std::ostringstream str; + str << assetName << '/' << assetName << "_write_db.cpp"; + files.emplace_back(str.str(), TAG_SOURCE); + } - return files; + return files; } -void ZoneWriteTemplate::RenderFile(std::ostream& stream, const int fileTag, RenderingContext* context) -{ - Internal internal(stream, context); +void ZoneWriteTemplate::RenderFile(std::ostream &stream, const int fileTag, RenderingContext *context) { + Internal internal(stream, context); - if (fileTag == TAG_HEADER) - { - internal.Header(); - } - else if (fileTag == TAG_SOURCE) - { - internal.Source(); - } - else - { - std::cout << "Unknown tag for ZoneWriteTemplate: " << fileTag << "\n"; - } + if (fileTag == TAG_HEADER) { + internal.Header(); + } else if (fileTag == TAG_SOURCE) { + internal.Source(); + } else { + std::cout << "Unknown tag for ZoneWriteTemplate: " << fileTag << "\n"; + } } diff --git a/src/ZoneCodeGeneratorLib/Generating/Templates/ZoneWriteTemplate.h b/src/ZoneCodeGeneratorLib/Generating/Templates/ZoneWriteTemplate.h index afbbe2f12..7c9d4ae01 100644 --- a/src/ZoneCodeGeneratorLib/Generating/Templates/ZoneWriteTemplate.h +++ b/src/ZoneCodeGeneratorLib/Generating/Templates/ZoneWriteTemplate.h @@ -1,14 +1,13 @@ #pragma once #include "Generating/ICodeTemplate.h" -class ZoneWriteTemplate final : public ICodeTemplate -{ - static constexpr int TAG_HEADER = 1; - static constexpr int TAG_SOURCE = 2; +class ZoneWriteTemplate final : public ICodeTemplate { + static constexpr int TAG_HEADER = 1; + static constexpr int TAG_SOURCE = 2; - class Internal; + class Internal; public: - std::vector<CodeTemplateFile> GetFilesToRender(RenderingContext* context) override; - void RenderFile(std::ostream& stream, int fileTag, RenderingContext* context) override; + std::vector<CodeTemplateFile> GetFilesToRender(RenderingContext *context) override; + void RenderFile(std::ostream &stream, int fileTag, RenderingContext *context) override; }; diff --git a/src/ZoneCodeGeneratorLib/Parsing/Commands/CommandsFileReader.cpp b/src/ZoneCodeGeneratorLib/Parsing/Commands/CommandsFileReader.cpp index c9bd679d4..2e5d6652b 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Commands/CommandsFileReader.cpp +++ b/src/ZoneCodeGeneratorLib/Parsing/Commands/CommandsFileReader.cpp @@ -16,81 +16,69 @@ #include "Parsing/PostProcessing/UnionsPostProcessor.h" #include "Parsing/PostProcessing/UsagesPostProcessor.h" -CommandsFileReader::CommandsFileReader(const ZoneCodeGeneratorArguments* args, std::string filename) - : m_args(args), - m_filename(std::move(filename)), - m_stream(nullptr) -{ - SetupPostProcessors(); +CommandsFileReader::CommandsFileReader(const ZoneCodeGeneratorArguments *args, std::string filename) + : m_args(args), m_filename(std::move(filename)), m_stream(nullptr) { + SetupPostProcessors(); } -bool CommandsFileReader::OpenBaseStream() -{ - auto stream = std::make_unique<ParserFilesystemStream>(m_filename); - if (!stream->IsOpen()) - { - std::cout << "Could not open commands file" << std::endl; - return false; - } - - m_stream = stream.get(); - m_open_streams.emplace_back(std::move(stream)); - return true; +bool CommandsFileReader::OpenBaseStream() { + auto stream = std::make_unique<ParserFilesystemStream>(m_filename); + if (!stream->IsOpen()) { + std::cout << "Could not open commands file" << std::endl; + return false; + } + + m_stream = stream.get(); + m_open_streams.emplace_back(std::move(stream)); + return true; } -void CommandsFileReader::SetupStreamProxies() -{ - auto commentProxy = std::make_unique<CommentRemovingStreamProxy>(m_stream); - auto includeProxy = std::make_unique<IncludingStreamProxy>(commentProxy.get()); - auto definesProxy = std::make_unique<DefinesStreamProxy>(includeProxy.get()); - definesProxy->AddDefine(DefinesStreamProxy::Define(ZONE_CODE_GENERATOR_DEFINE_NAME, ZONE_CODE_GENERATOR_DEFINE_VALUE)); +void CommandsFileReader::SetupStreamProxies() { + auto commentProxy = std::make_unique<CommentRemovingStreamProxy>(m_stream); + auto includeProxy = std::make_unique<IncludingStreamProxy>(commentProxy.get()); + auto definesProxy = std::make_unique<DefinesStreamProxy>(includeProxy.get()); + definesProxy->AddDefine(DefinesStreamProxy::Define(ZONE_CODE_GENERATOR_DEFINE_NAME, ZONE_CODE_GENERATOR_DEFINE_VALUE)); - m_stream = definesProxy.get(); + m_stream = definesProxy.get(); - m_open_streams.emplace_back(std::move(commentProxy)); - m_open_streams.emplace_back(std::move(includeProxy)); - m_open_streams.emplace_back(std::move(definesProxy)); + m_open_streams.emplace_back(std::move(commentProxy)); + m_open_streams.emplace_back(std::move(includeProxy)); + m_open_streams.emplace_back(std::move(definesProxy)); } -void CommandsFileReader::SetupPostProcessors() -{ - // Order is important - m_post_processors.emplace_back(std::make_unique<CalculateSizeAndAlignPostProcessor>()); - m_post_processors.emplace_back(std::make_unique<UsagesPostProcessor>()); - m_post_processors.emplace_back(std::make_unique<LeafsPostProcessor>()); - m_post_processors.emplace_back(std::make_unique<MemberLeafsPostProcessor>()); - m_post_processors.emplace_back(std::make_unique<UnionsPostProcessor>()); +void CommandsFileReader::SetupPostProcessors() { + // Order is important + m_post_processors.emplace_back(std::make_unique<CalculateSizeAndAlignPostProcessor>()); + m_post_processors.emplace_back(std::make_unique<UsagesPostProcessor>()); + m_post_processors.emplace_back(std::make_unique<LeafsPostProcessor>()); + m_post_processors.emplace_back(std::make_unique<MemberLeafsPostProcessor>()); + m_post_processors.emplace_back(std::make_unique<UnionsPostProcessor>()); } -bool CommandsFileReader::ReadCommandsFile(IDataRepository* repository) -{ - if(m_args->m_verbose) - { - std::cout << "Reading commands file: " << m_filename << std::endl; - } +bool CommandsFileReader::ReadCommandsFile(IDataRepository *repository) { + if (m_args->m_verbose) { + std::cout << "Reading commands file: " << m_filename << std::endl; + } - if (!OpenBaseStream()) - return false; + if (!OpenBaseStream()) + return false; - SetupStreamProxies(); + SetupStreamProxies(); - const auto lexer = std::make_unique<CommandsLexer>(m_stream); - const auto parser = std::make_unique<CommandsParser>(lexer.get(), repository); + const auto lexer = std::make_unique<CommandsLexer>(m_stream); + const auto parser = std::make_unique<CommandsParser>(lexer.get(), repository); - const auto start = std::chrono::steady_clock::now(); - const auto result = parser->Parse(); - const auto end = std::chrono::steady_clock::now(); + const auto start = std::chrono::steady_clock::now(); + const auto result = parser->Parse(); + const auto end = std::chrono::steady_clock::now(); - if(m_args->m_verbose) - { - std::cout << "Processing commands took " << std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count() << "ms" << std::endl; - } + if (m_args->m_verbose) { + std::cout << "Processing commands took " << std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count() << "ms" << std::endl; + } - if (!result) - return false; + if (!result) + return false; - return std::all_of(m_post_processors.begin(), m_post_processors.end(), [repository](const std::unique_ptr<IPostProcessor>& postProcessor) - { - return postProcessor->PostProcess(repository); - }); + return std::all_of(m_post_processors.begin(), m_post_processors.end(), + [repository](const std::unique_ptr<IPostProcessor> &postProcessor) { return postProcessor->PostProcess(repository); }); } diff --git a/src/ZoneCodeGeneratorLib/Parsing/Commands/CommandsFileReader.h b/src/ZoneCodeGeneratorLib/Parsing/Commands/CommandsFileReader.h index bfe77f607..191ddcca2 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Commands/CommandsFileReader.h +++ b/src/ZoneCodeGeneratorLib/Parsing/Commands/CommandsFileReader.h @@ -2,30 +2,29 @@ #include <string> -#include "ZoneCodeGeneratorArguments.h" #include "Parsing/IParserLineStream.h" #include "Parsing/PostProcessing/IPostProcessor.h" #include "Persistence/IDataRepository.h" +#include "ZoneCodeGeneratorArguments.h" -class CommandsFileReader -{ - static constexpr const char* ZONE_CODE_GENERATOR_DEFINE_NAME = "__zonecodegenerator"; - static constexpr const char* ZONE_CODE_GENERATOR_DEFINE_VALUE = "1"; +class CommandsFileReader { + static constexpr const char *ZONE_CODE_GENERATOR_DEFINE_NAME = "__zonecodegenerator"; + static constexpr const char *ZONE_CODE_GENERATOR_DEFINE_VALUE = "1"; - const ZoneCodeGeneratorArguments* m_args; - std::string m_filename; + const ZoneCodeGeneratorArguments *m_args; + std::string m_filename; - std::vector<std::unique_ptr<IParserLineStream>> m_open_streams; - IParserLineStream* m_stream; + std::vector<std::unique_ptr<IParserLineStream>> m_open_streams; + IParserLineStream *m_stream; - std::vector<std::unique_ptr<IPostProcessor>> m_post_processors; + std::vector<std::unique_ptr<IPostProcessor>> m_post_processors; - bool OpenBaseStream(); - void SetupStreamProxies(); - void SetupPostProcessors(); + bool OpenBaseStream(); + void SetupStreamProxies(); + void SetupPostProcessors(); public: - explicit CommandsFileReader(const ZoneCodeGeneratorArguments* args, std::string filename); + explicit CommandsFileReader(const ZoneCodeGeneratorArguments *args, std::string filename); - bool ReadCommandsFile(IDataRepository* repository); + bool ReadCommandsFile(IDataRepository *repository); }; diff --git a/src/ZoneCodeGeneratorLib/Parsing/Commands/Impl/CommandsLexer.cpp b/src/ZoneCodeGeneratorLib/Parsing/Commands/Impl/CommandsLexer.cpp index 97ec0b7a8..25bbe0b47 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Commands/Impl/CommandsLexer.cpp +++ b/src/ZoneCodeGeneratorLib/Parsing/Commands/Impl/CommandsLexer.cpp @@ -1,149 +1,123 @@ #include "CommandsLexer.h" -CommandsLexer::CommandsLexer(IParserLineStream* stream) - : AbstractLexer(stream) -{ -} +CommandsLexer::CommandsLexer(IParserLineStream *stream) : AbstractLexer(stream) {} -CommandsParserValue CommandsLexer::GetNextToken() -{ - auto c = NextChar(); - - while (c != EOF) - { - switch (c) - { - case '\"': - { - return CommandsParserValue::String(GetPreviousCharacterPos(), new std::string(ReadString())); - } +CommandsParserValue CommandsLexer::GetNextToken() { + auto c = NextChar(); - case '<': - { - if (!IsLineEnd()) - { - const auto pos = GetPreviousCharacterPos(); - const auto nextChar = PeekChar(); - - if (nextChar == '=') - { - NextChar(); - return CommandsParserValue::LessEqual(pos); - } - if (nextChar == '<') - { - NextChar(); - return CommandsParserValue::ShiftLeft(pos); - } - } - - return CommandsParserValue::Character(GetPreviousCharacterPos(), static_cast<char>(c)); - } + while (c != EOF) { + switch (c) { + case '\"': { + return CommandsParserValue::String(GetPreviousCharacterPos(), new std::string(ReadString())); + } + + case '<': { + if (!IsLineEnd()) { + const auto pos = GetPreviousCharacterPos(); + const auto nextChar = PeekChar(); - case '>': - { - if (!IsLineEnd()) - { - const auto pos = GetPreviousCharacterPos(); - const auto nextChar = PeekChar(); - - if (nextChar == '=') - { - NextChar(); - return CommandsParserValue::GreaterEqual(pos); - } - if (nextChar == '>') - { - NextChar(); - return CommandsParserValue::ShiftRight(pos); - } - } - - return CommandsParserValue::Character(GetPreviousCharacterPos(), static_cast<char>(c)); + if (nextChar == '=') { + NextChar(); + return CommandsParserValue::LessEqual(pos); + } + if (nextChar == '<') { + NextChar(); + return CommandsParserValue::ShiftLeft(pos); } + } - case '=': - { - if (NextCharInLineIs('=')) - { - const auto pos = GetPreviousCharacterPos(); - NextChar(); - return CommandsParserValue::Equals(pos); - } + return CommandsParserValue::Character(GetPreviousCharacterPos(), static_cast<char>(c)); + } + + case '>': { + if (!IsLineEnd()) { + const auto pos = GetPreviousCharacterPos(); + const auto nextChar = PeekChar(); - return CommandsParserValue::Character(GetPreviousCharacterPos(), static_cast<char>(c)); + if (nextChar == '=') { + NextChar(); + return CommandsParserValue::GreaterEqual(pos); + } + if (nextChar == '>') { + NextChar(); + return CommandsParserValue::ShiftRight(pos); } + } - case '&': - { - if (NextCharInLineIs('&')) - { - const auto pos = GetPreviousCharacterPos(); - NextChar(); - return CommandsParserValue::LogicalAnd(pos); - } + return CommandsParserValue::Character(GetPreviousCharacterPos(), static_cast<char>(c)); + } - return CommandsParserValue::Character(GetPreviousCharacterPos(), static_cast<char>(c)); - } + case '=': { + if (NextCharInLineIs('=')) { + const auto pos = GetPreviousCharacterPos(); + NextChar(); + return CommandsParserValue::Equals(pos); + } - case '|': - { - if (NextCharInLineIs('|')) - { - const auto pos = GetPreviousCharacterPos(); - NextChar(); - return CommandsParserValue::LogicalOr(pos); - } + return CommandsParserValue::Character(GetPreviousCharacterPos(), static_cast<char>(c)); + } - return CommandsParserValue::Character(GetPreviousCharacterPos(), static_cast<char>(c)); - } + case '&': { + if (NextCharInLineIs('&')) { + const auto pos = GetPreviousCharacterPos(); + NextChar(); + return CommandsParserValue::LogicalAnd(pos); + } - case '!': - { - if (NextCharInLineIs('=')) - { - const auto pos = GetPreviousCharacterPos(); - NextChar(); - return CommandsParserValue::NotEqual(pos); - } + return CommandsParserValue::Character(GetPreviousCharacterPos(), static_cast<char>(c)); + } - return CommandsParserValue::Character(GetPreviousCharacterPos(), static_cast<char>(c)); - } + case '|': { + if (NextCharInLineIs('|')) { + const auto pos = GetPreviousCharacterPos(); + NextChar(); + return CommandsParserValue::LogicalOr(pos); + } - default: - { - if (isspace(c)) - break; + return CommandsParserValue::Character(GetPreviousCharacterPos(), static_cast<char>(c)); + } - const auto pos = GetPreviousCharacterPos(); - if (isdigit(c)) - { - bool isFloatingPointValue; - bool hasSignPrefix; - double doubleValue; - int integerValue; + case '!': { + if (NextCharInLineIs('=')) { + const auto pos = GetPreviousCharacterPos(); + NextChar(); + return CommandsParserValue::NotEqual(pos); + } - ReadNumber(isFloatingPointValue, hasSignPrefix, doubleValue, integerValue); + return CommandsParserValue::Character(GetPreviousCharacterPos(), static_cast<char>(c)); + } - if (isFloatingPointValue) - return CommandsParserValue::FloatingPoint(pos, doubleValue); + default: { + if (isspace(c)) + break; - return CommandsParserValue::Integer(pos, integerValue); - } + const auto pos = GetPreviousCharacterPos(); + if (isdigit(c)) { + bool isFloatingPointValue; + bool hasSignPrefix; + double doubleValue; + int integerValue; - if (isalpha(c) || c == '_') - { - auto identifier = ReadIdentifier(); + ReadNumber(isFloatingPointValue, hasSignPrefix, doubleValue, integerValue); - return CommandsParserValue::Identifier(pos, new std::string(std::move(identifier))); - } + if (isFloatingPointValue) + return CommandsParserValue::FloatingPoint(pos, doubleValue); - return CommandsParserValue::Character(pos, static_cast<char>(c)); - } - } + return CommandsParserValue::Integer(pos, integerValue); + } + + if (isalpha(c) || c == '_') { + auto identifier = ReadIdentifier(); + + return CommandsParserValue::Identifier(pos, new std::string(std::move(identifier))); + } - c = NextChar(); + return CommandsParserValue::Character(pos, static_cast<char>(c)); } + } + + c = NextChar(); + } - return CommandsParserValue::EndOfFile(TokenPos()); + return CommandsParserValue::EndOfFile(TokenPos()); } diff --git a/src/ZoneCodeGeneratorLib/Parsing/Commands/Impl/CommandsLexer.h b/src/ZoneCodeGeneratorLib/Parsing/Commands/Impl/CommandsLexer.h index 19c0b700f..d032c11b0 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Commands/Impl/CommandsLexer.h +++ b/src/ZoneCodeGeneratorLib/Parsing/Commands/Impl/CommandsLexer.h @@ -3,11 +3,10 @@ #include "CommandsParserValue.h" #include "Parsing/Impl/AbstractLexer.h" -class CommandsLexer final : public AbstractLexer<CommandsParserValue> -{ +class CommandsLexer final : public AbstractLexer<CommandsParserValue> { protected: - CommandsParserValue GetNextToken() override; + CommandsParserValue GetNextToken() override; public: - explicit CommandsLexer(IParserLineStream* stream); + explicit CommandsLexer(IParserLineStream *stream); }; diff --git a/src/ZoneCodeGeneratorLib/Parsing/Commands/Impl/CommandsParser.cpp b/src/ZoneCodeGeneratorLib/Parsing/Commands/Impl/CommandsParser.cpp index 610dde7f4..dc97090fb 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Commands/Impl/CommandsParser.cpp +++ b/src/ZoneCodeGeneratorLib/Parsing/Commands/Impl/CommandsParser.cpp @@ -18,33 +18,14 @@ #include "Parsing/Commands/Sequence/SequenceString.h" #include "Parsing/Commands/Sequence/SequenceUse.h" -CommandsParser::CommandsParser(CommandsLexer* lexer, IDataRepository* targetRepository) - : AbstractParser(lexer, std::make_unique<CommandsParserState>(targetRepository)), - m_repository(targetRepository) -{ -} +CommandsParser::CommandsParser(CommandsLexer *lexer, IDataRepository *targetRepository) + : AbstractParser(lexer, std::make_unique<CommandsParserState>(targetRepository)), m_repository(targetRepository) {} -const std::vector<CommandsParser::sequence_t*>& CommandsParser::GetTestsForState() -{ - static std::vector<sequence_t*> tests({ - new SequenceAction(), - new SequenceAllocAlign(), - new SequenceArchitecture(), - new SequenceArrayCount(), - new SequenceArraySize(), - new SequenceAsset(), - new SequenceBlock(), - new SequenceCondition(), - new SequenceCount(), - new SequenceGame(), - new SequenceName(), - new SequenceReorder(), - new SequenceReusable(), - new SequenceScriptString(), - new SequenceSetBlock(), - new SequenceString(), - new SequenceUse() - }); +const std::vector<CommandsParser::sequence_t *> &CommandsParser::GetTestsForState() { + static std::vector<sequence_t *> tests({new SequenceAction(), new SequenceAllocAlign(), new SequenceArchitecture(), new SequenceArrayCount(), + new SequenceArraySize(), new SequenceAsset(), new SequenceBlock(), new SequenceCondition(), new SequenceCount(), + new SequenceGame(), new SequenceName(), new SequenceReorder(), new SequenceReusable(), new SequenceScriptString(), + new SequenceSetBlock(), new SequenceString(), new SequenceUse()}); - return tests; + return tests; } diff --git a/src/ZoneCodeGeneratorLib/Parsing/Commands/Impl/CommandsParser.h b/src/ZoneCodeGeneratorLib/Parsing/Commands/Impl/CommandsParser.h index b77c5e843..6f06eeb88 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Commands/Impl/CommandsParser.h +++ b/src/ZoneCodeGeneratorLib/Parsing/Commands/Impl/CommandsParser.h @@ -6,13 +6,12 @@ #include "Parsing/Impl/AbstractParser.h" #include "Persistence/IDataRepository.h" -class CommandsParser final : public AbstractParser<CommandsParserValue, CommandsParserState> -{ - IDataRepository* m_repository; +class CommandsParser final : public AbstractParser<CommandsParserValue, CommandsParserState> { + IDataRepository *m_repository; protected: - const std::vector<sequence_t*>& GetTestsForState() override; + const std::vector<sequence_t *> &GetTestsForState() override; public: - CommandsParser(CommandsLexer* lexer, IDataRepository* targetRepository); + CommandsParser(CommandsLexer *lexer, IDataRepository *targetRepository); }; diff --git a/src/ZoneCodeGeneratorLib/Parsing/Commands/Impl/CommandsParserState.cpp b/src/ZoneCodeGeneratorLib/Parsing/Commands/Impl/CommandsParserState.cpp index e7ba6ebd5..5c78ac897 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Commands/Impl/CommandsParserState.cpp +++ b/src/ZoneCodeGeneratorLib/Parsing/Commands/Impl/CommandsParserState.cpp @@ -1,140 +1,106 @@ #include "CommandsParserState.h" -CommandsParserState::CommandsParserState(IDataRepository* repository) - : m_repository(repository), - m_in_use(nullptr) -{ -} +CommandsParserState::CommandsParserState(IDataRepository *repository) : m_repository(repository), m_in_use(nullptr) {} -const IDataRepository* CommandsParserState::GetRepository() const -{ - return m_repository; -} +const IDataRepository *CommandsParserState::GetRepository() const { return m_repository; } -void CommandsParserState::AddBlock(std::unique_ptr<FastFileBlock> block) const -{ - m_repository->Add(std::move(block)); -} +void CommandsParserState::AddBlock(std::unique_ptr<FastFileBlock> block) const { m_repository->Add(std::move(block)); } -void CommandsParserState::SetArchitecture(const Architecture architecture) const -{ - m_repository->SetArchitecture(architecture); -} +void CommandsParserState::SetArchitecture(const Architecture architecture) const { m_repository->SetArchitecture(architecture); } -void CommandsParserState::SetGame(std::string gameName) const -{ - m_repository->SetGame(std::move(gameName)); -} +void CommandsParserState::SetGame(std::string gameName) const { m_repository->SetGame(std::move(gameName)); } -StructureInformation* CommandsParserState::GetInUse() const -{ - return m_in_use; -} +StructureInformation *CommandsParserState::GetInUse() const { return m_in_use; } -void CommandsParserState::SetInUse(StructureInformation* structure) -{ - m_in_use = structure; -} +void CommandsParserState::SetInUse(StructureInformation *structure) { m_in_use = structure; } -MemberInformation* CommandsParserState::GetMemberWithName(const std::string& memberName, StructureInformation* type) -{ - for (const auto& member : type->m_ordered_members) - { - if (member->m_member->m_name == memberName) - { - return member.get(); - } +MemberInformation *CommandsParserState::GetMemberWithName(const std::string &memberName, StructureInformation *type) { + for (const auto &member : type->m_ordered_members) { + if (member->m_member->m_name == memberName) { + return member.get(); } + } - return nullptr; + return nullptr; } -bool CommandsParserState::GetNextTypenameSeparatorPos(const std::string& typeNameValue, const unsigned startPos, unsigned& separatorPos) -{ - const auto typeNameValueSize = typeNameValue.size(); - for (auto currentHead = startPos + 1; currentHead < typeNameValueSize; currentHead++) - { - if (typeNameValue[currentHead] == ':' - && typeNameValue[currentHead - 1] == ':') - { - separatorPos = currentHead - 1; - return true; - } +bool CommandsParserState::GetNextTypenameSeparatorPos(const std::string &typeNameValue, const unsigned startPos, unsigned &separatorPos) { + const auto typeNameValueSize = typeNameValue.size(); + for (auto currentHead = startPos + 1; currentHead < typeNameValueSize; currentHead++) { + if (typeNameValue[currentHead] == ':' && typeNameValue[currentHead - 1] == ':') { + separatorPos = currentHead - 1; + return true; } + } - return false; + return false; } -bool CommandsParserState::ExtractMembersFromTypenameInternal(const std::string& typeNameValue, unsigned typeNameOffset, StructureInformation* type, std::vector<MemberInformation*>& members) -{ - auto startOffset = typeNameOffset; - while (GetNextTypenameSeparatorPos(typeNameValue, typeNameOffset, typeNameOffset)) - { - auto* foundMember = GetMemberWithName(std::string(typeNameValue, startOffset, typeNameOffset - startOffset), type); - - if (foundMember == nullptr) - return false; +bool CommandsParserState::ExtractMembersFromTypenameInternal(const std::string &typeNameValue, unsigned typeNameOffset, StructureInformation *type, + std::vector<MemberInformation *> &members) { + auto startOffset = typeNameOffset; + while (GetNextTypenameSeparatorPos(typeNameValue, typeNameOffset, typeNameOffset)) { + auto *foundMember = GetMemberWithName(std::string(typeNameValue, startOffset, typeNameOffset - startOffset), type); - members.push_back(foundMember); - type = foundMember->m_type; - typeNameOffset += 2; - startOffset = typeNameOffset; - } - - auto* foundMember = GetMemberWithName(std::string(typeNameValue, startOffset, typeNameValue.size() - startOffset), type); if (foundMember == nullptr) - return false; + return false; members.push_back(foundMember); - return true; -} - -bool CommandsParserState::GetMembersFromTypename(const std::string& typeNameValue, StructureInformation* baseType, std::vector<MemberInformation*>& members) const -{ - return m_in_use != nullptr && ExtractMembersFromTypenameInternal(typeNameValue, 0, m_in_use, members) - || ExtractMembersFromTypenameInternal(typeNameValue, 0, baseType, members); -} + type = foundMember->m_type; + typeNameOffset += 2; + startOffset = typeNameOffset; + } -bool CommandsParserState::GetTypenameAndMembersFromTypename(const std::string& typeNameValue, StructureInformation*& structure, std::vector<MemberInformation*>& members) const -{ - if (m_in_use != nullptr) - { - if (ExtractMembersFromTypenameInternal(typeNameValue, 0, m_in_use, members)) - { - structure = m_in_use; - return true; - } - members.clear(); - } + auto *foundMember = GetMemberWithName(std::string(typeNameValue, startOffset, typeNameValue.size() - startOffset), type); + if (foundMember == nullptr) + return false; - DataDefinition* foundDefinition = nullptr; - unsigned currentSeparatorPos = 0; - while (GetNextTypenameSeparatorPos(typeNameValue, currentSeparatorPos, currentSeparatorPos)) - { - std::string currentTypename(typeNameValue, 0, currentSeparatorPos); - currentSeparatorPos += 2; + members.push_back(foundMember); + return true; +} - foundDefinition = m_repository->GetDataDefinitionByName(currentTypename); - if (foundDefinition != nullptr) - break; - } +bool CommandsParserState::GetMembersFromTypename(const std::string &typeNameValue, StructureInformation *baseType, + std::vector<MemberInformation *> &members) const { + return m_in_use != nullptr && ExtractMembersFromTypenameInternal(typeNameValue, 0, m_in_use, members) || + ExtractMembersFromTypenameInternal(typeNameValue, 0, baseType, members); +} - if (foundDefinition == nullptr) - { - currentSeparatorPos = typeNameValue.size(); - foundDefinition = m_repository->GetDataDefinitionByName(typeNameValue); +bool CommandsParserState::GetTypenameAndMembersFromTypename(const std::string &typeNameValue, StructureInformation *&structure, + std::vector<MemberInformation *> &members) const { + if (m_in_use != nullptr) { + if (ExtractMembersFromTypenameInternal(typeNameValue, 0, m_in_use, members)) { + structure = m_in_use; + return true; } + members.clear(); + } + + DataDefinition *foundDefinition = nullptr; + unsigned currentSeparatorPos = 0; + while (GetNextTypenameSeparatorPos(typeNameValue, currentSeparatorPos, currentSeparatorPos)) { + std::string currentTypename(typeNameValue, 0, currentSeparatorPos); + currentSeparatorPos += 2; + + foundDefinition = m_repository->GetDataDefinitionByName(currentTypename); + if (foundDefinition != nullptr) + break; + } + + if (foundDefinition == nullptr) { + currentSeparatorPos = typeNameValue.size(); + foundDefinition = m_repository->GetDataDefinitionByName(typeNameValue); + } + + if (foundDefinition == nullptr) + return false; - if (foundDefinition == nullptr) - return false; - - auto* definitionWithMembers = dynamic_cast<DefinitionWithMembers*>(foundDefinition); - if (definitionWithMembers == nullptr) - return false; + auto *definitionWithMembers = dynamic_cast<DefinitionWithMembers *>(foundDefinition); + if (definitionWithMembers == nullptr) + return false; - structure = m_repository->GetInformationFor(definitionWithMembers); - if (currentSeparatorPos >= typeNameValue.size()) - return true; + structure = m_repository->GetInformationFor(definitionWithMembers); + if (currentSeparatorPos >= typeNameValue.size()) + return true; - return ExtractMembersFromTypenameInternal(typeNameValue, currentSeparatorPos, structure, members); + return ExtractMembersFromTypenameInternal(typeNameValue, currentSeparatorPos, structure, members); } diff --git a/src/ZoneCodeGeneratorLib/Parsing/Commands/Impl/CommandsParserState.h b/src/ZoneCodeGeneratorLib/Parsing/Commands/Impl/CommandsParserState.h index c23b3c807..524c40165 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Commands/Impl/CommandsParserState.h +++ b/src/ZoneCodeGeneratorLib/Parsing/Commands/Impl/CommandsParserState.h @@ -3,30 +3,30 @@ #include <memory> #include <string> -#include "Utils/ClassUtils.h" #include "Persistence/IDataRepository.h" +#include "Utils/ClassUtils.h" -class CommandsParserState -{ - IDataRepository* m_repository; - StructureInformation* m_in_use; +class CommandsParserState { + IDataRepository *m_repository; + StructureInformation *m_in_use; - static MemberInformation* GetMemberWithName(const std::string& memberName, StructureInformation* type); - static bool GetNextTypenameSeparatorPos(const std::string& typeNameValue, unsigned startPos, unsigned& separatorPos); - static bool ExtractMembersFromTypenameInternal(const std::string& typeNameValue, unsigned typeNameOffset, StructureInformation* type, std::vector<MemberInformation*>& members); + static MemberInformation *GetMemberWithName(const std::string &memberName, StructureInformation *type); + static bool GetNextTypenameSeparatorPos(const std::string &typeNameValue, unsigned startPos, unsigned &separatorPos); + static bool ExtractMembersFromTypenameInternal(const std::string &typeNameValue, unsigned typeNameOffset, StructureInformation *type, + std::vector<MemberInformation *> &members); public: - explicit CommandsParserState(IDataRepository* repository); + explicit CommandsParserState(IDataRepository *repository); - _NODISCARD const IDataRepository* GetRepository() const; + _NODISCARD const IDataRepository *GetRepository() const; - void AddBlock(std::unique_ptr<FastFileBlock> block) const; - void SetArchitecture(Architecture architecture) const; - void SetGame(std::string gameName) const; + void AddBlock(std::unique_ptr<FastFileBlock> block) const; + void SetArchitecture(Architecture architecture) const; + void SetGame(std::string gameName) const; - _NODISCARD StructureInformation* GetInUse() const; - void SetInUse(StructureInformation* structure); + _NODISCARD StructureInformation *GetInUse() const; + void SetInUse(StructureInformation *structure); - bool GetMembersFromTypename(const std::string& typeNameValue, StructureInformation* baseType, std::vector<MemberInformation*>& members) const; - bool GetTypenameAndMembersFromTypename(const std::string& typeNameValue, StructureInformation*& structure, std::vector<MemberInformation*>& members) const; + bool GetMembersFromTypename(const std::string &typeNameValue, StructureInformation *baseType, std::vector<MemberInformation *> &members) const; + bool GetTypenameAndMembersFromTypename(const std::string &typeNameValue, StructureInformation *&structure, std::vector<MemberInformation *> &members) const; }; diff --git a/src/ZoneCodeGeneratorLib/Parsing/Commands/Impl/CommandsParserValue.cpp b/src/ZoneCodeGeneratorLib/Parsing/Commands/Impl/CommandsParserValue.cpp index 4ce677a9e..225c5a54b 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Commands/Impl/CommandsParserValue.cpp +++ b/src/ZoneCodeGeneratorLib/Parsing/Commands/Impl/CommandsParserValue.cpp @@ -2,215 +2,171 @@ #include <cassert> -CommandsParserValue CommandsParserValue::Invalid(const TokenPos pos) -{ - CommandsParserValue pv(pos, CommandsParserValueType::INVALID); - return pv; +CommandsParserValue CommandsParserValue::Invalid(const TokenPos pos) { + CommandsParserValue pv(pos, CommandsParserValueType::INVALID); + return pv; } -CommandsParserValue CommandsParserValue::EndOfFile(const TokenPos pos) -{ - CommandsParserValue pv(pos, CommandsParserValueType::END_OF_FILE); - return pv; +CommandsParserValue CommandsParserValue::EndOfFile(const TokenPos pos) { + CommandsParserValue pv(pos, CommandsParserValueType::END_OF_FILE); + return pv; } -CommandsParserValue CommandsParserValue::Character(const TokenPos pos, const char c) -{ - CommandsParserValue pv(pos, CommandsParserValueType::CHARACTER); - pv.m_value.char_value = c; - return pv; +CommandsParserValue CommandsParserValue::Character(const TokenPos pos, const char c) { + CommandsParserValue pv(pos, CommandsParserValueType::CHARACTER); + pv.m_value.char_value = c; + return pv; } -CommandsParserValue CommandsParserValue::ShiftLeft(const TokenPos pos) -{ - CommandsParserValue pv(pos, CommandsParserValueType::SHIFT_LEFT); - return pv; +CommandsParserValue CommandsParserValue::ShiftLeft(const TokenPos pos) { + CommandsParserValue pv(pos, CommandsParserValueType::SHIFT_LEFT); + return pv; } -CommandsParserValue CommandsParserValue::ShiftRight(const TokenPos pos) -{ - CommandsParserValue pv(pos, CommandsParserValueType::SHIFT_RIGHT); - return pv; +CommandsParserValue CommandsParserValue::ShiftRight(const TokenPos pos) { + CommandsParserValue pv(pos, CommandsParserValueType::SHIFT_RIGHT); + return pv; } -CommandsParserValue CommandsParserValue::Equals(const TokenPos pos) -{ - CommandsParserValue pv(pos, CommandsParserValueType::EQUALS); - return pv; +CommandsParserValue CommandsParserValue::Equals(const TokenPos pos) { + CommandsParserValue pv(pos, CommandsParserValueType::EQUALS); + return pv; } -CommandsParserValue CommandsParserValue::NotEqual(const TokenPos pos) -{ - CommandsParserValue pv(pos, CommandsParserValueType::NOT_EQUAL); - return pv; +CommandsParserValue CommandsParserValue::NotEqual(const TokenPos pos) { + CommandsParserValue pv(pos, CommandsParserValueType::NOT_EQUAL); + return pv; } -CommandsParserValue CommandsParserValue::GreaterEqual(const TokenPos pos) -{ - CommandsParserValue pv(pos, CommandsParserValueType::GREATER_EQUAL); - return pv; +CommandsParserValue CommandsParserValue::GreaterEqual(const TokenPos pos) { + CommandsParserValue pv(pos, CommandsParserValueType::GREATER_EQUAL); + return pv; } -CommandsParserValue CommandsParserValue::LessEqual(const TokenPos pos) -{ - CommandsParserValue pv(pos, CommandsParserValueType::LESS_EQUAL); - return pv; +CommandsParserValue CommandsParserValue::LessEqual(const TokenPos pos) { + CommandsParserValue pv(pos, CommandsParserValueType::LESS_EQUAL); + return pv; } -CommandsParserValue CommandsParserValue::LogicalAnd(const TokenPos pos) -{ - CommandsParserValue pv(pos, CommandsParserValueType::LOGICAL_AND); - return pv; +CommandsParserValue CommandsParserValue::LogicalAnd(const TokenPos pos) { + CommandsParserValue pv(pos, CommandsParserValueType::LOGICAL_AND); + return pv; } -CommandsParserValue CommandsParserValue::LogicalOr(const TokenPos pos) -{ - CommandsParserValue pv(pos, CommandsParserValueType::LOGICAL_OR); - return pv; +CommandsParserValue CommandsParserValue::LogicalOr(const TokenPos pos) { + CommandsParserValue pv(pos, CommandsParserValueType::LOGICAL_OR); + return pv; } -CommandsParserValue CommandsParserValue::Integer(const TokenPos pos, const int value) -{ - CommandsParserValue pv(pos, CommandsParserValueType::INTEGER); - pv.m_value.int_value = value; - return pv; +CommandsParserValue CommandsParserValue::Integer(const TokenPos pos, const int value) { + CommandsParserValue pv(pos, CommandsParserValueType::INTEGER); + pv.m_value.int_value = value; + return pv; } -CommandsParserValue CommandsParserValue::FloatingPoint(const TokenPos pos, const double value) -{ - CommandsParserValue pv(pos, CommandsParserValueType::FLOATING_POINT); - pv.m_value.double_value = value; - return pv; +CommandsParserValue CommandsParserValue::FloatingPoint(const TokenPos pos, const double value) { + CommandsParserValue pv(pos, CommandsParserValueType::FLOATING_POINT); + pv.m_value.double_value = value; + return pv; } -CommandsParserValue CommandsParserValue::String(const TokenPos pos, std::string* stringValue) -{ - CommandsParserValue pv(pos, CommandsParserValueType::STRING); - pv.m_value.string_value = stringValue; - return pv; +CommandsParserValue CommandsParserValue::String(const TokenPos pos, std::string *stringValue) { + CommandsParserValue pv(pos, CommandsParserValueType::STRING); + pv.m_value.string_value = stringValue; + return pv; } -CommandsParserValue CommandsParserValue::Identifier(const TokenPos pos, std::string* identifier) -{ - CommandsParserValue pv(pos, CommandsParserValueType::IDENTIFIER); - pv.m_value.string_value = identifier; - pv.m_hash = std::hash<std::string>()(*identifier); - return pv; +CommandsParserValue CommandsParserValue::Identifier(const TokenPos pos, std::string *identifier) { + CommandsParserValue pv(pos, CommandsParserValueType::IDENTIFIER); + pv.m_value.string_value = identifier; + pv.m_hash = std::hash<std::string>()(*identifier); + return pv; } -CommandsParserValue CommandsParserValue::TypeName(const TokenPos pos, std::string* typeName) -{ - CommandsParserValue pv(pos, CommandsParserValueType::TYPE_NAME); - pv.m_value.string_value = typeName; - return pv; +CommandsParserValue CommandsParserValue::TypeName(const TokenPos pos, std::string *typeName) { + CommandsParserValue pv(pos, CommandsParserValueType::TYPE_NAME); + pv.m_value.string_value = typeName; + return pv; } -CommandsParserValue CommandsParserValue::OpType(const TokenPos pos, const OperationType* operationType) -{ - CommandsParserValue pv(pos, CommandsParserValueType::OPERATION_TYPE); - pv.m_value.op_type_value = operationType; - return pv; +CommandsParserValue CommandsParserValue::OpType(const TokenPos pos, const OperationType *operationType) { + CommandsParserValue pv(pos, CommandsParserValueType::OPERATION_TYPE); + pv.m_value.op_type_value = operationType; + return pv; } -CommandsParserValue::CommandsParserValue(const TokenPos pos, const CommandsParserValueType type) - : m_pos(pos), - m_type(type), - m_hash(0), - m_value{} -{ -} +CommandsParserValue::CommandsParserValue(const TokenPos pos, const CommandsParserValueType type) : m_pos(pos), m_type(type), m_hash(0), m_value{} {} -CommandsParserValue::~CommandsParserValue() -{ - switch (m_type) - { - case CommandsParserValueType::STRING: - case CommandsParserValueType::IDENTIFIER: - case CommandsParserValueType::TYPE_NAME: - delete m_value.string_value; - break; +CommandsParserValue::~CommandsParserValue() { + switch (m_type) { + case CommandsParserValueType::STRING: + case CommandsParserValueType::IDENTIFIER: + case CommandsParserValueType::TYPE_NAME: + delete m_value.string_value; + break; - default: - break; - } + default: + break; + } - m_value = ValueType(); + m_value = ValueType(); } -CommandsParserValue::CommandsParserValue(CommandsParserValue&& other) noexcept - : m_pos(other.m_pos), - m_type(other.m_type), - m_hash(other.m_hash), - m_value(other.m_value) -{ - other.m_value = ValueType(); +CommandsParserValue::CommandsParserValue(CommandsParserValue &&other) noexcept + : m_pos(other.m_pos), m_type(other.m_type), m_hash(other.m_hash), m_value(other.m_value) { + other.m_value = ValueType(); } -CommandsParserValue& CommandsParserValue::operator=(CommandsParserValue&& other) noexcept -{ - m_pos = other.m_pos; - m_type = other.m_type; - m_value = other.m_value; - m_hash = other.m_hash; - other.m_value = ValueType(); +CommandsParserValue &CommandsParserValue::operator=(CommandsParserValue &&other) noexcept { + m_pos = other.m_pos; + m_type = other.m_type; + m_value = other.m_value; + m_hash = other.m_hash; + other.m_value = ValueType(); - return *this; + return *this; } -bool CommandsParserValue::IsEof() const -{ - return m_type == CommandsParserValueType::END_OF_FILE; -} +bool CommandsParserValue::IsEof() const { return m_type == CommandsParserValueType::END_OF_FILE; } -const TokenPos& CommandsParserValue::GetPos() const -{ - return m_pos; -} +const TokenPos &CommandsParserValue::GetPos() const { return m_pos; } -char CommandsParserValue::CharacterValue() const -{ - assert(m_type == CommandsParserValueType::CHARACTER); - return m_value.char_value; +char CommandsParserValue::CharacterValue() const { + assert(m_type == CommandsParserValueType::CHARACTER); + return m_value.char_value; } -int CommandsParserValue::IntegerValue() const -{ - assert(m_type == CommandsParserValueType::INTEGER); - return m_value.int_value; +int CommandsParserValue::IntegerValue() const { + assert(m_type == CommandsParserValueType::INTEGER); + return m_value.int_value; } -double CommandsParserValue::FloatingPointValue() const -{ - assert(m_type == CommandsParserValueType::FLOATING_POINT); - return m_value.double_value; +double CommandsParserValue::FloatingPointValue() const { + assert(m_type == CommandsParserValueType::FLOATING_POINT); + return m_value.double_value; } -std::string& CommandsParserValue::StringValue() const -{ - assert(m_type == CommandsParserValueType::STRING); - return *m_value.string_value; +std::string &CommandsParserValue::StringValue() const { + assert(m_type == CommandsParserValueType::STRING); + return *m_value.string_value; } -std::string& CommandsParserValue::IdentifierValue() const -{ - assert(m_type == CommandsParserValueType::IDENTIFIER); - return *m_value.string_value; +std::string &CommandsParserValue::IdentifierValue() const { + assert(m_type == CommandsParserValueType::IDENTIFIER); + return *m_value.string_value; } -size_t CommandsParserValue::IdentifierHash() const -{ - assert(m_type == CommandsParserValueType::IDENTIFIER); - return m_hash; +size_t CommandsParserValue::IdentifierHash() const { + assert(m_type == CommandsParserValueType::IDENTIFIER); + return m_hash; } -std::string& CommandsParserValue::TypeNameValue() const -{ - assert(m_type == CommandsParserValueType::TYPE_NAME); - return *m_value.string_value; +std::string &CommandsParserValue::TypeNameValue() const { + assert(m_type == CommandsParserValueType::TYPE_NAME); + return *m_value.string_value; } -const OperationType* CommandsParserValue::OpTypeValue() const -{ - assert(m_type == CommandsParserValueType::OPERATION_TYPE); - return m_value.op_type_value; +const OperationType *CommandsParserValue::OpTypeValue() const { + assert(m_type == CommandsParserValueType::OPERATION_TYPE); + return m_value.op_type_value; } diff --git a/src/ZoneCodeGeneratorLib/Parsing/Commands/Impl/CommandsParserValue.h b/src/ZoneCodeGeneratorLib/Parsing/Commands/Impl/CommandsParserValue.h index 9ef0c204b..4878abb52 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Commands/Impl/CommandsParserValue.h +++ b/src/ZoneCodeGeneratorLib/Parsing/Commands/Impl/CommandsParserValue.h @@ -4,103 +4,100 @@ #include "Domain/Evaluation/OperationType.h" #include "Parsing/IParserValue.h" -#include "Utils/ClassUtils.h" #include "Parsing/TokenPos.h" +#include "Utils/ClassUtils.h" -enum class CommandsParserValueType -{ - // Meta tokens - INVALID, - END_OF_FILE, +enum class CommandsParserValueType { + // Meta tokens + INVALID, + END_OF_FILE, - // Single character - CHARACTER, + // Single character + CHARACTER, - // Symbol tokens - SHIFT_LEFT, - SHIFT_RIGHT, - EQUALS, - NOT_EQUAL, - GREATER_EQUAL, - LESS_EQUAL, - LOGICAL_AND, - LOGICAL_OR, + // Symbol tokens + SHIFT_LEFT, + SHIFT_RIGHT, + EQUALS, + NOT_EQUAL, + GREATER_EQUAL, + LESS_EQUAL, + LOGICAL_AND, + LOGICAL_OR, - // Built-in types - BUILT_IN_FIRST, - UNSIGNED = BUILT_IN_FIRST, - CHAR, - SHORT, - INT, - LONG, - BUILT_IN_LAST = LONG, + // Built-in types + BUILT_IN_FIRST, + UNSIGNED = BUILT_IN_FIRST, + CHAR, + SHORT, + INT, + LONG, + BUILT_IN_LAST = LONG, - // Generic token types - INTEGER, - FLOATING_POINT, - STRING, - IDENTIFIER, + // Generic token types + INTEGER, + FLOATING_POINT, + STRING, + IDENTIFIER, - // Parser created - TYPE_NAME, - OPERATION_TYPE, + // Parser created + TYPE_NAME, + OPERATION_TYPE, - // End - MAX + // End + MAX }; -class CommandsParserValue final : public IParserValue -{ +class CommandsParserValue final : public IParserValue { public: - TokenPos m_pos; - CommandsParserValueType m_type; - size_t m_hash; - union ValueType - { - char char_value; - int int_value; - double double_value; - std::string* string_value; - const OperationType* op_type_value; - } m_value; + TokenPos m_pos; + CommandsParserValueType m_type; + size_t m_hash; + union ValueType { + char char_value; + int int_value; + double double_value; + std::string *string_value; + const OperationType *op_type_value; + } m_value; - static CommandsParserValue Invalid(TokenPos pos); - static CommandsParserValue EndOfFile(TokenPos pos); - static CommandsParserValue Character(TokenPos pos, char c); - static CommandsParserValue ShiftLeft(TokenPos pos); - static CommandsParserValue ShiftRight(TokenPos pos); - static CommandsParserValue Equals(TokenPos pos); - static CommandsParserValue NotEqual(TokenPos pos); - static CommandsParserValue GreaterEqual(TokenPos pos); - static CommandsParserValue LessEqual(TokenPos pos); - static CommandsParserValue LogicalAnd(TokenPos pos); - static CommandsParserValue LogicalOr(TokenPos pos); - static CommandsParserValue Integer(TokenPos pos, int value); - static CommandsParserValue FloatingPoint(TokenPos pos, double value); - static CommandsParserValue String(TokenPos pos, std::string* stringValue); - static CommandsParserValue Identifier(TokenPos pos, std::string* identifier); - static CommandsParserValue TypeName(TokenPos pos, std::string* typeName); - static CommandsParserValue OpType(TokenPos pos, const OperationType* operationType); + static CommandsParserValue Invalid(TokenPos pos); + static CommandsParserValue EndOfFile(TokenPos pos); + static CommandsParserValue Character(TokenPos pos, char c); + static CommandsParserValue ShiftLeft(TokenPos pos); + static CommandsParserValue ShiftRight(TokenPos pos); + static CommandsParserValue Equals(TokenPos pos); + static CommandsParserValue NotEqual(TokenPos pos); + static CommandsParserValue GreaterEqual(TokenPos pos); + static CommandsParserValue LessEqual(TokenPos pos); + static CommandsParserValue LogicalAnd(TokenPos pos); + static CommandsParserValue LogicalOr(TokenPos pos); + static CommandsParserValue Integer(TokenPos pos, int value); + static CommandsParserValue FloatingPoint(TokenPos pos, double value); + static CommandsParserValue String(TokenPos pos, std::string *stringValue); + static CommandsParserValue Identifier(TokenPos pos, std::string *identifier); + static CommandsParserValue TypeName(TokenPos pos, std::string *typeName); + static CommandsParserValue OpType(TokenPos pos, const OperationType *operationType); private: - CommandsParserValue(TokenPos pos, CommandsParserValueType type); + CommandsParserValue(TokenPos pos, CommandsParserValueType type); public: - ~CommandsParserValue() override; - CommandsParserValue(const CommandsParserValue& other) = delete; - CommandsParserValue(CommandsParserValue&& other) noexcept; - CommandsParserValue& operator=(const CommandsParserValue& other) = delete; - CommandsParserValue& operator=(CommandsParserValue&& other) noexcept; + ~CommandsParserValue() override; + CommandsParserValue(const CommandsParserValue &other) = delete; + CommandsParserValue(CommandsParserValue &&other) noexcept; + CommandsParserValue &operator=(const CommandsParserValue &other) = delete; + CommandsParserValue &operator=(CommandsParserValue &&other) noexcept; - _NODISCARD bool IsEof() const override; - _NODISCARD const TokenPos& GetPos() const override; + _NODISCARD bool IsEof() const override; + _NODISCARD const TokenPos &GetPos() const override; - _NODISCARD char CharacterValue() const; - _NODISCARD int IntegerValue() const; - _NODISCARD double FloatingPointValue() const; - _NODISCARD std::string& StringValue() const; - _NODISCARD std::string& IdentifierValue() const; - _NODISCARD size_t IdentifierHash() const; - _NODISCARD std::string& TypeNameValue() const; - _NODISCARD const OperationType* OpTypeValue() const; + _NODISCARD char CharacterValue() const; + _NODISCARD int IntegerValue() const; + _NODISCARD double FloatingPointValue() const; + _NODISCARD std::string &StringValue() const; + _NODISCARD std::string &IdentifierValue() const; + _NODISCARD size_t IdentifierHash() const; + _NODISCARD std::string &TypeNameValue() const; + _NODISCARD const OperationType *OpTypeValue() const; }; \ No newline at end of file diff --git a/src/ZoneCodeGeneratorLib/Parsing/Commands/Matcher/CommandsCommonMatchers.cpp b/src/ZoneCodeGeneratorLib/Parsing/Commands/Matcher/CommandsCommonMatchers.cpp index d95a6fa0f..4744e597a 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Commands/Matcher/CommandsCommonMatchers.cpp +++ b/src/ZoneCodeGeneratorLib/Parsing/Commands/Matcher/CommandsCommonMatchers.cpp @@ -2,94 +2,62 @@ #include <list> #include <sstream> -#include <vector> #include <type_traits> +#include <vector> #include "CommandsMatcherFactory.h" #include "Domain/Evaluation/OperandDynamic.h" #include "Domain/Evaluation/OperandStatic.h" #include "Domain/Evaluation/Operation.h" -std::unique_ptr<CommandsCommonMatchers::matcher_t> CommandsCommonMatchers::Typename(const supplier_t* labelSupplier) -{ - static constexpr const char* BUILT_IN_TYPE_NAMES[] - { - "unsigned", - "char", - "short", - "int", - "long" - }; - static_assert(std::extent<decltype(BUILT_IN_TYPE_NAMES)>::value == static_cast<int>(CommandsParserValueType::BUILT_IN_LAST) - static_cast<int>(CommandsParserValueType::BUILT_IN_FIRST) + 1); - - const CommandsMatcherFactory create(labelSupplier); - - return create.Or({ - create.And({ - create.Optional(create.Type(CommandsParserValueType::UNSIGNED)), - create.Or({ - create.Type(CommandsParserValueType::CHAR), - create.Type(CommandsParserValueType::SHORT), - create.Type(CommandsParserValueType::INT), - create.And({ - create.Type(CommandsParserValueType::LONG), - create.Optional(create.Type(CommandsParserValueType::LONG)) - }) - }) - }).Transform([](CommandsMatcherFactory::token_list_t& values) - { - std::ostringstream str; - auto first = true; - - for (const auto& token : values) - { - if (first) - first = false; - else - str << " "; - str << BUILT_IN_TYPE_NAMES[static_cast<int>(token.get().m_type) - static_cast<int>(CommandsParserValueType::BUILT_IN_FIRST)]; - } - - return CommandsParserValue::TypeName(values[0].get().GetPos(), new std::string(str.str())); - }), - create.And({ - create.Identifier(), - create.OptionalLoop(create.And({ - create.Char(':'), - create.Char(':'), - create.Identifier() - })) - }).Transform([](CommandsMatcherFactory::token_list_t& values) - { - std::ostringstream str; - str << values[0].get().IdentifierValue(); - - for (auto i = 3u; i < values.size(); i += 3) - str << "::" << values[i].get().IdentifierValue(); - - return CommandsParserValue::TypeName(values[0].get().GetPos(), new std::string(str.str())); - }) - }); +std::unique_ptr<CommandsCommonMatchers::matcher_t> CommandsCommonMatchers::Typename(const supplier_t *labelSupplier) { + static constexpr const char *BUILT_IN_TYPE_NAMES[]{"unsigned", "char", "short", "int", "long"}; + static_assert(std::extent<decltype(BUILT_IN_TYPE_NAMES)>::value == + static_cast<int>(CommandsParserValueType::BUILT_IN_LAST) - static_cast<int>(CommandsParserValueType::BUILT_IN_FIRST) + 1); + + const CommandsMatcherFactory create(labelSupplier); + + return create.Or( + {create + .And({create.Optional(create.Type(CommandsParserValueType::UNSIGNED)), + create.Or({create.Type(CommandsParserValueType::CHAR), create.Type(CommandsParserValueType::SHORT), create.Type(CommandsParserValueType::INT), + create.And({create.Type(CommandsParserValueType::LONG), create.Optional(create.Type(CommandsParserValueType::LONG))})})}) + .Transform([](CommandsMatcherFactory::token_list_t &values) { + std::ostringstream str; + auto first = true; + + for (const auto &token : values) { + if (first) + first = false; + else + str << " "; + str << BUILT_IN_TYPE_NAMES[static_cast<int>(token.get().m_type) - static_cast<int>(CommandsParserValueType::BUILT_IN_FIRST)]; + } + + return CommandsParserValue::TypeName(values[0].get().GetPos(), new std::string(str.str())); + }), + create.And({create.Identifier(), create.OptionalLoop(create.And({create.Char(':'), create.Char(':'), create.Identifier()}))}) + .Transform([](CommandsMatcherFactory::token_list_t &values) { + std::ostringstream str; + str << values[0].get().IdentifierValue(); + + for (auto i = 3u; i < values.size(); i += 3) + str << "::" << values[i].get().IdentifierValue(); + + return CommandsParserValue::TypeName(values[0].get().GetPos(), new std::string(str.str())); + })}); } -std::unique_ptr<CommandsCommonMatchers::matcher_t> CommandsCommonMatchers::ArrayDef(const supplier_t* labelSupplier) -{ - const CommandsMatcherFactory create(labelSupplier); - - return create.And({ - create.Char('['), - create.Or({ - create.Integer(), - create.Identifier() - }), - create.Char(']') - }).Transform([](CommandsMatcherFactory::token_list_t& values) - { +std::unique_ptr<CommandsCommonMatchers::matcher_t> CommandsCommonMatchers::ArrayDef(const supplier_t *labelSupplier) { + const CommandsMatcherFactory create(labelSupplier); + + return create.And({create.Char('['), create.Or({create.Integer(), create.Identifier()}), create.Char(']')}) + .Transform([](CommandsMatcherFactory::token_list_t &values) { if (values[1].get().m_type == CommandsParserValueType::INTEGER) - return CommandsParserValue::Integer(values[1].get().GetPos(), values[1].get().IntegerValue()); + return CommandsParserValue::Integer(values[1].get().GetPos(), values[1].get().IntegerValue()); return CommandsParserValue::Identifier(values[1].get().GetPos(), new std::string(values[1].get().IdentifierValue())); - }); + }); } static constexpr int TAG_OPERAND = std::numeric_limits<int>::max() - 1; @@ -108,254 +76,211 @@ static constexpr int CAPTURE_OPERAND_ARRAY = std::numeric_limits<int>::max() - 2 static constexpr int CAPTURE_OPERAND_INTEGER = std::numeric_limits<int>::max() - 3; static constexpr int CAPTURE_BINARY_OPERATION_TYPE = std::numeric_limits<int>::max() - 4; -std::unique_ptr<CommandsCommonMatchers::matcher_t> CommandsCommonMatchers::ParseOperandArray(const supplier_t* labelSupplier) -{ - const CommandsMatcherFactory create(labelSupplier); +std::unique_ptr<CommandsCommonMatchers::matcher_t> CommandsCommonMatchers::ParseOperandArray(const supplier_t *labelSupplier) { + const CommandsMatcherFactory create(labelSupplier); - return create.And({ - create.Char('['), - create.Label(LABEL_EVALUATION), - create.Char(']').Tag(TAG_OPERAND_ARRAY_END) - }).Tag(TAG_OPERAND_ARRAY); + return create.And({create.Char('['), create.Label(LABEL_EVALUATION), create.Char(']').Tag(TAG_OPERAND_ARRAY_END)}).Tag(TAG_OPERAND_ARRAY); } -std::unique_ptr<CommandsCommonMatchers::matcher_t> CommandsCommonMatchers::ParseOperand(const supplier_t* labelSupplier) -{ - const CommandsMatcherFactory create(labelSupplier); - - return create.Or({ - create.And({ - create.Label(LABEL_TYPENAME).Capture(CAPTURE_OPERAND_TYPENAME), - create.OptionalLoop(MatcherFactoryWrapper<CommandsParserValue>(ParseOperandArray(labelSupplier)).Capture(CAPTURE_OPERAND_ARRAY)) - }).Tag(TAG_OPERAND_TYPENAME), - create.Integer().Tag(TAG_OPERAND_INTEGER).Capture(CAPTURE_OPERAND_INTEGER) - }).Tag(TAG_OPERAND); +std::unique_ptr<CommandsCommonMatchers::matcher_t> CommandsCommonMatchers::ParseOperand(const supplier_t *labelSupplier) { + const CommandsMatcherFactory create(labelSupplier); + + return create + .Or({create + .And({create.Label(LABEL_TYPENAME).Capture(CAPTURE_OPERAND_TYPENAME), + create.OptionalLoop(MatcherFactoryWrapper<CommandsParserValue>(ParseOperandArray(labelSupplier)).Capture(CAPTURE_OPERAND_ARRAY))}) + .Tag(TAG_OPERAND_TYPENAME), + create.Integer().Tag(TAG_OPERAND_INTEGER).Capture(CAPTURE_OPERAND_INTEGER)}) + .Tag(TAG_OPERAND); } -std::unique_ptr<CommandsCommonMatchers::matcher_t> CommandsCommonMatchers::ParseOperationType(const supplier_t* labelSupplier) -{ - const CommandsMatcherFactory create(labelSupplier); - - return create.Or({ - create.Char('+').Transform([](CommandsMatcherFactory::token_list_t& values) - { - return CommandsParserValue::OpType(values[0].get().GetPos(), OperationType::OPERATION_ADD); - }), - create.Char('-').Transform([](CommandsMatcherFactory::token_list_t& values) - { - return CommandsParserValue::OpType(values[0].get().GetPos(), OperationType::OPERATION_SUBTRACT); - }), - create.Char('*').Transform([](CommandsMatcherFactory::token_list_t& values) - { - return CommandsParserValue::OpType(values[0].get().GetPos(), OperationType::OPERATION_MULTIPLY); - }), - create.Char('/').Transform([](CommandsMatcherFactory::token_list_t& values) - { - return CommandsParserValue::OpType(values[0].get().GetPos(), OperationType::OPERATION_DIVIDE); - }), - create.Char('%').Transform([](CommandsMatcherFactory::token_list_t& values) - { - return CommandsParserValue::OpType(values[0].get().GetPos(), OperationType::OPERATION_REMAINDER); - }), - create.Char('&').Transform([](CommandsMatcherFactory::token_list_t& values) - { - return CommandsParserValue::OpType(values[0].get().GetPos(), OperationType::OPERATION_BITWISE_AND); - }), - create.Char('^').Transform([](CommandsMatcherFactory::token_list_t& values) - { - return CommandsParserValue::OpType(values[0].get().GetPos(), OperationType::OPERATION_BITWISE_XOR); - }), - create.Char('|').Transform([](CommandsMatcherFactory::token_list_t& values) - { - return CommandsParserValue::OpType(values[0].get().GetPos(), OperationType::OPERATION_BITWISE_OR); - }), - create.Type(CommandsParserValueType::SHIFT_LEFT).Transform([](CommandsMatcherFactory::token_list_t& values) - { - return CommandsParserValue::OpType(values[0].get().GetPos(), OperationType::OPERATION_SHIFT_LEFT); - }), - create.Type(CommandsParserValueType::SHIFT_RIGHT).Transform([](CommandsMatcherFactory::token_list_t& values) - { - return CommandsParserValue::OpType(values[0].get().GetPos(), OperationType::OPERATION_SHIFT_RIGHT); - }), - create.Char('>').Transform([](CommandsMatcherFactory::token_list_t& values) - { - return CommandsParserValue::OpType(values[0].get().GetPos(), OperationType::OPERATION_GREATER_THAN); - }), - create.Type(CommandsParserValueType::GREATER_EQUAL).Transform([](CommandsMatcherFactory::token_list_t& values) - { - return CommandsParserValue::OpType(values[0].get().GetPos(), OperationType::OPERATION_GREATER_EQUAL_THAN); - }), - create.Char('<').Transform([](CommandsMatcherFactory::token_list_t& values) - { - return CommandsParserValue::OpType(values[0].get().GetPos(), OperationType::OPERATION_LESS_THAN); - }), - create.Type(CommandsParserValueType::LESS_EQUAL).Transform([](CommandsMatcherFactory::token_list_t& values) - { - return CommandsParserValue::OpType(values[0].get().GetPos(), OperationType::OPERATION_LESS_EQUAL_THAN); - }), - create.Type(CommandsParserValueType::EQUALS).Transform([](CommandsMatcherFactory::token_list_t& values) - { - return CommandsParserValue::OpType(values[0].get().GetPos(), OperationType::OPERATION_EQUALS); - }), - create.Type(CommandsParserValueType::NOT_EQUAL).Transform([](CommandsMatcherFactory::token_list_t& values) - { - return CommandsParserValue::OpType(values[0].get().GetPos(), OperationType::OPERATION_NOT_EQUAL); - }), - create.Type(CommandsParserValueType::LOGICAL_AND).Transform([](CommandsMatcherFactory::token_list_t& values) - { - return CommandsParserValue::OpType(values[0].get().GetPos(), OperationType::OPERATION_AND); - }), - create.Type(CommandsParserValueType::LOGICAL_OR).Transform([](CommandsMatcherFactory::token_list_t& values) - { - return CommandsParserValue::OpType(values[0].get().GetPos(), OperationType::OPERATION_OR); - }) - }).Capture(CAPTURE_BINARY_OPERATION_TYPE); +std::unique_ptr<CommandsCommonMatchers::matcher_t> CommandsCommonMatchers::ParseOperationType(const supplier_t *labelSupplier) { + const CommandsMatcherFactory create(labelSupplier); + + return create + .Or({create.Char('+').Transform([](CommandsMatcherFactory::token_list_t &values) { + return CommandsParserValue::OpType(values[0].get().GetPos(), OperationType::OPERATION_ADD); + }), + create.Char('-').Transform([](CommandsMatcherFactory::token_list_t &values) { + return CommandsParserValue::OpType(values[0].get().GetPos(), OperationType::OPERATION_SUBTRACT); + }), + create.Char('*').Transform([](CommandsMatcherFactory::token_list_t &values) { + return CommandsParserValue::OpType(values[0].get().GetPos(), OperationType::OPERATION_MULTIPLY); + }), + create.Char('/').Transform([](CommandsMatcherFactory::token_list_t &values) { + return CommandsParserValue::OpType(values[0].get().GetPos(), OperationType::OPERATION_DIVIDE); + }), + create.Char('%').Transform([](CommandsMatcherFactory::token_list_t &values) { + return CommandsParserValue::OpType(values[0].get().GetPos(), OperationType::OPERATION_REMAINDER); + }), + create.Char('&').Transform([](CommandsMatcherFactory::token_list_t &values) { + return CommandsParserValue::OpType(values[0].get().GetPos(), OperationType::OPERATION_BITWISE_AND); + }), + create.Char('^').Transform([](CommandsMatcherFactory::token_list_t &values) { + return CommandsParserValue::OpType(values[0].get().GetPos(), OperationType::OPERATION_BITWISE_XOR); + }), + create.Char('|').Transform([](CommandsMatcherFactory::token_list_t &values) { + return CommandsParserValue::OpType(values[0].get().GetPos(), OperationType::OPERATION_BITWISE_OR); + }), + create.Type(CommandsParserValueType::SHIFT_LEFT).Transform([](CommandsMatcherFactory::token_list_t &values) { + return CommandsParserValue::OpType(values[0].get().GetPos(), OperationType::OPERATION_SHIFT_LEFT); + }), + create.Type(CommandsParserValueType::SHIFT_RIGHT).Transform([](CommandsMatcherFactory::token_list_t &values) { + return CommandsParserValue::OpType(values[0].get().GetPos(), OperationType::OPERATION_SHIFT_RIGHT); + }), + create.Char('>').Transform([](CommandsMatcherFactory::token_list_t &values) { + return CommandsParserValue::OpType(values[0].get().GetPos(), OperationType::OPERATION_GREATER_THAN); + }), + create.Type(CommandsParserValueType::GREATER_EQUAL).Transform([](CommandsMatcherFactory::token_list_t &values) { + return CommandsParserValue::OpType(values[0].get().GetPos(), OperationType::OPERATION_GREATER_EQUAL_THAN); + }), + create.Char('<').Transform([](CommandsMatcherFactory::token_list_t &values) { + return CommandsParserValue::OpType(values[0].get().GetPos(), OperationType::OPERATION_LESS_THAN); + }), + create.Type(CommandsParserValueType::LESS_EQUAL).Transform([](CommandsMatcherFactory::token_list_t &values) { + return CommandsParserValue::OpType(values[0].get().GetPos(), OperationType::OPERATION_LESS_EQUAL_THAN); + }), + create.Type(CommandsParserValueType::EQUALS).Transform([](CommandsMatcherFactory::token_list_t &values) { + return CommandsParserValue::OpType(values[0].get().GetPos(), OperationType::OPERATION_EQUALS); + }), + create.Type(CommandsParserValueType::NOT_EQUAL).Transform([](CommandsMatcherFactory::token_list_t &values) { + return CommandsParserValue::OpType(values[0].get().GetPos(), OperationType::OPERATION_NOT_EQUAL); + }), + create.Type(CommandsParserValueType::LOGICAL_AND).Transform([](CommandsMatcherFactory::token_list_t &values) { + return CommandsParserValue::OpType(values[0].get().GetPos(), OperationType::OPERATION_AND); + }), + create.Type(CommandsParserValueType::LOGICAL_OR).Transform([](CommandsMatcherFactory::token_list_t &values) { + return CommandsParserValue::OpType(values[0].get().GetPos(), OperationType::OPERATION_OR); + })}) + .Capture(CAPTURE_BINARY_OPERATION_TYPE); } -std::unique_ptr<CommandsCommonMatchers::matcher_t> CommandsCommonMatchers::Evaluation(const supplier_t* labelSupplier) -{ - const CommandsMatcherFactory create(labelSupplier); - - return create.And({ - create.Or({ - create.And({ - create.Optional(create.Char('!').Tag(TAG_EVALUATION_NOT)), - create.Char('('), - create.Label(LABEL_EVALUATION), - create.Char(')').Tag(TAG_EVALUATION_PARENTHESIS_END) - }).Tag(TAG_EVALUATION_PARENTHESIS), - ParseOperand(labelSupplier) - }), - create.Optional(create.And({ - ParseOperationType(labelSupplier), - create.Label(LABEL_EVALUATION) - }).Tag(TAG_EVALUATION_OPERATION)) - }).Tag(TAG_EVALUATION); +std::unique_ptr<CommandsCommonMatchers::matcher_t> CommandsCommonMatchers::Evaluation(const supplier_t *labelSupplier) { + const CommandsMatcherFactory create(labelSupplier); + + return create + .And({create.Or({create + .And({create.Optional(create.Char('!').Tag(TAG_EVALUATION_NOT)), create.Char('('), create.Label(LABEL_EVALUATION), + create.Char(')').Tag(TAG_EVALUATION_PARENTHESIS_END)}) + .Tag(TAG_EVALUATION_PARENTHESIS), + ParseOperand(labelSupplier)}), + create.Optional(create.And({ParseOperationType(labelSupplier), create.Label(LABEL_EVALUATION)}).Tag(TAG_EVALUATION_OPERATION))}) + .Tag(TAG_EVALUATION); } -std::unique_ptr<IEvaluation> CommandsCommonMatchers::ProcessEvaluationInParenthesis(CommandsParserState* state, SequenceResult<CommandsParserValue>& result) -{ - const auto isNegated = result.PeekAndRemoveIfTag(TAG_EVALUATION_NOT) == TAG_EVALUATION_NOT; +std::unique_ptr<IEvaluation> CommandsCommonMatchers::ProcessEvaluationInParenthesis(CommandsParserState *state, SequenceResult<CommandsParserValue> &result) { + const auto isNegated = result.PeekAndRemoveIfTag(TAG_EVALUATION_NOT) == TAG_EVALUATION_NOT; - auto processedEvaluation = ProcessEvaluation(state, result); + auto processedEvaluation = ProcessEvaluation(state, result); - if (result.PeekAndRemoveIfTag(TAG_EVALUATION_PARENTHESIS_END) != TAG_EVALUATION_PARENTHESIS_END) - throw ParsingException(TokenPos(), "Expected parenthesis end tag @ EvaluationInParenthesis"); + if (result.PeekAndRemoveIfTag(TAG_EVALUATION_PARENTHESIS_END) != TAG_EVALUATION_PARENTHESIS_END) + throw ParsingException(TokenPos(), "Expected parenthesis end tag @ EvaluationInParenthesis"); - if (isNegated) - processedEvaluation = std::make_unique<Operation>(OperationType::OPERATION_EQUALS, std::move(processedEvaluation), std::make_unique<OperandStatic>(0)); + if (isNegated) + processedEvaluation = std::make_unique<Operation>(OperationType::OPERATION_EQUALS, std::move(processedEvaluation), std::make_unique<OperandStatic>(0)); - return processedEvaluation; + return processedEvaluation; } -std::unique_ptr<IEvaluation> CommandsCommonMatchers::ProcessOperand(CommandsParserState* state, SequenceResult<CommandsParserValue>& result, StructureInformation* currentType) -{ - const auto nextTag = result.NextTag(); +std::unique_ptr<IEvaluation> CommandsCommonMatchers::ProcessOperand(CommandsParserState *state, SequenceResult<CommandsParserValue> &result, + StructureInformation *currentType) { + const auto nextTag = result.NextTag(); - if (nextTag == TAG_OPERAND_INTEGER) - { - return std::make_unique<OperandStatic>(result.NextCapture(CAPTURE_OPERAND_INTEGER).IntegerValue()); - } + if (nextTag == TAG_OPERAND_INTEGER) { + return std::make_unique<OperandStatic>(result.NextCapture(CAPTURE_OPERAND_INTEGER).IntegerValue()); + } - if (nextTag == TAG_OPERAND_TYPENAME) - { - const auto& typeNameToken = result.NextCapture(CAPTURE_OPERAND_TYPENAME); - std::vector<std::unique_ptr<IEvaluation>> arrayIndexEvaluations; + if (nextTag == TAG_OPERAND_TYPENAME) { + const auto &typeNameToken = result.NextCapture(CAPTURE_OPERAND_TYPENAME); + std::vector<std::unique_ptr<IEvaluation>> arrayIndexEvaluations; - while (result.PeekAndRemoveIfTag(TAG_OPERAND_ARRAY) == TAG_OPERAND_ARRAY) - { - arrayIndexEvaluations.emplace_back(ProcessEvaluation(state, result, currentType)); + while (result.PeekAndRemoveIfTag(TAG_OPERAND_ARRAY) == TAG_OPERAND_ARRAY) { + arrayIndexEvaluations.emplace_back(ProcessEvaluation(state, result, currentType)); - if (result.PeekAndRemoveIfTag(TAG_OPERAND_ARRAY_END) != TAG_OPERAND_ARRAY_END) - throw ParsingException(TokenPos(), "Expected operand array end tag @ Operand"); - } + if (result.PeekAndRemoveIfTag(TAG_OPERAND_ARRAY_END) != TAG_OPERAND_ARRAY_END) + throw ParsingException(TokenPos(), "Expected operand array end tag @ Operand"); + } - auto* foundEnumMember = state->GetRepository()->GetEnumMemberByName(typeNameToken.TypeNameValue()); - if (foundEnumMember != nullptr) - return std::make_unique<OperandStatic>(foundEnumMember); + auto *foundEnumMember = state->GetRepository()->GetEnumMemberByName(typeNameToken.TypeNameValue()); + if (foundEnumMember != nullptr) + return std::make_unique<OperandStatic>(foundEnumMember); - StructureInformation* structure; - std::vector<MemberInformation*> memberChain; - if (state->GetTypenameAndMembersFromTypename(typeNameToken.TypeNameValue(), structure, memberChain)) - return std::make_unique<OperandDynamic>(structure, std::move(memberChain), std::move(arrayIndexEvaluations)); + StructureInformation *structure; + std::vector<MemberInformation *> memberChain; + if (state->GetTypenameAndMembersFromTypename(typeNameToken.TypeNameValue(), structure, memberChain)) + return std::make_unique<OperandDynamic>(structure, std::move(memberChain), std::move(arrayIndexEvaluations)); - if (currentType != nullptr && state->GetMembersFromTypename(typeNameToken.TypeNameValue(), currentType, memberChain)) - return std::make_unique<OperandDynamic>(currentType, std::move(memberChain), std::move(arrayIndexEvaluations)); + if (currentType != nullptr && state->GetMembersFromTypename(typeNameToken.TypeNameValue(), currentType, memberChain)) + return std::make_unique<OperandDynamic>(currentType, std::move(memberChain), std::move(arrayIndexEvaluations)); - throw ParsingException(typeNameToken.GetPos(), "Unknown type"); - } + throw ParsingException(typeNameToken.GetPos(), "Unknown type"); + } - throw ParsingException(TokenPos(), "Unknown operand type @ Operand"); + throw ParsingException(TokenPos(), "Unknown operand type @ Operand"); } -std::unique_ptr<IEvaluation> CommandsCommonMatchers::ProcessEvaluation(CommandsParserState* state, SequenceResult<CommandsParserValue>& result) -{ - return ProcessEvaluation(state, result, nullptr); +std::unique_ptr<IEvaluation> CommandsCommonMatchers::ProcessEvaluation(CommandsParserState *state, SequenceResult<CommandsParserValue> &result) { + return ProcessEvaluation(state, result, nullptr); } -std::unique_ptr<IEvaluation> CommandsCommonMatchers::ProcessEvaluation(CommandsParserState* state, SequenceResult<CommandsParserValue>& result, StructureInformation* currentType) -{ - if (result.PeekAndRemoveIfTag(TAG_EVALUATION) != TAG_EVALUATION) - return nullptr; - - if (currentType == state->GetInUse()) - currentType = nullptr; - - std::vector<std::unique_ptr<IEvaluation>> operands; - std::list<std::pair<unsigned, const OperationType*>> operators; - - while (true) - { - std::unique_ptr<IEvaluation> firstStatementPart; - const auto nextTag = result.NextTag(); - switch (nextTag) - { - case TAG_EVALUATION_PARENTHESIS: - firstStatementPart = ProcessEvaluationInParenthesis(state, result); - break; - - case TAG_OPERAND: - firstStatementPart = ProcessOperand(state, result, currentType); - break; - - default: - throw ParsingException(TokenPos(), "Invalid followup tag @ Evaluation"); - } - operands.emplace_back(std::move(firstStatementPart)); - - if (result.PeekAndRemoveIfTag(TAG_EVALUATION_OPERATION) == TAG_EVALUATION_OPERATION) - operators.emplace_back(operators.size(), result.NextCapture(CAPTURE_BINARY_OPERATION_TYPE).OpTypeValue()); - else - break; - - if (result.PeekAndRemoveIfTag(TAG_EVALUATION) != TAG_EVALUATION) - throw ParsingException(TokenPos(), "Expected EvaluationTag @ Evaluation"); +std::unique_ptr<IEvaluation> CommandsCommonMatchers::ProcessEvaluation(CommandsParserState *state, SequenceResult<CommandsParserValue> &result, + StructureInformation *currentType) { + if (result.PeekAndRemoveIfTag(TAG_EVALUATION) != TAG_EVALUATION) + return nullptr; + + if (currentType == state->GetInUse()) + currentType = nullptr; + + std::vector<std::unique_ptr<IEvaluation>> operands; + std::list<std::pair<unsigned, const OperationType *>> operators; + + while (true) { + std::unique_ptr<IEvaluation> firstStatementPart; + const auto nextTag = result.NextTag(); + switch (nextTag) { + case TAG_EVALUATION_PARENTHESIS: + firstStatementPart = ProcessEvaluationInParenthesis(state, result); + break; + + case TAG_OPERAND: + firstStatementPart = ProcessOperand(state, result, currentType); + break; + + default: + throw ParsingException(TokenPos(), "Invalid followup tag @ Evaluation"); } + operands.emplace_back(std::move(firstStatementPart)); + + if (result.PeekAndRemoveIfTag(TAG_EVALUATION_OPERATION) == TAG_EVALUATION_OPERATION) + operators.emplace_back(operators.size(), result.NextCapture(CAPTURE_BINARY_OPERATION_TYPE).OpTypeValue()); + else + break; + + if (result.PeekAndRemoveIfTag(TAG_EVALUATION) != TAG_EVALUATION) + throw ParsingException(TokenPos(), "Expected EvaluationTag @ Evaluation"); + } - operators.sort([](const std::pair<unsigned, const OperationType*>& p1, const std::pair<unsigned, const OperationType*>& p2) - { - if(p1.second->m_precedence != p2.second->m_precedence) - return p1.second->m_precedence > p2.second->m_precedence; - - return p1.first > p2.first; - }); - - while (!operators.empty()) - { - const auto [operatorIndex, operatorType] = operators.back(); - - auto operation = std::make_unique<Operation>(operatorType, std::move(operands[operatorIndex]), std::move(operands[operatorIndex + 1])); - operands.erase(operands.begin() + operatorIndex); - operands[operatorIndex] = std::move(operation); - - operators.pop_back(); - - for(auto& [opIndex, _] : operators) - { - if (opIndex > operatorIndex) - opIndex--; - } + operators.sort([](const std::pair<unsigned, const OperationType *> &p1, const std::pair<unsigned, const OperationType *> &p2) { + if (p1.second->m_precedence != p2.second->m_precedence) + return p1.second->m_precedence > p2.second->m_precedence; + + return p1.first > p2.first; + }); + + while (!operators.empty()) { + const auto [operatorIndex, operatorType] = operators.back(); + + auto operation = std::make_unique<Operation>(operatorType, std::move(operands[operatorIndex]), std::move(operands[operatorIndex + 1])); + operands.erase(operands.begin() + operatorIndex); + operands[operatorIndex] = std::move(operation); + + operators.pop_back(); + + for (auto &[opIndex, _] : operators) { + if (opIndex > operatorIndex) + opIndex--; } - - return std::move(operands.front()); + } + + return std::move(operands.front()); } diff --git a/src/ZoneCodeGeneratorLib/Parsing/Commands/Matcher/CommandsCommonMatchers.h b/src/ZoneCodeGeneratorLib/Parsing/Commands/Matcher/CommandsCommonMatchers.h index 7514257ff..86f5afcbf 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Commands/Matcher/CommandsCommonMatchers.h +++ b/src/ZoneCodeGeneratorLib/Parsing/Commands/Matcher/CommandsCommonMatchers.h @@ -11,29 +11,30 @@ #include "Parsing/Matcher/MatcherLabel.h" #include "Parsing/Sequence/SequenceResult.h" -class CommandsCommonMatchers -{ +class CommandsCommonMatchers { public: - typedef AbstractMatcher<CommandsParserValue> matcher_t; - typedef IMatcherForLabelSupplier<CommandsParserValue> supplier_t; + typedef AbstractMatcher<CommandsParserValue> matcher_t; + typedef IMatcherForLabelSupplier<CommandsParserValue> supplier_t; - static constexpr int LABEL_TYPENAME = std::numeric_limits<int>::max() - 1; - static constexpr int LABEL_ARRAY_DEF = std::numeric_limits<int>::max() - 2; - static constexpr int LABEL_EVALUATION = std::numeric_limits<int>::max() - 3; - - static std::unique_ptr<matcher_t> Typename(const supplier_t* labelSupplier); - static std::unique_ptr<matcher_t> ArrayDef(const supplier_t* labelSupplier); + static constexpr int LABEL_TYPENAME = std::numeric_limits<int>::max() - 1; + static constexpr int LABEL_ARRAY_DEF = std::numeric_limits<int>::max() - 2; + static constexpr int LABEL_EVALUATION = std::numeric_limits<int>::max() - 3; + + static std::unique_ptr<matcher_t> Typename(const supplier_t *labelSupplier); + static std::unique_ptr<matcher_t> ArrayDef(const supplier_t *labelSupplier); private: - static std::unique_ptr<matcher_t> ParseOperandArray(const supplier_t* labelSupplier); - static std::unique_ptr<matcher_t> ParseOperand(const supplier_t* labelSupplier); - static std::unique_ptr<matcher_t> ParseOperationType(const supplier_t* labelSupplier); + static std::unique_ptr<matcher_t> ParseOperandArray(const supplier_t *labelSupplier); + static std::unique_ptr<matcher_t> ParseOperand(const supplier_t *labelSupplier); + static std::unique_ptr<matcher_t> ParseOperationType(const supplier_t *labelSupplier); - static std::unique_ptr<IEvaluation> ProcessEvaluationInParenthesis(CommandsParserState* state, SequenceResult<CommandsParserValue>& result); - static std::unique_ptr<IEvaluation> ProcessOperand(CommandsParserState* state, SequenceResult<CommandsParserValue>& result, StructureInformation* currentType); + static std::unique_ptr<IEvaluation> ProcessEvaluationInParenthesis(CommandsParserState *state, SequenceResult<CommandsParserValue> &result); + static std::unique_ptr<IEvaluation> ProcessOperand(CommandsParserState *state, SequenceResult<CommandsParserValue> &result, + StructureInformation *currentType); public: - static std::unique_ptr<matcher_t> Evaluation(const supplier_t* labelSupplier); - static std::unique_ptr<IEvaluation> ProcessEvaluation(CommandsParserState* state, SequenceResult<CommandsParserValue>& result); - static std::unique_ptr<IEvaluation> ProcessEvaluation(CommandsParserState* state, SequenceResult<CommandsParserValue>& result, StructureInformation* currentType); + static std::unique_ptr<matcher_t> Evaluation(const supplier_t *labelSupplier); + static std::unique_ptr<IEvaluation> ProcessEvaluation(CommandsParserState *state, SequenceResult<CommandsParserValue> &result); + static std::unique_ptr<IEvaluation> ProcessEvaluation(CommandsParserState *state, SequenceResult<CommandsParserValue> &result, + StructureInformation *currentType); }; diff --git a/src/ZoneCodeGeneratorLib/Parsing/Commands/Matcher/CommandsMatcherCharacter.cpp b/src/ZoneCodeGeneratorLib/Parsing/Commands/Matcher/CommandsMatcherCharacter.cpp index 7ed5c9dee..c0ae356bb 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Commands/Matcher/CommandsMatcherCharacter.cpp +++ b/src/ZoneCodeGeneratorLib/Parsing/Commands/Matcher/CommandsMatcherCharacter.cpp @@ -1,14 +1,9 @@ #include "CommandsMatcherCharacter.h" -CommandsMatcherCharacter::CommandsMatcherCharacter(const char c) - : m_char(c) -{ -} +CommandsMatcherCharacter::CommandsMatcherCharacter(const char c) : m_char(c) {} -MatcherResult<CommandsParserValue> CommandsMatcherCharacter::CanMatch(ILexer<CommandsParserValue>* lexer, const unsigned tokenOffset) -{ - const auto& token = lexer->GetToken(tokenOffset); - return token.m_type == CommandsParserValueType::CHARACTER && token.CharacterValue() == m_char - ? MatcherResult<CommandsParserValue>::Match(1) - : MatcherResult<CommandsParserValue>::NoMatch(); +MatcherResult<CommandsParserValue> CommandsMatcherCharacter::CanMatch(ILexer<CommandsParserValue> *lexer, const unsigned tokenOffset) { + const auto &token = lexer->GetToken(tokenOffset); + return token.m_type == CommandsParserValueType::CHARACTER && token.CharacterValue() == m_char ? MatcherResult<CommandsParserValue>::Match(1) + : MatcherResult<CommandsParserValue>::NoMatch(); } diff --git a/src/ZoneCodeGeneratorLib/Parsing/Commands/Matcher/CommandsMatcherCharacter.h b/src/ZoneCodeGeneratorLib/Parsing/Commands/Matcher/CommandsMatcherCharacter.h index 794c372b1..8ffca4c1e 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Commands/Matcher/CommandsMatcherCharacter.h +++ b/src/ZoneCodeGeneratorLib/Parsing/Commands/Matcher/CommandsMatcherCharacter.h @@ -3,13 +3,12 @@ #include "Parsing/Commands/Impl/CommandsParserValue.h" #include "Parsing/Matcher/AbstractMatcher.h" -class CommandsMatcherCharacter final : public AbstractMatcher<CommandsParserValue> -{ - char m_char; +class CommandsMatcherCharacter final : public AbstractMatcher<CommandsParserValue> { + char m_char; protected: - MatcherResult<CommandsParserValue> CanMatch(ILexer<CommandsParserValue>* lexer, unsigned tokenOffset) override; + MatcherResult<CommandsParserValue> CanMatch(ILexer<CommandsParserValue> *lexer, unsigned tokenOffset) override; public: - explicit CommandsMatcherCharacter(char c); + explicit CommandsMatcherCharacter(char c); }; diff --git a/src/ZoneCodeGeneratorLib/Parsing/Commands/Matcher/CommandsMatcherFactory.cpp b/src/ZoneCodeGeneratorLib/Parsing/Commands/Matcher/CommandsMatcherFactory.cpp index 0bd92ed51..1d5c47153 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Commands/Matcher/CommandsMatcherFactory.cpp +++ b/src/ZoneCodeGeneratorLib/Parsing/Commands/Matcher/CommandsMatcherFactory.cpp @@ -4,37 +4,28 @@ #include "CommandsMatcherKeyword.h" #include "CommandsMatcherValueType.h" -CommandsMatcherFactory::CommandsMatcherFactory(const IMatcherForLabelSupplier<CommandsParserValue>* labelSupplier) - : AbstractMatcherFactory(labelSupplier) -{ -} +CommandsMatcherFactory::CommandsMatcherFactory(const IMatcherForLabelSupplier<CommandsParserValue> *labelSupplier) : AbstractMatcherFactory(labelSupplier) {} -MatcherFactoryWrapper<CommandsParserValue> CommandsMatcherFactory::Type(CommandsParserValueType type) const -{ - return MatcherFactoryWrapper<CommandsParserValue>(std::make_unique<CommandsMatcherValueType>(type)); +MatcherFactoryWrapper<CommandsParserValue> CommandsMatcherFactory::Type(CommandsParserValueType type) const { + return MatcherFactoryWrapper<CommandsParserValue>(std::make_unique<CommandsMatcherValueType>(type)); } -MatcherFactoryWrapper<CommandsParserValue> CommandsMatcherFactory::Keyword(std::string value) const -{ - return MatcherFactoryWrapper<CommandsParserValue>(std::make_unique<CommandsMatcherKeyword>(std::move(value))); +MatcherFactoryWrapper<CommandsParserValue> CommandsMatcherFactory::Keyword(std::string value) const { + return MatcherFactoryWrapper<CommandsParserValue>(std::make_unique<CommandsMatcherKeyword>(std::move(value))); } -MatcherFactoryWrapper<CommandsParserValue> CommandsMatcherFactory::Identifier() const -{ - return MatcherFactoryWrapper<CommandsParserValue>(std::make_unique<CommandsMatcherValueType>(CommandsParserValueType::IDENTIFIER)); +MatcherFactoryWrapper<CommandsParserValue> CommandsMatcherFactory::Identifier() const { + return MatcherFactoryWrapper<CommandsParserValue>(std::make_unique<CommandsMatcherValueType>(CommandsParserValueType::IDENTIFIER)); } -MatcherFactoryWrapper<CommandsParserValue> CommandsMatcherFactory::Integer() const -{ - return MatcherFactoryWrapper<CommandsParserValue>(std::make_unique<CommandsMatcherValueType>(CommandsParserValueType::INTEGER)); +MatcherFactoryWrapper<CommandsParserValue> CommandsMatcherFactory::Integer() const { + return MatcherFactoryWrapper<CommandsParserValue>(std::make_unique<CommandsMatcherValueType>(CommandsParserValueType::INTEGER)); } -MatcherFactoryWrapper<CommandsParserValue> CommandsMatcherFactory::FloatingPoint() const -{ - return MatcherFactoryWrapper<CommandsParserValue>(std::make_unique<CommandsMatcherValueType>(CommandsParserValueType::FLOATING_POINT)); +MatcherFactoryWrapper<CommandsParserValue> CommandsMatcherFactory::FloatingPoint() const { + return MatcherFactoryWrapper<CommandsParserValue>(std::make_unique<CommandsMatcherValueType>(CommandsParserValueType::FLOATING_POINT)); } -MatcherFactoryWrapper<CommandsParserValue> CommandsMatcherFactory::Char(char c) const -{ - return MatcherFactoryWrapper<CommandsParserValue>(std::make_unique<CommandsMatcherCharacter>(c)); +MatcherFactoryWrapper<CommandsParserValue> CommandsMatcherFactory::Char(char c) const { + return MatcherFactoryWrapper<CommandsParserValue>(std::make_unique<CommandsMatcherCharacter>(c)); } diff --git a/src/ZoneCodeGeneratorLib/Parsing/Commands/Matcher/CommandsMatcherFactory.h b/src/ZoneCodeGeneratorLib/Parsing/Commands/Matcher/CommandsMatcherFactory.h index 42013f370..6fe9a5b61 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Commands/Matcher/CommandsMatcherFactory.h +++ b/src/ZoneCodeGeneratorLib/Parsing/Commands/Matcher/CommandsMatcherFactory.h @@ -5,15 +5,14 @@ #include "Parsing/Commands/Impl/CommandsParserValue.h" #include "Parsing/Matcher/AbstractMatcherFactory.h" -class CommandsMatcherFactory final : public AbstractMatcherFactory<CommandsParserValue> -{ +class CommandsMatcherFactory final : public AbstractMatcherFactory<CommandsParserValue> { public: - explicit CommandsMatcherFactory(const IMatcherForLabelSupplier<CommandsParserValue>* labelSupplier); + explicit CommandsMatcherFactory(const IMatcherForLabelSupplier<CommandsParserValue> *labelSupplier); - _NODISCARD MatcherFactoryWrapper<CommandsParserValue> Type(CommandsParserValueType type) const; - _NODISCARD MatcherFactoryWrapper<CommandsParserValue> Keyword(std::string value) const; - _NODISCARD MatcherFactoryWrapper<CommandsParserValue> Identifier() const; - _NODISCARD MatcherFactoryWrapper<CommandsParserValue> Integer() const; - _NODISCARD MatcherFactoryWrapper<CommandsParserValue> FloatingPoint() const; - _NODISCARD MatcherFactoryWrapper<CommandsParserValue> Char(char c) const; + _NODISCARD MatcherFactoryWrapper<CommandsParserValue> Type(CommandsParserValueType type) const; + _NODISCARD MatcherFactoryWrapper<CommandsParserValue> Keyword(std::string value) const; + _NODISCARD MatcherFactoryWrapper<CommandsParserValue> Identifier() const; + _NODISCARD MatcherFactoryWrapper<CommandsParserValue> Integer() const; + _NODISCARD MatcherFactoryWrapper<CommandsParserValue> FloatingPoint() const; + _NODISCARD MatcherFactoryWrapper<CommandsParserValue> Char(char c) const; }; diff --git a/src/ZoneCodeGeneratorLib/Parsing/Commands/Matcher/CommandsMatcherKeyword.cpp b/src/ZoneCodeGeneratorLib/Parsing/Commands/Matcher/CommandsMatcherKeyword.cpp index 521666347..e00acfc5a 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Commands/Matcher/CommandsMatcherKeyword.cpp +++ b/src/ZoneCodeGeneratorLib/Parsing/Commands/Matcher/CommandsMatcherKeyword.cpp @@ -1,16 +1,13 @@ #include "CommandsMatcherKeyword.h" -CommandsMatcherKeyword::CommandsMatcherKeyword(std::string value) - : m_value(std::move(value)) -{ - const std::hash<std::string> hash; - m_hash = hash(m_value); +CommandsMatcherKeyword::CommandsMatcherKeyword(std::string value) : m_value(std::move(value)) { + const std::hash<std::string> hash; + m_hash = hash(m_value); } -MatcherResult<CommandsParserValue> CommandsMatcherKeyword::CanMatch(ILexer<CommandsParserValue>* lexer, const unsigned tokenOffset) -{ - const auto& token = lexer->GetToken(tokenOffset); - return token.m_type == CommandsParserValueType::IDENTIFIER && token.IdentifierHash() == m_hash && token.IdentifierValue() == m_value - ? MatcherResult<CommandsParserValue>::Match(1) - : MatcherResult<CommandsParserValue>::NoMatch(); +MatcherResult<CommandsParserValue> CommandsMatcherKeyword::CanMatch(ILexer<CommandsParserValue> *lexer, const unsigned tokenOffset) { + const auto &token = lexer->GetToken(tokenOffset); + return token.m_type == CommandsParserValueType::IDENTIFIER && token.IdentifierHash() == m_hash && token.IdentifierValue() == m_value + ? MatcherResult<CommandsParserValue>::Match(1) + : MatcherResult<CommandsParserValue>::NoMatch(); } diff --git a/src/ZoneCodeGeneratorLib/Parsing/Commands/Matcher/CommandsMatcherKeyword.h b/src/ZoneCodeGeneratorLib/Parsing/Commands/Matcher/CommandsMatcherKeyword.h index 290c09e75..e34713e8c 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Commands/Matcher/CommandsMatcherKeyword.h +++ b/src/ZoneCodeGeneratorLib/Parsing/Commands/Matcher/CommandsMatcherKeyword.h @@ -5,14 +5,13 @@ #include "Parsing/Commands/Impl/CommandsParserValue.h" #include "Parsing/Matcher/AbstractMatcher.h" -class CommandsMatcherKeyword final : public AbstractMatcher<CommandsParserValue> -{ - size_t m_hash; - std::string m_value; +class CommandsMatcherKeyword final : public AbstractMatcher<CommandsParserValue> { + size_t m_hash; + std::string m_value; protected: - MatcherResult<CommandsParserValue> CanMatch(ILexer<CommandsParserValue>* lexer, unsigned tokenOffset) override; + MatcherResult<CommandsParserValue> CanMatch(ILexer<CommandsParserValue> *lexer, unsigned tokenOffset) override; public: - explicit CommandsMatcherKeyword(std::string value); + explicit CommandsMatcherKeyword(std::string value); }; diff --git a/src/ZoneCodeGeneratorLib/Parsing/Commands/Matcher/CommandsMatcherValueType.cpp b/src/ZoneCodeGeneratorLib/Parsing/Commands/Matcher/CommandsMatcherValueType.cpp index 6c4e35325..58326d3b9 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Commands/Matcher/CommandsMatcherValueType.cpp +++ b/src/ZoneCodeGeneratorLib/Parsing/Commands/Matcher/CommandsMatcherValueType.cpp @@ -1,13 +1,7 @@ #include "CommandsMatcherValueType.h" -CommandsMatcherValueType::CommandsMatcherValueType(CommandsParserValueType type) - : m_type(type) -{ -} +CommandsMatcherValueType::CommandsMatcherValueType(CommandsParserValueType type) : m_type(type) {} -MatcherResult<CommandsParserValue> CommandsMatcherValueType::CanMatch(ILexer<CommandsParserValue>* lexer, const unsigned tokenOffset) -{ - return lexer->GetToken(tokenOffset).m_type == m_type - ? MatcherResult<CommandsParserValue>::Match(1) - : MatcherResult<CommandsParserValue>::NoMatch(); +MatcherResult<CommandsParserValue> CommandsMatcherValueType::CanMatch(ILexer<CommandsParserValue> *lexer, const unsigned tokenOffset) { + return lexer->GetToken(tokenOffset).m_type == m_type ? MatcherResult<CommandsParserValue>::Match(1) : MatcherResult<CommandsParserValue>::NoMatch(); } diff --git a/src/ZoneCodeGeneratorLib/Parsing/Commands/Matcher/CommandsMatcherValueType.h b/src/ZoneCodeGeneratorLib/Parsing/Commands/Matcher/CommandsMatcherValueType.h index 59c806edd..1982479de 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Commands/Matcher/CommandsMatcherValueType.h +++ b/src/ZoneCodeGeneratorLib/Parsing/Commands/Matcher/CommandsMatcherValueType.h @@ -3,13 +3,12 @@ #include "Parsing/Commands/Impl/CommandsParserValue.h" #include "Parsing/Matcher/AbstractMatcher.h" -class CommandsMatcherValueType final : public AbstractMatcher<CommandsParserValue> -{ - CommandsParserValueType m_type; +class CommandsMatcherValueType final : public AbstractMatcher<CommandsParserValue> { + CommandsParserValueType m_type; protected: - MatcherResult<CommandsParserValue> CanMatch(ILexer<CommandsParserValue>* lexer, unsigned tokenOffset) override; + MatcherResult<CommandsParserValue> CanMatch(ILexer<CommandsParserValue> *lexer, unsigned tokenOffset) override; public: - explicit CommandsMatcherValueType(CommandsParserValueType type); + explicit CommandsMatcherValueType(CommandsParserValueType type); }; diff --git a/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceAction.cpp b/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceAction.cpp index 59ad7231b..01bad67fe 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceAction.cpp +++ b/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceAction.cpp @@ -1,82 +1,61 @@ #include "SequenceAction.h" -#include "Parsing/Commands/Matcher/CommandsMatcherFactory.h" #include "Parsing/Commands/Matcher/CommandsCommonMatchers.h" +#include "Parsing/Commands/Matcher/CommandsMatcherFactory.h" -SequenceAction::SequenceAction() -{ - const CommandsMatcherFactory create(this); - - AddLabeledMatchers(CommandsCommonMatchers::Typename(this), CommandsCommonMatchers::LABEL_TYPENAME); - AddLabeledMatchers( - { - create.Char('('), - create.Optional(create.And({ - create.Label(CommandsCommonMatchers::LABEL_TYPENAME).Capture(CAPTURE_ARG_TYPE), - create.OptionalLoop(create.And({ - create.Char(','), - create.Label(CommandsCommonMatchers::LABEL_TYPENAME).Capture(CAPTURE_ARG_TYPE) - })) - })), - create.Char(')') - }, LABEL_ACTION_ARGS); - - AddMatchers({ - create.Keyword("set"), - create.Keyword("action"), - create.Or({ - create.And({ - create.Label(CommandsCommonMatchers::LABEL_TYPENAME).Capture(CAPTURE_TYPE), - create.Identifier().Capture(CAPTURE_ACTION_NAME) - }), - create.Identifier().Capture(CAPTURE_ACTION_NAME) - }), - create.Label(LABEL_ACTION_ARGS), - create.Char(';') - }); +SequenceAction::SequenceAction() { + const CommandsMatcherFactory create(this); + + AddLabeledMatchers(CommandsCommonMatchers::Typename(this), CommandsCommonMatchers::LABEL_TYPENAME); + AddLabeledMatchers( + {create.Char('('), + create.Optional( + create.And({create.Label(CommandsCommonMatchers::LABEL_TYPENAME).Capture(CAPTURE_ARG_TYPE), + create.OptionalLoop(create.And({create.Char(','), create.Label(CommandsCommonMatchers::LABEL_TYPENAME).Capture(CAPTURE_ARG_TYPE)}))})), + create.Char(')')}, + LABEL_ACTION_ARGS); + + AddMatchers( + {create.Keyword("set"), create.Keyword("action"), + create.Or({create.And({create.Label(CommandsCommonMatchers::LABEL_TYPENAME).Capture(CAPTURE_TYPE), create.Identifier().Capture(CAPTURE_ACTION_NAME)}), + create.Identifier().Capture(CAPTURE_ACTION_NAME)}), + create.Label(LABEL_ACTION_ARGS), create.Char(';')}); } -void SequenceAction::ProcessMatch(CommandsParserState* state, SequenceResult<CommandsParserValue>& result) const -{ - StructureInformation* type; - const auto& actionNameToken = result.NextCapture(CAPTURE_ACTION_NAME); +void SequenceAction::ProcessMatch(CommandsParserState *state, SequenceResult<CommandsParserValue> &result) const { + StructureInformation *type; + const auto &actionNameToken = result.NextCapture(CAPTURE_ACTION_NAME); - // If a typename was specified then try to parse it - // Otherwise take the name that was specified with the last use command - if (result.HasNextCapture(CAPTURE_TYPE)) - { - const auto& typeNameToken = result.NextCapture(CAPTURE_TYPE); - std::vector<MemberInformation*> memberChain; + // If a typename was specified then try to parse it + // Otherwise take the name that was specified with the last use command + if (result.HasNextCapture(CAPTURE_TYPE)) { + const auto &typeNameToken = result.NextCapture(CAPTURE_TYPE); + std::vector<MemberInformation *> memberChain; - if (!state->GetTypenameAndMembersFromTypename(typeNameToken.TypeNameValue(), type, memberChain)) - throw ParsingException(typeNameToken.GetPos(), "Unknown type"); + if (!state->GetTypenameAndMembersFromTypename(typeNameToken.TypeNameValue(), type, memberChain)) + throw ParsingException(typeNameToken.GetPos(), "Unknown type"); - if (!memberChain.empty()) - { - type = memberChain.back()->m_type; - if (type == nullptr) - throw ParsingException(typeNameToken.GetPos(), "Member is not a data type with members."); - } - } - else if (state->GetInUse() != nullptr) - { - type = state->GetInUse(); + if (!memberChain.empty()) { + type = memberChain.back()->m_type; + if (type == nullptr) + throw ParsingException(typeNameToken.GetPos(), "Member is not a data type with members."); } - else - throw ParsingException(actionNameToken.GetPos(), "No type is used. Therefore one needs to be specified directly."); + } else if (state->GetInUse() != nullptr) { + type = state->GetInUse(); + } else + throw ParsingException(actionNameToken.GetPos(), "No type is used. Therefore one needs to be specified directly."); - // Extract all parameter types that were specified - std::vector<DataDefinition*> parameterTypes; - while(result.HasNextCapture(CAPTURE_ARG_TYPE)) - { - const auto& argTypeToken = result.NextCapture(CAPTURE_ARG_TYPE); - auto* dataDefinition = state->GetRepository()->GetDataDefinitionByName(argTypeToken.TypeNameValue()); + // Extract all parameter types that were specified + std::vector<DataDefinition *> parameterTypes; + while (result.HasNextCapture(CAPTURE_ARG_TYPE)) { + const auto &argTypeToken = result.NextCapture(CAPTURE_ARG_TYPE); + auto *dataDefinition = state->GetRepository()->GetDataDefinitionByName(argTypeToken.TypeNameValue()); - if (dataDefinition == nullptr) - throw ParsingException(argTypeToken.GetPos(), "Unknown type"); + if (dataDefinition == nullptr) + throw ParsingException(argTypeToken.GetPos(), "Unknown type"); - parameterTypes.push_back(dataDefinition); - } + parameterTypes.push_back(dataDefinition); + } - type->m_post_load_action = std::make_unique<CustomAction>(actionNameToken.IdentifierValue(), std::move(parameterTypes)); + type->m_post_load_action = std::make_unique<CustomAction>(actionNameToken.IdentifierValue(), std::move(parameterTypes)); } diff --git a/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceAction.h b/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceAction.h index b418ec818..0e24ef2d6 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceAction.h +++ b/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceAction.h @@ -2,17 +2,16 @@ #include "Parsing/Commands/Impl/CommandsParser.h" -class SequenceAction final : public CommandsParser::sequence_t -{ - static constexpr auto CAPTURE_ACTION_NAME = 1; - static constexpr auto CAPTURE_TYPE = 2; - static constexpr auto CAPTURE_ARG_TYPE = 3; +class SequenceAction final : public CommandsParser::sequence_t { + static constexpr auto CAPTURE_ACTION_NAME = 1; + static constexpr auto CAPTURE_TYPE = 2; + static constexpr auto CAPTURE_ARG_TYPE = 3; - static constexpr auto LABEL_ACTION_ARGS = 1; + static constexpr auto LABEL_ACTION_ARGS = 1; protected: - void ProcessMatch(CommandsParserState* state, SequenceResult<CommandsParserValue>& result) const override; + void ProcessMatch(CommandsParserState *state, SequenceResult<CommandsParserValue> &result) const override; public: - SequenceAction(); + SequenceAction(); }; diff --git a/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceAllocAlign.cpp b/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceAllocAlign.cpp index 52e362537..fe9ba2b1f 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceAllocAlign.cpp +++ b/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceAllocAlign.cpp @@ -1,34 +1,27 @@ #include "SequenceAllocAlign.h" -#include "Parsing/Commands/Matcher/CommandsMatcherFactory.h" #include "Parsing/Commands/Matcher/CommandsCommonMatchers.h" +#include "Parsing/Commands/Matcher/CommandsMatcherFactory.h" -SequenceAllocAlign::SequenceAllocAlign() -{ - const CommandsMatcherFactory create(this); +SequenceAllocAlign::SequenceAllocAlign() { + const CommandsMatcherFactory create(this); - AddLabeledMatchers(CommandsCommonMatchers::Typename(this), CommandsCommonMatchers::LABEL_TYPENAME); - AddLabeledMatchers(CommandsCommonMatchers::Evaluation(this), CommandsCommonMatchers::LABEL_EVALUATION); - AddMatchers({ - create.Keyword("set"), - create.Keyword("allocalign"), - create.Label(CommandsCommonMatchers::LABEL_TYPENAME).Capture(CAPTURE_TYPE), - create.Label(CommandsCommonMatchers::LABEL_EVALUATION), - create.Char(';') - }); + AddLabeledMatchers(CommandsCommonMatchers::Typename(this), CommandsCommonMatchers::LABEL_TYPENAME); + AddLabeledMatchers(CommandsCommonMatchers::Evaluation(this), CommandsCommonMatchers::LABEL_EVALUATION); + AddMatchers({create.Keyword("set"), create.Keyword("allocalign"), create.Label(CommandsCommonMatchers::LABEL_TYPENAME).Capture(CAPTURE_TYPE), + create.Label(CommandsCommonMatchers::LABEL_EVALUATION), create.Char(';')}); } -void SequenceAllocAlign::ProcessMatch(CommandsParserState* state, SequenceResult<CommandsParserValue>& result) const -{ - const auto& typeNameToken = result.NextCapture(CAPTURE_TYPE); - StructureInformation* type; - std::vector<MemberInformation*> memberChain; - if (!state->GetTypenameAndMembersFromTypename(typeNameToken.TypeNameValue(), type, memberChain)) - throw ParsingException(typeNameToken.GetPos(), "Unknown type"); +void SequenceAllocAlign::ProcessMatch(CommandsParserState *state, SequenceResult<CommandsParserValue> &result) const { + const auto &typeNameToken = result.NextCapture(CAPTURE_TYPE); + StructureInformation *type; + std::vector<MemberInformation *> memberChain; + if (!state->GetTypenameAndMembersFromTypename(typeNameToken.TypeNameValue(), type, memberChain)) + throw ParsingException(typeNameToken.GetPos(), "Unknown type"); - if(memberChain.empty()) - throw ParsingException(typeNameToken.GetPos(), "Need to specify a member"); + if (memberChain.empty()) + throw ParsingException(typeNameToken.GetPos(), "Need to specify a member"); - auto allocAlignEvaluation = CommandsCommonMatchers::ProcessEvaluation(state, result, type); - memberChain.back()->m_alloc_alignment = std::move(allocAlignEvaluation); + auto allocAlignEvaluation = CommandsCommonMatchers::ProcessEvaluation(state, result, type); + memberChain.back()->m_alloc_alignment = std::move(allocAlignEvaluation); } diff --git a/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceAllocAlign.h b/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceAllocAlign.h index d4bc00d8f..51b760c9f 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceAllocAlign.h +++ b/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceAllocAlign.h @@ -2,13 +2,12 @@ #include "Parsing/Commands/Impl/CommandsParser.h" -class SequenceAllocAlign final : public CommandsParser::sequence_t -{ - static constexpr auto CAPTURE_TYPE = 1; +class SequenceAllocAlign final : public CommandsParser::sequence_t { + static constexpr auto CAPTURE_TYPE = 1; protected: - void ProcessMatch(CommandsParserState* state, SequenceResult<CommandsParserValue>& result) const override; + void ProcessMatch(CommandsParserState *state, SequenceResult<CommandsParserValue> &result) const override; public: - SequenceAllocAlign(); + SequenceAllocAlign(); }; diff --git a/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceArchitecture.cpp b/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceArchitecture.cpp index a553e5c4c..5b46ccf25 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceArchitecture.cpp +++ b/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceArchitecture.cpp @@ -1,30 +1,24 @@ #include "SequenceArchitecture.h" -#include "Parsing/Commands/Matcher/CommandsMatcherFactory.h" #include "Parsing/Commands/Matcher/CommandsCommonMatchers.h" +#include "Parsing/Commands/Matcher/CommandsMatcherFactory.h" -SequenceArchitecture::SequenceArchitecture() -{ - const CommandsMatcherFactory create(this); +SequenceArchitecture::SequenceArchitecture() { + const CommandsMatcherFactory create(this); - AddMatchers({ - create.Keyword("architecture"), - create.Identifier().Capture(CAPTURE_ARCHITECTURE), - create.Char(';') - }); + AddMatchers({create.Keyword("architecture"), create.Identifier().Capture(CAPTURE_ARCHITECTURE), create.Char(';')}); - m_architecture_mapping["x86"] = Architecture::X86; - m_architecture_mapping["x64"] = Architecture::X64; + m_architecture_mapping["x86"] = Architecture::X86; + m_architecture_mapping["x64"] = Architecture::X64; } -void SequenceArchitecture::ProcessMatch(CommandsParserState* state, SequenceResult<CommandsParserValue>& result) const -{ - const auto& architectureToken = result.NextCapture(CAPTURE_ARCHITECTURE); +void SequenceArchitecture::ProcessMatch(CommandsParserState *state, SequenceResult<CommandsParserValue> &result) const { + const auto &architectureToken = result.NextCapture(CAPTURE_ARCHITECTURE); - const auto foundArchitecture = m_architecture_mapping.find(architectureToken.IdentifierValue()); + const auto foundArchitecture = m_architecture_mapping.find(architectureToken.IdentifierValue()); - if(foundArchitecture == m_architecture_mapping.end()) - throw ParsingException(architectureToken.GetPos(), "Unknown architecture"); + if (foundArchitecture == m_architecture_mapping.end()) + throw ParsingException(architectureToken.GetPos(), "Unknown architecture"); - state->SetArchitecture(foundArchitecture->second); + state->SetArchitecture(foundArchitecture->second); } diff --git a/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceArchitecture.h b/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceArchitecture.h index 4dd0b5bd8..adfcb9ecb 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceArchitecture.h +++ b/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceArchitecture.h @@ -2,15 +2,14 @@ #include "Parsing/Commands/Impl/CommandsParser.h" -class SequenceArchitecture final : public CommandsParser::sequence_t -{ - static constexpr auto CAPTURE_ARCHITECTURE = 1; +class SequenceArchitecture final : public CommandsParser::sequence_t { + static constexpr auto CAPTURE_ARCHITECTURE = 1; - std::unordered_map<std::string, Architecture> m_architecture_mapping; + std::unordered_map<std::string, Architecture> m_architecture_mapping; protected: - void ProcessMatch(CommandsParserState* state, SequenceResult<CommandsParserValue>& result) const override; + void ProcessMatch(CommandsParserState *state, SequenceResult<CommandsParserValue> &result) const override; public: - SequenceArchitecture(); + SequenceArchitecture(); }; diff --git a/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceArrayCount.cpp b/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceArrayCount.cpp index 48a1284e9..2114ff6ed 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceArrayCount.cpp +++ b/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceArrayCount.cpp @@ -1,52 +1,42 @@ #include "SequenceArrayCount.h" - #include "Domain/Definition/ArrayDeclarationModifier.h" -#include "Parsing/Commands/Matcher/CommandsMatcherFactory.h" #include "Parsing/Commands/Matcher/CommandsCommonMatchers.h" +#include "Parsing/Commands/Matcher/CommandsMatcherFactory.h" + +SequenceArrayCount::SequenceArrayCount() { + const CommandsMatcherFactory create(this); -SequenceArrayCount::SequenceArrayCount() -{ - const CommandsMatcherFactory create(this); - - AddLabeledMatchers(CommandsCommonMatchers::Typename(this), CommandsCommonMatchers::LABEL_TYPENAME); - AddLabeledMatchers(CommandsCommonMatchers::Evaluation(this), CommandsCommonMatchers::LABEL_EVALUATION); - AddMatchers({ - create.Keyword("set"), - create.Keyword("arraycount"), - create.Label(CommandsCommonMatchers::LABEL_TYPENAME).Capture(CAPTURE_TYPE), - create.Label(CommandsCommonMatchers::LABEL_EVALUATION), - create.Char(';') - }); + AddLabeledMatchers(CommandsCommonMatchers::Typename(this), CommandsCommonMatchers::LABEL_TYPENAME); + AddLabeledMatchers(CommandsCommonMatchers::Evaluation(this), CommandsCommonMatchers::LABEL_EVALUATION); + AddMatchers({create.Keyword("set"), create.Keyword("arraycount"), create.Label(CommandsCommonMatchers::LABEL_TYPENAME).Capture(CAPTURE_TYPE), + create.Label(CommandsCommonMatchers::LABEL_EVALUATION), create.Char(';')}); } -void SequenceArrayCount::ProcessMatch(CommandsParserState* state, SequenceResult<CommandsParserValue>& result) const -{ - const auto& typeNameToken = result.NextCapture(CAPTURE_TYPE); - - StructureInformation* structure; - std::vector<MemberInformation*> memberChain; - if (!state->GetTypenameAndMembersFromTypename(typeNameToken.TypeNameValue(), structure, memberChain)) - throw ParsingException(typeNameToken.GetPos(), "Unknown type"); - - if(memberChain.empty()) - throw ParsingException(typeNameToken.GetPos(), "Must specify type with member"); - - const auto& memberDeclarationModifiers = memberChain.back()->m_member->m_type_declaration->m_declaration_modifiers; - ArrayDeclarationModifier* arrayModifier = nullptr; - for (const auto& modifier : memberDeclarationModifiers) - { - if (modifier->GetType() == DeclarationModifierType::ARRAY) - { - arrayModifier = dynamic_cast<ArrayDeclarationModifier*>(modifier.get()); - break; - } +void SequenceArrayCount::ProcessMatch(CommandsParserState *state, SequenceResult<CommandsParserValue> &result) const { + const auto &typeNameToken = result.NextCapture(CAPTURE_TYPE); + + StructureInformation *structure; + std::vector<MemberInformation *> memberChain; + if (!state->GetTypenameAndMembersFromTypename(typeNameToken.TypeNameValue(), structure, memberChain)) + throw ParsingException(typeNameToken.GetPos(), "Unknown type"); + + if (memberChain.empty()) + throw ParsingException(typeNameToken.GetPos(), "Must specify type with member"); + + const auto &memberDeclarationModifiers = memberChain.back()->m_member->m_type_declaration->m_declaration_modifiers; + ArrayDeclarationModifier *arrayModifier = nullptr; + for (const auto &modifier : memberDeclarationModifiers) { + if (modifier->GetType() == DeclarationModifierType::ARRAY) { + arrayModifier = dynamic_cast<ArrayDeclarationModifier *>(modifier.get()); + break; } + } - if (arrayModifier == nullptr) - throw ParsingException(typeNameToken.GetPos(), "Specified member is not an array"); + if (arrayModifier == nullptr) + throw ParsingException(typeNameToken.GetPos(), "Specified member is not an array"); - auto evaluation = CommandsCommonMatchers::ProcessEvaluation(state, result, structure); + auto evaluation = CommandsCommonMatchers::ProcessEvaluation(state, result, structure); - arrayModifier->m_dynamic_count_evaluation = std::move(evaluation); + arrayModifier->m_dynamic_count_evaluation = std::move(evaluation); } diff --git a/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceArrayCount.h b/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceArrayCount.h index d134304fb..73eec4ddb 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceArrayCount.h +++ b/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceArrayCount.h @@ -2,13 +2,12 @@ #include "Parsing/Commands/Impl/CommandsParser.h" -class SequenceArrayCount final : public CommandsParser::sequence_t -{ - static constexpr auto CAPTURE_TYPE = 1; +class SequenceArrayCount final : public CommandsParser::sequence_t { + static constexpr auto CAPTURE_TYPE = 1; protected: - void ProcessMatch(CommandsParserState* state, SequenceResult<CommandsParserValue>& result) const override; + void ProcessMatch(CommandsParserState *state, SequenceResult<CommandsParserValue> &result) const override; public: - SequenceArrayCount(); + SequenceArrayCount(); }; diff --git a/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceArraySize.cpp b/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceArraySize.cpp index 88a25a38a..57be15dc9 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceArraySize.cpp +++ b/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceArraySize.cpp @@ -1,52 +1,42 @@ #include "SequenceArraySize.h" - #include "Domain/Definition/ArrayDeclarationModifier.h" -#include "Parsing/Commands/Matcher/CommandsMatcherFactory.h" #include "Parsing/Commands/Matcher/CommandsCommonMatchers.h" +#include "Parsing/Commands/Matcher/CommandsMatcherFactory.h" + +SequenceArraySize::SequenceArraySize() { + const CommandsMatcherFactory create(this); -SequenceArraySize::SequenceArraySize() -{ - const CommandsMatcherFactory create(this); - - AddLabeledMatchers(CommandsCommonMatchers::Typename(this), CommandsCommonMatchers::LABEL_TYPENAME); - AddLabeledMatchers(CommandsCommonMatchers::Evaluation(this), CommandsCommonMatchers::LABEL_EVALUATION); - AddMatchers({ - create.Keyword("set"), - create.Keyword("arraysize"), - create.Label(CommandsCommonMatchers::LABEL_TYPENAME).Capture(CAPTURE_TYPE), - create.Label(CommandsCommonMatchers::LABEL_EVALUATION).Capture(CAPTURE_EVALUATION), - create.Char(';') - }); + AddLabeledMatchers(CommandsCommonMatchers::Typename(this), CommandsCommonMatchers::LABEL_TYPENAME); + AddLabeledMatchers(CommandsCommonMatchers::Evaluation(this), CommandsCommonMatchers::LABEL_EVALUATION); + AddMatchers({create.Keyword("set"), create.Keyword("arraysize"), create.Label(CommandsCommonMatchers::LABEL_TYPENAME).Capture(CAPTURE_TYPE), + create.Label(CommandsCommonMatchers::LABEL_EVALUATION).Capture(CAPTURE_EVALUATION), create.Char(';')}); } -void SequenceArraySize::ProcessMatch(CommandsParserState* state, SequenceResult<CommandsParserValue>& result) const -{ - const auto& typeNameToken = result.NextCapture(CAPTURE_TYPE); - - StructureInformation* structure; - std::vector<MemberInformation*> memberChain; - if (!state->GetTypenameAndMembersFromTypename(typeNameToken.TypeNameValue(), structure, memberChain)) - throw ParsingException(typeNameToken.GetPos(), "Unknown type"); - - if (memberChain.empty()) - throw ParsingException(typeNameToken.GetPos(), "Must specify type with member"); - - const auto& memberDeclarationModifiers = memberChain.back()->m_member->m_type_declaration->m_declaration_modifiers; - ArrayDeclarationModifier* arrayModifier = nullptr; - for (const auto& modifier : memberDeclarationModifiers) - { - if (modifier->GetType() == DeclarationModifierType::ARRAY) - { - arrayModifier = dynamic_cast<ArrayDeclarationModifier*>(modifier.get()); - break; - } +void SequenceArraySize::ProcessMatch(CommandsParserState *state, SequenceResult<CommandsParserValue> &result) const { + const auto &typeNameToken = result.NextCapture(CAPTURE_TYPE); + + StructureInformation *structure; + std::vector<MemberInformation *> memberChain; + if (!state->GetTypenameAndMembersFromTypename(typeNameToken.TypeNameValue(), structure, memberChain)) + throw ParsingException(typeNameToken.GetPos(), "Unknown type"); + + if (memberChain.empty()) + throw ParsingException(typeNameToken.GetPos(), "Must specify type with member"); + + const auto &memberDeclarationModifiers = memberChain.back()->m_member->m_type_declaration->m_declaration_modifiers; + ArrayDeclarationModifier *arrayModifier = nullptr; + for (const auto &modifier : memberDeclarationModifiers) { + if (modifier->GetType() == DeclarationModifierType::ARRAY) { + arrayModifier = dynamic_cast<ArrayDeclarationModifier *>(modifier.get()); + break; } + } - if (arrayModifier == nullptr) - throw ParsingException(typeNameToken.GetPos(), "Specified member is not an array"); + if (arrayModifier == nullptr) + throw ParsingException(typeNameToken.GetPos(), "Specified member is not an array"); - auto evaluation = CommandsCommonMatchers::ProcessEvaluation(state, result, structure); + auto evaluation = CommandsCommonMatchers::ProcessEvaluation(state, result, structure); - arrayModifier->m_dynamic_size_evaluation = std::move(evaluation); + arrayModifier->m_dynamic_size_evaluation = std::move(evaluation); } diff --git a/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceArraySize.h b/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceArraySize.h index 795318bbf..c70075c5d 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceArraySize.h +++ b/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceArraySize.h @@ -2,14 +2,13 @@ #include "Parsing/Commands/Impl/CommandsParser.h" -class SequenceArraySize final : public CommandsParser::sequence_t -{ - static constexpr auto CAPTURE_TYPE = 1; - static constexpr auto CAPTURE_EVALUATION = 2; +class SequenceArraySize final : public CommandsParser::sequence_t { + static constexpr auto CAPTURE_TYPE = 1; + static constexpr auto CAPTURE_EVALUATION = 2; protected: - void ProcessMatch(CommandsParserState* state, SequenceResult<CommandsParserValue>& result) const override; + void ProcessMatch(CommandsParserState *state, SequenceResult<CommandsParserValue> &result) const override; public: - SequenceArraySize(); + SequenceArraySize(); }; diff --git a/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceAsset.cpp b/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceAsset.cpp index 2e11db0bb..1f2d1c094 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceAsset.cpp +++ b/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceAsset.cpp @@ -1,41 +1,35 @@ #include "SequenceAsset.h" -#include "Parsing/Commands/Matcher/CommandsMatcherFactory.h" #include "Parsing/Commands/Matcher/CommandsCommonMatchers.h" +#include "Parsing/Commands/Matcher/CommandsMatcherFactory.h" + +SequenceAsset::SequenceAsset() { + const CommandsMatcherFactory create(this); -SequenceAsset::SequenceAsset() -{ - const CommandsMatcherFactory create(this); - - AddLabeledMatchers(CommandsCommonMatchers::Typename(this), CommandsCommonMatchers::LABEL_TYPENAME); - AddMatchers({ - create.Keyword("asset"), - create.Label(CommandsCommonMatchers::LABEL_TYPENAME).Capture(CAPTURE_TYPE), - create.Identifier().Capture(CAPTURE_ENUM_ENTRY), - create.Char(';') - }); + AddLabeledMatchers(CommandsCommonMatchers::Typename(this), CommandsCommonMatchers::LABEL_TYPENAME); + AddMatchers({create.Keyword("asset"), create.Label(CommandsCommonMatchers::LABEL_TYPENAME).Capture(CAPTURE_TYPE), + create.Identifier().Capture(CAPTURE_ENUM_ENTRY), create.Char(';')}); } -void SequenceAsset::ProcessMatch(CommandsParserState* state, SequenceResult<CommandsParserValue>& result) const -{ - const auto& typeNameToken = result.NextCapture(CAPTURE_TYPE); - const auto& enumEntryToken = result.NextCapture(CAPTURE_ENUM_ENTRY); +void SequenceAsset::ProcessMatch(CommandsParserState *state, SequenceResult<CommandsParserValue> &result) const { + const auto &typeNameToken = result.NextCapture(CAPTURE_TYPE); + const auto &enumEntryToken = result.NextCapture(CAPTURE_ENUM_ENTRY); - auto* definition = state->GetRepository()->GetDataDefinitionByName(typeNameToken.TypeNameValue()); - if (definition == nullptr) - throw ParsingException(typeNameToken.GetPos(), "Unknown type"); + auto *definition = state->GetRepository()->GetDataDefinitionByName(typeNameToken.TypeNameValue()); + if (definition == nullptr) + throw ParsingException(typeNameToken.GetPos(), "Unknown type"); - auto* definitionWithMembers = dynamic_cast<DefinitionWithMembers*>(definition); - if (definitionWithMembers == nullptr) - throw ParsingException(typeNameToken.GetPos(), "Type must be struct or union"); + auto *definitionWithMembers = dynamic_cast<DefinitionWithMembers *>(definition); + if (definitionWithMembers == nullptr) + throw ParsingException(typeNameToken.GetPos(), "Type must be struct or union"); - auto* information = state->GetRepository()->GetInformationFor(definitionWithMembers); - if (information == nullptr) - throw ParsingException(typeNameToken.GetPos(), "No information for definition"); + auto *information = state->GetRepository()->GetInformationFor(definitionWithMembers); + if (information == nullptr) + throw ParsingException(typeNameToken.GetPos(), "No information for definition"); - auto* enumMember = state->GetRepository()->GetEnumMemberByName(enumEntryToken.IdentifierValue()); - if (enumMember == nullptr) - throw ParsingException(enumEntryToken.GetPos(), "Unknown enum entry"); + auto *enumMember = state->GetRepository()->GetEnumMemberByName(enumEntryToken.IdentifierValue()); + if (enumMember == nullptr) + throw ParsingException(enumEntryToken.GetPos(), "Unknown enum entry"); - information->m_asset_enum_entry = enumMember; + information->m_asset_enum_entry = enumMember; } diff --git a/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceAsset.h b/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceAsset.h index b4cae4f39..a5feb4349 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceAsset.h +++ b/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceAsset.h @@ -2,14 +2,13 @@ #include "Parsing/Commands/Impl/CommandsParser.h" -class SequenceAsset final : public CommandsParser::sequence_t -{ - static constexpr auto CAPTURE_TYPE = 1; - static constexpr auto CAPTURE_ENUM_ENTRY = 2; +class SequenceAsset final : public CommandsParser::sequence_t { + static constexpr auto CAPTURE_TYPE = 1; + static constexpr auto CAPTURE_ENUM_ENTRY = 2; protected: - void ProcessMatch(CommandsParserState* state, SequenceResult<CommandsParserValue>& result) const override; + void ProcessMatch(CommandsParserState *state, SequenceResult<CommandsParserValue> &result) const override; public: - SequenceAsset(); + SequenceAsset(); }; diff --git a/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceBlock.cpp b/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceBlock.cpp index 85f21dee0..fbcb78460 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceBlock.cpp +++ b/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceBlock.cpp @@ -1,59 +1,50 @@ #include "SequenceBlock.h" -#include "Parsing/Commands/Matcher/CommandsMatcherFactory.h" #include "Parsing/Commands/Matcher/CommandsCommonMatchers.h" +#include "Parsing/Commands/Matcher/CommandsMatcherFactory.h" -SequenceBlock::SequenceBlock() -{ - const CommandsMatcherFactory create(this); +SequenceBlock::SequenceBlock() { + const CommandsMatcherFactory create(this); #define DEFINE_FAST_FILE_BLOCK_TYPE(type) AddFastFileBlockToLookup(#type, FastFileBlockType::type) - DEFINE_FAST_FILE_BLOCK_TYPE(TEMP); - DEFINE_FAST_FILE_BLOCK_TYPE(RUNTIME); - DEFINE_FAST_FILE_BLOCK_TYPE(DELAY); - DEFINE_FAST_FILE_BLOCK_TYPE(NORMAL); + DEFINE_FAST_FILE_BLOCK_TYPE(TEMP); + DEFINE_FAST_FILE_BLOCK_TYPE(RUNTIME); + DEFINE_FAST_FILE_BLOCK_TYPE(DELAY); + DEFINE_FAST_FILE_BLOCK_TYPE(NORMAL); #undef DEFINE_FAST_FILE_BLOCK_TYPE - AddMatchers({ - create.Keyword("block"), - create.Identifier().Capture(CAPTURE_BLOCK_TYPE), - create.Identifier().Capture(CAPTURE_BLOCK_ENUM_ENTRY), - create.Optional(create.Keyword("default").Tag(TAG_DEFAULT)), - create.Char(';') - }); + AddMatchers({create.Keyword("block"), create.Identifier().Capture(CAPTURE_BLOCK_TYPE), create.Identifier().Capture(CAPTURE_BLOCK_ENUM_ENTRY), + create.Optional(create.Keyword("default").Tag(TAG_DEFAULT)), create.Char(';')}); } -void SequenceBlock::AddFastFileBlockToLookup(std::string name, const FastFileBlockType type) -{ - for (auto& c : name) - c = static_cast<char>(tolower(c)); +void SequenceBlock::AddFastFileBlockToLookup(std::string name, const FastFileBlockType type) { + for (auto &c : name) + c = static_cast<char>(tolower(c)); - m_type_lookup[name] = type; + m_type_lookup[name] = type; } -bool SequenceBlock::GetFastFileBlockNameByType(const std::string& name, FastFileBlockType& type) const -{ - const auto foundEntry = m_type_lookup.find(name); - if (foundEntry == m_type_lookup.end()) - return false; +bool SequenceBlock::GetFastFileBlockNameByType(const std::string &name, FastFileBlockType &type) const { + const auto foundEntry = m_type_lookup.find(name); + if (foundEntry == m_type_lookup.end()) + return false; - type = foundEntry->second; - return true; + type = foundEntry->second; + return true; } -void SequenceBlock::ProcessMatch(CommandsParserState* state, SequenceResult<CommandsParserValue>& result) const -{ - const auto& enumEntryToken = result.NextCapture(CAPTURE_BLOCK_ENUM_ENTRY); - auto* enumMember = state->GetRepository()->GetEnumMemberByName(enumEntryToken.IdentifierValue()); - if (enumMember == nullptr) - throw ParsingException(enumEntryToken.GetPos(), "Unknown block enum entry"); +void SequenceBlock::ProcessMatch(CommandsParserState *state, SequenceResult<CommandsParserValue> &result) const { + const auto &enumEntryToken = result.NextCapture(CAPTURE_BLOCK_ENUM_ENTRY); + auto *enumMember = state->GetRepository()->GetEnumMemberByName(enumEntryToken.IdentifierValue()); + if (enumMember == nullptr) + throw ParsingException(enumEntryToken.GetPos(), "Unknown block enum entry"); - const auto& typeToken = result.NextCapture(CAPTURE_BLOCK_TYPE); - FastFileBlockType type; - if (!GetFastFileBlockNameByType(typeToken.IdentifierValue(), type)) - throw ParsingException(typeToken.GetPos(), "Unknown fastfile block type"); + const auto &typeToken = result.NextCapture(CAPTURE_BLOCK_TYPE); + FastFileBlockType type; + if (!GetFastFileBlockNameByType(typeToken.IdentifierValue(), type)) + throw ParsingException(typeToken.GetPos(), "Unknown fastfile block type"); - auto isDefault = result.PeekAndRemoveIfTag(TAG_DEFAULT) == TAG_DEFAULT; + auto isDefault = result.PeekAndRemoveIfTag(TAG_DEFAULT) == TAG_DEFAULT; - state->AddBlock(std::make_unique<FastFileBlock>(enumMember->m_name, static_cast<int>(enumMember->m_value), type, isDefault)); + state->AddBlock(std::make_unique<FastFileBlock>(enumMember->m_name, static_cast<int>(enumMember->m_value), type, isDefault)); } diff --git a/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceBlock.h b/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceBlock.h index 296ac97db..2679e7a5a 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceBlock.h +++ b/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceBlock.h @@ -2,24 +2,23 @@ #include <unordered_map> -#include "Utils/ClassUtils.h" #include "Parsing/Commands/Impl/CommandsParser.h" +#include "Utils/ClassUtils.h" -class SequenceBlock final : public CommandsParser::sequence_t -{ - static constexpr auto TAG_DEFAULT = 1; +class SequenceBlock final : public CommandsParser::sequence_t { + static constexpr auto TAG_DEFAULT = 1; - static constexpr auto CAPTURE_BLOCK_ENUM_ENTRY = 1; - static constexpr auto CAPTURE_BLOCK_TYPE = 2; + static constexpr auto CAPTURE_BLOCK_ENUM_ENTRY = 1; + static constexpr auto CAPTURE_BLOCK_TYPE = 2; - std::unordered_map<std::string, FastFileBlockType> m_type_lookup; + std::unordered_map<std::string, FastFileBlockType> m_type_lookup; - void AddFastFileBlockToLookup(std::string name, FastFileBlockType type); - _NODISCARD bool GetFastFileBlockNameByType(const std::string& name, FastFileBlockType& type) const; + void AddFastFileBlockToLookup(std::string name, FastFileBlockType type); + _NODISCARD bool GetFastFileBlockNameByType(const std::string &name, FastFileBlockType &type) const; protected: - void ProcessMatch(CommandsParserState* state, SequenceResult<CommandsParserValue>& result) const override; + void ProcessMatch(CommandsParserState *state, SequenceResult<CommandsParserValue> &result) const override; public: - SequenceBlock(); + SequenceBlock(); }; diff --git a/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceCondition.cpp b/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceCondition.cpp index db18a5d5e..a1758d6a7 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceCondition.cpp +++ b/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceCondition.cpp @@ -1,58 +1,48 @@ #include "SequenceCondition.h" #include "Domain/Evaluation/OperandStatic.h" -#include "Parsing/Commands/Matcher/CommandsMatcherFactory.h" #include "Parsing/Commands/Matcher/CommandsCommonMatchers.h" +#include "Parsing/Commands/Matcher/CommandsMatcherFactory.h" + +SequenceCondition::SequenceCondition() { + const CommandsMatcherFactory create(this); -SequenceCondition::SequenceCondition() -{ - const CommandsMatcherFactory create(this); - - AddLabeledMatchers(CommandsCommonMatchers::Typename(this), CommandsCommonMatchers::LABEL_TYPENAME); - AddLabeledMatchers(CommandsCommonMatchers::Evaluation(this), CommandsCommonMatchers::LABEL_EVALUATION); - AddMatchers({ - create.Keyword("set"), - create.Keyword("condition"), - create.Label(CommandsCommonMatchers::LABEL_TYPENAME).Capture(CAPTURE_TYPE), - create.Or({ - create.Keyword("always").Tag(TAG_ALWAYS), - create.Keyword("never").Tag(TAG_NEVER), - create.Label(CommandsCommonMatchers::LABEL_EVALUATION).Tag(TAG_EVALUATION).Capture(CAPTURE_EVALUATION) - }), - create.Char(';') - }); + AddLabeledMatchers(CommandsCommonMatchers::Typename(this), CommandsCommonMatchers::LABEL_TYPENAME); + AddLabeledMatchers(CommandsCommonMatchers::Evaluation(this), CommandsCommonMatchers::LABEL_EVALUATION); + AddMatchers({create.Keyword("set"), create.Keyword("condition"), create.Label(CommandsCommonMatchers::LABEL_TYPENAME).Capture(CAPTURE_TYPE), + create.Or({create.Keyword("always").Tag(TAG_ALWAYS), create.Keyword("never").Tag(TAG_NEVER), + create.Label(CommandsCommonMatchers::LABEL_EVALUATION).Tag(TAG_EVALUATION).Capture(CAPTURE_EVALUATION)}), + create.Char(';')}); } -void SequenceCondition::ProcessMatch(CommandsParserState* state, SequenceResult<CommandsParserValue>& result) const -{ - const auto& typeNameToken = result.NextCapture(CAPTURE_TYPE); +void SequenceCondition::ProcessMatch(CommandsParserState *state, SequenceResult<CommandsParserValue> &result) const { + const auto &typeNameToken = result.NextCapture(CAPTURE_TYPE); - StructureInformation* type; - std::vector<MemberInformation*> memberChain; - if (!state->GetTypenameAndMembersFromTypename(typeNameToken.TypeNameValue(), type, memberChain)) - throw ParsingException(typeNameToken.GetPos(), "Unknown type"); + StructureInformation *type; + std::vector<MemberInformation *> memberChain; + if (!state->GetTypenameAndMembersFromTypename(typeNameToken.TypeNameValue(), type, memberChain)) + throw ParsingException(typeNameToken.GetPos(), "Unknown type"); - if (memberChain.empty()) - throw ParsingException(typeNameToken.GetPos(), "Conditions can only be set on members and not for types"); + if (memberChain.empty()) + throw ParsingException(typeNameToken.GetPos(), "Conditions can only be set on members and not for types"); - std::unique_ptr<IEvaluation> conditionEvaluation; - switch(result.NextTag()) - { - case TAG_ALWAYS: - conditionEvaluation = std::make_unique<OperandStatic>(1); - break; + std::unique_ptr<IEvaluation> conditionEvaluation; + switch (result.NextTag()) { + case TAG_ALWAYS: + conditionEvaluation = std::make_unique<OperandStatic>(1); + break; - case TAG_NEVER: - conditionEvaluation = std::make_unique<OperandStatic>(0); - break; + case TAG_NEVER: + conditionEvaluation = std::make_unique<OperandStatic>(0); + break; - case TAG_EVALUATION: - conditionEvaluation = CommandsCommonMatchers::ProcessEvaluation(state, result, type); - break; + case TAG_EVALUATION: + conditionEvaluation = CommandsCommonMatchers::ProcessEvaluation(state, result, type); + break; - default: - throw ParsingException(TokenPos(), "Unknown evaluation type @ Condition"); - } + default: + throw ParsingException(TokenPos(), "Unknown evaluation type @ Condition"); + } - memberChain.back()->m_condition = std::move(conditionEvaluation); + memberChain.back()->m_condition = std::move(conditionEvaluation); } diff --git a/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceCondition.h b/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceCondition.h index b10f46001..08a4e32e8 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceCondition.h +++ b/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceCondition.h @@ -2,18 +2,17 @@ #include "Parsing/Commands/Impl/CommandsParser.h" -class SequenceCondition final : public CommandsParser::sequence_t -{ - static constexpr auto TAG_ALWAYS = 1; - static constexpr auto TAG_NEVER = 2; - static constexpr auto TAG_EVALUATION = 3; +class SequenceCondition final : public CommandsParser::sequence_t { + static constexpr auto TAG_ALWAYS = 1; + static constexpr auto TAG_NEVER = 2; + static constexpr auto TAG_EVALUATION = 3; - static constexpr auto CAPTURE_TYPE = 1; - static constexpr auto CAPTURE_EVALUATION = 2; + static constexpr auto CAPTURE_TYPE = 1; + static constexpr auto CAPTURE_EVALUATION = 2; protected: - void ProcessMatch(CommandsParserState* state, SequenceResult<CommandsParserValue>& result) const override; + void ProcessMatch(CommandsParserState *state, SequenceResult<CommandsParserValue> &result) const override; public: - SequenceCondition(); + SequenceCondition(); }; diff --git a/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceCount.cpp b/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceCount.cpp index 5844fdd1c..41bc5f370 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceCount.cpp +++ b/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceCount.cpp @@ -2,127 +2,103 @@ #include "Domain/Definition/ArrayDeclarationModifier.h" #include "Domain/Definition/PointerDeclarationModifier.h" -#include "Parsing/Commands/Matcher/CommandsMatcherFactory.h" #include "Parsing/Commands/Matcher/CommandsCommonMatchers.h" +#include "Parsing/Commands/Matcher/CommandsMatcherFactory.h" -SequenceCount::SequenceCount() -{ - const CommandsMatcherFactory create(this); - - AddLabeledMatchers(CommandsCommonMatchers::Typename(this), CommandsCommonMatchers::LABEL_TYPENAME); - AddLabeledMatchers(CommandsCommonMatchers::Evaluation(this), CommandsCommonMatchers::LABEL_EVALUATION); - AddLabeledMatchers(CommandsCommonMatchers::ArrayDef(this), CommandsCommonMatchers::LABEL_ARRAY_DEF); - AddMatchers({ - create.Keyword("set").Capture(CAPTURE_START), - create.Keyword("count"), - create.OptionalLoop(create.Char('*').Tag(TAG_POINTER_RESOLVE)), - create.Label(CommandsCommonMatchers::LABEL_TYPENAME).Capture(CAPTURE_TYPE), - create.OptionalLoop(create.Label(CommandsCommonMatchers::LABEL_ARRAY_DEF).Capture(CAPTURE_ARRAY_INDEX)), - create.Label(CommandsCommonMatchers::LABEL_EVALUATION), - create.Char(';') - }); -} +SequenceCount::SequenceCount() { + const CommandsMatcherFactory create(this); -void SequenceCount::SetCountByArrayIndex(CommandsParserState* state, SequenceResult<CommandsParserValue>& result, MemberInformation* member, PointerDeclarationModifier* pointer, - std::unique_ptr<IEvaluation> evaluation) -{ - std::vector<int> arraySizes; - std::vector<int> depthSize; - for (const auto& modifier : member->m_member->m_type_declaration->m_declaration_modifiers) - { - if (modifier->GetType() == DeclarationModifierType::ARRAY) - arraySizes.push_back(dynamic_cast<ArrayDeclarationModifier*>(modifier.get())->m_size); - } - - depthSize.resize(arraySizes.size()); - auto currentDepthSize = 1u; - for (auto i = arraySizes.size(); i > 0; i--) - { - if(i < arraySizes.size()) - currentDepthSize *= arraySizes[i]; - depthSize[i - 1] = currentDepthSize; - } + AddLabeledMatchers(CommandsCommonMatchers::Typename(this), CommandsCommonMatchers::LABEL_TYPENAME); + AddLabeledMatchers(CommandsCommonMatchers::Evaluation(this), CommandsCommonMatchers::LABEL_EVALUATION); + AddLabeledMatchers(CommandsCommonMatchers::ArrayDef(this), CommandsCommonMatchers::LABEL_ARRAY_DEF); + AddMatchers({create.Keyword("set").Capture(CAPTURE_START), create.Keyword("count"), create.OptionalLoop(create.Char('*').Tag(TAG_POINTER_RESOLVE)), + create.Label(CommandsCommonMatchers::LABEL_TYPENAME).Capture(CAPTURE_TYPE), + create.OptionalLoop(create.Label(CommandsCommonMatchers::LABEL_ARRAY_DEF).Capture(CAPTURE_ARRAY_INDEX)), + create.Label(CommandsCommonMatchers::LABEL_EVALUATION), create.Char(';')}); +} - if (pointer->m_count_evaluation_by_array_index.empty()) - { - auto neededCapacity = 0u; - for (auto arraySize : arraySizes) - { - if (neededCapacity == 0) - neededCapacity = arraySize; - else - neededCapacity *= arraySize; - } - pointer->m_count_evaluation_by_array_index.resize(neededCapacity); +void SequenceCount::SetCountByArrayIndex(CommandsParserState *state, SequenceResult<CommandsParserValue> &result, MemberInformation *member, + PointerDeclarationModifier *pointer, std::unique_ptr<IEvaluation> evaluation) { + std::vector<int> arraySizes; + std::vector<int> depthSize; + for (const auto &modifier : member->m_member->m_type_declaration->m_declaration_modifiers) { + if (modifier->GetType() == DeclarationModifierType::ARRAY) + arraySizes.push_back(dynamic_cast<ArrayDeclarationModifier *>(modifier.get())->m_size); + } + + depthSize.resize(arraySizes.size()); + auto currentDepthSize = 1u; + for (auto i = arraySizes.size(); i > 0; i--) { + if (i < arraySizes.size()) + currentDepthSize *= arraySizes[i]; + depthSize[i - 1] = currentDepthSize; + } + + if (pointer->m_count_evaluation_by_array_index.empty()) { + auto neededCapacity = 0u; + for (auto arraySize : arraySizes) { + if (neededCapacity == 0) + neededCapacity = arraySize; + else + neededCapacity *= arraySize; } - - auto currentIndex = 0u; - auto currentIndexOffset = 0u; - while (result.HasNextCapture(CAPTURE_ARRAY_INDEX) && currentIndexOffset < depthSize.size()) - { - const auto& arrayIndexToken = result.NextCapture(CAPTURE_ARRAY_INDEX); - if (arrayIndexToken.m_type == CommandsParserValueType::INTEGER) - { - currentIndex += depthSize[currentIndexOffset++] * arrayIndexToken.IntegerValue(); - } - else - { - auto* enumEntry = state->GetRepository()->GetEnumMemberByName(arrayIndexToken.IdentifierValue()); - if (enumEntry == nullptr) - throw ParsingException(arrayIndexToken.GetPos(), "Unknown enum entry"); - - currentIndex += depthSize[currentIndexOffset++] * enumEntry->m_value; - } + pointer->m_count_evaluation_by_array_index.resize(neededCapacity); + } + + auto currentIndex = 0u; + auto currentIndexOffset = 0u; + while (result.HasNextCapture(CAPTURE_ARRAY_INDEX) && currentIndexOffset < depthSize.size()) { + const auto &arrayIndexToken = result.NextCapture(CAPTURE_ARRAY_INDEX); + if (arrayIndexToken.m_type == CommandsParserValueType::INTEGER) { + currentIndex += depthSize[currentIndexOffset++] * arrayIndexToken.IntegerValue(); + } else { + auto *enumEntry = state->GetRepository()->GetEnumMemberByName(arrayIndexToken.IdentifierValue()); + if (enumEntry == nullptr) + throw ParsingException(arrayIndexToken.GetPos(), "Unknown enum entry"); + + currentIndex += depthSize[currentIndexOffset++] * enumEntry->m_value; } + } - pointer->m_count_evaluation_by_array_index[currentIndex] = std::move(evaluation); + pointer->m_count_evaluation_by_array_index[currentIndex] = std::move(evaluation); } -void SequenceCount::ProcessMatch(CommandsParserState* state, SequenceResult<CommandsParserValue>& result) const -{ - const auto& typeNameToken = result.NextCapture(CAPTURE_TYPE); - - StructureInformation* type; - std::vector<MemberInformation*> memberChain; - if (!state->GetTypenameAndMembersFromTypename(typeNameToken.TypeNameValue(), type, memberChain)) - throw ParsingException(typeNameToken.GetPos(), "Unknown type"); - - if (memberChain.empty()) - throw ParsingException(typeNameToken.GetPos(), "Conditions can only be set on members and not for types"); - - auto resolve = 0u; - while (result.PeekAndRemoveIfTag(TAG_POINTER_RESOLVE) == TAG_POINTER_RESOLVE) - resolve++; - - auto* lastMember = memberChain.back(); - PointerDeclarationModifier* pointer = nullptr; - for (const auto& modifier : lastMember->m_member->m_type_declaration->m_declaration_modifiers) - { - if (modifier->GetType() == DeclarationModifierType::POINTER) - { - if (resolve > 0) - { - resolve--; - } - else - { - pointer = dynamic_cast<PointerDeclarationModifier*>(modifier.get()); - break; - } - } +void SequenceCount::ProcessMatch(CommandsParserState *state, SequenceResult<CommandsParserValue> &result) const { + const auto &typeNameToken = result.NextCapture(CAPTURE_TYPE); + + StructureInformation *type; + std::vector<MemberInformation *> memberChain; + if (!state->GetTypenameAndMembersFromTypename(typeNameToken.TypeNameValue(), type, memberChain)) + throw ParsingException(typeNameToken.GetPos(), "Unknown type"); + + if (memberChain.empty()) + throw ParsingException(typeNameToken.GetPos(), "Conditions can only be set on members and not for types"); + + auto resolve = 0u; + while (result.PeekAndRemoveIfTag(TAG_POINTER_RESOLVE) == TAG_POINTER_RESOLVE) + resolve++; + + auto *lastMember = memberChain.back(); + PointerDeclarationModifier *pointer = nullptr; + for (const auto &modifier : lastMember->m_member->m_type_declaration->m_declaration_modifiers) { + if (modifier->GetType() == DeclarationModifierType::POINTER) { + if (resolve > 0) { + resolve--; + } else { + pointer = dynamic_cast<PointerDeclarationModifier *>(modifier.get()); + break; + } } + } - if (pointer == nullptr) - throw ParsingException(result.NextCapture(CAPTURE_START).GetPos(), "No matching pointer modifier found"); + if (pointer == nullptr) + throw ParsingException(result.NextCapture(CAPTURE_START).GetPos(), "No matching pointer modifier found"); - auto countEvaluation = CommandsCommonMatchers::ProcessEvaluation(state, result, type); + auto countEvaluation = CommandsCommonMatchers::ProcessEvaluation(state, result, type); - if (!result.HasNextCapture(CAPTURE_ARRAY_INDEX)) - { - pointer->m_count_evaluation = std::move(countEvaluation); - } - else - { - SetCountByArrayIndex(state, result, lastMember, pointer, std::move(countEvaluation)); - } + if (!result.HasNextCapture(CAPTURE_ARRAY_INDEX)) { + pointer->m_count_evaluation = std::move(countEvaluation); + } else { + SetCountByArrayIndex(state, result, lastMember, pointer, std::move(countEvaluation)); + } } diff --git a/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceCount.h b/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceCount.h index dafa49814..ef7b716bf 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceCount.h +++ b/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceCount.h @@ -3,20 +3,19 @@ #include "Domain/Definition/PointerDeclarationModifier.h" #include "Parsing/Commands/Impl/CommandsParser.h" -class SequenceCount final : public CommandsParser::sequence_t -{ - static constexpr auto TAG_POINTER_RESOLVE = 1; +class SequenceCount final : public CommandsParser::sequence_t { + static constexpr auto TAG_POINTER_RESOLVE = 1; - static constexpr auto CAPTURE_START = 1; - static constexpr auto CAPTURE_TYPE = 2; - static constexpr auto CAPTURE_ARRAY_INDEX = 3; + static constexpr auto CAPTURE_START = 1; + static constexpr auto CAPTURE_TYPE = 2; + static constexpr auto CAPTURE_ARRAY_INDEX = 3; - static void SetCountByArrayIndex(CommandsParserState* state, SequenceResult<CommandsParserValue>& result, MemberInformation* member, PointerDeclarationModifier* pointer, - std::unique_ptr<IEvaluation> evaluation); + static void SetCountByArrayIndex(CommandsParserState *state, SequenceResult<CommandsParserValue> &result, MemberInformation *member, + PointerDeclarationModifier *pointer, std::unique_ptr<IEvaluation> evaluation); protected: - void ProcessMatch(CommandsParserState* state, SequenceResult<CommandsParserValue>& result) const override; + void ProcessMatch(CommandsParserState *state, SequenceResult<CommandsParserValue> &result) const override; public: - SequenceCount(); + SequenceCount(); }; diff --git a/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceGame.cpp b/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceGame.cpp index 0b904b691..b9df0b57b 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceGame.cpp +++ b/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceGame.cpp @@ -1,20 +1,14 @@ #include "SequenceGame.h" -#include "Parsing/Commands/Matcher/CommandsMatcherFactory.h" #include "Parsing/Commands/Matcher/CommandsCommonMatchers.h" +#include "Parsing/Commands/Matcher/CommandsMatcherFactory.h" -SequenceGame::SequenceGame() -{ - const CommandsMatcherFactory create(this); +SequenceGame::SequenceGame() { + const CommandsMatcherFactory create(this); - AddMatchers({ - create.Keyword("game"), - create.Identifier().Capture(CAPTURE_GAME), - create.Char(';') - }); + AddMatchers({create.Keyword("game"), create.Identifier().Capture(CAPTURE_GAME), create.Char(';')}); } -void SequenceGame::ProcessMatch(CommandsParserState* state, SequenceResult<CommandsParserValue>& result) const -{ - state->SetGame(result.NextCapture(CAPTURE_GAME).IdentifierValue()); +void SequenceGame::ProcessMatch(CommandsParserState *state, SequenceResult<CommandsParserValue> &result) const { + state->SetGame(result.NextCapture(CAPTURE_GAME).IdentifierValue()); } diff --git a/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceGame.h b/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceGame.h index 2de63c081..1bc5f0816 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceGame.h +++ b/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceGame.h @@ -2,13 +2,12 @@ #include "Parsing/Commands/Impl/CommandsParser.h" -class SequenceGame final : public CommandsParser::sequence_t -{ - static constexpr auto CAPTURE_GAME = 1; +class SequenceGame final : public CommandsParser::sequence_t { + static constexpr auto CAPTURE_GAME = 1; protected: - void ProcessMatch(CommandsParserState* state, SequenceResult<CommandsParserValue>& result) const override; + void ProcessMatch(CommandsParserState *state, SequenceResult<CommandsParserValue> &result) const override; public: - SequenceGame(); + SequenceGame(); }; diff --git a/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceName.cpp b/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceName.cpp index 58e695405..85d22e3a0 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceName.cpp +++ b/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceName.cpp @@ -1,32 +1,25 @@ #include "SequenceName.h" -#include "Parsing/Commands/Matcher/CommandsMatcherFactory.h" #include "Parsing/Commands/Matcher/CommandsCommonMatchers.h" +#include "Parsing/Commands/Matcher/CommandsMatcherFactory.h" -SequenceName::SequenceName() -{ - const CommandsMatcherFactory create(this); +SequenceName::SequenceName() { + const CommandsMatcherFactory create(this); - AddLabeledMatchers(CommandsCommonMatchers::Typename(this), CommandsCommonMatchers::LABEL_TYPENAME); - AddMatchers({ - create.Keyword("set"), - create.Keyword("name"), - create.Label(CommandsCommonMatchers::LABEL_TYPENAME).Capture(CAPTURE_TYPE), - create.Char(';') - }); + AddLabeledMatchers(CommandsCommonMatchers::Typename(this), CommandsCommonMatchers::LABEL_TYPENAME); + AddMatchers({create.Keyword("set"), create.Keyword("name"), create.Label(CommandsCommonMatchers::LABEL_TYPENAME).Capture(CAPTURE_TYPE), create.Char(';')}); } -void SequenceName::ProcessMatch(CommandsParserState* state, SequenceResult<CommandsParserValue>& result) const -{ - const auto& typeNameToken = result.NextCapture(CAPTURE_TYPE); +void SequenceName::ProcessMatch(CommandsParserState *state, SequenceResult<CommandsParserValue> &result) const { + const auto &typeNameToken = result.NextCapture(CAPTURE_TYPE); - StructureInformation* type; - std::vector<MemberInformation*> members; - if (!state->GetTypenameAndMembersFromTypename(typeNameToken.TypeNameValue(), type, members)) - throw ParsingException(typeNameToken.GetPos(), "Unknown type"); + StructureInformation *type; + std::vector<MemberInformation *> members; + if (!state->GetTypenameAndMembersFromTypename(typeNameToken.TypeNameValue(), type, members)) + throw ParsingException(typeNameToken.GetPos(), "Unknown type"); - if (members.empty()) - throw ParsingException(typeNameToken.GetPos(), "Need to specify a member when trying to set to a structure name."); + if (members.empty()) + throw ParsingException(typeNameToken.GetPos(), "Need to specify a member when trying to set to a structure name."); - type->m_name_chain = std::move(members); + type->m_name_chain = std::move(members); } diff --git a/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceName.h b/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceName.h index 56b5da844..5fa49f8c1 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceName.h +++ b/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceName.h @@ -2,13 +2,12 @@ #include "Parsing/Commands/Impl/CommandsParser.h" -class SequenceName final : public CommandsParser::sequence_t -{ - static constexpr auto CAPTURE_TYPE = 1; +class SequenceName final : public CommandsParser::sequence_t { + static constexpr auto CAPTURE_TYPE = 1; protected: - void ProcessMatch(CommandsParserState* state, SequenceResult<CommandsParserValue>& result) const override; + void ProcessMatch(CommandsParserState *state, SequenceResult<CommandsParserValue> &result) const override; public: - SequenceName(); + SequenceName(); }; diff --git a/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceReorder.cpp b/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceReorder.cpp index b93e63e39..4050b8141 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceReorder.cpp +++ b/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceReorder.cpp @@ -2,106 +2,89 @@ #include <list> -#include "Parsing/Commands/Matcher/CommandsMatcherFactory.h" #include "Parsing/Commands/Matcher/CommandsCommonMatchers.h" +#include "Parsing/Commands/Matcher/CommandsMatcherFactory.h" + +SequenceReorder::SequenceReorder() { + const CommandsMatcherFactory create(this); -SequenceReorder::SequenceReorder() -{ - const CommandsMatcherFactory create(this); - - AddLabeledMatchers(CommandsCommonMatchers::Typename(this), CommandsCommonMatchers::LABEL_TYPENAME); - AddMatchers({ - create.Keyword("reorder").Capture(CAPTURE_START), - create.Optional(create.Label(CommandsCommonMatchers::LABEL_TYPENAME).Capture(CAPTURE_TYPE)), - create.Char(':'), - create.Optional(create.And({ - create.Char('.'), - create.Char('.'), - create.Char('.') - }).Tag(TAG_FIND_FIRST)), - create.Loop(create.Identifier().Capture(CAPTURE_ENTRY)), - create.Char(';') - }); + AddLabeledMatchers(CommandsCommonMatchers::Typename(this), CommandsCommonMatchers::LABEL_TYPENAME); + AddMatchers({create.Keyword("reorder").Capture(CAPTURE_START), create.Optional(create.Label(CommandsCommonMatchers::LABEL_TYPENAME).Capture(CAPTURE_TYPE)), + create.Char(':'), create.Optional(create.And({create.Char('.'), create.Char('.'), create.Char('.')}).Tag(TAG_FIND_FIRST)), + create.Loop(create.Identifier().Capture(CAPTURE_ENTRY)), create.Char(';')}); } -StructureInformation* SequenceReorder::GetType(CommandsParserState* state, SequenceResult<CommandsParserValue>& result) -{ - if (result.HasNextCapture(CAPTURE_TYPE)) - { - const auto& typeNameToken = result.NextCapture(CAPTURE_TYPE); - StructureInformation* information; - std::vector<MemberInformation*> memberChain; +StructureInformation *SequenceReorder::GetType(CommandsParserState *state, SequenceResult<CommandsParserValue> &result) { + if (result.HasNextCapture(CAPTURE_TYPE)) { + const auto &typeNameToken = result.NextCapture(CAPTURE_TYPE); + StructureInformation *information; + std::vector<MemberInformation *> memberChain; - if (!state->GetTypenameAndMembersFromTypename(typeNameToken.TypeNameValue(), information, memberChain)) - throw ParsingException(typeNameToken.GetPos(), "Unknown type"); + if (!state->GetTypenameAndMembersFromTypename(typeNameToken.TypeNameValue(), information, memberChain)) + throw ParsingException(typeNameToken.GetPos(), "Unknown type"); - if (memberChain.empty()) - return information; + if (memberChain.empty()) + return information; - auto* lastMember = memberChain.back(); + auto *lastMember = memberChain.back(); - if (lastMember->m_type == nullptr) - throw ParsingException(typeNameToken.GetPos(), "Member type must either be struct or union"); + if (lastMember->m_type == nullptr) + throw ParsingException(typeNameToken.GetPos(), "Member type must either be struct or union"); - return lastMember->m_type; - } + return lastMember->m_type; + } - if (state->GetInUse() != nullptr) - return state->GetInUse(); + if (state->GetInUse() != nullptr) + return state->GetInUse(); - throw ParsingException(result.NextCapture(CAPTURE_START).GetPos(), "No type is used. Therefore one needs to be specified directly."); + throw ParsingException(result.NextCapture(CAPTURE_START).GetPos(), "No type is used. Therefore one needs to be specified directly."); } -void SequenceReorder::ProcessMatch(CommandsParserState* state, SequenceResult<CommandsParserValue>& result) const -{ - auto* information = GetType(state, result); - auto findFirst = result.PeekAndRemoveIfTag(TAG_FIND_FIRST) == TAG_FIND_FIRST; - - std::string firstVariableName; - if(findFirst) - firstVariableName = result.NextCapture(CAPTURE_ENTRY).IdentifierValue(); - - std::vector<std::unique_ptr<MemberInformation>> newMembers; - std::list<std::unique_ptr<MemberInformation>> oldMembers; - - for (auto& oldMember : information->m_ordered_members) - oldMembers.emplace_back(std::move(oldMember)); - - while(result.HasNextCapture(CAPTURE_ENTRY)) - { - const auto& entryToken = result.NextCapture(CAPTURE_ENTRY); - const auto& nextVariableName = entryToken.IdentifierValue(); - auto foundEntry = false; - - for(auto i = oldMembers.begin(); i != oldMembers.end(); ++i) - { - if(i->get()->m_member->m_name == nextVariableName) - { - newMembers.emplace_back(std::move(*i)); - oldMembers.erase(i); - foundEntry = true; - break; - } - } - - if (!foundEntry) - throw ParsingException(entryToken.GetPos(), "Could not find member with specified name"); - } +void SequenceReorder::ProcessMatch(CommandsParserState *state, SequenceResult<CommandsParserValue> &result) const { + auto *information = GetType(state, result); + auto findFirst = result.PeekAndRemoveIfTag(TAG_FIND_FIRST) == TAG_FIND_FIRST; + + std::string firstVariableName; + if (findFirst) + firstVariableName = result.NextCapture(CAPTURE_ENTRY).IdentifierValue(); - information->m_ordered_members.clear(); + std::vector<std::unique_ptr<MemberInformation>> newMembers; + std::list<std::unique_ptr<MemberInformation>> oldMembers; - while(findFirst && !oldMembers.empty()) - { - if (oldMembers.front()->m_member->m_name == firstVariableName) - findFirst = false; + for (auto &oldMember : information->m_ordered_members) + oldMembers.emplace_back(std::move(oldMember)); - information->m_ordered_members.push_back(std::move(oldMembers.front())); - oldMembers.pop_front(); + while (result.HasNextCapture(CAPTURE_ENTRY)) { + const auto &entryToken = result.NextCapture(CAPTURE_ENTRY); + const auto &nextVariableName = entryToken.IdentifierValue(); + auto foundEntry = false; + + for (auto i = oldMembers.begin(); i != oldMembers.end(); ++i) { + if (i->get()->m_member->m_name == nextVariableName) { + newMembers.emplace_back(std::move(*i)); + oldMembers.erase(i); + foundEntry = true; + break; + } } - for (auto& newMember : newMembers) - information->m_ordered_members.push_back(std::move(newMember)); + if (!foundEntry) + throw ParsingException(entryToken.GetPos(), "Could not find member with specified name"); + } + + information->m_ordered_members.clear(); + + while (findFirst && !oldMembers.empty()) { + if (oldMembers.front()->m_member->m_name == firstVariableName) + findFirst = false; + + information->m_ordered_members.push_back(std::move(oldMembers.front())); + oldMembers.pop_front(); + } + + for (auto &newMember : newMembers) + information->m_ordered_members.push_back(std::move(newMember)); - for (auto& oldMember : oldMembers) - information->m_ordered_members.emplace_back(std::move(oldMember)); + for (auto &oldMember : oldMembers) + information->m_ordered_members.emplace_back(std::move(oldMember)); } diff --git a/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceReorder.h b/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceReorder.h index c26fd14f3..ca751ebfd 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceReorder.h +++ b/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceReorder.h @@ -2,19 +2,18 @@ #include "Parsing/Commands/Impl/CommandsParser.h" -class SequenceReorder final : public CommandsParser::sequence_t -{ - static constexpr auto TAG_FIND_FIRST = 1; +class SequenceReorder final : public CommandsParser::sequence_t { + static constexpr auto TAG_FIND_FIRST = 1; - static constexpr auto CAPTURE_START = 1; - static constexpr auto CAPTURE_TYPE = 2; - static constexpr auto CAPTURE_ENTRY = 3; + static constexpr auto CAPTURE_START = 1; + static constexpr auto CAPTURE_TYPE = 2; + static constexpr auto CAPTURE_ENTRY = 3; - static StructureInformation* GetType(CommandsParserState* state, SequenceResult<CommandsParserValue>& result); + static StructureInformation *GetType(CommandsParserState *state, SequenceResult<CommandsParserValue> &result); protected: - void ProcessMatch(CommandsParserState* state, SequenceResult<CommandsParserValue>& result) const override; + void ProcessMatch(CommandsParserState *state, SequenceResult<CommandsParserValue> &result) const override; public: - SequenceReorder(); + SequenceReorder(); }; diff --git a/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceReusable.cpp b/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceReusable.cpp index 89ab259c2..9ad441b35 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceReusable.cpp +++ b/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceReusable.cpp @@ -1,32 +1,26 @@ #include "SequenceReusable.h" -#include "Parsing/Commands/Matcher/CommandsMatcherFactory.h" #include "Parsing/Commands/Matcher/CommandsCommonMatchers.h" +#include "Parsing/Commands/Matcher/CommandsMatcherFactory.h" -SequenceReusable::SequenceReusable() -{ - const CommandsMatcherFactory create(this); +SequenceReusable::SequenceReusable() { + const CommandsMatcherFactory create(this); - AddLabeledMatchers(CommandsCommonMatchers::Typename(this), CommandsCommonMatchers::LABEL_TYPENAME); - AddMatchers({ - create.Keyword("set"), - create.Keyword("reusable"), - create.Label(CommandsCommonMatchers::LABEL_TYPENAME).Capture(CAPTURE_TYPE), - create.Char(';') - }); + AddLabeledMatchers(CommandsCommonMatchers::Typename(this), CommandsCommonMatchers::LABEL_TYPENAME); + AddMatchers( + {create.Keyword("set"), create.Keyword("reusable"), create.Label(CommandsCommonMatchers::LABEL_TYPENAME).Capture(CAPTURE_TYPE), create.Char(';')}); } -void SequenceReusable::ProcessMatch(CommandsParserState* state, SequenceResult<CommandsParserValue>& result) const -{ - const auto& typeNameToken = result.NextCapture(CAPTURE_TYPE); +void SequenceReusable::ProcessMatch(CommandsParserState *state, SequenceResult<CommandsParserValue> &result) const { + const auto &typeNameToken = result.NextCapture(CAPTURE_TYPE); - StructureInformation* type; - std::vector<MemberInformation*> members; - if (!state->GetTypenameAndMembersFromTypename(typeNameToken.TypeNameValue(), type, members)) - throw ParsingException(typeNameToken.GetPos(), "Unknown type"); + StructureInformation *type; + std::vector<MemberInformation *> members; + if (!state->GetTypenameAndMembersFromTypename(typeNameToken.TypeNameValue(), type, members)) + throw ParsingException(typeNameToken.GetPos(), "Unknown type"); - if (members.empty()) - throw ParsingException(typeNameToken.GetPos(), "Need to specify a member when trying to mark as reusable."); + if (members.empty()) + throw ParsingException(typeNameToken.GetPos(), "Need to specify a member when trying to mark as reusable."); - members.back()->m_is_reusable = true; + members.back()->m_is_reusable = true; } diff --git a/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceReusable.h b/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceReusable.h index 90aaa9955..fb22fe7ba 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceReusable.h +++ b/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceReusable.h @@ -2,13 +2,12 @@ #include "Parsing/Commands/Impl/CommandsParser.h" -class SequenceReusable final : public CommandsParser::sequence_t -{ - static constexpr auto CAPTURE_TYPE = 1; +class SequenceReusable final : public CommandsParser::sequence_t { + static constexpr auto CAPTURE_TYPE = 1; protected: - void ProcessMatch(CommandsParserState* state, SequenceResult<CommandsParserValue>& result) const override; + void ProcessMatch(CommandsParserState *state, SequenceResult<CommandsParserValue> &result) const override; public: - SequenceReusable(); + SequenceReusable(); }; diff --git a/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceScriptString.cpp b/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceScriptString.cpp index fc813baaf..402ca26b4 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceScriptString.cpp +++ b/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceScriptString.cpp @@ -1,40 +1,34 @@ #include "SequenceScriptString.h" -#include "Parsing/Commands/Matcher/CommandsMatcherFactory.h" #include "Parsing/Commands/Matcher/CommandsCommonMatchers.h" +#include "Parsing/Commands/Matcher/CommandsMatcherFactory.h" + +SequenceScriptString::SequenceScriptString() { + const CommandsMatcherFactory create(this); -SequenceScriptString::SequenceScriptString() -{ - const CommandsMatcherFactory create(this); - - AddLabeledMatchers(CommandsCommonMatchers::Typename(this), CommandsCommonMatchers::LABEL_TYPENAME); - AddMatchers({ - create.Keyword("set"), - create.Keyword("scriptstring"), - create.Label(CommandsCommonMatchers::LABEL_TYPENAME).Capture(CAPTURE_TYPE), - create.Char(';') - }); + AddLabeledMatchers(CommandsCommonMatchers::Typename(this), CommandsCommonMatchers::LABEL_TYPENAME); + AddMatchers( + {create.Keyword("set"), create.Keyword("scriptstring"), create.Label(CommandsCommonMatchers::LABEL_TYPENAME).Capture(CAPTURE_TYPE), create.Char(';')}); } -void SequenceScriptString::ProcessMatch(CommandsParserState* state, SequenceResult<CommandsParserValue>& result) const -{ - const auto& typeNameToken = result.NextCapture(CAPTURE_TYPE); +void SequenceScriptString::ProcessMatch(CommandsParserState *state, SequenceResult<CommandsParserValue> &result) const { + const auto &typeNameToken = result.NextCapture(CAPTURE_TYPE); - StructureInformation* type; - std::vector<MemberInformation*> members; - if (!state->GetTypenameAndMembersFromTypename(typeNameToken.TypeNameValue(), type, members)) - throw ParsingException(typeNameToken.GetPos(), "Unknown type"); + StructureInformation *type; + std::vector<MemberInformation *> members; + if (!state->GetTypenameAndMembersFromTypename(typeNameToken.TypeNameValue(), type, members)) + throw ParsingException(typeNameToken.GetPos(), "Unknown type"); - if (members.empty()) - throw ParsingException(typeNameToken.GetPos(), "Need to specify a member when trying to mark as script string."); + if (members.empty()) + throw ParsingException(typeNameToken.GetPos(), "Need to specify a member when trying to mark as script string."); - auto* lastMember = members.back(); - const auto* dataDef = lastMember->m_member->m_type_declaration->m_type; - while (dataDef->GetType() == DataDefinitionType::TYPEDEF) - dataDef = dynamic_cast<const TypedefDefinition*>(dataDef)->m_type_declaration->m_type; + auto *lastMember = members.back(); + const auto *dataDef = lastMember->m_member->m_type_declaration->m_type; + while (dataDef->GetType() == DataDefinitionType::TYPEDEF) + dataDef = dynamic_cast<const TypedefDefinition *>(dataDef)->m_type_declaration->m_type; - if (dataDef->GetType() != DataDefinitionType::BASE_TYPE) - throw ParsingException(typeNameToken.GetPos(), "Invalid type for script string, must be a base type"); + if (dataDef->GetType() != DataDefinitionType::BASE_TYPE) + throw ParsingException(typeNameToken.GetPos(), "Invalid type for script string, must be a base type"); - members.back()->m_is_script_string = true; + members.back()->m_is_script_string = true; } diff --git a/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceScriptString.h b/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceScriptString.h index d6b903065..fefa3ad04 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceScriptString.h +++ b/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceScriptString.h @@ -2,13 +2,12 @@ #include "Parsing/Commands/Impl/CommandsParser.h" -class SequenceScriptString final : public CommandsParser::sequence_t -{ - static constexpr auto CAPTURE_TYPE = 1; +class SequenceScriptString final : public CommandsParser::sequence_t { + static constexpr auto CAPTURE_TYPE = 1; protected: - void ProcessMatch(CommandsParserState* state, SequenceResult<CommandsParserValue>& result) const override; + void ProcessMatch(CommandsParserState *state, SequenceResult<CommandsParserValue> &result) const override; public: - SequenceScriptString(); + SequenceScriptString(); }; diff --git a/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceSetBlock.cpp b/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceSetBlock.cpp index d24c2aa5f..978893fb4 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceSetBlock.cpp +++ b/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceSetBlock.cpp @@ -1,52 +1,39 @@ #include "SequenceSetBlock.h" -#include "Parsing/Commands/Matcher/CommandsMatcherFactory.h" #include "Parsing/Commands/Matcher/CommandsCommonMatchers.h" +#include "Parsing/Commands/Matcher/CommandsMatcherFactory.h" -SequenceSetBlock::SequenceSetBlock() -{ - const CommandsMatcherFactory create(this); +SequenceSetBlock::SequenceSetBlock() { + const CommandsMatcherFactory create(this); - AddLabeledMatchers(CommandsCommonMatchers::Typename(this), CommandsCommonMatchers::LABEL_TYPENAME); - AddMatchers({ - create.Keyword("set").Capture(CAPTURE_START), - create.Keyword("block"), - create.Or({ - create.And({ - create.Label(CommandsCommonMatchers::LABEL_TYPENAME).Capture(CAPTURE_TYPE), - create.Identifier().Capture(CAPTURE_BLOCK_ENUM_ENTRY) - }), - create.Identifier().Capture(CAPTURE_BLOCK_ENUM_ENTRY) - }), - create.Char(';') - }); + AddLabeledMatchers(CommandsCommonMatchers::Typename(this), CommandsCommonMatchers::LABEL_TYPENAME); + AddMatchers({create.Keyword("set").Capture(CAPTURE_START), create.Keyword("block"), + create.Or({create.And({create.Label(CommandsCommonMatchers::LABEL_TYPENAME).Capture(CAPTURE_TYPE), + create.Identifier().Capture(CAPTURE_BLOCK_ENUM_ENTRY)}), + create.Identifier().Capture(CAPTURE_BLOCK_ENUM_ENTRY)}), + create.Char(';')}); } -void SequenceSetBlock::ProcessMatch(CommandsParserState* state, SequenceResult<CommandsParserValue>& result) const -{ - StructureInformation* information; - std::vector<MemberInformation*> memberChain; +void SequenceSetBlock::ProcessMatch(CommandsParserState *state, SequenceResult<CommandsParserValue> &result) const { + StructureInformation *information; + std::vector<MemberInformation *> memberChain; - if (result.HasNextCapture(CAPTURE_TYPE)) - { - const auto& typeNameToken = result.NextCapture(CAPTURE_TYPE); - if (!state->GetTypenameAndMembersFromTypename(typeNameToken.TypeNameValue(), information, memberChain)) - throw ParsingException(typeNameToken.GetPos(), "Unknown type"); - } - else if (state->GetInUse() != nullptr) - { - information = state->GetInUse(); - } - else - throw ParsingException(result.NextCapture(CAPTURE_START).GetPos(), "No type is used. Therefore one needs to be specified directly."); + if (result.HasNextCapture(CAPTURE_TYPE)) { + const auto &typeNameToken = result.NextCapture(CAPTURE_TYPE); + if (!state->GetTypenameAndMembersFromTypename(typeNameToken.TypeNameValue(), information, memberChain)) + throw ParsingException(typeNameToken.GetPos(), "Unknown type"); + } else if (state->GetInUse() != nullptr) { + information = state->GetInUse(); + } else + throw ParsingException(result.NextCapture(CAPTURE_START).GetPos(), "No type is used. Therefore one needs to be specified directly."); - const auto& blockNameToken = result.NextCapture(CAPTURE_BLOCK_ENUM_ENTRY); - auto* fastFileBlock = state->GetRepository()->GetFastFileBlockByName(blockNameToken.IdentifierValue()); - if (fastFileBlock == nullptr) - throw ParsingException(blockNameToken.GetPos(), "Unknown block"); + const auto &blockNameToken = result.NextCapture(CAPTURE_BLOCK_ENUM_ENTRY); + auto *fastFileBlock = state->GetRepository()->GetFastFileBlockByName(blockNameToken.IdentifierValue()); + if (fastFileBlock == nullptr) + throw ParsingException(blockNameToken.GetPos(), "Unknown block"); - if (!memberChain.empty()) - memberChain.back()->m_fast_file_block = fastFileBlock; - else - information->m_block = fastFileBlock; + if (!memberChain.empty()) + memberChain.back()->m_fast_file_block = fastFileBlock; + else + information->m_block = fastFileBlock; } diff --git a/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceSetBlock.h b/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceSetBlock.h index ee06cc88e..e39aaed3b 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceSetBlock.h +++ b/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceSetBlock.h @@ -2,15 +2,14 @@ #include "Parsing/Commands/Impl/CommandsParser.h" -class SequenceSetBlock final : public CommandsParser::sequence_t -{ - static constexpr auto CAPTURE_START = 1; - static constexpr auto CAPTURE_TYPE = 2; - static constexpr auto CAPTURE_BLOCK_ENUM_ENTRY = 3; +class SequenceSetBlock final : public CommandsParser::sequence_t { + static constexpr auto CAPTURE_START = 1; + static constexpr auto CAPTURE_TYPE = 2; + static constexpr auto CAPTURE_BLOCK_ENUM_ENTRY = 3; protected: - void ProcessMatch(CommandsParserState* state, SequenceResult<CommandsParserValue>& result) const override; + void ProcessMatch(CommandsParserState *state, SequenceResult<CommandsParserValue> &result) const override; public: - SequenceSetBlock(); + SequenceSetBlock(); }; diff --git a/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceString.cpp b/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceString.cpp index dd8a3e580..267806067 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceString.cpp +++ b/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceString.cpp @@ -2,64 +2,50 @@ #include <algorithm> - -#include "Parsing/Commands/Matcher/CommandsMatcherFactory.h" #include "Parsing/Commands/Matcher/CommandsCommonMatchers.h" +#include "Parsing/Commands/Matcher/CommandsMatcherFactory.h" -SequenceString::SequenceString() -{ - const CommandsMatcherFactory create(this); +SequenceString::SequenceString() { + const CommandsMatcherFactory create(this); - AddLabeledMatchers(CommandsCommonMatchers::Typename(this), CommandsCommonMatchers::LABEL_TYPENAME); - AddMatchers({ - create.Keyword("set"), - create.Keyword("string"), - create.Label(CommandsCommonMatchers::LABEL_TYPENAME).Capture(CAPTURE_TYPE), - create.Char(';') - }); + AddLabeledMatchers(CommandsCommonMatchers::Typename(this), CommandsCommonMatchers::LABEL_TYPENAME); + AddMatchers({create.Keyword("set"), create.Keyword("string"), create.Label(CommandsCommonMatchers::LABEL_TYPENAME).Capture(CAPTURE_TYPE), create.Char(';')}); } -void SequenceString::ProcessMatch(CommandsParserState* state, SequenceResult<CommandsParserValue>& result) const -{ - const auto& typeNameToken = result.NextCapture(CAPTURE_TYPE); +void SequenceString::ProcessMatch(CommandsParserState *state, SequenceResult<CommandsParserValue> &result) const { + const auto &typeNameToken = result.NextCapture(CAPTURE_TYPE); - StructureInformation* type; - std::vector<MemberInformation*> members; - if (!state->GetTypenameAndMembersFromTypename(typeNameToken.TypeNameValue(), type, members)) - throw ParsingException(typeNameToken.GetPos(), "Unknown type"); + StructureInformation *type; + std::vector<MemberInformation *> members; + if (!state->GetTypenameAndMembersFromTypename(typeNameToken.TypeNameValue(), type, members)) + throw ParsingException(typeNameToken.GetPos(), "Unknown type"); - if (members.empty()) - throw ParsingException(typeNameToken.GetPos(), "Need to specify a member when trying to mark as string."); + if (members.empty()) + throw ParsingException(typeNameToken.GetPos(), "Need to specify a member when trying to mark as string."); - auto* lastMember = members.back(); - auto* typeDecl = lastMember->m_member->m_type_declaration.get(); - auto hasPointerRef = false; + auto *lastMember = members.back(); + auto *typeDecl = lastMember->m_member->m_type_declaration.get(); + auto hasPointerRef = false; - while (true) - { - if (!hasPointerRef) - { - const auto& modifiers = typeDecl->m_declaration_modifiers; - hasPointerRef = std::any_of(modifiers.begin(), modifiers.end(), [](const std::unique_ptr<DeclarationModifier>& modifier) - { - return modifier->GetType() == DeclarationModifierType::POINTER; - }); - } - - if (typeDecl->m_type->GetType() == DataDefinitionType::TYPEDEF) - { - const auto* typedefDef = dynamic_cast<const TypedefDefinition*>(typeDecl->m_type); - typeDecl = typedefDef->m_type_declaration.get(); - } - else - break; + while (true) { + if (!hasPointerRef) { + const auto &modifiers = typeDecl->m_declaration_modifiers; + hasPointerRef = std::any_of(modifiers.begin(), modifiers.end(), + [](const std::unique_ptr<DeclarationModifier> &modifier) { return modifier->GetType() == DeclarationModifierType::POINTER; }); } - if (!hasPointerRef) - throw ParsingException(typeNameToken.GetPos(), "Invalid type for string, must be a pointer"); + if (typeDecl->m_type->GetType() == DataDefinitionType::TYPEDEF) { + const auto *typedefDef = dynamic_cast<const TypedefDefinition *>(typeDecl->m_type); + typeDecl = typedefDef->m_type_declaration.get(); + } else + break; + } + + if (!hasPointerRef) + throw ParsingException(typeNameToken.GetPos(), "Invalid type for string, must be a pointer"); - if (typeDecl->m_type->GetType() != DataDefinitionType::BASE_TYPE) - throw ParsingException(typeNameToken.GetPos(), "Invalid type for string, must be a base type"); + if (typeDecl->m_type->GetType() != DataDefinitionType::BASE_TYPE) + throw ParsingException(typeNameToken.GetPos(), "Invalid type for string, must be a base type"); - lastMember->m_is_string = true; + lastMember->m_is_string = true; } diff --git a/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceString.h b/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceString.h index b902c3c6f..9485a452d 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceString.h +++ b/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceString.h @@ -2,13 +2,12 @@ #include "Parsing/Commands/Impl/CommandsParser.h" -class SequenceString final : public CommandsParser::sequence_t -{ - static constexpr auto CAPTURE_TYPE = 1; +class SequenceString final : public CommandsParser::sequence_t { + static constexpr auto CAPTURE_TYPE = 1; protected: - void ProcessMatch(CommandsParserState* state, SequenceResult<CommandsParserValue>& result) const override; + void ProcessMatch(CommandsParserState *state, SequenceResult<CommandsParserValue> &result) const override; public: - SequenceString(); + SequenceString(); }; diff --git a/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceUse.cpp b/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceUse.cpp index 5a82381df..5ea1fd357 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceUse.cpp +++ b/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceUse.cpp @@ -1,30 +1,24 @@ #include "SequenceUse.h" -#include "Parsing/Commands/Matcher/CommandsMatcherFactory.h" #include "Parsing/Commands/Matcher/CommandsCommonMatchers.h" +#include "Parsing/Commands/Matcher/CommandsMatcherFactory.h" -SequenceUse::SequenceUse() -{ - const CommandsMatcherFactory create(this); +SequenceUse::SequenceUse() { + const CommandsMatcherFactory create(this); - AddLabeledMatchers(CommandsCommonMatchers::Typename(this), CommandsCommonMatchers::LABEL_TYPENAME); - AddMatchers({ - create.Keyword("use"), - create.Label(CommandsCommonMatchers::LABEL_TYPENAME).Capture(CAPTURE_TYPE), - create.Char(';') - }); + AddLabeledMatchers(CommandsCommonMatchers::Typename(this), CommandsCommonMatchers::LABEL_TYPENAME); + AddMatchers({create.Keyword("use"), create.Label(CommandsCommonMatchers::LABEL_TYPENAME).Capture(CAPTURE_TYPE), create.Char(';')}); } -void SequenceUse::ProcessMatch(CommandsParserState* state, SequenceResult<CommandsParserValue>& result) const -{ - const auto& typeNameToken = result.NextCapture(CAPTURE_TYPE); - auto* definition = state->GetRepository()->GetDataDefinitionByName(typeNameToken.TypeNameValue()); - if (definition == nullptr) - throw ParsingException(typeNameToken.GetPos(), "Unknown type"); +void SequenceUse::ProcessMatch(CommandsParserState *state, SequenceResult<CommandsParserValue> &result) const { + const auto &typeNameToken = result.NextCapture(CAPTURE_TYPE); + auto *definition = state->GetRepository()->GetDataDefinitionByName(typeNameToken.TypeNameValue()); + if (definition == nullptr) + throw ParsingException(typeNameToken.GetPos(), "Unknown type"); - auto* definitionWithMembers = dynamic_cast<DefinitionWithMembers*>(definition); - if (definitionWithMembers == nullptr) - throw ParsingException(typeNameToken.GetPos(), "Type must be able to have members"); + auto *definitionWithMembers = dynamic_cast<DefinitionWithMembers *>(definition); + if (definitionWithMembers == nullptr) + throw ParsingException(typeNameToken.GetPos(), "Type must be able to have members"); - state->SetInUse(state->GetRepository()->GetInformationFor(definitionWithMembers)); + state->SetInUse(state->GetRepository()->GetInformationFor(definitionWithMembers)); } diff --git a/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceUse.h b/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceUse.h index 82aaae158..7966bedc3 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceUse.h +++ b/src/ZoneCodeGeneratorLib/Parsing/Commands/Sequence/SequenceUse.h @@ -2,13 +2,12 @@ #include "Parsing/Commands/Impl/CommandsParser.h" -class SequenceUse final : public CommandsParser::sequence_t -{ - static constexpr auto CAPTURE_TYPE = 1; +class SequenceUse final : public CommandsParser::sequence_t { + static constexpr auto CAPTURE_TYPE = 1; protected: - void ProcessMatch(CommandsParserState* state, SequenceResult<CommandsParserValue>& result) const override; + void ProcessMatch(CommandsParserState *state, SequenceResult<CommandsParserValue> &result) const override; public: - SequenceUse(); + SequenceUse(); }; diff --git a/src/ZoneCodeGeneratorLib/Parsing/Header/Block/HeaderBlockEnum.cpp b/src/ZoneCodeGeneratorLib/Parsing/Header/Block/HeaderBlockEnum.cpp index f213bcade..723aeb68b 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Header/Block/HeaderBlockEnum.cpp +++ b/src/ZoneCodeGeneratorLib/Parsing/Header/Block/HeaderBlockEnum.cpp @@ -3,96 +3,61 @@ #include "Parsing/Header/Sequence/SequenceCloseBlock.h" #include "Parsing/Header/Sequence/SequenceEnumMember.h" -HeaderBlockEnum::HeaderBlockEnum(std::string typeName, const BaseTypeDefinition* parentType, const bool isTypeDef) - : m_type_name(std::move(typeName)), - m_parent_type(parentType), - m_is_typedef(isTypeDef), - m_next_value(0), - m_enum_definition(nullptr) -{ -} +HeaderBlockEnum::HeaderBlockEnum(std::string typeName, const BaseTypeDefinition *parentType, const bool isTypeDef) + : m_type_name(std::move(typeName)), m_parent_type(parentType), m_is_typedef(isTypeDef), m_next_value(0), m_enum_definition(nullptr) {} -HeaderBlockType HeaderBlockEnum::GetType() -{ - return HeaderBlockType::ENUM; -} +HeaderBlockType HeaderBlockEnum::GetType() { return HeaderBlockType::ENUM; } -const std::vector<IHeaderBlock::sequence_t*>& HeaderBlockEnum::GetTestsForBlock() -{ - static std::vector<sequence_t*> tests({ - new SequenceCloseBlock(true), - new SequenceEnumMember() - }); +const std::vector<IHeaderBlock::sequence_t *> &HeaderBlockEnum::GetTestsForBlock() { + static std::vector<sequence_t *> tests({new SequenceCloseBlock(true), new SequenceEnumMember()}); - return tests; + return tests; } -void HeaderBlockEnum::OnOpen(HeaderParserState* state) -{ - m_namespace = state->m_namespace.ToString(); +void HeaderBlockEnum::OnOpen(HeaderParserState *state) { + m_namespace = state->m_namespace.ToString(); - if (!m_type_name.empty()) - state->m_namespace.Push(m_type_name); + if (!m_type_name.empty()) + state->m_namespace.Push(m_type_name); } -void HeaderBlockEnum::OnClose(HeaderParserState* state) -{ - if (!m_type_name.empty()) - state->m_namespace.Pop(); +void HeaderBlockEnum::OnClose(HeaderParserState *state) { + if (!m_type_name.empty()) + state->m_namespace.Pop(); - auto enumDefinition = std::make_unique<EnumDefinition>(m_namespace, m_type_name, m_parent_type); - m_enum_definition = enumDefinition.get(); - for (auto& member : m_members) - enumDefinition->m_members.emplace_back(std::move(member)); + auto enumDefinition = std::make_unique<EnumDefinition>(m_namespace, m_type_name, m_parent_type); + m_enum_definition = enumDefinition.get(); + for (auto &member : m_members) + enumDefinition->m_members.emplace_back(std::move(member)); - state->AddDataType(std::move(enumDefinition)); + state->AddDataType(std::move(enumDefinition)); - if (m_is_typedef) - state->AddDataType(std::make_unique<TypedefDefinition>(m_namespace, m_variable_name, std::make_unique<TypeDeclaration>(m_enum_definition))); + if (m_is_typedef) + state->AddDataType(std::make_unique<TypedefDefinition>(m_namespace, m_variable_name, std::make_unique<TypeDeclaration>(m_enum_definition))); } -void HeaderBlockEnum::OnChildBlockClose(HeaderParserState* state, IHeaderBlock* block) -{ -} +void HeaderBlockEnum::OnChildBlockClose(HeaderParserState *state, IHeaderBlock *block) {} -void HeaderBlockEnum::AddEnumMember(std::unique_ptr<EnumMember> enumMember) -{ - m_next_value = enumMember->m_value + 1; - m_members.emplace_back(std::move(enumMember)); +void HeaderBlockEnum::AddEnumMember(std::unique_ptr<EnumMember> enumMember) { + m_next_value = enumMember->m_value + 1; + m_members.emplace_back(std::move(enumMember)); } -EnumMember* HeaderBlockEnum::GetEnumMember(const std::string& name) const -{ - for (const auto& member : m_members) - { - if (member->m_name == name) - return member.get(); - } +EnumMember *HeaderBlockEnum::GetEnumMember(const std::string &name) const { + for (const auto &member : m_members) { + if (member->m_name == name) + return member.get(); + } - return nullptr; + return nullptr; } -int HeaderBlockEnum::GetNextEnumMemberValue() const -{ - return m_next_value; -} +int HeaderBlockEnum::GetNextEnumMemberValue() const { return m_next_value; } -void HeaderBlockEnum::SetBlockName(const TokenPos& nameTokenPos, std::string name) -{ - m_variable_name = std::move(name); -} +void HeaderBlockEnum::SetBlockName(const TokenPos &nameTokenPos, std::string name) { m_variable_name = std::move(name); } -bool HeaderBlockEnum::IsDefiningVariable() -{ - return !m_is_typedef && !m_variable_name.empty(); -} +bool HeaderBlockEnum::IsDefiningVariable() { return !m_is_typedef && !m_variable_name.empty(); } -DataDefinition* HeaderBlockEnum::GetVariableType() -{ - return m_enum_definition; -} +DataDefinition *HeaderBlockEnum::GetVariableType() { return m_enum_definition; } -std::string HeaderBlockEnum::GetVariableName() -{ - return m_variable_name; -} +std::string HeaderBlockEnum::GetVariableName() { return m_variable_name; } diff --git a/src/ZoneCodeGeneratorLib/Parsing/Header/Block/HeaderBlockEnum.h b/src/ZoneCodeGeneratorLib/Parsing/Header/Block/HeaderBlockEnum.h index e9eb91649..d94477063 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Header/Block/HeaderBlockEnum.h +++ b/src/ZoneCodeGeneratorLib/Parsing/Header/Block/HeaderBlockEnum.h @@ -1,39 +1,38 @@ #pragma once -#include "Utils/ClassUtils.h" +#include "Domain/Definition/BaseTypeDefinition.h" +#include "Domain/Definition/EnumDefinition.h" #include "IHeaderBlock.h" #include "IHeaderBlockNameHolder.h" #include "IHeaderBlockVariableDefining.h" -#include "Domain/Definition/BaseTypeDefinition.h" -#include "Domain/Definition/EnumDefinition.h" +#include "Utils/ClassUtils.h" -class HeaderBlockEnum final : public IHeaderBlock, public IHeaderBlockNameHolder, public IHeaderBlockVariableDefining -{ - std::string m_namespace; - std::string m_type_name; - const BaseTypeDefinition* m_parent_type; - bool m_is_typedef; - std::vector<std::unique_ptr<EnumMember>> m_members; - int m_next_value; - EnumDefinition* m_enum_definition; +class HeaderBlockEnum final : public IHeaderBlock, public IHeaderBlockNameHolder, public IHeaderBlockVariableDefining { + std::string m_namespace; + std::string m_type_name; + const BaseTypeDefinition *m_parent_type; + bool m_is_typedef; + std::vector<std::unique_ptr<EnumMember>> m_members; + int m_next_value; + EnumDefinition *m_enum_definition; - std::string m_variable_name; + std::string m_variable_name; public: - HeaderBlockEnum(std::string typeName, const BaseTypeDefinition* parentType, bool isTypeDef); + HeaderBlockEnum(std::string typeName, const BaseTypeDefinition *parentType, bool isTypeDef); - HeaderBlockType GetType() override; - const std::vector<sequence_t*>& GetTestsForBlock() override; - void OnOpen(HeaderParserState* state) override; - void OnClose(HeaderParserState* state) override; - void OnChildBlockClose(HeaderParserState* state, IHeaderBlock* block) override; + HeaderBlockType GetType() override; + const std::vector<sequence_t *> &GetTestsForBlock() override; + void OnOpen(HeaderParserState *state) override; + void OnClose(HeaderParserState *state) override; + void OnChildBlockClose(HeaderParserState *state, IHeaderBlock *block) override; - void AddEnumMember(std::unique_ptr<EnumMember> enumMember); - _NODISCARD EnumMember* GetEnumMember(const std::string& name) const; - _NODISCARD int GetNextEnumMemberValue() const; + void AddEnumMember(std::unique_ptr<EnumMember> enumMember); + _NODISCARD EnumMember *GetEnumMember(const std::string &name) const; + _NODISCARD int GetNextEnumMemberValue() const; - void SetBlockName(const TokenPos& nameTokenPos, std::string name) override; - bool IsDefiningVariable() override; - DataDefinition* GetVariableType() override; - std::string GetVariableName() override; + void SetBlockName(const TokenPos &nameTokenPos, std::string name) override; + bool IsDefiningVariable() override; + DataDefinition *GetVariableType() override; + std::string GetVariableName() override; }; diff --git a/src/ZoneCodeGeneratorLib/Parsing/Header/Block/HeaderBlockNamespace.cpp b/src/ZoneCodeGeneratorLib/Parsing/Header/Block/HeaderBlockNamespace.cpp index 79b7591ac..184eaf3e5 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Header/Block/HeaderBlockNamespace.cpp +++ b/src/ZoneCodeGeneratorLib/Parsing/Header/Block/HeaderBlockNamespace.cpp @@ -8,41 +8,19 @@ #include "Parsing/Header/Sequence/SequenceTypedef.h" #include "Parsing/Header/Sequence/SequenceUnion.h" -HeaderBlockNamespace::HeaderBlockNamespace(std::string namespaceName) - : m_namespace_name(std::move(namespaceName)) -{ -} +HeaderBlockNamespace::HeaderBlockNamespace(std::string namespaceName) : m_namespace_name(std::move(namespaceName)) {} -HeaderBlockType HeaderBlockNamespace::GetType() -{ - return HeaderBlockType::NAMESPACE; -} +HeaderBlockType HeaderBlockNamespace::GetType() { return HeaderBlockType::NAMESPACE; } -const std::vector<IHeaderBlock::sequence_t*>& HeaderBlockNamespace::GetTestsForBlock() -{ - static std::vector<sequence_t*> tests({ - new SequenceCloseBlock(false), - new SequenceEnum(), - new SequenceForwardDecl(), - new SequenceNamespace(), - new SequenceStruct(), - new SequenceTypedef(), - new SequenceUnion() - }); - - return tests; -} +const std::vector<IHeaderBlock::sequence_t *> &HeaderBlockNamespace::GetTestsForBlock() { + static std::vector<sequence_t *> tests({new SequenceCloseBlock(false), new SequenceEnum(), new SequenceForwardDecl(), new SequenceNamespace(), + new SequenceStruct(), new SequenceTypedef(), new SequenceUnion()}); -void HeaderBlockNamespace::OnOpen(HeaderParserState* state) -{ - state->m_namespace.Push(m_namespace_name); + return tests; } -void HeaderBlockNamespace::OnClose(HeaderParserState* state) -{ - state->m_namespace.Pop(); -} +void HeaderBlockNamespace::OnOpen(HeaderParserState *state) { state->m_namespace.Push(m_namespace_name); } -void HeaderBlockNamespace::OnChildBlockClose(HeaderParserState* state, IHeaderBlock* block) -{ -} +void HeaderBlockNamespace::OnClose(HeaderParserState *state) { state->m_namespace.Pop(); } + +void HeaderBlockNamespace::OnChildBlockClose(HeaderParserState *state, IHeaderBlock *block) {} diff --git a/src/ZoneCodeGeneratorLib/Parsing/Header/Block/HeaderBlockNamespace.h b/src/ZoneCodeGeneratorLib/Parsing/Header/Block/HeaderBlockNamespace.h index 6f99ce5d8..0bd01302c 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Header/Block/HeaderBlockNamespace.h +++ b/src/ZoneCodeGeneratorLib/Parsing/Header/Block/HeaderBlockNamespace.h @@ -2,16 +2,15 @@ #include "IHeaderBlock.h" -class HeaderBlockNamespace final : public IHeaderBlock -{ - std::string m_namespace_name; +class HeaderBlockNamespace final : public IHeaderBlock { + std::string m_namespace_name; public: - explicit HeaderBlockNamespace(std::string namespaceName); + explicit HeaderBlockNamespace(std::string namespaceName); - HeaderBlockType GetType() override; - const std::vector<sequence_t*>& GetTestsForBlock() override; - void OnOpen(HeaderParserState* state) override; - void OnClose(HeaderParserState* state) override; - void OnChildBlockClose(HeaderParserState* state, IHeaderBlock* block) override; + HeaderBlockType GetType() override; + const std::vector<sequence_t *> &GetTestsForBlock() override; + void OnOpen(HeaderParserState *state) override; + void OnClose(HeaderParserState *state) override; + void OnChildBlockClose(HeaderParserState *state, IHeaderBlock *block) override; }; diff --git a/src/ZoneCodeGeneratorLib/Parsing/Header/Block/HeaderBlockNone.cpp b/src/ZoneCodeGeneratorLib/Parsing/Header/Block/HeaderBlockNone.cpp index 342c5226d..7d8047f25 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Header/Block/HeaderBlockNone.cpp +++ b/src/ZoneCodeGeneratorLib/Parsing/Header/Block/HeaderBlockNone.cpp @@ -7,33 +7,17 @@ #include "Parsing/Header/Sequence/SequenceTypedef.h" #include "Parsing/Header/Sequence/SequenceUnion.h" -HeaderBlockType HeaderBlockNone::GetType() -{ - return HeaderBlockType::NONE; -} +HeaderBlockType HeaderBlockNone::GetType() { return HeaderBlockType::NONE; } -const std::vector<IHeaderBlock::sequence_t*>& HeaderBlockNone::GetTestsForBlock() -{ - static std::vector<sequence_t*> tests({ - new SequenceEnum(), - new SequenceForwardDecl(), - new SequenceNamespace(), - new SequenceStruct(), - new SequenceTypedef(), - new SequenceUnion() - }); - - return tests; -} +const std::vector<IHeaderBlock::sequence_t *> &HeaderBlockNone::GetTestsForBlock() { + static std::vector<sequence_t *> tests( + {new SequenceEnum(), new SequenceForwardDecl(), new SequenceNamespace(), new SequenceStruct(), new SequenceTypedef(), new SequenceUnion()}); -void HeaderBlockNone::OnOpen(HeaderParserState* state) -{ + return tests; } -void HeaderBlockNone::OnClose(HeaderParserState* state) -{ -} +void HeaderBlockNone::OnOpen(HeaderParserState *state) {} -void HeaderBlockNone::OnChildBlockClose(HeaderParserState* state, IHeaderBlock* block) -{ -} +void HeaderBlockNone::OnClose(HeaderParserState *state) {} + +void HeaderBlockNone::OnChildBlockClose(HeaderParserState *state, IHeaderBlock *block) {} diff --git a/src/ZoneCodeGeneratorLib/Parsing/Header/Block/HeaderBlockNone.h b/src/ZoneCodeGeneratorLib/Parsing/Header/Block/HeaderBlockNone.h index 76391f2b0..cb5d73d09 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Header/Block/HeaderBlockNone.h +++ b/src/ZoneCodeGeneratorLib/Parsing/Header/Block/HeaderBlockNone.h @@ -2,12 +2,11 @@ #include "IHeaderBlock.h" -class HeaderBlockNone final : public IHeaderBlock -{ +class HeaderBlockNone final : public IHeaderBlock { public: - HeaderBlockType GetType() override; - const std::vector<sequence_t*>& GetTestsForBlock() override; - void OnOpen(HeaderParserState* state) override; - void OnClose(HeaderParserState* state) override; - void OnChildBlockClose(HeaderParserState* state, IHeaderBlock* block) override; + HeaderBlockType GetType() override; + const std::vector<sequence_t *> &GetTestsForBlock() override; + void OnOpen(HeaderParserState *state) override; + void OnClose(HeaderParserState *state) override; + void OnChildBlockClose(HeaderParserState *state, IHeaderBlock *block) override; }; diff --git a/src/ZoneCodeGeneratorLib/Parsing/Header/Block/HeaderBlockStruct.cpp b/src/ZoneCodeGeneratorLib/Parsing/Header/Block/HeaderBlockStruct.cpp index 6678a4ade..615f59ef9 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Header/Block/HeaderBlockStruct.cpp +++ b/src/ZoneCodeGeneratorLib/Parsing/Header/Block/HeaderBlockStruct.cpp @@ -8,117 +8,78 @@ #include "Utils/NameUtils.h" HeaderBlockStruct::HeaderBlockStruct(std::string name, const bool isTypedef) - : m_type_name(std::move(name)), - m_struct_definition(nullptr), - m_custom_alignment(0), - m_is_typedef(isTypedef), - m_has_custom_align(false), - m_is_anonymous(false) -{ -} + : m_type_name(std::move(name)), m_struct_definition(nullptr), m_custom_alignment(0), m_is_typedef(isTypedef), m_has_custom_align(false), + m_is_anonymous(false) {} -HeaderBlockType HeaderBlockStruct::GetType() -{ - return HeaderBlockType::STRUCT; -} +HeaderBlockType HeaderBlockStruct::GetType() { return HeaderBlockType::STRUCT; } + +const std::vector<IHeaderBlock::sequence_t *> &HeaderBlockStruct::GetTestsForBlock() { + static std::vector<sequence_t *> tests({new SequenceCloseBlock(true), new SequenceEnum(), new SequenceStruct(), new SequenceUnion(), new SequenceVariable()}); -const std::vector<IHeaderBlock::sequence_t*>& HeaderBlockStruct::GetTestsForBlock() -{ - static std::vector<sequence_t*> tests({ - new SequenceCloseBlock(true), - new SequenceEnum(), - new SequenceStruct(), - new SequenceUnion(), - new SequenceVariable() - }); - - return tests; + return tests; } -void HeaderBlockStruct::OnOpen(HeaderParserState* state) -{ - m_namespace = state->m_namespace.ToString(); - - if (m_type_name.empty()) - { - m_is_anonymous = true; - m_type_name = NameUtils::GenerateRandomName(); - } - else - { - state->m_namespace.Push(m_type_name); - } - - state->AddForwardDeclaration(std::make_unique<ForwardDeclaration>(m_namespace, m_type_name, DataDefinitionType::STRUCT)); +void HeaderBlockStruct::OnOpen(HeaderParserState *state) { + m_namespace = state->m_namespace.ToString(); + + if (m_type_name.empty()) { + m_is_anonymous = true; + m_type_name = NameUtils::GenerateRandomName(); + } else { + state->m_namespace.Push(m_type_name); + } + + state->AddForwardDeclaration(std::make_unique<ForwardDeclaration>(m_namespace, m_type_name, DataDefinitionType::STRUCT)); } -void HeaderBlockStruct::OnClose(HeaderParserState* state) -{ - if (!m_is_anonymous) - state->m_namespace.Pop(); +void HeaderBlockStruct::OnClose(HeaderParserState *state) { + if (!m_is_anonymous) + state->m_namespace.Pop(); - auto structDefinition = std::make_unique<StructDefinition>(m_namespace, m_type_name, state->m_pack_value_supplier->GetCurrentPack()); - m_struct_definition = structDefinition.get(); + auto structDefinition = std::make_unique<StructDefinition>(m_namespace, m_type_name, state->m_pack_value_supplier->GetCurrentPack()); + m_struct_definition = structDefinition.get(); - if (m_is_anonymous) - structDefinition->m_anonymous = true; + if (m_is_anonymous) + structDefinition->m_anonymous = true; - for (auto& member : m_members) - structDefinition->m_members.emplace_back(std::move(member)); + for (auto &member : m_members) + structDefinition->m_members.emplace_back(std::move(member)); - if(m_has_custom_align) - { - structDefinition->m_alignment_override = static_cast<unsigned>(m_custom_alignment); - structDefinition->m_has_alignment_override = true; - } + if (m_has_custom_align) { + structDefinition->m_alignment_override = static_cast<unsigned>(m_custom_alignment); + structDefinition->m_has_alignment_override = true; + } - state->AddDataType(std::move(structDefinition)); + state->AddDataType(std::move(structDefinition)); - if (m_is_typedef) - state->AddDataType(std::make_unique<TypedefDefinition>(m_namespace, m_variable_name, std::make_unique<TypeDeclaration>(m_struct_definition))); + if (m_is_typedef) + state->AddDataType(std::make_unique<TypedefDefinition>(m_namespace, m_variable_name, std::make_unique<TypeDeclaration>(m_struct_definition))); } -void HeaderBlockStruct::OnChildBlockClose(HeaderParserState* state, IHeaderBlock* block) -{ - auto* variableDefining = dynamic_cast<IHeaderBlockVariableDefining*>(block); +void HeaderBlockStruct::OnChildBlockClose(HeaderParserState *state, IHeaderBlock *block) { + auto *variableDefining = dynamic_cast<IHeaderBlockVariableDefining *>(block); - if (variableDefining && variableDefining->IsDefiningVariable()) - m_members.emplace_back(std::make_shared<Variable>(variableDefining->GetVariableName(), std::make_unique<TypeDeclaration>(variableDefining->GetVariableType()))); + if (variableDefining && variableDefining->IsDefiningVariable()) + m_members.emplace_back( + std::make_shared<Variable>(variableDefining->GetVariableName(), std::make_unique<TypeDeclaration>(variableDefining->GetVariableType()))); } -void HeaderBlockStruct::AddVariable(std::shared_ptr<Variable> variable) -{ - m_members.emplace_back(std::move(variable)); -} +void HeaderBlockStruct::AddVariable(std::shared_ptr<Variable> variable) { m_members.emplace_back(std::move(variable)); } -void HeaderBlockStruct::SetCustomAlignment(const int alignment) -{ - m_has_custom_align = true; - m_custom_alignment = alignment; +void HeaderBlockStruct::SetCustomAlignment(const int alignment) { + m_has_custom_align = true; + m_custom_alignment = alignment; } -void HeaderBlockStruct::Inherit(const StructDefinition* parentStruct) -{ - for (const auto& parentMember : parentStruct->m_members) - AddVariable(parentMember); +void HeaderBlockStruct::Inherit(const StructDefinition *parentStruct) { + for (const auto &parentMember : parentStruct->m_members) + AddVariable(parentMember); } -void HeaderBlockStruct::SetBlockName(const TokenPos& nameTokenPos, std::string name) -{ - m_variable_name = std::move(name); -} +void HeaderBlockStruct::SetBlockName(const TokenPos &nameTokenPos, std::string name) { m_variable_name = std::move(name); } -bool HeaderBlockStruct::IsDefiningVariable() -{ - return true; -} +bool HeaderBlockStruct::IsDefiningVariable() { return true; } -DataDefinition* HeaderBlockStruct::GetVariableType() -{ - return m_struct_definition; -} +DataDefinition *HeaderBlockStruct::GetVariableType() { return m_struct_definition; } -std::string HeaderBlockStruct::GetVariableName() -{ - return m_variable_name; -} +std::string HeaderBlockStruct::GetVariableName() { return m_variable_name; } diff --git a/src/ZoneCodeGeneratorLib/Parsing/Header/Block/HeaderBlockStruct.h b/src/ZoneCodeGeneratorLib/Parsing/Header/Block/HeaderBlockStruct.h index eba3c274c..ff96d4a99 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Header/Block/HeaderBlockStruct.h +++ b/src/ZoneCodeGeneratorLib/Parsing/Header/Block/HeaderBlockStruct.h @@ -2,43 +2,42 @@ #include <string> +#include "Domain/Definition/StructDefinition.h" +#include "Domain/Definition/Variable.h" #include "IHeaderBlock.h" #include "IHeaderBlockNameHolder.h" #include "IHeaderBlockVariableDefining.h" #include "IHeaderBlockVariableHolder.h" -#include "Domain/Definition/StructDefinition.h" -#include "Domain/Definition/Variable.h" -class HeaderBlockStruct final : public IHeaderBlock, public IHeaderBlockNameHolder, public IHeaderBlockVariableDefining, public IHeaderBlockVariableHolder -{ - std::string m_namespace; - std::string m_type_name; - std::vector<std::shared_ptr<Variable>> m_members; - StructDefinition* m_struct_definition; +class HeaderBlockStruct final : public IHeaderBlock, public IHeaderBlockNameHolder, public IHeaderBlockVariableDefining, public IHeaderBlockVariableHolder { + std::string m_namespace; + std::string m_type_name; + std::vector<std::shared_ptr<Variable>> m_members; + StructDefinition *m_struct_definition; - int m_custom_alignment; + int m_custom_alignment; - bool m_is_typedef; - bool m_has_custom_align; - bool m_is_anonymous; + bool m_is_typedef; + bool m_has_custom_align; + bool m_is_anonymous; - std::string m_variable_name; + std::string m_variable_name; public: - HeaderBlockStruct(std::string name, bool isTypedef); - - HeaderBlockType GetType() override; - const std::vector<sequence_t*>& GetTestsForBlock() override; - void OnOpen(HeaderParserState* state) override; - void OnClose(HeaderParserState* state) override; - void OnChildBlockClose(HeaderParserState* state, IHeaderBlock* block) override; - - void AddVariable(std::shared_ptr<Variable> variable) override; - void SetCustomAlignment(int alignment); - void Inherit(const StructDefinition* parentStruct); - - void SetBlockName(const TokenPos& nameTokenPos, std::string name) override; - bool IsDefiningVariable() override; - DataDefinition* GetVariableType() override; - std::string GetVariableName() override; + HeaderBlockStruct(std::string name, bool isTypedef); + + HeaderBlockType GetType() override; + const std::vector<sequence_t *> &GetTestsForBlock() override; + void OnOpen(HeaderParserState *state) override; + void OnClose(HeaderParserState *state) override; + void OnChildBlockClose(HeaderParserState *state, IHeaderBlock *block) override; + + void AddVariable(std::shared_ptr<Variable> variable) override; + void SetCustomAlignment(int alignment); + void Inherit(const StructDefinition *parentStruct); + + void SetBlockName(const TokenPos &nameTokenPos, std::string name) override; + bool IsDefiningVariable() override; + DataDefinition *GetVariableType() override; + std::string GetVariableName() override; }; diff --git a/src/ZoneCodeGeneratorLib/Parsing/Header/Block/HeaderBlockUnion.cpp b/src/ZoneCodeGeneratorLib/Parsing/Header/Block/HeaderBlockUnion.cpp index 7a032a300..2dc1363fd 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Header/Block/HeaderBlockUnion.cpp +++ b/src/ZoneCodeGeneratorLib/Parsing/Header/Block/HeaderBlockUnion.cpp @@ -8,117 +8,78 @@ #include "Utils/NameUtils.h" HeaderBlockUnion::HeaderBlockUnion(std::string name, const bool isTypedef) - : m_type_name(std::move(name)), - m_union_definition(nullptr), - m_custom_alignment(0), - m_is_typedef(isTypedef), - m_has_custom_align(false), - m_is_anonymous(false) -{ -} + : m_type_name(std::move(name)), m_union_definition(nullptr), m_custom_alignment(0), m_is_typedef(isTypedef), m_has_custom_align(false), + m_is_anonymous(false) {} -HeaderBlockType HeaderBlockUnion::GetType() -{ - return HeaderBlockType::UNION; -} +HeaderBlockType HeaderBlockUnion::GetType() { return HeaderBlockType::UNION; } + +const std::vector<IHeaderBlock::sequence_t *> &HeaderBlockUnion::GetTestsForBlock() { + static std::vector<sequence_t *> tests({new SequenceCloseBlock(true), new SequenceEnum(), new SequenceStruct(), new SequenceUnion(), new SequenceVariable()}); -const std::vector<IHeaderBlock::sequence_t*>& HeaderBlockUnion::GetTestsForBlock() -{ - static std::vector<sequence_t*> tests({ - new SequenceCloseBlock(true), - new SequenceEnum(), - new SequenceStruct(), - new SequenceUnion(), - new SequenceVariable() - }); - - return tests; + return tests; } -void HeaderBlockUnion::OnOpen(HeaderParserState* state) -{ - m_namespace = state->m_namespace.ToString(); - - if (m_type_name.empty()) - { - m_is_anonymous = true; - m_type_name = NameUtils::GenerateRandomName(); - } - else - { - state->m_namespace.Push(m_type_name); - } - - state->AddForwardDeclaration(std::make_unique<ForwardDeclaration>(m_namespace, m_type_name, DataDefinitionType::UNION)); +void HeaderBlockUnion::OnOpen(HeaderParserState *state) { + m_namespace = state->m_namespace.ToString(); + + if (m_type_name.empty()) { + m_is_anonymous = true; + m_type_name = NameUtils::GenerateRandomName(); + } else { + state->m_namespace.Push(m_type_name); + } + + state->AddForwardDeclaration(std::make_unique<ForwardDeclaration>(m_namespace, m_type_name, DataDefinitionType::UNION)); } -void HeaderBlockUnion::OnClose(HeaderParserState* state) -{ - if (!m_is_anonymous) - state->m_namespace.Pop(); +void HeaderBlockUnion::OnClose(HeaderParserState *state) { + if (!m_is_anonymous) + state->m_namespace.Pop(); - auto unionDefinition = std::make_unique<UnionDefinition>(m_namespace, m_type_name, state->m_pack_value_supplier->GetCurrentPack()); - m_union_definition = unionDefinition.get(); + auto unionDefinition = std::make_unique<UnionDefinition>(m_namespace, m_type_name, state->m_pack_value_supplier->GetCurrentPack()); + m_union_definition = unionDefinition.get(); - if (m_is_anonymous) - unionDefinition->m_anonymous = true; + if (m_is_anonymous) + unionDefinition->m_anonymous = true; - for (auto& member : m_members) - unionDefinition->m_members.emplace_back(std::move(member)); + for (auto &member : m_members) + unionDefinition->m_members.emplace_back(std::move(member)); - if (m_has_custom_align) - { - unionDefinition->m_alignment_override = static_cast<unsigned>(m_custom_alignment); - unionDefinition->m_has_alignment_override = true; - } + if (m_has_custom_align) { + unionDefinition->m_alignment_override = static_cast<unsigned>(m_custom_alignment); + unionDefinition->m_has_alignment_override = true; + } - state->AddDataType(std::move(unionDefinition)); + state->AddDataType(std::move(unionDefinition)); - if (m_is_typedef) - state->AddDataType(std::make_unique<TypedefDefinition>(m_namespace, m_variable_name, std::make_unique<TypeDeclaration>(m_union_definition))); + if (m_is_typedef) + state->AddDataType(std::make_unique<TypedefDefinition>(m_namespace, m_variable_name, std::make_unique<TypeDeclaration>(m_union_definition))); } -void HeaderBlockUnion::OnChildBlockClose(HeaderParserState* state, IHeaderBlock* block) -{ - auto* variableDefining = dynamic_cast<IHeaderBlockVariableDefining*>(block); +void HeaderBlockUnion::OnChildBlockClose(HeaderParserState *state, IHeaderBlock *block) { + auto *variableDefining = dynamic_cast<IHeaderBlockVariableDefining *>(block); - if (variableDefining && variableDefining->IsDefiningVariable()) - m_members.emplace_back(std::make_shared<Variable>(variableDefining->GetVariableName(), std::make_unique<TypeDeclaration>(variableDefining->GetVariableType()))); + if (variableDefining && variableDefining->IsDefiningVariable()) + m_members.emplace_back( + std::make_shared<Variable>(variableDefining->GetVariableName(), std::make_unique<TypeDeclaration>(variableDefining->GetVariableType()))); } -void HeaderBlockUnion::AddVariable(std::shared_ptr<Variable> variable) -{ - m_members.emplace_back(std::move(variable)); -} +void HeaderBlockUnion::AddVariable(std::shared_ptr<Variable> variable) { m_members.emplace_back(std::move(variable)); } -void HeaderBlockUnion::SetCustomAlignment(const int alignment) -{ - m_has_custom_align = true; - m_custom_alignment = alignment; +void HeaderBlockUnion::SetCustomAlignment(const int alignment) { + m_has_custom_align = true; + m_custom_alignment = alignment; } -void HeaderBlockUnion::Inherit(const StructDefinition* parentStruct) -{ - for (const auto& parentMember : parentStruct->m_members) - AddVariable(parentMember); +void HeaderBlockUnion::Inherit(const StructDefinition *parentStruct) { + for (const auto &parentMember : parentStruct->m_members) + AddVariable(parentMember); } -void HeaderBlockUnion::SetBlockName(const TokenPos& nameTokenPos, std::string name) -{ - m_variable_name = std::move(name); -} +void HeaderBlockUnion::SetBlockName(const TokenPos &nameTokenPos, std::string name) { m_variable_name = std::move(name); } -bool HeaderBlockUnion::IsDefiningVariable() -{ - return true; -} +bool HeaderBlockUnion::IsDefiningVariable() { return true; } -DataDefinition* HeaderBlockUnion::GetVariableType() -{ - return m_union_definition; -} +DataDefinition *HeaderBlockUnion::GetVariableType() { return m_union_definition; } -std::string HeaderBlockUnion::GetVariableName() -{ - return m_variable_name; -} +std::string HeaderBlockUnion::GetVariableName() { return m_variable_name; } diff --git a/src/ZoneCodeGeneratorLib/Parsing/Header/Block/HeaderBlockUnion.h b/src/ZoneCodeGeneratorLib/Parsing/Header/Block/HeaderBlockUnion.h index 3fc53fd74..b3031057e 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Header/Block/HeaderBlockUnion.h +++ b/src/ZoneCodeGeneratorLib/Parsing/Header/Block/HeaderBlockUnion.h @@ -5,36 +5,35 @@ #include "IHeaderBlockVariableDefining.h" #include "IHeaderBlockVariableHolder.h" -class HeaderBlockUnion final : public IHeaderBlock, public IHeaderBlockNameHolder, public IHeaderBlockVariableDefining, public IHeaderBlockVariableHolder -{ - std::string m_namespace; - std::string m_type_name; - std::vector<std::shared_ptr<Variable>> m_members; - UnionDefinition* m_union_definition; +class HeaderBlockUnion final : public IHeaderBlock, public IHeaderBlockNameHolder, public IHeaderBlockVariableDefining, public IHeaderBlockVariableHolder { + std::string m_namespace; + std::string m_type_name; + std::vector<std::shared_ptr<Variable>> m_members; + UnionDefinition *m_union_definition; - int m_custom_alignment; + int m_custom_alignment; - bool m_is_typedef; - bool m_has_custom_align; - bool m_is_anonymous; + bool m_is_typedef; + bool m_has_custom_align; + bool m_is_anonymous; - std::string m_variable_name; + std::string m_variable_name; public: - HeaderBlockUnion(std::string name, bool isTypedef); - - HeaderBlockType GetType() override; - const std::vector<sequence_t*>& GetTestsForBlock() override; - void OnOpen(HeaderParserState* state) override; - void OnClose(HeaderParserState* state) override; - void OnChildBlockClose(HeaderParserState* state, IHeaderBlock* block) override; - - void AddVariable(std::shared_ptr<Variable> variable) override; - void SetCustomAlignment(int alignment); - void Inherit(const StructDefinition* parentStruct); - - void SetBlockName(const TokenPos& nameTokenPos, std::string name) override; - bool IsDefiningVariable() override; - DataDefinition* GetVariableType() override; - std::string GetVariableName() override; + HeaderBlockUnion(std::string name, bool isTypedef); + + HeaderBlockType GetType() override; + const std::vector<sequence_t *> &GetTestsForBlock() override; + void OnOpen(HeaderParserState *state) override; + void OnClose(HeaderParserState *state) override; + void OnChildBlockClose(HeaderParserState *state, IHeaderBlock *block) override; + + void AddVariable(std::shared_ptr<Variable> variable) override; + void SetCustomAlignment(int alignment); + void Inherit(const StructDefinition *parentStruct); + + void SetBlockName(const TokenPos &nameTokenPos, std::string name) override; + bool IsDefiningVariable() override; + DataDefinition *GetVariableType() override; + std::string GetVariableName() override; }; diff --git a/src/ZoneCodeGeneratorLib/Parsing/Header/Block/IHeaderBlock.h b/src/ZoneCodeGeneratorLib/Parsing/Header/Block/IHeaderBlock.h index b42286f18..9a133da88 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Header/Block/IHeaderBlock.h +++ b/src/ZoneCodeGeneratorLib/Parsing/Header/Block/IHeaderBlock.h @@ -2,37 +2,29 @@ #include <vector> -#include "Parsing/Sequence/AbstractSequence.h" #include "Parsing/Header/Impl/HeaderParserState.h" +#include "Parsing/Sequence/AbstractSequence.h" -enum class HeaderBlockType -{ - NONE, - NAMESPACE, - ENUM, - STRUCT, - UNION -}; +enum class HeaderBlockType { NONE, NAMESPACE, ENUM, STRUCT, UNION }; class HeaderParserValue; class HeaderParserState; -class IHeaderBlock -{ +class IHeaderBlock { public: - typedef AbstractSequence<HeaderParserValue, HeaderParserState> sequence_t; + typedef AbstractSequence<HeaderParserValue, HeaderParserState> sequence_t; - IHeaderBlock() = default; - virtual ~IHeaderBlock() = default; - IHeaderBlock(const IHeaderBlock& other) = default; - IHeaderBlock(IHeaderBlock&& other) noexcept = default; - IHeaderBlock& operator=(const IHeaderBlock& other) = default; - IHeaderBlock& operator=(IHeaderBlock&& other) noexcept = default; + IHeaderBlock() = default; + virtual ~IHeaderBlock() = default; + IHeaderBlock(const IHeaderBlock &other) = default; + IHeaderBlock(IHeaderBlock &&other) noexcept = default; + IHeaderBlock &operator=(const IHeaderBlock &other) = default; + IHeaderBlock &operator=(IHeaderBlock &&other) noexcept = default; - virtual HeaderBlockType GetType() = 0; + virtual HeaderBlockType GetType() = 0; - virtual const std::vector<sequence_t*>& GetTestsForBlock() = 0; + virtual const std::vector<sequence_t *> &GetTestsForBlock() = 0; - virtual void OnOpen(HeaderParserState* state) = 0; - virtual void OnClose(HeaderParserState* state) = 0; - virtual void OnChildBlockClose(HeaderParserState* state, IHeaderBlock* block) = 0; + virtual void OnOpen(HeaderParserState *state) = 0; + virtual void OnClose(HeaderParserState *state) = 0; + virtual void OnChildBlockClose(HeaderParserState *state, IHeaderBlock *block) = 0; }; \ No newline at end of file diff --git a/src/ZoneCodeGeneratorLib/Parsing/Header/Block/IHeaderBlockNameHolder.h b/src/ZoneCodeGeneratorLib/Parsing/Header/Block/IHeaderBlockNameHolder.h index 4dbd5e9c6..746e9474b 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Header/Block/IHeaderBlockNameHolder.h +++ b/src/ZoneCodeGeneratorLib/Parsing/Header/Block/IHeaderBlockNameHolder.h @@ -2,15 +2,14 @@ #include <string> -class IHeaderBlockNameHolder -{ +class IHeaderBlockNameHolder { public: - IHeaderBlockNameHolder() = default; - virtual ~IHeaderBlockNameHolder() = default; - IHeaderBlockNameHolder(const IHeaderBlockNameHolder& other) = default; - IHeaderBlockNameHolder(IHeaderBlockNameHolder&& other) noexcept = default; - IHeaderBlockNameHolder& operator=(const IHeaderBlockNameHolder& other) = default; - IHeaderBlockNameHolder& operator=(IHeaderBlockNameHolder&& other) noexcept = default; + IHeaderBlockNameHolder() = default; + virtual ~IHeaderBlockNameHolder() = default; + IHeaderBlockNameHolder(const IHeaderBlockNameHolder &other) = default; + IHeaderBlockNameHolder(IHeaderBlockNameHolder &&other) noexcept = default; + IHeaderBlockNameHolder &operator=(const IHeaderBlockNameHolder &other) = default; + IHeaderBlockNameHolder &operator=(IHeaderBlockNameHolder &&other) noexcept = default; - virtual void SetBlockName(const TokenPos& nameTokenPos, std::string name) = 0; + virtual void SetBlockName(const TokenPos &nameTokenPos, std::string name) = 0; }; diff --git a/src/ZoneCodeGeneratorLib/Parsing/Header/Block/IHeaderBlockVariableDefining.h b/src/ZoneCodeGeneratorLib/Parsing/Header/Block/IHeaderBlockVariableDefining.h index 23b7cb830..24685bb03 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Header/Block/IHeaderBlockVariableDefining.h +++ b/src/ZoneCodeGeneratorLib/Parsing/Header/Block/IHeaderBlockVariableDefining.h @@ -4,17 +4,16 @@ #include "Domain/Definition/DataDefinition.h" -class IHeaderBlockVariableDefining -{ +class IHeaderBlockVariableDefining { public: - IHeaderBlockVariableDefining() = default; - virtual ~IHeaderBlockVariableDefining() = default; - IHeaderBlockVariableDefining(const IHeaderBlockVariableDefining& other) = default; - IHeaderBlockVariableDefining(IHeaderBlockVariableDefining&& other) noexcept = default; - IHeaderBlockVariableDefining& operator=(const IHeaderBlockVariableDefining& other) = default; - IHeaderBlockVariableDefining& operator=(IHeaderBlockVariableDefining&& other) noexcept = default; + IHeaderBlockVariableDefining() = default; + virtual ~IHeaderBlockVariableDefining() = default; + IHeaderBlockVariableDefining(const IHeaderBlockVariableDefining &other) = default; + IHeaderBlockVariableDefining(IHeaderBlockVariableDefining &&other) noexcept = default; + IHeaderBlockVariableDefining &operator=(const IHeaderBlockVariableDefining &other) = default; + IHeaderBlockVariableDefining &operator=(IHeaderBlockVariableDefining &&other) noexcept = default; - virtual bool IsDefiningVariable() = 0; - virtual DataDefinition* GetVariableType() = 0; - virtual std::string GetVariableName() = 0; + virtual bool IsDefiningVariable() = 0; + virtual DataDefinition *GetVariableType() = 0; + virtual std::string GetVariableName() = 0; }; diff --git a/src/ZoneCodeGeneratorLib/Parsing/Header/Block/IHeaderBlockVariableHolder.h b/src/ZoneCodeGeneratorLib/Parsing/Header/Block/IHeaderBlockVariableHolder.h index 86141f4c1..ba500732a 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Header/Block/IHeaderBlockVariableHolder.h +++ b/src/ZoneCodeGeneratorLib/Parsing/Header/Block/IHeaderBlockVariableHolder.h @@ -4,15 +4,14 @@ #include "Domain/Definition/Variable.h" -class IHeaderBlockVariableHolder -{ +class IHeaderBlockVariableHolder { public: - IHeaderBlockVariableHolder() = default; - virtual ~IHeaderBlockVariableHolder() = default; - IHeaderBlockVariableHolder(const IHeaderBlockVariableHolder& other) = default; - IHeaderBlockVariableHolder(IHeaderBlockVariableHolder&& other) noexcept = default; - IHeaderBlockVariableHolder& operator=(const IHeaderBlockVariableHolder& other) = default; - IHeaderBlockVariableHolder& operator=(IHeaderBlockVariableHolder&& other) noexcept = default; + IHeaderBlockVariableHolder() = default; + virtual ~IHeaderBlockVariableHolder() = default; + IHeaderBlockVariableHolder(const IHeaderBlockVariableHolder &other) = default; + IHeaderBlockVariableHolder(IHeaderBlockVariableHolder &&other) noexcept = default; + IHeaderBlockVariableHolder &operator=(const IHeaderBlockVariableHolder &other) = default; + IHeaderBlockVariableHolder &operator=(IHeaderBlockVariableHolder &&other) noexcept = default; - virtual void AddVariable(std::shared_ptr<Variable> variable) = 0; + virtual void AddVariable(std::shared_ptr<Variable> variable) = 0; }; diff --git a/src/ZoneCodeGeneratorLib/Parsing/Header/HeaderFileReader.cpp b/src/ZoneCodeGeneratorLib/Parsing/Header/HeaderFileReader.cpp index 83871165a..aa5d16311 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Header/HeaderFileReader.cpp +++ b/src/ZoneCodeGeneratorLib/Parsing/Header/HeaderFileReader.cpp @@ -15,84 +15,71 @@ #include "Parsing/PostProcessing/CreateStructureInformationPostProcessor.h" #include "Parsing/PostProcessing/IPostProcessor.h" -HeaderFileReader::HeaderFileReader(const ZoneCodeGeneratorArguments* args, std::string filename) - : m_args(args), - m_filename(std::move(filename)), - m_pack_value_supplier(nullptr), - m_stream(nullptr) -{ - SetupPostProcessors(); +HeaderFileReader::HeaderFileReader(const ZoneCodeGeneratorArguments *args, std::string filename) + : m_args(args), m_filename(std::move(filename)), m_pack_value_supplier(nullptr), m_stream(nullptr) { + SetupPostProcessors(); } -bool HeaderFileReader::OpenBaseStream() -{ - auto stream = std::make_unique<ParserFilesystemStream>(m_filename); - if (!stream->IsOpen()) - { - std::cout << "Could not open header file" << std::endl; - return false; - } - - m_stream = stream.get(); - m_open_streams.emplace_back(std::move(stream)); - return true; +bool HeaderFileReader::OpenBaseStream() { + auto stream = std::make_unique<ParserFilesystemStream>(m_filename); + if (!stream->IsOpen()) { + std::cout << "Could not open header file" << std::endl; + return false; + } + + m_stream = stream.get(); + m_open_streams.emplace_back(std::move(stream)); + return true; } -void HeaderFileReader::SetupStreamProxies() -{ - auto commentProxy = std::make_unique<CommentRemovingStreamProxy>(m_stream); - auto includeProxy = std::make_unique<IncludingStreamProxy>(commentProxy.get()); - auto packProxy = std::make_unique<PackDefinitionStreamProxy>(includeProxy.get()); - auto definesProxy = std::make_unique<DefinesStreamProxy>(packProxy.get()); - definesProxy->AddDefine(DefinesStreamProxy::Define(ZONE_CODE_GENERATOR_DEFINE_NAME, ZONE_CODE_GENERATOR_DEFINE_VALUE)); - - m_pack_value_supplier = packProxy.get(); - m_stream = definesProxy.get(); - - m_open_streams.emplace_back(std::move(commentProxy)); - m_open_streams.emplace_back(std::move(includeProxy)); - m_open_streams.emplace_back(std::move(packProxy)); - m_open_streams.emplace_back(std::move(definesProxy)); +void HeaderFileReader::SetupStreamProxies() { + auto commentProxy = std::make_unique<CommentRemovingStreamProxy>(m_stream); + auto includeProxy = std::make_unique<IncludingStreamProxy>(commentProxy.get()); + auto packProxy = std::make_unique<PackDefinitionStreamProxy>(includeProxy.get()); + auto definesProxy = std::make_unique<DefinesStreamProxy>(packProxy.get()); + definesProxy->AddDefine(DefinesStreamProxy::Define(ZONE_CODE_GENERATOR_DEFINE_NAME, ZONE_CODE_GENERATOR_DEFINE_VALUE)); + + m_pack_value_supplier = packProxy.get(); + m_stream = definesProxy.get(); + + m_open_streams.emplace_back(std::move(commentProxy)); + m_open_streams.emplace_back(std::move(includeProxy)); + m_open_streams.emplace_back(std::move(packProxy)); + m_open_streams.emplace_back(std::move(definesProxy)); } -void HeaderFileReader::SetupPostProcessors() -{ - // Order is important - m_post_processors.emplace_back(std::make_unique<CreateStructureInformationPostProcessor>()); - m_post_processors.emplace_back(std::make_unique<CreateMemberInformationPostProcessor>()); +void HeaderFileReader::SetupPostProcessors() { + // Order is important + m_post_processors.emplace_back(std::make_unique<CreateStructureInformationPostProcessor>()); + m_post_processors.emplace_back(std::make_unique<CreateMemberInformationPostProcessor>()); } -bool HeaderFileReader::ReadHeaderFile(IDataRepository* repository) -{ - if (m_args->m_verbose) - { - std::cout << "Reading header file: " << m_filename << std::endl; - } +bool HeaderFileReader::ReadHeaderFile(IDataRepository *repository) { + if (m_args->m_verbose) { + std::cout << "Reading header file: " << m_filename << std::endl; + } - if (!OpenBaseStream()) - return false; + if (!OpenBaseStream()) + return false; - SetupStreamProxies(); + SetupStreamProxies(); - const auto lexer = std::make_unique<HeaderLexer>(m_stream); - const auto parser = std::make_unique<HeaderParser>(lexer.get(), m_pack_value_supplier); + const auto lexer = std::make_unique<HeaderLexer>(m_stream); + const auto parser = std::make_unique<HeaderParser>(lexer.get(), m_pack_value_supplier); - const auto start = std::chrono::steady_clock::now(); - auto result = parser->Parse(); - if (result) - result = parser->SaveToRepository(repository); - const auto end = std::chrono::steady_clock::now(); + const auto start = std::chrono::steady_clock::now(); + auto result = parser->Parse(); + if (result) + result = parser->SaveToRepository(repository); + const auto end = std::chrono::steady_clock::now(); - if(m_args->m_verbose) - { - std::cout << "Processing header took " << std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count() << "ms" << std::endl; - } + if (m_args->m_verbose) { + std::cout << "Processing header took " << std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count() << "ms" << std::endl; + } - if (!result) - return false; + if (!result) + return false; - return std::all_of(m_post_processors.begin(), m_post_processors.end(), [repository](const std::unique_ptr<IPostProcessor>& postProcessor) - { - return postProcessor->PostProcess(repository); - }); + return std::all_of(m_post_processors.begin(), m_post_processors.end(), + [repository](const std::unique_ptr<IPostProcessor> &postProcessor) { return postProcessor->PostProcess(repository); }); } diff --git a/src/ZoneCodeGeneratorLib/Parsing/Header/HeaderFileReader.h b/src/ZoneCodeGeneratorLib/Parsing/Header/HeaderFileReader.h index 6b9ed2599..f6f5c3433 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Header/HeaderFileReader.h +++ b/src/ZoneCodeGeneratorLib/Parsing/Header/HeaderFileReader.h @@ -2,32 +2,31 @@ #include <string> -#include "ZoneCodeGeneratorArguments.h" #include "Parsing/IPackValueSupplier.h" #include "Parsing/IParserLineStream.h" #include "Parsing/PostProcessing/IPostProcessor.h" #include "Persistence/IDataRepository.h" +#include "ZoneCodeGeneratorArguments.h" -class HeaderFileReader -{ - static constexpr const char* ZONE_CODE_GENERATOR_DEFINE_NAME = "__zonecodegenerator"; - static constexpr const char* ZONE_CODE_GENERATOR_DEFINE_VALUE = "1"; +class HeaderFileReader { + static constexpr const char *ZONE_CODE_GENERATOR_DEFINE_NAME = "__zonecodegenerator"; + static constexpr const char *ZONE_CODE_GENERATOR_DEFINE_VALUE = "1"; - const ZoneCodeGeneratorArguments* m_args; - std::string m_filename; + const ZoneCodeGeneratorArguments *m_args; + std::string m_filename; - std::vector<std::unique_ptr<IParserLineStream>> m_open_streams; - const IPackValueSupplier* m_pack_value_supplier; - IParserLineStream* m_stream; + std::vector<std::unique_ptr<IParserLineStream>> m_open_streams; + const IPackValueSupplier *m_pack_value_supplier; + IParserLineStream *m_stream; - std::vector<std::unique_ptr<IPostProcessor>> m_post_processors; + std::vector<std::unique_ptr<IPostProcessor>> m_post_processors; - bool OpenBaseStream(); - void SetupStreamProxies(); - void SetupPostProcessors(); + bool OpenBaseStream(); + void SetupStreamProxies(); + void SetupPostProcessors(); public: - HeaderFileReader(const ZoneCodeGeneratorArguments* args, std::string filename); + HeaderFileReader(const ZoneCodeGeneratorArguments *args, std::string filename); - bool ReadHeaderFile(IDataRepository* repository); + bool ReadHeaderFile(IDataRepository *repository); }; diff --git a/src/ZoneCodeGeneratorLib/Parsing/Header/Impl/HeaderLexer.cpp b/src/ZoneCodeGeneratorLib/Parsing/Header/Impl/HeaderLexer.cpp index ff4dd0346..52842099b 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Header/Impl/HeaderLexer.cpp +++ b/src/ZoneCodeGeneratorLib/Parsing/Header/Impl/HeaderLexer.cpp @@ -1,172 +1,144 @@ #include "HeaderLexer.h" -HeaderLexer::HeaderLexer(IParserLineStream* stream) - : AbstractLexer(stream) -{ - PrepareKeywords(); +HeaderLexer::HeaderLexer(IParserLineStream *stream) : AbstractLexer(stream) { PrepareKeywords(); } + +void HeaderLexer::PrepareKeywords() { + m_keywords["__declspec"] = HeaderParserValueType::DECLSPEC; + m_keywords["align"] = HeaderParserValueType::ALIGN; + m_keywords["alignas"] = HeaderParserValueType::ALIGNAS; + m_keywords["char"] = HeaderParserValueType::CHAR; + m_keywords["const"] = HeaderParserValueType::CONST; + m_keywords["enum"] = HeaderParserValueType::ENUM; + m_keywords["int"] = HeaderParserValueType::INT; + m_keywords["long"] = HeaderParserValueType::LONG; + m_keywords["namespace"] = HeaderParserValueType::NAMESPACE; + m_keywords["short"] = HeaderParserValueType::SHORT; + m_keywords["struct"] = HeaderParserValueType::STRUCT; + m_keywords["typedef"] = HeaderParserValueType::TYPEDEF; + m_keywords["union"] = HeaderParserValueType::UNION; + m_keywords["unsigned"] = HeaderParserValueType::UNSIGNED; } -void HeaderLexer::PrepareKeywords() -{ - m_keywords["__declspec"] = HeaderParserValueType::DECLSPEC; - m_keywords["align"] = HeaderParserValueType::ALIGN; - m_keywords["alignas"] = HeaderParserValueType::ALIGNAS; - m_keywords["char"] = HeaderParserValueType::CHAR; - m_keywords["const"] = HeaderParserValueType::CONST; - m_keywords["enum"] = HeaderParserValueType::ENUM; - m_keywords["int"] = HeaderParserValueType::INT; - m_keywords["long"] = HeaderParserValueType::LONG; - m_keywords["namespace"] = HeaderParserValueType::NAMESPACE; - m_keywords["short"] = HeaderParserValueType::SHORT; - m_keywords["struct"] = HeaderParserValueType::STRUCT; - m_keywords["typedef"] = HeaderParserValueType::TYPEDEF; - m_keywords["union"] = HeaderParserValueType::UNION; - m_keywords["unsigned"] = HeaderParserValueType::UNSIGNED; -} +HeaderParserValue HeaderLexer::GetNextToken() { + auto c = NextChar(); + + while (c != EOF) { + switch (c) { + case '\"': { + return HeaderParserValue::String(GetPreviousCharacterPos(), new std::string(ReadString())); + } + + case '<': { + if (!IsLineEnd()) { + const auto pos = GetPreviousCharacterPos(); + const auto nextChar = PeekChar(); + + if (nextChar == '=') { + NextChar(); + return HeaderParserValue::LessEqual(pos); + } + if (nextChar == '<') { + NextChar(); + return HeaderParserValue::ShiftLeft(pos); + } + } + + return HeaderParserValue::Character(GetPreviousCharacterPos(), static_cast<char>(c)); + } -HeaderParserValue HeaderLexer::GetNextToken() -{ - auto c = NextChar(); - - while (c != EOF) - { - switch (c) - { - case '\"': - { - return HeaderParserValue::String(GetPreviousCharacterPos(), new std::string(ReadString())); - } - - case '<': - { - if (!IsLineEnd()) - { - const auto pos = GetPreviousCharacterPos(); - const auto nextChar = PeekChar(); - - if (nextChar == '=') - { - NextChar(); - return HeaderParserValue::LessEqual(pos); - } - if (nextChar == '<') - { - NextChar(); - return HeaderParserValue::ShiftLeft(pos); - } - } - - return HeaderParserValue::Character(GetPreviousCharacterPos(), static_cast<char>(c)); - } - - case '>': - { - if (!IsLineEnd()) - { - const auto pos = GetPreviousCharacterPos(); - const auto nextChar = PeekChar(); - - if (nextChar == '=') - { - NextChar(); - return HeaderParserValue::GreaterEqual(pos); - } - if (nextChar == '>') - { - NextChar(); - return HeaderParserValue::ShiftRight(pos); - } - } - - return HeaderParserValue::Character(GetPreviousCharacterPos(), static_cast<char>(c)); - } - - case '=': - { - if (NextCharInLineIs('=')) - { - const auto pos = GetPreviousCharacterPos(); - NextChar(); - return HeaderParserValue::Equals(pos); - } - - return HeaderParserValue::Character(GetPreviousCharacterPos(), static_cast<char>(c)); - } - - case '&': - { - if (NextCharInLineIs('&')) - { - const auto pos = GetPreviousCharacterPos(); - NextChar(); - return HeaderParserValue::LogicalAnd(pos); - } - - return HeaderParserValue::Character(GetPreviousCharacterPos(), static_cast<char>(c)); - } - - case '|': - { - if (NextCharInLineIs('|')) - { - const auto pos = GetPreviousCharacterPos(); - NextChar(); - return HeaderParserValue::LogicalOr(pos); - } - - return HeaderParserValue::Character(GetPreviousCharacterPos(), static_cast<char>(c)); - } - - case '!': - { - if (NextCharInLineIs('=')) - { - const auto pos = GetPreviousCharacterPos(); - NextChar(); - return HeaderParserValue::NotEqual(pos); - } - - return HeaderParserValue::Character(GetPreviousCharacterPos(), static_cast<char>(c)); - } - - default: - { - if (isspace(c)) - break; - - const auto pos = GetPreviousCharacterPos(); - if(isdigit(c)) - { - bool isFloatingPointValue; - bool hasSignPrefix; - double doubleValue; - int integerValue; - - ReadNumber(isFloatingPointValue, hasSignPrefix, doubleValue, integerValue); - - if (isFloatingPointValue) - return HeaderParserValue::FloatingPoint(pos, doubleValue); - - return HeaderParserValue::Integer(pos, integerValue); - } - - if (isalpha(c) || c == '_') - { - auto identifier = ReadIdentifier(); - - const auto foundKeyword = m_keywords.find(identifier); - if (foundKeyword != m_keywords.end()) - return HeaderParserValue::Keyword(pos, foundKeyword->second); - - return HeaderParserValue::Identifier(pos, new std::string(std::move(identifier))); - } - - return HeaderParserValue::Character(pos, static_cast<char>(c)); - } + case '>': { + if (!IsLineEnd()) { + const auto pos = GetPreviousCharacterPos(); + const auto nextChar = PeekChar(); + + if (nextChar == '=') { + NextChar(); + return HeaderParserValue::GreaterEqual(pos); + } + if (nextChar == '>') { + NextChar(); + return HeaderParserValue::ShiftRight(pos); } + } + + return HeaderParserValue::Character(GetPreviousCharacterPos(), static_cast<char>(c)); + } + + case '=': { + if (NextCharInLineIs('=')) { + const auto pos = GetPreviousCharacterPos(); + NextChar(); + return HeaderParserValue::Equals(pos); + } - c = NextChar(); + return HeaderParserValue::Character(GetPreviousCharacterPos(), static_cast<char>(c)); } - return HeaderParserValue::EndOfFile(TokenPos()); + case '&': { + if (NextCharInLineIs('&')) { + const auto pos = GetPreviousCharacterPos(); + NextChar(); + return HeaderParserValue::LogicalAnd(pos); + } + + return HeaderParserValue::Character(GetPreviousCharacterPos(), static_cast<char>(c)); + } + + case '|': { + if (NextCharInLineIs('|')) { + const auto pos = GetPreviousCharacterPos(); + NextChar(); + return HeaderParserValue::LogicalOr(pos); + } + + return HeaderParserValue::Character(GetPreviousCharacterPos(), static_cast<char>(c)); + } + + case '!': { + if (NextCharInLineIs('=')) { + const auto pos = GetPreviousCharacterPos(); + NextChar(); + return HeaderParserValue::NotEqual(pos); + } + + return HeaderParserValue::Character(GetPreviousCharacterPos(), static_cast<char>(c)); + } + + default: { + if (isspace(c)) + break; + + const auto pos = GetPreviousCharacterPos(); + if (isdigit(c)) { + bool isFloatingPointValue; + bool hasSignPrefix; + double doubleValue; + int integerValue; + + ReadNumber(isFloatingPointValue, hasSignPrefix, doubleValue, integerValue); + + if (isFloatingPointValue) + return HeaderParserValue::FloatingPoint(pos, doubleValue); + + return HeaderParserValue::Integer(pos, integerValue); + } + + if (isalpha(c) || c == '_') { + auto identifier = ReadIdentifier(); + + const auto foundKeyword = m_keywords.find(identifier); + if (foundKeyword != m_keywords.end()) + return HeaderParserValue::Keyword(pos, foundKeyword->second); + + return HeaderParserValue::Identifier(pos, new std::string(std::move(identifier))); + } + + return HeaderParserValue::Character(pos, static_cast<char>(c)); + } + } + + c = NextChar(); + } + + return HeaderParserValue::EndOfFile(TokenPos()); } diff --git a/src/ZoneCodeGeneratorLib/Parsing/Header/Impl/HeaderLexer.h b/src/ZoneCodeGeneratorLib/Parsing/Header/Impl/HeaderLexer.h index ab9640b7c..763da94a9 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Header/Impl/HeaderLexer.h +++ b/src/ZoneCodeGeneratorLib/Parsing/Header/Impl/HeaderLexer.h @@ -5,15 +5,14 @@ #include "HeaderParserValue.h" #include "Parsing/Impl/AbstractLexer.h" -class HeaderLexer final : public AbstractLexer<HeaderParserValue> -{ - std::unordered_map<std::string, HeaderParserValueType> m_keywords; +class HeaderLexer final : public AbstractLexer<HeaderParserValue> { + std::unordered_map<std::string, HeaderParserValueType> m_keywords; - void PrepareKeywords(); + void PrepareKeywords(); protected: - HeaderParserValue GetNextToken() override; + HeaderParserValue GetNextToken() override; public: - explicit HeaderLexer(IParserLineStream* stream); + explicit HeaderLexer(IParserLineStream *stream); }; diff --git a/src/ZoneCodeGeneratorLib/Parsing/Header/Impl/HeaderParser.cpp b/src/ZoneCodeGeneratorLib/Parsing/Header/Impl/HeaderParser.cpp index 2b6bee8b4..ed00ebe2b 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Header/Impl/HeaderParser.cpp +++ b/src/ZoneCodeGeneratorLib/Parsing/Header/Impl/HeaderParser.cpp @@ -2,18 +2,11 @@ #include "Parsing/Header/Sequence/SequenceNamespace.h" -HeaderParser::HeaderParser(HeaderLexer* lexer, const IPackValueSupplier* packValueSupplier) - : AbstractParser(lexer, std::make_unique<HeaderParserState>(packValueSupplier)) -{ - auto sequenceNamespace = std::make_unique<SequenceNamespace>(); +HeaderParser::HeaderParser(HeaderLexer *lexer, const IPackValueSupplier *packValueSupplier) + : AbstractParser(lexer, std::make_unique<HeaderParserState>(packValueSupplier)) { + auto sequenceNamespace = std::make_unique<SequenceNamespace>(); } -const std::vector<HeaderParser::sequence_t*>& HeaderParser::GetTestsForState() -{ - return m_state->GetBlock()->GetTestsForBlock(); -} +const std::vector<HeaderParser::sequence_t *> &HeaderParser::GetTestsForState() { return m_state->GetBlock()->GetTestsForBlock(); } -bool HeaderParser::SaveToRepository(IDataRepository* repository) const -{ - return m_state->SaveToRepository(repository); -} +bool HeaderParser::SaveToRepository(IDataRepository *repository) const { return m_state->SaveToRepository(repository); } diff --git a/src/ZoneCodeGeneratorLib/Parsing/Header/Impl/HeaderParser.h b/src/ZoneCodeGeneratorLib/Parsing/Header/Impl/HeaderParser.h index a52bbabaf..c6f48b530 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Header/Impl/HeaderParser.h +++ b/src/ZoneCodeGeneratorLib/Parsing/Header/Impl/HeaderParser.h @@ -6,13 +6,12 @@ #include "Parsing/Impl/AbstractParser.h" #include "Persistence/IDataRepository.h" -class HeaderParser final : public AbstractParser<HeaderParserValue, HeaderParserState> -{ +class HeaderParser final : public AbstractParser<HeaderParserValue, HeaderParserState> { protected: - const std::vector<sequence_t*>& GetTestsForState() override; + const std::vector<sequence_t *> &GetTestsForState() override; public: - HeaderParser(HeaderLexer* lexer, const IPackValueSupplier* packValueSupplier); + HeaderParser(HeaderLexer *lexer, const IPackValueSupplier *packValueSupplier); - bool SaveToRepository(IDataRepository* repository) const; + bool SaveToRepository(IDataRepository *repository) const; }; diff --git a/src/ZoneCodeGeneratorLib/Parsing/Header/Impl/HeaderParserState.cpp b/src/ZoneCodeGeneratorLib/Parsing/Header/Impl/HeaderParserState.cpp index b4dbb7f8d..20bb38204 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Header/Impl/HeaderParserState.cpp +++ b/src/ZoneCodeGeneratorLib/Parsing/Header/Impl/HeaderParserState.cpp @@ -2,203 +2,170 @@ #include <iostream> - #include "Domain/Definition/EnumDefinition.h" #include "Parsing/Header/Block/HeaderBlockNone.h" -HeaderParserState::HeaderParserState(const IPackValueSupplier* packValueSupplier) +HeaderParserState::HeaderParserState(const IPackValueSupplier *packValueSupplier) : m_pack_value_supplier(packValueSupplier) { - m_blocks.push(std::make_unique<HeaderBlockNone>()); + m_blocks.push(std::make_unique<HeaderBlockNone>()); - for (auto i = 0u; i < BaseTypeDefinition::ALL_BASE_TYPES_COUNT; i++) - AddBaseDataType(BaseTypeDefinition::ALL_BASE_TYPES[i]); + for (auto i = 0u; i < BaseTypeDefinition::ALL_BASE_TYPES_COUNT; i++) + AddBaseDataType(BaseTypeDefinition::ALL_BASE_TYPES[i]); } -void HeaderParserState::AddBaseDataType(const BaseTypeDefinition* baseType) -{ - m_definitions.insert(std::make_pair(baseType->GetFullName(), baseType)); -} +void HeaderParserState::AddBaseDataType(const BaseTypeDefinition *baseType) { m_definitions.insert(std::make_pair(baseType->GetFullName(), baseType)); } -IHeaderBlock* HeaderParserState::GetBlock() const -{ - return m_blocks.top().get(); -} +IHeaderBlock *HeaderParserState::GetBlock() const { return m_blocks.top().get(); } -void HeaderParserState::PushBlock(std::unique_ptr<IHeaderBlock> block) -{ - m_blocks.emplace(std::move(block)); - m_blocks.top()->OnOpen(this); +void HeaderParserState::PushBlock(std::unique_ptr<IHeaderBlock> block) { + m_blocks.emplace(std::move(block)); + m_blocks.top()->OnOpen(this); } -void HeaderParserState::PopBlock() -{ - // Leave at least one block on the stack which should be the only "none" block - if (m_blocks.size() > 1) - { - std::unique_ptr<IHeaderBlock> poppedBlock = std::move(m_blocks.top()); - m_blocks.pop(); - poppedBlock->OnClose(this); - m_blocks.top()->OnChildBlockClose(this, poppedBlock.get()); - } +void HeaderParserState::PopBlock() { + // Leave at least one block on the stack which should be the only "none" block + if (m_blocks.size() > 1) { + std::unique_ptr<IHeaderBlock> poppedBlock = std::move(m_blocks.top()); + m_blocks.pop(); + poppedBlock->OnClose(this); + m_blocks.top()->OnChildBlockClose(this, poppedBlock.get()); + } } -void HeaderParserState::AddDataType(std::unique_ptr<DataDefinition> definition) -{ - if (definition->GetType() == DataDefinitionType::ENUM) - { - for (const auto& enumMember : dynamic_cast<EnumDefinition*>(definition.get())->m_members) - { - m_enum_members.insert(std::make_pair(enumMember->m_name, enumMember.get())); - } +void HeaderParserState::AddDataType(std::unique_ptr<DataDefinition> definition) { + if (definition->GetType() == DataDefinitionType::ENUM) { + for (const auto &enumMember : dynamic_cast<EnumDefinition *>(definition.get())->m_members) { + m_enum_members.insert(std::make_pair(enumMember->m_name, enumMember.get())); } + } - const DataDefinition* dataDefinition = definition.get(); - m_header_definitions.emplace_back(std::move(definition)); - m_definitions.insert(std::make_pair(dataDefinition->m_name, dataDefinition)); + const DataDefinition *dataDefinition = definition.get(); + m_header_definitions.emplace_back(std::move(definition)); + m_definitions.insert(std::make_pair(dataDefinition->m_name, dataDefinition)); } -void HeaderParserState::AddForwardDeclaration(std::unique_ptr<ForwardDeclaration> forwardDeclaration) -{ - m_forward_declarations.insert(std::make_pair(forwardDeclaration->GetFullName(), std::move(forwardDeclaration))); +void HeaderParserState::AddForwardDeclaration(std::unique_ptr<ForwardDeclaration> forwardDeclaration) { + m_forward_declarations.insert(std::make_pair(forwardDeclaration->GetFullName(), std::move(forwardDeclaration))); } -const DataDefinition* HeaderParserState::FindType(const std::string& typeName) -{ - const auto foundDefinitionEntry = m_definitions.find(typeName); +const DataDefinition *HeaderParserState::FindType(const std::string &typeName) { + const auto foundDefinitionEntry = m_definitions.find(typeName); - if (foundDefinitionEntry != m_definitions.end()) - return foundDefinitionEntry->second; + if (foundDefinitionEntry != m_definitions.end()) + return foundDefinitionEntry->second; - const auto foundForwardEntry = m_forward_declarations.find(typeName); + const auto foundForwardEntry = m_forward_declarations.find(typeName); - if (foundForwardEntry != m_forward_declarations.end()) - return foundForwardEntry->second.get(); + if (foundForwardEntry != m_forward_declarations.end()) + return foundForwardEntry->second.get(); - return nullptr; + return nullptr; } -EnumMember* HeaderParserState::FindEnumMember(const std::string& enumMemberName) -{ - const auto foundEntry = m_enum_members.find(enumMemberName); +EnumMember *HeaderParserState::FindEnumMember(const std::string &enumMemberName) { + const auto foundEntry = m_enum_members.find(enumMemberName); - if (foundEntry != m_enum_members.end()) - return foundEntry->second; + if (foundEntry != m_enum_members.end()) + return foundEntry->second; - return nullptr; + return nullptr; } -bool HeaderParserState::ResolveForwardDeclarations() -{ - for (auto& [_, forwardDeclaration] : m_forward_declarations) - { - const auto* dataDefinition = FindType(forwardDeclaration->GetFullName()); - - if (dataDefinition == nullptr) - { - std::cout << "Forward declaration \"" << forwardDeclaration->GetFullName() << "\" was not defined" << std::endl; - return false; - } +bool HeaderParserState::ResolveForwardDeclarations() { + for (auto &[_, forwardDeclaration] : m_forward_declarations) { + const auto *dataDefinition = FindType(forwardDeclaration->GetFullName()); - forwardDeclaration->m_definition = dataDefinition; + if (dataDefinition == nullptr) { + std::cout << "Forward declaration \"" << forwardDeclaration->GetFullName() << "\" was not defined" << std::endl; + return false; } - return true; + forwardDeclaration->m_definition = dataDefinition; + } + + return true; } -bool HeaderParserState::ReplaceForwardDeclarationsInStruct(StructDefinition* structDefinition) -{ - for (const auto& variable : structDefinition->m_members) - { - if (variable->m_type_declaration->m_type->GetType() == DataDefinitionType::FORWARD_DECLARATION) - variable->m_type_declaration->m_type = dynamic_cast<const ForwardDeclaration*>(variable->m_type_declaration->m_type)->m_definition; - } +bool HeaderParserState::ReplaceForwardDeclarationsInStruct(StructDefinition *structDefinition) { + for (const auto &variable : structDefinition->m_members) { + if (variable->m_type_declaration->m_type->GetType() == DataDefinitionType::FORWARD_DECLARATION) + variable->m_type_declaration->m_type = dynamic_cast<const ForwardDeclaration *>(variable->m_type_declaration->m_type)->m_definition; + } - return true; + return true; } -bool HeaderParserState::ReplaceForwardDeclarationsInTypedef(TypedefDefinition* typedefDefinition) -{ - if (typedefDefinition->m_type_declaration->m_type->GetType() == DataDefinitionType::FORWARD_DECLARATION) - typedefDefinition->m_type_declaration->m_type = dynamic_cast<const ForwardDeclaration*>(typedefDefinition->m_type_declaration->m_type)->m_definition; +bool HeaderParserState::ReplaceForwardDeclarationsInTypedef(TypedefDefinition *typedefDefinition) { + if (typedefDefinition->m_type_declaration->m_type->GetType() == DataDefinitionType::FORWARD_DECLARATION) + typedefDefinition->m_type_declaration->m_type = dynamic_cast<const ForwardDeclaration *>(typedefDefinition->m_type_declaration->m_type)->m_definition; - return true; + return true; } -bool HeaderParserState::ReplaceForwardDeclarationsInUnion(UnionDefinition* unionDefinition) -{ - for (const auto& variable : unionDefinition->m_members) - { - if (variable->m_type_declaration->m_type->GetType() == DataDefinitionType::FORWARD_DECLARATION) - variable->m_type_declaration->m_type = dynamic_cast<const ForwardDeclaration*>(variable->m_type_declaration->m_type)->m_definition; - } +bool HeaderParserState::ReplaceForwardDeclarationsInUnion(UnionDefinition *unionDefinition) { + for (const auto &variable : unionDefinition->m_members) { + if (variable->m_type_declaration->m_type->GetType() == DataDefinitionType::FORWARD_DECLARATION) + variable->m_type_declaration->m_type = dynamic_cast<const ForwardDeclaration *>(variable->m_type_declaration->m_type)->m_definition; + } - return true; + return true; } -bool HeaderParserState::ReplaceForwardDeclarationsInDefinitions() -{ - for (auto& definition : m_header_definitions) - { - switch (definition->GetType()) - { - case DataDefinitionType::STRUCT: - if (!ReplaceForwardDeclarationsInStruct(dynamic_cast<StructDefinition*>(definition.get()))) - return false; - break; - - case DataDefinitionType::TYPEDEF: - if (!ReplaceForwardDeclarationsInTypedef(dynamic_cast<TypedefDefinition*>(definition.get()))) - return false; - break; - - case DataDefinitionType::UNION: - if (!ReplaceForwardDeclarationsInUnion(dynamic_cast<UnionDefinition*>(definition.get()))) - return false; - break; - - default: - break; - } +bool HeaderParserState::ReplaceForwardDeclarationsInDefinitions() { + for (auto &definition : m_header_definitions) { + switch (definition->GetType()) { + case DataDefinitionType::STRUCT: + if (!ReplaceForwardDeclarationsInStruct(dynamic_cast<StructDefinition *>(definition.get()))) + return false; + break; + + case DataDefinitionType::TYPEDEF: + if (!ReplaceForwardDeclarationsInTypedef(dynamic_cast<TypedefDefinition *>(definition.get()))) + return false; + break; + + case DataDefinitionType::UNION: + if (!ReplaceForwardDeclarationsInUnion(dynamic_cast<UnionDefinition *>(definition.get()))) + return false; + break; + + default: + break; } + } - return true; + return true; } -bool HeaderParserState::MoveDefinitionsToRepository(IDataRepository* repository) -{ - for (auto& definition : m_header_definitions) - { - switch (definition->GetType()) - { - case DataDefinitionType::ENUM: - repository->Add(std::unique_ptr<EnumDefinition>(dynamic_cast<EnumDefinition*>(definition.release()))); - break; - - case DataDefinitionType::STRUCT: - repository->Add(std::unique_ptr<StructDefinition>(dynamic_cast<StructDefinition*>(definition.release()))); - break; - - case DataDefinitionType::UNION: - repository->Add(std::unique_ptr<UnionDefinition>(dynamic_cast<UnionDefinition*>(definition.release()))); - break; - - case DataDefinitionType::TYPEDEF: - repository->Add(std::unique_ptr<TypedefDefinition>(dynamic_cast<TypedefDefinition*>(definition.release()))); - break; - - default: - break; - } +bool HeaderParserState::MoveDefinitionsToRepository(IDataRepository *repository) { + for (auto &definition : m_header_definitions) { + switch (definition->GetType()) { + case DataDefinitionType::ENUM: + repository->Add(std::unique_ptr<EnumDefinition>(dynamic_cast<EnumDefinition *>(definition.release()))); + break; + + case DataDefinitionType::STRUCT: + repository->Add(std::unique_ptr<StructDefinition>(dynamic_cast<StructDefinition *>(definition.release()))); + break; + + case DataDefinitionType::UNION: + repository->Add(std::unique_ptr<UnionDefinition>(dynamic_cast<UnionDefinition *>(definition.release()))); + break; + + case DataDefinitionType::TYPEDEF: + repository->Add(std::unique_ptr<TypedefDefinition>(dynamic_cast<TypedefDefinition *>(definition.release()))); + break; + + default: + break; } + } - return true; + return true; } -bool HeaderParserState::SaveToRepository(IDataRepository* repository) -{ - return ResolveForwardDeclarations() - && ReplaceForwardDeclarationsInDefinitions() - && MoveDefinitionsToRepository(repository); +bool HeaderParserState::SaveToRepository(IDataRepository *repository) { + return ResolveForwardDeclarations() && ReplaceForwardDeclarationsInDefinitions() && MoveDefinitionsToRepository(repository); } diff --git a/src/ZoneCodeGeneratorLib/Parsing/Header/Impl/HeaderParserState.h b/src/ZoneCodeGeneratorLib/Parsing/Header/Impl/HeaderParserState.h index e0b6b4c94..e2efca987 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Header/Impl/HeaderParserState.h +++ b/src/ZoneCodeGeneratorLib/Parsing/Header/Impl/HeaderParserState.h @@ -4,50 +4,49 @@ #include <stack> #include <unordered_map> -#include "Utils/ClassUtils.h" #include "Domain/Definition/BaseTypeDefinition.h" #include "Domain/Definition/DataDefinition.h" #include "Domain/Definition/EnumMember.h" #include "Domain/Definition/ForwardDeclaration.h" -#include "Parsing/IPackValueSupplier.h" -#include "Utils/NamespaceBuilder.h" #include "Parsing/Header/Block/IHeaderBlock.h" +#include "Parsing/IPackValueSupplier.h" #include "Persistence/IDataRepository.h" +#include "Utils/ClassUtils.h" +#include "Utils/NamespaceBuilder.h" class IHeaderBlock; -class HeaderParserState -{ - std::vector<std::unique_ptr<DataDefinition>> m_header_definitions; +class HeaderParserState { + std::vector<std::unique_ptr<DataDefinition>> m_header_definitions; - std::stack<std::unique_ptr<IHeaderBlock>> m_blocks; - std::unordered_map<std::string, const DataDefinition*> m_definitions; - std::unordered_map<std::string, EnumMember*> m_enum_members; - std::unordered_map<std::string, std::unique_ptr<ForwardDeclaration>> m_forward_declarations; + std::stack<std::unique_ptr<IHeaderBlock>> m_blocks; + std::unordered_map<std::string, const DataDefinition *> m_definitions; + std::unordered_map<std::string, EnumMember *> m_enum_members; + std::unordered_map<std::string, std::unique_ptr<ForwardDeclaration>> m_forward_declarations; - void AddBaseDataType(const BaseTypeDefinition* baseType); - bool ResolveForwardDeclarations(); - static bool ReplaceForwardDeclarationsInStruct(StructDefinition* structDefinition); - static bool ReplaceForwardDeclarationsInTypedef(TypedefDefinition* typedefDefinition); - static bool ReplaceForwardDeclarationsInUnion(UnionDefinition* unionDefinition); - bool ReplaceForwardDeclarationsInDefinitions(); - bool MoveDefinitionsToRepository(IDataRepository* repository); + void AddBaseDataType(const BaseTypeDefinition *baseType); + bool ResolveForwardDeclarations(); + static bool ReplaceForwardDeclarationsInStruct(StructDefinition *structDefinition); + static bool ReplaceForwardDeclarationsInTypedef(TypedefDefinition *typedefDefinition); + static bool ReplaceForwardDeclarationsInUnion(UnionDefinition *unionDefinition); + bool ReplaceForwardDeclarationsInDefinitions(); + bool MoveDefinitionsToRepository(IDataRepository *repository); public: - const IPackValueSupplier* const m_pack_value_supplier; - NamespaceBuilder m_namespace; + const IPackValueSupplier *const m_pack_value_supplier; + NamespaceBuilder m_namespace; - explicit HeaderParserState(const IPackValueSupplier* packValueSupplier); + explicit HeaderParserState(const IPackValueSupplier *packValueSupplier); - _NODISCARD IHeaderBlock* GetBlock() const; - void PushBlock(std::unique_ptr<IHeaderBlock> block); - void PopBlock(); + _NODISCARD IHeaderBlock *GetBlock() const; + void PushBlock(std::unique_ptr<IHeaderBlock> block); + void PopBlock(); - void AddDataType(std::unique_ptr<DataDefinition> definition); - void AddForwardDeclaration(std::unique_ptr<ForwardDeclaration> forwardDeclaration); + void AddDataType(std::unique_ptr<DataDefinition> definition); + void AddForwardDeclaration(std::unique_ptr<ForwardDeclaration> forwardDeclaration); - const DataDefinition* FindType(const std::string& typeName); - EnumMember* FindEnumMember(const std::string& enumMemberName); + const DataDefinition *FindType(const std::string &typeName); + EnumMember *FindEnumMember(const std::string &enumMemberName); - bool SaveToRepository(IDataRepository* repository); + bool SaveToRepository(IDataRepository *repository); }; diff --git a/src/ZoneCodeGeneratorLib/Parsing/Header/Impl/HeaderParserValue.cpp b/src/ZoneCodeGeneratorLib/Parsing/Header/Impl/HeaderParserValue.cpp index c89068206..04e0c5af1 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Header/Impl/HeaderParserValue.cpp +++ b/src/ZoneCodeGeneratorLib/Parsing/Header/Impl/HeaderParserValue.cpp @@ -2,197 +2,154 @@ #include <cassert> -HeaderParserValue HeaderParserValue::Invalid(const TokenPos pos) -{ - HeaderParserValue pv(pos, HeaderParserValueType::INVALID); - return pv; +HeaderParserValue HeaderParserValue::Invalid(const TokenPos pos) { + HeaderParserValue pv(pos, HeaderParserValueType::INVALID); + return pv; } -HeaderParserValue HeaderParserValue::EndOfFile(const TokenPos pos) -{ - HeaderParserValue pv(pos, HeaderParserValueType::END_OF_FILE); - return pv; +HeaderParserValue HeaderParserValue::EndOfFile(const TokenPos pos) { + HeaderParserValue pv(pos, HeaderParserValueType::END_OF_FILE); + return pv; } -HeaderParserValue HeaderParserValue::Character(const TokenPos pos, const char c) -{ - HeaderParserValue pv(pos, HeaderParserValueType::CHARACTER); - pv.m_value.char_value = c; - return pv; +HeaderParserValue HeaderParserValue::Character(const TokenPos pos, const char c) { + HeaderParserValue pv(pos, HeaderParserValueType::CHARACTER); + pv.m_value.char_value = c; + return pv; } -HeaderParserValue HeaderParserValue::ShiftLeft(const TokenPos pos) -{ - HeaderParserValue pv(pos, HeaderParserValueType::SHIFT_LEFT); - return pv; +HeaderParserValue HeaderParserValue::ShiftLeft(const TokenPos pos) { + HeaderParserValue pv(pos, HeaderParserValueType::SHIFT_LEFT); + return pv; } -HeaderParserValue HeaderParserValue::ShiftRight(const TokenPos pos) -{ - HeaderParserValue pv(pos, HeaderParserValueType::SHIFT_RIGHT); - return pv; +HeaderParserValue HeaderParserValue::ShiftRight(const TokenPos pos) { + HeaderParserValue pv(pos, HeaderParserValueType::SHIFT_RIGHT); + return pv; } -HeaderParserValue HeaderParserValue::Equals(const TokenPos pos) -{ - HeaderParserValue pv(pos, HeaderParserValueType::EQUALS); - return pv; +HeaderParserValue HeaderParserValue::Equals(const TokenPos pos) { + HeaderParserValue pv(pos, HeaderParserValueType::EQUALS); + return pv; } -HeaderParserValue HeaderParserValue::NotEqual(const TokenPos pos) -{ - HeaderParserValue pv(pos, HeaderParserValueType::NOT_EQUAL); - return pv; +HeaderParserValue HeaderParserValue::NotEqual(const TokenPos pos) { + HeaderParserValue pv(pos, HeaderParserValueType::NOT_EQUAL); + return pv; } -HeaderParserValue HeaderParserValue::GreaterEqual(const TokenPos pos) -{ - HeaderParserValue pv(pos, HeaderParserValueType::GREATER_EQUAL); - return pv; +HeaderParserValue HeaderParserValue::GreaterEqual(const TokenPos pos) { + HeaderParserValue pv(pos, HeaderParserValueType::GREATER_EQUAL); + return pv; } -HeaderParserValue HeaderParserValue::LessEqual(const TokenPos pos) -{ - HeaderParserValue pv(pos, HeaderParserValueType::LESS_EQUAL); - return pv; +HeaderParserValue HeaderParserValue::LessEqual(const TokenPos pos) { + HeaderParserValue pv(pos, HeaderParserValueType::LESS_EQUAL); + return pv; } -HeaderParserValue HeaderParserValue::LogicalAnd(const TokenPos pos) -{ - HeaderParserValue pv(pos, HeaderParserValueType::LOGICAL_AND); - return pv; +HeaderParserValue HeaderParserValue::LogicalAnd(const TokenPos pos) { + HeaderParserValue pv(pos, HeaderParserValueType::LOGICAL_AND); + return pv; } -HeaderParserValue HeaderParserValue::LogicalOr(const TokenPos pos) -{ - HeaderParserValue pv(pos, HeaderParserValueType::LOGICAL_OR); - return pv; +HeaderParserValue HeaderParserValue::LogicalOr(const TokenPos pos) { + HeaderParserValue pv(pos, HeaderParserValueType::LOGICAL_OR); + return pv; } -HeaderParserValue HeaderParserValue::Integer(const TokenPos pos, const int value) -{ - HeaderParserValue pv(pos, HeaderParserValueType::INTEGER); - pv.m_value.int_value = value; - return pv; +HeaderParserValue HeaderParserValue::Integer(const TokenPos pos, const int value) { + HeaderParserValue pv(pos, HeaderParserValueType::INTEGER); + pv.m_value.int_value = value; + return pv; } -HeaderParserValue HeaderParserValue::FloatingPoint(const TokenPos pos, const double value) -{ - HeaderParserValue pv(pos, HeaderParserValueType::FLOATING_POINT); - pv.m_value.double_value = value; - return pv; +HeaderParserValue HeaderParserValue::FloatingPoint(const TokenPos pos, const double value) { + HeaderParserValue pv(pos, HeaderParserValueType::FLOATING_POINT); + pv.m_value.double_value = value; + return pv; } -HeaderParserValue HeaderParserValue::String(const TokenPos pos, std::string* stringValue) -{ - HeaderParserValue pv(pos, HeaderParserValueType::STRING); - pv.m_value.string_value = stringValue; - return pv; +HeaderParserValue HeaderParserValue::String(const TokenPos pos, std::string *stringValue) { + HeaderParserValue pv(pos, HeaderParserValueType::STRING); + pv.m_value.string_value = stringValue; + return pv; } -HeaderParserValue HeaderParserValue::Identifier(const TokenPos pos, std::string* identifier) -{ - HeaderParserValue pv(pos, HeaderParserValueType::IDENTIFIER); - pv.m_value.string_value = identifier; - return pv; +HeaderParserValue HeaderParserValue::Identifier(const TokenPos pos, std::string *identifier) { + HeaderParserValue pv(pos, HeaderParserValueType::IDENTIFIER); + pv.m_value.string_value = identifier; + return pv; } -HeaderParserValue HeaderParserValue::Keyword(const TokenPos pos, const HeaderParserValueType type) -{ - return HeaderParserValue(pos, type); -} +HeaderParserValue HeaderParserValue::Keyword(const TokenPos pos, const HeaderParserValueType type) { return HeaderParserValue(pos, type); } -HeaderParserValue HeaderParserValue::TypeName(const TokenPos pos, std::string* typeName) -{ - HeaderParserValue pv(pos, HeaderParserValueType::TYPE_NAME); - pv.m_value.string_value = typeName; - return pv; +HeaderParserValue HeaderParserValue::TypeName(const TokenPos pos, std::string *typeName) { + HeaderParserValue pv(pos, HeaderParserValueType::TYPE_NAME); + pv.m_value.string_value = typeName; + return pv; } -HeaderParserValue::HeaderParserValue(const TokenPos pos, const HeaderParserValueType type) - : m_pos(pos), - m_type(type), - m_value() -{ -} +HeaderParserValue::HeaderParserValue(const TokenPos pos, const HeaderParserValueType type) : m_pos(pos), m_type(type), m_value() {} -HeaderParserValue::~HeaderParserValue() -{ - switch (m_type) - { - case HeaderParserValueType::STRING: - case HeaderParserValueType::IDENTIFIER: - case HeaderParserValueType::TYPE_NAME: - delete m_value.string_value; - break; +HeaderParserValue::~HeaderParserValue() { + switch (m_type) { + case HeaderParserValueType::STRING: + case HeaderParserValueType::IDENTIFIER: + case HeaderParserValueType::TYPE_NAME: + delete m_value.string_value; + break; - default: - break; - } + default: + break; + } - m_value = ValueType(); + m_value = ValueType(); } -HeaderParserValue::HeaderParserValue(HeaderParserValue&& other) noexcept - : m_pos(other.m_pos), - m_type(other.m_type), - m_value(other.m_value) -{ - other.m_value = ValueType(); +HeaderParserValue::HeaderParserValue(HeaderParserValue &&other) noexcept : m_pos(other.m_pos), m_type(other.m_type), m_value(other.m_value) { + other.m_value = ValueType(); } -HeaderParserValue& HeaderParserValue::operator=(HeaderParserValue&& other) noexcept -{ - m_pos = other.m_pos; - m_type = other.m_type; - m_value = other.m_value; - other.m_value = ValueType(); +HeaderParserValue &HeaderParserValue::operator=(HeaderParserValue &&other) noexcept { + m_pos = other.m_pos; + m_type = other.m_type; + m_value = other.m_value; + other.m_value = ValueType(); - return *this; + return *this; } -bool HeaderParserValue::IsEof() const -{ - return m_type == HeaderParserValueType::END_OF_FILE; -} +bool HeaderParserValue::IsEof() const { return m_type == HeaderParserValueType::END_OF_FILE; } -const TokenPos& HeaderParserValue::GetPos() const -{ - return m_pos; -} +const TokenPos &HeaderParserValue::GetPos() const { return m_pos; } -char HeaderParserValue::CharacterValue() const -{ - assert(m_type == HeaderParserValueType::CHARACTER); - return m_value.char_value; +char HeaderParserValue::CharacterValue() const { + assert(m_type == HeaderParserValueType::CHARACTER); + return m_value.char_value; } -int HeaderParserValue::IntegerValue() const -{ - assert(m_type == HeaderParserValueType::INTEGER); - return m_value.int_value; +int HeaderParserValue::IntegerValue() const { + assert(m_type == HeaderParserValueType::INTEGER); + return m_value.int_value; } -double HeaderParserValue::FloatingPointValue() const -{ - assert(m_type == HeaderParserValueType::FLOATING_POINT); - return m_value.double_value; +double HeaderParserValue::FloatingPointValue() const { + assert(m_type == HeaderParserValueType::FLOATING_POINT); + return m_value.double_value; } -std::string& HeaderParserValue::StringValue() const -{ - assert(m_type == HeaderParserValueType::STRING); - return *m_value.string_value; +std::string &HeaderParserValue::StringValue() const { + assert(m_type == HeaderParserValueType::STRING); + return *m_value.string_value; } -std::string& HeaderParserValue::IdentifierValue() const -{ - assert(m_type == HeaderParserValueType::IDENTIFIER); - return *m_value.string_value; +std::string &HeaderParserValue::IdentifierValue() const { + assert(m_type == HeaderParserValueType::IDENTIFIER); + return *m_value.string_value; } -std::string& HeaderParserValue::TypeNameValue() const -{ - assert(m_type == HeaderParserValueType::TYPE_NAME); - return *m_value.string_value; +std::string &HeaderParserValue::TypeNameValue() const { + assert(m_type == HeaderParserValueType::TYPE_NAME); + return *m_value.string_value; } diff --git a/src/ZoneCodeGeneratorLib/Parsing/Header/Impl/HeaderParserValue.h b/src/ZoneCodeGeneratorLib/Parsing/Header/Impl/HeaderParserValue.h index d707c677b..de688a54c 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Header/Impl/HeaderParserValue.h +++ b/src/ZoneCodeGeneratorLib/Parsing/Header/Impl/HeaderParserValue.h @@ -3,109 +3,106 @@ #include <string> #include "Parsing/IParserValue.h" -#include "Utils/ClassUtils.h" #include "Parsing/TokenPos.h" +#include "Utils/ClassUtils.h" -enum class HeaderParserValueType -{ - // Meta tokens - INVALID, - END_OF_FILE, - - // Single character - CHARACTER, - - // Symbol tokens - SHIFT_LEFT, - SHIFT_RIGHT, - EQUALS, - NOT_EQUAL, - GREATER_EQUAL, - LESS_EQUAL, - LOGICAL_AND, - LOGICAL_OR, - - // Generic token types - INTEGER, - FLOATING_POINT, - STRING, - IDENTIFIER, - - // Built-in types - BUILT_IN_FIRST, - UNSIGNED = BUILT_IN_FIRST, - CHAR, - SHORT, - INT, - LONG, - BUILT_IN_LAST = LONG, - - // Keywords - DECLSPEC, - ALIGN, - ALIGNAS, - CONST, - ENUM, - NAMESPACE, - STRUCT, - TYPEDEF, - UNION, - - // Parser created - TYPE_NAME, - - // End - MAX +enum class HeaderParserValueType { + // Meta tokens + INVALID, + END_OF_FILE, + + // Single character + CHARACTER, + + // Symbol tokens + SHIFT_LEFT, + SHIFT_RIGHT, + EQUALS, + NOT_EQUAL, + GREATER_EQUAL, + LESS_EQUAL, + LOGICAL_AND, + LOGICAL_OR, + + // Generic token types + INTEGER, + FLOATING_POINT, + STRING, + IDENTIFIER, + + // Built-in types + BUILT_IN_FIRST, + UNSIGNED = BUILT_IN_FIRST, + CHAR, + SHORT, + INT, + LONG, + BUILT_IN_LAST = LONG, + + // Keywords + DECLSPEC, + ALIGN, + ALIGNAS, + CONST, + ENUM, + NAMESPACE, + STRUCT, + TYPEDEF, + UNION, + + // Parser created + TYPE_NAME, + + // End + MAX }; -class HeaderParserValue final : public IParserValue -{ +class HeaderParserValue final : public IParserValue { public: - TokenPos m_pos; - HeaderParserValueType m_type; - union ValueType - { - char char_value; - int int_value; - double double_value; - std::string* string_value; - } m_value; - - static HeaderParserValue Invalid(TokenPos pos); - static HeaderParserValue EndOfFile(TokenPos pos); - static HeaderParserValue Character(TokenPos pos, char c); - static HeaderParserValue ShiftLeft(TokenPos pos); - static HeaderParserValue ShiftRight(TokenPos pos); - static HeaderParserValue Equals(TokenPos pos); - static HeaderParserValue NotEqual(TokenPos pos); - static HeaderParserValue GreaterEqual(TokenPos pos); - static HeaderParserValue LessEqual(TokenPos pos); - static HeaderParserValue LogicalAnd(TokenPos pos); - static HeaderParserValue LogicalOr(TokenPos pos); - static HeaderParserValue Integer(TokenPos pos, int value); - static HeaderParserValue FloatingPoint(TokenPos pos, double value); - static HeaderParserValue String(TokenPos pos, std::string* stringValue); - static HeaderParserValue Identifier(TokenPos pos, std::string* identifier); - static HeaderParserValue Keyword(TokenPos pos, HeaderParserValueType type); - static HeaderParserValue TypeName(TokenPos pos, std::string* typeName); + TokenPos m_pos; + HeaderParserValueType m_type; + union ValueType { + char char_value; + int int_value; + double double_value; + std::string *string_value; + } m_value; + + static HeaderParserValue Invalid(TokenPos pos); + static HeaderParserValue EndOfFile(TokenPos pos); + static HeaderParserValue Character(TokenPos pos, char c); + static HeaderParserValue ShiftLeft(TokenPos pos); + static HeaderParserValue ShiftRight(TokenPos pos); + static HeaderParserValue Equals(TokenPos pos); + static HeaderParserValue NotEqual(TokenPos pos); + static HeaderParserValue GreaterEqual(TokenPos pos); + static HeaderParserValue LessEqual(TokenPos pos); + static HeaderParserValue LogicalAnd(TokenPos pos); + static HeaderParserValue LogicalOr(TokenPos pos); + static HeaderParserValue Integer(TokenPos pos, int value); + static HeaderParserValue FloatingPoint(TokenPos pos, double value); + static HeaderParserValue String(TokenPos pos, std::string *stringValue); + static HeaderParserValue Identifier(TokenPos pos, std::string *identifier); + static HeaderParserValue Keyword(TokenPos pos, HeaderParserValueType type); + static HeaderParserValue TypeName(TokenPos pos, std::string *typeName); private: - HeaderParserValue(TokenPos pos, HeaderParserValueType type); + HeaderParserValue(TokenPos pos, HeaderParserValueType type); public: - ~HeaderParserValue() override; - HeaderParserValue(const HeaderParserValue& other) = delete; - HeaderParserValue(HeaderParserValue&& other) noexcept; - HeaderParserValue& operator=(const HeaderParserValue& other) = delete; - HeaderParserValue& operator=(HeaderParserValue&& other) noexcept; - - _NODISCARD bool IsEof() const override; - _NODISCARD const TokenPos& GetPos() const override; - - _NODISCARD char CharacterValue() const; - _NODISCARD int IntegerValue() const; - _NODISCARD double FloatingPointValue() const; - _NODISCARD std::string& StringValue() const; - _NODISCARD std::string& IdentifierValue() const; - _NODISCARD std::string& TypeNameValue() const; + ~HeaderParserValue() override; + HeaderParserValue(const HeaderParserValue &other) = delete; + HeaderParserValue(HeaderParserValue &&other) noexcept; + HeaderParserValue &operator=(const HeaderParserValue &other) = delete; + HeaderParserValue &operator=(HeaderParserValue &&other) noexcept; + + _NODISCARD bool IsEof() const override; + _NODISCARD const TokenPos &GetPos() const override; + + _NODISCARD char CharacterValue() const; + _NODISCARD int IntegerValue() const; + _NODISCARD double FloatingPointValue() const; + _NODISCARD std::string &StringValue() const; + _NODISCARD std::string &IdentifierValue() const; + _NODISCARD std::string &TypeNameValue() const; }; \ No newline at end of file diff --git a/src/ZoneCodeGeneratorLib/Parsing/Header/Matcher/HeaderCommonMatchers.cpp b/src/ZoneCodeGeneratorLib/Parsing/Header/Matcher/HeaderCommonMatchers.cpp index 8e632fd31..588ded894 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Header/Matcher/HeaderCommonMatchers.cpp +++ b/src/ZoneCodeGeneratorLib/Parsing/Header/Matcher/HeaderCommonMatchers.cpp @@ -5,113 +5,67 @@ #include "HeaderMatcherFactory.h" -std::unique_ptr<HeaderCommonMatchers::matcher_t> HeaderCommonMatchers::Align(const supplier_t* labelSupplier) -{ - const HeaderMatcherFactory create(labelSupplier); +std::unique_ptr<HeaderCommonMatchers::matcher_t> HeaderCommonMatchers::Align(const supplier_t *labelSupplier) { + const HeaderMatcherFactory create(labelSupplier); - return create.Or({ - create.And({ - create.Type(HeaderParserValueType::DECLSPEC), - create.Char('('), - create.Type(HeaderParserValueType::ALIGN), - create.Char('('), - create.Integer(), - create.Char(')'), - create.Char(')') - }).Transform([](HeaderMatcherFactory::token_list_t& values) - { - return HeaderParserValue::Integer(values[4].get().GetPos(), values[4].get().IntegerValue()); - }), - create.And({ - create.Type(HeaderParserValueType::ALIGNAS), - create.Char('('), - create.Integer(), - create.Char(')') - }).Transform([](HeaderMatcherFactory::token_list_t& values) - { - return HeaderParserValue::Integer(values[2].get().GetPos(), values[2].get().IntegerValue()); - }) - }); + return create.Or({create + .And({create.Type(HeaderParserValueType::DECLSPEC), create.Char('('), create.Type(HeaderParserValueType::ALIGN), create.Char('('), + create.Integer(), create.Char(')'), create.Char(')')}) + .Transform([](HeaderMatcherFactory::token_list_t &values) { + return HeaderParserValue::Integer(values[4].get().GetPos(), values[4].get().IntegerValue()); + }), + create.And({create.Type(HeaderParserValueType::ALIGNAS), create.Char('('), create.Integer(), create.Char(')')}) + .Transform([](HeaderMatcherFactory::token_list_t &values) { + return HeaderParserValue::Integer(values[2].get().GetPos(), values[2].get().IntegerValue()); + })}); } -std::unique_ptr<HeaderCommonMatchers::matcher_t> HeaderCommonMatchers::ArrayDef(const supplier_t* labelSupplier) -{ - const HeaderMatcherFactory create(labelSupplier); +std::unique_ptr<HeaderCommonMatchers::matcher_t> HeaderCommonMatchers::ArrayDef(const supplier_t *labelSupplier) { + const HeaderMatcherFactory create(labelSupplier); - return create.And({ - create.Char('['), - create.Or({ - create.Integer(), - create.Identifier() - }), - create.Char(']') - }).Transform([](HeaderMatcherFactory::token_list_t& values) - { + return create.And({create.Char('['), create.Or({create.Integer(), create.Identifier()}), create.Char(']')}) + .Transform([](HeaderMatcherFactory::token_list_t &values) { if (values[1].get().m_type == HeaderParserValueType::INTEGER) - return HeaderParserValue::Integer(values[1].get().GetPos(), values[1].get().IntegerValue()); + return HeaderParserValue::Integer(values[1].get().GetPos(), values[1].get().IntegerValue()); return HeaderParserValue::Identifier(values[1].get().GetPos(), new std::string(values[1].get().IdentifierValue())); - }); + }); } -std::unique_ptr<HeaderCommonMatchers::matcher_t> HeaderCommonMatchers::Typename(const supplier_t* labelSupplier) -{ - static constexpr const char* BUILT_IN_TYPE_NAMES[] - { - "unsigned", - "char", - "short", - "int", - "long" - }; - static_assert(std::extent<decltype(BUILT_IN_TYPE_NAMES)>::value == static_cast<int>(HeaderParserValueType::BUILT_IN_LAST) - static_cast<int>(HeaderParserValueType::BUILT_IN_FIRST) + 1); +std::unique_ptr<HeaderCommonMatchers::matcher_t> HeaderCommonMatchers::Typename(const supplier_t *labelSupplier) { + static constexpr const char *BUILT_IN_TYPE_NAMES[]{"unsigned", "char", "short", "int", "long"}; + static_assert(std::extent<decltype(BUILT_IN_TYPE_NAMES)>::value == + static_cast<int>(HeaderParserValueType::BUILT_IN_LAST) - static_cast<int>(HeaderParserValueType::BUILT_IN_FIRST) + 1); - const HeaderMatcherFactory create(labelSupplier); + const HeaderMatcherFactory create(labelSupplier); - return create.Or({ - create.And({ - create.Optional(create.Type(HeaderParserValueType::UNSIGNED)), - create.Or({ - create.Type(HeaderParserValueType::CHAR), - create.Type(HeaderParserValueType::SHORT), - create.Type(HeaderParserValueType::INT), - create.And({ - create.Type(HeaderParserValueType::LONG), - create.Optional(create.Type(HeaderParserValueType::LONG)) - }) - }) - }).Transform([](HeaderMatcherFactory::token_list_t& values) - { - std::ostringstream str; - auto first = true; + return create.Or( + {create + .And({create.Optional(create.Type(HeaderParserValueType::UNSIGNED)), + create.Or({create.Type(HeaderParserValueType::CHAR), create.Type(HeaderParserValueType::SHORT), create.Type(HeaderParserValueType::INT), + create.And({create.Type(HeaderParserValueType::LONG), create.Optional(create.Type(HeaderParserValueType::LONG))})})}) + .Transform([](HeaderMatcherFactory::token_list_t &values) { + std::ostringstream str; + auto first = true; - for (const auto& token : values) - { - if (first) - first = false; - else - str << " "; - str << BUILT_IN_TYPE_NAMES[static_cast<int>(token.get().m_type) - static_cast<int>(HeaderParserValueType::BUILT_IN_FIRST)]; - } + for (const auto &token : values) { + if (first) + first = false; + else + str << " "; + str << BUILT_IN_TYPE_NAMES[static_cast<int>(token.get().m_type) - static_cast<int>(HeaderParserValueType::BUILT_IN_FIRST)]; + } - return HeaderParserValue::TypeName(values[0].get().GetPos(), new std::string(str.str())); - }), - create.And({ - create.Identifier(), - create.OptionalLoop(create.And({ - create.Char(':'), - create.Char(':'), - create.Identifier() - })) - }).Transform([](HeaderMatcherFactory::token_list_t& values) - { - std::ostringstream str; - str << values[0].get().IdentifierValue(); + return HeaderParserValue::TypeName(values[0].get().GetPos(), new std::string(str.str())); + }), + create.And({create.Identifier(), create.OptionalLoop(create.And({create.Char(':'), create.Char(':'), create.Identifier()}))}) + .Transform([](HeaderMatcherFactory::token_list_t &values) { + std::ostringstream str; + str << values[0].get().IdentifierValue(); - for (auto i = 3u; i < values.size(); i += 3) - str << "::" << values[i].get().IdentifierValue(); + for (auto i = 3u; i < values.size(); i += 3) + str << "::" << values[i].get().IdentifierValue(); - return HeaderParserValue::TypeName(values[0].get().GetPos(), new std::string(str.str())); - }) - }); + return HeaderParserValue::TypeName(values[0].get().GetPos(), new std::string(str.str())); + })}); } diff --git a/src/ZoneCodeGeneratorLib/Parsing/Header/Matcher/HeaderCommonMatchers.h b/src/ZoneCodeGeneratorLib/Parsing/Header/Matcher/HeaderCommonMatchers.h index 516bf4ce3..d3b07ff83 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Header/Matcher/HeaderCommonMatchers.h +++ b/src/ZoneCodeGeneratorLib/Parsing/Header/Matcher/HeaderCommonMatchers.h @@ -7,17 +7,16 @@ #include "Parsing/Matcher/AbstractMatcher.h" #include "Parsing/Matcher/MatcherLabel.h" -class HeaderCommonMatchers -{ +class HeaderCommonMatchers { public: - typedef AbstractMatcher<HeaderParserValue> matcher_t; - typedef IMatcherForLabelSupplier<HeaderParserValue> supplier_t; + typedef AbstractMatcher<HeaderParserValue> matcher_t; + typedef IMatcherForLabelSupplier<HeaderParserValue> supplier_t; - static constexpr int LABEL_ALIGN = std::numeric_limits<int>::max() - 1; - static constexpr int LABEL_ARRAY_DEF = std::numeric_limits<int>::max() - 2; - static constexpr int LABEL_TYPENAME = std::numeric_limits<int>::max() - 3; + static constexpr int LABEL_ALIGN = std::numeric_limits<int>::max() - 1; + static constexpr int LABEL_ARRAY_DEF = std::numeric_limits<int>::max() - 2; + static constexpr int LABEL_TYPENAME = std::numeric_limits<int>::max() - 3; - static std::unique_ptr<matcher_t> Align(const supplier_t* labelSupplier); - static std::unique_ptr<matcher_t> ArrayDef(const supplier_t* labelSupplier); - static std::unique_ptr<matcher_t> Typename(const supplier_t* labelSupplier); + static std::unique_ptr<matcher_t> Align(const supplier_t *labelSupplier); + static std::unique_ptr<matcher_t> ArrayDef(const supplier_t *labelSupplier); + static std::unique_ptr<matcher_t> Typename(const supplier_t *labelSupplier); }; diff --git a/src/ZoneCodeGeneratorLib/Parsing/Header/Matcher/HeaderMatcherCharacter.cpp b/src/ZoneCodeGeneratorLib/Parsing/Header/Matcher/HeaderMatcherCharacter.cpp index 8305a27c0..73b75e5ef 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Header/Matcher/HeaderMatcherCharacter.cpp +++ b/src/ZoneCodeGeneratorLib/Parsing/Header/Matcher/HeaderMatcherCharacter.cpp @@ -1,14 +1,9 @@ #include "HeaderMatcherCharacter.h" -HeaderMatcherCharacter::HeaderMatcherCharacter(const char c) - : m_char(c) -{ -} +HeaderMatcherCharacter::HeaderMatcherCharacter(const char c) : m_char(c) {} -MatcherResult<HeaderParserValue> HeaderMatcherCharacter::CanMatch(ILexer<HeaderParserValue>* lexer, const unsigned tokenOffset) -{ - const auto& token = lexer->GetToken(tokenOffset); - return token.m_type == HeaderParserValueType::CHARACTER && token.CharacterValue() == m_char - ? MatcherResult<HeaderParserValue>::Match(1) - : MatcherResult<HeaderParserValue>::NoMatch(); +MatcherResult<HeaderParserValue> HeaderMatcherCharacter::CanMatch(ILexer<HeaderParserValue> *lexer, const unsigned tokenOffset) { + const auto &token = lexer->GetToken(tokenOffset); + return token.m_type == HeaderParserValueType::CHARACTER && token.CharacterValue() == m_char ? MatcherResult<HeaderParserValue>::Match(1) + : MatcherResult<HeaderParserValue>::NoMatch(); } diff --git a/src/ZoneCodeGeneratorLib/Parsing/Header/Matcher/HeaderMatcherCharacter.h b/src/ZoneCodeGeneratorLib/Parsing/Header/Matcher/HeaderMatcherCharacter.h index 7f195e4d2..fbb5673a5 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Header/Matcher/HeaderMatcherCharacter.h +++ b/src/ZoneCodeGeneratorLib/Parsing/Header/Matcher/HeaderMatcherCharacter.h @@ -3,13 +3,12 @@ #include "Parsing/Header/Impl/HeaderParserValue.h" #include "Parsing/Matcher/AbstractMatcher.h" -class HeaderMatcherCharacter final : public AbstractMatcher<HeaderParserValue> -{ - char m_char; +class HeaderMatcherCharacter final : public AbstractMatcher<HeaderParserValue> { + char m_char; protected: - MatcherResult<HeaderParserValue> CanMatch(ILexer<HeaderParserValue>* lexer, unsigned tokenOffset) override; + MatcherResult<HeaderParserValue> CanMatch(ILexer<HeaderParserValue> *lexer, unsigned tokenOffset) override; public: - explicit HeaderMatcherCharacter(char c); + explicit HeaderMatcherCharacter(char c); }; diff --git a/src/ZoneCodeGeneratorLib/Parsing/Header/Matcher/HeaderMatcherFactory.cpp b/src/ZoneCodeGeneratorLib/Parsing/Header/Matcher/HeaderMatcherFactory.cpp index f00862bd4..64dfa5536 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Header/Matcher/HeaderMatcherFactory.cpp +++ b/src/ZoneCodeGeneratorLib/Parsing/Header/Matcher/HeaderMatcherFactory.cpp @@ -3,32 +3,24 @@ #include "HeaderMatcherCharacter.h" #include "HeaderMatcherValueType.h" -HeaderMatcherFactory::HeaderMatcherFactory(const IMatcherForLabelSupplier<HeaderParserValue>* labelSupplier) - : AbstractMatcherFactory(labelSupplier) -{ -} +HeaderMatcherFactory::HeaderMatcherFactory(const IMatcherForLabelSupplier<HeaderParserValue> *labelSupplier) : AbstractMatcherFactory(labelSupplier) {} -MatcherFactoryWrapper<HeaderParserValue> HeaderMatcherFactory::Type(HeaderParserValueType type) const -{ - return MatcherFactoryWrapper<HeaderParserValue>(std::make_unique<HeaderMatcherValueType>(type)); +MatcherFactoryWrapper<HeaderParserValue> HeaderMatcherFactory::Type(HeaderParserValueType type) const { + return MatcherFactoryWrapper<HeaderParserValue>(std::make_unique<HeaderMatcherValueType>(type)); } -MatcherFactoryWrapper<HeaderParserValue> HeaderMatcherFactory::Identifier() const -{ - return MatcherFactoryWrapper<HeaderParserValue>(std::make_unique<HeaderMatcherValueType>(HeaderParserValueType::IDENTIFIER)); +MatcherFactoryWrapper<HeaderParserValue> HeaderMatcherFactory::Identifier() const { + return MatcherFactoryWrapper<HeaderParserValue>(std::make_unique<HeaderMatcherValueType>(HeaderParserValueType::IDENTIFIER)); } -MatcherFactoryWrapper<HeaderParserValue> HeaderMatcherFactory::Integer() const -{ - return MatcherFactoryWrapper<HeaderParserValue>(std::make_unique<HeaderMatcherValueType>(HeaderParserValueType::INTEGER)); +MatcherFactoryWrapper<HeaderParserValue> HeaderMatcherFactory::Integer() const { + return MatcherFactoryWrapper<HeaderParserValue>(std::make_unique<HeaderMatcherValueType>(HeaderParserValueType::INTEGER)); } -MatcherFactoryWrapper<HeaderParserValue> HeaderMatcherFactory::FloatingPoint() const -{ - return MatcherFactoryWrapper<HeaderParserValue>(std::make_unique<HeaderMatcherValueType>(HeaderParserValueType::FLOATING_POINT)); +MatcherFactoryWrapper<HeaderParserValue> HeaderMatcherFactory::FloatingPoint() const { + return MatcherFactoryWrapper<HeaderParserValue>(std::make_unique<HeaderMatcherValueType>(HeaderParserValueType::FLOATING_POINT)); } -MatcherFactoryWrapper<HeaderParserValue> HeaderMatcherFactory::Char(char c) const -{ - return MatcherFactoryWrapper<HeaderParserValue>(std::make_unique<HeaderMatcherCharacter>(c)); +MatcherFactoryWrapper<HeaderParserValue> HeaderMatcherFactory::Char(char c) const { + return MatcherFactoryWrapper<HeaderParserValue>(std::make_unique<HeaderMatcherCharacter>(c)); } diff --git a/src/ZoneCodeGeneratorLib/Parsing/Header/Matcher/HeaderMatcherFactory.h b/src/ZoneCodeGeneratorLib/Parsing/Header/Matcher/HeaderMatcherFactory.h index 82fd80320..10d72dfe6 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Header/Matcher/HeaderMatcherFactory.h +++ b/src/ZoneCodeGeneratorLib/Parsing/Header/Matcher/HeaderMatcherFactory.h @@ -3,14 +3,13 @@ #include "Parsing/Header/Impl/HeaderParserValue.h" #include "Parsing/Matcher/AbstractMatcherFactory.h" -class HeaderMatcherFactory final : public AbstractMatcherFactory<HeaderParserValue> -{ +class HeaderMatcherFactory final : public AbstractMatcherFactory<HeaderParserValue> { public: - explicit HeaderMatcherFactory(const IMatcherForLabelSupplier<HeaderParserValue>* labelSupplier); + explicit HeaderMatcherFactory(const IMatcherForLabelSupplier<HeaderParserValue> *labelSupplier); - _NODISCARD MatcherFactoryWrapper<HeaderParserValue> Type(HeaderParserValueType type) const; - _NODISCARD MatcherFactoryWrapper<HeaderParserValue> Identifier() const; - _NODISCARD MatcherFactoryWrapper<HeaderParserValue> Integer() const; - _NODISCARD MatcherFactoryWrapper<HeaderParserValue> FloatingPoint() const; - _NODISCARD MatcherFactoryWrapper<HeaderParserValue> Char(char c) const; + _NODISCARD MatcherFactoryWrapper<HeaderParserValue> Type(HeaderParserValueType type) const; + _NODISCARD MatcherFactoryWrapper<HeaderParserValue> Identifier() const; + _NODISCARD MatcherFactoryWrapper<HeaderParserValue> Integer() const; + _NODISCARD MatcherFactoryWrapper<HeaderParserValue> FloatingPoint() const; + _NODISCARD MatcherFactoryWrapper<HeaderParserValue> Char(char c) const; }; diff --git a/src/ZoneCodeGeneratorLib/Parsing/Header/Matcher/HeaderMatcherValueType.cpp b/src/ZoneCodeGeneratorLib/Parsing/Header/Matcher/HeaderMatcherValueType.cpp index a37c8eb2f..dea9c0503 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Header/Matcher/HeaderMatcherValueType.cpp +++ b/src/ZoneCodeGeneratorLib/Parsing/Header/Matcher/HeaderMatcherValueType.cpp @@ -1,13 +1,7 @@ #include "HeaderMatcherValueType.h" -HeaderMatcherValueType::HeaderMatcherValueType(HeaderParserValueType type) - : m_type(type) -{ -} +HeaderMatcherValueType::HeaderMatcherValueType(HeaderParserValueType type) : m_type(type) {} -MatcherResult<HeaderParserValue> HeaderMatcherValueType::CanMatch(ILexer<HeaderParserValue>* lexer, const unsigned tokenOffset) -{ - return lexer->GetToken(tokenOffset).m_type == m_type - ? MatcherResult<HeaderParserValue>::Match(1) - : MatcherResult<HeaderParserValue>::NoMatch(); +MatcherResult<HeaderParserValue> HeaderMatcherValueType::CanMatch(ILexer<HeaderParserValue> *lexer, const unsigned tokenOffset) { + return lexer->GetToken(tokenOffset).m_type == m_type ? MatcherResult<HeaderParserValue>::Match(1) : MatcherResult<HeaderParserValue>::NoMatch(); } diff --git a/src/ZoneCodeGeneratorLib/Parsing/Header/Matcher/HeaderMatcherValueType.h b/src/ZoneCodeGeneratorLib/Parsing/Header/Matcher/HeaderMatcherValueType.h index 5b9571f9a..a7ab0d917 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Header/Matcher/HeaderMatcherValueType.h +++ b/src/ZoneCodeGeneratorLib/Parsing/Header/Matcher/HeaderMatcherValueType.h @@ -3,13 +3,12 @@ #include "Parsing/Header/Impl/HeaderParserValue.h" #include "Parsing/Matcher/AbstractMatcher.h" -class HeaderMatcherValueType final : public AbstractMatcher<HeaderParserValue> -{ - HeaderParserValueType m_type; +class HeaderMatcherValueType final : public AbstractMatcher<HeaderParserValue> { + HeaderParserValueType m_type; protected: - MatcherResult<HeaderParserValue> CanMatch(ILexer<HeaderParserValue>* lexer, unsigned tokenOffset) override; + MatcherResult<HeaderParserValue> CanMatch(ILexer<HeaderParserValue> *lexer, unsigned tokenOffset) override; public: - explicit HeaderMatcherValueType(HeaderParserValueType type); + explicit HeaderMatcherValueType(HeaderParserValueType type); }; diff --git a/src/ZoneCodeGeneratorLib/Parsing/Header/Sequence/SequenceCloseBlock.cpp b/src/ZoneCodeGeneratorLib/Parsing/Header/Sequence/SequenceCloseBlock.cpp index 84718444e..c7880bdb9 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Header/Sequence/SequenceCloseBlock.cpp +++ b/src/ZoneCodeGeneratorLib/Parsing/Header/Sequence/SequenceCloseBlock.cpp @@ -1,46 +1,34 @@ #include "SequenceCloseBlock.h" #include "Parsing/Header/Block/IHeaderBlockNameHolder.h" -#include "Parsing/Header/Matcher/HeaderMatcherFactory.h" #include "Parsing/Header/Matcher/HeaderCommonMatchers.h" +#include "Parsing/Header/Matcher/HeaderMatcherFactory.h" -SequenceCloseBlock::SequenceCloseBlock(const bool semicolonRequired) - : m_semicolon_required(semicolonRequired) -{ - const HeaderMatcherFactory create(this); - - AddMatchers({ - create.Char('}').Capture(CAPTURE_CLOSING_PARENTHESIS), - create.Optional(create.And({ - create.Optional(create.Identifier().Capture(CAPTURE_NAME)), - create.Char(';').Tag(TAG_SEMICOLON) - })) - }); +SequenceCloseBlock::SequenceCloseBlock(const bool semicolonRequired) : m_semicolon_required(semicolonRequired) { + const HeaderMatcherFactory create(this); + + AddMatchers({create.Char('}').Capture(CAPTURE_CLOSING_PARENTHESIS), + create.Optional(create.And({create.Optional(create.Identifier().Capture(CAPTURE_NAME)), create.Char(';').Tag(TAG_SEMICOLON)}))}); } -void SequenceCloseBlock::ProcessMatch(HeaderParserState* state, SequenceResult<HeaderParserValue>& result) const -{ - if (result.NextTag() == TAG_SEMICOLON) - { - if (!m_semicolon_required) - throw ParsingException(result.NextCapture(CAPTURE_CLOSING_PARENTHESIS).GetPos(), "Block should not be closed with semicolon"); - } - else - { - if (m_semicolon_required) - throw ParsingException(result.NextCapture(CAPTURE_CLOSING_PARENTHESIS).GetPos(), "Block must be closed with semicolon"); - } - - if (result.HasNextCapture(CAPTURE_NAME)) - { - auto* variableDefiningBlock = dynamic_cast<IHeaderBlockNameHolder*>(state->GetBlock()); - const auto& name = result.NextCapture(CAPTURE_NAME); - - if (variableDefiningBlock == nullptr) - throw ParsingException(name.GetPos(), "Block does not support holding names."); - - variableDefiningBlock->SetBlockName(name.GetPos(), name.IdentifierValue()); - } - - state->PopBlock(); +void SequenceCloseBlock::ProcessMatch(HeaderParserState *state, SequenceResult<HeaderParserValue> &result) const { + if (result.NextTag() == TAG_SEMICOLON) { + if (!m_semicolon_required) + throw ParsingException(result.NextCapture(CAPTURE_CLOSING_PARENTHESIS).GetPos(), "Block should not be closed with semicolon"); + } else { + if (m_semicolon_required) + throw ParsingException(result.NextCapture(CAPTURE_CLOSING_PARENTHESIS).GetPos(), "Block must be closed with semicolon"); + } + + if (result.HasNextCapture(CAPTURE_NAME)) { + auto *variableDefiningBlock = dynamic_cast<IHeaderBlockNameHolder *>(state->GetBlock()); + const auto &name = result.NextCapture(CAPTURE_NAME); + + if (variableDefiningBlock == nullptr) + throw ParsingException(name.GetPos(), "Block does not support holding names."); + + variableDefiningBlock->SetBlockName(name.GetPos(), name.IdentifierValue()); + } + + state->PopBlock(); } diff --git a/src/ZoneCodeGeneratorLib/Parsing/Header/Sequence/SequenceCloseBlock.h b/src/ZoneCodeGeneratorLib/Parsing/Header/Sequence/SequenceCloseBlock.h index 1376dccc6..368b4133c 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Header/Sequence/SequenceCloseBlock.h +++ b/src/ZoneCodeGeneratorLib/Parsing/Header/Sequence/SequenceCloseBlock.h @@ -1,22 +1,21 @@ #pragma once #include "Parsing/Header/Impl/HeaderParser.h" -#include "Parsing/Sequence/AbstractSequence.h" #include "Parsing/Header/Impl/HeaderParserState.h" #include "Parsing/Header/Impl/HeaderParserValue.h" +#include "Parsing/Sequence/AbstractSequence.h" -class SequenceCloseBlock final : public HeaderParser::sequence_t -{ - static constexpr auto TAG_SEMICOLON = 1; +class SequenceCloseBlock final : public HeaderParser::sequence_t { + static constexpr auto TAG_SEMICOLON = 1; - static constexpr auto CAPTURE_NAME = 1; - static constexpr auto CAPTURE_CLOSING_PARENTHESIS = 2; + static constexpr auto CAPTURE_NAME = 1; + static constexpr auto CAPTURE_CLOSING_PARENTHESIS = 2; - bool m_semicolon_required; + bool m_semicolon_required; protected: - void ProcessMatch(HeaderParserState* state, SequenceResult<HeaderParserValue>& result) const override; + void ProcessMatch(HeaderParserState *state, SequenceResult<HeaderParserValue> &result) const override; public: - explicit SequenceCloseBlock(bool semicolonRequired); + explicit SequenceCloseBlock(bool semicolonRequired); }; diff --git a/src/ZoneCodeGeneratorLib/Parsing/Header/Sequence/SequenceEnum.cpp b/src/ZoneCodeGeneratorLib/Parsing/Header/Sequence/SequenceEnum.cpp index c60704c68..b5f741d78 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Header/Sequence/SequenceEnum.cpp +++ b/src/ZoneCodeGeneratorLib/Parsing/Header/Sequence/SequenceEnum.cpp @@ -1,51 +1,42 @@ #include "SequenceEnum.h" #include "Parsing/Header/Block/HeaderBlockEnum.h" -#include "Parsing/Header/Matcher/HeaderMatcherFactory.h" #include "Parsing/Header/Matcher/HeaderCommonMatchers.h" +#include "Parsing/Header/Matcher/HeaderMatcherFactory.h" + +SequenceEnum::SequenceEnum() { + const HeaderMatcherFactory create(this); -SequenceEnum::SequenceEnum() -{ - const HeaderMatcherFactory create(this); - - AddLabeledMatchers(HeaderCommonMatchers::Typename(this), HeaderCommonMatchers::LABEL_TYPENAME); - AddMatchers({ - create.Optional(create.Type(HeaderParserValueType::TYPEDEF).Tag(TAG_TYPEDEF)), - create.Type(HeaderParserValueType::ENUM), - create.Optional(create.Identifier().Capture(CAPTURE_NAME)), - create.Optional(create.And({ - create.Char(':'), - create.Label(HeaderCommonMatchers::LABEL_TYPENAME).Capture(CAPTURE_PARENT_TYPE) - })), - create.Char('{') - }); + AddLabeledMatchers(HeaderCommonMatchers::Typename(this), HeaderCommonMatchers::LABEL_TYPENAME); + AddMatchers({create.Optional(create.Type(HeaderParserValueType::TYPEDEF).Tag(TAG_TYPEDEF)), create.Type(HeaderParserValueType::ENUM), + create.Optional(create.Identifier().Capture(CAPTURE_NAME)), + create.Optional(create.And({create.Char(':'), create.Label(HeaderCommonMatchers::LABEL_TYPENAME).Capture(CAPTURE_PARENT_TYPE)})), + create.Char('{')}); } -void SequenceEnum::ProcessMatch(HeaderParserState* state, SequenceResult<HeaderParserValue>& result) const -{ - auto isTypedef = result.PeekAndRemoveIfTag(TAG_TYPEDEF) == TAG_TYPEDEF; - std::string name; - const auto* parentType = BaseTypeDefinition::INT; +void SequenceEnum::ProcessMatch(HeaderParserState *state, SequenceResult<HeaderParserValue> &result) const { + auto isTypedef = result.PeekAndRemoveIfTag(TAG_TYPEDEF) == TAG_TYPEDEF; + std::string name; + const auto *parentType = BaseTypeDefinition::INT; - if (result.HasNextCapture(CAPTURE_NAME)) - name = result.NextCapture(CAPTURE_NAME).IdentifierValue(); + if (result.HasNextCapture(CAPTURE_NAME)) + name = result.NextCapture(CAPTURE_NAME).IdentifierValue(); - if(result.HasNextCapture(CAPTURE_PARENT_TYPE)) - { - const auto& typeNameToken = result.NextCapture(CAPTURE_PARENT_TYPE); - const auto* foundTypeDefinition = state->FindType(typeNameToken.TypeNameValue()); + if (result.HasNextCapture(CAPTURE_PARENT_TYPE)) { + const auto &typeNameToken = result.NextCapture(CAPTURE_PARENT_TYPE); + const auto *foundTypeDefinition = state->FindType(typeNameToken.TypeNameValue()); - if (foundTypeDefinition == nullptr) - throw ParsingException(typeNameToken.GetPos(), "Cannot find type"); + if (foundTypeDefinition == nullptr) + throw ParsingException(typeNameToken.GetPos(), "Cannot find type"); - while (foundTypeDefinition->GetType() == DataDefinitionType::TYPEDEF) - foundTypeDefinition = dynamic_cast<const TypedefDefinition*>(foundTypeDefinition)->m_type_declaration->m_type; + while (foundTypeDefinition->GetType() == DataDefinitionType::TYPEDEF) + foundTypeDefinition = dynamic_cast<const TypedefDefinition *>(foundTypeDefinition)->m_type_declaration->m_type; - if (foundTypeDefinition->GetType() != DataDefinitionType::BASE_TYPE) - throw ParsingException(typeNameToken.GetPos(), "Enums can only have base types as parent type"); + if (foundTypeDefinition->GetType() != DataDefinitionType::BASE_TYPE) + throw ParsingException(typeNameToken.GetPos(), "Enums can only have base types as parent type"); - parentType = dynamic_cast<const BaseTypeDefinition*>(foundTypeDefinition); - } + parentType = dynamic_cast<const BaseTypeDefinition *>(foundTypeDefinition); + } - state->PushBlock(std::make_unique<HeaderBlockEnum>(name, parentType, isTypedef)); + state->PushBlock(std::make_unique<HeaderBlockEnum>(name, parentType, isTypedef)); } diff --git a/src/ZoneCodeGeneratorLib/Parsing/Header/Sequence/SequenceEnum.h b/src/ZoneCodeGeneratorLib/Parsing/Header/Sequence/SequenceEnum.h index 93f1641dc..7109f3928 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Header/Sequence/SequenceEnum.h +++ b/src/ZoneCodeGeneratorLib/Parsing/Header/Sequence/SequenceEnum.h @@ -1,20 +1,19 @@ #pragma once #include "Parsing/Header/Impl/HeaderParser.h" -#include "Parsing/Sequence/AbstractSequence.h" #include "Parsing/Header/Impl/HeaderParserState.h" #include "Parsing/Header/Impl/HeaderParserValue.h" +#include "Parsing/Sequence/AbstractSequence.h" -class SequenceEnum final : public HeaderParser::sequence_t -{ - static constexpr auto TAG_TYPEDEF = 1; +class SequenceEnum final : public HeaderParser::sequence_t { + static constexpr auto TAG_TYPEDEF = 1; - static constexpr auto CAPTURE_NAME = 1; - static constexpr auto CAPTURE_PARENT_TYPE = 2; + static constexpr auto CAPTURE_NAME = 1; + static constexpr auto CAPTURE_PARENT_TYPE = 2; protected: - void ProcessMatch(HeaderParserState* state, SequenceResult<HeaderParserValue>& result) const override; + void ProcessMatch(HeaderParserState *state, SequenceResult<HeaderParserValue> &result) const override; public: - SequenceEnum(); + SequenceEnum(); }; diff --git a/src/ZoneCodeGeneratorLib/Parsing/Header/Sequence/SequenceEnumMember.cpp b/src/ZoneCodeGeneratorLib/Parsing/Header/Sequence/SequenceEnumMember.cpp index ca482b589..202316e4f 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Header/Sequence/SequenceEnumMember.cpp +++ b/src/ZoneCodeGeneratorLib/Parsing/Header/Sequence/SequenceEnumMember.cpp @@ -1,58 +1,40 @@ #include "SequenceEnumMember.h" #include "Parsing/Header/Block/HeaderBlockEnum.h" -#include "Parsing/Header/Matcher/HeaderMatcherFactory.h" #include "Parsing/Header/Matcher/HeaderCommonMatchers.h" +#include "Parsing/Header/Matcher/HeaderMatcherFactory.h" -SequenceEnumMember::SequenceEnumMember() -{ - const HeaderMatcherFactory create(this); - - AddMatchers({ - create.Identifier().Capture(CAPTURE_NAME), - create.Optional(create.And({ - create.Char('='), - create.Or({ - create.Identifier().Capture(CAPTURE_VALUE), - create.Integer().Capture(CAPTURE_VALUE) - }) - })), - create.Or({ - create.Char(','), - create.Char('}').NoConsume() - }) - }); +SequenceEnumMember::SequenceEnumMember() { + const HeaderMatcherFactory create(this); + + AddMatchers( + {create.Identifier().Capture(CAPTURE_NAME), + create.Optional(create.And({create.Char('='), create.Or({create.Identifier().Capture(CAPTURE_VALUE), create.Integer().Capture(CAPTURE_VALUE)})})), + create.Or({create.Char(','), create.Char('}').NoConsume()})}); } -void SequenceEnumMember::ProcessMatch(HeaderParserState* state, SequenceResult<HeaderParserValue>& result) const -{ - int value; - auto* enumBlock = dynamic_cast<HeaderBlockEnum*>(state->GetBlock()); - - if (result.HasNextCapture(CAPTURE_VALUE)) - { - const auto& valueToken = result.NextCapture(CAPTURE_VALUE); - if (valueToken.m_type == HeaderParserValueType::IDENTIFIER) - { - auto* enumMember = enumBlock->GetEnumMember(valueToken.IdentifierValue()); - - if (enumMember == nullptr) - enumMember = state->FindEnumMember(valueToken.IdentifierValue()); - - if (enumMember == nullptr) - throw ParsingException(valueToken.GetPos(), "Could not find enum member with specified name"); - - value = enumMember->m_value; - } - else - { - value = valueToken.IntegerValue(); - } - } - else - { - value = enumBlock->GetNextEnumMemberValue(); +void SequenceEnumMember::ProcessMatch(HeaderParserState *state, SequenceResult<HeaderParserValue> &result) const { + int value; + auto *enumBlock = dynamic_cast<HeaderBlockEnum *>(state->GetBlock()); + + if (result.HasNextCapture(CAPTURE_VALUE)) { + const auto &valueToken = result.NextCapture(CAPTURE_VALUE); + if (valueToken.m_type == HeaderParserValueType::IDENTIFIER) { + auto *enumMember = enumBlock->GetEnumMember(valueToken.IdentifierValue()); + + if (enumMember == nullptr) + enumMember = state->FindEnumMember(valueToken.IdentifierValue()); + + if (enumMember == nullptr) + throw ParsingException(valueToken.GetPos(), "Could not find enum member with specified name"); + + value = enumMember->m_value; + } else { + value = valueToken.IntegerValue(); } + } else { + value = enumBlock->GetNextEnumMemberValue(); + } - enumBlock->AddEnumMember(std::make_unique<EnumMember>(result.NextCapture(CAPTURE_NAME).IdentifierValue(), value)); + enumBlock->AddEnumMember(std::make_unique<EnumMember>(result.NextCapture(CAPTURE_NAME).IdentifierValue(), value)); } diff --git a/src/ZoneCodeGeneratorLib/Parsing/Header/Sequence/SequenceEnumMember.h b/src/ZoneCodeGeneratorLib/Parsing/Header/Sequence/SequenceEnumMember.h index bd039d734..25efc10f0 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Header/Sequence/SequenceEnumMember.h +++ b/src/ZoneCodeGeneratorLib/Parsing/Header/Sequence/SequenceEnumMember.h @@ -1,18 +1,17 @@ #pragma once #include "Parsing/Header/Impl/HeaderParser.h" -#include "Parsing/Sequence/AbstractSequence.h" #include "Parsing/Header/Impl/HeaderParserState.h" #include "Parsing/Header/Impl/HeaderParserValue.h" +#include "Parsing/Sequence/AbstractSequence.h" -class SequenceEnumMember final : public HeaderParser::sequence_t -{ - static constexpr auto CAPTURE_NAME = 1; - static constexpr auto CAPTURE_VALUE = 2; +class SequenceEnumMember final : public HeaderParser::sequence_t { + static constexpr auto CAPTURE_NAME = 1; + static constexpr auto CAPTURE_VALUE = 2; protected: - void ProcessMatch(HeaderParserState* state, SequenceResult<HeaderParserValue>& result) const override; + void ProcessMatch(HeaderParserState *state, SequenceResult<HeaderParserValue> &result) const override; public: - SequenceEnumMember(); + SequenceEnumMember(); }; diff --git a/src/ZoneCodeGeneratorLib/Parsing/Header/Sequence/SequenceForwardDecl.cpp b/src/ZoneCodeGeneratorLib/Parsing/Header/Sequence/SequenceForwardDecl.cpp index 77dc1b60e..f0005684c 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Header/Sequence/SequenceForwardDecl.cpp +++ b/src/ZoneCodeGeneratorLib/Parsing/Header/Sequence/SequenceForwardDecl.cpp @@ -1,45 +1,38 @@ #include "SequenceForwardDecl.h" -#include "Parsing/Header/Matcher/HeaderMatcherFactory.h" #include "Parsing/Header/Matcher/HeaderCommonMatchers.h" +#include "Parsing/Header/Matcher/HeaderMatcherFactory.h" + +SequenceForwardDecl::SequenceForwardDecl() { + const HeaderMatcherFactory create(this); -SequenceForwardDecl::SequenceForwardDecl() -{ - const HeaderMatcherFactory create(this); - - AddMatchers({ - create.Or({ - create.Type(HeaderParserValueType::ENUM).Tag(TAG_ENUM), - create.Type(HeaderParserValueType::STRUCT).Tag(TAG_STRUCT), - create.Type(HeaderParserValueType::UNION).Tag(TAG_UNION) - }).Capture(CAPTURE_TYPE), - create.Identifier().Capture(CAPTURE_NAME), - create.Char(';') - }); + AddMatchers({create + .Or({create.Type(HeaderParserValueType::ENUM).Tag(TAG_ENUM), create.Type(HeaderParserValueType::STRUCT).Tag(TAG_STRUCT), + create.Type(HeaderParserValueType::UNION).Tag(TAG_UNION)}) + .Capture(CAPTURE_TYPE), + create.Identifier().Capture(CAPTURE_NAME), create.Char(';')}); } -void SequenceForwardDecl::ProcessMatch(HeaderParserState* state, SequenceResult<HeaderParserValue>& result) const -{ - const auto typeTag = result.NextTag(); - DataDefinitionType type; +void SequenceForwardDecl::ProcessMatch(HeaderParserState *state, SequenceResult<HeaderParserValue> &result) const { + const auto typeTag = result.NextTag(); + DataDefinitionType type; - switch(typeTag) - { - case TAG_ENUM: - type = DataDefinitionType::ENUM; - break; + switch (typeTag) { + case TAG_ENUM: + type = DataDefinitionType::ENUM; + break; - case TAG_STRUCT: - type = DataDefinitionType::STRUCT; - break; + case TAG_STRUCT: + type = DataDefinitionType::STRUCT; + break; - case TAG_UNION: - type = DataDefinitionType::UNION; - break; + case TAG_UNION: + type = DataDefinitionType::UNION; + break; - default: - throw ParsingException(result.NextCapture(CAPTURE_TYPE).GetPos(), "Unknown type"); - } + default: + throw ParsingException(result.NextCapture(CAPTURE_TYPE).GetPos(), "Unknown type"); + } - state->AddForwardDeclaration(std::make_unique<ForwardDeclaration>(state->m_namespace.ToString(), result.NextCapture(CAPTURE_NAME).IdentifierValue(), type)); + state->AddForwardDeclaration(std::make_unique<ForwardDeclaration>(state->m_namespace.ToString(), result.NextCapture(CAPTURE_NAME).IdentifierValue(), type)); } diff --git a/src/ZoneCodeGeneratorLib/Parsing/Header/Sequence/SequenceForwardDecl.h b/src/ZoneCodeGeneratorLib/Parsing/Header/Sequence/SequenceForwardDecl.h index 44304de2c..041057946 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Header/Sequence/SequenceForwardDecl.h +++ b/src/ZoneCodeGeneratorLib/Parsing/Header/Sequence/SequenceForwardDecl.h @@ -1,22 +1,21 @@ #pragma once #include "Parsing/Header/Impl/HeaderParser.h" -#include "Parsing/Sequence/AbstractSequence.h" #include "Parsing/Header/Impl/HeaderParserState.h" #include "Parsing/Header/Impl/HeaderParserValue.h" +#include "Parsing/Sequence/AbstractSequence.h" -class SequenceForwardDecl final : public HeaderParser::sequence_t -{ - static constexpr auto TAG_ENUM = 1; - static constexpr auto TAG_STRUCT = 2; - static constexpr auto TAG_UNION = 3; +class SequenceForwardDecl final : public HeaderParser::sequence_t { + static constexpr auto TAG_ENUM = 1; + static constexpr auto TAG_STRUCT = 2; + static constexpr auto TAG_UNION = 3; - static constexpr auto CAPTURE_TYPE = 1; - static constexpr auto CAPTURE_NAME = 2; + static constexpr auto CAPTURE_TYPE = 1; + static constexpr auto CAPTURE_NAME = 2; protected: - void ProcessMatch(HeaderParserState* state, SequenceResult<HeaderParserValue>& result) const override; + void ProcessMatch(HeaderParserState *state, SequenceResult<HeaderParserValue> &result) const override; public: - SequenceForwardDecl(); + SequenceForwardDecl(); }; diff --git a/src/ZoneCodeGeneratorLib/Parsing/Header/Sequence/SequenceNamespace.cpp b/src/ZoneCodeGeneratorLib/Parsing/Header/Sequence/SequenceNamespace.cpp index 261293924..bf5813043 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Header/Sequence/SequenceNamespace.cpp +++ b/src/ZoneCodeGeneratorLib/Parsing/Header/Sequence/SequenceNamespace.cpp @@ -1,22 +1,15 @@ #include "SequenceNamespace.h" - #include "Parsing/Header/Block/HeaderBlockNamespace.h" #include "Parsing/Header/Matcher/HeaderMatcherFactory.h" -SequenceNamespace::SequenceNamespace() -{ - const HeaderMatcherFactory create(this); +SequenceNamespace::SequenceNamespace() { + const HeaderMatcherFactory create(this); - AddMatchers({ - create.Type(HeaderParserValueType::NAMESPACE), - create.Type(HeaderParserValueType::IDENTIFIER).Capture(CAPTURE_NAME), - create.Char('{') - }); + AddMatchers({create.Type(HeaderParserValueType::NAMESPACE), create.Type(HeaderParserValueType::IDENTIFIER).Capture(CAPTURE_NAME), create.Char('{')}); } -void SequenceNamespace::ProcessMatch(HeaderParserState* state, SequenceResult<HeaderParserValue>& result) const -{ - assert(result.HasNextCapture(CAPTURE_NAME)); - state->PushBlock(std::make_unique<HeaderBlockNamespace>(result.NextCapture(CAPTURE_NAME).IdentifierValue())); +void SequenceNamespace::ProcessMatch(HeaderParserState *state, SequenceResult<HeaderParserValue> &result) const { + assert(result.HasNextCapture(CAPTURE_NAME)); + state->PushBlock(std::make_unique<HeaderBlockNamespace>(result.NextCapture(CAPTURE_NAME).IdentifierValue())); } diff --git a/src/ZoneCodeGeneratorLib/Parsing/Header/Sequence/SequenceNamespace.h b/src/ZoneCodeGeneratorLib/Parsing/Header/Sequence/SequenceNamespace.h index a3d7793a9..893838c0b 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Header/Sequence/SequenceNamespace.h +++ b/src/ZoneCodeGeneratorLib/Parsing/Header/Sequence/SequenceNamespace.h @@ -1,17 +1,16 @@ #pragma once #include "Parsing/Header/Impl/HeaderParser.h" -#include "Parsing/Sequence/AbstractSequence.h" #include "Parsing/Header/Impl/HeaderParserState.h" #include "Parsing/Header/Impl/HeaderParserValue.h" +#include "Parsing/Sequence/AbstractSequence.h" -class SequenceNamespace final : public HeaderParser::sequence_t -{ - static constexpr int CAPTURE_NAME = 0; +class SequenceNamespace final : public HeaderParser::sequence_t { + static constexpr int CAPTURE_NAME = 0; protected: - void ProcessMatch(HeaderParserState* state, SequenceResult<HeaderParserValue>& result) const override; + void ProcessMatch(HeaderParserState *state, SequenceResult<HeaderParserValue> &result) const override; public: - SequenceNamespace(); + SequenceNamespace(); }; diff --git a/src/ZoneCodeGeneratorLib/Parsing/Header/Sequence/SequenceStruct.cpp b/src/ZoneCodeGeneratorLib/Parsing/Header/Sequence/SequenceStruct.cpp index 1a89ee042..e45b3b3bb 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Header/Sequence/SequenceStruct.cpp +++ b/src/ZoneCodeGeneratorLib/Parsing/Header/Sequence/SequenceStruct.cpp @@ -1,61 +1,50 @@ #include "SequenceStruct.h" #include "Parsing/Header/Block/HeaderBlockStruct.h" -#include "Parsing/Header/Matcher/HeaderMatcherFactory.h" #include "Parsing/Header/Matcher/HeaderCommonMatchers.h" +#include "Parsing/Header/Matcher/HeaderMatcherFactory.h" + +SequenceStruct::SequenceStruct() { + const HeaderMatcherFactory create(this); -SequenceStruct::SequenceStruct() -{ - const HeaderMatcherFactory create(this); - - AddLabeledMatchers(HeaderCommonMatchers::Align(this), HeaderCommonMatchers::LABEL_ALIGN); - AddLabeledMatchers(HeaderCommonMatchers::Typename(this), HeaderCommonMatchers::LABEL_TYPENAME); - AddMatchers({ - create.Optional(create.Type(HeaderParserValueType::TYPEDEF).Tag(TAG_TYPEDEF)), - create.Optional(create.Type(HeaderParserValueType::CONST)), - create.Type(HeaderParserValueType::STRUCT), - create.Optional(create.Label(HeaderCommonMatchers::LABEL_ALIGN).Capture(CAPTURE_ALIGN)), - create.Optional(create.Identifier().Capture(CAPTURE_NAME)), - create.Optional(create.And({ - create.Char(':'), - create.Label(HeaderCommonMatchers::LABEL_TYPENAME).Capture(CAPTURE_PARENT_TYPE) - })), - create.Char('{') - }); + AddLabeledMatchers(HeaderCommonMatchers::Align(this), HeaderCommonMatchers::LABEL_ALIGN); + AddLabeledMatchers(HeaderCommonMatchers::Typename(this), HeaderCommonMatchers::LABEL_TYPENAME); + AddMatchers({create.Optional(create.Type(HeaderParserValueType::TYPEDEF).Tag(TAG_TYPEDEF)), create.Optional(create.Type(HeaderParserValueType::CONST)), + create.Type(HeaderParserValueType::STRUCT), create.Optional(create.Label(HeaderCommonMatchers::LABEL_ALIGN).Capture(CAPTURE_ALIGN)), + create.Optional(create.Identifier().Capture(CAPTURE_NAME)), + create.Optional(create.And({create.Char(':'), create.Label(HeaderCommonMatchers::LABEL_TYPENAME).Capture(CAPTURE_PARENT_TYPE)})), + create.Char('{')}); } -void SequenceStruct::ProcessMatch(HeaderParserState* state, SequenceResult<HeaderParserValue>& result) const -{ - auto isTypedef = result.PeekAndRemoveIfTag(TAG_TYPEDEF) == TAG_TYPEDEF; - std::string name; +void SequenceStruct::ProcessMatch(HeaderParserState *state, SequenceResult<HeaderParserValue> &result) const { + auto isTypedef = result.PeekAndRemoveIfTag(TAG_TYPEDEF) == TAG_TYPEDEF; + std::string name; - if (result.HasNextCapture(CAPTURE_NAME)) - name = result.NextCapture(CAPTURE_NAME).IdentifierValue(); + if (result.HasNextCapture(CAPTURE_NAME)) + name = result.NextCapture(CAPTURE_NAME).IdentifierValue(); - auto structBlock = std::make_unique<HeaderBlockStruct>(std::move(name), isTypedef); + auto structBlock = std::make_unique<HeaderBlockStruct>(std::move(name), isTypedef); - if (result.HasNextCapture(CAPTURE_ALIGN)) - structBlock->SetCustomAlignment(result.NextCapture(CAPTURE_ALIGN).IntegerValue()); + if (result.HasNextCapture(CAPTURE_ALIGN)) + structBlock->SetCustomAlignment(result.NextCapture(CAPTURE_ALIGN).IntegerValue()); - if(result.HasNextCapture(CAPTURE_PARENT_TYPE)) - { - const auto& parentTypeToken = result.NextCapture(CAPTURE_PARENT_TYPE); - const auto* parentDefinition = state->FindType(parentTypeToken.TypeNameValue()); + if (result.HasNextCapture(CAPTURE_PARENT_TYPE)) { + const auto &parentTypeToken = result.NextCapture(CAPTURE_PARENT_TYPE); + const auto *parentDefinition = state->FindType(parentTypeToken.TypeNameValue()); - if(parentDefinition == nullptr && !state->m_namespace.IsEmpty()) - { - const auto fullTypeName = NamespaceBuilder::Combine(state->m_namespace.ToString(), parentTypeToken.TypeNameValue()); - parentDefinition = state->FindType(fullTypeName); - } + if (parentDefinition == nullptr && !state->m_namespace.IsEmpty()) { + const auto fullTypeName = NamespaceBuilder::Combine(state->m_namespace.ToString(), parentTypeToken.TypeNameValue()); + parentDefinition = state->FindType(fullTypeName); + } - if (parentDefinition == nullptr) - throw ParsingException(parentTypeToken.GetPos(), "Cannot find specified parent type"); + if (parentDefinition == nullptr) + throw ParsingException(parentTypeToken.GetPos(), "Cannot find specified parent type"); - if(parentDefinition->GetType() != DataDefinitionType::STRUCT) - throw ParsingException(parentTypeToken.GetPos(), "Parent type must be a struct"); + if (parentDefinition->GetType() != DataDefinitionType::STRUCT) + throw ParsingException(parentTypeToken.GetPos(), "Parent type must be a struct"); - structBlock->Inherit(dynamic_cast<const StructDefinition*>(parentDefinition)); - } + structBlock->Inherit(dynamic_cast<const StructDefinition *>(parentDefinition)); + } - state->PushBlock(std::move(structBlock)); + state->PushBlock(std::move(structBlock)); } diff --git a/src/ZoneCodeGeneratorLib/Parsing/Header/Sequence/SequenceStruct.h b/src/ZoneCodeGeneratorLib/Parsing/Header/Sequence/SequenceStruct.h index 5fee02838..eb2f59cc9 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Header/Sequence/SequenceStruct.h +++ b/src/ZoneCodeGeneratorLib/Parsing/Header/Sequence/SequenceStruct.h @@ -1,21 +1,20 @@ #pragma once #include "Parsing/Header/Impl/HeaderParser.h" -#include "Parsing/Sequence/AbstractSequence.h" #include "Parsing/Header/Impl/HeaderParserState.h" #include "Parsing/Header/Impl/HeaderParserValue.h" +#include "Parsing/Sequence/AbstractSequence.h" -class SequenceStruct final : public HeaderParser::sequence_t -{ - static constexpr int TAG_TYPEDEF = 1; +class SequenceStruct final : public HeaderParser::sequence_t { + static constexpr int TAG_TYPEDEF = 1; - static constexpr int CAPTURE_NAME = 1; - static constexpr int CAPTURE_ALIGN = 2; - static constexpr int CAPTURE_PARENT_TYPE = 3; + static constexpr int CAPTURE_NAME = 1; + static constexpr int CAPTURE_ALIGN = 2; + static constexpr int CAPTURE_PARENT_TYPE = 3; protected: - void ProcessMatch(HeaderParserState* state, SequenceResult<HeaderParserValue>& result) const override; + void ProcessMatch(HeaderParserState *state, SequenceResult<HeaderParserValue> &result) const override; public: - SequenceStruct(); + SequenceStruct(); }; diff --git a/src/ZoneCodeGeneratorLib/Parsing/Header/Sequence/SequenceTypedef.cpp b/src/ZoneCodeGeneratorLib/Parsing/Header/Sequence/SequenceTypedef.cpp index 4204f0efe..4b9f8911a 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Header/Sequence/SequenceTypedef.cpp +++ b/src/ZoneCodeGeneratorLib/Parsing/Header/Sequence/SequenceTypedef.cpp @@ -2,114 +2,86 @@ #include "Domain/Definition/ArrayDeclarationModifier.h" #include "Domain/Definition/PointerDeclarationModifier.h" -#include "Parsing/Header/Matcher/HeaderMatcherFactory.h" #include "Parsing/Header/Matcher/HeaderCommonMatchers.h" +#include "Parsing/Header/Matcher/HeaderMatcherFactory.h" -SequenceTypedef::SequenceTypedef() -{ - const HeaderMatcherFactory create(this); - - AddLabeledMatchers(HeaderCommonMatchers::Align(this), HeaderCommonMatchers::LABEL_ALIGN); - AddLabeledMatchers(HeaderCommonMatchers::ArrayDef(this), HeaderCommonMatchers::LABEL_ARRAY_DEF); - AddLabeledMatchers(HeaderCommonMatchers::Typename(this), HeaderCommonMatchers::LABEL_TYPENAME); - - AddLabeledMatchers( - { - create.Optional(create.Type(HeaderParserValueType::CONST).Tag(TAG_CONST)), - create.Label(HeaderCommonMatchers::LABEL_TYPENAME).Capture(CAPTURE_TYPE), - create.OptionalLoop(create.Char('*').Tag(TAG_POINTER)), - create.Identifier().Capture(CAPTURE_NAME), - create.OptionalLoop(create.Label(HeaderCommonMatchers::LABEL_ARRAY_DEF).Capture(CAPTURE_ARRAY)), - create.Char(';') - }, LABEL_ARRAY_OF_POINTERS); - - AddLabeledMatchers( - { - create.Optional(create.Type(HeaderParserValueType::CONST).Tag(TAG_CONST)), - create.Label(HeaderCommonMatchers::LABEL_TYPENAME).Capture(CAPTURE_TYPE), - create.Char('('), - create.Loop(create.Char('*').Tag(TAG_POINTER)), - create.Identifier().Capture(CAPTURE_NAME), - create.Char(')'), - create.Loop(create.Label(HeaderCommonMatchers::LABEL_ARRAY_DEF).Capture(CAPTURE_ARRAY)), - create.Char(';') - }, LABEL_POINTER_TO_ARRAY); - - AddMatchers({ - create.Type(HeaderParserValueType::TYPEDEF), - create.Optional(create.Label(HeaderCommonMatchers::LABEL_ALIGN).Capture(CAPTURE_ALIGN)), - create.Or({ - create.Label(LABEL_ARRAY_OF_POINTERS).Tag(TAG_ARRAY_OF_POINTERS), - create.Label(LABEL_POINTER_TO_ARRAY).Tag(TAG_POINTER_TO_ARRAY) - }) - }); -} +SequenceTypedef::SequenceTypedef() { + const HeaderMatcherFactory create(this); -void SequenceTypedef::AddPointerDeclarationModifiers(SequenceResult<HeaderParserValue>& result, TypeDeclaration* typeDeclaration) const -{ - while (result.PeekAndRemoveIfTag(TAG_POINTER) == TAG_POINTER) - typeDeclaration->m_declaration_modifiers.emplace_back(std::make_unique<PointerDeclarationModifier>()); -} + AddLabeledMatchers(HeaderCommonMatchers::Align(this), HeaderCommonMatchers::LABEL_ALIGN); + AddLabeledMatchers(HeaderCommonMatchers::ArrayDef(this), HeaderCommonMatchers::LABEL_ARRAY_DEF); + AddLabeledMatchers(HeaderCommonMatchers::Typename(this), HeaderCommonMatchers::LABEL_TYPENAME); -void SequenceTypedef::AddArrayDeclarationModifiers(HeaderParserState* state, SequenceResult<HeaderParserValue>& result, TypeDeclaration* typeDeclaration) const -{ - while (result.HasNextCapture(CAPTURE_ARRAY)) - { - const auto& arrayToken = result.NextCapture(CAPTURE_ARRAY); - - if (arrayToken.m_type == HeaderParserValueType::INTEGER) - { - typeDeclaration->m_declaration_modifiers.emplace_back(std::make_unique<ArrayDeclarationModifier>(arrayToken.IntegerValue())); - } - else - { - auto* enumMember = state->FindEnumMember(arrayToken.IdentifierValue()); - - if (enumMember == nullptr) - throw ParsingException(arrayToken.GetPos(), "Unknown enum member"); - - typeDeclaration->m_declaration_modifiers.emplace_back(std::make_unique<ArrayDeclarationModifier>(enumMember->m_value)); - } - } -} + AddLabeledMatchers({create.Optional(create.Type(HeaderParserValueType::CONST).Tag(TAG_CONST)), + create.Label(HeaderCommonMatchers::LABEL_TYPENAME).Capture(CAPTURE_TYPE), create.OptionalLoop(create.Char('*').Tag(TAG_POINTER)), + create.Identifier().Capture(CAPTURE_NAME), + create.OptionalLoop(create.Label(HeaderCommonMatchers::LABEL_ARRAY_DEF).Capture(CAPTURE_ARRAY)), create.Char(';')}, + LABEL_ARRAY_OF_POINTERS); -void SequenceTypedef::ProcessMatch(HeaderParserState* state, SequenceResult<HeaderParserValue>& result) const -{ - const auto modeTag = result.NextTag(); - assert(modeTag == TAG_ARRAY_OF_POINTERS || modeTag == TAG_POINTER_TO_ARRAY); + AddLabeledMatchers({create.Optional(create.Type(HeaderParserValueType::CONST).Tag(TAG_CONST)), + create.Label(HeaderCommonMatchers::LABEL_TYPENAME).Capture(CAPTURE_TYPE), create.Char('('), + create.Loop(create.Char('*').Tag(TAG_POINTER)), create.Identifier().Capture(CAPTURE_NAME), create.Char(')'), + create.Loop(create.Label(HeaderCommonMatchers::LABEL_ARRAY_DEF).Capture(CAPTURE_ARRAY)), create.Char(';')}, + LABEL_POINTER_TO_ARRAY); - const auto name = result.NextCapture(CAPTURE_NAME).IdentifierValue(); + AddMatchers({create.Type(HeaderParserValueType::TYPEDEF), create.Optional(create.Label(HeaderCommonMatchers::LABEL_ALIGN).Capture(CAPTURE_ALIGN)), + create.Or({create.Label(LABEL_ARRAY_OF_POINTERS).Tag(TAG_ARRAY_OF_POINTERS), create.Label(LABEL_POINTER_TO_ARRAY).Tag(TAG_POINTER_TO_ARRAY)})}); +} - const auto& typenameToken = result.NextCapture(CAPTURE_TYPE); - const auto* type = state->FindType(typenameToken.TypeNameValue()); - if (type == nullptr && !state->m_namespace.IsEmpty()) - { - const auto fullTypename = NamespaceBuilder::Combine(state->m_namespace.ToString(), typenameToken.TypeNameValue()); - type = state->FindType(fullTypename); - } - if (type == nullptr) - throw ParsingException(typenameToken.GetPos(), "Unknown type"); +void SequenceTypedef::AddPointerDeclarationModifiers(SequenceResult<HeaderParserValue> &result, TypeDeclaration *typeDeclaration) const { + while (result.PeekAndRemoveIfTag(TAG_POINTER) == TAG_POINTER) + typeDeclaration->m_declaration_modifiers.emplace_back(std::make_unique<PointerDeclarationModifier>()); +} - auto typedefDefinition = std::make_unique<TypedefDefinition>(state->m_namespace.ToString(), name, std::make_unique<TypeDeclaration>(type)); - typedefDefinition->m_type_declaration->m_is_const = result.PeekAndRemoveIfTag(TAG_CONST) == TAG_CONST; +void SequenceTypedef::AddArrayDeclarationModifiers(HeaderParserState *state, SequenceResult<HeaderParserValue> &result, + TypeDeclaration *typeDeclaration) const { + while (result.HasNextCapture(CAPTURE_ARRAY)) { + const auto &arrayToken = result.NextCapture(CAPTURE_ARRAY); - if(result.HasNextCapture(CAPTURE_ALIGN)) - { - const auto& alignToken = result.NextCapture(CAPTURE_ALIGN); - typedefDefinition->m_alignment_override = static_cast<unsigned>(alignToken.IntegerValue()); - typedefDefinition->m_has_alignment_override = true; - } + if (arrayToken.m_type == HeaderParserValueType::INTEGER) { + typeDeclaration->m_declaration_modifiers.emplace_back(std::make_unique<ArrayDeclarationModifier>(arrayToken.IntegerValue())); + } else { + auto *enumMember = state->FindEnumMember(arrayToken.IdentifierValue()); - if (modeTag == TAG_ARRAY_OF_POINTERS) - { - AddArrayDeclarationModifiers(state, result, typedefDefinition->m_type_declaration.get()); - AddPointerDeclarationModifiers(result, typedefDefinition->m_type_declaration.get()); - } - else - { - AddPointerDeclarationModifiers(result, typedefDefinition->m_type_declaration.get()); - AddArrayDeclarationModifiers(state, result, typedefDefinition->m_type_declaration.get()); + if (enumMember == nullptr) + throw ParsingException(arrayToken.GetPos(), "Unknown enum member"); + + typeDeclaration->m_declaration_modifiers.emplace_back(std::make_unique<ArrayDeclarationModifier>(enumMember->m_value)); } + } +} - state->AddDataType(std::move(typedefDefinition)); +void SequenceTypedef::ProcessMatch(HeaderParserState *state, SequenceResult<HeaderParserValue> &result) const { + const auto modeTag = result.NextTag(); + assert(modeTag == TAG_ARRAY_OF_POINTERS || modeTag == TAG_POINTER_TO_ARRAY); + + const auto name = result.NextCapture(CAPTURE_NAME).IdentifierValue(); + + const auto &typenameToken = result.NextCapture(CAPTURE_TYPE); + const auto *type = state->FindType(typenameToken.TypeNameValue()); + if (type == nullptr && !state->m_namespace.IsEmpty()) { + const auto fullTypename = NamespaceBuilder::Combine(state->m_namespace.ToString(), typenameToken.TypeNameValue()); + type = state->FindType(fullTypename); + } + if (type == nullptr) + throw ParsingException(typenameToken.GetPos(), "Unknown type"); + + auto typedefDefinition = std::make_unique<TypedefDefinition>(state->m_namespace.ToString(), name, std::make_unique<TypeDeclaration>(type)); + typedefDefinition->m_type_declaration->m_is_const = result.PeekAndRemoveIfTag(TAG_CONST) == TAG_CONST; + + if (result.HasNextCapture(CAPTURE_ALIGN)) { + const auto &alignToken = result.NextCapture(CAPTURE_ALIGN); + typedefDefinition->m_alignment_override = static_cast<unsigned>(alignToken.IntegerValue()); + typedefDefinition->m_has_alignment_override = true; + } + + if (modeTag == TAG_ARRAY_OF_POINTERS) { + AddArrayDeclarationModifiers(state, result, typedefDefinition->m_type_declaration.get()); + AddPointerDeclarationModifiers(result, typedefDefinition->m_type_declaration.get()); + } else { + AddPointerDeclarationModifiers(result, typedefDefinition->m_type_declaration.get()); + AddArrayDeclarationModifiers(state, result, typedefDefinition->m_type_declaration.get()); + } + + state->AddDataType(std::move(typedefDefinition)); } diff --git a/src/ZoneCodeGeneratorLib/Parsing/Header/Sequence/SequenceTypedef.h b/src/ZoneCodeGeneratorLib/Parsing/Header/Sequence/SequenceTypedef.h index 424e47e93..aa548fbac 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Header/Sequence/SequenceTypedef.h +++ b/src/ZoneCodeGeneratorLib/Parsing/Header/Sequence/SequenceTypedef.h @@ -1,31 +1,30 @@ #pragma once #include "Parsing/Header/Impl/HeaderParser.h" -#include "Parsing/Sequence/AbstractSequence.h" #include "Parsing/Header/Impl/HeaderParserState.h" #include "Parsing/Header/Impl/HeaderParserValue.h" +#include "Parsing/Sequence/AbstractSequence.h" -class SequenceTypedef final : public HeaderParser::sequence_t -{ - static constexpr auto TAG_ARRAY_OF_POINTERS = 1; - static constexpr auto TAG_POINTER_TO_ARRAY = 2; - static constexpr auto TAG_CONST = 3; - static constexpr auto TAG_POINTER = 4; +class SequenceTypedef final : public HeaderParser::sequence_t { + static constexpr auto TAG_ARRAY_OF_POINTERS = 1; + static constexpr auto TAG_POINTER_TO_ARRAY = 2; + static constexpr auto TAG_CONST = 3; + static constexpr auto TAG_POINTER = 4; - static constexpr auto CAPTURE_NAME = 1; - static constexpr auto CAPTURE_ALIGN = 2; - static constexpr auto CAPTURE_TYPE = 3; - static constexpr auto CAPTURE_ARRAY = 4; + static constexpr auto CAPTURE_NAME = 1; + static constexpr auto CAPTURE_ALIGN = 2; + static constexpr auto CAPTURE_TYPE = 3; + static constexpr auto CAPTURE_ARRAY = 4; - static constexpr auto LABEL_ARRAY_OF_POINTERS = 1; - static constexpr auto LABEL_POINTER_TO_ARRAY = 2; + static constexpr auto LABEL_ARRAY_OF_POINTERS = 1; + static constexpr auto LABEL_POINTER_TO_ARRAY = 2; - void AddPointerDeclarationModifiers(SequenceResult<HeaderParserValue>& result, TypeDeclaration* typeDeclaration) const; - void AddArrayDeclarationModifiers(HeaderParserState* state, SequenceResult<HeaderParserValue>& result, TypeDeclaration* typeDeclaration) const; + void AddPointerDeclarationModifiers(SequenceResult<HeaderParserValue> &result, TypeDeclaration *typeDeclaration) const; + void AddArrayDeclarationModifiers(HeaderParserState *state, SequenceResult<HeaderParserValue> &result, TypeDeclaration *typeDeclaration) const; protected: - void ProcessMatch(HeaderParserState* state, SequenceResult<HeaderParserValue>& result) const override; + void ProcessMatch(HeaderParserState *state, SequenceResult<HeaderParserValue> &result) const override; public: - SequenceTypedef(); + SequenceTypedef(); }; diff --git a/src/ZoneCodeGeneratorLib/Parsing/Header/Sequence/SequenceUnion.cpp b/src/ZoneCodeGeneratorLib/Parsing/Header/Sequence/SequenceUnion.cpp index a2fe83da3..afd597709 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Header/Sequence/SequenceUnion.cpp +++ b/src/ZoneCodeGeneratorLib/Parsing/Header/Sequence/SequenceUnion.cpp @@ -1,61 +1,50 @@ #include "SequenceUnion.h" #include "Parsing/Header/Block/HeaderBlockUnion.h" -#include "Parsing/Header/Matcher/HeaderMatcherFactory.h" #include "Parsing/Header/Matcher/HeaderCommonMatchers.h" +#include "Parsing/Header/Matcher/HeaderMatcherFactory.h" + +SequenceUnion::SequenceUnion() { + const HeaderMatcherFactory create(this); -SequenceUnion::SequenceUnion() -{ - const HeaderMatcherFactory create(this); - - AddLabeledMatchers(HeaderCommonMatchers::Align(this), HeaderCommonMatchers::LABEL_ALIGN); - AddLabeledMatchers(HeaderCommonMatchers::Typename(this), HeaderCommonMatchers::LABEL_TYPENAME); - AddMatchers({ - create.Optional(create.Type(HeaderParserValueType::TYPEDEF).Tag(TAG_TYPEDEF)), - create.Optional(create.Type(HeaderParserValueType::CONST)), - create.Type(HeaderParserValueType::UNION), - create.Optional(create.Label(HeaderCommonMatchers::LABEL_ALIGN).Capture(CAPTURE_ALIGN)), - create.Optional(create.Identifier().Capture(CAPTURE_NAME)), - create.Optional(create.And({ - create.Char(':'), - create.Label(HeaderCommonMatchers::LABEL_TYPENAME).Capture(CAPTURE_PARENT_TYPE) - })), - create.Char('{') - }); + AddLabeledMatchers(HeaderCommonMatchers::Align(this), HeaderCommonMatchers::LABEL_ALIGN); + AddLabeledMatchers(HeaderCommonMatchers::Typename(this), HeaderCommonMatchers::LABEL_TYPENAME); + AddMatchers({create.Optional(create.Type(HeaderParserValueType::TYPEDEF).Tag(TAG_TYPEDEF)), create.Optional(create.Type(HeaderParserValueType::CONST)), + create.Type(HeaderParserValueType::UNION), create.Optional(create.Label(HeaderCommonMatchers::LABEL_ALIGN).Capture(CAPTURE_ALIGN)), + create.Optional(create.Identifier().Capture(CAPTURE_NAME)), + create.Optional(create.And({create.Char(':'), create.Label(HeaderCommonMatchers::LABEL_TYPENAME).Capture(CAPTURE_PARENT_TYPE)})), + create.Char('{')}); } -void SequenceUnion::ProcessMatch(HeaderParserState* state, SequenceResult<HeaderParserValue>& result) const -{ - auto isTypedef = result.PeekAndRemoveIfTag(TAG_TYPEDEF) == TAG_TYPEDEF; - std::string name; +void SequenceUnion::ProcessMatch(HeaderParserState *state, SequenceResult<HeaderParserValue> &result) const { + auto isTypedef = result.PeekAndRemoveIfTag(TAG_TYPEDEF) == TAG_TYPEDEF; + std::string name; - if (result.HasNextCapture(CAPTURE_NAME)) - name = result.NextCapture(CAPTURE_NAME).IdentifierValue(); + if (result.HasNextCapture(CAPTURE_NAME)) + name = result.NextCapture(CAPTURE_NAME).IdentifierValue(); - auto unionBlock = std::make_unique<HeaderBlockUnion>(std::move(name), isTypedef); + auto unionBlock = std::make_unique<HeaderBlockUnion>(std::move(name), isTypedef); - if (result.HasNextCapture(CAPTURE_ALIGN)) - unionBlock->SetCustomAlignment(result.NextCapture(CAPTURE_ALIGN).IntegerValue()); + if (result.HasNextCapture(CAPTURE_ALIGN)) + unionBlock->SetCustomAlignment(result.NextCapture(CAPTURE_ALIGN).IntegerValue()); - if (result.HasNextCapture(CAPTURE_PARENT_TYPE)) - { - const auto& parentTypeToken = result.NextCapture(CAPTURE_PARENT_TYPE); - const auto* parentDefinition = state->FindType(parentTypeToken.TypeNameValue()); + if (result.HasNextCapture(CAPTURE_PARENT_TYPE)) { + const auto &parentTypeToken = result.NextCapture(CAPTURE_PARENT_TYPE); + const auto *parentDefinition = state->FindType(parentTypeToken.TypeNameValue()); - if (parentDefinition == nullptr && !state->m_namespace.IsEmpty()) - { - const auto fullTypeName = NamespaceBuilder::Combine(state->m_namespace.ToString(), parentTypeToken.TypeNameValue()); - parentDefinition = state->FindType(fullTypeName); - } + if (parentDefinition == nullptr && !state->m_namespace.IsEmpty()) { + const auto fullTypeName = NamespaceBuilder::Combine(state->m_namespace.ToString(), parentTypeToken.TypeNameValue()); + parentDefinition = state->FindType(fullTypeName); + } - if (parentDefinition == nullptr) - throw ParsingException(parentTypeToken.GetPos(), "Cannot find specified parent type"); + if (parentDefinition == nullptr) + throw ParsingException(parentTypeToken.GetPos(), "Cannot find specified parent type"); - if (parentDefinition->GetType() != DataDefinitionType::STRUCT) - throw ParsingException(parentTypeToken.GetPos(), "Parent type must be a struct"); + if (parentDefinition->GetType() != DataDefinitionType::STRUCT) + throw ParsingException(parentTypeToken.GetPos(), "Parent type must be a struct"); - unionBlock->Inherit(dynamic_cast<const StructDefinition*>(parentDefinition)); - } + unionBlock->Inherit(dynamic_cast<const StructDefinition *>(parentDefinition)); + } - state->PushBlock(std::move(unionBlock)); + state->PushBlock(std::move(unionBlock)); } diff --git a/src/ZoneCodeGeneratorLib/Parsing/Header/Sequence/SequenceUnion.h b/src/ZoneCodeGeneratorLib/Parsing/Header/Sequence/SequenceUnion.h index 707243563..8eee207e8 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Header/Sequence/SequenceUnion.h +++ b/src/ZoneCodeGeneratorLib/Parsing/Header/Sequence/SequenceUnion.h @@ -1,21 +1,20 @@ #pragma once #include "Parsing/Header/Impl/HeaderParser.h" -#include "Parsing/Sequence/AbstractSequence.h" #include "Parsing/Header/Impl/HeaderParserState.h" #include "Parsing/Header/Impl/HeaderParserValue.h" +#include "Parsing/Sequence/AbstractSequence.h" -class SequenceUnion final : public HeaderParser::sequence_t -{ - static constexpr int TAG_TYPEDEF = 1; +class SequenceUnion final : public HeaderParser::sequence_t { + static constexpr int TAG_TYPEDEF = 1; - static constexpr int CAPTURE_NAME = 1; - static constexpr int CAPTURE_ALIGN = 2; - static constexpr int CAPTURE_PARENT_TYPE = 3; + static constexpr int CAPTURE_NAME = 1; + static constexpr int CAPTURE_ALIGN = 2; + static constexpr int CAPTURE_PARENT_TYPE = 3; protected: - void ProcessMatch(HeaderParserState* state, SequenceResult<HeaderParserValue>& result) const override; + void ProcessMatch(HeaderParserState *state, SequenceResult<HeaderParserValue> &result) const override; public: - SequenceUnion(); + SequenceUnion(); }; diff --git a/src/ZoneCodeGeneratorLib/Parsing/Header/Sequence/SequenceVariable.cpp b/src/ZoneCodeGeneratorLib/Parsing/Header/Sequence/SequenceVariable.cpp index 5d348044e..53f80ff7c 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Header/Sequence/SequenceVariable.cpp +++ b/src/ZoneCodeGeneratorLib/Parsing/Header/Sequence/SequenceVariable.cpp @@ -3,129 +3,100 @@ #include "Domain/Definition/ArrayDeclarationModifier.h" #include "Domain/Definition/PointerDeclarationModifier.h" #include "Parsing/Header/Block/IHeaderBlockVariableHolder.h" -#include "Parsing/Header/Matcher/HeaderMatcherFactory.h" #include "Parsing/Header/Matcher/HeaderCommonMatchers.h" +#include "Parsing/Header/Matcher/HeaderMatcherFactory.h" -SequenceVariable::SequenceVariable() -{ - const HeaderMatcherFactory create(this); - - AddLabeledMatchers(HeaderCommonMatchers::Align(this), HeaderCommonMatchers::LABEL_ALIGN); - AddLabeledMatchers(HeaderCommonMatchers::ArrayDef(this), HeaderCommonMatchers::LABEL_ARRAY_DEF); - AddLabeledMatchers(HeaderCommonMatchers::Typename(this), HeaderCommonMatchers::LABEL_TYPENAME); - - AddLabeledMatchers( - { - create.Optional(create.Type(HeaderParserValueType::CONST).Tag(TAG_CONST)), - create.Label(HeaderCommonMatchers::LABEL_TYPENAME).Capture(CAPTURE_TYPE), - create.OptionalLoop(create.Char('*').Tag(TAG_POINTER)), - create.Identifier().Capture(CAPTURE_NAME), - create.OptionalLoop(create.Label(HeaderCommonMatchers::LABEL_ARRAY_DEF).Capture(CAPTURE_ARRAY)), - create.Optional(create.And({ - create.Char(':'), - create.Integer().Capture(CAPTURE_BIT_SIZE) - })), - create.Char(';') - }, LABEL_ARRAY_OF_POINTERS); - - AddLabeledMatchers( - { - create.Optional(create.Type(HeaderParserValueType::CONST).Tag(TAG_CONST)), - create.Label(HeaderCommonMatchers::LABEL_TYPENAME).Capture(CAPTURE_TYPE), - create.Char('('), - create.Loop(create.Char('*').Tag(TAG_POINTER)), - create.Identifier().Capture(CAPTURE_NAME), - create.Char(')'), - create.Loop(create.Label(HeaderCommonMatchers::LABEL_ARRAY_DEF).Capture(CAPTURE_ARRAY)), - create.Char(';') - }, LABEL_POINTER_TO_ARRAY); - - AddMatchers(create.Or({ - create.Label(LABEL_ARRAY_OF_POINTERS).Tag(TAG_ARRAY_OF_POINTERS), - create.Label(LABEL_POINTER_TO_ARRAY).Tag(TAG_POINTER_TO_ARRAY) - })); -} - -void SequenceVariable::AddPointerDeclarationModifiers(SequenceResult<HeaderParserValue>& result, TypeDeclaration* typeDeclaration) const -{ - while (result.PeekAndRemoveIfTag(TAG_POINTER) == TAG_POINTER) - typeDeclaration->m_declaration_modifiers.emplace_back(std::make_unique<PointerDeclarationModifier>()); -} - -void SequenceVariable::AddArrayDeclarationModifiers(HeaderParserState* state, SequenceResult<HeaderParserValue>& result, TypeDeclaration* typeDeclaration) const -{ - while (result.HasNextCapture(CAPTURE_ARRAY)) - { - const auto& arrayToken = result.NextCapture(CAPTURE_ARRAY); - - if (arrayToken.m_type == HeaderParserValueType::INTEGER) - { - typeDeclaration->m_declaration_modifiers.emplace_back(std::make_unique<ArrayDeclarationModifier>(arrayToken.IntegerValue())); - } - else - { - auto* enumMember = state->FindEnumMember(arrayToken.IdentifierValue()); - - if (enumMember == nullptr) - throw ParsingException(arrayToken.GetPos(), "Unknown enum member"); - - typeDeclaration->m_declaration_modifiers.emplace_back(std::make_unique<ArrayDeclarationModifier>(enumMember->m_value)); - } - } -} - -void SequenceVariable::ProcessMatch(HeaderParserState* state, SequenceResult<HeaderParserValue>& result) const -{ - auto* variableHolder = dynamic_cast<IHeaderBlockVariableHolder*>(state->GetBlock()); - if (variableHolder == nullptr) - throw ParsingException(TokenPos(), "Defining variable in non VariableHolder block"); +SequenceVariable::SequenceVariable() { + const HeaderMatcherFactory create(this); - const auto modeTag = result.NextTag(); - assert(modeTag == TAG_ARRAY_OF_POINTERS || modeTag == TAG_POINTER_TO_ARRAY); + AddLabeledMatchers(HeaderCommonMatchers::Align(this), HeaderCommonMatchers::LABEL_ALIGN); + AddLabeledMatchers(HeaderCommonMatchers::ArrayDef(this), HeaderCommonMatchers::LABEL_ARRAY_DEF); + AddLabeledMatchers(HeaderCommonMatchers::Typename(this), HeaderCommonMatchers::LABEL_TYPENAME); - const auto name = result.NextCapture(CAPTURE_NAME).IdentifierValue(); + AddLabeledMatchers({create.Optional(create.Type(HeaderParserValueType::CONST).Tag(TAG_CONST)), + create.Label(HeaderCommonMatchers::LABEL_TYPENAME).Capture(CAPTURE_TYPE), create.OptionalLoop(create.Char('*').Tag(TAG_POINTER)), + create.Identifier().Capture(CAPTURE_NAME), + create.OptionalLoop(create.Label(HeaderCommonMatchers::LABEL_ARRAY_DEF).Capture(CAPTURE_ARRAY)), + create.Optional(create.And({create.Char(':'), create.Integer().Capture(CAPTURE_BIT_SIZE)})), create.Char(';')}, + LABEL_ARRAY_OF_POINTERS); - const auto& typenameToken = result.NextCapture(CAPTURE_TYPE); - const auto* type = state->FindType(typenameToken.TypeNameValue()); - if (type == nullptr && !state->m_namespace.IsEmpty()) - { - const auto fullTypename = NamespaceBuilder::Combine(state->m_namespace.ToString(), typenameToken.TypeNameValue()); - type = state->FindType(fullTypename); - } - if (type == nullptr) - throw ParsingException(typenameToken.GetPos(), "Unknown type"); + AddLabeledMatchers({create.Optional(create.Type(HeaderParserValueType::CONST).Tag(TAG_CONST)), + create.Label(HeaderCommonMatchers::LABEL_TYPENAME).Capture(CAPTURE_TYPE), create.Char('('), + create.Loop(create.Char('*').Tag(TAG_POINTER)), create.Identifier().Capture(CAPTURE_NAME), create.Char(')'), + create.Loop(create.Label(HeaderCommonMatchers::LABEL_ARRAY_DEF).Capture(CAPTURE_ARRAY)), create.Char(';')}, + LABEL_POINTER_TO_ARRAY); - auto variable = std::make_shared<Variable>(name, std::make_unique<TypeDeclaration>(type)); - variable->m_type_declaration->m_is_const = result.PeekAndRemoveIfTag(TAG_CONST) == TAG_CONST; + AddMatchers(create.Or({create.Label(LABEL_ARRAY_OF_POINTERS).Tag(TAG_ARRAY_OF_POINTERS), create.Label(LABEL_POINTER_TO_ARRAY).Tag(TAG_POINTER_TO_ARRAY)})); +} - if (result.HasNextCapture(CAPTURE_ALIGN)) - { - const auto& alignToken = result.NextCapture(CAPTURE_ALIGN); - variable->m_alignment_override = static_cast<unsigned>(alignToken.IntegerValue()); - variable->m_has_alignment_override = true; - } +void SequenceVariable::AddPointerDeclarationModifiers(SequenceResult<HeaderParserValue> &result, TypeDeclaration *typeDeclaration) const { + while (result.PeekAndRemoveIfTag(TAG_POINTER) == TAG_POINTER) + typeDeclaration->m_declaration_modifiers.emplace_back(std::make_unique<PointerDeclarationModifier>()); +} - if(result.HasNextCapture(CAPTURE_BIT_SIZE)) - { - const auto& bitSizeToken = result.NextCapture(CAPTURE_BIT_SIZE); - variable->m_type_declaration->m_custom_bit_size = bitSizeToken.IntegerValue(); +void SequenceVariable::AddArrayDeclarationModifiers(HeaderParserState *state, SequenceResult<HeaderParserValue> &result, + TypeDeclaration *typeDeclaration) const { + while (result.HasNextCapture(CAPTURE_ARRAY)) { + const auto &arrayToken = result.NextCapture(CAPTURE_ARRAY); - if (variable->m_type_declaration->m_custom_bit_size <= 0) - throw ParsingException(bitSizeToken.GetPos(), "Custom bit size must be greater than 0"); + if (arrayToken.m_type == HeaderParserValueType::INTEGER) { + typeDeclaration->m_declaration_modifiers.emplace_back(std::make_unique<ArrayDeclarationModifier>(arrayToken.IntegerValue())); + } else { + auto *enumMember = state->FindEnumMember(arrayToken.IdentifierValue()); - variable->m_type_declaration->m_has_custom_bit_size = true; - } + if (enumMember == nullptr) + throw ParsingException(arrayToken.GetPos(), "Unknown enum member"); - if (modeTag == TAG_ARRAY_OF_POINTERS) - { - AddArrayDeclarationModifiers(state, result, variable->m_type_declaration.get()); - AddPointerDeclarationModifiers(result, variable->m_type_declaration.get()); - } - else - { - AddPointerDeclarationModifiers(result, variable->m_type_declaration.get()); - AddArrayDeclarationModifiers(state, result, variable->m_type_declaration.get()); + typeDeclaration->m_declaration_modifiers.emplace_back(std::make_unique<ArrayDeclarationModifier>(enumMember->m_value)); } + } +} - variableHolder->AddVariable(std::move(variable)); +void SequenceVariable::ProcessMatch(HeaderParserState *state, SequenceResult<HeaderParserValue> &result) const { + auto *variableHolder = dynamic_cast<IHeaderBlockVariableHolder *>(state->GetBlock()); + if (variableHolder == nullptr) + throw ParsingException(TokenPos(), "Defining variable in non VariableHolder block"); + + const auto modeTag = result.NextTag(); + assert(modeTag == TAG_ARRAY_OF_POINTERS || modeTag == TAG_POINTER_TO_ARRAY); + + const auto name = result.NextCapture(CAPTURE_NAME).IdentifierValue(); + + const auto &typenameToken = result.NextCapture(CAPTURE_TYPE); + const auto *type = state->FindType(typenameToken.TypeNameValue()); + if (type == nullptr && !state->m_namespace.IsEmpty()) { + const auto fullTypename = NamespaceBuilder::Combine(state->m_namespace.ToString(), typenameToken.TypeNameValue()); + type = state->FindType(fullTypename); + } + if (type == nullptr) + throw ParsingException(typenameToken.GetPos(), "Unknown type"); + + auto variable = std::make_shared<Variable>(name, std::make_unique<TypeDeclaration>(type)); + variable->m_type_declaration->m_is_const = result.PeekAndRemoveIfTag(TAG_CONST) == TAG_CONST; + + if (result.HasNextCapture(CAPTURE_ALIGN)) { + const auto &alignToken = result.NextCapture(CAPTURE_ALIGN); + variable->m_alignment_override = static_cast<unsigned>(alignToken.IntegerValue()); + variable->m_has_alignment_override = true; + } + + if (result.HasNextCapture(CAPTURE_BIT_SIZE)) { + const auto &bitSizeToken = result.NextCapture(CAPTURE_BIT_SIZE); + variable->m_type_declaration->m_custom_bit_size = bitSizeToken.IntegerValue(); + + if (variable->m_type_declaration->m_custom_bit_size <= 0) + throw ParsingException(bitSizeToken.GetPos(), "Custom bit size must be greater than 0"); + + variable->m_type_declaration->m_has_custom_bit_size = true; + } + + if (modeTag == TAG_ARRAY_OF_POINTERS) { + AddArrayDeclarationModifiers(state, result, variable->m_type_declaration.get()); + AddPointerDeclarationModifiers(result, variable->m_type_declaration.get()); + } else { + AddPointerDeclarationModifiers(result, variable->m_type_declaration.get()); + AddArrayDeclarationModifiers(state, result, variable->m_type_declaration.get()); + } + + variableHolder->AddVariable(std::move(variable)); } diff --git a/src/ZoneCodeGeneratorLib/Parsing/Header/Sequence/SequenceVariable.h b/src/ZoneCodeGeneratorLib/Parsing/Header/Sequence/SequenceVariable.h index 70a5986f4..99088afb7 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/Header/Sequence/SequenceVariable.h +++ b/src/ZoneCodeGeneratorLib/Parsing/Header/Sequence/SequenceVariable.h @@ -1,32 +1,31 @@ #pragma once #include "Parsing/Header/Impl/HeaderParser.h" -#include "Parsing/Sequence/AbstractSequence.h" #include "Parsing/Header/Impl/HeaderParserState.h" #include "Parsing/Header/Impl/HeaderParserValue.h" +#include "Parsing/Sequence/AbstractSequence.h" -class SequenceVariable final : public HeaderParser::sequence_t -{ - static constexpr auto TAG_ARRAY_OF_POINTERS = 1; - static constexpr auto TAG_POINTER_TO_ARRAY = 2; - static constexpr auto TAG_CONST = 3; - static constexpr auto TAG_POINTER = 4; +class SequenceVariable final : public HeaderParser::sequence_t { + static constexpr auto TAG_ARRAY_OF_POINTERS = 1; + static constexpr auto TAG_POINTER_TO_ARRAY = 2; + static constexpr auto TAG_CONST = 3; + static constexpr auto TAG_POINTER = 4; - static constexpr auto CAPTURE_NAME = 1; - static constexpr auto CAPTURE_ALIGN = 2; - static constexpr auto CAPTURE_TYPE = 3; - static constexpr auto CAPTURE_ARRAY = 4; - static constexpr auto CAPTURE_BIT_SIZE = 5; + static constexpr auto CAPTURE_NAME = 1; + static constexpr auto CAPTURE_ALIGN = 2; + static constexpr auto CAPTURE_TYPE = 3; + static constexpr auto CAPTURE_ARRAY = 4; + static constexpr auto CAPTURE_BIT_SIZE = 5; - static constexpr auto LABEL_ARRAY_OF_POINTERS = 1; - static constexpr auto LABEL_POINTER_TO_ARRAY = 2; + static constexpr auto LABEL_ARRAY_OF_POINTERS = 1; + static constexpr auto LABEL_POINTER_TO_ARRAY = 2; - void AddPointerDeclarationModifiers(SequenceResult<HeaderParserValue>& result, TypeDeclaration* typeDeclaration) const; - void AddArrayDeclarationModifiers(HeaderParserState* state, SequenceResult<HeaderParserValue>& result, TypeDeclaration* typeDeclaration) const; + void AddPointerDeclarationModifiers(SequenceResult<HeaderParserValue> &result, TypeDeclaration *typeDeclaration) const; + void AddArrayDeclarationModifiers(HeaderParserState *state, SequenceResult<HeaderParserValue> &result, TypeDeclaration *typeDeclaration) const; protected: - void ProcessMatch(HeaderParserState* state, SequenceResult<HeaderParserValue>& result) const override; + void ProcessMatch(HeaderParserState *state, SequenceResult<HeaderParserValue> &result) const override; public: - SequenceVariable(); + SequenceVariable(); }; diff --git a/src/ZoneCodeGeneratorLib/Parsing/PostProcessing/CalculateSizeAndAlignPostProcessor.cpp b/src/ZoneCodeGeneratorLib/Parsing/PostProcessing/CalculateSizeAndAlignPostProcessor.cpp index d686ab3a7..c03cd3ab2 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/PostProcessing/CalculateSizeAndAlignPostProcessor.cpp +++ b/src/ZoneCodeGeneratorLib/Parsing/PostProcessing/CalculateSizeAndAlignPostProcessor.cpp @@ -1,306 +1,255 @@ #include "CalculateSizeAndAlignPostProcessor.h" #include <cassert> -#include <iostream> #include <cstdint> +#include <iostream> #include "Domain/Definition/ArrayDeclarationModifier.h" #include "Utils/AlignmentUtils.h" -unsigned CalculateSizeAndAlignPostProcessor::GetPointerSizeForArchitecture(const Architecture architecture) -{ - switch (architecture) - { - case Architecture::X86: - return sizeof(uint32_t); +unsigned CalculateSizeAndAlignPostProcessor::GetPointerSizeForArchitecture(const Architecture architecture) { + switch (architecture) { + case Architecture::X86: + return sizeof(uint32_t); - case Architecture::X64: - return sizeof(uint64_t); + case Architecture::X64: + return sizeof(uint64_t); - default: - assert(false); - return sizeof(uint32_t); - } + default: + assert(false); + return sizeof(uint32_t); + } } -bool CalculateSizeAndAlignPostProcessor::CalculateAlign(IDataRepository* repository, TypeDeclaration* declaration) -{ - auto hasPointerModifier = false; - for (const auto& declarationModifier : declaration->m_declaration_modifiers) - { - if (declarationModifier->GetType() == DeclarationModifierType::POINTER) - { - hasPointerModifier = true; - break; - } - } +bool CalculateSizeAndAlignPostProcessor::CalculateAlign(IDataRepository *repository, TypeDeclaration *declaration) { + auto hasPointerModifier = false; + for (const auto &declarationModifier : declaration->m_declaration_modifiers) { + if (declarationModifier->GetType() == DeclarationModifierType::POINTER) { + hasPointerModifier = true; + break; + } + } + + if (hasPointerModifier) { + declaration->m_alignment = GetPointerSizeForArchitecture(repository->GetArchitecture()); + } else { + if (!CalculateFieldsIfNecessary(repository, declaration->m_type)) + return false; + declaration->m_alignment = declaration->m_type->GetAlignment(); + if (declaration->m_type->GetForceAlignment()) + declaration->m_flags |= TypeDeclaration::FLAG_ALIGNMENT_FORCED; + } + + return true; +} - if (hasPointerModifier) - { - declaration->m_alignment = GetPointerSizeForArchitecture(repository->GetArchitecture()); - } - else - { - if (!CalculateFieldsIfNecessary(repository, declaration->m_type)) - return false; - declaration->m_alignment = declaration->m_type->GetAlignment(); - if (declaration->m_type->GetForceAlignment()) - declaration->m_flags |= TypeDeclaration::FLAG_ALIGNMENT_FORCED; +bool CalculateSizeAndAlignPostProcessor::CalculateAlign(IDataRepository *repository, DefinitionWithMembers *definition) { + if (definition->m_has_alignment_override) { + definition->m_flags |= DefinitionWithMembers::FLAG_ALIGNMENT_FORCED; + definition->m_alignment = definition->m_alignment_override; + } else { + definition->m_alignment = 0; + for (const auto &member : definition->m_members) { + if (!CalculateFields(repository, member->m_type_declaration.get())) + return false; + + const auto memberAlignment = member->GetAlignment(); + if (memberAlignment > definition->m_alignment) + definition->m_alignment = memberAlignment; } + } - return true; + return true; } -bool CalculateSizeAndAlignPostProcessor::CalculateAlign(IDataRepository* repository, DefinitionWithMembers* definition) -{ - if (definition->m_has_alignment_override) - { - definition->m_flags |= DefinitionWithMembers::FLAG_ALIGNMENT_FORCED; - definition->m_alignment = definition->m_alignment_override; - } - else - { - definition->m_alignment = 0; - for (const auto& member : definition->m_members) - { - if (!CalculateFields(repository, member->m_type_declaration.get())) - return false; - - const auto memberAlignment = member->GetAlignment(); - if (memberAlignment > definition->m_alignment) - definition->m_alignment = memberAlignment; - } +bool CalculateSizeAndAlignPostProcessor::CalculateSize(IDataRepository *repository, TypeDeclaration *declaration) { + if (declaration->m_declaration_modifiers.empty()) { + if (!CalculateFieldsIfNecessary(repository, declaration->m_type)) + return false; + declaration->m_size = declaration->m_type->GetSize(); + } else { + auto currentSize = 0u; + + // If the first modifier is a pointer we do not need the actual type size + if (declaration->m_declaration_modifiers.back()->GetType() != DeclarationModifierType::POINTER) { + if (!CalculateFieldsIfNecessary(repository, declaration->m_type)) + return false; + currentSize = declaration->m_type->GetSize(); } - return true; -} + for (auto i = declaration->m_declaration_modifiers.size(); i > 0; i--) { + const auto &declarationModifier = declaration->m_declaration_modifiers[i - 1]; -bool CalculateSizeAndAlignPostProcessor::CalculateSize(IDataRepository* repository, TypeDeclaration* declaration) -{ - if (declaration->m_declaration_modifiers.empty()) - { - if (!CalculateFieldsIfNecessary(repository, declaration->m_type)) - return false; - declaration->m_size = declaration->m_type->GetSize(); - } - else - { - auto currentSize = 0u; - - // If the first modifier is a pointer we do not need the actual type size - if (declaration->m_declaration_modifiers.back()->GetType() != DeclarationModifierType::POINTER) - { - if (!CalculateFieldsIfNecessary(repository, declaration->m_type)) - return false; - currentSize = declaration->m_type->GetSize(); - } - - for (auto i = declaration->m_declaration_modifiers.size(); i > 0; i--) - { - const auto& declarationModifier = declaration->m_declaration_modifiers[i - 1]; - - switch (declarationModifier->GetType()) - { - case DeclarationModifierType::POINTER: - currentSize = GetPointerSizeForArchitecture(repository->GetArchitecture()); - break; - - case DeclarationModifierType::ARRAY: - currentSize *= dynamic_cast<ArrayDeclarationModifier*>(declarationModifier.get())->m_size; - break; - } - } - - declaration->m_size = currentSize; + switch (declarationModifier->GetType()) { + case DeclarationModifierType::POINTER: + currentSize = GetPointerSizeForArchitecture(repository->GetArchitecture()); + break; + + case DeclarationModifierType::ARRAY: + currentSize *= dynamic_cast<ArrayDeclarationModifier *>(declarationModifier.get())->m_size; + break; + } } - return true; + declaration->m_size = currentSize; + } + + return true; } -bool CalculateSizeAndAlignPostProcessor::CalculateSize(IDataRepository* repository, StructDefinition* definition) -{ - definition->m_size = 0; - auto currentBitOffset = 0u; - - for (const auto& member : definition->m_members) - { - if (!CalculateFields(repository, member->m_type_declaration.get())) - return false; - - if (member->m_type_declaration->m_has_custom_bit_size) - { - member->m_offset = definition->m_size + currentBitOffset / 8; - currentBitOffset += member->m_type_declaration->m_custom_bit_size; - } - else - { - if (currentBitOffset > 0) - { - currentBitOffset = AlignmentUtils::Align(currentBitOffset, 8u); - definition->m_size += currentBitOffset / 8; - currentBitOffset = 0; - } - - definition->m_size = AlignmentUtils::Align(definition->m_size, member->GetForceAlignment() ? member->GetAlignment() : std::min(member->GetAlignment(), definition->m_pack)); - - member->m_offset = definition->m_size; - - definition->m_size += member->m_type_declaration->GetSize(); - } - } +bool CalculateSizeAndAlignPostProcessor::CalculateSize(IDataRepository *repository, StructDefinition *definition) { + definition->m_size = 0; + auto currentBitOffset = 0u; + + for (const auto &member : definition->m_members) { + if (!CalculateFields(repository, member->m_type_declaration.get())) + return false; - if (currentBitOffset > 0) - { + if (member->m_type_declaration->m_has_custom_bit_size) { + member->m_offset = definition->m_size + currentBitOffset / 8; + currentBitOffset += member->m_type_declaration->m_custom_bit_size; + } else { + if (currentBitOffset > 0) { currentBitOffset = AlignmentUtils::Align(currentBitOffset, 8u); definition->m_size += currentBitOffset / 8; + currentBitOffset = 0; + } + + definition->m_size = AlignmentUtils::Align(definition->m_size, + member->GetForceAlignment() ? member->GetAlignment() : std::min(member->GetAlignment(), definition->m_pack)); + + member->m_offset = definition->m_size; + + definition->m_size += member->m_type_declaration->GetSize(); } + } - definition->m_size = AlignmentUtils::Align(definition->m_size, definition->m_alignment); + if (currentBitOffset > 0) { + currentBitOffset = AlignmentUtils::Align(currentBitOffset, 8u); + definition->m_size += currentBitOffset / 8; + } - return true; + definition->m_size = AlignmentUtils::Align(definition->m_size, definition->m_alignment); + + return true; } -bool CalculateSizeAndAlignPostProcessor::CalculateSize(IDataRepository* repository, UnionDefinition* definition) -{ - definition->m_size = 0; +bool CalculateSizeAndAlignPostProcessor::CalculateSize(IDataRepository *repository, UnionDefinition *definition) { + definition->m_size = 0; - for (const auto& member : definition->m_members) - { - if (!CalculateFields(repository, member->m_type_declaration.get())) - return false; + for (const auto &member : definition->m_members) { + if (!CalculateFields(repository, member->m_type_declaration.get())) + return false; - member->m_offset = 0; + member->m_offset = 0; - const auto memberSize = member->m_type_declaration->GetSize(); - if (memberSize > definition->m_size) - definition->m_size = memberSize; - } + const auto memberSize = member->m_type_declaration->GetSize(); + if (memberSize > definition->m_size) + definition->m_size = memberSize; + } - definition->m_size = AlignmentUtils::Align(definition->m_size, definition->m_alignment); + definition->m_size = AlignmentUtils::Align(definition->m_size, definition->m_alignment); - return true; + return true; } -bool CalculateSizeAndAlignPostProcessor::CalculateFields(IDataRepository* repository, TypeDeclaration* declaration) -{ - if (declaration->m_flags & TypeDeclaration::FLAG_FIELDS_CALCULATED) - return true; +bool CalculateSizeAndAlignPostProcessor::CalculateFields(IDataRepository *repository, TypeDeclaration *declaration) { + if (declaration->m_flags & TypeDeclaration::FLAG_FIELDS_CALCULATED) + return true; - if(!CalculateAlign(repository, declaration) - || !CalculateSize(repository, declaration)) - { - return false; - } + if (!CalculateAlign(repository, declaration) || !CalculateSize(repository, declaration)) { + return false; + } - declaration->m_flags |= TypeDeclaration::FLAG_FIELDS_CALCULATED; - return true; + declaration->m_flags |= TypeDeclaration::FLAG_FIELDS_CALCULATED; + return true; } -bool CalculateSizeAndAlignPostProcessor::CalculateFields(IDataRepository* repository, StructDefinition* structDefinition) -{ - if (structDefinition->m_flags & DefinitionWithMembers::FLAG_FIELDS_CALCULATED) - return true; - if (structDefinition->m_flags & DefinitionWithMembers::FLAG_FIELDS_CALCULATING) - { - std::cout << "Detected circular dependency:\n"; - return false; - } +bool CalculateSizeAndAlignPostProcessor::CalculateFields(IDataRepository *repository, StructDefinition *structDefinition) { + if (structDefinition->m_flags & DefinitionWithMembers::FLAG_FIELDS_CALCULATED) + return true; + if (structDefinition->m_flags & DefinitionWithMembers::FLAG_FIELDS_CALCULATING) { + std::cout << "Detected circular dependency:\n"; + return false; + } - structDefinition->m_flags |= DefinitionWithMembers::FLAG_FIELDS_CALCULATING; + structDefinition->m_flags |= DefinitionWithMembers::FLAG_FIELDS_CALCULATING; - if (!CalculateAlign(repository, structDefinition) - || !CalculateSize(repository, structDefinition)) - { - return false; - } + if (!CalculateAlign(repository, structDefinition) || !CalculateSize(repository, structDefinition)) { + return false; + } - structDefinition->m_flags &= ~DefinitionWithMembers::FLAG_FIELDS_CALCULATING; - structDefinition->m_flags |= DefinitionWithMembers::FLAG_FIELDS_CALCULATED; + structDefinition->m_flags &= ~DefinitionWithMembers::FLAG_FIELDS_CALCULATING; + structDefinition->m_flags |= DefinitionWithMembers::FLAG_FIELDS_CALCULATED; - return true; + return true; } -bool CalculateSizeAndAlignPostProcessor::CalculateFields(IDataRepository* repository, UnionDefinition* unionDefinition) -{ - if (unionDefinition->m_flags & DefinitionWithMembers::FLAG_FIELDS_CALCULATED) - return true; - if (unionDefinition->m_flags & DefinitionWithMembers::FLAG_FIELDS_CALCULATING) - { - std::cout << "Detected circular dependency:\n"; - return false; - } +bool CalculateSizeAndAlignPostProcessor::CalculateFields(IDataRepository *repository, UnionDefinition *unionDefinition) { + if (unionDefinition->m_flags & DefinitionWithMembers::FLAG_FIELDS_CALCULATED) + return true; + if (unionDefinition->m_flags & DefinitionWithMembers::FLAG_FIELDS_CALCULATING) { + std::cout << "Detected circular dependency:\n"; + return false; + } - unionDefinition->m_flags |= DefinitionWithMembers::FLAG_FIELDS_CALCULATING; + unionDefinition->m_flags |= DefinitionWithMembers::FLAG_FIELDS_CALCULATING; - if (!CalculateAlign(repository, unionDefinition) - || !CalculateSize(repository, unionDefinition)) - { - return false; - } + if (!CalculateAlign(repository, unionDefinition) || !CalculateSize(repository, unionDefinition)) { + return false; + } - unionDefinition->m_flags &= ~DefinitionWithMembers::FLAG_FIELDS_CALCULATING; - unionDefinition->m_flags |= DefinitionWithMembers::FLAG_FIELDS_CALCULATED; + unionDefinition->m_flags &= ~DefinitionWithMembers::FLAG_FIELDS_CALCULATING; + unionDefinition->m_flags |= DefinitionWithMembers::FLAG_FIELDS_CALCULATED; - return true; + return true; } -bool CalculateSizeAndAlignPostProcessor::CalculateFieldsIfNecessary(IDataRepository* repository, const DataDefinition* definition) -{ - if(definition->GetType() == DataDefinitionType::STRUCT) - { - // We can do a const cast here because the only reason that field is const anyway is because it could be a base type - return CalculateFields(repository, dynamic_cast<StructDefinition*>(const_cast<DataDefinition*>(definition))); - } +bool CalculateSizeAndAlignPostProcessor::CalculateFieldsIfNecessary(IDataRepository *repository, const DataDefinition *definition) { + if (definition->GetType() == DataDefinitionType::STRUCT) { + // We can do a const cast here because the only reason that field is const anyway is because it could be a base type + return CalculateFields(repository, dynamic_cast<StructDefinition *>(const_cast<DataDefinition *>(definition))); + } - if(definition->GetType() == DataDefinitionType::UNION) - { - // We can do a const cast here because the only reason that field is const anyway is because it could be a base type - return CalculateFields(repository, dynamic_cast<UnionDefinition*>(const_cast<DataDefinition*>(definition))); - } + if (definition->GetType() == DataDefinitionType::UNION) { + // We can do a const cast here because the only reason that field is const anyway is because it could be a base type + return CalculateFields(repository, dynamic_cast<UnionDefinition *>(const_cast<DataDefinition *>(definition))); + } - if(definition->GetType() == DataDefinitionType::TYPEDEF) - { - // We can do a const cast here because the only reason that field is const anyway is because it could be a base type - return CalculateFields(repository, dynamic_cast<TypedefDefinition*>(const_cast<DataDefinition*>(definition))->m_type_declaration.get()); - } + if (definition->GetType() == DataDefinitionType::TYPEDEF) { + // We can do a const cast here because the only reason that field is const anyway is because it could be a base type + return CalculateFields(repository, dynamic_cast<TypedefDefinition *>(const_cast<DataDefinition *>(definition))->m_type_declaration.get()); + } - return true; + return true; } -bool CalculateSizeAndAlignPostProcessor::PostProcess(IDataRepository* repository) -{ - if (repository->GetArchitecture() == Architecture::UNKNOWN) - { - std::cout << "You must set an architecture!" << std::endl; - return false; - } +bool CalculateSizeAndAlignPostProcessor::PostProcess(IDataRepository *repository) { + if (repository->GetArchitecture() == Architecture::UNKNOWN) { + std::cout << "You must set an architecture!" << std::endl; + return false; + } - for (auto* structDefinition : repository->GetAllStructs()) - { - if (!CalculateFields(repository, structDefinition)) - { - std::cout << std::endl; - return false; - } + for (auto *structDefinition : repository->GetAllStructs()) { + if (!CalculateFields(repository, structDefinition)) { + std::cout << std::endl; + return false; } + } - for (auto* unionDefinition : repository->GetAllUnions()) - { - if (!CalculateFields(repository, unionDefinition)) - { - std::cout << std::endl; - return false; - } + for (auto *unionDefinition : repository->GetAllUnions()) { + if (!CalculateFields(repository, unionDefinition)) { + std::cout << std::endl; + return false; } + } - for (auto* typedefDeclaration : repository->GetAllTypedefs()) - { - if (!CalculateFields(repository, typedefDeclaration->m_type_declaration.get())) - { - std::cout << std::endl; - return false; - } + for (auto *typedefDeclaration : repository->GetAllTypedefs()) { + if (!CalculateFields(repository, typedefDeclaration->m_type_declaration.get())) { + std::cout << std::endl; + return false; } + } - return true; + return true; } diff --git a/src/ZoneCodeGeneratorLib/Parsing/PostProcessing/CalculateSizeAndAlignPostProcessor.h b/src/ZoneCodeGeneratorLib/Parsing/PostProcessing/CalculateSizeAndAlignPostProcessor.h index ec5adc59e..956025d6b 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/PostProcessing/CalculateSizeAndAlignPostProcessor.h +++ b/src/ZoneCodeGeneratorLib/Parsing/PostProcessing/CalculateSizeAndAlignPostProcessor.h @@ -2,19 +2,18 @@ #include "IPostProcessor.h" -class CalculateSizeAndAlignPostProcessor final : public IPostProcessor -{ - static unsigned GetPointerSizeForArchitecture(Architecture architecture); - static bool CalculateAlign(IDataRepository* repository, TypeDeclaration* declaration); - static bool CalculateAlign(IDataRepository* repository, DefinitionWithMembers* definition); - static bool CalculateSize(IDataRepository* repository, TypeDeclaration* declaration); - static bool CalculateSize(IDataRepository* repository, StructDefinition* definition); - static bool CalculateSize(IDataRepository* repository, UnionDefinition* definition); - static bool CalculateFields(IDataRepository* repository, TypeDeclaration* declaration); - static bool CalculateFields(IDataRepository* repository, StructDefinition* structDefinition); - static bool CalculateFields(IDataRepository* repository, UnionDefinition* unionDefinition); - static bool CalculateFieldsIfNecessary(IDataRepository* repository, const DataDefinition* definition); +class CalculateSizeAndAlignPostProcessor final : public IPostProcessor { + static unsigned GetPointerSizeForArchitecture(Architecture architecture); + static bool CalculateAlign(IDataRepository *repository, TypeDeclaration *declaration); + static bool CalculateAlign(IDataRepository *repository, DefinitionWithMembers *definition); + static bool CalculateSize(IDataRepository *repository, TypeDeclaration *declaration); + static bool CalculateSize(IDataRepository *repository, StructDefinition *definition); + static bool CalculateSize(IDataRepository *repository, UnionDefinition *definition); + static bool CalculateFields(IDataRepository *repository, TypeDeclaration *declaration); + static bool CalculateFields(IDataRepository *repository, StructDefinition *structDefinition); + static bool CalculateFields(IDataRepository *repository, UnionDefinition *unionDefinition); + static bool CalculateFieldsIfNecessary(IDataRepository *repository, const DataDefinition *definition); public: - bool PostProcess(IDataRepository* repository) override; + bool PostProcess(IDataRepository *repository) override; }; diff --git a/src/ZoneCodeGeneratorLib/Parsing/PostProcessing/CreateMemberInformationPostProcessor.cpp b/src/ZoneCodeGeneratorLib/Parsing/PostProcessing/CreateMemberInformationPostProcessor.cpp index 5bd9b5c50..b1c63366a 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/PostProcessing/CreateMemberInformationPostProcessor.cpp +++ b/src/ZoneCodeGeneratorLib/Parsing/PostProcessing/CreateMemberInformationPostProcessor.cpp @@ -2,35 +2,29 @@ #include <algorithm> -bool CreateMemberInformationPostProcessor::CreateMemberInformationForStructure(IDataRepository* repository, StructureInformation* structure) const -{ - for(const auto& member : structure->m_definition->m_members) - { - StructureInformation* typeInfo = nullptr; - const auto* currentDefinition = member->m_type_declaration->m_type; +bool CreateMemberInformationPostProcessor::CreateMemberInformationForStructure(IDataRepository *repository, StructureInformation *structure) const { + for (const auto &member : structure->m_definition->m_members) { + StructureInformation *typeInfo = nullptr; + const auto *currentDefinition = member->m_type_declaration->m_type; - while(currentDefinition->GetType() == DataDefinitionType::TYPEDEF) - { - currentDefinition = dynamic_cast<const TypedefDefinition*>(currentDefinition)->m_type_declaration->m_type; - } + while (currentDefinition->GetType() == DataDefinitionType::TYPEDEF) { + currentDefinition = dynamic_cast<const TypedefDefinition *>(currentDefinition)->m_type_declaration->m_type; + } - const auto* memberDefinition = dynamic_cast<const DefinitionWithMembers*>(currentDefinition); + const auto *memberDefinition = dynamic_cast<const DefinitionWithMembers *>(currentDefinition); - if(memberDefinition != nullptr) - typeInfo = repository->GetInformationFor(memberDefinition); + if (memberDefinition != nullptr) + typeInfo = repository->GetInformationFor(memberDefinition); - structure->m_ordered_members.emplace_back(std::make_unique<MemberInformation>(structure, typeInfo, member.get())); - } + structure->m_ordered_members.emplace_back(std::make_unique<MemberInformation>(structure, typeInfo, member.get())); + } - return true; + return true; } -bool CreateMemberInformationPostProcessor::PostProcess(IDataRepository* repository) -{ - const auto& allStructureInformation = repository->GetAllStructureInformation(); +bool CreateMemberInformationPostProcessor::PostProcess(IDataRepository *repository) { + const auto &allStructureInformation = repository->GetAllStructureInformation(); - return std::all_of(allStructureInformation.begin(), allStructureInformation.end(), [this, repository](StructureInformation* structure) - { - return CreateMemberInformationForStructure(repository, structure); - }); + return std::all_of(allStructureInformation.begin(), allStructureInformation.end(), + [this, repository](StructureInformation *structure) { return CreateMemberInformationForStructure(repository, structure); }); } diff --git a/src/ZoneCodeGeneratorLib/Parsing/PostProcessing/CreateMemberInformationPostProcessor.h b/src/ZoneCodeGeneratorLib/Parsing/PostProcessing/CreateMemberInformationPostProcessor.h index 31c83c150..d27bb3352 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/PostProcessing/CreateMemberInformationPostProcessor.h +++ b/src/ZoneCodeGeneratorLib/Parsing/PostProcessing/CreateMemberInformationPostProcessor.h @@ -2,10 +2,9 @@ #include "IPostProcessor.h" -class CreateMemberInformationPostProcessor final : public IPostProcessor -{ - bool CreateMemberInformationForStructure(IDataRepository* repository, StructureInformation* structure) const; +class CreateMemberInformationPostProcessor final : public IPostProcessor { + bool CreateMemberInformationForStructure(IDataRepository *repository, StructureInformation *structure) const; public: - bool PostProcess(IDataRepository* repository) override; + bool PostProcess(IDataRepository *repository) override; }; diff --git a/src/ZoneCodeGeneratorLib/Parsing/PostProcessing/CreateStructureInformationPostProcessor.cpp b/src/ZoneCodeGeneratorLib/Parsing/PostProcessing/CreateStructureInformationPostProcessor.cpp index 3d95f041f..1704bf84c 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/PostProcessing/CreateStructureInformationPostProcessor.cpp +++ b/src/ZoneCodeGeneratorLib/Parsing/PostProcessing/CreateStructureInformationPostProcessor.cpp @@ -1,20 +1,17 @@ #include "CreateStructureInformationPostProcessor.h" -bool CreateStructureInformationPostProcessor::PostProcess(IDataRepository* repository) -{ - for(auto* structDefinition : repository->GetAllStructs()) - { - auto* information = repository->GetInformationFor(structDefinition); - if(information == nullptr) - repository->Add(std::make_unique<StructureInformation>(structDefinition)); - } +bool CreateStructureInformationPostProcessor::PostProcess(IDataRepository *repository) { + for (auto *structDefinition : repository->GetAllStructs()) { + auto *information = repository->GetInformationFor(structDefinition); + if (information == nullptr) + repository->Add(std::make_unique<StructureInformation>(structDefinition)); + } - for(auto* unionDefinition : repository->GetAllUnions()) - { - auto* information = repository->GetInformationFor(unionDefinition); - if(information == nullptr) - repository->Add(std::make_unique<StructureInformation>(unionDefinition)); - } + for (auto *unionDefinition : repository->GetAllUnions()) { + auto *information = repository->GetInformationFor(unionDefinition); + if (information == nullptr) + repository->Add(std::make_unique<StructureInformation>(unionDefinition)); + } - return true; + return true; } diff --git a/src/ZoneCodeGeneratorLib/Parsing/PostProcessing/CreateStructureInformationPostProcessor.h b/src/ZoneCodeGeneratorLib/Parsing/PostProcessing/CreateStructureInformationPostProcessor.h index 040a011cf..75cf67611 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/PostProcessing/CreateStructureInformationPostProcessor.h +++ b/src/ZoneCodeGeneratorLib/Parsing/PostProcessing/CreateStructureInformationPostProcessor.h @@ -2,8 +2,7 @@ #include "IPostProcessor.h" -class CreateStructureInformationPostProcessor final : public IPostProcessor -{ +class CreateStructureInformationPostProcessor final : public IPostProcessor { public: - bool PostProcess(IDataRepository* repository) override; + bool PostProcess(IDataRepository *repository) override; }; diff --git a/src/ZoneCodeGeneratorLib/Parsing/PostProcessing/IPostProcessor.h b/src/ZoneCodeGeneratorLib/Parsing/PostProcessing/IPostProcessor.h index 2fc9fb452..c39d82c04 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/PostProcessing/IPostProcessor.h +++ b/src/ZoneCodeGeneratorLib/Parsing/PostProcessing/IPostProcessor.h @@ -1,15 +1,14 @@ #pragma once #include "Persistence/IDataRepository.h" -class IPostProcessor -{ +class IPostProcessor { public: - IPostProcessor() = default; - virtual ~IPostProcessor() = default; - IPostProcessor(const IPostProcessor& other) = default; - IPostProcessor(IPostProcessor&& other) noexcept = default; - IPostProcessor& operator=(const IPostProcessor& other) = default; - IPostProcessor& operator=(IPostProcessor&& other) noexcept = default; + IPostProcessor() = default; + virtual ~IPostProcessor() = default; + IPostProcessor(const IPostProcessor &other) = default; + IPostProcessor(IPostProcessor &&other) noexcept = default; + IPostProcessor &operator=(const IPostProcessor &other) = default; + IPostProcessor &operator=(IPostProcessor &&other) noexcept = default; - virtual bool PostProcess(IDataRepository* repository) = 0; + virtual bool PostProcess(IDataRepository *repository) = 0; }; diff --git a/src/ZoneCodeGeneratorLib/Parsing/PostProcessing/LeafsPostProcessor.cpp b/src/ZoneCodeGeneratorLib/Parsing/PostProcessing/LeafsPostProcessor.cpp index fa692323d..031cd43f5 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/PostProcessing/LeafsPostProcessor.cpp +++ b/src/ZoneCodeGeneratorLib/Parsing/PostProcessing/LeafsPostProcessor.cpp @@ -4,56 +4,47 @@ #include "Domain/Computations/StructureComputations.h" #include "Domain/Definition/PointerDeclarationModifier.h" -bool LeafsPostProcessor::IsLeaf(StructureInformation* info) -{ - for (const auto& member : info->m_ordered_members) - { - // If there is a condition to this member and it always evaluates to false: Skip this member - if (member->m_condition && member->m_condition->IsStatic() && member->m_condition->EvaluateNumeric() == 0) - continue; - - // Any ScriptStrings or Strings need to be processed. - if (member->m_is_script_string || member->m_is_string) - return false; - - // If there are any Pointer members that are not always count 0 it needs to be processed. - for (const auto& modifier : member->m_member->m_type_declaration->m_declaration_modifiers) - { - if (modifier->GetType() == DeclarationModifierType::POINTER) - { - auto* pointer = dynamic_cast<PointerDeclarationModifier*>(modifier.get()); - const auto* countEvaluation = pointer->GetCountEvaluation(); - - if (!countEvaluation->IsStatic() || countEvaluation->EvaluateNumeric() != 0) - return false; - } - } - - MemberComputations computations(member.get()); - - // If the member has an embedded type with dynamic size - if (computations.HasDynamicArraySize()) - return false; - - if (member->m_type != nullptr - && member->m_type != info - && !IsLeaf(member->m_type)) - { - return false; - } +bool LeafsPostProcessor::IsLeaf(StructureInformation *info) { + for (const auto &member : info->m_ordered_members) { + // If there is a condition to this member and it always evaluates to false: Skip this member + if (member->m_condition && member->m_condition->IsStatic() && member->m_condition->EvaluateNumeric() == 0) + continue; + + // Any ScriptStrings or Strings need to be processed. + if (member->m_is_script_string || member->m_is_string) + return false; + + // If there are any Pointer members that are not always count 0 it needs to be processed. + for (const auto &modifier : member->m_member->m_type_declaration->m_declaration_modifiers) { + if (modifier->GetType() == DeclarationModifierType::POINTER) { + auto *pointer = dynamic_cast<PointerDeclarationModifier *>(modifier.get()); + const auto *countEvaluation = pointer->GetCountEvaluation(); + + if (!countEvaluation->IsStatic() || countEvaluation->EvaluateNumeric() != 0) + return false; + } } - return true; -} + MemberComputations computations(member.get()); -bool LeafsPostProcessor::PostProcess(IDataRepository* repository) -{ - const auto& allInfos = repository->GetAllStructureInformation(); + // If the member has an embedded type with dynamic size + if (computations.HasDynamicArraySize()) + return false; - for (const auto& info : allInfos) - { - info->m_is_leaf = IsLeaf(info); + if (member->m_type != nullptr && member->m_type != info && !IsLeaf(member->m_type)) { + return false; } + } + + return true; +} + +bool LeafsPostProcessor::PostProcess(IDataRepository *repository) { + const auto &allInfos = repository->GetAllStructureInformation(); + + for (const auto &info : allInfos) { + info->m_is_leaf = IsLeaf(info); + } - return true; + return true; } diff --git a/src/ZoneCodeGeneratorLib/Parsing/PostProcessing/LeafsPostProcessor.h b/src/ZoneCodeGeneratorLib/Parsing/PostProcessing/LeafsPostProcessor.h index b19848b45..be58afafa 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/PostProcessing/LeafsPostProcessor.h +++ b/src/ZoneCodeGeneratorLib/Parsing/PostProcessing/LeafsPostProcessor.h @@ -2,10 +2,9 @@ #include "IPostProcessor.h" -class LeafsPostProcessor final : public IPostProcessor -{ - static bool IsLeaf(StructureInformation* info); +class LeafsPostProcessor final : public IPostProcessor { + static bool IsLeaf(StructureInformation *info); public: - bool PostProcess(IDataRepository* repository) override; + bool PostProcess(IDataRepository *repository) override; }; diff --git a/src/ZoneCodeGeneratorLib/Parsing/PostProcessing/MemberLeafsPostProcessor.cpp b/src/ZoneCodeGeneratorLib/Parsing/PostProcessing/MemberLeafsPostProcessor.cpp index 4c8d2a2dc..ac3448d58 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/PostProcessing/MemberLeafsPostProcessor.cpp +++ b/src/ZoneCodeGeneratorLib/Parsing/PostProcessing/MemberLeafsPostProcessor.cpp @@ -3,51 +3,44 @@ #include "Domain/Computations/MemberComputations.h" #include "Domain/Definition/PointerDeclarationModifier.h" -bool MemberLeafsPostProcessor::MemberIsLeaf(MemberInformation* member) -{ - if (member->m_is_string || member->m_is_script_string) - return false; +bool MemberLeafsPostProcessor::MemberIsLeaf(MemberInformation *member) { + if (member->m_is_string || member->m_is_script_string) + return false; - if (member->m_type != nullptr && !member->m_type->m_is_leaf) - return false; + if (member->m_type != nullptr && !member->m_type->m_is_leaf) + return false; - // If there are any Pointer members that are not always count 0 it needs to be processed. - for (const auto& modifier : member->m_member->m_type_declaration->m_declaration_modifiers) - { - if (modifier->GetType() == DeclarationModifierType::POINTER) - { - auto* pointer = dynamic_cast<PointerDeclarationModifier*>(modifier.get()); - const auto* countEvaluation = pointer->GetCountEvaluation(); - - if (!countEvaluation->IsStatic() || countEvaluation->EvaluateNumeric() != 0) - return false; - } + // If there are any Pointer members that are not always count 0 it needs to be processed. + for (const auto &modifier : member->m_member->m_type_declaration->m_declaration_modifiers) { + if (modifier->GetType() == DeclarationModifierType::POINTER) { + auto *pointer = dynamic_cast<PointerDeclarationModifier *>(modifier.get()); + const auto *countEvaluation = pointer->GetCountEvaluation(); + + if (!countEvaluation->IsStatic() || countEvaluation->EvaluateNumeric() != 0) + return false; } + } - const MemberComputations computations(member); + const MemberComputations computations(member); - if (computations.HasDynamicArraySize()) - return false; + if (computations.HasDynamicArraySize()) + return false; - return true; + return true; } -void MemberLeafsPostProcessor::ProcessInfo(StructureInformation* info) -{ - for(const auto& member : info->m_ordered_members) - { - member->m_is_leaf = MemberIsLeaf(member.get()); - } +void MemberLeafsPostProcessor::ProcessInfo(StructureInformation *info) { + for (const auto &member : info->m_ordered_members) { + member->m_is_leaf = MemberIsLeaf(member.get()); + } } -bool MemberLeafsPostProcessor::PostProcess(IDataRepository* repository) -{ - const auto& allInfos = repository->GetAllStructureInformation(); +bool MemberLeafsPostProcessor::PostProcess(IDataRepository *repository) { + const auto &allInfos = repository->GetAllStructureInformation(); - for (const auto& info : allInfos) - { - ProcessInfo(info); - } + for (const auto &info : allInfos) { + ProcessInfo(info); + } - return true; + return true; } diff --git a/src/ZoneCodeGeneratorLib/Parsing/PostProcessing/MemberLeafsPostProcessor.h b/src/ZoneCodeGeneratorLib/Parsing/PostProcessing/MemberLeafsPostProcessor.h index 763e9a798..81c49c4c2 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/PostProcessing/MemberLeafsPostProcessor.h +++ b/src/ZoneCodeGeneratorLib/Parsing/PostProcessing/MemberLeafsPostProcessor.h @@ -2,11 +2,10 @@ #include "IPostProcessor.h" -class MemberLeafsPostProcessor final : public IPostProcessor -{ - static bool MemberIsLeaf(MemberInformation* member); - static void ProcessInfo(StructureInformation* info); +class MemberLeafsPostProcessor final : public IPostProcessor { + static bool MemberIsLeaf(MemberInformation *member); + static void ProcessInfo(StructureInformation *info); public: - bool PostProcess(IDataRepository* repository) override; + bool PostProcess(IDataRepository *repository) override; }; diff --git a/src/ZoneCodeGeneratorLib/Parsing/PostProcessing/UnionsPostProcessor.cpp b/src/ZoneCodeGeneratorLib/Parsing/PostProcessing/UnionsPostProcessor.cpp index f843092ac..b977bfb98 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/PostProcessing/UnionsPostProcessor.cpp +++ b/src/ZoneCodeGeneratorLib/Parsing/PostProcessing/UnionsPostProcessor.cpp @@ -3,48 +3,41 @@ #include <algorithm> #include <iostream> -bool UnionsPostProcessor::ProcessUnion(StructureInformation* info) -{ - auto index = 0u; - auto lastEntryWithoutCondition = 0u; - auto entriesWithoutConditionCount = 0u; - - for(const auto& member : info->m_ordered_members) - { - if(!member->m_condition && !member->m_is_leaf) - { - entriesWithoutConditionCount++; - lastEntryWithoutCondition = index; - } - index++; +bool UnionsPostProcessor::ProcessUnion(StructureInformation *info) { + auto index = 0u; + auto lastEntryWithoutCondition = 0u; + auto entriesWithoutConditionCount = 0u; + + for (const auto &member : info->m_ordered_members) { + if (!member->m_condition && !member->m_is_leaf) { + entriesWithoutConditionCount++; + lastEntryWithoutCondition = index; } - - if (entriesWithoutConditionCount > 1 && !info->m_usages.empty() && !info->m_is_leaf) - { - std::cout << "Union '" << info->m_definition->GetFullName() << "' has more than one entry without a condition!" << std::endl; - return false; - } - - if (entriesWithoutConditionCount == 1) - { - // If there is only one entry without condition make it the last of the ordered members - auto entryWithoutCondition = std::move(info->m_ordered_members.at(lastEntryWithoutCondition)); - info->m_ordered_members.erase(info->m_ordered_members.begin() + lastEntryWithoutCondition); - info->m_ordered_members.emplace_back(std::move(entryWithoutCondition)); - } - - return true; + index++; + } + + if (entriesWithoutConditionCount > 1 && !info->m_usages.empty() && !info->m_is_leaf) { + std::cout << "Union '" << info->m_definition->GetFullName() << "' has more than one entry without a condition!" << std::endl; + return false; + } + + if (entriesWithoutConditionCount == 1) { + // If there is only one entry without condition make it the last of the ordered members + auto entryWithoutCondition = std::move(info->m_ordered_members.at(lastEntryWithoutCondition)); + info->m_ordered_members.erase(info->m_ordered_members.begin() + lastEntryWithoutCondition); + info->m_ordered_members.emplace_back(std::move(entryWithoutCondition)); + } + + return true; } -bool UnionsPostProcessor::PostProcess(IDataRepository* repository) -{ - const auto& allInfos = repository->GetAllStructureInformation(); +bool UnionsPostProcessor::PostProcess(IDataRepository *repository) { + const auto &allInfos = repository->GetAllStructureInformation(); - return std::all_of(allInfos.begin(), allInfos.end(), [](StructureInformation* info) - { - if (info->m_definition->GetType() != DataDefinitionType::UNION) - return true; + return std::all_of(allInfos.begin(), allInfos.end(), [](StructureInformation *info) { + if (info->m_definition->GetType() != DataDefinitionType::UNION) + return true; - return ProcessUnion(info); - }); + return ProcessUnion(info); + }); } diff --git a/src/ZoneCodeGeneratorLib/Parsing/PostProcessing/UnionsPostProcessor.h b/src/ZoneCodeGeneratorLib/Parsing/PostProcessing/UnionsPostProcessor.h index 85b9d53c6..7b893dceb 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/PostProcessing/UnionsPostProcessor.h +++ b/src/ZoneCodeGeneratorLib/Parsing/PostProcessing/UnionsPostProcessor.h @@ -2,10 +2,9 @@ #include "IPostProcessor.h" -class UnionsPostProcessor final : public IPostProcessor -{ - static bool ProcessUnion(StructureInformation* info); +class UnionsPostProcessor final : public IPostProcessor { + static bool ProcessUnion(StructureInformation *info); public: - bool PostProcess(IDataRepository* repository) override; + bool PostProcess(IDataRepository *repository) override; }; diff --git a/src/ZoneCodeGeneratorLib/Parsing/PostProcessing/UsagesPostProcessor.cpp b/src/ZoneCodeGeneratorLib/Parsing/PostProcessing/UsagesPostProcessor.cpp index cc48213b6..3e3664a97 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/PostProcessing/UsagesPostProcessor.cpp +++ b/src/ZoneCodeGeneratorLib/Parsing/PostProcessing/UsagesPostProcessor.cpp @@ -7,65 +7,60 @@ #include "Domain/Computations/MemberComputations.h" #include "Domain/Computations/StructureComputations.h" -bool UsagesPostProcessor::ProcessAsset(StructureInformation* info) -{ - std::set<StructureInformation*> processedInfos; - std::queue<StructureInformation*> processingQueue; +bool UsagesPostProcessor::ProcessAsset(StructureInformation *info) { + std::set<StructureInformation *> processedInfos; + std::queue<StructureInformation *> processingQueue; - processingQueue.push(info); + processingQueue.push(info); - while(!processingQueue.empty()) - { - auto* currentStructure = processingQueue.front(); - processingQueue.pop(); + while (!processingQueue.empty()) { + auto *currentStructure = processingQueue.front(); + processingQueue.pop(); - if(processedInfos.find(currentStructure) != processedInfos.end()) - continue; - processedInfos.emplace(currentStructure); + if (processedInfos.find(currentStructure) != processedInfos.end()) + continue; + processedInfos.emplace(currentStructure); - for (const auto& member : currentStructure->m_ordered_members) - { - if(member->m_type == nullptr) - continue; + for (const auto &member : currentStructure->m_ordered_members) { + if (member->m_type == nullptr) + continue; - const MemberComputations computations(member.get()); + const MemberComputations computations(member.get()); - if(computations.ShouldIgnore()) - continue; + if (computations.ShouldIgnore()) + continue; - if (computations.ContainsNonEmbeddedReference()) - member->m_type->m_non_embedded_reference_exists = true; + if (computations.ContainsNonEmbeddedReference()) + member->m_type->m_non_embedded_reference_exists = true; - if (computations.ContainsSinglePointerReference()) - member->m_type->m_single_pointer_reference_exists = true; + if (computations.ContainsSinglePointerReference()) + member->m_type->m_single_pointer_reference_exists = true; - if (computations.ContainsArrayPointerReference()) - member->m_type->m_array_pointer_reference_exists = true; + if (computations.ContainsArrayPointerReference()) + member->m_type->m_array_pointer_reference_exists = true; - if (computations.ContainsArrayReference()) - member->m_type->m_array_reference_exists = true; + if (computations.ContainsArrayReference()) + member->m_type->m_array_reference_exists = true; - if (computations.IsNotInDefaultNormalBlock()) - member->m_type->m_reference_from_non_default_normal_block_exists = true; + if (computations.IsNotInDefaultNormalBlock()) + member->m_type->m_reference_from_non_default_normal_block_exists = true; - if (member->m_is_reusable) - member->m_type->m_reusable_reference_exists = true; + if (member->m_is_reusable) + member->m_type->m_reusable_reference_exists = true; - member->m_type->m_usages.push_back(currentStructure); - processingQueue.push(member->m_type); - } + member->m_type->m_usages.push_back(currentStructure); + processingQueue.push(member->m_type); } + } - return true; + return true; } -bool UsagesPostProcessor::PostProcess(IDataRepository* repository) -{ - const auto& allInfos = repository->GetAllStructureInformation(); +bool UsagesPostProcessor::PostProcess(IDataRepository *repository) { + const auto &allInfos = repository->GetAllStructureInformation(); - return std::all_of(allInfos.begin(), allInfos.end(), [](StructureInformation* info) - { - const StructureComputations computations(info); - return !computations.IsAsset() || ProcessAsset(info); - }); + return std::all_of(allInfos.begin(), allInfos.end(), [](StructureInformation *info) { + const StructureComputations computations(info); + return !computations.IsAsset() || ProcessAsset(info); + }); } diff --git a/src/ZoneCodeGeneratorLib/Parsing/PostProcessing/UsagesPostProcessor.h b/src/ZoneCodeGeneratorLib/Parsing/PostProcessing/UsagesPostProcessor.h index e5b1f7784..d7e1d5037 100644 --- a/src/ZoneCodeGeneratorLib/Parsing/PostProcessing/UsagesPostProcessor.h +++ b/src/ZoneCodeGeneratorLib/Parsing/PostProcessing/UsagesPostProcessor.h @@ -2,10 +2,9 @@ #include "IPostProcessor.h" -class UsagesPostProcessor final : public IPostProcessor -{ - static bool ProcessAsset(StructureInformation* info); +class UsagesPostProcessor final : public IPostProcessor { + static bool ProcessAsset(StructureInformation *info); public: - bool PostProcess(IDataRepository* repository) override; + bool PostProcess(IDataRepository *repository) override; }; diff --git a/src/ZoneCodeGeneratorLib/Persistence/IDataRepository.h b/src/ZoneCodeGeneratorLib/Persistence/IDataRepository.h index 8bb6758b1..f0ec9a0f2 100644 --- a/src/ZoneCodeGeneratorLib/Persistence/IDataRepository.h +++ b/src/ZoneCodeGeneratorLib/Persistence/IDataRepository.h @@ -2,46 +2,45 @@ #include <vector> -#include "Utils/ClassUtils.h" #include "Domain/Definition/EnumDefinition.h" #include "Domain/Definition/StructDefinition.h" #include "Domain/Definition/TypedefDefinition.h" #include "Domain/Definition/UnionDefinition.h" #include "Domain/Environment/Architecture.h" -#include "Domain/Information/StructureInformation.h" #include "Domain/FastFile/FastFileBlock.h" +#include "Domain/Information/StructureInformation.h" +#include "Utils/ClassUtils.h" -class IDataRepository -{ +class IDataRepository { public: - IDataRepository() = default; - virtual ~IDataRepository() = default; - IDataRepository(const IDataRepository& other) = default; - IDataRepository(IDataRepository&& other) noexcept = default; - IDataRepository& operator=(const IDataRepository& other) = default; - IDataRepository& operator=(IDataRepository&& other) noexcept = default; + IDataRepository() = default; + virtual ~IDataRepository() = default; + IDataRepository(const IDataRepository &other) = default; + IDataRepository(IDataRepository &&other) noexcept = default; + IDataRepository &operator=(const IDataRepository &other) = default; + IDataRepository &operator=(IDataRepository &&other) noexcept = default; - virtual void Add(std::unique_ptr<EnumDefinition> enumsDefinition) = 0; - virtual void Add(std::unique_ptr<StructDefinition> structDefinition) = 0; - virtual void Add(std::unique_ptr<UnionDefinition> unionDefinition) = 0; - virtual void Add(std::unique_ptr<TypedefDefinition> typedefDefinition) = 0; - virtual void Add(std::unique_ptr<StructureInformation> structureInformation) = 0; - virtual void Add(std::unique_ptr<FastFileBlock> fastFileBlock) = 0; + virtual void Add(std::unique_ptr<EnumDefinition> enumsDefinition) = 0; + virtual void Add(std::unique_ptr<StructDefinition> structDefinition) = 0; + virtual void Add(std::unique_ptr<UnionDefinition> unionDefinition) = 0; + virtual void Add(std::unique_ptr<TypedefDefinition> typedefDefinition) = 0; + virtual void Add(std::unique_ptr<StructureInformation> structureInformation) = 0; + virtual void Add(std::unique_ptr<FastFileBlock> fastFileBlock) = 0; - _NODISCARD virtual const std::string& GetGameName() const = 0; - virtual void SetGame(std::string gameName) = 0; - _NODISCARD virtual Architecture GetArchitecture() const = 0; - virtual void SetArchitecture(Architecture architecture) = 0; + _NODISCARD virtual const std::string &GetGameName() const = 0; + virtual void SetGame(std::string gameName) = 0; + _NODISCARD virtual Architecture GetArchitecture() const = 0; + virtual void SetArchitecture(Architecture architecture) = 0; - _NODISCARD virtual const std::vector<EnumDefinition*>& GetAllEnums() const = 0; - _NODISCARD virtual const std::vector<StructDefinition*>& GetAllStructs() const = 0; - _NODISCARD virtual const std::vector<UnionDefinition*>& GetAllUnions() const = 0; - _NODISCARD virtual const std::vector<TypedefDefinition*>& GetAllTypedefs() const = 0; - _NODISCARD virtual const std::vector<StructureInformation*>& GetAllStructureInformation() const = 0; - _NODISCARD virtual const std::vector<const FastFileBlock*>& GetAllFastFileBlocks() const = 0; + _NODISCARD virtual const std::vector<EnumDefinition *> &GetAllEnums() const = 0; + _NODISCARD virtual const std::vector<StructDefinition *> &GetAllStructs() const = 0; + _NODISCARD virtual const std::vector<UnionDefinition *> &GetAllUnions() const = 0; + _NODISCARD virtual const std::vector<TypedefDefinition *> &GetAllTypedefs() const = 0; + _NODISCARD virtual const std::vector<StructureInformation *> &GetAllStructureInformation() const = 0; + _NODISCARD virtual const std::vector<const FastFileBlock *> &GetAllFastFileBlocks() const = 0; - _NODISCARD virtual DataDefinition* GetDataDefinitionByName(const std::string& name) const = 0; - _NODISCARD virtual StructureInformation* GetInformationFor(const DefinitionWithMembers* definitionWithMembers) const = 0; - _NODISCARD virtual EnumMember* GetEnumMemberByName(const std::string& name) const = 0; - _NODISCARD virtual const FastFileBlock* GetFastFileBlockByName(const std::string& name) const = 0; + _NODISCARD virtual DataDefinition *GetDataDefinitionByName(const std::string &name) const = 0; + _NODISCARD virtual StructureInformation *GetInformationFor(const DefinitionWithMembers *definitionWithMembers) const = 0; + _NODISCARD virtual EnumMember *GetEnumMemberByName(const std::string &name) const = 0; + _NODISCARD virtual const FastFileBlock *GetFastFileBlockByName(const std::string &name) const = 0; }; diff --git a/src/ZoneCodeGeneratorLib/Persistence/InMemory/InMemoryRepository.cpp b/src/ZoneCodeGeneratorLib/Persistence/InMemory/InMemoryRepository.cpp index 62cd54f35..a0748e47c 100644 --- a/src/ZoneCodeGeneratorLib/Persistence/InMemory/InMemoryRepository.cpp +++ b/src/ZoneCodeGeneratorLib/Persistence/InMemory/InMemoryRepository.cpp @@ -1,157 +1,113 @@ #include "InMemoryRepository.h" -InMemoryRepository::InMemoryRepository() - : m_architecture(Architecture::UNKNOWN) -{ -} +InMemoryRepository::InMemoryRepository() : m_architecture(Architecture::UNKNOWN) {} -InMemoryRepository::~InMemoryRepository() -{ - for (auto* enumDefinition : m_enums) - delete enumDefinition; - for (auto* structDefinition : m_structs) - delete structDefinition; - for (auto* unionDefinition : m_unions) - delete unionDefinition; - for (auto* typedefDefinition : m_typedefs) - delete typedefDefinition; - for (auto* structureInformation : m_structures_information) - delete structureInformation; - for (const auto* fastFileBlock : m_fast_file_blocks) - delete fastFileBlock; +InMemoryRepository::~InMemoryRepository() { + for (auto *enumDefinition : m_enums) + delete enumDefinition; + for (auto *structDefinition : m_structs) + delete structDefinition; + for (auto *unionDefinition : m_unions) + delete unionDefinition; + for (auto *typedefDefinition : m_typedefs) + delete typedefDefinition; + for (auto *structureInformation : m_structures_information) + delete structureInformation; + for (const auto *fastFileBlock : m_fast_file_blocks) + delete fastFileBlock; } -void InMemoryRepository::Add(std::unique_ptr<EnumDefinition> enumsDefinition) -{ - auto* raw = enumsDefinition.release(); - m_enums.push_back(raw); - m_data_definitions_by_name[raw->m_name] = raw; +void InMemoryRepository::Add(std::unique_ptr<EnumDefinition> enumsDefinition) { + auto *raw = enumsDefinition.release(); + m_enums.push_back(raw); + m_data_definitions_by_name[raw->m_name] = raw; - for (const auto& enumMember : raw->m_members) - m_enum_members_by_name[enumMember->m_name] = enumMember.get(); + for (const auto &enumMember : raw->m_members) + m_enum_members_by_name[enumMember->m_name] = enumMember.get(); } -void InMemoryRepository::Add(std::unique_ptr<StructDefinition> structDefinition) -{ - auto* raw = structDefinition.release(); - m_structs.push_back(raw); - m_data_definitions_by_name[raw->m_name] = raw; +void InMemoryRepository::Add(std::unique_ptr<StructDefinition> structDefinition) { + auto *raw = structDefinition.release(); + m_structs.push_back(raw); + m_data_definitions_by_name[raw->m_name] = raw; } -void InMemoryRepository::Add(std::unique_ptr<UnionDefinition> unionDefinition) -{ - auto* raw = unionDefinition.release(); - m_unions.push_back(raw); - m_data_definitions_by_name[raw->m_name] = raw; +void InMemoryRepository::Add(std::unique_ptr<UnionDefinition> unionDefinition) { + auto *raw = unionDefinition.release(); + m_unions.push_back(raw); + m_data_definitions_by_name[raw->m_name] = raw; } -void InMemoryRepository::Add(std::unique_ptr<TypedefDefinition> typedefDefinition) -{ - auto* raw = typedefDefinition.release(); - m_typedefs.push_back(raw); - m_data_definitions_by_name[raw->m_name] = raw; +void InMemoryRepository::Add(std::unique_ptr<TypedefDefinition> typedefDefinition) { + auto *raw = typedefDefinition.release(); + m_typedefs.push_back(raw); + m_data_definitions_by_name[raw->m_name] = raw; } -void InMemoryRepository::Add(std::unique_ptr<StructureInformation> structureInformation) -{ - auto* raw = structureInformation.release(); - m_structures_information.push_back(raw); - m_structure_information_by_definition[raw->m_definition] = raw; +void InMemoryRepository::Add(std::unique_ptr<StructureInformation> structureInformation) { + auto *raw = structureInformation.release(); + m_structures_information.push_back(raw); + m_structure_information_by_definition[raw->m_definition] = raw; } -void InMemoryRepository::Add(std::unique_ptr<FastFileBlock> fastFileBlock) -{ - auto* raw = fastFileBlock.release(); - m_fast_file_blocks.push_back(raw); - m_fast_file_blocks_by_name[raw->m_name] = raw; +void InMemoryRepository::Add(std::unique_ptr<FastFileBlock> fastFileBlock) { + auto *raw = fastFileBlock.release(); + m_fast_file_blocks.push_back(raw); + m_fast_file_blocks_by_name[raw->m_name] = raw; } -const std::string& InMemoryRepository::GetGameName() const -{ - return m_game_name; -} +const std::string &InMemoryRepository::GetGameName() const { return m_game_name; } -void InMemoryRepository::SetGame(std::string gameName) -{ - m_game_name = std::move(gameName); -} +void InMemoryRepository::SetGame(std::string gameName) { m_game_name = std::move(gameName); } -Architecture InMemoryRepository::GetArchitecture() const -{ - return m_architecture; -} +Architecture InMemoryRepository::GetArchitecture() const { return m_architecture; } -void InMemoryRepository::SetArchitecture(const Architecture architecture) -{ - m_architecture = architecture; -} +void InMemoryRepository::SetArchitecture(const Architecture architecture) { m_architecture = architecture; } -const std::vector<EnumDefinition*>& InMemoryRepository::GetAllEnums() const -{ - return m_enums; -} +const std::vector<EnumDefinition *> &InMemoryRepository::GetAllEnums() const { return m_enums; } -const std::vector<StructDefinition*>& InMemoryRepository::GetAllStructs() const -{ - return m_structs; -} +const std::vector<StructDefinition *> &InMemoryRepository::GetAllStructs() const { return m_structs; } -const std::vector<UnionDefinition*>& InMemoryRepository::GetAllUnions() const -{ - return m_unions; -} +const std::vector<UnionDefinition *> &InMemoryRepository::GetAllUnions() const { return m_unions; } -const std::vector<TypedefDefinition*>& InMemoryRepository::GetAllTypedefs() const -{ - return m_typedefs; -} +const std::vector<TypedefDefinition *> &InMemoryRepository::GetAllTypedefs() const { return m_typedefs; } -const std::vector<StructureInformation*>& InMemoryRepository::GetAllStructureInformation() const -{ - return m_structures_information; -} +const std::vector<StructureInformation *> &InMemoryRepository::GetAllStructureInformation() const { return m_structures_information; } -const std::vector<const FastFileBlock*>& InMemoryRepository::GetAllFastFileBlocks() const -{ - return m_fast_file_blocks; -} +const std::vector<const FastFileBlock *> &InMemoryRepository::GetAllFastFileBlocks() const { return m_fast_file_blocks; } -DataDefinition* InMemoryRepository::GetDataDefinitionByName(const std::string& name) const -{ - const auto foundEntry = m_data_definitions_by_name.find(name); +DataDefinition *InMemoryRepository::GetDataDefinitionByName(const std::string &name) const { + const auto foundEntry = m_data_definitions_by_name.find(name); - if (foundEntry != m_data_definitions_by_name.end()) - return foundEntry->second; + if (foundEntry != m_data_definitions_by_name.end()) + return foundEntry->second; - return nullptr; + return nullptr; } -StructureInformation* InMemoryRepository::GetInformationFor(const DefinitionWithMembers* definitionWithMembers) const -{ - const auto foundEntry = m_structure_information_by_definition.find(definitionWithMembers); +StructureInformation *InMemoryRepository::GetInformationFor(const DefinitionWithMembers *definitionWithMembers) const { + const auto foundEntry = m_structure_information_by_definition.find(definitionWithMembers); - if (foundEntry != m_structure_information_by_definition.end()) - return foundEntry->second; + if (foundEntry != m_structure_information_by_definition.end()) + return foundEntry->second; - return nullptr; + return nullptr; } -EnumMember* InMemoryRepository::GetEnumMemberByName(const std::string& name) const -{ - const auto foundEntry = m_enum_members_by_name.find(name); +EnumMember *InMemoryRepository::GetEnumMemberByName(const std::string &name) const { + const auto foundEntry = m_enum_members_by_name.find(name); - if (foundEntry != m_enum_members_by_name.end()) - return foundEntry->second; + if (foundEntry != m_enum_members_by_name.end()) + return foundEntry->second; - return nullptr; + return nullptr; } -const FastFileBlock* InMemoryRepository::GetFastFileBlockByName(const std::string& name) const -{ - const auto foundEntry = m_fast_file_blocks_by_name.find(name); +const FastFileBlock *InMemoryRepository::GetFastFileBlockByName(const std::string &name) const { + const auto foundEntry = m_fast_file_blocks_by_name.find(name); - if (foundEntry != m_fast_file_blocks_by_name.end()) - return foundEntry->second; + if (foundEntry != m_fast_file_blocks_by_name.end()) + return foundEntry->second; - return nullptr; + return nullptr; } diff --git a/src/ZoneCodeGeneratorLib/Persistence/InMemory/InMemoryRepository.h b/src/ZoneCodeGeneratorLib/Persistence/InMemory/InMemoryRepository.h index 3ba5566df..6036d3df9 100644 --- a/src/ZoneCodeGeneratorLib/Persistence/InMemory/InMemoryRepository.h +++ b/src/ZoneCodeGeneratorLib/Persistence/InMemory/InMemoryRepository.h @@ -4,50 +4,49 @@ #include "Persistence/IDataRepository.h" -class InMemoryRepository final : public IDataRepository -{ - std::vector<EnumDefinition*> m_enums; - std::vector<StructDefinition*> m_structs; - std::vector<UnionDefinition*> m_unions; - std::vector<TypedefDefinition*> m_typedefs; - std::vector<StructureInformation*> m_structures_information; - std::vector<const FastFileBlock*> m_fast_file_blocks; - std::map<std::string, DataDefinition*> m_data_definitions_by_name; - std::map<std::string, EnumMember*> m_enum_members_by_name; - std::map<std::string, const FastFileBlock*> m_fast_file_blocks_by_name; - std::map<const DefinitionWithMembers*, StructureInformation*> m_structure_information_by_definition; - std::string m_game_name; - Architecture m_architecture; +class InMemoryRepository final : public IDataRepository { + std::vector<EnumDefinition *> m_enums; + std::vector<StructDefinition *> m_structs; + std::vector<UnionDefinition *> m_unions; + std::vector<TypedefDefinition *> m_typedefs; + std::vector<StructureInformation *> m_structures_information; + std::vector<const FastFileBlock *> m_fast_file_blocks; + std::map<std::string, DataDefinition *> m_data_definitions_by_name; + std::map<std::string, EnumMember *> m_enum_members_by_name; + std::map<std::string, const FastFileBlock *> m_fast_file_blocks_by_name; + std::map<const DefinitionWithMembers *, StructureInformation *> m_structure_information_by_definition; + std::string m_game_name; + Architecture m_architecture; public: - InMemoryRepository(); - ~InMemoryRepository() override; - InMemoryRepository(const InMemoryRepository& other) = delete; - InMemoryRepository(InMemoryRepository&& other) noexcept = default; - InMemoryRepository& operator=(const InMemoryRepository& other) = delete; - InMemoryRepository& operator=(InMemoryRepository&& other) noexcept = default; - - void Add(std::unique_ptr<EnumDefinition> enumsDefinition) override; - void Add(std::unique_ptr<StructDefinition> structDefinition) override; - void Add(std::unique_ptr<UnionDefinition> unionDefinition) override; - void Add(std::unique_ptr<TypedefDefinition> typedefDefinition) override; - void Add(std::unique_ptr<StructureInformation> structureInformation) override; - void Add(std::unique_ptr<FastFileBlock> fastFileBlock) override; - - _NODISCARD const std::string& GetGameName() const override; - void SetGame(std::string gameName) override; - _NODISCARD Architecture GetArchitecture() const override; - void SetArchitecture(Architecture architecture) override; - - _NODISCARD const std::vector<EnumDefinition*>& GetAllEnums() const override; - _NODISCARD const std::vector<StructDefinition*>& GetAllStructs() const override; - _NODISCARD const std::vector<UnionDefinition*>& GetAllUnions() const override; - _NODISCARD const std::vector<TypedefDefinition*>& GetAllTypedefs() const override; - _NODISCARD const std::vector<StructureInformation*>& GetAllStructureInformation() const override; - _NODISCARD const std::vector<const FastFileBlock*>& GetAllFastFileBlocks() const override; - - _NODISCARD DataDefinition* GetDataDefinitionByName(const std::string& name) const override; - _NODISCARD StructureInformation* GetInformationFor(const DefinitionWithMembers* definitionWithMembers) const override; - _NODISCARD EnumMember* GetEnumMemberByName(const std::string& name) const override; - _NODISCARD const FastFileBlock* GetFastFileBlockByName(const std::string& name) const override; + InMemoryRepository(); + ~InMemoryRepository() override; + InMemoryRepository(const InMemoryRepository &other) = delete; + InMemoryRepository(InMemoryRepository &&other) noexcept = default; + InMemoryRepository &operator=(const InMemoryRepository &other) = delete; + InMemoryRepository &operator=(InMemoryRepository &&other) noexcept = default; + + void Add(std::unique_ptr<EnumDefinition> enumsDefinition) override; + void Add(std::unique_ptr<StructDefinition> structDefinition) override; + void Add(std::unique_ptr<UnionDefinition> unionDefinition) override; + void Add(std::unique_ptr<TypedefDefinition> typedefDefinition) override; + void Add(std::unique_ptr<StructureInformation> structureInformation) override; + void Add(std::unique_ptr<FastFileBlock> fastFileBlock) override; + + _NODISCARD const std::string &GetGameName() const override; + void SetGame(std::string gameName) override; + _NODISCARD Architecture GetArchitecture() const override; + void SetArchitecture(Architecture architecture) override; + + _NODISCARD const std::vector<EnumDefinition *> &GetAllEnums() const override; + _NODISCARD const std::vector<StructDefinition *> &GetAllStructs() const override; + _NODISCARD const std::vector<UnionDefinition *> &GetAllUnions() const override; + _NODISCARD const std::vector<TypedefDefinition *> &GetAllTypedefs() const override; + _NODISCARD const std::vector<StructureInformation *> &GetAllStructureInformation() const override; + _NODISCARD const std::vector<const FastFileBlock *> &GetAllFastFileBlocks() const override; + + _NODISCARD DataDefinition *GetDataDefinitionByName(const std::string &name) const override; + _NODISCARD StructureInformation *GetInformationFor(const DefinitionWithMembers *definitionWithMembers) const override; + _NODISCARD EnumMember *GetEnumMemberByName(const std::string &name) const override; + _NODISCARD const FastFileBlock *GetFastFileBlockByName(const std::string &name) const override; }; diff --git a/src/ZoneCodeGeneratorLib/Printing/PrettyPrinter.cpp b/src/ZoneCodeGeneratorLib/Printing/PrettyPrinter.cpp index d6306c799..9577cb70a 100644 --- a/src/ZoneCodeGeneratorLib/Printing/PrettyPrinter.cpp +++ b/src/ZoneCodeGeneratorLib/Printing/PrettyPrinter.cpp @@ -1,299 +1,251 @@ #include "PrettyPrinter.h" - #include <algorithm> #include <iostream> - #include "Domain/Definition/ArrayDeclarationModifier.h" #include "Utils/NamespaceBuilder.h" -PrettyPrinter::PrettyPrinter(std::ostream& stream, const IDataRepository* repository) - : m_stream(stream), - m_repository(repository) -{ -} +PrettyPrinter::PrettyPrinter(std::ostream &stream, const IDataRepository *repository) : m_stream(stream), m_repository(repository) {} -void PrettyPrinter::PrintSeparator() const -{ - m_stream << std::endl - << "==========================================================================================================" << std::endl - << std::endl; +void PrettyPrinter::PrintSeparator() const { + m_stream << std::endl + << "==========================================================================================================" << std::endl + << std::endl; } -void PrettyPrinter::PrintVariablePointerToArray(Variable* variable) const -{ - const auto& declarationModifiers = variable->m_type_declaration->m_declaration_modifiers; +void PrettyPrinter::PrintVariablePointerToArray(Variable *variable) const { + const auto &declarationModifiers = variable->m_type_declaration->m_declaration_modifiers; - std::vector<int> arraySize; - auto pointerDepth = 0; - auto modifierOffset = 0u; + std::vector<int> arraySize; + auto pointerDepth = 0; + auto modifierOffset = 0u; - for (; modifierOffset < declarationModifiers.size(); modifierOffset++) - { - const auto& modifier = declarationModifiers[modifierOffset]; - if (modifier->GetType() != DeclarationModifierType::POINTER) - break; + for (; modifierOffset < declarationModifiers.size(); modifierOffset++) { + const auto &modifier = declarationModifiers[modifierOffset]; + if (modifier->GetType() != DeclarationModifierType::POINTER) + break; - pointerDepth++; - } + pointerDepth++; + } - for (; modifierOffset < declarationModifiers.size(); modifierOffset++) - { - const auto& modifier = declarationModifiers[modifierOffset]; - if (modifier->GetType() != DeclarationModifierType::ARRAY) - break; + for (; modifierOffset < declarationModifiers.size(); modifierOffset++) { + const auto &modifier = declarationModifiers[modifierOffset]; + if (modifier->GetType() != DeclarationModifierType::ARRAY) + break; - arraySize.push_back(dynamic_cast<ArrayDeclarationModifier*>(modifier.get())->m_size); - } + arraySize.push_back(dynamic_cast<ArrayDeclarationModifier *>(modifier.get())->m_size); + } - m_stream << " " << variable->m_type_declaration->m_type->GetFullName() << '('; - for (auto p = 0; p < pointerDepth; p++) - m_stream << '*'; - m_stream << variable->m_name << ")"; - for (auto size : arraySize) - m_stream << '[' << size << ']'; - m_stream << std::endl; + m_stream << " " << variable->m_type_declaration->m_type->GetFullName() << '('; + for (auto p = 0; p < pointerDepth; p++) + m_stream << '*'; + m_stream << variable->m_name << ")"; + for (auto size : arraySize) + m_stream << '[' << size << ']'; + m_stream << std::endl; } -void PrettyPrinter::PrintVariableArrayOfPointers(Variable* variable) const -{ - const auto& declarationModifiers = variable->m_type_declaration->m_declaration_modifiers; +void PrettyPrinter::PrintVariableArrayOfPointers(Variable *variable) const { + const auto &declarationModifiers = variable->m_type_declaration->m_declaration_modifiers; - std::vector<int> arraySize; - auto pointerDepth = 0; - auto modifierOffset = 0u; + std::vector<int> arraySize; + auto pointerDepth = 0; + auto modifierOffset = 0u; - for(; modifierOffset < declarationModifiers.size(); modifierOffset++) - { - const auto& modifier = declarationModifiers[modifierOffset]; - if (modifier->GetType() != DeclarationModifierType::ARRAY) - break; + for (; modifierOffset < declarationModifiers.size(); modifierOffset++) { + const auto &modifier = declarationModifiers[modifierOffset]; + if (modifier->GetType() != DeclarationModifierType::ARRAY) + break; - arraySize.push_back(dynamic_cast<ArrayDeclarationModifier*>(modifier.get())->m_size); - } + arraySize.push_back(dynamic_cast<ArrayDeclarationModifier *>(modifier.get())->m_size); + } - for(; modifierOffset < declarationModifiers.size(); modifierOffset++) - { - const auto& modifier = declarationModifiers[modifierOffset]; - if (modifier->GetType() != DeclarationModifierType::POINTER) - break; + for (; modifierOffset < declarationModifiers.size(); modifierOffset++) { + const auto &modifier = declarationModifiers[modifierOffset]; + if (modifier->GetType() != DeclarationModifierType::POINTER) + break; - pointerDepth++; - } + pointerDepth++; + } - m_stream << " " << variable->m_type_declaration->m_type->GetFullName(); - for (auto p = 0; p < pointerDepth; p++) - m_stream << '*'; - m_stream << " " << variable->m_name; - for (auto size : arraySize) - m_stream << '[' << size << ']'; - m_stream << std::endl; + m_stream << " " << variable->m_type_declaration->m_type->GetFullName(); + for (auto p = 0; p < pointerDepth; p++) + m_stream << '*'; + m_stream << " " << variable->m_name; + for (auto size : arraySize) + m_stream << '[' << size << ']'; + m_stream << std::endl; } -void PrettyPrinter::PrintVariable(Variable* variable) const -{ - const auto& declarationModifiers = variable->m_type_declaration->m_declaration_modifiers; - if (declarationModifiers.empty()) - { - std::cout << " " << variable->m_type_declaration->m_type->GetFullName() << " " << variable->m_name << std::endl; - } - else - { - if (declarationModifiers[0]->GetType() == DeclarationModifierType::POINTER - && std::any_of(declarationModifiers.begin(), declarationModifiers.end(), [](const std::unique_ptr<DeclarationModifier>& modifier) - { - return modifier->GetType() == DeclarationModifierType::ARRAY; - })) - { - PrintVariablePointerToArray(variable); - } - else - { - PrintVariableArrayOfPointers(variable); - } +void PrettyPrinter::PrintVariable(Variable *variable) const { + const auto &declarationModifiers = variable->m_type_declaration->m_declaration_modifiers; + if (declarationModifiers.empty()) { + std::cout << " " << variable->m_type_declaration->m_type->GetFullName() << " " << variable->m_name << std::endl; + } else { + if (declarationModifiers[0]->GetType() == DeclarationModifierType::POINTER && + std::any_of(declarationModifiers.begin(), declarationModifiers.end(), + [](const std::unique_ptr<DeclarationModifier> &modifier) { return modifier->GetType() == DeclarationModifierType::ARRAY; })) { + PrintVariablePointerToArray(variable); + } else { + PrintVariableArrayOfPointers(variable); } + } } -void PrettyPrinter::PrintTypedefPointerToArray(TypedefDefinition* typedefDefinition) const -{ - const auto& declarationModifiers = typedefDefinition->m_type_declaration->m_declaration_modifiers; +void PrettyPrinter::PrintTypedefPointerToArray(TypedefDefinition *typedefDefinition) const { + const auto &declarationModifiers = typedefDefinition->m_type_declaration->m_declaration_modifiers; - std::vector<int> arraySize; - auto pointerDepth = 0; - auto modifierOffset = 0u; + std::vector<int> arraySize; + auto pointerDepth = 0; + auto modifierOffset = 0u; - for (; modifierOffset < declarationModifiers.size(); modifierOffset++) - { - const auto& modifier = declarationModifiers[modifierOffset]; - if (modifier->GetType() != DeclarationModifierType::POINTER) - break; + for (; modifierOffset < declarationModifiers.size(); modifierOffset++) { + const auto &modifier = declarationModifiers[modifierOffset]; + if (modifier->GetType() != DeclarationModifierType::POINTER) + break; - pointerDepth++; - } + pointerDepth++; + } - for (; modifierOffset < declarationModifiers.size(); modifierOffset++) - { - const auto& modifier = declarationModifiers[modifierOffset]; - if (modifier->GetType() != DeclarationModifierType::ARRAY) - break; + for (; modifierOffset < declarationModifiers.size(); modifierOffset++) { + const auto &modifier = declarationModifiers[modifierOffset]; + if (modifier->GetType() != DeclarationModifierType::ARRAY) + break; - arraySize.push_back(dynamic_cast<ArrayDeclarationModifier*>(modifier.get())->m_size); - } + arraySize.push_back(dynamic_cast<ArrayDeclarationModifier *>(modifier.get())->m_size); + } - m_stream << " " << typedefDefinition->m_type_declaration->m_type->GetFullName() << '('; - for (auto p = 0; p < pointerDepth; p++) - m_stream << '*'; - m_stream << typedefDefinition->m_name << ")"; - for (auto size : arraySize) - m_stream << '[' << size << ']'; - m_stream << std::endl; + m_stream << " " << typedefDefinition->m_type_declaration->m_type->GetFullName() << '('; + for (auto p = 0; p < pointerDepth; p++) + m_stream << '*'; + m_stream << typedefDefinition->m_name << ")"; + for (auto size : arraySize) + m_stream << '[' << size << ']'; + m_stream << std::endl; } -void PrettyPrinter::PrintTypedefArrayOfPointers(TypedefDefinition* typedefDefinition) const -{ - const auto& declarationModifiers = typedefDefinition->m_type_declaration->m_declaration_modifiers; +void PrettyPrinter::PrintTypedefArrayOfPointers(TypedefDefinition *typedefDefinition) const { + const auto &declarationModifiers = typedefDefinition->m_type_declaration->m_declaration_modifiers; - std::vector<int> arraySize; - auto pointerDepth = 0; - auto modifierOffset = 0u; + std::vector<int> arraySize; + auto pointerDepth = 0; + auto modifierOffset = 0u; - for (; modifierOffset < declarationModifiers.size(); modifierOffset++) - { - const auto& modifier = declarationModifiers[modifierOffset]; - if (modifier->GetType() != DeclarationModifierType::ARRAY) - break; + for (; modifierOffset < declarationModifiers.size(); modifierOffset++) { + const auto &modifier = declarationModifiers[modifierOffset]; + if (modifier->GetType() != DeclarationModifierType::ARRAY) + break; - arraySize.push_back(dynamic_cast<ArrayDeclarationModifier*>(modifier.get())->m_size); - } + arraySize.push_back(dynamic_cast<ArrayDeclarationModifier *>(modifier.get())->m_size); + } - for (; modifierOffset < declarationModifiers.size(); modifierOffset++) - { - const auto& modifier = declarationModifiers[modifierOffset]; - if (modifier->GetType() != DeclarationModifierType::POINTER) - break; + for (; modifierOffset < declarationModifiers.size(); modifierOffset++) { + const auto &modifier = declarationModifiers[modifierOffset]; + if (modifier->GetType() != DeclarationModifierType::POINTER) + break; - pointerDepth++; - } + pointerDepth++; + } - m_stream << " " << typedefDefinition->m_type_declaration->m_type->GetFullName(); - for (auto p = 0; p < pointerDepth; p++) - m_stream << '*'; - m_stream << " " << typedefDefinition->m_name; - for (auto size : arraySize) - m_stream << '[' << size << ']'; - m_stream << std::endl; + m_stream << " " << typedefDefinition->m_type_declaration->m_type->GetFullName(); + for (auto p = 0; p < pointerDepth; p++) + m_stream << '*'; + m_stream << " " << typedefDefinition->m_name; + for (auto size : arraySize) + m_stream << '[' << size << ']'; + m_stream << std::endl; } -void PrettyPrinter::PrintEnums() const -{ - const auto& allEnums = m_repository->GetAllEnums(); - m_stream << allEnums.size() << " enums:" << std::endl; +void PrettyPrinter::PrintEnums() const { + const auto &allEnums = m_repository->GetAllEnums(); + m_stream << allEnums.size() << " enums:" << std::endl; - for (auto* enumDefinition : allEnums) - { - m_stream << " Name: " << enumDefinition->GetFullName() << std::endl; - m_stream << " Alignment: " << enumDefinition->GetAlignment() << std::endl; - m_stream << " Size: " << enumDefinition->GetSize() << std::endl; + for (auto *enumDefinition : allEnums) { + m_stream << " Name: " << enumDefinition->GetFullName() << std::endl; + m_stream << " Alignment: " << enumDefinition->GetAlignment() << std::endl; + m_stream << " Size: " << enumDefinition->GetSize() << std::endl; - for (const auto& enumMember : enumDefinition->m_members) - { - m_stream << " " << enumMember->m_name << " = " << enumMember->m_value << std::endl; - } - - m_stream << std::endl; + for (const auto &enumMember : enumDefinition->m_members) { + m_stream << " " << enumMember->m_name << " = " << enumMember->m_value << std::endl; } -} -void PrettyPrinter::PrintStructs() const -{ - const auto& allStructs = m_repository->GetAllStructs(); - m_stream << allStructs.size() << " structs:" << std::endl; + m_stream << std::endl; + } +} - for (auto* structDefinition : allStructs) - { - m_stream << " Name: " << structDefinition->GetFullName() << std::endl; - m_stream << " Alignment: " << structDefinition->GetAlignment() << std::endl; - m_stream << " Size: " << structDefinition->GetSize() << std::endl; +void PrettyPrinter::PrintStructs() const { + const auto &allStructs = m_repository->GetAllStructs(); + m_stream << allStructs.size() << " structs:" << std::endl; - for (const auto& variable : structDefinition->m_members) - { - PrintVariable(variable.get()); - } + for (auto *structDefinition : allStructs) { + m_stream << " Name: " << structDefinition->GetFullName() << std::endl; + m_stream << " Alignment: " << structDefinition->GetAlignment() << std::endl; + m_stream << " Size: " << structDefinition->GetSize() << std::endl; - m_stream << std::endl; + for (const auto &variable : structDefinition->m_members) { + PrintVariable(variable.get()); } -} -void PrettyPrinter::PrintUnions() const -{ - const auto& allUnions = m_repository->GetAllUnions(); - m_stream << allUnions.size() << " unions:" << std::endl; + m_stream << std::endl; + } +} - for (auto* unionDefinition : allUnions) - { - m_stream << " Name: " << unionDefinition->GetFullName() << std::endl; - m_stream << " Alignment: " << unionDefinition->GetAlignment() << std::endl; - m_stream << " Size: " << unionDefinition->GetSize() << std::endl; +void PrettyPrinter::PrintUnions() const { + const auto &allUnions = m_repository->GetAllUnions(); + m_stream << allUnions.size() << " unions:" << std::endl; - for (const auto& variable : unionDefinition->m_members) - { - PrintVariable(variable.get()); - } + for (auto *unionDefinition : allUnions) { + m_stream << " Name: " << unionDefinition->GetFullName() << std::endl; + m_stream << " Alignment: " << unionDefinition->GetAlignment() << std::endl; + m_stream << " Size: " << unionDefinition->GetSize() << std::endl; - m_stream << std::endl; + for (const auto &variable : unionDefinition->m_members) { + PrintVariable(variable.get()); } + + m_stream << std::endl; + } } -void PrettyPrinter::PrintTypedefs() const -{ - const auto& allTypedefs = m_repository->GetAllTypedefs(); - m_stream << allTypedefs.size() << " typedefs:" << std::endl; - - for (auto* typedefDefinition : allTypedefs) - { - m_stream << " Name: " << typedefDefinition->GetFullName() << std::endl; - m_stream << " Alignment: " << typedefDefinition->GetAlignment() << std::endl; - m_stream << " Size: " << typedefDefinition->GetSize() << std::endl; - - const auto& declarationModifiers = typedefDefinition->m_type_declaration->m_declaration_modifiers; - if (declarationModifiers.empty()) - { - std::cout << " " << typedefDefinition->m_type_declaration->m_type->GetFullName() << std::endl; - } - else - { - if (declarationModifiers[0]->GetType() == DeclarationModifierType::POINTER - && std::any_of(declarationModifiers.begin(), declarationModifiers.end(), [](const std::unique_ptr<DeclarationModifier>& modifier) - { - return modifier->GetType() == DeclarationModifierType::ARRAY; - })) - { - PrintTypedefPointerToArray(typedefDefinition); - } - else - { - PrintTypedefArrayOfPointers(typedefDefinition); - } - } - - m_stream << std::endl; +void PrettyPrinter::PrintTypedefs() const { + const auto &allTypedefs = m_repository->GetAllTypedefs(); + m_stream << allTypedefs.size() << " typedefs:" << std::endl; + + for (auto *typedefDefinition : allTypedefs) { + m_stream << " Name: " << typedefDefinition->GetFullName() << std::endl; + m_stream << " Alignment: " << typedefDefinition->GetAlignment() << std::endl; + m_stream << " Size: " << typedefDefinition->GetSize() << std::endl; + + const auto &declarationModifiers = typedefDefinition->m_type_declaration->m_declaration_modifiers; + if (declarationModifiers.empty()) { + std::cout << " " << typedefDefinition->m_type_declaration->m_type->GetFullName() << std::endl; + } else { + if (declarationModifiers[0]->GetType() == DeclarationModifierType::POINTER && + std::any_of(declarationModifiers.begin(), declarationModifiers.end(), + [](const std::unique_ptr<DeclarationModifier> &modifier) { return modifier->GetType() == DeclarationModifierType::ARRAY; })) { + PrintTypedefPointerToArray(typedefDefinition); + } else { + PrintTypedefArrayOfPointers(typedefDefinition); + } } + + m_stream << std::endl; + } } -void PrettyPrinter::PrintAll() const -{ - PrintEnums(); +void PrettyPrinter::PrintAll() const { + PrintEnums(); - PrintSeparator(); + PrintSeparator(); - PrintStructs(); + PrintStructs(); - PrintSeparator(); + PrintSeparator(); - PrintUnions(); + PrintUnions(); - PrintSeparator(); + PrintSeparator(); - PrintTypedefs(); + PrintTypedefs(); } diff --git a/src/ZoneCodeGeneratorLib/Printing/PrettyPrinter.h b/src/ZoneCodeGeneratorLib/Printing/PrettyPrinter.h index 714f33654..1cee63932 100644 --- a/src/ZoneCodeGeneratorLib/Printing/PrettyPrinter.h +++ b/src/ZoneCodeGeneratorLib/Printing/PrettyPrinter.h @@ -4,25 +4,24 @@ #include "Persistence/IDataRepository.h" -class PrettyPrinter -{ - std::ostream& m_stream; - const IDataRepository* const m_repository; +class PrettyPrinter { + std::ostream &m_stream; + const IDataRepository *const m_repository; - void PrintSeparator() const; - void PrintVariablePointerToArray(Variable* variable) const; - void PrintVariableArrayOfPointers(Variable* variable) const; - void PrintVariable(Variable* variable) const; - void PrintTypedefPointerToArray(TypedefDefinition* typedefDefinition) const; - void PrintTypedefArrayOfPointers(TypedefDefinition* typedefDefinition) const; + void PrintSeparator() const; + void PrintVariablePointerToArray(Variable *variable) const; + void PrintVariableArrayOfPointers(Variable *variable) const; + void PrintVariable(Variable *variable) const; + void PrintTypedefPointerToArray(TypedefDefinition *typedefDefinition) const; + void PrintTypedefArrayOfPointers(TypedefDefinition *typedefDefinition) const; - void PrintEnums() const; - void PrintStructs() const; - void PrintUnions() const; - void PrintTypedefs() const; + void PrintEnums() const; + void PrintStructs() const; + void PrintUnions() const; + void PrintTypedefs() const; public: - PrettyPrinter(std::ostream& stream, const IDataRepository* repository); + PrettyPrinter(std::ostream &stream, const IDataRepository *repository); - void PrintAll() const; + void PrintAll() const; }; diff --git a/src/ZoneCodeGeneratorLib/Utils/AlignmentUtils.h b/src/ZoneCodeGeneratorLib/Utils/AlignmentUtils.h index b734193f7..6c7cea4f2 100644 --- a/src/ZoneCodeGeneratorLib/Utils/AlignmentUtils.h +++ b/src/ZoneCodeGeneratorLib/Utils/AlignmentUtils.h @@ -1,14 +1,11 @@ #pragma once -class AlignmentUtils -{ +class AlignmentUtils { public: - template<typename T> - static T Align(T number, T alignmentValue) - { - if (alignmentValue == 0) - return number; + template <typename T> static T Align(T number, T alignmentValue) { + if (alignmentValue == 0) + return number; - return (number + (alignmentValue - 1)) / alignmentValue * alignmentValue; - } + return (number + (alignmentValue - 1)) / alignmentValue * alignmentValue; + } }; \ No newline at end of file diff --git a/src/ZoneCodeGeneratorLib/Utils/NameUtils.cpp b/src/ZoneCodeGeneratorLib/Utils/NameUtils.cpp index 3c282d8f7..c6a2af925 100644 --- a/src/ZoneCodeGeneratorLib/Utils/NameUtils.cpp +++ b/src/ZoneCodeGeneratorLib/Utils/NameUtils.cpp @@ -3,15 +3,14 @@ #include <random> #include <sstream> -std::string NameUtils::GenerateRandomName() -{ - static constexpr auto ALPHABET = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; - std::ostringstream str; +std::string NameUtils::GenerateRandomName() { + static constexpr auto ALPHABET = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; + std::ostringstream str; - std::random_device random; + std::random_device random; - for (auto i = 0u; i < 32u; i++) - str << ALPHABET[random() % std::char_traits<char>::length(ALPHABET)]; + for (auto i = 0u; i < 32u; i++) + str << ALPHABET[random() % std::char_traits<char>::length(ALPHABET)]; - return str.str(); + return str.str(); } diff --git a/src/ZoneCodeGeneratorLib/Utils/NameUtils.h b/src/ZoneCodeGeneratorLib/Utils/NameUtils.h index 355f19527..3ffd3c350 100644 --- a/src/ZoneCodeGeneratorLib/Utils/NameUtils.h +++ b/src/ZoneCodeGeneratorLib/Utils/NameUtils.h @@ -2,8 +2,7 @@ #include <string> -class NameUtils -{ +class NameUtils { public: - static std::string GenerateRandomName(); + static std::string GenerateRandomName(); }; diff --git a/src/ZoneCodeGeneratorLib/Utils/NamespaceBuilder.cpp b/src/ZoneCodeGeneratorLib/Utils/NamespaceBuilder.cpp index 572be3329..0d9c10e5d 100644 --- a/src/ZoneCodeGeneratorLib/Utils/NamespaceBuilder.cpp +++ b/src/ZoneCodeGeneratorLib/Utils/NamespaceBuilder.cpp @@ -2,46 +2,34 @@ #include <sstream> -std::string NamespaceBuilder::Combine(const std::string& _namespace, const std::string& name) -{ - if (_namespace.empty()) - return name; +std::string NamespaceBuilder::Combine(const std::string &_namespace, const std::string &name) { + if (_namespace.empty()) + return name; - std::ostringstream str; - str << _namespace << "::" << name; + std::ostringstream str; + str << _namespace << "::" << name; - return str.str(); + return str.str(); } -bool NamespaceBuilder::IsEmpty() const -{ - return m_elements.empty(); -} +bool NamespaceBuilder::IsEmpty() const { return m_elements.empty(); } -void NamespaceBuilder::Push(std::string element) -{ - m_elements.emplace_back(std::move(element)); -} +void NamespaceBuilder::Push(std::string element) { m_elements.emplace_back(std::move(element)); } -void NamespaceBuilder::Pop() -{ - m_elements.pop_back(); -} +void NamespaceBuilder::Pop() { m_elements.pop_back(); } -std::string NamespaceBuilder::ToString() -{ - std::ostringstream str; - auto first = true; +std::string NamespaceBuilder::ToString() { + std::ostringstream str; + auto first = true; - for(const auto& element : m_elements) - { - if (first) - first = false; - else - str << "::"; + for (const auto &element : m_elements) { + if (first) + first = false; + else + str << "::"; - str << element; - } + str << element; + } - return str.str(); + return str.str(); } diff --git a/src/ZoneCodeGeneratorLib/Utils/NamespaceBuilder.h b/src/ZoneCodeGeneratorLib/Utils/NamespaceBuilder.h index f64863fec..135966f32 100644 --- a/src/ZoneCodeGeneratorLib/Utils/NamespaceBuilder.h +++ b/src/ZoneCodeGeneratorLib/Utils/NamespaceBuilder.h @@ -4,15 +4,14 @@ #include <string> #include <vector> -class NamespaceBuilder -{ - std::vector<std::string> m_elements; +class NamespaceBuilder { + std::vector<std::string> m_elements; public: - static std::string Combine(const std::string& _namespace, const std::string& name); + static std::string Combine(const std::string &_namespace, const std::string &name); - _NODISCARD bool IsEmpty() const; - void Push(std::string element); - void Pop(); - std::string ToString(); + _NODISCARD bool IsEmpty() const; + void Push(std::string element); + void Pop(); + std::string ToString(); }; diff --git a/src/ZoneCodeGeneratorLib/ZoneCodeGenerator.cpp b/src/ZoneCodeGeneratorLib/ZoneCodeGenerator.cpp index ac4186e00..724c48e67 100644 --- a/src/ZoneCodeGeneratorLib/ZoneCodeGenerator.cpp +++ b/src/ZoneCodeGeneratorLib/ZoneCodeGenerator.cpp @@ -1,102 +1,82 @@ #include "ZoneCodeGenerator.h" #include <cstdio> +#include <iostream> #include <memory> #include <string> -#include <iostream> -#include "ZoneCodeGeneratorArguments.h" #include "Generating/CodeGenerator.h" #include "Parsing/Commands/CommandsFileReader.h" #include "Parsing/Header/HeaderFileReader.h" #include "Persistence/IDataRepository.h" #include "Persistence/InMemory/InMemoryRepository.h" #include "Printing/PrettyPrinter.h" +#include "ZoneCodeGeneratorArguments.h" -class ZoneCodeGenerator::Impl -{ - ZoneCodeGeneratorArguments m_args; - std::unique_ptr<IDataRepository> m_repository; - - bool ReadHeaderData() - { - for (const auto& headerFile : m_args.m_header_paths) - { - HeaderFileReader headerFileReader(&m_args, headerFile); +class ZoneCodeGenerator::Impl { + ZoneCodeGeneratorArguments m_args; + std::unique_ptr<IDataRepository> m_repository; - if (!headerFileReader.ReadHeaderFile(m_repository.get())) - return false; - } + bool ReadHeaderData() { + for (const auto &headerFile : m_args.m_header_paths) { + HeaderFileReader headerFileReader(&m_args, headerFile); - return true; + if (!headerFileReader.ReadHeaderFile(m_repository.get())) + return false; } - bool ReadCommandsData() - { - for (const auto& commandsFile : m_args.m_command_paths) - { - CommandsFileReader commandsFileReader(&m_args, commandsFile); + return true; + } - if (!commandsFileReader.ReadCommandsFile(m_repository.get())) - return false; - } + bool ReadCommandsData() { + for (const auto &commandsFile : m_args.m_command_paths) { + CommandsFileReader commandsFileReader(&m_args, commandsFile); - return true; + if (!commandsFileReader.ReadCommandsFile(m_repository.get())) + return false; } - void PrintData() const - { - const PrettyPrinter prettyPrinter(std::cout, m_repository.get()); - prettyPrinter.PrintAll(); - } + return true; + } - _NODISCARD bool GenerateCode() const - { - CodeGenerator codeGenerator(&m_args); - return codeGenerator.GenerateCode(m_repository.get()); - } + void PrintData() const { + const PrettyPrinter prettyPrinter(std::cout, m_repository.get()); + prettyPrinter.PrintAll(); + } -public: - Impl() - { - m_repository = std::make_unique<InMemoryRepository>(); - } + _NODISCARD bool GenerateCode() const { + CodeGenerator codeGenerator(&m_args); + return codeGenerator.GenerateCode(m_repository.get()); + } - int Run(const int argc, const char** argv) - { - if (!m_args.Parse(argc, argv)) - return 1; +public: + Impl() { m_repository = std::make_unique<InMemoryRepository>(); } - if (!ReadHeaderData() || !ReadCommandsData()) - return 1; + int Run(const int argc, const char **argv) { + if (!m_args.Parse(argc, argv)) + return 1; - if(m_args.ShouldPrint()) - { - PrintData(); - } + if (!ReadHeaderData() || !ReadCommandsData()) + return 1; - if(m_args.ShouldGenerate()) - { - if (!GenerateCode()) - return 1; - } + if (m_args.ShouldPrint()) { + PrintData(); + } - return 0; + if (m_args.ShouldGenerate()) { + if (!GenerateCode()) + return 1; } + + return 0; + } }; -ZoneCodeGenerator::ZoneCodeGenerator() -{ - m_impl = new Impl(); -} +ZoneCodeGenerator::ZoneCodeGenerator() { m_impl = new Impl(); } -ZoneCodeGenerator::~ZoneCodeGenerator() -{ - delete m_impl; - m_impl = nullptr; +ZoneCodeGenerator::~ZoneCodeGenerator() { + delete m_impl; + m_impl = nullptr; } -int ZoneCodeGenerator::Run(const int argc, const char** argv) const -{ - return m_impl->Run(argc, argv); -} +int ZoneCodeGenerator::Run(const int argc, const char **argv) const { return m_impl->Run(argc, argv); } diff --git a/src/ZoneCodeGeneratorLib/ZoneCodeGenerator.h b/src/ZoneCodeGeneratorLib/ZoneCodeGenerator.h index 61f5b3417..acc943fac 100644 --- a/src/ZoneCodeGeneratorLib/ZoneCodeGenerator.h +++ b/src/ZoneCodeGeneratorLib/ZoneCodeGenerator.h @@ -1,17 +1,16 @@ #pragma once -class ZoneCodeGenerator -{ - class Impl; - Impl* m_impl; +class ZoneCodeGenerator { + class Impl; + Impl *m_impl; public: - ZoneCodeGenerator(); - ~ZoneCodeGenerator(); - ZoneCodeGenerator(const ZoneCodeGenerator& other) = delete; - ZoneCodeGenerator(ZoneCodeGenerator&& other) noexcept = default; - ZoneCodeGenerator& operator=(const ZoneCodeGenerator& other) = delete; - ZoneCodeGenerator& operator=(ZoneCodeGenerator&& other) noexcept = default; + ZoneCodeGenerator(); + ~ZoneCodeGenerator(); + ZoneCodeGenerator(const ZoneCodeGenerator &other) = delete; + ZoneCodeGenerator(ZoneCodeGenerator &&other) noexcept = default; + ZoneCodeGenerator &operator=(const ZoneCodeGenerator &other) = delete; + ZoneCodeGenerator &operator=(ZoneCodeGenerator &&other) noexcept = default; - int Run(int argc, const char** argv) const; + int Run(int argc, const char **argv) const; }; \ No newline at end of file diff --git a/src/ZoneCodeGeneratorLib/ZoneCodeGeneratorArguments.cpp b/src/ZoneCodeGeneratorLib/ZoneCodeGeneratorArguments.cpp index 675184c45..c0fb6fc98 100644 --- a/src/ZoneCodeGeneratorLib/ZoneCodeGeneratorArguments.cpp +++ b/src/ZoneCodeGeneratorLib/ZoneCodeGeneratorArguments.cpp @@ -6,206 +6,160 @@ #include "Utils/Arguments/CommandLineOption.h" #include "Utils/Arguments/UsageInformation.h" -const CommandLineOption* const OPTION_HELP = CommandLineOption::Builder::Create() - .WithShortName("?") - .WithLongName("help") - .WithDescription("Displays usage information.") - .Build(); - -const CommandLineOption* const OPTION_VERBOSE = CommandLineOption::Builder::Create() - .WithShortName("v") - .WithLongName("verbose") - .WithDescription("Outputs a lot more and more detailed messages.") - .Build(); +const CommandLineOption *const OPTION_HELP = + CommandLineOption::Builder::Create().WithShortName("?").WithLongName("help").WithDescription("Displays usage information.").Build(); + +const CommandLineOption *const OPTION_VERBOSE = + CommandLineOption::Builder::Create().WithShortName("v").WithLongName("verbose").WithDescription("Outputs a lot more and more detailed messages.").Build(); // ------ // INPUT // ------ -constexpr const char* CATEGORY_INPUT = "Input"; - -const CommandLineOption* const OPTION_HEADER = CommandLineOption::Builder::Create() - .WithShortName("h") - .WithLongName("header") - .WithDescription("Reads from the specified header file.") - .WithCategory(CATEGORY_INPUT) - .WithParameter("headerFile") - .Reusable() - .Build(); - -const CommandLineOption* const OPTION_COMMANDS_FILE = CommandLineOption::Builder::Create() - .WithShortName("c") - .WithLongName("commands-file") - .WithDescription("Specifies the commands file. Defaults to stdin.") - .WithCategory(CATEGORY_INPUT) - .WithParameter("commandFile") - .Reusable() - .Build(); +constexpr const char *CATEGORY_INPUT = "Input"; + +const CommandLineOption *const OPTION_HEADER = CommandLineOption::Builder::Create() + .WithShortName("h") + .WithLongName("header") + .WithDescription("Reads from the specified header file.") + .WithCategory(CATEGORY_INPUT) + .WithParameter("headerFile") + .Reusable() + .Build(); + +const CommandLineOption *const OPTION_COMMANDS_FILE = CommandLineOption::Builder::Create() + .WithShortName("c") + .WithLongName("commands-file") + .WithDescription("Specifies the commands file. Defaults to stdin.") + .WithCategory(CATEGORY_INPUT) + .WithParameter("commandFile") + .Reusable() + .Build(); // ------ // OUTPUT // ------ -constexpr const char* CATEGORY_OUTPUT = "Output"; - -const CommandLineOption* const OPTION_OUTPUT_FOLDER = CommandLineOption::Builder::Create() - .WithShortName("o") - .WithLongName("output") - .WithDescription("Specify the folder to save the generate code files to. Defaults to the current directory.") - .WithCategory(CATEGORY_OUTPUT) - .WithParameter("outputPath") - .Build(); - -const CommandLineOption* const OPTION_PRINT = CommandLineOption::Builder::Create() - .WithShortName("p") - .WithLongName("print") - .WithDescription("Print the loaded data.") - .WithCategory(CATEGORY_OUTPUT) - .Build(); - -const CommandLineOption* const OPTION_GENERATE = CommandLineOption::Builder::Create() - .WithShortName("g") - .WithLongName("generate") - .WithDescription( - "Generates a specified asset/preset combination. Can be used multiple times. Available presets: " - "ZoneLoad, ZoneWrite, AssetStructTests") - .WithCategory(CATEGORY_OUTPUT) - .WithParameter("assetName") - .WithParameter("preset") - .Reusable() - .Build(); - -const CommandLineOption* const COMMAND_LINE_OPTIONS[] -{ - OPTION_HELP, - OPTION_VERBOSE, - OPTION_HEADER, - OPTION_COMMANDS_FILE, - OPTION_OUTPUT_FOLDER, - OPTION_PRINT, - OPTION_GENERATE -}; - -ZoneCodeGeneratorArguments::GenerationTask::GenerationTask() - : m_all_assets(false) -{ -} - -ZoneCodeGeneratorArguments::GenerationTask::GenerationTask(std::string templateName) - : m_all_assets(true), - m_template_name(std::move(templateName)) -{ -} +constexpr const char *CATEGORY_OUTPUT = "Output"; + +const CommandLineOption *const OPTION_OUTPUT_FOLDER = + CommandLineOption::Builder::Create() + .WithShortName("o") + .WithLongName("output") + .WithDescription("Specify the folder to save the generate code files to. Defaults to the current directory.") + .WithCategory(CATEGORY_OUTPUT) + .WithParameter("outputPath") + .Build(); + +const CommandLineOption *const OPTION_PRINT = CommandLineOption::Builder::Create() + .WithShortName("p") + .WithLongName("print") + .WithDescription("Print the loaded data.") + .WithCategory(CATEGORY_OUTPUT) + .Build(); + +const CommandLineOption *const OPTION_GENERATE = + CommandLineOption::Builder::Create() + .WithShortName("g") + .WithLongName("generate") + .WithDescription("Generates a specified asset/preset combination. Can be used multiple times. Available presets: " + "ZoneLoad, ZoneWrite, AssetStructTests") + .WithCategory(CATEGORY_OUTPUT) + .WithParameter("assetName") + .WithParameter("preset") + .Reusable() + .Build(); + +const CommandLineOption *const COMMAND_LINE_OPTIONS[]{OPTION_HELP, OPTION_VERBOSE, OPTION_HEADER, OPTION_COMMANDS_FILE, + OPTION_OUTPUT_FOLDER, OPTION_PRINT, OPTION_GENERATE}; + +ZoneCodeGeneratorArguments::GenerationTask::GenerationTask() : m_all_assets(false) {} + +ZoneCodeGeneratorArguments::GenerationTask::GenerationTask(std::string templateName) : m_all_assets(true), m_template_name(std::move(templateName)) {} ZoneCodeGeneratorArguments::GenerationTask::GenerationTask(std::string assetName, std::string templateName) - : m_all_assets(false), - m_asset_name(std::move(assetName)), - m_template_name(std::move(templateName)) -{ -} + : m_all_assets(false), m_asset_name(std::move(assetName)), m_template_name(std::move(templateName)) {} ZoneCodeGeneratorArguments::ZoneCodeGeneratorArguments() - : m_argument_parser(COMMAND_LINE_OPTIONS, std::extent<decltype(COMMAND_LINE_OPTIONS)>::value), - m_task_flags(0) -{ - m_verbose = false; + : m_argument_parser(COMMAND_LINE_OPTIONS, std::extent<decltype(COMMAND_LINE_OPTIONS)>::value), m_task_flags(0) { + m_verbose = false; } -void ZoneCodeGeneratorArguments::PrintUsage() -{ - UsageInformation usage("ZoneCodeGenerator.exe"); +void ZoneCodeGeneratorArguments::PrintUsage() { + UsageInformation usage("ZoneCodeGenerator.exe"); - for (const auto* commandLineOption : COMMAND_LINE_OPTIONS) - { - usage.AddCommandLineOption(commandLineOption); - } + for (const auto *commandLineOption : COMMAND_LINE_OPTIONS) { + usage.AddCommandLineOption(commandLineOption); + } - usage.Print(); + usage.Print(); } -bool ZoneCodeGeneratorArguments::Parse(const int argc, const char** argv) -{ - if (!m_argument_parser.ParseArguments(argc - 1, &argv[1])) - { - PrintUsage(); - return false; - } - - // Check if the user requested help - if (m_argument_parser.IsOptionSpecified(OPTION_HELP)) - { - PrintUsage(); - return false; - } - - // -v; --verbose - m_verbose = m_argument_parser.IsOptionSpecified(OPTION_VERBOSE); - - // -p; --print - if (m_argument_parser.IsOptionSpecified(OPTION_PRINT)) - m_task_flags |= FLAG_TASK_PRINT; - - // -o; --output - if (m_argument_parser.IsOptionSpecified(OPTION_OUTPUT_FOLDER)) - m_output_directory = m_argument_parser.GetValueForOption(OPTION_OUTPUT_FOLDER); - else - m_output_directory = "."; - - // -h; --header - if (m_argument_parser.IsOptionSpecified(OPTION_HEADER)) - { - for (const auto& arg : m_argument_parser.GetParametersForOption(OPTION_HEADER)) - m_header_paths.push_back(arg); - } - else - { - std::cout << "At least one header file must be specified via -h / --header." << std::endl; - return false; +bool ZoneCodeGeneratorArguments::Parse(const int argc, const char **argv) { + if (!m_argument_parser.ParseArguments(argc - 1, &argv[1])) { + PrintUsage(); + return false; + } + + // Check if the user requested help + if (m_argument_parser.IsOptionSpecified(OPTION_HELP)) { + PrintUsage(); + return false; + } + + // -v; --verbose + m_verbose = m_argument_parser.IsOptionSpecified(OPTION_VERBOSE); + + // -p; --print + if (m_argument_parser.IsOptionSpecified(OPTION_PRINT)) + m_task_flags |= FLAG_TASK_PRINT; + + // -o; --output + if (m_argument_parser.IsOptionSpecified(OPTION_OUTPUT_FOLDER)) + m_output_directory = m_argument_parser.GetValueForOption(OPTION_OUTPUT_FOLDER); + else + m_output_directory = "."; + + // -h; --header + if (m_argument_parser.IsOptionSpecified(OPTION_HEADER)) { + for (const auto &arg : m_argument_parser.GetParametersForOption(OPTION_HEADER)) + m_header_paths.push_back(arg); + } else { + std::cout << "At least one header file must be specified via -h / --header." << std::endl; + return false; + } + + // -c; --commands-file + if (m_argument_parser.IsOptionSpecified(OPTION_COMMANDS_FILE)) { + for (const auto &arg : m_argument_parser.GetParametersForOption(OPTION_COMMANDS_FILE)) + m_command_paths.push_back(arg); + } else { + std::cout << "At least one commands file must be specified via -c / --commands-file." << std::endl; + return false; + } + + if (m_argument_parser.IsOptionSpecified(OPTION_GENERATE)) { + m_task_flags |= FLAG_TASK_GENERATE; + const auto generateParameterValues = m_argument_parser.GetParametersForOption(OPTION_GENERATE); + for (auto i = 0u; i < generateParameterValues.size(); i += 2) { + const auto &assetName = generateParameterValues[i]; + const auto &templateName = generateParameterValues[i + 1]; + + if (assetName == "*") + m_generation_tasks.emplace_back(templateName); + else + m_generation_tasks.emplace_back(assetName, templateName); } + } - // -c; --commands-file - if (m_argument_parser.IsOptionSpecified(OPTION_COMMANDS_FILE)) - { - for (const auto& arg : m_argument_parser.GetParametersForOption(OPTION_COMMANDS_FILE)) - m_command_paths.push_back(arg); - } - else - { - std::cout << "At least one commands file must be specified via -c / --commands-file." << std::endl; - return false; - } + if (m_task_flags == 0) { + std::cout << "There was no output task specified." << std::endl; + PrintUsage(); + return false; + } - if (m_argument_parser.IsOptionSpecified(OPTION_GENERATE)) - { - m_task_flags |= FLAG_TASK_GENERATE; - const auto generateParameterValues = m_argument_parser.GetParametersForOption(OPTION_GENERATE); - for (auto i = 0u; i < generateParameterValues.size(); i += 2) - { - const auto& assetName = generateParameterValues[i]; - const auto& templateName = generateParameterValues[i + 1]; - - if (assetName == "*") - m_generation_tasks.emplace_back(templateName); - else - m_generation_tasks.emplace_back(assetName, templateName); - } - } - - if (m_task_flags == 0) - { - std::cout << "There was no output task specified." << std::endl; - PrintUsage(); - return false; - } - - return true; + return true; } -bool ZoneCodeGeneratorArguments::ShouldGenerate() const -{ - return m_task_flags & FLAG_TASK_GENERATE; -} +bool ZoneCodeGeneratorArguments::ShouldGenerate() const { return m_task_flags & FLAG_TASK_GENERATE; } -bool ZoneCodeGeneratorArguments::ShouldPrint() const -{ - return m_task_flags & FLAG_TASK_PRINT; -} +bool ZoneCodeGeneratorArguments::ShouldPrint() const { return m_task_flags & FLAG_TASK_PRINT; } diff --git a/src/ZoneCodeGeneratorLib/ZoneCodeGeneratorArguments.h b/src/ZoneCodeGeneratorLib/ZoneCodeGeneratorArguments.h index 286e5e68f..d76ea2272 100644 --- a/src/ZoneCodeGeneratorLib/ZoneCodeGeneratorArguments.h +++ b/src/ZoneCodeGeneratorLib/ZoneCodeGeneratorArguments.h @@ -1,48 +1,46 @@ #pragma once -#include "Utils/ClassUtils.h" #include "Utils/Arguments/ArgumentParser.h" +#include "Utils/ClassUtils.h" #include <vector> -class ZoneCodeGeneratorArguments -{ - ArgumentParser m_argument_parser; +class ZoneCodeGeneratorArguments { + ArgumentParser m_argument_parser; - /** - * \brief Prints a command line usage help text for the Unlinker tool to stdout. - */ - static void PrintUsage(); + /** + * \brief Prints a command line usage help text for the Unlinker tool to stdout. + */ + static void PrintUsage(); public: - static constexpr unsigned FLAG_TASK_GENERATE = 1 << 0; - static constexpr unsigned FLAG_TASK_PRINT = 1 << 1; + static constexpr unsigned FLAG_TASK_GENERATE = 1 << 0; + static constexpr unsigned FLAG_TASK_PRINT = 1 << 1; - class GenerationTask - { - public: - bool m_all_assets; - std::string m_asset_name; - std::string m_template_name; + class GenerationTask { + public: + bool m_all_assets; + std::string m_asset_name; + std::string m_template_name; - GenerationTask(); - explicit GenerationTask(std::string templateName); - GenerationTask(std::string assetName, std::string templateName); - }; + GenerationTask(); + explicit GenerationTask(std::string templateName); + GenerationTask(std::string assetName, std::string templateName); + }; - bool m_verbose; + bool m_verbose; - std::vector<std::string> m_header_paths; - std::vector<std::string> m_command_paths; - std::string m_output_directory; + std::vector<std::string> m_header_paths; + std::vector<std::string> m_command_paths; + std::string m_output_directory; - unsigned m_task_flags; - std::vector<GenerationTask> m_generation_tasks; + unsigned m_task_flags; + std::vector<GenerationTask> m_generation_tasks; - ZoneCodeGeneratorArguments(); + ZoneCodeGeneratorArguments(); - bool Parse(int argc, const char** argv); + bool Parse(int argc, const char **argv); - _NODISCARD bool ShouldGenerate() const; - _NODISCARD bool ShouldPrint() const; + _NODISCARD bool ShouldGenerate() const; + _NODISCARD bool ShouldPrint() const; }; diff --git a/src/ZoneCommon/Game/IW3/GameAssetPoolIW3.cpp b/src/ZoneCommon/Game/IW3/GameAssetPoolIW3.cpp index e203030c8..1123243ce 100644 --- a/src/ZoneCommon/Game/IW3/GameAssetPoolIW3.cpp +++ b/src/ZoneCommon/Game/IW3/GameAssetPoolIW3.cpp @@ -3,47 +3,16 @@ #include <cassert> #include <type_traits> -#include "Pool/AssetPoolStatic.h" #include "Pool/AssetPoolDynamic.h" +#include "Pool/AssetPoolStatic.h" using namespace IW3; -const char* GameAssetPoolIW3::ASSET_TYPE_NAMES[] -{ - "xmodelpieces", - "physpreset", - "xanim", - "xmodel", - "material", - "techniqueset", - "image", - "sound", - "soundcurve", - "loadedsound", - "clipmap", - "clipmap", - "comworld", - "gameworldsp", - "gameworldmp", - "mapents", - "gfxworld", - "lightdef", - "uimap", - "font", - "menulist", - "menu", - "localize", - "weapon", - "snddriverglobals", - "fx", - "impactfx", - "aitype", - "mptype", - "character", - "xmodelalias", - "rawfile", - "stringtable" -}; +const char *GameAssetPoolIW3::ASSET_TYPE_NAMES[]{"xmodelpieces", "physpreset", "xanim", "xmodel", "material", "techniqueset", "image", + "sound", "soundcurve", "loadedsound", "clipmap", "clipmap", "comworld", "gameworldsp", + "gameworldmp", "mapents", "gfxworld", "lightdef", "uimap", "font", "menulist", + "menu", "localize", "weapon", "snddriverglobals", "fx", "impactfx", "aitype", + "mptype", "character", "xmodelalias", "rawfile", "stringtable"}; /* Asset Pool Table @@ -79,232 +48,206 @@ const char* GameAssetPoolIW3::ASSET_TYPE_NAMES[] ASSET_TYPE_STRINGTABLE, StringTable, stringTable, m_string_table */ -GameAssetPoolIW3::GameAssetPoolIW3(Zone* zone, const int priority) - : ZoneAssetPools(zone), - m_priority(priority) -{ - static_assert(std::extent<decltype(ASSET_TYPE_NAMES)>::value == ASSET_TYPE_COUNT); +GameAssetPoolIW3::GameAssetPoolIW3(Zone *zone, const int priority) : ZoneAssetPools(zone), m_priority(priority) { + static_assert(std::extent<decltype(ASSET_TYPE_NAMES)>::value == ASSET_TYPE_COUNT); } -void GameAssetPoolIW3::InitPoolStatic(const asset_type_t type, const size_t capacity) -{ -#define CASE_INIT_POOL_STATIC(assetType, poolName, poolType) \ - case assetType: \ - { \ - if((poolName) == nullptr && capacity > 0) \ - { \ - (poolName) = std::make_unique<AssetPoolStatic<poolType>>(capacity, m_priority, (assetType)); \ - } \ - break; \ - } - - switch (type) - { - CASE_INIT_POOL_STATIC(ASSET_TYPE_PHYSPRESET, m_phys_preset, PhysPreset); - CASE_INIT_POOL_STATIC(ASSET_TYPE_XANIMPARTS, m_xanim_parts, XAnimParts); - CASE_INIT_POOL_STATIC(ASSET_TYPE_XMODEL, m_xmodel, XModel); - CASE_INIT_POOL_STATIC(ASSET_TYPE_MATERIAL, m_material, Material); - CASE_INIT_POOL_STATIC(ASSET_TYPE_TECHNIQUE_SET, m_technique_set, MaterialTechniqueSet); - CASE_INIT_POOL_STATIC(ASSET_TYPE_IMAGE, m_image, GfxImage); - CASE_INIT_POOL_STATIC(ASSET_TYPE_SOUND, m_sound, snd_alias_list_t); - CASE_INIT_POOL_STATIC(ASSET_TYPE_SOUND_CURVE, m_sound_curve, SndCurve); - CASE_INIT_POOL_STATIC(ASSET_TYPE_LOADED_SOUND, m_loaded_sound, LoadedSound); - CASE_INIT_POOL_STATIC(ASSET_TYPE_CLIPMAP, m_clip_map, clipMap_t); - CASE_INIT_POOL_STATIC(ASSET_TYPE_CLIPMAP_PVS, m_clip_map, clipMap_t); - CASE_INIT_POOL_STATIC(ASSET_TYPE_COMWORLD, m_com_world, ComWorld); - CASE_INIT_POOL_STATIC(ASSET_TYPE_GAMEWORLD_SP, m_game_world_sp, GameWorldSp); - CASE_INIT_POOL_STATIC(ASSET_TYPE_GAMEWORLD_MP, m_game_world_mp, GameWorldMp); - CASE_INIT_POOL_STATIC(ASSET_TYPE_MAP_ENTS, m_map_ents, MapEnts); - CASE_INIT_POOL_STATIC(ASSET_TYPE_GFXWORLD, m_gfx_world, GfxWorld); - CASE_INIT_POOL_STATIC(ASSET_TYPE_LIGHT_DEF, m_gfx_light_def, GfxLightDef); - CASE_INIT_POOL_STATIC(ASSET_TYPE_FONT, m_font, Font_s); - CASE_INIT_POOL_STATIC(ASSET_TYPE_MENULIST, m_menu_list, MenuList); - CASE_INIT_POOL_STATIC(ASSET_TYPE_MENU, m_menu_def, menuDef_t); - CASE_INIT_POOL_STATIC(ASSET_TYPE_LOCALIZE_ENTRY, m_localize, LocalizeEntry); - CASE_INIT_POOL_STATIC(ASSET_TYPE_WEAPON, m_weapon, WeaponDef); - CASE_INIT_POOL_STATIC(ASSET_TYPE_FX, m_fx, FxEffectDef); - CASE_INIT_POOL_STATIC(ASSET_TYPE_IMPACT_FX, m_fx_impact_table, FxImpactTable); - CASE_INIT_POOL_STATIC(ASSET_TYPE_RAWFILE, m_raw_file, RawFile); - CASE_INIT_POOL_STATIC(ASSET_TYPE_STRINGTABLE, m_string_table, StringTable); - - default: - assert(type >= 0 && type < ASSET_TYPE_COUNT); - break; - } +void GameAssetPoolIW3::InitPoolStatic(const asset_type_t type, const size_t capacity) { +#define CASE_INIT_POOL_STATIC(assetType, poolName, poolType) \ + case assetType: { \ + if ((poolName) == nullptr && capacity > 0) { \ + (poolName) = std::make_unique<AssetPoolStatic<poolType>>(capacity, m_priority, (assetType)); \ + } \ + break; \ + } + + switch (type) { + CASE_INIT_POOL_STATIC(ASSET_TYPE_PHYSPRESET, m_phys_preset, PhysPreset); + CASE_INIT_POOL_STATIC(ASSET_TYPE_XANIMPARTS, m_xanim_parts, XAnimParts); + CASE_INIT_POOL_STATIC(ASSET_TYPE_XMODEL, m_xmodel, XModel); + CASE_INIT_POOL_STATIC(ASSET_TYPE_MATERIAL, m_material, Material); + CASE_INIT_POOL_STATIC(ASSET_TYPE_TECHNIQUE_SET, m_technique_set, MaterialTechniqueSet); + CASE_INIT_POOL_STATIC(ASSET_TYPE_IMAGE, m_image, GfxImage); + CASE_INIT_POOL_STATIC(ASSET_TYPE_SOUND, m_sound, snd_alias_list_t); + CASE_INIT_POOL_STATIC(ASSET_TYPE_SOUND_CURVE, m_sound_curve, SndCurve); + CASE_INIT_POOL_STATIC(ASSET_TYPE_LOADED_SOUND, m_loaded_sound, LoadedSound); + CASE_INIT_POOL_STATIC(ASSET_TYPE_CLIPMAP, m_clip_map, clipMap_t); + CASE_INIT_POOL_STATIC(ASSET_TYPE_CLIPMAP_PVS, m_clip_map, clipMap_t); + CASE_INIT_POOL_STATIC(ASSET_TYPE_COMWORLD, m_com_world, ComWorld); + CASE_INIT_POOL_STATIC(ASSET_TYPE_GAMEWORLD_SP, m_game_world_sp, GameWorldSp); + CASE_INIT_POOL_STATIC(ASSET_TYPE_GAMEWORLD_MP, m_game_world_mp, GameWorldMp); + CASE_INIT_POOL_STATIC(ASSET_TYPE_MAP_ENTS, m_map_ents, MapEnts); + CASE_INIT_POOL_STATIC(ASSET_TYPE_GFXWORLD, m_gfx_world, GfxWorld); + CASE_INIT_POOL_STATIC(ASSET_TYPE_LIGHT_DEF, m_gfx_light_def, GfxLightDef); + CASE_INIT_POOL_STATIC(ASSET_TYPE_FONT, m_font, Font_s); + CASE_INIT_POOL_STATIC(ASSET_TYPE_MENULIST, m_menu_list, MenuList); + CASE_INIT_POOL_STATIC(ASSET_TYPE_MENU, m_menu_def, menuDef_t); + CASE_INIT_POOL_STATIC(ASSET_TYPE_LOCALIZE_ENTRY, m_localize, LocalizeEntry); + CASE_INIT_POOL_STATIC(ASSET_TYPE_WEAPON, m_weapon, WeaponDef); + CASE_INIT_POOL_STATIC(ASSET_TYPE_FX, m_fx, FxEffectDef); + CASE_INIT_POOL_STATIC(ASSET_TYPE_IMPACT_FX, m_fx_impact_table, FxImpactTable); + CASE_INIT_POOL_STATIC(ASSET_TYPE_RAWFILE, m_raw_file, RawFile); + CASE_INIT_POOL_STATIC(ASSET_TYPE_STRINGTABLE, m_string_table, StringTable); + + default: + assert(type >= 0 && type < ASSET_TYPE_COUNT); + break; + } #undef CASE_INIT_POOL_STATIC } -void GameAssetPoolIW3::InitPoolDynamic(const asset_type_t type) -{ -#define CASE_INIT_POOL_DYNAMIC(assetType, poolName, poolType) \ - case assetType: \ - { \ - if((poolName) == nullptr) \ - { \ - (poolName) = std::make_unique<AssetPoolDynamic<poolType>>(m_priority, (assetType)); \ - } \ - break; \ - } - - switch (type) - { - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_PHYSPRESET, m_phys_preset, PhysPreset); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_XANIMPARTS, m_xanim_parts, XAnimParts); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_XMODEL, m_xmodel, XModel); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_MATERIAL, m_material, Material); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_TECHNIQUE_SET, m_technique_set, MaterialTechniqueSet); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_IMAGE, m_image, GfxImage); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_SOUND, m_sound, snd_alias_list_t); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_SOUND_CURVE, m_sound_curve, SndCurve); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_LOADED_SOUND, m_loaded_sound, LoadedSound); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_CLIPMAP, m_clip_map, clipMap_t); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_CLIPMAP_PVS, m_clip_map, clipMap_t); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_COMWORLD, m_com_world, ComWorld); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_GAMEWORLD_SP, m_game_world_sp, GameWorldSp); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_GAMEWORLD_MP, m_game_world_mp, GameWorldMp); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_MAP_ENTS, m_map_ents, MapEnts); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_GFXWORLD, m_gfx_world, GfxWorld); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_LIGHT_DEF, m_gfx_light_def, GfxLightDef); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_FONT, m_font, Font_s); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_MENULIST, m_menu_list, MenuList); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_MENU, m_menu_def, menuDef_t); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_LOCALIZE_ENTRY, m_localize, LocalizeEntry); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_WEAPON, m_weapon, WeaponDef); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_FX, m_fx, FxEffectDef); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_IMPACT_FX, m_fx_impact_table, FxImpactTable); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_RAWFILE, m_raw_file, RawFile); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_STRINGTABLE, m_string_table, StringTable); - - default: - assert(type >= 0 && type < ASSET_TYPE_COUNT); - break; - } +void GameAssetPoolIW3::InitPoolDynamic(const asset_type_t type) { +#define CASE_INIT_POOL_DYNAMIC(assetType, poolName, poolType) \ + case assetType: { \ + if ((poolName) == nullptr) { \ + (poolName) = std::make_unique<AssetPoolDynamic<poolType>>(m_priority, (assetType)); \ + } \ + break; \ + } + + switch (type) { + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_PHYSPRESET, m_phys_preset, PhysPreset); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_XANIMPARTS, m_xanim_parts, XAnimParts); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_XMODEL, m_xmodel, XModel); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_MATERIAL, m_material, Material); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_TECHNIQUE_SET, m_technique_set, MaterialTechniqueSet); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_IMAGE, m_image, GfxImage); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_SOUND, m_sound, snd_alias_list_t); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_SOUND_CURVE, m_sound_curve, SndCurve); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_LOADED_SOUND, m_loaded_sound, LoadedSound); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_CLIPMAP, m_clip_map, clipMap_t); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_CLIPMAP_PVS, m_clip_map, clipMap_t); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_COMWORLD, m_com_world, ComWorld); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_GAMEWORLD_SP, m_game_world_sp, GameWorldSp); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_GAMEWORLD_MP, m_game_world_mp, GameWorldMp); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_MAP_ENTS, m_map_ents, MapEnts); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_GFXWORLD, m_gfx_world, GfxWorld); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_LIGHT_DEF, m_gfx_light_def, GfxLightDef); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_FONT, m_font, Font_s); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_MENULIST, m_menu_list, MenuList); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_MENU, m_menu_def, menuDef_t); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_LOCALIZE_ENTRY, m_localize, LocalizeEntry); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_WEAPON, m_weapon, WeaponDef); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_FX, m_fx, FxEffectDef); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_IMPACT_FX, m_fx_impact_table, FxImpactTable); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_RAWFILE, m_raw_file, RawFile); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_STRINGTABLE, m_string_table, StringTable); + + default: + assert(type >= 0 && type < ASSET_TYPE_COUNT); + break; + } #undef CASE_INIT_POOL_STATIC } -XAssetInfoGeneric* GameAssetPoolIW3::AddAssetToPool(asset_type_t type, std::string name, void* asset, std::vector<XAssetInfoGeneric*> dependencies, std::vector<scr_string_t> usedScriptStrings, Zone* zone) -{ - XAsset xAsset{}; - - xAsset.type = static_cast<XAssetType>(type); - xAsset.header.data = asset; - -#define CASE_ADD_TO_POOL(assetType, poolName, headerName) \ - case assetType: \ - { \ - assert((poolName) != nullptr); \ - return (poolName)->AddAsset(std::move(name), xAsset.header.headerName, zone, std::move(dependencies), std::move(usedScriptStrings)); \ - } - - switch (xAsset.type) - { - CASE_ADD_TO_POOL(ASSET_TYPE_PHYSPRESET, m_phys_preset, physPreset); - CASE_ADD_TO_POOL(ASSET_TYPE_XANIMPARTS, m_xanim_parts, parts); - CASE_ADD_TO_POOL(ASSET_TYPE_XMODEL, m_xmodel, model); - CASE_ADD_TO_POOL(ASSET_TYPE_MATERIAL, m_material, material); - CASE_ADD_TO_POOL(ASSET_TYPE_TECHNIQUE_SET, m_technique_set, techniqueSet); - CASE_ADD_TO_POOL(ASSET_TYPE_IMAGE, m_image, image); - CASE_ADD_TO_POOL(ASSET_TYPE_SOUND, m_sound, sound); - CASE_ADD_TO_POOL(ASSET_TYPE_SOUND_CURVE, m_sound_curve, sndCurve); - CASE_ADD_TO_POOL(ASSET_TYPE_LOADED_SOUND, m_loaded_sound, loadSnd); - CASE_ADD_TO_POOL(ASSET_TYPE_CLIPMAP, m_clip_map, clipMap); - CASE_ADD_TO_POOL(ASSET_TYPE_CLIPMAP_PVS, m_clip_map, clipMap); - CASE_ADD_TO_POOL(ASSET_TYPE_COMWORLD, m_com_world, comWorld); - CASE_ADD_TO_POOL(ASSET_TYPE_GAMEWORLD_SP, m_game_world_sp, gameWorldSp); - CASE_ADD_TO_POOL(ASSET_TYPE_GAMEWORLD_MP, m_game_world_mp, gameWorldMp); - CASE_ADD_TO_POOL(ASSET_TYPE_MAP_ENTS, m_map_ents, mapEnts); - CASE_ADD_TO_POOL(ASSET_TYPE_GFXWORLD, m_gfx_world, gfxWorld); - CASE_ADD_TO_POOL(ASSET_TYPE_LIGHT_DEF, m_gfx_light_def, lightDef); - CASE_ADD_TO_POOL(ASSET_TYPE_FONT, m_font, font); - CASE_ADD_TO_POOL(ASSET_TYPE_MENULIST, m_menu_list, menuList); - CASE_ADD_TO_POOL(ASSET_TYPE_MENU, m_menu_def, menu); - CASE_ADD_TO_POOL(ASSET_TYPE_LOCALIZE_ENTRY, m_localize, localize); - CASE_ADD_TO_POOL(ASSET_TYPE_WEAPON, m_weapon, weapon); - CASE_ADD_TO_POOL(ASSET_TYPE_FX, m_fx, fx); - CASE_ADD_TO_POOL(ASSET_TYPE_IMPACT_FX, m_fx_impact_table, impactFx); - CASE_ADD_TO_POOL(ASSET_TYPE_RAWFILE, m_raw_file, rawfile); - CASE_ADD_TO_POOL(ASSET_TYPE_STRINGTABLE, m_string_table, stringTable); - - default: - assert(false); - break; - } - - return nullptr; +XAssetInfoGeneric *GameAssetPoolIW3::AddAssetToPool(asset_type_t type, std::string name, void *asset, std::vector<XAssetInfoGeneric *> dependencies, + std::vector<scr_string_t> usedScriptStrings, Zone *zone) { + XAsset xAsset{}; + + xAsset.type = static_cast<XAssetType>(type); + xAsset.header.data = asset; + +#define CASE_ADD_TO_POOL(assetType, poolName, headerName) \ + case assetType: { \ + assert((poolName) != nullptr); \ + return (poolName)->AddAsset(std::move(name), xAsset.header.headerName, zone, std::move(dependencies), std::move(usedScriptStrings)); \ + } + + switch (xAsset.type) { + CASE_ADD_TO_POOL(ASSET_TYPE_PHYSPRESET, m_phys_preset, physPreset); + CASE_ADD_TO_POOL(ASSET_TYPE_XANIMPARTS, m_xanim_parts, parts); + CASE_ADD_TO_POOL(ASSET_TYPE_XMODEL, m_xmodel, model); + CASE_ADD_TO_POOL(ASSET_TYPE_MATERIAL, m_material, material); + CASE_ADD_TO_POOL(ASSET_TYPE_TECHNIQUE_SET, m_technique_set, techniqueSet); + CASE_ADD_TO_POOL(ASSET_TYPE_IMAGE, m_image, image); + CASE_ADD_TO_POOL(ASSET_TYPE_SOUND, m_sound, sound); + CASE_ADD_TO_POOL(ASSET_TYPE_SOUND_CURVE, m_sound_curve, sndCurve); + CASE_ADD_TO_POOL(ASSET_TYPE_LOADED_SOUND, m_loaded_sound, loadSnd); + CASE_ADD_TO_POOL(ASSET_TYPE_CLIPMAP, m_clip_map, clipMap); + CASE_ADD_TO_POOL(ASSET_TYPE_CLIPMAP_PVS, m_clip_map, clipMap); + CASE_ADD_TO_POOL(ASSET_TYPE_COMWORLD, m_com_world, comWorld); + CASE_ADD_TO_POOL(ASSET_TYPE_GAMEWORLD_SP, m_game_world_sp, gameWorldSp); + CASE_ADD_TO_POOL(ASSET_TYPE_GAMEWORLD_MP, m_game_world_mp, gameWorldMp); + CASE_ADD_TO_POOL(ASSET_TYPE_MAP_ENTS, m_map_ents, mapEnts); + CASE_ADD_TO_POOL(ASSET_TYPE_GFXWORLD, m_gfx_world, gfxWorld); + CASE_ADD_TO_POOL(ASSET_TYPE_LIGHT_DEF, m_gfx_light_def, lightDef); + CASE_ADD_TO_POOL(ASSET_TYPE_FONT, m_font, font); + CASE_ADD_TO_POOL(ASSET_TYPE_MENULIST, m_menu_list, menuList); + CASE_ADD_TO_POOL(ASSET_TYPE_MENU, m_menu_def, menu); + CASE_ADD_TO_POOL(ASSET_TYPE_LOCALIZE_ENTRY, m_localize, localize); + CASE_ADD_TO_POOL(ASSET_TYPE_WEAPON, m_weapon, weapon); + CASE_ADD_TO_POOL(ASSET_TYPE_FX, m_fx, fx); + CASE_ADD_TO_POOL(ASSET_TYPE_IMPACT_FX, m_fx_impact_table, impactFx); + CASE_ADD_TO_POOL(ASSET_TYPE_RAWFILE, m_raw_file, rawfile); + CASE_ADD_TO_POOL(ASSET_TYPE_STRINGTABLE, m_string_table, stringTable); + + default: + assert(false); + break; + } + + return nullptr; #undef CASE_ADD_TO_POOL } -XAssetInfoGeneric* GameAssetPoolIW3::GetAsset(const asset_type_t type, std::string name) const -{ -#define CASE_GET_ASSET(assetType, poolName) \ - case assetType: \ - { \ - if((poolName) != nullptr) \ - return (poolName)->GetAsset(std::move(name)); \ - break; \ - } - - switch (type) - { - CASE_GET_ASSET(ASSET_TYPE_PHYSPRESET, m_phys_preset); - CASE_GET_ASSET(ASSET_TYPE_XANIMPARTS, m_xanim_parts); - CASE_GET_ASSET(ASSET_TYPE_XMODEL, m_xmodel); - CASE_GET_ASSET(ASSET_TYPE_MATERIAL, m_material); - CASE_GET_ASSET(ASSET_TYPE_TECHNIQUE_SET, m_technique_set); - CASE_GET_ASSET(ASSET_TYPE_IMAGE, m_image); - CASE_GET_ASSET(ASSET_TYPE_SOUND, m_sound); - CASE_GET_ASSET(ASSET_TYPE_SOUND_CURVE, m_sound_curve); - CASE_GET_ASSET(ASSET_TYPE_LOADED_SOUND, m_loaded_sound); - CASE_GET_ASSET(ASSET_TYPE_CLIPMAP, m_clip_map); - CASE_GET_ASSET(ASSET_TYPE_CLIPMAP_PVS, m_clip_map); - CASE_GET_ASSET(ASSET_TYPE_COMWORLD, m_com_world); - CASE_GET_ASSET(ASSET_TYPE_GAMEWORLD_SP, m_game_world_sp); - CASE_GET_ASSET(ASSET_TYPE_GAMEWORLD_MP, m_game_world_mp); - CASE_GET_ASSET(ASSET_TYPE_MAP_ENTS, m_map_ents); - CASE_GET_ASSET(ASSET_TYPE_GFXWORLD, m_gfx_world); - CASE_GET_ASSET(ASSET_TYPE_LIGHT_DEF, m_gfx_light_def); - CASE_GET_ASSET(ASSET_TYPE_FONT, m_font); - CASE_GET_ASSET(ASSET_TYPE_MENULIST, m_menu_list); - CASE_GET_ASSET(ASSET_TYPE_MENU, m_menu_def); - CASE_GET_ASSET(ASSET_TYPE_LOCALIZE_ENTRY, m_localize); - CASE_GET_ASSET(ASSET_TYPE_WEAPON, m_weapon); - CASE_GET_ASSET(ASSET_TYPE_FX, m_fx); - CASE_GET_ASSET(ASSET_TYPE_IMPACT_FX, m_fx_impact_table); - CASE_GET_ASSET(ASSET_TYPE_RAWFILE, m_raw_file); - CASE_GET_ASSET(ASSET_TYPE_STRINGTABLE, m_string_table); - - default: - assert(false); - break; - } - - return nullptr; +XAssetInfoGeneric *GameAssetPoolIW3::GetAsset(const asset_type_t type, std::string name) const { +#define CASE_GET_ASSET(assetType, poolName) \ + case assetType: { \ + if ((poolName) != nullptr) \ + return (poolName)->GetAsset(std::move(name)); \ + break; \ + } + + switch (type) { + CASE_GET_ASSET(ASSET_TYPE_PHYSPRESET, m_phys_preset); + CASE_GET_ASSET(ASSET_TYPE_XANIMPARTS, m_xanim_parts); + CASE_GET_ASSET(ASSET_TYPE_XMODEL, m_xmodel); + CASE_GET_ASSET(ASSET_TYPE_MATERIAL, m_material); + CASE_GET_ASSET(ASSET_TYPE_TECHNIQUE_SET, m_technique_set); + CASE_GET_ASSET(ASSET_TYPE_IMAGE, m_image); + CASE_GET_ASSET(ASSET_TYPE_SOUND, m_sound); + CASE_GET_ASSET(ASSET_TYPE_SOUND_CURVE, m_sound_curve); + CASE_GET_ASSET(ASSET_TYPE_LOADED_SOUND, m_loaded_sound); + CASE_GET_ASSET(ASSET_TYPE_CLIPMAP, m_clip_map); + CASE_GET_ASSET(ASSET_TYPE_CLIPMAP_PVS, m_clip_map); + CASE_GET_ASSET(ASSET_TYPE_COMWORLD, m_com_world); + CASE_GET_ASSET(ASSET_TYPE_GAMEWORLD_SP, m_game_world_sp); + CASE_GET_ASSET(ASSET_TYPE_GAMEWORLD_MP, m_game_world_mp); + CASE_GET_ASSET(ASSET_TYPE_MAP_ENTS, m_map_ents); + CASE_GET_ASSET(ASSET_TYPE_GFXWORLD, m_gfx_world); + CASE_GET_ASSET(ASSET_TYPE_LIGHT_DEF, m_gfx_light_def); + CASE_GET_ASSET(ASSET_TYPE_FONT, m_font); + CASE_GET_ASSET(ASSET_TYPE_MENULIST, m_menu_list); + CASE_GET_ASSET(ASSET_TYPE_MENU, m_menu_def); + CASE_GET_ASSET(ASSET_TYPE_LOCALIZE_ENTRY, m_localize); + CASE_GET_ASSET(ASSET_TYPE_WEAPON, m_weapon); + CASE_GET_ASSET(ASSET_TYPE_FX, m_fx); + CASE_GET_ASSET(ASSET_TYPE_IMPACT_FX, m_fx_impact_table); + CASE_GET_ASSET(ASSET_TYPE_RAWFILE, m_raw_file); + CASE_GET_ASSET(ASSET_TYPE_STRINGTABLE, m_string_table); + + default: + assert(false); + break; + } + + return nullptr; #undef CASE_GET_ASSET } -const char* GameAssetPoolIW3::AssetTypeNameByType(asset_type_t assetType) -{ - if (assetType >= 0 && assetType < static_cast<int>(std::extent<decltype(ASSET_TYPE_NAMES)>::value)) - return ASSET_TYPE_NAMES[assetType]; +const char *GameAssetPoolIW3::AssetTypeNameByType(asset_type_t assetType) { + if (assetType >= 0 && assetType < static_cast<int>(std::extent<decltype(ASSET_TYPE_NAMES)>::value)) + return ASSET_TYPE_NAMES[assetType]; - return ASSET_TYPE_INVALID; + return ASSET_TYPE_INVALID; } -const char* GameAssetPoolIW3::GetAssetTypeName(const asset_type_t assetType) const -{ - return AssetTypeNameByType(assetType); -} +const char *GameAssetPoolIW3::GetAssetTypeName(const asset_type_t assetType) const { return AssetTypeNameByType(assetType); } -asset_type_t GameAssetPoolIW3::AssetTypeCount() -{ - return ASSET_TYPE_COUNT; -} +asset_type_t GameAssetPoolIW3::AssetTypeCount() { return ASSET_TYPE_COUNT; } -asset_type_t GameAssetPoolIW3::GetAssetTypeCount() const -{ - return AssetTypeCount(); -} +asset_type_t GameAssetPoolIW3::GetAssetTypeCount() const { return AssetTypeCount(); } diff --git a/src/ZoneCommon/Game/IW3/GameAssetPoolIW3.h b/src/ZoneCommon/Game/IW3/GameAssetPoolIW3.h index 71bcc282c..9b324b9db 100644 --- a/src/ZoneCommon/Game/IW3/GameAssetPoolIW3.h +++ b/src/ZoneCommon/Game/IW3/GameAssetPoolIW3.h @@ -2,61 +2,61 @@ #include <memory> -#include "Pool/ZoneAssetPools.h" -#include "Pool/AssetPool.h" #include "Game/IW3/IW3.h" +#include "Pool/AssetPool.h" +#include "Pool/ZoneAssetPools.h" -class GameAssetPoolIW3 final : public ZoneAssetPools -{ - int m_priority; +class GameAssetPoolIW3 final : public ZoneAssetPools { + int m_priority; - static constexpr const char* ASSET_TYPE_INVALID = "invalid_asset_type"; - static const char* ASSET_TYPE_NAMES[]; + static constexpr const char *ASSET_TYPE_INVALID = "invalid_asset_type"; + static const char *ASSET_TYPE_NAMES[]; protected: - XAssetInfoGeneric* AddAssetToPool(asset_type_t type, std::string name, void* asset, std::vector<XAssetInfoGeneric*> dependencies, std::vector<scr_string_t> usedScriptStrings, Zone* zone) override; + XAssetInfoGeneric *AddAssetToPool(asset_type_t type, std::string name, void *asset, std::vector<XAssetInfoGeneric *> dependencies, + std::vector<scr_string_t> usedScriptStrings, Zone *zone) override; public: - std::unique_ptr<AssetPool<IW3::PhysPreset>> m_phys_preset; - std::unique_ptr<AssetPool<IW3::XAnimParts>> m_xanim_parts; - std::unique_ptr<AssetPool<IW3::XModel>> m_xmodel; - std::unique_ptr<AssetPool<IW3::Material>> m_material; - std::unique_ptr<AssetPool<IW3::MaterialPixelShader>> m_material_pixel_shader; - std::unique_ptr<AssetPool<IW3::MaterialVertexShader>> m_material_vertex_shader; - std::unique_ptr<AssetPool<IW3::MaterialVertexDeclaration>> m_material_vertex_decl; - std::unique_ptr<AssetPool<IW3::MaterialTechniqueSet>> m_technique_set; - std::unique_ptr<AssetPool<IW3::GfxImage>> m_image; - std::unique_ptr<AssetPool<IW3::snd_alias_list_t>> m_sound; - std::unique_ptr<AssetPool<IW3::SndCurve>> m_sound_curve; - std::unique_ptr<AssetPool<IW3::LoadedSound>> m_loaded_sound; - std::unique_ptr<AssetPool<IW3::clipMap_t>> m_clip_map; - std::unique_ptr<AssetPool<IW3::ComWorld>> m_com_world; - std::unique_ptr<AssetPool<IW3::GameWorldSp>> m_game_world_sp; - std::unique_ptr<AssetPool<IW3::GameWorldMp>> m_game_world_mp; - std::unique_ptr<AssetPool<IW3::MapEnts>> m_map_ents; - std::unique_ptr<AssetPool<IW3::GfxWorld>> m_gfx_world; - std::unique_ptr<AssetPool<IW3::GfxLightDef>> m_gfx_light_def; - std::unique_ptr<AssetPool<IW3::Font_s>> m_font; - std::unique_ptr<AssetPool<IW3::MenuList>> m_menu_list; - std::unique_ptr<AssetPool<IW3::menuDef_t>> m_menu_def; - std::unique_ptr<AssetPool<IW3::LocalizeEntry>> m_localize; - std::unique_ptr<AssetPool<IW3::WeaponDef>> m_weapon; - std::unique_ptr<AssetPool<IW3::FxEffectDef>> m_fx; - std::unique_ptr<AssetPool<IW3::FxImpactTable>> m_fx_impact_table; - std::unique_ptr<AssetPool<IW3::RawFile>> m_raw_file; - std::unique_ptr<AssetPool<IW3::StringTable>> m_string_table; - - GameAssetPoolIW3(Zone* zone, int priority); - ~GameAssetPoolIW3() override = default; - - void InitPoolStatic(asset_type_t type, size_t capacity) override; - void InitPoolDynamic(asset_type_t type) override; - - _NODISCARD XAssetInfoGeneric* GetAsset(asset_type_t type, std::string name) const override; - - static const char* AssetTypeNameByType(asset_type_t assetType); - _NODISCARD const char* GetAssetTypeName(asset_type_t assetType) const override; - - static asset_type_t AssetTypeCount(); - _NODISCARD asset_type_t GetAssetTypeCount() const override; + std::unique_ptr<AssetPool<IW3::PhysPreset>> m_phys_preset; + std::unique_ptr<AssetPool<IW3::XAnimParts>> m_xanim_parts; + std::unique_ptr<AssetPool<IW3::XModel>> m_xmodel; + std::unique_ptr<AssetPool<IW3::Material>> m_material; + std::unique_ptr<AssetPool<IW3::MaterialPixelShader>> m_material_pixel_shader; + std::unique_ptr<AssetPool<IW3::MaterialVertexShader>> m_material_vertex_shader; + std::unique_ptr<AssetPool<IW3::MaterialVertexDeclaration>> m_material_vertex_decl; + std::unique_ptr<AssetPool<IW3::MaterialTechniqueSet>> m_technique_set; + std::unique_ptr<AssetPool<IW3::GfxImage>> m_image; + std::unique_ptr<AssetPool<IW3::snd_alias_list_t>> m_sound; + std::unique_ptr<AssetPool<IW3::SndCurve>> m_sound_curve; + std::unique_ptr<AssetPool<IW3::LoadedSound>> m_loaded_sound; + std::unique_ptr<AssetPool<IW3::clipMap_t>> m_clip_map; + std::unique_ptr<AssetPool<IW3::ComWorld>> m_com_world; + std::unique_ptr<AssetPool<IW3::GameWorldSp>> m_game_world_sp; + std::unique_ptr<AssetPool<IW3::GameWorldMp>> m_game_world_mp; + std::unique_ptr<AssetPool<IW3::MapEnts>> m_map_ents; + std::unique_ptr<AssetPool<IW3::GfxWorld>> m_gfx_world; + std::unique_ptr<AssetPool<IW3::GfxLightDef>> m_gfx_light_def; + std::unique_ptr<AssetPool<IW3::Font_s>> m_font; + std::unique_ptr<AssetPool<IW3::MenuList>> m_menu_list; + std::unique_ptr<AssetPool<IW3::menuDef_t>> m_menu_def; + std::unique_ptr<AssetPool<IW3::LocalizeEntry>> m_localize; + std::unique_ptr<AssetPool<IW3::WeaponDef>> m_weapon; + std::unique_ptr<AssetPool<IW3::FxEffectDef>> m_fx; + std::unique_ptr<AssetPool<IW3::FxImpactTable>> m_fx_impact_table; + std::unique_ptr<AssetPool<IW3::RawFile>> m_raw_file; + std::unique_ptr<AssetPool<IW3::StringTable>> m_string_table; + + GameAssetPoolIW3(Zone *zone, int priority); + ~GameAssetPoolIW3() override = default; + + void InitPoolStatic(asset_type_t type, size_t capacity) override; + void InitPoolDynamic(asset_type_t type) override; + + _NODISCARD XAssetInfoGeneric *GetAsset(asset_type_t type, std::string name) const override; + + static const char *AssetTypeNameByType(asset_type_t assetType); + _NODISCARD const char *GetAssetTypeName(asset_type_t assetType) const override; + + static asset_type_t AssetTypeCount(); + _NODISCARD asset_type_t GetAssetTypeCount() const override; }; diff --git a/src/ZoneCommon/Game/IW3/ZoneConstantsIW3.h b/src/ZoneCommon/Game/IW3/ZoneConstantsIW3.h index 1c85befe9..350809283 100644 --- a/src/ZoneCommon/Game/IW3/ZoneConstantsIW3.h +++ b/src/ZoneCommon/Game/IW3/ZoneConstantsIW3.h @@ -2,25 +2,23 @@ #include <cstdint> #include <string> -#include "Zone/ZoneTypes.h" #include "Game/IW3/IW3.h" +#include "Zone/ZoneTypes.h" + +namespace IW3 { +class ZoneConstants final { + ZoneConstants() = default; -namespace IW3 -{ - class ZoneConstants final - { - ZoneConstants() = default; +public: + static constexpr const char *MAGIC_UNSIGNED = "IWffu100"; + static constexpr int ZONE_VERSION = 5; - public: - static constexpr const char* MAGIC_UNSIGNED = "IWffu100"; - static constexpr int ZONE_VERSION = 5; - - static_assert(std::char_traits<char>::length(MAGIC_UNSIGNED) == sizeof(ZoneHeader::m_magic)); + static_assert(std::char_traits<char>::length(MAGIC_UNSIGNED) == sizeof(ZoneHeader::m_magic)); - static constexpr size_t AUTHED_CHUNK_SIZE = 0x2000; - static constexpr unsigned AUTHED_CHUNK_COUNT_PER_GROUP = 256; + static constexpr size_t AUTHED_CHUNK_SIZE = 0x2000; + static constexpr unsigned AUTHED_CHUNK_COUNT_PER_GROUP = 256; - static constexpr int OFFSET_BLOCK_BIT_COUNT = 4; - static constexpr block_t INSERT_BLOCK = XFILE_BLOCK_VIRTUAL; - }; -} + static constexpr int OFFSET_BLOCK_BIT_COUNT = 4; + static constexpr block_t INSERT_BLOCK = XFILE_BLOCK_VIRTUAL; +}; +} // namespace IW3 diff --git a/src/ZoneCommon/Game/IW4/GameAssetPoolIW4.cpp b/src/ZoneCommon/Game/IW4/GameAssetPoolIW4.cpp index d6cf8a863..1d60f9b15 100644 --- a/src/ZoneCommon/Game/IW4/GameAssetPoolIW4.cpp +++ b/src/ZoneCommon/Game/IW4/GameAssetPoolIW4.cpp @@ -3,62 +3,22 @@ #include <cassert> #include <type_traits> -#include "Pool/AssetPoolStatic.h" #include "Pool/AssetPoolDynamic.h" +#include "Pool/AssetPoolStatic.h" using namespace IW4; -const char* GameAssetPoolIW4::ASSET_TYPE_NAMES[] -{ - "physpreset", - "physcollmap", - "xanim", - "xmodelsurfs", - "xmodel", - "material", - "pixelshader", - "vertexshader", - "vertexdecl", - "techniqueset", - "image", - "sound", - "soundcurve", - "loadedsound", - "clipmap", - "clipmap", - "comworld", - "gameworldsp", - "gameworldmp", - "mapents", - "fxworld", - "gfxworld", - "lightdef", - "uimap", - "font", - "menulist", - "menu", - "localize", - "weapon", - "snddriverglobals", - "fx", - "impactfx", - "aitype", - "mptype", - "character", - "xmodelalias", - "rawfile", - "stringtable", - "leaderboard", - "structureddatadef", - "tracer", - "vehicle", - "addonmapents" -}; +const char *GameAssetPoolIW4::ASSET_TYPE_NAMES[]{ + "physpreset", "physcollmap", "xanim", "xmodelsurfs", "xmodel", "material", "pixelshader", "vertexshader", "vertexdecl", "techniqueset", + "image", "sound", "soundcurve", "loadedsound", "clipmap", "clipmap", "comworld", "gameworldsp", "gameworldmp", "mapents", + "fxworld", "gfxworld", "lightdef", "uimap", "font", "menulist", "menu", "localize", "weapon", "snddriverglobals", + "fx", "impactfx", "aitype", "mptype", "character", "xmodelalias", "rawfile", "stringtable", "leaderboard", "structureddatadef", + "tracer", "vehicle", "addonmapents"}; /* Asset Pool Table Useful for macro generation via regex-replace for example - + #assetType, #typeName, #unionEntry, #poolName ASSET_TYPE_PHYSPRESET, PhysPreset, physPreset, m_phys_preset ASSET_TYPE_PHYSCOLLMAP, PhysCollmap, physCollmap, m_phys_collmap @@ -99,27 +59,20 @@ const char* GameAssetPoolIW4::ASSET_TYPE_NAMES[] ASSET_TYPE_ADDON_MAP_ENTS, AddonMapEnts, addonMapEnts, m_addon_map_ents */ -GameAssetPoolIW4::GameAssetPoolIW4(Zone* zone, const int priority) - : ZoneAssetPools(zone), - m_priority(priority) -{ - assert(std::extent<decltype(ASSET_TYPE_NAMES)>::value == ASSET_TYPE_COUNT); +GameAssetPoolIW4::GameAssetPoolIW4(Zone *zone, const int priority) : ZoneAssetPools(zone), m_priority(priority) { + assert(std::extent<decltype(ASSET_TYPE_NAMES)>::value == ASSET_TYPE_COUNT); } -void GameAssetPoolIW4::InitPoolStatic(const asset_type_t type, const size_t capacity) -{ -#define CASE_INIT_POOL_STATIC(assetType, poolName, poolType) \ - case assetType: \ - { \ - if((poolName) == nullptr && capacity > 0) \ - { \ - (poolName) = std::make_unique<AssetPoolStatic<poolType>>(capacity, m_priority, (assetType)); \ - } \ - break; \ - } - - switch (type) - { +void GameAssetPoolIW4::InitPoolStatic(const asset_type_t type, const size_t capacity) { +#define CASE_INIT_POOL_STATIC(assetType, poolName, poolType) \ + case assetType: { \ + if ((poolName) == nullptr && capacity > 0) { \ + (poolName) = std::make_unique<AssetPoolStatic<poolType>>(capacity, m_priority, (assetType)); \ + } \ + break; \ + } + + switch (type) { CASE_INIT_POOL_STATIC(ASSET_TYPE_PHYSPRESET, m_phys_preset, PhysPreset); CASE_INIT_POOL_STATIC(ASSET_TYPE_PHYSCOLLMAP, m_phys_collmap, PhysCollmap); CASE_INIT_POOL_STATIC(ASSET_TYPE_XANIMPARTS, m_xanim_parts, XAnimParts); @@ -157,28 +110,24 @@ void GameAssetPoolIW4::InitPoolStatic(const asset_type_t type, const size_t capa CASE_INIT_POOL_STATIC(ASSET_TYPE_VEHICLE, m_vehicle, VehicleDef); CASE_INIT_POOL_STATIC(ASSET_TYPE_ADDON_MAP_ENTS, m_addon_map_ents, AddonMapEnts); - default: - assert(type >= 0 && type < ASSET_TYPE_COUNT); - break; - } + default: + assert(type >= 0 && type < ASSET_TYPE_COUNT); + break; + } #undef CASE_INIT_POOL_STATIC } -void GameAssetPoolIW4::InitPoolDynamic(const asset_type_t type) -{ -#define CASE_INIT_POOL_DYNAMIC(assetType, poolName, poolType) \ - case assetType: \ - { \ - if((poolName) == nullptr) \ - { \ - (poolName) = std::make_unique<AssetPoolDynamic<poolType>>(m_priority, (assetType)); \ - } \ - break; \ - } - - switch (type) - { +void GameAssetPoolIW4::InitPoolDynamic(const asset_type_t type) { +#define CASE_INIT_POOL_DYNAMIC(assetType, poolName, poolType) \ + case assetType: { \ + if ((poolName) == nullptr) { \ + (poolName) = std::make_unique<AssetPoolDynamic<poolType>>(m_priority, (assetType)); \ + } \ + break; \ + } + + switch (type) { CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_PHYSPRESET, m_phys_preset, PhysPreset); CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_PHYSCOLLMAP, m_phys_collmap, PhysCollmap); CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_XANIMPARTS, m_xanim_parts, XAnimParts); @@ -216,30 +165,28 @@ void GameAssetPoolIW4::InitPoolDynamic(const asset_type_t type) CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_VEHICLE, m_vehicle, VehicleDef); CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_ADDON_MAP_ENTS, m_addon_map_ents, AddonMapEnts); - default: - assert(type >= 0 && type < ASSET_TYPE_COUNT); - break; - } + default: + assert(type >= 0 && type < ASSET_TYPE_COUNT); + break; + } #undef CASE_INIT_POOL_STATIC } -XAssetInfoGeneric* GameAssetPoolIW4::AddAssetToPool(asset_type_t type, std::string name, void* asset, std::vector<XAssetInfoGeneric*> dependencies, std::vector<scr_string_t> usedScriptStrings, Zone* zone) -{ - XAsset xAsset{}; +XAssetInfoGeneric *GameAssetPoolIW4::AddAssetToPool(asset_type_t type, std::string name, void *asset, std::vector<XAssetInfoGeneric *> dependencies, + std::vector<scr_string_t> usedScriptStrings, Zone *zone) { + XAsset xAsset{}; - xAsset.type = static_cast<XAssetType>(type); - xAsset.header.data = asset; + xAsset.type = static_cast<XAssetType>(type); + xAsset.header.data = asset; -#define CASE_ADD_TO_POOL(assetType, poolName, headerName) \ - case assetType: \ - { \ - assert((poolName) != nullptr); \ - return (poolName)->AddAsset(std::move(name), xAsset.header.headerName, zone, std::move(dependencies), std::move(usedScriptStrings)); \ - } +#define CASE_ADD_TO_POOL(assetType, poolName, headerName) \ + case assetType: { \ + assert((poolName) != nullptr); \ + return (poolName)->AddAsset(std::move(name), xAsset.header.headerName, zone, std::move(dependencies), std::move(usedScriptStrings)); \ + } - switch (xAsset.type) - { + switch (xAsset.type) { CASE_ADD_TO_POOL(ASSET_TYPE_PHYSPRESET, m_phys_preset, physPreset); CASE_ADD_TO_POOL(ASSET_TYPE_PHYSCOLLMAP, m_phys_collmap, physCollmap); CASE_ADD_TO_POOL(ASSET_TYPE_XANIMPARTS, m_xanim_parts, parts); @@ -277,28 +224,25 @@ XAssetInfoGeneric* GameAssetPoolIW4::AddAssetToPool(asset_type_t type, std::stri CASE_ADD_TO_POOL(ASSET_TYPE_VEHICLE, m_vehicle, vehDef); CASE_ADD_TO_POOL(ASSET_TYPE_ADDON_MAP_ENTS, m_addon_map_ents, addonMapEnts); - default: - assert(false); - break; - } + default: + assert(false); + break; + } - return nullptr; + return nullptr; #undef CASE_ADD_TO_POOL } -XAssetInfoGeneric* GameAssetPoolIW4::GetAsset(const asset_type_t type, std::string name) const -{ -#define CASE_GET_ASSET(assetType, poolName) \ - case assetType: \ - { \ - if((poolName) != nullptr) \ - return (poolName)->GetAsset(std::move(name)); \ - break; \ - } - - switch (type) - { +XAssetInfoGeneric *GameAssetPoolIW4::GetAsset(const asset_type_t type, std::string name) const { +#define CASE_GET_ASSET(assetType, poolName) \ + case assetType: { \ + if ((poolName) != nullptr) \ + return (poolName)->GetAsset(std::move(name)); \ + break; \ + } + + switch (type) { CASE_GET_ASSET(ASSET_TYPE_PHYSPRESET, m_phys_preset); CASE_GET_ASSET(ASSET_TYPE_PHYSCOLLMAP, m_phys_collmap); CASE_GET_ASSET(ASSET_TYPE_XANIMPARTS, m_xanim_parts); @@ -336,35 +280,25 @@ XAssetInfoGeneric* GameAssetPoolIW4::GetAsset(const asset_type_t type, std::stri CASE_GET_ASSET(ASSET_TYPE_VEHICLE, m_vehicle); CASE_GET_ASSET(ASSET_TYPE_ADDON_MAP_ENTS, m_addon_map_ents); - default: - assert(false); - break; - } + default: + assert(false); + break; + } - return nullptr; + return nullptr; #undef CASE_GET_ASSET } -const char* GameAssetPoolIW4::AssetTypeNameByType(asset_type_t assetType) -{ - if (assetType >= 0 && assetType < static_cast<int>(std::extent<decltype(ASSET_TYPE_NAMES)>::value)) - return ASSET_TYPE_NAMES[assetType]; +const char *GameAssetPoolIW4::AssetTypeNameByType(asset_type_t assetType) { + if (assetType >= 0 && assetType < static_cast<int>(std::extent<decltype(ASSET_TYPE_NAMES)>::value)) + return ASSET_TYPE_NAMES[assetType]; - return ASSET_TYPE_INVALID; + return ASSET_TYPE_INVALID; } -const char* GameAssetPoolIW4::GetAssetTypeName(const asset_type_t assetType) const -{ - return AssetTypeNameByType(assetType); -} +const char *GameAssetPoolIW4::GetAssetTypeName(const asset_type_t assetType) const { return AssetTypeNameByType(assetType); } -asset_type_t GameAssetPoolIW4::AssetTypeCount() -{ - return ASSET_TYPE_COUNT; -} +asset_type_t GameAssetPoolIW4::AssetTypeCount() { return ASSET_TYPE_COUNT; } -asset_type_t GameAssetPoolIW4::GetAssetTypeCount() const -{ - return AssetTypeCount(); -} +asset_type_t GameAssetPoolIW4::GetAssetTypeCount() const { return AssetTypeCount(); } diff --git a/src/ZoneCommon/Game/IW4/GameAssetPoolIW4.h b/src/ZoneCommon/Game/IW4/GameAssetPoolIW4.h index 1cf60a472..083c740c6 100644 --- a/src/ZoneCommon/Game/IW4/GameAssetPoolIW4.h +++ b/src/ZoneCommon/Game/IW4/GameAssetPoolIW4.h @@ -2,69 +2,69 @@ #include <memory> -#include "Utils/ClassUtils.h" -#include "Pool/ZoneAssetPools.h" -#include "Pool/AssetPool.h" #include "Game/IW4/IW4.h" +#include "Pool/AssetPool.h" +#include "Pool/ZoneAssetPools.h" +#include "Utils/ClassUtils.h" -class GameAssetPoolIW4 final : public ZoneAssetPools -{ - int m_priority; +class GameAssetPoolIW4 final : public ZoneAssetPools { + int m_priority; - static constexpr const char* ASSET_TYPE_INVALID = "invalid_asset_type"; - static const char* ASSET_TYPE_NAMES[]; + static constexpr const char *ASSET_TYPE_INVALID = "invalid_asset_type"; + static const char *ASSET_TYPE_NAMES[]; protected: - XAssetInfoGeneric* AddAssetToPool(asset_type_t type, std::string name, void* asset, std::vector<XAssetInfoGeneric*> dependencies, std::vector<scr_string_t> usedScriptStrings, Zone* zone) override; + XAssetInfoGeneric *AddAssetToPool(asset_type_t type, std::string name, void *asset, std::vector<XAssetInfoGeneric *> dependencies, + std::vector<scr_string_t> usedScriptStrings, Zone *zone) override; public: - std::unique_ptr<AssetPool<IW4::PhysPreset>> m_phys_preset; - std::unique_ptr<AssetPool<IW4::PhysCollmap>> m_phys_collmap; - std::unique_ptr<AssetPool<IW4::XAnimParts>> m_xanim_parts; - std::unique_ptr<AssetPool<IW4::XModel>> m_xmodel; - std::unique_ptr<AssetPool<IW4::Material>> m_material; - std::unique_ptr<AssetPool<IW4::MaterialPixelShader>> m_material_pixel_shader; - std::unique_ptr<AssetPool<IW4::MaterialVertexShader>> m_material_vertex_shader; - std::unique_ptr<AssetPool<IW4::MaterialVertexDeclaration>> m_material_vertex_decl; - std::unique_ptr<AssetPool<IW4::MaterialTechniqueSet>> m_technique_set; - std::unique_ptr<AssetPool<IW4::GfxImage>> m_image; - std::unique_ptr<AssetPool<IW4::snd_alias_list_t>> m_sound; - std::unique_ptr<AssetPool<IW4::SndCurve>> m_sound_curve; - std::unique_ptr<AssetPool<IW4::LoadedSound>> m_loaded_sound; - std::unique_ptr<AssetPool<IW4::clipMap_t>> m_clip_map; - std::unique_ptr<AssetPool<IW4::ComWorld>> m_com_world; - std::unique_ptr<AssetPool<IW4::GameWorldSp>> m_game_world_sp; - std::unique_ptr<AssetPool<IW4::GameWorldMp>> m_game_world_mp; - std::unique_ptr<AssetPool<IW4::MapEnts>> m_map_ents; - std::unique_ptr<AssetPool<IW4::FxWorld>> m_fx_world; - std::unique_ptr<AssetPool<IW4::GfxWorld>> m_gfx_world; - std::unique_ptr<AssetPool<IW4::GfxLightDef>> m_gfx_light_def; - std::unique_ptr<AssetPool<IW4::Font_s>> m_font; - std::unique_ptr<AssetPool<IW4::MenuList>> m_menu_list; - std::unique_ptr<AssetPool<IW4::menuDef_t>> m_menu_def; - std::unique_ptr<AssetPool<IW4::LocalizeEntry>> m_localize; - std::unique_ptr<AssetPool<IW4::WeaponCompleteDef>> m_weapon; - std::unique_ptr<AssetPool<IW4::FxEffectDef>> m_fx; - std::unique_ptr<AssetPool<IW4::FxImpactTable>> m_fx_impact_table; - std::unique_ptr<AssetPool<IW4::RawFile>> m_raw_file; - std::unique_ptr<AssetPool<IW4::StringTable>> m_string_table; - std::unique_ptr<AssetPool<IW4::LeaderboardDef>> m_leaderboard; - std::unique_ptr<AssetPool<IW4::StructuredDataDefSet>> m_structed_data_def_set; - std::unique_ptr<AssetPool<IW4::TracerDef>> m_tracer; - std::unique_ptr<AssetPool<IW4::VehicleDef>> m_vehicle; - std::unique_ptr<AssetPool<IW4::AddonMapEnts>> m_addon_map_ents; + std::unique_ptr<AssetPool<IW4::PhysPreset>> m_phys_preset; + std::unique_ptr<AssetPool<IW4::PhysCollmap>> m_phys_collmap; + std::unique_ptr<AssetPool<IW4::XAnimParts>> m_xanim_parts; + std::unique_ptr<AssetPool<IW4::XModel>> m_xmodel; + std::unique_ptr<AssetPool<IW4::Material>> m_material; + std::unique_ptr<AssetPool<IW4::MaterialPixelShader>> m_material_pixel_shader; + std::unique_ptr<AssetPool<IW4::MaterialVertexShader>> m_material_vertex_shader; + std::unique_ptr<AssetPool<IW4::MaterialVertexDeclaration>> m_material_vertex_decl; + std::unique_ptr<AssetPool<IW4::MaterialTechniqueSet>> m_technique_set; + std::unique_ptr<AssetPool<IW4::GfxImage>> m_image; + std::unique_ptr<AssetPool<IW4::snd_alias_list_t>> m_sound; + std::unique_ptr<AssetPool<IW4::SndCurve>> m_sound_curve; + std::unique_ptr<AssetPool<IW4::LoadedSound>> m_loaded_sound; + std::unique_ptr<AssetPool<IW4::clipMap_t>> m_clip_map; + std::unique_ptr<AssetPool<IW4::ComWorld>> m_com_world; + std::unique_ptr<AssetPool<IW4::GameWorldSp>> m_game_world_sp; + std::unique_ptr<AssetPool<IW4::GameWorldMp>> m_game_world_mp; + std::unique_ptr<AssetPool<IW4::MapEnts>> m_map_ents; + std::unique_ptr<AssetPool<IW4::FxWorld>> m_fx_world; + std::unique_ptr<AssetPool<IW4::GfxWorld>> m_gfx_world; + std::unique_ptr<AssetPool<IW4::GfxLightDef>> m_gfx_light_def; + std::unique_ptr<AssetPool<IW4::Font_s>> m_font; + std::unique_ptr<AssetPool<IW4::MenuList>> m_menu_list; + std::unique_ptr<AssetPool<IW4::menuDef_t>> m_menu_def; + std::unique_ptr<AssetPool<IW4::LocalizeEntry>> m_localize; + std::unique_ptr<AssetPool<IW4::WeaponCompleteDef>> m_weapon; + std::unique_ptr<AssetPool<IW4::FxEffectDef>> m_fx; + std::unique_ptr<AssetPool<IW4::FxImpactTable>> m_fx_impact_table; + std::unique_ptr<AssetPool<IW4::RawFile>> m_raw_file; + std::unique_ptr<AssetPool<IW4::StringTable>> m_string_table; + std::unique_ptr<AssetPool<IW4::LeaderboardDef>> m_leaderboard; + std::unique_ptr<AssetPool<IW4::StructuredDataDefSet>> m_structed_data_def_set; + std::unique_ptr<AssetPool<IW4::TracerDef>> m_tracer; + std::unique_ptr<AssetPool<IW4::VehicleDef>> m_vehicle; + std::unique_ptr<AssetPool<IW4::AddonMapEnts>> m_addon_map_ents; - GameAssetPoolIW4(Zone* zone, int priority); - ~GameAssetPoolIW4() override = default; + GameAssetPoolIW4(Zone *zone, int priority); + ~GameAssetPoolIW4() override = default; - void InitPoolStatic(asset_type_t type, size_t capacity) override; - void InitPoolDynamic(asset_type_t type) override; + void InitPoolStatic(asset_type_t type, size_t capacity) override; + void InitPoolDynamic(asset_type_t type) override; - _NODISCARD XAssetInfoGeneric* GetAsset(asset_type_t type, std::string name) const override; + _NODISCARD XAssetInfoGeneric *GetAsset(asset_type_t type, std::string name) const override; - static const char* AssetTypeNameByType(asset_type_t assetType); - _NODISCARD const char* GetAssetTypeName(asset_type_t assetType) const override; + static const char *AssetTypeNameByType(asset_type_t assetType); + _NODISCARD const char *GetAssetTypeName(asset_type_t assetType) const override; - static asset_type_t AssetTypeCount(); - _NODISCARD asset_type_t GetAssetTypeCount() const override; + static asset_type_t AssetTypeCount(); + _NODISCARD asset_type_t GetAssetTypeCount() const override; }; diff --git a/src/ZoneCommon/Game/IW4/ZoneConstantsIW4.h b/src/ZoneCommon/Game/IW4/ZoneConstantsIW4.h index 621e91ee3..21d2267b1 100644 --- a/src/ZoneCommon/Game/IW4/ZoneConstantsIW4.h +++ b/src/ZoneCommon/Game/IW4/ZoneConstantsIW4.h @@ -2,71 +2,44 @@ #include <cstdint> #include <string> -#include "Zone/ZoneTypes.h" #include "Game/IW4/IW4.h" +#include "Zone/ZoneTypes.h" -namespace IW4 -{ - class ZoneConstants final - { - ZoneConstants() = default; +namespace IW4 { +class ZoneConstants final { + ZoneConstants() = default; - public: - static constexpr const char* MAGIC_SIGNED_INFINITY_WARD = "IWff0100"; - static constexpr const char* MAGIC_SIGNED_OAT = "ABff0100"; - static constexpr const char* MAGIC_UNSIGNED = "IWffu100"; - static constexpr const char* MAGIC_IW4X = "IW4x"; - static constexpr int ZONE_VERSION = 276; - static constexpr int IW4X_ZONE_VERSION = 3; +public: + static constexpr const char *MAGIC_SIGNED_INFINITY_WARD = "IWff0100"; + static constexpr const char *MAGIC_SIGNED_OAT = "ABff0100"; + static constexpr const char *MAGIC_UNSIGNED = "IWffu100"; + static constexpr const char *MAGIC_IW4X = "IW4x"; + static constexpr int ZONE_VERSION = 276; + static constexpr int IW4X_ZONE_VERSION = 3; - static_assert(std::char_traits<char>::length(MAGIC_SIGNED_INFINITY_WARD) == sizeof(ZoneHeader::m_magic)); - static_assert(std::char_traits<char>::length(MAGIC_SIGNED_OAT) == sizeof(ZoneHeader::m_magic)); - static_assert(std::char_traits<char>::length(MAGIC_UNSIGNED) == sizeof(ZoneHeader::m_magic)); - static_assert(std::char_traits<char>::length(MAGIC_IW4X) == sizeof(ZoneHeader::m_magic) - sizeof(uint32_t)); + static_assert(std::char_traits<char>::length(MAGIC_SIGNED_INFINITY_WARD) == sizeof(ZoneHeader::m_magic)); + static_assert(std::char_traits<char>::length(MAGIC_SIGNED_OAT) == sizeof(ZoneHeader::m_magic)); + static_assert(std::char_traits<char>::length(MAGIC_UNSIGNED) == sizeof(ZoneHeader::m_magic)); + static_assert(std::char_traits<char>::length(MAGIC_IW4X) == sizeof(ZoneHeader::m_magic) - sizeof(uint32_t)); - static constexpr const char* MAGIC_AUTH_HEADER = "IWffs100"; - inline static const uint8_t RSA_PUBLIC_KEY_INFINITY_WARD[] - { - 0x30, 0x82, 0x01, 0x0A, 0x02, 0x82, 0x01, 0x01, - 0x00, 0xA5, 0x86, 0xCC, 0x18, 0xA9, 0x12, 0x17, - 0x4F, 0x3A, 0xC9, 0x0C, 0xD2, 0x38, 0x5D, 0xDB, - 0x67, 0x62, 0xA4, 0xE3, 0xD4, 0x42, 0x05, 0x8A, - 0x57, 0x0C, 0x31, 0x4E, 0x19, 0xE4, 0xBA, 0x89, - 0x73, 0x13, 0xDB, 0x72, 0x25, 0x63, 0xB1, 0x2F, - 0xD7, 0xF1, 0x08, 0x48, 0x34, 0x06, 0xD7, 0x84, - 0x5F, 0xC8, 0xCF, 0x2F, 0xB6, 0xA3, 0x5A, 0x8F, - 0x7E, 0xAA, 0x9D, 0x51, 0xE7, 0x0F, 0xB9, 0x07, - 0xB7, 0x30, 0x91, 0x04, 0x39, 0x9C, 0xDC, 0x1C, - 0xF1, 0x16, 0xCB, 0x96, 0x10, 0xEB, 0x38, 0xB1, - 0x3B, 0xBA, 0x42, 0xE3, 0xE2, 0x78, 0xBD, 0x77, - 0x82, 0x1A, 0x2B, 0x54, 0x27, 0x0A, 0xF7, 0x66, - 0x06, 0xAD, 0x46, 0x39, 0xC0, 0xEB, 0xB5, 0xC2, - 0x27, 0xDD, 0x2C, 0x08, 0x62, 0x2C, 0x0B, 0xC4, - 0x00, 0x0D, 0xCB, 0xAD, 0x22, 0x67, 0x01, 0xA6, - 0x92, 0x9C, 0x00, 0xAF, 0x9D, 0x55, 0xCC, 0x68, - 0xEC, 0x39, 0x49, 0x85, 0x7E, 0x2C, 0x98, 0xCF, - 0x4C, 0x12, 0x8D, 0xED, 0xC7, 0x1D, 0x21, 0x54, - 0x9C, 0x2F, 0xC9, 0x54, 0x36, 0x08, 0xA9, 0x67, - 0xEE, 0x91, 0xE6, 0xD9, 0xB1, 0xFA, 0xA9, 0x2B, - 0x88, 0xAD, 0x2A, 0xD0, 0xAA, 0x28, 0xF9, 0x47, - 0xA6, 0x0F, 0xCF, 0x55, 0x4C, 0x9B, 0x26, 0x41, - 0x89, 0x76, 0x11, 0xFD, 0x1B, 0x83, 0xE4, 0xE8, - 0x8E, 0x7E, 0xB4, 0x03, 0xA3, 0x29, 0xDD, 0x4F, - 0xAC, 0x99, 0xBE, 0x7C, 0xD3, 0xFD, 0x14, 0x28, - 0x1C, 0x59, 0x69, 0xE0, 0x79, 0x5F, 0x4B, 0xDA, - 0x6B, 0xAB, 0x48, 0x4E, 0x28, 0x39, 0x84, 0xC6, - 0x2B, 0xC6, 0x20, 0x05, 0xDB, 0x05, 0x21, 0xC3, - 0xE1, 0xD4, 0x20, 0x28, 0xDD, 0x3A, 0x4D, 0x51, - 0xE7, 0x49, 0x8A, 0x49, 0xEF, 0xF5, 0xDA, 0xDA, - 0x7D, 0x5D, 0xA8, 0x0B, 0xA1, 0x77, 0xCD, 0x62, - 0x7D, 0x9D, 0x40, 0x26, 0x44, 0x4B, 0x3B, 0x0A, - 0x89, 0x02, 0x03, 0x01, 0x00, 0x01 - }; + static constexpr const char *MAGIC_AUTH_HEADER = "IWffs100"; + inline static const uint8_t RSA_PUBLIC_KEY_INFINITY_WARD[]{ + 0x30, 0x82, 0x01, 0x0A, 0x02, 0x82, 0x01, 0x01, 0x00, 0xA5, 0x86, 0xCC, 0x18, 0xA9, 0x12, 0x17, 0x4F, 0x3A, 0xC9, 0x0C, 0xD2, 0x38, 0x5D, 0xDB, 0x67, + 0x62, 0xA4, 0xE3, 0xD4, 0x42, 0x05, 0x8A, 0x57, 0x0C, 0x31, 0x4E, 0x19, 0xE4, 0xBA, 0x89, 0x73, 0x13, 0xDB, 0x72, 0x25, 0x63, 0xB1, 0x2F, 0xD7, 0xF1, + 0x08, 0x48, 0x34, 0x06, 0xD7, 0x84, 0x5F, 0xC8, 0xCF, 0x2F, 0xB6, 0xA3, 0x5A, 0x8F, 0x7E, 0xAA, 0x9D, 0x51, 0xE7, 0x0F, 0xB9, 0x07, 0xB7, 0x30, 0x91, + 0x04, 0x39, 0x9C, 0xDC, 0x1C, 0xF1, 0x16, 0xCB, 0x96, 0x10, 0xEB, 0x38, 0xB1, 0x3B, 0xBA, 0x42, 0xE3, 0xE2, 0x78, 0xBD, 0x77, 0x82, 0x1A, 0x2B, 0x54, + 0x27, 0x0A, 0xF7, 0x66, 0x06, 0xAD, 0x46, 0x39, 0xC0, 0xEB, 0xB5, 0xC2, 0x27, 0xDD, 0x2C, 0x08, 0x62, 0x2C, 0x0B, 0xC4, 0x00, 0x0D, 0xCB, 0xAD, 0x22, + 0x67, 0x01, 0xA6, 0x92, 0x9C, 0x00, 0xAF, 0x9D, 0x55, 0xCC, 0x68, 0xEC, 0x39, 0x49, 0x85, 0x7E, 0x2C, 0x98, 0xCF, 0x4C, 0x12, 0x8D, 0xED, 0xC7, 0x1D, + 0x21, 0x54, 0x9C, 0x2F, 0xC9, 0x54, 0x36, 0x08, 0xA9, 0x67, 0xEE, 0x91, 0xE6, 0xD9, 0xB1, 0xFA, 0xA9, 0x2B, 0x88, 0xAD, 0x2A, 0xD0, 0xAA, 0x28, 0xF9, + 0x47, 0xA6, 0x0F, 0xCF, 0x55, 0x4C, 0x9B, 0x26, 0x41, 0x89, 0x76, 0x11, 0xFD, 0x1B, 0x83, 0xE4, 0xE8, 0x8E, 0x7E, 0xB4, 0x03, 0xA3, 0x29, 0xDD, 0x4F, + 0xAC, 0x99, 0xBE, 0x7C, 0xD3, 0xFD, 0x14, 0x28, 0x1C, 0x59, 0x69, 0xE0, 0x79, 0x5F, 0x4B, 0xDA, 0x6B, 0xAB, 0x48, 0x4E, 0x28, 0x39, 0x84, 0xC6, 0x2B, + 0xC6, 0x20, 0x05, 0xDB, 0x05, 0x21, 0xC3, 0xE1, 0xD4, 0x20, 0x28, 0xDD, 0x3A, 0x4D, 0x51, 0xE7, 0x49, 0x8A, 0x49, 0xEF, 0xF5, 0xDA, 0xDA, 0x7D, 0x5D, + 0xA8, 0x0B, 0xA1, 0x77, 0xCD, 0x62, 0x7D, 0x9D, 0x40, 0x26, 0x44, 0x4B, 0x3B, 0x0A, 0x89, 0x02, 0x03, 0x01, 0x00, 0x01}; - static constexpr size_t AUTHED_CHUNK_SIZE = 0x2000; - static constexpr unsigned AUTHED_CHUNK_COUNT_PER_GROUP = 256; + static constexpr size_t AUTHED_CHUNK_SIZE = 0x2000; + static constexpr unsigned AUTHED_CHUNK_COUNT_PER_GROUP = 256; - static constexpr int OFFSET_BLOCK_BIT_COUNT = 4; - static constexpr block_t INSERT_BLOCK = XFILE_BLOCK_VIRTUAL; - }; -} + static constexpr int OFFSET_BLOCK_BIT_COUNT = 4; + static constexpr block_t INSERT_BLOCK = XFILE_BLOCK_VIRTUAL; +}; +} // namespace IW4 diff --git a/src/ZoneCommon/Game/IW5/GameAssetPoolIW5.cpp b/src/ZoneCommon/Game/IW5/GameAssetPoolIW5.cpp index 0c1761653..71dc2a6b2 100644 --- a/src/ZoneCommon/Game/IW5/GameAssetPoolIW5.cpp +++ b/src/ZoneCommon/Game/IW5/GameAssetPoolIW5.cpp @@ -3,60 +3,57 @@ #include <cassert> #include <type_traits> -#include "Pool/AssetPoolStatic.h" #include "Pool/AssetPoolDynamic.h" +#include "Pool/AssetPoolStatic.h" using namespace IW5; -const char* GameAssetPoolIW5::ASSET_TYPE_NAMES[] -{ - "physpreset", - "physcollmap", - "xanim", - "xmodelsurfs", - "xmodel", - "material", - "pixelshader", - "vertexshader", - "vertexdecl", - "techniqueset", - "image", - "sound", - "soundcurve", - "loadedsound", - "clipmap", - "comworld", - "glassworld", - "pathdata", - "vehicletrack", - "mapents", - "fxworld", - "gfxworld", - "lightdef", - "uimap", - "font", - "menulist", - "menu", - "localize", - "attachment", - "weapon", - "snddriverglobals", - "fx", - "impactfx", - "surfacefx", - "aitype", - "mptype", - "character", - "xmodelalias", - "rawfile", - "scriptfile", - "stringtable", - "leaderboard", - "structureddatadef", - "tracer", - "vehicle", - "addonmapents" -}; +const char *GameAssetPoolIW5::ASSET_TYPE_NAMES[]{"physpreset", + "physcollmap", + "xanim", + "xmodelsurfs", + "xmodel", + "material", + "pixelshader", + "vertexshader", + "vertexdecl", + "techniqueset", + "image", + "sound", + "soundcurve", + "loadedsound", + "clipmap", + "comworld", + "glassworld", + "pathdata", + "vehicletrack", + "mapents", + "fxworld", + "gfxworld", + "lightdef", + "uimap", + "font", + "menulist", + "menu", + "localize", + "attachment", + "weapon", + "snddriverglobals", + "fx", + "impactfx", + "surfacefx", + "aitype", + "mptype", + "character", + "xmodelalias", + "rawfile", + "scriptfile", + "stringtable", + "leaderboard", + "structureddatadef", + "tracer", + "vehicle", + "addonmapents"}; /* Asset Pool Table @@ -105,288 +102,262 @@ const char* GameAssetPoolIW5::ASSET_TYPE_NAMES[] ASSET_TYPE_ADDON_MAP_ENTS, AddonMapEnts, addonMapEnts, m_addon_map_ents */ -GameAssetPoolIW5::GameAssetPoolIW5(Zone* zone, const int priority) - : ZoneAssetPools(zone), - m_priority(priority) -{ - assert(std::extent<decltype(ASSET_TYPE_NAMES)>::value == ASSET_TYPE_COUNT); +GameAssetPoolIW5::GameAssetPoolIW5(Zone *zone, const int priority) : ZoneAssetPools(zone), m_priority(priority) { + assert(std::extent<decltype(ASSET_TYPE_NAMES)>::value == ASSET_TYPE_COUNT); } -void GameAssetPoolIW5::InitPoolStatic(const asset_type_t type, const size_t capacity) -{ -#define CASE_INIT_POOL_STATIC(assetType, poolName, poolType) \ - case assetType: \ - { \ - if((poolName) == nullptr && capacity > 0) \ - { \ - (poolName) = std::make_unique<AssetPoolStatic<poolType>>(capacity, m_priority, (assetType)); \ - } \ - break; \ - } - - switch (type) - { - CASE_INIT_POOL_STATIC(ASSET_TYPE_PHYSPRESET, m_phys_preset, PhysPreset); - CASE_INIT_POOL_STATIC(ASSET_TYPE_PHYSCOLLMAP, m_phys_collmap, PhysCollmap); - CASE_INIT_POOL_STATIC(ASSET_TYPE_XANIMPARTS, m_xanim_parts, XAnimParts); - CASE_INIT_POOL_STATIC(ASSET_TYPE_XMODEL_SURFS, m_xmodel_surfs, XModelSurfs); - CASE_INIT_POOL_STATIC(ASSET_TYPE_XMODEL, m_xmodel, XModel); - CASE_INIT_POOL_STATIC(ASSET_TYPE_MATERIAL, m_material, Material); - CASE_INIT_POOL_STATIC(ASSET_TYPE_PIXELSHADER, m_material_pixel_shader, MaterialPixelShader); - CASE_INIT_POOL_STATIC(ASSET_TYPE_VERTEXSHADER, m_material_vertex_shader, MaterialVertexShader); - CASE_INIT_POOL_STATIC(ASSET_TYPE_VERTEXDECL, m_material_vertex_decl, MaterialVertexDeclaration); - CASE_INIT_POOL_STATIC(ASSET_TYPE_TECHNIQUE_SET, m_technique_set, MaterialTechniqueSet); - CASE_INIT_POOL_STATIC(ASSET_TYPE_IMAGE, m_image, GfxImage); - CASE_INIT_POOL_STATIC(ASSET_TYPE_SOUND, m_sound, snd_alias_list_t); - CASE_INIT_POOL_STATIC(ASSET_TYPE_SOUND_CURVE, m_sound_curve, SndCurve); - CASE_INIT_POOL_STATIC(ASSET_TYPE_LOADED_SOUND, m_loaded_sound, LoadedSound); - CASE_INIT_POOL_STATIC(ASSET_TYPE_CLIPMAP, m_clip_map, clipMap_t); - CASE_INIT_POOL_STATIC(ASSET_TYPE_COMWORLD, m_com_world, ComWorld); - CASE_INIT_POOL_STATIC(ASSET_TYPE_GLASSWORLD, m_glass_world, GlassWorld); - CASE_INIT_POOL_STATIC(ASSET_TYPE_PATHDATA, m_path_data, PathData); - CASE_INIT_POOL_STATIC(ASSET_TYPE_VEHICLE_TRACK, m_vehicle_track, VehicleTrack); - CASE_INIT_POOL_STATIC(ASSET_TYPE_MAP_ENTS, m_map_ents, MapEnts); - CASE_INIT_POOL_STATIC(ASSET_TYPE_FXWORLD, m_fx_world, FxWorld); - CASE_INIT_POOL_STATIC(ASSET_TYPE_GFXWORLD, m_gfx_world, GfxWorld); - CASE_INIT_POOL_STATIC(ASSET_TYPE_LIGHT_DEF, m_gfx_light_def, GfxLightDef); - CASE_INIT_POOL_STATIC(ASSET_TYPE_FONT, m_font, Font_s); - CASE_INIT_POOL_STATIC(ASSET_TYPE_MENULIST, m_menu_list, MenuList); - CASE_INIT_POOL_STATIC(ASSET_TYPE_MENU, m_menu_def, menuDef_t); - CASE_INIT_POOL_STATIC(ASSET_TYPE_LOCALIZE_ENTRY, m_localize, LocalizeEntry); - CASE_INIT_POOL_STATIC(ASSET_TYPE_ATTACHMENT, m_attachment, WeaponAttachment); - CASE_INIT_POOL_STATIC(ASSET_TYPE_WEAPON, m_weapon, WeaponCompleteDef); - CASE_INIT_POOL_STATIC(ASSET_TYPE_FX, m_fx, FxEffectDef); - CASE_INIT_POOL_STATIC(ASSET_TYPE_IMPACT_FX, m_fx_impact_table, FxImpactTable); - CASE_INIT_POOL_STATIC(ASSET_TYPE_SURFACE_FX, m_surface_fx_table, SurfaceFxTable); - CASE_INIT_POOL_STATIC(ASSET_TYPE_RAWFILE, m_raw_file, RawFile); - CASE_INIT_POOL_STATIC(ASSET_TYPE_SCRIPTFILE, m_script_file, ScriptFile); - CASE_INIT_POOL_STATIC(ASSET_TYPE_STRINGTABLE, m_string_table, StringTable); - CASE_INIT_POOL_STATIC(ASSET_TYPE_LEADERBOARD, m_leaderboard, LeaderboardDef); - CASE_INIT_POOL_STATIC(ASSET_TYPE_STRUCTURED_DATA_DEF, m_structed_data_def_set, StructuredDataDefSet); - CASE_INIT_POOL_STATIC(ASSET_TYPE_TRACER, m_tracer, TracerDef); - CASE_INIT_POOL_STATIC(ASSET_TYPE_VEHICLE, m_vehicle, VehicleDef); - CASE_INIT_POOL_STATIC(ASSET_TYPE_ADDON_MAP_ENTS, m_addon_map_ents, AddonMapEnts); - - default: - assert(type >= 0 && type < ASSET_TYPE_COUNT); - break; - } +void GameAssetPoolIW5::InitPoolStatic(const asset_type_t type, const size_t capacity) { +#define CASE_INIT_POOL_STATIC(assetType, poolName, poolType) \ + case assetType: { \ + if ((poolName) == nullptr && capacity > 0) { \ + (poolName) = std::make_unique<AssetPoolStatic<poolType>>(capacity, m_priority, (assetType)); \ + } \ + break; \ + } + + switch (type) { + CASE_INIT_POOL_STATIC(ASSET_TYPE_PHYSPRESET, m_phys_preset, PhysPreset); + CASE_INIT_POOL_STATIC(ASSET_TYPE_PHYSCOLLMAP, m_phys_collmap, PhysCollmap); + CASE_INIT_POOL_STATIC(ASSET_TYPE_XANIMPARTS, m_xanim_parts, XAnimParts); + CASE_INIT_POOL_STATIC(ASSET_TYPE_XMODEL_SURFS, m_xmodel_surfs, XModelSurfs); + CASE_INIT_POOL_STATIC(ASSET_TYPE_XMODEL, m_xmodel, XModel); + CASE_INIT_POOL_STATIC(ASSET_TYPE_MATERIAL, m_material, Material); + CASE_INIT_POOL_STATIC(ASSET_TYPE_PIXELSHADER, m_material_pixel_shader, MaterialPixelShader); + CASE_INIT_POOL_STATIC(ASSET_TYPE_VERTEXSHADER, m_material_vertex_shader, MaterialVertexShader); + CASE_INIT_POOL_STATIC(ASSET_TYPE_VERTEXDECL, m_material_vertex_decl, MaterialVertexDeclaration); + CASE_INIT_POOL_STATIC(ASSET_TYPE_TECHNIQUE_SET, m_technique_set, MaterialTechniqueSet); + CASE_INIT_POOL_STATIC(ASSET_TYPE_IMAGE, m_image, GfxImage); + CASE_INIT_POOL_STATIC(ASSET_TYPE_SOUND, m_sound, snd_alias_list_t); + CASE_INIT_POOL_STATIC(ASSET_TYPE_SOUND_CURVE, m_sound_curve, SndCurve); + CASE_INIT_POOL_STATIC(ASSET_TYPE_LOADED_SOUND, m_loaded_sound, LoadedSound); + CASE_INIT_POOL_STATIC(ASSET_TYPE_CLIPMAP, m_clip_map, clipMap_t); + CASE_INIT_POOL_STATIC(ASSET_TYPE_COMWORLD, m_com_world, ComWorld); + CASE_INIT_POOL_STATIC(ASSET_TYPE_GLASSWORLD, m_glass_world, GlassWorld); + CASE_INIT_POOL_STATIC(ASSET_TYPE_PATHDATA, m_path_data, PathData); + CASE_INIT_POOL_STATIC(ASSET_TYPE_VEHICLE_TRACK, m_vehicle_track, VehicleTrack); + CASE_INIT_POOL_STATIC(ASSET_TYPE_MAP_ENTS, m_map_ents, MapEnts); + CASE_INIT_POOL_STATIC(ASSET_TYPE_FXWORLD, m_fx_world, FxWorld); + CASE_INIT_POOL_STATIC(ASSET_TYPE_GFXWORLD, m_gfx_world, GfxWorld); + CASE_INIT_POOL_STATIC(ASSET_TYPE_LIGHT_DEF, m_gfx_light_def, GfxLightDef); + CASE_INIT_POOL_STATIC(ASSET_TYPE_FONT, m_font, Font_s); + CASE_INIT_POOL_STATIC(ASSET_TYPE_MENULIST, m_menu_list, MenuList); + CASE_INIT_POOL_STATIC(ASSET_TYPE_MENU, m_menu_def, menuDef_t); + CASE_INIT_POOL_STATIC(ASSET_TYPE_LOCALIZE_ENTRY, m_localize, LocalizeEntry); + CASE_INIT_POOL_STATIC(ASSET_TYPE_ATTACHMENT, m_attachment, WeaponAttachment); + CASE_INIT_POOL_STATIC(ASSET_TYPE_WEAPON, m_weapon, WeaponCompleteDef); + CASE_INIT_POOL_STATIC(ASSET_TYPE_FX, m_fx, FxEffectDef); + CASE_INIT_POOL_STATIC(ASSET_TYPE_IMPACT_FX, m_fx_impact_table, FxImpactTable); + CASE_INIT_POOL_STATIC(ASSET_TYPE_SURFACE_FX, m_surface_fx_table, SurfaceFxTable); + CASE_INIT_POOL_STATIC(ASSET_TYPE_RAWFILE, m_raw_file, RawFile); + CASE_INIT_POOL_STATIC(ASSET_TYPE_SCRIPTFILE, m_script_file, ScriptFile); + CASE_INIT_POOL_STATIC(ASSET_TYPE_STRINGTABLE, m_string_table, StringTable); + CASE_INIT_POOL_STATIC(ASSET_TYPE_LEADERBOARD, m_leaderboard, LeaderboardDef); + CASE_INIT_POOL_STATIC(ASSET_TYPE_STRUCTURED_DATA_DEF, m_structed_data_def_set, StructuredDataDefSet); + CASE_INIT_POOL_STATIC(ASSET_TYPE_TRACER, m_tracer, TracerDef); + CASE_INIT_POOL_STATIC(ASSET_TYPE_VEHICLE, m_vehicle, VehicleDef); + CASE_INIT_POOL_STATIC(ASSET_TYPE_ADDON_MAP_ENTS, m_addon_map_ents, AddonMapEnts); + + default: + assert(type >= 0 && type < ASSET_TYPE_COUNT); + break; + } #undef CASE_INIT_POOL_STATIC } -void GameAssetPoolIW5::InitPoolDynamic(const asset_type_t type) -{ -#define CASE_INIT_POOL_DYNAMIC(assetType, poolName, poolType) \ - case assetType: \ - { \ - if((poolName) == nullptr) \ - { \ - (poolName) = std::make_unique<AssetPoolDynamic<poolType>>(m_priority, (assetType)); \ - } \ - break; \ - } - - switch (type) - { - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_PHYSPRESET, m_phys_preset, PhysPreset); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_PHYSCOLLMAP, m_phys_collmap, PhysCollmap); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_XANIMPARTS, m_xanim_parts, XAnimParts); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_XMODEL_SURFS, m_xmodel_surfs, XModelSurfs); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_XMODEL, m_xmodel, XModel); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_MATERIAL, m_material, Material); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_PIXELSHADER, m_material_pixel_shader, MaterialPixelShader); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_VERTEXSHADER, m_material_vertex_shader, MaterialVertexShader); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_VERTEXDECL, m_material_vertex_decl, MaterialVertexDeclaration); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_TECHNIQUE_SET, m_technique_set, MaterialTechniqueSet); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_IMAGE, m_image, GfxImage); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_SOUND, m_sound, snd_alias_list_t); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_SOUND_CURVE, m_sound_curve, SndCurve); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_LOADED_SOUND, m_loaded_sound, LoadedSound); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_CLIPMAP, m_clip_map, clipMap_t); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_COMWORLD, m_com_world, ComWorld); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_GLASSWORLD, m_glass_world, GlassWorld); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_PATHDATA, m_path_data, PathData); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_VEHICLE_TRACK, m_vehicle_track, VehicleTrack); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_MAP_ENTS, m_map_ents, MapEnts); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_FXWORLD, m_fx_world, FxWorld); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_GFXWORLD, m_gfx_world, GfxWorld); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_LIGHT_DEF, m_gfx_light_def, GfxLightDef); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_FONT, m_font, Font_s); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_MENULIST, m_menu_list, MenuList); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_MENU, m_menu_def, menuDef_t); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_LOCALIZE_ENTRY, m_localize, LocalizeEntry); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_ATTACHMENT, m_attachment, WeaponAttachment); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_WEAPON, m_weapon, WeaponCompleteDef); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_FX, m_fx, FxEffectDef); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_IMPACT_FX, m_fx_impact_table, FxImpactTable); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_SURFACE_FX, m_surface_fx_table, SurfaceFxTable); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_RAWFILE, m_raw_file, RawFile); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_SCRIPTFILE, m_script_file, ScriptFile); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_STRINGTABLE, m_string_table, StringTable); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_LEADERBOARD, m_leaderboard, LeaderboardDef); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_STRUCTURED_DATA_DEF, m_structed_data_def_set, StructuredDataDefSet); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_TRACER, m_tracer, TracerDef); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_VEHICLE, m_vehicle, VehicleDef); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_ADDON_MAP_ENTS, m_addon_map_ents, AddonMapEnts); - - default: - assert(type >= 0 && type < ASSET_TYPE_COUNT); - break; - } +void GameAssetPoolIW5::InitPoolDynamic(const asset_type_t type) { +#define CASE_INIT_POOL_DYNAMIC(assetType, poolName, poolType) \ + case assetType: { \ + if ((poolName) == nullptr) { \ + (poolName) = std::make_unique<AssetPoolDynamic<poolType>>(m_priority, (assetType)); \ + } \ + break; \ + } + + switch (type) { + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_PHYSPRESET, m_phys_preset, PhysPreset); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_PHYSCOLLMAP, m_phys_collmap, PhysCollmap); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_XANIMPARTS, m_xanim_parts, XAnimParts); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_XMODEL_SURFS, m_xmodel_surfs, XModelSurfs); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_XMODEL, m_xmodel, XModel); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_MATERIAL, m_material, Material); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_PIXELSHADER, m_material_pixel_shader, MaterialPixelShader); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_VERTEXSHADER, m_material_vertex_shader, MaterialVertexShader); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_VERTEXDECL, m_material_vertex_decl, MaterialVertexDeclaration); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_TECHNIQUE_SET, m_technique_set, MaterialTechniqueSet); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_IMAGE, m_image, GfxImage); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_SOUND, m_sound, snd_alias_list_t); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_SOUND_CURVE, m_sound_curve, SndCurve); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_LOADED_SOUND, m_loaded_sound, LoadedSound); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_CLIPMAP, m_clip_map, clipMap_t); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_COMWORLD, m_com_world, ComWorld); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_GLASSWORLD, m_glass_world, GlassWorld); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_PATHDATA, m_path_data, PathData); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_VEHICLE_TRACK, m_vehicle_track, VehicleTrack); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_MAP_ENTS, m_map_ents, MapEnts); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_FXWORLD, m_fx_world, FxWorld); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_GFXWORLD, m_gfx_world, GfxWorld); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_LIGHT_DEF, m_gfx_light_def, GfxLightDef); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_FONT, m_font, Font_s); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_MENULIST, m_menu_list, MenuList); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_MENU, m_menu_def, menuDef_t); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_LOCALIZE_ENTRY, m_localize, LocalizeEntry); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_ATTACHMENT, m_attachment, WeaponAttachment); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_WEAPON, m_weapon, WeaponCompleteDef); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_FX, m_fx, FxEffectDef); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_IMPACT_FX, m_fx_impact_table, FxImpactTable); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_SURFACE_FX, m_surface_fx_table, SurfaceFxTable); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_RAWFILE, m_raw_file, RawFile); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_SCRIPTFILE, m_script_file, ScriptFile); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_STRINGTABLE, m_string_table, StringTable); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_LEADERBOARD, m_leaderboard, LeaderboardDef); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_STRUCTURED_DATA_DEF, m_structed_data_def_set, StructuredDataDefSet); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_TRACER, m_tracer, TracerDef); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_VEHICLE, m_vehicle, VehicleDef); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_ADDON_MAP_ENTS, m_addon_map_ents, AddonMapEnts); + + default: + assert(type >= 0 && type < ASSET_TYPE_COUNT); + break; + } #undef CASE_INIT_POOL_STATIC } -XAssetInfoGeneric* GameAssetPoolIW5::AddAssetToPool(asset_type_t type, std::string name, void* asset, std::vector<XAssetInfoGeneric*> dependencies, std::vector<scr_string_t> usedScriptStrings, Zone* zone) -{ - XAsset xAsset{}; - - xAsset.type = static_cast<XAssetType>(type); - xAsset.header.data = asset; - -#define CASE_ADD_TO_POOL(assetType, poolName, headerName) \ - case assetType: \ - { \ - assert((poolName) != nullptr); \ - return (poolName)->AddAsset(std::move(name), xAsset.header.headerName, zone, std::move(dependencies), std::move(usedScriptStrings)); \ - } - - switch (xAsset.type) - { - CASE_ADD_TO_POOL(ASSET_TYPE_PHYSPRESET, m_phys_preset, physPreset); - CASE_ADD_TO_POOL(ASSET_TYPE_PHYSCOLLMAP, m_phys_collmap, physCollmap); - CASE_ADD_TO_POOL(ASSET_TYPE_XANIMPARTS, m_xanim_parts, parts); - CASE_ADD_TO_POOL(ASSET_TYPE_XMODEL_SURFS, m_xmodel_surfs, modelSurfs); - CASE_ADD_TO_POOL(ASSET_TYPE_XMODEL, m_xmodel, model); - CASE_ADD_TO_POOL(ASSET_TYPE_MATERIAL, m_material, material); - CASE_ADD_TO_POOL(ASSET_TYPE_PIXELSHADER, m_material_pixel_shader, pixelShader); - CASE_ADD_TO_POOL(ASSET_TYPE_VERTEXSHADER, m_material_vertex_shader, vertexShader); - CASE_ADD_TO_POOL(ASSET_TYPE_VERTEXDECL, m_material_vertex_decl, vertexDecl); - CASE_ADD_TO_POOL(ASSET_TYPE_TECHNIQUE_SET, m_technique_set, techniqueSet); - CASE_ADD_TO_POOL(ASSET_TYPE_IMAGE, m_image, image); - CASE_ADD_TO_POOL(ASSET_TYPE_SOUND, m_sound, sound); - CASE_ADD_TO_POOL(ASSET_TYPE_SOUND_CURVE, m_sound_curve, sndCurve); - CASE_ADD_TO_POOL(ASSET_TYPE_LOADED_SOUND, m_loaded_sound, loadSnd); - CASE_ADD_TO_POOL(ASSET_TYPE_CLIPMAP, m_clip_map, clipMap); - CASE_ADD_TO_POOL(ASSET_TYPE_COMWORLD, m_com_world, comWorld); - CASE_ADD_TO_POOL(ASSET_TYPE_GLASSWORLD, m_glass_world, glassWorld); - CASE_ADD_TO_POOL(ASSET_TYPE_PATHDATA, m_path_data, pathData); - CASE_ADD_TO_POOL(ASSET_TYPE_VEHICLE_TRACK, m_vehicle_track, vehicleTrack); - CASE_ADD_TO_POOL(ASSET_TYPE_MAP_ENTS, m_map_ents, mapEnts); - CASE_ADD_TO_POOL(ASSET_TYPE_FXWORLD, m_fx_world, fxWorld); - CASE_ADD_TO_POOL(ASSET_TYPE_GFXWORLD, m_gfx_world, gfxWorld); - CASE_ADD_TO_POOL(ASSET_TYPE_LIGHT_DEF, m_gfx_light_def, lightDef); - CASE_ADD_TO_POOL(ASSET_TYPE_FONT, m_font, font); - CASE_ADD_TO_POOL(ASSET_TYPE_MENULIST, m_menu_list, menuList); - CASE_ADD_TO_POOL(ASSET_TYPE_MENU, m_menu_def, menu); - CASE_ADD_TO_POOL(ASSET_TYPE_LOCALIZE_ENTRY, m_localize, localize); - CASE_ADD_TO_POOL(ASSET_TYPE_ATTACHMENT, m_attachment, attachment); - CASE_ADD_TO_POOL(ASSET_TYPE_WEAPON, m_weapon, weapon); - CASE_ADD_TO_POOL(ASSET_TYPE_FX, m_fx, fx); - CASE_ADD_TO_POOL(ASSET_TYPE_IMPACT_FX, m_fx_impact_table, impactFx); - CASE_ADD_TO_POOL(ASSET_TYPE_SURFACE_FX, m_surface_fx_table, surfaceFx); - CASE_ADD_TO_POOL(ASSET_TYPE_RAWFILE, m_raw_file, rawfile); - CASE_ADD_TO_POOL(ASSET_TYPE_SCRIPTFILE, m_script_file, scriptfile); - CASE_ADD_TO_POOL(ASSET_TYPE_STRINGTABLE, m_string_table, stringTable); - CASE_ADD_TO_POOL(ASSET_TYPE_LEADERBOARD, m_leaderboard, leaderboardDef); - CASE_ADD_TO_POOL(ASSET_TYPE_STRUCTURED_DATA_DEF, m_structed_data_def_set, structuredDataDefSet); - CASE_ADD_TO_POOL(ASSET_TYPE_TRACER, m_tracer, tracerDef); - CASE_ADD_TO_POOL(ASSET_TYPE_VEHICLE, m_vehicle, vehDef); - CASE_ADD_TO_POOL(ASSET_TYPE_ADDON_MAP_ENTS, m_addon_map_ents, addonMapEnts); - - default: - assert(false); - break; - } - - return nullptr; +XAssetInfoGeneric *GameAssetPoolIW5::AddAssetToPool(asset_type_t type, std::string name, void *asset, std::vector<XAssetInfoGeneric *> dependencies, + std::vector<scr_string_t> usedScriptStrings, Zone *zone) { + XAsset xAsset{}; + + xAsset.type = static_cast<XAssetType>(type); + xAsset.header.data = asset; + +#define CASE_ADD_TO_POOL(assetType, poolName, headerName) \ + case assetType: { \ + assert((poolName) != nullptr); \ + return (poolName)->AddAsset(std::move(name), xAsset.header.headerName, zone, std::move(dependencies), std::move(usedScriptStrings)); \ + } + + switch (xAsset.type) { + CASE_ADD_TO_POOL(ASSET_TYPE_PHYSPRESET, m_phys_preset, physPreset); + CASE_ADD_TO_POOL(ASSET_TYPE_PHYSCOLLMAP, m_phys_collmap, physCollmap); + CASE_ADD_TO_POOL(ASSET_TYPE_XANIMPARTS, m_xanim_parts, parts); + CASE_ADD_TO_POOL(ASSET_TYPE_XMODEL_SURFS, m_xmodel_surfs, modelSurfs); + CASE_ADD_TO_POOL(ASSET_TYPE_XMODEL, m_xmodel, model); + CASE_ADD_TO_POOL(ASSET_TYPE_MATERIAL, m_material, material); + CASE_ADD_TO_POOL(ASSET_TYPE_PIXELSHADER, m_material_pixel_shader, pixelShader); + CASE_ADD_TO_POOL(ASSET_TYPE_VERTEXSHADER, m_material_vertex_shader, vertexShader); + CASE_ADD_TO_POOL(ASSET_TYPE_VERTEXDECL, m_material_vertex_decl, vertexDecl); + CASE_ADD_TO_POOL(ASSET_TYPE_TECHNIQUE_SET, m_technique_set, techniqueSet); + CASE_ADD_TO_POOL(ASSET_TYPE_IMAGE, m_image, image); + CASE_ADD_TO_POOL(ASSET_TYPE_SOUND, m_sound, sound); + CASE_ADD_TO_POOL(ASSET_TYPE_SOUND_CURVE, m_sound_curve, sndCurve); + CASE_ADD_TO_POOL(ASSET_TYPE_LOADED_SOUND, m_loaded_sound, loadSnd); + CASE_ADD_TO_POOL(ASSET_TYPE_CLIPMAP, m_clip_map, clipMap); + CASE_ADD_TO_POOL(ASSET_TYPE_COMWORLD, m_com_world, comWorld); + CASE_ADD_TO_POOL(ASSET_TYPE_GLASSWORLD, m_glass_world, glassWorld); + CASE_ADD_TO_POOL(ASSET_TYPE_PATHDATA, m_path_data, pathData); + CASE_ADD_TO_POOL(ASSET_TYPE_VEHICLE_TRACK, m_vehicle_track, vehicleTrack); + CASE_ADD_TO_POOL(ASSET_TYPE_MAP_ENTS, m_map_ents, mapEnts); + CASE_ADD_TO_POOL(ASSET_TYPE_FXWORLD, m_fx_world, fxWorld); + CASE_ADD_TO_POOL(ASSET_TYPE_GFXWORLD, m_gfx_world, gfxWorld); + CASE_ADD_TO_POOL(ASSET_TYPE_LIGHT_DEF, m_gfx_light_def, lightDef); + CASE_ADD_TO_POOL(ASSET_TYPE_FONT, m_font, font); + CASE_ADD_TO_POOL(ASSET_TYPE_MENULIST, m_menu_list, menuList); + CASE_ADD_TO_POOL(ASSET_TYPE_MENU, m_menu_def, menu); + CASE_ADD_TO_POOL(ASSET_TYPE_LOCALIZE_ENTRY, m_localize, localize); + CASE_ADD_TO_POOL(ASSET_TYPE_ATTACHMENT, m_attachment, attachment); + CASE_ADD_TO_POOL(ASSET_TYPE_WEAPON, m_weapon, weapon); + CASE_ADD_TO_POOL(ASSET_TYPE_FX, m_fx, fx); + CASE_ADD_TO_POOL(ASSET_TYPE_IMPACT_FX, m_fx_impact_table, impactFx); + CASE_ADD_TO_POOL(ASSET_TYPE_SURFACE_FX, m_surface_fx_table, surfaceFx); + CASE_ADD_TO_POOL(ASSET_TYPE_RAWFILE, m_raw_file, rawfile); + CASE_ADD_TO_POOL(ASSET_TYPE_SCRIPTFILE, m_script_file, scriptfile); + CASE_ADD_TO_POOL(ASSET_TYPE_STRINGTABLE, m_string_table, stringTable); + CASE_ADD_TO_POOL(ASSET_TYPE_LEADERBOARD, m_leaderboard, leaderboardDef); + CASE_ADD_TO_POOL(ASSET_TYPE_STRUCTURED_DATA_DEF, m_structed_data_def_set, structuredDataDefSet); + CASE_ADD_TO_POOL(ASSET_TYPE_TRACER, m_tracer, tracerDef); + CASE_ADD_TO_POOL(ASSET_TYPE_VEHICLE, m_vehicle, vehDef); + CASE_ADD_TO_POOL(ASSET_TYPE_ADDON_MAP_ENTS, m_addon_map_ents, addonMapEnts); + + default: + assert(false); + break; + } + + return nullptr; #undef CASE_ADD_TO_POOL } -XAssetInfoGeneric* GameAssetPoolIW5::GetAsset(const asset_type_t type, std::string name) const -{ -#define CASE_GET_ASSET(assetType, poolName) \ - case assetType: \ - { \ - if((poolName) != nullptr) \ - return (poolName)->GetAsset(std::move(name)); \ - break; \ - } - - switch (type) - { - CASE_GET_ASSET(ASSET_TYPE_PHYSPRESET, m_phys_preset); - CASE_GET_ASSET(ASSET_TYPE_PHYSCOLLMAP, m_phys_collmap); - CASE_GET_ASSET(ASSET_TYPE_XANIMPARTS, m_xanim_parts); - CASE_GET_ASSET(ASSET_TYPE_XMODEL_SURFS, m_xmodel_surfs); - CASE_GET_ASSET(ASSET_TYPE_XMODEL, m_xmodel); - CASE_GET_ASSET(ASSET_TYPE_MATERIAL, m_material); - CASE_GET_ASSET(ASSET_TYPE_PIXELSHADER, m_material_pixel_shader); - CASE_GET_ASSET(ASSET_TYPE_VERTEXSHADER, m_material_vertex_shader); - CASE_GET_ASSET(ASSET_TYPE_VERTEXDECL, m_material_vertex_decl); - CASE_GET_ASSET(ASSET_TYPE_TECHNIQUE_SET, m_technique_set); - CASE_GET_ASSET(ASSET_TYPE_IMAGE, m_image); - CASE_GET_ASSET(ASSET_TYPE_SOUND, m_sound); - CASE_GET_ASSET(ASSET_TYPE_SOUND_CURVE, m_sound_curve); - CASE_GET_ASSET(ASSET_TYPE_LOADED_SOUND, m_loaded_sound); - CASE_GET_ASSET(ASSET_TYPE_CLIPMAP, m_clip_map); - CASE_GET_ASSET(ASSET_TYPE_COMWORLD, m_com_world); - CASE_GET_ASSET(ASSET_TYPE_GLASSWORLD, m_glass_world); - CASE_GET_ASSET(ASSET_TYPE_PATHDATA, m_path_data); - CASE_GET_ASSET(ASSET_TYPE_VEHICLE_TRACK, m_vehicle_track); - CASE_GET_ASSET(ASSET_TYPE_MAP_ENTS, m_map_ents); - CASE_GET_ASSET(ASSET_TYPE_FXWORLD, m_fx_world); - CASE_GET_ASSET(ASSET_TYPE_GFXWORLD, m_gfx_world); - CASE_GET_ASSET(ASSET_TYPE_LIGHT_DEF, m_gfx_light_def); - CASE_GET_ASSET(ASSET_TYPE_FONT, m_font); - CASE_GET_ASSET(ASSET_TYPE_MENULIST, m_menu_list); - CASE_GET_ASSET(ASSET_TYPE_MENU, m_menu_def); - CASE_GET_ASSET(ASSET_TYPE_LOCALIZE_ENTRY, m_localize); - CASE_GET_ASSET(ASSET_TYPE_ATTACHMENT, m_attachment); - CASE_GET_ASSET(ASSET_TYPE_WEAPON, m_weapon); - CASE_GET_ASSET(ASSET_TYPE_FX, m_fx); - CASE_GET_ASSET(ASSET_TYPE_IMPACT_FX, m_fx_impact_table); - CASE_GET_ASSET(ASSET_TYPE_SURFACE_FX, m_surface_fx_table); - CASE_GET_ASSET(ASSET_TYPE_RAWFILE, m_raw_file); - CASE_GET_ASSET(ASSET_TYPE_SCRIPTFILE, m_script_file); - CASE_GET_ASSET(ASSET_TYPE_STRINGTABLE, m_string_table); - CASE_GET_ASSET(ASSET_TYPE_LEADERBOARD, m_leaderboard); - CASE_GET_ASSET(ASSET_TYPE_STRUCTURED_DATA_DEF, m_structed_data_def_set); - CASE_GET_ASSET(ASSET_TYPE_TRACER, m_tracer); - CASE_GET_ASSET(ASSET_TYPE_VEHICLE, m_vehicle); - CASE_GET_ASSET(ASSET_TYPE_ADDON_MAP_ENTS, m_addon_map_ents); - - default: - assert(false); - break; - } - - return nullptr; +XAssetInfoGeneric *GameAssetPoolIW5::GetAsset(const asset_type_t type, std::string name) const { +#define CASE_GET_ASSET(assetType, poolName) \ + case assetType: { \ + if ((poolName) != nullptr) \ + return (poolName)->GetAsset(std::move(name)); \ + break; \ + } + + switch (type) { + CASE_GET_ASSET(ASSET_TYPE_PHYSPRESET, m_phys_preset); + CASE_GET_ASSET(ASSET_TYPE_PHYSCOLLMAP, m_phys_collmap); + CASE_GET_ASSET(ASSET_TYPE_XANIMPARTS, m_xanim_parts); + CASE_GET_ASSET(ASSET_TYPE_XMODEL_SURFS, m_xmodel_surfs); + CASE_GET_ASSET(ASSET_TYPE_XMODEL, m_xmodel); + CASE_GET_ASSET(ASSET_TYPE_MATERIAL, m_material); + CASE_GET_ASSET(ASSET_TYPE_PIXELSHADER, m_material_pixel_shader); + CASE_GET_ASSET(ASSET_TYPE_VERTEXSHADER, m_material_vertex_shader); + CASE_GET_ASSET(ASSET_TYPE_VERTEXDECL, m_material_vertex_decl); + CASE_GET_ASSET(ASSET_TYPE_TECHNIQUE_SET, m_technique_set); + CASE_GET_ASSET(ASSET_TYPE_IMAGE, m_image); + CASE_GET_ASSET(ASSET_TYPE_SOUND, m_sound); + CASE_GET_ASSET(ASSET_TYPE_SOUND_CURVE, m_sound_curve); + CASE_GET_ASSET(ASSET_TYPE_LOADED_SOUND, m_loaded_sound); + CASE_GET_ASSET(ASSET_TYPE_CLIPMAP, m_clip_map); + CASE_GET_ASSET(ASSET_TYPE_COMWORLD, m_com_world); + CASE_GET_ASSET(ASSET_TYPE_GLASSWORLD, m_glass_world); + CASE_GET_ASSET(ASSET_TYPE_PATHDATA, m_path_data); + CASE_GET_ASSET(ASSET_TYPE_VEHICLE_TRACK, m_vehicle_track); + CASE_GET_ASSET(ASSET_TYPE_MAP_ENTS, m_map_ents); + CASE_GET_ASSET(ASSET_TYPE_FXWORLD, m_fx_world); + CASE_GET_ASSET(ASSET_TYPE_GFXWORLD, m_gfx_world); + CASE_GET_ASSET(ASSET_TYPE_LIGHT_DEF, m_gfx_light_def); + CASE_GET_ASSET(ASSET_TYPE_FONT, m_font); + CASE_GET_ASSET(ASSET_TYPE_MENULIST, m_menu_list); + CASE_GET_ASSET(ASSET_TYPE_MENU, m_menu_def); + CASE_GET_ASSET(ASSET_TYPE_LOCALIZE_ENTRY, m_localize); + CASE_GET_ASSET(ASSET_TYPE_ATTACHMENT, m_attachment); + CASE_GET_ASSET(ASSET_TYPE_WEAPON, m_weapon); + CASE_GET_ASSET(ASSET_TYPE_FX, m_fx); + CASE_GET_ASSET(ASSET_TYPE_IMPACT_FX, m_fx_impact_table); + CASE_GET_ASSET(ASSET_TYPE_SURFACE_FX, m_surface_fx_table); + CASE_GET_ASSET(ASSET_TYPE_RAWFILE, m_raw_file); + CASE_GET_ASSET(ASSET_TYPE_SCRIPTFILE, m_script_file); + CASE_GET_ASSET(ASSET_TYPE_STRINGTABLE, m_string_table); + CASE_GET_ASSET(ASSET_TYPE_LEADERBOARD, m_leaderboard); + CASE_GET_ASSET(ASSET_TYPE_STRUCTURED_DATA_DEF, m_structed_data_def_set); + CASE_GET_ASSET(ASSET_TYPE_TRACER, m_tracer); + CASE_GET_ASSET(ASSET_TYPE_VEHICLE, m_vehicle); + CASE_GET_ASSET(ASSET_TYPE_ADDON_MAP_ENTS, m_addon_map_ents); + + default: + assert(false); + break; + } + + return nullptr; #undef CASE_GET_ASSET } -const char* GameAssetPoolIW5::AssetTypeNameByType(asset_type_t assetType) -{ - if (assetType >= 0 && assetType < static_cast<int>(std::extent<decltype(ASSET_TYPE_NAMES)>::value)) - return ASSET_TYPE_NAMES[assetType]; +const char *GameAssetPoolIW5::AssetTypeNameByType(asset_type_t assetType) { + if (assetType >= 0 && assetType < static_cast<int>(std::extent<decltype(ASSET_TYPE_NAMES)>::value)) + return ASSET_TYPE_NAMES[assetType]; - return ASSET_TYPE_INVALID; + return ASSET_TYPE_INVALID; } -const char* GameAssetPoolIW5::GetAssetTypeName(const asset_type_t assetType) const -{ - return AssetTypeNameByType(assetType); -} +const char *GameAssetPoolIW5::GetAssetTypeName(const asset_type_t assetType) const { return AssetTypeNameByType(assetType); } -asset_type_t GameAssetPoolIW5::AssetTypeCount() -{ - return ASSET_TYPE_COUNT; -} +asset_type_t GameAssetPoolIW5::AssetTypeCount() { return ASSET_TYPE_COUNT; } -asset_type_t GameAssetPoolIW5::GetAssetTypeCount() const -{ - return AssetTypeCount(); -} +asset_type_t GameAssetPoolIW5::GetAssetTypeCount() const { return AssetTypeCount(); } diff --git a/src/ZoneCommon/Game/IW5/GameAssetPoolIW5.h b/src/ZoneCommon/Game/IW5/GameAssetPoolIW5.h index a9d03a7a5..ad98510ef 100644 --- a/src/ZoneCommon/Game/IW5/GameAssetPoolIW5.h +++ b/src/ZoneCommon/Game/IW5/GameAssetPoolIW5.h @@ -2,73 +2,73 @@ #include <memory> -#include "Pool/ZoneAssetPools.h" -#include "Pool/AssetPool.h" #include "Game/IW5/IW5.h" +#include "Pool/AssetPool.h" +#include "Pool/ZoneAssetPools.h" -class GameAssetPoolIW5 final : public ZoneAssetPools -{ - int m_priority; +class GameAssetPoolIW5 final : public ZoneAssetPools { + int m_priority; - static constexpr const char* ASSET_TYPE_INVALID = "invalid_asset_type"; - static const char* ASSET_TYPE_NAMES[]; + static constexpr const char *ASSET_TYPE_INVALID = "invalid_asset_type"; + static const char *ASSET_TYPE_NAMES[]; protected: - XAssetInfoGeneric* AddAssetToPool(asset_type_t type, std::string name, void* asset, std::vector<XAssetInfoGeneric*> dependencies, std::vector<scr_string_t> usedScriptStrings, Zone* zone) override; + XAssetInfoGeneric *AddAssetToPool(asset_type_t type, std::string name, void *asset, std::vector<XAssetInfoGeneric *> dependencies, + std::vector<scr_string_t> usedScriptStrings, Zone *zone) override; public: - std::unique_ptr<AssetPool<IW5::PhysPreset>> m_phys_preset; - std::unique_ptr<AssetPool<IW5::PhysCollmap>> m_phys_collmap; - std::unique_ptr<AssetPool<IW5::XAnimParts>> m_xanim_parts; - std::unique_ptr<AssetPool<IW5::XModelSurfs>> m_xmodel_surfs; - std::unique_ptr<AssetPool<IW5::XModel>> m_xmodel; - std::unique_ptr<AssetPool<IW5::Material>> m_material; - std::unique_ptr<AssetPool<IW5::MaterialPixelShader>> m_material_pixel_shader; - std::unique_ptr<AssetPool<IW5::MaterialVertexShader>> m_material_vertex_shader; - std::unique_ptr<AssetPool<IW5::MaterialVertexDeclaration>> m_material_vertex_decl; - std::unique_ptr<AssetPool<IW5::MaterialTechniqueSet>> m_technique_set; - std::unique_ptr<AssetPool<IW5::GfxImage>> m_image; - std::unique_ptr<AssetPool<IW5::snd_alias_list_t>> m_sound; - std::unique_ptr<AssetPool<IW5::SndCurve>> m_sound_curve; - std::unique_ptr<AssetPool<IW5::LoadedSound>> m_loaded_sound; - std::unique_ptr<AssetPool<IW5::clipMap_t>> m_clip_map; - std::unique_ptr<AssetPool<IW5::ComWorld>> m_com_world; - std::unique_ptr<AssetPool<IW5::GlassWorld>> m_glass_world; - std::unique_ptr<AssetPool<IW5::PathData>> m_path_data; - std::unique_ptr<AssetPool<IW5::VehicleTrack>> m_vehicle_track; - std::unique_ptr<AssetPool<IW5::MapEnts>> m_map_ents; - std::unique_ptr<AssetPool<IW5::FxWorld>> m_fx_world; - std::unique_ptr<AssetPool<IW5::GfxWorld>> m_gfx_world; - std::unique_ptr<AssetPool<IW5::GfxLightDef>> m_gfx_light_def; - std::unique_ptr<AssetPool<IW5::Font_s>> m_font; - std::unique_ptr<AssetPool<IW5::MenuList>> m_menu_list; - std::unique_ptr<AssetPool<IW5::menuDef_t>> m_menu_def; - std::unique_ptr<AssetPool<IW5::LocalizeEntry>> m_localize; - std::unique_ptr<AssetPool<IW5::WeaponAttachment>> m_attachment; - std::unique_ptr<AssetPool<IW5::WeaponCompleteDef>> m_weapon; - std::unique_ptr<AssetPool<IW5::FxEffectDef>> m_fx; - std::unique_ptr<AssetPool<IW5::FxImpactTable>> m_fx_impact_table; - std::unique_ptr<AssetPool<IW5::SurfaceFxTable>> m_surface_fx_table; - std::unique_ptr<AssetPool<IW5::RawFile>> m_raw_file; - std::unique_ptr<AssetPool<IW5::ScriptFile>> m_script_file; - std::unique_ptr<AssetPool<IW5::StringTable>> m_string_table; - std::unique_ptr<AssetPool<IW5::LeaderboardDef>> m_leaderboard; - std::unique_ptr<AssetPool<IW5::StructuredDataDefSet>> m_structed_data_def_set; - std::unique_ptr<AssetPool<IW5::TracerDef>> m_tracer; - std::unique_ptr<AssetPool<IW5::VehicleDef>> m_vehicle; - std::unique_ptr<AssetPool<IW5::AddonMapEnts>> m_addon_map_ents; + std::unique_ptr<AssetPool<IW5::PhysPreset>> m_phys_preset; + std::unique_ptr<AssetPool<IW5::PhysCollmap>> m_phys_collmap; + std::unique_ptr<AssetPool<IW5::XAnimParts>> m_xanim_parts; + std::unique_ptr<AssetPool<IW5::XModelSurfs>> m_xmodel_surfs; + std::unique_ptr<AssetPool<IW5::XModel>> m_xmodel; + std::unique_ptr<AssetPool<IW5::Material>> m_material; + std::unique_ptr<AssetPool<IW5::MaterialPixelShader>> m_material_pixel_shader; + std::unique_ptr<AssetPool<IW5::MaterialVertexShader>> m_material_vertex_shader; + std::unique_ptr<AssetPool<IW5::MaterialVertexDeclaration>> m_material_vertex_decl; + std::unique_ptr<AssetPool<IW5::MaterialTechniqueSet>> m_technique_set; + std::unique_ptr<AssetPool<IW5::GfxImage>> m_image; + std::unique_ptr<AssetPool<IW5::snd_alias_list_t>> m_sound; + std::unique_ptr<AssetPool<IW5::SndCurve>> m_sound_curve; + std::unique_ptr<AssetPool<IW5::LoadedSound>> m_loaded_sound; + std::unique_ptr<AssetPool<IW5::clipMap_t>> m_clip_map; + std::unique_ptr<AssetPool<IW5::ComWorld>> m_com_world; + std::unique_ptr<AssetPool<IW5::GlassWorld>> m_glass_world; + std::unique_ptr<AssetPool<IW5::PathData>> m_path_data; + std::unique_ptr<AssetPool<IW5::VehicleTrack>> m_vehicle_track; + std::unique_ptr<AssetPool<IW5::MapEnts>> m_map_ents; + std::unique_ptr<AssetPool<IW5::FxWorld>> m_fx_world; + std::unique_ptr<AssetPool<IW5::GfxWorld>> m_gfx_world; + std::unique_ptr<AssetPool<IW5::GfxLightDef>> m_gfx_light_def; + std::unique_ptr<AssetPool<IW5::Font_s>> m_font; + std::unique_ptr<AssetPool<IW5::MenuList>> m_menu_list; + std::unique_ptr<AssetPool<IW5::menuDef_t>> m_menu_def; + std::unique_ptr<AssetPool<IW5::LocalizeEntry>> m_localize; + std::unique_ptr<AssetPool<IW5::WeaponAttachment>> m_attachment; + std::unique_ptr<AssetPool<IW5::WeaponCompleteDef>> m_weapon; + std::unique_ptr<AssetPool<IW5::FxEffectDef>> m_fx; + std::unique_ptr<AssetPool<IW5::FxImpactTable>> m_fx_impact_table; + std::unique_ptr<AssetPool<IW5::SurfaceFxTable>> m_surface_fx_table; + std::unique_ptr<AssetPool<IW5::RawFile>> m_raw_file; + std::unique_ptr<AssetPool<IW5::ScriptFile>> m_script_file; + std::unique_ptr<AssetPool<IW5::StringTable>> m_string_table; + std::unique_ptr<AssetPool<IW5::LeaderboardDef>> m_leaderboard; + std::unique_ptr<AssetPool<IW5::StructuredDataDefSet>> m_structed_data_def_set; + std::unique_ptr<AssetPool<IW5::TracerDef>> m_tracer; + std::unique_ptr<AssetPool<IW5::VehicleDef>> m_vehicle; + std::unique_ptr<AssetPool<IW5::AddonMapEnts>> m_addon_map_ents; - GameAssetPoolIW5(Zone* zone, int priority); - ~GameAssetPoolIW5() override = default; + GameAssetPoolIW5(Zone *zone, int priority); + ~GameAssetPoolIW5() override = default; - void InitPoolStatic(asset_type_t type, size_t capacity) override; - void InitPoolDynamic(asset_type_t type) override; + void InitPoolStatic(asset_type_t type, size_t capacity) override; + void InitPoolDynamic(asset_type_t type) override; - _NODISCARD XAssetInfoGeneric* GetAsset(asset_type_t type, std::string name) const override; + _NODISCARD XAssetInfoGeneric *GetAsset(asset_type_t type, std::string name) const override; - static const char* AssetTypeNameByType(asset_type_t assetType); - _NODISCARD const char* GetAssetTypeName(asset_type_t assetType) const override; + static const char *AssetTypeNameByType(asset_type_t assetType); + _NODISCARD const char *GetAssetTypeName(asset_type_t assetType) const override; - static asset_type_t AssetTypeCount(); - _NODISCARD asset_type_t GetAssetTypeCount() const override; + static asset_type_t AssetTypeCount(); + _NODISCARD asset_type_t GetAssetTypeCount() const override; }; diff --git a/src/ZoneCommon/Game/IW5/ZoneConstantsIW5.h b/src/ZoneCommon/Game/IW5/ZoneConstantsIW5.h index a62fe2c53..fd32ff9d2 100644 --- a/src/ZoneCommon/Game/IW5/ZoneConstantsIW5.h +++ b/src/ZoneCommon/Game/IW5/ZoneConstantsIW5.h @@ -2,68 +2,41 @@ #include <cstdint> #include <string> -#include "Zone/ZoneTypes.h" #include "Game/IW5/IW5.h" +#include "Zone/ZoneTypes.h" -namespace IW5 -{ - class ZoneConstants final - { - ZoneConstants() = default; +namespace IW5 { +class ZoneConstants final { + ZoneConstants() = default; - public: - static constexpr const char* MAGIC_SIGNED_INFINITY_WARD = "IWff0100"; - static constexpr const char* MAGIC_SIGNED_OAT = "ABff0100"; - static constexpr const char* MAGIC_UNSIGNED = "IWffu100"; - static constexpr int ZONE_VERSION = 1; +public: + static constexpr const char *MAGIC_SIGNED_INFINITY_WARD = "IWff0100"; + static constexpr const char *MAGIC_SIGNED_OAT = "ABff0100"; + static constexpr const char *MAGIC_UNSIGNED = "IWffu100"; + static constexpr int ZONE_VERSION = 1; - static_assert(std::char_traits<char>::length(MAGIC_SIGNED_INFINITY_WARD) == sizeof(ZoneHeader::m_magic)); - static_assert(std::char_traits<char>::length(MAGIC_SIGNED_OAT) == sizeof(ZoneHeader::m_magic)); - static_assert(std::char_traits<char>::length(MAGIC_UNSIGNED) == sizeof(ZoneHeader::m_magic)); + static_assert(std::char_traits<char>::length(MAGIC_SIGNED_INFINITY_WARD) == sizeof(ZoneHeader::m_magic)); + static_assert(std::char_traits<char>::length(MAGIC_SIGNED_OAT) == sizeof(ZoneHeader::m_magic)); + static_assert(std::char_traits<char>::length(MAGIC_UNSIGNED) == sizeof(ZoneHeader::m_magic)); - static constexpr const char* MAGIC_AUTH_HEADER = "IWffs100"; - inline static const uint8_t RSA_PUBLIC_KEY_INFINITY_WARD[] - { - 0x30, 0x82, 0x01, 0x0A, 0x02, 0x82, 0x01, 0x01, - 0x00, 0xA5, 0x86, 0xCC, 0x18, 0xA9, 0x12, 0x17, - 0x4F, 0x3A, 0xC9, 0x0C, 0xD2, 0x38, 0x5D, 0xDB, - 0x67, 0x62, 0xA4, 0xE3, 0xD4, 0x42, 0x05, 0x8A, - 0x57, 0x0C, 0x31, 0x4E, 0x19, 0xE4, 0xBA, 0x89, - 0x73, 0x13, 0xDB, 0x72, 0x25, 0x63, 0xB1, 0x2F, - 0xD7, 0xF1, 0x08, 0x48, 0x34, 0x06, 0xD7, 0x84, - 0x5F, 0xC8, 0xCF, 0x2F, 0xB6, 0xA3, 0x5A, 0x8F, - 0x7E, 0xAA, 0x9D, 0x51, 0xE7, 0x0F, 0xB9, 0x07, - 0xB7, 0x30, 0x91, 0x04, 0x39, 0x9C, 0xDC, 0x1C, - 0xF1, 0x16, 0xCB, 0x96, 0x10, 0xEB, 0x38, 0xB1, - 0x3B, 0xBA, 0x42, 0xE3, 0xE2, 0x78, 0xBD, 0x77, - 0x82, 0x1A, 0x2B, 0x54, 0x27, 0x0A, 0xF7, 0x66, - 0x06, 0xAD, 0x46, 0x39, 0xC0, 0xEB, 0xB5, 0xC2, - 0x27, 0xDD, 0x2C, 0x08, 0x62, 0x2C, 0x0B, 0xC4, - 0x00, 0x0D, 0xCB, 0xAD, 0x22, 0x67, 0x01, 0xA6, - 0x92, 0x9C, 0x00, 0xAF, 0x9D, 0x55, 0xCC, 0x68, - 0xEC, 0x39, 0x49, 0x85, 0x7E, 0x2C, 0x98, 0xCF, - 0x4C, 0x12, 0x8D, 0xED, 0xC7, 0x1D, 0x21, 0x54, - 0x9C, 0x2F, 0xC9, 0x54, 0x36, 0x08, 0xA9, 0x67, - 0xEE, 0x91, 0xE6, 0xD9, 0xB1, 0xFA, 0xA9, 0x2B, - 0x88, 0xAD, 0x2A, 0xD0, 0xAA, 0x28, 0xF9, 0x47, - 0xA6, 0x0F, 0xCF, 0x55, 0x4C, 0x9B, 0x26, 0x41, - 0x89, 0x76, 0x11, 0xFD, 0x1B, 0x83, 0xE4, 0xE8, - 0x8E, 0x7E, 0xB4, 0x03, 0xA3, 0x29, 0xDD, 0x4F, - 0xAC, 0x99, 0xBE, 0x7C, 0xD3, 0xFD, 0x14, 0x28, - 0x1C, 0x59, 0x69, 0xE0, 0x79, 0x5F, 0x4B, 0xDA, - 0x6B, 0xAB, 0x48, 0x4E, 0x28, 0x39, 0x84, 0xC6, - 0x2B, 0xC6, 0x20, 0x05, 0xDB, 0x05, 0x21, 0xC3, - 0xE1, 0xD4, 0x20, 0x28, 0xDD, 0x3A, 0x4D, 0x51, - 0xE7, 0x49, 0x8A, 0x49, 0xEF, 0xF5, 0xDA, 0xDA, - 0x7D, 0x5D, 0xA8, 0x0B, 0xA1, 0x77, 0xCD, 0x62, - 0x7D, 0x9D, 0x40, 0x26, 0x44, 0x4B, 0x3B, 0x0A, - 0x89, 0x02, 0x03, 0x01, 0x00, 0x01 - }; + static constexpr const char *MAGIC_AUTH_HEADER = "IWffs100"; + inline static const uint8_t RSA_PUBLIC_KEY_INFINITY_WARD[]{ + 0x30, 0x82, 0x01, 0x0A, 0x02, 0x82, 0x01, 0x01, 0x00, 0xA5, 0x86, 0xCC, 0x18, 0xA9, 0x12, 0x17, 0x4F, 0x3A, 0xC9, 0x0C, 0xD2, 0x38, 0x5D, 0xDB, 0x67, + 0x62, 0xA4, 0xE3, 0xD4, 0x42, 0x05, 0x8A, 0x57, 0x0C, 0x31, 0x4E, 0x19, 0xE4, 0xBA, 0x89, 0x73, 0x13, 0xDB, 0x72, 0x25, 0x63, 0xB1, 0x2F, 0xD7, 0xF1, + 0x08, 0x48, 0x34, 0x06, 0xD7, 0x84, 0x5F, 0xC8, 0xCF, 0x2F, 0xB6, 0xA3, 0x5A, 0x8F, 0x7E, 0xAA, 0x9D, 0x51, 0xE7, 0x0F, 0xB9, 0x07, 0xB7, 0x30, 0x91, + 0x04, 0x39, 0x9C, 0xDC, 0x1C, 0xF1, 0x16, 0xCB, 0x96, 0x10, 0xEB, 0x38, 0xB1, 0x3B, 0xBA, 0x42, 0xE3, 0xE2, 0x78, 0xBD, 0x77, 0x82, 0x1A, 0x2B, 0x54, + 0x27, 0x0A, 0xF7, 0x66, 0x06, 0xAD, 0x46, 0x39, 0xC0, 0xEB, 0xB5, 0xC2, 0x27, 0xDD, 0x2C, 0x08, 0x62, 0x2C, 0x0B, 0xC4, 0x00, 0x0D, 0xCB, 0xAD, 0x22, + 0x67, 0x01, 0xA6, 0x92, 0x9C, 0x00, 0xAF, 0x9D, 0x55, 0xCC, 0x68, 0xEC, 0x39, 0x49, 0x85, 0x7E, 0x2C, 0x98, 0xCF, 0x4C, 0x12, 0x8D, 0xED, 0xC7, 0x1D, + 0x21, 0x54, 0x9C, 0x2F, 0xC9, 0x54, 0x36, 0x08, 0xA9, 0x67, 0xEE, 0x91, 0xE6, 0xD9, 0xB1, 0xFA, 0xA9, 0x2B, 0x88, 0xAD, 0x2A, 0xD0, 0xAA, 0x28, 0xF9, + 0x47, 0xA6, 0x0F, 0xCF, 0x55, 0x4C, 0x9B, 0x26, 0x41, 0x89, 0x76, 0x11, 0xFD, 0x1B, 0x83, 0xE4, 0xE8, 0x8E, 0x7E, 0xB4, 0x03, 0xA3, 0x29, 0xDD, 0x4F, + 0xAC, 0x99, 0xBE, 0x7C, 0xD3, 0xFD, 0x14, 0x28, 0x1C, 0x59, 0x69, 0xE0, 0x79, 0x5F, 0x4B, 0xDA, 0x6B, 0xAB, 0x48, 0x4E, 0x28, 0x39, 0x84, 0xC6, 0x2B, + 0xC6, 0x20, 0x05, 0xDB, 0x05, 0x21, 0xC3, 0xE1, 0xD4, 0x20, 0x28, 0xDD, 0x3A, 0x4D, 0x51, 0xE7, 0x49, 0x8A, 0x49, 0xEF, 0xF5, 0xDA, 0xDA, 0x7D, 0x5D, + 0xA8, 0x0B, 0xA1, 0x77, 0xCD, 0x62, 0x7D, 0x9D, 0x40, 0x26, 0x44, 0x4B, 0x3B, 0x0A, 0x89, 0x02, 0x03, 0x01, 0x00, 0x01}; - static constexpr size_t AUTHED_CHUNK_SIZE = 0x2000; - static constexpr unsigned AUTHED_CHUNK_COUNT_PER_GROUP = 256; + static constexpr size_t AUTHED_CHUNK_SIZE = 0x2000; + static constexpr unsigned AUTHED_CHUNK_COUNT_PER_GROUP = 256; - static constexpr int OFFSET_BLOCK_BIT_COUNT = 4; - static constexpr block_t INSERT_BLOCK = XFILE_BLOCK_VIRTUAL; - }; -} + static constexpr int OFFSET_BLOCK_BIT_COUNT = 4; + static constexpr block_t INSERT_BLOCK = XFILE_BLOCK_VIRTUAL; +}; +} // namespace IW5 diff --git a/src/ZoneCommon/Game/T5/GameAssetPoolT5.cpp b/src/ZoneCommon/Game/T5/GameAssetPoolT5.cpp index b46e8d3c0..b49d1e5d2 100644 --- a/src/ZoneCommon/Game/T5/GameAssetPoolT5.cpp +++ b/src/ZoneCommon/Game/T5/GameAssetPoolT5.cpp @@ -3,313 +3,248 @@ #include <cassert> #include <type_traits> -#include "Pool/AssetPoolStatic.h" #include "Pool/AssetPoolDynamic.h" +#include "Pool/AssetPoolStatic.h" using namespace T5; -const char* GameAssetPoolT5::ASSET_TYPE_NAMES[] -{ - "xmodelpieces", - "physpreset", - "physconstraints", - "destructibledef", - "xanim", - "xmodel", - "material", - "techniqueset", - "image", - "soundbank", - "soundpatch", - "clipmap", - "clipmap", - "comworld", - "gameworldsp", - "gameworldmp", - "mapents", - "gfxworld", - "gfxlightdef", - "uimap", - "font", - "menulist", - "menu", - "localize", - "weapon", - "weapondef", - "weaponvariant", - "snddriverglobals", - "fx", - "fximpacttable", - "aitype", - "mptype", - "mpbody", - "mphead", - "character", - "xmodelalias", - "rawfile", - "stringtable", - "packindex", - "xglobals", - "ddl", - "glasses", - "emblemset" -}; - -GameAssetPoolT5::GameAssetPoolT5(Zone* zone, const int priority) - : ZoneAssetPools(zone), - m_priority(priority) -{ - assert(std::extent<decltype(ASSET_TYPE_NAMES)>::value == ASSET_TYPE_COUNT); +const char *GameAssetPoolT5::ASSET_TYPE_NAMES[]{ + "xmodelpieces", "physpreset", "physconstraints", "destructibledef", "xanim", "xmodel", "material", + "techniqueset", "image", "soundbank", "soundpatch", "clipmap", "clipmap", "comworld", + "gameworldsp", "gameworldmp", "mapents", "gfxworld", "gfxlightdef", "uimap", "font", + "menulist", "menu", "localize", "weapon", "weapondef", "weaponvariant", "snddriverglobals", + "fx", "fximpacttable", "aitype", "mptype", "mpbody", "mphead", "character", + "xmodelalias", "rawfile", "stringtable", "packindex", "xglobals", "ddl", "glasses", + "emblemset"}; + +GameAssetPoolT5::GameAssetPoolT5(Zone *zone, const int priority) : ZoneAssetPools(zone), m_priority(priority) { + assert(std::extent<decltype(ASSET_TYPE_NAMES)>::value == ASSET_TYPE_COUNT); } -void GameAssetPoolT5::InitPoolStatic(const asset_type_t type, const size_t capacity) -{ -#define CASE_INIT_POOL_STATIC(assetType, poolName, poolType) \ - case assetType: \ - { \ - if((poolName) == nullptr && capacity > 0) \ - { \ - (poolName) = std::make_unique<AssetPoolStatic<poolType>>(capacity, m_priority, (assetType)); \ - } \ - break; \ - } - - switch (type) - { - CASE_INIT_POOL_STATIC(ASSET_TYPE_PHYSPRESET, m_phys_preset, PhysPreset); - CASE_INIT_POOL_STATIC(ASSET_TYPE_PHYSCONSTRAINTS, m_phys_constraints, PhysConstraints); - CASE_INIT_POOL_STATIC(ASSET_TYPE_DESTRUCTIBLEDEF, m_destructible_def, DestructibleDef); - CASE_INIT_POOL_STATIC(ASSET_TYPE_XANIMPARTS, m_xanim_parts, XAnimParts); - CASE_INIT_POOL_STATIC(ASSET_TYPE_XMODEL, m_xmodel, XModel); - CASE_INIT_POOL_STATIC(ASSET_TYPE_MATERIAL, m_material, Material); - CASE_INIT_POOL_STATIC(ASSET_TYPE_TECHNIQUE_SET, m_technique_set, MaterialTechniqueSet); - CASE_INIT_POOL_STATIC(ASSET_TYPE_IMAGE, m_image, GfxImage); - CASE_INIT_POOL_STATIC(ASSET_TYPE_SOUND, m_sound_bank, SndBank); - CASE_INIT_POOL_STATIC(ASSET_TYPE_SOUND_PATCH, m_sound_patch, SndPatch); - CASE_INIT_POOL_STATIC(ASSET_TYPE_CLIPMAP, m_clip_map, clipMap_t); - CASE_INIT_POOL_STATIC(ASSET_TYPE_CLIPMAP_PVS, m_clip_map, clipMap_t); - CASE_INIT_POOL_STATIC(ASSET_TYPE_COMWORLD, m_com_world, ComWorld); - CASE_INIT_POOL_STATIC(ASSET_TYPE_GAMEWORLD_SP, m_game_world_sp, GameWorldSp); - CASE_INIT_POOL_STATIC(ASSET_TYPE_GAMEWORLD_MP, m_game_world_mp, GameWorldMp); - CASE_INIT_POOL_STATIC(ASSET_TYPE_MAP_ENTS, m_map_ents, MapEnts); - CASE_INIT_POOL_STATIC(ASSET_TYPE_GFXWORLD, m_gfx_world, GfxWorld); - CASE_INIT_POOL_STATIC(ASSET_TYPE_LIGHT_DEF, m_gfx_light_def, GfxLightDef); - CASE_INIT_POOL_STATIC(ASSET_TYPE_FONT, m_font, Font_s); - CASE_INIT_POOL_STATIC(ASSET_TYPE_MENULIST, m_menu_list, MenuList); - CASE_INIT_POOL_STATIC(ASSET_TYPE_MENU, m_menu_def, menuDef_t); - CASE_INIT_POOL_STATIC(ASSET_TYPE_LOCALIZE_ENTRY, m_localize, LocalizeEntry); - CASE_INIT_POOL_STATIC(ASSET_TYPE_WEAPON, m_weapon, WeaponVariantDef); - CASE_INIT_POOL_STATIC(ASSET_TYPE_SNDDRIVER_GLOBALS, m_snd_driver_globals, SndDriverGlobals); - CASE_INIT_POOL_STATIC(ASSET_TYPE_FX, m_fx, FxEffectDef); - CASE_INIT_POOL_STATIC(ASSET_TYPE_IMPACT_FX, m_fx_impact_table, FxImpactTable); - CASE_INIT_POOL_STATIC(ASSET_TYPE_RAWFILE, m_raw_file, RawFile); - CASE_INIT_POOL_STATIC(ASSET_TYPE_STRINGTABLE, m_string_table, StringTable); - CASE_INIT_POOL_STATIC(ASSET_TYPE_PACK_INDEX, m_pack_index, PackIndex); - CASE_INIT_POOL_STATIC(ASSET_TYPE_XGLOBALS, m_xglobals, XGlobals); - CASE_INIT_POOL_STATIC(ASSET_TYPE_DDL, m_ddl, ddlRoot_t); - CASE_INIT_POOL_STATIC(ASSET_TYPE_GLASSES, m_glasses, Glasses); - CASE_INIT_POOL_STATIC(ASSET_TYPE_EMBLEMSET, m_emblem_set, EmblemSet); - - default: - assert(type >= 0 && type < ASSET_TYPE_COUNT); - break; - } +void GameAssetPoolT5::InitPoolStatic(const asset_type_t type, const size_t capacity) { +#define CASE_INIT_POOL_STATIC(assetType, poolName, poolType) \ + case assetType: { \ + if ((poolName) == nullptr && capacity > 0) { \ + (poolName) = std::make_unique<AssetPoolStatic<poolType>>(capacity, m_priority, (assetType)); \ + } \ + break; \ + } + + switch (type) { + CASE_INIT_POOL_STATIC(ASSET_TYPE_PHYSPRESET, m_phys_preset, PhysPreset); + CASE_INIT_POOL_STATIC(ASSET_TYPE_PHYSCONSTRAINTS, m_phys_constraints, PhysConstraints); + CASE_INIT_POOL_STATIC(ASSET_TYPE_DESTRUCTIBLEDEF, m_destructible_def, DestructibleDef); + CASE_INIT_POOL_STATIC(ASSET_TYPE_XANIMPARTS, m_xanim_parts, XAnimParts); + CASE_INIT_POOL_STATIC(ASSET_TYPE_XMODEL, m_xmodel, XModel); + CASE_INIT_POOL_STATIC(ASSET_TYPE_MATERIAL, m_material, Material); + CASE_INIT_POOL_STATIC(ASSET_TYPE_TECHNIQUE_SET, m_technique_set, MaterialTechniqueSet); + CASE_INIT_POOL_STATIC(ASSET_TYPE_IMAGE, m_image, GfxImage); + CASE_INIT_POOL_STATIC(ASSET_TYPE_SOUND, m_sound_bank, SndBank); + CASE_INIT_POOL_STATIC(ASSET_TYPE_SOUND_PATCH, m_sound_patch, SndPatch); + CASE_INIT_POOL_STATIC(ASSET_TYPE_CLIPMAP, m_clip_map, clipMap_t); + CASE_INIT_POOL_STATIC(ASSET_TYPE_CLIPMAP_PVS, m_clip_map, clipMap_t); + CASE_INIT_POOL_STATIC(ASSET_TYPE_COMWORLD, m_com_world, ComWorld); + CASE_INIT_POOL_STATIC(ASSET_TYPE_GAMEWORLD_SP, m_game_world_sp, GameWorldSp); + CASE_INIT_POOL_STATIC(ASSET_TYPE_GAMEWORLD_MP, m_game_world_mp, GameWorldMp); + CASE_INIT_POOL_STATIC(ASSET_TYPE_MAP_ENTS, m_map_ents, MapEnts); + CASE_INIT_POOL_STATIC(ASSET_TYPE_GFXWORLD, m_gfx_world, GfxWorld); + CASE_INIT_POOL_STATIC(ASSET_TYPE_LIGHT_DEF, m_gfx_light_def, GfxLightDef); + CASE_INIT_POOL_STATIC(ASSET_TYPE_FONT, m_font, Font_s); + CASE_INIT_POOL_STATIC(ASSET_TYPE_MENULIST, m_menu_list, MenuList); + CASE_INIT_POOL_STATIC(ASSET_TYPE_MENU, m_menu_def, menuDef_t); + CASE_INIT_POOL_STATIC(ASSET_TYPE_LOCALIZE_ENTRY, m_localize, LocalizeEntry); + CASE_INIT_POOL_STATIC(ASSET_TYPE_WEAPON, m_weapon, WeaponVariantDef); + CASE_INIT_POOL_STATIC(ASSET_TYPE_SNDDRIVER_GLOBALS, m_snd_driver_globals, SndDriverGlobals); + CASE_INIT_POOL_STATIC(ASSET_TYPE_FX, m_fx, FxEffectDef); + CASE_INIT_POOL_STATIC(ASSET_TYPE_IMPACT_FX, m_fx_impact_table, FxImpactTable); + CASE_INIT_POOL_STATIC(ASSET_TYPE_RAWFILE, m_raw_file, RawFile); + CASE_INIT_POOL_STATIC(ASSET_TYPE_STRINGTABLE, m_string_table, StringTable); + CASE_INIT_POOL_STATIC(ASSET_TYPE_PACK_INDEX, m_pack_index, PackIndex); + CASE_INIT_POOL_STATIC(ASSET_TYPE_XGLOBALS, m_xglobals, XGlobals); + CASE_INIT_POOL_STATIC(ASSET_TYPE_DDL, m_ddl, ddlRoot_t); + CASE_INIT_POOL_STATIC(ASSET_TYPE_GLASSES, m_glasses, Glasses); + CASE_INIT_POOL_STATIC(ASSET_TYPE_EMBLEMSET, m_emblem_set, EmblemSet); + + default: + assert(type >= 0 && type < ASSET_TYPE_COUNT); + break; + } #undef CASE_INIT_POOL_STATIC } -void GameAssetPoolT5::InitPoolDynamic(const asset_type_t type) -{ -#define CASE_INIT_POOL_DYNAMIC(assetType, poolName, poolType) \ - case assetType: \ - { \ - if((poolName) == nullptr) \ - { \ - (poolName) = std::make_unique<AssetPoolDynamic<poolType>>(m_priority, (assetType)); \ - } \ - break; \ - } - - switch (type) - { - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_PHYSPRESET, m_phys_preset, PhysPreset); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_PHYSCONSTRAINTS, m_phys_constraints, PhysConstraints); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_DESTRUCTIBLEDEF, m_destructible_def, DestructibleDef); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_XANIMPARTS, m_xanim_parts, XAnimParts); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_XMODEL, m_xmodel, XModel); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_MATERIAL, m_material, Material); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_TECHNIQUE_SET, m_technique_set, MaterialTechniqueSet); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_IMAGE, m_image, GfxImage); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_SOUND, m_sound_bank, SndBank); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_SOUND_PATCH, m_sound_patch, SndPatch); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_CLIPMAP, m_clip_map, clipMap_t); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_CLIPMAP_PVS, m_clip_map, clipMap_t); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_COMWORLD, m_com_world, ComWorld); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_GAMEWORLD_SP, m_game_world_sp, GameWorldSp); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_GAMEWORLD_MP, m_game_world_mp, GameWorldMp); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_MAP_ENTS, m_map_ents, MapEnts); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_GFXWORLD, m_gfx_world, GfxWorld); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_LIGHT_DEF, m_gfx_light_def, GfxLightDef); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_FONT, m_font, Font_s); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_MENULIST, m_menu_list, MenuList); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_MENU, m_menu_def, menuDef_t); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_LOCALIZE_ENTRY, m_localize, LocalizeEntry); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_WEAPON, m_weapon, WeaponVariantDef); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_SNDDRIVER_GLOBALS, m_snd_driver_globals, SndDriverGlobals); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_FX, m_fx, FxEffectDef); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_IMPACT_FX, m_fx_impact_table, FxImpactTable); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_RAWFILE, m_raw_file, RawFile); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_STRINGTABLE, m_string_table, StringTable); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_PACK_INDEX, m_pack_index, PackIndex); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_XGLOBALS, m_xglobals, XGlobals); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_DDL, m_ddl, ddlRoot_t); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_GLASSES, m_glasses, Glasses); - CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_EMBLEMSET, m_emblem_set, EmblemSet); - - default: - assert(type >= 0 && type < ASSET_TYPE_COUNT); - break; - } +void GameAssetPoolT5::InitPoolDynamic(const asset_type_t type) { +#define CASE_INIT_POOL_DYNAMIC(assetType, poolName, poolType) \ + case assetType: { \ + if ((poolName) == nullptr) { \ + (poolName) = std::make_unique<AssetPoolDynamic<poolType>>(m_priority, (assetType)); \ + } \ + break; \ + } + + switch (type) { + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_PHYSPRESET, m_phys_preset, PhysPreset); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_PHYSCONSTRAINTS, m_phys_constraints, PhysConstraints); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_DESTRUCTIBLEDEF, m_destructible_def, DestructibleDef); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_XANIMPARTS, m_xanim_parts, XAnimParts); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_XMODEL, m_xmodel, XModel); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_MATERIAL, m_material, Material); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_TECHNIQUE_SET, m_technique_set, MaterialTechniqueSet); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_IMAGE, m_image, GfxImage); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_SOUND, m_sound_bank, SndBank); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_SOUND_PATCH, m_sound_patch, SndPatch); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_CLIPMAP, m_clip_map, clipMap_t); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_CLIPMAP_PVS, m_clip_map, clipMap_t); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_COMWORLD, m_com_world, ComWorld); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_GAMEWORLD_SP, m_game_world_sp, GameWorldSp); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_GAMEWORLD_MP, m_game_world_mp, GameWorldMp); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_MAP_ENTS, m_map_ents, MapEnts); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_GFXWORLD, m_gfx_world, GfxWorld); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_LIGHT_DEF, m_gfx_light_def, GfxLightDef); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_FONT, m_font, Font_s); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_MENULIST, m_menu_list, MenuList); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_MENU, m_menu_def, menuDef_t); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_LOCALIZE_ENTRY, m_localize, LocalizeEntry); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_WEAPON, m_weapon, WeaponVariantDef); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_SNDDRIVER_GLOBALS, m_snd_driver_globals, SndDriverGlobals); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_FX, m_fx, FxEffectDef); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_IMPACT_FX, m_fx_impact_table, FxImpactTable); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_RAWFILE, m_raw_file, RawFile); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_STRINGTABLE, m_string_table, StringTable); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_PACK_INDEX, m_pack_index, PackIndex); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_XGLOBALS, m_xglobals, XGlobals); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_DDL, m_ddl, ddlRoot_t); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_GLASSES, m_glasses, Glasses); + CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_EMBLEMSET, m_emblem_set, EmblemSet); + + default: + assert(type >= 0 && type < ASSET_TYPE_COUNT); + break; + } #undef CASE_INIT_POOL_STATIC } -XAssetInfoGeneric* GameAssetPoolT5::AddAssetToPool(asset_type_t type, std::string name, void* asset, std::vector<XAssetInfoGeneric*> dependencies, std::vector<scr_string_t> usedScriptStrings, - Zone* zone) -{ - XAsset xAsset{}; - - xAsset.type = static_cast<XAssetType>(type); - xAsset.header.data = asset; - -#define CASE_ADD_TO_POOL(assetType, poolName, headerName) \ - case assetType: \ - { \ - assert((poolName) != nullptr); \ - return (poolName)->AddAsset(std::move(name), xAsset.header.headerName, zone, std::move(dependencies), std::move(usedScriptStrings)); \ - } - - switch (xAsset.type) - { - CASE_ADD_TO_POOL(ASSET_TYPE_PHYSPRESET, m_phys_preset, physPreset); - CASE_ADD_TO_POOL(ASSET_TYPE_PHYSCONSTRAINTS, m_phys_constraints, physConstraints); - CASE_ADD_TO_POOL(ASSET_TYPE_DESTRUCTIBLEDEF, m_destructible_def, destructibleDef); - CASE_ADD_TO_POOL(ASSET_TYPE_XANIMPARTS, m_xanim_parts, parts); - CASE_ADD_TO_POOL(ASSET_TYPE_XMODEL, m_xmodel, model); - CASE_ADD_TO_POOL(ASSET_TYPE_MATERIAL, m_material, material); - CASE_ADD_TO_POOL(ASSET_TYPE_TECHNIQUE_SET, m_technique_set, techniqueSet); - CASE_ADD_TO_POOL(ASSET_TYPE_IMAGE, m_image, image); - CASE_ADD_TO_POOL(ASSET_TYPE_SOUND, m_sound_bank, sound); - CASE_ADD_TO_POOL(ASSET_TYPE_SOUND_PATCH, m_sound_patch, soundPatch); - CASE_ADD_TO_POOL(ASSET_TYPE_CLIPMAP, m_clip_map, clipMap); - CASE_ADD_TO_POOL(ASSET_TYPE_CLIPMAP_PVS, m_clip_map, clipMap); - CASE_ADD_TO_POOL(ASSET_TYPE_COMWORLD, m_com_world, comWorld); - CASE_ADD_TO_POOL(ASSET_TYPE_GAMEWORLD_SP, m_game_world_sp, gameWorldSp); - CASE_ADD_TO_POOL(ASSET_TYPE_GAMEWORLD_MP, m_game_world_mp, gameWorldMp); - CASE_ADD_TO_POOL(ASSET_TYPE_MAP_ENTS, m_map_ents, mapEnts); - CASE_ADD_TO_POOL(ASSET_TYPE_GFXWORLD, m_gfx_world, gfxWorld); - CASE_ADD_TO_POOL(ASSET_TYPE_LIGHT_DEF, m_gfx_light_def, lightDef); - CASE_ADD_TO_POOL(ASSET_TYPE_FONT, m_font, font); - CASE_ADD_TO_POOL(ASSET_TYPE_MENULIST, m_menu_list, menuList); - CASE_ADD_TO_POOL(ASSET_TYPE_MENU, m_menu_def, menu); - CASE_ADD_TO_POOL(ASSET_TYPE_LOCALIZE_ENTRY, m_localize, localize); - CASE_ADD_TO_POOL(ASSET_TYPE_WEAPON, m_weapon, weapon); - CASE_ADD_TO_POOL(ASSET_TYPE_SNDDRIVER_GLOBALS, m_snd_driver_globals, sndDriverGlobals); - CASE_ADD_TO_POOL(ASSET_TYPE_FX, m_fx, fx); - CASE_ADD_TO_POOL(ASSET_TYPE_IMPACT_FX, m_fx_impact_table, impactFx); - CASE_ADD_TO_POOL(ASSET_TYPE_RAWFILE, m_raw_file, rawfile); - CASE_ADD_TO_POOL(ASSET_TYPE_STRINGTABLE, m_string_table, stringTable); - CASE_ADD_TO_POOL(ASSET_TYPE_PACK_INDEX, m_pack_index, packIndex); - CASE_ADD_TO_POOL(ASSET_TYPE_XGLOBALS, m_xglobals, xGlobals); - CASE_ADD_TO_POOL(ASSET_TYPE_DDL, m_ddl, ddlRoot); - CASE_ADD_TO_POOL(ASSET_TYPE_GLASSES, m_glasses, glasses); - CASE_ADD_TO_POOL(ASSET_TYPE_EMBLEMSET, m_emblem_set, emblemSet); - - default: - assert(false); - break; - } - - return nullptr; +XAssetInfoGeneric *GameAssetPoolT5::AddAssetToPool(asset_type_t type, std::string name, void *asset, std::vector<XAssetInfoGeneric *> dependencies, + std::vector<scr_string_t> usedScriptStrings, Zone *zone) { + XAsset xAsset{}; + + xAsset.type = static_cast<XAssetType>(type); + xAsset.header.data = asset; + +#define CASE_ADD_TO_POOL(assetType, poolName, headerName) \ + case assetType: { \ + assert((poolName) != nullptr); \ + return (poolName)->AddAsset(std::move(name), xAsset.header.headerName, zone, std::move(dependencies), std::move(usedScriptStrings)); \ + } + + switch (xAsset.type) { + CASE_ADD_TO_POOL(ASSET_TYPE_PHYSPRESET, m_phys_preset, physPreset); + CASE_ADD_TO_POOL(ASSET_TYPE_PHYSCONSTRAINTS, m_phys_constraints, physConstraints); + CASE_ADD_TO_POOL(ASSET_TYPE_DESTRUCTIBLEDEF, m_destructible_def, destructibleDef); + CASE_ADD_TO_POOL(ASSET_TYPE_XANIMPARTS, m_xanim_parts, parts); + CASE_ADD_TO_POOL(ASSET_TYPE_XMODEL, m_xmodel, model); + CASE_ADD_TO_POOL(ASSET_TYPE_MATERIAL, m_material, material); + CASE_ADD_TO_POOL(ASSET_TYPE_TECHNIQUE_SET, m_technique_set, techniqueSet); + CASE_ADD_TO_POOL(ASSET_TYPE_IMAGE, m_image, image); + CASE_ADD_TO_POOL(ASSET_TYPE_SOUND, m_sound_bank, sound); + CASE_ADD_TO_POOL(ASSET_TYPE_SOUND_PATCH, m_sound_patch, soundPatch); + CASE_ADD_TO_POOL(ASSET_TYPE_CLIPMAP, m_clip_map, clipMap); + CASE_ADD_TO_POOL(ASSET_TYPE_CLIPMAP_PVS, m_clip_map, clipMap); + CASE_ADD_TO_POOL(ASSET_TYPE_COMWORLD, m_com_world, comWorld); + CASE_ADD_TO_POOL(ASSET_TYPE_GAMEWORLD_SP, m_game_world_sp, gameWorldSp); + CASE_ADD_TO_POOL(ASSET_TYPE_GAMEWORLD_MP, m_game_world_mp, gameWorldMp); + CASE_ADD_TO_POOL(ASSET_TYPE_MAP_ENTS, m_map_ents, mapEnts); + CASE_ADD_TO_POOL(ASSET_TYPE_GFXWORLD, m_gfx_world, gfxWorld); + CASE_ADD_TO_POOL(ASSET_TYPE_LIGHT_DEF, m_gfx_light_def, lightDef); + CASE_ADD_TO_POOL(ASSET_TYPE_FONT, m_font, font); + CASE_ADD_TO_POOL(ASSET_TYPE_MENULIST, m_menu_list, menuList); + CASE_ADD_TO_POOL(ASSET_TYPE_MENU, m_menu_def, menu); + CASE_ADD_TO_POOL(ASSET_TYPE_LOCALIZE_ENTRY, m_localize, localize); + CASE_ADD_TO_POOL(ASSET_TYPE_WEAPON, m_weapon, weapon); + CASE_ADD_TO_POOL(ASSET_TYPE_SNDDRIVER_GLOBALS, m_snd_driver_globals, sndDriverGlobals); + CASE_ADD_TO_POOL(ASSET_TYPE_FX, m_fx, fx); + CASE_ADD_TO_POOL(ASSET_TYPE_IMPACT_FX, m_fx_impact_table, impactFx); + CASE_ADD_TO_POOL(ASSET_TYPE_RAWFILE, m_raw_file, rawfile); + CASE_ADD_TO_POOL(ASSET_TYPE_STRINGTABLE, m_string_table, stringTable); + CASE_ADD_TO_POOL(ASSET_TYPE_PACK_INDEX, m_pack_index, packIndex); + CASE_ADD_TO_POOL(ASSET_TYPE_XGLOBALS, m_xglobals, xGlobals); + CASE_ADD_TO_POOL(ASSET_TYPE_DDL, m_ddl, ddlRoot); + CASE_ADD_TO_POOL(ASSET_TYPE_GLASSES, m_glasses, glasses); + CASE_ADD_TO_POOL(ASSET_TYPE_EMBLEMSET, m_emblem_set, emblemSet); + + default: + assert(false); + break; + } + + return nullptr; #undef CASE_ADD_TO_POOL } -XAssetInfoGeneric* GameAssetPoolT5::GetAsset(const asset_type_t type, std::string name) const -{ -#define CASE_GET_ASSET(assetType, poolName) \ - case assetType: \ - { \ - if((poolName) != nullptr) \ - return (poolName)->GetAsset(std::move(name)); \ - break; \ - } - - switch (type) - { - CASE_GET_ASSET(ASSET_TYPE_PHYSPRESET, m_phys_preset); - CASE_GET_ASSET(ASSET_TYPE_PHYSCONSTRAINTS, m_phys_constraints); - CASE_GET_ASSET(ASSET_TYPE_DESTRUCTIBLEDEF, m_destructible_def); - CASE_GET_ASSET(ASSET_TYPE_XANIMPARTS, m_xanim_parts); - CASE_GET_ASSET(ASSET_TYPE_XMODEL, m_xmodel); - CASE_GET_ASSET(ASSET_TYPE_MATERIAL, m_material); - CASE_GET_ASSET(ASSET_TYPE_TECHNIQUE_SET, m_technique_set); - CASE_GET_ASSET(ASSET_TYPE_IMAGE, m_image); - CASE_GET_ASSET(ASSET_TYPE_SOUND, m_sound_bank); - CASE_GET_ASSET(ASSET_TYPE_SOUND_PATCH, m_sound_patch); - CASE_GET_ASSET(ASSET_TYPE_CLIPMAP, m_clip_map); - CASE_GET_ASSET(ASSET_TYPE_CLIPMAP_PVS, m_clip_map); - CASE_GET_ASSET(ASSET_TYPE_COMWORLD, m_com_world); - CASE_GET_ASSET(ASSET_TYPE_GAMEWORLD_SP, m_game_world_sp); - CASE_GET_ASSET(ASSET_TYPE_GAMEWORLD_MP, m_game_world_mp); - CASE_GET_ASSET(ASSET_TYPE_MAP_ENTS, m_map_ents); - CASE_GET_ASSET(ASSET_TYPE_GFXWORLD, m_gfx_world); - CASE_GET_ASSET(ASSET_TYPE_LIGHT_DEF, m_gfx_light_def); - CASE_GET_ASSET(ASSET_TYPE_FONT, m_font); - CASE_GET_ASSET(ASSET_TYPE_MENULIST, m_menu_list); - CASE_GET_ASSET(ASSET_TYPE_MENU, m_menu_def); - CASE_GET_ASSET(ASSET_TYPE_LOCALIZE_ENTRY, m_localize); - CASE_GET_ASSET(ASSET_TYPE_WEAPON, m_weapon); - CASE_GET_ASSET(ASSET_TYPE_SNDDRIVER_GLOBALS, m_snd_driver_globals); - CASE_GET_ASSET(ASSET_TYPE_FX, m_fx); - CASE_GET_ASSET(ASSET_TYPE_IMPACT_FX, m_fx_impact_table); - CASE_GET_ASSET(ASSET_TYPE_RAWFILE, m_raw_file); - CASE_GET_ASSET(ASSET_TYPE_STRINGTABLE, m_string_table); - CASE_GET_ASSET(ASSET_TYPE_PACK_INDEX, m_pack_index); - CASE_GET_ASSET(ASSET_TYPE_XGLOBALS, m_xglobals); - CASE_GET_ASSET(ASSET_TYPE_DDL, m_ddl); - CASE_GET_ASSET(ASSET_TYPE_GLASSES, m_glasses); - CASE_GET_ASSET(ASSET_TYPE_EMBLEMSET, m_emblem_set); - - default: - assert(false); - break; - } - - return nullptr; +XAssetInfoGeneric *GameAssetPoolT5::GetAsset(const asset_type_t type, std::string name) const { +#define CASE_GET_ASSET(assetType, poolName) \ + case assetType: { \ + if ((poolName) != nullptr) \ + return (poolName)->GetAsset(std::move(name)); \ + break; \ + } + + switch (type) { + CASE_GET_ASSET(ASSET_TYPE_PHYSPRESET, m_phys_preset); + CASE_GET_ASSET(ASSET_TYPE_PHYSCONSTRAINTS, m_phys_constraints); + CASE_GET_ASSET(ASSET_TYPE_DESTRUCTIBLEDEF, m_destructible_def); + CASE_GET_ASSET(ASSET_TYPE_XANIMPARTS, m_xanim_parts); + CASE_GET_ASSET(ASSET_TYPE_XMODEL, m_xmodel); + CASE_GET_ASSET(ASSET_TYPE_MATERIAL, m_material); + CASE_GET_ASSET(ASSET_TYPE_TECHNIQUE_SET, m_technique_set); + CASE_GET_ASSET(ASSET_TYPE_IMAGE, m_image); + CASE_GET_ASSET(ASSET_TYPE_SOUND, m_sound_bank); + CASE_GET_ASSET(ASSET_TYPE_SOUND_PATCH, m_sound_patch); + CASE_GET_ASSET(ASSET_TYPE_CLIPMAP, m_clip_map); + CASE_GET_ASSET(ASSET_TYPE_CLIPMAP_PVS, m_clip_map); + CASE_GET_ASSET(ASSET_TYPE_COMWORLD, m_com_world); + CASE_GET_ASSET(ASSET_TYPE_GAMEWORLD_SP, m_game_world_sp); + CASE_GET_ASSET(ASSET_TYPE_GAMEWORLD_MP, m_game_world_mp); + CASE_GET_ASSET(ASSET_TYPE_MAP_ENTS, m_map_ents); + CASE_GET_ASSET(ASSET_TYPE_GFXWORLD, m_gfx_world); + CASE_GET_ASSET(ASSET_TYPE_LIGHT_DEF, m_gfx_light_def); + CASE_GET_ASSET(ASSET_TYPE_FONT, m_font); + CASE_GET_ASSET(ASSET_TYPE_MENULIST, m_menu_list); + CASE_GET_ASSET(ASSET_TYPE_MENU, m_menu_def); + CASE_GET_ASSET(ASSET_TYPE_LOCALIZE_ENTRY, m_localize); + CASE_GET_ASSET(ASSET_TYPE_WEAPON, m_weapon); + CASE_GET_ASSET(ASSET_TYPE_SNDDRIVER_GLOBALS, m_snd_driver_globals); + CASE_GET_ASSET(ASSET_TYPE_FX, m_fx); + CASE_GET_ASSET(ASSET_TYPE_IMPACT_FX, m_fx_impact_table); + CASE_GET_ASSET(ASSET_TYPE_RAWFILE, m_raw_file); + CASE_GET_ASSET(ASSET_TYPE_STRINGTABLE, m_string_table); + CASE_GET_ASSET(ASSET_TYPE_PACK_INDEX, m_pack_index); + CASE_GET_ASSET(ASSET_TYPE_XGLOBALS, m_xglobals); + CASE_GET_ASSET(ASSET_TYPE_DDL, m_ddl); + CASE_GET_ASSET(ASSET_TYPE_GLASSES, m_glasses); + CASE_GET_ASSET(ASSET_TYPE_EMBLEMSET, m_emblem_set); + + default: + assert(false); + break; + } + + return nullptr; #undef CASE_GET_ASSET } -const char* GameAssetPoolT5::AssetTypeNameByType(asset_type_t assetType) -{ - if (assetType >= 0 && assetType < static_cast<int>(std::extent<decltype(ASSET_TYPE_NAMES)>::value)) - return ASSET_TYPE_NAMES[assetType]; +const char *GameAssetPoolT5::AssetTypeNameByType(asset_type_t assetType) { + if (assetType >= 0 && assetType < static_cast<int>(std::extent<decltype(ASSET_TYPE_NAMES)>::value)) + return ASSET_TYPE_NAMES[assetType]; - return ASSET_TYPE_INVALID; + return ASSET_TYPE_INVALID; } -const char* GameAssetPoolT5::GetAssetTypeName(const asset_type_t assetType) const -{ - return AssetTypeNameByType(assetType); -} +const char *GameAssetPoolT5::GetAssetTypeName(const asset_type_t assetType) const { return AssetTypeNameByType(assetType); } -asset_type_t GameAssetPoolT5::AssetTypeCount() -{ - return ASSET_TYPE_COUNT; -} +asset_type_t GameAssetPoolT5::AssetTypeCount() { return ASSET_TYPE_COUNT; } -asset_type_t GameAssetPoolT5::GetAssetTypeCount() const -{ - return AssetTypeCount(); -} +asset_type_t GameAssetPoolT5::GetAssetTypeCount() const { return AssetTypeCount(); } diff --git a/src/ZoneCommon/Game/T5/GameAssetPoolT5.h b/src/ZoneCommon/Game/T5/GameAssetPoolT5.h index e1aba0d14..5afd00cb8 100644 --- a/src/ZoneCommon/Game/T5/GameAssetPoolT5.h +++ b/src/ZoneCommon/Game/T5/GameAssetPoolT5.h @@ -2,65 +2,65 @@ #include <memory> -#include "Pool/ZoneAssetPools.h" -#include "Pool/AssetPool.h" #include "Game/T5/T5.h" +#include "Pool/AssetPool.h" +#include "Pool/ZoneAssetPools.h" -class GameAssetPoolT5 final : public ZoneAssetPools -{ - int m_priority; +class GameAssetPoolT5 final : public ZoneAssetPools { + int m_priority; - static constexpr const char* ASSET_TYPE_INVALID = "invalid_asset_type"; - static const char* ASSET_TYPE_NAMES[]; + static constexpr const char *ASSET_TYPE_INVALID = "invalid_asset_type"; + static const char *ASSET_TYPE_NAMES[]; protected: - XAssetInfoGeneric* AddAssetToPool(asset_type_t type, std::string name, void* asset, std::vector<XAssetInfoGeneric*> dependencies, std::vector<scr_string_t> usedScriptStrings, Zone* zone) override; + XAssetInfoGeneric *AddAssetToPool(asset_type_t type, std::string name, void *asset, std::vector<XAssetInfoGeneric *> dependencies, + std::vector<scr_string_t> usedScriptStrings, Zone *zone) override; public: - std::unique_ptr<AssetPool<T5::PhysPreset>> m_phys_preset; - std::unique_ptr<AssetPool<T5::PhysConstraints>> m_phys_constraints; - std::unique_ptr<AssetPool<T5::DestructibleDef>> m_destructible_def; - std::unique_ptr<AssetPool<T5::XAnimParts>> m_xanim_parts; - std::unique_ptr<AssetPool<T5::XModel>> m_xmodel; - std::unique_ptr<AssetPool<T5::Material>> m_material; - std::unique_ptr<AssetPool<T5::MaterialTechniqueSet>> m_technique_set; - std::unique_ptr<AssetPool<T5::GfxImage>> m_image; - std::unique_ptr<AssetPool<T5::SndBank>> m_sound_bank; - std::unique_ptr<AssetPool<T5::SndPatch>> m_sound_patch; - std::unique_ptr<AssetPool<T5::clipMap_t>> m_clip_map; - std::unique_ptr<AssetPool<T5::ComWorld>> m_com_world; - std::unique_ptr<AssetPool<T5::GameWorldSp>> m_game_world_sp; - std::unique_ptr<AssetPool<T5::GameWorldMp>> m_game_world_mp; - std::unique_ptr<AssetPool<T5::MapEnts>> m_map_ents; - std::unique_ptr<AssetPool<T5::GfxWorld>> m_gfx_world; - std::unique_ptr<AssetPool<T5::GfxLightDef>> m_gfx_light_def; - std::unique_ptr<AssetPool<T5::Font_s>> m_font; - std::unique_ptr<AssetPool<T5::MenuList>> m_menu_list; - std::unique_ptr<AssetPool<T5::menuDef_t>> m_menu_def; - std::unique_ptr<AssetPool<T5::LocalizeEntry>> m_localize; - std::unique_ptr<AssetPool<T5::WeaponVariantDef>> m_weapon; - std::unique_ptr<AssetPool<T5::SndDriverGlobals>> m_snd_driver_globals; - std::unique_ptr<AssetPool<T5::FxEffectDef>> m_fx; - std::unique_ptr<AssetPool<T5::FxImpactTable>> m_fx_impact_table; - std::unique_ptr<AssetPool<T5::RawFile>> m_raw_file; - std::unique_ptr<AssetPool<T5::StringTable>> m_string_table; - std::unique_ptr<AssetPool<T5::PackIndex>> m_pack_index; - std::unique_ptr<AssetPool<T5::XGlobals>> m_xglobals; - std::unique_ptr<AssetPool<T5::ddlRoot_t>> m_ddl; - std::unique_ptr<AssetPool<T5::Glasses>> m_glasses; - std::unique_ptr<AssetPool<T5::EmblemSet>> m_emblem_set; + std::unique_ptr<AssetPool<T5::PhysPreset>> m_phys_preset; + std::unique_ptr<AssetPool<T5::PhysConstraints>> m_phys_constraints; + std::unique_ptr<AssetPool<T5::DestructibleDef>> m_destructible_def; + std::unique_ptr<AssetPool<T5::XAnimParts>> m_xanim_parts; + std::unique_ptr<AssetPool<T5::XModel>> m_xmodel; + std::unique_ptr<AssetPool<T5::Material>> m_material; + std::unique_ptr<AssetPool<T5::MaterialTechniqueSet>> m_technique_set; + std::unique_ptr<AssetPool<T5::GfxImage>> m_image; + std::unique_ptr<AssetPool<T5::SndBank>> m_sound_bank; + std::unique_ptr<AssetPool<T5::SndPatch>> m_sound_patch; + std::unique_ptr<AssetPool<T5::clipMap_t>> m_clip_map; + std::unique_ptr<AssetPool<T5::ComWorld>> m_com_world; + std::unique_ptr<AssetPool<T5::GameWorldSp>> m_game_world_sp; + std::unique_ptr<AssetPool<T5::GameWorldMp>> m_game_world_mp; + std::unique_ptr<AssetPool<T5::MapEnts>> m_map_ents; + std::unique_ptr<AssetPool<T5::GfxWorld>> m_gfx_world; + std::unique_ptr<AssetPool<T5::GfxLightDef>> m_gfx_light_def; + std::unique_ptr<AssetPool<T5::Font_s>> m_font; + std::unique_ptr<AssetPool<T5::MenuList>> m_menu_list; + std::unique_ptr<AssetPool<T5::menuDef_t>> m_menu_def; + std::unique_ptr<AssetPool<T5::LocalizeEntry>> m_localize; + std::unique_ptr<AssetPool<T5::WeaponVariantDef>> m_weapon; + std::unique_ptr<AssetPool<T5::SndDriverGlobals>> m_snd_driver_globals; + std::unique_ptr<AssetPool<T5::FxEffectDef>> m_fx; + std::unique_ptr<AssetPool<T5::FxImpactTable>> m_fx_impact_table; + std::unique_ptr<AssetPool<T5::RawFile>> m_raw_file; + std::unique_ptr<AssetPool<T5::StringTable>> m_string_table; + std::unique_ptr<AssetPool<T5::PackIndex>> m_pack_index; + std::unique_ptr<AssetPool<T5::XGlobals>> m_xglobals; + std::unique_ptr<AssetPool<T5::ddlRoot_t>> m_ddl; + std::unique_ptr<AssetPool<T5::Glasses>> m_glasses; + std::unique_ptr<AssetPool<T5::EmblemSet>> m_emblem_set; - GameAssetPoolT5(Zone* zone, int priority); - ~GameAssetPoolT5() override = default; + GameAssetPoolT5(Zone *zone, int priority); + ~GameAssetPoolT5() override = default; - void InitPoolStatic(asset_type_t type, size_t capacity) override; - void InitPoolDynamic(asset_type_t type) override; + void InitPoolStatic(asset_type_t type, size_t capacity) override; + void InitPoolDynamic(asset_type_t type) override; - _NODISCARD XAssetInfoGeneric* GetAsset(asset_type_t type, std::string name) const override; + _NODISCARD XAssetInfoGeneric *GetAsset(asset_type_t type, std::string name) const override; - static const char* AssetTypeNameByType(asset_type_t assetType); - _NODISCARD const char* GetAssetTypeName(asset_type_t assetType) const override; + static const char *AssetTypeNameByType(asset_type_t assetType); + _NODISCARD const char *GetAssetTypeName(asset_type_t assetType) const override; - static asset_type_t AssetTypeCount(); - _NODISCARD asset_type_t GetAssetTypeCount() const override; + static asset_type_t AssetTypeCount(); + _NODISCARD asset_type_t GetAssetTypeCount() const override; }; diff --git a/src/ZoneCommon/Game/T5/ZoneConstantsT5.h b/src/ZoneCommon/Game/T5/ZoneConstantsT5.h index 6a1cfc8d9..5f8e63d83 100644 --- a/src/ZoneCommon/Game/T5/ZoneConstantsT5.h +++ b/src/ZoneCommon/Game/T5/ZoneConstantsT5.h @@ -2,25 +2,23 @@ #include <cstdint> #include <string> -#include "Zone/ZoneTypes.h" #include "Game/T5/T5.h" +#include "Zone/ZoneTypes.h" + +namespace T5 { +class ZoneConstants final { + ZoneConstants() = default; -namespace T5 -{ - class ZoneConstants final - { - ZoneConstants() = default; +public: + static constexpr const char *MAGIC_UNSIGNED = "IWffu100"; + static constexpr int ZONE_VERSION = 473; - public: - static constexpr const char* MAGIC_UNSIGNED = "IWffu100"; - static constexpr int ZONE_VERSION = 473; - - static_assert(std::char_traits<char>::length(MAGIC_UNSIGNED) == sizeof(ZoneHeader::m_magic)); + static_assert(std::char_traits<char>::length(MAGIC_UNSIGNED) == sizeof(ZoneHeader::m_magic)); - static constexpr size_t AUTHED_CHUNK_SIZE = 0x2000; - static constexpr unsigned AUTHED_CHUNK_COUNT_PER_GROUP = 256; + static constexpr size_t AUTHED_CHUNK_SIZE = 0x2000; + static constexpr unsigned AUTHED_CHUNK_COUNT_PER_GROUP = 256; - static constexpr int OFFSET_BLOCK_BIT_COUNT = 3; - static constexpr block_t INSERT_BLOCK = XFILE_BLOCK_VIRTUAL; - }; -} + static constexpr int OFFSET_BLOCK_BIT_COUNT = 3; + static constexpr block_t INSERT_BLOCK = XFILE_BLOCK_VIRTUAL; +}; +} // namespace T5 diff --git a/src/ZoneCommon/Game/T6/GameAssetPoolT6.cpp b/src/ZoneCommon/Game/T6/GameAssetPoolT6.cpp index b667df7ed..1b48d9070 100644 --- a/src/ZoneCommon/Game/T6/GameAssetPoolT6.cpp +++ b/src/ZoneCommon/Game/T6/GameAssetPoolT6.cpp @@ -3,96 +3,86 @@ #include <cassert> #include <type_traits> -#include "Pool/AssetPoolStatic.h" #include "Pool/AssetPoolDynamic.h" +#include "Pool/AssetPoolStatic.h" using namespace T6; -const char* GameAssetPoolT6::ASSET_TYPE_NAMES[] -{ - "xmodelpieces", - "physpreset", - "physconstraints", - "destructibledef", - "xanim", - "xmodel", - "material", - "techniqueset", - "image", - "soundbank", - "soundpatch", - "clipmap", - "clipmap", - "comworld", - "gameworldsp", - "gameworldmp", - "mapents", - "gfxworld", - "gfxlightdef", - "uimap", - "font", - "fonticon", - "menulist", - "menu", - "localize", - "weapon", - "weapondef", - "weaponvariant", - "weaponfull", - "attachment", - "attachmentunique", - "camo", - "snddriverglobals", - "fx", - "fximpacttable", - "aitype", - "mptype", - "mpbody", - "mphead", - "character", - "xmodelalias", - "rawfile", - "stringtable", - "leaderboard", - "xglobals", - "ddl", - "glasses", - "emblemset", - "script", - "keyvaluepairs", - "vehicle", - "memoryblock", - "addonmapents", - "tracer", - "skinnedverts", - "qdb", - "slug", - "footsteptable", - "footstepfxtable", - "zbarrier" -}; +const char *GameAssetPoolT6::ASSET_TYPE_NAMES[]{"xmodelpieces", + "physpreset", + "physconstraints", + "destructibledef", + "xanim", + "xmodel", + "material", + "techniqueset", + "image", + "soundbank", + "soundpatch", + "clipmap", + "clipmap", + "comworld", + "gameworldsp", + "gameworldmp", + "mapents", + "gfxworld", + "gfxlightdef", + "uimap", + "font", + "fonticon", + "menulist", + "menu", + "localize", + "weapon", + "weapondef", + "weaponvariant", + "weaponfull", + "attachment", + "attachmentunique", + "camo", + "snddriverglobals", + "fx", + "fximpacttable", + "aitype", + "mptype", + "mpbody", + "mphead", + "character", + "xmodelalias", + "rawfile", + "stringtable", + "leaderboard", + "xglobals", + "ddl", + "glasses", + "emblemset", + "script", + "keyvaluepairs", + "vehicle", + "memoryblock", + "addonmapents", + "tracer", + "skinnedverts", + "qdb", + "slug", + "footsteptable", + "footstepfxtable", + "zbarrier"}; -GameAssetPoolT6::GameAssetPoolT6(Zone* zone, const int priority) - : ZoneAssetPools(zone), - m_priority(priority) -{ - assert(std::extent<decltype(ASSET_TYPE_NAMES)>::value == ASSET_TYPE_COUNT); +GameAssetPoolT6::GameAssetPoolT6(Zone *zone, const int priority) : ZoneAssetPools(zone), m_priority(priority) { + assert(std::extent<decltype(ASSET_TYPE_NAMES)>::value == ASSET_TYPE_COUNT); } -void GameAssetPoolT6::InitPoolStatic(const asset_type_t type, const size_t capacity) -{ -#define CASE_INIT_POOL_STATIC(assetType, poolName, poolType) \ - case assetType: \ - { \ - if((poolName) == nullptr && capacity > 0) \ - { \ - (poolName) = std::make_unique<AssetPoolStatic<poolType>>(capacity, m_priority, (assetType)); \ - } \ - break; \ - } +void GameAssetPoolT6::InitPoolStatic(const asset_type_t type, const size_t capacity) { +#define CASE_INIT_POOL_STATIC(assetType, poolName, poolType) \ + case assetType: { \ + if ((poolName) == nullptr && capacity > 0) { \ + (poolName) = std::make_unique<AssetPoolStatic<poolType>>(capacity, m_priority, (assetType)); \ + } \ + break; \ + } - switch (type) - { + switch (type) { CASE_INIT_POOL_STATIC(ASSET_TYPE_PHYSPRESET, m_phys_preset, PhysPreset); CASE_INIT_POOL_STATIC(ASSET_TYPE_PHYSCONSTRAINTS, m_phys_constraints, PhysConstraints); CASE_INIT_POOL_STATIC(ASSET_TYPE_DESTRUCTIBLEDEF, m_destructible_def, DestructibleDef); @@ -143,28 +133,24 @@ void GameAssetPoolT6::InitPoolStatic(const asset_type_t type, const size_t capac CASE_INIT_POOL_STATIC(ASSET_TYPE_FOOTSTEPFX_TABLE, m_footstep_fx_table, FootstepFXTableDef); CASE_INIT_POOL_STATIC(ASSET_TYPE_ZBARRIER, m_zbarrier, ZBarrierDef); - default: - assert(type >= 0 && type < ASSET_TYPE_COUNT); - break; - } + default: + assert(type >= 0 && type < ASSET_TYPE_COUNT); + break; + } #undef CASE_INIT_POOL_STATIC } -void GameAssetPoolT6::InitPoolDynamic(const asset_type_t type) -{ -#define CASE_INIT_POOL_DYNAMIC(assetType, poolName, poolType) \ - case assetType: \ - { \ - if((poolName) == nullptr) \ - { \ - (poolName) = std::make_unique<AssetPoolDynamic<poolType>>(m_priority, (assetType)); \ - } \ - break; \ - } +void GameAssetPoolT6::InitPoolDynamic(const asset_type_t type) { +#define CASE_INIT_POOL_DYNAMIC(assetType, poolName, poolType) \ + case assetType: { \ + if ((poolName) == nullptr) { \ + (poolName) = std::make_unique<AssetPoolDynamic<poolType>>(m_priority, (assetType)); \ + } \ + break; \ + } - switch (type) - { + switch (type) { CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_PHYSPRESET, m_phys_preset, PhysPreset); CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_PHYSCONSTRAINTS, m_phys_constraints, PhysConstraints); CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_DESTRUCTIBLEDEF, m_destructible_def, DestructibleDef); @@ -215,31 +201,28 @@ void GameAssetPoolT6::InitPoolDynamic(const asset_type_t type) CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_FOOTSTEPFX_TABLE, m_footstep_fx_table, FootstepFXTableDef); CASE_INIT_POOL_DYNAMIC(ASSET_TYPE_ZBARRIER, m_zbarrier, ZBarrierDef); - default: - assert(type >= 0 && type < ASSET_TYPE_COUNT); - break; - } + default: + assert(type >= 0 && type < ASSET_TYPE_COUNT); + break; + } #undef CASE_INIT_POOL_STATIC } -XAssetInfoGeneric* GameAssetPoolT6::AddAssetToPool(asset_type_t type, std::string name, void* asset, std::vector<XAssetInfoGeneric*> dependencies, std::vector<scr_string_t> usedScriptStrings, - Zone* zone) -{ - XAsset xAsset{}; +XAssetInfoGeneric *GameAssetPoolT6::AddAssetToPool(asset_type_t type, std::string name, void *asset, std::vector<XAssetInfoGeneric *> dependencies, + std::vector<scr_string_t> usedScriptStrings, Zone *zone) { + XAsset xAsset{}; - xAsset.type = static_cast<XAssetType>(type); - xAsset.header.data = asset; + xAsset.type = static_cast<XAssetType>(type); + xAsset.header.data = asset; -#define CASE_ADD_TO_POOL(assetType, poolName, headerName) \ - case assetType: \ - { \ - assert((poolName) != nullptr); \ - return (poolName)->AddAsset(std::move(name), xAsset.header.headerName, zone, std::move(dependencies), std::move(usedScriptStrings)); \ - } +#define CASE_ADD_TO_POOL(assetType, poolName, headerName) \ + case assetType: { \ + assert((poolName) != nullptr); \ + return (poolName)->AddAsset(std::move(name), xAsset.header.headerName, zone, std::move(dependencies), std::move(usedScriptStrings)); \ + } - switch (xAsset.type) - { + switch (xAsset.type) { CASE_ADD_TO_POOL(ASSET_TYPE_PHYSPRESET, m_phys_preset, physPreset); CASE_ADD_TO_POOL(ASSET_TYPE_PHYSCONSTRAINTS, m_phys_constraints, physConstraints); CASE_ADD_TO_POOL(ASSET_TYPE_DESTRUCTIBLEDEF, m_destructible_def, destructibleDef); @@ -290,28 +273,25 @@ XAssetInfoGeneric* GameAssetPoolT6::AddAssetToPool(asset_type_t type, std::strin CASE_ADD_TO_POOL(ASSET_TYPE_FOOTSTEPFX_TABLE, m_footstep_fx_table, footstepFXTableDef); CASE_ADD_TO_POOL(ASSET_TYPE_ZBARRIER, m_zbarrier, zbarrierDef); - default: - assert(false); - break; - } + default: + assert(false); + break; + } - return nullptr; + return nullptr; #undef CASE_ADD_TO_POOL } -XAssetInfoGeneric* GameAssetPoolT6::GetAsset(const asset_type_t type, std::string name) const -{ -#define CASE_GET_ASSET(assetType, poolName) \ - case assetType: \ - { \ - if((poolName) != nullptr) \ - return (poolName)->GetAsset(std::move(name)); \ - break; \ - } +XAssetInfoGeneric *GameAssetPoolT6::GetAsset(const asset_type_t type, std::string name) const { +#define CASE_GET_ASSET(assetType, poolName) \ + case assetType: { \ + if ((poolName) != nullptr) \ + return (poolName)->GetAsset(std::move(name)); \ + break; \ + } - switch (type) - { + switch (type) { CASE_GET_ASSET(ASSET_TYPE_PHYSPRESET, m_phys_preset); CASE_GET_ASSET(ASSET_TYPE_PHYSCONSTRAINTS, m_phys_constraints); CASE_GET_ASSET(ASSET_TYPE_DESTRUCTIBLEDEF, m_destructible_def); @@ -362,35 +342,25 @@ XAssetInfoGeneric* GameAssetPoolT6::GetAsset(const asset_type_t type, std::strin CASE_GET_ASSET(ASSET_TYPE_FOOTSTEPFX_TABLE, m_footstep_fx_table); CASE_GET_ASSET(ASSET_TYPE_ZBARRIER, m_zbarrier); - default: - assert(false); - break; - } + default: + assert(false); + break; + } - return nullptr; + return nullptr; #undef CASE_GET_ASSET } -const char* GameAssetPoolT6::AssetTypeNameByType(asset_type_t assetType) -{ - if (assetType >= 0 && assetType < static_cast<int>(std::extent<decltype(ASSET_TYPE_NAMES)>::value)) - return ASSET_TYPE_NAMES[assetType]; +const char *GameAssetPoolT6::AssetTypeNameByType(asset_type_t assetType) { + if (assetType >= 0 && assetType < static_cast<int>(std::extent<decltype(ASSET_TYPE_NAMES)>::value)) + return ASSET_TYPE_NAMES[assetType]; - return ASSET_TYPE_INVALID; + return ASSET_TYPE_INVALID; } -const char* GameAssetPoolT6::GetAssetTypeName(const asset_type_t assetType) const -{ - return AssetTypeNameByType(assetType); -} +const char *GameAssetPoolT6::GetAssetTypeName(const asset_type_t assetType) const { return AssetTypeNameByType(assetType); } -asset_type_t GameAssetPoolT6::AssetTypeCount() -{ - return ASSET_TYPE_COUNT; -} +asset_type_t GameAssetPoolT6::AssetTypeCount() { return ASSET_TYPE_COUNT; } -asset_type_t GameAssetPoolT6::GetAssetTypeCount() const -{ - return AssetTypeCount(); -} +asset_type_t GameAssetPoolT6::GetAssetTypeCount() const { return AssetTypeCount(); } diff --git a/src/ZoneCommon/Game/T6/GameAssetPoolT6.h b/src/ZoneCommon/Game/T6/GameAssetPoolT6.h index 1daddca66..9cb78d4e4 100644 --- a/src/ZoneCommon/Game/T6/GameAssetPoolT6.h +++ b/src/ZoneCommon/Game/T6/GameAssetPoolT6.h @@ -2,81 +2,81 @@ #include <memory> -#include "Pool/ZoneAssetPools.h" -#include "Pool/AssetPool.h" #include "Game/T6/T6.h" +#include "Pool/AssetPool.h" +#include "Pool/ZoneAssetPools.h" -class GameAssetPoolT6 final : public ZoneAssetPools -{ - int m_priority; +class GameAssetPoolT6 final : public ZoneAssetPools { + int m_priority; - static constexpr const char* ASSET_TYPE_INVALID = "invalid_asset_type"; - static const char* ASSET_TYPE_NAMES[]; + static constexpr const char *ASSET_TYPE_INVALID = "invalid_asset_type"; + static const char *ASSET_TYPE_NAMES[]; protected: - XAssetInfoGeneric* AddAssetToPool(asset_type_t type, std::string name, void* asset, std::vector<XAssetInfoGeneric*> dependencies, std::vector<scr_string_t> usedScriptStrings, Zone* zone) override; + XAssetInfoGeneric *AddAssetToPool(asset_type_t type, std::string name, void *asset, std::vector<XAssetInfoGeneric *> dependencies, + std::vector<scr_string_t> usedScriptStrings, Zone *zone) override; public: - std::unique_ptr<AssetPool<T6::PhysPreset>> m_phys_preset; - std::unique_ptr<AssetPool<T6::PhysConstraints>> m_phys_constraints; - std::unique_ptr<AssetPool<T6::DestructibleDef>> m_destructible_def; - std::unique_ptr<AssetPool<T6::XAnimParts>> m_xanim_parts; - std::unique_ptr<AssetPool<T6::XModel>> m_xmodel; - std::unique_ptr<AssetPool<T6::Material>> m_material; - std::unique_ptr<AssetPool<T6::MaterialTechniqueSet>> m_technique_set; - std::unique_ptr<AssetPool<T6::GfxImage>> m_image; - std::unique_ptr<AssetPool<T6::SndBank>> m_sound_bank; - std::unique_ptr<AssetPool<T6::SndPatch>> m_sound_patch; - std::unique_ptr<AssetPool<T6::clipMap_t>> m_clip_map; - std::unique_ptr<AssetPool<T6::ComWorld>> m_com_world; - std::unique_ptr<AssetPool<T6::GameWorldSp>> m_game_world_sp; - std::unique_ptr<AssetPool<T6::GameWorldMp>> m_game_world_mp; - std::unique_ptr<AssetPool<T6::MapEnts>> m_map_ents; - std::unique_ptr<AssetPool<T6::GfxWorld>> m_gfx_world; - std::unique_ptr<AssetPool<T6::GfxLightDef>> m_gfx_light_def; - std::unique_ptr<AssetPool<T6::Font_s>> m_font; - std::unique_ptr<AssetPool<T6::FontIcon>> m_font_icon; - std::unique_ptr<AssetPool<T6::MenuList>> m_menu_list; - std::unique_ptr<AssetPool<T6::menuDef_t>> m_menu_def; - std::unique_ptr<AssetPool<T6::LocalizeEntry>> m_localize; - std::unique_ptr<AssetPool<T6::WeaponVariantDef>> m_weapon; - std::unique_ptr<AssetPool<T6::WeaponAttachment>> m_attachment; - std::unique_ptr<AssetPool<T6::WeaponAttachmentUnique>> m_attachment_unique; - std::unique_ptr<AssetPool<T6::WeaponCamo>> m_camo; - std::unique_ptr<AssetPool<T6::SndDriverGlobals>> m_snd_driver_globals; - std::unique_ptr<AssetPool<T6::FxEffectDef>> m_fx; - std::unique_ptr<AssetPool<T6::FxImpactTable>> m_fx_impact_table; - std::unique_ptr<AssetPool<T6::RawFile>> m_raw_file; - std::unique_ptr<AssetPool<T6::StringTable>> m_string_table; - std::unique_ptr<AssetPool<T6::LeaderboardDef>> m_leaderboard; - std::unique_ptr<AssetPool<T6::XGlobals>> m_xglobals; - std::unique_ptr<AssetPool<T6::ddlRoot_t>> m_ddl; - std::unique_ptr<AssetPool<T6::Glasses>> m_glasses; - std::unique_ptr<AssetPool<T6::EmblemSet>> m_emblem_set; - std::unique_ptr<AssetPool<T6::ScriptParseTree>> m_script; - std::unique_ptr<AssetPool<T6::KeyValuePairs>> m_key_value_pairs; - std::unique_ptr<AssetPool<T6::VehicleDef>> m_vehicle; - std::unique_ptr<AssetPool<T6::MemoryBlock>> m_memory_block; - std::unique_ptr<AssetPool<T6::AddonMapEnts>> m_addon_map_ents; - std::unique_ptr<AssetPool<T6::TracerDef>> m_tracer; - std::unique_ptr<AssetPool<T6::SkinnedVertsDef>> m_skinned_verts; - std::unique_ptr<AssetPool<T6::Qdb>> m_qdb; - std::unique_ptr<AssetPool<T6::Slug>> m_slug; - std::unique_ptr<AssetPool<T6::FootstepTableDef>> m_footstep_table; - std::unique_ptr<AssetPool<T6::FootstepFXTableDef>> m_footstep_fx_table; - std::unique_ptr<AssetPool<T6::ZBarrierDef>> m_zbarrier; + std::unique_ptr<AssetPool<T6::PhysPreset>> m_phys_preset; + std::unique_ptr<AssetPool<T6::PhysConstraints>> m_phys_constraints; + std::unique_ptr<AssetPool<T6::DestructibleDef>> m_destructible_def; + std::unique_ptr<AssetPool<T6::XAnimParts>> m_xanim_parts; + std::unique_ptr<AssetPool<T6::XModel>> m_xmodel; + std::unique_ptr<AssetPool<T6::Material>> m_material; + std::unique_ptr<AssetPool<T6::MaterialTechniqueSet>> m_technique_set; + std::unique_ptr<AssetPool<T6::GfxImage>> m_image; + std::unique_ptr<AssetPool<T6::SndBank>> m_sound_bank; + std::unique_ptr<AssetPool<T6::SndPatch>> m_sound_patch; + std::unique_ptr<AssetPool<T6::clipMap_t>> m_clip_map; + std::unique_ptr<AssetPool<T6::ComWorld>> m_com_world; + std::unique_ptr<AssetPool<T6::GameWorldSp>> m_game_world_sp; + std::unique_ptr<AssetPool<T6::GameWorldMp>> m_game_world_mp; + std::unique_ptr<AssetPool<T6::MapEnts>> m_map_ents; + std::unique_ptr<AssetPool<T6::GfxWorld>> m_gfx_world; + std::unique_ptr<AssetPool<T6::GfxLightDef>> m_gfx_light_def; + std::unique_ptr<AssetPool<T6::Font_s>> m_font; + std::unique_ptr<AssetPool<T6::FontIcon>> m_font_icon; + std::unique_ptr<AssetPool<T6::MenuList>> m_menu_list; + std::unique_ptr<AssetPool<T6::menuDef_t>> m_menu_def; + std::unique_ptr<AssetPool<T6::LocalizeEntry>> m_localize; + std::unique_ptr<AssetPool<T6::WeaponVariantDef>> m_weapon; + std::unique_ptr<AssetPool<T6::WeaponAttachment>> m_attachment; + std::unique_ptr<AssetPool<T6::WeaponAttachmentUnique>> m_attachment_unique; + std::unique_ptr<AssetPool<T6::WeaponCamo>> m_camo; + std::unique_ptr<AssetPool<T6::SndDriverGlobals>> m_snd_driver_globals; + std::unique_ptr<AssetPool<T6::FxEffectDef>> m_fx; + std::unique_ptr<AssetPool<T6::FxImpactTable>> m_fx_impact_table; + std::unique_ptr<AssetPool<T6::RawFile>> m_raw_file; + std::unique_ptr<AssetPool<T6::StringTable>> m_string_table; + std::unique_ptr<AssetPool<T6::LeaderboardDef>> m_leaderboard; + std::unique_ptr<AssetPool<T6::XGlobals>> m_xglobals; + std::unique_ptr<AssetPool<T6::ddlRoot_t>> m_ddl; + std::unique_ptr<AssetPool<T6::Glasses>> m_glasses; + std::unique_ptr<AssetPool<T6::EmblemSet>> m_emblem_set; + std::unique_ptr<AssetPool<T6::ScriptParseTree>> m_script; + std::unique_ptr<AssetPool<T6::KeyValuePairs>> m_key_value_pairs; + std::unique_ptr<AssetPool<T6::VehicleDef>> m_vehicle; + std::unique_ptr<AssetPool<T6::MemoryBlock>> m_memory_block; + std::unique_ptr<AssetPool<T6::AddonMapEnts>> m_addon_map_ents; + std::unique_ptr<AssetPool<T6::TracerDef>> m_tracer; + std::unique_ptr<AssetPool<T6::SkinnedVertsDef>> m_skinned_verts; + std::unique_ptr<AssetPool<T6::Qdb>> m_qdb; + std::unique_ptr<AssetPool<T6::Slug>> m_slug; + std::unique_ptr<AssetPool<T6::FootstepTableDef>> m_footstep_table; + std::unique_ptr<AssetPool<T6::FootstepFXTableDef>> m_footstep_fx_table; + std::unique_ptr<AssetPool<T6::ZBarrierDef>> m_zbarrier; - GameAssetPoolT6(Zone* zone, int priority); - ~GameAssetPoolT6() override = default; + GameAssetPoolT6(Zone *zone, int priority); + ~GameAssetPoolT6() override = default; - void InitPoolStatic(asset_type_t type, size_t capacity) override; - void InitPoolDynamic(asset_type_t type) override; + void InitPoolStatic(asset_type_t type, size_t capacity) override; + void InitPoolDynamic(asset_type_t type) override; - _NODISCARD XAssetInfoGeneric* GetAsset(asset_type_t type, std::string name) const override; + _NODISCARD XAssetInfoGeneric *GetAsset(asset_type_t type, std::string name) const override; - static const char* AssetTypeNameByType(asset_type_t assetType); - _NODISCARD const char* GetAssetTypeName(asset_type_t assetType) const override; + static const char *AssetTypeNameByType(asset_type_t assetType); + _NODISCARD const char *GetAssetTypeName(asset_type_t assetType) const override; - static asset_type_t AssetTypeCount(); - _NODISCARD asset_type_t GetAssetTypeCount() const override; + static asset_type_t AssetTypeCount(); + _NODISCARD asset_type_t GetAssetTypeCount() const override; }; diff --git a/src/ZoneCommon/Game/T6/ZoneConstantsT6.h b/src/ZoneCommon/Game/T6/ZoneConstantsT6.h index 5f66fdbde..4f5a08afb 100644 --- a/src/ZoneCommon/Game/T6/ZoneConstantsT6.h +++ b/src/ZoneCommon/Game/T6/ZoneConstantsT6.h @@ -2,86 +2,50 @@ #include <cstdint> #include <string> -#include "Zone/ZoneTypes.h" #include "Game/T6/T6.h" +#include "Zone/ZoneTypes.h" -namespace T6 -{ - class ZoneConstants final - { - ZoneConstants() = default; - - public: - static constexpr const char* MAGIC_SIGNED_TREYARCH = "TAff0100"; - static constexpr const char* MAGIC_SIGNED_OAT = "ABff0100"; - static constexpr const char* MAGIC_UNSIGNED = "TAffu100"; - static constexpr const char* MAGIC_UNSIGNED_SERVER = "TAsvu100"; - - static_assert(std::char_traits<char>::length(MAGIC_SIGNED_TREYARCH) == sizeof(ZoneHeader::m_magic)); - static_assert(std::char_traits<char>::length(MAGIC_SIGNED_OAT) == sizeof(ZoneHeader::m_magic)); - static_assert(std::char_traits<char>::length(MAGIC_UNSIGNED) == sizeof(ZoneHeader::m_magic)); - static_assert(std::char_traits<char>::length(MAGIC_UNSIGNED_SERVER) == sizeof(ZoneHeader::m_magic)); - - static constexpr int ZONE_VERSION = 147; - static constexpr int STREAM_COUNT = 4; - static constexpr int XCHUNK_SIZE = 0x8000; - static constexpr int XCHUNK_MAX_WRITE_SIZE = XCHUNK_SIZE - 0x40; - static constexpr int VANILLA_BUFFER_SIZE = 0x80000; - static constexpr int OFFSET_BLOCK_BIT_COUNT = 3; - static constexpr block_t INSERT_BLOCK = XFILE_BLOCK_VIRTUAL; - - static constexpr size_t FILE_SUFFIX_ZERO_MIN_SIZE = 0x40; - static constexpr size_t FILE_SUFFIX_ZERO_ALIGN = 0x40; - - static constexpr const char* MAGIC_AUTH_HEADER = "PHEEBs71"; - inline static const uint8_t SALSA20_KEY_TREYARCH[] - { - 0x64, 0x1D, 0x8A, 0x2F, - 0xE3, 0x1D, 0x3A, 0xA6, - 0x36, 0x22, 0xBB, 0xC9, - 0xCE, 0x85, 0x87, 0x22, - 0x9D, 0x42, 0xB0, 0xF8, - 0xED, 0x9B, 0x92, 0x41, - 0x30, 0xBF, 0x88, 0xB6, - 0x5E, 0xDC, 0x50, 0xBE - }; - - inline static const uint8_t RSA_PUBLIC_KEY_TREYARCH[] - { - 0x30, 0x82, 0x01, 0x0a, 0x02, 0x82, 0x01, 0x01, - 0x00, 0xc7, 0x9d, 0x33, 0xe0, 0x75, 0xaf, 0xef, - 0x08, 0x08, 0x2b, 0x89, 0xd9, 0x3b, 0xf3, 0xd5, - 0x9a, 0x65, 0xa6, 0xde, 0x3b, 0x1e, 0x20, 0xde, - 0x59, 0x19, 0x43, 0x88, 0x1a, 0x8b, 0x39, 0x13, - 0x60, 0x12, 0xd3, 0xb2, 0x77, 0x6d, 0xe1, 0x99, - 0x75, 0x24, 0xb4, 0x0d, 0x8c, 0xb7, 0x84, 0xf2, - 0x48, 0x8f, 0xd5, 0x4c, 0xb7, 0x64, 0x44, 0xa3, - 0xa8, 0x4a, 0xac, 0x2d, 0x54, 0x15, 0x2b, 0x1f, - 0xb3, 0xf4, 0x4c, 0x16, 0xa0, 0x92, 0x8e, 0xd2, - 0xfa, 0xcc, 0x11, 0x6a, 0x74, 0x6a, 0x70, 0xb8, - 0xd3, 0x34, 0x6b, 0x39, 0xc6, 0x2a, 0x69, 0xde, - 0x31, 0x34, 0xdf, 0xe7, 0x8b, 0x7e, 0x17, 0xa3, - 0x17, 0xd9, 0x5e, 0x88, 0x39, 0x21, 0xf8, 0x7d, - 0x3c, 0x29, 0x21, 0x6c, 0x0e, 0xf1, 0xb4, 0x09, - 0x54, 0xe8, 0x20, 0x34, 0x90, 0x2e, 0xb4, 0x1a, - 0x95, 0x95, 0x90, 0xe5, 0xfb, 0xce, 0xfe, 0x8a, - 0xbf, 0xea, 0xaf, 0x09, 0x0c, 0x0b, 0x87, 0x22, - 0xe1, 0xfe, 0x82, 0x6e, 0x91, 0xe8, 0xd1, 0xb6, - 0x35, 0x03, 0x4f, 0xdb, 0xc1, 0x31, 0xe2, 0xba, - 0xa0, 0x13, 0xf6, 0xdb, 0x07, 0x9b, 0xcb, 0x99, - 0xce, 0x9f, 0x49, 0xc4, 0x51, 0x8e, 0xf1, 0x04, - 0x9b, 0x30, 0xc3, 0x02, 0xff, 0x7b, 0x94, 0xca, - 0x12, 0x69, 0x1e, 0xdb, 0x2d, 0x3e, 0xbd, 0x48, - 0x16, 0xe1, 0x72, 0x37, 0xb8, 0x5f, 0x61, 0xfa, - 0x24, 0x16, 0x3a, 0xde, 0xbf, 0x6a, 0x71, 0x62, - 0x32, 0xf3, 0xaa, 0x7f, 0x28, 0x3a, 0x0c, 0x27, - 0xeb, 0xa9, 0x0a, 0x4c, 0x79, 0x88, 0x84, 0xb3, - 0xe2, 0x52, 0xb9, 0x68, 0x1e, 0x82, 0xcf, 0x67, - 0x43, 0xf3, 0x68, 0xf7, 0x26, 0x19, 0xaa, 0xdd, - 0x3f, 0x1e, 0xc6, 0x46, 0x11, 0x9f, 0x24, 0x23, - 0xa7, 0xb0, 0x1b, 0x79, 0xa7, 0x0c, 0x5a, 0xfe, - 0x96, 0xf7, 0xe7, 0x88, 0x09, 0xa6, 0x69, 0xe3, - 0x8b, 0x02, 0x03, 0x01, 0x00, 0x01 - }; - }; -} \ No newline at end of file +namespace T6 { +class ZoneConstants final { + ZoneConstants() = default; + +public: + static constexpr const char *MAGIC_SIGNED_TREYARCH = "TAff0100"; + static constexpr const char *MAGIC_SIGNED_OAT = "ABff0100"; + static constexpr const char *MAGIC_UNSIGNED = "TAffu100"; + static constexpr const char *MAGIC_UNSIGNED_SERVER = "TAsvu100"; + + static_assert(std::char_traits<char>::length(MAGIC_SIGNED_TREYARCH) == sizeof(ZoneHeader::m_magic)); + static_assert(std::char_traits<char>::length(MAGIC_SIGNED_OAT) == sizeof(ZoneHeader::m_magic)); + static_assert(std::char_traits<char>::length(MAGIC_UNSIGNED) == sizeof(ZoneHeader::m_magic)); + static_assert(std::char_traits<char>::length(MAGIC_UNSIGNED_SERVER) == sizeof(ZoneHeader::m_magic)); + + static constexpr int ZONE_VERSION = 147; + static constexpr int STREAM_COUNT = 4; + static constexpr int XCHUNK_SIZE = 0x8000; + static constexpr int XCHUNK_MAX_WRITE_SIZE = XCHUNK_SIZE - 0x40; + static constexpr int VANILLA_BUFFER_SIZE = 0x80000; + static constexpr int OFFSET_BLOCK_BIT_COUNT = 3; + static constexpr block_t INSERT_BLOCK = XFILE_BLOCK_VIRTUAL; + + static constexpr size_t FILE_SUFFIX_ZERO_MIN_SIZE = 0x40; + static constexpr size_t FILE_SUFFIX_ZERO_ALIGN = 0x40; + + static constexpr const char *MAGIC_AUTH_HEADER = "PHEEBs71"; + inline static const uint8_t SALSA20_KEY_TREYARCH[]{0x64, 0x1D, 0x8A, 0x2F, 0xE3, 0x1D, 0x3A, 0xA6, 0x36, 0x22, 0xBB, 0xC9, 0xCE, 0x85, 0x87, 0x22, + 0x9D, 0x42, 0xB0, 0xF8, 0xED, 0x9B, 0x92, 0x41, 0x30, 0xBF, 0x88, 0xB6, 0x5E, 0xDC, 0x50, 0xBE}; + + inline static const uint8_t RSA_PUBLIC_KEY_TREYARCH[]{ + 0x30, 0x82, 0x01, 0x0a, 0x02, 0x82, 0x01, 0x01, 0x00, 0xc7, 0x9d, 0x33, 0xe0, 0x75, 0xaf, 0xef, 0x08, 0x08, 0x2b, 0x89, 0xd9, 0x3b, 0xf3, 0xd5, 0x9a, + 0x65, 0xa6, 0xde, 0x3b, 0x1e, 0x20, 0xde, 0x59, 0x19, 0x43, 0x88, 0x1a, 0x8b, 0x39, 0x13, 0x60, 0x12, 0xd3, 0xb2, 0x77, 0x6d, 0xe1, 0x99, 0x75, 0x24, + 0xb4, 0x0d, 0x8c, 0xb7, 0x84, 0xf2, 0x48, 0x8f, 0xd5, 0x4c, 0xb7, 0x64, 0x44, 0xa3, 0xa8, 0x4a, 0xac, 0x2d, 0x54, 0x15, 0x2b, 0x1f, 0xb3, 0xf4, 0x4c, + 0x16, 0xa0, 0x92, 0x8e, 0xd2, 0xfa, 0xcc, 0x11, 0x6a, 0x74, 0x6a, 0x70, 0xb8, 0xd3, 0x34, 0x6b, 0x39, 0xc6, 0x2a, 0x69, 0xde, 0x31, 0x34, 0xdf, 0xe7, + 0x8b, 0x7e, 0x17, 0xa3, 0x17, 0xd9, 0x5e, 0x88, 0x39, 0x21, 0xf8, 0x7d, 0x3c, 0x29, 0x21, 0x6c, 0x0e, 0xf1, 0xb4, 0x09, 0x54, 0xe8, 0x20, 0x34, 0x90, + 0x2e, 0xb4, 0x1a, 0x95, 0x95, 0x90, 0xe5, 0xfb, 0xce, 0xfe, 0x8a, 0xbf, 0xea, 0xaf, 0x09, 0x0c, 0x0b, 0x87, 0x22, 0xe1, 0xfe, 0x82, 0x6e, 0x91, 0xe8, + 0xd1, 0xb6, 0x35, 0x03, 0x4f, 0xdb, 0xc1, 0x31, 0xe2, 0xba, 0xa0, 0x13, 0xf6, 0xdb, 0x07, 0x9b, 0xcb, 0x99, 0xce, 0x9f, 0x49, 0xc4, 0x51, 0x8e, 0xf1, + 0x04, 0x9b, 0x30, 0xc3, 0x02, 0xff, 0x7b, 0x94, 0xca, 0x12, 0x69, 0x1e, 0xdb, 0x2d, 0x3e, 0xbd, 0x48, 0x16, 0xe1, 0x72, 0x37, 0xb8, 0x5f, 0x61, 0xfa, + 0x24, 0x16, 0x3a, 0xde, 0xbf, 0x6a, 0x71, 0x62, 0x32, 0xf3, 0xaa, 0x7f, 0x28, 0x3a, 0x0c, 0x27, 0xeb, 0xa9, 0x0a, 0x4c, 0x79, 0x88, 0x84, 0xb3, 0xe2, + 0x52, 0xb9, 0x68, 0x1e, 0x82, 0xcf, 0x67, 0x43, 0xf3, 0x68, 0xf7, 0x26, 0x19, 0xaa, 0xdd, 0x3f, 0x1e, 0xc6, 0x46, 0x11, 0x9f, 0x24, 0x23, 0xa7, 0xb0, + 0x1b, 0x79, 0xa7, 0x0c, 0x5a, 0xfe, 0x96, 0xf7, 0xe7, 0x88, 0x09, 0xa6, 0x69, 0xe3, 0x8b, 0x02, 0x03, 0x01, 0x00, 0x01}; +}; +} // namespace T6 \ No newline at end of file diff --git a/src/ZoneCommon/Parsing/ZoneDefinition/Matcher/ZoneDefinitionMatcherCharacter.cpp b/src/ZoneCommon/Parsing/ZoneDefinition/Matcher/ZoneDefinitionMatcherCharacter.cpp index f3734ab60..2d23eee8a 100644 --- a/src/ZoneCommon/Parsing/ZoneDefinition/Matcher/ZoneDefinitionMatcherCharacter.cpp +++ b/src/ZoneCommon/Parsing/ZoneDefinition/Matcher/ZoneDefinitionMatcherCharacter.cpp @@ -1,14 +1,9 @@ #include "ZoneDefinitionMatcherCharacter.h" -ZoneDefinitionMatcherCharacter::ZoneDefinitionMatcherCharacter(const char c) - : m_char(c) -{ -} +ZoneDefinitionMatcherCharacter::ZoneDefinitionMatcherCharacter(const char c) : m_char(c) {} -MatcherResult<ZoneDefinitionParserValue> ZoneDefinitionMatcherCharacter::CanMatch(ILexer<ZoneDefinitionParserValue>* lexer, const unsigned tokenOffset) -{ - const auto& token = lexer->GetToken(tokenOffset); - return token.m_type == ZoneDefinitionParserValueType::CHARACTER && token.CharacterValue() == m_char - ? MatcherResult<ZoneDefinitionParserValue>::Match(1) - : MatcherResult<ZoneDefinitionParserValue>::NoMatch(); +MatcherResult<ZoneDefinitionParserValue> ZoneDefinitionMatcherCharacter::CanMatch(ILexer<ZoneDefinitionParserValue> *lexer, const unsigned tokenOffset) { + const auto &token = lexer->GetToken(tokenOffset); + return token.m_type == ZoneDefinitionParserValueType::CHARACTER && token.CharacterValue() == m_char ? MatcherResult<ZoneDefinitionParserValue>::Match(1) + : MatcherResult<ZoneDefinitionParserValue>::NoMatch(); } diff --git a/src/ZoneCommon/Parsing/ZoneDefinition/Matcher/ZoneDefinitionMatcherCharacter.h b/src/ZoneCommon/Parsing/ZoneDefinition/Matcher/ZoneDefinitionMatcherCharacter.h index 9cb0fc68f..226c63015 100644 --- a/src/ZoneCommon/Parsing/ZoneDefinition/Matcher/ZoneDefinitionMatcherCharacter.h +++ b/src/ZoneCommon/Parsing/ZoneDefinition/Matcher/ZoneDefinitionMatcherCharacter.h @@ -3,13 +3,12 @@ #include "Parsing/Matcher/AbstractMatcher.h" #include "Parsing/ZoneDefinition/ZoneDefinitionParserValue.h" -class ZoneDefinitionMatcherCharacter final : public AbstractMatcher<ZoneDefinitionParserValue> -{ - char m_char; +class ZoneDefinitionMatcherCharacter final : public AbstractMatcher<ZoneDefinitionParserValue> { + char m_char; protected: - MatcherResult<ZoneDefinitionParserValue> CanMatch(ILexer<ZoneDefinitionParserValue>* lexer, unsigned tokenOffset) override; + MatcherResult<ZoneDefinitionParserValue> CanMatch(ILexer<ZoneDefinitionParserValue> *lexer, unsigned tokenOffset) override; public: - explicit ZoneDefinitionMatcherCharacter(char c); + explicit ZoneDefinitionMatcherCharacter(char c); }; diff --git a/src/ZoneCommon/Parsing/ZoneDefinition/Matcher/ZoneDefinitionMatcherFactory.cpp b/src/ZoneCommon/Parsing/ZoneDefinition/Matcher/ZoneDefinitionMatcherFactory.cpp index 4b6acb0d9..de11d928d 100644 --- a/src/ZoneCommon/Parsing/ZoneDefinition/Matcher/ZoneDefinitionMatcherFactory.cpp +++ b/src/ZoneCommon/Parsing/ZoneDefinition/Matcher/ZoneDefinitionMatcherFactory.cpp @@ -4,32 +4,25 @@ #include "ZoneDefinitionMatcherKeyword.h" #include "ZoneDefinitionMatcherValueType.h" -ZoneDefinitionMatcherFactory::ZoneDefinitionMatcherFactory(const IMatcherForLabelSupplier<ZoneDefinitionParserValue>* labelSupplier) - : AbstractMatcherFactory(labelSupplier) -{ -} +ZoneDefinitionMatcherFactory::ZoneDefinitionMatcherFactory(const IMatcherForLabelSupplier<ZoneDefinitionParserValue> *labelSupplier) + : AbstractMatcherFactory(labelSupplier) {} -MatcherFactoryWrapper<ZoneDefinitionParserValue> ZoneDefinitionMatcherFactory::Type(ZoneDefinitionParserValueType type) const -{ - return MatcherFactoryWrapper<ZoneDefinitionParserValue>(std::make_unique<ZoneDefinitionMatcherValueType>(type)); +MatcherFactoryWrapper<ZoneDefinitionParserValue> ZoneDefinitionMatcherFactory::Type(ZoneDefinitionParserValueType type) const { + return MatcherFactoryWrapper<ZoneDefinitionParserValue>(std::make_unique<ZoneDefinitionMatcherValueType>(type)); } -MatcherFactoryWrapper<ZoneDefinitionParserValue> ZoneDefinitionMatcherFactory::Keyword(std::string keyword) const -{ - return MatcherFactoryWrapper<ZoneDefinitionParserValue>(std::make_unique<ZoneDefinitionMatcherKeyword>(std::move(keyword))); +MatcherFactoryWrapper<ZoneDefinitionParserValue> ZoneDefinitionMatcherFactory::Keyword(std::string keyword) const { + return MatcherFactoryWrapper<ZoneDefinitionParserValue>(std::make_unique<ZoneDefinitionMatcherKeyword>(std::move(keyword))); } -MatcherFactoryWrapper<ZoneDefinitionParserValue> ZoneDefinitionMatcherFactory::Field() const -{ - return MatcherFactoryWrapper<ZoneDefinitionParserValue>(std::make_unique<ZoneDefinitionMatcherValueType>(ZoneDefinitionParserValueType::FIELD)); +MatcherFactoryWrapper<ZoneDefinitionParserValue> ZoneDefinitionMatcherFactory::Field() const { + return MatcherFactoryWrapper<ZoneDefinitionParserValue>(std::make_unique<ZoneDefinitionMatcherValueType>(ZoneDefinitionParserValueType::FIELD)); } -MatcherFactoryWrapper<ZoneDefinitionParserValue> ZoneDefinitionMatcherFactory::String() const -{ - return MatcherFactoryWrapper<ZoneDefinitionParserValue>(std::make_unique<ZoneDefinitionMatcherValueType>(ZoneDefinitionParserValueType::STRING)); +MatcherFactoryWrapper<ZoneDefinitionParserValue> ZoneDefinitionMatcherFactory::String() const { + return MatcherFactoryWrapper<ZoneDefinitionParserValue>(std::make_unique<ZoneDefinitionMatcherValueType>(ZoneDefinitionParserValueType::STRING)); } -MatcherFactoryWrapper<ZoneDefinitionParserValue> ZoneDefinitionMatcherFactory::Char(char c) const -{ - return MatcherFactoryWrapper<ZoneDefinitionParserValue>(std::make_unique<ZoneDefinitionMatcherCharacter>(c)); +MatcherFactoryWrapper<ZoneDefinitionParserValue> ZoneDefinitionMatcherFactory::Char(char c) const { + return MatcherFactoryWrapper<ZoneDefinitionParserValue>(std::make_unique<ZoneDefinitionMatcherCharacter>(c)); } diff --git a/src/ZoneCommon/Parsing/ZoneDefinition/Matcher/ZoneDefinitionMatcherFactory.h b/src/ZoneCommon/Parsing/ZoneDefinition/Matcher/ZoneDefinitionMatcherFactory.h index 9059cb491..ab79c0f64 100644 --- a/src/ZoneCommon/Parsing/ZoneDefinition/Matcher/ZoneDefinitionMatcherFactory.h +++ b/src/ZoneCommon/Parsing/ZoneDefinition/Matcher/ZoneDefinitionMatcherFactory.h @@ -2,17 +2,16 @@ #include <string> -#include "Parsing/ZoneDefinition/ZoneDefinitionParserValue.h" #include "Parsing/Matcher/AbstractMatcherFactory.h" +#include "Parsing/ZoneDefinition/ZoneDefinitionParserValue.h" -class ZoneDefinitionMatcherFactory final : public AbstractMatcherFactory<ZoneDefinitionParserValue> -{ +class ZoneDefinitionMatcherFactory final : public AbstractMatcherFactory<ZoneDefinitionParserValue> { public: - explicit ZoneDefinitionMatcherFactory(const IMatcherForLabelSupplier<ZoneDefinitionParserValue>* labelSupplier); + explicit ZoneDefinitionMatcherFactory(const IMatcherForLabelSupplier<ZoneDefinitionParserValue> *labelSupplier); - _NODISCARD MatcherFactoryWrapper<ZoneDefinitionParserValue> Type(ZoneDefinitionParserValueType type) const; - _NODISCARD MatcherFactoryWrapper<ZoneDefinitionParserValue> Keyword(std::string keyword) const; - _NODISCARD MatcherFactoryWrapper<ZoneDefinitionParserValue> Field() const; - _NODISCARD MatcherFactoryWrapper<ZoneDefinitionParserValue> String() const; - _NODISCARD MatcherFactoryWrapper<ZoneDefinitionParserValue> Char(char c) const; + _NODISCARD MatcherFactoryWrapper<ZoneDefinitionParserValue> Type(ZoneDefinitionParserValueType type) const; + _NODISCARD MatcherFactoryWrapper<ZoneDefinitionParserValue> Keyword(std::string keyword) const; + _NODISCARD MatcherFactoryWrapper<ZoneDefinitionParserValue> Field() const; + _NODISCARD MatcherFactoryWrapper<ZoneDefinitionParserValue> String() const; + _NODISCARD MatcherFactoryWrapper<ZoneDefinitionParserValue> Char(char c) const; }; diff --git a/src/ZoneCommon/Parsing/ZoneDefinition/Matcher/ZoneDefinitionMatcherKeyword.cpp b/src/ZoneCommon/Parsing/ZoneDefinition/Matcher/ZoneDefinitionMatcherKeyword.cpp index ae787fcaa..22952a604 100644 --- a/src/ZoneCommon/Parsing/ZoneDefinition/Matcher/ZoneDefinitionMatcherKeyword.cpp +++ b/src/ZoneCommon/Parsing/ZoneDefinition/Matcher/ZoneDefinitionMatcherKeyword.cpp @@ -1,16 +1,13 @@ #include "ZoneDefinitionMatcherKeyword.h" -ZoneDefinitionMatcherKeyword::ZoneDefinitionMatcherKeyword(std::string value) - : m_value(std::move(value)) -{ - const std::hash<std::string> hash; - m_hash = hash(m_value); +ZoneDefinitionMatcherKeyword::ZoneDefinitionMatcherKeyword(std::string value) : m_value(std::move(value)) { + const std::hash<std::string> hash; + m_hash = hash(m_value); } -MatcherResult<ZoneDefinitionParserValue> ZoneDefinitionMatcherKeyword::CanMatch(ILexer<ZoneDefinitionParserValue>* lexer, const unsigned tokenOffset) -{ - const auto& token = lexer->GetToken(tokenOffset); - return token.m_type == ZoneDefinitionParserValueType::FIELD && token.FieldHash() == m_hash && token.FieldValue() == m_value - ? MatcherResult<ZoneDefinitionParserValue>::Match(1) - : MatcherResult<ZoneDefinitionParserValue>::NoMatch(); +MatcherResult<ZoneDefinitionParserValue> ZoneDefinitionMatcherKeyword::CanMatch(ILexer<ZoneDefinitionParserValue> *lexer, const unsigned tokenOffset) { + const auto &token = lexer->GetToken(tokenOffset); + return token.m_type == ZoneDefinitionParserValueType::FIELD && token.FieldHash() == m_hash && token.FieldValue() == m_value + ? MatcherResult<ZoneDefinitionParserValue>::Match(1) + : MatcherResult<ZoneDefinitionParserValue>::NoMatch(); } diff --git a/src/ZoneCommon/Parsing/ZoneDefinition/Matcher/ZoneDefinitionMatcherKeyword.h b/src/ZoneCommon/Parsing/ZoneDefinition/Matcher/ZoneDefinitionMatcherKeyword.h index a643af45e..19c95b191 100644 --- a/src/ZoneCommon/Parsing/ZoneDefinition/Matcher/ZoneDefinitionMatcherKeyword.h +++ b/src/ZoneCommon/Parsing/ZoneDefinition/Matcher/ZoneDefinitionMatcherKeyword.h @@ -2,17 +2,16 @@ #include <string> -#include "Parsing/ZoneDefinition/ZoneDefinitionParserValue.h" #include "Parsing/Matcher/AbstractMatcher.h" +#include "Parsing/ZoneDefinition/ZoneDefinitionParserValue.h" -class ZoneDefinitionMatcherKeyword final : public AbstractMatcher<ZoneDefinitionParserValue> -{ - size_t m_hash; - std::string m_value; +class ZoneDefinitionMatcherKeyword final : public AbstractMatcher<ZoneDefinitionParserValue> { + size_t m_hash; + std::string m_value; protected: - MatcherResult<ZoneDefinitionParserValue> CanMatch(ILexer<ZoneDefinitionParserValue>* lexer, unsigned tokenOffset) override; + MatcherResult<ZoneDefinitionParserValue> CanMatch(ILexer<ZoneDefinitionParserValue> *lexer, unsigned tokenOffset) override; public: - explicit ZoneDefinitionMatcherKeyword(std::string value); + explicit ZoneDefinitionMatcherKeyword(std::string value); }; diff --git a/src/ZoneCommon/Parsing/ZoneDefinition/Matcher/ZoneDefinitionMatcherValueType.cpp b/src/ZoneCommon/Parsing/ZoneDefinition/Matcher/ZoneDefinitionMatcherValueType.cpp index d2fd51ab6..05d8de273 100644 --- a/src/ZoneCommon/Parsing/ZoneDefinition/Matcher/ZoneDefinitionMatcherValueType.cpp +++ b/src/ZoneCommon/Parsing/ZoneDefinition/Matcher/ZoneDefinitionMatcherValueType.cpp @@ -1,13 +1,8 @@ #include "ZoneDefinitionMatcherValueType.h" -ZoneDefinitionMatcherValueType::ZoneDefinitionMatcherValueType(const ZoneDefinitionParserValueType type) - : m_type(type) -{ -} +ZoneDefinitionMatcherValueType::ZoneDefinitionMatcherValueType(const ZoneDefinitionParserValueType type) : m_type(type) {} -MatcherResult<ZoneDefinitionParserValue> ZoneDefinitionMatcherValueType::CanMatch(ILexer<ZoneDefinitionParserValue>* lexer, const unsigned tokenOffset) -{ - return lexer->GetToken(tokenOffset).m_type == m_type - ? MatcherResult<ZoneDefinitionParserValue>::Match(1) - : MatcherResult<ZoneDefinitionParserValue>::NoMatch(); +MatcherResult<ZoneDefinitionParserValue> ZoneDefinitionMatcherValueType::CanMatch(ILexer<ZoneDefinitionParserValue> *lexer, const unsigned tokenOffset) { + return lexer->GetToken(tokenOffset).m_type == m_type ? MatcherResult<ZoneDefinitionParserValue>::Match(1) + : MatcherResult<ZoneDefinitionParserValue>::NoMatch(); } diff --git a/src/ZoneCommon/Parsing/ZoneDefinition/Matcher/ZoneDefinitionMatcherValueType.h b/src/ZoneCommon/Parsing/ZoneDefinition/Matcher/ZoneDefinitionMatcherValueType.h index 1749a389f..50036df43 100644 --- a/src/ZoneCommon/Parsing/ZoneDefinition/Matcher/ZoneDefinitionMatcherValueType.h +++ b/src/ZoneCommon/Parsing/ZoneDefinition/Matcher/ZoneDefinitionMatcherValueType.h @@ -1,15 +1,14 @@ #pragma once -#include "Parsing/ZoneDefinition/ZoneDefinitionParserValue.h" #include "Parsing/Matcher/AbstractMatcher.h" +#include "Parsing/ZoneDefinition/ZoneDefinitionParserValue.h" -class ZoneDefinitionMatcherValueType final : public AbstractMatcher<ZoneDefinitionParserValue> -{ - ZoneDefinitionParserValueType m_type; +class ZoneDefinitionMatcherValueType final : public AbstractMatcher<ZoneDefinitionParserValue> { + ZoneDefinitionParserValueType m_type; protected: - MatcherResult<ZoneDefinitionParserValue> CanMatch(ILexer<ZoneDefinitionParserValue>* lexer, unsigned tokenOffset) override; + MatcherResult<ZoneDefinitionParserValue> CanMatch(ILexer<ZoneDefinitionParserValue> *lexer, unsigned tokenOffset) override; public: - explicit ZoneDefinitionMatcherValueType(ZoneDefinitionParserValueType type); + explicit ZoneDefinitionMatcherValueType(ZoneDefinitionParserValueType type); }; diff --git a/src/ZoneCommon/Parsing/ZoneDefinition/Sequence/SequenceZoneDefinitionEntry.cpp b/src/ZoneCommon/Parsing/ZoneDefinition/Sequence/SequenceZoneDefinitionEntry.cpp index 1e1c402ea..1c9439526 100644 --- a/src/ZoneCommon/Parsing/ZoneDefinition/Sequence/SequenceZoneDefinitionEntry.cpp +++ b/src/ZoneCommon/Parsing/ZoneDefinition/Sequence/SequenceZoneDefinitionEntry.cpp @@ -2,37 +2,22 @@ #include "Parsing/ZoneDefinition/Matcher/ZoneDefinitionMatcherFactory.h" -SequenceZoneDefinitionEntry::SequenceZoneDefinitionEntry() -{ - const ZoneDefinitionMatcherFactory create(this); - - AddMatchers({ - create.Field().Capture(CAPTURE_TYPE_NAME), - create.Char(','), - create.Optional(create.Char(',').Tag(TAG_REFERENCE)), - create.Or({ - create.String(), - create.Field() - }).Capture(CAPTURE_ASSET_NAME) - }); +SequenceZoneDefinitionEntry::SequenceZoneDefinitionEntry() { + const ZoneDefinitionMatcherFactory create(this); + + AddMatchers({create.Field().Capture(CAPTURE_TYPE_NAME), create.Char(','), create.Optional(create.Char(',').Tag(TAG_REFERENCE)), + create.Or({create.String(), create.Field()}).Capture(CAPTURE_ASSET_NAME)}); } -void SequenceZoneDefinitionEntry::ProcessMatch(ZoneDefinition* state, SequenceResult<ZoneDefinitionParserValue>& result) const -{ - const auto& assetNameCapture = result.NextCapture(CAPTURE_ASSET_NAME); +void SequenceZoneDefinitionEntry::ProcessMatch(ZoneDefinition *state, SequenceResult<ZoneDefinitionParserValue> &result) const { + const auto &assetNameCapture = result.NextCapture(CAPTURE_ASSET_NAME); - std::string assetName; - if (assetNameCapture.m_type == ZoneDefinitionParserValueType::STRING) - { - assetName = assetNameCapture.StringValue(); - } - else - { - assetName = assetNameCapture.FieldValue(); - } + std::string assetName; + if (assetNameCapture.m_type == ZoneDefinitionParserValueType::STRING) { + assetName = assetNameCapture.StringValue(); + } else { + assetName = assetNameCapture.FieldValue(); + } - state->m_assets.emplace_back( - result.NextCapture(CAPTURE_TYPE_NAME).FieldValue(), - assetName, - result.NextTag() == TAG_REFERENCE); + state->m_assets.emplace_back(result.NextCapture(CAPTURE_TYPE_NAME).FieldValue(), assetName, result.NextTag() == TAG_REFERENCE); } diff --git a/src/ZoneCommon/Parsing/ZoneDefinition/Sequence/SequenceZoneDefinitionEntry.h b/src/ZoneCommon/Parsing/ZoneDefinition/Sequence/SequenceZoneDefinitionEntry.h index e9a6c44f5..593ff0003 100644 --- a/src/ZoneCommon/Parsing/ZoneDefinition/Sequence/SequenceZoneDefinitionEntry.h +++ b/src/ZoneCommon/Parsing/ZoneDefinition/Sequence/SequenceZoneDefinitionEntry.h @@ -2,16 +2,15 @@ #include "Parsing/ZoneDefinition/ZoneDefinitionParser.h" -class SequenceZoneDefinitionEntry final : public ZoneDefinitionParser::sequence_t -{ - static constexpr auto TAG_REFERENCE = 1; +class SequenceZoneDefinitionEntry final : public ZoneDefinitionParser::sequence_t { + static constexpr auto TAG_REFERENCE = 1; - static constexpr auto CAPTURE_TYPE_NAME = 1; - static constexpr auto CAPTURE_ASSET_NAME = 2; + static constexpr auto CAPTURE_TYPE_NAME = 1; + static constexpr auto CAPTURE_ASSET_NAME = 2; protected: - void ProcessMatch(ZoneDefinition* state, SequenceResult<ZoneDefinitionParserValue>& result) const override; + void ProcessMatch(ZoneDefinition *state, SequenceResult<ZoneDefinitionParserValue> &result) const override; public: - SequenceZoneDefinitionEntry(); + SequenceZoneDefinitionEntry(); }; diff --git a/src/ZoneCommon/Parsing/ZoneDefinition/Sequence/SequenceZoneDefinitionIgnore.cpp b/src/ZoneCommon/Parsing/ZoneDefinition/Sequence/SequenceZoneDefinitionIgnore.cpp index c08144575..85a6cf122 100644 --- a/src/ZoneCommon/Parsing/ZoneDefinition/Sequence/SequenceZoneDefinitionIgnore.cpp +++ b/src/ZoneCommon/Parsing/ZoneDefinition/Sequence/SequenceZoneDefinitionIgnore.cpp @@ -2,18 +2,12 @@ #include "Parsing/ZoneDefinition/Matcher/ZoneDefinitionMatcherFactory.h" -SequenceZoneDefinitionIgnore::SequenceZoneDefinitionIgnore() -{ - const ZoneDefinitionMatcherFactory create(this); +SequenceZoneDefinitionIgnore::SequenceZoneDefinitionIgnore() { + const ZoneDefinitionMatcherFactory create(this); - AddMatchers({ - create.Keyword("ignore"), - create.Char(','), - create.Field().Capture(CAPTURE_IGNORE_NAME) - }); + AddMatchers({create.Keyword("ignore"), create.Char(','), create.Field().Capture(CAPTURE_IGNORE_NAME)}); } -void SequenceZoneDefinitionIgnore::ProcessMatch(ZoneDefinition* state, SequenceResult<ZoneDefinitionParserValue>& result) const -{ - state->m_ignores.emplace_back(result.NextCapture(CAPTURE_IGNORE_NAME).FieldValue()); +void SequenceZoneDefinitionIgnore::ProcessMatch(ZoneDefinition *state, SequenceResult<ZoneDefinitionParserValue> &result) const { + state->m_ignores.emplace_back(result.NextCapture(CAPTURE_IGNORE_NAME).FieldValue()); } diff --git a/src/ZoneCommon/Parsing/ZoneDefinition/Sequence/SequenceZoneDefinitionIgnore.h b/src/ZoneCommon/Parsing/ZoneDefinition/Sequence/SequenceZoneDefinitionIgnore.h index 9b2587873..bad2dcb3d 100644 --- a/src/ZoneCommon/Parsing/ZoneDefinition/Sequence/SequenceZoneDefinitionIgnore.h +++ b/src/ZoneCommon/Parsing/ZoneDefinition/Sequence/SequenceZoneDefinitionIgnore.h @@ -2,13 +2,12 @@ #include "Parsing/ZoneDefinition/ZoneDefinitionParser.h" -class SequenceZoneDefinitionIgnore final : public ZoneDefinitionParser::sequence_t -{ - static constexpr auto CAPTURE_IGNORE_NAME = 1; +class SequenceZoneDefinitionIgnore final : public ZoneDefinitionParser::sequence_t { + static constexpr auto CAPTURE_IGNORE_NAME = 1; protected: - void ProcessMatch(ZoneDefinition* state, SequenceResult<ZoneDefinitionParserValue>& result) const override; + void ProcessMatch(ZoneDefinition *state, SequenceResult<ZoneDefinitionParserValue> &result) const override; public: - SequenceZoneDefinitionIgnore(); + SequenceZoneDefinitionIgnore(); }; diff --git a/src/ZoneCommon/Parsing/ZoneDefinition/Sequence/SequenceZoneDefinitionInclude.cpp b/src/ZoneCommon/Parsing/ZoneDefinition/Sequence/SequenceZoneDefinitionInclude.cpp index c76134195..537293ef4 100644 --- a/src/ZoneCommon/Parsing/ZoneDefinition/Sequence/SequenceZoneDefinitionInclude.cpp +++ b/src/ZoneCommon/Parsing/ZoneDefinition/Sequence/SequenceZoneDefinitionInclude.cpp @@ -2,18 +2,12 @@ #include "Parsing/ZoneDefinition/Matcher/ZoneDefinitionMatcherFactory.h" -SequenceZoneDefinitionInclude::SequenceZoneDefinitionInclude() -{ - const ZoneDefinitionMatcherFactory create(this); +SequenceZoneDefinitionInclude::SequenceZoneDefinitionInclude() { + const ZoneDefinitionMatcherFactory create(this); - AddMatchers({ - create.Keyword("include"), - create.Char(','), - create.Field().Capture(CAPTURE_INCLUDE_NAME) - }); + AddMatchers({create.Keyword("include"), create.Char(','), create.Field().Capture(CAPTURE_INCLUDE_NAME)}); } -void SequenceZoneDefinitionInclude::ProcessMatch(ZoneDefinition* state, SequenceResult<ZoneDefinitionParserValue>& result) const -{ - state->m_includes.emplace_back(result.NextCapture(CAPTURE_INCLUDE_NAME).FieldValue()); +void SequenceZoneDefinitionInclude::ProcessMatch(ZoneDefinition *state, SequenceResult<ZoneDefinitionParserValue> &result) const { + state->m_includes.emplace_back(result.NextCapture(CAPTURE_INCLUDE_NAME).FieldValue()); } diff --git a/src/ZoneCommon/Parsing/ZoneDefinition/Sequence/SequenceZoneDefinitionInclude.h b/src/ZoneCommon/Parsing/ZoneDefinition/Sequence/SequenceZoneDefinitionInclude.h index a981bcbac..e820507e3 100644 --- a/src/ZoneCommon/Parsing/ZoneDefinition/Sequence/SequenceZoneDefinitionInclude.h +++ b/src/ZoneCommon/Parsing/ZoneDefinition/Sequence/SequenceZoneDefinitionInclude.h @@ -2,13 +2,12 @@ #include "Parsing/ZoneDefinition/ZoneDefinitionParser.h" -class SequenceZoneDefinitionInclude final : public ZoneDefinitionParser::sequence_t -{ - static constexpr auto CAPTURE_INCLUDE_NAME = 1; +class SequenceZoneDefinitionInclude final : public ZoneDefinitionParser::sequence_t { + static constexpr auto CAPTURE_INCLUDE_NAME = 1; protected: - void ProcessMatch(ZoneDefinition* state, SequenceResult<ZoneDefinitionParserValue>& result) const override; + void ProcessMatch(ZoneDefinition *state, SequenceResult<ZoneDefinitionParserValue> &result) const override; public: - SequenceZoneDefinitionInclude(); + SequenceZoneDefinitionInclude(); }; diff --git a/src/ZoneCommon/Parsing/ZoneDefinition/Sequence/SequenceZoneDefinitionMetaData.cpp b/src/ZoneCommon/Parsing/ZoneDefinition/Sequence/SequenceZoneDefinitionMetaData.cpp index 32a347efd..aa00d16be 100644 --- a/src/ZoneCommon/Parsing/ZoneDefinition/Sequence/SequenceZoneDefinitionMetaData.cpp +++ b/src/ZoneCommon/Parsing/ZoneDefinition/Sequence/SequenceZoneDefinitionMetaData.cpp @@ -2,19 +2,12 @@ #include "Parsing/ZoneDefinition/Matcher/ZoneDefinitionMatcherFactory.h" -SequenceZoneDefinitionMetaData::SequenceZoneDefinitionMetaData() -{ - const ZoneDefinitionMatcherFactory create(this); +SequenceZoneDefinitionMetaData::SequenceZoneDefinitionMetaData() { + const ZoneDefinitionMatcherFactory create(this); - AddMatchers({ - create.Char('>'), - create.Field().Capture(CAPTURE_KEY), - create.Char(','), - create.Field().Capture(CAPTURE_VALUE) - }); + AddMatchers({create.Char('>'), create.Field().Capture(CAPTURE_KEY), create.Char(','), create.Field().Capture(CAPTURE_VALUE)}); } -void SequenceZoneDefinitionMetaData::ProcessMatch(ZoneDefinition* state, SequenceResult<ZoneDefinitionParserValue>& result) const -{ - state->AddMetaData(result.NextCapture(CAPTURE_KEY).FieldValue(), result.NextCapture(CAPTURE_VALUE).FieldValue()); +void SequenceZoneDefinitionMetaData::ProcessMatch(ZoneDefinition *state, SequenceResult<ZoneDefinitionParserValue> &result) const { + state->AddMetaData(result.NextCapture(CAPTURE_KEY).FieldValue(), result.NextCapture(CAPTURE_VALUE).FieldValue()); } diff --git a/src/ZoneCommon/Parsing/ZoneDefinition/Sequence/SequenceZoneDefinitionMetaData.h b/src/ZoneCommon/Parsing/ZoneDefinition/Sequence/SequenceZoneDefinitionMetaData.h index efca91c23..41af00c60 100644 --- a/src/ZoneCommon/Parsing/ZoneDefinition/Sequence/SequenceZoneDefinitionMetaData.h +++ b/src/ZoneCommon/Parsing/ZoneDefinition/Sequence/SequenceZoneDefinitionMetaData.h @@ -2,14 +2,13 @@ #include "Parsing/ZoneDefinition/ZoneDefinitionParser.h" -class SequenceZoneDefinitionMetaData final : public ZoneDefinitionParser::sequence_t -{ - static constexpr auto CAPTURE_KEY = 1; - static constexpr auto CAPTURE_VALUE = 2; +class SequenceZoneDefinitionMetaData final : public ZoneDefinitionParser::sequence_t { + static constexpr auto CAPTURE_KEY = 1; + static constexpr auto CAPTURE_VALUE = 2; protected: - void ProcessMatch(ZoneDefinition* state, SequenceResult<ZoneDefinitionParserValue>& result) const override; + void ProcessMatch(ZoneDefinition *state, SequenceResult<ZoneDefinitionParserValue> &result) const override; public: - SequenceZoneDefinitionMetaData(); + SequenceZoneDefinitionMetaData(); }; diff --git a/src/ZoneCommon/Parsing/ZoneDefinition/ZoneDefinitionLexer.cpp b/src/ZoneCommon/Parsing/ZoneDefinition/ZoneDefinitionLexer.cpp index fb81b5794..4e0d7a08d 100644 --- a/src/ZoneCommon/Parsing/ZoneDefinition/ZoneDefinitionLexer.cpp +++ b/src/ZoneCommon/Parsing/ZoneDefinition/ZoneDefinitionLexer.cpp @@ -2,74 +2,65 @@ #include <sstream> -ZoneDefinitionLexer::ZoneDefinitionLexer(IParserLineStream* stream) - : AbstractLexer(stream) -{ -} - -std::string ZoneDefinitionLexer::ReadField() -{ - const auto& currentLine = CurrentLine(); - assert(m_current_line_offset >= 1); - - const auto startPos = m_current_line_offset - 1; - const auto lineSize = currentLine.m_line.size(); - auto lastNonSpaceOffset = m_current_line_offset; - while (m_current_line_offset < lineSize) - { - const auto c = currentLine.m_line[m_current_line_offset]; - - bool isNonFieldCharacter; - switch (c) - { - case '\"': - case '>': - case '<': - case ',': - isNonFieldCharacter = true; - break; - default: - isNonFieldCharacter = false; - break; - } - - if (isNonFieldCharacter) - break; - - m_current_line_offset++; - - if (!isspace(c)) - lastNonSpaceOffset = m_current_line_offset; +ZoneDefinitionLexer::ZoneDefinitionLexer(IParserLineStream *stream) : AbstractLexer(stream) {} + +std::string ZoneDefinitionLexer::ReadField() { + const auto ¤tLine = CurrentLine(); + assert(m_current_line_offset >= 1); + + const auto startPos = m_current_line_offset - 1; + const auto lineSize = currentLine.m_line.size(); + auto lastNonSpaceOffset = m_current_line_offset; + while (m_current_line_offset < lineSize) { + const auto c = currentLine.m_line[m_current_line_offset]; + + bool isNonFieldCharacter; + switch (c) { + case '\"': + case '>': + case '<': + case ',': + isNonFieldCharacter = true; + break; + default: + isNonFieldCharacter = false; + break; } - return std::string(currentLine.m_line, startPos, lastNonSpaceOffset - startPos); -} + if (isNonFieldCharacter) + break; -ZoneDefinitionParserValue ZoneDefinitionLexer::GetNextToken() -{ - auto c = NextChar(); + m_current_line_offset++; - while (c != EOF) - { - switch (c) - { - case '\"': - return ZoneDefinitionParserValue::String(GetPreviousCharacterPos(), new std::string(ReadString())); + if (!isspace(c)) + lastNonSpaceOffset = m_current_line_offset; + } - case '>': - case '<': - case ',': - return ZoneDefinitionParserValue::Character(GetPreviousCharacterPos(), static_cast<char>(c)); + return std::string(currentLine.m_line, startPos, lastNonSpaceOffset - startPos); +} - default: - if (isspace(c)) - break; +ZoneDefinitionParserValue ZoneDefinitionLexer::GetNextToken() { + auto c = NextChar(); - return ZoneDefinitionParserValue::Field(GetPreviousCharacterPos(), new std::string(ReadField())); - } + while (c != EOF) { + switch (c) { + case '\"': + return ZoneDefinitionParserValue::String(GetPreviousCharacterPos(), new std::string(ReadString())); - c = NextChar(); + case '>': + case '<': + case ',': + return ZoneDefinitionParserValue::Character(GetPreviousCharacterPos(), static_cast<char>(c)); + + default: + if (isspace(c)) + break; + + return ZoneDefinitionParserValue::Field(GetPreviousCharacterPos(), new std::string(ReadField())); } - return ZoneDefinitionParserValue::EndOfFile(TokenPos()); + c = NextChar(); + } + + return ZoneDefinitionParserValue::EndOfFile(TokenPos()); } diff --git a/src/ZoneCommon/Parsing/ZoneDefinition/ZoneDefinitionLexer.h b/src/ZoneCommon/Parsing/ZoneDefinition/ZoneDefinitionLexer.h index 10f0ddd06..ad3bd8b6e 100644 --- a/src/ZoneCommon/Parsing/ZoneDefinition/ZoneDefinitionLexer.h +++ b/src/ZoneCommon/Parsing/ZoneDefinition/ZoneDefinitionLexer.h @@ -1,15 +1,14 @@ #pragma once -#include "ZoneDefinitionParserValue.h" #include "Parsing/Impl/AbstractLexer.h" +#include "ZoneDefinitionParserValue.h" -class ZoneDefinitionLexer final : public AbstractLexer<ZoneDefinitionParserValue> -{ - std::string ReadField(); +class ZoneDefinitionLexer final : public AbstractLexer<ZoneDefinitionParserValue> { + std::string ReadField(); protected: - ZoneDefinitionParserValue GetNextToken() override; + ZoneDefinitionParserValue GetNextToken() override; public: - explicit ZoneDefinitionLexer(IParserLineStream* stream); + explicit ZoneDefinitionLexer(IParserLineStream *stream); }; diff --git a/src/ZoneCommon/Parsing/ZoneDefinition/ZoneDefinitionParser.cpp b/src/ZoneCommon/Parsing/ZoneDefinition/ZoneDefinitionParser.cpp index ed52f58fc..6d2326471 100644 --- a/src/ZoneCommon/Parsing/ZoneDefinition/ZoneDefinitionParser.cpp +++ b/src/ZoneCommon/Parsing/ZoneDefinition/ZoneDefinitionParser.cpp @@ -5,24 +5,13 @@ #include "Sequence/SequenceZoneDefinitionInclude.h" #include "Sequence/SequenceZoneDefinitionMetaData.h" -ZoneDefinitionParser::ZoneDefinitionParser(ZoneDefinitionLexer* lexer) - : AbstractParser(lexer, std::make_unique<ZoneDefinition>()) -{ -} +ZoneDefinitionParser::ZoneDefinitionParser(ZoneDefinitionLexer *lexer) : AbstractParser(lexer, std::make_unique<ZoneDefinition>()) {} -const std::vector<AbstractParser<ZoneDefinitionParserValue, ZoneDefinition>::sequence_t*>& ZoneDefinitionParser::GetTestsForState() -{ - static std::vector<sequence_t*> tests({ - new SequenceZoneDefinitionMetaData(), - new SequenceZoneDefinitionInclude(), - new SequenceZoneDefinitionIgnore(), - new SequenceZoneDefinitionEntry() - }); +const std::vector<AbstractParser<ZoneDefinitionParserValue, ZoneDefinition>::sequence_t *> &ZoneDefinitionParser::GetTestsForState() { + static std::vector<sequence_t *> tests( + {new SequenceZoneDefinitionMetaData(), new SequenceZoneDefinitionInclude(), new SequenceZoneDefinitionIgnore(), new SequenceZoneDefinitionEntry()}); - return tests; + return tests; } -std::unique_ptr<ZoneDefinition> ZoneDefinitionParser::GetParsedValue() -{ - return std::move(m_state); -} +std::unique_ptr<ZoneDefinition> ZoneDefinitionParser::GetParsedValue() { return std::move(m_state); } diff --git a/src/ZoneCommon/Parsing/ZoneDefinition/ZoneDefinitionParser.h b/src/ZoneCommon/Parsing/ZoneDefinition/ZoneDefinitionParser.h index 29a861973..e7dc00377 100644 --- a/src/ZoneCommon/Parsing/ZoneDefinition/ZoneDefinitionParser.h +++ b/src/ZoneCommon/Parsing/ZoneDefinition/ZoneDefinitionParser.h @@ -1,16 +1,15 @@ #pragma once -#include "ZoneDefinitionLexer.h" -#include "ZoneDefinitionParserValue.h" #include "Parsing/Impl/AbstractParser.h" #include "Zone/Definition/ZoneDefinition.h" +#include "ZoneDefinitionLexer.h" +#include "ZoneDefinitionParserValue.h" -class ZoneDefinitionParser final : public AbstractParser<ZoneDefinitionParserValue, ZoneDefinition> -{ +class ZoneDefinitionParser final : public AbstractParser<ZoneDefinitionParserValue, ZoneDefinition> { protected: - const std::vector<sequence_t*>& GetTestsForState() override; + const std::vector<sequence_t *> &GetTestsForState() override; public: - explicit ZoneDefinitionParser(ZoneDefinitionLexer* lexer); - std::unique_ptr<ZoneDefinition> GetParsedValue(); + explicit ZoneDefinitionParser(ZoneDefinitionLexer *lexer); + std::unique_ptr<ZoneDefinition> GetParsedValue(); }; diff --git a/src/ZoneCommon/Parsing/ZoneDefinition/ZoneDefinitionParserValue.cpp b/src/ZoneCommon/Parsing/ZoneDefinition/ZoneDefinitionParserValue.cpp index ac120cc7b..05524253e 100644 --- a/src/ZoneCommon/Parsing/ZoneDefinition/ZoneDefinitionParserValue.cpp +++ b/src/ZoneCommon/Parsing/ZoneDefinition/ZoneDefinitionParserValue.cpp @@ -2,114 +2,87 @@ #include <cassert> -ZoneDefinitionParserValue ZoneDefinitionParserValue::Invalid(const TokenPos pos) -{ - ZoneDefinitionParserValue pv(pos, ZoneDefinitionParserValueType::INVALID); - return pv; +ZoneDefinitionParserValue ZoneDefinitionParserValue::Invalid(const TokenPos pos) { + ZoneDefinitionParserValue pv(pos, ZoneDefinitionParserValueType::INVALID); + return pv; } -ZoneDefinitionParserValue ZoneDefinitionParserValue::EndOfFile(const TokenPos pos) -{ - ZoneDefinitionParserValue pv(pos, ZoneDefinitionParserValueType::END_OF_FILE); - return pv; +ZoneDefinitionParserValue ZoneDefinitionParserValue::EndOfFile(const TokenPos pos) { + ZoneDefinitionParserValue pv(pos, ZoneDefinitionParserValueType::END_OF_FILE); + return pv; } -ZoneDefinitionParserValue ZoneDefinitionParserValue::Character(const TokenPos pos, const char c) -{ - ZoneDefinitionParserValue pv(pos, ZoneDefinitionParserValueType::CHARACTER); - pv.m_value.char_value = c; - return pv; +ZoneDefinitionParserValue ZoneDefinitionParserValue::Character(const TokenPos pos, const char c) { + ZoneDefinitionParserValue pv(pos, ZoneDefinitionParserValueType::CHARACTER); + pv.m_value.char_value = c; + return pv; } -ZoneDefinitionParserValue ZoneDefinitionParserValue::String(const TokenPos pos, std::string* str) -{ - ZoneDefinitionParserValue pv(pos, ZoneDefinitionParserValueType::STRING); - pv.m_value.string_value = str; - return pv; +ZoneDefinitionParserValue ZoneDefinitionParserValue::String(const TokenPos pos, std::string *str) { + ZoneDefinitionParserValue pv(pos, ZoneDefinitionParserValueType::STRING); + pv.m_value.string_value = str; + return pv; } -ZoneDefinitionParserValue ZoneDefinitionParserValue::Field(const TokenPos pos, std::string* field) -{ - ZoneDefinitionParserValue pv(pos, ZoneDefinitionParserValueType::FIELD); - pv.m_value.string_value = field; - pv.m_hash = std::hash<std::string>()(*field); - return pv; +ZoneDefinitionParserValue ZoneDefinitionParserValue::Field(const TokenPos pos, std::string *field) { + ZoneDefinitionParserValue pv(pos, ZoneDefinitionParserValueType::FIELD); + pv.m_value.string_value = field; + pv.m_hash = std::hash<std::string>()(*field); + return pv; } ZoneDefinitionParserValue::ZoneDefinitionParserValue(const TokenPos pos, const ZoneDefinitionParserValueType type) - : m_pos(pos), - m_type(type), - m_hash(0), - m_value{} -{ -} + : m_pos(pos), m_type(type), m_hash(0), m_value{} {} -ZoneDefinitionParserValue::~ZoneDefinitionParserValue() -{ - switch (m_type) - { - case ZoneDefinitionParserValueType::STRING: - case ZoneDefinitionParserValueType::FIELD: - delete m_value.string_value; - break; +ZoneDefinitionParserValue::~ZoneDefinitionParserValue() { + switch (m_type) { + case ZoneDefinitionParserValueType::STRING: + case ZoneDefinitionParserValueType::FIELD: + delete m_value.string_value; + break; - default: - break; - } + default: + break; + } - m_value = ValueType(); + m_value = ValueType(); } -ZoneDefinitionParserValue::ZoneDefinitionParserValue(ZoneDefinitionParserValue&& other) noexcept - : m_pos(other.m_pos), - m_type(other.m_type), - m_hash(other.m_hash), - m_value(other.m_value) -{ - other.m_value = ValueType(); +ZoneDefinitionParserValue::ZoneDefinitionParserValue(ZoneDefinitionParserValue &&other) noexcept + : m_pos(other.m_pos), m_type(other.m_type), m_hash(other.m_hash), m_value(other.m_value) { + other.m_value = ValueType(); } -ZoneDefinitionParserValue& ZoneDefinitionParserValue::operator=(ZoneDefinitionParserValue&& other) noexcept -{ - m_pos = other.m_pos; - m_type = other.m_type; - m_value = other.m_value; - m_hash = other.m_hash; - other.m_value = ValueType(); +ZoneDefinitionParserValue &ZoneDefinitionParserValue::operator=(ZoneDefinitionParserValue &&other) noexcept { + m_pos = other.m_pos; + m_type = other.m_type; + m_value = other.m_value; + m_hash = other.m_hash; + other.m_value = ValueType(); - return *this; + return *this; } -bool ZoneDefinitionParserValue::IsEof() const -{ - return m_type == ZoneDefinitionParserValueType::END_OF_FILE; -} +bool ZoneDefinitionParserValue::IsEof() const { return m_type == ZoneDefinitionParserValueType::END_OF_FILE; } -const TokenPos& ZoneDefinitionParserValue::GetPos() const -{ - return m_pos; -} +const TokenPos &ZoneDefinitionParserValue::GetPos() const { return m_pos; } -char ZoneDefinitionParserValue::CharacterValue() const -{ - assert(m_type == ZoneDefinitionParserValueType::CHARACTER); - return m_value.char_value; +char ZoneDefinitionParserValue::CharacterValue() const { + assert(m_type == ZoneDefinitionParserValueType::CHARACTER); + return m_value.char_value; } -std::string& ZoneDefinitionParserValue::StringValue() const -{ - assert(m_type == ZoneDefinitionParserValueType::STRING); - return *m_value.string_value; +std::string &ZoneDefinitionParserValue::StringValue() const { + assert(m_type == ZoneDefinitionParserValueType::STRING); + return *m_value.string_value; } -std::string& ZoneDefinitionParserValue::FieldValue() const -{ - assert(m_type == ZoneDefinitionParserValueType::FIELD); - return *m_value.string_value; +std::string &ZoneDefinitionParserValue::FieldValue() const { + assert(m_type == ZoneDefinitionParserValueType::FIELD); + return *m_value.string_value; } -size_t ZoneDefinitionParserValue::FieldHash() const -{ - assert(m_type == ZoneDefinitionParserValueType::FIELD); - return m_hash; +size_t ZoneDefinitionParserValue::FieldHash() const { + assert(m_type == ZoneDefinitionParserValueType::FIELD); + return m_hash; } diff --git a/src/ZoneCommon/Parsing/ZoneDefinition/ZoneDefinitionParserValue.h b/src/ZoneCommon/Parsing/ZoneDefinition/ZoneDefinitionParserValue.h index 1b57b229c..6759bb7fd 100644 --- a/src/ZoneCommon/Parsing/ZoneDefinition/ZoneDefinitionParserValue.h +++ b/src/ZoneCommon/Parsing/ZoneDefinition/ZoneDefinitionParserValue.h @@ -3,56 +3,53 @@ #include <string> #include "Parsing/IParserValue.h" -#include "Utils/ClassUtils.h" #include "Parsing/TokenPos.h" +#include "Utils/ClassUtils.h" + +enum class ZoneDefinitionParserValueType { + // Meta tokens + INVALID, + END_OF_FILE, + + CHARACTER, + STRING, + FIELD, -enum class ZoneDefinitionParserValueType -{ - // Meta tokens - INVALID, - END_OF_FILE, - - CHARACTER, - STRING, - FIELD, - - // End - MAX + // End + MAX }; -class ZoneDefinitionParserValue final : public IParserValue -{ +class ZoneDefinitionParserValue final : public IParserValue { public: - TokenPos m_pos; - ZoneDefinitionParserValueType m_type; - size_t m_hash; - union ValueType - { - char char_value; - std::string* string_value; - } m_value; - - static ZoneDefinitionParserValue Invalid(TokenPos pos); - static ZoneDefinitionParserValue EndOfFile(TokenPos pos); - static ZoneDefinitionParserValue Character(TokenPos pos, char c); - static ZoneDefinitionParserValue String(TokenPos pos, std::string* str); - static ZoneDefinitionParserValue Field(TokenPos pos, std::string* field); + TokenPos m_pos; + ZoneDefinitionParserValueType m_type; + size_t m_hash; + union ValueType { + char char_value; + std::string *string_value; + } m_value; + + static ZoneDefinitionParserValue Invalid(TokenPos pos); + static ZoneDefinitionParserValue EndOfFile(TokenPos pos); + static ZoneDefinitionParserValue Character(TokenPos pos, char c); + static ZoneDefinitionParserValue String(TokenPos pos, std::string *str); + static ZoneDefinitionParserValue Field(TokenPos pos, std::string *field); private: - ZoneDefinitionParserValue(TokenPos pos, ZoneDefinitionParserValueType type); + ZoneDefinitionParserValue(TokenPos pos, ZoneDefinitionParserValueType type); public: - ~ZoneDefinitionParserValue() override; - ZoneDefinitionParserValue(const ZoneDefinitionParserValue& other) = delete; - ZoneDefinitionParserValue(ZoneDefinitionParserValue&& other) noexcept; - ZoneDefinitionParserValue& operator=(const ZoneDefinitionParserValue& other) = delete; - ZoneDefinitionParserValue& operator=(ZoneDefinitionParserValue&& other) noexcept; - - _NODISCARD bool IsEof() const override; - _NODISCARD const TokenPos& GetPos() const override; - - _NODISCARD char CharacterValue() const; - _NODISCARD std::string& StringValue() const; - _NODISCARD std::string& FieldValue() const; - _NODISCARD size_t FieldHash() const; + ~ZoneDefinitionParserValue() override; + ZoneDefinitionParserValue(const ZoneDefinitionParserValue &other) = delete; + ZoneDefinitionParserValue(ZoneDefinitionParserValue &&other) noexcept; + ZoneDefinitionParserValue &operator=(const ZoneDefinitionParserValue &other) = delete; + ZoneDefinitionParserValue &operator=(ZoneDefinitionParserValue &&other) noexcept; + + _NODISCARD bool IsEof() const override; + _NODISCARD const TokenPos &GetPos() const override; + + _NODISCARD char CharacterValue() const; + _NODISCARD std::string &StringValue() const; + _NODISCARD std::string &FieldValue() const; + _NODISCARD size_t FieldHash() const; }; diff --git a/src/ZoneCommon/Pool/AssetPool.h b/src/ZoneCommon/Pool/AssetPool.h index 86c64b3d2..1879f0189 100644 --- a/src/ZoneCommon/Pool/AssetPool.h +++ b/src/ZoneCommon/Pool/AssetPool.h @@ -1,71 +1,47 @@ #pragma once -#include <string> #include <map> +#include <string> #include "XAssetInfo.h" #include "Zone/Zone.h" class Zone; -template<typename T> -class AssetPool -{ +template <typename T> class AssetPool { public: - std::map<std::string, XAssetInfo<T>*> m_asset_lookup; - - class Iterator - { - typename std::map<std::string, XAssetInfo<T>*>::iterator m_iterator; - - public: - explicit Iterator(typename std::map<std::string, XAssetInfo<T>*>::iterator i) - { - m_iterator = i; - } - - bool operator!=(Iterator rhs) - { - return m_iterator != rhs.m_iterator; - } - - XAssetInfo<T>* operator*() - { - return m_iterator.operator*().second; - } - - void operator++() - { - ++m_iterator; - } - }; - - AssetPool() - { - m_asset_lookup = std::map<std::string, XAssetInfo<T>*>(); - } - - virtual ~AssetPool() = default; - - virtual XAssetInfo<T>* AddAsset(std::string name, T* asset, Zone* zone, std::vector<XAssetInfoGeneric*> dependencies, std::vector<scr_string_t> usedScriptStrings) = 0; - - XAssetInfo<T>* GetAsset(const std::string& name) - { - auto foundAsset = m_asset_lookup.find(name); - - if(foundAsset == m_asset_lookup.end()) - return nullptr; - - return foundAsset->second; - } - - Iterator begin() - { - return Iterator(m_asset_lookup.begin()); - } - - Iterator end() - { - return Iterator(m_asset_lookup.end()); - } + std::map<std::string, XAssetInfo<T> *> m_asset_lookup; + + class Iterator { + typename std::map<std::string, XAssetInfo<T> *>::iterator m_iterator; + + public: + explicit Iterator(typename std::map<std::string, XAssetInfo<T> *>::iterator i) { m_iterator = i; } + + bool operator!=(Iterator rhs) { return m_iterator != rhs.m_iterator; } + + XAssetInfo<T> *operator*() { return m_iterator.operator*().second; } + + void operator++() { ++m_iterator; } + }; + + AssetPool() { m_asset_lookup = std::map<std::string, XAssetInfo<T> *>(); } + + virtual ~AssetPool() = default; + + virtual XAssetInfo<T> *AddAsset(std::string name, T *asset, Zone *zone, std::vector<XAssetInfoGeneric *> dependencies, + std::vector<scr_string_t> usedScriptStrings) = 0; + + XAssetInfo<T> *GetAsset(const std::string &name) { + auto foundAsset = m_asset_lookup.find(name); + + if (foundAsset == m_asset_lookup.end()) + return nullptr; + + return foundAsset->second; + } + + Iterator begin() { return Iterator(m_asset_lookup.begin()); } + + Iterator end() { return Iterator(m_asset_lookup.end()); } }; \ No newline at end of file diff --git a/src/ZoneCommon/Pool/AssetPoolDynamic.h b/src/ZoneCommon/Pool/AssetPoolDynamic.h index 26d72532d..67889fe7f 100644 --- a/src/ZoneCommon/Pool/AssetPoolDynamic.h +++ b/src/ZoneCommon/Pool/AssetPoolDynamic.h @@ -6,58 +6,53 @@ #include <cstring> -template <typename T> -class AssetPoolDynamic final : public AssetPool<T> -{ - using AssetPool<T>::m_asset_lookup; +template <typename T> class AssetPoolDynamic final : public AssetPool<T> { + using AssetPool<T>::m_asset_lookup; - std::vector<XAssetInfo<T>*> m_assets; - asset_type_t m_type; + std::vector<XAssetInfo<T> *> m_assets; + asset_type_t m_type; public: - AssetPoolDynamic(const int priority, const asset_type_t type) - { - GlobalAssetPool<T>::LinkAssetPool(this, priority); - m_type = type; + AssetPoolDynamic(const int priority, const asset_type_t type) { + GlobalAssetPool<T>::LinkAssetPool(this, priority); + m_type = type; + } + + AssetPoolDynamic(AssetPoolDynamic<T> &) = delete; + AssetPoolDynamic(AssetPoolDynamic<T> &&) = delete; + AssetPoolDynamic<T> &operator=(AssetPoolDynamic<T> &) = delete; + AssetPoolDynamic<T> &operator=(AssetPoolDynamic<T> &&) = default; + + ~AssetPoolDynamic() override { + GlobalAssetPool<T>::UnlinkAssetPool(this); + + for (auto *entry : m_assets) { + delete entry->Asset(); + delete entry; } - AssetPoolDynamic(AssetPoolDynamic<T>&) = delete; - AssetPoolDynamic(AssetPoolDynamic<T>&&) = delete; - AssetPoolDynamic<T>& operator =(AssetPoolDynamic<T>&) = delete; - AssetPoolDynamic<T>& operator =(AssetPoolDynamic<T>&&) = default; + m_assets.clear(); + m_asset_lookup.clear(); + } - ~AssetPoolDynamic() override - { - GlobalAssetPool<T>::UnlinkAssetPool(this); + XAssetInfo<T> *AddAsset(std::string name, T *asset, Zone *zone, std::vector<XAssetInfoGeneric *> dependencies, + std::vector<scr_string_t> usedScriptStrings) override { + auto *newInfo = new XAssetInfo<T>(); + newInfo->m_type = m_type; + newInfo->m_name = std::move(name); + newInfo->m_zone = zone; + newInfo->m_dependencies = std::move(dependencies); + newInfo->m_used_script_strings = std::move(usedScriptStrings); - for(auto* entry : m_assets) - { - delete entry->Asset(); - delete entry; - } + T *newAsset = new T(); + memcpy(newAsset, asset, sizeof(T)); + newInfo->m_ptr = newAsset; - m_assets.clear(); - m_asset_lookup.clear(); - } + m_assets.push_back(newInfo); + m_asset_lookup[newInfo->m_name] = newInfo; - XAssetInfo<T>* AddAsset(std::string name, T* asset, Zone* zone, std::vector<XAssetInfoGeneric*> dependencies, std::vector<scr_string_t> usedScriptStrings) override - { - auto* newInfo = new XAssetInfo<T>(); - newInfo->m_type = m_type; - newInfo->m_name = std::move(name); - newInfo->m_zone = zone; - newInfo->m_dependencies = std::move(dependencies); - newInfo->m_used_script_strings = std::move(usedScriptStrings); - - T* newAsset = new T(); - memcpy(newAsset, asset, sizeof(T)); - newInfo->m_ptr = newAsset; - - m_assets.push_back(newInfo); - m_asset_lookup[newInfo->m_name] = newInfo; - - GlobalAssetPool<T>::LinkAsset(this, newInfo); - - return newInfo; - } + GlobalAssetPool<T>::LinkAsset(this, newInfo); + + return newInfo; + } }; diff --git a/src/ZoneCommon/Pool/AssetPoolStatic.h b/src/ZoneCommon/Pool/AssetPoolStatic.h index 07473b2fc..f39c5d367 100644 --- a/src/ZoneCommon/Pool/AssetPoolStatic.h +++ b/src/ZoneCommon/Pool/AssetPoolStatic.h @@ -3,108 +3,96 @@ #include <cstring> #include <stdexcept> -#include "GlobalAssetPool.h" #include "AssetPool.h" +#include "GlobalAssetPool.h" #include "XAssetInfo.h" -template <typename T> -class AssetPoolStatic final : public AssetPool<T> -{ - using AssetPool<T>::m_asset_lookup; +template <typename T> class AssetPoolStatic final : public AssetPool<T> { + using AssetPool<T>::m_asset_lookup; - struct AssetPoolEntry - { - XAssetInfo<T>* m_info; + struct AssetPoolEntry { + XAssetInfo<T> *m_info; - union - { - T m_entry; - AssetPoolEntry* m_next; - }; + union { + T m_entry; + AssetPoolEntry *m_next; }; + }; - AssetPoolEntry* m_free; - AssetPoolEntry* m_pool; - XAssetInfo<T>* m_info_pool; - size_t m_capacity; - asset_type_t m_type; + AssetPoolEntry *m_free; + AssetPoolEntry *m_pool; + XAssetInfo<T> *m_info_pool; + size_t m_capacity; + asset_type_t m_type; public: - AssetPoolStatic(const size_t capacity, const int priority, const asset_type_t type) - { - m_capacity = capacity; - m_type = type; - - if (m_capacity > 0) - { - m_pool = new AssetPoolEntry[m_capacity]; - m_info_pool = new XAssetInfo<T>[m_capacity]; - - for(size_t i = 0; i < m_capacity - 1; i++) - { - m_pool[i].m_info = &m_info_pool[i]; - m_pool[i].m_next = &m_pool[i + 1]; - } - m_pool[m_capacity - 1].m_info = &m_info_pool[m_capacity - 1]; - m_pool[m_capacity - 1].m_next = nullptr; - - m_free = m_pool; - - GlobalAssetPool<T>::LinkAssetPool(this, priority); - } - else - { - m_pool = nullptr; - m_free = nullptr; - m_info_pool = nullptr; - } + AssetPoolStatic(const size_t capacity, const int priority, const asset_type_t type) { + m_capacity = capacity; + m_type = type; + + if (m_capacity > 0) { + m_pool = new AssetPoolEntry[m_capacity]; + m_info_pool = new XAssetInfo<T>[m_capacity]; + + for (size_t i = 0; i < m_capacity - 1; i++) { + m_pool[i].m_info = &m_info_pool[i]; + m_pool[i].m_next = &m_pool[i + 1]; + } + m_pool[m_capacity - 1].m_info = &m_info_pool[m_capacity - 1]; + m_pool[m_capacity - 1].m_next = nullptr; + + m_free = m_pool; + + GlobalAssetPool<T>::LinkAssetPool(this, priority); + } else { + m_pool = nullptr; + m_free = nullptr; + m_info_pool = nullptr; } + } - AssetPoolStatic(AssetPoolStatic<T>&) = delete; - AssetPoolStatic(AssetPoolStatic<T>&&) = delete; - AssetPoolStatic<T>& operator =(AssetPoolStatic<T>&) = delete; - AssetPoolStatic<T>& operator =(AssetPoolStatic<T>&&) = default; + AssetPoolStatic(AssetPoolStatic<T> &) = delete; + AssetPoolStatic(AssetPoolStatic<T> &&) = delete; + AssetPoolStatic<T> &operator=(AssetPoolStatic<T> &) = delete; + AssetPoolStatic<T> &operator=(AssetPoolStatic<T> &&) = default; - ~AssetPoolStatic() override - { - if(m_capacity > 0) - { - GlobalAssetPool<T>::UnlinkAssetPool(this); - } + ~AssetPoolStatic() override { + if (m_capacity > 0) { + GlobalAssetPool<T>::UnlinkAssetPool(this); + } - delete[] m_pool; - m_pool = nullptr; + delete[] m_pool; + m_pool = nullptr; - delete[] m_info_pool; - m_info_pool = nullptr; + delete[] m_info_pool; + m_info_pool = nullptr; - m_free = nullptr; - m_capacity = 0; + m_free = nullptr; + m_capacity = 0; + } + + XAssetInfo<T> *AddAsset(std::string name, T *asset, Zone *zone, std::vector<XAssetInfoGeneric *> dependencies, + std::vector<scr_string_t> usedScriptStrings) override { + if (m_free == nullptr) { + throw std::runtime_error("Could not add asset to static asset pool: capacity exhausted."); } - XAssetInfo<T>* AddAsset(std::string name, T* asset, Zone* zone, std::vector<XAssetInfoGeneric*> dependencies, std::vector<scr_string_t> usedScriptStrings) override - { - if(m_free == nullptr) - { - throw std::runtime_error("Could not add asset to static asset pool: capacity exhausted."); - } + AssetPoolEntry *poolSlot = m_free; + m_free = m_free->m_next; - AssetPoolEntry* poolSlot = m_free; - m_free = m_free->m_next; + memcpy(&poolSlot->m_entry, asset, sizeof(T)); - memcpy(&poolSlot->m_entry, asset, sizeof(T)); + poolSlot->m_info->m_type = m_type; + poolSlot->m_info->m_name = std::move(name); + poolSlot->m_info->m_ptr = &poolSlot->m_entry; + poolSlot->m_info->m_zone = zone; + poolSlot->m_info->m_dependencies = std::move(dependencies); + poolSlot->m_info->m_used_script_strings = std::move(usedScriptStrings); - poolSlot->m_info->m_type = m_type; - poolSlot->m_info->m_name = std::move(name); - poolSlot->m_info->m_ptr = &poolSlot->m_entry; - poolSlot->m_info->m_zone = zone; - poolSlot->m_info->m_dependencies = std::move(dependencies); - poolSlot->m_info->m_used_script_strings = std::move(usedScriptStrings); + m_asset_lookup[poolSlot->m_info->m_name] = poolSlot->m_info; - m_asset_lookup[poolSlot->m_info->m_name] = poolSlot->m_info; + GlobalAssetPool<T>::LinkAsset(this, poolSlot->m_info); - GlobalAssetPool<T>::LinkAsset(this, poolSlot->m_info); - - return poolSlot->m_info; - } + return poolSlot->m_info; + } }; diff --git a/src/ZoneCommon/Pool/GlobalAssetPool.h b/src/ZoneCommon/Pool/GlobalAssetPool.h index c185de772..81d1eecd4 100644 --- a/src/ZoneCommon/Pool/GlobalAssetPool.h +++ b/src/ZoneCommon/Pool/GlobalAssetPool.h @@ -1,186 +1,158 @@ #pragma once -#include <vector> -#include <unordered_map> -#include <string> #include <algorithm> #include <cassert> #include <memory> +#include <string> +#include <unordered_map> +#include <vector> #include "AssetPool.h" -template <typename T> -class GlobalAssetPool -{ - struct LinkedAssetPool - { - AssetPool<T>* m_asset_pool; - int m_priority; - }; - - struct GameAssetPoolEntry - { - XAssetInfo<T>* m_asset; - bool m_duplicate; - LinkedAssetPool* m_asset_pool; - }; - - static std::vector<std::unique_ptr<LinkedAssetPool>> m_linked_asset_pools; - static std::unordered_map<std::string, GameAssetPoolEntry> m_assets; - - static void SortLinkedAssetPools() - { - std::sort(m_linked_asset_pools.begin(), m_linked_asset_pools.end(), [](const std::unique_ptr<LinkedAssetPool>& a, const std::unique_ptr<LinkedAssetPool>& b) -> bool - { - return a->m_priority < b->m_priority; - }); - } - - static bool ReplaceAssetPoolEntry(GameAssetPoolEntry& assetEntry) - { - int occurrences = 0; - - for (const auto& linkedAssetPool : m_linked_asset_pools) - { - XAssetInfo<T>* foundAsset = linkedAssetPool->m_asset_pool->GetAsset(assetEntry.m_asset->m_name); - - if (foundAsset != nullptr) - { - if (++occurrences == 1) - { - assetEntry.m_asset = foundAsset; - assetEntry.m_duplicate = false; - assetEntry.m_asset_pool = linkedAssetPool.get(); - } - else - { - assetEntry.m_duplicate = true; - break; - } - } +template <typename T> class GlobalAssetPool { + struct LinkedAssetPool { + AssetPool<T> *m_asset_pool; + int m_priority; + }; + + struct GameAssetPoolEntry { + XAssetInfo<T> *m_asset; + bool m_duplicate; + LinkedAssetPool *m_asset_pool; + }; + + static std::vector<std::unique_ptr<LinkedAssetPool>> m_linked_asset_pools; + static std::unordered_map<std::string, GameAssetPoolEntry> m_assets; + + static void SortLinkedAssetPools() { + std::sort(m_linked_asset_pools.begin(), m_linked_asset_pools.end(), + [](const std::unique_ptr<LinkedAssetPool> &a, const std::unique_ptr<LinkedAssetPool> &b) -> bool { return a->m_priority < b->m_priority; }); + } + + static bool ReplaceAssetPoolEntry(GameAssetPoolEntry &assetEntry) { + int occurrences = 0; + + for (const auto &linkedAssetPool : m_linked_asset_pools) { + XAssetInfo<T> *foundAsset = linkedAssetPool->m_asset_pool->GetAsset(assetEntry.m_asset->m_name); + + if (foundAsset != nullptr) { + if (++occurrences == 1) { + assetEntry.m_asset = foundAsset; + assetEntry.m_duplicate = false; + assetEntry.m_asset_pool = linkedAssetPool.get(); + } else { + assetEntry.m_duplicate = true; + break; } - - return occurrences > 0; + } } - static void LinkAsset(LinkedAssetPool* link, XAssetInfo<T>* asset) - { - std::string assetName = std::string(asset->m_name); + return occurrences > 0; + } - auto existingAsset = m_assets.find(assetName); + static void LinkAsset(LinkedAssetPool *link, XAssetInfo<T> *asset) { + std::string assetName = std::string(asset->m_name); - if (existingAsset == m_assets.end()) - { - GameAssetPoolEntry entry{}; - entry.m_asset = asset; - entry.m_asset_pool = link; - entry.m_duplicate = false; + auto existingAsset = m_assets.find(assetName); - m_assets[assetName] = entry; - } - else - { - auto& existingEntry = existingAsset->second; + if (existingAsset == m_assets.end()) { + GameAssetPoolEntry entry{}; + entry.m_asset = asset; + entry.m_asset_pool = link; + entry.m_duplicate = false; - existingEntry.m_duplicate = true; + m_assets[assetName] = entry; + } else { + auto &existingEntry = existingAsset->second; - if (existingEntry.m_asset_pool->m_priority < link->m_priority) - { - existingEntry.m_asset_pool = link; - existingEntry.m_asset = asset; - } - } + existingEntry.m_duplicate = true; + + if (existingEntry.m_asset_pool->m_priority < link->m_priority) { + existingEntry.m_asset_pool = link; + existingEntry.m_asset = asset; + } } + } public: - static void LinkAssetPool(AssetPool<T>* assetPool, const int priority) - { - auto newLink = std::make_unique<LinkedAssetPool>(); - newLink->m_asset_pool = assetPool; - newLink->m_priority = priority; - - auto* newLinkPtr = newLink.get(); - m_linked_asset_pools.emplace_back(std::move(newLink)); - SortLinkedAssetPools(); - - for (auto asset : *assetPool) - { - LinkAsset(newLinkPtr, asset); - } - } + static void LinkAssetPool(AssetPool<T> *assetPool, const int priority) { + auto newLink = std::make_unique<LinkedAssetPool>(); + newLink->m_asset_pool = assetPool; + newLink->m_priority = priority; - static void LinkAsset(AssetPool<T>* assetPool, XAssetInfo<T>* asset) - { - LinkedAssetPool* link = nullptr; - - for (const auto& existingLink : m_linked_asset_pools) - { - if (existingLink->m_asset_pool == assetPool) - { - link = existingLink.get(); - break; - } - } + auto *newLinkPtr = newLink.get(); + m_linked_asset_pools.emplace_back(std::move(newLink)); + SortLinkedAssetPools(); - assert(link != nullptr); - if (link == nullptr) - return; + for (auto asset : *assetPool) { + LinkAsset(newLinkPtr, asset); + } + } + + static void LinkAsset(AssetPool<T> *assetPool, XAssetInfo<T> *asset) { + LinkedAssetPool *link = nullptr; - LinkAsset(link, asset); + for (const auto &existingLink : m_linked_asset_pools) { + if (existingLink->m_asset_pool == assetPool) { + link = existingLink.get(); + break; + } } - static void UnlinkAssetPool(AssetPool<T>* assetPool) - { - auto iLinkEntry = m_linked_asset_pools.begin(); - - for (; iLinkEntry != m_linked_asset_pools.end(); ++iLinkEntry) - { - LinkedAssetPool* linkEntry = iLinkEntry->get(); - if (linkEntry->m_asset_pool == assetPool) - { - break; - } - } + assert(link != nullptr); + if (link == nullptr) + return; - assert(iLinkEntry != m_linked_asset_pools.end()); - if (iLinkEntry == m_linked_asset_pools.end()) - return; + LinkAsset(link, asset); + } - auto assetPoolToUnlink = std::move(*iLinkEntry); - m_linked_asset_pools.erase(iLinkEntry); + static void UnlinkAssetPool(AssetPool<T> *assetPool) { + auto iLinkEntry = m_linked_asset_pools.begin(); - for (auto iAssetEntry = m_assets.begin(); iAssetEntry != m_assets.end();) - { - auto& assetEntry = *iAssetEntry; + for (; iLinkEntry != m_linked_asset_pools.end(); ++iLinkEntry) { + LinkedAssetPool *linkEntry = iLinkEntry->get(); + if (linkEntry->m_asset_pool == assetPool) { + break; + } + } - if (assetEntry.second.m_asset_pool != assetPoolToUnlink.get()) - { - ++iAssetEntry; - continue; - } + assert(iLinkEntry != m_linked_asset_pools.end()); + if (iLinkEntry == m_linked_asset_pools.end()) + return; - if (assetEntry.second.m_duplicate && ReplaceAssetPoolEntry(assetEntry.second)) - { - ++iAssetEntry; - continue; - } + auto assetPoolToUnlink = std::move(*iLinkEntry); + m_linked_asset_pools.erase(iLinkEntry); - iAssetEntry = m_assets.erase(iAssetEntry); - } - } + for (auto iAssetEntry = m_assets.begin(); iAssetEntry != m_assets.end();) { + auto &assetEntry = *iAssetEntry; - static XAssetInfo<T>* GetAssetByName(const std::string& name) - { - const auto foundEntry = m_assets.find(name); - if (foundEntry == m_assets.end()) - return nullptr; + if (assetEntry.second.m_asset_pool != assetPoolToUnlink.get()) { + ++iAssetEntry; + continue; + } - return foundEntry->second.m_asset; + if (assetEntry.second.m_duplicate && ReplaceAssetPoolEntry(assetEntry.second)) { + ++iAssetEntry; + continue; + } + + iAssetEntry = m_assets.erase(iAssetEntry); } + } + + static XAssetInfo<T> *GetAssetByName(const std::string &name) { + const auto foundEntry = m_assets.find(name); + if (foundEntry == m_assets.end()) + return nullptr; + + return foundEntry->second.m_asset; + } }; template <typename T> -std::vector<std::unique_ptr<typename GlobalAssetPool<T>::LinkedAssetPool>> GlobalAssetPool<T>::m_linked_asset_pools = std::vector<std::unique_ptr<LinkedAssetPool>>(); +std::vector<std::unique_ptr<typename GlobalAssetPool<T>::LinkedAssetPool>> GlobalAssetPool<T>::m_linked_asset_pools = + std::vector<std::unique_ptr<LinkedAssetPool>>(); template <typename T> -std::unordered_map<std::string, typename GlobalAssetPool<T>::GameAssetPoolEntry> GlobalAssetPool<T>::m_assets = std::unordered_map<std::string, GameAssetPoolEntry>(); +std::unordered_map<std::string, typename GlobalAssetPool<T>::GameAssetPoolEntry> GlobalAssetPool<T>::m_assets = + std::unordered_map<std::string, GameAssetPoolEntry>(); diff --git a/src/ZoneCommon/Pool/XAssetInfo.h b/src/ZoneCommon/Pool/XAssetInfo.h index d698cb975..7c398c6d2 100644 --- a/src/ZoneCommon/Pool/XAssetInfo.h +++ b/src/ZoneCommon/Pool/XAssetInfo.h @@ -1,33 +1,24 @@ #pragma once -#include <vector> #include <string> +#include <vector> #include "Zone/Zone.h" class Zone; -class XAssetInfoGeneric -{ +class XAssetInfoGeneric { public: - asset_type_t m_type = -1; - std::string m_name; - Zone* m_zone; - std::vector<XAssetInfoGeneric*> m_dependencies; - std::vector<scr_string_t> m_used_script_strings; - void* m_ptr; + asset_type_t m_type = -1; + std::string m_name; + Zone *m_zone; + std::vector<XAssetInfoGeneric *> m_dependencies; + std::vector<scr_string_t> m_used_script_strings; + void *m_ptr; }; -template<typename T> -class XAssetInfo : public XAssetInfoGeneric -{ +template <typename T> class XAssetInfo : public XAssetInfoGeneric { public: - T* Asset() - { - return static_cast<T*>(m_ptr); - } + T *Asset() { return static_cast<T *>(m_ptr); } - const T* Asset() const - { - return static_cast<const T*>(const_cast<const void*>(m_ptr)); - } + const T *Asset() const { return static_cast<const T *>(const_cast<const void *>(m_ptr)); } }; diff --git a/src/ZoneCommon/Pool/ZoneAssetPools.cpp b/src/ZoneCommon/Pool/ZoneAssetPools.cpp index 16bf5cccb..0bb6134db 100644 --- a/src/ZoneCommon/Pool/ZoneAssetPools.cpp +++ b/src/ZoneCommon/Pool/ZoneAssetPools.cpp @@ -1,37 +1,24 @@ #include "ZoneAssetPools.h" -ZoneAssetPools::ZoneAssetPools(Zone* zone) - : m_zone(zone) -{ -} +ZoneAssetPools::ZoneAssetPools(Zone *zone) : m_zone(zone) {} -XAssetInfoGeneric* ZoneAssetPools::AddAsset(const asset_type_t type, std::string name, void* asset, std::vector<XAssetInfoGeneric*> dependencies, std::vector<scr_string_t> usedScriptStrings) -{ - return AddAsset(type, std::move(name), asset, std::move(dependencies), std::move(usedScriptStrings), m_zone); +XAssetInfoGeneric *ZoneAssetPools::AddAsset(const asset_type_t type, std::string name, void *asset, std::vector<XAssetInfoGeneric *> dependencies, + std::vector<scr_string_t> usedScriptStrings) { + return AddAsset(type, std::move(name), asset, std::move(dependencies), std::move(usedScriptStrings), m_zone); } -XAssetInfoGeneric* ZoneAssetPools::AddAsset(const asset_type_t type, std::string name, void* asset, std::vector<XAssetInfoGeneric*> dependencies, std::vector<scr_string_t> usedScriptStrings, Zone* zone) -{ - auto* assetInfo = AddAssetToPool(type, std::move(name), asset, std::move(dependencies), std::move(usedScriptStrings), zone); - if (assetInfo) - { - m_assets_in_order.push_back(assetInfo); - } +XAssetInfoGeneric *ZoneAssetPools::AddAsset(const asset_type_t type, std::string name, void *asset, std::vector<XAssetInfoGeneric *> dependencies, + std::vector<scr_string_t> usedScriptStrings, Zone *zone) { + auto *assetInfo = AddAssetToPool(type, std::move(name), asset, std::move(dependencies), std::move(usedScriptStrings), zone); + if (assetInfo) { + m_assets_in_order.push_back(assetInfo); + } - return assetInfo; + return assetInfo; } -size_t ZoneAssetPools::GetTotalAssetCount() const -{ - return m_assets_in_order.size(); -} +size_t ZoneAssetPools::GetTotalAssetCount() const { return m_assets_in_order.size(); } -ZoneAssetPools::iterator ZoneAssetPools::begin() const -{ - return m_assets_in_order.begin(); -} +ZoneAssetPools::iterator ZoneAssetPools::begin() const { return m_assets_in_order.begin(); } -ZoneAssetPools::iterator ZoneAssetPools::end() const -{ - return m_assets_in_order.end(); -} +ZoneAssetPools::iterator ZoneAssetPools::end() const { return m_assets_in_order.end(); } diff --git a/src/ZoneCommon/Pool/ZoneAssetPools.h b/src/ZoneCommon/Pool/ZoneAssetPools.h index d2c7efc4e..d828e5df8 100644 --- a/src/ZoneCommon/Pool/ZoneAssetPools.h +++ b/src/ZoneCommon/Pool/ZoneAssetPools.h @@ -1,46 +1,47 @@ #pragma once -#include <vector> -#include <string> #include <cstddef> +#include <string> +#include <vector> #include "Utils/ClassUtils.h" #include "XAssetInfo.h" -#include "Zone/ZoneTypes.h" #include "Zone/Zone.h" +#include "Zone/ZoneTypes.h" class Zone; class XAssetInfoGeneric; -class ZoneAssetPools -{ +class ZoneAssetPools { protected: - Zone* m_zone; - std::vector<XAssetInfoGeneric*> m_assets_in_order; + Zone *m_zone; + std::vector<XAssetInfoGeneric *> m_assets_in_order; - virtual XAssetInfoGeneric* AddAssetToPool(asset_type_t type, std::string name, void* asset, std::vector<XAssetInfoGeneric*> dependencies, std::vector<scr_string_t> usedScriptStrings, - Zone* zone) = 0; + virtual XAssetInfoGeneric *AddAssetToPool(asset_type_t type, std::string name, void *asset, std::vector<XAssetInfoGeneric *> dependencies, + std::vector<scr_string_t> usedScriptStrings, Zone *zone) = 0; public: - using iterator = std::vector<XAssetInfoGeneric*>::const_iterator; - - explicit ZoneAssetPools(Zone* zone); - virtual ~ZoneAssetPools() = default; - ZoneAssetPools(const ZoneAssetPools& other) = delete; - ZoneAssetPools(ZoneAssetPools&& other) noexcept = default; - ZoneAssetPools& operator=(const ZoneAssetPools& other) = delete; - ZoneAssetPools& operator=(ZoneAssetPools&& other) noexcept = default; - - XAssetInfoGeneric* AddAsset(asset_type_t type, std::string name, void* asset, std::vector<XAssetInfoGeneric*> dependencies, std::vector<scr_string_t> usedScriptStrings); - XAssetInfoGeneric* AddAsset(asset_type_t type, std::string name, void* asset, std::vector<XAssetInfoGeneric*> dependencies, std::vector<scr_string_t> usedScriptStrings, Zone* zone); - _NODISCARD virtual XAssetInfoGeneric* GetAsset(asset_type_t type, std::string name) const = 0; - _NODISCARD virtual asset_type_t GetAssetTypeCount() const = 0; - _NODISCARD virtual const char* GetAssetTypeName(asset_type_t assetType) const = 0; - - virtual void InitPoolStatic(asset_type_t type, size_t capacity) = 0; - virtual void InitPoolDynamic(asset_type_t type) = 0; - - _NODISCARD size_t GetTotalAssetCount() const; - - iterator begin() const; - iterator end() const; + using iterator = std::vector<XAssetInfoGeneric *>::const_iterator; + + explicit ZoneAssetPools(Zone *zone); + virtual ~ZoneAssetPools() = default; + ZoneAssetPools(const ZoneAssetPools &other) = delete; + ZoneAssetPools(ZoneAssetPools &&other) noexcept = default; + ZoneAssetPools &operator=(const ZoneAssetPools &other) = delete; + ZoneAssetPools &operator=(ZoneAssetPools &&other) noexcept = default; + + XAssetInfoGeneric *AddAsset(asset_type_t type, std::string name, void *asset, std::vector<XAssetInfoGeneric *> dependencies, + std::vector<scr_string_t> usedScriptStrings); + XAssetInfoGeneric *AddAsset(asset_type_t type, std::string name, void *asset, std::vector<XAssetInfoGeneric *> dependencies, + std::vector<scr_string_t> usedScriptStrings, Zone *zone); + _NODISCARD virtual XAssetInfoGeneric *GetAsset(asset_type_t type, std::string name) const = 0; + _NODISCARD virtual asset_type_t GetAssetTypeCount() const = 0; + _NODISCARD virtual const char *GetAssetTypeName(asset_type_t assetType) const = 0; + + virtual void InitPoolStatic(asset_type_t type, size_t capacity) = 0; + virtual void InitPoolDynamic(asset_type_t type) = 0; + + _NODISCARD size_t GetTotalAssetCount() const; + + iterator begin() const; + iterator end() const; }; diff --git a/src/ZoneCommon/Utils/ICapturedDataProvider.h b/src/ZoneCommon/Utils/ICapturedDataProvider.h index 4c37420fd..892ca1ab8 100644 --- a/src/ZoneCommon/Utils/ICapturedDataProvider.h +++ b/src/ZoneCommon/Utils/ICapturedDataProvider.h @@ -1,8 +1,7 @@ #pragma once #include <cstdint> -class ICapturedDataProvider -{ +class ICapturedDataProvider { public: - virtual void GetCapturedData(const uint8_t** pCapturedData, size_t* pSize) = 0; + virtual void GetCapturedData(const uint8_t **pCapturedData, size_t *pSize) = 0; }; diff --git a/src/ZoneCommon/Zone/AssetList/AssetList.cpp b/src/ZoneCommon/Zone/AssetList/AssetList.cpp index 56bb487ee..61026ef7e 100644 --- a/src/ZoneCommon/Zone/AssetList/AssetList.cpp +++ b/src/ZoneCommon/Zone/AssetList/AssetList.cpp @@ -1,10 +1,5 @@ #include "AssetList.h" -AssetListEntry::AssetListEntry() -= default; +AssetListEntry::AssetListEntry() = default; -AssetListEntry::AssetListEntry(std::string type, std::string name) - : m_type(std::move(type)), - m_name(std::move(name)) -{ -} +AssetListEntry::AssetListEntry(std::string type, std::string name) : m_type(std::move(type)), m_name(std::move(name)) {} diff --git a/src/ZoneCommon/Zone/AssetList/AssetList.h b/src/ZoneCommon/Zone/AssetList/AssetList.h index 0bd7c0f3f..04a1c2905 100644 --- a/src/ZoneCommon/Zone/AssetList/AssetList.h +++ b/src/ZoneCommon/Zone/AssetList/AssetList.h @@ -1,12 +1,11 @@ #pragma once #include <string> -class AssetListEntry -{ +class AssetListEntry { public: - std::string m_type; - std::string m_name; + std::string m_type; + std::string m_name; - AssetListEntry(); - AssetListEntry(std::string type, std::string name); + AssetListEntry(); + AssetListEntry(std::string type, std::string name); }; diff --git a/src/ZoneCommon/Zone/AssetList/AssetListStream.cpp b/src/ZoneCommon/Zone/AssetList/AssetListStream.cpp index e1d849542..be831a081 100644 --- a/src/ZoneCommon/Zone/AssetList/AssetListStream.cpp +++ b/src/ZoneCommon/Zone/AssetList/AssetListStream.cpp @@ -1,37 +1,28 @@ #include "AssetListStream.h" -AssetListInputStream::AssetListInputStream(std::istream& stream) - : m_stream(stream) -{ -} +AssetListInputStream::AssetListInputStream(std::istream &stream) : m_stream(stream) {} -bool AssetListInputStream::NextEntry(AssetListEntry& entry) const -{ - std::vector<std::string> row; +bool AssetListInputStream::NextEntry(AssetListEntry &entry) const { + std::vector<std::string> row; - while(true) - { - if (!m_stream.NextRow(row)) - return false; + while (true) { + if (!m_stream.NextRow(row)) + return false; - if (row.empty()) - continue; + if (row.empty()) + continue; - entry.m_type = row[0]; - if (row.size() >= 2) - entry.m_name = row[1]; - return true; - } + entry.m_type = row[0]; + if (row.size() >= 2) + entry.m_name = row[1]; + return true; + } } -AssetListOutputStream::AssetListOutputStream(std::ostream& stream) - : m_stream(stream) -{ -} +AssetListOutputStream::AssetListOutputStream(std::ostream &stream) : m_stream(stream) {} -void AssetListOutputStream::WriteEntry(const AssetListEntry& entry) -{ - m_stream.WriteColumn(entry.m_type); - m_stream.WriteColumn(entry.m_name); - m_stream.NextRow(); +void AssetListOutputStream::WriteEntry(const AssetListEntry &entry) { + m_stream.WriteColumn(entry.m_type); + m_stream.WriteColumn(entry.m_name); + m_stream.NextRow(); } diff --git a/src/ZoneCommon/Zone/AssetList/AssetListStream.h b/src/ZoneCommon/Zone/AssetList/AssetListStream.h index d15807c6d..13fbd659e 100644 --- a/src/ZoneCommon/Zone/AssetList/AssetListStream.h +++ b/src/ZoneCommon/Zone/AssetList/AssetListStream.h @@ -4,22 +4,20 @@ #include "AssetList.h" #include "Csv/CsvStream.h" -class AssetListInputStream -{ - CsvInputStream m_stream; +class AssetListInputStream { + CsvInputStream m_stream; public: - explicit AssetListInputStream(std::istream& stream); + explicit AssetListInputStream(std::istream &stream); - bool NextEntry(AssetListEntry& entry) const; + bool NextEntry(AssetListEntry &entry) const; }; -class AssetListOutputStream -{ - CsvOutputStream m_stream; +class AssetListOutputStream { + CsvOutputStream m_stream; public: - explicit AssetListOutputStream(std::ostream& stream); + explicit AssetListOutputStream(std::ostream &stream); - void WriteEntry(const AssetListEntry& entry); + void WriteEntry(const AssetListEntry &entry); }; \ No newline at end of file diff --git a/src/ZoneCommon/Zone/Definition/ZoneDefinition.cpp b/src/ZoneCommon/Zone/Definition/ZoneDefinition.cpp index 1c3ed7e2a..38ffb328a 100644 --- a/src/ZoneCommon/Zone/Definition/ZoneDefinition.cpp +++ b/src/ZoneCommon/Zone/Definition/ZoneDefinition.cpp @@ -1,48 +1,31 @@ #include "ZoneDefinition.h" -ZoneDefinitionEntry::ZoneDefinitionEntry() - : m_is_reference(false) -{ -} +ZoneDefinitionEntry::ZoneDefinitionEntry() : m_is_reference(false) {} ZoneDefinitionEntry::ZoneDefinitionEntry(std::string type, std::string name, const bool isReference) - : m_asset_type(std::move(type)), - m_asset_name(std::move(name)), - m_is_reference(isReference) -{ -} + : m_asset_type(std::move(type)), m_asset_name(std::move(name)), m_is_reference(isReference) {} -ZoneMetaDataEntry::ZoneMetaDataEntry() -= default; +ZoneMetaDataEntry::ZoneMetaDataEntry() = default; -ZoneMetaDataEntry::ZoneMetaDataEntry(std::string key, std::string value) - : m_key(std::move(key)), - m_value(std::move(value)) -{ -} +ZoneMetaDataEntry::ZoneMetaDataEntry(std::string key, std::string value) : m_key(std::move(key)), m_value(std::move(value)) {} -void ZoneDefinition::AddMetaData(std::string key, std::string value) -{ - auto metaData = std::make_unique<ZoneMetaDataEntry>(std::move(key), std::move(value)); - auto* metaDataPtr = metaData.get(); - m_metadata.emplace_back(std::move(metaData)); - m_metadata_lookup.emplace(std::make_pair(metaDataPtr->m_key, metaDataPtr)); +void ZoneDefinition::AddMetaData(std::string key, std::string value) { + auto metaData = std::make_unique<ZoneMetaDataEntry>(std::move(key), std::move(value)); + auto *metaDataPtr = metaData.get(); + m_metadata.emplace_back(std::move(metaData)); + m_metadata_lookup.emplace(std::make_pair(metaDataPtr->m_key, metaDataPtr)); } -void ZoneDefinition::Include(ZoneDefinition& definitionToInclude) -{ - for (const auto& metaData : definitionToInclude.m_metadata) - { - AddMetaData(metaData->m_key, metaData->m_value); - } - - for (const auto& ignore : definitionToInclude.m_ignores) - { - m_ignores.emplace_back(ignore); - } - - for (const auto& asset : definitionToInclude.m_assets) - { - m_assets.emplace_back(asset); - } +void ZoneDefinition::Include(ZoneDefinition &definitionToInclude) { + for (const auto &metaData : definitionToInclude.m_metadata) { + AddMetaData(metaData->m_key, metaData->m_value); + } + + for (const auto &ignore : definitionToInclude.m_ignores) { + m_ignores.emplace_back(ignore); + } + + for (const auto &asset : definitionToInclude.m_assets) { + m_assets.emplace_back(asset); + } } diff --git a/src/ZoneCommon/Zone/Definition/ZoneDefinition.h b/src/ZoneCommon/Zone/Definition/ZoneDefinition.h index 2a093f8dc..70d90a7e3 100644 --- a/src/ZoneCommon/Zone/Definition/ZoneDefinition.h +++ b/src/ZoneCommon/Zone/Definition/ZoneDefinition.h @@ -1,41 +1,38 @@ #pragma once -#include <string> #include <memory> +#include <string> #include <unordered_map> #include <vector> -class ZoneDefinitionEntry -{ +class ZoneDefinitionEntry { public: - std::string m_asset_type; - std::string m_asset_name; - bool m_is_reference; + std::string m_asset_type; + std::string m_asset_name; + bool m_is_reference; - ZoneDefinitionEntry(); - ZoneDefinitionEntry(std::string type, std::string name, bool isReference); + ZoneDefinitionEntry(); + ZoneDefinitionEntry(std::string type, std::string name, bool isReference); }; -class ZoneMetaDataEntry -{ +class ZoneMetaDataEntry { public: - std::string m_key; - std::string m_value; + std::string m_key; + std::string m_value; - ZoneMetaDataEntry(); - ZoneMetaDataEntry(std::string key, std::string value); + ZoneMetaDataEntry(); + ZoneMetaDataEntry(std::string key, std::string value); }; -class ZoneDefinition -{ +class ZoneDefinition { public: - std::string m_name; - std::vector<std::unique_ptr<ZoneMetaDataEntry>> m_metadata; - std::unordered_multimap<std::string, ZoneMetaDataEntry*> m_metadata_lookup; - std::vector<std::string> m_includes; - std::vector<std::string> m_ignores; - std::vector<ZoneDefinitionEntry> m_assets; + std::string m_name; + std::vector<std::unique_ptr<ZoneMetaDataEntry>> m_metadata; + std::unordered_multimap<std::string, ZoneMetaDataEntry *> m_metadata_lookup; + std::vector<std::string> m_includes; + std::vector<std::string> m_ignores; + std::vector<ZoneDefinitionEntry> m_assets; - void AddMetaData(std::string key, std::string value); - void Include(ZoneDefinition& definitionToInclude); + void AddMetaData(std::string key, std::string value); + void Include(ZoneDefinition &definitionToInclude); }; \ No newline at end of file diff --git a/src/ZoneCommon/Zone/Definition/ZoneDefinitionStream.cpp b/src/ZoneCommon/Zone/Definition/ZoneDefinitionStream.cpp index e2a4774dc..88cc21137 100644 --- a/src/ZoneCommon/Zone/Definition/ZoneDefinitionStream.cpp +++ b/src/ZoneCommon/Zone/Definition/ZoneDefinitionStream.cpp @@ -10,111 +10,84 @@ #include "Parsing/ZoneDefinition/ZoneDefinitionLexer.h" #include "Parsing/ZoneDefinition/ZoneDefinitionParser.h" -ZoneDefinitionInputStream::ZoneDefinitionInputStream(std::istream& stream, std::string fileName, bool verbose) - : m_file_name(std::move(fileName)), - m_verbose(verbose), - m_stream(nullptr) -{ - OpenBaseStream(stream); - SetupStreamProxies(); - m_stream = m_open_streams.back().get(); +ZoneDefinitionInputStream::ZoneDefinitionInputStream(std::istream &stream, std::string fileName, bool verbose) + : m_file_name(std::move(fileName)), m_verbose(verbose), m_stream(nullptr) { + OpenBaseStream(stream); + SetupStreamProxies(); + m_stream = m_open_streams.back().get(); } -bool ZoneDefinitionInputStream::OpenBaseStream(std::istream& stream) -{ - m_open_streams.emplace_back(std::make_unique<ParserSingleInputStream>(stream, m_file_name)); - return true; +bool ZoneDefinitionInputStream::OpenBaseStream(std::istream &stream) { + m_open_streams.emplace_back(std::make_unique<ParserSingleInputStream>(stream, m_file_name)); + return true; } -void ZoneDefinitionInputStream::SetupStreamProxies() -{ - m_open_streams.emplace_back(std::make_unique<CommentRemovingStreamProxy>(m_open_streams.back().get())); - auto definesProxy = std::make_unique<DefinesStreamProxy>(m_open_streams.back().get()); - definesProxy->AddDefine(DefinesStreamProxy::Define(ZONE_CODE_GENERATOR_DEFINE_NAME, ZONE_CODE_GENERATOR_DEFINE_VALUE)); - m_open_streams.emplace_back(std::move(definesProxy)); +void ZoneDefinitionInputStream::SetupStreamProxies() { + m_open_streams.emplace_back(std::make_unique<CommentRemovingStreamProxy>(m_open_streams.back().get())); + auto definesProxy = std::make_unique<DefinesStreamProxy>(m_open_streams.back().get()); + definesProxy->AddDefine(DefinesStreamProxy::Define(ZONE_CODE_GENERATOR_DEFINE_NAME, ZONE_CODE_GENERATOR_DEFINE_VALUE)); + m_open_streams.emplace_back(std::move(definesProxy)); - m_stream = m_open_streams.back().get(); + m_stream = m_open_streams.back().get(); } -std::unique_ptr<ZoneDefinition> ZoneDefinitionInputStream::ReadDefinition() -{ - if (m_verbose) - { - std::cout << "Reading zone definition file: " << m_file_name << std::endl; - } +std::unique_ptr<ZoneDefinition> ZoneDefinitionInputStream::ReadDefinition() { + if (m_verbose) { + std::cout << "Reading zone definition file: " << m_file_name << std::endl; + } - const auto lexer = std::make_unique<ZoneDefinitionLexer>(m_stream); - const auto parser = std::make_unique<ZoneDefinitionParser>(lexer.get()); + const auto lexer = std::make_unique<ZoneDefinitionLexer>(m_stream); + const auto parser = std::make_unique<ZoneDefinitionParser>(lexer.get()); - const auto start = std::chrono::steady_clock::now(); - std::unique_ptr<ZoneDefinition> definition; - if (parser->Parse()) - definition = parser->GetParsedValue(); - const auto end = std::chrono::steady_clock::now(); + const auto start = std::chrono::steady_clock::now(); + std::unique_ptr<ZoneDefinition> definition; + if (parser->Parse()) + definition = parser->GetParsedValue(); + const auto end = std::chrono::steady_clock::now(); - if (m_verbose) - { - std::cout << "Processing zone definition took " << std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count() << "ms" << std::endl; - } + if (m_verbose) { + std::cout << "Processing zone definition took " << std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count() << "ms" << std::endl; + } - return std::move(definition); + return std::move(definition); } -ZoneDefinitionOutputStream::ZoneDefinitionOutputStream(std::ostream& stream) - : m_stream(stream) -{ -} +ZoneDefinitionOutputStream::ZoneDefinitionOutputStream(std::ostream &stream) : m_stream(stream) {} -void ZoneDefinitionOutputStream::EmptyLine() const -{ - m_stream << "\n"; -} +void ZoneDefinitionOutputStream::EmptyLine() const { m_stream << "\n"; } -void ZoneDefinitionOutputStream::WriteComment(const std::string& comment) const -{ - m_stream << "// " << comment << "\n"; -} +void ZoneDefinitionOutputStream::WriteComment(const std::string &comment) const { m_stream << "// " << comment << "\n"; } -void ZoneDefinitionOutputStream::WriteMetaData(const std::string& metaDataKey, const std::string& metaDataValue) const -{ - m_stream << ">" << metaDataKey << "," << metaDataValue << "\n"; +void ZoneDefinitionOutputStream::WriteMetaData(const std::string &metaDataKey, const std::string &metaDataValue) const { + m_stream << ">" << metaDataKey << "," << metaDataValue << "\n"; } -void ZoneDefinitionOutputStream::WriteEntry(const std::string& entryKey, const std::string& entryValue) const -{ - m_stream << entryKey << ","; - - if (entryValue.find('"') != std::string::npos - || entryValue.find("//") != std::string::npos) - { - m_stream << '"'; - for (const auto& c : entryValue) - { - switch (c) - { - case '"': - m_stream << "\\\""; - break; - - case '\\': - m_stream << "\\\\"; - break; - - default: - m_stream << c; - break; - } - } - m_stream << '"'; - } - else if (entryValue.empty()) - { - m_stream << R"("")"; +void ZoneDefinitionOutputStream::WriteEntry(const std::string &entryKey, const std::string &entryValue) const { + m_stream << entryKey << ","; + + if (entryValue.find('"') != std::string::npos || entryValue.find("//") != std::string::npos) { + m_stream << '"'; + for (const auto &c : entryValue) { + switch (c) { + case '"': + m_stream << "\\\""; + break; + + case '\\': + m_stream << "\\\\"; + break; + + default: + m_stream << c; + break; + } } - else - { - m_stream << entryValue; - } - - m_stream << "\n"; + m_stream << '"'; + } else if (entryValue.empty()) { + m_stream << R"("")"; + } else { + m_stream << entryValue; + } + + m_stream << "\n"; } diff --git a/src/ZoneCommon/Zone/Definition/ZoneDefinitionStream.h b/src/ZoneCommon/Zone/Definition/ZoneDefinitionStream.h index 54441a470..91d706817 100644 --- a/src/ZoneCommon/Zone/Definition/ZoneDefinitionStream.h +++ b/src/ZoneCommon/Zone/Definition/ZoneDefinitionStream.h @@ -2,37 +2,35 @@ #include <iostream> #include <memory> -#include "ZoneDefinition.h" #include "Parsing/IParserLineStream.h" +#include "ZoneDefinition.h" -class ZoneDefinitionInputStream -{ - static constexpr const char* ZONE_CODE_GENERATOR_DEFINE_NAME = "__zonecodegenerator"; - static constexpr const char* ZONE_CODE_GENERATOR_DEFINE_VALUE = "1"; +class ZoneDefinitionInputStream { + static constexpr const char *ZONE_CODE_GENERATOR_DEFINE_NAME = "__zonecodegenerator"; + static constexpr const char *ZONE_CODE_GENERATOR_DEFINE_VALUE = "1"; - std::string m_file_name; - bool m_verbose; - IParserLineStream* m_stream; - std::vector<std::unique_ptr<IParserLineStream>> m_open_streams; + std::string m_file_name; + bool m_verbose; + IParserLineStream *m_stream; + std::vector<std::unique_ptr<IParserLineStream>> m_open_streams; - bool OpenBaseStream(std::istream& stream); - void SetupStreamProxies(); + bool OpenBaseStream(std::istream &stream); + void SetupStreamProxies(); public: - ZoneDefinitionInputStream(std::istream& stream, std::string fileName, bool verbose); + ZoneDefinitionInputStream(std::istream &stream, std::string fileName, bool verbose); - std::unique_ptr<ZoneDefinition> ReadDefinition(); + std::unique_ptr<ZoneDefinition> ReadDefinition(); }; -class ZoneDefinitionOutputStream -{ - std::ostream& m_stream; +class ZoneDefinitionOutputStream { + std::ostream &m_stream; public: - explicit ZoneDefinitionOutputStream(std::ostream& stream); + explicit ZoneDefinitionOutputStream(std::ostream &stream); - void EmptyLine() const; - void WriteComment(const std::string& comment) const; - void WriteMetaData(const std::string& metaDataKey, const std::string& metaDataValue) const; - void WriteEntry(const std::string& entryKey, const std::string& entryValue) const; + void EmptyLine() const; + void WriteComment(const std::string &comment) const; + void WriteMetaData(const std::string &metaDataKey, const std::string &metaDataValue) const; + void WriteEntry(const std::string &entryKey, const std::string &entryValue) const; }; \ No newline at end of file diff --git a/src/ZoneCommon/Zone/Stream/IZoneStream.h b/src/ZoneCommon/Zone/Stream/IZoneStream.h index cefdf8035..f760c041c 100644 --- a/src/ZoneCommon/Zone/Stream/IZoneStream.h +++ b/src/ZoneCommon/Zone/Stream/IZoneStream.h @@ -1,16 +1,15 @@ #pragma once #include "Zone/ZoneTypes.h" -class IZoneStream -{ +class IZoneStream { public: - IZoneStream() = default; - virtual ~IZoneStream() = default; - IZoneStream(const IZoneStream& other) = default; - IZoneStream(IZoneStream&& other) noexcept = default; - IZoneStream& operator=(const IZoneStream& other) = default; - IZoneStream& operator=(IZoneStream&& other) noexcept = default; + IZoneStream() = default; + virtual ~IZoneStream() = default; + IZoneStream(const IZoneStream &other) = default; + IZoneStream(IZoneStream &&other) noexcept = default; + IZoneStream &operator=(const IZoneStream &other) = default; + IZoneStream &operator=(IZoneStream &&other) noexcept = default; - virtual void PushBlock(block_t block) = 0; - virtual block_t PopBlock() = 0; + virtual void PushBlock(block_t block) = 0; + virtual block_t PopBlock() = 0; }; \ No newline at end of file diff --git a/src/ZoneCommon/Zone/XBlock.cpp b/src/ZoneCommon/Zone/XBlock.cpp index cdf7c53c2..a4654a93f 100644 --- a/src/ZoneCommon/Zone/XBlock.cpp +++ b/src/ZoneCommon/Zone/XBlock.cpp @@ -1,33 +1,27 @@ #include "XBlock.h" #include <cassert> -XBlock::XBlock(const std::string& name, const int index, const Type type) -{ - m_name = name; - m_index = index; - m_type = type; - m_buffer = nullptr; - m_buffer_size = 0; +XBlock::XBlock(const std::string &name, const int index, const Type type) { + m_name = name; + m_index = index; + m_type = type; + m_buffer = nullptr; + m_buffer_size = 0; } -XBlock::~XBlock() -{ - delete[] m_buffer; - m_buffer = nullptr; +XBlock::~XBlock() { + delete[] m_buffer; + m_buffer = nullptr; } -void XBlock::Alloc(const size_t blockSize) -{ - delete[] m_buffer; +void XBlock::Alloc(const size_t blockSize) { + delete[] m_buffer; - if(blockSize > 0) - { - m_buffer = new uint8_t[blockSize]; - m_buffer_size = blockSize; - } - else - { - m_buffer = nullptr; - m_buffer_size = 0; - } + if (blockSize > 0) { + m_buffer = new uint8_t[blockSize]; + m_buffer_size = blockSize; + } else { + m_buffer = nullptr; + m_buffer_size = 0; + } } \ No newline at end of file diff --git a/src/ZoneCommon/Zone/XBlock.h b/src/ZoneCommon/Zone/XBlock.h index b65c28dfc..957faf243 100644 --- a/src/ZoneCommon/Zone/XBlock.h +++ b/src/ZoneCommon/Zone/XBlock.h @@ -2,26 +2,19 @@ #include <cstdint> #include <string> -class XBlock -{ +class XBlock { public: - enum class Type - { - BLOCK_TYPE_TEMP, - BLOCK_TYPE_RUNTIME, - BLOCK_TYPE_DELAY, - BLOCK_TYPE_NORMAL - }; + enum class Type { BLOCK_TYPE_TEMP, BLOCK_TYPE_RUNTIME, BLOCK_TYPE_DELAY, BLOCK_TYPE_NORMAL }; - std::string m_name; - int m_index; - Type m_type; + std::string m_name; + int m_index; + Type m_type; - uint8_t* m_buffer; - size_t m_buffer_size; + uint8_t *m_buffer; + size_t m_buffer_size; - XBlock(const std::string& name, int index, Type type); - ~XBlock(); + XBlock(const std::string &name, int index, Type type); + ~XBlock(); - void Alloc(size_t blockSize); + void Alloc(size_t blockSize); }; diff --git a/src/ZoneCommon/Zone/XChunk/AbstractSalsa20Processor.cpp b/src/ZoneCommon/Zone/XChunk/AbstractSalsa20Processor.cpp index b1bd7d1ef..28b5463a7 100644 --- a/src/ZoneCommon/Zone/XChunk/AbstractSalsa20Processor.cpp +++ b/src/ZoneCommon/Zone/XChunk/AbstractSalsa20Processor.cpp @@ -2,52 +2,45 @@ #include <cassert> -AbstractSalsa20Processor::AbstractSalsa20Processor(const int streamCount, std::string& zoneName, const uint8_t* salsa20Key, size_t keySize) - : m_stream_count(streamCount), - m_stream_contexts(std::make_unique<StreamContext[]>(streamCount)), - m_stream_block_indices(std::make_unique<unsigned int[]>(streamCount)) -{ - m_block_hashes = std::make_unique<uint8_t[]>(BLOCK_HASHES_COUNT * streamCount * SHA1_HASH_SIZE); - InitStreams(zoneName, salsa20Key, keySize); +AbstractSalsa20Processor::AbstractSalsa20Processor(const int streamCount, std::string &zoneName, const uint8_t *salsa20Key, size_t keySize) + : m_stream_count(streamCount), m_stream_contexts(std::make_unique<StreamContext[]>(streamCount)), + m_stream_block_indices(std::make_unique<unsigned int[]>(streamCount)) { + m_block_hashes = std::make_unique<uint8_t[]>(BLOCK_HASHES_COUNT * streamCount * SHA1_HASH_SIZE); + InitStreams(zoneName, salsa20Key, keySize); } -uint8_t* AbstractSalsa20Processor::GetHashBlock(const int streamNumber) const -{ - const auto blockIndexOffset = m_stream_block_indices[streamNumber] * m_stream_count * SHA1_HASH_SIZE; - const auto streamOffset = static_cast<size_t>(streamNumber) * SHA1_HASH_SIZE; +uint8_t *AbstractSalsa20Processor::GetHashBlock(const int streamNumber) const { + const auto blockIndexOffset = m_stream_block_indices[streamNumber] * m_stream_count * SHA1_HASH_SIZE; + const auto streamOffset = static_cast<size_t>(streamNumber) * SHA1_HASH_SIZE; - return &m_block_hashes[blockIndexOffset + streamOffset]; + return &m_block_hashes[blockIndexOffset + streamOffset]; } -void AbstractSalsa20Processor::InitStreams(std::string& zoneName, const uint8_t* salsa20Key, size_t keySize) const -{ - const int zoneNameLength = zoneName.length(); - const size_t blockHashBufferSize = BLOCK_HASHES_COUNT * m_stream_count * SHA1_HASH_SIZE; +void AbstractSalsa20Processor::InitStreams(std::string &zoneName, const uint8_t *salsa20Key, size_t keySize) const { + const int zoneNameLength = zoneName.length(); + const size_t blockHashBufferSize = BLOCK_HASHES_COUNT * m_stream_count * SHA1_HASH_SIZE; - assert(blockHashBufferSize % 4 == 0); + assert(blockHashBufferSize % 4 == 0); - size_t zoneNameOffset = 0; - for (size_t i = 0; i < blockHashBufferSize; i += 4) - { - *reinterpret_cast<uint32_t*>(&m_block_hashes[i]) = 0x1010101 * zoneName[zoneNameOffset++]; + size_t zoneNameOffset = 0; + for (size_t i = 0; i < blockHashBufferSize; i += 4) { + *reinterpret_cast<uint32_t *>(&m_block_hashes[i]) = 0x1010101 * zoneName[zoneNameOffset++]; - zoneNameOffset %= zoneNameLength; - } + zoneNameOffset %= zoneNameLength; + } - for (auto stream = 0; stream < m_stream_count; stream++) - { - m_stream_block_indices[stream] = 0; + for (auto stream = 0; stream < m_stream_count; stream++) { + m_stream_block_indices[stream] = 0; - m_stream_contexts[stream].m_salsa20 = Crypto::CreateSalsa20(salsa20Key, keySize); - m_stream_contexts[stream].m_sha1 = Crypto::CreateSHA1(); - } + m_stream_contexts[stream].m_salsa20 = Crypto::CreateSalsa20(salsa20Key, keySize); + m_stream_contexts[stream].m_sha1 = Crypto::CreateSHA1(); + } } -void AbstractSalsa20Processor::GetCapturedData(const uint8_t** pCapturedData, size_t* pSize) -{ - assert(pCapturedData != nullptr); - assert(pSize != nullptr); +void AbstractSalsa20Processor::GetCapturedData(const uint8_t **pCapturedData, size_t *pSize) { + assert(pCapturedData != nullptr); + assert(pSize != nullptr); - *pCapturedData = m_block_hashes.get(); - *pSize = BLOCK_HASHES_COUNT * m_stream_count * SHA1_HASH_SIZE; + *pCapturedData = m_block_hashes.get(); + *pSize = BLOCK_HASHES_COUNT * m_stream_count * SHA1_HASH_SIZE; } diff --git a/src/ZoneCommon/Zone/XChunk/AbstractSalsa20Processor.h b/src/ZoneCommon/Zone/XChunk/AbstractSalsa20Processor.h index 884ae18e7..42f87e944 100644 --- a/src/ZoneCommon/Zone/XChunk/AbstractSalsa20Processor.h +++ b/src/ZoneCommon/Zone/XChunk/AbstractSalsa20Processor.h @@ -3,43 +3,41 @@ #include <memory> #include <string> -#include "Utils/ClassUtils.h" #include "Crypto.h" +#include "Utils/ClassUtils.h" #include "Utils/ICapturedDataProvider.h" -class AbstractSalsa20Processor : public ICapturedDataProvider -{ +class AbstractSalsa20Processor : public ICapturedDataProvider { protected: - static constexpr int BLOCK_HASHES_COUNT = 200; - static constexpr int SHA1_HASH_SIZE = 20; - static constexpr int SALSA20_IV_SIZE = 8; + static constexpr int BLOCK_HASHES_COUNT = 200; + static constexpr int SHA1_HASH_SIZE = 20; + static constexpr int SALSA20_IV_SIZE = 8; - class StreamContext - { - public: - std::unique_ptr<IStreamCipher> m_salsa20; - std::unique_ptr<IHashFunction> m_sha1; - }; + class StreamContext { + public: + std::unique_ptr<IStreamCipher> m_salsa20; + std::unique_ptr<IHashFunction> m_sha1; + }; - int m_stream_count; - std::unique_ptr<StreamContext[]> m_stream_contexts; + int m_stream_count; + std::unique_ptr<StreamContext[]> m_stream_contexts; - // m_block_hashes[BLOCK_HASHES_COUNT][numStreams][HASH_SIZE] - std::unique_ptr<uint8_t[]> m_block_hashes; - std::unique_ptr<unsigned int[]> m_stream_block_indices; + // m_block_hashes[BLOCK_HASHES_COUNT][numStreams][HASH_SIZE] + std::unique_ptr<uint8_t[]> m_block_hashes; + std::unique_ptr<unsigned int[]> m_stream_block_indices; - AbstractSalsa20Processor(int streamCount, std::string& zoneName, const uint8_t* salsa20Key, size_t keySize); + AbstractSalsa20Processor(int streamCount, std::string &zoneName, const uint8_t *salsa20Key, size_t keySize); - _NODISCARD uint8_t* GetHashBlock(int streamNumber) const; + _NODISCARD uint8_t *GetHashBlock(int streamNumber) const; - void InitStreams(std::string& zoneName, const uint8_t* salsa20Key, size_t keySize) const; + void InitStreams(std::string &zoneName, const uint8_t *salsa20Key, size_t keySize) const; public: - virtual ~AbstractSalsa20Processor() = default; - AbstractSalsa20Processor(const AbstractSalsa20Processor& other) = delete; - AbstractSalsa20Processor(AbstractSalsa20Processor&& other) noexcept = default; - AbstractSalsa20Processor& operator=(const AbstractSalsa20Processor& other) = delete; - AbstractSalsa20Processor& operator=(AbstractSalsa20Processor&& other) noexcept = default; + virtual ~AbstractSalsa20Processor() = default; + AbstractSalsa20Processor(const AbstractSalsa20Processor &other) = delete; + AbstractSalsa20Processor(AbstractSalsa20Processor &&other) noexcept = default; + AbstractSalsa20Processor &operator=(const AbstractSalsa20Processor &other) = delete; + AbstractSalsa20Processor &operator=(AbstractSalsa20Processor &&other) noexcept = default; - void GetCapturedData(const uint8_t** pCapturedData, size_t* pSize) override; + void GetCapturedData(const uint8_t **pCapturedData, size_t *pSize) override; }; diff --git a/src/ZoneCommon/Zone/XChunk/IXChunkProcessor.h b/src/ZoneCommon/Zone/XChunk/IXChunkProcessor.h index 7eb164dec..477b77930 100644 --- a/src/ZoneCommon/Zone/XChunk/IXChunkProcessor.h +++ b/src/ZoneCommon/Zone/XChunk/IXChunkProcessor.h @@ -1,11 +1,10 @@ #pragma once -#include <cstdint> #include <cstddef> +#include <cstdint> -class IXChunkProcessor -{ +class IXChunkProcessor { public: - virtual ~IXChunkProcessor() = default; - virtual size_t Process(int streamNumber, const uint8_t* input, size_t inputLength, uint8_t* output, size_t outputBufferSize) = 0; + virtual ~IXChunkProcessor() = default; + virtual size_t Process(int streamNumber, const uint8_t *input, size_t inputLength, uint8_t *output, size_t outputBufferSize) = 0; }; diff --git a/src/ZoneCommon/Zone/XChunk/XChunkException.cpp b/src/ZoneCommon/Zone/XChunk/XChunkException.cpp index 7d437def6..6dd3c0147 100644 --- a/src/ZoneCommon/Zone/XChunk/XChunkException.cpp +++ b/src/ZoneCommon/Zone/XChunk/XChunkException.cpp @@ -1,16 +1,7 @@ #include "XChunkException.h" -XChunkException::XChunkException(std::string message) - : m_message(std::move(message)) -{ -} +XChunkException::XChunkException(std::string message) : m_message(std::move(message)) {} -char const* XChunkException::what() const noexcept -{ - return m_message.c_str(); -} +char const *XChunkException::what() const noexcept { return m_message.c_str(); } -const std::string& XChunkException::Message() const -{ - return m_message; -} +const std::string &XChunkException::Message() const { return m_message; } diff --git a/src/ZoneCommon/Zone/XChunk/XChunkException.h b/src/ZoneCommon/Zone/XChunk/XChunkException.h index 79df22136..1fbef5823 100644 --- a/src/ZoneCommon/Zone/XChunk/XChunkException.h +++ b/src/ZoneCommon/Zone/XChunk/XChunkException.h @@ -4,13 +4,12 @@ #include "Utils/ClassUtils.h" -class XChunkException final : public std::exception -{ - std::string m_message; +class XChunkException final : public std::exception { + std::string m_message; public: - explicit XChunkException(std::string message); + explicit XChunkException(std::string message); - _NODISCARD char const* what() const noexcept override; - _NODISCARD const std::string& Message() const; + _NODISCARD char const *what() const noexcept override; + _NODISCARD const std::string &Message() const; }; diff --git a/src/ZoneCommon/Zone/XChunk/XChunkProcessorDeflate.cpp b/src/ZoneCommon/Zone/XChunk/XChunkProcessorDeflate.cpp index 0556ff101..6ddcf6f6c 100644 --- a/src/ZoneCommon/Zone/XChunk/XChunkProcessorDeflate.cpp +++ b/src/ZoneCommon/Zone/XChunk/XChunkProcessorDeflate.cpp @@ -1,35 +1,33 @@ #include "XChunkProcessorDeflate.h" - #include <cassert> #include <zlib.h> #include <zutil.h> #include "XChunkException.h" -size_t XChunkProcessorDeflate::Process(int streamNumber, const uint8_t* input, const size_t inputLength, uint8_t* output, const size_t outputBufferSize) -{ - z_stream stream{}; - stream.zalloc = Z_NULL; - stream.zfree = Z_NULL; - stream.opaque = Z_NULL; - - auto ret = deflateInit2(&stream, Z_BEST_COMPRESSION, Z_DEFLATED, -DEF_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY); - if (ret != Z_OK) - throw XChunkException("Initializing deflate failed."); +size_t XChunkProcessorDeflate::Process(int streamNumber, const uint8_t *input, const size_t inputLength, uint8_t *output, const size_t outputBufferSize) { + z_stream stream{}; + stream.zalloc = Z_NULL; + stream.zfree = Z_NULL; + stream.opaque = Z_NULL; + + auto ret = deflateInit2(&stream, Z_BEST_COMPRESSION, Z_DEFLATED, -DEF_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY); + if (ret != Z_OK) + throw XChunkException("Initializing deflate failed."); - stream.avail_in = inputLength; - stream.next_in = input; - stream.avail_out = outputBufferSize; - stream.next_out = output; + stream.avail_in = inputLength; + stream.next_in = input; + stream.avail_out = outputBufferSize; + stream.next_out = output; - ret = deflate(&stream, Z_FINISH); - if (ret != Z_STREAM_END) - throw XChunkException("Failed to deflate memory of zone."); + ret = deflate(&stream, Z_FINISH); + if (ret != Z_STREAM_END) + throw XChunkException("Failed to deflate memory of zone."); - const size_t outputSize = stream.total_out; + const size_t outputSize = stream.total_out; - deflateEnd(&stream); + deflateEnd(&stream); - return outputSize; + return outputSize; } diff --git a/src/ZoneCommon/Zone/XChunk/XChunkProcessorDeflate.h b/src/ZoneCommon/Zone/XChunk/XChunkProcessorDeflate.h index 7c158c861..c7cea0751 100644 --- a/src/ZoneCommon/Zone/XChunk/XChunkProcessorDeflate.h +++ b/src/ZoneCommon/Zone/XChunk/XChunkProcessorDeflate.h @@ -1,8 +1,7 @@ #pragma once #include "IXChunkProcessor.h" -class XChunkProcessorDeflate final : public IXChunkProcessor -{ +class XChunkProcessorDeflate final : public IXChunkProcessor { public: - size_t Process(int streamNumber, const uint8_t* input, size_t inputLength, uint8_t* output, size_t outputBufferSize) override; + size_t Process(int streamNumber, const uint8_t *input, size_t inputLength, uint8_t *output, size_t outputBufferSize) override; }; diff --git a/src/ZoneCommon/Zone/XChunk/XChunkProcessorInflate.cpp b/src/ZoneCommon/Zone/XChunk/XChunkProcessorInflate.cpp index 82203921d..15c21cc0b 100644 --- a/src/ZoneCommon/Zone/XChunk/XChunkProcessorInflate.cpp +++ b/src/ZoneCommon/Zone/XChunk/XChunkProcessorInflate.cpp @@ -5,29 +5,28 @@ #include "XChunkException.h" -size_t XChunkProcessorInflate::Process(int streamNumber, const uint8_t* input, const size_t inputLength, uint8_t* output, const size_t outputBufferSize) -{ - z_stream stream{}; - stream.zalloc = Z_NULL; - stream.zfree = Z_NULL; - stream.opaque = Z_NULL; +size_t XChunkProcessorInflate::Process(int streamNumber, const uint8_t *input, const size_t inputLength, uint8_t *output, const size_t outputBufferSize) { + z_stream stream{}; + stream.zalloc = Z_NULL; + stream.zfree = Z_NULL; + stream.opaque = Z_NULL; - auto ret = inflateInit2(&stream, -DEF_WBITS); - if (ret != Z_OK) - throw XChunkException("Initializing inflate failed."); + auto ret = inflateInit2(&stream, -DEF_WBITS); + if (ret != Z_OK) + throw XChunkException("Initializing inflate failed."); - stream.avail_in = inputLength; - stream.next_in = input; - stream.avail_out = outputBufferSize; - stream.next_out = output; + stream.avail_in = inputLength; + stream.next_in = input; + stream.avail_out = outputBufferSize; + stream.next_out = output; - ret = inflate(&stream, Z_FULL_FLUSH); - if (ret != Z_STREAM_END) - throw XChunkException("Zone has invalid or unsupported compression. Inflate failed"); + ret = inflate(&stream, Z_FULL_FLUSH); + if (ret != Z_STREAM_END) + throw XChunkException("Zone has invalid or unsupported compression. Inflate failed"); - const size_t outputSize = stream.total_out; + const size_t outputSize = stream.total_out; - inflateEnd(&stream); + inflateEnd(&stream); - return outputSize; + return outputSize; } diff --git a/src/ZoneCommon/Zone/XChunk/XChunkProcessorInflate.h b/src/ZoneCommon/Zone/XChunk/XChunkProcessorInflate.h index c328219fd..661b530d6 100644 --- a/src/ZoneCommon/Zone/XChunk/XChunkProcessorInflate.h +++ b/src/ZoneCommon/Zone/XChunk/XChunkProcessorInflate.h @@ -1,8 +1,7 @@ #pragma once #include "IXChunkProcessor.h" -class XChunkProcessorInflate final : public IXChunkProcessor -{ +class XChunkProcessorInflate final : public IXChunkProcessor { public: - size_t Process(int streamNumber, const uint8_t* input, size_t inputLength, uint8_t* output, size_t outputBufferSize) override; + size_t Process(int streamNumber, const uint8_t *input, size_t inputLength, uint8_t *output, size_t outputBufferSize) override; }; diff --git a/src/ZoneCommon/Zone/XChunk/XChunkProcessorSalsa20Decryption.cpp b/src/ZoneCommon/Zone/XChunk/XChunkProcessorSalsa20Decryption.cpp index e44990687..c26a9392c 100644 --- a/src/ZoneCommon/Zone/XChunk/XChunkProcessorSalsa20Decryption.cpp +++ b/src/ZoneCommon/Zone/XChunk/XChunkProcessorSalsa20Decryption.cpp @@ -2,43 +2,41 @@ #include <cassert> -#include "Crypto.h" #include "AbstractSalsa20Processor.h" +#include "Crypto.h" -XChunkProcessorSalsa20Decryption::XChunkProcessorSalsa20Decryption(const int streamCount, std::string& zoneName, const uint8_t* salsa20Key, const size_t keySize) - : AbstractSalsa20Processor(streamCount, zoneName, salsa20Key, keySize) -{ -} +XChunkProcessorSalsa20Decryption::XChunkProcessorSalsa20Decryption(const int streamCount, std::string &zoneName, const uint8_t *salsa20Key, + const size_t keySize) + : AbstractSalsa20Processor(streamCount, zoneName, salsa20Key, keySize) {} -size_t XChunkProcessorSalsa20Decryption::Process(const int streamNumber, const uint8_t* input, const size_t inputLength, uint8_t* output, const size_t outputBufferSize) -{ - assert(streamNumber >= 0 && streamNumber < m_stream_count); - assert(input != nullptr); - assert(output != nullptr); - assert(inputLength <= outputBufferSize); +size_t XChunkProcessorSalsa20Decryption::Process(const int streamNumber, const uint8_t *input, const size_t inputLength, uint8_t *output, + const size_t outputBufferSize) { + assert(streamNumber >= 0 && streamNumber < m_stream_count); + assert(input != nullptr); + assert(output != nullptr); + assert(inputLength <= outputBufferSize); - auto& streamContext = m_stream_contexts[streamNumber]; + auto &streamContext = m_stream_contexts[streamNumber]; - // Initialize Salsa20 with an IV of the first 8 bytes of the current hash block - streamContext.m_salsa20->SetIV(GetHashBlock(streamNumber), SALSA20_IV_SIZE); - streamContext.m_salsa20->Process(input, output, inputLength); + // Initialize Salsa20 with an IV of the first 8 bytes of the current hash block + streamContext.m_salsa20->SetIV(GetHashBlock(streamNumber), SALSA20_IV_SIZE); + streamContext.m_salsa20->Process(input, output, inputLength); - // Hash decrypted XChunk - uint8_t blockSha1Hash[SHA1_HASH_SIZE]; - streamContext.m_sha1->Init(); - streamContext.m_sha1->Process(output, inputLength); - streamContext.m_sha1->Finish(&blockSha1Hash); + // Hash decrypted XChunk + uint8_t blockSha1Hash[SHA1_HASH_SIZE]; + streamContext.m_sha1->Init(); + streamContext.m_sha1->Process(output, inputLength); + streamContext.m_sha1->Finish(&blockSha1Hash); - // Advance index to next hash block - m_stream_block_indices[streamNumber] = (m_stream_block_indices[streamNumber] + 1) % BLOCK_HASHES_COUNT; + // Advance index to next hash block + m_stream_block_indices[streamNumber] = (m_stream_block_indices[streamNumber] + 1) % BLOCK_HASHES_COUNT; - auto* nextHashBlock = GetHashBlock(streamNumber); + auto *nextHashBlock = GetHashBlock(streamNumber); - // XOR the upcoming hash block with the hash of the XChunk utilizing the previous hash block - for (unsigned int hashOffset = 0; hashOffset < sizeof(blockSha1Hash); hashOffset++) - { - nextHashBlock[hashOffset] ^= blockSha1Hash[hashOffset]; - } + // XOR the upcoming hash block with the hash of the XChunk utilizing the previous hash block + for (unsigned int hashOffset = 0; hashOffset < sizeof(blockSha1Hash); hashOffset++) { + nextHashBlock[hashOffset] ^= blockSha1Hash[hashOffset]; + } - return inputLength; + return inputLength; } diff --git a/src/ZoneCommon/Zone/XChunk/XChunkProcessorSalsa20Decryption.h b/src/ZoneCommon/Zone/XChunk/XChunkProcessorSalsa20Decryption.h index 380768483..ea505ba77 100644 --- a/src/ZoneCommon/Zone/XChunk/XChunkProcessorSalsa20Decryption.h +++ b/src/ZoneCommon/Zone/XChunk/XChunkProcessorSalsa20Decryption.h @@ -1,13 +1,12 @@ #pragma once #include <string> -#include "IXChunkProcessor.h" #include "AbstractSalsa20Processor.h" +#include "IXChunkProcessor.h" -class XChunkProcessorSalsa20Decryption final : public IXChunkProcessor, public AbstractSalsa20Processor -{ +class XChunkProcessorSalsa20Decryption final : public IXChunkProcessor, public AbstractSalsa20Processor { public: - XChunkProcessorSalsa20Decryption(int streamCount, std::string& zoneName, const uint8_t* salsa20Key, size_t keySize); + XChunkProcessorSalsa20Decryption(int streamCount, std::string &zoneName, const uint8_t *salsa20Key, size_t keySize); - size_t Process(int streamNumber, const uint8_t* input, size_t inputLength, uint8_t* output, size_t outputBufferSize) override; + size_t Process(int streamNumber, const uint8_t *input, size_t inputLength, uint8_t *output, size_t outputBufferSize) override; }; diff --git a/src/ZoneCommon/Zone/XChunk/XChunkProcessorSalsa20Encryption.cpp b/src/ZoneCommon/Zone/XChunk/XChunkProcessorSalsa20Encryption.cpp index b95795676..6d93300e3 100644 --- a/src/ZoneCommon/Zone/XChunk/XChunkProcessorSalsa20Encryption.cpp +++ b/src/ZoneCommon/Zone/XChunk/XChunkProcessorSalsa20Encryption.cpp @@ -2,40 +2,38 @@ #include <cassert> -XChunkProcessorSalsa20Encryption::XChunkProcessorSalsa20Encryption(const int streamCount, std::string& zoneName, const uint8_t* salsa20Key, const size_t keySize) - : AbstractSalsa20Processor(streamCount, zoneName, salsa20Key, keySize) -{ -} +XChunkProcessorSalsa20Encryption::XChunkProcessorSalsa20Encryption(const int streamCount, std::string &zoneName, const uint8_t *salsa20Key, + const size_t keySize) + : AbstractSalsa20Processor(streamCount, zoneName, salsa20Key, keySize) {} -size_t XChunkProcessorSalsa20Encryption::Process(const int streamNumber, const uint8_t* input, const size_t inputLength, uint8_t* output, const size_t outputBufferSize) -{ - assert(streamNumber >= 0 && streamNumber < m_stream_count); - assert(input != nullptr); - assert(output != nullptr); - assert(inputLength <= outputBufferSize); +size_t XChunkProcessorSalsa20Encryption::Process(const int streamNumber, const uint8_t *input, const size_t inputLength, uint8_t *output, + const size_t outputBufferSize) { + assert(streamNumber >= 0 && streamNumber < m_stream_count); + assert(input != nullptr); + assert(output != nullptr); + assert(inputLength <= outputBufferSize); - auto& streamContext = m_stream_contexts[streamNumber]; + auto &streamContext = m_stream_contexts[streamNumber]; - // Hash not yet encrypted XChunk - uint8_t blockSha1Hash[SHA1_HASH_SIZE]; - streamContext.m_sha1->Init(); - streamContext.m_sha1->Process(input, inputLength); - streamContext.m_sha1->Finish(&blockSha1Hash); + // Hash not yet encrypted XChunk + uint8_t blockSha1Hash[SHA1_HASH_SIZE]; + streamContext.m_sha1->Init(); + streamContext.m_sha1->Process(input, inputLength); + streamContext.m_sha1->Finish(&blockSha1Hash); - // Initialize Salsa20 with an IV of the first 8 bytes of the current hash block - streamContext.m_salsa20->SetIV(GetHashBlock(streamNumber), SALSA20_IV_SIZE); - streamContext.m_salsa20->Process(input, output, inputLength); + // Initialize Salsa20 with an IV of the first 8 bytes of the current hash block + streamContext.m_salsa20->SetIV(GetHashBlock(streamNumber), SALSA20_IV_SIZE); + streamContext.m_salsa20->Process(input, output, inputLength); - // Advance index to next hash block - m_stream_block_indices[streamNumber] = (m_stream_block_indices[streamNumber] + 1) % BLOCK_HASHES_COUNT; + // Advance index to next hash block + m_stream_block_indices[streamNumber] = (m_stream_block_indices[streamNumber] + 1) % BLOCK_HASHES_COUNT; - auto* nextHashBlock = GetHashBlock(streamNumber); + auto *nextHashBlock = GetHashBlock(streamNumber); - // XOR the upcoming hash block with the hash of the XChunk utilizing the previous hash block - for (unsigned int hashOffset = 0; hashOffset < sizeof(blockSha1Hash); hashOffset++) - { - nextHashBlock[hashOffset] ^= blockSha1Hash[hashOffset]; - } + // XOR the upcoming hash block with the hash of the XChunk utilizing the previous hash block + for (unsigned int hashOffset = 0; hashOffset < sizeof(blockSha1Hash); hashOffset++) { + nextHashBlock[hashOffset] ^= blockSha1Hash[hashOffset]; + } - return inputLength; + return inputLength; } diff --git a/src/ZoneCommon/Zone/XChunk/XChunkProcessorSalsa20Encryption.h b/src/ZoneCommon/Zone/XChunk/XChunkProcessorSalsa20Encryption.h index cc5637ed5..1358ee70e 100644 --- a/src/ZoneCommon/Zone/XChunk/XChunkProcessorSalsa20Encryption.h +++ b/src/ZoneCommon/Zone/XChunk/XChunkProcessorSalsa20Encryption.h @@ -5,10 +5,9 @@ #include "AbstractSalsa20Processor.h" #include "IXChunkProcessor.h" -class XChunkProcessorSalsa20Encryption final : public IXChunkProcessor, public AbstractSalsa20Processor -{ +class XChunkProcessorSalsa20Encryption final : public IXChunkProcessor, public AbstractSalsa20Processor { public: - XChunkProcessorSalsa20Encryption(int streamCount, std::string& zoneName, const uint8_t* salsa20Key, size_t keySize); + XChunkProcessorSalsa20Encryption(int streamCount, std::string &zoneName, const uint8_t *salsa20Key, size_t keySize); - size_t Process(int streamNumber, const uint8_t* input, size_t inputLength, uint8_t* output, size_t outputBufferSize) override; + size_t Process(int streamNumber, const uint8_t *input, size_t inputLength, uint8_t *output, size_t outputBufferSize) override; }; diff --git a/src/ZoneCommon/Zone/Zone.cpp b/src/ZoneCommon/Zone/Zone.cpp index 88a6b2265..e4d5f5dfc 100644 --- a/src/ZoneCommon/Zone/Zone.cpp +++ b/src/ZoneCommon/Zone/Zone.cpp @@ -1,33 +1,20 @@ #include "Zone.h" -Zone::Zone(std::string name, const zone_priority_t priority, IGame* game) - : m_memory(std::make_unique<ZoneMemory>()), - m_registered(false), - m_name(std::move(name)), - m_priority(priority), - m_language(GameLanguage::LANGUAGE_NONE), - m_game(game) -{ -} +Zone::Zone(std::string name, const zone_priority_t priority, IGame *game) + : m_memory(std::make_unique<ZoneMemory>()), m_registered(false), m_name(std::move(name)), m_priority(priority), m_language(GameLanguage::LANGUAGE_NONE), + m_game(game) {} -Zone::~Zone() -{ - if (m_registered) - { - m_game->RemoveZone(this); - } +Zone::~Zone() { + if (m_registered) { + m_game->RemoveZone(this); + } } -void Zone::Register() -{ - if (!m_registered) - { - m_game->AddZone(this); - m_registered = true; - } +void Zone::Register() { + if (!m_registered) { + m_game->AddZone(this); + m_registered = true; + } } -ZoneMemory* Zone::GetMemory() const -{ - return m_memory.get(); -} +ZoneMemory *Zone::GetMemory() const { return m_memory.get(); } diff --git a/src/ZoneCommon/Zone/Zone.h b/src/ZoneCommon/Zone/Zone.h index 2e4d7efdf..c3eafdcfe 100644 --- a/src/ZoneCommon/Zone/Zone.h +++ b/src/ZoneCommon/Zone/Zone.h @@ -3,39 +3,38 @@ #include <memory> #include <string> +#include "Game/GameLanguage.h" +#include "Game/IGame.h" +#include "Pool/ZoneAssetPools.h" #include "Utils/ClassUtils.h" #include "Zone/ZoneTypes.h" -#include "Pool/ZoneAssetPools.h" -#include "Game/IGame.h" -#include "Game/GameLanguage.h" #include "ZoneMemory.h" #include "ZoneScriptStrings.h" class IGame; class ZoneAssetPools; -class Zone -{ - std::unique_ptr<ZoneMemory> m_memory; +class Zone { + std::unique_ptr<ZoneMemory> m_memory; - bool m_registered; + bool m_registered; public: - std::string m_name; - zone_priority_t m_priority; - GameLanguage m_language; - IGame* m_game; - ZoneScriptStrings m_script_strings; - std::unique_ptr<ZoneAssetPools> m_pools; - - Zone(std::string name, zone_priority_t priority, IGame* game); - ~Zone(); - Zone(const Zone& other) = delete; - Zone(Zone&& other) noexcept = default; - Zone& operator=(const Zone& other) = delete; - Zone& operator=(Zone&& other) noexcept = default; - - void Register(); - - _NODISCARD ZoneMemory* GetMemory() const; + std::string m_name; + zone_priority_t m_priority; + GameLanguage m_language; + IGame *m_game; + ZoneScriptStrings m_script_strings; + std::unique_ptr<ZoneAssetPools> m_pools; + + Zone(std::string name, zone_priority_t priority, IGame *game); + ~Zone(); + Zone(const Zone &other) = delete; + Zone(Zone &&other) noexcept = default; + Zone &operator=(const Zone &other) = delete; + Zone &operator=(Zone &&other) noexcept = default; + + void Register(); + + _NODISCARD ZoneMemory *GetMemory() const; }; diff --git a/src/ZoneCommon/Zone/ZoneMemory.cpp b/src/ZoneCommon/Zone/ZoneMemory.cpp index 0b3745d26..14ff1bc32 100644 --- a/src/ZoneCommon/Zone/ZoneMemory.cpp +++ b/src/ZoneCommon/Zone/ZoneMemory.cpp @@ -1,9 +1,5 @@ #include "ZoneMemory.h" -ZoneMemory::ZoneMemory() -= default; +ZoneMemory::ZoneMemory() = default; -void ZoneMemory::AddBlock(std::unique_ptr<XBlock> block) -{ - m_blocks.emplace_back(std::move(block)); -} +void ZoneMemory::AddBlock(std::unique_ptr<XBlock> block) { m_blocks.emplace_back(std::move(block)); } diff --git a/src/ZoneCommon/Zone/ZoneMemory.h b/src/ZoneCommon/Zone/ZoneMemory.h index d5120dee8..1684aa00a 100644 --- a/src/ZoneCommon/Zone/ZoneMemory.h +++ b/src/ZoneCommon/Zone/ZoneMemory.h @@ -6,12 +6,11 @@ #include "Utils/MemoryManager.h" #include "Zone/XBlock.h" -class ZoneMemory : public MemoryManager -{ - std::vector<std::unique_ptr<XBlock>> m_blocks; +class ZoneMemory : public MemoryManager { + std::vector<std::unique_ptr<XBlock>> m_blocks; public: - ZoneMemory(); + ZoneMemory(); - void AddBlock(std::unique_ptr<XBlock> block); + void AddBlock(std::unique_ptr<XBlock> block); }; diff --git a/src/ZoneCommon/Zone/ZoneScriptStrings.cpp b/src/ZoneCommon/Zone/ZoneScriptStrings.cpp index d78cdf69d..4089967b8 100644 --- a/src/ZoneCommon/Zone/ZoneScriptStrings.cpp +++ b/src/ZoneCommon/Zone/ZoneScriptStrings.cpp @@ -1,188 +1,151 @@ #include "ZoneScriptStrings.h" #include <cassert> -#include <stdexcept> #include <sstream> +#include <stdexcept> -ZoneScriptStrings::ZoneScriptStrings() - : m_null_entry_pos(0) -{ - // Make script string 0 a nullptr string - m_scr_strings.emplace_back(); +ZoneScriptStrings::ZoneScriptStrings() : m_null_entry_pos(0) { + // Make script string 0 a nullptr string + m_scr_strings.emplace_back(); } -void ZoneScriptStrings::InitializeForExistingZone() -{ - m_null_entry_pos = -1; - m_scr_strings.clear(); +void ZoneScriptStrings::InitializeForExistingZone() { + m_null_entry_pos = -1; + m_scr_strings.clear(); } -void ZoneScriptStrings::InitializeForExistingZone(const char** scrStrList, const size_t scrStrCount) -{ - InitializeForExistingZone(); +void ZoneScriptStrings::InitializeForExistingZone(const char **scrStrList, const size_t scrStrCount) { + InitializeForExistingZone(); - if (!scrStrList) - return; + if (!scrStrList) + return; - for (auto i = 0u; i < scrStrCount; i++) - AddScriptString(scrStrList[i]); + for (auto i = 0u; i < scrStrCount; i++) + AddScriptString(scrStrList[i]); } -void ZoneScriptStrings::AddScriptString(const char* value) -{ - const auto newStringIndex = m_scr_strings.size(); - const auto newScrStringIndex = static_cast<scr_string_t>(newStringIndex); - - if (value != nullptr) - { - m_scr_strings.emplace_back(value); - m_scr_string_lookup[value] = newScrStringIndex; - } - else - { - assert(m_null_entry_pos < 0); // If null index is already set, the previous cost will not be considered null string anymore. - m_scr_strings.emplace_back(); - m_null_entry_pos = static_cast<int>(newStringIndex); - } -} +void ZoneScriptStrings::AddScriptString(const char *value) { + const auto newStringIndex = m_scr_strings.size(); + const auto newScrStringIndex = static_cast<scr_string_t>(newStringIndex); -void ZoneScriptStrings::AddScriptString(const std::string& value) -{ - const auto newScrStringIndex = static_cast<scr_string_t>(m_scr_strings.size()); + if (value != nullptr) { m_scr_strings.emplace_back(value); m_scr_string_lookup[value] = newScrStringIndex; + } else { + assert(m_null_entry_pos < 0); // If null index is already set, the previous cost will not be considered null string anymore. + m_scr_strings.emplace_back(); + m_null_entry_pos = static_cast<int>(newStringIndex); + } } -scr_string_t ZoneScriptStrings::AddOrGetScriptString(const char* value) -{ - if (value != nullptr) - { - const auto existingScriptString = m_scr_string_lookup.find(value); - if (existingScriptString != m_scr_string_lookup.end()) - return existingScriptString->second; - - const auto newScrStringIndex = static_cast<scr_string_t>(m_scr_strings.size()); - m_scr_strings.emplace_back(value); - m_scr_string_lookup[value] = newScrStringIndex; - return newScrStringIndex; - } - - if (m_null_entry_pos < 0) - { - const auto newStringIndex = m_scr_strings.size(); - m_scr_strings.emplace_back(); - m_null_entry_pos = static_cast<int>(newStringIndex); - return static_cast<scr_string_t>(newStringIndex); - } - return static_cast<scr_string_t>(m_null_entry_pos); +void ZoneScriptStrings::AddScriptString(const std::string &value) { + const auto newScrStringIndex = static_cast<scr_string_t>(m_scr_strings.size()); + m_scr_strings.emplace_back(value); + m_scr_string_lookup[value] = newScrStringIndex; } -scr_string_t ZoneScriptStrings::AddOrGetScriptString(const std::string& value) -{ +scr_string_t ZoneScriptStrings::AddOrGetScriptString(const char *value) { + if (value != nullptr) { const auto existingScriptString = m_scr_string_lookup.find(value); if (existingScriptString != m_scr_string_lookup.end()) - return existingScriptString->second; + return existingScriptString->second; const auto newScrStringIndex = static_cast<scr_string_t>(m_scr_strings.size()); m_scr_strings.emplace_back(value); m_scr_string_lookup[value] = newScrStringIndex; - return newScrStringIndex; -} + } -scr_string_t ZoneScriptStrings::GetScriptString(const char* value) const -{ - if (value == nullptr) - { - if (m_null_entry_pos >= 0) - return static_cast<scr_string_t>(m_null_entry_pos); + if (m_null_entry_pos < 0) { + const auto newStringIndex = m_scr_strings.size(); + m_scr_strings.emplace_back(); + m_null_entry_pos = static_cast<int>(newStringIndex); + return static_cast<scr_string_t>(newStringIndex); + } + return static_cast<scr_string_t>(m_null_entry_pos); +} - std::ostringstream str; - str << "Unable to find script string nullptr"; - throw std::runtime_error(str.str()); - } +scr_string_t ZoneScriptStrings::AddOrGetScriptString(const std::string &value) { + const auto existingScriptString = m_scr_string_lookup.find(value); + if (existingScriptString != m_scr_string_lookup.end()) + return existingScriptString->second; - const auto existingScriptString = m_scr_string_lookup.find(value); - if (existingScriptString != m_scr_string_lookup.end()) - return existingScriptString->second; + const auto newScrStringIndex = static_cast<scr_string_t>(m_scr_strings.size()); + m_scr_strings.emplace_back(value); + m_scr_string_lookup[value] = newScrStringIndex; - std::ostringstream str; - str << "Unable to find script string \"" << value << "\""; - throw std::runtime_error(str.str()); + return newScrStringIndex; } -scr_string_t ZoneScriptStrings::GetScriptString(const std::string& value) const -{ - const auto existingScriptString = m_scr_string_lookup.find(value); - if (existingScriptString != m_scr_string_lookup.end()) - return existingScriptString->second; +scr_string_t ZoneScriptStrings::GetScriptString(const char *value) const { + if (value == nullptr) { + if (m_null_entry_pos >= 0) + return static_cast<scr_string_t>(m_null_entry_pos); std::ostringstream str; - str << "Unable to find script string \"" << value << "\""; + str << "Unable to find script string nullptr"; throw std::runtime_error(str.str()); -} + } -size_t ZoneScriptStrings::Count() const -{ - return m_scr_strings.size(); + const auto existingScriptString = m_scr_string_lookup.find(value); + if (existingScriptString != m_scr_string_lookup.end()) + return existingScriptString->second; + + std::ostringstream str; + str << "Unable to find script string \"" << value << "\""; + throw std::runtime_error(str.str()); } -bool ZoneScriptStrings::Empty() const -{ - return m_scr_strings.empty(); +scr_string_t ZoneScriptStrings::GetScriptString(const std::string &value) const { + const auto existingScriptString = m_scr_string_lookup.find(value); + if (existingScriptString != m_scr_string_lookup.end()) + return existingScriptString->second; + + std::ostringstream str; + str << "Unable to find script string \"" << value << "\""; + throw std::runtime_error(str.str()); } -const char* ZoneScriptStrings::CValue(const size_t index) const -{ - if (index > m_scr_strings.size()) - { - std::ostringstream str; - str << "Script string index '" << index << "' is not inside range of zone script strings (count: " << m_scr_strings.size() << ")"; - throw std::runtime_error(str.str()); - } +size_t ZoneScriptStrings::Count() const { return m_scr_strings.size(); } - if (m_null_entry_pos == static_cast<int>(index)) - return nullptr; +bool ZoneScriptStrings::Empty() const { return m_scr_strings.empty(); } - return m_scr_strings[index].c_str(); -} +const char *ZoneScriptStrings::CValue(const size_t index) const { + if (index > m_scr_strings.size()) { + std::ostringstream str; + str << "Script string index '" << index << "' is not inside range of zone script strings (count: " << m_scr_strings.size() << ")"; + throw std::runtime_error(str.str()); + } -const std::string& ZoneScriptStrings::Value(const size_t index) const -{ - return (*this)[index]; -} + if (m_null_entry_pos == static_cast<int>(index)) + return nullptr; -const std::string& ZoneScriptStrings::Value(const size_t index, bool& isNull) const -{ - if (index > m_scr_strings.size()) - { - std::ostringstream str; - str << "Script string index '" << index << "' is not inside range of zone script strings (count: " << m_scr_strings.size() << ")"; - throw std::runtime_error(str.str()); - } - - isNull = m_null_entry_pos == static_cast<int>(index); - return m_scr_strings[index]; + return m_scr_strings[index].c_str(); } -const std::string& ZoneScriptStrings::operator[](const size_t index) const -{ - if (index > m_scr_strings.size()) - { - std::ostringstream str; - str << "Script string index '" << index << "' is not inside range of zone script strings (count: " << m_scr_strings.size() << ")"; - throw std::runtime_error(str.str()); - } +const std::string &ZoneScriptStrings::Value(const size_t index) const { return (*this)[index]; } - return m_scr_strings[index]; -} +const std::string &ZoneScriptStrings::Value(const size_t index, bool &isNull) const { + if (index > m_scr_strings.size()) { + std::ostringstream str; + str << "Script string index '" << index << "' is not inside range of zone script strings (count: " << m_scr_strings.size() << ")"; + throw std::runtime_error(str.str()); + } -std::vector<std::string>::const_iterator ZoneScriptStrings::begin() const -{ - return m_scr_strings.cbegin(); + isNull = m_null_entry_pos == static_cast<int>(index); + return m_scr_strings[index]; } -std::vector<std::string>::const_iterator ZoneScriptStrings::end() const -{ - return m_scr_strings.end(); +const std::string &ZoneScriptStrings::operator[](const size_t index) const { + if (index > m_scr_strings.size()) { + std::ostringstream str; + str << "Script string index '" << index << "' is not inside range of zone script strings (count: " << m_scr_strings.size() << ")"; + throw std::runtime_error(str.str()); + } + + return m_scr_strings[index]; } + +std::vector<std::string>::const_iterator ZoneScriptStrings::begin() const { return m_scr_strings.cbegin(); } + +std::vector<std::string>::const_iterator ZoneScriptStrings::end() const { return m_scr_strings.end(); } diff --git a/src/ZoneCommon/Zone/ZoneScriptStrings.h b/src/ZoneCommon/Zone/ZoneScriptStrings.h index 3ccbd3fdd..3ae3b435f 100644 --- a/src/ZoneCommon/Zone/ZoneScriptStrings.h +++ b/src/ZoneCommon/Zone/ZoneScriptStrings.h @@ -8,32 +8,31 @@ #include "Utils/ClassUtils.h" #include "Zone/ZoneTypes.h" -class ZoneScriptStrings -{ - int m_null_entry_pos; - std::vector<std::string> m_scr_strings; - std::unordered_map<std::string, scr_string_t> m_scr_string_lookup; +class ZoneScriptStrings { + int m_null_entry_pos; + std::vector<std::string> m_scr_strings; + std::unordered_map<std::string, scr_string_t> m_scr_string_lookup; public: - ZoneScriptStrings(); - - void InitializeForExistingZone(); - void InitializeForExistingZone(const char** scrStrList, size_t scrStrCount); - - void AddScriptString(const char* value); - void AddScriptString(const std::string& value); - scr_string_t AddOrGetScriptString(const char* value); - scr_string_t AddOrGetScriptString(const std::string& value); - _NODISCARD scr_string_t GetScriptString(const char* value) const; - _NODISCARD scr_string_t GetScriptString(const std::string& value) const; - - _NODISCARD size_t Count() const; - _NODISCARD bool Empty() const; - - _NODISCARD const char* CValue(size_t index) const; - _NODISCARD const std::string& Value(size_t index) const; - _NODISCARD const std::string& Value(size_t index, bool& isNull) const; - _NODISCARD const std::string& operator[](size_t index) const; - _NODISCARD std::vector<std::string>::const_iterator begin() const; - _NODISCARD std::vector<std::string>::const_iterator end() const; + ZoneScriptStrings(); + + void InitializeForExistingZone(); + void InitializeForExistingZone(const char **scrStrList, size_t scrStrCount); + + void AddScriptString(const char *value); + void AddScriptString(const std::string &value); + scr_string_t AddOrGetScriptString(const char *value); + scr_string_t AddOrGetScriptString(const std::string &value); + _NODISCARD scr_string_t GetScriptString(const char *value) const; + _NODISCARD scr_string_t GetScriptString(const std::string &value) const; + + _NODISCARD size_t Count() const; + _NODISCARD bool Empty() const; + + _NODISCARD const char *CValue(size_t index) const; + _NODISCARD const std::string &Value(size_t index) const; + _NODISCARD const std::string &Value(size_t index, bool &isNull) const; + _NODISCARD const std::string &operator[](size_t index) const; + _NODISCARD std::vector<std::string>::const_iterator begin() const; + _NODISCARD std::vector<std::string>::const_iterator end() const; }; \ No newline at end of file diff --git a/src/ZoneLoading/Game/IW3/ContentLoaderIW3.cpp b/src/ZoneLoading/Game/IW3/ContentLoaderIW3.cpp index 08e18ea5b..172d9c75f 100644 --- a/src/ZoneLoading/Game/IW3/ContentLoaderIW3.cpp +++ b/src/ZoneLoading/Game/IW3/ContentLoaderIW3.cpp @@ -32,56 +32,47 @@ using namespace IW3; -ContentLoader::ContentLoader() - : varXAsset(nullptr), - varScriptStringList(nullptr) -{ -} +ContentLoader::ContentLoader() : varXAsset(nullptr), varScriptStringList(nullptr) {} -void ContentLoader::LoadScriptStringList(const bool atStreamStart) -{ - m_stream->PushBlock(XFILE_BLOCK_VIRTUAL); +void ContentLoader::LoadScriptStringList(const bool atStreamStart) { + m_stream->PushBlock(XFILE_BLOCK_VIRTUAL); - if (atStreamStart) - m_stream->Load<ScriptStringList>(varScriptStringList); + if (atStreamStart) + m_stream->Load<ScriptStringList>(varScriptStringList); - if (varScriptStringList->strings != nullptr) - { - assert(varScriptStringList->strings == PTR_FOLLOWING); + if (varScriptStringList->strings != nullptr) { + assert(varScriptStringList->strings == PTR_FOLLOWING); - varScriptStringList->strings = m_stream->Alloc<const char*>(alignof(const char*)); - varXString = varScriptStringList->strings; - LoadXStringArray(true, varScriptStringList->count); + varScriptStringList->strings = m_stream->Alloc<const char *>(alignof(const char *)); + varXString = varScriptStringList->strings; + LoadXStringArray(true, varScriptStringList->count); - if (varScriptStringList->strings && varScriptStringList->count > 0) - m_zone->m_script_strings.InitializeForExistingZone(varScriptStringList->strings, static_cast<size_t>(varScriptStringList->count)); - } + if (varScriptStringList->strings && varScriptStringList->count > 0) + m_zone->m_script_strings.InitializeForExistingZone(varScriptStringList->strings, static_cast<size_t>(varScriptStringList->count)); + } - m_stream->PopBlock(); + m_stream->PopBlock(); - assert(m_zone->m_script_strings.Count() <= SCR_STRING_MAX + 1); + assert(m_zone->m_script_strings.Count() <= SCR_STRING_MAX + 1); } -void ContentLoader::LoadXAsset(const bool atStreamStart) const -{ -#define LOAD_ASSET(type_index, typeName, headerEntry) \ - case type_index: \ - { \ - Loader_##typeName loader(m_zone, m_stream); \ - loader.Load(&varXAsset->header.headerEntry); \ - break; \ - } -#define SKIP_ASSET(type_index, typeName, headerEntry) \ - case type_index: \ - break; - - assert(varXAsset != nullptr); - - if (atStreamStart) - m_stream->Load<XAsset>(varXAsset); - - switch (varXAsset->type) - { +void ContentLoader::LoadXAsset(const bool atStreamStart) const { +#define LOAD_ASSET(type_index, typeName, headerEntry) \ + case type_index: { \ + Loader_##typeName loader(m_zone, m_stream); \ + loader.Load(&varXAsset->header.headerEntry); \ + break; \ + } +#define SKIP_ASSET(type_index, typeName, headerEntry) \ + case type_index: \ + break; + + assert(varXAsset != nullptr); + + if (atStreamStart) + m_stream->Load<XAsset>(varXAsset); + + switch (varXAsset->type) { LOAD_ASSET(ASSET_TYPE_PHYSPRESET, PhysPreset, physPreset) LOAD_ASSET(ASSET_TYPE_XANIMPARTS, XAnimParts, parts) LOAD_ASSET(ASSET_TYPE_XMODEL, XModel, model) @@ -110,55 +101,49 @@ void ContentLoader::LoadXAsset(const bool atStreamStart) const LOAD_ASSET(ASSET_TYPE_RAWFILE, RawFile, rawfile) LOAD_ASSET(ASSET_TYPE_STRINGTABLE, StringTable, stringTable) - default: - { - throw UnsupportedAssetTypeException(varXAsset->type); - } - } + default: { + throw UnsupportedAssetTypeException(varXAsset->type); + } + } #undef LOAD_ASSET } -void ContentLoader::LoadXAssetArray(const bool atStreamStart, const size_t count) -{ - assert(varXAsset != nullptr); +void ContentLoader::LoadXAssetArray(const bool atStreamStart, const size_t count) { + assert(varXAsset != nullptr); - if (atStreamStart) - m_stream->Load<XAsset>(varXAsset, count); + if (atStreamStart) + m_stream->Load<XAsset>(varXAsset, count); - for (asset_type_t assetType = 0; assetType < ASSET_TYPE_COUNT; assetType++) - { - m_zone->m_pools->InitPoolDynamic(assetType); - } + for (asset_type_t assetType = 0; assetType < ASSET_TYPE_COUNT; assetType++) { + m_zone->m_pools->InitPoolDynamic(assetType); + } - for (size_t index = 0; index < count; index++) - { - LoadXAsset(false); - varXAsset++; - } + for (size_t index = 0; index < count; index++) { + LoadXAsset(false); + varXAsset++; + } } -void ContentLoader::Load(Zone* zone, IZoneInputStream* stream) -{ - m_zone = zone; - m_stream = stream; +void ContentLoader::Load(Zone *zone, IZoneInputStream *stream) { + m_zone = zone; + m_stream = stream; - m_stream->PushBlock(XFILE_BLOCK_VIRTUAL); + m_stream->PushBlock(XFILE_BLOCK_VIRTUAL); - XAssetList assetList{}; - m_stream->LoadDataRaw(&assetList, sizeof assetList); + XAssetList assetList{}; + m_stream->LoadDataRaw(&assetList, sizeof assetList); - varScriptStringList = &assetList.stringList; - LoadScriptStringList(false); + varScriptStringList = &assetList.stringList; + LoadScriptStringList(false); - if (assetList.assets != nullptr) - { - assert(assetList.assets == PTR_FOLLOWING); + if (assetList.assets != nullptr) { + assert(assetList.assets == PTR_FOLLOWING); - assetList.assets = m_stream->Alloc<XAsset>(alignof(XAsset)); - varXAsset = assetList.assets; - LoadXAssetArray(true, assetList.assetCount); - } + assetList.assets = m_stream->Alloc<XAsset>(alignof(XAsset)); + varXAsset = assetList.assets; + LoadXAssetArray(true, assetList.assetCount); + } - m_stream->PopBlock(); + m_stream->PopBlock(); } diff --git a/src/ZoneLoading/Game/IW3/ContentLoaderIW3.h b/src/ZoneLoading/Game/IW3/ContentLoaderIW3.h index 1790a1fce..7a80ae151 100644 --- a/src/ZoneLoading/Game/IW3/ContentLoaderIW3.h +++ b/src/ZoneLoading/Game/IW3/ContentLoaderIW3.h @@ -1,23 +1,21 @@ #pragma once +#include "Game/IW3/IW3.h" #include "Loading/ContentLoaderBase.h" #include "Loading/IContentLoadingEntryPoint.h" -#include "Game/IW3/IW3.h" -namespace IW3 -{ - class ContentLoader final : public ContentLoaderBase, public IContentLoadingEntryPoint - { - XAsset* varXAsset; - ScriptStringList* varScriptStringList; +namespace IW3 { +class ContentLoader final : public ContentLoaderBase, public IContentLoadingEntryPoint { + XAsset *varXAsset; + ScriptStringList *varScriptStringList; - void LoadScriptStringList(bool atStreamStart); + void LoadScriptStringList(bool atStreamStart); - void LoadXAsset(bool atStreamStart) const; - void LoadXAssetArray(bool atStreamStart, size_t count); + void LoadXAsset(bool atStreamStart) const; + void LoadXAssetArray(bool atStreamStart, size_t count); - public: - ContentLoader(); +public: + ContentLoader(); - void Load(Zone* zone, IZoneInputStream* stream) override; - }; -} + void Load(Zone *zone, IZoneInputStream *stream) override; +}; +} // namespace IW3 diff --git a/src/ZoneLoading/Game/IW3/XAssets/gfximage/gfximage_actions.cpp b/src/ZoneLoading/Game/IW3/XAssets/gfximage/gfximage_actions.cpp index f90cbd149..c7b576e5a 100644 --- a/src/ZoneLoading/Game/IW3/XAssets/gfximage/gfximage_actions.cpp +++ b/src/ZoneLoading/Game/IW3/XAssets/gfximage/gfximage_actions.cpp @@ -5,20 +5,13 @@ using namespace IW3; -Actions_GfxImage::Actions_GfxImage(Zone* zone) - : AssetLoadingActions(zone) -{ -} +Actions_GfxImage::Actions_GfxImage(Zone *zone) : AssetLoadingActions(zone) {} -void Actions_GfxImage::OnImageLoaded(GfxImage* image) const -{ - image->cardMemory.platform[0] = 0; -} +void Actions_GfxImage::OnImageLoaded(GfxImage *image) const { image->cardMemory.platform[0] = 0; } -void Actions_GfxImage::LoadImageData(GfxImageLoadDef* loadDef, GfxImage* image) const -{ - const size_t loadDefSize = offsetof(IW3::GfxImageLoadDef, data) + loadDef->resourceSize; +void Actions_GfxImage::LoadImageData(GfxImageLoadDef *loadDef, GfxImage *image) const { + const size_t loadDefSize = offsetof(IW3::GfxImageLoadDef, data) + loadDef->resourceSize; - image->texture.loadDef = static_cast<GfxImageLoadDef*>(m_zone->GetMemory()->Alloc(loadDefSize)); - memcpy(image->texture.loadDef, loadDef, loadDefSize); + image->texture.loadDef = static_cast<GfxImageLoadDef *>(m_zone->GetMemory()->Alloc(loadDefSize)); + memcpy(image->texture.loadDef, loadDef, loadDefSize); } diff --git a/src/ZoneLoading/Game/IW3/XAssets/gfximage/gfximage_actions.h b/src/ZoneLoading/Game/IW3/XAssets/gfximage/gfximage_actions.h index 440bf9a41..8710a0abc 100644 --- a/src/ZoneLoading/Game/IW3/XAssets/gfximage/gfximage_actions.h +++ b/src/ZoneLoading/Game/IW3/XAssets/gfximage/gfximage_actions.h @@ -1,16 +1,14 @@ #pragma once -#include "Loading/AssetLoadingActions.h" #include "Game/IW3/IW3.h" +#include "Loading/AssetLoadingActions.h" -namespace IW3 -{ - class Actions_GfxImage final : public AssetLoadingActions - { - public: - explicit Actions_GfxImage(Zone* zone); +namespace IW3 { +class Actions_GfxImage final : public AssetLoadingActions { +public: + explicit Actions_GfxImage(Zone *zone); - void OnImageLoaded(GfxImage* image) const; - void LoadImageData(GfxImageLoadDef* loadDef, GfxImage* image) const; - }; -} + void OnImageLoaded(GfxImage *image) const; + void LoadImageData(GfxImageLoadDef *loadDef, GfxImage *image) const; +}; +} // namespace IW3 diff --git a/src/ZoneLoading/Game/IW3/XAssets/loadedsound/loadedsound_actions.cpp b/src/ZoneLoading/Game/IW3/XAssets/loadedsound/loadedsound_actions.cpp index 864040cb8..1b5097adf 100644 --- a/src/ZoneLoading/Game/IW3/XAssets/loadedsound/loadedsound_actions.cpp +++ b/src/ZoneLoading/Game/IW3/XAssets/loadedsound/loadedsound_actions.cpp @@ -4,21 +4,14 @@ using namespace IW3; -Actions_LoadedSound::Actions_LoadedSound(Zone* zone) - : AssetLoadingActions(zone) -{ -} +Actions_LoadedSound::Actions_LoadedSound(Zone *zone) : AssetLoadingActions(zone) {} -void Actions_LoadedSound::SetSoundData(MssSound* sound) const -{ - if (sound->info.data_len > 0) - { - char* tempData = sound->data; - sound->data = static_cast<char*>(m_zone->GetMemory()->Alloc(sound->info.data_len)); - memcpy(sound->data, tempData, sound->info.data_len); - } - else - { - sound->data = nullptr; - } +void Actions_LoadedSound::SetSoundData(MssSound *sound) const { + if (sound->info.data_len > 0) { + char *tempData = sound->data; + sound->data = static_cast<char *>(m_zone->GetMemory()->Alloc(sound->info.data_len)); + memcpy(sound->data, tempData, sound->info.data_len); + } else { + sound->data = nullptr; + } } diff --git a/src/ZoneLoading/Game/IW3/XAssets/loadedsound/loadedsound_actions.h b/src/ZoneLoading/Game/IW3/XAssets/loadedsound/loadedsound_actions.h index cb0b1332a..1fa9f1b1d 100644 --- a/src/ZoneLoading/Game/IW3/XAssets/loadedsound/loadedsound_actions.h +++ b/src/ZoneLoading/Game/IW3/XAssets/loadedsound/loadedsound_actions.h @@ -1,15 +1,13 @@ #pragma once -#include "Loading/AssetLoadingActions.h" #include "Game/IW3/IW3.h" +#include "Loading/AssetLoadingActions.h" -namespace IW3 -{ - class Actions_LoadedSound final : public AssetLoadingActions - { - public: - explicit Actions_LoadedSound(Zone* zone); +namespace IW3 { +class Actions_LoadedSound final : public AssetLoadingActions { +public: + explicit Actions_LoadedSound(Zone *zone); - void SetSoundData(MssSound* sound) const; - }; -} + void SetSoundData(MssSound *sound) const; +}; +} // namespace IW3 diff --git a/src/ZoneLoading/Game/IW3/ZoneLoaderFactoryIW3.cpp b/src/ZoneLoading/Game/IW3/ZoneLoaderFactoryIW3.cpp index 77c59f534..3321408b0 100644 --- a/src/ZoneLoading/Game/IW3/ZoneLoaderFactoryIW3.cpp +++ b/src/ZoneLoading/Game/IW3/ZoneLoaderFactoryIW3.cpp @@ -6,101 +6,90 @@ #include "Game/IW3/IW3.h" -#include "Utils/ClassUtils.h" #include "ContentLoaderIW3.h" +#include "Game/GameLanguage.h" #include "Game/IW3/GameAssetPoolIW3.h" #include "Game/IW3/GameIW3.h" -#include "Game/GameLanguage.h" #include "Game/IW3/ZoneConstantsIW3.h" #include "Loading/Processor/ProcessorInflate.h" -#include "Loading/Steps/StepSkipBytes.h" #include "Loading/Steps/StepAddProcessor.h" #include "Loading/Steps/StepAllocXBlocks.h" #include "Loading/Steps/StepLoadZoneContent.h" +#include "Loading/Steps/StepSkipBytes.h" +#include "Utils/ClassUtils.h" using namespace IW3; -class ZoneLoaderFactory::Impl -{ - static GameLanguage GetZoneLanguage(std::string& zoneName) - { - return GameLanguage::LANGUAGE_NONE; - } - - static bool CanLoad(ZoneHeader& header, bool* isSecure, bool* isOfficial) - { - assert(isSecure != nullptr); - assert(isOfficial != nullptr); +class ZoneLoaderFactory::Impl { + static GameLanguage GetZoneLanguage(std::string &zoneName) { return GameLanguage::LANGUAGE_NONE; } - if (header.m_version != ZoneConstants::ZONE_VERSION) - { - return false; - } + static bool CanLoad(ZoneHeader &header, bool *isSecure, bool *isOfficial) { + assert(isSecure != nullptr); + assert(isOfficial != nullptr); - if (!memcmp(header.m_magic, ZoneConstants::MAGIC_UNSIGNED, std::char_traits<char>::length(ZoneConstants::MAGIC_UNSIGNED))) - { - *isSecure = false; - *isOfficial = true; - return true; - } + if (header.m_version != ZoneConstants::ZONE_VERSION) { + return false; + } - return false; + if (!memcmp(header.m_magic, ZoneConstants::MAGIC_UNSIGNED, std::char_traits<char>::length(ZoneConstants::MAGIC_UNSIGNED))) { + *isSecure = false; + *isOfficial = true; + return true; } - static void SetupBlock(ZoneLoader* zoneLoader) - { + return false; + } + + static void SetupBlock(ZoneLoader *zoneLoader) { #define XBLOCK_DEF(name, type) std::make_unique<XBlock>(STR(name), name, type) - zoneLoader->AddXBlock(XBLOCK_DEF(IW3::XFILE_BLOCK_TEMP, XBlock::Type::BLOCK_TYPE_TEMP)); - zoneLoader->AddXBlock(XBLOCK_DEF(IW3::XFILE_BLOCK_RUNTIME, XBlock::Type::BLOCK_TYPE_RUNTIME)); - zoneLoader->AddXBlock(XBLOCK_DEF(IW3::XFILE_BLOCK_LARGE_RUNTIME, XBlock::Type::BLOCK_TYPE_RUNTIME)); - zoneLoader->AddXBlock(XBLOCK_DEF(IW3::XFILE_BLOCK_PHYSICAL_RUNTIME, XBlock::Type::BLOCK_TYPE_RUNTIME)); - zoneLoader->AddXBlock(XBLOCK_DEF(IW3::XFILE_BLOCK_VIRTUAL, XBlock::Type::BLOCK_TYPE_NORMAL)); - zoneLoader->AddXBlock(XBLOCK_DEF(IW3::XFILE_BLOCK_LARGE, XBlock::Type::BLOCK_TYPE_NORMAL)); - zoneLoader->AddXBlock(XBLOCK_DEF(IW3::XFILE_BLOCK_PHYSICAL, XBlock::Type::BLOCK_TYPE_NORMAL)); - zoneLoader->AddXBlock(XBLOCK_DEF(IW3::XFILE_BLOCK_VERTEX, XBlock::Type::BLOCK_TYPE_NORMAL)); - zoneLoader->AddXBlock(XBLOCK_DEF(IW3::XFILE_BLOCK_INDEX, XBlock::Type::BLOCK_TYPE_NORMAL)); + zoneLoader->AddXBlock(XBLOCK_DEF(IW3::XFILE_BLOCK_TEMP, XBlock::Type::BLOCK_TYPE_TEMP)); + zoneLoader->AddXBlock(XBLOCK_DEF(IW3::XFILE_BLOCK_RUNTIME, XBlock::Type::BLOCK_TYPE_RUNTIME)); + zoneLoader->AddXBlock(XBLOCK_DEF(IW3::XFILE_BLOCK_LARGE_RUNTIME, XBlock::Type::BLOCK_TYPE_RUNTIME)); + zoneLoader->AddXBlock(XBLOCK_DEF(IW3::XFILE_BLOCK_PHYSICAL_RUNTIME, XBlock::Type::BLOCK_TYPE_RUNTIME)); + zoneLoader->AddXBlock(XBLOCK_DEF(IW3::XFILE_BLOCK_VIRTUAL, XBlock::Type::BLOCK_TYPE_NORMAL)); + zoneLoader->AddXBlock(XBLOCK_DEF(IW3::XFILE_BLOCK_LARGE, XBlock::Type::BLOCK_TYPE_NORMAL)); + zoneLoader->AddXBlock(XBLOCK_DEF(IW3::XFILE_BLOCK_PHYSICAL, XBlock::Type::BLOCK_TYPE_NORMAL)); + zoneLoader->AddXBlock(XBLOCK_DEF(IW3::XFILE_BLOCK_VERTEX, XBlock::Type::BLOCK_TYPE_NORMAL)); + zoneLoader->AddXBlock(XBLOCK_DEF(IW3::XFILE_BLOCK_INDEX, XBlock::Type::BLOCK_TYPE_NORMAL)); #undef XBLOCK_DEF - } + } public: - static ZoneLoader* CreateLoaderForHeader(ZoneHeader& header, std::string& fileName) - { - bool isSecure; - bool isOfficial; + static ZoneLoader *CreateLoaderForHeader(ZoneHeader &header, std::string &fileName) { + bool isSecure; + bool isOfficial; - // Check if this file is a supported IW4 zone. - if (!CanLoad(header, &isSecure, &isOfficial)) - return nullptr; + // Check if this file is a supported IW4 zone. + if (!CanLoad(header, &isSecure, &isOfficial)) + return nullptr; - // Create new zone - auto zone = std::make_unique<Zone>(fileName, 0, &g_GameIW3); - auto* zonePtr = zone.get(); - zone->m_pools = std::make_unique<GameAssetPoolIW3>(zonePtr, 0); - zone->m_language = GetZoneLanguage(fileName); + // Create new zone + auto zone = std::make_unique<Zone>(fileName, 0, &g_GameIW3); + auto *zonePtr = zone.get(); + zone->m_pools = std::make_unique<GameAssetPoolIW3>(zonePtr, 0); + zone->m_language = GetZoneLanguage(fileName); - // File is supported. Now setup all required steps for loading this file. - auto* zoneLoader = new ZoneLoader(std::move(zone)); + // File is supported. Now setup all required steps for loading this file. + auto *zoneLoader = new ZoneLoader(std::move(zone)); - SetupBlock(zoneLoader); + SetupBlock(zoneLoader); - zoneLoader->AddLoadingStep(std::make_unique<StepAddProcessor>(std::make_unique<ProcessorInflate>(ZoneConstants::AUTHED_CHUNK_SIZE))); + zoneLoader->AddLoadingStep(std::make_unique<StepAddProcessor>(std::make_unique<ProcessorInflate>(ZoneConstants::AUTHED_CHUNK_SIZE))); - // Start of the XFile struct - zoneLoader->AddLoadingStep(std::make_unique<StepSkipBytes>(8)); - // Skip size and externalSize fields since they are not interesting for us - zoneLoader->AddLoadingStep(std::make_unique<StepAllocXBlocks>()); + // Start of the XFile struct + zoneLoader->AddLoadingStep(std::make_unique<StepSkipBytes>(8)); + // Skip size and externalSize fields since they are not interesting for us + zoneLoader->AddLoadingStep(std::make_unique<StepAllocXBlocks>()); - // Start of the zone content - zoneLoader->AddLoadingStep(std::make_unique<StepLoadZoneContent>(std::make_unique<ContentLoader>(), zonePtr, ZoneConstants::OFFSET_BLOCK_BIT_COUNT, ZoneConstants::INSERT_BLOCK)); + // Start of the zone content + zoneLoader->AddLoadingStep( + std::make_unique<StepLoadZoneContent>(std::make_unique<ContentLoader>(), zonePtr, ZoneConstants::OFFSET_BLOCK_BIT_COUNT, ZoneConstants::INSERT_BLOCK)); - // Return the fully setup zoneloader - return zoneLoader; - } + // Return the fully setup zoneloader + return zoneLoader; + } }; -ZoneLoader* ZoneLoaderFactory::CreateLoaderForHeader(ZoneHeader& header, std::string& fileName) -{ - return Impl::CreateLoaderForHeader(header, fileName); -} +ZoneLoader *ZoneLoaderFactory::CreateLoaderForHeader(ZoneHeader &header, std::string &fileName) { return Impl::CreateLoaderForHeader(header, fileName); } diff --git a/src/ZoneLoading/Game/IW3/ZoneLoaderFactoryIW3.h b/src/ZoneLoading/Game/IW3/ZoneLoaderFactoryIW3.h index 65362e053..f56428cc1 100644 --- a/src/ZoneLoading/Game/IW3/ZoneLoaderFactoryIW3.h +++ b/src/ZoneLoading/Game/IW3/ZoneLoaderFactoryIW3.h @@ -3,13 +3,11 @@ #include "Loading/IZoneLoaderFactory.h" #include <string> -namespace IW3 -{ - class ZoneLoaderFactory final : public IZoneLoaderFactory - { - class Impl; +namespace IW3 { +class ZoneLoaderFactory final : public IZoneLoaderFactory { + class Impl; - public: - ZoneLoader* CreateLoaderForHeader(ZoneHeader& header, std::string& fileName) override; - }; -} +public: + ZoneLoader *CreateLoaderForHeader(ZoneHeader &header, std::string &fileName) override; +}; +} // namespace IW3 diff --git a/src/ZoneLoading/Game/IW4/ContentLoaderIW4.cpp b/src/ZoneLoading/Game/IW4/ContentLoaderIW4.cpp index 9c265686e..72de05501 100644 --- a/src/ZoneLoading/Game/IW4/ContentLoaderIW4.cpp +++ b/src/ZoneLoading/Game/IW4/ContentLoaderIW4.cpp @@ -42,56 +42,47 @@ using namespace IW4; -ContentLoader::ContentLoader() - : varXAsset(nullptr), - varScriptStringList(nullptr) -{ -} +ContentLoader::ContentLoader() : varXAsset(nullptr), varScriptStringList(nullptr) {} -void ContentLoader::LoadScriptStringList(const bool atStreamStart) -{ - m_stream->PushBlock(XFILE_BLOCK_VIRTUAL); +void ContentLoader::LoadScriptStringList(const bool atStreamStart) { + m_stream->PushBlock(XFILE_BLOCK_VIRTUAL); - if (atStreamStart) - m_stream->Load<ScriptStringList>(varScriptStringList); + if (atStreamStart) + m_stream->Load<ScriptStringList>(varScriptStringList); - if (varScriptStringList->strings != nullptr) - { - assert(varScriptStringList->strings == PTR_FOLLOWING); + if (varScriptStringList->strings != nullptr) { + assert(varScriptStringList->strings == PTR_FOLLOWING); - varScriptStringList->strings = m_stream->Alloc<const char*>(alignof(const char*)); - varXString = varScriptStringList->strings; - LoadXStringArray(true, varScriptStringList->count); + varScriptStringList->strings = m_stream->Alloc<const char *>(alignof(const char *)); + varXString = varScriptStringList->strings; + LoadXStringArray(true, varScriptStringList->count); - if (varScriptStringList->strings && varScriptStringList->count > 0) - m_zone->m_script_strings.InitializeForExistingZone(varScriptStringList->strings, static_cast<size_t>(varScriptStringList->count)); - } + if (varScriptStringList->strings && varScriptStringList->count > 0) + m_zone->m_script_strings.InitializeForExistingZone(varScriptStringList->strings, static_cast<size_t>(varScriptStringList->count)); + } - m_stream->PopBlock(); + m_stream->PopBlock(); - assert(m_zone->m_script_strings.Count() <= SCR_STRING_MAX + 1); + assert(m_zone->m_script_strings.Count() <= SCR_STRING_MAX + 1); } -void ContentLoader::LoadXAsset(const bool atStreamStart) const -{ -#define LOAD_ASSET(type_index, typeName, headerEntry) \ - case type_index: \ - { \ - Loader_##typeName loader(m_zone, m_stream); \ - loader.Load(&varXAsset->header.headerEntry); \ - break; \ - } -#define SKIP_ASSET(type_index, typeName, headerEntry) \ - case type_index: \ - break; - - assert(varXAsset != nullptr); - - if (atStreamStart) - m_stream->Load<XAsset>(varXAsset); - - switch (varXAsset->type) - { +void ContentLoader::LoadXAsset(const bool atStreamStart) const { +#define LOAD_ASSET(type_index, typeName, headerEntry) \ + case type_index: { \ + Loader_##typeName loader(m_zone, m_stream); \ + loader.Load(&varXAsset->header.headerEntry); \ + break; \ + } +#define SKIP_ASSET(type_index, typeName, headerEntry) \ + case type_index: \ + break; + + assert(varXAsset != nullptr); + + if (atStreamStart) + m_stream->Load<XAsset>(varXAsset); + + switch (varXAsset->type) { LOAD_ASSET(ASSET_TYPE_PHYSPRESET, PhysPreset, physPreset) LOAD_ASSET(ASSET_TYPE_PHYSCOLLMAP, PhysCollmap, physCollmap) LOAD_ASSET(ASSET_TYPE_XANIMPARTS, XAnimParts, parts) @@ -130,55 +121,49 @@ void ContentLoader::LoadXAsset(const bool atStreamStart) const LOAD_ASSET(ASSET_TYPE_VEHICLE, VehicleDef, vehDef) LOAD_ASSET(ASSET_TYPE_ADDON_MAP_ENTS, AddonMapEnts, addonMapEnts) - default: - { - throw UnsupportedAssetTypeException(varXAsset->type); - } - } + default: { + throw UnsupportedAssetTypeException(varXAsset->type); + } + } #undef LOAD_ASSET } -void ContentLoader::LoadXAssetArray(const bool atStreamStart, const size_t count) -{ - assert(varXAsset != nullptr); +void ContentLoader::LoadXAssetArray(const bool atStreamStart, const size_t count) { + assert(varXAsset != nullptr); - if (atStreamStart) - m_stream->Load<XAsset>(varXAsset, count); + if (atStreamStart) + m_stream->Load<XAsset>(varXAsset, count); - for (asset_type_t assetType = 0; assetType < ASSET_TYPE_COUNT; assetType++) - { - m_zone->m_pools->InitPoolDynamic(assetType); - } + for (asset_type_t assetType = 0; assetType < ASSET_TYPE_COUNT; assetType++) { + m_zone->m_pools->InitPoolDynamic(assetType); + } - for (size_t index = 0; index < count; index++) - { - LoadXAsset(false); - varXAsset++; - } + for (size_t index = 0; index < count; index++) { + LoadXAsset(false); + varXAsset++; + } } -void ContentLoader::Load(Zone* zone, IZoneInputStream* stream) -{ - m_zone = zone; - m_stream = stream; +void ContentLoader::Load(Zone *zone, IZoneInputStream *stream) { + m_zone = zone; + m_stream = stream; - m_stream->PushBlock(XFILE_BLOCK_VIRTUAL); + m_stream->PushBlock(XFILE_BLOCK_VIRTUAL); - XAssetList assetList{}; - m_stream->LoadDataRaw(&assetList, sizeof assetList); + XAssetList assetList{}; + m_stream->LoadDataRaw(&assetList, sizeof assetList); - varScriptStringList = &assetList.stringList; - LoadScriptStringList(false); + varScriptStringList = &assetList.stringList; + LoadScriptStringList(false); - if (assetList.assets != nullptr) - { - assert(assetList.assets == PTR_FOLLOWING); + if (assetList.assets != nullptr) { + assert(assetList.assets == PTR_FOLLOWING); - assetList.assets = m_stream->Alloc<XAsset>(alignof(XAsset)); - varXAsset = assetList.assets; - LoadXAssetArray(true, assetList.assetCount); - } + assetList.assets = m_stream->Alloc<XAsset>(alignof(XAsset)); + varXAsset = assetList.assets; + LoadXAssetArray(true, assetList.assetCount); + } - m_stream->PopBlock(); + m_stream->PopBlock(); } diff --git a/src/ZoneLoading/Game/IW4/ContentLoaderIW4.h b/src/ZoneLoading/Game/IW4/ContentLoaderIW4.h index da132e4f0..fcbcb40bc 100644 --- a/src/ZoneLoading/Game/IW4/ContentLoaderIW4.h +++ b/src/ZoneLoading/Game/IW4/ContentLoaderIW4.h @@ -1,23 +1,21 @@ #pragma once +#include "Game/IW4/IW4.h" #include "Loading/ContentLoaderBase.h" #include "Loading/IContentLoadingEntryPoint.h" -#include "Game/IW4/IW4.h" -namespace IW4 -{ - class ContentLoader final : public ContentLoaderBase, public IContentLoadingEntryPoint - { - XAsset* varXAsset; - ScriptStringList* varScriptStringList; +namespace IW4 { +class ContentLoader final : public ContentLoaderBase, public IContentLoadingEntryPoint { + XAsset *varXAsset; + ScriptStringList *varScriptStringList; - void LoadScriptStringList(bool atStreamStart); + void LoadScriptStringList(bool atStreamStart); - void LoadXAsset(bool atStreamStart) const; - void LoadXAssetArray(bool atStreamStart, size_t count); + void LoadXAsset(bool atStreamStart) const; + void LoadXAssetArray(bool atStreamStart, size_t count); - public: - ContentLoader(); +public: + ContentLoader(); - void Load(Zone* zone, IZoneInputStream* stream) override; - }; -} + void Load(Zone *zone, IZoneInputStream *stream) override; +}; +} // namespace IW4 diff --git a/src/ZoneLoading/Game/IW4/XAssets/gfximage/gfximage_actions.cpp b/src/ZoneLoading/Game/IW4/XAssets/gfximage/gfximage_actions.cpp index 726b33e27..dab6efab8 100644 --- a/src/ZoneLoading/Game/IW4/XAssets/gfximage/gfximage_actions.cpp +++ b/src/ZoneLoading/Game/IW4/XAssets/gfximage/gfximage_actions.cpp @@ -5,20 +5,13 @@ using namespace IW4; -Actions_GfxImage::Actions_GfxImage(Zone* zone) - : AssetLoadingActions(zone) -{ -} +Actions_GfxImage::Actions_GfxImage(Zone *zone) : AssetLoadingActions(zone) {} -void Actions_GfxImage::OnImageLoaded(GfxImage* image) const -{ - image->cardMemory.platform[0] = 0; -} +void Actions_GfxImage::OnImageLoaded(GfxImage *image) const { image->cardMemory.platform[0] = 0; } -void Actions_GfxImage::LoadImageData(GfxImageLoadDef* loadDef, GfxImage* image) const -{ - const size_t loadDefSize = offsetof(IW4::GfxImageLoadDef, data) + loadDef->resourceSize; +void Actions_GfxImage::LoadImageData(GfxImageLoadDef *loadDef, GfxImage *image) const { + const size_t loadDefSize = offsetof(IW4::GfxImageLoadDef, data) + loadDef->resourceSize; - image->texture.loadDef = static_cast<GfxImageLoadDef*>(m_zone->GetMemory()->Alloc(loadDefSize)); - memcpy(image->texture.loadDef, loadDef, loadDefSize); + image->texture.loadDef = static_cast<GfxImageLoadDef *>(m_zone->GetMemory()->Alloc(loadDefSize)); + memcpy(image->texture.loadDef, loadDef, loadDefSize); } diff --git a/src/ZoneLoading/Game/IW4/XAssets/gfximage/gfximage_actions.h b/src/ZoneLoading/Game/IW4/XAssets/gfximage/gfximage_actions.h index ed2e12adc..0990ff0d4 100644 --- a/src/ZoneLoading/Game/IW4/XAssets/gfximage/gfximage_actions.h +++ b/src/ZoneLoading/Game/IW4/XAssets/gfximage/gfximage_actions.h @@ -1,16 +1,14 @@ #pragma once -#include "Loading/AssetLoadingActions.h" #include "Game/IW4/IW4.h" +#include "Loading/AssetLoadingActions.h" -namespace IW4 -{ - class Actions_GfxImage final : public AssetLoadingActions - { - public: - explicit Actions_GfxImage(Zone* zone); +namespace IW4 { +class Actions_GfxImage final : public AssetLoadingActions { +public: + explicit Actions_GfxImage(Zone *zone); - void OnImageLoaded(GfxImage* image) const; - void LoadImageData(GfxImageLoadDef* loadDef, GfxImage* image) const; - }; -} + void OnImageLoaded(GfxImage *image) const; + void LoadImageData(GfxImageLoadDef *loadDef, GfxImage *image) const; +}; +} // namespace IW4 diff --git a/src/ZoneLoading/Game/IW4/XAssets/loadedsound/loadedsound_actions.cpp b/src/ZoneLoading/Game/IW4/XAssets/loadedsound/loadedsound_actions.cpp index 92efcff42..4a003c15f 100644 --- a/src/ZoneLoading/Game/IW4/XAssets/loadedsound/loadedsound_actions.cpp +++ b/src/ZoneLoading/Game/IW4/XAssets/loadedsound/loadedsound_actions.cpp @@ -4,21 +4,14 @@ using namespace IW4; -Actions_LoadedSound::Actions_LoadedSound(Zone* zone) - : AssetLoadingActions(zone) -{ -} +Actions_LoadedSound::Actions_LoadedSound(Zone *zone) : AssetLoadingActions(zone) {} -void Actions_LoadedSound::SetSoundData(MssSound* sound) const -{ - if (sound->info.data_len > 0) - { - char* tempData = sound->data; - sound->data = static_cast<char*>(m_zone->GetMemory()->Alloc(sound->info.data_len)); - memcpy(sound->data, tempData, sound->info.data_len); - } - else - { - sound->data = nullptr; - } +void Actions_LoadedSound::SetSoundData(MssSound *sound) const { + if (sound->info.data_len > 0) { + char *tempData = sound->data; + sound->data = static_cast<char *>(m_zone->GetMemory()->Alloc(sound->info.data_len)); + memcpy(sound->data, tempData, sound->info.data_len); + } else { + sound->data = nullptr; + } } diff --git a/src/ZoneLoading/Game/IW4/XAssets/loadedsound/loadedsound_actions.h b/src/ZoneLoading/Game/IW4/XAssets/loadedsound/loadedsound_actions.h index bf0f16de1..f85362cf5 100644 --- a/src/ZoneLoading/Game/IW4/XAssets/loadedsound/loadedsound_actions.h +++ b/src/ZoneLoading/Game/IW4/XAssets/loadedsound/loadedsound_actions.h @@ -1,15 +1,13 @@ #pragma once -#include "Loading/AssetLoadingActions.h" #include "Game/IW4/IW4.h" +#include "Loading/AssetLoadingActions.h" -namespace IW4 -{ - class Actions_LoadedSound final : public AssetLoadingActions - { - public: - explicit Actions_LoadedSound(Zone* zone); +namespace IW4 { +class Actions_LoadedSound final : public AssetLoadingActions { +public: + explicit Actions_LoadedSound(Zone *zone); - void SetSoundData(MssSound* sound) const; - }; -} + void SetSoundData(MssSound *sound) const; +}; +} // namespace IW4 diff --git a/src/ZoneLoading/Game/IW4/XAssets/xmodel/xmodel_actions.cpp b/src/ZoneLoading/Game/IW4/XAssets/xmodel/xmodel_actions.cpp index 39152ed45..01dadda84 100644 --- a/src/ZoneLoading/Game/IW4/XAssets/xmodel/xmodel_actions.cpp +++ b/src/ZoneLoading/Game/IW4/XAssets/xmodel/xmodel_actions.cpp @@ -4,16 +4,11 @@ using namespace IW4; -Actions_XModel::Actions_XModel(Zone* zone) - : AssetLoadingActions(zone) -{ -} +Actions_XModel::Actions_XModel(Zone *zone) : AssetLoadingActions(zone) {} -void Actions_XModel::SetModelSurfs(XModelLodInfo* lodInfo, XModelSurfs* modelSurfs) const -{ - if(modelSurfs) - { - lodInfo->modelSurfs = m_zone->GetMemory()->Create<XModelSurfs>(); - memcpy(lodInfo->modelSurfs, modelSurfs, sizeof(XModelSurfs)); - } +void Actions_XModel::SetModelSurfs(XModelLodInfo *lodInfo, XModelSurfs *modelSurfs) const { + if (modelSurfs) { + lodInfo->modelSurfs = m_zone->GetMemory()->Create<XModelSurfs>(); + memcpy(lodInfo->modelSurfs, modelSurfs, sizeof(XModelSurfs)); + } } diff --git a/src/ZoneLoading/Game/IW4/XAssets/xmodel/xmodel_actions.h b/src/ZoneLoading/Game/IW4/XAssets/xmodel/xmodel_actions.h index e19dbc0af..e8da4b812 100644 --- a/src/ZoneLoading/Game/IW4/XAssets/xmodel/xmodel_actions.h +++ b/src/ZoneLoading/Game/IW4/XAssets/xmodel/xmodel_actions.h @@ -1,15 +1,13 @@ #pragma once -#include "Loading/AssetLoadingActions.h" #include "Game/IW4/IW4.h" +#include "Loading/AssetLoadingActions.h" -namespace IW4 -{ - class Actions_XModel final : public AssetLoadingActions - { - public: - explicit Actions_XModel(Zone* zone); +namespace IW4 { +class Actions_XModel final : public AssetLoadingActions { +public: + explicit Actions_XModel(Zone *zone); - void SetModelSurfs(XModelLodInfo* lodInfo, XModelSurfs* modelSurfs) const; - }; -} + void SetModelSurfs(XModelLodInfo *lodInfo, XModelSurfs *modelSurfs) const; +}; +} // namespace IW4 diff --git a/src/ZoneLoading/Game/IW4/ZoneLoaderFactoryIW4.cpp b/src/ZoneLoading/Game/IW4/ZoneLoaderFactoryIW4.cpp index c1e46935d..f9116b357 100644 --- a/src/ZoneLoading/Game/IW4/ZoneLoaderFactoryIW4.cpp +++ b/src/ZoneLoading/Game/IW4/ZoneLoaderFactoryIW4.cpp @@ -6,218 +6,197 @@ #include "Game/IW4/IW4.h" -#include "Utils/ClassUtils.h" #include "ContentLoaderIW4.h" +#include "Game/GameLanguage.h" #include "Game/IW4/GameAssetPoolIW4.h" #include "Game/IW4/GameIW4.h" -#include "Game/GameLanguage.h" #include "Game/IW4/ZoneConstantsIW4.h" #include "Loading/Processor/ProcessorAuthedBlocks.h" #include "Loading/Processor/ProcessorCaptureData.h" -#include "Loading/Processor/ProcessorInflate.h" #include "Loading/Processor/ProcessorIW4xDecryption.h" -#include "Loading/Steps/StepVerifyMagic.h" -#include "Loading/Steps/StepSkipBytes.h" -#include "Loading/Steps/StepVerifyFileName.h" -#include "Loading/Steps/StepLoadSignature.h" -#include "Loading/Steps/StepVerifySignature.h" +#include "Loading/Processor/ProcessorInflate.h" #include "Loading/Steps/StepAddProcessor.h" #include "Loading/Steps/StepAllocXBlocks.h" -#include "Loading/Steps/StepLoadZoneContent.h" #include "Loading/Steps/StepLoadHash.h" +#include "Loading/Steps/StepLoadSignature.h" +#include "Loading/Steps/StepLoadZoneContent.h" #include "Loading/Steps/StepRemoveProcessor.h" +#include "Loading/Steps/StepSkipBytes.h" +#include "Loading/Steps/StepVerifyFileName.h" #include "Loading/Steps/StepVerifyHash.h" +#include "Loading/Steps/StepVerifyMagic.h" +#include "Loading/Steps/StepVerifySignature.h" +#include "Utils/ClassUtils.h" using namespace IW4; -class ZoneLoaderFactory::Impl -{ - static GameLanguage GetZoneLanguage(std::string& zoneName) - { - return GameLanguage::LANGUAGE_NONE; +class ZoneLoaderFactory::Impl { + static GameLanguage GetZoneLanguage(std::string &zoneName) { return GameLanguage::LANGUAGE_NONE; } + + static bool CanLoad(ZoneHeader &header, bool *isSecure, bool *isOfficial, bool *isIw4x) { + assert(isSecure != nullptr); + assert(isOfficial != nullptr); + assert(isIw4x != nullptr); + + if (header.m_version != ZoneConstants::ZONE_VERSION) { + return false; } - static bool CanLoad(ZoneHeader& header, bool* isSecure, bool* isOfficial, bool* isIw4x) - { - assert(isSecure != nullptr); - assert(isOfficial != nullptr); - assert(isIw4x != nullptr); - - if (header.m_version != ZoneConstants::ZONE_VERSION) - { - return false; - } - - if (!memcmp(header.m_magic, ZoneConstants::MAGIC_IW4X, std::char_traits<char>::length(ZoneConstants::MAGIC_IW4X))) - { - if(*reinterpret_cast<uint32_t*>(&header.m_magic[std::char_traits<char>::length(ZoneConstants::MAGIC_IW4X)]) == ZoneConstants::IW4X_ZONE_VERSION) - { - *isSecure = false; - *isOfficial = false; - *isIw4x = true; - return true; - } - - return false; - } - - if (!memcmp(header.m_magic, ZoneConstants::MAGIC_SIGNED_INFINITY_WARD, std::char_traits<char>::length(ZoneConstants::MAGIC_SIGNED_INFINITY_WARD))) - { - *isSecure = true; - *isOfficial = true; - *isIw4x = false; - return true; - } - - if (!memcmp(header.m_magic, ZoneConstants::MAGIC_UNSIGNED, std::char_traits<char>::length(ZoneConstants::MAGIC_UNSIGNED))) - { - *isSecure = false; - *isOfficial = true; - *isIw4x = false; - return true; - } - - return false; + if (!memcmp(header.m_magic, ZoneConstants::MAGIC_IW4X, std::char_traits<char>::length(ZoneConstants::MAGIC_IW4X))) { + if (*reinterpret_cast<uint32_t *>(&header.m_magic[std::char_traits<char>::length(ZoneConstants::MAGIC_IW4X)]) == ZoneConstants::IW4X_ZONE_VERSION) { + *isSecure = false; + *isOfficial = false; + *isIw4x = true; + return true; + } + + return false; } - static void SetupBlock(ZoneLoader* zoneLoader) - { + if (!memcmp(header.m_magic, ZoneConstants::MAGIC_SIGNED_INFINITY_WARD, std::char_traits<char>::length(ZoneConstants::MAGIC_SIGNED_INFINITY_WARD))) { + *isSecure = true; + *isOfficial = true; + *isIw4x = false; + return true; + } + + if (!memcmp(header.m_magic, ZoneConstants::MAGIC_UNSIGNED, std::char_traits<char>::length(ZoneConstants::MAGIC_UNSIGNED))) { + *isSecure = false; + *isOfficial = true; + *isIw4x = false; + return true; + } + + return false; + } + + static void SetupBlock(ZoneLoader *zoneLoader) { #define XBLOCK_DEF(name, type) std::make_unique<XBlock>(STR(name), name, type) - zoneLoader->AddXBlock(XBLOCK_DEF(IW4::XFILE_BLOCK_TEMP, XBlock::Type::BLOCK_TYPE_TEMP)); - zoneLoader->AddXBlock(XBLOCK_DEF(IW4::XFILE_BLOCK_PHYSICAL, XBlock::Type::BLOCK_TYPE_NORMAL)); - zoneLoader->AddXBlock(XBLOCK_DEF(IW4::XFILE_BLOCK_RUNTIME, XBlock::Type::BLOCK_TYPE_RUNTIME)); - zoneLoader->AddXBlock(XBLOCK_DEF(IW4::XFILE_BLOCK_VIRTUAL, XBlock::Type::BLOCK_TYPE_NORMAL)); - zoneLoader->AddXBlock(XBLOCK_DEF(IW4::XFILE_BLOCK_LARGE, XBlock::Type::BLOCK_TYPE_NORMAL)); - zoneLoader->AddXBlock(XBLOCK_DEF(IW4::XFILE_BLOCK_CALLBACK, XBlock::Type::BLOCK_TYPE_NORMAL)); - zoneLoader->AddXBlock(XBLOCK_DEF(IW4::XFILE_BLOCK_VERTEX, XBlock::Type::BLOCK_TYPE_NORMAL)); - zoneLoader->AddXBlock(XBLOCK_DEF(IW4::XFILE_BLOCK_INDEX, XBlock::Type::BLOCK_TYPE_NORMAL)); + zoneLoader->AddXBlock(XBLOCK_DEF(IW4::XFILE_BLOCK_TEMP, XBlock::Type::BLOCK_TYPE_TEMP)); + zoneLoader->AddXBlock(XBLOCK_DEF(IW4::XFILE_BLOCK_PHYSICAL, XBlock::Type::BLOCK_TYPE_NORMAL)); + zoneLoader->AddXBlock(XBLOCK_DEF(IW4::XFILE_BLOCK_RUNTIME, XBlock::Type::BLOCK_TYPE_RUNTIME)); + zoneLoader->AddXBlock(XBLOCK_DEF(IW4::XFILE_BLOCK_VIRTUAL, XBlock::Type::BLOCK_TYPE_NORMAL)); + zoneLoader->AddXBlock(XBLOCK_DEF(IW4::XFILE_BLOCK_LARGE, XBlock::Type::BLOCK_TYPE_NORMAL)); + zoneLoader->AddXBlock(XBLOCK_DEF(IW4::XFILE_BLOCK_CALLBACK, XBlock::Type::BLOCK_TYPE_NORMAL)); + zoneLoader->AddXBlock(XBLOCK_DEF(IW4::XFILE_BLOCK_VERTEX, XBlock::Type::BLOCK_TYPE_NORMAL)); + zoneLoader->AddXBlock(XBLOCK_DEF(IW4::XFILE_BLOCK_INDEX, XBlock::Type::BLOCK_TYPE_NORMAL)); #undef XBLOCK_DEF - } + } - static std::unique_ptr<IPublicKeyAlgorithm> SetupRSA(const bool isOfficial) - { - if (isOfficial) - { - auto rsa = Crypto::CreateRSA(IPublicKeyAlgorithm::HashingAlgorithm::RSA_HASH_SHA256, - Crypto::RSAPaddingMode::RSA_PADDING_PSS); - - if (!rsa->SetKey(ZoneConstants::RSA_PUBLIC_KEY_INFINITY_WARD, sizeof(ZoneConstants::RSA_PUBLIC_KEY_INFINITY_WARD))) - { - printf("Invalid public key for signature checking\n"); - return nullptr; - } - - return rsa; - } - else - { - assert(false); - - // TODO: Load custom RSA key here - return nullptr; - } + static std::unique_ptr<IPublicKeyAlgorithm> SetupRSA(const bool isOfficial) { + if (isOfficial) { + auto rsa = Crypto::CreateRSA(IPublicKeyAlgorithm::HashingAlgorithm::RSA_HASH_SHA256, Crypto::RSAPaddingMode::RSA_PADDING_PSS); + + if (!rsa->SetKey(ZoneConstants::RSA_PUBLIC_KEY_INFINITY_WARD, sizeof(ZoneConstants::RSA_PUBLIC_KEY_INFINITY_WARD))) { + printf("Invalid public key for signature checking\n"); + return nullptr; + } + + return rsa; + } else { + assert(false); + + // TODO: Load custom RSA key here + return nullptr; } + } - static void AddAuthHeaderSteps(const bool isSecure, const bool isOfficial, ZoneLoader* zoneLoader, - std::string& fileName) - { - // Unsigned zones do not have an auth header - if (!isSecure) - return; + static void AddAuthHeaderSteps(const bool isSecure, const bool isOfficial, ZoneLoader *zoneLoader, std::string &fileName) { + // Unsigned zones do not have an auth header + if (!isSecure) + return; - // If file is signed setup a RSA instance. - auto rsa = SetupRSA(isOfficial); + // If file is signed setup a RSA instance. + auto rsa = SetupRSA(isOfficial); - zoneLoader->AddLoadingStep(std::make_unique<StepVerifyMagic>(ZoneConstants::MAGIC_AUTH_HEADER)); - zoneLoader->AddLoadingStep(std::make_unique<StepSkipBytes>(4)); // Skip reserved + zoneLoader->AddLoadingStep(std::make_unique<StepVerifyMagic>(ZoneConstants::MAGIC_AUTH_HEADER)); + zoneLoader->AddLoadingStep(std::make_unique<StepSkipBytes>(4)); // Skip reserved - auto subHeaderHash = std::make_unique<StepLoadHash>(sizeof DB_AuthHash::bytes, 1); - auto* subHeaderHashPtr = subHeaderHash.get(); - zoneLoader->AddLoadingStep(std::move(subHeaderHash)); + auto subHeaderHash = std::make_unique<StepLoadHash>(sizeof DB_AuthHash::bytes, 1); + auto *subHeaderHashPtr = subHeaderHash.get(); + zoneLoader->AddLoadingStep(std::move(subHeaderHash)); - auto subHeaderHashSignature = std::make_unique<StepLoadSignature>(sizeof DB_AuthSignature::bytes); - auto* subHeaderHashSignaturePtr = subHeaderHashSignature.get(); - zoneLoader->AddLoadingStep(std::move(subHeaderHashSignature)); + auto subHeaderHashSignature = std::make_unique<StepLoadSignature>(sizeof DB_AuthSignature::bytes); + auto *subHeaderHashSignaturePtr = subHeaderHashSignature.get(); + zoneLoader->AddLoadingStep(std::move(subHeaderHashSignature)); - zoneLoader->AddLoadingStep(std::make_unique<StepVerifySignature>(std::move(rsa), subHeaderHashSignaturePtr, subHeaderHashPtr)); + zoneLoader->AddLoadingStep(std::make_unique<StepVerifySignature>(std::move(rsa), subHeaderHashSignaturePtr, subHeaderHashPtr)); - auto subHeaderCapture = std::make_unique<ProcessorCaptureData>(sizeof(DB_AuthSubHeader)); - auto* subHeaderCapturePtr = subHeaderCapture.get(); - zoneLoader->AddLoadingStep(std::make_unique<StepAddProcessor>(std::move(subHeaderCapture))); + auto subHeaderCapture = std::make_unique<ProcessorCaptureData>(sizeof(DB_AuthSubHeader)); + auto *subHeaderCapturePtr = subHeaderCapture.get(); + zoneLoader->AddLoadingStep(std::make_unique<StepAddProcessor>(std::move(subHeaderCapture))); - zoneLoader->AddLoadingStep(std::make_unique<StepVerifyFileName>(fileName, sizeof(DB_AuthSubHeader::fastfileName))); - zoneLoader->AddLoadingStep(std::make_unique<StepSkipBytes>(4)); // Skip reserved + zoneLoader->AddLoadingStep(std::make_unique<StepVerifyFileName>(fileName, sizeof(DB_AuthSubHeader::fastfileName))); + zoneLoader->AddLoadingStep(std::make_unique<StepSkipBytes>(4)); // Skip reserved - auto masterBlockHashes = std::make_unique<StepLoadHash>(sizeof DB_AuthHash::bytes, std::extent<decltype(DB_AuthSubHeader::masterBlockHashes)>::value); - auto* masterBlockHashesPtr = masterBlockHashes.get(); - zoneLoader->AddLoadingStep(std::move(masterBlockHashes)); + auto masterBlockHashes = std::make_unique<StepLoadHash>(sizeof DB_AuthHash::bytes, std::extent<decltype(DB_AuthSubHeader::masterBlockHashes)>::value); + auto *masterBlockHashesPtr = masterBlockHashes.get(); + zoneLoader->AddLoadingStep(std::move(masterBlockHashes)); - zoneLoader->AddLoadingStep(std::make_unique<StepVerifyHash>(std::unique_ptr<IHashFunction>(Crypto::CreateSHA256()), 0, subHeaderHashPtr, subHeaderCapturePtr)); - zoneLoader->AddLoadingStep(std::make_unique<StepRemoveProcessor>(subHeaderCapturePtr)); + zoneLoader->AddLoadingStep( + std::make_unique<StepVerifyHash>(std::unique_ptr<IHashFunction>(Crypto::CreateSHA256()), 0, subHeaderHashPtr, subHeaderCapturePtr)); + zoneLoader->AddLoadingStep(std::make_unique<StepRemoveProcessor>(subHeaderCapturePtr)); - // Skip the rest of the first chunk - zoneLoader->AddLoadingStep(std::make_unique<StepSkipBytes>(ZoneConstants::AUTHED_CHUNK_SIZE - sizeof(DB_AuthHeader))); + // Skip the rest of the first chunk + zoneLoader->AddLoadingStep(std::make_unique<StepSkipBytes>(ZoneConstants::AUTHED_CHUNK_SIZE - sizeof(DB_AuthHeader))); - zoneLoader->AddLoadingStep(std::make_unique<StepAddProcessor>(std::make_unique<ProcessorAuthedBlocks>( - ZoneConstants::AUTHED_CHUNK_COUNT_PER_GROUP, ZoneConstants::AUTHED_CHUNK_SIZE, std::extent<decltype(DB_AuthSubHeader::masterBlockHashes)>::value, - std::unique_ptr<IHashFunction>(Crypto::CreateSHA256()), masterBlockHashesPtr))); - } + zoneLoader->AddLoadingStep(std::make_unique<StepAddProcessor>(std::make_unique<ProcessorAuthedBlocks>( + ZoneConstants::AUTHED_CHUNK_COUNT_PER_GROUP, ZoneConstants::AUTHED_CHUNK_SIZE, std::extent<decltype(DB_AuthSubHeader::masterBlockHashes)>::value, + std::unique_ptr<IHashFunction>(Crypto::CreateSHA256()), masterBlockHashesPtr))); + } public: - static ZoneLoader* CreateLoaderForHeader(ZoneHeader& header, std::string& fileName) - { - bool isSecure; - bool isOfficial; - bool isIw4x; + static ZoneLoader *CreateLoaderForHeader(ZoneHeader &header, std::string &fileName) { + bool isSecure; + bool isOfficial; + bool isIw4x; - // Check if this file is a supported IW4 zone. - if (!CanLoad(header, &isSecure, &isOfficial, &isIw4x)) - return nullptr; + // Check if this file is a supported IW4 zone. + if (!CanLoad(header, &isSecure, &isOfficial, &isIw4x)) + return nullptr; - // Create new zone - auto zone = std::make_unique<Zone>(fileName, 0, &g_GameIW4); - auto* zonePtr = zone.get(); - zone->m_pools = std::make_unique<GameAssetPoolIW4>(zonePtr, 0); - zone->m_language = GetZoneLanguage(fileName); + // Create new zone + auto zone = std::make_unique<Zone>(fileName, 0, &g_GameIW4); + auto *zonePtr = zone.get(); + zone->m_pools = std::make_unique<GameAssetPoolIW4>(zonePtr, 0); + zone->m_language = GetZoneLanguage(fileName); - // File is supported. Now setup all required steps for loading this file. - auto* zoneLoader = new ZoneLoader(std::move(zone)); + // File is supported. Now setup all required steps for loading this file. + auto *zoneLoader = new ZoneLoader(std::move(zone)); - SetupBlock(zoneLoader); + SetupBlock(zoneLoader); - // Skip unknown 1 byte field that the game ignores as well - zoneLoader->AddLoadingStep(std::make_unique<StepSkipBytes>(1)); + // Skip unknown 1 byte field that the game ignores as well + zoneLoader->AddLoadingStep(std::make_unique<StepSkipBytes>(1)); - // Skip timestamp - zoneLoader->AddLoadingStep(std::make_unique<StepSkipBytes>(8)); + // Skip timestamp + zoneLoader->AddLoadingStep(std::make_unique<StepSkipBytes>(8)); - // Add steps for loading the auth header which also contain the signature of the zone if it is signed. - AddAuthHeaderSteps(isSecure, isOfficial, zoneLoader, fileName); + // Add steps for loading the auth header which also contain the signature of the zone if it is signed. + AddAuthHeaderSteps(isSecure, isOfficial, zoneLoader, fileName); - zoneLoader->AddLoadingStep(std::make_unique<StepAddProcessor>(std::make_unique<ProcessorInflate>(ZoneConstants::AUTHED_CHUNK_SIZE))); + zoneLoader->AddLoadingStep(std::make_unique<StepAddProcessor>(std::make_unique<ProcessorInflate>(ZoneConstants::AUTHED_CHUNK_SIZE))); - if (isIw4x) // IW4x has one extra byte of padding here for protection purposes - { - zoneLoader->AddLoadingStep(std::make_unique<StepAddProcessor>(std::make_unique<ProcessorIW4xDecryption>())); - zoneLoader->AddLoadingStep(std::make_unique<StepSkipBytes>(1)); - } + if (isIw4x) // IW4x has one extra byte of padding here for protection purposes + { + zoneLoader->AddLoadingStep(std::make_unique<StepAddProcessor>(std::make_unique<ProcessorIW4xDecryption>())); + zoneLoader->AddLoadingStep(std::make_unique<StepSkipBytes>(1)); + } - // Start of the XFile struct - zoneLoader->AddLoadingStep(std::make_unique<StepSkipBytes>(8)); - // Skip size and externalSize fields since they are not interesting for us - zoneLoader->AddLoadingStep(std::make_unique<StepAllocXBlocks>()); + // Start of the XFile struct + zoneLoader->AddLoadingStep(std::make_unique<StepSkipBytes>(8)); + // Skip size and externalSize fields since they are not interesting for us + zoneLoader->AddLoadingStep(std::make_unique<StepAllocXBlocks>()); - // Start of the zone content - zoneLoader->AddLoadingStep(std::make_unique<StepLoadZoneContent>(std::make_unique<ContentLoader>(), zonePtr, ZoneConstants::OFFSET_BLOCK_BIT_COUNT, ZoneConstants::INSERT_BLOCK)); + // Start of the zone content + zoneLoader->AddLoadingStep( + std::make_unique<StepLoadZoneContent>(std::make_unique<ContentLoader>(), zonePtr, ZoneConstants::OFFSET_BLOCK_BIT_COUNT, ZoneConstants::INSERT_BLOCK)); - // Return the fully setup zoneloader - return zoneLoader; - } + // Return the fully setup zoneloader + return zoneLoader; + } }; -ZoneLoader* ZoneLoaderFactory::CreateLoaderForHeader(ZoneHeader& header, std::string& fileName) -{ - return Impl::CreateLoaderForHeader(header, fileName); -} +ZoneLoader *ZoneLoaderFactory::CreateLoaderForHeader(ZoneHeader &header, std::string &fileName) { return Impl::CreateLoaderForHeader(header, fileName); } diff --git a/src/ZoneLoading/Game/IW4/ZoneLoaderFactoryIW4.h b/src/ZoneLoading/Game/IW4/ZoneLoaderFactoryIW4.h index 636fd84ac..cd80870ce 100644 --- a/src/ZoneLoading/Game/IW4/ZoneLoaderFactoryIW4.h +++ b/src/ZoneLoading/Game/IW4/ZoneLoaderFactoryIW4.h @@ -3,13 +3,11 @@ #include "Loading/IZoneLoaderFactory.h" #include <string> -namespace IW4 -{ - class ZoneLoaderFactory final : public IZoneLoaderFactory - { - class Impl; +namespace IW4 { +class ZoneLoaderFactory final : public IZoneLoaderFactory { + class Impl; - public: - ZoneLoader* CreateLoaderForHeader(ZoneHeader& header, std::string& fileName) override; - }; -} +public: + ZoneLoader *CreateLoaderForHeader(ZoneHeader &header, std::string &fileName) override; +}; +} // namespace IW4 diff --git a/src/ZoneLoading/Game/IW5/ContentLoaderIW5.cpp b/src/ZoneLoading/Game/IW5/ContentLoaderIW5.cpp index 3f63d81bf..2ad07bca9 100644 --- a/src/ZoneLoading/Game/IW5/ContentLoaderIW5.cpp +++ b/src/ZoneLoading/Game/IW5/ContentLoaderIW5.cpp @@ -47,56 +47,47 @@ using namespace IW5; -ContentLoader::ContentLoader() - : varXAsset(nullptr), - varScriptStringList(nullptr) -{ -} +ContentLoader::ContentLoader() : varXAsset(nullptr), varScriptStringList(nullptr) {} -void ContentLoader::LoadScriptStringList(const bool atStreamStart) -{ - m_stream->PushBlock(XFILE_BLOCK_VIRTUAL); +void ContentLoader::LoadScriptStringList(const bool atStreamStart) { + m_stream->PushBlock(XFILE_BLOCK_VIRTUAL); - if (atStreamStart) - m_stream->Load<ScriptStringList>(varScriptStringList); + if (atStreamStart) + m_stream->Load<ScriptStringList>(varScriptStringList); - if (varScriptStringList->strings != nullptr) - { - assert(varScriptStringList->strings == PTR_FOLLOWING); + if (varScriptStringList->strings != nullptr) { + assert(varScriptStringList->strings == PTR_FOLLOWING); - varScriptStringList->strings = m_stream->Alloc<const char*>(alignof(const char*)); - varXString = varScriptStringList->strings; - LoadXStringArray(true, varScriptStringList->count); + varScriptStringList->strings = m_stream->Alloc<const char *>(alignof(const char *)); + varXString = varScriptStringList->strings; + LoadXStringArray(true, varScriptStringList->count); - if (varScriptStringList->strings && varScriptStringList->count > 0) - m_zone->m_script_strings.InitializeForExistingZone(varScriptStringList->strings, static_cast<size_t>(varScriptStringList->count)); - } + if (varScriptStringList->strings && varScriptStringList->count > 0) + m_zone->m_script_strings.InitializeForExistingZone(varScriptStringList->strings, static_cast<size_t>(varScriptStringList->count)); + } - m_stream->PopBlock(); + m_stream->PopBlock(); - assert(m_zone->m_script_strings.Count() <= SCR_STRING_MAX + 1); + assert(m_zone->m_script_strings.Count() <= SCR_STRING_MAX + 1); } -void ContentLoader::LoadXAsset(const bool atStreamStart) const -{ -#define LOAD_ASSET(type_index, typeName, headerEntry) \ - case type_index: \ - { \ - Loader_##typeName loader(m_zone, m_stream); \ - loader.Load(&varXAsset->header.headerEntry); \ - break; \ - } -#define SKIP_ASSET(type_index) \ - case type_index: \ - break; - - assert(varXAsset != nullptr); - - if (atStreamStart) - m_stream->Load<XAsset>(varXAsset); - - switch (varXAsset->type) - { +void ContentLoader::LoadXAsset(const bool atStreamStart) const { +#define LOAD_ASSET(type_index, typeName, headerEntry) \ + case type_index: { \ + Loader_##typeName loader(m_zone, m_stream); \ + loader.Load(&varXAsset->header.headerEntry); \ + break; \ + } +#define SKIP_ASSET(type_index) \ + case type_index: \ + break; + + assert(varXAsset != nullptr); + + if (atStreamStart) + m_stream->Load<XAsset>(varXAsset); + + switch (varXAsset->type) { LOAD_ASSET(ASSET_TYPE_PHYSPRESET, PhysPreset, physPreset) LOAD_ASSET(ASSET_TYPE_PHYSCOLLMAP, PhysCollmap, physCollmap) LOAD_ASSET(ASSET_TYPE_XANIMPARTS, XAnimParts, parts) @@ -139,55 +130,49 @@ void ContentLoader::LoadXAsset(const bool atStreamStart) const LOAD_ASSET(ASSET_TYPE_VEHICLE, VehicleDef, vehDef) LOAD_ASSET(ASSET_TYPE_ADDON_MAP_ENTS, AddonMapEnts, addonMapEnts) - default: - { - throw UnsupportedAssetTypeException(varXAsset->type); - } - } + default: { + throw UnsupportedAssetTypeException(varXAsset->type); + } + } #undef LOAD_ASSET } -void ContentLoader::LoadXAssetArray(const bool atStreamStart, const size_t count) -{ - assert(count == 0 || varXAsset != nullptr); +void ContentLoader::LoadXAssetArray(const bool atStreamStart, const size_t count) { + assert(count == 0 || varXAsset != nullptr); - if (atStreamStart) - m_stream->Load<XAsset>(varXAsset, count); + if (atStreamStart) + m_stream->Load<XAsset>(varXAsset, count); - for (asset_type_t assetType = 0; assetType < ASSET_TYPE_COUNT; assetType++) - { - m_zone->m_pools->InitPoolDynamic(assetType); - } + for (asset_type_t assetType = 0; assetType < ASSET_TYPE_COUNT; assetType++) { + m_zone->m_pools->InitPoolDynamic(assetType); + } - for (size_t index = 0; index < count; index++) - { - LoadXAsset(false); - varXAsset++; - } + for (size_t index = 0; index < count; index++) { + LoadXAsset(false); + varXAsset++; + } } -void ContentLoader::Load(Zone* zone, IZoneInputStream* stream) -{ - m_zone = zone; - m_stream = stream; +void ContentLoader::Load(Zone *zone, IZoneInputStream *stream) { + m_zone = zone; + m_stream = stream; - m_stream->PushBlock(XFILE_BLOCK_VIRTUAL); + m_stream->PushBlock(XFILE_BLOCK_VIRTUAL); - XAssetList assetList{}; - m_stream->LoadDataRaw(&assetList, sizeof assetList); + XAssetList assetList{}; + m_stream->LoadDataRaw(&assetList, sizeof assetList); - varScriptStringList = &assetList.stringList; - LoadScriptStringList(false); + varScriptStringList = &assetList.stringList; + LoadScriptStringList(false); - if (assetList.assets != nullptr) - { - assert(assetList.assets == PTR_FOLLOWING); + if (assetList.assets != nullptr) { + assert(assetList.assets == PTR_FOLLOWING); - assetList.assets = m_stream->Alloc<XAsset>(alignof(XAsset)); - varXAsset = assetList.assets; - LoadXAssetArray(true, assetList.assetCount); - } + assetList.assets = m_stream->Alloc<XAsset>(alignof(XAsset)); + varXAsset = assetList.assets; + LoadXAssetArray(true, assetList.assetCount); + } - m_stream->PopBlock(); + m_stream->PopBlock(); } diff --git a/src/ZoneLoading/Game/IW5/ContentLoaderIW5.h b/src/ZoneLoading/Game/IW5/ContentLoaderIW5.h index 79a0813c8..d6a3e3877 100644 --- a/src/ZoneLoading/Game/IW5/ContentLoaderIW5.h +++ b/src/ZoneLoading/Game/IW5/ContentLoaderIW5.h @@ -1,23 +1,21 @@ #pragma once +#include "Game/IW5/IW5.h" #include "Loading/ContentLoaderBase.h" #include "Loading/IContentLoadingEntryPoint.h" -#include "Game/IW5/IW5.h" -namespace IW5 -{ - class ContentLoader final : public ContentLoaderBase, public IContentLoadingEntryPoint - { - XAsset* varXAsset; - ScriptStringList* varScriptStringList; +namespace IW5 { +class ContentLoader final : public ContentLoaderBase, public IContentLoadingEntryPoint { + XAsset *varXAsset; + ScriptStringList *varScriptStringList; - void LoadScriptStringList(bool atStreamStart); + void LoadScriptStringList(bool atStreamStart); - void LoadXAsset(bool atStreamStart) const; - void LoadXAssetArray(bool atStreamStart, size_t count); + void LoadXAsset(bool atStreamStart) const; + void LoadXAssetArray(bool atStreamStart, size_t count); - public: - ContentLoader(); +public: + ContentLoader(); - void Load(Zone* zone, IZoneInputStream* stream) override; - }; -} + void Load(Zone *zone, IZoneInputStream *stream) override; +}; +} // namespace IW5 diff --git a/src/ZoneLoading/Game/IW5/XAssets/gfximage/gfximage_actions.cpp b/src/ZoneLoading/Game/IW5/XAssets/gfximage/gfximage_actions.cpp index a6e71c00d..63eff0645 100644 --- a/src/ZoneLoading/Game/IW5/XAssets/gfximage/gfximage_actions.cpp +++ b/src/ZoneLoading/Game/IW5/XAssets/gfximage/gfximage_actions.cpp @@ -5,20 +5,13 @@ using namespace IW5; -Actions_GfxImage::Actions_GfxImage(Zone* zone) - : AssetLoadingActions(zone) -{ -} +Actions_GfxImage::Actions_GfxImage(Zone *zone) : AssetLoadingActions(zone) {} -void Actions_GfxImage::OnImageLoaded(GfxImage* image) const -{ - image->cardMemory.platform[0] = 0; -} +void Actions_GfxImage::OnImageLoaded(GfxImage *image) const { image->cardMemory.platform[0] = 0; } -void Actions_GfxImage::LoadImageData(GfxImageLoadDef* loadDef, GfxImage* image) const -{ - const size_t loadDefSize = offsetof(IW5::GfxImageLoadDef, data) + loadDef->resourceSize; +void Actions_GfxImage::LoadImageData(GfxImageLoadDef *loadDef, GfxImage *image) const { + const size_t loadDefSize = offsetof(IW5::GfxImageLoadDef, data) + loadDef->resourceSize; - image->texture.loadDef = static_cast<GfxImageLoadDef*>(m_zone->GetMemory()->Alloc(loadDefSize)); - memcpy(image->texture.loadDef, loadDef, loadDefSize); + image->texture.loadDef = static_cast<GfxImageLoadDef *>(m_zone->GetMemory()->Alloc(loadDefSize)); + memcpy(image->texture.loadDef, loadDef, loadDefSize); } diff --git a/src/ZoneLoading/Game/IW5/XAssets/gfximage/gfximage_actions.h b/src/ZoneLoading/Game/IW5/XAssets/gfximage/gfximage_actions.h index ca2e6dcbc..5a29f0cd8 100644 --- a/src/ZoneLoading/Game/IW5/XAssets/gfximage/gfximage_actions.h +++ b/src/ZoneLoading/Game/IW5/XAssets/gfximage/gfximage_actions.h @@ -1,16 +1,14 @@ #pragma once -#include "Loading/AssetLoadingActions.h" #include "Game/IW5/IW5.h" +#include "Loading/AssetLoadingActions.h" -namespace IW5 -{ - class Actions_GfxImage final : public AssetLoadingActions - { - public: - explicit Actions_GfxImage(Zone* zone); +namespace IW5 { +class Actions_GfxImage final : public AssetLoadingActions { +public: + explicit Actions_GfxImage(Zone *zone); - void OnImageLoaded(GfxImage* image) const; - void LoadImageData(GfxImageLoadDef* loadDef, GfxImage* image) const; - }; -} + void OnImageLoaded(GfxImage *image) const; + void LoadImageData(GfxImageLoadDef *loadDef, GfxImage *image) const; +}; +} // namespace IW5 diff --git a/src/ZoneLoading/Game/IW5/XAssets/loadedsound/loadedsound_actions.cpp b/src/ZoneLoading/Game/IW5/XAssets/loadedsound/loadedsound_actions.cpp index 1d4463876..368f56f67 100644 --- a/src/ZoneLoading/Game/IW5/XAssets/loadedsound/loadedsound_actions.cpp +++ b/src/ZoneLoading/Game/IW5/XAssets/loadedsound/loadedsound_actions.cpp @@ -4,21 +4,14 @@ using namespace IW5; -Actions_LoadedSound::Actions_LoadedSound(Zone* zone) - : AssetLoadingActions(zone) -{ -} +Actions_LoadedSound::Actions_LoadedSound(Zone *zone) : AssetLoadingActions(zone) {} -void Actions_LoadedSound::SetSoundData(MssSound* sound) const -{ - if (sound->info.data_len > 0) - { - char* tempData = sound->data; - sound->data = static_cast<char*>(m_zone->GetMemory()->Alloc(sound->info.data_len)); - memcpy(sound->data, tempData, sound->info.data_len); - } - else - { - sound->data = nullptr; - } +void Actions_LoadedSound::SetSoundData(MssSound *sound) const { + if (sound->info.data_len > 0) { + char *tempData = sound->data; + sound->data = static_cast<char *>(m_zone->GetMemory()->Alloc(sound->info.data_len)); + memcpy(sound->data, tempData, sound->info.data_len); + } else { + sound->data = nullptr; + } } diff --git a/src/ZoneLoading/Game/IW5/XAssets/loadedsound/loadedsound_actions.h b/src/ZoneLoading/Game/IW5/XAssets/loadedsound/loadedsound_actions.h index a6bbfc1a4..4f74299c4 100644 --- a/src/ZoneLoading/Game/IW5/XAssets/loadedsound/loadedsound_actions.h +++ b/src/ZoneLoading/Game/IW5/XAssets/loadedsound/loadedsound_actions.h @@ -1,15 +1,13 @@ #pragma once -#include "Loading/AssetLoadingActions.h" #include "Game/IW5/IW5.h" +#include "Loading/AssetLoadingActions.h" -namespace IW5 -{ - class Actions_LoadedSound final : public AssetLoadingActions - { - public: - explicit Actions_LoadedSound(Zone* zone); +namespace IW5 { +class Actions_LoadedSound final : public AssetLoadingActions { +public: + explicit Actions_LoadedSound(Zone *zone); - void SetSoundData(MssSound* sound) const; - }; -} + void SetSoundData(MssSound *sound) const; +}; +} // namespace IW5 diff --git a/src/ZoneLoading/Game/IW5/XAssets/xmodel/xmodel_actions.cpp b/src/ZoneLoading/Game/IW5/XAssets/xmodel/xmodel_actions.cpp index 499557814..a366dd015 100644 --- a/src/ZoneLoading/Game/IW5/XAssets/xmodel/xmodel_actions.cpp +++ b/src/ZoneLoading/Game/IW5/XAssets/xmodel/xmodel_actions.cpp @@ -4,16 +4,11 @@ using namespace IW5; -Actions_XModel::Actions_XModel(Zone* zone) - : AssetLoadingActions(zone) -{ -} +Actions_XModel::Actions_XModel(Zone *zone) : AssetLoadingActions(zone) {} -void Actions_XModel::SetModelSurfs(XModelLodInfo* lodInfo, XModelSurfs* modelSurfs) const -{ - if(modelSurfs) - { - lodInfo->modelSurfs = m_zone->GetMemory()->Create<XModelSurfs>(); - memcpy(lodInfo->modelSurfs, modelSurfs, sizeof(XModelSurfs)); - } +void Actions_XModel::SetModelSurfs(XModelLodInfo *lodInfo, XModelSurfs *modelSurfs) const { + if (modelSurfs) { + lodInfo->modelSurfs = m_zone->GetMemory()->Create<XModelSurfs>(); + memcpy(lodInfo->modelSurfs, modelSurfs, sizeof(XModelSurfs)); + } } diff --git a/src/ZoneLoading/Game/IW5/XAssets/xmodel/xmodel_actions.h b/src/ZoneLoading/Game/IW5/XAssets/xmodel/xmodel_actions.h index 60cb637ea..39d693e01 100644 --- a/src/ZoneLoading/Game/IW5/XAssets/xmodel/xmodel_actions.h +++ b/src/ZoneLoading/Game/IW5/XAssets/xmodel/xmodel_actions.h @@ -1,15 +1,13 @@ #pragma once -#include "Loading/AssetLoadingActions.h" #include "Game/IW5/IW5.h" +#include "Loading/AssetLoadingActions.h" -namespace IW5 -{ - class Actions_XModel final : public AssetLoadingActions - { - public: - explicit Actions_XModel(Zone* zone); +namespace IW5 { +class Actions_XModel final : public AssetLoadingActions { +public: + explicit Actions_XModel(Zone *zone); - void SetModelSurfs(XModelLodInfo* lodInfo, XModelSurfs* modelSurfs) const; - }; -} + void SetModelSurfs(XModelLodInfo *lodInfo, XModelSurfs *modelSurfs) const; +}; +} // namespace IW5 diff --git a/src/ZoneLoading/Game/IW5/ZoneLoaderFactoryIW5.cpp b/src/ZoneLoading/Game/IW5/ZoneLoaderFactoryIW5.cpp index 8a6a1a94c..8350d62b7 100644 --- a/src/ZoneLoading/Game/IW5/ZoneLoaderFactoryIW5.cpp +++ b/src/ZoneLoading/Game/IW5/ZoneLoaderFactoryIW5.cpp @@ -6,195 +6,176 @@ #include "Game/IW5/IW5.h" -#include "Utils/ClassUtils.h" #include "ContentLoaderIW5.h" +#include "Game/GameLanguage.h" #include "Game/IW5/GameAssetPoolIW5.h" #include "Game/IW5/GameIW5.h" -#include "Game/GameLanguage.h" #include "Game/IW5/ZoneConstantsIW5.h" #include "Loading/Processor/ProcessorAuthedBlocks.h" #include "Loading/Processor/ProcessorCaptureData.h" #include "Loading/Processor/ProcessorInflate.h" -#include "Loading/Steps/StepVerifyMagic.h" -#include "Loading/Steps/StepSkipBytes.h" -#include "Loading/Steps/StepVerifyFileName.h" -#include "Loading/Steps/StepLoadSignature.h" -#include "Loading/Steps/StepVerifySignature.h" #include "Loading/Steps/StepAddProcessor.h" #include "Loading/Steps/StepAllocXBlocks.h" -#include "Loading/Steps/StepLoadZoneContent.h" #include "Loading/Steps/StepLoadHash.h" +#include "Loading/Steps/StepLoadSignature.h" +#include "Loading/Steps/StepLoadZoneContent.h" #include "Loading/Steps/StepRemoveProcessor.h" +#include "Loading/Steps/StepSkipBytes.h" +#include "Loading/Steps/StepVerifyFileName.h" #include "Loading/Steps/StepVerifyHash.h" +#include "Loading/Steps/StepVerifyMagic.h" +#include "Loading/Steps/StepVerifySignature.h" +#include "Utils/ClassUtils.h" using namespace IW5; -class ZoneLoaderFactory::Impl -{ - static GameLanguage GetZoneLanguage(std::string& zoneName) - { - return GameLanguage::LANGUAGE_NONE; +class ZoneLoaderFactory::Impl { + static GameLanguage GetZoneLanguage(std::string &zoneName) { return GameLanguage::LANGUAGE_NONE; } + + static bool CanLoad(ZoneHeader &header, bool *isSecure, bool *isOfficial) { + assert(isSecure != nullptr); + assert(isOfficial != nullptr); + + if (header.m_version != ZoneConstants::ZONE_VERSION) { + return false; } - static bool CanLoad(ZoneHeader& header, bool* isSecure, bool* isOfficial) - { - assert(isSecure != nullptr); - assert(isOfficial != nullptr); - - if (header.m_version != ZoneConstants::ZONE_VERSION) - { - return false; - } - - if (!memcmp(header.m_magic, ZoneConstants::MAGIC_SIGNED_INFINITY_WARD, std::char_traits<char>::length(ZoneConstants::MAGIC_SIGNED_INFINITY_WARD))) - { - *isSecure = true; - *isOfficial = true; - return true; - } - - if (!memcmp(header.m_magic, ZoneConstants::MAGIC_UNSIGNED, std::char_traits<char>::length(ZoneConstants::MAGIC_UNSIGNED))) - { - *isSecure = false; - *isOfficial = true; - return true; - } - - return false; + if (!memcmp(header.m_magic, ZoneConstants::MAGIC_SIGNED_INFINITY_WARD, std::char_traits<char>::length(ZoneConstants::MAGIC_SIGNED_INFINITY_WARD))) { + *isSecure = true; + *isOfficial = true; + return true; } - static void SetupBlock(ZoneLoader* zoneLoader) - { + if (!memcmp(header.m_magic, ZoneConstants::MAGIC_UNSIGNED, std::char_traits<char>::length(ZoneConstants::MAGIC_UNSIGNED))) { + *isSecure = false; + *isOfficial = true; + return true; + } + + return false; + } + + static void SetupBlock(ZoneLoader *zoneLoader) { #define XBLOCK_DEF(name, type) std::make_unique<XBlock>(STR(name), name, type) - zoneLoader->AddXBlock(XBLOCK_DEF(XFILE_BLOCK_TEMP, XBlock::Type::BLOCK_TYPE_TEMP)); - zoneLoader->AddXBlock(XBLOCK_DEF(XFILE_BLOCK_PHYSICAL, XBlock::Type::BLOCK_TYPE_NORMAL)); - zoneLoader->AddXBlock(XBLOCK_DEF(XFILE_BLOCK_RUNTIME, XBlock::Type::BLOCK_TYPE_RUNTIME)); - zoneLoader->AddXBlock(XBLOCK_DEF(XFILE_BLOCK_VIRTUAL, XBlock::Type::BLOCK_TYPE_NORMAL)); - zoneLoader->AddXBlock(XBLOCK_DEF(XFILE_BLOCK_LARGE, XBlock::Type::BLOCK_TYPE_NORMAL)); - zoneLoader->AddXBlock(XBLOCK_DEF(XFILE_BLOCK_CALLBACK, XBlock::Type::BLOCK_TYPE_NORMAL)); - zoneLoader->AddXBlock(XBLOCK_DEF(XFILE_BLOCK_VERTEX, XBlock::Type::BLOCK_TYPE_NORMAL)); - zoneLoader->AddXBlock(XBLOCK_DEF(XFILE_BLOCK_INDEX, XBlock::Type::BLOCK_TYPE_NORMAL)); - zoneLoader->AddXBlock(XBLOCK_DEF(XFILE_BLOCK_SCRIPT, XBlock::Type::BLOCK_TYPE_NORMAL)); + zoneLoader->AddXBlock(XBLOCK_DEF(XFILE_BLOCK_TEMP, XBlock::Type::BLOCK_TYPE_TEMP)); + zoneLoader->AddXBlock(XBLOCK_DEF(XFILE_BLOCK_PHYSICAL, XBlock::Type::BLOCK_TYPE_NORMAL)); + zoneLoader->AddXBlock(XBLOCK_DEF(XFILE_BLOCK_RUNTIME, XBlock::Type::BLOCK_TYPE_RUNTIME)); + zoneLoader->AddXBlock(XBLOCK_DEF(XFILE_BLOCK_VIRTUAL, XBlock::Type::BLOCK_TYPE_NORMAL)); + zoneLoader->AddXBlock(XBLOCK_DEF(XFILE_BLOCK_LARGE, XBlock::Type::BLOCK_TYPE_NORMAL)); + zoneLoader->AddXBlock(XBLOCK_DEF(XFILE_BLOCK_CALLBACK, XBlock::Type::BLOCK_TYPE_NORMAL)); + zoneLoader->AddXBlock(XBLOCK_DEF(XFILE_BLOCK_VERTEX, XBlock::Type::BLOCK_TYPE_NORMAL)); + zoneLoader->AddXBlock(XBLOCK_DEF(XFILE_BLOCK_INDEX, XBlock::Type::BLOCK_TYPE_NORMAL)); + zoneLoader->AddXBlock(XBLOCK_DEF(XFILE_BLOCK_SCRIPT, XBlock::Type::BLOCK_TYPE_NORMAL)); #undef XBLOCK_DEF - } + } + + static std::unique_ptr<IPublicKeyAlgorithm> SetupRSA(const bool isOfficial) { + if (isOfficial) { + auto rsa = Crypto::CreateRSA(IPublicKeyAlgorithm::HashingAlgorithm::RSA_HASH_SHA256, Crypto::RSAPaddingMode::RSA_PADDING_PSS); + + if (!rsa->SetKey(ZoneConstants::RSA_PUBLIC_KEY_INFINITY_WARD, sizeof(ZoneConstants::RSA_PUBLIC_KEY_INFINITY_WARD))) { + printf("Invalid public key for signature checking\n"); + return nullptr; + } - static std::unique_ptr<IPublicKeyAlgorithm> SetupRSA(const bool isOfficial) - { - if (isOfficial) - { - auto rsa = Crypto::CreateRSA(IPublicKeyAlgorithm::HashingAlgorithm::RSA_HASH_SHA256, - Crypto::RSAPaddingMode::RSA_PADDING_PSS); - - if (!rsa->SetKey(ZoneConstants::RSA_PUBLIC_KEY_INFINITY_WARD, sizeof(ZoneConstants::RSA_PUBLIC_KEY_INFINITY_WARD))) - { - printf("Invalid public key for signature checking\n"); - return nullptr; - } - - return rsa; - } - else - { - assert(false); - - // TODO: Load custom RSA key here - return nullptr; - } + return rsa; + } else { + assert(false); + + // TODO: Load custom RSA key here + return nullptr; } + } - static void AddAuthHeaderSteps(const bool isSecure, const bool isOfficial, ZoneLoader* zoneLoader, - std::string& fileName) - { - // Unsigned zones do not have an auth header - if (!isSecure) - return; + static void AddAuthHeaderSteps(const bool isSecure, const bool isOfficial, ZoneLoader *zoneLoader, std::string &fileName) { + // Unsigned zones do not have an auth header + if (!isSecure) + return; - // If file is signed setup a RSA instance. - auto rsa = SetupRSA(isOfficial); + // If file is signed setup a RSA instance. + auto rsa = SetupRSA(isOfficial); - zoneLoader->AddLoadingStep(std::make_unique<StepVerifyMagic>(ZoneConstants::MAGIC_AUTH_HEADER)); - zoneLoader->AddLoadingStep(std::make_unique<StepSkipBytes>(4)); // Skip reserved + zoneLoader->AddLoadingStep(std::make_unique<StepVerifyMagic>(ZoneConstants::MAGIC_AUTH_HEADER)); + zoneLoader->AddLoadingStep(std::make_unique<StepSkipBytes>(4)); // Skip reserved - auto subHeaderHash = std::make_unique<StepLoadHash>(sizeof DB_AuthHash::bytes, 1); - auto* subHeaderHashPtr = subHeaderHash.get(); - zoneLoader->AddLoadingStep(std::move(subHeaderHash)); + auto subHeaderHash = std::make_unique<StepLoadHash>(sizeof DB_AuthHash::bytes, 1); + auto *subHeaderHashPtr = subHeaderHash.get(); + zoneLoader->AddLoadingStep(std::move(subHeaderHash)); - auto subHeaderHashSignature = std::make_unique<StepLoadSignature>(sizeof DB_AuthSignature::bytes); - auto* subHeaderHashSignaturePtr = subHeaderHashSignature.get(); - zoneLoader->AddLoadingStep(std::move(subHeaderHashSignature)); + auto subHeaderHashSignature = std::make_unique<StepLoadSignature>(sizeof DB_AuthSignature::bytes); + auto *subHeaderHashSignaturePtr = subHeaderHashSignature.get(); + zoneLoader->AddLoadingStep(std::move(subHeaderHashSignature)); - zoneLoader->AddLoadingStep(std::make_unique<StepVerifySignature>(std::move(rsa), subHeaderHashSignaturePtr, subHeaderHashPtr)); + zoneLoader->AddLoadingStep(std::make_unique<StepVerifySignature>(std::move(rsa), subHeaderHashSignaturePtr, subHeaderHashPtr)); - auto subHeaderCapture = std::make_unique<ProcessorCaptureData>(sizeof(DB_AuthSubHeader)); - auto* subHeaderCapturePtr = subHeaderCapture.get(); - zoneLoader->AddLoadingStep(std::make_unique<StepAddProcessor>(std::move(subHeaderCapture))); + auto subHeaderCapture = std::make_unique<ProcessorCaptureData>(sizeof(DB_AuthSubHeader)); + auto *subHeaderCapturePtr = subHeaderCapture.get(); + zoneLoader->AddLoadingStep(std::make_unique<StepAddProcessor>(std::move(subHeaderCapture))); - zoneLoader->AddLoadingStep(std::make_unique<StepVerifyFileName>(fileName, sizeof(DB_AuthSubHeader::fastfileName))); - zoneLoader->AddLoadingStep(std::make_unique<StepSkipBytes>(4)); // Skip reserved + zoneLoader->AddLoadingStep(std::make_unique<StepVerifyFileName>(fileName, sizeof(DB_AuthSubHeader::fastfileName))); + zoneLoader->AddLoadingStep(std::make_unique<StepSkipBytes>(4)); // Skip reserved - auto masterBlockHashes = std::make_unique<StepLoadHash>(sizeof DB_AuthHash::bytes, std::extent<decltype(DB_AuthSubHeader::masterBlockHashes)>::value); - auto* masterBlockHashesPtr = masterBlockHashes.get(); - zoneLoader->AddLoadingStep(std::move(masterBlockHashes)); + auto masterBlockHashes = std::make_unique<StepLoadHash>(sizeof DB_AuthHash::bytes, std::extent<decltype(DB_AuthSubHeader::masterBlockHashes)>::value); + auto *masterBlockHashesPtr = masterBlockHashes.get(); + zoneLoader->AddLoadingStep(std::move(masterBlockHashes)); - zoneLoader->AddLoadingStep(std::make_unique<StepVerifyHash>(std::unique_ptr<IHashFunction>(Crypto::CreateSHA256()), 0, subHeaderHashPtr, subHeaderCapturePtr)); - zoneLoader->AddLoadingStep(std::make_unique<StepRemoveProcessor>(subHeaderCapturePtr)); + zoneLoader->AddLoadingStep( + std::make_unique<StepVerifyHash>(std::unique_ptr<IHashFunction>(Crypto::CreateSHA256()), 0, subHeaderHashPtr, subHeaderCapturePtr)); + zoneLoader->AddLoadingStep(std::make_unique<StepRemoveProcessor>(subHeaderCapturePtr)); - // Skip the rest of the first chunk - zoneLoader->AddLoadingStep(std::make_unique<StepSkipBytes>(ZoneConstants::AUTHED_CHUNK_SIZE - sizeof(DB_AuthHeader))); + // Skip the rest of the first chunk + zoneLoader->AddLoadingStep(std::make_unique<StepSkipBytes>(ZoneConstants::AUTHED_CHUNK_SIZE - sizeof(DB_AuthHeader))); - zoneLoader->AddLoadingStep(std::make_unique<StepAddProcessor>(std::make_unique<ProcessorAuthedBlocks>( - ZoneConstants::AUTHED_CHUNK_COUNT_PER_GROUP, ZoneConstants::AUTHED_CHUNK_SIZE, std::extent<decltype(DB_AuthSubHeader::masterBlockHashes)>::value, - std::unique_ptr<IHashFunction>(Crypto::CreateSHA256()), masterBlockHashesPtr))); - } + zoneLoader->AddLoadingStep(std::make_unique<StepAddProcessor>(std::make_unique<ProcessorAuthedBlocks>( + ZoneConstants::AUTHED_CHUNK_COUNT_PER_GROUP, ZoneConstants::AUTHED_CHUNK_SIZE, std::extent<decltype(DB_AuthSubHeader::masterBlockHashes)>::value, + std::unique_ptr<IHashFunction>(Crypto::CreateSHA256()), masterBlockHashesPtr))); + } public: - static ZoneLoader* CreateLoaderForHeader(ZoneHeader& header, std::string& fileName) - { - bool isSecure; - bool isOfficial; + static ZoneLoader *CreateLoaderForHeader(ZoneHeader &header, std::string &fileName) { + bool isSecure; + bool isOfficial; - // Check if this file is a supported IW4 zone. - if (!CanLoad(header, &isSecure, &isOfficial)) - return nullptr; + // Check if this file is a supported IW4 zone. + if (!CanLoad(header, &isSecure, &isOfficial)) + return nullptr; - // Create new zone - auto zone = std::make_unique<Zone>(fileName, 0, &g_GameIW5); - auto* zonePtr = zone.get(); - zone->m_pools = std::make_unique<GameAssetPoolIW5>(zonePtr, 0); - zone->m_language = GetZoneLanguage(fileName); + // Create new zone + auto zone = std::make_unique<Zone>(fileName, 0, &g_GameIW5); + auto *zonePtr = zone.get(); + zone->m_pools = std::make_unique<GameAssetPoolIW5>(zonePtr, 0); + zone->m_language = GetZoneLanguage(fileName); - // File is supported. Now setup all required steps for loading this file. - auto* zoneLoader = new ZoneLoader(std::move(zone)); + // File is supported. Now setup all required steps for loading this file. + auto *zoneLoader = new ZoneLoader(std::move(zone)); - SetupBlock(zoneLoader); + SetupBlock(zoneLoader); - // Skip unknown 1 byte field that the game ignores as well - zoneLoader->AddLoadingStep(std::make_unique<StepSkipBytes>(1)); + // Skip unknown 1 byte field that the game ignores as well + zoneLoader->AddLoadingStep(std::make_unique<StepSkipBytes>(1)); - // Skip timestamp - zoneLoader->AddLoadingStep(std::make_unique<StepSkipBytes>(8)); + // Skip timestamp + zoneLoader->AddLoadingStep(std::make_unique<StepSkipBytes>(8)); - // Add steps for loading the auth header which also contain the signature of the zone if it is signed. - AddAuthHeaderSteps(isSecure, isOfficial, zoneLoader, fileName); + // Add steps for loading the auth header which also contain the signature of the zone if it is signed. + AddAuthHeaderSteps(isSecure, isOfficial, zoneLoader, fileName); - zoneLoader->AddLoadingStep(std::make_unique<StepAddProcessor>(std::make_unique<ProcessorInflate>(ZoneConstants::AUTHED_CHUNK_SIZE))); + zoneLoader->AddLoadingStep(std::make_unique<StepAddProcessor>(std::make_unique<ProcessorInflate>(ZoneConstants::AUTHED_CHUNK_SIZE))); - // Start of the XFile struct - zoneLoader->AddLoadingStep(std::make_unique<StepSkipBytes>(8)); - // Skip size and externalSize fields since they are not interesting for us - zoneLoader->AddLoadingStep(std::make_unique<StepAllocXBlocks>()); + // Start of the XFile struct + zoneLoader->AddLoadingStep(std::make_unique<StepSkipBytes>(8)); + // Skip size and externalSize fields since they are not interesting for us + zoneLoader->AddLoadingStep(std::make_unique<StepAllocXBlocks>()); - // Start of the zone content - zoneLoader->AddLoadingStep(std::make_unique<StepLoadZoneContent>(std::make_unique<ContentLoader>(), zonePtr, ZoneConstants::OFFSET_BLOCK_BIT_COUNT, ZoneConstants::INSERT_BLOCK)); + // Start of the zone content + zoneLoader->AddLoadingStep( + std::make_unique<StepLoadZoneContent>(std::make_unique<ContentLoader>(), zonePtr, ZoneConstants::OFFSET_BLOCK_BIT_COUNT, ZoneConstants::INSERT_BLOCK)); - // Return the fully setup zoneloader - return zoneLoader; - } + // Return the fully setup zoneloader + return zoneLoader; + } }; -ZoneLoader* ZoneLoaderFactory::CreateLoaderForHeader(ZoneHeader& header, std::string& fileName) -{ - return Impl::CreateLoaderForHeader(header, fileName); -} +ZoneLoader *ZoneLoaderFactory::CreateLoaderForHeader(ZoneHeader &header, std::string &fileName) { return Impl::CreateLoaderForHeader(header, fileName); } diff --git a/src/ZoneLoading/Game/IW5/ZoneLoaderFactoryIW5.h b/src/ZoneLoading/Game/IW5/ZoneLoaderFactoryIW5.h index cecef3001..f254a1270 100644 --- a/src/ZoneLoading/Game/IW5/ZoneLoaderFactoryIW5.h +++ b/src/ZoneLoading/Game/IW5/ZoneLoaderFactoryIW5.h @@ -3,13 +3,11 @@ #include "Loading/IZoneLoaderFactory.h" #include <string> -namespace IW5 -{ - class ZoneLoaderFactory final : public IZoneLoaderFactory - { - class Impl; +namespace IW5 { +class ZoneLoaderFactory final : public IZoneLoaderFactory { + class Impl; - public: - ZoneLoader* CreateLoaderForHeader(ZoneHeader& header, std::string& fileName) override; - }; -} +public: + ZoneLoader *CreateLoaderForHeader(ZoneHeader &header, std::string &fileName) override; +}; +} // namespace IW5 diff --git a/src/ZoneLoading/Game/T5/ContentLoaderT5.cpp b/src/ZoneLoading/Game/T5/ContentLoaderT5.cpp index c5fd6de3b..ef3887f5e 100644 --- a/src/ZoneLoading/Game/T5/ContentLoaderT5.cpp +++ b/src/ZoneLoading/Game/T5/ContentLoaderT5.cpp @@ -39,56 +39,47 @@ using namespace T5; -ContentLoader::ContentLoader() - : varXAsset(nullptr), - varScriptStringList(nullptr) -{ -} +ContentLoader::ContentLoader() : varXAsset(nullptr), varScriptStringList(nullptr) {} -void ContentLoader::LoadScriptStringList(const bool atStreamStart) -{ - m_stream->PushBlock(XFILE_BLOCK_VIRTUAL); +void ContentLoader::LoadScriptStringList(const bool atStreamStart) { + m_stream->PushBlock(XFILE_BLOCK_VIRTUAL); - if (atStreamStart) - m_stream->Load<ScriptStringList>(varScriptStringList); + if (atStreamStart) + m_stream->Load<ScriptStringList>(varScriptStringList); - if (varScriptStringList->strings != nullptr) - { - assert(varScriptStringList->strings == PTR_FOLLOWING); + if (varScriptStringList->strings != nullptr) { + assert(varScriptStringList->strings == PTR_FOLLOWING); - varScriptStringList->strings = m_stream->Alloc<const char*>(alignof(const char*)); - varXString = varScriptStringList->strings; - LoadXStringArray(true, varScriptStringList->count); + varScriptStringList->strings = m_stream->Alloc<const char *>(alignof(const char *)); + varXString = varScriptStringList->strings; + LoadXStringArray(true, varScriptStringList->count); - if (varScriptStringList->strings && varScriptStringList->count > 0) - m_zone->m_script_strings.InitializeForExistingZone(varScriptStringList->strings, static_cast<size_t>(varScriptStringList->count)); - } + if (varScriptStringList->strings && varScriptStringList->count > 0) + m_zone->m_script_strings.InitializeForExistingZone(varScriptStringList->strings, static_cast<size_t>(varScriptStringList->count)); + } - m_stream->PopBlock(); + m_stream->PopBlock(); - assert(m_zone->m_script_strings.Count() <= SCR_STRING_MAX + 1); + assert(m_zone->m_script_strings.Count() <= SCR_STRING_MAX + 1); } -void ContentLoader::LoadXAsset(const bool atStreamStart) const -{ -#define LOAD_ASSET(type_index, typeName, headerEntry) \ - case type_index: \ - { \ - Loader_##typeName loader(m_zone, m_stream); \ - loader.Load(&varXAsset->header.headerEntry); \ - break; \ - } -#define SKIP_ASSET(type_index, typeName, headerEntry) \ - case type_index: \ - break; - - assert(varXAsset != nullptr); - - if (atStreamStart) - m_stream->Load<XAsset>(varXAsset); - - switch (varXAsset->type) - { +void ContentLoader::LoadXAsset(const bool atStreamStart) const { +#define LOAD_ASSET(type_index, typeName, headerEntry) \ + case type_index: { \ + Loader_##typeName loader(m_zone, m_stream); \ + loader.Load(&varXAsset->header.headerEntry); \ + break; \ + } +#define SKIP_ASSET(type_index, typeName, headerEntry) \ + case type_index: \ + break; + + assert(varXAsset != nullptr); + + if (atStreamStart) + m_stream->Load<XAsset>(varXAsset); + + switch (varXAsset->type) { LOAD_ASSET(ASSET_TYPE_PHYSPRESET, PhysPreset, physPreset) LOAD_ASSET(ASSET_TYPE_PHYSCONSTRAINTS, PhysConstraints, physConstraints) LOAD_ASSET(ASSET_TYPE_DESTRUCTIBLEDEF, DestructibleDef, destructibleDef) @@ -123,55 +114,49 @@ void ContentLoader::LoadXAsset(const bool atStreamStart) const LOAD_ASSET(ASSET_TYPE_GLASSES, Glasses, glasses) LOAD_ASSET(ASSET_TYPE_EMBLEMSET, EmblemSet, emblemSet) - default: - { - throw UnsupportedAssetTypeException(varXAsset->type); - } - } + default: { + throw UnsupportedAssetTypeException(varXAsset->type); + } + } #undef LOAD_ASSET } -void ContentLoader::LoadXAssetArray(const bool atStreamStart, const size_t count) -{ - assert(varXAsset != nullptr); +void ContentLoader::LoadXAssetArray(const bool atStreamStart, const size_t count) { + assert(varXAsset != nullptr); - if (atStreamStart) - m_stream->Load<XAsset>(varXAsset, count); + if (atStreamStart) + m_stream->Load<XAsset>(varXAsset, count); - for (asset_type_t assetType = 0; assetType < ASSET_TYPE_COUNT; assetType++) - { - m_zone->m_pools->InitPoolDynamic(assetType); - } + for (asset_type_t assetType = 0; assetType < ASSET_TYPE_COUNT; assetType++) { + m_zone->m_pools->InitPoolDynamic(assetType); + } - for (size_t index = 0; index < count; index++) - { - LoadXAsset(false); - varXAsset++; - } + for (size_t index = 0; index < count; index++) { + LoadXAsset(false); + varXAsset++; + } } -void ContentLoader::Load(Zone* zone, IZoneInputStream* stream) -{ - m_zone = zone; - m_stream = stream; +void ContentLoader::Load(Zone *zone, IZoneInputStream *stream) { + m_zone = zone; + m_stream = stream; - m_stream->PushBlock(XFILE_BLOCK_VIRTUAL); + m_stream->PushBlock(XFILE_BLOCK_VIRTUAL); - XAssetList assetList{}; - m_stream->LoadDataRaw(&assetList, sizeof assetList); + XAssetList assetList{}; + m_stream->LoadDataRaw(&assetList, sizeof assetList); - varScriptStringList = &assetList.stringList; - LoadScriptStringList(false); + varScriptStringList = &assetList.stringList; + LoadScriptStringList(false); - if (assetList.assets != nullptr) - { - assert(assetList.assets == PTR_FOLLOWING); + if (assetList.assets != nullptr) { + assert(assetList.assets == PTR_FOLLOWING); - assetList.assets = m_stream->Alloc<XAsset>(alignof(XAsset)); - varXAsset = assetList.assets; - LoadXAssetArray(true, assetList.assetCount); - } + assetList.assets = m_stream->Alloc<XAsset>(alignof(XAsset)); + varXAsset = assetList.assets; + LoadXAssetArray(true, assetList.assetCount); + } - m_stream->PopBlock(); + m_stream->PopBlock(); } diff --git a/src/ZoneLoading/Game/T5/ContentLoaderT5.h b/src/ZoneLoading/Game/T5/ContentLoaderT5.h index ffc36ceb0..0bc20ddd2 100644 --- a/src/ZoneLoading/Game/T5/ContentLoaderT5.h +++ b/src/ZoneLoading/Game/T5/ContentLoaderT5.h @@ -1,23 +1,21 @@ #pragma once +#include "Game/T5/T5.h" #include "Loading/ContentLoaderBase.h" #include "Loading/IContentLoadingEntryPoint.h" -#include "Game/T5/T5.h" -namespace T5 -{ - class ContentLoader final : public ContentLoaderBase, public IContentLoadingEntryPoint - { - XAsset* varXAsset; - ScriptStringList* varScriptStringList; +namespace T5 { +class ContentLoader final : public ContentLoaderBase, public IContentLoadingEntryPoint { + XAsset *varXAsset; + ScriptStringList *varScriptStringList; - void LoadScriptStringList(bool atStreamStart); + void LoadScriptStringList(bool atStreamStart); - void LoadXAsset(bool atStreamStart) const; - void LoadXAssetArray(bool atStreamStart, size_t count); + void LoadXAsset(bool atStreamStart) const; + void LoadXAssetArray(bool atStreamStart, size_t count); - public: - ContentLoader(); +public: + ContentLoader(); - void Load(Zone* zone, IZoneInputStream* stream) override; - }; -} + void Load(Zone *zone, IZoneInputStream *stream) override; +}; +} // namespace T5 diff --git a/src/ZoneLoading/Game/T5/XAssets/gfximage/gfximage_actions.cpp b/src/ZoneLoading/Game/T5/XAssets/gfximage/gfximage_actions.cpp index 1185ee455..e6ade56f1 100644 --- a/src/ZoneLoading/Game/T5/XAssets/gfximage/gfximage_actions.cpp +++ b/src/ZoneLoading/Game/T5/XAssets/gfximage/gfximage_actions.cpp @@ -5,20 +5,13 @@ using namespace T5; -Actions_GfxImage::Actions_GfxImage(Zone* zone) - : AssetLoadingActions(zone) -{ -} +Actions_GfxImage::Actions_GfxImage(Zone *zone) : AssetLoadingActions(zone) {} -void Actions_GfxImage::OnImageLoaded(GfxImage* image) const -{ - image->loadedSize = 0; -} +void Actions_GfxImage::OnImageLoaded(GfxImage *image) const { image->loadedSize = 0; } -void Actions_GfxImage::LoadImageData(GfxImageLoadDef* loadDef, GfxImage* image) const -{ - const size_t loadDefSize = offsetof(GfxImageLoadDef, data) + loadDef->resourceSize; +void Actions_GfxImage::LoadImageData(GfxImageLoadDef *loadDef, GfxImage *image) const { + const size_t loadDefSize = offsetof(GfxImageLoadDef, data) + loadDef->resourceSize; - image->texture.loadDef = static_cast<GfxImageLoadDef*>(m_zone->GetMemory()->Alloc(loadDefSize)); - memcpy(image->texture.loadDef, loadDef, loadDefSize); + image->texture.loadDef = static_cast<GfxImageLoadDef *>(m_zone->GetMemory()->Alloc(loadDefSize)); + memcpy(image->texture.loadDef, loadDef, loadDefSize); } diff --git a/src/ZoneLoading/Game/T5/XAssets/gfximage/gfximage_actions.h b/src/ZoneLoading/Game/T5/XAssets/gfximage/gfximage_actions.h index e5f252b9a..58b396c48 100644 --- a/src/ZoneLoading/Game/T5/XAssets/gfximage/gfximage_actions.h +++ b/src/ZoneLoading/Game/T5/XAssets/gfximage/gfximage_actions.h @@ -1,16 +1,14 @@ #pragma once -#include "Loading/AssetLoadingActions.h" #include "Game/T5/T5.h" +#include "Loading/AssetLoadingActions.h" -namespace T5 -{ - class Actions_GfxImage final : public AssetLoadingActions - { - public: - explicit Actions_GfxImage(Zone* zone); +namespace T5 { +class Actions_GfxImage final : public AssetLoadingActions { +public: + explicit Actions_GfxImage(Zone *zone); - void OnImageLoaded(GfxImage* image) const; - void LoadImageData(GfxImageLoadDef* loadDef, GfxImage* image) const; - }; -} + void OnImageLoaded(GfxImage *image) const; + void LoadImageData(GfxImageLoadDef *loadDef, GfxImage *image) const; +}; +} // namespace T5 diff --git a/src/ZoneLoading/Game/T5/ZoneLoaderFactoryT5.cpp b/src/ZoneLoading/Game/T5/ZoneLoaderFactoryT5.cpp index b33a6d8f9..958474971 100644 --- a/src/ZoneLoading/Game/T5/ZoneLoaderFactoryT5.cpp +++ b/src/ZoneLoading/Game/T5/ZoneLoaderFactoryT5.cpp @@ -6,99 +6,88 @@ #include "Game/T5/T5.h" -#include "Utils/ClassUtils.h" #include "ContentLoaderT5.h" +#include "Game/GameLanguage.h" #include "Game/T5/GameAssetPoolT5.h" #include "Game/T5/GameT5.h" -#include "Game/GameLanguage.h" #include "Game/T5/ZoneConstantsT5.h" #include "Loading/Processor/ProcessorInflate.h" -#include "Loading/Steps/StepSkipBytes.h" #include "Loading/Steps/StepAddProcessor.h" #include "Loading/Steps/StepAllocXBlocks.h" #include "Loading/Steps/StepLoadZoneContent.h" +#include "Loading/Steps/StepSkipBytes.h" +#include "Utils/ClassUtils.h" using namespace T5; -class ZoneLoaderFactory::Impl -{ - static GameLanguage GetZoneLanguage(std::string& zoneName) - { - return GameLanguage::LANGUAGE_NONE; - } - - static bool CanLoad(ZoneHeader& header, bool* isSecure, bool* isOfficial) - { - assert(isSecure != nullptr); - assert(isOfficial != nullptr); +class ZoneLoaderFactory::Impl { + static GameLanguage GetZoneLanguage(std::string &zoneName) { return GameLanguage::LANGUAGE_NONE; } - if (header.m_version != ZoneConstants::ZONE_VERSION) - { - return false; - } + static bool CanLoad(ZoneHeader &header, bool *isSecure, bool *isOfficial) { + assert(isSecure != nullptr); + assert(isOfficial != nullptr); - if (!memcmp(header.m_magic, ZoneConstants::MAGIC_UNSIGNED, std::char_traits<char>::length(ZoneConstants::MAGIC_UNSIGNED))) - { - *isSecure = false; - *isOfficial = true; - return true; - } + if (header.m_version != ZoneConstants::ZONE_VERSION) { + return false; + } - return false; + if (!memcmp(header.m_magic, ZoneConstants::MAGIC_UNSIGNED, std::char_traits<char>::length(ZoneConstants::MAGIC_UNSIGNED))) { + *isSecure = false; + *isOfficial = true; + return true; } - static void SetupBlock(ZoneLoader* zoneLoader) - { + return false; + } + + static void SetupBlock(ZoneLoader *zoneLoader) { #define XBLOCK_DEF(name, type) std::make_unique<XBlock>(STR(name), name, type) - zoneLoader->AddXBlock(XBLOCK_DEF(T5::XFILE_BLOCK_TEMP, XBlock::Type::BLOCK_TYPE_TEMP)); - zoneLoader->AddXBlock(XBLOCK_DEF(T5::XFILE_BLOCK_RUNTIME, XBlock::Type::BLOCK_TYPE_RUNTIME)); - zoneLoader->AddXBlock(XBLOCK_DEF(T5::XFILE_BLOCK_LARGE_RUNTIME, XBlock::Type::BLOCK_TYPE_RUNTIME)); - zoneLoader->AddXBlock(XBLOCK_DEF(T5::XFILE_BLOCK_PHYSICAL_RUNTIME, XBlock::Type::BLOCK_TYPE_RUNTIME)); - zoneLoader->AddXBlock(XBLOCK_DEF(T5::XFILE_BLOCK_VIRTUAL, XBlock::Type::BLOCK_TYPE_NORMAL)); - zoneLoader->AddXBlock(XBLOCK_DEF(T5::XFILE_BLOCK_LARGE, XBlock::Type::BLOCK_TYPE_NORMAL)); - zoneLoader->AddXBlock(XBLOCK_DEF(T5::XFILE_BLOCK_PHYSICAL, XBlock::Type::BLOCK_TYPE_NORMAL)); + zoneLoader->AddXBlock(XBLOCK_DEF(T5::XFILE_BLOCK_TEMP, XBlock::Type::BLOCK_TYPE_TEMP)); + zoneLoader->AddXBlock(XBLOCK_DEF(T5::XFILE_BLOCK_RUNTIME, XBlock::Type::BLOCK_TYPE_RUNTIME)); + zoneLoader->AddXBlock(XBLOCK_DEF(T5::XFILE_BLOCK_LARGE_RUNTIME, XBlock::Type::BLOCK_TYPE_RUNTIME)); + zoneLoader->AddXBlock(XBLOCK_DEF(T5::XFILE_BLOCK_PHYSICAL_RUNTIME, XBlock::Type::BLOCK_TYPE_RUNTIME)); + zoneLoader->AddXBlock(XBLOCK_DEF(T5::XFILE_BLOCK_VIRTUAL, XBlock::Type::BLOCK_TYPE_NORMAL)); + zoneLoader->AddXBlock(XBLOCK_DEF(T5::XFILE_BLOCK_LARGE, XBlock::Type::BLOCK_TYPE_NORMAL)); + zoneLoader->AddXBlock(XBLOCK_DEF(T5::XFILE_BLOCK_PHYSICAL, XBlock::Type::BLOCK_TYPE_NORMAL)); #undef XBLOCK_DEF - } + } public: - static ZoneLoader* CreateLoaderForHeader(ZoneHeader& header, std::string& fileName) - { - bool isSecure; - bool isOfficial; + static ZoneLoader *CreateLoaderForHeader(ZoneHeader &header, std::string &fileName) { + bool isSecure; + bool isOfficial; - // Check if this file is a supported IW4 zone. - if (!CanLoad(header, &isSecure, &isOfficial)) - return nullptr; + // Check if this file is a supported IW4 zone. + if (!CanLoad(header, &isSecure, &isOfficial)) + return nullptr; - // Create new zone - auto zone = std::make_unique<Zone>(fileName, 0, &g_GameT5); - auto* zonePtr = zone.get(); - zone->m_pools = std::make_unique<GameAssetPoolT5>(zonePtr, 0); - zone->m_language = GetZoneLanguage(fileName); + // Create new zone + auto zone = std::make_unique<Zone>(fileName, 0, &g_GameT5); + auto *zonePtr = zone.get(); + zone->m_pools = std::make_unique<GameAssetPoolT5>(zonePtr, 0); + zone->m_language = GetZoneLanguage(fileName); - // File is supported. Now setup all required steps for loading this file. - auto* zoneLoader = new ZoneLoader(std::move(zone)); + // File is supported. Now setup all required steps for loading this file. + auto *zoneLoader = new ZoneLoader(std::move(zone)); - SetupBlock(zoneLoader); + SetupBlock(zoneLoader); - zoneLoader->AddLoadingStep(std::make_unique<StepAddProcessor>(std::make_unique<ProcessorInflate>(ZoneConstants::AUTHED_CHUNK_SIZE))); + zoneLoader->AddLoadingStep(std::make_unique<StepAddProcessor>(std::make_unique<ProcessorInflate>(ZoneConstants::AUTHED_CHUNK_SIZE))); - // Start of the XFile struct - zoneLoader->AddLoadingStep(std::make_unique<StepSkipBytes>(8)); - // Skip size and externalSize fields since they are not interesting for us - zoneLoader->AddLoadingStep(std::make_unique<StepAllocXBlocks>()); + // Start of the XFile struct + zoneLoader->AddLoadingStep(std::make_unique<StepSkipBytes>(8)); + // Skip size and externalSize fields since they are not interesting for us + zoneLoader->AddLoadingStep(std::make_unique<StepAllocXBlocks>()); - // Start of the zone content - zoneLoader->AddLoadingStep(std::make_unique<StepLoadZoneContent>(std::make_unique<ContentLoader>(), zonePtr, ZoneConstants::OFFSET_BLOCK_BIT_COUNT, ZoneConstants::INSERT_BLOCK)); + // Start of the zone content + zoneLoader->AddLoadingStep( + std::make_unique<StepLoadZoneContent>(std::make_unique<ContentLoader>(), zonePtr, ZoneConstants::OFFSET_BLOCK_BIT_COUNT, ZoneConstants::INSERT_BLOCK)); - // Return the fully setup zoneloader - return zoneLoader; - } + // Return the fully setup zoneloader + return zoneLoader; + } }; -ZoneLoader* ZoneLoaderFactory::CreateLoaderForHeader(ZoneHeader& header, std::string& fileName) -{ - return Impl::CreateLoaderForHeader(header, fileName); -} +ZoneLoader *ZoneLoaderFactory::CreateLoaderForHeader(ZoneHeader &header, std::string &fileName) { return Impl::CreateLoaderForHeader(header, fileName); } diff --git a/src/ZoneLoading/Game/T5/ZoneLoaderFactoryT5.h b/src/ZoneLoading/Game/T5/ZoneLoaderFactoryT5.h index 4a55573c7..7fc218bcb 100644 --- a/src/ZoneLoading/Game/T5/ZoneLoaderFactoryT5.h +++ b/src/ZoneLoading/Game/T5/ZoneLoaderFactoryT5.h @@ -3,13 +3,11 @@ #include "Loading/IZoneLoaderFactory.h" #include <string> -namespace T5 -{ - class ZoneLoaderFactory final : public IZoneLoaderFactory - { - class Impl; +namespace T5 { +class ZoneLoaderFactory final : public IZoneLoaderFactory { + class Impl; - public: - ZoneLoader* CreateLoaderForHeader(ZoneHeader& header, std::string& fileName) override; - }; -} +public: + ZoneLoader *CreateLoaderForHeader(ZoneHeader &header, std::string &fileName) override; +}; +} // namespace T5 diff --git a/src/ZoneLoading/Game/T6/ContentLoaderT6.cpp b/src/ZoneLoading/Game/T6/ContentLoaderT6.cpp index cffe27efc..936816dcb 100644 --- a/src/ZoneLoading/Game/T6/ContentLoaderT6.cpp +++ b/src/ZoneLoading/Game/T6/ContentLoaderT6.cpp @@ -55,53 +55,44 @@ using namespace T6; -ContentLoader::ContentLoader() - : varXAsset(nullptr), - varScriptStringList(nullptr) -{ -} +ContentLoader::ContentLoader() : varXAsset(nullptr), varScriptStringList(nullptr) {} -void ContentLoader::LoadScriptStringList(const bool atStreamStart) -{ - m_stream->PushBlock(XFILE_BLOCK_VIRTUAL); +void ContentLoader::LoadScriptStringList(const bool atStreamStart) { + m_stream->PushBlock(XFILE_BLOCK_VIRTUAL); - if (atStreamStart) - m_stream->Load<ScriptStringList>(varScriptStringList); + if (atStreamStart) + m_stream->Load<ScriptStringList>(varScriptStringList); - if (varScriptStringList->strings != nullptr) - { - assert(varScriptStringList->strings == PTR_FOLLOWING); + if (varScriptStringList->strings != nullptr) { + assert(varScriptStringList->strings == PTR_FOLLOWING); - varScriptStringList->strings = m_stream->Alloc<const char*>(alignof(const char*)); - varXString = varScriptStringList->strings; - LoadXStringArray(true, varScriptStringList->count); + varScriptStringList->strings = m_stream->Alloc<const char *>(alignof(const char *)); + varXString = varScriptStringList->strings; + LoadXStringArray(true, varScriptStringList->count); - if (varScriptStringList->strings && varScriptStringList->count > 0) - m_zone->m_script_strings.InitializeForExistingZone(varScriptStringList->strings, static_cast<size_t>(varScriptStringList->count)); - } + if (varScriptStringList->strings && varScriptStringList->count > 0) + m_zone->m_script_strings.InitializeForExistingZone(varScriptStringList->strings, static_cast<size_t>(varScriptStringList->count)); + } - m_stream->PopBlock(); + m_stream->PopBlock(); - assert(m_zone->m_script_strings.Count() <= SCR_STRING_MAX + 1); + assert(m_zone->m_script_strings.Count() <= SCR_STRING_MAX + 1); } -void ContentLoader::LoadXAsset(const bool atStreamStart) const -{ -#define LOAD_ASSET(type_index, typeName, headerEntry) \ - case type_index: \ - { \ - Loader_##typeName loader(m_zone, m_stream); \ - loader.Load(&varXAsset->header.headerEntry); \ - break; \ - } +void ContentLoader::LoadXAsset(const bool atStreamStart) const { +#define LOAD_ASSET(type_index, typeName, headerEntry) \ + case type_index: { \ + Loader_##typeName loader(m_zone, m_stream); \ + loader.Load(&varXAsset->header.headerEntry); \ + break; \ + } - assert(varXAsset != nullptr); + assert(varXAsset != nullptr); - if (atStreamStart) - m_stream->Load<XAsset>(varXAsset); + if (atStreamStart) + m_stream->Load<XAsset>(varXAsset); - switch (varXAsset->type) - { + switch (varXAsset->type) { LOAD_ASSET(ASSET_TYPE_PHYSPRESET, PhysPreset, physPreset) LOAD_ASSET(ASSET_TYPE_PHYSCONSTRAINTS, PhysConstraints, physConstraints) LOAD_ASSET(ASSET_TYPE_DESTRUCTIBLEDEF, DestructibleDef, destructibleDef) @@ -152,64 +143,57 @@ void ContentLoader::LoadXAsset(const bool atStreamStart) const LOAD_ASSET(ASSET_TYPE_FOOTSTEPFX_TABLE, FootstepFXTableDef, footstepFXTableDef) LOAD_ASSET(ASSET_TYPE_ZBARRIER, ZBarrierDef, zbarrierDef) - default: - { - throw UnsupportedAssetTypeException(varXAsset->type); - } - } + default: { + throw UnsupportedAssetTypeException(varXAsset->type); + } + } #undef LOAD_ASSET } -void ContentLoader::LoadXAssetArray(const bool atStreamStart, const size_t count) -{ - assert(varXAsset != nullptr); +void ContentLoader::LoadXAssetArray(const bool atStreamStart, const size_t count) { + assert(varXAsset != nullptr); - if (atStreamStart) - m_stream->Load<XAsset>(varXAsset, count); + if (atStreamStart) + m_stream->Load<XAsset>(varXAsset, count); - for (asset_type_t assetType = 0; assetType < ASSET_TYPE_COUNT; assetType++) - { - m_zone->m_pools->InitPoolDynamic(assetType); - } + for (asset_type_t assetType = 0; assetType < ASSET_TYPE_COUNT; assetType++) { + m_zone->m_pools->InitPoolDynamic(assetType); + } - for (size_t index = 0; index < count; index++) - { - LoadXAsset(false); - varXAsset++; - } + for (size_t index = 0; index < count; index++) { + LoadXAsset(false); + varXAsset++; + } } -void ContentLoader::Load(Zone* zone, IZoneInputStream* stream) -{ - m_zone = zone; - m_stream = stream; +void ContentLoader::Load(Zone *zone, IZoneInputStream *stream) { + m_zone = zone; + m_stream = stream; - m_stream->PushBlock(XFILE_BLOCK_VIRTUAL); + m_stream->PushBlock(XFILE_BLOCK_VIRTUAL); - XAssetList assetList{}; - m_stream->LoadDataRaw(&assetList, sizeof assetList); + XAssetList assetList{}; + m_stream->LoadDataRaw(&assetList, sizeof assetList); - varScriptStringList = &assetList.stringList; - LoadScriptStringList(false); + varScriptStringList = &assetList.stringList; + LoadScriptStringList(false); - if (assetList.depends != nullptr) - { - assert(assetList.depends == PTR_FOLLOWING); + if (assetList.depends != nullptr) { + assert(assetList.depends == PTR_FOLLOWING); - assetList.depends = m_stream->Alloc<const char*>(alignof(const char*)); - varXString = assetList.depends; - LoadXStringArray(true, assetList.dependCount); - } + assetList.depends = m_stream->Alloc<const char *>(alignof(const char *)); + varXString = assetList.depends; + LoadXStringArray(true, assetList.dependCount); + } - if (assetList.assets != nullptr) - { - assert(assetList.assets == PTR_FOLLOWING); + if (assetList.assets != nullptr) { + assert(assetList.assets == PTR_FOLLOWING); - assetList.assets = m_stream->Alloc<XAsset>(alignof(XAsset)); - varXAsset = assetList.assets; - LoadXAssetArray(true, assetList.assetCount); - } + assetList.assets = m_stream->Alloc<XAsset>(alignof(XAsset)); + varXAsset = assetList.assets; + LoadXAssetArray(true, assetList.assetCount); + } - m_stream->PopBlock(); + m_stream->PopBlock(); } diff --git a/src/ZoneLoading/Game/T6/ContentLoaderT6.h b/src/ZoneLoading/Game/T6/ContentLoaderT6.h index 592e6f81e..9e52850a9 100644 --- a/src/ZoneLoading/Game/T6/ContentLoaderT6.h +++ b/src/ZoneLoading/Game/T6/ContentLoaderT6.h @@ -1,23 +1,21 @@ #pragma once +#include "Game/T6/T6.h" #include "Loading/ContentLoaderBase.h" #include "Loading/IContentLoadingEntryPoint.h" -#include "Game/T6/T6.h" -namespace T6 -{ - class ContentLoader final : public ContentLoaderBase, public IContentLoadingEntryPoint - { - XAsset* varXAsset; - ScriptStringList* varScriptStringList; +namespace T6 { +class ContentLoader final : public ContentLoaderBase, public IContentLoadingEntryPoint { + XAsset *varXAsset; + ScriptStringList *varScriptStringList; - void LoadScriptStringList(bool atStreamStart); + void LoadScriptStringList(bool atStreamStart); - void LoadXAsset(bool atStreamStart) const; - void LoadXAssetArray(bool atStreamStart, size_t count); + void LoadXAsset(bool atStreamStart) const; + void LoadXAssetArray(bool atStreamStart, size_t count); - public: - ContentLoader(); +public: + ContentLoader(); - void Load(Zone* zone, IZoneInputStream* stream) override; - }; -} + void Load(Zone *zone, IZoneInputStream *stream) override; +}; +} // namespace T6 diff --git a/src/ZoneLoading/Game/T6/XAssets/gfximage/gfximage_actions.cpp b/src/ZoneLoading/Game/T6/XAssets/gfximage/gfximage_actions.cpp index 8c047c00a..9988f0f16 100644 --- a/src/ZoneLoading/Game/T6/XAssets/gfximage/gfximage_actions.cpp +++ b/src/ZoneLoading/Game/T6/XAssets/gfximage/gfximage_actions.cpp @@ -5,20 +5,13 @@ using namespace T6; -Actions_GfxImage::Actions_GfxImage(Zone* zone) - : AssetLoadingActions(zone) -{ -} +Actions_GfxImage::Actions_GfxImage(Zone *zone) : AssetLoadingActions(zone) {} -void Actions_GfxImage::OnImageLoaded(GfxImage* image) const -{ - image->loadedSize = 0; -} +void Actions_GfxImage::OnImageLoaded(GfxImage *image) const { image->loadedSize = 0; } -void Actions_GfxImage::LoadImageData(GfxImageLoadDef* loadDef, GfxImage* image) const -{ - const size_t loadDefSize = offsetof(T6::GfxImageLoadDef, data) + loadDef->resourceSize; +void Actions_GfxImage::LoadImageData(GfxImageLoadDef *loadDef, GfxImage *image) const { + const size_t loadDefSize = offsetof(T6::GfxImageLoadDef, data) + loadDef->resourceSize; - image->texture.loadDef = static_cast<GfxImageLoadDef*>(m_zone->GetMemory()->Alloc(loadDefSize)); - memcpy(image->texture.loadDef, loadDef, loadDefSize); + image->texture.loadDef = static_cast<GfxImageLoadDef *>(m_zone->GetMemory()->Alloc(loadDefSize)); + memcpy(image->texture.loadDef, loadDef, loadDefSize); } diff --git a/src/ZoneLoading/Game/T6/XAssets/gfximage/gfximage_actions.h b/src/ZoneLoading/Game/T6/XAssets/gfximage/gfximage_actions.h index 67b32395a..2379708ea 100644 --- a/src/ZoneLoading/Game/T6/XAssets/gfximage/gfximage_actions.h +++ b/src/ZoneLoading/Game/T6/XAssets/gfximage/gfximage_actions.h @@ -1,16 +1,14 @@ #pragma once -#include "Loading/AssetLoadingActions.h" #include "Game/T6/T6.h" +#include "Loading/AssetLoadingActions.h" -namespace T6 -{ - class Actions_GfxImage final : public AssetLoadingActions - { - public: - explicit Actions_GfxImage(Zone* zone); +namespace T6 { +class Actions_GfxImage final : public AssetLoadingActions { +public: + explicit Actions_GfxImage(Zone *zone); - void OnImageLoaded(GfxImage* image) const; - void LoadImageData(GfxImageLoadDef* loadDef, GfxImage* image) const; - }; -} + void OnImageLoaded(GfxImage *image) const; + void LoadImageData(GfxImageLoadDef *loadDef, GfxImage *image) const; +}; +} // namespace T6 diff --git a/src/ZoneLoading/Game/T6/ZoneLoaderFactoryT6.cpp b/src/ZoneLoading/Game/T6/ZoneLoaderFactoryT6.cpp index b613d2ef8..ffe44c45a 100644 --- a/src/ZoneLoading/Game/T6/ZoneLoaderFactoryT6.cpp +++ b/src/ZoneLoading/Game/T6/ZoneLoaderFactoryT6.cpp @@ -7,215 +7,192 @@ #include "Game/T6/T6.h" #include "Game/T6/ZoneConstantsT6.h" -#include "Utils/ClassUtils.h" #include "ContentLoaderT6.h" -#include "Game/T6/GameAssetPoolT6.h" #include "Game/GameLanguage.h" +#include "Game/T6/GameAssetPoolT6.h" #include "Game/T6/GameT6.h" #include "Loading/Processor/ProcessorXChunks.h" -#include "Zone/XChunk/XChunkProcessorSalsa20Decryption.h" -#include "Zone/XChunk/XChunkProcessorInflate.h" -#include "Loading/Steps/StepVerifyMagic.h" -#include "Loading/Steps/StepSkipBytes.h" -#include "Loading/Steps/StepVerifyFileName.h" -#include "Loading/Steps/StepLoadSignature.h" -#include "Loading/Steps/StepVerifySignature.h" #include "Loading/Steps/StepAddProcessor.h" #include "Loading/Steps/StepAllocXBlocks.h" +#include "Loading/Steps/StepLoadSignature.h" #include "Loading/Steps/StepLoadZoneContent.h" #include "Loading/Steps/StepLoadZoneSizes.h" +#include "Loading/Steps/StepSkipBytes.h" +#include "Loading/Steps/StepVerifyFileName.h" +#include "Loading/Steps/StepVerifyMagic.h" +#include "Loading/Steps/StepVerifySignature.h" +#include "Utils/ClassUtils.h" +#include "Zone/XChunk/XChunkProcessorInflate.h" +#include "Zone/XChunk/XChunkProcessorSalsa20Decryption.h" using namespace T6; -class ZoneLoaderFactory::Impl -{ - static GameLanguage GetZoneLanguage(std::string& zoneName) - { - auto languagePrefixes = g_GameT6.GetLanguagePrefixes(); - - for (const auto& languagePrefix : languagePrefixes) - { - if (zoneName.compare(0, languagePrefix.m_prefix.length(), languagePrefix.m_prefix) == 0) - { - return languagePrefix.m_language; - } - } - - return GameLanguage::LANGUAGE_NONE; +class ZoneLoaderFactory::Impl { + static GameLanguage GetZoneLanguage(std::string &zoneName) { + auto languagePrefixes = g_GameT6.GetLanguagePrefixes(); + + for (const auto &languagePrefix : languagePrefixes) { + if (zoneName.compare(0, languagePrefix.m_prefix.length(), languagePrefix.m_prefix) == 0) { + return languagePrefix.m_language; + } } - static bool CanLoad(ZoneHeader& header, bool* isSecure, bool* isOfficial, bool* isEncrypted) - { - assert(isSecure != nullptr); - assert(isOfficial != nullptr); - - if (header.m_version != ZoneConstants::ZONE_VERSION) - { - return false; - } - - if (!memcmp(header.m_magic, ZoneConstants::MAGIC_SIGNED_TREYARCH, 8)) - { - *isSecure = true; - *isOfficial = true; - *isEncrypted = true; - return true; - } - - if (!memcmp(header.m_magic, ZoneConstants::MAGIC_SIGNED_OAT, 8)) - { - *isSecure = true; - *isOfficial = false; - *isEncrypted = true; - return true; - } - - if (!memcmp(header.m_magic, ZoneConstants::MAGIC_UNSIGNED, 8)) - { - *isSecure = false; - *isOfficial = true; - *isEncrypted = true; - return true; - } - - if (!memcmp(header.m_magic, ZoneConstants::MAGIC_UNSIGNED_SERVER, 8)) - { - *isSecure = false; - *isOfficial = true; - *isEncrypted = false; - return true; - } - - return false; + return GameLanguage::LANGUAGE_NONE; + } + + static bool CanLoad(ZoneHeader &header, bool *isSecure, bool *isOfficial, bool *isEncrypted) { + assert(isSecure != nullptr); + assert(isOfficial != nullptr); + + if (header.m_version != ZoneConstants::ZONE_VERSION) { + return false; } - static void SetupBlock(ZoneLoader* zoneLoader) - { -#define XBLOCK_DEF(name, type) std::make_unique<XBlock>(STR(name), name, type) + if (!memcmp(header.m_magic, ZoneConstants::MAGIC_SIGNED_TREYARCH, 8)) { + *isSecure = true; + *isOfficial = true; + *isEncrypted = true; + return true; + } - zoneLoader->AddXBlock(XBLOCK_DEF(T6::XFILE_BLOCK_TEMP, XBlock::Type::BLOCK_TYPE_TEMP)); - zoneLoader->AddXBlock(XBLOCK_DEF(T6::XFILE_BLOCK_RUNTIME_VIRTUAL, XBlock::Type::BLOCK_TYPE_RUNTIME)); - zoneLoader->AddXBlock(XBLOCK_DEF(T6::XFILE_BLOCK_RUNTIME_PHYSICAL, XBlock::Type::BLOCK_TYPE_RUNTIME)); - zoneLoader->AddXBlock(XBLOCK_DEF(T6::XFILE_BLOCK_DELAY_VIRTUAL, XBlock::Type::BLOCK_TYPE_DELAY)); - zoneLoader->AddXBlock(XBLOCK_DEF(T6::XFILE_BLOCK_DELAY_PHYSICAL, XBlock::Type::BLOCK_TYPE_DELAY)); - zoneLoader->AddXBlock(XBLOCK_DEF(T6::XFILE_BLOCK_VIRTUAL, XBlock::Type::BLOCK_TYPE_NORMAL)); - zoneLoader->AddXBlock(XBLOCK_DEF(T6::XFILE_BLOCK_PHYSICAL, XBlock::Type::BLOCK_TYPE_NORMAL)); - zoneLoader->AddXBlock(XBLOCK_DEF(T6::XFILE_BLOCK_STREAMER_RESERVE, XBlock::Type::BLOCK_TYPE_NORMAL)); + if (!memcmp(header.m_magic, ZoneConstants::MAGIC_SIGNED_OAT, 8)) { + *isSecure = true; + *isOfficial = false; + *isEncrypted = true; + return true; + } -#undef XBLOCK_DEF + if (!memcmp(header.m_magic, ZoneConstants::MAGIC_UNSIGNED, 8)) { + *isSecure = false; + *isOfficial = true; + *isEncrypted = true; + return true; } - static std::unique_ptr<IPublicKeyAlgorithm> SetupRSA(const bool isOfficial) - { - if (isOfficial) - { - auto rsa = Crypto::CreateRSA(IPublicKeyAlgorithm::HashingAlgorithm::RSA_HASH_SHA256, Crypto::RSAPaddingMode::RSA_PADDING_PSS); - - if (!rsa->SetKey(ZoneConstants::RSA_PUBLIC_KEY_TREYARCH, sizeof(ZoneConstants::RSA_PUBLIC_KEY_TREYARCH))) - { - printf("Invalid public key for signature checking\n"); - return nullptr; - } - - return rsa; - } - else - { - assert(false); - - // TODO: Load custom RSA key here - return nullptr; - } + if (!memcmp(header.m_magic, ZoneConstants::MAGIC_UNSIGNED_SERVER, 8)) { + *isSecure = false; + *isOfficial = true; + *isEncrypted = false; + return true; } - static ISignatureProvider* AddAuthHeaderSteps(const bool isSecure, ZoneLoader* zoneLoader, std::string& fileName) - { - // Unsigned zones do not have an auth header - if (!isSecure) - return nullptr; + return false; + } - zoneLoader->AddLoadingStep(std::make_unique<StepVerifyMagic>(ZoneConstants::MAGIC_AUTH_HEADER)); - zoneLoader->AddLoadingStep(std::make_unique<StepSkipBytes>(4)); // Loading Flags which are always zero - zoneLoader->AddLoadingStep(std::make_unique<StepVerifyFileName>(fileName, 32)); + static void SetupBlock(ZoneLoader *zoneLoader) { +#define XBLOCK_DEF(name, type) std::make_unique<XBlock>(STR(name), name, type) - auto signatureLoadStep = std::make_unique<StepLoadSignature>(256); - auto* signatureLoadStepPtr = signatureLoadStep.get(); - zoneLoader->AddLoadingStep(std::move(signatureLoadStep)); + zoneLoader->AddXBlock(XBLOCK_DEF(T6::XFILE_BLOCK_TEMP, XBlock::Type::BLOCK_TYPE_TEMP)); + zoneLoader->AddXBlock(XBLOCK_DEF(T6::XFILE_BLOCK_RUNTIME_VIRTUAL, XBlock::Type::BLOCK_TYPE_RUNTIME)); + zoneLoader->AddXBlock(XBLOCK_DEF(T6::XFILE_BLOCK_RUNTIME_PHYSICAL, XBlock::Type::BLOCK_TYPE_RUNTIME)); + zoneLoader->AddXBlock(XBLOCK_DEF(T6::XFILE_BLOCK_DELAY_VIRTUAL, XBlock::Type::BLOCK_TYPE_DELAY)); + zoneLoader->AddXBlock(XBLOCK_DEF(T6::XFILE_BLOCK_DELAY_PHYSICAL, XBlock::Type::BLOCK_TYPE_DELAY)); + zoneLoader->AddXBlock(XBLOCK_DEF(T6::XFILE_BLOCK_VIRTUAL, XBlock::Type::BLOCK_TYPE_NORMAL)); + zoneLoader->AddXBlock(XBLOCK_DEF(T6::XFILE_BLOCK_PHYSICAL, XBlock::Type::BLOCK_TYPE_NORMAL)); + zoneLoader->AddXBlock(XBLOCK_DEF(T6::XFILE_BLOCK_STREAMER_RESERVE, XBlock::Type::BLOCK_TYPE_NORMAL)); - return signatureLoadStepPtr; - } +#undef XBLOCK_DEF + } + + static std::unique_ptr<IPublicKeyAlgorithm> SetupRSA(const bool isOfficial) { + if (isOfficial) { + auto rsa = Crypto::CreateRSA(IPublicKeyAlgorithm::HashingAlgorithm::RSA_HASH_SHA256, Crypto::RSAPaddingMode::RSA_PADDING_PSS); + + if (!rsa->SetKey(ZoneConstants::RSA_PUBLIC_KEY_TREYARCH, sizeof(ZoneConstants::RSA_PUBLIC_KEY_TREYARCH))) { + printf("Invalid public key for signature checking\n"); + return nullptr; + } - static ICapturedDataProvider* AddXChunkProcessor(bool isEncrypted, ZoneLoader* zoneLoader, std::string& fileName) - { - ICapturedDataProvider* result = nullptr; - auto xChunkProcessor = std::make_unique<ProcessorXChunks>(ZoneConstants::STREAM_COUNT, ZoneConstants::XCHUNK_SIZE, ZoneConstants::VANILLA_BUFFER_SIZE); - - if (isEncrypted) - { - // If zone is encrypted, the decryption is applied before the decompression. T6 Zones always use Salsa20. - auto chunkProcessorSalsa20 = std::make_unique<XChunkProcessorSalsa20Decryption>(ZoneConstants::STREAM_COUNT, fileName, ZoneConstants::SALSA20_KEY_TREYARCH, - sizeof(ZoneConstants::SALSA20_KEY_TREYARCH)); - result = chunkProcessorSalsa20.get(); - xChunkProcessor->AddChunkProcessor(std::move(chunkProcessorSalsa20)); - } - - // Decompress the chunks using zlib - xChunkProcessor->AddChunkProcessor(std::make_unique<XChunkProcessorInflate>()); - zoneLoader->AddLoadingStep(std::make_unique<StepAddProcessor>(std::move(xChunkProcessor))); - - // If there is encryption, the signed data of the zone is the final hash blocks provided by the Salsa20 IV adaption algorithm - return result; + return rsa; + } else { + assert(false); + + // TODO: Load custom RSA key here + return nullptr; + } + } + + static ISignatureProvider *AddAuthHeaderSteps(const bool isSecure, ZoneLoader *zoneLoader, std::string &fileName) { + // Unsigned zones do not have an auth header + if (!isSecure) + return nullptr; + + zoneLoader->AddLoadingStep(std::make_unique<StepVerifyMagic>(ZoneConstants::MAGIC_AUTH_HEADER)); + zoneLoader->AddLoadingStep(std::make_unique<StepSkipBytes>(4)); // Loading Flags which are always zero + zoneLoader->AddLoadingStep(std::make_unique<StepVerifyFileName>(fileName, 32)); + + auto signatureLoadStep = std::make_unique<StepLoadSignature>(256); + auto *signatureLoadStepPtr = signatureLoadStep.get(); + zoneLoader->AddLoadingStep(std::move(signatureLoadStep)); + + return signatureLoadStepPtr; + } + + static ICapturedDataProvider *AddXChunkProcessor(bool isEncrypted, ZoneLoader *zoneLoader, std::string &fileName) { + ICapturedDataProvider *result = nullptr; + auto xChunkProcessor = std::make_unique<ProcessorXChunks>(ZoneConstants::STREAM_COUNT, ZoneConstants::XCHUNK_SIZE, ZoneConstants::VANILLA_BUFFER_SIZE); + + if (isEncrypted) { + // If zone is encrypted, the decryption is applied before the decompression. T6 Zones always use Salsa20. + auto chunkProcessorSalsa20 = std::make_unique<XChunkProcessorSalsa20Decryption>( + ZoneConstants::STREAM_COUNT, fileName, ZoneConstants::SALSA20_KEY_TREYARCH, sizeof(ZoneConstants::SALSA20_KEY_TREYARCH)); + result = chunkProcessorSalsa20.get(); + xChunkProcessor->AddChunkProcessor(std::move(chunkProcessorSalsa20)); } -public: - static ZoneLoader* CreateLoaderForHeader(ZoneHeader& header, std::string& fileName) - { - bool isSecure; - bool isOfficial; - bool isEncrypted; + // Decompress the chunks using zlib + xChunkProcessor->AddChunkProcessor(std::make_unique<XChunkProcessorInflate>()); + zoneLoader->AddLoadingStep(std::make_unique<StepAddProcessor>(std::move(xChunkProcessor))); + + // If there is encryption, the signed data of the zone is the final hash blocks provided by the Salsa20 IV adaption algorithm + return result; + } - // Check if this file is a supported T6 zone. - if (!CanLoad(header, &isSecure, &isOfficial, &isEncrypted)) - return nullptr; +public: + static ZoneLoader *CreateLoaderForHeader(ZoneHeader &header, std::string &fileName) { + bool isSecure; + bool isOfficial; + bool isEncrypted; - // Create new zone - auto zone = std::make_unique<Zone>(fileName, 0, &g_GameT6); - auto* zonePtr = zone.get(); - zone->m_pools = std::make_unique<GameAssetPoolT6>(zonePtr, 0); - zone->m_language = GetZoneLanguage(fileName); + // Check if this file is a supported T6 zone. + if (!CanLoad(header, &isSecure, &isOfficial, &isEncrypted)) + return nullptr; - // File is supported. Now setup all required steps for loading this file. - auto* zoneLoader = new ZoneLoader(std::move(zone)); + // Create new zone + auto zone = std::make_unique<Zone>(fileName, 0, &g_GameT6); + auto *zonePtr = zone.get(); + zone->m_pools = std::make_unique<GameAssetPoolT6>(zonePtr, 0); + zone->m_language = GetZoneLanguage(fileName); - SetupBlock(zoneLoader); + // File is supported. Now setup all required steps for loading this file. + auto *zoneLoader = new ZoneLoader(std::move(zone)); - // If file is signed setup a RSA instance. - auto rsa = isSecure ? SetupRSA(isOfficial) : nullptr; + SetupBlock(zoneLoader); - // Add steps for loading the auth header which also contain the signature of the zone if it is signed. - ISignatureProvider* signatureProvider = AddAuthHeaderSteps(isSecure, zoneLoader, fileName); + // If file is signed setup a RSA instance. + auto rsa = isSecure ? SetupRSA(isOfficial) : nullptr; - // Setup loading XChunks from the zone from this point on. - ICapturedDataProvider* signatureDataProvider = AddXChunkProcessor(isEncrypted, zoneLoader, fileName); + // Add steps for loading the auth header which also contain the signature of the zone if it is signed. + ISignatureProvider *signatureProvider = AddAuthHeaderSteps(isSecure, zoneLoader, fileName); - // Start of the XFile struct - zoneLoader->AddLoadingStep(std::make_unique<StepLoadZoneSizes>()); - zoneLoader->AddLoadingStep(std::make_unique<StepAllocXBlocks>()); + // Setup loading XChunks from the zone from this point on. + ICapturedDataProvider *signatureDataProvider = AddXChunkProcessor(isEncrypted, zoneLoader, fileName); - // Start of the zone content - zoneLoader->AddLoadingStep(std::make_unique<StepLoadZoneContent>(std::make_unique<ContentLoader>(), zonePtr, ZoneConstants::OFFSET_BLOCK_BIT_COUNT, ZoneConstants::INSERT_BLOCK)); + // Start of the XFile struct + zoneLoader->AddLoadingStep(std::make_unique<StepLoadZoneSizes>()); + zoneLoader->AddLoadingStep(std::make_unique<StepAllocXBlocks>()); - if (isSecure) - { - zoneLoader->AddLoadingStep(std::make_unique<StepVerifySignature>(std::move(rsa), signatureProvider, signatureDataProvider)); - } + // Start of the zone content + zoneLoader->AddLoadingStep( + std::make_unique<StepLoadZoneContent>(std::make_unique<ContentLoader>(), zonePtr, ZoneConstants::OFFSET_BLOCK_BIT_COUNT, ZoneConstants::INSERT_BLOCK)); - // Return the fully setup zoneloader - return zoneLoader; + if (isSecure) { + zoneLoader->AddLoadingStep(std::make_unique<StepVerifySignature>(std::move(rsa), signatureProvider, signatureDataProvider)); } + + // Return the fully setup zoneloader + return zoneLoader; + } }; -ZoneLoader* ZoneLoaderFactory::CreateLoaderForHeader(ZoneHeader& header, std::string& fileName) -{ - return Impl::CreateLoaderForHeader(header, fileName); -} +ZoneLoader *ZoneLoaderFactory::CreateLoaderForHeader(ZoneHeader &header, std::string &fileName) { return Impl::CreateLoaderForHeader(header, fileName); } diff --git a/src/ZoneLoading/Game/T6/ZoneLoaderFactoryT6.h b/src/ZoneLoading/Game/T6/ZoneLoaderFactoryT6.h index 4ff8af076..6244066df 100644 --- a/src/ZoneLoading/Game/T6/ZoneLoaderFactoryT6.h +++ b/src/ZoneLoading/Game/T6/ZoneLoaderFactoryT6.h @@ -3,13 +3,11 @@ #include "Loading/IZoneLoaderFactory.h" #include <string> -namespace T6 -{ - class ZoneLoaderFactory final : public IZoneLoaderFactory - { - class Impl; +namespace T6 { +class ZoneLoaderFactory final : public IZoneLoaderFactory { + class Impl; - public: - ZoneLoader* CreateLoaderForHeader(ZoneHeader& header, std::string& fileName) override; - }; -} +public: + ZoneLoader *CreateLoaderForHeader(ZoneHeader &header, std::string &fileName) override; +}; +} // namespace T6 diff --git a/src/ZoneLoading/Loading/AssetLoader.cpp b/src/ZoneLoading/Loading/AssetLoader.cpp index b2fb1eaf0..5cffb6ce0 100644 --- a/src/ZoneLoading/Loading/AssetLoader.cpp +++ b/src/ZoneLoading/Loading/AssetLoader.cpp @@ -1,85 +1,68 @@ #include "AssetLoader.h" -#include <cassert> #include <algorithm> +#include <cassert> -AssetLoader::AssetLoader(const asset_type_t assetType, Zone* zone, IZoneInputStream* stream) - : ContentLoaderBase(zone, stream), - m_asset_type(assetType), - varScriptString(nullptr) -{ -} +AssetLoader::AssetLoader(const asset_type_t assetType, Zone *zone, IZoneInputStream *stream) + : ContentLoaderBase(zone, stream), m_asset_type(assetType), varScriptString(nullptr) {} -void AssetLoader::AddDependency(XAssetInfoGeneric* assetInfo) -{ - if (assetInfo == nullptr) - return; +void AssetLoader::AddDependency(XAssetInfoGeneric *assetInfo) { + if (assetInfo == nullptr) + return; - const auto existingEntry = std::find(m_dependencies.begin(), m_dependencies.end(), assetInfo); - if (existingEntry != m_dependencies.end()) - { - return; - } + const auto existingEntry = std::find(m_dependencies.begin(), m_dependencies.end(), assetInfo); + if (existingEntry != m_dependencies.end()) { + return; + } - m_dependencies.push_back(assetInfo); + m_dependencies.push_back(assetInfo); } -scr_string_t AssetLoader::UseScriptString(const scr_string_t scrString) -{ - assert(scrString < m_zone->m_script_strings.Count()); +scr_string_t AssetLoader::UseScriptString(const scr_string_t scrString) { + assert(scrString < m_zone->m_script_strings.Count()); - if (scrString >= m_zone->m_script_strings.Count()) - return 0u; + if (scrString >= m_zone->m_script_strings.Count()) + return 0u; - m_used_script_strings.emplace(scrString); - return scrString; + m_used_script_strings.emplace(scrString); + return scrString; } -void AssetLoader::LoadScriptStringArray(const bool atStreamStart, const size_t count) -{ - assert(varScriptString != nullptr); +void AssetLoader::LoadScriptStringArray(const bool atStreamStart, const size_t count) { + assert(varScriptString != nullptr); - if (atStreamStart) - m_stream->Load<scr_string_t>(varScriptString, count); + if (atStreamStart) + m_stream->Load<scr_string_t>(varScriptString, count); - auto* ptr = varScriptString; - for (size_t index = 0; index < count; index++) - { - *ptr = UseScriptString(*ptr); - ptr++; - } + auto *ptr = varScriptString; + for (size_t index = 0; index < count; index++) { + *ptr = UseScriptString(*ptr); + ptr++; + } } -void AssetLoader::MarkScriptStringArrayAsUsed(const scr_string_t* scrStringArray, const size_t count) -{ - for (size_t index = 0; index < count; index++) - { - const auto scrString = scrStringArray[index]; - if (scrString >= m_zone->m_script_strings.Count()) - continue; +void AssetLoader::MarkScriptStringArrayAsUsed(const scr_string_t *scrStringArray, const size_t count) { + for (size_t index = 0; index < count; index++) { + const auto scrString = scrStringArray[index]; + if (scrString >= m_zone->m_script_strings.Count()) + continue; - m_used_script_strings.emplace(scrString); - } + m_used_script_strings.emplace(scrString); + } } -XAssetInfoGeneric* AssetLoader::LinkAsset(std::string name, void* asset) -{ - std::vector<scr_string_t> usedScriptStrings; - if (!m_used_script_strings.empty()) - { - for (auto scrString : m_used_script_strings) - { - usedScriptStrings.push_back(scrString); - } - - std::sort(usedScriptStrings.begin(), usedScriptStrings.end()); - m_used_script_strings.clear(); +XAssetInfoGeneric *AssetLoader::LinkAsset(std::string name, void *asset) { + std::vector<scr_string_t> usedScriptStrings; + if (!m_used_script_strings.empty()) { + for (auto scrString : m_used_script_strings) { + usedScriptStrings.push_back(scrString); } - return m_zone->m_pools->AddAsset(m_asset_type, std::move(name), asset, std::move(m_dependencies), std::move(usedScriptStrings)); -} + std::sort(usedScriptStrings.begin(), usedScriptStrings.end()); + m_used_script_strings.clear(); + } -XAssetInfoGeneric* AssetLoader::GetAssetInfo(std::string name) const -{ - return m_zone->m_pools->GetAsset(m_asset_type, std::move(name)); + return m_zone->m_pools->AddAsset(m_asset_type, std::move(name), asset, std::move(m_dependencies), std::move(usedScriptStrings)); } + +XAssetInfoGeneric *AssetLoader::GetAssetInfo(std::string name) const { return m_zone->m_pools->GetAsset(m_asset_type, std::move(name)); } diff --git a/src/ZoneLoading/Loading/AssetLoader.h b/src/ZoneLoading/Loading/AssetLoader.h index 6c7550f67..1cce8087b 100644 --- a/src/ZoneLoading/Loading/AssetLoader.h +++ b/src/ZoneLoading/Loading/AssetLoader.h @@ -1,31 +1,30 @@ #pragma once -#include <vector> #include <unordered_set> +#include <vector> -#include "Zone/ZoneTypes.h" -#include "Pool/XAssetInfo.h" #include "ContentLoaderBase.h" +#include "Pool/XAssetInfo.h" +#include "Zone/ZoneTypes.h" -class AssetLoader : public ContentLoaderBase -{ - asset_type_t m_asset_type; +class AssetLoader : public ContentLoaderBase { + asset_type_t m_asset_type; - std::vector<XAssetInfoGeneric*> m_dependencies; - std::unordered_set<scr_string_t> m_used_script_strings; + std::vector<XAssetInfoGeneric *> m_dependencies; + std::unordered_set<scr_string_t> m_used_script_strings; protected: - scr_string_t* varScriptString; + scr_string_t *varScriptString; + + AssetLoader(asset_type_t assetType, Zone *zone, IZoneInputStream *stream); - AssetLoader(asset_type_t assetType, Zone* zone, IZoneInputStream* stream); - - void AddDependency(XAssetInfoGeneric* assetInfo); + void AddDependency(XAssetInfoGeneric *assetInfo); - scr_string_t UseScriptString(scr_string_t scrString); - void LoadScriptStringArray(bool atStreamStart, size_t count); - void MarkScriptStringArrayAsUsed(const scr_string_t* scrStringArray, size_t count); + scr_string_t UseScriptString(scr_string_t scrString); + void LoadScriptStringArray(bool atStreamStart, size_t count); + void MarkScriptStringArrayAsUsed(const scr_string_t *scrStringArray, size_t count); - XAssetInfoGeneric* LinkAsset(std::string name, void* asset); + XAssetInfoGeneric *LinkAsset(std::string name, void *asset); - XAssetInfoGeneric* GetAssetInfo(std::string name) const; + XAssetInfoGeneric *GetAssetInfo(std::string name) const; }; diff --git a/src/ZoneLoading/Loading/AssetLoadingActions.cpp b/src/ZoneLoading/Loading/AssetLoadingActions.cpp index 2908a982f..3f76e8c5e 100644 --- a/src/ZoneLoading/Loading/AssetLoadingActions.cpp +++ b/src/ZoneLoading/Loading/AssetLoadingActions.cpp @@ -1,6 +1,3 @@ #include "AssetLoadingActions.h" -AssetLoadingActions::AssetLoadingActions(Zone* zone) -{ - m_zone = zone; -} +AssetLoadingActions::AssetLoadingActions(Zone *zone) { m_zone = zone; } diff --git a/src/ZoneLoading/Loading/AssetLoadingActions.h b/src/ZoneLoading/Loading/AssetLoadingActions.h index 5f62066d3..0715c5a3b 100644 --- a/src/ZoneLoading/Loading/AssetLoadingActions.h +++ b/src/ZoneLoading/Loading/AssetLoadingActions.h @@ -2,11 +2,10 @@ #include "Zone/Zone.h" -class AssetLoadingActions -{ +class AssetLoadingActions { protected: - Zone* m_zone; + Zone *m_zone; public: - explicit AssetLoadingActions(Zone* zone); + explicit AssetLoadingActions(Zone *zone); }; \ No newline at end of file diff --git a/src/ZoneLoading/Loading/ContentLoaderBase.cpp b/src/ZoneLoading/Loading/ContentLoaderBase.cpp index b3c4e83b7..e4395a4e1 100644 --- a/src/ZoneLoading/Loading/ContentLoaderBase.cpp +++ b/src/ZoneLoading/Loading/ContentLoaderBase.cpp @@ -1,54 +1,37 @@ #include "ContentLoaderBase.h" #include <cassert> -const void* ContentLoaderBase::PTR_FOLLOWING = reinterpret_cast<void*>(-1); -const void* ContentLoaderBase::PTR_INSERT = reinterpret_cast<void*>(-2); - -ContentLoaderBase::ContentLoaderBase() - : varXString(nullptr), - m_zone(nullptr), - m_stream(nullptr) -{ -} +const void *ContentLoaderBase::PTR_FOLLOWING = reinterpret_cast<void *>(-1); +const void *ContentLoaderBase::PTR_INSERT = reinterpret_cast<void *>(-2); -ContentLoaderBase::ContentLoaderBase(Zone* zone, IZoneInputStream* stream) - : varXString(nullptr), - m_zone(zone), - m_stream(stream) -{ -} +ContentLoaderBase::ContentLoaderBase() : varXString(nullptr), m_zone(nullptr), m_stream(nullptr) {} + +ContentLoaderBase::ContentLoaderBase(Zone *zone, IZoneInputStream *stream) : varXString(nullptr), m_zone(zone), m_stream(stream) {} -void ContentLoaderBase::LoadXString(const bool atStreamStart) const -{ - assert(varXString != nullptr); - - if (atStreamStart) - m_stream->Load<const char*>(varXString); - - if (*varXString != nullptr) - { - if (*varXString == PTR_FOLLOWING) - { - *varXString = m_stream->Alloc<const char>(alignof(const char)); - m_stream->LoadNullTerminated(const_cast<char*>(*varXString)); - } - else - { - *varXString = m_stream->ConvertOffsetToPointer<const char>(*varXString); - } +void ContentLoaderBase::LoadXString(const bool atStreamStart) const { + assert(varXString != nullptr); + + if (atStreamStart) + m_stream->Load<const char *>(varXString); + + if (*varXString != nullptr) { + if (*varXString == PTR_FOLLOWING) { + *varXString = m_stream->Alloc<const char>(alignof(const char)); + m_stream->LoadNullTerminated(const_cast<char *>(*varXString)); + } else { + *varXString = m_stream->ConvertOffsetToPointer<const char>(*varXString); } + } } -void ContentLoaderBase::LoadXStringArray(const bool atStreamStart, const size_t count) -{ - assert(varXString != nullptr); +void ContentLoaderBase::LoadXStringArray(const bool atStreamStart, const size_t count) { + assert(varXString != nullptr); - if (atStreamStart) - m_stream->Load<const char*>(varXString, count); + if (atStreamStart) + m_stream->Load<const char *>(varXString, count); - for (size_t index = 0; index < count; index++) - { - LoadXString(false); - varXString++; - } + for (size_t index = 0; index < count; index++) { + LoadXString(false); + varXString++; + } } diff --git a/src/ZoneLoading/Loading/ContentLoaderBase.h b/src/ZoneLoading/Loading/ContentLoaderBase.h index 122b706b1..9b9c43daa 100644 --- a/src/ZoneLoading/Loading/ContentLoaderBase.h +++ b/src/ZoneLoading/Loading/ContentLoaderBase.h @@ -1,25 +1,24 @@ #pragma once -#include "Zone/Zone.h" #include "Zone/Stream/IZoneInputStream.h" +#include "Zone/Zone.h" -class ContentLoaderBase -{ +class ContentLoaderBase { protected: - static const void* PTR_FOLLOWING; - static const void* PTR_INSERT; + static const void *PTR_FOLLOWING; + static const void *PTR_INSERT; - const char** varXString; + const char **varXString; - Zone* m_zone; - IZoneInputStream* m_stream; + Zone *m_zone; + IZoneInputStream *m_stream; - ContentLoaderBase(); - ContentLoaderBase(Zone* zone, IZoneInputStream* stream); + ContentLoaderBase(); + ContentLoaderBase(Zone *zone, IZoneInputStream *stream); - void LoadXString(bool atStreamStart) const; - void LoadXStringArray(bool atStreamStart, size_t count); + void LoadXString(bool atStreamStart) const; + void LoadXStringArray(bool atStreamStart, size_t count); public: - virtual ~ContentLoaderBase() = default; + virtual ~ContentLoaderBase() = default; }; diff --git a/src/ZoneLoading/Loading/Exception/BlockOverflowException.cpp b/src/ZoneLoading/Loading/Exception/BlockOverflowException.cpp index 779e77e59..418d94097 100644 --- a/src/ZoneLoading/Loading/Exception/BlockOverflowException.cpp +++ b/src/ZoneLoading/Loading/Exception/BlockOverflowException.cpp @@ -1,16 +1,7 @@ #include "BlockOverflowException.h" -BlockOverflowException::BlockOverflowException(XBlock* block) -{ - m_block = block; -} +BlockOverflowException::BlockOverflowException(XBlock *block) { m_block = block; } -std::string BlockOverflowException::DetailedMessage() -{ - return "XBlock " + m_block->m_name + " overflowed while trying to load zone."; -} +std::string BlockOverflowException::DetailedMessage() { return "XBlock " + m_block->m_name + " overflowed while trying to load zone."; } -char const* BlockOverflowException::what() const noexcept -{ - return "Invalid Zone. XBlock overflowed."; -} \ No newline at end of file +char const *BlockOverflowException::what() const noexcept { return "Invalid Zone. XBlock overflowed."; } \ No newline at end of file diff --git a/src/ZoneLoading/Loading/Exception/BlockOverflowException.h b/src/ZoneLoading/Loading/Exception/BlockOverflowException.h index 294d36ced..3a2da5365 100644 --- a/src/ZoneLoading/Loading/Exception/BlockOverflowException.h +++ b/src/ZoneLoading/Loading/Exception/BlockOverflowException.h @@ -2,13 +2,12 @@ #include "LoadingException.h" #include "Zone/XBlock.h" -class BlockOverflowException final : public LoadingException -{ - XBlock* m_block; +class BlockOverflowException final : public LoadingException { + XBlock *m_block; public: - explicit BlockOverflowException(XBlock* block); + explicit BlockOverflowException(XBlock *block); - std::string DetailedMessage() override; - char const* what() const noexcept override; + std::string DetailedMessage() override; + char const *what() const noexcept override; }; diff --git a/src/ZoneLoading/Loading/Exception/InvalidChunkSizeException.cpp b/src/ZoneLoading/Loading/Exception/InvalidChunkSizeException.cpp index ea6959b46..c4bc3b13d 100644 --- a/src/ZoneLoading/Loading/Exception/InvalidChunkSizeException.cpp +++ b/src/ZoneLoading/Loading/Exception/InvalidChunkSizeException.cpp @@ -1,30 +1,21 @@ #include "InvalidChunkSizeException.h" -InvalidChunkSizeException::InvalidChunkSizeException(const size_t size) -{ - m_size = size; - m_max = 0; +InvalidChunkSizeException::InvalidChunkSizeException(const size_t size) { + m_size = size; + m_max = 0; } -InvalidChunkSizeException::InvalidChunkSizeException(const size_t size, const size_t max) -{ - m_size = size; - m_max = max; +InvalidChunkSizeException::InvalidChunkSizeException(const size_t size, const size_t max) { + m_size = size; + m_max = max; } -std::string InvalidChunkSizeException::DetailedMessage() -{ - if(m_max > 0) - { - return "Zone chunk size has a chunk size of " + std::to_string(m_size) + " which is larger than the maximum of " + std::to_string(m_max); - } - else - { - return "Zone chunk size has an invalid chunk size of " + std::to_string(m_size); - } +std::string InvalidChunkSizeException::DetailedMessage() { + if (m_max > 0) { + return "Zone chunk size has a chunk size of " + std::to_string(m_size) + " which is larger than the maximum of " + std::to_string(m_max); + } else { + return "Zone chunk size has an invalid chunk size of " + std::to_string(m_size); + } } -char const* InvalidChunkSizeException::what() const noexcept -{ - return "Zone has invalid chunk size"; -} \ No newline at end of file +char const *InvalidChunkSizeException::what() const noexcept { return "Zone has invalid chunk size"; } \ No newline at end of file diff --git a/src/ZoneLoading/Loading/Exception/InvalidChunkSizeException.h b/src/ZoneLoading/Loading/Exception/InvalidChunkSizeException.h index 76d1ad29c..02fc4d9a5 100644 --- a/src/ZoneLoading/Loading/Exception/InvalidChunkSizeException.h +++ b/src/ZoneLoading/Loading/Exception/InvalidChunkSizeException.h @@ -1,15 +1,14 @@ #pragma once #include "LoadingException.h" -class InvalidChunkSizeException final : public LoadingException -{ - size_t m_size; - size_t m_max; +class InvalidChunkSizeException final : public LoadingException { + size_t m_size; + size_t m_max; public: - explicit InvalidChunkSizeException(size_t size); - InvalidChunkSizeException(size_t size, size_t max); + explicit InvalidChunkSizeException(size_t size); + InvalidChunkSizeException(size_t size, size_t max); - std::string DetailedMessage() override; - char const* what() const noexcept override; + std::string DetailedMessage() override; + char const *what() const noexcept override; }; diff --git a/src/ZoneLoading/Loading/Exception/InvalidCompressionException.cpp b/src/ZoneLoading/Loading/Exception/InvalidCompressionException.cpp index de1ab4db9..13105b5c0 100644 --- a/src/ZoneLoading/Loading/Exception/InvalidCompressionException.cpp +++ b/src/ZoneLoading/Loading/Exception/InvalidCompressionException.cpp @@ -1,11 +1,5 @@ #include "InvalidCompressionException.h" -std::string InvalidCompressionException::DetailedMessage() -{ - return "Zone has invalid or unsupported compression. Inflate failed"; -} +std::string InvalidCompressionException::DetailedMessage() { return "Zone has invalid or unsupported compression. Inflate failed"; } -char const* InvalidCompressionException::what() const noexcept -{ - return "Zone has invalid or unsupported compression. Inflate failed"; -} +char const *InvalidCompressionException::what() const noexcept { return "Zone has invalid or unsupported compression. Inflate failed"; } diff --git a/src/ZoneLoading/Loading/Exception/InvalidCompressionException.h b/src/ZoneLoading/Loading/Exception/InvalidCompressionException.h index 364d52bd3..a6cf93c6e 100644 --- a/src/ZoneLoading/Loading/Exception/InvalidCompressionException.h +++ b/src/ZoneLoading/Loading/Exception/InvalidCompressionException.h @@ -1,9 +1,8 @@ #pragma once #include "LoadingException.h" -class InvalidCompressionException final : public LoadingException -{ +class InvalidCompressionException final : public LoadingException { public: - std::string DetailedMessage() override; - char const* what() const noexcept override; + std::string DetailedMessage() override; + char const *what() const noexcept override; }; diff --git a/src/ZoneLoading/Loading/Exception/InvalidFileNameException.cpp b/src/ZoneLoading/Loading/Exception/InvalidFileNameException.cpp index ac82d25a6..421dd1735 100644 --- a/src/ZoneLoading/Loading/Exception/InvalidFileNameException.cpp +++ b/src/ZoneLoading/Loading/Exception/InvalidFileNameException.cpp @@ -1,17 +1,12 @@ #include "InvalidFileNameException.h" -InvalidFileNameException::InvalidFileNameException(std::string& actualFileName, std::string& expectedFileName) -{ - m_actual_file_name = actualFileName; - m_expected_file_name = expectedFileName; +InvalidFileNameException::InvalidFileNameException(std::string &actualFileName, std::string &expectedFileName) { + m_actual_file_name = actualFileName; + m_expected_file_name = expectedFileName; } -std::string InvalidFileNameException::DetailedMessage() -{ - return "Name verification failed: The fastfile was created as '" + m_expected_file_name + "' but loaded as '" + m_actual_file_name + "'"; +std::string InvalidFileNameException::DetailedMessage() { + return "Name verification failed: The fastfile was created as '" + m_expected_file_name + "' but loaded as '" + m_actual_file_name + "'"; } -char const* InvalidFileNameException::what() const noexcept -{ - return "The filename when created and when loaded does not match"; -} \ No newline at end of file +char const *InvalidFileNameException::what() const noexcept { return "The filename when created and when loaded does not match"; } \ No newline at end of file diff --git a/src/ZoneLoading/Loading/Exception/InvalidFileNameException.h b/src/ZoneLoading/Loading/Exception/InvalidFileNameException.h index 89c51f244..2555db863 100644 --- a/src/ZoneLoading/Loading/Exception/InvalidFileNameException.h +++ b/src/ZoneLoading/Loading/Exception/InvalidFileNameException.h @@ -1,14 +1,13 @@ #pragma once #include "LoadingException.h" -class InvalidFileNameException final : public LoadingException -{ - std::string m_actual_file_name; - std::string m_expected_file_name; +class InvalidFileNameException final : public LoadingException { + std::string m_actual_file_name; + std::string m_expected_file_name; public: - InvalidFileNameException(std::string& actualFileName, std::string& expectedFileName); + InvalidFileNameException(std::string &actualFileName, std::string &expectedFileName); - std::string DetailedMessage() override; - char const* what() const noexcept override; + std::string DetailedMessage() override; + char const *what() const noexcept override; }; diff --git a/src/ZoneLoading/Loading/Exception/InvalidHashException.cpp b/src/ZoneLoading/Loading/Exception/InvalidHashException.cpp index ffab2c8c3..9aa4f0f4f 100644 --- a/src/ZoneLoading/Loading/Exception/InvalidHashException.cpp +++ b/src/ZoneLoading/Loading/Exception/InvalidHashException.cpp @@ -1,11 +1,5 @@ #include "InvalidHashException.h" -std::string InvalidHashException::DetailedMessage() -{ - return "Loaded fastfile has an invalid hash."; -} +std::string InvalidHashException::DetailedMessage() { return "Loaded fastfile has an invalid hash."; } -char const* InvalidHashException::what() const noexcept -{ - return "Loaded fastfile has an invalid hash."; -} \ No newline at end of file +char const *InvalidHashException::what() const noexcept { return "Loaded fastfile has an invalid hash."; } \ No newline at end of file diff --git a/src/ZoneLoading/Loading/Exception/InvalidHashException.h b/src/ZoneLoading/Loading/Exception/InvalidHashException.h index 17d0ed4b5..88b4e7c99 100644 --- a/src/ZoneLoading/Loading/Exception/InvalidHashException.h +++ b/src/ZoneLoading/Loading/Exception/InvalidHashException.h @@ -1,9 +1,8 @@ #pragma once #include "LoadingException.h" -class InvalidHashException final : public LoadingException -{ +class InvalidHashException final : public LoadingException { public: - std::string DetailedMessage() override; - char const* what() const noexcept override; + std::string DetailedMessage() override; + char const *what() const noexcept override; }; diff --git a/src/ZoneLoading/Loading/Exception/InvalidMagicException.cpp b/src/ZoneLoading/Loading/Exception/InvalidMagicException.cpp index 22395ed03..846bf9a01 100644 --- a/src/ZoneLoading/Loading/Exception/InvalidMagicException.cpp +++ b/src/ZoneLoading/Loading/Exception/InvalidMagicException.cpp @@ -1,16 +1,7 @@ #include "InvalidMagicException.h" - -InvalidMagicException::InvalidMagicException(const char* expectedMagic) -{ - m_expected_magic = expectedMagic; -} -std::string InvalidMagicException::DetailedMessage() -{ - return "Expected magic '" + std::string(m_expected_magic) + "'"; -} +InvalidMagicException::InvalidMagicException(const char *expectedMagic) { m_expected_magic = expectedMagic; } -char const* InvalidMagicException::what() const noexcept -{ - return "Encountered invalid magic when loading."; -} \ No newline at end of file +std::string InvalidMagicException::DetailedMessage() { return "Expected magic '" + std::string(m_expected_magic) + "'"; } + +char const *InvalidMagicException::what() const noexcept { return "Encountered invalid magic when loading."; } \ No newline at end of file diff --git a/src/ZoneLoading/Loading/Exception/InvalidMagicException.h b/src/ZoneLoading/Loading/Exception/InvalidMagicException.h index ab2d79106..414d53a21 100644 --- a/src/ZoneLoading/Loading/Exception/InvalidMagicException.h +++ b/src/ZoneLoading/Loading/Exception/InvalidMagicException.h @@ -1,13 +1,12 @@ #pragma once #include "LoadingException.h" -class InvalidMagicException final : public LoadingException -{ - const char* m_expected_magic; +class InvalidMagicException final : public LoadingException { + const char *m_expected_magic; public: - explicit InvalidMagicException(const char* expectedMagic); + explicit InvalidMagicException(const char *expectedMagic); - std::string DetailedMessage() override; - char const* what() const noexcept override; + std::string DetailedMessage() override; + char const *what() const noexcept override; }; diff --git a/src/ZoneLoading/Loading/Exception/InvalidOffsetBlockException.cpp b/src/ZoneLoading/Loading/Exception/InvalidOffsetBlockException.cpp index fbe4114d5..426cd264a 100644 --- a/src/ZoneLoading/Loading/Exception/InvalidOffsetBlockException.cpp +++ b/src/ZoneLoading/Loading/Exception/InvalidOffsetBlockException.cpp @@ -1,16 +1,7 @@ #include "InvalidOffsetBlockException.h" -InvalidOffsetBlockException::InvalidOffsetBlockException(const block_t referencedBlock) -{ - m_referenced_block = referencedBlock; -} +InvalidOffsetBlockException::InvalidOffsetBlockException(const block_t referencedBlock) { m_referenced_block = referencedBlock; } -std::string InvalidOffsetBlockException::DetailedMessage() -{ - return "Zone tried to reference invalid block " + std::to_string(m_referenced_block); -} +std::string InvalidOffsetBlockException::DetailedMessage() { return "Zone tried to reference invalid block " + std::to_string(m_referenced_block); } -char const* InvalidOffsetBlockException::what() const noexcept -{ - return "Zone referenced invalid block"; -} \ No newline at end of file +char const *InvalidOffsetBlockException::what() const noexcept { return "Zone referenced invalid block"; } \ No newline at end of file diff --git a/src/ZoneLoading/Loading/Exception/InvalidOffsetBlockException.h b/src/ZoneLoading/Loading/Exception/InvalidOffsetBlockException.h index 0a5718943..4d62a0efa 100644 --- a/src/ZoneLoading/Loading/Exception/InvalidOffsetBlockException.h +++ b/src/ZoneLoading/Loading/Exception/InvalidOffsetBlockException.h @@ -2,13 +2,12 @@ #include "LoadingException.h" #include "Zone/ZoneTypes.h" -class InvalidOffsetBlockException final : public LoadingException -{ - block_t m_referenced_block; +class InvalidOffsetBlockException final : public LoadingException { + block_t m_referenced_block; public: - explicit InvalidOffsetBlockException(block_t referencedBlock); + explicit InvalidOffsetBlockException(block_t referencedBlock); - std::string DetailedMessage() override; - char const* what() const noexcept override; + std::string DetailedMessage() override; + char const *what() const noexcept override; }; diff --git a/src/ZoneLoading/Loading/Exception/InvalidOffsetBlockOffsetException.cpp b/src/ZoneLoading/Loading/Exception/InvalidOffsetBlockOffsetException.cpp index 58ab1dbc6..89e59eff9 100644 --- a/src/ZoneLoading/Loading/Exception/InvalidOffsetBlockOffsetException.cpp +++ b/src/ZoneLoading/Loading/Exception/InvalidOffsetBlockOffsetException.cpp @@ -1,18 +1,13 @@ #include "InvalidOffsetBlockOffsetException.h" -InvalidOffsetBlockOffsetException::InvalidOffsetBlockOffsetException(XBlock* block, const size_t referencedOffset) -{ - m_referenced_block = block; - m_referenced_offset = referencedOffset; +InvalidOffsetBlockOffsetException::InvalidOffsetBlockOffsetException(XBlock *block, const size_t referencedOffset) { + m_referenced_block = block; + m_referenced_offset = referencedOffset; } -std::string InvalidOffsetBlockOffsetException::DetailedMessage() -{ - return "Zone referenced offset " + std::to_string(m_referenced_offset) + " of block " + m_referenced_block->m_name - + " which is larger than its size " + std::to_string(m_referenced_block->m_buffer_size); +std::string InvalidOffsetBlockOffsetException::DetailedMessage() { + return "Zone referenced offset " + std::to_string(m_referenced_offset) + " of block " + m_referenced_block->m_name + " which is larger than its size " + + std::to_string(m_referenced_block->m_buffer_size); } -char const* InvalidOffsetBlockOffsetException::what() const noexcept -{ - return "Zone referenced offset of block that is out of bounds"; -} \ No newline at end of file +char const *InvalidOffsetBlockOffsetException::what() const noexcept { return "Zone referenced offset of block that is out of bounds"; } \ No newline at end of file diff --git a/src/ZoneLoading/Loading/Exception/InvalidOffsetBlockOffsetException.h b/src/ZoneLoading/Loading/Exception/InvalidOffsetBlockOffsetException.h index b93eeaa28..8a6ce7524 100644 --- a/src/ZoneLoading/Loading/Exception/InvalidOffsetBlockOffsetException.h +++ b/src/ZoneLoading/Loading/Exception/InvalidOffsetBlockOffsetException.h @@ -2,14 +2,13 @@ #include "LoadingException.h" #include "Zone/XBlock.h" -class InvalidOffsetBlockOffsetException final : public LoadingException -{ - XBlock* m_referenced_block; - size_t m_referenced_offset; +class InvalidOffsetBlockOffsetException final : public LoadingException { + XBlock *m_referenced_block; + size_t m_referenced_offset; public: - InvalidOffsetBlockOffsetException(XBlock* block, size_t referencedOffset); + InvalidOffsetBlockOffsetException(XBlock *block, size_t referencedOffset); - std::string DetailedMessage() override; - char const* what() const noexcept override; + std::string DetailedMessage() override; + char const *what() const noexcept override; }; diff --git a/src/ZoneLoading/Loading/Exception/InvalidSignatureException.cpp b/src/ZoneLoading/Loading/Exception/InvalidSignatureException.cpp index 429d4ecb5..e3b236130 100644 --- a/src/ZoneLoading/Loading/Exception/InvalidSignatureException.cpp +++ b/src/ZoneLoading/Loading/Exception/InvalidSignatureException.cpp @@ -1,11 +1,5 @@ #include "InvalidSignatureException.h" -std::string InvalidSignatureException::DetailedMessage() -{ - return "Loaded fastfile has an invalid signature."; -} +std::string InvalidSignatureException::DetailedMessage() { return "Loaded fastfile has an invalid signature."; } -char const* InvalidSignatureException::what() const noexcept -{ - return "Loaded fastfile has an invalid signature."; -} \ No newline at end of file +char const *InvalidSignatureException::what() const noexcept { return "Loaded fastfile has an invalid signature."; } \ No newline at end of file diff --git a/src/ZoneLoading/Loading/Exception/InvalidSignatureException.h b/src/ZoneLoading/Loading/Exception/InvalidSignatureException.h index 7940dcbae..6250f6ab2 100644 --- a/src/ZoneLoading/Loading/Exception/InvalidSignatureException.h +++ b/src/ZoneLoading/Loading/Exception/InvalidSignatureException.h @@ -1,9 +1,8 @@ #pragma once #include "LoadingException.h" -class InvalidSignatureException final : public LoadingException -{ +class InvalidSignatureException final : public LoadingException { public: - std::string DetailedMessage() override; - char const* what() const noexcept override; + std::string DetailedMessage() override; + char const *what() const noexcept override; }; diff --git a/src/ZoneLoading/Loading/Exception/InvalidVersionException.cpp b/src/ZoneLoading/Loading/Exception/InvalidVersionException.cpp index 6aabdc597..5412a94b7 100644 --- a/src/ZoneLoading/Loading/Exception/InvalidVersionException.cpp +++ b/src/ZoneLoading/Loading/Exception/InvalidVersionException.cpp @@ -1,17 +1,12 @@ #include "InvalidVersionException.h" -InvalidVersionException::InvalidVersionException(const unsigned int expectedVersion, const unsigned int actualVersion) -{ - m_expected_version = expectedVersion; - m_actual_version = actualVersion; +InvalidVersionException::InvalidVersionException(const unsigned int expectedVersion, const unsigned int actualVersion) { + m_expected_version = expectedVersion; + m_actual_version = actualVersion; } -std::string InvalidVersionException::DetailedMessage() -{ - return "Expected version " + std::to_string(m_expected_version) + " but encountered version " + std::to_string(m_actual_version); +std::string InvalidVersionException::DetailedMessage() { + return "Expected version " + std::to_string(m_expected_version) + " but encountered version " + std::to_string(m_actual_version); } -char const* InvalidVersionException::what() const noexcept -{ - return "Encountered invalid version when loading."; -} \ No newline at end of file +char const *InvalidVersionException::what() const noexcept { return "Encountered invalid version when loading."; } \ No newline at end of file diff --git a/src/ZoneLoading/Loading/Exception/InvalidVersionException.h b/src/ZoneLoading/Loading/Exception/InvalidVersionException.h index 35664144e..fb1a8af6a 100644 --- a/src/ZoneLoading/Loading/Exception/InvalidVersionException.h +++ b/src/ZoneLoading/Loading/Exception/InvalidVersionException.h @@ -1,14 +1,13 @@ #pragma once #include "LoadingException.h" -class InvalidVersionException final : public LoadingException -{ - unsigned int m_expected_version; - unsigned int m_actual_version; +class InvalidVersionException final : public LoadingException { + unsigned int m_expected_version; + unsigned int m_actual_version; public: - InvalidVersionException(unsigned int expectedVersion, unsigned int actualVersion); + InvalidVersionException(unsigned int expectedVersion, unsigned int actualVersion); - std::string DetailedMessage() override; - char const* what() const noexcept override; + std::string DetailedMessage() override; + char const *what() const noexcept override; }; diff --git a/src/ZoneLoading/Loading/Exception/InvalidXBlockSizeException.cpp b/src/ZoneLoading/Loading/Exception/InvalidXBlockSizeException.cpp index 4ca598b86..61525bdcd 100644 --- a/src/ZoneLoading/Loading/Exception/InvalidXBlockSizeException.cpp +++ b/src/ZoneLoading/Loading/Exception/InvalidXBlockSizeException.cpp @@ -1,17 +1,12 @@ #include "InvalidXBlockSizeException.h" -InvalidXBlockSizeException::InvalidXBlockSizeException(const uint64_t size, const uint64_t max) -{ - m_size = size; - m_max = max; +InvalidXBlockSizeException::InvalidXBlockSizeException(const uint64_t size, const uint64_t max) { + m_size = size; + m_max = max; } -std::string InvalidXBlockSizeException::DetailedMessage() -{ - return "Zone uses more XBlock memory than allowed: " + std::to_string(m_size) + " (max is " + std::to_string(m_max) + ")"; +std::string InvalidXBlockSizeException::DetailedMessage() { + return "Zone uses more XBlock memory than allowed: " + std::to_string(m_size) + " (max is " + std::to_string(m_max) + ")"; } -char const* InvalidXBlockSizeException::what() const noexcept -{ - return "Zone has invalid block size"; -} \ No newline at end of file +char const *InvalidXBlockSizeException::what() const noexcept { return "Zone has invalid block size"; } \ No newline at end of file diff --git a/src/ZoneLoading/Loading/Exception/InvalidXBlockSizeException.h b/src/ZoneLoading/Loading/Exception/InvalidXBlockSizeException.h index 41ca32de4..44c89c679 100644 --- a/src/ZoneLoading/Loading/Exception/InvalidXBlockSizeException.h +++ b/src/ZoneLoading/Loading/Exception/InvalidXBlockSizeException.h @@ -1,15 +1,14 @@ #pragma once -#include <cstdint> #include "LoadingException.h" +#include <cstdint> -class InvalidXBlockSizeException final : public LoadingException -{ - uint64_t m_size; - uint64_t m_max; +class InvalidXBlockSizeException final : public LoadingException { + uint64_t m_size; + uint64_t m_max; public: - InvalidXBlockSizeException(uint64_t size, uint64_t max); + InvalidXBlockSizeException(uint64_t size, uint64_t max); - std::string DetailedMessage() override; - char const* what() const noexcept override; + std::string DetailedMessage() override; + char const *what() const noexcept override; }; diff --git a/src/ZoneLoading/Loading/Exception/LoadingException.h b/src/ZoneLoading/Loading/Exception/LoadingException.h index f1af2ddb2..bbd3dd41b 100644 --- a/src/ZoneLoading/Loading/Exception/LoadingException.h +++ b/src/ZoneLoading/Loading/Exception/LoadingException.h @@ -2,8 +2,7 @@ #include <exception> #include <string> -class LoadingException : public std::exception -{ +class LoadingException : public std::exception { public: - virtual std::string DetailedMessage() = 0; + virtual std::string DetailedMessage() = 0; }; diff --git a/src/ZoneLoading/Loading/Exception/OutOfBlockBoundsException.cpp b/src/ZoneLoading/Loading/Exception/OutOfBlockBoundsException.cpp index 3b020eb1b..76a6d6555 100644 --- a/src/ZoneLoading/Loading/Exception/OutOfBlockBoundsException.cpp +++ b/src/ZoneLoading/Loading/Exception/OutOfBlockBoundsException.cpp @@ -1,16 +1,7 @@ #include "OutOfBlockBoundsException.h" -OutOfBlockBoundsException::OutOfBlockBoundsException(XBlock* block) -{ - m_block = block; -} +OutOfBlockBoundsException::OutOfBlockBoundsException(XBlock *block) { m_block = block; } -std::string OutOfBlockBoundsException::DetailedMessage() -{ - return "Tried to load to location out of bounds from current XBlock " + m_block->m_name + "."; -} +std::string OutOfBlockBoundsException::DetailedMessage() { return "Tried to load to location out of bounds from current XBlock " + m_block->m_name + "."; } -char const* OutOfBlockBoundsException::what() const noexcept -{ - return "Invalid Zone. Out of XBlock bounds."; -} \ No newline at end of file +char const *OutOfBlockBoundsException::what() const noexcept { return "Invalid Zone. Out of XBlock bounds."; } \ No newline at end of file diff --git a/src/ZoneLoading/Loading/Exception/OutOfBlockBoundsException.h b/src/ZoneLoading/Loading/Exception/OutOfBlockBoundsException.h index ab2e4bb9b..5e443bb38 100644 --- a/src/ZoneLoading/Loading/Exception/OutOfBlockBoundsException.h +++ b/src/ZoneLoading/Loading/Exception/OutOfBlockBoundsException.h @@ -2,13 +2,12 @@ #include "LoadingException.h" #include "Zone/XBlock.h" -class OutOfBlockBoundsException final : public LoadingException -{ - XBlock* m_block; +class OutOfBlockBoundsException final : public LoadingException { + XBlock *m_block; public: - explicit OutOfBlockBoundsException(XBlock* block); + explicit OutOfBlockBoundsException(XBlock *block); - std::string DetailedMessage() override; - char const* what() const noexcept override; + std::string DetailedMessage() override; + char const *what() const noexcept override; }; diff --git a/src/ZoneLoading/Loading/Exception/TooManyAuthedGroupsException.cpp b/src/ZoneLoading/Loading/Exception/TooManyAuthedGroupsException.cpp index 3f580b362..00d572f4e 100644 --- a/src/ZoneLoading/Loading/Exception/TooManyAuthedGroupsException.cpp +++ b/src/ZoneLoading/Loading/Exception/TooManyAuthedGroupsException.cpp @@ -1,11 +1,5 @@ #include "TooManyAuthedGroupsException.h" -std::string TooManyAuthedGroupsException::DetailedMessage() -{ - return "Loaded fastfile has too many authed groups."; -} +std::string TooManyAuthedGroupsException::DetailedMessage() { return "Loaded fastfile has too many authed groups."; } -char const* TooManyAuthedGroupsException::what() const noexcept -{ - return "Loaded fastfile has too many authed groups."; -} \ No newline at end of file +char const *TooManyAuthedGroupsException::what() const noexcept { return "Loaded fastfile has too many authed groups."; } \ No newline at end of file diff --git a/src/ZoneLoading/Loading/Exception/TooManyAuthedGroupsException.h b/src/ZoneLoading/Loading/Exception/TooManyAuthedGroupsException.h index 389e2b009..139bb57c6 100644 --- a/src/ZoneLoading/Loading/Exception/TooManyAuthedGroupsException.h +++ b/src/ZoneLoading/Loading/Exception/TooManyAuthedGroupsException.h @@ -1,9 +1,8 @@ #pragma once #include "LoadingException.h" -class TooManyAuthedGroupsException final : public LoadingException -{ +class TooManyAuthedGroupsException final : public LoadingException { public: - std::string DetailedMessage() override; - char const* what() const noexcept override; + std::string DetailedMessage() override; + char const *what() const noexcept override; }; diff --git a/src/ZoneLoading/Loading/Exception/UnexpectedEndOfFileException.cpp b/src/ZoneLoading/Loading/Exception/UnexpectedEndOfFileException.cpp index c860eacf0..ead8889ee 100644 --- a/src/ZoneLoading/Loading/Exception/UnexpectedEndOfFileException.cpp +++ b/src/ZoneLoading/Loading/Exception/UnexpectedEndOfFileException.cpp @@ -1,13 +1,7 @@ #include "UnexpectedEndOfFileException.h" - + UnexpectedEndOfFileException::UnexpectedEndOfFileException() = default; -std::string UnexpectedEndOfFileException::DetailedMessage() -{ - return "Unexpected end of file"; -} +std::string UnexpectedEndOfFileException::DetailedMessage() { return "Unexpected end of file"; } -char const* UnexpectedEndOfFileException::what() const noexcept -{ - return "Unexpected end of file"; -} \ No newline at end of file +char const *UnexpectedEndOfFileException::what() const noexcept { return "Unexpected end of file"; } \ No newline at end of file diff --git a/src/ZoneLoading/Loading/Exception/UnexpectedEndOfFileException.h b/src/ZoneLoading/Loading/Exception/UnexpectedEndOfFileException.h index d0f1d7bb6..871b8909e 100644 --- a/src/ZoneLoading/Loading/Exception/UnexpectedEndOfFileException.h +++ b/src/ZoneLoading/Loading/Exception/UnexpectedEndOfFileException.h @@ -1,11 +1,10 @@ #pragma once #include "LoadingException.h" -class UnexpectedEndOfFileException final : public LoadingException -{ +class UnexpectedEndOfFileException final : public LoadingException { public: - UnexpectedEndOfFileException(); + UnexpectedEndOfFileException(); - std::string DetailedMessage() override; - char const* what() const noexcept override; + std::string DetailedMessage() override; + char const *what() const noexcept override; }; diff --git a/src/ZoneLoading/Loading/Exception/UnsupportedAssetTypeException.cpp b/src/ZoneLoading/Loading/Exception/UnsupportedAssetTypeException.cpp index 20f68d156..a2ef104da 100644 --- a/src/ZoneLoading/Loading/Exception/UnsupportedAssetTypeException.cpp +++ b/src/ZoneLoading/Loading/Exception/UnsupportedAssetTypeException.cpp @@ -1,16 +1,9 @@ #include "UnsupportedAssetTypeException.h" -UnsupportedAssetTypeException::UnsupportedAssetTypeException(const int assetType) -{ - m_asset_type = assetType; -} +UnsupportedAssetTypeException::UnsupportedAssetTypeException(const int assetType) { m_asset_type = assetType; } -std::string UnsupportedAssetTypeException::DetailedMessage() -{ - return "Zone has an unsupported asset type " + std::to_string(m_asset_type) + " and therefore cannot be loaded."; +std::string UnsupportedAssetTypeException::DetailedMessage() { + return "Zone has an unsupported asset type " + std::to_string(m_asset_type) + " and therefore cannot be loaded."; } -char const* UnsupportedAssetTypeException::what() const noexcept -{ - return "Zone has unsupported asset type."; -} \ No newline at end of file +char const *UnsupportedAssetTypeException::what() const noexcept { return "Zone has unsupported asset type."; } \ No newline at end of file diff --git a/src/ZoneLoading/Loading/Exception/UnsupportedAssetTypeException.h b/src/ZoneLoading/Loading/Exception/UnsupportedAssetTypeException.h index 4f262c5bc..72a8e444b 100644 --- a/src/ZoneLoading/Loading/Exception/UnsupportedAssetTypeException.h +++ b/src/ZoneLoading/Loading/Exception/UnsupportedAssetTypeException.h @@ -1,13 +1,12 @@ #pragma once #include "LoadingException.h" -class UnsupportedAssetTypeException final : public LoadingException -{ - int m_asset_type; +class UnsupportedAssetTypeException final : public LoadingException { + int m_asset_type; public: - explicit UnsupportedAssetTypeException(int assetType); + explicit UnsupportedAssetTypeException(int assetType); - std::string DetailedMessage() override; - char const* what() const noexcept override; + std::string DetailedMessage() override; + char const *what() const noexcept override; }; diff --git a/src/ZoneLoading/Loading/IContentLoadingEntryPoint.h b/src/ZoneLoading/Loading/IContentLoadingEntryPoint.h index 271bbe039..d847eb38a 100644 --- a/src/ZoneLoading/Loading/IContentLoadingEntryPoint.h +++ b/src/ZoneLoading/Loading/IContentLoadingEntryPoint.h @@ -1,12 +1,11 @@ #pragma once -#include "Zone/Zone.h" #include "Zone/Stream/IZoneInputStream.h" +#include "Zone/Zone.h" -class IContentLoadingEntryPoint -{ +class IContentLoadingEntryPoint { public: - virtual ~IContentLoadingEntryPoint() = default; + virtual ~IContentLoadingEntryPoint() = default; - virtual void Load(Zone* zone, IZoneInputStream* stream) = 0; + virtual void Load(Zone *zone, IZoneInputStream *stream) = 0; }; \ No newline at end of file diff --git a/src/ZoneLoading/Loading/IHashProvider.h b/src/ZoneLoading/Loading/IHashProvider.h index 27d8562cd..4a35453d6 100644 --- a/src/ZoneLoading/Loading/IHashProvider.h +++ b/src/ZoneLoading/Loading/IHashProvider.h @@ -1,8 +1,7 @@ #pragma once #include <cstdint> -class IHashProvider -{ +class IHashProvider { public: - virtual void GetHash(unsigned hashIndex, const uint8_t** pHash, size_t* pSize) = 0; + virtual void GetHash(unsigned hashIndex, const uint8_t **pHash, size_t *pSize) = 0; }; diff --git a/src/ZoneLoading/Loading/ILoadingStep.h b/src/ZoneLoading/Loading/ILoadingStep.h index 2460e5b5a..3cffe5187 100644 --- a/src/ZoneLoading/Loading/ILoadingStep.h +++ b/src/ZoneLoading/Loading/ILoadingStep.h @@ -1,14 +1,13 @@ #pragma once -#include "Loading/ZoneLoader.h" #include "ILoadingStream.h" +#include "Loading/ZoneLoader.h" class ZoneLoader; -class ILoadingStep -{ +class ILoadingStep { public: - virtual ~ILoadingStep() = default; + virtual ~ILoadingStep() = default; - virtual void PerformStep(ZoneLoader* zoneLoader, ILoadingStream* stream) = 0; + virtual void PerformStep(ZoneLoader *zoneLoader, ILoadingStream *stream) = 0; }; diff --git a/src/ZoneLoading/Loading/ILoadingStream.h b/src/ZoneLoading/Loading/ILoadingStream.h index 95f7b1c49..4eb70f416 100644 --- a/src/ZoneLoading/Loading/ILoadingStream.h +++ b/src/ZoneLoading/Loading/ILoadingStream.h @@ -1,13 +1,12 @@ #pragma once -#include <cstdint> #include <cstddef> +#include <cstdint> -class ILoadingStream -{ +class ILoadingStream { public: - virtual ~ILoadingStream() = default; + virtual ~ILoadingStream() = default; - virtual size_t Load(void* buffer, size_t length) = 0; - virtual int64_t Pos() = 0; + virtual size_t Load(void *buffer, size_t length) = 0; + virtual int64_t Pos() = 0; }; \ No newline at end of file diff --git a/src/ZoneLoading/Loading/ISignatureProvider.h b/src/ZoneLoading/Loading/ISignatureProvider.h index 009eaaeac..62d00eef5 100644 --- a/src/ZoneLoading/Loading/ISignatureProvider.h +++ b/src/ZoneLoading/Loading/ISignatureProvider.h @@ -1,8 +1,7 @@ #pragma once #include <cstdint> -class ISignatureProvider -{ +class ISignatureProvider { public: - virtual void GetSignature(const uint8_t** pSignature, size_t* pSize) = 0; + virtual void GetSignature(const uint8_t **pSignature, size_t *pSize) = 0; }; diff --git a/src/ZoneLoading/Loading/IZoneLoaderFactory.h b/src/ZoneLoading/Loading/IZoneLoaderFactory.h index 7cd03092f..0f4b19886 100644 --- a/src/ZoneLoading/Loading/IZoneLoaderFactory.h +++ b/src/ZoneLoading/Loading/IZoneLoaderFactory.h @@ -3,15 +3,14 @@ #include "Zone/ZoneTypes.h" #include "ZoneLoader.h" -class IZoneLoaderFactory -{ +class IZoneLoaderFactory { public: - IZoneLoaderFactory() = default; - virtual ~IZoneLoaderFactory() = default; - IZoneLoaderFactory(const IZoneLoaderFactory& other) = default; - IZoneLoaderFactory(IZoneLoaderFactory&& other) noexcept = default; - IZoneLoaderFactory& operator=(const IZoneLoaderFactory& other) = default; - IZoneLoaderFactory& operator=(IZoneLoaderFactory&& other) noexcept = default; + IZoneLoaderFactory() = default; + virtual ~IZoneLoaderFactory() = default; + IZoneLoaderFactory(const IZoneLoaderFactory &other) = default; + IZoneLoaderFactory(IZoneLoaderFactory &&other) noexcept = default; + IZoneLoaderFactory &operator=(const IZoneLoaderFactory &other) = default; + IZoneLoaderFactory &operator=(IZoneLoaderFactory &&other) noexcept = default; - virtual ZoneLoader* CreateLoaderForHeader(ZoneHeader& header, std::string& fileName) = 0; + virtual ZoneLoader *CreateLoaderForHeader(ZoneHeader &header, std::string &fileName) = 0; }; \ No newline at end of file diff --git a/src/ZoneLoading/Loading/LoadingFileStream.cpp b/src/ZoneLoading/Loading/LoadingFileStream.cpp index 807db569f..7404110d5 100644 --- a/src/ZoneLoading/Loading/LoadingFileStream.cpp +++ b/src/ZoneLoading/Loading/LoadingFileStream.cpp @@ -1,17 +1,10 @@ #include "LoadingFileStream.h" -LoadingFileStream::LoadingFileStream(std::istream& stream) - : m_stream(stream) -{ -} +LoadingFileStream::LoadingFileStream(std::istream &stream) : m_stream(stream) {} -size_t LoadingFileStream::Load(void* buffer, const size_t length) -{ - m_stream.read(static_cast<char*>(buffer), length); - return static_cast<size_t>(m_stream.gcount()); +size_t LoadingFileStream::Load(void *buffer, const size_t length) { + m_stream.read(static_cast<char *>(buffer), length); + return static_cast<size_t>(m_stream.gcount()); } -int64_t LoadingFileStream::Pos() -{ - return m_stream.tellg(); -} \ No newline at end of file +int64_t LoadingFileStream::Pos() { return m_stream.tellg(); } \ No newline at end of file diff --git a/src/ZoneLoading/Loading/LoadingFileStream.h b/src/ZoneLoading/Loading/LoadingFileStream.h index 21a7cc320..262bd6489 100644 --- a/src/ZoneLoading/Loading/LoadingFileStream.h +++ b/src/ZoneLoading/Loading/LoadingFileStream.h @@ -3,13 +3,12 @@ #include "ILoadingStream.h" -class LoadingFileStream final : public ILoadingStream -{ - std::istream& m_stream; +class LoadingFileStream final : public ILoadingStream { + std::istream &m_stream; public: - explicit LoadingFileStream(std::istream& stream); + explicit LoadingFileStream(std::istream &stream); - size_t Load(void* buffer, size_t length) override; - int64_t Pos() override; + size_t Load(void *buffer, size_t length) override; + int64_t Pos() override; }; diff --git a/src/ZoneLoading/Loading/Processor/ProcessorAuthedBlocks.cpp b/src/ZoneLoading/Loading/Processor/ProcessorAuthedBlocks.cpp index 144fda654..6640335be 100644 --- a/src/ZoneLoading/Loading/Processor/ProcessorAuthedBlocks.cpp +++ b/src/ZoneLoading/Loading/Processor/ProcessorAuthedBlocks.cpp @@ -1,162 +1,124 @@ #include "ProcessorAuthedBlocks.h" #include <cassert> -#include <memory> #include <cstring> +#include <memory> #include "Game/IW4/IW4.h" #include "Loading/Exception/InvalidHashException.h" #include "Loading/Exception/TooManyAuthedGroupsException.h" #include "Loading/Exception/UnexpectedEndOfFileException.h" -class ProcessorAuthedBlocks::Impl -{ - ProcessorAuthedBlocks* const m_base; +class ProcessorAuthedBlocks::Impl { + ProcessorAuthedBlocks *const m_base; - const unsigned m_authed_chunk_count; - const size_t m_chunk_size; - const unsigned m_max_master_block_count; + const unsigned m_authed_chunk_count; + const size_t m_chunk_size; + const unsigned m_max_master_block_count; - const std::unique_ptr<IHashFunction> m_hash_function; - IHashProvider* const m_master_block_hash_provider; - const std::unique_ptr<uint8_t[]> m_chunk_hashes_buffer; - const std::unique_ptr<uint8_t[]> m_current_chunk_hash_buffer; + const std::unique_ptr<IHashFunction> m_hash_function; + IHashProvider *const m_master_block_hash_provider; + const std::unique_ptr<uint8_t[]> m_chunk_hashes_buffer; + const std::unique_ptr<uint8_t[]> m_current_chunk_hash_buffer; - const std::unique_ptr<uint8_t[]> m_chunk_buffer; - unsigned m_current_group; - unsigned m_current_chunk_in_group; + const std::unique_ptr<uint8_t[]> m_chunk_buffer; + unsigned m_current_group; + unsigned m_current_chunk_in_group; - size_t m_current_chunk_offset; - size_t m_current_chunk_size; + size_t m_current_chunk_offset; + size_t m_current_chunk_size; public: - Impl(ProcessorAuthedBlocks* base, const unsigned authedChunkCount, const size_t chunkSize, - const unsigned maxMasterBlockCount, - std::unique_ptr<IHashFunction> hashFunction, - IHashProvider* masterBlockHashProvider) - : m_base(base), - m_authed_chunk_count(authedChunkCount), - m_chunk_size(chunkSize), - m_max_master_block_count(maxMasterBlockCount), - m_hash_function(std::move(hashFunction)), - m_master_block_hash_provider(masterBlockHashProvider), - m_chunk_hashes_buffer(std::make_unique<uint8_t[]>(m_authed_chunk_count * m_hash_function->GetHashSize())), - m_current_chunk_hash_buffer(std::make_unique<uint8_t[]>(m_hash_function->GetHashSize())), - m_chunk_buffer(std::make_unique<uint8_t[]>(m_chunk_size)), - m_current_group(1), - m_current_chunk_in_group(0), - m_current_chunk_offset(0), - m_current_chunk_size(0) - { - assert(m_authed_chunk_count * m_hash_function->GetHashSize() <= m_chunk_size); - } - - bool NextChunk() - { - m_current_chunk_offset = 0; - - while (true) - { - m_current_chunk_size = m_base->m_base_stream->Load(m_chunk_buffer.get(), m_chunk_size); - - if (m_current_chunk_size == 0) - return false; - - m_hash_function->Init(); - m_hash_function->Process(m_chunk_buffer.get(), m_current_chunk_size); - m_hash_function->Finish(m_current_chunk_hash_buffer.get()); - - if (m_current_chunk_in_group == 0) - { - if (m_current_chunk_size < m_authed_chunk_count * m_hash_function->GetHashSize()) - throw UnexpectedEndOfFileException(); - - const uint8_t* masterBlockHash = nullptr; - size_t masterBlockHashSize = 0; - m_master_block_hash_provider->GetHash(m_current_group - 1, &masterBlockHash, &masterBlockHashSize); - - if (masterBlockHashSize != m_hash_function->GetHashSize() - || std::memcmp(m_current_chunk_hash_buffer.get(), masterBlockHash, - m_hash_function->GetHashSize()) != 0) - throw InvalidHashException(); - - memcpy(m_chunk_hashes_buffer.get(), m_chunk_buffer.get(), m_authed_chunk_count * m_hash_function->GetHashSize()); - - m_current_chunk_in_group++; - } - else - { - if (std::memcmp(m_current_chunk_hash_buffer.get(), - &m_chunk_hashes_buffer[(m_current_chunk_in_group - 1) * m_hash_function->GetHashSize()], - m_hash_function->GetHashSize()) != 0) - throw InvalidHashException(); - - if (++m_current_chunk_in_group > m_authed_chunk_count) - { - m_current_chunk_in_group = 0; - m_current_group++; - - if (m_current_group > m_max_master_block_count) - throw TooManyAuthedGroupsException(); - } - - return true; - } + Impl(ProcessorAuthedBlocks *base, const unsigned authedChunkCount, const size_t chunkSize, const unsigned maxMasterBlockCount, + std::unique_ptr<IHashFunction> hashFunction, IHashProvider *masterBlockHashProvider) + : m_base(base), m_authed_chunk_count(authedChunkCount), m_chunk_size(chunkSize), m_max_master_block_count(maxMasterBlockCount), + m_hash_function(std::move(hashFunction)), m_master_block_hash_provider(masterBlockHashProvider), + m_chunk_hashes_buffer(std::make_unique<uint8_t[]>(m_authed_chunk_count * m_hash_function->GetHashSize())), + m_current_chunk_hash_buffer(std::make_unique<uint8_t[]>(m_hash_function->GetHashSize())), m_chunk_buffer(std::make_unique<uint8_t[]>(m_chunk_size)), + m_current_group(1), m_current_chunk_in_group(0), m_current_chunk_offset(0), m_current_chunk_size(0) { + assert(m_authed_chunk_count * m_hash_function->GetHashSize() <= m_chunk_size); + } + + bool NextChunk() { + m_current_chunk_offset = 0; + + while (true) { + m_current_chunk_size = m_base->m_base_stream->Load(m_chunk_buffer.get(), m_chunk_size); + + if (m_current_chunk_size == 0) + return false; + + m_hash_function->Init(); + m_hash_function->Process(m_chunk_buffer.get(), m_current_chunk_size); + m_hash_function->Finish(m_current_chunk_hash_buffer.get()); + + if (m_current_chunk_in_group == 0) { + if (m_current_chunk_size < m_authed_chunk_count * m_hash_function->GetHashSize()) + throw UnexpectedEndOfFileException(); + + const uint8_t *masterBlockHash = nullptr; + size_t masterBlockHashSize = 0; + m_master_block_hash_provider->GetHash(m_current_group - 1, &masterBlockHash, &masterBlockHashSize); + + if (masterBlockHashSize != m_hash_function->GetHashSize() || + std::memcmp(m_current_chunk_hash_buffer.get(), masterBlockHash, m_hash_function->GetHashSize()) != 0) + throw InvalidHashException(); + + memcpy(m_chunk_hashes_buffer.get(), m_chunk_buffer.get(), m_authed_chunk_count * m_hash_function->GetHashSize()); + + m_current_chunk_in_group++; + } else { + if (std::memcmp(m_current_chunk_hash_buffer.get(), &m_chunk_hashes_buffer[(m_current_chunk_in_group - 1) * m_hash_function->GetHashSize()], + m_hash_function->GetHashSize()) != 0) + throw InvalidHashException(); + + if (++m_current_chunk_in_group > m_authed_chunk_count) { + m_current_chunk_in_group = 0; + m_current_group++; + + if (m_current_group > m_max_master_block_count) + throw TooManyAuthedGroupsException(); } + + return true; + } } + } - size_t Load(void* buffer, const size_t length) - { - size_t loadedSize = 0; - - while (loadedSize < length) - { - if (m_current_chunk_offset >= m_current_chunk_size) - { - if (!NextChunk()) - return loadedSize; - } - - size_t sizeToWrite = length - loadedSize; - if (sizeToWrite > m_current_chunk_size - m_current_chunk_offset) - sizeToWrite = m_current_chunk_size - m_current_chunk_offset; - - assert(length - loadedSize >= sizeToWrite); - memcpy(&static_cast<uint8_t*>(buffer)[loadedSize], &m_chunk_buffer[m_current_chunk_offset], sizeToWrite); - loadedSize += sizeToWrite; - m_current_chunk_offset += sizeToWrite; - } + size_t Load(void *buffer, const size_t length) { + size_t loadedSize = 0; - return loadedSize; - } + while (loadedSize < length) { + if (m_current_chunk_offset >= m_current_chunk_size) { + if (!NextChunk()) + return loadedSize; + } - int64_t Pos() - { - return m_base->m_base_stream->Pos() - (m_current_chunk_size - m_current_chunk_offset); + size_t sizeToWrite = length - loadedSize; + if (sizeToWrite > m_current_chunk_size - m_current_chunk_offset) + sizeToWrite = m_current_chunk_size - m_current_chunk_offset; + + assert(length - loadedSize >= sizeToWrite); + memcpy(&static_cast<uint8_t *>(buffer)[loadedSize], &m_chunk_buffer[m_current_chunk_offset], sizeToWrite); + loadedSize += sizeToWrite; + m_current_chunk_offset += sizeToWrite; } + + return loadedSize; + } + + int64_t Pos() { return m_base->m_base_stream->Pos() - (m_current_chunk_size - m_current_chunk_offset); } }; -ProcessorAuthedBlocks::ProcessorAuthedBlocks(const unsigned authedChunkCount, const size_t chunkSize, - const unsigned maxMasterBlockCount, - std::unique_ptr<IHashFunction> hashFunction, - IHashProvider* masterBlockHashProvider) - : m_impl(new Impl(this, authedChunkCount, chunkSize, maxMasterBlockCount, std::move(hashFunction), - masterBlockHashProvider)) -{ -} +ProcessorAuthedBlocks::ProcessorAuthedBlocks(const unsigned authedChunkCount, const size_t chunkSize, const unsigned maxMasterBlockCount, + std::unique_ptr<IHashFunction> hashFunction, IHashProvider *masterBlockHashProvider) + : m_impl(new Impl(this, authedChunkCount, chunkSize, maxMasterBlockCount, std::move(hashFunction), masterBlockHashProvider)) {} -ProcessorAuthedBlocks::~ProcessorAuthedBlocks() -{ - delete m_impl; - m_impl = nullptr; +ProcessorAuthedBlocks::~ProcessorAuthedBlocks() { + delete m_impl; + m_impl = nullptr; } -size_t ProcessorAuthedBlocks::Load(void* buffer, const size_t length) -{ - return m_impl->Load(buffer, length); -} +size_t ProcessorAuthedBlocks::Load(void *buffer, const size_t length) { return m_impl->Load(buffer, length); } -int64_t ProcessorAuthedBlocks::Pos() -{ - return m_impl->Pos(); -} +int64_t ProcessorAuthedBlocks::Pos() { return m_impl->Pos(); } diff --git a/src/ZoneLoading/Loading/Processor/ProcessorAuthedBlocks.h b/src/ZoneLoading/Loading/Processor/ProcessorAuthedBlocks.h index b7be3891f..fd8dee22b 100644 --- a/src/ZoneLoading/Loading/Processor/ProcessorAuthedBlocks.h +++ b/src/ZoneLoading/Loading/Processor/ProcessorAuthedBlocks.h @@ -2,23 +2,22 @@ #include <memory> #include "Crypto.h" -#include "Loading/StreamProcessor.h" #include "Loading/IHashProvider.h" +#include "Loading/StreamProcessor.h" -class ProcessorAuthedBlocks final : public StreamProcessor -{ - class Impl; - Impl* m_impl; +class ProcessorAuthedBlocks final : public StreamProcessor { + class Impl; + Impl *m_impl; public: - ProcessorAuthedBlocks(unsigned authedChunkCount, size_t chunkSize, unsigned maxMasterBlockCount, - std::unique_ptr<IHashFunction> hashFunction, IHashProvider* masterBlockHashProvider); - ~ProcessorAuthedBlocks() override; - ProcessorAuthedBlocks(const ProcessorAuthedBlocks& other) = delete; - ProcessorAuthedBlocks(ProcessorAuthedBlocks&& other) noexcept = default; - ProcessorAuthedBlocks& operator=(const ProcessorAuthedBlocks& other) = delete; - ProcessorAuthedBlocks& operator=(ProcessorAuthedBlocks&& other) noexcept = default; + ProcessorAuthedBlocks(unsigned authedChunkCount, size_t chunkSize, unsigned maxMasterBlockCount, std::unique_ptr<IHashFunction> hashFunction, + IHashProvider *masterBlockHashProvider); + ~ProcessorAuthedBlocks() override; + ProcessorAuthedBlocks(const ProcessorAuthedBlocks &other) = delete; + ProcessorAuthedBlocks(ProcessorAuthedBlocks &&other) noexcept = default; + ProcessorAuthedBlocks &operator=(const ProcessorAuthedBlocks &other) = delete; + ProcessorAuthedBlocks &operator=(ProcessorAuthedBlocks &&other) noexcept = default; - size_t Load(void* buffer, size_t length) override; - int64_t Pos() override; + size_t Load(void *buffer, size_t length) override; + int64_t Pos() override; }; diff --git a/src/ZoneLoading/Loading/Processor/ProcessorCaptureData.cpp b/src/ZoneLoading/Loading/Processor/ProcessorCaptureData.cpp index 8168d8047..c3e7065b2 100644 --- a/src/ZoneLoading/Loading/Processor/ProcessorCaptureData.cpp +++ b/src/ZoneLoading/Loading/Processor/ProcessorCaptureData.cpp @@ -4,49 +4,39 @@ #include <cstring> ProcessorCaptureData::ProcessorCaptureData(const size_t captureSize) - : m_data(std::make_unique<uint8_t[]>(captureSize)), - m_capture_size(captureSize), - m_captured_data_size(0) -{ -} + : m_data(std::make_unique<uint8_t[]>(captureSize)), m_capture_size(captureSize), m_captured_data_size(0) {} -ProcessorCaptureData::~ProcessorCaptureData() -= default; +ProcessorCaptureData::~ProcessorCaptureData() = default; -size_t ProcessorCaptureData::Load(void* buffer, const size_t length) -{ - if (m_captured_data_size >= m_capture_size) - return m_base_stream->Load(buffer, length); +size_t ProcessorCaptureData::Load(void *buffer, const size_t length) { + if (m_captured_data_size >= m_capture_size) + return m_base_stream->Load(buffer, length); - size_t dataToCapture = m_capture_size - m_captured_data_size; + size_t dataToCapture = m_capture_size - m_captured_data_size; - if (length < dataToCapture) - dataToCapture = length; + if (length < dataToCapture) + dataToCapture = length; - size_t loadedSize = m_base_stream->Load(&m_data[m_captured_data_size], dataToCapture); - assert(length >= loadedSize); - memcpy(buffer, &m_data[m_captured_data_size], loadedSize); + size_t loadedSize = m_base_stream->Load(&m_data[m_captured_data_size], dataToCapture); + assert(length >= loadedSize); + memcpy(buffer, &m_data[m_captured_data_size], loadedSize); - m_captured_data_size += loadedSize; + m_captured_data_size += loadedSize; - if(length > dataToCapture) - loadedSize += m_base_stream->Load(&static_cast<uint8_t*>(buffer)[dataToCapture], length - dataToCapture); + if (length > dataToCapture) + loadedSize += m_base_stream->Load(&static_cast<uint8_t *>(buffer)[dataToCapture], length - dataToCapture); - return loadedSize; + return loadedSize; } -int64_t ProcessorCaptureData::Pos() -{ - return m_base_stream->Pos(); -} +int64_t ProcessorCaptureData::Pos() { return m_base_stream->Pos(); } -void ProcessorCaptureData::GetCapturedData(const uint8_t** pCapturedData, size_t* pSize) -{ - assert(pCapturedData != nullptr); - assert(pSize != nullptr); +void ProcessorCaptureData::GetCapturedData(const uint8_t **pCapturedData, size_t *pSize) { + assert(pCapturedData != nullptr); + assert(pSize != nullptr); - assert(m_captured_data_size == m_capture_size); + assert(m_captured_data_size == m_capture_size); - *pCapturedData = m_data.get(); - *pSize = m_captured_data_size; + *pCapturedData = m_data.get(); + *pSize = m_captured_data_size; } diff --git a/src/ZoneLoading/Loading/Processor/ProcessorCaptureData.h b/src/ZoneLoading/Loading/Processor/ProcessorCaptureData.h index 28f46bd81..877fba3b9 100644 --- a/src/ZoneLoading/Loading/Processor/ProcessorCaptureData.h +++ b/src/ZoneLoading/Loading/Processor/ProcessorCaptureData.h @@ -4,17 +4,16 @@ #include "Loading/StreamProcessor.h" #include "Utils/ICapturedDataProvider.h" -class ProcessorCaptureData final : public StreamProcessor, public ICapturedDataProvider -{ - std::unique_ptr<uint8_t[]> m_data; - const size_t m_capture_size; - size_t m_captured_data_size; +class ProcessorCaptureData final : public StreamProcessor, public ICapturedDataProvider { + std::unique_ptr<uint8_t[]> m_data; + const size_t m_capture_size; + size_t m_captured_data_size; public: - explicit ProcessorCaptureData(size_t captureSize); - ~ProcessorCaptureData() override; + explicit ProcessorCaptureData(size_t captureSize); + ~ProcessorCaptureData() override; - size_t Load(void* buffer, size_t length) override; - int64_t Pos() override; - void GetCapturedData(const uint8_t** pCapturedData, size_t* pSize) override; + size_t Load(void *buffer, size_t length) override; + int64_t Pos() override; + void GetCapturedData(const uint8_t **pCapturedData, size_t *pSize) override; }; diff --git a/src/ZoneLoading/Loading/Processor/ProcessorIW4xDecryption.cpp b/src/ZoneLoading/Loading/Processor/ProcessorIW4xDecryption.cpp index bb66145b3..17250e369 100644 --- a/src/ZoneLoading/Loading/Processor/ProcessorIW4xDecryption.cpp +++ b/src/ZoneLoading/Loading/Processor/ProcessorIW4xDecryption.cpp @@ -2,44 +2,34 @@ #include <cassert> -ProcessorIW4xDecryption::ProcessorIW4xDecryption() - : m_last_byte(0u) -{ -} +ProcessorIW4xDecryption::ProcessorIW4xDecryption() : m_last_byte(0u) {} -uint8_t ProcessorIW4xDecryption::RotateLeft(const uint8_t value, const unsigned count) -{ - assert(count < sizeof(value) * 8); - return static_cast<uint8_t>(value << count | (value >> ((sizeof(value) * 8) - count))); +uint8_t ProcessorIW4xDecryption::RotateLeft(const uint8_t value, const unsigned count) { + assert(count < sizeof(value) * 8); + return static_cast<uint8_t>(value << count | (value >> ((sizeof(value) * 8) - count))); } -uint8_t ProcessorIW4xDecryption::RotateRight(uint8_t value, const unsigned count) -{ - assert(count < sizeof(value) * 8); - return static_cast<uint8_t>(value >> count | (value << ((sizeof(value) * 8) - count))); +uint8_t ProcessorIW4xDecryption::RotateRight(uint8_t value, const unsigned count) { + assert(count < sizeof(value) * 8); + return static_cast<uint8_t>(value >> count | (value << ((sizeof(value) * 8) - count))); } -size_t ProcessorIW4xDecryption::Load(void* buffer, const size_t length) -{ - const auto readLen = m_base_stream->Load(buffer, length); +size_t ProcessorIW4xDecryption::Load(void *buffer, const size_t length) { + const auto readLen = m_base_stream->Load(buffer, length); - auto* charBuffer = static_cast<uint8_t*>(buffer); - for(auto i = 0u; i < readLen; i++) - { - auto value = charBuffer[i]; - value ^= m_last_byte; - value = RotateLeft(value, 4); - value ^= -1; - value = RotateRight(value, 6); + auto *charBuffer = static_cast<uint8_t *>(buffer); + for (auto i = 0u; i < readLen; i++) { + auto value = charBuffer[i]; + value ^= m_last_byte; + value = RotateLeft(value, 4); + value ^= -1; + value = RotateRight(value, 6); - charBuffer[i] = value; - m_last_byte = value; - } + charBuffer[i] = value; + m_last_byte = value; + } - return readLen; + return readLen; } -int64_t ProcessorIW4xDecryption::Pos() -{ - return m_base_stream->Pos(); -} +int64_t ProcessorIW4xDecryption::Pos() { return m_base_stream->Pos(); } diff --git a/src/ZoneLoading/Loading/Processor/ProcessorIW4xDecryption.h b/src/ZoneLoading/Loading/Processor/ProcessorIW4xDecryption.h index 6f9acc379..feae7f78a 100644 --- a/src/ZoneLoading/Loading/Processor/ProcessorIW4xDecryption.h +++ b/src/ZoneLoading/Loading/Processor/ProcessorIW4xDecryption.h @@ -1,16 +1,15 @@ #pragma once #include "Loading/StreamProcessor.h" -class ProcessorIW4xDecryption final : public StreamProcessor -{ - uint8_t m_last_byte; +class ProcessorIW4xDecryption final : public StreamProcessor { + uint8_t m_last_byte; - static uint8_t RotateLeft(uint8_t value, unsigned count); - static uint8_t RotateRight(uint8_t value, unsigned count); + static uint8_t RotateLeft(uint8_t value, unsigned count); + static uint8_t RotateRight(uint8_t value, unsigned count); public: - ProcessorIW4xDecryption(); + ProcessorIW4xDecryption(); - size_t Load(void* buffer, size_t length) override; - int64_t Pos() override; + size_t Load(void *buffer, size_t length) override; + int64_t Pos() override; }; diff --git a/src/ZoneLoading/Loading/Processor/ProcessorInflate.cpp b/src/ZoneLoading/Loading/Processor/ProcessorInflate.cpp index 2a4c7a520..c7714460c 100644 --- a/src/ZoneLoading/Loading/Processor/ProcessorInflate.cpp +++ b/src/ZoneLoading/Loading/Processor/ProcessorInflate.cpp @@ -1,100 +1,76 @@ #include "ProcessorInflate.h" -#include <stdexcept> #include <cstdint> #include <memory> +#include <stdexcept> #include <zlib.h> #include <zutil.h> #include "Loading/Exception/InvalidCompressionException.h" -class ProcessorInflate::Impl -{ - z_stream m_stream{}; - ProcessorInflate* m_base; +class ProcessorInflate::Impl { + z_stream m_stream{}; + ProcessorInflate *m_base; - std::unique_ptr<uint8_t[]> m_buffer; - size_t m_buffer_size; + std::unique_ptr<uint8_t[]> m_buffer; + size_t m_buffer_size; public: - Impl(ProcessorInflate* baseClass, const size_t bufferSize) - : m_buffer(std::make_unique<uint8_t[]>(bufferSize)), - m_buffer_size(bufferSize) - { - m_base = baseClass; - - m_stream.zalloc = Z_NULL; - m_stream.zfree = Z_NULL; - m_stream.opaque = Z_NULL; - m_stream.avail_in = 0; - m_stream.next_in = Z_NULL; - - const int ret = inflateInit(&m_stream); - - if (ret != Z_OK) - { - throw std::runtime_error("Initializing inflate failed"); - } - } + Impl(ProcessorInflate *baseClass, const size_t bufferSize) : m_buffer(std::make_unique<uint8_t[]>(bufferSize)), m_buffer_size(bufferSize) { + m_base = baseClass; + + m_stream.zalloc = Z_NULL; + m_stream.zfree = Z_NULL; + m_stream.opaque = Z_NULL; + m_stream.avail_in = 0; + m_stream.next_in = Z_NULL; + + const int ret = inflateInit(&m_stream); - ~Impl() - { - inflateEnd(&m_stream); + if (ret != Z_OK) { + throw std::runtime_error("Initializing inflate failed"); } + } - Impl(const Impl& other) = delete; - Impl(Impl&& other) noexcept = default; - Impl& operator=(const Impl& other) = delete; - Impl& operator=(Impl&& other) noexcept = default; + ~Impl() { inflateEnd(&m_stream); } - size_t Load(void* buffer, const size_t length) - { - m_stream.next_out = static_cast<Bytef*>(buffer); - m_stream.avail_out = length; + Impl(const Impl &other) = delete; + Impl(Impl &&other) noexcept = default; + Impl &operator=(const Impl &other) = delete; + Impl &operator=(Impl &&other) noexcept = default; - while (m_stream.avail_out > 0) - { - if (m_stream.avail_in == 0) - { - m_stream.avail_in = m_base->m_base_stream->Load(m_buffer.get(), m_buffer_size); - m_stream.next_in = m_buffer.get(); + size_t Load(void *buffer, const size_t length) { + m_stream.next_out = static_cast<Bytef *>(buffer); + m_stream.avail_out = length; - if (m_stream.avail_in == 0) // EOF - return length - m_stream.avail_out; - } + while (m_stream.avail_out > 0) { + if (m_stream.avail_in == 0) { + m_stream.avail_in = m_base->m_base_stream->Load(m_buffer.get(), m_buffer_size); + m_stream.next_in = m_buffer.get(); - auto ret = inflate(&m_stream, Z_SYNC_FLUSH); + if (m_stream.avail_in == 0) // EOF + return length - m_stream.avail_out; + } - if(ret < 0) - throw InvalidCompressionException(); - } + auto ret = inflate(&m_stream, Z_SYNC_FLUSH); - return length - m_stream.avail_out; + if (ret < 0) + throw InvalidCompressionException(); } + + return length - m_stream.avail_out; + } }; -ProcessorInflate::ProcessorInflate() - : ProcessorInflate(DEFAULT_BUFFER_SIZE) -{ -} +ProcessorInflate::ProcessorInflate() : ProcessorInflate(DEFAULT_BUFFER_SIZE) {} -ProcessorInflate::ProcessorInflate(const size_t bufferSize) - : m_impl(new Impl(this, bufferSize)) -{ -} +ProcessorInflate::ProcessorInflate(const size_t bufferSize) : m_impl(new Impl(this, bufferSize)) {} -ProcessorInflate::~ProcessorInflate() -{ - delete m_impl; - m_impl = nullptr; +ProcessorInflate::~ProcessorInflate() { + delete m_impl; + m_impl = nullptr; } -size_t ProcessorInflate::Load(void* buffer, const size_t length) -{ - return m_impl->Load(buffer, length); -} +size_t ProcessorInflate::Load(void *buffer, const size_t length) { return m_impl->Load(buffer, length); } -int64_t ProcessorInflate::Pos() -{ - return m_base_stream->Pos(); -} +int64_t ProcessorInflate::Pos() { return m_base_stream->Pos(); } diff --git a/src/ZoneLoading/Loading/Processor/ProcessorInflate.h b/src/ZoneLoading/Loading/Processor/ProcessorInflate.h index f1e17ed59..22fcc8d2b 100644 --- a/src/ZoneLoading/Loading/Processor/ProcessorInflate.h +++ b/src/ZoneLoading/Loading/Processor/ProcessorInflate.h @@ -1,22 +1,21 @@ #pragma once #include "Loading/StreamProcessor.h" -class ProcessorInflate final : public StreamProcessor -{ - class Impl; - Impl* m_impl; +class ProcessorInflate final : public StreamProcessor { + class Impl; + Impl *m_impl; - static constexpr size_t DEFAULT_BUFFER_SIZE = 0x2000; + static constexpr size_t DEFAULT_BUFFER_SIZE = 0x2000; public: - ProcessorInflate(); - ProcessorInflate(size_t bufferSize); - ~ProcessorInflate() override; - ProcessorInflate(const ProcessorInflate& other) = delete; - ProcessorInflate(ProcessorInflate&& other) noexcept = default; - ProcessorInflate& operator=(const ProcessorInflate& other) = delete; - ProcessorInflate& operator=(ProcessorInflate&& other) noexcept = default; + ProcessorInflate(); + ProcessorInflate(size_t bufferSize); + ~ProcessorInflate() override; + ProcessorInflate(const ProcessorInflate &other) = delete; + ProcessorInflate(ProcessorInflate &&other) noexcept = default; + ProcessorInflate &operator=(const ProcessorInflate &other) = delete; + ProcessorInflate &operator=(ProcessorInflate &&other) noexcept = default; - size_t Load(void* buffer, size_t length) override; - int64_t Pos() override; + size_t Load(void *buffer, size_t length) override; + int64_t Pos() override; }; diff --git a/src/ZoneLoading/Loading/Processor/ProcessorStreamCipher.cpp b/src/ZoneLoading/Loading/Processor/ProcessorStreamCipher.cpp index 8dfaf4c76..b343f5a17 100644 --- a/src/ZoneLoading/Loading/Processor/ProcessorStreamCipher.cpp +++ b/src/ZoneLoading/Loading/Processor/ProcessorStreamCipher.cpp @@ -1,28 +1,21 @@ #include "ProcessorStreamCipher.h" -ProcessorStreamCipher::ProcessorStreamCipher(IStreamCipher* cipher) -{ - m_cipher = cipher; -} +ProcessorStreamCipher::ProcessorStreamCipher(IStreamCipher *cipher) { m_cipher = cipher; } -ProcessorStreamCipher::~ProcessorStreamCipher() -{ - delete m_cipher; - m_cipher = nullptr; +ProcessorStreamCipher::~ProcessorStreamCipher() { + delete m_cipher; + m_cipher = nullptr; } +size_t ProcessorStreamCipher::Load(void *buffer, const size_t length) { + if (m_base_stream != nullptr) { + const size_t readSize = m_base_stream->Load(buffer, length); -size_t ProcessorStreamCipher::Load(void* buffer, const size_t length) -{ - if(m_base_stream != nullptr) - { - const size_t readSize = m_base_stream->Load(buffer, length); - - if(readSize > 0) - m_cipher->Process(buffer, buffer, readSize); + if (readSize > 0) + m_cipher->Process(buffer, buffer, readSize); - return readSize; - } + return readSize; + } - return 0; + return 0; } \ No newline at end of file diff --git a/src/ZoneLoading/Loading/Processor/ProcessorStreamCipher.h b/src/ZoneLoading/Loading/Processor/ProcessorStreamCipher.h index cb81ef5f4..76b28e961 100644 --- a/src/ZoneLoading/Loading/Processor/ProcessorStreamCipher.h +++ b/src/ZoneLoading/Loading/Processor/ProcessorStreamCipher.h @@ -1,14 +1,13 @@ #pragma once -#include "Loading/StreamProcessor.h" #include "Crypto.h" +#include "Loading/StreamProcessor.h" -class ProcessorStreamCipher final : public StreamProcessor -{ - IStreamCipher* m_cipher; +class ProcessorStreamCipher final : public StreamProcessor { + IStreamCipher *m_cipher; public: - explicit ProcessorStreamCipher(IStreamCipher* cipher); - ~ProcessorStreamCipher() override; + explicit ProcessorStreamCipher(IStreamCipher *cipher); + ~ProcessorStreamCipher() override; - size_t Load(void* buffer, size_t length) override; + size_t Load(void *buffer, size_t length) override; }; diff --git a/src/ZoneLoading/Loading/Processor/ProcessorXChunks.cpp b/src/ZoneLoading/Loading/Processor/ProcessorXChunks.cpp index 80e655995..77c6e694a 100644 --- a/src/ZoneLoading/Loading/Processor/ProcessorXChunks.cpp +++ b/src/ZoneLoading/Loading/Processor/ProcessorXChunks.cpp @@ -1,337 +1,279 @@ #include "ProcessorXChunks.h" -#include "Zone/ZoneTypes.h" #include "Loading/Exception/InvalidChunkSizeException.h" +#include "Zone/ZoneTypes.h" -#include <vector> -#include <thread> -#include <mutex> -#include <condition_variable> #include <cassert> +#include <condition_variable> #include <cstring> #include <memory> +#include <mutex> +#include <thread> +#include <vector> -class DBLoadStream -{ - int m_index; - - std::unique_ptr<uint8_t[]> m_buffers[2]; +class DBLoadStream { + int m_index; - uint8_t* m_input_buffer; - size_t m_input_size; + std::unique_ptr<uint8_t[]> m_buffers[2]; - uint8_t* m_output_buffer; - size_t m_output_size; + uint8_t *m_input_buffer; + size_t m_input_size; - size_t m_chunk_size; + uint8_t *m_output_buffer; + size_t m_output_size; - bool m_is_loading; - std::mutex m_load_mutex; - std::condition_variable m_loading_finished; - std::thread m_load_thread; + size_t m_chunk_size; - std::vector<std::unique_ptr<IXChunkProcessor>>& m_processors; + bool m_is_loading; + std::mutex m_load_mutex; + std::condition_variable m_loading_finished; + std::thread m_load_thread; - void Load() - { - std::lock_guard<std::mutex> lock(m_load_mutex); + std::vector<std::unique_ptr<IXChunkProcessor>> &m_processors; - bool firstProcessor = true; + void Load() { + std::lock_guard<std::mutex> lock(m_load_mutex); - for (const auto& processor : m_processors) - { - if (!firstProcessor) - { - uint8_t* previousInputBuffer = m_input_buffer; - m_input_buffer = m_output_buffer; - m_output_buffer = previousInputBuffer; + bool firstProcessor = true; - m_input_size = m_output_size; - m_output_size = 0; - } + for (const auto &processor : m_processors) { + if (!firstProcessor) { + uint8_t *previousInputBuffer = m_input_buffer; + m_input_buffer = m_output_buffer; + m_output_buffer = previousInputBuffer; - m_output_size = processor->Process(m_index, m_input_buffer, m_input_size, m_output_buffer, m_chunk_size); + m_input_size = m_output_size; + m_output_size = 0; + } - firstProcessor = false; - } + m_output_size = processor->Process(m_index, m_input_buffer, m_input_size, m_output_buffer, m_chunk_size); - m_is_loading = false; - m_loading_finished.notify_all(); + firstProcessor = false; } + m_is_loading = false; + m_loading_finished.notify_all(); + } + public: - DBLoadStream(const int streamIndex, const size_t chunkSize, - std::vector<std::unique_ptr<IXChunkProcessor>>& chunkProcessors) : m_processors(chunkProcessors) - { - m_index = streamIndex; - m_chunk_size = chunkSize; - - for(auto& buffer : m_buffers) - buffer = std::make_unique<uint8_t[]>(chunkSize); - - m_input_buffer = m_buffers[0].get(); - m_output_buffer = m_buffers[1].get(); - - m_input_size = 0; - m_output_size = 0; + DBLoadStream(const int streamIndex, const size_t chunkSize, std::vector<std::unique_ptr<IXChunkProcessor>> &chunkProcessors) : m_processors(chunkProcessors) { + m_index = streamIndex; + m_chunk_size = chunkSize; - m_is_loading = false; - } + for (auto &buffer : m_buffers) + buffer = std::make_unique<uint8_t[]>(chunkSize); - uint8_t* GetInputBuffer() const - { - return m_input_buffer; - } + m_input_buffer = m_buffers[0].get(); + m_output_buffer = m_buffers[1].get(); - void StartLoading(const size_t inputSize) - { - if (inputSize > 0) - { - std::unique_lock<std::mutex> lock(m_load_mutex); - - if (m_is_loading) - { - m_loading_finished.wait(lock); - } - - m_input_size = inputSize; - m_is_loading = true; - m_load_thread = std::thread(&DBLoadStream::Load, this); - m_load_thread.detach(); - } - else - { - m_output_size = 0; - } - } + m_input_size = 0; + m_output_size = 0; - void GetOutput(const uint8_t** pBuffer, size_t* pSize) - { - assert(pBuffer != nullptr); - assert(pSize != nullptr); + m_is_loading = false; + } - std::unique_lock<std::mutex> lock(m_load_mutex); - if (m_is_loading) - { - m_loading_finished.wait(lock); - } + uint8_t *GetInputBuffer() const { return m_input_buffer; } - *pBuffer = m_output_buffer; - *pSize = m_output_size; + void StartLoading(const size_t inputSize) { + if (inputSize > 0) { + std::unique_lock<std::mutex> lock(m_load_mutex); + + if (m_is_loading) { + m_loading_finished.wait(lock); + } + + m_input_size = inputSize; + m_is_loading = true; + m_load_thread = std::thread(&DBLoadStream::Load, this); + m_load_thread.detach(); + } else { + m_output_size = 0; } + } + + void GetOutput(const uint8_t **pBuffer, size_t *pSize) { + assert(pBuffer != nullptr); + assert(pSize != nullptr); + + std::unique_lock<std::mutex> lock(m_load_mutex); + if (m_is_loading) { + m_loading_finished.wait(lock); + } + + *pBuffer = m_output_buffer; + *pSize = m_output_size; + } }; -class ProcessorXChunks::ProcessorXChunksImpl -{ - ProcessorXChunks* m_base; - - std::vector<std::unique_ptr<DBLoadStream>> m_streams; - size_t m_chunk_size; - size_t m_vanilla_buffer_size; - std::vector<std::unique_ptr<IXChunkProcessor>> m_chunk_processors; - - bool m_initialized_streams; - unsigned int m_current_stream; - const uint8_t* m_current_chunk; - size_t m_current_chunk_size; - size_t m_current_chunk_offset; - size_t m_vanilla_buffer_offset; - - bool m_eof_reached; - unsigned int m_eof_stream; - - void AdvanceStream(const unsigned int streamNum) - { - assert(streamNum >= 0 && streamNum < m_streams.size()); - - if (m_eof_reached) - return; - - xchunk_size_t chunkSize; - if (m_vanilla_buffer_size > 0) - { - if (m_vanilla_buffer_offset + sizeof chunkSize > m_vanilla_buffer_size) - { - m_base->m_base_stream->Load(&chunkSize, m_vanilla_buffer_size - m_vanilla_buffer_offset); - m_vanilla_buffer_offset = 0; - } - - m_vanilla_buffer_offset = (m_vanilla_buffer_offset + sizeof chunkSize) % m_vanilla_buffer_size; - } +class ProcessorXChunks::ProcessorXChunksImpl { + ProcessorXChunks *m_base; - const size_t readSize = m_base->m_base_stream->Load(&chunkSize, sizeof chunkSize); + std::vector<std::unique_ptr<DBLoadStream>> m_streams; + size_t m_chunk_size; + size_t m_vanilla_buffer_size; + std::vector<std::unique_ptr<IXChunkProcessor>> m_chunk_processors; - if (readSize == 0) - { - m_eof_reached = true; - m_eof_stream = streamNum; - return; - } + bool m_initialized_streams; + unsigned int m_current_stream; + const uint8_t *m_current_chunk; + size_t m_current_chunk_size; + size_t m_current_chunk_offset; + size_t m_vanilla_buffer_offset; - if (chunkSize > m_chunk_size) - { - throw InvalidChunkSizeException(chunkSize, m_chunk_size); - } + bool m_eof_reached; + unsigned int m_eof_stream; - const auto& stream = m_streams[streamNum]; - const size_t loadedChunkSize = m_base->m_base_stream->Load(stream->GetInputBuffer(), chunkSize); + void AdvanceStream(const unsigned int streamNum) { + assert(streamNum >= 0 && streamNum < m_streams.size()); - if (loadedChunkSize != chunkSize) - { - throw InvalidChunkSizeException(chunkSize); - } + if (m_eof_reached) + return; - if (m_vanilla_buffer_size > 0) - { - m_vanilla_buffer_offset = (m_vanilla_buffer_offset + loadedChunkSize) % m_vanilla_buffer_size; - } + xchunk_size_t chunkSize; + if (m_vanilla_buffer_size > 0) { + if (m_vanilla_buffer_offset + sizeof chunkSize > m_vanilla_buffer_size) { + m_base->m_base_stream->Load(&chunkSize, m_vanilla_buffer_size - m_vanilla_buffer_offset); + m_vanilla_buffer_offset = 0; + } - stream->StartLoading(loadedChunkSize); + m_vanilla_buffer_offset = (m_vanilla_buffer_offset + sizeof chunkSize) % m_vanilla_buffer_size; } - void NextStream() - { - AdvanceStream(m_current_stream); + const size_t readSize = m_base->m_base_stream->Load(&chunkSize, sizeof chunkSize); - m_current_stream = (m_current_stream + 1) % m_streams.size(); - m_current_chunk_offset = 0; - m_streams[m_current_stream]->GetOutput(&m_current_chunk, &m_current_chunk_size); + if (readSize == 0) { + m_eof_reached = true; + m_eof_stream = streamNum; + return; } - void InitStreams() - { - m_initialized_streams = true; - m_vanilla_buffer_offset = static_cast<size_t>(m_base->m_base_stream->Pos()); + if (chunkSize > m_chunk_size) { + throw InvalidChunkSizeException(chunkSize, m_chunk_size); + } - const unsigned int streamCount = m_streams.size(); - for (unsigned int streamNum = 0; streamNum < streamCount; streamNum++) - { - AdvanceStream(streamNum); - } + const auto &stream = m_streams[streamNum]; + const size_t loadedChunkSize = m_base->m_base_stream->Load(stream->GetInputBuffer(), chunkSize); - m_current_stream = 0; - m_current_chunk_offset = 0; - m_streams[0]->GetOutput(&m_current_chunk, &m_current_chunk_size); + if (loadedChunkSize != chunkSize) { + throw InvalidChunkSizeException(chunkSize); } - bool EndOfStream() const - { - return m_eof_reached && m_eof_stream == m_current_stream; + if (m_vanilla_buffer_size > 0) { + m_vanilla_buffer_offset = (m_vanilla_buffer_offset + loadedChunkSize) % m_vanilla_buffer_size; } -public: - ProcessorXChunksImpl(ProcessorXChunks* base, const int numStreams, const size_t xChunkSize) - { - assert(base != nullptr); - assert(numStreams > 0); - assert(xChunkSize > 0); - - m_base = base; + stream->StartLoading(loadedChunkSize); + } - for (int streamIndex = 0; streamIndex < numStreams; streamIndex++) - { - m_streams.emplace_back(std::make_unique<DBLoadStream>(streamIndex, xChunkSize, m_chunk_processors)); - } + void NextStream() { + AdvanceStream(m_current_stream); - m_chunk_size = xChunkSize; - m_vanilla_buffer_size = 0; + m_current_stream = (m_current_stream + 1) % m_streams.size(); + m_current_chunk_offset = 0; + m_streams[m_current_stream]->GetOutput(&m_current_chunk, &m_current_chunk_size); + } - m_initialized_streams = false; - m_current_stream = 0; - m_current_chunk = nullptr; - m_current_chunk_size = 0; - m_current_chunk_offset = 0; - m_vanilla_buffer_offset = 0; + void InitStreams() { + m_initialized_streams = true; + m_vanilla_buffer_offset = static_cast<size_t>(m_base->m_base_stream->Pos()); - m_eof_reached = false; - m_eof_stream = 0; + const unsigned int streamCount = m_streams.size(); + for (unsigned int streamNum = 0; streamNum < streamCount; streamNum++) { + AdvanceStream(streamNum); } - ProcessorXChunksImpl(ProcessorXChunks* base, const int numStreams, const size_t xChunkSize, - const size_t vanillaBufferSize) : ProcessorXChunksImpl(base, numStreams, xChunkSize) - { - m_vanilla_buffer_size = vanillaBufferSize; - } + m_current_stream = 0; + m_current_chunk_offset = 0; + m_streams[0]->GetOutput(&m_current_chunk, &m_current_chunk_size); + } + + bool EndOfStream() const { return m_eof_reached && m_eof_stream == m_current_stream; } - void AddChunkProcessor(std::unique_ptr<IXChunkProcessor> streamProcessor) - { - assert(streamProcessor != nullptr); +public: + ProcessorXChunksImpl(ProcessorXChunks *base, const int numStreams, const size_t xChunkSize) { + assert(base != nullptr); + assert(numStreams > 0); + assert(xChunkSize > 0); - m_chunk_processors.emplace_back(std::move(streamProcessor)); + m_base = base; + + for (int streamIndex = 0; streamIndex < numStreams; streamIndex++) { + m_streams.emplace_back(std::make_unique<DBLoadStream>(streamIndex, xChunkSize, m_chunk_processors)); } - size_t Load(void* buffer, const size_t length) - { - assert(buffer != nullptr); + m_chunk_size = xChunkSize; + m_vanilla_buffer_size = 0; - if (!m_initialized_streams) - { - InitStreams(); - } + m_initialized_streams = false; + m_current_stream = 0; + m_current_chunk = nullptr; + m_current_chunk_size = 0; + m_current_chunk_offset = 0; + m_vanilla_buffer_offset = 0; - size_t loadedSize = 0; - while (!EndOfStream() && loadedSize < length) - { - auto* bufferPos = static_cast<uint8_t*>(buffer) + loadedSize; - const size_t sizeToRead = length - loadedSize; - const size_t bytesLeftInCurrentChunk = m_current_chunk_size - m_current_chunk_offset; - - if (sizeToRead > bytesLeftInCurrentChunk) - { - assert(sizeToRead >= bytesLeftInCurrentChunk); - memcpy(bufferPos, &m_current_chunk[m_current_chunk_offset], bytesLeftInCurrentChunk); - loadedSize += bytesLeftInCurrentChunk; - - NextStream(); - } - else - { - memcpy(bufferPos, &m_current_chunk[m_current_chunk_offset], sizeToRead); - loadedSize += sizeToRead; - m_current_chunk_offset += sizeToRead; - - if (m_current_chunk_offset == m_current_chunk_size) - { - NextStream(); - } - } - } + m_eof_reached = false; + m_eof_stream = 0; + } + + ProcessorXChunksImpl(ProcessorXChunks *base, const int numStreams, const size_t xChunkSize, const size_t vanillaBufferSize) + : ProcessorXChunksImpl(base, numStreams, xChunkSize) { + m_vanilla_buffer_size = vanillaBufferSize; + } + + void AddChunkProcessor(std::unique_ptr<IXChunkProcessor> streamProcessor) { + assert(streamProcessor != nullptr); + + m_chunk_processors.emplace_back(std::move(streamProcessor)); + } + + size_t Load(void *buffer, const size_t length) { + assert(buffer != nullptr); - return loadedSize; + if (!m_initialized_streams) { + InitStreams(); } - int64_t Pos() const - { - return m_base->m_base_stream->Pos(); + size_t loadedSize = 0; + while (!EndOfStream() && loadedSize < length) { + auto *bufferPos = static_cast<uint8_t *>(buffer) + loadedSize; + const size_t sizeToRead = length - loadedSize; + const size_t bytesLeftInCurrentChunk = m_current_chunk_size - m_current_chunk_offset; + + if (sizeToRead > bytesLeftInCurrentChunk) { + assert(sizeToRead >= bytesLeftInCurrentChunk); + memcpy(bufferPos, &m_current_chunk[m_current_chunk_offset], bytesLeftInCurrentChunk); + loadedSize += bytesLeftInCurrentChunk; + + NextStream(); + } else { + memcpy(bufferPos, &m_current_chunk[m_current_chunk_offset], sizeToRead); + loadedSize += sizeToRead; + m_current_chunk_offset += sizeToRead; + + if (m_current_chunk_offset == m_current_chunk_size) { + NextStream(); + } + } } + + return loadedSize; + } + + int64_t Pos() const { return m_base->m_base_stream->Pos(); } }; -ProcessorXChunks::ProcessorXChunks(const int numStreams, const size_t xChunkSize) -{ - m_impl = new ProcessorXChunksImpl(this, numStreams, xChunkSize); -} +ProcessorXChunks::ProcessorXChunks(const int numStreams, const size_t xChunkSize) { m_impl = new ProcessorXChunksImpl(this, numStreams, xChunkSize); } -ProcessorXChunks::ProcessorXChunks(const int numStreams, const size_t xChunkSize, const size_t vanillaBufferSize) -{ - m_impl = new ProcessorXChunksImpl(this, numStreams, xChunkSize, vanillaBufferSize); +ProcessorXChunks::ProcessorXChunks(const int numStreams, const size_t xChunkSize, const size_t vanillaBufferSize) { + m_impl = new ProcessorXChunksImpl(this, numStreams, xChunkSize, vanillaBufferSize); } -ProcessorXChunks::~ProcessorXChunks() -{ - delete m_impl; - m_impl = nullptr; +ProcessorXChunks::~ProcessorXChunks() { + delete m_impl; + m_impl = nullptr; } -void ProcessorXChunks::AddChunkProcessor(std::unique_ptr<IXChunkProcessor> chunkProcessor) const -{ - m_impl->AddChunkProcessor(std::move(chunkProcessor)); -} +void ProcessorXChunks::AddChunkProcessor(std::unique_ptr<IXChunkProcessor> chunkProcessor) const { m_impl->AddChunkProcessor(std::move(chunkProcessor)); } -size_t ProcessorXChunks::Load(void* buffer, const size_t length) -{ - return m_impl->Load(buffer, length); -} +size_t ProcessorXChunks::Load(void *buffer, const size_t length) { return m_impl->Load(buffer, length); } -int64_t ProcessorXChunks::Pos() -{ - return m_impl->Pos(); -} \ No newline at end of file +int64_t ProcessorXChunks::Pos() { return m_impl->Pos(); } \ No newline at end of file diff --git a/src/ZoneLoading/Loading/Processor/ProcessorXChunks.h b/src/ZoneLoading/Loading/Processor/ProcessorXChunks.h index f3f82e447..1f0045bd0 100644 --- a/src/ZoneLoading/Loading/Processor/ProcessorXChunks.h +++ b/src/ZoneLoading/Loading/Processor/ProcessorXChunks.h @@ -4,18 +4,17 @@ #include "Loading/StreamProcessor.h" #include "Zone/XChunk/IXChunkProcessor.h" -class ProcessorXChunks : public StreamProcessor -{ - class ProcessorXChunksImpl; - ProcessorXChunksImpl* m_impl; +class ProcessorXChunks : public StreamProcessor { + class ProcessorXChunksImpl; + ProcessorXChunksImpl *m_impl; public: - ProcessorXChunks(int numStreams, size_t xChunkSize); - ProcessorXChunks(int numStreams, size_t xChunkSize, size_t vanillaBufferSize); - ~ProcessorXChunks() override; + ProcessorXChunks(int numStreams, size_t xChunkSize); + ProcessorXChunks(int numStreams, size_t xChunkSize, size_t vanillaBufferSize); + ~ProcessorXChunks() override; - size_t Load(void* buffer, size_t length) override; - int64_t Pos() override; + size_t Load(void *buffer, size_t length) override; + int64_t Pos() override; - void AddChunkProcessor(std::unique_ptr<IXChunkProcessor> chunkProcessor) const; + void AddChunkProcessor(std::unique_ptr<IXChunkProcessor> chunkProcessor) const; }; diff --git a/src/ZoneLoading/Loading/Steps/StepAddProcessor.cpp b/src/ZoneLoading/Loading/Steps/StepAddProcessor.cpp index 9c8d23d9f..d046c4676 100644 --- a/src/ZoneLoading/Loading/Steps/StepAddProcessor.cpp +++ b/src/ZoneLoading/Loading/Steps/StepAddProcessor.cpp @@ -1,16 +1,12 @@ #include "StepAddProcessor.h" #include <cassert> -StepAddProcessor::StepAddProcessor(std::unique_ptr<StreamProcessor> streamProcessor) - : m_stream_processor(std::move(streamProcessor)) -{ -} +StepAddProcessor::StepAddProcessor(std::unique_ptr<StreamProcessor> streamProcessor) : m_stream_processor(std::move(streamProcessor)) {} -void StepAddProcessor::PerformStep(ZoneLoader* zoneLoader, ILoadingStream* stream) -{ - assert(zoneLoader != nullptr); - assert(m_stream_processor != nullptr); +void StepAddProcessor::PerformStep(ZoneLoader *zoneLoader, ILoadingStream *stream) { + assert(zoneLoader != nullptr); + assert(m_stream_processor != nullptr); - zoneLoader->AddStreamProcessor(std::move(m_stream_processor)); - m_stream_processor = nullptr; + zoneLoader->AddStreamProcessor(std::move(m_stream_processor)); + m_stream_processor = nullptr; } \ No newline at end of file diff --git a/src/ZoneLoading/Loading/Steps/StepAddProcessor.h b/src/ZoneLoading/Loading/Steps/StepAddProcessor.h index 72bf92b40..cf1512cc5 100644 --- a/src/ZoneLoading/Loading/Steps/StepAddProcessor.h +++ b/src/ZoneLoading/Loading/Steps/StepAddProcessor.h @@ -4,12 +4,11 @@ #include "Loading/ILoadingStep.h" -class StepAddProcessor final : public ILoadingStep -{ - std::unique_ptr<StreamProcessor> m_stream_processor; +class StepAddProcessor final : public ILoadingStep { + std::unique_ptr<StreamProcessor> m_stream_processor; public: - explicit StepAddProcessor(std::unique_ptr<StreamProcessor> streamProcessor); + explicit StepAddProcessor(std::unique_ptr<StreamProcessor> streamProcessor); - void PerformStep(ZoneLoader* zoneLoader, ILoadingStream* stream) override; + void PerformStep(ZoneLoader *zoneLoader, ILoadingStream *stream) override; }; diff --git a/src/ZoneLoading/Loading/Steps/StepAllocXBlocks.cpp b/src/ZoneLoading/Loading/Steps/StepAllocXBlocks.cpp index 52dc7d44f..4776fcd37 100644 --- a/src/ZoneLoading/Loading/Steps/StepAllocXBlocks.cpp +++ b/src/ZoneLoading/Loading/Steps/StepAllocXBlocks.cpp @@ -3,28 +3,24 @@ const uint64_t StepAllocXBlocks::MAX_XBLOCK_SIZE = 0x3C000000; -void StepAllocXBlocks::PerformStep(ZoneLoader* zoneLoader, ILoadingStream* stream) -{ - const unsigned int blockCount = zoneLoader->m_blocks.size(); +void StepAllocXBlocks::PerformStep(ZoneLoader *zoneLoader, ILoadingStream *stream) { + const unsigned int blockCount = zoneLoader->m_blocks.size(); - auto* blockSizes = new xblock_size_t[blockCount]; - stream->Load(blockSizes, sizeof(xblock_size_t) * blockCount); + auto *blockSizes = new xblock_size_t[blockCount]; + stream->Load(blockSizes, sizeof(xblock_size_t) * blockCount); - uint64_t totalMemory = 0; - for(unsigned int block = 0; block < blockCount; block++) - { - totalMemory += blockSizes[block]; - } + uint64_t totalMemory = 0; + for (unsigned int block = 0; block < blockCount; block++) { + totalMemory += blockSizes[block]; + } - if(totalMemory > MAX_XBLOCK_SIZE) - { - throw InvalidXBlockSizeException(totalMemory, MAX_XBLOCK_SIZE); - } + if (totalMemory > MAX_XBLOCK_SIZE) { + throw InvalidXBlockSizeException(totalMemory, MAX_XBLOCK_SIZE); + } - for(unsigned int block = 0; block < blockCount; block++) - { - zoneLoader->m_blocks[block]->Alloc(blockSizes[block]); - } + for (unsigned int block = 0; block < blockCount; block++) { + zoneLoader->m_blocks[block]->Alloc(blockSizes[block]); + } - delete[] blockSizes; + delete[] blockSizes; } \ No newline at end of file diff --git a/src/ZoneLoading/Loading/Steps/StepAllocXBlocks.h b/src/ZoneLoading/Loading/Steps/StepAllocXBlocks.h index 99f1cc3af..48c3dd3c2 100644 --- a/src/ZoneLoading/Loading/Steps/StepAllocXBlocks.h +++ b/src/ZoneLoading/Loading/Steps/StepAllocXBlocks.h @@ -2,10 +2,9 @@ #include "Loading/ILoadingStep.h" -class StepAllocXBlocks final : public ILoadingStep -{ - static const uint64_t MAX_XBLOCK_SIZE; +class StepAllocXBlocks final : public ILoadingStep { + static const uint64_t MAX_XBLOCK_SIZE; public: - void PerformStep(ZoneLoader* zoneLoader, ILoadingStream* stream) override; + void PerformStep(ZoneLoader *zoneLoader, ILoadingStream *stream) override; }; diff --git a/src/ZoneLoading/Loading/Steps/StepDumpData.cpp b/src/ZoneLoading/Loading/Steps/StepDumpData.cpp index 960227efe..af923f1aa 100644 --- a/src/ZoneLoading/Loading/Steps/StepDumpData.cpp +++ b/src/ZoneLoading/Loading/Steps/StepDumpData.cpp @@ -2,39 +2,31 @@ #include <fstream> -StepDumpData::StepDumpData(const unsigned int dumpCount) -{ - m_dump_count = dumpCount; -} - -void StepDumpData::PerformStep(ZoneLoader* zoneLoader, ILoadingStream* stream) -{ - uint8_t tempBuffer[128]; - unsigned int dumpedBytes = 0; - - std::ofstream tempFile("dump.dat", std::fstream::out | std::fstream::binary); - - while (dumpedBytes < m_dump_count) - { - unsigned int toDump; - - if (m_dump_count - dumpedBytes < sizeof(tempBuffer)) - { - toDump = m_dump_count - dumpedBytes; - } - else - { - toDump = sizeof(tempBuffer); - } - - const auto loadedSize = stream->Load(tempBuffer, toDump); - dumpedBytes += loadedSize; - - if (loadedSize == 0) - break; - - tempFile.write(reinterpret_cast<char*>(tempBuffer), loadedSize); +StepDumpData::StepDumpData(const unsigned int dumpCount) { m_dump_count = dumpCount; } + +void StepDumpData::PerformStep(ZoneLoader *zoneLoader, ILoadingStream *stream) { + uint8_t tempBuffer[128]; + unsigned int dumpedBytes = 0; + + std::ofstream tempFile("dump.dat", std::fstream::out | std::fstream::binary); + + while (dumpedBytes < m_dump_count) { + unsigned int toDump; + + if (m_dump_count - dumpedBytes < sizeof(tempBuffer)) { + toDump = m_dump_count - dumpedBytes; + } else { + toDump = sizeof(tempBuffer); } - tempFile.close(); + const auto loadedSize = stream->Load(tempBuffer, toDump); + dumpedBytes += loadedSize; + + if (loadedSize == 0) + break; + + tempFile.write(reinterpret_cast<char *>(tempBuffer), loadedSize); + } + + tempFile.close(); } \ No newline at end of file diff --git a/src/ZoneLoading/Loading/Steps/StepDumpData.h b/src/ZoneLoading/Loading/Steps/StepDumpData.h index 021e73913..1fb4d11de 100644 --- a/src/ZoneLoading/Loading/Steps/StepDumpData.h +++ b/src/ZoneLoading/Loading/Steps/StepDumpData.h @@ -2,12 +2,11 @@ #include "Loading/ILoadingStep.h" -class StepDumpData final : public ILoadingStep -{ - unsigned int m_dump_count; +class StepDumpData final : public ILoadingStep { + unsigned int m_dump_count; public: - explicit StepDumpData(unsigned int dumpCount); + explicit StepDumpData(unsigned int dumpCount); - void PerformStep(ZoneLoader* zoneLoader, ILoadingStream* stream) override; + void PerformStep(ZoneLoader *zoneLoader, ILoadingStream *stream) override; }; \ No newline at end of file diff --git a/src/ZoneLoading/Loading/Steps/StepLoadHash.cpp b/src/ZoneLoading/Loading/Steps/StepLoadHash.cpp index 847f5c5be..b68f0cd92 100644 --- a/src/ZoneLoading/Loading/Steps/StepLoadHash.cpp +++ b/src/ZoneLoading/Loading/Steps/StepLoadHash.cpp @@ -3,40 +3,32 @@ #include <cassert> StepLoadHash::StepLoadHash(const size_t hashSize, const unsigned hashCount) - : m_hash_size(hashSize), - m_hash_count(hashCount), - m_hashes(std::make_unique<uint8_t[]>(hashSize * hashCount)) -{ -} + : m_hash_size(hashSize), m_hash_count(hashCount), m_hashes(std::make_unique<uint8_t[]>(hashSize * hashCount)) {} -StepLoadHash::~StepLoadHash() -= default; +StepLoadHash::~StepLoadHash() = default; -void StepLoadHash::PerformStep(ZoneLoader* zoneLoader, ILoadingStream* stream) -{ - assert(stream != nullptr); +void StepLoadHash::PerformStep(ZoneLoader *zoneLoader, ILoadingStream *stream) { + assert(stream != nullptr); - if (stream->Load(m_hashes.get(), m_hash_size * m_hash_count) != m_hash_size * m_hash_count) - throw UnexpectedEndOfFileException(); + if (stream->Load(m_hashes.get(), m_hash_size * m_hash_count) != m_hash_size * m_hash_count) + throw UnexpectedEndOfFileException(); } -void StepLoadHash::GetHash(const unsigned hashIndex, const uint8_t** pHash, size_t* pSize) -{ - assert(pHash != nullptr); - assert(pSize != nullptr); - assert(hashIndex >= 0 && hashIndex < m_hash_count); +void StepLoadHash::GetHash(const unsigned hashIndex, const uint8_t **pHash, size_t *pSize) { + assert(pHash != nullptr); + assert(pSize != nullptr); + assert(hashIndex >= 0 && hashIndex < m_hash_count); - assert(m_hashes); + assert(m_hashes); - *pHash = &m_hashes[m_hash_size * hashIndex]; - *pSize = m_hash_size; + *pHash = &m_hashes[m_hash_size * hashIndex]; + *pSize = m_hash_size; } -void StepLoadHash::GetCapturedData(const uint8_t** pCapturedData, size_t* pSize) -{ - assert(pCapturedData != nullptr); - assert(pSize != nullptr); - - *pCapturedData = m_hashes.get(); - *pSize = m_hash_size * m_hash_count; +void StepLoadHash::GetCapturedData(const uint8_t **pCapturedData, size_t *pSize) { + assert(pCapturedData != nullptr); + assert(pSize != nullptr); + + *pCapturedData = m_hashes.get(); + *pSize = m_hash_size * m_hash_count; } diff --git a/src/ZoneLoading/Loading/Steps/StepLoadHash.h b/src/ZoneLoading/Loading/Steps/StepLoadHash.h index bc5dbe576..8d0b5c7b7 100644 --- a/src/ZoneLoading/Loading/Steps/StepLoadHash.h +++ b/src/ZoneLoading/Loading/Steps/StepLoadHash.h @@ -2,26 +2,25 @@ #include <memory> -#include "Utils/ICapturedDataProvider.h" -#include "Loading/ILoadingStep.h" #include "Loading/IHashProvider.h" +#include "Loading/ILoadingStep.h" +#include "Utils/ICapturedDataProvider.h" -class StepLoadHash final : public ILoadingStep, public IHashProvider, public ICapturedDataProvider -{ - const size_t m_hash_size; - const unsigned m_hash_count; - std::unique_ptr<uint8_t[]> m_hashes; +class StepLoadHash final : public ILoadingStep, public IHashProvider, public ICapturedDataProvider { + const size_t m_hash_size; + const unsigned m_hash_count; + std::unique_ptr<uint8_t[]> m_hashes; public: - StepLoadHash(size_t hashSize, unsigned hashCount); - ~StepLoadHash() override; + StepLoadHash(size_t hashSize, unsigned hashCount); + ~StepLoadHash() override; - StepLoadHash(const StepLoadHash& other) = delete; - StepLoadHash(StepLoadHash&& other) noexcept = default; - StepLoadHash& operator=(const StepLoadHash& other) = delete; - StepLoadHash& operator=(StepLoadHash&& other) noexcept = delete; + StepLoadHash(const StepLoadHash &other) = delete; + StepLoadHash(StepLoadHash &&other) noexcept = default; + StepLoadHash &operator=(const StepLoadHash &other) = delete; + StepLoadHash &operator=(StepLoadHash &&other) noexcept = delete; - void PerformStep(ZoneLoader* zoneLoader, ILoadingStream* stream) override; - void GetHash(unsigned hashIndex, const uint8_t** pHash, size_t* pSize) override; - void GetCapturedData(const uint8_t** pCapturedData, size_t* pSize) override; + void PerformStep(ZoneLoader *zoneLoader, ILoadingStream *stream) override; + void GetHash(unsigned hashIndex, const uint8_t **pHash, size_t *pSize) override; + void GetCapturedData(const uint8_t **pCapturedData, size_t *pSize) override; }; diff --git a/src/ZoneLoading/Loading/Steps/StepLoadSignature.cpp b/src/ZoneLoading/Loading/Steps/StepLoadSignature.cpp index beae7ef15..b506de42d 100644 --- a/src/ZoneLoading/Loading/Steps/StepLoadSignature.cpp +++ b/src/ZoneLoading/Loading/Steps/StepLoadSignature.cpp @@ -2,33 +2,29 @@ #include "Loading/Exception/UnexpectedEndOfFileException.h" #include <cassert> -StepLoadSignature::StepLoadSignature(const size_t signatureSize) -{ - m_signature_size = signatureSize; - m_signature = new uint8_t[signatureSize]; +StepLoadSignature::StepLoadSignature(const size_t signatureSize) { + m_signature_size = signatureSize; + m_signature = new uint8_t[signatureSize]; } -StepLoadSignature::~StepLoadSignature() -{ - delete[] m_signature; - m_signature = nullptr; +StepLoadSignature::~StepLoadSignature() { + delete[] m_signature; + m_signature = nullptr; } -void StepLoadSignature::PerformStep(ZoneLoader* zoneLoader, ILoadingStream* stream) -{ - assert(stream != nullptr); - - if(stream->Load(m_signature, m_signature_size) != m_signature_size) - throw UnexpectedEndOfFileException(); +void StepLoadSignature::PerformStep(ZoneLoader *zoneLoader, ILoadingStream *stream) { + assert(stream != nullptr); + + if (stream->Load(m_signature, m_signature_size) != m_signature_size) + throw UnexpectedEndOfFileException(); } -void StepLoadSignature::GetSignature(const uint8_t** pSignature, size_t* pSize) -{ - assert(pSignature != nullptr); - assert(pSize != nullptr); +void StepLoadSignature::GetSignature(const uint8_t **pSignature, size_t *pSize) { + assert(pSignature != nullptr); + assert(pSize != nullptr); - assert(m_signature != nullptr); + assert(m_signature != nullptr); - *pSignature = m_signature; - *pSize = m_signature_size; + *pSignature = m_signature; + *pSize = m_signature_size; } \ No newline at end of file diff --git a/src/ZoneLoading/Loading/Steps/StepLoadSignature.h b/src/ZoneLoading/Loading/Steps/StepLoadSignature.h index 822653ce5..88b18416e 100644 --- a/src/ZoneLoading/Loading/Steps/StepLoadSignature.h +++ b/src/ZoneLoading/Loading/Steps/StepLoadSignature.h @@ -3,15 +3,14 @@ #include "Loading/ILoadingStep.h" #include "Loading/ISignatureProvider.h" -class StepLoadSignature final : public ILoadingStep, public ISignatureProvider -{ - uint8_t* m_signature; - size_t m_signature_size; +class StepLoadSignature final : public ILoadingStep, public ISignatureProvider { + uint8_t *m_signature; + size_t m_signature_size; public: - explicit StepLoadSignature(size_t signatureSize); - ~StepLoadSignature() override; + explicit StepLoadSignature(size_t signatureSize); + ~StepLoadSignature() override; - void PerformStep(ZoneLoader* zoneLoader, ILoadingStream* stream) override; - void GetSignature(const uint8_t** pSignature, size_t* pSize) override; + void PerformStep(ZoneLoader *zoneLoader, ILoadingStream *stream) override; + void GetSignature(const uint8_t **pSignature, size_t *pSize) override; }; diff --git a/src/ZoneLoading/Loading/Steps/StepLoadZoneContent.cpp b/src/ZoneLoading/Loading/Steps/StepLoadZoneContent.cpp index 16360fe6a..78ad64288 100644 --- a/src/ZoneLoading/Loading/Steps/StepLoadZoneContent.cpp +++ b/src/ZoneLoading/Loading/Steps/StepLoadZoneContent.cpp @@ -2,19 +2,14 @@ #include "Zone/Stream/Impl/XBlockInputStream.h" #include <cassert> -StepLoadZoneContent::StepLoadZoneContent(std::unique_ptr<IContentLoadingEntryPoint> entryPoint, Zone* zone, const int offsetBlockBitCount, const block_t insertBlock) - : m_content_loader(std::move(entryPoint)), - m_zone(zone), - m_offset_block_bit_count(offsetBlockBitCount), - m_insert_block(insertBlock) -{ -} +StepLoadZoneContent::StepLoadZoneContent(std::unique_ptr<IContentLoadingEntryPoint> entryPoint, Zone *zone, const int offsetBlockBitCount, + const block_t insertBlock) + : m_content_loader(std::move(entryPoint)), m_zone(zone), m_offset_block_bit_count(offsetBlockBitCount), m_insert_block(insertBlock) {} -void StepLoadZoneContent::PerformStep(ZoneLoader* zoneLoader, ILoadingStream* stream) -{ - auto* inputStream = new XBlockInputStream(zoneLoader->m_blocks, stream, m_offset_block_bit_count, m_insert_block); +void StepLoadZoneContent::PerformStep(ZoneLoader *zoneLoader, ILoadingStream *stream) { + auto *inputStream = new XBlockInputStream(zoneLoader->m_blocks, stream, m_offset_block_bit_count, m_insert_block); - m_content_loader->Load(m_zone, inputStream); + m_content_loader->Load(m_zone, inputStream); - delete inputStream; + delete inputStream; } diff --git a/src/ZoneLoading/Loading/Steps/StepLoadZoneContent.h b/src/ZoneLoading/Loading/Steps/StepLoadZoneContent.h index d0c5bcbeb..17ab76430 100644 --- a/src/ZoneLoading/Loading/Steps/StepLoadZoneContent.h +++ b/src/ZoneLoading/Loading/Steps/StepLoadZoneContent.h @@ -2,18 +2,17 @@ #include <memory> -#include "Loading/ILoadingStep.h" #include "Loading/IContentLoadingEntryPoint.h" +#include "Loading/ILoadingStep.h" -class StepLoadZoneContent final : public ILoadingStep -{ - std::unique_ptr<IContentLoadingEntryPoint> m_content_loader; - Zone* m_zone; - int m_offset_block_bit_count; - block_t m_insert_block; +class StepLoadZoneContent final : public ILoadingStep { + std::unique_ptr<IContentLoadingEntryPoint> m_content_loader; + Zone *m_zone; + int m_offset_block_bit_count; + block_t m_insert_block; public: - StepLoadZoneContent(std::unique_ptr<IContentLoadingEntryPoint> entryPoint, Zone* zone, int offsetBlockBitCount, block_t insertBlock); + StepLoadZoneContent(std::unique_ptr<IContentLoadingEntryPoint> entryPoint, Zone *zone, int offsetBlockBitCount, block_t insertBlock); - void PerformStep(ZoneLoader* zoneLoader, ILoadingStream* stream) override; + void PerformStep(ZoneLoader *zoneLoader, ILoadingStream *stream) override; }; diff --git a/src/ZoneLoading/Loading/Steps/StepLoadZoneSizes.cpp b/src/ZoneLoading/Loading/Steps/StepLoadZoneSizes.cpp index b9cd87e60..d7e479b66 100644 --- a/src/ZoneLoading/Loading/Steps/StepLoadZoneSizes.cpp +++ b/src/ZoneLoading/Loading/Steps/StepLoadZoneSizes.cpp @@ -1,23 +1,12 @@ #include "StepLoadZoneSizes.h" -StepLoadZoneSizes::StepLoadZoneSizes() - : m_size(0), - m_external_size(0) -{ -} +StepLoadZoneSizes::StepLoadZoneSizes() : m_size(0), m_external_size(0) {} -void StepLoadZoneSizes::PerformStep(ZoneLoader* zoneLoader, ILoadingStream* stream) -{ - stream->Load(&m_size, sizeof(m_size)); - stream->Load(&m_external_size, sizeof(m_external_size)); +void StepLoadZoneSizes::PerformStep(ZoneLoader *zoneLoader, ILoadingStream *stream) { + stream->Load(&m_size, sizeof(m_size)); + stream->Load(&m_external_size, sizeof(m_external_size)); } -size_t StepLoadZoneSizes::GetSize() const -{ - return m_size; -} +size_t StepLoadZoneSizes::GetSize() const { return m_size; } -size_t StepLoadZoneSizes::GetExternalSize() const -{ - return m_external_size; -} +size_t StepLoadZoneSizes::GetExternalSize() const { return m_external_size; } diff --git a/src/ZoneLoading/Loading/Steps/StepLoadZoneSizes.h b/src/ZoneLoading/Loading/Steps/StepLoadZoneSizes.h index eac0c3cb2..af5a007b9 100644 --- a/src/ZoneLoading/Loading/Steps/StepLoadZoneSizes.h +++ b/src/ZoneLoading/Loading/Steps/StepLoadZoneSizes.h @@ -2,19 +2,18 @@ #include <cstddef> -#include "Utils/ClassUtils.h" #include "Loading/ILoadingStep.h" +#include "Utils/ClassUtils.h" -class StepLoadZoneSizes final : public ILoadingStep -{ - size_t m_size; - size_t m_external_size; +class StepLoadZoneSizes final : public ILoadingStep { + size_t m_size; + size_t m_external_size; public: - StepLoadZoneSizes(); + StepLoadZoneSizes(); - void PerformStep(ZoneLoader* zoneLoader, ILoadingStream* stream) override; + void PerformStep(ZoneLoader *zoneLoader, ILoadingStream *stream) override; - _NODISCARD size_t GetSize() const; - _NODISCARD size_t GetExternalSize() const; + _NODISCARD size_t GetSize() const; + _NODISCARD size_t GetExternalSize() const; }; diff --git a/src/ZoneLoading/Loading/Steps/StepRemoveProcessor.cpp b/src/ZoneLoading/Loading/Steps/StepRemoveProcessor.cpp index 343bce187..3c87a3519 100644 --- a/src/ZoneLoading/Loading/Steps/StepRemoveProcessor.cpp +++ b/src/ZoneLoading/Loading/Steps/StepRemoveProcessor.cpp @@ -1,15 +1,11 @@ #include "StepRemoveProcessor.h" #include <cassert> -StepRemoveProcessor::StepRemoveProcessor(StreamProcessor* streamProcessor) - : m_stream_processor(streamProcessor) -{ -} +StepRemoveProcessor::StepRemoveProcessor(StreamProcessor *streamProcessor) : m_stream_processor(streamProcessor) {} -void StepRemoveProcessor::PerformStep(ZoneLoader* zoneLoader, ILoadingStream* stream) -{ - assert(zoneLoader != nullptr); - assert(m_stream_processor != nullptr); +void StepRemoveProcessor::PerformStep(ZoneLoader *zoneLoader, ILoadingStream *stream) { + assert(zoneLoader != nullptr); + assert(m_stream_processor != nullptr); - zoneLoader->RemoveStreamProcessor(m_stream_processor); + zoneLoader->RemoveStreamProcessor(m_stream_processor); } diff --git a/src/ZoneLoading/Loading/Steps/StepRemoveProcessor.h b/src/ZoneLoading/Loading/Steps/StepRemoveProcessor.h index 8049bad55..5644ee51f 100644 --- a/src/ZoneLoading/Loading/Steps/StepRemoveProcessor.h +++ b/src/ZoneLoading/Loading/Steps/StepRemoveProcessor.h @@ -2,12 +2,11 @@ #include "Loading/ILoadingStep.h" -class StepRemoveProcessor final : public ILoadingStep -{ - StreamProcessor* m_stream_processor; +class StepRemoveProcessor final : public ILoadingStep { + StreamProcessor *m_stream_processor; public: - explicit StepRemoveProcessor(StreamProcessor* streamProcessor); + explicit StepRemoveProcessor(StreamProcessor *streamProcessor); - void PerformStep(ZoneLoader* zoneLoader, ILoadingStream* stream) override; + void PerformStep(ZoneLoader *zoneLoader, ILoadingStream *stream) override; }; diff --git a/src/ZoneLoading/Loading/Steps/StepSkipBytes.cpp b/src/ZoneLoading/Loading/Steps/StepSkipBytes.cpp index f2849c231..975198a45 100644 --- a/src/ZoneLoading/Loading/Steps/StepSkipBytes.cpp +++ b/src/ZoneLoading/Loading/Steps/StepSkipBytes.cpp @@ -1,30 +1,22 @@ #include "StepSkipBytes.h" -StepSkipBytes::StepSkipBytes(const unsigned int skipCount) -{ - m_skip_count = skipCount; -} +StepSkipBytes::StepSkipBytes(const unsigned int skipCount) { m_skip_count = skipCount; } -void StepSkipBytes::PerformStep(ZoneLoader* zoneLoader, ILoadingStream* stream) -{ - uint8_t tempBuffer[128]; - unsigned int skippedBytes = 0; +void StepSkipBytes::PerformStep(ZoneLoader *zoneLoader, ILoadingStream *stream) { + uint8_t tempBuffer[128]; + unsigned int skippedBytes = 0; - while(skippedBytes < m_skip_count) - { - unsigned int toSkip; + while (skippedBytes < m_skip_count) { + unsigned int toSkip; - if(m_skip_count - skippedBytes < sizeof(tempBuffer)) - { - toSkip = m_skip_count - skippedBytes; - } - else - { - toSkip = sizeof(tempBuffer); - } + if (m_skip_count - skippedBytes < sizeof(tempBuffer)) { + toSkip = m_skip_count - skippedBytes; + } else { + toSkip = sizeof(tempBuffer); + } - stream->Load(tempBuffer, toSkip); + stream->Load(tempBuffer, toSkip); - skippedBytes += toSkip; - } + skippedBytes += toSkip; + } } \ No newline at end of file diff --git a/src/ZoneLoading/Loading/Steps/StepSkipBytes.h b/src/ZoneLoading/Loading/Steps/StepSkipBytes.h index 2166f8757..a2631f4e2 100644 --- a/src/ZoneLoading/Loading/Steps/StepSkipBytes.h +++ b/src/ZoneLoading/Loading/Steps/StepSkipBytes.h @@ -2,12 +2,11 @@ #include "Loading/ILoadingStep.h" -class StepSkipBytes final : public ILoadingStep -{ - unsigned int m_skip_count; +class StepSkipBytes final : public ILoadingStep { + unsigned int m_skip_count; public: - explicit StepSkipBytes(unsigned int skipCount); + explicit StepSkipBytes(unsigned int skipCount); - void PerformStep(ZoneLoader* zoneLoader, ILoadingStream* stream) override; + void PerformStep(ZoneLoader *zoneLoader, ILoadingStream *stream) override; }; \ No newline at end of file diff --git a/src/ZoneLoading/Loading/Steps/StepVerifyFileName.cpp b/src/ZoneLoading/Loading/Steps/StepVerifyFileName.cpp index 3f633f633..9dfeb8c90 100644 --- a/src/ZoneLoading/Loading/Steps/StepVerifyFileName.cpp +++ b/src/ZoneLoading/Loading/Steps/StepVerifyFileName.cpp @@ -4,44 +4,39 @@ #include "Loading/Exception/InvalidFileNameException.h" -StepVerifyFileName::StepVerifyFileName(std::string fileName, const size_t fileNameBufferSize) -{ - m_file_name = std::move(fileName); - m_file_name_buffer_size = fileNameBufferSize; +StepVerifyFileName::StepVerifyFileName(std::string fileName, const size_t fileNameBufferSize) { + m_file_name = std::move(fileName); + m_file_name_buffer_size = fileNameBufferSize; - if(m_file_name.length() > m_file_name_buffer_size) - m_file_name.erase(m_file_name_buffer_size); + if (m_file_name.length() > m_file_name_buffer_size) + m_file_name.erase(m_file_name_buffer_size); } -void StepVerifyFileName::PerformStep(ZoneLoader* zoneLoader, ILoadingStream* stream) -{ - std::stringstream originalFilenameStream; - unsigned bufferOffset = 0; - char c; +void StepVerifyFileName::PerformStep(ZoneLoader *zoneLoader, ILoadingStream *stream) { + std::stringstream originalFilenameStream; + unsigned bufferOffset = 0; + char c; - for(; bufferOffset < m_file_name_buffer_size; bufferOffset++) - { + for (; bufferOffset < m_file_name_buffer_size; bufferOffset++) { - stream->Load(&c, sizeof(char)); + stream->Load(&c, sizeof(char)); - if(c == '\00') - { - bufferOffset++; - break; - } - - originalFilenameStream << c; + if (c == '\00') { + bufferOffset++; + break; } - // Skip the rest of the buffer which should be null bytes - while(bufferOffset < m_file_name_buffer_size) - { - stream->Load(&c, sizeof(char)); - bufferOffset++; - } + originalFilenameStream << c; + } + + // Skip the rest of the buffer which should be null bytes + while (bufferOffset < m_file_name_buffer_size) { + stream->Load(&c, sizeof(char)); + bufferOffset++; + } - std::string originalFileName = originalFilenameStream.str(); + std::string originalFileName = originalFilenameStream.str(); - if(originalFileName != m_file_name) - throw InvalidFileNameException(m_file_name, originalFileName); + if (originalFileName != m_file_name) + throw InvalidFileNameException(m_file_name, originalFileName); } \ No newline at end of file diff --git a/src/ZoneLoading/Loading/Steps/StepVerifyFileName.h b/src/ZoneLoading/Loading/Steps/StepVerifyFileName.h index be9447ebe..6ba91ef0c 100644 --- a/src/ZoneLoading/Loading/Steps/StepVerifyFileName.h +++ b/src/ZoneLoading/Loading/Steps/StepVerifyFileName.h @@ -2,13 +2,12 @@ #include "Loading/ILoadingStep.h" -class StepVerifyFileName final : public ILoadingStep -{ - std::string m_file_name; - size_t m_file_name_buffer_size; +class StepVerifyFileName final : public ILoadingStep { + std::string m_file_name; + size_t m_file_name_buffer_size; public: - explicit StepVerifyFileName(std::string fileName, size_t fileNameBufferSize); + explicit StepVerifyFileName(std::string fileName, size_t fileNameBufferSize); - void PerformStep(ZoneLoader* zoneLoader, ILoadingStream* stream) override; + void PerformStep(ZoneLoader *zoneLoader, ILoadingStream *stream) override; }; \ No newline at end of file diff --git a/src/ZoneLoading/Loading/Steps/StepVerifyHash.cpp b/src/ZoneLoading/Loading/Steps/StepVerifyHash.cpp index 55936d08e..2a146fd2b 100644 --- a/src/ZoneLoading/Loading/Steps/StepVerifyHash.cpp +++ b/src/ZoneLoading/Loading/Steps/StepVerifyHash.cpp @@ -1,40 +1,33 @@ #include "StepVerifyHash.h" -#include <memory> #include <cstring> +#include <memory> #include "Loading/Exception/InvalidHashException.h" -StepVerifyHash::StepVerifyHash(std::unique_ptr<IHashFunction> hashFunction, const unsigned hashIndex, IHashProvider* hashProvider, - ICapturedDataProvider* dataProvider) - : m_hash_function(std::move(hashFunction)), - m_hash_index(hashIndex), - m_hash_provider(hashProvider), - m_data_provider(dataProvider) -{ -} +StepVerifyHash::StepVerifyHash(std::unique_ptr<IHashFunction> hashFunction, const unsigned hashIndex, IHashProvider *hashProvider, + ICapturedDataProvider *dataProvider) + : m_hash_function(std::move(hashFunction)), m_hash_index(hashIndex), m_hash_provider(hashProvider), m_data_provider(dataProvider) {} -StepVerifyHash::~StepVerifyHash() -= default; +StepVerifyHash::~StepVerifyHash() = default; -void StepVerifyHash::PerformStep(ZoneLoader* zoneLoader, ILoadingStream* stream) -{ - const uint8_t* dataToHash = nullptr; - size_t dataToHashSize = 0; - m_data_provider->GetCapturedData(&dataToHash, &dataToHashSize); +void StepVerifyHash::PerformStep(ZoneLoader *zoneLoader, ILoadingStream *stream) { + const uint8_t *dataToHash = nullptr; + size_t dataToHashSize = 0; + m_data_provider->GetCapturedData(&dataToHash, &dataToHashSize); - const uint8_t* hashData = nullptr; - size_t hashSize = 0; - m_hash_provider->GetHash(m_hash_index, &hashData, &hashSize); + const uint8_t *hashData = nullptr; + size_t hashSize = 0; + m_hash_provider->GetHash(m_hash_index, &hashData, &hashSize); - if (hashSize != m_hash_function->GetHashSize()) - throw InvalidHashException(); + if (hashSize != m_hash_function->GetHashSize()) + throw InvalidHashException(); - const std::unique_ptr<uint8_t[]> hashMemory = std::make_unique<uint8_t[]>(m_hash_function->GetHashSize()); - m_hash_function->Init(); - m_hash_function->Process(dataToHash, dataToHashSize); - m_hash_function->Finish(hashMemory.get()); + const std::unique_ptr<uint8_t[]> hashMemory = std::make_unique<uint8_t[]>(m_hash_function->GetHashSize()); + m_hash_function->Init(); + m_hash_function->Process(dataToHash, dataToHashSize); + m_hash_function->Finish(hashMemory.get()); - if(std::memcmp(hashData, hashMemory.get(), m_hash_function->GetHashSize()) != 0) - throw InvalidHashException(); + if (std::memcmp(hashData, hashMemory.get(), m_hash_function->GetHashSize()) != 0) + throw InvalidHashException(); } diff --git a/src/ZoneLoading/Loading/Steps/StepVerifyHash.h b/src/ZoneLoading/Loading/Steps/StepVerifyHash.h index bc3bcb7b9..588eaf7c9 100644 --- a/src/ZoneLoading/Loading/Steps/StepVerifyHash.h +++ b/src/ZoneLoading/Loading/Steps/StepVerifyHash.h @@ -3,24 +3,23 @@ #include <memory> #include "Crypto.h" +#include "Loading/IHashProvider.h" #include "Loading/ILoadingStep.h" #include "Utils/ICapturedDataProvider.h" -#include "Loading/IHashProvider.h" -class StepVerifyHash final : public ILoadingStep -{ - std::unique_ptr<IHashFunction> m_hash_function; - unsigned m_hash_index; - IHashProvider* m_hash_provider; - ICapturedDataProvider* m_data_provider; +class StepVerifyHash final : public ILoadingStep { + std::unique_ptr<IHashFunction> m_hash_function; + unsigned m_hash_index; + IHashProvider *m_hash_provider; + ICapturedDataProvider *m_data_provider; public: - StepVerifyHash(std::unique_ptr<IHashFunction> hashFunction, unsigned hashIndex, IHashProvider* hashProvider, ICapturedDataProvider* dataProvider); - ~StepVerifyHash(); - StepVerifyHash(const StepVerifyHash& other) = delete; - StepVerifyHash(StepVerifyHash&& other) noexcept = default; - StepVerifyHash& operator=(const StepVerifyHash& other) = delete; - StepVerifyHash& operator=(StepVerifyHash&& other) noexcept = default; + StepVerifyHash(std::unique_ptr<IHashFunction> hashFunction, unsigned hashIndex, IHashProvider *hashProvider, ICapturedDataProvider *dataProvider); + ~StepVerifyHash(); + StepVerifyHash(const StepVerifyHash &other) = delete; + StepVerifyHash(StepVerifyHash &&other) noexcept = default; + StepVerifyHash &operator=(const StepVerifyHash &other) = delete; + StepVerifyHash &operator=(StepVerifyHash &&other) noexcept = default; - void PerformStep(ZoneLoader* zoneLoader, ILoadingStream* stream) override; + void PerformStep(ZoneLoader *zoneLoader, ILoadingStream *stream) override; }; diff --git a/src/ZoneLoading/Loading/Steps/StepVerifyMagic.cpp b/src/ZoneLoading/Loading/Steps/StepVerifyMagic.cpp index 4e9b13cd7..96bbb2133 100644 --- a/src/ZoneLoading/Loading/Steps/StepVerifyMagic.cpp +++ b/src/ZoneLoading/Loading/Steps/StepVerifyMagic.cpp @@ -4,21 +4,18 @@ #include "Loading/Exception/InvalidMagicException.h" -StepVerifyMagic::StepVerifyMagic(const char* magic) -{ - m_magic = magic; - m_magic_len = strlen(m_magic); +StepVerifyMagic::StepVerifyMagic(const char *magic) { + m_magic = magic; + m_magic_len = strlen(m_magic); } -void StepVerifyMagic::PerformStep(ZoneLoader* zoneLoader, ILoadingStream* stream) -{ - char currentCharacter; +void StepVerifyMagic::PerformStep(ZoneLoader *zoneLoader, ILoadingStream *stream) { + char currentCharacter; - for(unsigned i = 0; i < m_magic_len; i++) - { - stream->Load(¤tCharacter, sizeof(char)); + for (unsigned i = 0; i < m_magic_len; i++) { + stream->Load(¤tCharacter, sizeof(char)); - if(currentCharacter != m_magic[i]) - throw InvalidMagicException(m_magic); - } + if (currentCharacter != m_magic[i]) + throw InvalidMagicException(m_magic); + } } \ No newline at end of file diff --git a/src/ZoneLoading/Loading/Steps/StepVerifyMagic.h b/src/ZoneLoading/Loading/Steps/StepVerifyMagic.h index 3fa35bd82..c21bb996b 100644 --- a/src/ZoneLoading/Loading/Steps/StepVerifyMagic.h +++ b/src/ZoneLoading/Loading/Steps/StepVerifyMagic.h @@ -2,13 +2,12 @@ #include "Loading/ILoadingStep.h" -class StepVerifyMagic final : public ILoadingStep -{ - const char* m_magic; - size_t m_magic_len; +class StepVerifyMagic final : public ILoadingStep { + const char *m_magic; + size_t m_magic_len; public: - explicit StepVerifyMagic(const char* magic); + explicit StepVerifyMagic(const char *magic); - void PerformStep(ZoneLoader* zoneLoader, ILoadingStream* stream) override; + void PerformStep(ZoneLoader *zoneLoader, ILoadingStream *stream) override; }; \ No newline at end of file diff --git a/src/ZoneLoading/Loading/Steps/StepVerifySignature.cpp b/src/ZoneLoading/Loading/Steps/StepVerifySignature.cpp index 728240823..9ad8ff119 100644 --- a/src/ZoneLoading/Loading/Steps/StepVerifySignature.cpp +++ b/src/ZoneLoading/Loading/Steps/StepVerifySignature.cpp @@ -2,29 +2,24 @@ #include "Loading/Exception/InvalidSignatureException.h" #include <cassert> -StepVerifySignature::StepVerifySignature(std::unique_ptr<IPublicKeyAlgorithm> signatureAlgorithm, ISignatureProvider* signatureProvider, ICapturedDataProvider* signatureDataProvider) - : m_algorithm(std::move(signatureAlgorithm)), - m_signature_provider(signatureProvider), - m_signature_data_provider(signatureDataProvider) -{ -} +StepVerifySignature::StepVerifySignature(std::unique_ptr<IPublicKeyAlgorithm> signatureAlgorithm, ISignatureProvider *signatureProvider, + ICapturedDataProvider *signatureDataProvider) + : m_algorithm(std::move(signatureAlgorithm)), m_signature_provider(signatureProvider), m_signature_data_provider(signatureDataProvider) {} -void StepVerifySignature::PerformStep(ZoneLoader* zoneLoader, ILoadingStream* stream) -{ - assert(m_algorithm != nullptr); - assert(m_signature_provider != nullptr); - assert(m_signature_data_provider != nullptr); +void StepVerifySignature::PerformStep(ZoneLoader *zoneLoader, ILoadingStream *stream) { + assert(m_algorithm != nullptr); + assert(m_signature_provider != nullptr); + assert(m_signature_data_provider != nullptr); - const uint8_t* signature; - size_t signatureSize; - m_signature_provider->GetSignature(&signature, &signatureSize); + const uint8_t *signature; + size_t signatureSize; + m_signature_provider->GetSignature(&signature, &signatureSize); - const uint8_t* signatureData; - size_t signatureDataSize; - m_signature_data_provider->GetCapturedData(&signatureData, &signatureDataSize); + const uint8_t *signatureData; + size_t signatureDataSize; + m_signature_data_provider->GetCapturedData(&signatureData, &signatureDataSize); - if (!m_algorithm->Verify(signatureData, signatureDataSize, signature, signatureSize)) - { - throw InvalidSignatureException(); - } + if (!m_algorithm->Verify(signatureData, signatureDataSize, signature, signatureSize)) { + throw InvalidSignatureException(); + } } diff --git a/src/ZoneLoading/Loading/Steps/StepVerifySignature.h b/src/ZoneLoading/Loading/Steps/StepVerifySignature.h index 2beb0d39c..ebd55c5da 100644 --- a/src/ZoneLoading/Loading/Steps/StepVerifySignature.h +++ b/src/ZoneLoading/Loading/Steps/StepVerifySignature.h @@ -1,23 +1,23 @@ #pragma once -#include "Loading/ILoadingStep.h" #include "Crypto.h" +#include "Loading/ILoadingStep.h" #include "Loading/ISignatureProvider.h" #include "Utils/ICapturedDataProvider.h" -class StepVerifySignature final : public ILoadingStep -{ - std::unique_ptr<IPublicKeyAlgorithm> m_algorithm; - ISignatureProvider* m_signature_provider; - ICapturedDataProvider* m_signature_data_provider; +class StepVerifySignature final : public ILoadingStep { + std::unique_ptr<IPublicKeyAlgorithm> m_algorithm; + ISignatureProvider *m_signature_provider; + ICapturedDataProvider *m_signature_data_provider; public: - StepVerifySignature(std::unique_ptr<IPublicKeyAlgorithm> signatureAlgorithm, ISignatureProvider* signatureProvider, ICapturedDataProvider* signatureDataProvider); - ~StepVerifySignature() override = default; - StepVerifySignature(const StepVerifySignature& other) = delete; - StepVerifySignature(StepVerifySignature&& other) noexcept = default; - StepVerifySignature& operator=(const StepVerifySignature& other) = delete; - StepVerifySignature& operator=(StepVerifySignature&& other) noexcept = default; + StepVerifySignature(std::unique_ptr<IPublicKeyAlgorithm> signatureAlgorithm, ISignatureProvider *signatureProvider, + ICapturedDataProvider *signatureDataProvider); + ~StepVerifySignature() override = default; + StepVerifySignature(const StepVerifySignature &other) = delete; + StepVerifySignature(StepVerifySignature &&other) noexcept = default; + StepVerifySignature &operator=(const StepVerifySignature &other) = delete; + StepVerifySignature &operator=(StepVerifySignature &&other) noexcept = default; - void PerformStep(ZoneLoader* zoneLoader, ILoadingStream* stream) override; + void PerformStep(ZoneLoader *zoneLoader, ILoadingStream *stream) override; }; \ No newline at end of file diff --git a/src/ZoneLoading/Loading/StreamProcessor.cpp b/src/ZoneLoading/Loading/StreamProcessor.cpp index d6d4daf1f..d14ff3682 100644 --- a/src/ZoneLoading/Loading/StreamProcessor.cpp +++ b/src/ZoneLoading/Loading/StreamProcessor.cpp @@ -1,11 +1,5 @@ #include "StreamProcessor.h" -StreamProcessor::StreamProcessor() -{ - m_base_stream = nullptr; -} +StreamProcessor::StreamProcessor() { m_base_stream = nullptr; } -void StreamProcessor::SetBaseStream(ILoadingStream* baseStream) -{ - m_base_stream = baseStream; -} \ No newline at end of file +void StreamProcessor::SetBaseStream(ILoadingStream *baseStream) { m_base_stream = baseStream; } \ No newline at end of file diff --git a/src/ZoneLoading/Loading/StreamProcessor.h b/src/ZoneLoading/Loading/StreamProcessor.h index d37027776..ad295c6f9 100644 --- a/src/ZoneLoading/Loading/StreamProcessor.h +++ b/src/ZoneLoading/Loading/StreamProcessor.h @@ -2,13 +2,12 @@ #include "ILoadingStream.h" -class StreamProcessor : public ILoadingStream -{ +class StreamProcessor : public ILoadingStream { protected: - ILoadingStream* m_base_stream; + ILoadingStream *m_base_stream; public: - StreamProcessor(); + StreamProcessor(); - void SetBaseStream(ILoadingStream* baseStream); + void SetBaseStream(ILoadingStream *baseStream); }; diff --git a/src/ZoneLoading/Loading/ZoneLoader.cpp b/src/ZoneLoading/Loading/ZoneLoader.cpp index 22e407485..b1ce12d5c 100644 --- a/src/ZoneLoading/Loading/ZoneLoader.cpp +++ b/src/ZoneLoading/Loading/ZoneLoader.cpp @@ -5,89 +5,66 @@ #include "Exception/LoadingException.h" #include "LoadingFileStream.h" -ZoneLoader::ZoneLoader(std::unique_ptr<Zone> zone) - : m_processor_chain_dirty(false), - m_zone(std::move(zone)) -{ -} +ZoneLoader::ZoneLoader(std::unique_ptr<Zone> zone) : m_processor_chain_dirty(false), m_zone(std::move(zone)) {} -ILoadingStream* ZoneLoader::BuildLoadingChain(ILoadingStream* rootStream) -{ - auto* currentStream = rootStream; +ILoadingStream *ZoneLoader::BuildLoadingChain(ILoadingStream *rootStream) { + auto *currentStream = rootStream; - for (const auto& processor : m_processors) - { - processor->SetBaseStream(currentStream); + for (const auto &processor : m_processors) { + processor->SetBaseStream(currentStream); - currentStream = processor.get(); - } + currentStream = processor.get(); + } - m_processor_chain_dirty = false; - return currentStream; + m_processor_chain_dirty = false; + return currentStream; } -void ZoneLoader::AddXBlock(std::unique_ptr<XBlock> block) -{ - m_blocks.push_back(block.get()); +void ZoneLoader::AddXBlock(std::unique_ptr<XBlock> block) { + m_blocks.push_back(block.get()); - std::sort(m_blocks.begin(), m_blocks.end(), [](XBlock* b1, XBlock* b2) -> bool - { - return b1->m_index < b2->m_index; - }); + std::sort(m_blocks.begin(), m_blocks.end(), [](XBlock *b1, XBlock *b2) -> bool { return b1->m_index < b2->m_index; }); - m_zone->GetMemory()->AddBlock(std::move(block)); + m_zone->GetMemory()->AddBlock(std::move(block)); } -void ZoneLoader::AddLoadingStep(std::unique_ptr<ILoadingStep> step) -{ - m_steps.emplace_back(std::move(step)); -} +void ZoneLoader::AddLoadingStep(std::unique_ptr<ILoadingStep> step) { m_steps.emplace_back(std::move(step)); } -void ZoneLoader::AddStreamProcessor(std::unique_ptr<StreamProcessor> streamProcessor) -{ - m_processors.push_back(std::move(streamProcessor)); - m_processor_chain_dirty = true; +void ZoneLoader::AddStreamProcessor(std::unique_ptr<StreamProcessor> streamProcessor) { + m_processors.push_back(std::move(streamProcessor)); + m_processor_chain_dirty = true; } -void ZoneLoader::RemoveStreamProcessor(StreamProcessor* streamProcessor) -{ - for (auto i = m_processors.begin(); i < m_processors.end(); ++i) - { - if (i->get() == streamProcessor) - { - m_processors.erase(i); - m_processor_chain_dirty = true; - break; - } +void ZoneLoader::RemoveStreamProcessor(StreamProcessor *streamProcessor) { + for (auto i = m_processors.begin(); i < m_processors.end(); ++i) { + if (i->get() == streamProcessor) { + m_processors.erase(i); + m_processor_chain_dirty = true; + break; } + } } -std::unique_ptr<Zone> ZoneLoader::LoadZone(std::istream& stream) -{ - LoadingFileStream fileStream(stream); - auto* endStream = BuildLoadingChain(&fileStream); - - try - { - for (const auto& step : m_steps) - { - step->PerformStep(this, endStream); - - if (m_processor_chain_dirty) - { - endStream = BuildLoadingChain(&fileStream); - } - } - } - catch (LoadingException& e) - { - const auto detailedMessage = e.DetailedMessage(); - printf("Loading fastfile failed: %s\n", detailedMessage.c_str()); +std::unique_ptr<Zone> ZoneLoader::LoadZone(std::istream &stream) { + LoadingFileStream fileStream(stream); + auto *endStream = BuildLoadingChain(&fileStream); + + try { + for (const auto &step : m_steps) { + step->PerformStep(this, endStream); - return nullptr; + if (m_processor_chain_dirty) { + endStream = BuildLoadingChain(&fileStream); + } } + } catch (LoadingException &e) { + const auto detailedMessage = e.DetailedMessage(); + printf("Loading fastfile failed: %s\n", detailedMessage.c_str()); + + return nullptr; + } - m_zone->Register(); + m_zone->Register(); - return std::move(m_zone); + return std::move(m_zone); } diff --git a/src/ZoneLoading/Loading/ZoneLoader.h b/src/ZoneLoading/Loading/ZoneLoader.h index ad0d4689f..c20b3fd22 100644 --- a/src/ZoneLoading/Loading/ZoneLoader.h +++ b/src/ZoneLoading/Loading/ZoneLoader.h @@ -1,37 +1,36 @@ #pragma once #include "ILoadingStep.h" -#include "Zone/Zone.h" -#include "Zone/XBlock.h" #include "StreamProcessor.h" +#include "Zone/XBlock.h" +#include "Zone/Zone.h" -#include <vector> #include <istream> #include <memory> +#include <vector> class ILoadingStep; -class ZoneLoader -{ - std::vector<std::unique_ptr<ILoadingStep>> m_steps; - std::vector<std::unique_ptr<StreamProcessor>> m_processors; +class ZoneLoader { + std::vector<std::unique_ptr<ILoadingStep>> m_steps; + std::vector<std::unique_ptr<StreamProcessor>> m_processors; - bool m_processor_chain_dirty; + bool m_processor_chain_dirty; - std::unique_ptr<Zone> m_zone; + std::unique_ptr<Zone> m_zone; - ILoadingStream* BuildLoadingChain(ILoadingStream* rootStream); + ILoadingStream *BuildLoadingChain(ILoadingStream *rootStream); public: - std::vector<XBlock*> m_blocks; + std::vector<XBlock *> m_blocks; - explicit ZoneLoader(std::unique_ptr<Zone> zone); + explicit ZoneLoader(std::unique_ptr<Zone> zone); - void AddXBlock(std::unique_ptr<XBlock> block); - void AddLoadingStep(std::unique_ptr<ILoadingStep> step); - void AddStreamProcessor(std::unique_ptr<StreamProcessor> streamProcessor); + void AddXBlock(std::unique_ptr<XBlock> block); + void AddLoadingStep(std::unique_ptr<ILoadingStep> step); + void AddStreamProcessor(std::unique_ptr<StreamProcessor> streamProcessor); - void RemoveStreamProcessor(StreamProcessor* streamProcessor); + void RemoveStreamProcessor(StreamProcessor *streamProcessor); - std::unique_ptr<Zone> LoadZone(std::istream& stream); + std::unique_ptr<Zone> LoadZone(std::istream &stream); }; diff --git a/src/ZoneLoading/Zone/Stream/IZoneInputStream.h b/src/ZoneLoading/Zone/Stream/IZoneInputStream.h index 4738ec438..38bfb6c79 100644 --- a/src/ZoneLoading/Zone/Stream/IZoneInputStream.h +++ b/src/ZoneLoading/Zone/Stream/IZoneInputStream.h @@ -1,62 +1,33 @@ #pragma once -#include <cstdint> #include <cstddef> +#include <cstdint> #include "Zone/Stream/IZoneStream.h" -class IZoneInputStream : public IZoneStream -{ +class IZoneInputStream : public IZoneStream { public: - virtual void* Alloc(unsigned align) = 0; - - template<typename T> - T* Alloc(const unsigned align) - { - return static_cast<T*>(Alloc(align)); - } - - virtual void LoadDataRaw(void* dst, size_t size) = 0; - virtual void LoadDataInBlock(void* dst, size_t size) = 0; - virtual void IncBlockPos(size_t size) = 0; - virtual void LoadNullTerminated(void* dst) = 0; - - template<typename T> - void Load(T* dst) - { - LoadDataInBlock(const_cast<void*>(reinterpret_cast<const void*>(dst)), sizeof(T)); - } - - template<typename T> - void Load(T* dst, const uint32_t count) - { - LoadDataInBlock(const_cast<void*>(reinterpret_cast<const void*>(dst)), count * sizeof(T)); - } - - template<typename T> - void LoadPartial(T* dst, const size_t size) - { - LoadDataInBlock(const_cast<void*>(reinterpret_cast<const void*>(dst)), size); - } - - virtual void** InsertPointer() = 0; - template<typename T> - T** InsertPointer() - { - return reinterpret_cast<T**>(InsertPointer()); - } - - virtual void* ConvertOffsetToPointer(const void* offset) = 0; - template<typename T> - T* ConvertOffsetToPointer(T* offset) - { - return static_cast<T*>(ConvertOffsetToPointer(static_cast<const void*>(offset))); - } - - virtual void* ConvertOffsetToAlias(const void* offset) = 0; - template<typename T> - T* ConvertOffsetToAlias(T* offset) - { - return static_cast<T*>(ConvertOffsetToAlias(static_cast<const void*>(offset))); - } + virtual void *Alloc(unsigned align) = 0; + + template <typename T> T *Alloc(const unsigned align) { return static_cast<T *>(Alloc(align)); } + + virtual void LoadDataRaw(void *dst, size_t size) = 0; + virtual void LoadDataInBlock(void *dst, size_t size) = 0; + virtual void IncBlockPos(size_t size) = 0; + virtual void LoadNullTerminated(void *dst) = 0; + + template <typename T> void Load(T *dst) { LoadDataInBlock(const_cast<void *>(reinterpret_cast<const void *>(dst)), sizeof(T)); } + + template <typename T> void Load(T *dst, const uint32_t count) { LoadDataInBlock(const_cast<void *>(reinterpret_cast<const void *>(dst)), count * sizeof(T)); } + + template <typename T> void LoadPartial(T *dst, const size_t size) { LoadDataInBlock(const_cast<void *>(reinterpret_cast<const void *>(dst)), size); } + + virtual void **InsertPointer() = 0; + template <typename T> T **InsertPointer() { return reinterpret_cast<T **>(InsertPointer()); } + + virtual void *ConvertOffsetToPointer(const void *offset) = 0; + template <typename T> T *ConvertOffsetToPointer(T *offset) { return static_cast<T *>(ConvertOffsetToPointer(static_cast<const void *>(offset))); } + + virtual void *ConvertOffsetToAlias(const void *offset) = 0; + template <typename T> T *ConvertOffsetToAlias(T *offset) { return static_cast<T *>(ConvertOffsetToAlias(static_cast<const void *>(offset))); } }; diff --git a/src/ZoneLoading/Zone/Stream/Impl/XBlockInputStream.cpp b/src/ZoneLoading/Zone/Stream/Impl/XBlockInputStream.cpp index 0c2466540..8af03677d 100644 --- a/src/ZoneLoading/Zone/Stream/Impl/XBlockInputStream.cpp +++ b/src/ZoneLoading/Zone/Stream/Impl/XBlockInputStream.cpp @@ -8,250 +8,218 @@ #include "Loading/Exception/InvalidOffsetBlockOffsetException.h" #include "Loading/Exception/OutOfBlockBoundsException.h" -XBlockInputStream::XBlockInputStream(std::vector<XBlock*>& blocks, ILoadingStream* stream, const int blockBitCount, - const block_t insertBlock) : m_blocks(blocks) -{ - m_stream = stream; +XBlockInputStream::XBlockInputStream(std::vector<XBlock *> &blocks, ILoadingStream *stream, const int blockBitCount, const block_t insertBlock) + : m_blocks(blocks) { + m_stream = stream; - const unsigned int blockCount = blocks.size(); - m_block_offsets = new size_t[blockCount]{0}; + const unsigned int blockCount = blocks.size(); + m_block_offsets = new size_t[blockCount]{0}; - m_block_bit_count = blockBitCount; + m_block_bit_count = blockBitCount; - assert(insertBlock >= 0 && insertBlock < static_cast<block_t>(blocks.size())); - m_insert_block = blocks[insertBlock]; + assert(insertBlock >= 0 && insertBlock < static_cast<block_t>(blocks.size())); + m_insert_block = blocks[insertBlock]; } -XBlockInputStream::~XBlockInputStream() -{ - delete[] m_block_offsets; - m_block_offsets = nullptr; +XBlockInputStream::~XBlockInputStream() { + delete[] m_block_offsets; + m_block_offsets = nullptr; - assert(m_block_stack.empty()); + assert(m_block_stack.empty()); } -void XBlockInputStream::Align(const unsigned align) -{ - assert(!m_block_stack.empty()); +void XBlockInputStream::Align(const unsigned align) { + assert(!m_block_stack.empty()); - if (align > 0) - { - const block_t blockIndex = m_block_stack.top()->m_index; - m_block_offsets[blockIndex] = (m_block_offsets[blockIndex] + align - 1) / align * align; - } + if (align > 0) { + const block_t blockIndex = m_block_stack.top()->m_index; + m_block_offsets[blockIndex] = (m_block_offsets[blockIndex] + align - 1) / align * align; + } } -void XBlockInputStream::PushBlock(const block_t block) -{ - assert(block >= 0 && block < static_cast<block_t>(m_blocks.size())); +void XBlockInputStream::PushBlock(const block_t block) { + assert(block >= 0 && block < static_cast<block_t>(m_blocks.size())); - XBlock* newBlock = m_blocks[block]; + XBlock *newBlock = m_blocks[block]; - assert(newBlock->m_index == block); + assert(newBlock->m_index == block); - m_block_stack.push(newBlock); + m_block_stack.push(newBlock); - if(newBlock->m_type == XBlock::Type::BLOCK_TYPE_TEMP) - { - m_temp_offsets.push(m_block_offsets[newBlock->m_index]); - } + if (newBlock->m_type == XBlock::Type::BLOCK_TYPE_TEMP) { + m_temp_offsets.push(m_block_offsets[newBlock->m_index]); + } } -block_t XBlockInputStream::PopBlock() -{ - assert(!m_block_stack.empty()); +block_t XBlockInputStream::PopBlock() { + assert(!m_block_stack.empty()); - if (m_block_stack.empty()) - return -1; + if (m_block_stack.empty()) + return -1; - const XBlock* poppedBlock = m_block_stack.top(); + const XBlock *poppedBlock = m_block_stack.top(); - m_block_stack.pop(); + m_block_stack.pop(); - // If the temp block is not used anymore right now, reset it to the buffer start since as the name suggests, the data inside is temporary. - if (poppedBlock->m_type == XBlock::Type::BLOCK_TYPE_TEMP) - { - m_block_offsets[poppedBlock->m_index] = m_temp_offsets.top(); - m_temp_offsets.pop(); - } + // If the temp block is not used anymore right now, reset it to the buffer start since as the name suggests, the data inside is temporary. + if (poppedBlock->m_type == XBlock::Type::BLOCK_TYPE_TEMP) { + m_block_offsets[poppedBlock->m_index] = m_temp_offsets.top(); + m_temp_offsets.pop(); + } - return poppedBlock->m_index; + return poppedBlock->m_index; } -void* XBlockInputStream::Alloc(const unsigned align) -{ - assert(!m_block_stack.empty()); +void *XBlockInputStream::Alloc(const unsigned align) { + assert(!m_block_stack.empty()); - if (m_block_stack.empty()) - return nullptr; + if (m_block_stack.empty()) + return nullptr; - XBlock* block = m_block_stack.top(); + XBlock *block = m_block_stack.top(); - Align(align); + Align(align); - if (m_block_offsets[block->m_index] > block->m_buffer_size) - { - throw BlockOverflowException(block); - } + if (m_block_offsets[block->m_index] > block->m_buffer_size) { + throw BlockOverflowException(block); + } - return &block->m_buffer[m_block_offsets[block->m_index]]; + return &block->m_buffer[m_block_offsets[block->m_index]]; } -void XBlockInputStream::LoadDataRaw(void* dst, const size_t size) -{ - m_stream->Load(dst, size); -} +void XBlockInputStream::LoadDataRaw(void *dst, const size_t size) { m_stream->Load(dst, size); } -void XBlockInputStream::LoadDataInBlock(void* dst, const size_t size) -{ - assert(!m_block_stack.empty()); +void XBlockInputStream::LoadDataInBlock(void *dst, const size_t size) { + assert(!m_block_stack.empty()); - if (m_block_stack.empty()) - return; + if (m_block_stack.empty()) + return; - XBlock* block = m_block_stack.top(); + XBlock *block = m_block_stack.top(); - if (block->m_buffer > dst || block->m_buffer + block->m_buffer_size < dst) - { - throw OutOfBlockBoundsException(block); - } + if (block->m_buffer > dst || block->m_buffer + block->m_buffer_size < dst) { + throw OutOfBlockBoundsException(block); + } - if (static_cast<uint8_t*>(dst) + size > block->m_buffer + block->m_buffer_size) - { - throw BlockOverflowException(block); - } + if (static_cast<uint8_t *>(dst) + size > block->m_buffer + block->m_buffer_size) { + throw BlockOverflowException(block); + } - // Theoretically ptr should always be at the current block offset. - assert(dst == &block->m_buffer[m_block_offsets[block->m_index]]); + // Theoretically ptr should always be at the current block offset. + assert(dst == &block->m_buffer[m_block_offsets[block->m_index]]); - switch (block->m_type) - { - case XBlock::Type::BLOCK_TYPE_TEMP: - case XBlock::Type::BLOCK_TYPE_NORMAL: - m_stream->Load(dst, size); - break; + switch (block->m_type) { + case XBlock::Type::BLOCK_TYPE_TEMP: + case XBlock::Type::BLOCK_TYPE_NORMAL: + m_stream->Load(dst, size); + break; - case XBlock::Type::BLOCK_TYPE_RUNTIME: - memset(dst, 0, size); - break; + case XBlock::Type::BLOCK_TYPE_RUNTIME: + memset(dst, 0, size); + break; - case XBlock::Type::BLOCK_TYPE_DELAY: - assert(false); - break; - } + case XBlock::Type::BLOCK_TYPE_DELAY: + assert(false); + break; + } - - IncBlockPos(size); + IncBlockPos(size); } -void XBlockInputStream::IncBlockPos(const size_t size) -{ - assert(!m_block_stack.empty()); +void XBlockInputStream::IncBlockPos(const size_t size) { + assert(!m_block_stack.empty()); - if (m_block_stack.empty()) - return; + if (m_block_stack.empty()) + return; - XBlock* block = m_block_stack.top(); - m_block_offsets[block->m_index] += size; + XBlock *block = m_block_stack.top(); + m_block_offsets[block->m_index] += size; } -void XBlockInputStream::LoadNullTerminated(void* dst) -{ - assert(!m_block_stack.empty()); - - if (m_block_stack.empty()) - return; +void XBlockInputStream::LoadNullTerminated(void *dst) { + assert(!m_block_stack.empty()); - XBlock* block = m_block_stack.top(); + if (m_block_stack.empty()) + return; - if (block->m_buffer > dst || block->m_buffer + block->m_buffer_size < dst) - { - throw OutOfBlockBoundsException(block); - } + XBlock *block = m_block_stack.top(); - // Theoretically ptr should always be at the current block offset. - assert(dst == &block->m_buffer[m_block_offsets[block->m_index]]); + if (block->m_buffer > dst || block->m_buffer + block->m_buffer_size < dst) { + throw OutOfBlockBoundsException(block); + } - uint8_t byte; - size_t offset = reinterpret_cast<uint8_t*>(dst) - block->m_buffer; - do - { - if (offset >= block->m_buffer_size) - { - throw BlockOverflowException(block); - } + // Theoretically ptr should always be at the current block offset. + assert(dst == &block->m_buffer[m_block_offsets[block->m_index]]); - m_stream->Load(&byte, 1); - block->m_buffer[offset++] = byte; + uint8_t byte; + size_t offset = reinterpret_cast<uint8_t *>(dst) - block->m_buffer; + do { + if (offset >= block->m_buffer_size) { + throw BlockOverflowException(block); } - while (byte != 0); - m_block_offsets[block->m_index] = offset; + m_stream->Load(&byte, 1); + block->m_buffer[offset++] = byte; + } while (byte != 0); + + m_block_offsets[block->m_index] = offset; } -void** XBlockInputStream::InsertPointer() -{ - m_block_stack.push(m_insert_block); +void **XBlockInputStream::InsertPointer() { + m_block_stack.push(m_insert_block); - Align(alignof(void*)); + Align(alignof(void *)); - if (m_block_offsets[m_insert_block->m_index] + sizeof(void*) > m_insert_block->m_buffer_size) - { - throw BlockOverflowException(m_insert_block); - } + if (m_block_offsets[m_insert_block->m_index] + sizeof(void *) > m_insert_block->m_buffer_size) { + throw BlockOverflowException(m_insert_block); + } - void** ptr = reinterpret_cast<void**>(&m_insert_block->m_buffer[m_block_offsets[m_insert_block->m_index]]); + void **ptr = reinterpret_cast<void **>(&m_insert_block->m_buffer[m_block_offsets[m_insert_block->m_index]]); - IncBlockPos(sizeof(void*)); + IncBlockPos(sizeof(void *)); - m_block_stack.pop(); + m_block_stack.pop(); - return ptr; + return ptr; } -void* XBlockInputStream::ConvertOffsetToPointer(const void* offset) -{ - // -1 because otherwise Block 0 Offset 0 would be just 0 which is already used to signalize a nullptr. - // So all offsets are moved by 1. - auto offsetInt = reinterpret_cast<uintptr_t>(offset) - 1; +void *XBlockInputStream::ConvertOffsetToPointer(const void *offset) { + // -1 because otherwise Block 0 Offset 0 would be just 0 which is already used to signalize a nullptr. + // So all offsets are moved by 1. + auto offsetInt = reinterpret_cast<uintptr_t>(offset) - 1; - const block_t blockNum = offsetInt >> (sizeof(offsetInt) * 8 - m_block_bit_count); - const size_t blockOffset = offsetInt & (UINTPTR_MAX >> m_block_bit_count); + const block_t blockNum = offsetInt >> (sizeof(offsetInt) * 8 - m_block_bit_count); + const size_t blockOffset = offsetInt & (UINTPTR_MAX >> m_block_bit_count); - if (blockNum < 0 || blockNum >= static_cast<block_t>(m_blocks.size())) - { - throw InvalidOffsetBlockException(blockNum); - } + if (blockNum < 0 || blockNum >= static_cast<block_t>(m_blocks.size())) { + throw InvalidOffsetBlockException(blockNum); + } - XBlock* block = m_blocks[blockNum]; + XBlock *block = m_blocks[blockNum]; - if (block->m_buffer_size <= blockOffset) - { - throw InvalidOffsetBlockOffsetException(block, blockOffset); - } + if (block->m_buffer_size <= blockOffset) { + throw InvalidOffsetBlockOffsetException(block, blockOffset); + } - return &block->m_buffer[blockOffset]; + return &block->m_buffer[blockOffset]; } -void* XBlockInputStream::ConvertOffsetToAlias(const void* offset) -{ - // For details see ConvertOffsetToPointer - auto offsetInt = reinterpret_cast<uintptr_t>(offset) - 1; +void *XBlockInputStream::ConvertOffsetToAlias(const void *offset) { + // For details see ConvertOffsetToPointer + auto offsetInt = reinterpret_cast<uintptr_t>(offset) - 1; - const block_t blockNum = offsetInt >> (sizeof(offsetInt) * 8 - m_block_bit_count); - const size_t blockOffset = offsetInt & (UINTPTR_MAX >> m_block_bit_count); + const block_t blockNum = offsetInt >> (sizeof(offsetInt) * 8 - m_block_bit_count); + const size_t blockOffset = offsetInt & (UINTPTR_MAX >> m_block_bit_count); - if (blockNum < 0 || blockNum >= static_cast<block_t>(m_blocks.size())) - { - throw InvalidOffsetBlockException(blockNum); - } + if (blockNum < 0 || blockNum >= static_cast<block_t>(m_blocks.size())) { + throw InvalidOffsetBlockException(blockNum); + } - XBlock* block = m_blocks[blockNum]; + XBlock *block = m_blocks[blockNum]; - if (block->m_buffer_size <= blockOffset + sizeof(void*)) - { - throw InvalidOffsetBlockOffsetException(block, blockOffset); - } + if (block->m_buffer_size <= blockOffset + sizeof(void *)) { + throw InvalidOffsetBlockOffsetException(block, blockOffset); + } - return *reinterpret_cast<void**>(&block->m_buffer[blockOffset]); + return *reinterpret_cast<void **>(&block->m_buffer[blockOffset]); } diff --git a/src/ZoneLoading/Zone/Stream/Impl/XBlockInputStream.h b/src/ZoneLoading/Zone/Stream/Impl/XBlockInputStream.h index 1c6c8d36f..48bcc38b3 100644 --- a/src/ZoneLoading/Zone/Stream/Impl/XBlockInputStream.h +++ b/src/ZoneLoading/Zone/Stream/Impl/XBlockInputStream.h @@ -1,43 +1,41 @@ #pragma once +#include "Loading/ILoadingStream.h" #include "Zone/Stream/IZoneInputStream.h" #include "Zone/XBlock.h" -#include "Loading/ILoadingStream.h" -#include <vector> #include <stack> +#include <vector> -class XBlockInputStream final : public IZoneInputStream -{ - std::vector<XBlock*>& m_blocks; - size_t* m_block_offsets; +class XBlockInputStream final : public IZoneInputStream { + std::vector<XBlock *> &m_blocks; + size_t *m_block_offsets; - std::stack<XBlock*> m_block_stack; - std::stack<size_t> m_temp_offsets; - ILoadingStream* m_stream; + std::stack<XBlock *> m_block_stack; + std::stack<size_t> m_temp_offsets; + ILoadingStream *m_stream; - int m_block_bit_count; - XBlock* m_insert_block; + int m_block_bit_count; + XBlock *m_insert_block; - void Align(unsigned align); + void Align(unsigned align); public: - XBlockInputStream(std::vector<XBlock*>& blocks, ILoadingStream* stream, int blockBitCount, block_t insertBlock); - ~XBlockInputStream() override; + XBlockInputStream(std::vector<XBlock *> &blocks, ILoadingStream *stream, int blockBitCount, block_t insertBlock); + ~XBlockInputStream() override; - void PushBlock(block_t block) override; - block_t PopBlock() override; + void PushBlock(block_t block) override; + block_t PopBlock() override; - void* Alloc(unsigned align) override; + void *Alloc(unsigned align) override; - void LoadDataRaw(void* dst, size_t size) override; - void LoadDataInBlock(void* dst, size_t size) override; - void IncBlockPos(size_t size) override; - void LoadNullTerminated(void* dst) override; + void LoadDataRaw(void *dst, size_t size) override; + void LoadDataInBlock(void *dst, size_t size) override; + void IncBlockPos(size_t size) override; + void LoadNullTerminated(void *dst) override; - void** InsertPointer() override; + void **InsertPointer() override; - void* ConvertOffsetToPointer(const void* offset) override; - void* ConvertOffsetToAlias(const void* offset) override; - + void *ConvertOffsetToPointer(const void *offset) override; + void *ConvertOffsetToAlias(const void *offset) override; }; diff --git a/src/ZoneLoading/ZoneLoading.cpp b/src/ZoneLoading/ZoneLoading.cpp index 995c011cd..c3ea99aab 100644 --- a/src/ZoneLoading/ZoneLoading.cpp +++ b/src/ZoneLoading/ZoneLoading.cpp @@ -13,52 +13,41 @@ namespace fs = std::filesystem; -IZoneLoaderFactory* ZoneLoaderFactories[] -{ - new IW3::ZoneLoaderFactory(), - new IW4::ZoneLoaderFactory(), - new IW5::ZoneLoaderFactory(), - new T5::ZoneLoaderFactory(), - new T6::ZoneLoaderFactory() -}; - -std::unique_ptr<Zone> ZoneLoading::LoadZone(const std::string& path) -{ - auto zoneName = fs::path(path).filename().replace_extension("").string(); - std::ifstream file(path, std::fstream::in | std::fstream::binary); - - if(!file.is_open()) - { - printf("Could not open file '%s'.\n", path.c_str()); - return nullptr; - } - - ZoneHeader header{}; - file.read(reinterpret_cast<char*>(&header), sizeof header); - if(file.gcount() != sizeof header) - { - std::cout << "Failed to read zone header from file '" << path << "'.\n"; - return nullptr; - } - - ZoneLoader* zoneLoader = nullptr; - for(auto* factory : ZoneLoaderFactories) - { - zoneLoader = factory->CreateLoaderForHeader(header, zoneName); - - if(zoneLoader != nullptr) - break; - } - - if(zoneLoader == nullptr) - { - printf("Could not create factory for zone '%s'.\n", zoneName.c_str()); - return nullptr; - } - - auto loadedZone = zoneLoader->LoadZone(file); - delete zoneLoader; - - file.close(); - return std::move(loadedZone); +IZoneLoaderFactory *ZoneLoaderFactories[]{new IW3::ZoneLoaderFactory(), new IW4::ZoneLoaderFactory(), new IW5::ZoneLoaderFactory(), new T5::ZoneLoaderFactory(), + new T6::ZoneLoaderFactory()}; + +std::unique_ptr<Zone> ZoneLoading::LoadZone(const std::string &path) { + auto zoneName = fs::path(path).filename().replace_extension("").string(); + std::ifstream file(path, std::fstream::in | std::fstream::binary); + + if (!file.is_open()) { + printf("Could not open file '%s'.\n", path.c_str()); + return nullptr; + } + + ZoneHeader header{}; + file.read(reinterpret_cast<char *>(&header), sizeof header); + if (file.gcount() != sizeof header) { + std::cout << "Failed to read zone header from file '" << path << "'.\n"; + return nullptr; + } + + ZoneLoader *zoneLoader = nullptr; + for (auto *factory : ZoneLoaderFactories) { + zoneLoader = factory->CreateLoaderForHeader(header, zoneName); + + if (zoneLoader != nullptr) + break; + } + + if (zoneLoader == nullptr) { + printf("Could not create factory for zone '%s'.\n", zoneName.c_str()); + return nullptr; + } + + auto loadedZone = zoneLoader->LoadZone(file); + delete zoneLoader; + + file.close(); + return std::move(loadedZone); } \ No newline at end of file diff --git a/src/ZoneLoading/ZoneLoading.h b/src/ZoneLoading/ZoneLoading.h index 3017e115f..825590a2a 100644 --- a/src/ZoneLoading/ZoneLoading.h +++ b/src/ZoneLoading/ZoneLoading.h @@ -3,8 +3,7 @@ #include "Zone/Zone.h" -class ZoneLoading -{ +class ZoneLoading { public: - static std::unique_ptr<Zone> LoadZone(const std::string& path); + static std::unique_ptr<Zone> LoadZone(const std::string &path); }; diff --git a/src/ZoneWriting/Game/IW3/ContentWriterIW3.cpp b/src/ZoneWriting/Game/IW3/ContentWriterIW3.cpp index 161beaa19..f743aef39 100644 --- a/src/ZoneWriting/Game/IW3/ContentWriterIW3.cpp +++ b/src/ZoneWriting/Game/IW3/ContentWriterIW3.cpp @@ -33,91 +33,73 @@ using namespace IW3; -ContentWriter::ContentWriter() - : varXAssetList(nullptr), - varXAsset(nullptr), - varScriptStringList(nullptr) -{ +ContentWriter::ContentWriter() : varXAssetList(nullptr), varXAsset(nullptr), varScriptStringList(nullptr) {} + +void ContentWriter::CreateXAssetList(XAssetList &xAssetList, MemoryManager &memory) const { + if (!m_zone->m_script_strings.Empty()) { + assert(m_zone->m_script_strings.Count() <= SCR_STRING_MAX + 1); + xAssetList.stringList.count = static_cast<int>(m_zone->m_script_strings.Count()); + xAssetList.stringList.strings = static_cast<const char **>(memory.Alloc(sizeof(const char *) * m_zone->m_script_strings.Count())); + + for (auto i = 0u; i < m_zone->m_script_strings.Count(); i++) + xAssetList.stringList.strings[i] = m_zone->m_script_strings.CValue(i); + } else { + xAssetList.stringList.count = 0; + xAssetList.stringList.strings = nullptr; + } + + const auto assetCount = m_zone->m_pools->GetTotalAssetCount(); + if (assetCount > 0) { + xAssetList.assetCount = static_cast<int>(assetCount); + xAssetList.assets = static_cast<XAsset *>(memory.Alloc(sizeof(XAsset) * assetCount)); + + const auto end = m_zone->m_pools->end(); + auto index = 0u; + for (auto i = m_zone->m_pools->begin(); i != end; ++i) { + auto &asset = xAssetList.assets[index++]; + asset.type = static_cast<XAssetType>((*i)->m_type); + asset.header.data = (*i)->m_ptr; + } + } else { + xAssetList.assetCount = 0; + xAssetList.assets = nullptr; + } } -void ContentWriter::CreateXAssetList(XAssetList& xAssetList, MemoryManager& memory) const -{ - if (!m_zone->m_script_strings.Empty()) - { - assert(m_zone->m_script_strings.Count() <= SCR_STRING_MAX + 1); - xAssetList.stringList.count = static_cast<int>(m_zone->m_script_strings.Count()); - xAssetList.stringList.strings = static_cast<const char**>(memory.Alloc(sizeof(const char*) * m_zone->m_script_strings.Count())); +void ContentWriter::WriteScriptStringList(const bool atStreamStart) { + m_stream->PushBlock(XFILE_BLOCK_VIRTUAL); - for (auto i = 0u; i < m_zone->m_script_strings.Count(); i++) - xAssetList.stringList.strings[i] = m_zone->m_script_strings.CValue(i); - } - else - { - xAssetList.stringList.count = 0; - xAssetList.stringList.strings = nullptr; - } + if (atStreamStart) + varScriptStringList = m_stream->Write(varScriptStringList); - const auto assetCount = m_zone->m_pools->GetTotalAssetCount(); - if (assetCount > 0) - { - xAssetList.assetCount = static_cast<int>(assetCount); - xAssetList.assets = static_cast<XAsset*>(memory.Alloc(sizeof(XAsset) * assetCount)); - - const auto end = m_zone->m_pools->end(); - auto index = 0u; - for (auto i = m_zone->m_pools->begin(); i != end; ++i) - { - auto& asset = xAssetList.assets[index++]; - asset.type = static_cast<XAssetType>((*i)->m_type); - asset.header.data = (*i)->m_ptr; - } - } - else - { - xAssetList.assetCount = 0; - xAssetList.assets = nullptr; - } -} + if (varScriptStringList->strings != nullptr) { + m_stream->Align(alignof(const char *)); + varXString = varScriptStringList->strings; + WriteXStringArray(true, varScriptStringList->count); -void ContentWriter::WriteScriptStringList(const bool atStreamStart) -{ - m_stream->PushBlock(XFILE_BLOCK_VIRTUAL); + m_stream->MarkFollowing(varScriptStringList->strings); + } - if (atStreamStart) - varScriptStringList = m_stream->Write(varScriptStringList); + m_stream->PopBlock(); +} - if (varScriptStringList->strings != nullptr) - { - m_stream->Align(alignof(const char*)); - varXString = varScriptStringList->strings; - WriteXStringArray(true, varScriptStringList->count); +void ContentWriter::WriteXAsset(const bool atStreamStart) { +#define WRITE_ASSET(type_index, typeName, headerEntry) \ + case type_index: { \ + Writer_##typeName writer(varXAsset->header.headerEntry, m_zone, m_stream); \ + writer.Write(&varXAsset->header.headerEntry); \ + break; \ + } +#define SKIP_ASSET(type_index, typeName, headerEntry) \ + case type_index: \ + break; - m_stream->MarkFollowing(varScriptStringList->strings); - } + assert(varXAsset != nullptr); - m_stream->PopBlock(); -} + if (atStreamStart) + varXAsset = m_stream->Write(varXAsset); -void ContentWriter::WriteXAsset(const bool atStreamStart) -{ -#define WRITE_ASSET(type_index, typeName, headerEntry) \ - case type_index: \ - { \ - Writer_##typeName writer(varXAsset->header.headerEntry, m_zone, m_stream); \ - writer.Write(&varXAsset->header.headerEntry); \ - break; \ - } -#define SKIP_ASSET(type_index, typeName, headerEntry) \ - case type_index: \ - break; - - assert(varXAsset != nullptr); - - if (atStreamStart) - varXAsset = m_stream->Write(varXAsset); - - switch (varXAsset->type) - { + switch (varXAsset->type) { WRITE_ASSET(ASSET_TYPE_PHYSPRESET, PhysPreset, physPreset) WRITE_ASSET(ASSET_TYPE_XANIMPARTS, XAnimParts, parts) WRITE_ASSET(ASSET_TYPE_XMODEL, XModel, model) @@ -146,56 +128,51 @@ void ContentWriter::WriteXAsset(const bool atStreamStart) WRITE_ASSET(ASSET_TYPE_RAWFILE, RawFile, rawfile) WRITE_ASSET(ASSET_TYPE_STRINGTABLE, StringTable, stringTable) - default: - { - std::ostringstream str; - str << "Unsupported asset type: " << varXAsset->type << "."; - throw WritingException(str.str()); - } - } + default: { + std::ostringstream str; + str << "Unsupported asset type: " << varXAsset->type << "."; + throw WritingException(str.str()); + } + } #undef WRITE_ASSET #undef SKIP_ASSET } -void ContentWriter::WriteXAssetArray(const bool atStreamStart, const size_t count) -{ - assert(varXAsset != nullptr); +void ContentWriter::WriteXAssetArray(const bool atStreamStart, const size_t count) { + assert(varXAsset != nullptr); - if (atStreamStart) - varXAsset = m_stream->Write(varXAsset, count); + if (atStreamStart) + varXAsset = m_stream->Write(varXAsset, count); - for (size_t index = 0; index < count; index++) - { - WriteXAsset(false); - varXAsset++; - } + for (size_t index = 0; index < count; index++) { + WriteXAsset(false); + varXAsset++; + } } -void ContentWriter::WriteContent(Zone* zone, IZoneOutputStream* stream) -{ - m_zone = zone; - m_stream = stream; +void ContentWriter::WriteContent(Zone *zone, IZoneOutputStream *stream) { + m_zone = zone; + m_stream = stream; - m_stream->PushBlock(XFILE_BLOCK_VIRTUAL); + m_stream->PushBlock(XFILE_BLOCK_VIRTUAL); - MemoryManager memory; - XAssetList assetList{}; + MemoryManager memory; + XAssetList assetList{}; - CreateXAssetList(assetList, memory); + CreateXAssetList(assetList, memory); - varXAssetList = static_cast<XAssetList*>(m_stream->WriteDataRaw(&assetList, sizeof(assetList))); + varXAssetList = static_cast<XAssetList *>(m_stream->WriteDataRaw(&assetList, sizeof(assetList))); - varScriptStringList = &varXAssetList->stringList; - WriteScriptStringList(false); + varScriptStringList = &varXAssetList->stringList; + WriteScriptStringList(false); - if (varXAssetList->assets != nullptr) - { - m_stream->Align(alignof(XAsset)); - varXAsset = varXAssetList->assets; - WriteXAssetArray(true, varXAssetList->assetCount); - m_stream->MarkFollowing(varXAssetList->assets); - } + if (varXAssetList->assets != nullptr) { + m_stream->Align(alignof(XAsset)); + varXAsset = varXAssetList->assets; + WriteXAssetArray(true, varXAssetList->assetCount); + m_stream->MarkFollowing(varXAssetList->assets); + } - m_stream->PopBlock(); + m_stream->PopBlock(); } diff --git a/src/ZoneWriting/Game/IW3/ContentWriterIW3.h b/src/ZoneWriting/Game/IW3/ContentWriterIW3.h index 452029254..4e08f8e47 100644 --- a/src/ZoneWriting/Game/IW3/ContentWriterIW3.h +++ b/src/ZoneWriting/Game/IW3/ContentWriterIW3.h @@ -1,26 +1,24 @@ #pragma once +#include "Game/IW3/IW3.h" #include "Writing/ContentWriterBase.h" #include "Writing/IContentWritingEntryPoint.h" -#include "Game/IW3/IW3.h" -namespace IW3 -{ - class ContentWriter final : public ContentWriterBase, public IContentWritingEntryPoint - { - XAssetList* varXAssetList; - XAsset* varXAsset; - ScriptStringList* varScriptStringList; +namespace IW3 { +class ContentWriter final : public ContentWriterBase, public IContentWritingEntryPoint { + XAssetList *varXAssetList; + XAsset *varXAsset; + ScriptStringList *varScriptStringList; - void CreateXAssetList(XAssetList& xAssetList, MemoryManager& memory) const; + void CreateXAssetList(XAssetList &xAssetList, MemoryManager &memory) const; - void WriteScriptStringList(bool atStreamStart); + void WriteScriptStringList(bool atStreamStart); - void WriteXAsset(bool atStreamStart); - void WriteXAssetArray(bool atStreamStart, size_t count); + void WriteXAsset(bool atStreamStart); + void WriteXAssetArray(bool atStreamStart, size_t count); - public: - ContentWriter(); +public: + ContentWriter(); - void WriteContent(Zone* zone, IZoneOutputStream* stream) override; - }; -} + void WriteContent(Zone *zone, IZoneOutputStream *stream) override; +}; +} // namespace IW3 diff --git a/src/ZoneWriting/Game/IW3/ZoneWriterFactoryIW3.cpp b/src/ZoneWriting/Game/IW3/ZoneWriterFactoryIW3.cpp index 50cc4bff3..b4da2439f 100644 --- a/src/ZoneWriting/Game/IW3/ZoneWriterFactoryIW3.cpp +++ b/src/ZoneWriting/Game/IW3/ZoneWriterFactoryIW3.cpp @@ -3,8 +3,8 @@ #include <cstring> #include "ContentWriterIW3.h" -#include "Game/IW3/IW3.h" #include "Game/IW3/GameIW3.h" +#include "Game/IW3/IW3.h" #include "Game/IW3/ZoneConstantsIW3.h" #include "Writing/Processor/OutputProcessorDeflate.h" #include "Writing/Steps/StepAddOutputProcessor.h" @@ -16,76 +16,65 @@ using namespace IW3; -class ZoneWriterFactory::Impl -{ - Zone* m_zone; - std::unique_ptr<ZoneWriter> m_writer; +class ZoneWriterFactory::Impl { + Zone *m_zone; + std::unique_ptr<ZoneWriter> m_writer; public: - explicit Impl(Zone* zone) - : m_zone(zone), - m_writer(std::make_unique<ZoneWriter>()) - { - } - - void SetupBlocks() const - { + explicit Impl(Zone *zone) : m_zone(zone), m_writer(std::make_unique<ZoneWriter>()) {} + + void SetupBlocks() const { #define XBLOCK_DEF(name, type) std::make_unique<XBlock>(STR(name), name, type) - m_writer->AddXBlock(XBLOCK_DEF(IW3::XFILE_BLOCK_TEMP, XBlock::Type::BLOCK_TYPE_TEMP)); - m_writer->AddXBlock(XBLOCK_DEF(IW3::XFILE_BLOCK_RUNTIME, XBlock::Type::BLOCK_TYPE_RUNTIME)); - m_writer->AddXBlock(XBLOCK_DEF(IW3::XFILE_BLOCK_LARGE_RUNTIME, XBlock::Type::BLOCK_TYPE_RUNTIME)); - m_writer->AddXBlock(XBLOCK_DEF(IW3::XFILE_BLOCK_PHYSICAL_RUNTIME, XBlock::Type::BLOCK_TYPE_RUNTIME)); - m_writer->AddXBlock(XBLOCK_DEF(IW3::XFILE_BLOCK_VIRTUAL, XBlock::Type::BLOCK_TYPE_NORMAL)); - m_writer->AddXBlock(XBLOCK_DEF(IW3::XFILE_BLOCK_LARGE, XBlock::Type::BLOCK_TYPE_NORMAL)); - m_writer->AddXBlock(XBLOCK_DEF(IW3::XFILE_BLOCK_PHYSICAL, XBlock::Type::BLOCK_TYPE_NORMAL)); - m_writer->AddXBlock(XBLOCK_DEF(IW3::XFILE_BLOCK_VERTEX, XBlock::Type::BLOCK_TYPE_NORMAL)); - m_writer->AddXBlock(XBLOCK_DEF(IW3::XFILE_BLOCK_INDEX, XBlock::Type::BLOCK_TYPE_NORMAL)); + m_writer->AddXBlock(XBLOCK_DEF(IW3::XFILE_BLOCK_TEMP, XBlock::Type::BLOCK_TYPE_TEMP)); + m_writer->AddXBlock(XBLOCK_DEF(IW3::XFILE_BLOCK_RUNTIME, XBlock::Type::BLOCK_TYPE_RUNTIME)); + m_writer->AddXBlock(XBLOCK_DEF(IW3::XFILE_BLOCK_LARGE_RUNTIME, XBlock::Type::BLOCK_TYPE_RUNTIME)); + m_writer->AddXBlock(XBLOCK_DEF(IW3::XFILE_BLOCK_PHYSICAL_RUNTIME, XBlock::Type::BLOCK_TYPE_RUNTIME)); + m_writer->AddXBlock(XBLOCK_DEF(IW3::XFILE_BLOCK_VIRTUAL, XBlock::Type::BLOCK_TYPE_NORMAL)); + m_writer->AddXBlock(XBLOCK_DEF(IW3::XFILE_BLOCK_LARGE, XBlock::Type::BLOCK_TYPE_NORMAL)); + m_writer->AddXBlock(XBLOCK_DEF(IW3::XFILE_BLOCK_PHYSICAL, XBlock::Type::BLOCK_TYPE_NORMAL)); + m_writer->AddXBlock(XBLOCK_DEF(IW3::XFILE_BLOCK_VERTEX, XBlock::Type::BLOCK_TYPE_NORMAL)); + m_writer->AddXBlock(XBLOCK_DEF(IW3::XFILE_BLOCK_INDEX, XBlock::Type::BLOCK_TYPE_NORMAL)); #undef XBLOCK_DEF - } + } - static ZoneHeader CreateHeaderForParams() - { - ZoneHeader header{}; - header.m_version = ZoneConstants::ZONE_VERSION; - memcpy(header.m_magic, ZoneConstants::MAGIC_UNSIGNED, sizeof(ZoneHeader::m_magic)); + static ZoneHeader CreateHeaderForParams() { + ZoneHeader header{}; + header.m_version = ZoneConstants::ZONE_VERSION; + memcpy(header.m_magic, ZoneConstants::MAGIC_UNSIGNED, sizeof(ZoneHeader::m_magic)); - return header; - } + return header; + } - std::unique_ptr<ZoneWriter> CreateWriter() - { - SetupBlocks(); + std::unique_ptr<ZoneWriter> CreateWriter() { + SetupBlocks(); - auto contentInMemory = std::make_unique<StepWriteZoneContentToMemory>(std::make_unique<ContentWriter>(), m_zone, ZoneConstants::OFFSET_BLOCK_BIT_COUNT, ZoneConstants::INSERT_BLOCK); - auto* contentInMemoryPtr = contentInMemory.get(); - m_writer->AddWritingStep(std::move(contentInMemory)); + auto contentInMemory = std::make_unique<StepWriteZoneContentToMemory>(std::make_unique<ContentWriter>(), m_zone, ZoneConstants::OFFSET_BLOCK_BIT_COUNT, + ZoneConstants::INSERT_BLOCK); + auto *contentInMemoryPtr = contentInMemory.get(); + m_writer->AddWritingStep(std::move(contentInMemory)); - // Write zone header - m_writer->AddWritingStep(std::make_unique<StepWriteZoneHeader>(CreateHeaderForParams())); + // Write zone header + m_writer->AddWritingStep(std::make_unique<StepWriteZoneHeader>(CreateHeaderForParams())); - m_writer->AddWritingStep(std::make_unique<StepAddOutputProcessor>(std::make_unique<OutputProcessorDeflate>())); + m_writer->AddWritingStep(std::make_unique<StepAddOutputProcessor>(std::make_unique<OutputProcessorDeflate>())); - // Start of the XFile struct - m_writer->AddWritingStep(std::make_unique<StepWriteZoneSizes>(contentInMemoryPtr)); - m_writer->AddWritingStep(std::make_unique<StepWriteXBlockSizes>(m_zone)); + // Start of the XFile struct + m_writer->AddWritingStep(std::make_unique<StepWriteZoneSizes>(contentInMemoryPtr)); + m_writer->AddWritingStep(std::make_unique<StepWriteXBlockSizes>(m_zone)); - // Start of the zone content - m_writer->AddWritingStep(std::make_unique<StepWriteZoneContentToFile>(contentInMemoryPtr)); + // Start of the zone content + m_writer->AddWritingStep(std::make_unique<StepWriteZoneContentToFile>(contentInMemoryPtr)); - // Return the fully setup zoneloader - return std::move(m_writer); - } + // Return the fully setup zoneloader + return std::move(m_writer); + } }; -bool ZoneWriterFactory::SupportsZone(Zone* zone) const -{ - return zone->m_game == &g_GameIW3; -} +bool ZoneWriterFactory::SupportsZone(Zone *zone) const { return zone->m_game == &g_GameIW3; } -std::unique_ptr<ZoneWriter> ZoneWriterFactory::CreateWriter(Zone* zone) const -{ - Impl impl(zone); - return impl.CreateWriter(); +std::unique_ptr<ZoneWriter> ZoneWriterFactory::CreateWriter(Zone *zone) const { + Impl impl(zone); + return impl.CreateWriter(); } diff --git a/src/ZoneWriting/Game/IW3/ZoneWriterFactoryIW3.h b/src/ZoneWriting/Game/IW3/ZoneWriterFactoryIW3.h index f73d235af..0b64b39c7 100644 --- a/src/ZoneWriting/Game/IW3/ZoneWriterFactoryIW3.h +++ b/src/ZoneWriting/Game/IW3/ZoneWriterFactoryIW3.h @@ -4,14 +4,12 @@ #include "Writing/IZoneWriterFactory.h" -namespace IW3 -{ - class ZoneWriterFactory final : public IZoneWriterFactory - { - class Impl; - - public: - _NODISCARD bool SupportsZone(Zone* zone) const override; - _NODISCARD std::unique_ptr<ZoneWriter> CreateWriter(Zone* zone) const override; - }; -} +namespace IW3 { +class ZoneWriterFactory final : public IZoneWriterFactory { + class Impl; + +public: + _NODISCARD bool SupportsZone(Zone *zone) const override; + _NODISCARD std::unique_ptr<ZoneWriter> CreateWriter(Zone *zone) const override; +}; +} // namespace IW3 diff --git a/src/ZoneWriting/Game/IW4/ContentWriterIW4.cpp b/src/ZoneWriting/Game/IW4/ContentWriterIW4.cpp index c3e97cbbe..379f2c5e3 100644 --- a/src/ZoneWriting/Game/IW4/ContentWriterIW4.cpp +++ b/src/ZoneWriting/Game/IW4/ContentWriterIW4.cpp @@ -43,91 +43,73 @@ using namespace IW4; -ContentWriter::ContentWriter() - : varXAssetList(nullptr), - varXAsset(nullptr), - varScriptStringList(nullptr) -{ +ContentWriter::ContentWriter() : varXAssetList(nullptr), varXAsset(nullptr), varScriptStringList(nullptr) {} + +void ContentWriter::CreateXAssetList(XAssetList &xAssetList, MemoryManager &memory) const { + if (!m_zone->m_script_strings.Empty()) { + assert(m_zone->m_script_strings.Count() <= SCR_STRING_MAX + 1); + xAssetList.stringList.count = static_cast<int>(m_zone->m_script_strings.Count()); + xAssetList.stringList.strings = static_cast<const char **>(memory.Alloc(sizeof(const char *) * m_zone->m_script_strings.Count())); + + for (auto i = 0u; i < m_zone->m_script_strings.Count(); i++) + xAssetList.stringList.strings[i] = m_zone->m_script_strings.CValue(i); + } else { + xAssetList.stringList.count = 0; + xAssetList.stringList.strings = nullptr; + } + + const auto assetCount = m_zone->m_pools->GetTotalAssetCount(); + if (assetCount > 0) { + xAssetList.assetCount = static_cast<int>(assetCount); + xAssetList.assets = static_cast<XAsset *>(memory.Alloc(sizeof(XAsset) * assetCount)); + + const auto end = m_zone->m_pools->end(); + auto index = 0u; + for (auto i = m_zone->m_pools->begin(); i != end; ++i) { + auto &asset = xAssetList.assets[index++]; + asset.type = static_cast<XAssetType>((*i)->m_type); + asset.header.data = (*i)->m_ptr; + } + } else { + xAssetList.assetCount = 0; + xAssetList.assets = nullptr; + } } -void ContentWriter::CreateXAssetList(XAssetList& xAssetList, MemoryManager& memory) const -{ - if (!m_zone->m_script_strings.Empty()) - { - assert(m_zone->m_script_strings.Count() <= SCR_STRING_MAX + 1); - xAssetList.stringList.count = static_cast<int>(m_zone->m_script_strings.Count()); - xAssetList.stringList.strings = static_cast<const char**>(memory.Alloc(sizeof(const char*) * m_zone->m_script_strings.Count())); +void ContentWriter::WriteScriptStringList(const bool atStreamStart) { + m_stream->PushBlock(XFILE_BLOCK_VIRTUAL); - for (auto i = 0u; i < m_zone->m_script_strings.Count(); i++) - xAssetList.stringList.strings[i] = m_zone->m_script_strings.CValue(i); - } - else - { - xAssetList.stringList.count = 0; - xAssetList.stringList.strings = nullptr; - } + if (atStreamStart) + varScriptStringList = m_stream->Write(varScriptStringList); - const auto assetCount = m_zone->m_pools->GetTotalAssetCount(); - if (assetCount > 0) - { - xAssetList.assetCount = static_cast<int>(assetCount); - xAssetList.assets = static_cast<XAsset*>(memory.Alloc(sizeof(XAsset) * assetCount)); - - const auto end = m_zone->m_pools->end(); - auto index = 0u; - for (auto i = m_zone->m_pools->begin(); i != end; ++i) - { - auto& asset = xAssetList.assets[index++]; - asset.type = static_cast<XAssetType>((*i)->m_type); - asset.header.data = (*i)->m_ptr; - } - } - else - { - xAssetList.assetCount = 0; - xAssetList.assets = nullptr; - } -} + if (varScriptStringList->strings != nullptr) { + m_stream->Align(alignof(const char *)); + varXString = varScriptStringList->strings; + WriteXStringArray(true, varScriptStringList->count); -void ContentWriter::WriteScriptStringList(const bool atStreamStart) -{ - m_stream->PushBlock(XFILE_BLOCK_VIRTUAL); + m_stream->MarkFollowing(varScriptStringList->strings); + } - if (atStreamStart) - varScriptStringList = m_stream->Write(varScriptStringList); + m_stream->PopBlock(); +} - if (varScriptStringList->strings != nullptr) - { - m_stream->Align(alignof(const char*)); - varXString = varScriptStringList->strings; - WriteXStringArray(true, varScriptStringList->count); +void ContentWriter::WriteXAsset(const bool atStreamStart) { +#define WRITE_ASSET(type_index, typeName, headerEntry) \ + case type_index: { \ + Writer_##typeName writer(varXAsset->header.headerEntry, m_zone, m_stream); \ + writer.Write(&varXAsset->header.headerEntry); \ + break; \ + } +#define SKIP_ASSET(type_index, typeName, headerEntry) \ + case type_index: \ + break; - m_stream->MarkFollowing(varScriptStringList->strings); - } + assert(varXAsset != nullptr); - m_stream->PopBlock(); -} + if (atStreamStart) + varXAsset = m_stream->Write(varXAsset); -void ContentWriter::WriteXAsset(const bool atStreamStart) -{ -#define WRITE_ASSET(type_index, typeName, headerEntry) \ - case type_index: \ - { \ - Writer_##typeName writer(varXAsset->header.headerEntry, m_zone, m_stream); \ - writer.Write(&varXAsset->header.headerEntry); \ - break; \ - } -#define SKIP_ASSET(type_index, typeName, headerEntry) \ - case type_index: \ - break; - - assert(varXAsset != nullptr); - - if (atStreamStart) - varXAsset = m_stream->Write(varXAsset); - - switch (varXAsset->type) - { + switch (varXAsset->type) { WRITE_ASSET(ASSET_TYPE_PHYSPRESET, PhysPreset, physPreset) WRITE_ASSET(ASSET_TYPE_PHYSCOLLMAP, PhysCollmap, physCollmap) WRITE_ASSET(ASSET_TYPE_XANIMPARTS, XAnimParts, parts) @@ -166,56 +148,51 @@ void ContentWriter::WriteXAsset(const bool atStreamStart) WRITE_ASSET(ASSET_TYPE_VEHICLE, VehicleDef, vehDef) WRITE_ASSET(ASSET_TYPE_ADDON_MAP_ENTS, AddonMapEnts, addonMapEnts) - default: - { - std::ostringstream str; - str << "Unsupported asset type: " << varXAsset->type << "."; - throw WritingException(str.str()); - } - } + default: { + std::ostringstream str; + str << "Unsupported asset type: " << varXAsset->type << "."; + throw WritingException(str.str()); + } + } #undef WRITE_ASSET #undef SKIP_ASSET } -void ContentWriter::WriteXAssetArray(const bool atStreamStart, const size_t count) -{ - assert(varXAsset != nullptr); +void ContentWriter::WriteXAssetArray(const bool atStreamStart, const size_t count) { + assert(varXAsset != nullptr); - if (atStreamStart) - varXAsset = m_stream->Write(varXAsset, count); + if (atStreamStart) + varXAsset = m_stream->Write(varXAsset, count); - for (size_t index = 0; index < count; index++) - { - WriteXAsset(false); - varXAsset++; - } + for (size_t index = 0; index < count; index++) { + WriteXAsset(false); + varXAsset++; + } } -void ContentWriter::WriteContent(Zone* zone, IZoneOutputStream* stream) -{ - m_zone = zone; - m_stream = stream; +void ContentWriter::WriteContent(Zone *zone, IZoneOutputStream *stream) { + m_zone = zone; + m_stream = stream; - m_stream->PushBlock(XFILE_BLOCK_VIRTUAL); + m_stream->PushBlock(XFILE_BLOCK_VIRTUAL); - MemoryManager memory; - XAssetList assetList{}; + MemoryManager memory; + XAssetList assetList{}; - CreateXAssetList(assetList, memory); + CreateXAssetList(assetList, memory); - varXAssetList = static_cast<XAssetList*>(m_stream->WriteDataRaw(&assetList, sizeof(assetList))); + varXAssetList = static_cast<XAssetList *>(m_stream->WriteDataRaw(&assetList, sizeof(assetList))); - varScriptStringList = &varXAssetList->stringList; - WriteScriptStringList(false); + varScriptStringList = &varXAssetList->stringList; + WriteScriptStringList(false); - if (varXAssetList->assets != nullptr) - { - m_stream->Align(alignof(XAsset)); - varXAsset = varXAssetList->assets; - WriteXAssetArray(true, varXAssetList->assetCount); - m_stream->MarkFollowing(varXAssetList->assets); - } + if (varXAssetList->assets != nullptr) { + m_stream->Align(alignof(XAsset)); + varXAsset = varXAssetList->assets; + WriteXAssetArray(true, varXAssetList->assetCount); + m_stream->MarkFollowing(varXAssetList->assets); + } - m_stream->PopBlock(); + m_stream->PopBlock(); } diff --git a/src/ZoneWriting/Game/IW4/ContentWriterIW4.h b/src/ZoneWriting/Game/IW4/ContentWriterIW4.h index 945d2afcc..aa37e800c 100644 --- a/src/ZoneWriting/Game/IW4/ContentWriterIW4.h +++ b/src/ZoneWriting/Game/IW4/ContentWriterIW4.h @@ -1,26 +1,24 @@ #pragma once +#include "Game/IW4/IW4.h" #include "Writing/ContentWriterBase.h" #include "Writing/IContentWritingEntryPoint.h" -#include "Game/IW4/IW4.h" -namespace IW4 -{ - class ContentWriter final : public ContentWriterBase, public IContentWritingEntryPoint - { - XAssetList* varXAssetList; - XAsset* varXAsset; - ScriptStringList* varScriptStringList; +namespace IW4 { +class ContentWriter final : public ContentWriterBase, public IContentWritingEntryPoint { + XAssetList *varXAssetList; + XAsset *varXAsset; + ScriptStringList *varScriptStringList; - void CreateXAssetList(XAssetList& xAssetList, MemoryManager& memory) const; + void CreateXAssetList(XAssetList &xAssetList, MemoryManager &memory) const; - void WriteScriptStringList(bool atStreamStart); + void WriteScriptStringList(bool atStreamStart); - void WriteXAsset(bool atStreamStart); - void WriteXAssetArray(bool atStreamStart, size_t count); + void WriteXAsset(bool atStreamStart); + void WriteXAssetArray(bool atStreamStart, size_t count); - public: - ContentWriter(); +public: + ContentWriter(); - void WriteContent(Zone* zone, IZoneOutputStream* stream) override; - }; -} + void WriteContent(Zone *zone, IZoneOutputStream *stream) override; +}; +} // namespace IW4 diff --git a/src/ZoneWriting/Game/IW4/ZoneWriterFactoryIW4.cpp b/src/ZoneWriting/Game/IW4/ZoneWriterFactoryIW4.cpp index 50fea07b3..f6ae69d37 100644 --- a/src/ZoneWriting/Game/IW4/ZoneWriterFactoryIW4.cpp +++ b/src/ZoneWriting/Game/IW4/ZoneWriterFactoryIW4.cpp @@ -3,8 +3,8 @@ #include <cstring> #include "ContentWriterIW4.h" -#include "Game/IW4/IW4.h" #include "Game/IW4/GameIW4.h" +#include "Game/IW4/IW4.h" #include "Game/IW4/ZoneConstantsIW4.h" #include "Writing/Processor/OutputProcessorDeflate.h" #include "Writing/Steps/StepAddOutputProcessor.h" @@ -18,95 +18,81 @@ using namespace IW4; -class ZoneWriterFactory::Impl -{ - Zone* m_zone; - std::unique_ptr<ZoneWriter> m_writer; +class ZoneWriterFactory::Impl { + Zone *m_zone; + std::unique_ptr<ZoneWriter> m_writer; public: - explicit Impl(Zone* zone) - : m_zone(zone), - m_writer(std::make_unique<ZoneWriter>()) - { - } + explicit Impl(Zone *zone) : m_zone(zone), m_writer(std::make_unique<ZoneWriter>()) {} - void SetupBlocks() const - { + void SetupBlocks() const { #define XBLOCK_DEF(name, type) std::make_unique<XBlock>(STR(name), name, type) - m_writer->AddXBlock(XBLOCK_DEF(XFILE_BLOCK_TEMP, XBlock::Type::BLOCK_TYPE_TEMP)); - m_writer->AddXBlock(XBLOCK_DEF(XFILE_BLOCK_PHYSICAL, XBlock::Type::BLOCK_TYPE_NORMAL)); - m_writer->AddXBlock(XBLOCK_DEF(XFILE_BLOCK_RUNTIME, XBlock::Type::BLOCK_TYPE_RUNTIME)); - m_writer->AddXBlock(XBLOCK_DEF(XFILE_BLOCK_VIRTUAL, XBlock::Type::BLOCK_TYPE_NORMAL)); - m_writer->AddXBlock(XBLOCK_DEF(XFILE_BLOCK_LARGE, XBlock::Type::BLOCK_TYPE_NORMAL)); - m_writer->AddXBlock(XBLOCK_DEF(XFILE_BLOCK_CALLBACK, XBlock::Type::BLOCK_TYPE_NORMAL)); - m_writer->AddXBlock(XBLOCK_DEF(XFILE_BLOCK_VERTEX, XBlock::Type::BLOCK_TYPE_NORMAL)); - m_writer->AddXBlock(XBLOCK_DEF(XFILE_BLOCK_INDEX, XBlock::Type::BLOCK_TYPE_NORMAL)); + m_writer->AddXBlock(XBLOCK_DEF(XFILE_BLOCK_TEMP, XBlock::Type::BLOCK_TYPE_TEMP)); + m_writer->AddXBlock(XBLOCK_DEF(XFILE_BLOCK_PHYSICAL, XBlock::Type::BLOCK_TYPE_NORMAL)); + m_writer->AddXBlock(XBLOCK_DEF(XFILE_BLOCK_RUNTIME, XBlock::Type::BLOCK_TYPE_RUNTIME)); + m_writer->AddXBlock(XBLOCK_DEF(XFILE_BLOCK_VIRTUAL, XBlock::Type::BLOCK_TYPE_NORMAL)); + m_writer->AddXBlock(XBLOCK_DEF(XFILE_BLOCK_LARGE, XBlock::Type::BLOCK_TYPE_NORMAL)); + m_writer->AddXBlock(XBLOCK_DEF(XFILE_BLOCK_CALLBACK, XBlock::Type::BLOCK_TYPE_NORMAL)); + m_writer->AddXBlock(XBLOCK_DEF(XFILE_BLOCK_VERTEX, XBlock::Type::BLOCK_TYPE_NORMAL)); + m_writer->AddXBlock(XBLOCK_DEF(XFILE_BLOCK_INDEX, XBlock::Type::BLOCK_TYPE_NORMAL)); #undef XBLOCK_DEF + } + + static ZoneHeader CreateHeaderForParams(const bool isSecure, const bool isOfficial) { + ZoneHeader header{}; + header.m_version = ZoneConstants::ZONE_VERSION; + + if (isSecure) { + if (isOfficial) + memcpy(header.m_magic, ZoneConstants::MAGIC_SIGNED_INFINITY_WARD, sizeof(ZoneHeader::m_magic)); + else + memcpy(header.m_magic, ZoneConstants::MAGIC_SIGNED_OAT, sizeof(ZoneHeader::m_magic)); + } else { + memcpy(header.m_magic, ZoneConstants::MAGIC_UNSIGNED, sizeof(ZoneHeader::m_magic)); } - static ZoneHeader CreateHeaderForParams(const bool isSecure, const bool isOfficial) - { - ZoneHeader header{}; - header.m_version = ZoneConstants::ZONE_VERSION; - - if (isSecure) - { - if (isOfficial) - memcpy(header.m_magic, ZoneConstants::MAGIC_SIGNED_INFINITY_WARD, sizeof(ZoneHeader::m_magic)); - else - memcpy(header.m_magic, ZoneConstants::MAGIC_SIGNED_OAT, sizeof(ZoneHeader::m_magic)); - } - else - { - memcpy(header.m_magic, ZoneConstants::MAGIC_UNSIGNED, sizeof(ZoneHeader::m_magic)); - } - - return header; - } + return header; + } - std::unique_ptr<ZoneWriter> CreateWriter() - { - // TODO Support signed fastfiles - bool isSecure = false; + std::unique_ptr<ZoneWriter> CreateWriter() { + // TODO Support signed fastfiles + bool isSecure = false; - SetupBlocks(); + SetupBlocks(); - auto contentInMemory = std::make_unique<StepWriteZoneContentToMemory>(std::make_unique<ContentWriter>(), m_zone, ZoneConstants::OFFSET_BLOCK_BIT_COUNT, ZoneConstants::INSERT_BLOCK); - auto* contentInMemoryPtr = contentInMemory.get(); - m_writer->AddWritingStep(std::move(contentInMemory)); + auto contentInMemory = std::make_unique<StepWriteZoneContentToMemory>(std::make_unique<ContentWriter>(), m_zone, ZoneConstants::OFFSET_BLOCK_BIT_COUNT, + ZoneConstants::INSERT_BLOCK); + auto *contentInMemoryPtr = contentInMemory.get(); + m_writer->AddWritingStep(std::move(contentInMemory)); - // Write zone header - m_writer->AddWritingStep(std::make_unique<StepWriteZoneHeader>(CreateHeaderForParams(isSecure, false))); + // Write zone header + m_writer->AddWritingStep(std::make_unique<StepWriteZoneHeader>(CreateHeaderForParams(isSecure, false))); - // Write dummy byte that the game ignores as well. No clue what it means. - m_writer->AddWritingStep(std::make_unique<StepWriteZero>(1)); + // Write dummy byte that the game ignores as well. No clue what it means. + m_writer->AddWritingStep(std::make_unique<StepWriteZero>(1)); - // Write timestamp - m_writer->AddWritingStep(std::make_unique<StepWriteTimestamp>()); + // Write timestamp + m_writer->AddWritingStep(std::make_unique<StepWriteTimestamp>()); - m_writer->AddWritingStep(std::make_unique<StepAddOutputProcessor>(std::make_unique<OutputProcessorDeflate>())); + m_writer->AddWritingStep(std::make_unique<StepAddOutputProcessor>(std::make_unique<OutputProcessorDeflate>())); - // Start of the XFile struct - m_writer->AddWritingStep(std::make_unique<StepWriteZoneSizes>(contentInMemoryPtr)); - m_writer->AddWritingStep(std::make_unique<StepWriteXBlockSizes>(m_zone)); + // Start of the XFile struct + m_writer->AddWritingStep(std::make_unique<StepWriteZoneSizes>(contentInMemoryPtr)); + m_writer->AddWritingStep(std::make_unique<StepWriteXBlockSizes>(m_zone)); - // Start of the zone content - m_writer->AddWritingStep(std::make_unique<StepWriteZoneContentToFile>(contentInMemoryPtr)); + // Start of the zone content + m_writer->AddWritingStep(std::make_unique<StepWriteZoneContentToFile>(contentInMemoryPtr)); - // Return the fully setup zoneloader - return std::move(m_writer); - } + // Return the fully setup zoneloader + return std::move(m_writer); + } }; -bool ZoneWriterFactory::SupportsZone(Zone* zone) const -{ - return zone->m_game == &g_GameIW4; -} +bool ZoneWriterFactory::SupportsZone(Zone *zone) const { return zone->m_game == &g_GameIW4; } -std::unique_ptr<ZoneWriter> ZoneWriterFactory::CreateWriter(Zone* zone) const -{ - Impl impl(zone); - return impl.CreateWriter(); +std::unique_ptr<ZoneWriter> ZoneWriterFactory::CreateWriter(Zone *zone) const { + Impl impl(zone); + return impl.CreateWriter(); } diff --git a/src/ZoneWriting/Game/IW4/ZoneWriterFactoryIW4.h b/src/ZoneWriting/Game/IW4/ZoneWriterFactoryIW4.h index d6017aa5a..8e1752b3b 100644 --- a/src/ZoneWriting/Game/IW4/ZoneWriterFactoryIW4.h +++ b/src/ZoneWriting/Game/IW4/ZoneWriterFactoryIW4.h @@ -4,14 +4,12 @@ #include "Writing/IZoneWriterFactory.h" -namespace IW4 -{ - class ZoneWriterFactory final : public IZoneWriterFactory - { - class Impl; - - public: - _NODISCARD bool SupportsZone(Zone* zone) const override; - _NODISCARD std::unique_ptr<ZoneWriter> CreateWriter(Zone* zone) const override; - }; -} +namespace IW4 { +class ZoneWriterFactory final : public IZoneWriterFactory { + class Impl; + +public: + _NODISCARD bool SupportsZone(Zone *zone) const override; + _NODISCARD std::unique_ptr<ZoneWriter> CreateWriter(Zone *zone) const override; +}; +} // namespace IW4 diff --git a/src/ZoneWriting/Game/IW5/ContentWriterIW5.cpp b/src/ZoneWriting/Game/IW5/ContentWriterIW5.cpp index 916294a7a..68db69459 100644 --- a/src/ZoneWriting/Game/IW5/ContentWriterIW5.cpp +++ b/src/ZoneWriting/Game/IW5/ContentWriterIW5.cpp @@ -48,91 +48,73 @@ using namespace IW5; -ContentWriter::ContentWriter() - : varXAssetList(nullptr), - varXAsset(nullptr), - varScriptStringList(nullptr) -{ +ContentWriter::ContentWriter() : varXAssetList(nullptr), varXAsset(nullptr), varScriptStringList(nullptr) {} + +void ContentWriter::CreateXAssetList(XAssetList &xAssetList, MemoryManager &memory) const { + if (!m_zone->m_script_strings.Empty()) { + assert(m_zone->m_script_strings.Count() <= SCR_STRING_MAX + 1); + xAssetList.stringList.count = static_cast<int>(m_zone->m_script_strings.Count()); + xAssetList.stringList.strings = static_cast<const char **>(memory.Alloc(sizeof(const char *) * m_zone->m_script_strings.Count())); + + for (auto i = 0u; i < m_zone->m_script_strings.Count(); i++) + xAssetList.stringList.strings[i] = m_zone->m_script_strings.CValue(i); + } else { + xAssetList.stringList.count = 0; + xAssetList.stringList.strings = nullptr; + } + + const auto assetCount = m_zone->m_pools->GetTotalAssetCount(); + if (assetCount > 0) { + xAssetList.assetCount = static_cast<int>(assetCount); + xAssetList.assets = static_cast<XAsset *>(memory.Alloc(sizeof(XAsset) * assetCount)); + + const auto end = m_zone->m_pools->end(); + auto index = 0u; + for (auto i = m_zone->m_pools->begin(); i != end; ++i) { + auto &asset = xAssetList.assets[index++]; + asset.type = static_cast<XAssetType>((*i)->m_type); + asset.header.data = (*i)->m_ptr; + } + } else { + xAssetList.assetCount = 0; + xAssetList.assets = nullptr; + } } -void ContentWriter::CreateXAssetList(XAssetList& xAssetList, MemoryManager& memory) const -{ - if (!m_zone->m_script_strings.Empty()) - { - assert(m_zone->m_script_strings.Count() <= SCR_STRING_MAX + 1); - xAssetList.stringList.count = static_cast<int>(m_zone->m_script_strings.Count()); - xAssetList.stringList.strings = static_cast<const char**>(memory.Alloc(sizeof(const char*) * m_zone->m_script_strings.Count())); +void ContentWriter::WriteScriptStringList(const bool atStreamStart) { + m_stream->PushBlock(XFILE_BLOCK_VIRTUAL); - for (auto i = 0u; i < m_zone->m_script_strings.Count(); i++) - xAssetList.stringList.strings[i] = m_zone->m_script_strings.CValue(i); - } - else - { - xAssetList.stringList.count = 0; - xAssetList.stringList.strings = nullptr; - } + if (atStreamStart) + varScriptStringList = m_stream->Write(varScriptStringList); - const auto assetCount = m_zone->m_pools->GetTotalAssetCount(); - if (assetCount > 0) - { - xAssetList.assetCount = static_cast<int>(assetCount); - xAssetList.assets = static_cast<XAsset*>(memory.Alloc(sizeof(XAsset) * assetCount)); - - const auto end = m_zone->m_pools->end(); - auto index = 0u; - for (auto i = m_zone->m_pools->begin(); i != end; ++i) - { - auto& asset = xAssetList.assets[index++]; - asset.type = static_cast<XAssetType>((*i)->m_type); - asset.header.data = (*i)->m_ptr; - } - } - else - { - xAssetList.assetCount = 0; - xAssetList.assets = nullptr; - } -} + if (varScriptStringList->strings != nullptr) { + m_stream->Align(alignof(const char *)); + varXString = varScriptStringList->strings; + WriteXStringArray(true, varScriptStringList->count); -void ContentWriter::WriteScriptStringList(const bool atStreamStart) -{ - m_stream->PushBlock(XFILE_BLOCK_VIRTUAL); + m_stream->MarkFollowing(varScriptStringList->strings); + } - if (atStreamStart) - varScriptStringList = m_stream->Write(varScriptStringList); + m_stream->PopBlock(); +} - if (varScriptStringList->strings != nullptr) - { - m_stream->Align(alignof(const char*)); - varXString = varScriptStringList->strings; - WriteXStringArray(true, varScriptStringList->count); +void ContentWriter::WriteXAsset(const bool atStreamStart) { +#define WRITE_ASSET(type_index, typeName, headerEntry) \ + case type_index: { \ + Writer_##typeName writer(varXAsset->header.headerEntry, m_zone, m_stream); \ + writer.Write(&varXAsset->header.headerEntry); \ + break; \ + } +#define SKIP_ASSET(type_index, typeName, headerEntry) \ + case type_index: \ + break; - m_stream->MarkFollowing(varScriptStringList->strings); - } + assert(varXAsset != nullptr); - m_stream->PopBlock(); -} + if (atStreamStart) + varXAsset = m_stream->Write(varXAsset); -void ContentWriter::WriteXAsset(const bool atStreamStart) -{ -#define WRITE_ASSET(type_index, typeName, headerEntry) \ - case type_index: \ - { \ - Writer_##typeName writer(varXAsset->header.headerEntry, m_zone, m_stream); \ - writer.Write(&varXAsset->header.headerEntry); \ - break; \ - } -#define SKIP_ASSET(type_index, typeName, headerEntry) \ - case type_index: \ - break; - - assert(varXAsset != nullptr); - - if (atStreamStart) - varXAsset = m_stream->Write(varXAsset); - - switch (varXAsset->type) - { + switch (varXAsset->type) { WRITE_ASSET(ASSET_TYPE_PHYSPRESET, PhysPreset, physPreset) WRITE_ASSET(ASSET_TYPE_PHYSCOLLMAP, PhysCollmap, physCollmap) WRITE_ASSET(ASSET_TYPE_XANIMPARTS, XAnimParts, parts) @@ -174,56 +156,51 @@ void ContentWriter::WriteXAsset(const bool atStreamStart) WRITE_ASSET(ASSET_TYPE_VEHICLE, VehicleDef, vehDef) WRITE_ASSET(ASSET_TYPE_ADDON_MAP_ENTS, AddonMapEnts, addonMapEnts) - default: - { - std::ostringstream str; - str << "Unsupported asset type: " << varXAsset->type << "."; - throw WritingException(str.str()); - } - } + default: { + std::ostringstream str; + str << "Unsupported asset type: " << varXAsset->type << "."; + throw WritingException(str.str()); + } + } #undef WRITE_ASSET #undef SKIP_ASSET } -void ContentWriter::WriteXAssetArray(const bool atStreamStart, const size_t count) -{ - assert(varXAsset != nullptr); +void ContentWriter::WriteXAssetArray(const bool atStreamStart, const size_t count) { + assert(varXAsset != nullptr); - if (atStreamStart) - varXAsset = m_stream->Write(varXAsset, count); + if (atStreamStart) + varXAsset = m_stream->Write(varXAsset, count); - for (size_t index = 0; index < count; index++) - { - WriteXAsset(false); - varXAsset++; - } + for (size_t index = 0; index < count; index++) { + WriteXAsset(false); + varXAsset++; + } } -void ContentWriter::WriteContent(Zone* zone, IZoneOutputStream* stream) -{ - m_zone = zone; - m_stream = stream; +void ContentWriter::WriteContent(Zone *zone, IZoneOutputStream *stream) { + m_zone = zone; + m_stream = stream; - m_stream->PushBlock(XFILE_BLOCK_VIRTUAL); + m_stream->PushBlock(XFILE_BLOCK_VIRTUAL); - MemoryManager memory; - XAssetList assetList{}; + MemoryManager memory; + XAssetList assetList{}; - CreateXAssetList(assetList, memory); + CreateXAssetList(assetList, memory); - varXAssetList = static_cast<XAssetList*>(m_stream->WriteDataRaw(&assetList, sizeof(assetList))); + varXAssetList = static_cast<XAssetList *>(m_stream->WriteDataRaw(&assetList, sizeof(assetList))); - varScriptStringList = &varXAssetList->stringList; - WriteScriptStringList(false); + varScriptStringList = &varXAssetList->stringList; + WriteScriptStringList(false); - if (varXAssetList->assets != nullptr) - { - m_stream->Align(alignof(XAsset)); - varXAsset = varXAssetList->assets; - WriteXAssetArray(true, varXAssetList->assetCount); - m_stream->MarkFollowing(varXAssetList->assets); - } + if (varXAssetList->assets != nullptr) { + m_stream->Align(alignof(XAsset)); + varXAsset = varXAssetList->assets; + WriteXAssetArray(true, varXAssetList->assetCount); + m_stream->MarkFollowing(varXAssetList->assets); + } - m_stream->PopBlock(); + m_stream->PopBlock(); } diff --git a/src/ZoneWriting/Game/IW5/ContentWriterIW5.h b/src/ZoneWriting/Game/IW5/ContentWriterIW5.h index c90384b30..a31b978ae 100644 --- a/src/ZoneWriting/Game/IW5/ContentWriterIW5.h +++ b/src/ZoneWriting/Game/IW5/ContentWriterIW5.h @@ -1,26 +1,24 @@ #pragma once +#include "Game/IW5/IW5.h" #include "Writing/ContentWriterBase.h" #include "Writing/IContentWritingEntryPoint.h" -#include "Game/IW5/IW5.h" -namespace IW5 -{ - class ContentWriter final : public ContentWriterBase, public IContentWritingEntryPoint - { - XAssetList* varXAssetList; - XAsset* varXAsset; - ScriptStringList* varScriptStringList; +namespace IW5 { +class ContentWriter final : public ContentWriterBase, public IContentWritingEntryPoint { + XAssetList *varXAssetList; + XAsset *varXAsset; + ScriptStringList *varScriptStringList; - void CreateXAssetList(XAssetList& xAssetList, MemoryManager& memory) const; + void CreateXAssetList(XAssetList &xAssetList, MemoryManager &memory) const; - void WriteScriptStringList(bool atStreamStart); + void WriteScriptStringList(bool atStreamStart); - void WriteXAsset(bool atStreamStart); - void WriteXAssetArray(bool atStreamStart, size_t count); + void WriteXAsset(bool atStreamStart); + void WriteXAssetArray(bool atStreamStart, size_t count); - public: - ContentWriter(); +public: + ContentWriter(); - void WriteContent(Zone* zone, IZoneOutputStream* stream) override; - }; -} + void WriteContent(Zone *zone, IZoneOutputStream *stream) override; +}; +} // namespace IW5 diff --git a/src/ZoneWriting/Game/IW5/ZoneWriterFactoryIW5.cpp b/src/ZoneWriting/Game/IW5/ZoneWriterFactoryIW5.cpp index 0457f8e6a..6e57d7085 100644 --- a/src/ZoneWriting/Game/IW5/ZoneWriterFactoryIW5.cpp +++ b/src/ZoneWriting/Game/IW5/ZoneWriterFactoryIW5.cpp @@ -3,8 +3,8 @@ #include <cstring> #include "ContentWriterIW5.h" -#include "Game/IW5/IW5.h" #include "Game/IW5/GameIW5.h" +#include "Game/IW5/IW5.h" #include "Game/IW5/ZoneConstantsIW5.h" #include "Writing/Processor/OutputProcessorDeflate.h" #include "Writing/Steps/StepAddOutputProcessor.h" @@ -18,96 +18,82 @@ using namespace IW5; -class ZoneWriterFactory::Impl -{ - Zone* m_zone; - std::unique_ptr<ZoneWriter> m_writer; +class ZoneWriterFactory::Impl { + Zone *m_zone; + std::unique_ptr<ZoneWriter> m_writer; public: - explicit Impl(Zone* zone) - : m_zone(zone), - m_writer(std::make_unique<ZoneWriter>()) - { - } + explicit Impl(Zone *zone) : m_zone(zone), m_writer(std::make_unique<ZoneWriter>()) {} - void SetupBlocks() const - { + void SetupBlocks() const { #define XBLOCK_DEF(name, type) std::make_unique<XBlock>(STR(name), name, type) - m_writer->AddXBlock(XBLOCK_DEF(XFILE_BLOCK_TEMP, XBlock::Type::BLOCK_TYPE_TEMP)); - m_writer->AddXBlock(XBLOCK_DEF(XFILE_BLOCK_PHYSICAL, XBlock::Type::BLOCK_TYPE_NORMAL)); - m_writer->AddXBlock(XBLOCK_DEF(XFILE_BLOCK_RUNTIME, XBlock::Type::BLOCK_TYPE_RUNTIME)); - m_writer->AddXBlock(XBLOCK_DEF(XFILE_BLOCK_VIRTUAL, XBlock::Type::BLOCK_TYPE_NORMAL)); - m_writer->AddXBlock(XBLOCK_DEF(XFILE_BLOCK_LARGE, XBlock::Type::BLOCK_TYPE_NORMAL)); - m_writer->AddXBlock(XBLOCK_DEF(XFILE_BLOCK_CALLBACK, XBlock::Type::BLOCK_TYPE_NORMAL)); - m_writer->AddXBlock(XBLOCK_DEF(XFILE_BLOCK_VERTEX, XBlock::Type::BLOCK_TYPE_NORMAL)); - m_writer->AddXBlock(XBLOCK_DEF(XFILE_BLOCK_INDEX, XBlock::Type::BLOCK_TYPE_NORMAL)); - m_writer->AddXBlock(XBLOCK_DEF(XFILE_BLOCK_SCRIPT, XBlock::Type::BLOCK_TYPE_NORMAL)); + m_writer->AddXBlock(XBLOCK_DEF(XFILE_BLOCK_TEMP, XBlock::Type::BLOCK_TYPE_TEMP)); + m_writer->AddXBlock(XBLOCK_DEF(XFILE_BLOCK_PHYSICAL, XBlock::Type::BLOCK_TYPE_NORMAL)); + m_writer->AddXBlock(XBLOCK_DEF(XFILE_BLOCK_RUNTIME, XBlock::Type::BLOCK_TYPE_RUNTIME)); + m_writer->AddXBlock(XBLOCK_DEF(XFILE_BLOCK_VIRTUAL, XBlock::Type::BLOCK_TYPE_NORMAL)); + m_writer->AddXBlock(XBLOCK_DEF(XFILE_BLOCK_LARGE, XBlock::Type::BLOCK_TYPE_NORMAL)); + m_writer->AddXBlock(XBLOCK_DEF(XFILE_BLOCK_CALLBACK, XBlock::Type::BLOCK_TYPE_NORMAL)); + m_writer->AddXBlock(XBLOCK_DEF(XFILE_BLOCK_VERTEX, XBlock::Type::BLOCK_TYPE_NORMAL)); + m_writer->AddXBlock(XBLOCK_DEF(XFILE_BLOCK_INDEX, XBlock::Type::BLOCK_TYPE_NORMAL)); + m_writer->AddXBlock(XBLOCK_DEF(XFILE_BLOCK_SCRIPT, XBlock::Type::BLOCK_TYPE_NORMAL)); #undef XBLOCK_DEF + } + + static ZoneHeader CreateHeaderForParams(const bool isSecure, const bool isOfficial) { + ZoneHeader header{}; + header.m_version = ZoneConstants::ZONE_VERSION; + + if (isSecure) { + if (isOfficial) + memcpy(header.m_magic, ZoneConstants::MAGIC_SIGNED_INFINITY_WARD, sizeof(ZoneHeader::m_magic)); + else + memcpy(header.m_magic, ZoneConstants::MAGIC_SIGNED_OAT, sizeof(ZoneHeader::m_magic)); + } else { + memcpy(header.m_magic, ZoneConstants::MAGIC_UNSIGNED, sizeof(ZoneHeader::m_magic)); } - static ZoneHeader CreateHeaderForParams(const bool isSecure, const bool isOfficial) - { - ZoneHeader header{}; - header.m_version = ZoneConstants::ZONE_VERSION; - - if (isSecure) - { - if (isOfficial) - memcpy(header.m_magic, ZoneConstants::MAGIC_SIGNED_INFINITY_WARD, sizeof(ZoneHeader::m_magic)); - else - memcpy(header.m_magic, ZoneConstants::MAGIC_SIGNED_OAT, sizeof(ZoneHeader::m_magic)); - } - else - { - memcpy(header.m_magic, ZoneConstants::MAGIC_UNSIGNED, sizeof(ZoneHeader::m_magic)); - } - - return header; - } + return header; + } - std::unique_ptr<ZoneWriter> CreateWriter() - { - // TODO Support signed fastfiles - bool isSecure = false; + std::unique_ptr<ZoneWriter> CreateWriter() { + // TODO Support signed fastfiles + bool isSecure = false; - SetupBlocks(); + SetupBlocks(); - auto contentInMemory = std::make_unique<StepWriteZoneContentToMemory>(std::make_unique<ContentWriter>(), m_zone, ZoneConstants::OFFSET_BLOCK_BIT_COUNT, ZoneConstants::INSERT_BLOCK); - auto* contentInMemoryPtr = contentInMemory.get(); - m_writer->AddWritingStep(std::move(contentInMemory)); + auto contentInMemory = std::make_unique<StepWriteZoneContentToMemory>(std::make_unique<ContentWriter>(), m_zone, ZoneConstants::OFFSET_BLOCK_BIT_COUNT, + ZoneConstants::INSERT_BLOCK); + auto *contentInMemoryPtr = contentInMemory.get(); + m_writer->AddWritingStep(std::move(contentInMemory)); - // Write zone header - m_writer->AddWritingStep(std::make_unique<StepWriteZoneHeader>(CreateHeaderForParams(isSecure, false))); + // Write zone header + m_writer->AddWritingStep(std::make_unique<StepWriteZoneHeader>(CreateHeaderForParams(isSecure, false))); - // Write dummy byte that the game ignores as well. No clue what it means. - m_writer->AddWritingStep(std::make_unique<StepWriteZero>(1)); + // Write dummy byte that the game ignores as well. No clue what it means. + m_writer->AddWritingStep(std::make_unique<StepWriteZero>(1)); - // Write timestamp - m_writer->AddWritingStep(std::make_unique<StepWriteTimestamp>()); + // Write timestamp + m_writer->AddWritingStep(std::make_unique<StepWriteTimestamp>()); - m_writer->AddWritingStep(std::make_unique<StepAddOutputProcessor>(std::make_unique<OutputProcessorDeflate>())); + m_writer->AddWritingStep(std::make_unique<StepAddOutputProcessor>(std::make_unique<OutputProcessorDeflate>())); - // Start of the XFile struct - m_writer->AddWritingStep(std::make_unique<StepWriteZoneSizes>(contentInMemoryPtr)); - m_writer->AddWritingStep(std::make_unique<StepWriteXBlockSizes>(m_zone)); + // Start of the XFile struct + m_writer->AddWritingStep(std::make_unique<StepWriteZoneSizes>(contentInMemoryPtr)); + m_writer->AddWritingStep(std::make_unique<StepWriteXBlockSizes>(m_zone)); - // Start of the zone content - m_writer->AddWritingStep(std::make_unique<StepWriteZoneContentToFile>(contentInMemoryPtr)); + // Start of the zone content + m_writer->AddWritingStep(std::make_unique<StepWriteZoneContentToFile>(contentInMemoryPtr)); - // Return the fully setup zoneloader - return std::move(m_writer); - } + // Return the fully setup zoneloader + return std::move(m_writer); + } }; -bool ZoneWriterFactory::SupportsZone(Zone* zone) const -{ - return zone->m_game == &g_GameIW5; -} +bool ZoneWriterFactory::SupportsZone(Zone *zone) const { return zone->m_game == &g_GameIW5; } -std::unique_ptr<ZoneWriter> ZoneWriterFactory::CreateWriter(Zone* zone) const -{ - Impl impl(zone); - return impl.CreateWriter(); +std::unique_ptr<ZoneWriter> ZoneWriterFactory::CreateWriter(Zone *zone) const { + Impl impl(zone); + return impl.CreateWriter(); } diff --git a/src/ZoneWriting/Game/IW5/ZoneWriterFactoryIW5.h b/src/ZoneWriting/Game/IW5/ZoneWriterFactoryIW5.h index beb5147fa..1c973c58a 100644 --- a/src/ZoneWriting/Game/IW5/ZoneWriterFactoryIW5.h +++ b/src/ZoneWriting/Game/IW5/ZoneWriterFactoryIW5.h @@ -4,14 +4,12 @@ #include "Writing/IZoneWriterFactory.h" -namespace IW5 -{ - class ZoneWriterFactory final : public IZoneWriterFactory - { - class Impl; - - public: - _NODISCARD bool SupportsZone(Zone* zone) const override; - _NODISCARD std::unique_ptr<ZoneWriter> CreateWriter(Zone* zone) const override; - }; -} +namespace IW5 { +class ZoneWriterFactory final : public IZoneWriterFactory { + class Impl; + +public: + _NODISCARD bool SupportsZone(Zone *zone) const override; + _NODISCARD std::unique_ptr<ZoneWriter> CreateWriter(Zone *zone) const override; +}; +} // namespace IW5 diff --git a/src/ZoneWriting/Game/T5/ContentWriterT5.cpp b/src/ZoneWriting/Game/T5/ContentWriterT5.cpp index ef7b02466..12a61fca6 100644 --- a/src/ZoneWriting/Game/T5/ContentWriterT5.cpp +++ b/src/ZoneWriting/Game/T5/ContentWriterT5.cpp @@ -40,91 +40,73 @@ using namespace T5; -ContentWriter::ContentWriter() - : varXAssetList(nullptr), - varXAsset(nullptr), - varScriptStringList(nullptr) -{ +ContentWriter::ContentWriter() : varXAssetList(nullptr), varXAsset(nullptr), varScriptStringList(nullptr) {} + +void ContentWriter::CreateXAssetList(XAssetList &xAssetList, MemoryManager &memory) const { + if (!m_zone->m_script_strings.Empty()) { + assert(m_zone->m_script_strings.Count() <= SCR_STRING_MAX + 1); + xAssetList.stringList.count = static_cast<int>(m_zone->m_script_strings.Count()); + xAssetList.stringList.strings = static_cast<const char **>(memory.Alloc(sizeof(const char *) * m_zone->m_script_strings.Count())); + + for (auto i = 0u; i < m_zone->m_script_strings.Count(); i++) + xAssetList.stringList.strings[i] = m_zone->m_script_strings.CValue(i); + } else { + xAssetList.stringList.count = 0; + xAssetList.stringList.strings = nullptr; + } + + const auto assetCount = m_zone->m_pools->GetTotalAssetCount(); + if (assetCount > 0) { + xAssetList.assetCount = static_cast<int>(assetCount); + xAssetList.assets = static_cast<XAsset *>(memory.Alloc(sizeof(XAsset) * assetCount)); + + const auto end = m_zone->m_pools->end(); + auto index = 0u; + for (auto i = m_zone->m_pools->begin(); i != end; ++i) { + auto &asset = xAssetList.assets[index++]; + asset.type = static_cast<XAssetType>((*i)->m_type); + asset.header.data = (*i)->m_ptr; + } + } else { + xAssetList.assetCount = 0; + xAssetList.assets = nullptr; + } } -void ContentWriter::CreateXAssetList(XAssetList& xAssetList, MemoryManager& memory) const -{ - if (!m_zone->m_script_strings.Empty()) - { - assert(m_zone->m_script_strings.Count() <= SCR_STRING_MAX + 1); - xAssetList.stringList.count = static_cast<int>(m_zone->m_script_strings.Count()); - xAssetList.stringList.strings = static_cast<const char**>(memory.Alloc(sizeof(const char*) * m_zone->m_script_strings.Count())); +void ContentWriter::WriteScriptStringList(const bool atStreamStart) { + m_stream->PushBlock(XFILE_BLOCK_VIRTUAL); - for (auto i = 0u; i < m_zone->m_script_strings.Count(); i++) - xAssetList.stringList.strings[i] = m_zone->m_script_strings.CValue(i); - } - else - { - xAssetList.stringList.count = 0; - xAssetList.stringList.strings = nullptr; - } + if (atStreamStart) + varScriptStringList = m_stream->Write(varScriptStringList); - const auto assetCount = m_zone->m_pools->GetTotalAssetCount(); - if (assetCount > 0) - { - xAssetList.assetCount = static_cast<int>(assetCount); - xAssetList.assets = static_cast<XAsset*>(memory.Alloc(sizeof(XAsset) * assetCount)); - - const auto end = m_zone->m_pools->end(); - auto index = 0u; - for (auto i = m_zone->m_pools->begin(); i != end; ++i) - { - auto& asset = xAssetList.assets[index++]; - asset.type = static_cast<XAssetType>((*i)->m_type); - asset.header.data = (*i)->m_ptr; - } - } - else - { - xAssetList.assetCount = 0; - xAssetList.assets = nullptr; - } -} + if (varScriptStringList->strings != nullptr) { + m_stream->Align(alignof(const char *)); + varXString = varScriptStringList->strings; + WriteXStringArray(true, varScriptStringList->count); -void ContentWriter::WriteScriptStringList(const bool atStreamStart) -{ - m_stream->PushBlock(XFILE_BLOCK_VIRTUAL); + m_stream->MarkFollowing(varScriptStringList->strings); + } - if (atStreamStart) - varScriptStringList = m_stream->Write(varScriptStringList); + m_stream->PopBlock(); +} - if (varScriptStringList->strings != nullptr) - { - m_stream->Align(alignof(const char*)); - varXString = varScriptStringList->strings; - WriteXStringArray(true, varScriptStringList->count); +void ContentWriter::WriteXAsset(const bool atStreamStart) { +#define WRITE_ASSET(type_index, typeName, headerEntry) \ + case type_index: { \ + Writer_##typeName writer(varXAsset->header.headerEntry, m_zone, m_stream); \ + writer.Write(&varXAsset->header.headerEntry); \ + break; \ + } +#define SKIP_ASSET(type_index, typeName, headerEntry) \ + case type_index: \ + break; - m_stream->MarkFollowing(varScriptStringList->strings); - } + assert(varXAsset != nullptr); - m_stream->PopBlock(); -} + if (atStreamStart) + varXAsset = m_stream->Write(varXAsset); -void ContentWriter::WriteXAsset(const bool atStreamStart) -{ -#define WRITE_ASSET(type_index, typeName, headerEntry) \ - case type_index: \ - { \ - Writer_##typeName writer(varXAsset->header.headerEntry, m_zone, m_stream); \ - writer.Write(&varXAsset->header.headerEntry); \ - break; \ - } -#define SKIP_ASSET(type_index, typeName, headerEntry) \ - case type_index: \ - break; - - assert(varXAsset != nullptr); - - if (atStreamStart) - varXAsset = m_stream->Write(varXAsset); - - switch (varXAsset->type) - { + switch (varXAsset->type) { WRITE_ASSET(ASSET_TYPE_PHYSPRESET, PhysPreset, physPreset) WRITE_ASSET(ASSET_TYPE_PHYSCONSTRAINTS, PhysConstraints, physConstraints) WRITE_ASSET(ASSET_TYPE_DESTRUCTIBLEDEF, DestructibleDef, destructibleDef) @@ -159,56 +141,51 @@ void ContentWriter::WriteXAsset(const bool atStreamStart) WRITE_ASSET(ASSET_TYPE_GLASSES, Glasses, glasses) WRITE_ASSET(ASSET_TYPE_EMBLEMSET, EmblemSet, emblemSet) - default: - { - std::ostringstream str; - str << "Unsupported asset type: " << varXAsset->type << "."; - throw WritingException(str.str()); - } - } + default: { + std::ostringstream str; + str << "Unsupported asset type: " << varXAsset->type << "."; + throw WritingException(str.str()); + } + } #undef WRITE_ASSET #undef SKIP_ASSET } -void ContentWriter::WriteXAssetArray(const bool atStreamStart, const size_t count) -{ - assert(varXAsset != nullptr); +void ContentWriter::WriteXAssetArray(const bool atStreamStart, const size_t count) { + assert(varXAsset != nullptr); - if (atStreamStart) - varXAsset = m_stream->Write(varXAsset, count); + if (atStreamStart) + varXAsset = m_stream->Write(varXAsset, count); - for (size_t index = 0; index < count; index++) - { - WriteXAsset(false); - varXAsset++; - } + for (size_t index = 0; index < count; index++) { + WriteXAsset(false); + varXAsset++; + } } -void ContentWriter::WriteContent(Zone* zone, IZoneOutputStream* stream) -{ - m_zone = zone; - m_stream = stream; +void ContentWriter::WriteContent(Zone *zone, IZoneOutputStream *stream) { + m_zone = zone; + m_stream = stream; - m_stream->PushBlock(XFILE_BLOCK_VIRTUAL); + m_stream->PushBlock(XFILE_BLOCK_VIRTUAL); - MemoryManager memory; - XAssetList assetList{}; + MemoryManager memory; + XAssetList assetList{}; - CreateXAssetList(assetList, memory); + CreateXAssetList(assetList, memory); - varXAssetList = static_cast<XAssetList*>(m_stream->WriteDataRaw(&assetList, sizeof(assetList))); + varXAssetList = static_cast<XAssetList *>(m_stream->WriteDataRaw(&assetList, sizeof(assetList))); - varScriptStringList = &varXAssetList->stringList; - WriteScriptStringList(false); + varScriptStringList = &varXAssetList->stringList; + WriteScriptStringList(false); - if (varXAssetList->assets != nullptr) - { - m_stream->Align(alignof(XAsset)); - varXAsset = varXAssetList->assets; - WriteXAssetArray(true, varXAssetList->assetCount); - m_stream->MarkFollowing(varXAssetList->assets); - } + if (varXAssetList->assets != nullptr) { + m_stream->Align(alignof(XAsset)); + varXAsset = varXAssetList->assets; + WriteXAssetArray(true, varXAssetList->assetCount); + m_stream->MarkFollowing(varXAssetList->assets); + } - m_stream->PopBlock(); + m_stream->PopBlock(); } diff --git a/src/ZoneWriting/Game/T5/ContentWriterT5.h b/src/ZoneWriting/Game/T5/ContentWriterT5.h index 51b118ad8..44d7a0c07 100644 --- a/src/ZoneWriting/Game/T5/ContentWriterT5.h +++ b/src/ZoneWriting/Game/T5/ContentWriterT5.h @@ -1,26 +1,24 @@ #pragma once +#include "Game/T5/T5.h" #include "Writing/ContentWriterBase.h" #include "Writing/IContentWritingEntryPoint.h" -#include "Game/T5/T5.h" -namespace T5 -{ - class ContentWriter final : public ContentWriterBase, public IContentWritingEntryPoint - { - XAssetList* varXAssetList; - XAsset* varXAsset; - ScriptStringList* varScriptStringList; +namespace T5 { +class ContentWriter final : public ContentWriterBase, public IContentWritingEntryPoint { + XAssetList *varXAssetList; + XAsset *varXAsset; + ScriptStringList *varScriptStringList; - void CreateXAssetList(XAssetList& xAssetList, MemoryManager& memory) const; + void CreateXAssetList(XAssetList &xAssetList, MemoryManager &memory) const; - void WriteScriptStringList(bool atStreamStart); + void WriteScriptStringList(bool atStreamStart); - void WriteXAsset(bool atStreamStart); - void WriteXAssetArray(bool atStreamStart, size_t count); + void WriteXAsset(bool atStreamStart); + void WriteXAssetArray(bool atStreamStart, size_t count); - public: - ContentWriter(); +public: + ContentWriter(); - void WriteContent(Zone* zone, IZoneOutputStream* stream) override; - }; -} + void WriteContent(Zone *zone, IZoneOutputStream *stream) override; +}; +} // namespace T5 diff --git a/src/ZoneWriting/Game/T5/ZoneWriterFactoryT5.cpp b/src/ZoneWriting/Game/T5/ZoneWriterFactoryT5.cpp index 4eae84b6a..43de0baaa 100644 --- a/src/ZoneWriting/Game/T5/ZoneWriterFactoryT5.cpp +++ b/src/ZoneWriting/Game/T5/ZoneWriterFactoryT5.cpp @@ -3,8 +3,8 @@ #include <cstring> #include "ContentWriterT5.h" -#include "Game/T5/T5.h" #include "Game/T5/GameT5.h" +#include "Game/T5/T5.h" #include "Game/T5/ZoneConstantsT5.h" #include "Writing/Processor/OutputProcessorDeflate.h" #include "Writing/Steps/StepAddOutputProcessor.h" @@ -16,74 +16,63 @@ using namespace T5; -class ZoneWriterFactory::Impl -{ - Zone* m_zone; - std::unique_ptr<ZoneWriter> m_writer; +class ZoneWriterFactory::Impl { + Zone *m_zone; + std::unique_ptr<ZoneWriter> m_writer; public: - explicit Impl(Zone* zone) - : m_zone(zone), - m_writer(std::make_unique<ZoneWriter>()) - { - } - - void SetupBlocks() const - { + explicit Impl(Zone *zone) : m_zone(zone), m_writer(std::make_unique<ZoneWriter>()) {} + + void SetupBlocks() const { #define XBLOCK_DEF(name, type) std::make_unique<XBlock>(STR(name), name, type) - m_writer->AddXBlock(XBLOCK_DEF(T5::XFILE_BLOCK_TEMP, XBlock::Type::BLOCK_TYPE_TEMP)); - m_writer->AddXBlock(XBLOCK_DEF(T5::XFILE_BLOCK_RUNTIME, XBlock::Type::BLOCK_TYPE_RUNTIME)); - m_writer->AddXBlock(XBLOCK_DEF(T5::XFILE_BLOCK_LARGE_RUNTIME, XBlock::Type::BLOCK_TYPE_RUNTIME)); - m_writer->AddXBlock(XBLOCK_DEF(T5::XFILE_BLOCK_PHYSICAL_RUNTIME, XBlock::Type::BLOCK_TYPE_RUNTIME)); - m_writer->AddXBlock(XBLOCK_DEF(T5::XFILE_BLOCK_VIRTUAL, XBlock::Type::BLOCK_TYPE_NORMAL)); - m_writer->AddXBlock(XBLOCK_DEF(T5::XFILE_BLOCK_LARGE, XBlock::Type::BLOCK_TYPE_NORMAL)); - m_writer->AddXBlock(XBLOCK_DEF(T5::XFILE_BLOCK_PHYSICAL, XBlock::Type::BLOCK_TYPE_NORMAL)); + m_writer->AddXBlock(XBLOCK_DEF(T5::XFILE_BLOCK_TEMP, XBlock::Type::BLOCK_TYPE_TEMP)); + m_writer->AddXBlock(XBLOCK_DEF(T5::XFILE_BLOCK_RUNTIME, XBlock::Type::BLOCK_TYPE_RUNTIME)); + m_writer->AddXBlock(XBLOCK_DEF(T5::XFILE_BLOCK_LARGE_RUNTIME, XBlock::Type::BLOCK_TYPE_RUNTIME)); + m_writer->AddXBlock(XBLOCK_DEF(T5::XFILE_BLOCK_PHYSICAL_RUNTIME, XBlock::Type::BLOCK_TYPE_RUNTIME)); + m_writer->AddXBlock(XBLOCK_DEF(T5::XFILE_BLOCK_VIRTUAL, XBlock::Type::BLOCK_TYPE_NORMAL)); + m_writer->AddXBlock(XBLOCK_DEF(T5::XFILE_BLOCK_LARGE, XBlock::Type::BLOCK_TYPE_NORMAL)); + m_writer->AddXBlock(XBLOCK_DEF(T5::XFILE_BLOCK_PHYSICAL, XBlock::Type::BLOCK_TYPE_NORMAL)); #undef XBLOCK_DEF - } + } - static ZoneHeader CreateHeaderForParams() - { - ZoneHeader header{}; - header.m_version = ZoneConstants::ZONE_VERSION; - memcpy(header.m_magic, ZoneConstants::MAGIC_UNSIGNED, sizeof(ZoneHeader::m_magic)); + static ZoneHeader CreateHeaderForParams() { + ZoneHeader header{}; + header.m_version = ZoneConstants::ZONE_VERSION; + memcpy(header.m_magic, ZoneConstants::MAGIC_UNSIGNED, sizeof(ZoneHeader::m_magic)); - return header; - } + return header; + } - std::unique_ptr<ZoneWriter> CreateWriter() - { - SetupBlocks(); + std::unique_ptr<ZoneWriter> CreateWriter() { + SetupBlocks(); - auto contentInMemory = std::make_unique<StepWriteZoneContentToMemory>(std::make_unique<ContentWriter>(), m_zone, ZoneConstants::OFFSET_BLOCK_BIT_COUNT, ZoneConstants::INSERT_BLOCK); - auto* contentInMemoryPtr = contentInMemory.get(); - m_writer->AddWritingStep(std::move(contentInMemory)); + auto contentInMemory = std::make_unique<StepWriteZoneContentToMemory>(std::make_unique<ContentWriter>(), m_zone, ZoneConstants::OFFSET_BLOCK_BIT_COUNT, + ZoneConstants::INSERT_BLOCK); + auto *contentInMemoryPtr = contentInMemory.get(); + m_writer->AddWritingStep(std::move(contentInMemory)); - // Write zone header - m_writer->AddWritingStep(std::make_unique<StepWriteZoneHeader>(CreateHeaderForParams())); + // Write zone header + m_writer->AddWritingStep(std::make_unique<StepWriteZoneHeader>(CreateHeaderForParams())); - m_writer->AddWritingStep(std::make_unique<StepAddOutputProcessor>(std::make_unique<OutputProcessorDeflate>())); + m_writer->AddWritingStep(std::make_unique<StepAddOutputProcessor>(std::make_unique<OutputProcessorDeflate>())); - // Start of the XFile struct - m_writer->AddWritingStep(std::make_unique<StepWriteZoneSizes>(contentInMemoryPtr)); - m_writer->AddWritingStep(std::make_unique<StepWriteXBlockSizes>(m_zone)); + // Start of the XFile struct + m_writer->AddWritingStep(std::make_unique<StepWriteZoneSizes>(contentInMemoryPtr)); + m_writer->AddWritingStep(std::make_unique<StepWriteXBlockSizes>(m_zone)); - // Start of the zone content - m_writer->AddWritingStep(std::make_unique<StepWriteZoneContentToFile>(contentInMemoryPtr)); + // Start of the zone content + m_writer->AddWritingStep(std::make_unique<StepWriteZoneContentToFile>(contentInMemoryPtr)); - // Return the fully setup zoneloader - return std::move(m_writer); - } + // Return the fully setup zoneloader + return std::move(m_writer); + } }; -bool ZoneWriterFactory::SupportsZone(Zone* zone) const -{ - return zone->m_game == &g_GameT5; -} +bool ZoneWriterFactory::SupportsZone(Zone *zone) const { return zone->m_game == &g_GameT5; } -std::unique_ptr<ZoneWriter> ZoneWriterFactory::CreateWriter(Zone* zone) const -{ - Impl impl(zone); - return impl.CreateWriter(); +std::unique_ptr<ZoneWriter> ZoneWriterFactory::CreateWriter(Zone *zone) const { + Impl impl(zone); + return impl.CreateWriter(); } diff --git a/src/ZoneWriting/Game/T5/ZoneWriterFactoryT5.h b/src/ZoneWriting/Game/T5/ZoneWriterFactoryT5.h index 04d67bb4f..537965440 100644 --- a/src/ZoneWriting/Game/T5/ZoneWriterFactoryT5.h +++ b/src/ZoneWriting/Game/T5/ZoneWriterFactoryT5.h @@ -4,14 +4,12 @@ #include "Writing/IZoneWriterFactory.h" -namespace T5 -{ - class ZoneWriterFactory final : public IZoneWriterFactory - { - class Impl; - - public: - _NODISCARD bool SupportsZone(Zone* zone) const override; - _NODISCARD std::unique_ptr<ZoneWriter> CreateWriter(Zone* zone) const override; - }; -} +namespace T5 { +class ZoneWriterFactory final : public IZoneWriterFactory { + class Impl; + +public: + _NODISCARD bool SupportsZone(Zone *zone) const override; + _NODISCARD std::unique_ptr<ZoneWriter> CreateWriter(Zone *zone) const override; +}; +} // namespace T5 diff --git a/src/ZoneWriting/Game/T6/ContentWriterT6.cpp b/src/ZoneWriting/Game/T6/ContentWriterT6.cpp index cbb68e740..8d67c8d38 100644 --- a/src/ZoneWriting/Game/T6/ContentWriterT6.cpp +++ b/src/ZoneWriting/Game/T6/ContentWriterT6.cpp @@ -56,91 +56,73 @@ using namespace T6; -ContentWriter::ContentWriter() - : varXAssetList(nullptr), - varXAsset(nullptr), - varScriptStringList(nullptr) -{ -} - -void ContentWriter::CreateXAssetList(XAssetList& xAssetList, MemoryManager& memory) const -{ - if (!m_zone->m_script_strings.Empty()) - { - assert(m_zone->m_script_strings.Count() <= SCR_STRING_MAX + 1); - xAssetList.stringList.count = static_cast<int>(m_zone->m_script_strings.Count()); - xAssetList.stringList.strings = static_cast<const char**>(memory.Alloc(sizeof(const char*) * m_zone->m_script_strings.Count())); - - for (auto i = 0u; i < m_zone->m_script_strings.Count(); i++) - xAssetList.stringList.strings[i] = m_zone->m_script_strings.CValue(i); - } - else - { - xAssetList.stringList.count = 0; - xAssetList.stringList.strings = nullptr; - } - - xAssetList.dependCount = 0; - xAssetList.depends = nullptr; - - const auto assetCount = m_zone->m_pools->GetTotalAssetCount(); - if (assetCount > 0) - { - xAssetList.assetCount = static_cast<int>(assetCount); - xAssetList.assets = static_cast<XAsset*>(memory.Alloc(sizeof(XAsset) * assetCount)); - - const auto end = m_zone->m_pools->end(); - auto index = 0u; - for (auto i = m_zone->m_pools->begin(); i != end; ++i) - { - auto& asset = xAssetList.assets[index++]; - asset.type = static_cast<XAssetType>((*i)->m_type); - asset.header.data = (*i)->m_ptr; - } - } - else - { - xAssetList.assetCount = 0; - xAssetList.assets = nullptr; +ContentWriter::ContentWriter() : varXAssetList(nullptr), varXAsset(nullptr), varScriptStringList(nullptr) {} + +void ContentWriter::CreateXAssetList(XAssetList &xAssetList, MemoryManager &memory) const { + if (!m_zone->m_script_strings.Empty()) { + assert(m_zone->m_script_strings.Count() <= SCR_STRING_MAX + 1); + xAssetList.stringList.count = static_cast<int>(m_zone->m_script_strings.Count()); + xAssetList.stringList.strings = static_cast<const char **>(memory.Alloc(sizeof(const char *) * m_zone->m_script_strings.Count())); + + for (auto i = 0u; i < m_zone->m_script_strings.Count(); i++) + xAssetList.stringList.strings[i] = m_zone->m_script_strings.CValue(i); + } else { + xAssetList.stringList.count = 0; + xAssetList.stringList.strings = nullptr; + } + + xAssetList.dependCount = 0; + xAssetList.depends = nullptr; + + const auto assetCount = m_zone->m_pools->GetTotalAssetCount(); + if (assetCount > 0) { + xAssetList.assetCount = static_cast<int>(assetCount); + xAssetList.assets = static_cast<XAsset *>(memory.Alloc(sizeof(XAsset) * assetCount)); + + const auto end = m_zone->m_pools->end(); + auto index = 0u; + for (auto i = m_zone->m_pools->begin(); i != end; ++i) { + auto &asset = xAssetList.assets[index++]; + asset.type = static_cast<XAssetType>((*i)->m_type); + asset.header.data = (*i)->m_ptr; } + } else { + xAssetList.assetCount = 0; + xAssetList.assets = nullptr; + } } -void ContentWriter::WriteScriptStringList(const bool atStreamStart) -{ - m_stream->PushBlock(XFILE_BLOCK_VIRTUAL); +void ContentWriter::WriteScriptStringList(const bool atStreamStart) { + m_stream->PushBlock(XFILE_BLOCK_VIRTUAL); - if (atStreamStart) - varScriptStringList = m_stream->Write(varScriptStringList); + if (atStreamStart) + varScriptStringList = m_stream->Write(varScriptStringList); - if (varScriptStringList->strings != nullptr) - { - m_stream->Align(alignof(const char*)); - varXString = varScriptStringList->strings; - WriteXStringArray(true, varScriptStringList->count); + if (varScriptStringList->strings != nullptr) { + m_stream->Align(alignof(const char *)); + varXString = varScriptStringList->strings; + WriteXStringArray(true, varScriptStringList->count); - m_stream->MarkFollowing(varScriptStringList->strings); - } + m_stream->MarkFollowing(varScriptStringList->strings); + } - m_stream->PopBlock(); + m_stream->PopBlock(); } -void ContentWriter::WriteXAsset(const bool atStreamStart) -{ -#define WRITE_ASSET(type_index, typeName, headerEntry) \ - case type_index: \ - { \ - Writer_##typeName writer(varXAsset->header.headerEntry, m_zone, m_stream); \ - writer.Write(&varXAsset->header.headerEntry); \ - break; \ - } +void ContentWriter::WriteXAsset(const bool atStreamStart) { +#define WRITE_ASSET(type_index, typeName, headerEntry) \ + case type_index: { \ + Writer_##typeName writer(varXAsset->header.headerEntry, m_zone, m_stream); \ + writer.Write(&varXAsset->header.headerEntry); \ + break; \ + } - assert(varXAsset != nullptr); + assert(varXAsset != nullptr); - if (atStreamStart) - varXAsset = m_stream->Write(varXAsset); + if (atStreamStart) + varXAsset = m_stream->Write(varXAsset); - switch (varXAsset->type) - { + switch (varXAsset->type) { WRITE_ASSET(ASSET_TYPE_PHYSPRESET, PhysPreset, physPreset) WRITE_ASSET(ASSET_TYPE_PHYSCONSTRAINTS, PhysConstraints, physConstraints) WRITE_ASSET(ASSET_TYPE_DESTRUCTIBLEDEF, DestructibleDef, destructibleDef) @@ -191,63 +173,57 @@ void ContentWriter::WriteXAsset(const bool atStreamStart) WRITE_ASSET(ASSET_TYPE_FOOTSTEPFX_TABLE, FootstepFXTableDef, footstepFXTableDef) WRITE_ASSET(ASSET_TYPE_ZBARRIER, ZBarrierDef, zbarrierDef) - default: - { - std::ostringstream str; - str << "Unsupported asset type: " << varXAsset->type << "."; - throw WritingException(str.str()); - } - } + default: { + std::ostringstream str; + str << "Unsupported asset type: " << varXAsset->type << "."; + throw WritingException(str.str()); + } + } #undef WRITE_ASSET } -void ContentWriter::WriteXAssetArray(const bool atStreamStart, const size_t count) -{ - assert(varXAsset != nullptr); +void ContentWriter::WriteXAssetArray(const bool atStreamStart, const size_t count) { + assert(varXAsset != nullptr); - if (atStreamStart) - varXAsset = m_stream->Write(varXAsset, count); + if (atStreamStart) + varXAsset = m_stream->Write(varXAsset, count); - for (size_t index = 0; index < count; index++) - { - WriteXAsset(false); - varXAsset++; - } + for (size_t index = 0; index < count; index++) { + WriteXAsset(false); + varXAsset++; + } } -void ContentWriter::WriteContent(Zone* zone, IZoneOutputStream* stream) -{ - m_zone = zone; - m_stream = stream; +void ContentWriter::WriteContent(Zone *zone, IZoneOutputStream *stream) { + m_zone = zone; + m_stream = stream; - m_stream->PushBlock(XFILE_BLOCK_VIRTUAL); + m_stream->PushBlock(XFILE_BLOCK_VIRTUAL); - MemoryManager memory; - XAssetList assetList{}; + MemoryManager memory; + XAssetList assetList{}; - CreateXAssetList(assetList, memory); + CreateXAssetList(assetList, memory); - varXAssetList = static_cast<XAssetList*>(m_stream->WriteDataRaw(&assetList, sizeof(assetList))); + varXAssetList = static_cast<XAssetList *>(m_stream->WriteDataRaw(&assetList, sizeof(assetList))); - varScriptStringList = &varXAssetList->stringList; - WriteScriptStringList(false); + varScriptStringList = &varXAssetList->stringList; + WriteScriptStringList(false); - if (varXAssetList->depends != nullptr) - { - m_stream->Align(alignof(const char*)); - varXString = varXAssetList->depends; - WriteXStringArray(true, varXAssetList->dependCount); - m_stream->MarkFollowing(varXAssetList->depends); - } + if (varXAssetList->depends != nullptr) { + m_stream->Align(alignof(const char *)); + varXString = varXAssetList->depends; + WriteXStringArray(true, varXAssetList->dependCount); + m_stream->MarkFollowing(varXAssetList->depends); + } - if (varXAssetList->assets != nullptr) - { - m_stream->Align(alignof(XAsset)); - varXAsset = varXAssetList->assets; - WriteXAssetArray(true, varXAssetList->assetCount); - m_stream->MarkFollowing(varXAssetList->assets); - } + if (varXAssetList->assets != nullptr) { + m_stream->Align(alignof(XAsset)); + varXAsset = varXAssetList->assets; + WriteXAssetArray(true, varXAssetList->assetCount); + m_stream->MarkFollowing(varXAssetList->assets); + } - m_stream->PopBlock(); + m_stream->PopBlock(); } diff --git a/src/ZoneWriting/Game/T6/ContentWriterT6.h b/src/ZoneWriting/Game/T6/ContentWriterT6.h index af4d56fdc..ef145ed2a 100644 --- a/src/ZoneWriting/Game/T6/ContentWriterT6.h +++ b/src/ZoneWriting/Game/T6/ContentWriterT6.h @@ -1,26 +1,24 @@ #pragma once +#include "Game/T6/T6.h" #include "Writing/ContentWriterBase.h" #include "Writing/IContentWritingEntryPoint.h" -#include "Game/T6/T6.h" -namespace T6 -{ - class ContentWriter final : public ContentWriterBase, public IContentWritingEntryPoint - { - XAssetList* varXAssetList; - XAsset* varXAsset; - ScriptStringList* varScriptStringList; +namespace T6 { +class ContentWriter final : public ContentWriterBase, public IContentWritingEntryPoint { + XAssetList *varXAssetList; + XAsset *varXAsset; + ScriptStringList *varScriptStringList; - void CreateXAssetList(XAssetList& xAssetList, MemoryManager& memory) const; + void CreateXAssetList(XAssetList &xAssetList, MemoryManager &memory) const; - void WriteScriptStringList(bool atStreamStart); + void WriteScriptStringList(bool atStreamStart); - void WriteXAsset(bool atStreamStart); - void WriteXAssetArray(bool atStreamStart, size_t count); + void WriteXAsset(bool atStreamStart); + void WriteXAssetArray(bool atStreamStart, size_t count); - public: - ContentWriter(); +public: + ContentWriter(); - void WriteContent(Zone* zone, IZoneOutputStream* stream) override; - }; -} + void WriteContent(Zone *zone, IZoneOutputStream *stream) override; +}; +} // namespace T6 diff --git a/src/ZoneWriting/Game/T6/ZoneWriterFactoryT6.cpp b/src/ZoneWriting/Game/T6/ZoneWriterFactoryT6.cpp index 3bf154f5e..f3a397a0c 100644 --- a/src/ZoneWriting/Game/T6/ZoneWriterFactoryT6.cpp +++ b/src/ZoneWriting/Game/T6/ZoneWriterFactoryT6.cpp @@ -4,13 +4,11 @@ #include <cstring> #include "ContentWriterT6.h" -#include "Utils/ICapturedDataProvider.h" -#include "Game/T6/T6.h" #include "Game/T6/GameT6.h" +#include "Game/T6/T6.h" #include "Game/T6/ZoneConstantsT6.h" +#include "Utils/ICapturedDataProvider.h" #include "Writing/Processor/OutputProcessorXChunks.h" -#include "Zone/XChunk/XChunkProcessorDeflate.h" -#include "Zone/XChunk/XChunkProcessorSalsa20Encryption.h" #include "Writing/Steps/StepAddOutputProcessor.h" #include "Writing/Steps/StepAlign.h" #include "Writing/Steps/StepRemoveOutputProcessor.h" @@ -20,134 +18,120 @@ #include "Writing/Steps/StepWriteZoneContentToMemory.h" #include "Writing/Steps/StepWriteZoneHeader.h" #include "Writing/Steps/StepWriteZoneSizes.h" +#include "Zone/XChunk/XChunkProcessorDeflate.h" +#include "Zone/XChunk/XChunkProcessorSalsa20Encryption.h" using namespace T6; -class ZoneWriterFactory::Impl -{ - Zone* m_zone; - std::unique_ptr<ZoneWriter> m_writer; +class ZoneWriterFactory::Impl { + Zone *m_zone; + std::unique_ptr<ZoneWriter> m_writer; public: - explicit Impl(Zone* zone) - : m_zone(zone), - m_writer(std::make_unique<ZoneWriter>()) - { - } + explicit Impl(Zone *zone) : m_zone(zone), m_writer(std::make_unique<ZoneWriter>()) {} - void SetupBlocks() const - { + void SetupBlocks() const { #define XBLOCK_DEF(name, type) std::make_unique<XBlock>(STR(name), name, type) - m_writer->AddXBlock(XBLOCK_DEF(T6::XFILE_BLOCK_TEMP, XBlock::Type::BLOCK_TYPE_TEMP)); - m_writer->AddXBlock(XBLOCK_DEF(T6::XFILE_BLOCK_RUNTIME_VIRTUAL, XBlock::Type::BLOCK_TYPE_RUNTIME)); - m_writer->AddXBlock(XBLOCK_DEF(T6::XFILE_BLOCK_RUNTIME_PHYSICAL, XBlock::Type::BLOCK_TYPE_RUNTIME)); - m_writer->AddXBlock(XBLOCK_DEF(T6::XFILE_BLOCK_DELAY_VIRTUAL, XBlock::Type::BLOCK_TYPE_DELAY)); - m_writer->AddXBlock(XBLOCK_DEF(T6::XFILE_BLOCK_DELAY_PHYSICAL, XBlock::Type::BLOCK_TYPE_DELAY)); - m_writer->AddXBlock(XBLOCK_DEF(T6::XFILE_BLOCK_VIRTUAL, XBlock::Type::BLOCK_TYPE_NORMAL)); - m_writer->AddXBlock(XBLOCK_DEF(T6::XFILE_BLOCK_PHYSICAL, XBlock::Type::BLOCK_TYPE_NORMAL)); - m_writer->AddXBlock(XBLOCK_DEF(T6::XFILE_BLOCK_STREAMER_RESERVE, XBlock::Type::BLOCK_TYPE_NORMAL)); + m_writer->AddXBlock(XBLOCK_DEF(T6::XFILE_BLOCK_TEMP, XBlock::Type::BLOCK_TYPE_TEMP)); + m_writer->AddXBlock(XBLOCK_DEF(T6::XFILE_BLOCK_RUNTIME_VIRTUAL, XBlock::Type::BLOCK_TYPE_RUNTIME)); + m_writer->AddXBlock(XBLOCK_DEF(T6::XFILE_BLOCK_RUNTIME_PHYSICAL, XBlock::Type::BLOCK_TYPE_RUNTIME)); + m_writer->AddXBlock(XBLOCK_DEF(T6::XFILE_BLOCK_DELAY_VIRTUAL, XBlock::Type::BLOCK_TYPE_DELAY)); + m_writer->AddXBlock(XBLOCK_DEF(T6::XFILE_BLOCK_DELAY_PHYSICAL, XBlock::Type::BLOCK_TYPE_DELAY)); + m_writer->AddXBlock(XBLOCK_DEF(T6::XFILE_BLOCK_VIRTUAL, XBlock::Type::BLOCK_TYPE_NORMAL)); + m_writer->AddXBlock(XBLOCK_DEF(T6::XFILE_BLOCK_PHYSICAL, XBlock::Type::BLOCK_TYPE_NORMAL)); + m_writer->AddXBlock(XBLOCK_DEF(T6::XFILE_BLOCK_STREAMER_RESERVE, XBlock::Type::BLOCK_TYPE_NORMAL)); #undef XBLOCK_DEF + } + + static ZoneHeader CreateHeaderForParams(const bool isSecure, const bool isOfficial, const bool isEncrypted) { + ZoneHeader header{}; + header.m_version = ZoneConstants::ZONE_VERSION; + + if (isSecure) { + if (isOfficial) + memcpy(header.m_magic, ZoneConstants::MAGIC_SIGNED_TREYARCH, sizeof(ZoneHeader::m_magic)); + else + memcpy(header.m_magic, ZoneConstants::MAGIC_SIGNED_OAT, sizeof(ZoneHeader::m_magic)); + } else { + if (isEncrypted) + memcpy(header.m_magic, ZoneConstants::MAGIC_UNSIGNED, sizeof(ZoneHeader::m_magic)); + else + memcpy(header.m_magic, ZoneConstants::MAGIC_UNSIGNED_SERVER, sizeof(ZoneHeader::m_magic)); } - static ZoneHeader CreateHeaderForParams(const bool isSecure, const bool isOfficial, const bool isEncrypted) - { - ZoneHeader header{}; - header.m_version = ZoneConstants::ZONE_VERSION; - - if(isSecure) - { - if (isOfficial) - memcpy(header.m_magic, ZoneConstants::MAGIC_SIGNED_TREYARCH, sizeof(ZoneHeader::m_magic)); - else - memcpy(header.m_magic, ZoneConstants::MAGIC_SIGNED_OAT, sizeof(ZoneHeader::m_magic)); - } - else - { - if (isEncrypted) - memcpy(header.m_magic, ZoneConstants::MAGIC_UNSIGNED, sizeof(ZoneHeader::m_magic)); - else - memcpy(header.m_magic, ZoneConstants::MAGIC_UNSIGNED_SERVER, sizeof(ZoneHeader::m_magic)); - } - - return header; - } - - void AddXChunkProcessor(const bool isEncrypted, ICapturedDataProvider** dataToSignProviderPtr, OutputProcessorXChunks** xChunkProcessorPtr) const - { - auto xChunkProcessor = std::make_unique<OutputProcessorXChunks>(ZoneConstants::STREAM_COUNT, ZoneConstants::XCHUNK_SIZE, ZoneConstants::XCHUNK_MAX_WRITE_SIZE, ZoneConstants::VANILLA_BUFFER_SIZE); - if (xChunkProcessorPtr) - *xChunkProcessorPtr = xChunkProcessor.get(); - - // Decompress the chunks using zlib - xChunkProcessor->AddChunkProcessor(std::make_unique<XChunkProcessorDeflate>()); + return header; + } - if (isEncrypted) - { - // If zone is encrypted, the decryption is applied before the decompression. T6 Zones always use Salsa20. - auto chunkProcessorSalsa20 = std::make_unique<XChunkProcessorSalsa20Encryption>(ZoneConstants::STREAM_COUNT, m_zone->m_name, ZoneConstants::SALSA20_KEY_TREYARCH, - sizeof(ZoneConstants::SALSA20_KEY_TREYARCH)); + void AddXChunkProcessor(const bool isEncrypted, ICapturedDataProvider **dataToSignProviderPtr, OutputProcessorXChunks **xChunkProcessorPtr) const { + auto xChunkProcessor = std::make_unique<OutputProcessorXChunks>(ZoneConstants::STREAM_COUNT, ZoneConstants::XCHUNK_SIZE, + ZoneConstants::XCHUNK_MAX_WRITE_SIZE, ZoneConstants::VANILLA_BUFFER_SIZE); + if (xChunkProcessorPtr) + *xChunkProcessorPtr = xChunkProcessor.get(); - // If there is encryption, the signed data of the zone is the final hash blocks provided by the Salsa20 IV adaption algorithm - if (dataToSignProviderPtr) - *dataToSignProviderPtr = chunkProcessorSalsa20.get(); + // Decompress the chunks using zlib + xChunkProcessor->AddChunkProcessor(std::make_unique<XChunkProcessorDeflate>()); - xChunkProcessor->AddChunkProcessor(std::move(chunkProcessorSalsa20)); - } + if (isEncrypted) { + // If zone is encrypted, the decryption is applied before the decompression. T6 Zones always use Salsa20. + auto chunkProcessorSalsa20 = std::make_unique<XChunkProcessorSalsa20Encryption>( + ZoneConstants::STREAM_COUNT, m_zone->m_name, ZoneConstants::SALSA20_KEY_TREYARCH, sizeof(ZoneConstants::SALSA20_KEY_TREYARCH)); - m_writer->AddWritingStep(std::make_unique<StepAddOutputProcessor>(std::move(xChunkProcessor))); + // If there is encryption, the signed data of the zone is the final hash blocks provided by the Salsa20 IV adaption algorithm + if (dataToSignProviderPtr) + *dataToSignProviderPtr = chunkProcessorSalsa20.get(); + xChunkProcessor->AddChunkProcessor(std::move(chunkProcessorSalsa20)); } - std::unique_ptr<ZoneWriter> CreateWriter() - { - // TODO Support signed fastfiles - bool isSecure = false; - bool isEncrypted = true; + m_writer->AddWritingStep(std::make_unique<StepAddOutputProcessor>(std::move(xChunkProcessor))); + } - SetupBlocks(); + std::unique_ptr<ZoneWriter> CreateWriter() { + // TODO Support signed fastfiles + bool isSecure = false; + bool isEncrypted = true; - auto contentInMemory = std::make_unique<StepWriteZoneContentToMemory>(std::make_unique<ContentWriter>(), m_zone, ZoneConstants::OFFSET_BLOCK_BIT_COUNT, ZoneConstants::INSERT_BLOCK); - auto* contentInMemoryPtr = contentInMemory.get(); - m_writer->AddWritingStep(std::move(contentInMemory)); + SetupBlocks(); - // Write zone header - m_writer->AddWritingStep(std::make_unique<StepWriteZoneHeader>(CreateHeaderForParams(isSecure, false, isEncrypted))); + auto contentInMemory = std::make_unique<StepWriteZoneContentToMemory>(std::make_unique<ContentWriter>(), m_zone, ZoneConstants::OFFSET_BLOCK_BIT_COUNT, + ZoneConstants::INSERT_BLOCK); + auto *contentInMemoryPtr = contentInMemory.get(); + m_writer->AddWritingStep(std::move(contentInMemory)); - // Setup loading XChunks from the zone from this point on. - ICapturedDataProvider* dataToSignProvider; - OutputProcessorXChunks* xChunksProcessor; - AddXChunkProcessor(isEncrypted, &dataToSignProvider, &xChunksProcessor); + // Write zone header + m_writer->AddWritingStep(std::make_unique<StepWriteZoneHeader>(CreateHeaderForParams(isSecure, false, isEncrypted))); - // Start of the XFile struct - //m_writer->AddWritingStep(std::make_unique<StepSkipBytes>(8)); // Skip size and externalSize fields since they are not interesting for us - m_writer->AddWritingStep(std::make_unique<StepWriteZoneSizes>(contentInMemoryPtr)); - m_writer->AddWritingStep(std::make_unique<StepWriteXBlockSizes>(m_zone)); + // Setup loading XChunks from the zone from this point on. + ICapturedDataProvider *dataToSignProvider; + OutputProcessorXChunks *xChunksProcessor; + AddXChunkProcessor(isEncrypted, &dataToSignProvider, &xChunksProcessor); - // Start of the zone content - m_writer->AddWritingStep(std::make_unique<StepWriteZoneContentToFile>(contentInMemoryPtr)); + // Start of the XFile struct + // m_writer->AddWritingStep(std::make_unique<StepSkipBytes>(8)); // Skip size and externalSize fields since they are not interesting for us + m_writer->AddWritingStep(std::make_unique<StepWriteZoneSizes>(contentInMemoryPtr)); + m_writer->AddWritingStep(std::make_unique<StepWriteXBlockSizes>(m_zone)); - // Stop writing in XChunks - m_writer->AddWritingStep(std::make_unique<StepRemoveOutputProcessor>(xChunksProcessor)); + // Start of the zone content + m_writer->AddWritingStep(std::make_unique<StepWriteZoneContentToFile>(contentInMemoryPtr)); - // Pad ending with zeros like the original linker does it. The game's reader needs it for some reason. - // From my observations this is most likely the logic behind the amount of bytes: At least 0x40 bytes and aligned to the next 0x40 - m_writer->AddWritingStep(std::make_unique<StepWriteZero>(ZoneConstants::FILE_SUFFIX_ZERO_MIN_SIZE)); - m_writer->AddWritingStep(std::make_unique<StepAlign>(ZoneConstants::FILE_SUFFIX_ZERO_ALIGN, '\0')); + // Stop writing in XChunks + m_writer->AddWritingStep(std::make_unique<StepRemoveOutputProcessor>(xChunksProcessor)); - // Return the fully setup zoneloader - return std::move(m_writer); - } + // Pad ending with zeros like the original linker does it. The game's reader needs it for some reason. + // From my observations this is most likely the logic behind the amount of bytes: At least 0x40 bytes and aligned to the next 0x40 + m_writer->AddWritingStep(std::make_unique<StepWriteZero>(ZoneConstants::FILE_SUFFIX_ZERO_MIN_SIZE)); + m_writer->AddWritingStep(std::make_unique<StepAlign>(ZoneConstants::FILE_SUFFIX_ZERO_ALIGN, '\0')); + + // Return the fully setup zoneloader + return std::move(m_writer); + } }; -bool ZoneWriterFactory::SupportsZone(Zone* zone) const -{ - return zone->m_game == &g_GameT6; -} +bool ZoneWriterFactory::SupportsZone(Zone *zone) const { return zone->m_game == &g_GameT6; } -std::unique_ptr<ZoneWriter> ZoneWriterFactory::CreateWriter(Zone* zone) const -{ - Impl impl(zone); - return impl.CreateWriter(); +std::unique_ptr<ZoneWriter> ZoneWriterFactory::CreateWriter(Zone *zone) const { + Impl impl(zone); + return impl.CreateWriter(); } diff --git a/src/ZoneWriting/Game/T6/ZoneWriterFactoryT6.h b/src/ZoneWriting/Game/T6/ZoneWriterFactoryT6.h index a7ba249e1..6df6b69ef 100644 --- a/src/ZoneWriting/Game/T6/ZoneWriterFactoryT6.h +++ b/src/ZoneWriting/Game/T6/ZoneWriterFactoryT6.h @@ -4,14 +4,12 @@ #include "Writing/IZoneWriterFactory.h" -namespace T6 -{ - class ZoneWriterFactory final : public IZoneWriterFactory - { - class Impl; - - public: - _NODISCARD bool SupportsZone(Zone* zone) const override; - _NODISCARD std::unique_ptr<ZoneWriter> CreateWriter(Zone* zone) const override; - }; -} +namespace T6 { +class ZoneWriterFactory final : public IZoneWriterFactory { + class Impl; + +public: + _NODISCARD bool SupportsZone(Zone *zone) const override; + _NODISCARD std::unique_ptr<ZoneWriter> CreateWriter(Zone *zone) const override; +}; +} // namespace T6 diff --git a/src/ZoneWriting/Writing/AssetWriter.cpp b/src/ZoneWriting/Writing/AssetWriter.cpp index 087cb0482..299c9bffe 100644 --- a/src/ZoneWriting/Writing/AssetWriter.cpp +++ b/src/ZoneWriting/Writing/AssetWriter.cpp @@ -2,39 +2,30 @@ #include <cassert> -AssetWriter::AssetWriter(XAssetInfoGeneric* asset, Zone* zone, IZoneOutputStream* stream) - : ContentWriterBase(zone, stream), - m_asset(asset), - varScriptString(nullptr), - varScriptStringWritten(nullptr) -{ -} +AssetWriter::AssetWriter(XAssetInfoGeneric *asset, Zone *zone, IZoneOutputStream *stream) + : ContentWriterBase(zone, stream), m_asset(asset), varScriptString(nullptr), varScriptStringWritten(nullptr) {} -scr_string_t AssetWriter::UseScriptString(const scr_string_t scrString) const -{ - assert(scrString < m_asset->m_zone->m_script_strings.Count()); +scr_string_t AssetWriter::UseScriptString(const scr_string_t scrString) const { + assert(scrString < m_asset->m_zone->m_script_strings.Count()); - if (m_asset->m_zone == m_zone) - return scrString; + if (m_asset->m_zone == m_zone) + return scrString; - const auto strValue = m_asset->m_zone->m_script_strings.CValue(scrString); - return m_zone->m_script_strings.GetScriptString(strValue); + const auto strValue = m_asset->m_zone->m_script_strings.CValue(scrString); + return m_zone->m_script_strings.GetScriptString(strValue); } -void AssetWriter::WriteScriptStringArray(const bool atStreamStart, const size_t count) -{ - if (atStreamStart) - { - assert(varScriptString != nullptr); - varScriptStringWritten = m_stream->Write<scr_string_t>(varScriptString, count); - } - - assert(varScriptStringWritten != nullptr); - - auto* ptr = varScriptStringWritten; - for (size_t index = 0; index < count; index++) - { - *ptr = UseScriptString(*ptr); - ptr++; - } +void AssetWriter::WriteScriptStringArray(const bool atStreamStart, const size_t count) { + if (atStreamStart) { + assert(varScriptString != nullptr); + varScriptStringWritten = m_stream->Write<scr_string_t>(varScriptString, count); + } + + assert(varScriptStringWritten != nullptr); + + auto *ptr = varScriptStringWritten; + for (size_t index = 0; index < count; index++) { + *ptr = UseScriptString(*ptr); + ptr++; + } } diff --git a/src/ZoneWriting/Writing/AssetWriter.h b/src/ZoneWriting/Writing/AssetWriter.h index b074a889f..4b52ffd7a 100644 --- a/src/ZoneWriting/Writing/AssetWriter.h +++ b/src/ZoneWriting/Writing/AssetWriter.h @@ -1,21 +1,20 @@ #pragma once +#include "ContentWriterBase.h" +#include "Pool/XAssetInfo.h" #include "Utils/ClassUtils.h" #include "Zone/Zone.h" #include "Zone/ZoneTypes.h" -#include "Pool/XAssetInfo.h" -#include "ContentWriterBase.h" -class AssetWriter : public ContentWriterBase -{ +class AssetWriter : public ContentWriterBase { protected: - XAssetInfoGeneric* m_asset; + XAssetInfoGeneric *m_asset; - scr_string_t* varScriptString; - scr_string_t* varScriptStringWritten; + scr_string_t *varScriptString; + scr_string_t *varScriptStringWritten; - AssetWriter(XAssetInfoGeneric* asset, Zone* zone, IZoneOutputStream* stream); + AssetWriter(XAssetInfoGeneric *asset, Zone *zone, IZoneOutputStream *stream); - _NODISCARD scr_string_t UseScriptString(scr_string_t scrString) const; - void WriteScriptStringArray(bool atStreamStart, size_t count); + _NODISCARD scr_string_t UseScriptString(scr_string_t scrString) const; + void WriteScriptStringArray(bool atStreamStart, size_t count); }; diff --git a/src/ZoneWriting/Writing/ContentWriterBase.cpp b/src/ZoneWriting/Writing/ContentWriterBase.cpp index 668382a74..c188378a7 100644 --- a/src/ZoneWriting/Writing/ContentWriterBase.cpp +++ b/src/ZoneWriting/Writing/ContentWriterBase.cpp @@ -2,55 +2,37 @@ #include <cassert> -ContentWriterBase::ContentWriterBase() - : varXString(nullptr), - varXStringWritten(nullptr), - m_zone(nullptr), - m_stream(nullptr) -{ -} +ContentWriterBase::ContentWriterBase() : varXString(nullptr), varXStringWritten(nullptr), m_zone(nullptr), m_stream(nullptr) {} -ContentWriterBase::ContentWriterBase(Zone* zone, IZoneOutputStream* stream) - : varXString(nullptr), - varXStringWritten(nullptr), - m_zone(zone), - m_stream(stream) -{ -} +ContentWriterBase::ContentWriterBase(Zone *zone, IZoneOutputStream *stream) : varXString(nullptr), varXStringWritten(nullptr), m_zone(zone), m_stream(stream) {} -void ContentWriterBase::WriteXString(const bool atStreamStart) -{ - if (atStreamStart) - { - assert(varXString != nullptr); - varXStringWritten = m_stream->Write<const char*>(varXString); - } +void ContentWriterBase::WriteXString(const bool atStreamStart) { + if (atStreamStart) { + assert(varXString != nullptr); + varXStringWritten = m_stream->Write<const char *>(varXString); + } - assert(varXStringWritten != nullptr); + assert(varXStringWritten != nullptr); - if (m_stream->ReusableShouldWrite(varXStringWritten)) - { - m_stream->Align(alignof(const char)); - m_stream->ReusableAddOffset(*varXStringWritten); - m_stream->WriteNullTerminated(*varXStringWritten); + if (m_stream->ReusableShouldWrite(varXStringWritten)) { + m_stream->Align(alignof(const char)); + m_stream->ReusableAddOffset(*varXStringWritten); + m_stream->WriteNullTerminated(*varXStringWritten); - m_stream->MarkFollowing(*varXStringWritten); - } + m_stream->MarkFollowing(*varXStringWritten); + } } -void ContentWriterBase::WriteXStringArray(const bool atStreamStart, const size_t count) -{ - if (atStreamStart) - { - assert(varXString != nullptr); - varXStringWritten = m_stream->Write<const char*>(varXString, count); - } - - assert(varXStringWritten != nullptr); - - for (size_t index = 0; index < count; index++) - { - WriteXString(false); - varXStringWritten++; - } +void ContentWriterBase::WriteXStringArray(const bool atStreamStart, const size_t count) { + if (atStreamStart) { + assert(varXString != nullptr); + varXStringWritten = m_stream->Write<const char *>(varXString, count); + } + + assert(varXStringWritten != nullptr); + + for (size_t index = 0; index < count; index++) { + WriteXString(false); + varXStringWritten++; + } } diff --git a/src/ZoneWriting/Writing/ContentWriterBase.h b/src/ZoneWriting/Writing/ContentWriterBase.h index 8b752f851..7d9f321d1 100644 --- a/src/ZoneWriting/Writing/ContentWriterBase.h +++ b/src/ZoneWriting/Writing/ContentWriterBase.h @@ -1,27 +1,26 @@ #pragma once -#include "Zone/Zone.h" #include "Zone/Stream/IZoneOutputStream.h" +#include "Zone/Zone.h" -class ContentWriterBase -{ +class ContentWriterBase { protected: - const char** varXString; - const char** varXStringWritten; + const char **varXString; + const char **varXStringWritten; - Zone* m_zone; - IZoneOutputStream* m_stream; + Zone *m_zone; + IZoneOutputStream *m_stream; - ContentWriterBase(); - ContentWriterBase(Zone* zone, IZoneOutputStream* stream); + ContentWriterBase(); + ContentWriterBase(Zone *zone, IZoneOutputStream *stream); - void WriteXString(bool atStreamStart); - void WriteXStringArray(bool atStreamStart, size_t count); + void WriteXString(bool atStreamStart); + void WriteXStringArray(bool atStreamStart, size_t count); public: - virtual ~ContentWriterBase() = default; - ContentWriterBase(const ContentWriterBase& other) = default; - ContentWriterBase(ContentWriterBase&& other) noexcept = default; - ContentWriterBase& operator=(const ContentWriterBase& other) = default; - ContentWriterBase& operator=(ContentWriterBase&& other) noexcept = default; + virtual ~ContentWriterBase() = default; + ContentWriterBase(const ContentWriterBase &other) = default; + ContentWriterBase(ContentWriterBase &&other) noexcept = default; + ContentWriterBase &operator=(const ContentWriterBase &other) = default; + ContentWriterBase &operator=(ContentWriterBase &&other) noexcept = default; }; diff --git a/src/ZoneWriting/Writing/IContentWritingEntryPoint.h b/src/ZoneWriting/Writing/IContentWritingEntryPoint.h index d00f82d1b..7e47b135f 100644 --- a/src/ZoneWriting/Writing/IContentWritingEntryPoint.h +++ b/src/ZoneWriting/Writing/IContentWritingEntryPoint.h @@ -1,17 +1,16 @@ #pragma once -#include "Zone/Zone.h" #include "Zone/Stream/IZoneOutputStream.h" +#include "Zone/Zone.h" -class IContentWritingEntryPoint -{ +class IContentWritingEntryPoint { public: - IContentWritingEntryPoint() = default; - virtual ~IContentWritingEntryPoint() = default; - IContentWritingEntryPoint(const IContentWritingEntryPoint& other) = default; - IContentWritingEntryPoint(IContentWritingEntryPoint&& other) noexcept = default; - IContentWritingEntryPoint& operator=(const IContentWritingEntryPoint& other) = default; - IContentWritingEntryPoint& operator=(IContentWritingEntryPoint&& other) noexcept = default; + IContentWritingEntryPoint() = default; + virtual ~IContentWritingEntryPoint() = default; + IContentWritingEntryPoint(const IContentWritingEntryPoint &other) = default; + IContentWritingEntryPoint(IContentWritingEntryPoint &&other) noexcept = default; + IContentWritingEntryPoint &operator=(const IContentWritingEntryPoint &other) = default; + IContentWritingEntryPoint &operator=(IContentWritingEntryPoint &&other) noexcept = default; - virtual void WriteContent(Zone* zone, IZoneOutputStream* stream) = 0; + virtual void WriteContent(Zone *zone, IZoneOutputStream *stream) = 0; }; \ No newline at end of file diff --git a/src/ZoneWriting/Writing/IWritingStep.h b/src/ZoneWriting/Writing/IWritingStep.h index 43abf30c0..10d8a8da2 100644 --- a/src/ZoneWriting/Writing/IWritingStep.h +++ b/src/ZoneWriting/Writing/IWritingStep.h @@ -1,19 +1,18 @@ #pragma once -#include "Writing/ZoneWriter.h" #include "IWritingStream.h" +#include "Writing/ZoneWriter.h" class ZoneWriter; -class IWritingStep -{ +class IWritingStep { public: - IWritingStep() = default; - virtual ~IWritingStep() = default; - IWritingStep(const IWritingStep& other) = default; - IWritingStep(IWritingStep&& other) noexcept = default; - IWritingStep& operator=(const IWritingStep& other) = default; - IWritingStep& operator=(IWritingStep&& other) noexcept = default; + IWritingStep() = default; + virtual ~IWritingStep() = default; + IWritingStep(const IWritingStep &other) = default; + IWritingStep(IWritingStep &&other) noexcept = default; + IWritingStep &operator=(const IWritingStep &other) = default; + IWritingStep &operator=(IWritingStep &&other) noexcept = default; - virtual void PerformStep(ZoneWriter* zoneWriter, IWritingStream* stream) = 0; + virtual void PerformStep(ZoneWriter *zoneWriter, IWritingStream *stream) = 0; }; diff --git a/src/ZoneWriting/Writing/IWritingStream.h b/src/ZoneWriting/Writing/IWritingStream.h index 6324e1337..dccf00258 100644 --- a/src/ZoneWriting/Writing/IWritingStream.h +++ b/src/ZoneWriting/Writing/IWritingStream.h @@ -1,19 +1,18 @@ #pragma once -#include <cstdint> #include <cstddef> +#include <cstdint> -class IWritingStream -{ +class IWritingStream { public: - IWritingStream() = default; - virtual ~IWritingStream() = default; - IWritingStream(const IWritingStream& other) = default; - IWritingStream(IWritingStream&& other) noexcept = default; - IWritingStream& operator=(const IWritingStream& other) = default; - IWritingStream& operator=(IWritingStream&& other) noexcept = default; + IWritingStream() = default; + virtual ~IWritingStream() = default; + IWritingStream(const IWritingStream &other) = default; + IWritingStream(IWritingStream &&other) noexcept = default; + IWritingStream &operator=(const IWritingStream &other) = default; + IWritingStream &operator=(IWritingStream &&other) noexcept = default; - virtual void Write(const void* buffer, size_t length) = 0; - virtual void Flush() = 0; - virtual int64_t Pos() = 0; + virtual void Write(const void *buffer, size_t length) = 0; + virtual void Flush() = 0; + virtual int64_t Pos() = 0; }; \ No newline at end of file diff --git a/src/ZoneWriting/Writing/IZoneWriterFactory.h b/src/ZoneWriting/Writing/IZoneWriterFactory.h index e855b55fc..e8ab80515 100644 --- a/src/ZoneWriting/Writing/IZoneWriterFactory.h +++ b/src/ZoneWriting/Writing/IZoneWriterFactory.h @@ -1,19 +1,18 @@ #pragma once #include "Utils/ClassUtils.h" -#include "ZoneWriter.h" #include "Zone/Zone.h" +#include "ZoneWriter.h" -class IZoneWriterFactory -{ +class IZoneWriterFactory { public: - IZoneWriterFactory() = default; - virtual ~IZoneWriterFactory() = default; - IZoneWriterFactory(const IZoneWriterFactory& other) = default; - IZoneWriterFactory(IZoneWriterFactory&& other) noexcept = default; - IZoneWriterFactory& operator=(const IZoneWriterFactory& other) = default; - IZoneWriterFactory& operator=(IZoneWriterFactory&& other) noexcept = default; + IZoneWriterFactory() = default; + virtual ~IZoneWriterFactory() = default; + IZoneWriterFactory(const IZoneWriterFactory &other) = default; + IZoneWriterFactory(IZoneWriterFactory &&other) noexcept = default; + IZoneWriterFactory &operator=(const IZoneWriterFactory &other) = default; + IZoneWriterFactory &operator=(IZoneWriterFactory &&other) noexcept = default; - _NODISCARD virtual bool SupportsZone(Zone* zone) const = 0; - _NODISCARD virtual std::unique_ptr<ZoneWriter> CreateWriter(Zone* zone) const = 0; + _NODISCARD virtual bool SupportsZone(Zone *zone) const = 0; + _NODISCARD virtual std::unique_ptr<ZoneWriter> CreateWriter(Zone *zone) const = 0; }; \ No newline at end of file diff --git a/src/ZoneWriting/Writing/InMemoryZoneData.cpp b/src/ZoneWriting/Writing/InMemoryZoneData.cpp index 79a0a7ef3..2ee0fb8b7 100644 --- a/src/ZoneWriting/Writing/InMemoryZoneData.cpp +++ b/src/ZoneWriting/Writing/InMemoryZoneData.cpp @@ -2,37 +2,25 @@ #include <stdexcept> -InMemoryZoneData::InMemoryZoneData() - : m_total_size(0) -{ - m_buffers.emplace_back(BUFFER_SIZE); -} +InMemoryZoneData::InMemoryZoneData() : m_total_size(0) { m_buffers.emplace_back(BUFFER_SIZE); } -InMemoryZoneData::MemoryBuffer::MemoryBuffer(const size_t size) - : m_data(std::make_unique<char[]>(size)), - m_size(0) -{ - if (!m_data) - throw std::runtime_error("Failed to allocate memory for memory buffer."); +InMemoryZoneData::MemoryBuffer::MemoryBuffer(const size_t size) : m_data(std::make_unique<char[]>(size)), m_size(0) { + if (!m_data) + throw std::runtime_error("Failed to allocate memory for memory buffer."); } -void* InMemoryZoneData::GetBufferOfSize(const size_t size) -{ - if(size > BUFFER_SIZE) - { - m_buffers.emplace_back(size); - } - else - { - if (m_buffers.back().m_size + size > BUFFER_SIZE) - { - m_buffers.emplace_back(BUFFER_SIZE); - } +void *InMemoryZoneData::GetBufferOfSize(const size_t size) { + if (size > BUFFER_SIZE) { + m_buffers.emplace_back(size); + } else { + if (m_buffers.back().m_size + size > BUFFER_SIZE) { + m_buffers.emplace_back(BUFFER_SIZE); } + } - auto& backBuffer = m_buffers.back(); - void* result = &backBuffer.m_data[backBuffer.m_size]; - backBuffer.m_size += size; - m_total_size += size; - return result; + auto &backBuffer = m_buffers.back(); + void *result = &backBuffer.m_data[backBuffer.m_size]; + backBuffer.m_size += size; + m_total_size += size; + return result; } diff --git a/src/ZoneWriting/Writing/InMemoryZoneData.h b/src/ZoneWriting/Writing/InMemoryZoneData.h index 0d43bdb8a..f62d29b59 100644 --- a/src/ZoneWriting/Writing/InMemoryZoneData.h +++ b/src/ZoneWriting/Writing/InMemoryZoneData.h @@ -1,25 +1,23 @@ #pragma once -#include <vector> #include <memory> +#include <vector> -class InMemoryZoneData -{ - static constexpr size_t BUFFER_SIZE = 0x400000; +class InMemoryZoneData { + static constexpr size_t BUFFER_SIZE = 0x400000; public: - class MemoryBuffer - { - public: - std::unique_ptr<char[]> m_data; - size_t m_size; + class MemoryBuffer { + public: + std::unique_ptr<char[]> m_data; + size_t m_size; - explicit MemoryBuffer(size_t size); - }; + explicit MemoryBuffer(size_t size); + }; - int64_t m_total_size; - std::vector<MemoryBuffer> m_buffers; + int64_t m_total_size; + std::vector<MemoryBuffer> m_buffers; - InMemoryZoneData(); - void* GetBufferOfSize(size_t size); + InMemoryZoneData(); + void *GetBufferOfSize(size_t size); }; \ No newline at end of file diff --git a/src/ZoneWriting/Writing/OutputStreamProcessor.cpp b/src/ZoneWriting/Writing/OutputStreamProcessor.cpp index 81f5e86e0..70a4dd8d8 100644 --- a/src/ZoneWriting/Writing/OutputStreamProcessor.cpp +++ b/src/ZoneWriting/Writing/OutputStreamProcessor.cpp @@ -1,11 +1,5 @@ #include "OutputStreamProcessor.h" -OutputStreamProcessor::OutputStreamProcessor() -{ - m_base_stream = nullptr; -} +OutputStreamProcessor::OutputStreamProcessor() { m_base_stream = nullptr; } -void OutputStreamProcessor::SetBaseStream(IWritingStream* baseStream) -{ - m_base_stream = baseStream; -} \ No newline at end of file +void OutputStreamProcessor::SetBaseStream(IWritingStream *baseStream) { m_base_stream = baseStream; } \ No newline at end of file diff --git a/src/ZoneWriting/Writing/OutputStreamProcessor.h b/src/ZoneWriting/Writing/OutputStreamProcessor.h index 6f1090766..fba91d136 100644 --- a/src/ZoneWriting/Writing/OutputStreamProcessor.h +++ b/src/ZoneWriting/Writing/OutputStreamProcessor.h @@ -2,13 +2,12 @@ #include "IWritingStream.h" -class OutputStreamProcessor : public IWritingStream -{ +class OutputStreamProcessor : public IWritingStream { protected: - IWritingStream* m_base_stream; + IWritingStream *m_base_stream; public: - OutputStreamProcessor(); + OutputStreamProcessor(); - void SetBaseStream(IWritingStream* baseStream); + void SetBaseStream(IWritingStream *baseStream); }; diff --git a/src/ZoneWriting/Writing/Processor/OutputProcessorDeflate.cpp b/src/ZoneWriting/Writing/Processor/OutputProcessorDeflate.cpp index 84c6eaac3..d7dbbf8d7 100644 --- a/src/ZoneWriting/Writing/Processor/OutputProcessorDeflate.cpp +++ b/src/ZoneWriting/Writing/Processor/OutputProcessorDeflate.cpp @@ -1,138 +1,104 @@ #include "OutputProcessorDeflate.h" -#include <stdexcept> #include <cstdint> #include <memory> +#include <stdexcept> #include <zlib.h> #include "Utils/ClassUtils.h" #include "Writing/WritingException.h" -class OutputProcessorDeflate::Impl -{ - z_stream m_stream{}; - OutputProcessorDeflate* m_base; +class OutputProcessorDeflate::Impl { + z_stream m_stream{}; + OutputProcessorDeflate *m_base; - std::unique_ptr<uint8_t[]> m_buffer; - size_t m_buffer_size; + std::unique_ptr<uint8_t[]> m_buffer; + size_t m_buffer_size; public: - Impl(OutputProcessorDeflate* baseClass, const size_t bufferSize) - : m_buffer(std::make_unique<uint8_t[]>(bufferSize)), - m_buffer_size(bufferSize) - { - m_base = baseClass; - - m_stream.zalloc = Z_NULL; - m_stream.zfree = Z_NULL; - m_stream.opaque = Z_NULL; - m_stream.avail_in = 0; - m_stream.next_in = Z_NULL; - m_stream.next_out = m_buffer.get(); - m_stream.avail_out = m_buffer_size; + Impl(OutputProcessorDeflate *baseClass, const size_t bufferSize) : m_buffer(std::make_unique<uint8_t[]>(bufferSize)), m_buffer_size(bufferSize) { + m_base = baseClass; - const int ret = deflateInit(&m_stream, Z_DEFAULT_COMPRESSION); + m_stream.zalloc = Z_NULL; + m_stream.zfree = Z_NULL; + m_stream.opaque = Z_NULL; + m_stream.avail_in = 0; + m_stream.next_in = Z_NULL; + m_stream.next_out = m_buffer.get(); + m_stream.avail_out = m_buffer_size; - if (ret != Z_OK) - { - throw std::runtime_error("Initializing deflate failed"); - } - } + const int ret = deflateInit(&m_stream, Z_DEFAULT_COMPRESSION); - ~Impl() - { - deflateEnd(&m_stream); + if (ret != Z_OK) { + throw std::runtime_error("Initializing deflate failed"); } + } + + ~Impl() { deflateEnd(&m_stream); } + + Impl(const Impl &other) = delete; + Impl(Impl &&other) noexcept = default; + Impl &operator=(const Impl &other) = delete; + Impl &operator=(Impl &&other) noexcept = default; + + void Write(const void *buffer, const size_t length) { + m_stream.next_in = static_cast<const Bytef *>(buffer); + m_stream.avail_in = length; + + while (m_stream.avail_in > 0) { + if (m_stream.avail_out == 0) { + m_base->m_base_stream->Write(m_buffer.get(), m_buffer_size); + m_stream.next_out = m_buffer.get(); + m_stream.avail_out = m_buffer_size; + } - Impl(const Impl& other) = delete; - Impl(Impl&& other) noexcept = default; - Impl& operator=(const Impl& other) = delete; - Impl& operator=(Impl&& other) noexcept = default; - - void Write(const void* buffer, const size_t length) - { - m_stream.next_in = static_cast<const Bytef*>(buffer); - m_stream.avail_in = length; - - while (m_stream.avail_in > 0) - { - if (m_stream.avail_out == 0) - { - m_base->m_base_stream->Write(m_buffer.get(), m_buffer_size); - m_stream.next_out = m_buffer.get(); - m_stream.avail_out = m_buffer_size; - } - - const auto ret = deflate(&m_stream, Z_NO_FLUSH); - if (ret != Z_OK) - throw WritingException("Failed to deflate memory of zone."); - } + const auto ret = deflate(&m_stream, Z_NO_FLUSH); + if (ret != Z_OK) + throw WritingException("Failed to deflate memory of zone."); } + } + + void Flush() { + m_stream.avail_in = 0; + m_stream.next_in = Z_NULL; + while (true) { + if (m_stream.avail_out < m_buffer_size) { + m_base->m_base_stream->Write(m_buffer.get(), m_buffer_size - m_stream.avail_out); + m_stream.next_out = m_buffer.get(); + m_stream.avail_out = m_buffer_size; + } + + const auto ret = deflate(&m_stream, Z_FINISH); + if (ret == Z_OK) + continue; - void Flush() - { - m_stream.avail_in = 0; - m_stream.next_in = Z_NULL; - while(true) - { - if (m_stream.avail_out < m_buffer_size) - { - m_base->m_base_stream->Write(m_buffer.get(), m_buffer_size - m_stream.avail_out); - m_stream.next_out = m_buffer.get(); - m_stream.avail_out = m_buffer_size; - } - - const auto ret = deflate(&m_stream, Z_FINISH); - if(ret == Z_OK) - continue; - - if (ret != Z_STREAM_END) - throw WritingException("Failed to flush deflate memory of zone."); - - break; - } - - if (m_stream.avail_out < m_buffer_size) - { - m_base->m_base_stream->Write(m_buffer.get(), m_buffer_size - m_stream.avail_out); - m_stream.next_out = m_buffer.get(); - m_stream.avail_out = m_buffer_size; - } + if (ret != Z_STREAM_END) + throw WritingException("Failed to flush deflate memory of zone."); + + break; } - _NODISCARD int64_t Pos() const - { - return m_base->m_base_stream->Pos(); + if (m_stream.avail_out < m_buffer_size) { + m_base->m_base_stream->Write(m_buffer.get(), m_buffer_size - m_stream.avail_out); + m_stream.next_out = m_buffer.get(); + m_stream.avail_out = m_buffer_size; } + } + + _NODISCARD int64_t Pos() const { return m_base->m_base_stream->Pos(); } }; -OutputProcessorDeflate::OutputProcessorDeflate() - : m_impl(new Impl(this, DEFAULT_BUFFER_SIZE)) -{ -} +OutputProcessorDeflate::OutputProcessorDeflate() : m_impl(new Impl(this, DEFAULT_BUFFER_SIZE)) {} -OutputProcessorDeflate::OutputProcessorDeflate(const size_t bufferSize) - : m_impl(new Impl(this, bufferSize)) -{ -} +OutputProcessorDeflate::OutputProcessorDeflate(const size_t bufferSize) : m_impl(new Impl(this, bufferSize)) {} -OutputProcessorDeflate::~OutputProcessorDeflate() -{ - delete m_impl; - m_impl = nullptr; +OutputProcessorDeflate::~OutputProcessorDeflate() { + delete m_impl; + m_impl = nullptr; } -void OutputProcessorDeflate::Write(const void* buffer, const size_t length) -{ - m_impl->Write(buffer, length); -} +void OutputProcessorDeflate::Write(const void *buffer, const size_t length) { m_impl->Write(buffer, length); } -void OutputProcessorDeflate::Flush() -{ - m_impl->Flush(); -} +void OutputProcessorDeflate::Flush() { m_impl->Flush(); } -int64_t OutputProcessorDeflate::Pos() -{ - return m_impl->Pos(); -} +int64_t OutputProcessorDeflate::Pos() { return m_impl->Pos(); } diff --git a/src/ZoneWriting/Writing/Processor/OutputProcessorDeflate.h b/src/ZoneWriting/Writing/Processor/OutputProcessorDeflate.h index a7e7036e2..87acb79f4 100644 --- a/src/ZoneWriting/Writing/Processor/OutputProcessorDeflate.h +++ b/src/ZoneWriting/Writing/Processor/OutputProcessorDeflate.h @@ -1,26 +1,25 @@ #pragma once -#include <cstdint> #include <cstddef> +#include <cstdint> #include "Writing/OutputStreamProcessor.h" -class OutputProcessorDeflate final : public OutputStreamProcessor -{ - class Impl; - Impl* m_impl; +class OutputProcessorDeflate final : public OutputStreamProcessor { + class Impl; + Impl *m_impl; - static constexpr size_t DEFAULT_BUFFER_SIZE = 0x40000; + static constexpr size_t DEFAULT_BUFFER_SIZE = 0x40000; public: - OutputProcessorDeflate(); - OutputProcessorDeflate(size_t bufferSize); - ~OutputProcessorDeflate() override; - OutputProcessorDeflate(const OutputProcessorDeflate& other) = delete; - OutputProcessorDeflate(OutputProcessorDeflate&& other) noexcept = default; - OutputProcessorDeflate& operator=(const OutputProcessorDeflate& other) = delete; - OutputProcessorDeflate& operator=(OutputProcessorDeflate&& other) noexcept = default; + OutputProcessorDeflate(); + OutputProcessorDeflate(size_t bufferSize); + ~OutputProcessorDeflate() override; + OutputProcessorDeflate(const OutputProcessorDeflate &other) = delete; + OutputProcessorDeflate(OutputProcessorDeflate &&other) noexcept = default; + OutputProcessorDeflate &operator=(const OutputProcessorDeflate &other) = delete; + OutputProcessorDeflate &operator=(OutputProcessorDeflate &&other) noexcept = default; - void Write(const void* buffer, size_t length) override; - void Flush() override; - int64_t Pos() override; + void Write(const void *buffer, size_t length) override; + void Flush() override; + int64_t Pos() override; }; \ No newline at end of file diff --git a/src/ZoneWriting/Writing/Processor/OutputProcessorXChunks.cpp b/src/ZoneWriting/Writing/Processor/OutputProcessorXChunks.cpp index 4bf265a63..73f7a897c 100644 --- a/src/ZoneWriting/Writing/Processor/OutputProcessorXChunks.cpp +++ b/src/ZoneWriting/Writing/Processor/OutputProcessorXChunks.cpp @@ -4,124 +4,98 @@ #include <cstring> #include "Writing/WritingException.h" -#include "Zone/ZoneTypes.h" #include "Zone/XChunk/XChunkException.h" +#include "Zone/ZoneTypes.h" -void OutputProcessorXChunks::Init() -{ - if (m_vanilla_buffer_size > 0) - m_vanilla_buffer_offset = static_cast<size_t>(m_base_stream->Pos()) % m_vanilla_buffer_size; +void OutputProcessorXChunks::Init() { + if (m_vanilla_buffer_size > 0) + m_vanilla_buffer_offset = static_cast<size_t>(m_base_stream->Pos()) % m_vanilla_buffer_size; - m_initialized = true; + m_initialized = true; } -void OutputProcessorXChunks::WriteChunk() -{ - if (m_vanilla_buffer_size > 0) - { - if (m_vanilla_buffer_offset + sizeof(xchunk_size_t) > m_vanilla_buffer_size) - { - xchunk_size_t zeroMem = 0; - m_base_stream->Write(&zeroMem, m_vanilla_buffer_size - m_vanilla_buffer_offset); - m_vanilla_buffer_offset = 0; - } +void OutputProcessorXChunks::WriteChunk() { + if (m_vanilla_buffer_size > 0) { + if (m_vanilla_buffer_offset + sizeof(xchunk_size_t) > m_vanilla_buffer_size) { + xchunk_size_t zeroMem = 0; + m_base_stream->Write(&zeroMem, m_vanilla_buffer_size - m_vanilla_buffer_offset); + m_vanilla_buffer_offset = 0; } - - try - { - for (const auto& processor : m_chunk_processors) - { - m_input_size = processor->Process(m_current_stream, m_input_buffer, m_input_size, m_output_buffer, m_chunk_size); - auto* swap = m_input_buffer; - m_input_buffer = m_output_buffer; - m_output_buffer = swap; - } - } - catch (XChunkException& e) - { - throw WritingException(e.Message()); + } + + try { + for (const auto &processor : m_chunk_processors) { + m_input_size = processor->Process(m_current_stream, m_input_buffer, m_input_size, m_output_buffer, m_chunk_size); + auto *swap = m_input_buffer; + m_input_buffer = m_output_buffer; + m_output_buffer = swap; } + } catch (XChunkException &e) { + throw WritingException(e.Message()); + } - auto chunkSize = static_cast<xchunk_size_t>(m_input_size); - m_base_stream->Write(&chunkSize, sizeof(chunkSize)); - m_base_stream->Write(m_input_buffer, m_input_size); + auto chunkSize = static_cast<xchunk_size_t>(m_input_size); + m_base_stream->Write(&chunkSize, sizeof(chunkSize)); + m_base_stream->Write(m_input_buffer, m_input_size); - if (m_vanilla_buffer_size > 0) - { - m_vanilla_buffer_offset += sizeof(chunkSize) + m_input_size; - m_vanilla_buffer_offset %= m_vanilla_buffer_size; - } + if (m_vanilla_buffer_size > 0) { + m_vanilla_buffer_offset += sizeof(chunkSize) + m_input_size; + m_vanilla_buffer_offset %= m_vanilla_buffer_size; + } - m_current_stream = (m_current_stream + 1) % m_stream_count; - m_input_size = 0; + m_current_stream = (m_current_stream + 1) % m_stream_count; + m_input_size = 0; } OutputProcessorXChunks::OutputProcessorXChunks(const int numStreams, const size_t xChunkSize, const size_t xChunkWriteSize) - : m_stream_count(numStreams), - m_chunk_size(xChunkSize), - m_chunk_write_size(xChunkWriteSize), - m_vanilla_buffer_size(0), - m_initialized(false), - m_current_stream(0), - m_vanilla_buffer_offset(0), - m_input_buffer(nullptr), - m_output_buffer(nullptr), - m_input_size(0) -{ - assert(numStreams > 0); - assert(xChunkSize > 0); - assert(m_chunk_size >= m_chunk_write_size); - - for (auto i = 0u; i < 2u; i++) - m_buffers.emplace_back(std::make_unique<uint8_t[]>(xChunkSize)); - - m_input_buffer = m_buffers[0].get(); - m_output_buffer = m_buffers[1].get(); + : m_stream_count(numStreams), m_chunk_size(xChunkSize), m_chunk_write_size(xChunkWriteSize), m_vanilla_buffer_size(0), m_initialized(false), + m_current_stream(0), m_vanilla_buffer_offset(0), m_input_buffer(nullptr), m_output_buffer(nullptr), m_input_size(0) { + assert(numStreams > 0); + assert(xChunkSize > 0); + assert(m_chunk_size >= m_chunk_write_size); + + for (auto i = 0u; i < 2u; i++) + m_buffers.emplace_back(std::make_unique<uint8_t[]>(xChunkSize)); + + m_input_buffer = m_buffers[0].get(); + m_output_buffer = m_buffers[1].get(); } OutputProcessorXChunks::OutputProcessorXChunks(const int numStreams, const size_t xChunkSize, const size_t xChunkWriteSize, const size_t vanillaBufferSize) - : OutputProcessorXChunks(numStreams, xChunkSize, xChunkWriteSize) -{ - m_vanilla_buffer_size = vanillaBufferSize; + : OutputProcessorXChunks(numStreams, xChunkSize, xChunkWriteSize) { + m_vanilla_buffer_size = vanillaBufferSize; } -void OutputProcessorXChunks::AddChunkProcessor(std::unique_ptr<IXChunkProcessor> chunkProcessor) -{ - assert(chunkProcessor != nullptr); +void OutputProcessorXChunks::AddChunkProcessor(std::unique_ptr<IXChunkProcessor> chunkProcessor) { + assert(chunkProcessor != nullptr); - m_chunk_processors.emplace_back(std::move(chunkProcessor)); + m_chunk_processors.emplace_back(std::move(chunkProcessor)); } -void OutputProcessorXChunks::Write(const void* buffer, const size_t length) -{ - assert(buffer != nullptr); +void OutputProcessorXChunks::Write(const void *buffer, const size_t length) { + assert(buffer != nullptr); - if (!m_initialized) - Init(); + if (!m_initialized) + Init(); - auto sizeRemaining = length; - while (sizeRemaining > 0) - { - const auto toWrite = std::min(m_chunk_write_size - m_input_size, sizeRemaining); + auto sizeRemaining = length; + while (sizeRemaining > 0) { + const auto toWrite = std::min(m_chunk_write_size - m_input_size, sizeRemaining); - memcpy(&m_input_buffer[m_input_size], &static_cast<const char*>(buffer)[length - sizeRemaining], toWrite); - m_input_size += toWrite; - if (m_input_size >= m_chunk_write_size) - WriteChunk(); + memcpy(&m_input_buffer[m_input_size], &static_cast<const char *>(buffer)[length - sizeRemaining], toWrite); + m_input_size += toWrite; + if (m_input_size >= m_chunk_write_size) + WriteChunk(); - sizeRemaining -= toWrite; - } + sizeRemaining -= toWrite; + } } -void OutputProcessorXChunks::Flush() -{ - if (m_input_size) - WriteChunk(); +void OutputProcessorXChunks::Flush() { + if (m_input_size) + WriteChunk(); - m_base_stream->Flush(); + m_base_stream->Flush(); } -int64_t OutputProcessorXChunks::Pos() -{ - return m_base_stream->Pos(); -} +int64_t OutputProcessorXChunks::Pos() { return m_base_stream->Pos(); } diff --git a/src/ZoneWriting/Writing/Processor/OutputProcessorXChunks.h b/src/ZoneWriting/Writing/Processor/OutputProcessorXChunks.h index 83ff87156..15d4768fb 100644 --- a/src/ZoneWriting/Writing/Processor/OutputProcessorXChunks.h +++ b/src/ZoneWriting/Writing/Processor/OutputProcessorXChunks.h @@ -1,46 +1,45 @@ #pragma once +#include <cstddef> +#include <cstdint> #include <memory> #include <vector> -#include <cstdint> -#include <cstddef> #include "Writing/OutputStreamProcessor.h" #include "Zone/XChunk/IXChunkProcessor.h" -class OutputProcessorXChunks final : public OutputStreamProcessor -{ - std::vector<std::unique_ptr<IXChunkProcessor>> m_chunk_processors; +class OutputProcessorXChunks final : public OutputStreamProcessor { + std::vector<std::unique_ptr<IXChunkProcessor>> m_chunk_processors; - int m_stream_count; - size_t m_chunk_size; - size_t m_chunk_write_size; - size_t m_vanilla_buffer_size; + int m_stream_count; + size_t m_chunk_size; + size_t m_chunk_write_size; + size_t m_vanilla_buffer_size; - bool m_initialized; - int m_current_stream; - size_t m_vanilla_buffer_offset; + bool m_initialized; + int m_current_stream; + size_t m_vanilla_buffer_offset; - std::vector<std::unique_ptr<uint8_t[]>> m_buffers; - uint8_t* m_input_buffer; - uint8_t* m_output_buffer; - size_t m_input_size; + std::vector<std::unique_ptr<uint8_t[]>> m_buffers; + uint8_t *m_input_buffer; + uint8_t *m_output_buffer; + size_t m_input_size; - void Init(); - void WriteChunk(); + void Init(); + void WriteChunk(); public: - OutputProcessorXChunks(int numStreams, size_t xChunkSize, size_t xChunkWriteSize); - OutputProcessorXChunks(int numStreams, size_t xChunkSize, size_t xChunkWriteSize, size_t vanillaBufferSize); - ~OutputProcessorXChunks() override = default; + OutputProcessorXChunks(int numStreams, size_t xChunkSize, size_t xChunkWriteSize); + OutputProcessorXChunks(int numStreams, size_t xChunkSize, size_t xChunkWriteSize, size_t vanillaBufferSize); + ~OutputProcessorXChunks() override = default; - OutputProcessorXChunks(const OutputProcessorXChunks& other) = delete; - OutputProcessorXChunks(OutputProcessorXChunks&& other) noexcept = default; - OutputProcessorXChunks& operator=(const OutputProcessorXChunks& other) = delete; - OutputProcessorXChunks& operator=(OutputProcessorXChunks&& other) noexcept = default; + OutputProcessorXChunks(const OutputProcessorXChunks &other) = delete; + OutputProcessorXChunks(OutputProcessorXChunks &&other) noexcept = default; + OutputProcessorXChunks &operator=(const OutputProcessorXChunks &other) = delete; + OutputProcessorXChunks &operator=(OutputProcessorXChunks &&other) noexcept = default; - void AddChunkProcessor(std::unique_ptr<IXChunkProcessor> chunkProcessor); + void AddChunkProcessor(std::unique_ptr<IXChunkProcessor> chunkProcessor); - void Write(const void* buffer, size_t length) override; - void Flush() override; - int64_t Pos() override; + void Write(const void *buffer, size_t length) override; + void Flush() override; + int64_t Pos() override; }; diff --git a/src/ZoneWriting/Writing/Steps/StepAddOutputProcessor.cpp b/src/ZoneWriting/Writing/Steps/StepAddOutputProcessor.cpp index a61831197..9d7d6d21e 100644 --- a/src/ZoneWriting/Writing/Steps/StepAddOutputProcessor.cpp +++ b/src/ZoneWriting/Writing/Steps/StepAddOutputProcessor.cpp @@ -1,17 +1,13 @@ #include "StepAddOutputProcessor.h" #include <cassert> -StepAddOutputProcessor::StepAddOutputProcessor(std::unique_ptr<OutputStreamProcessor> streamProcessor) - : m_stream_processor(std::move(streamProcessor)) -{ -} +StepAddOutputProcessor::StepAddOutputProcessor(std::unique_ptr<OutputStreamProcessor> streamProcessor) : m_stream_processor(std::move(streamProcessor)) {} -void StepAddOutputProcessor::PerformStep(ZoneWriter* zoneWriter, IWritingStream* stream) -{ - assert(zoneWriter != nullptr); - assert(m_stream_processor != nullptr); +void StepAddOutputProcessor::PerformStep(ZoneWriter *zoneWriter, IWritingStream *stream) { + assert(zoneWriter != nullptr); + assert(m_stream_processor != nullptr); - stream->Flush(); - zoneWriter->AddStreamProcessor(std::move(m_stream_processor)); - m_stream_processor = nullptr; + stream->Flush(); + zoneWriter->AddStreamProcessor(std::move(m_stream_processor)); + m_stream_processor = nullptr; } \ No newline at end of file diff --git a/src/ZoneWriting/Writing/Steps/StepAddOutputProcessor.h b/src/ZoneWriting/Writing/Steps/StepAddOutputProcessor.h index 638a842a0..8e00f5707 100644 --- a/src/ZoneWriting/Writing/Steps/StepAddOutputProcessor.h +++ b/src/ZoneWriting/Writing/Steps/StepAddOutputProcessor.h @@ -2,15 +2,14 @@ #include <memory> -#include "Writing/OutputStreamProcessor.h" #include "Writing/IWritingStep.h" +#include "Writing/OutputStreamProcessor.h" -class StepAddOutputProcessor final : public IWritingStep -{ - std::unique_ptr<OutputStreamProcessor> m_stream_processor; +class StepAddOutputProcessor final : public IWritingStep { + std::unique_ptr<OutputStreamProcessor> m_stream_processor; public: - explicit StepAddOutputProcessor(std::unique_ptr<OutputStreamProcessor> streamProcessor); + explicit StepAddOutputProcessor(std::unique_ptr<OutputStreamProcessor> streamProcessor); - void PerformStep(ZoneWriter* zoneWriter, IWritingStream* stream) override; + void PerformStep(ZoneWriter *zoneWriter, IWritingStream *stream) override; }; diff --git a/src/ZoneWriting/Writing/Steps/StepAlign.cpp b/src/ZoneWriting/Writing/Steps/StepAlign.cpp index 9f8cdde7d..80ed1ba5e 100644 --- a/src/ZoneWriting/Writing/Steps/StepAlign.cpp +++ b/src/ZoneWriting/Writing/Steps/StepAlign.cpp @@ -1,17 +1,12 @@ #include "StepAlign.h" -StepAlign::StepAlign(const size_t alignTo, const uint8_t alignValue) - : m_align_to(alignTo), - m_align_value(alignValue) -{ -} +StepAlign::StepAlign(const size_t alignTo, const uint8_t alignValue) : m_align_to(alignTo), m_align_value(alignValue) {} -void StepAlign::PerformStep(ZoneWriter* zoneWriter, IWritingStream* stream) -{ - const auto pos = stream->Pos(); - const auto targetPos = (pos + m_align_to - 1) / m_align_to * m_align_to; - const auto valueCount = static_cast<size_t>(targetPos - pos); +void StepAlign::PerformStep(ZoneWriter *zoneWriter, IWritingStream *stream) { + const auto pos = stream->Pos(); + const auto targetPos = (pos + m_align_to - 1) / m_align_to * m_align_to; + const auto valueCount = static_cast<size_t>(targetPos - pos); - for(auto i = 0u; i < valueCount; i++) - stream->Write(&m_align_value, sizeof(m_align_value)); + for (auto i = 0u; i < valueCount; i++) + stream->Write(&m_align_value, sizeof(m_align_value)); } diff --git a/src/ZoneWriting/Writing/Steps/StepAlign.h b/src/ZoneWriting/Writing/Steps/StepAlign.h index aa730a2f9..314788a03 100644 --- a/src/ZoneWriting/Writing/Steps/StepAlign.h +++ b/src/ZoneWriting/Writing/Steps/StepAlign.h @@ -5,13 +5,12 @@ #include "Writing/IWritingStep.h" -class StepAlign final : public IWritingStep -{ - size_t m_align_to; - uint8_t m_align_value; +class StepAlign final : public IWritingStep { + size_t m_align_to; + uint8_t m_align_value; public: - StepAlign(size_t alignTo, uint8_t alignValue); + StepAlign(size_t alignTo, uint8_t alignValue); - void PerformStep(ZoneWriter* zoneWriter, IWritingStream* stream) override; + void PerformStep(ZoneWriter *zoneWriter, IWritingStream *stream) override; }; diff --git a/src/ZoneWriting/Writing/Steps/StepRemoveOutputProcessor.cpp b/src/ZoneWriting/Writing/Steps/StepRemoveOutputProcessor.cpp index a057d619c..96a721b7d 100644 --- a/src/ZoneWriting/Writing/Steps/StepRemoveOutputProcessor.cpp +++ b/src/ZoneWriting/Writing/Steps/StepRemoveOutputProcessor.cpp @@ -1,12 +1,8 @@ #include "StepRemoveOutputProcessor.h" -StepRemoveOutputProcessor::StepRemoveOutputProcessor(OutputStreamProcessor* streamProcessor) - : m_stream_processor(streamProcessor) -{ -} +StepRemoveOutputProcessor::StepRemoveOutputProcessor(OutputStreamProcessor *streamProcessor) : m_stream_processor(streamProcessor) {} -void StepRemoveOutputProcessor::PerformStep(ZoneWriter* zoneWriter, IWritingStream* stream) -{ - stream->Flush(); - zoneWriter->RemoveStreamProcessor(m_stream_processor); +void StepRemoveOutputProcessor::PerformStep(ZoneWriter *zoneWriter, IWritingStream *stream) { + stream->Flush(); + zoneWriter->RemoveStreamProcessor(m_stream_processor); } diff --git a/src/ZoneWriting/Writing/Steps/StepRemoveOutputProcessor.h b/src/ZoneWriting/Writing/Steps/StepRemoveOutputProcessor.h index 7b8fc1f8d..3bb101976 100644 --- a/src/ZoneWriting/Writing/Steps/StepRemoveOutputProcessor.h +++ b/src/ZoneWriting/Writing/Steps/StepRemoveOutputProcessor.h @@ -1,14 +1,13 @@ #pragma once -#include "Writing/OutputStreamProcessor.h" #include "Writing/IWritingStep.h" +#include "Writing/OutputStreamProcessor.h" -class StepRemoveOutputProcessor final : public IWritingStep -{ - OutputStreamProcessor* m_stream_processor; +class StepRemoveOutputProcessor final : public IWritingStep { + OutputStreamProcessor *m_stream_processor; public: - explicit StepRemoveOutputProcessor(OutputStreamProcessor* streamProcessor); + explicit StepRemoveOutputProcessor(OutputStreamProcessor *streamProcessor); - void PerformStep(ZoneWriter* zoneWriter, IWritingStream* stream) override; + void PerformStep(ZoneWriter *zoneWriter, IWritingStream *stream) override; }; diff --git a/src/ZoneWriting/Writing/Steps/StepWriteTimestamp.cpp b/src/ZoneWriting/Writing/Steps/StepWriteTimestamp.cpp index c06812655..ba753bd83 100644 --- a/src/ZoneWriting/Writing/Steps/StepWriteTimestamp.cpp +++ b/src/ZoneWriting/Writing/Steps/StepWriteTimestamp.cpp @@ -3,13 +3,10 @@ #include <algorithm> #include <ctime> -StepWriteTimestamp::StepWriteTimestamp() -{ -} +StepWriteTimestamp::StepWriteTimestamp() {} -void StepWriteTimestamp::PerformStep(ZoneWriter* zoneWriter, IWritingStream* stream) -{ - // time_t is not guaranteed to be 64bit so cast is necessary - const auto time = static_cast<int64_t>(std::time(nullptr)); - stream->Write(&time, sizeof(time)); +void StepWriteTimestamp::PerformStep(ZoneWriter *zoneWriter, IWritingStream *stream) { + // time_t is not guaranteed to be 64bit so cast is necessary + const auto time = static_cast<int64_t>(std::time(nullptr)); + stream->Write(&time, sizeof(time)); } diff --git a/src/ZoneWriting/Writing/Steps/StepWriteTimestamp.h b/src/ZoneWriting/Writing/Steps/StepWriteTimestamp.h index 58ae7021f..616dd5411 100644 --- a/src/ZoneWriting/Writing/Steps/StepWriteTimestamp.h +++ b/src/ZoneWriting/Writing/Steps/StepWriteTimestamp.h @@ -1,10 +1,9 @@ #pragma once #include "Writing/IWritingStep.h" -class StepWriteTimestamp final : public IWritingStep -{ +class StepWriteTimestamp final : public IWritingStep { public: - StepWriteTimestamp(); + StepWriteTimestamp(); - void PerformStep(ZoneWriter* zoneWriter, IWritingStream* stream) override; + void PerformStep(ZoneWriter *zoneWriter, IWritingStream *stream) override; }; diff --git a/src/ZoneWriting/Writing/Steps/StepWriteXBlockSizes.cpp b/src/ZoneWriting/Writing/Steps/StepWriteXBlockSizes.cpp index baa59ff56..a4d819f2d 100644 --- a/src/ZoneWriting/Writing/Steps/StepWriteXBlockSizes.cpp +++ b/src/ZoneWriting/Writing/Steps/StepWriteXBlockSizes.cpp @@ -1,15 +1,10 @@ #include "StepWriteXBlockSizes.h" -StepWriteXBlockSizes::StepWriteXBlockSizes(Zone* zone) - : m_zone(zone) -{ -} +StepWriteXBlockSizes::StepWriteXBlockSizes(Zone *zone) : m_zone(zone) {} -void StepWriteXBlockSizes::PerformStep(ZoneWriter* zoneWriter, IWritingStream* stream) -{ - for(const auto& block : zoneWriter->m_blocks) - { - auto blockSize = static_cast<xblock_size_t>(block->m_buffer_size); - stream->Write(&blockSize, sizeof(blockSize)); - } +void StepWriteXBlockSizes::PerformStep(ZoneWriter *zoneWriter, IWritingStream *stream) { + for (const auto &block : zoneWriter->m_blocks) { + auto blockSize = static_cast<xblock_size_t>(block->m_buffer_size); + stream->Write(&blockSize, sizeof(blockSize)); + } } diff --git a/src/ZoneWriting/Writing/Steps/StepWriteXBlockSizes.h b/src/ZoneWriting/Writing/Steps/StepWriteXBlockSizes.h index 88923283e..3b175a1f0 100644 --- a/src/ZoneWriting/Writing/Steps/StepWriteXBlockSizes.h +++ b/src/ZoneWriting/Writing/Steps/StepWriteXBlockSizes.h @@ -2,12 +2,11 @@ #include "Writing/IWritingStep.h" #include "Zone/Zone.h" -class StepWriteXBlockSizes final : public IWritingStep -{ - Zone* m_zone; +class StepWriteXBlockSizes final : public IWritingStep { + Zone *m_zone; public: - explicit StepWriteXBlockSizes(Zone* zone); + explicit StepWriteXBlockSizes(Zone *zone); - void PerformStep(ZoneWriter* zoneWriter, IWritingStream* stream) override; + void PerformStep(ZoneWriter *zoneWriter, IWritingStream *stream) override; }; diff --git a/src/ZoneWriting/Writing/Steps/StepWriteZero.cpp b/src/ZoneWriting/Writing/Steps/StepWriteZero.cpp index 940df2ae5..bfe9a84e4 100644 --- a/src/ZoneWriting/Writing/Steps/StepWriteZero.cpp +++ b/src/ZoneWriting/Writing/Steps/StepWriteZero.cpp @@ -2,19 +2,14 @@ #include <algorithm> -StepWriteZero::StepWriteZero(const size_t count) - : m_count(count) -{ -} +StepWriteZero::StepWriteZero(const size_t count) : m_count(count) {} -void StepWriteZero::PerformStep(ZoneWriter* zoneWriter, IWritingStream* stream) -{ - const uint64_t num = 0; - size_t toWrite; +void StepWriteZero::PerformStep(ZoneWriter *zoneWriter, IWritingStream *stream) { + const uint64_t num = 0; + size_t toWrite; - for(auto i = 0u; i < m_count; i += toWrite) - { - toWrite = std::min(sizeof(uint64_t), m_count - i); - stream->Write(&num, toWrite); - } + for (auto i = 0u; i < m_count; i += toWrite) { + toWrite = std::min(sizeof(uint64_t), m_count - i); + stream->Write(&num, toWrite); + } } diff --git a/src/ZoneWriting/Writing/Steps/StepWriteZero.h b/src/ZoneWriting/Writing/Steps/StepWriteZero.h index 2c4064142..74f77f504 100644 --- a/src/ZoneWriting/Writing/Steps/StepWriteZero.h +++ b/src/ZoneWriting/Writing/Steps/StepWriteZero.h @@ -1,12 +1,11 @@ #pragma once #include "Writing/IWritingStep.h" -class StepWriteZero final : public IWritingStep -{ - size_t m_count; +class StepWriteZero final : public IWritingStep { + size_t m_count; public: - explicit StepWriteZero(size_t count); + explicit StepWriteZero(size_t count); - void PerformStep(ZoneWriter* zoneWriter, IWritingStream* stream) override; + void PerformStep(ZoneWriter *zoneWriter, IWritingStream *stream) override; }; diff --git a/src/ZoneWriting/Writing/Steps/StepWriteZoneContentToFile.cpp b/src/ZoneWriting/Writing/Steps/StepWriteZoneContentToFile.cpp index 8348c331e..3b2506f42 100644 --- a/src/ZoneWriting/Writing/Steps/StepWriteZoneContentToFile.cpp +++ b/src/ZoneWriting/Writing/Steps/StepWriteZoneContentToFile.cpp @@ -1,14 +1,9 @@ #include "StepWriteZoneContentToFile.h" -StepWriteZoneContentToFile::StepWriteZoneContentToFile(StepWriteZoneContentToMemory* zoneMemory) - : m_memory(zoneMemory) -{ -} +StepWriteZoneContentToFile::StepWriteZoneContentToFile(StepWriteZoneContentToMemory *zoneMemory) : m_memory(zoneMemory) {} -void StepWriteZoneContentToFile::PerformStep(ZoneWriter* zoneWriter, IWritingStream* stream) -{ - for(const auto& dataBuffer : m_memory->GetData()->m_buffers) - { - stream->Write(dataBuffer.m_data.get(), dataBuffer.m_size); - } +void StepWriteZoneContentToFile::PerformStep(ZoneWriter *zoneWriter, IWritingStream *stream) { + for (const auto &dataBuffer : m_memory->GetData()->m_buffers) { + stream->Write(dataBuffer.m_data.get(), dataBuffer.m_size); + } } diff --git a/src/ZoneWriting/Writing/Steps/StepWriteZoneContentToFile.h b/src/ZoneWriting/Writing/Steps/StepWriteZoneContentToFile.h index 48f051627..ccbca8e81 100644 --- a/src/ZoneWriting/Writing/Steps/StepWriteZoneContentToFile.h +++ b/src/ZoneWriting/Writing/Steps/StepWriteZoneContentToFile.h @@ -2,12 +2,11 @@ #include "StepWriteZoneContentToMemory.h" #include "Writing/IWritingStep.h" -class StepWriteZoneContentToFile final : public IWritingStep -{ - StepWriteZoneContentToMemory* m_memory; +class StepWriteZoneContentToFile final : public IWritingStep { + StepWriteZoneContentToMemory *m_memory; public: - explicit StepWriteZoneContentToFile(StepWriteZoneContentToMemory* zoneMemory); + explicit StepWriteZoneContentToFile(StepWriteZoneContentToMemory *zoneMemory); - void PerformStep(ZoneWriter* zoneWriter, IWritingStream* stream) override; + void PerformStep(ZoneWriter *zoneWriter, IWritingStream *stream) override; }; diff --git a/src/ZoneWriting/Writing/Steps/StepWriteZoneContentToMemory.cpp b/src/ZoneWriting/Writing/Steps/StepWriteZoneContentToMemory.cpp index 225367a84..b8dfc648e 100644 --- a/src/ZoneWriting/Writing/Steps/StepWriteZoneContentToMemory.cpp +++ b/src/ZoneWriting/Writing/Steps/StepWriteZoneContentToMemory.cpp @@ -2,26 +2,18 @@ #include "Zone/Stream/Impl/InMemoryZoneOutputStream.h" -StepWriteZoneContentToMemory::StepWriteZoneContentToMemory(std::unique_ptr<IContentWritingEntryPoint> entryPoint, Zone* zone, int offsetBlockBitCount, block_t insertBlock) - : m_content_loader(std::move(entryPoint)), - m_zone_data(std::make_unique<InMemoryZoneData>()), - m_zone(zone), - m_offset_block_bit_count(offsetBlockBitCount), - m_insert_block(insertBlock) -{ -} +StepWriteZoneContentToMemory::StepWriteZoneContentToMemory(std::unique_ptr<IContentWritingEntryPoint> entryPoint, Zone *zone, int offsetBlockBitCount, + block_t insertBlock) + : m_content_loader(std::move(entryPoint)), m_zone_data(std::make_unique<InMemoryZoneData>()), m_zone(zone), m_offset_block_bit_count(offsetBlockBitCount), + m_insert_block(insertBlock) {} -void StepWriteZoneContentToMemory::PerformStep(ZoneWriter* zoneWriter, IWritingStream* stream) -{ - std::vector<XBlock*> blocks; - for (const auto& block : zoneWriter->m_blocks) - blocks.push_back(block.get()); +void StepWriteZoneContentToMemory::PerformStep(ZoneWriter *zoneWriter, IWritingStream *stream) { + std::vector<XBlock *> blocks; + for (const auto &block : zoneWriter->m_blocks) + blocks.push_back(block.get()); - const auto zoneOutputStream = std::make_unique<InMemoryZoneOutputStream>(m_zone_data.get(), std::move(blocks), m_offset_block_bit_count, m_insert_block); - m_content_loader->WriteContent(m_zone, zoneOutputStream.get()); + const auto zoneOutputStream = std::make_unique<InMemoryZoneOutputStream>(m_zone_data.get(), std::move(blocks), m_offset_block_bit_count, m_insert_block); + m_content_loader->WriteContent(m_zone, zoneOutputStream.get()); } -InMemoryZoneData* StepWriteZoneContentToMemory::GetData() const -{ - return m_zone_data.get(); -} +InMemoryZoneData *StepWriteZoneContentToMemory::GetData() const { return m_zone_data.get(); } diff --git a/src/ZoneWriting/Writing/Steps/StepWriteZoneContentToMemory.h b/src/ZoneWriting/Writing/Steps/StepWriteZoneContentToMemory.h index 6ec4713e6..461d302f7 100644 --- a/src/ZoneWriting/Writing/Steps/StepWriteZoneContentToMemory.h +++ b/src/ZoneWriting/Writing/Steps/StepWriteZoneContentToMemory.h @@ -4,20 +4,19 @@ #include "Utils/ClassUtils.h" #include "Writing/IContentWritingEntryPoint.h" -#include "Writing/InMemoryZoneData.h" #include "Writing/IWritingStep.h" +#include "Writing/InMemoryZoneData.h" -class StepWriteZoneContentToMemory final : public IWritingStep -{ - std::unique_ptr<IContentWritingEntryPoint> m_content_loader; - std::unique_ptr<InMemoryZoneData> m_zone_data; - Zone* m_zone; - int m_offset_block_bit_count; - block_t m_insert_block; +class StepWriteZoneContentToMemory final : public IWritingStep { + std::unique_ptr<IContentWritingEntryPoint> m_content_loader; + std::unique_ptr<InMemoryZoneData> m_zone_data; + Zone *m_zone; + int m_offset_block_bit_count; + block_t m_insert_block; public: - StepWriteZoneContentToMemory(std::unique_ptr<IContentWritingEntryPoint> entryPoint, Zone* zone, int offsetBlockBitCount, block_t insertBlock); + StepWriteZoneContentToMemory(std::unique_ptr<IContentWritingEntryPoint> entryPoint, Zone *zone, int offsetBlockBitCount, block_t insertBlock); - void PerformStep(ZoneWriter* zoneWriter, IWritingStream* stream) override; - _NODISCARD InMemoryZoneData* GetData() const; + void PerformStep(ZoneWriter *zoneWriter, IWritingStream *stream) override; + _NODISCARD InMemoryZoneData *GetData() const; }; diff --git a/src/ZoneWriting/Writing/Steps/StepWriteZoneHeader.cpp b/src/ZoneWriting/Writing/Steps/StepWriteZoneHeader.cpp index ebe34b2e8..506270a58 100644 --- a/src/ZoneWriting/Writing/Steps/StepWriteZoneHeader.cpp +++ b/src/ZoneWriting/Writing/Steps/StepWriteZoneHeader.cpp @@ -1,11 +1,5 @@ #include "StepWriteZoneHeader.h" -StepWriteZoneHeader::StepWriteZoneHeader(const ZoneHeader header) - : m_header(header) -{ -} +StepWriteZoneHeader::StepWriteZoneHeader(const ZoneHeader header) : m_header(header) {} -void StepWriteZoneHeader::PerformStep(ZoneWriter* zoneWriter, IWritingStream* stream) -{ - stream->Write(&m_header, sizeof(m_header)); -} +void StepWriteZoneHeader::PerformStep(ZoneWriter *zoneWriter, IWritingStream *stream) { stream->Write(&m_header, sizeof(m_header)); } diff --git a/src/ZoneWriting/Writing/Steps/StepWriteZoneHeader.h b/src/ZoneWriting/Writing/Steps/StepWriteZoneHeader.h index 249673c39..2c2fef339 100644 --- a/src/ZoneWriting/Writing/Steps/StepWriteZoneHeader.h +++ b/src/ZoneWriting/Writing/Steps/StepWriteZoneHeader.h @@ -1,12 +1,11 @@ #pragma once #include "Writing/IWritingStep.h" -class StepWriteZoneHeader final : public IWritingStep -{ - ZoneHeader m_header; +class StepWriteZoneHeader final : public IWritingStep { + ZoneHeader m_header; public: - explicit StepWriteZoneHeader(ZoneHeader header); + explicit StepWriteZoneHeader(ZoneHeader header); - void PerformStep(ZoneWriter* zoneWriter, IWritingStream* stream) override; + void PerformStep(ZoneWriter *zoneWriter, IWritingStream *stream) override; }; diff --git a/src/ZoneWriting/Writing/Steps/StepWriteZoneSizes.cpp b/src/ZoneWriting/Writing/Steps/StepWriteZoneSizes.cpp index 282159a8b..d9c4e3ec2 100644 --- a/src/ZoneWriting/Writing/Steps/StepWriteZoneSizes.cpp +++ b/src/ZoneWriting/Writing/Steps/StepWriteZoneSizes.cpp @@ -1,15 +1,11 @@ #include "StepWriteZoneSizes.h" -StepWriteZoneSizes::StepWriteZoneSizes(StepWriteZoneContentToMemory* memory) - : m_memory(memory) -{ -} +StepWriteZoneSizes::StepWriteZoneSizes(StepWriteZoneContentToMemory *memory) : m_memory(memory) {} -void StepWriteZoneSizes::PerformStep(ZoneWriter* zoneWriter, IWritingStream* stream) -{ - auto totalSize = static_cast<size_t>(m_memory->GetData()->m_total_size); - size_t externalSize = 0; +void StepWriteZoneSizes::PerformStep(ZoneWriter *zoneWriter, IWritingStream *stream) { + auto totalSize = static_cast<size_t>(m_memory->GetData()->m_total_size); + size_t externalSize = 0; - stream->Write(&totalSize, sizeof(totalSize)); - stream->Write(&externalSize, sizeof(externalSize)); + stream->Write(&totalSize, sizeof(totalSize)); + stream->Write(&externalSize, sizeof(externalSize)); } diff --git a/src/ZoneWriting/Writing/Steps/StepWriteZoneSizes.h b/src/ZoneWriting/Writing/Steps/StepWriteZoneSizes.h index 158e0fdf3..a4f85526c 100644 --- a/src/ZoneWriting/Writing/Steps/StepWriteZoneSizes.h +++ b/src/ZoneWriting/Writing/Steps/StepWriteZoneSizes.h @@ -2,12 +2,11 @@ #include "StepWriteZoneContentToMemory.h" #include "Writing/IWritingStep.h" -class StepWriteZoneSizes final : public IWritingStep -{ - StepWriteZoneContentToMemory* m_memory; +class StepWriteZoneSizes final : public IWritingStep { + StepWriteZoneContentToMemory *m_memory; public: - explicit StepWriteZoneSizes(StepWriteZoneContentToMemory* memory); + explicit StepWriteZoneSizes(StepWriteZoneContentToMemory *memory); - void PerformStep(ZoneWriter* zoneWriter, IWritingStream* stream) override; + void PerformStep(ZoneWriter *zoneWriter, IWritingStream *stream) override; }; diff --git a/src/ZoneWriting/Writing/WritingException.cpp b/src/ZoneWriting/Writing/WritingException.cpp index cc49ca395..fe1371bdf 100644 --- a/src/ZoneWriting/Writing/WritingException.cpp +++ b/src/ZoneWriting/Writing/WritingException.cpp @@ -1,16 +1,7 @@ #include "WritingException.h" -WritingException::WritingException(std::string message) - : m_error_message(std::move(message)) -{ -} +WritingException::WritingException(std::string message) : m_error_message(std::move(message)) {} -char const* WritingException::what() const noexcept -{ - return m_error_message.c_str(); -} +char const *WritingException::what() const noexcept { return m_error_message.c_str(); } -const std::string& WritingException::Message() const -{ - return m_error_message; -} +const std::string &WritingException::Message() const { return m_error_message; } diff --git a/src/ZoneWriting/Writing/WritingException.h b/src/ZoneWriting/Writing/WritingException.h index d3dc8664c..3280eb160 100644 --- a/src/ZoneWriting/Writing/WritingException.h +++ b/src/ZoneWriting/Writing/WritingException.h @@ -1,16 +1,15 @@ #pragma once -#include <string> #include <exception> +#include <string> #include "Utils/ClassUtils.h" -class WritingException final : public std::exception -{ - std::string m_error_message; +class WritingException final : public std::exception { + std::string m_error_message; public: - explicit WritingException(std::string message); + explicit WritingException(std::string message); - _NODISCARD char const* what() const noexcept override; - _NODISCARD const std::string& Message() const; + _NODISCARD char const *what() const noexcept override; + _NODISCARD const std::string &Message() const; }; diff --git a/src/ZoneWriting/Writing/WritingFileStream.cpp b/src/ZoneWriting/Writing/WritingFileStream.cpp index 1f6d8b234..b5740e299 100644 --- a/src/ZoneWriting/Writing/WritingFileStream.cpp +++ b/src/ZoneWriting/Writing/WritingFileStream.cpp @@ -1,21 +1,9 @@ #include "WritingFileStream.h" -WritingFileStream::WritingFileStream(std::ostream& stream) - : m_stream(stream) -{ -} +WritingFileStream::WritingFileStream(std::ostream &stream) : m_stream(stream) {} -void WritingFileStream::Write(const void* buffer, const size_t length) -{ - m_stream.write(static_cast<const char*>(buffer), length); -} +void WritingFileStream::Write(const void *buffer, const size_t length) { m_stream.write(static_cast<const char *>(buffer), length); } -void WritingFileStream::Flush() -{ - m_stream.flush(); -} +void WritingFileStream::Flush() { m_stream.flush(); } -int64_t WritingFileStream::Pos() -{ - return m_stream.tellp(); -} +int64_t WritingFileStream::Pos() { return m_stream.tellp(); } diff --git a/src/ZoneWriting/Writing/WritingFileStream.h b/src/ZoneWriting/Writing/WritingFileStream.h index 117d711f0..13e946ad5 100644 --- a/src/ZoneWriting/Writing/WritingFileStream.h +++ b/src/ZoneWriting/Writing/WritingFileStream.h @@ -3,14 +3,13 @@ #include "IWritingStream.h" -class WritingFileStream final : public IWritingStream -{ - std::ostream& m_stream; +class WritingFileStream final : public IWritingStream { + std::ostream &m_stream; public: - explicit WritingFileStream(std::ostream& stream); + explicit WritingFileStream(std::ostream &stream); - void Write(const void* buffer, size_t length) override; - void Flush() override; - int64_t Pos() override; + void Write(const void *buffer, size_t length) override; + void Flush() override; + int64_t Pos() override; }; diff --git a/src/ZoneWriting/Writing/ZoneWriter.cpp b/src/ZoneWriting/Writing/ZoneWriter.cpp index 0f5a96f62..c9c154cf7 100644 --- a/src/ZoneWriting/Writing/ZoneWriter.cpp +++ b/src/ZoneWriting/Writing/ZoneWriter.cpp @@ -6,82 +6,60 @@ #include "WritingException.h" #include "WritingFileStream.h" -ZoneWriter::ZoneWriter() - : m_processor_chain_dirty(false) -{ -} +ZoneWriter::ZoneWriter() : m_processor_chain_dirty(false) {} -IWritingStream* ZoneWriter::BuildWritingChain(IWritingStream* rootStream) -{ - auto* currentStream = rootStream; +IWritingStream *ZoneWriter::BuildWritingChain(IWritingStream *rootStream) { + auto *currentStream = rootStream; - for (const auto& processor : m_processors) - { - processor->SetBaseStream(currentStream); + for (const auto &processor : m_processors) { + processor->SetBaseStream(currentStream); - currentStream = processor.get(); - } + currentStream = processor.get(); + } - m_processor_chain_dirty = false; - return currentStream; + m_processor_chain_dirty = false; + return currentStream; } -void ZoneWriter::AddXBlock(std::unique_ptr<XBlock> block) -{ - m_blocks.emplace_back(std::move(block)); -} +void ZoneWriter::AddXBlock(std::unique_ptr<XBlock> block) { m_blocks.emplace_back(std::move(block)); } -void ZoneWriter::AddWritingStep(std::unique_ptr<IWritingStep> step) -{ - m_steps.emplace_back(std::move(step)); -} +void ZoneWriter::AddWritingStep(std::unique_ptr<IWritingStep> step) { m_steps.emplace_back(std::move(step)); } -void ZoneWriter::AddStreamProcessor(std::unique_ptr<OutputStreamProcessor> streamProcessor) -{ - m_processors.push_back(std::move(streamProcessor)); - m_processor_chain_dirty = true; +void ZoneWriter::AddStreamProcessor(std::unique_ptr<OutputStreamProcessor> streamProcessor) { + m_processors.push_back(std::move(streamProcessor)); + m_processor_chain_dirty = true; } -void ZoneWriter::RemoveStreamProcessor(OutputStreamProcessor* streamProcessor) -{ - for (auto i = m_processors.begin(); i < m_processors.end(); ++i) - { - if (i->get() == streamProcessor) - { - m_processors.erase(i); - m_processor_chain_dirty = true; - break; - } +void ZoneWriter::RemoveStreamProcessor(OutputStreamProcessor *streamProcessor) { + for (auto i = m_processors.begin(); i < m_processors.end(); ++i) { + if (i->get() == streamProcessor) { + m_processors.erase(i); + m_processor_chain_dirty = true; + break; } + } } -bool ZoneWriter::WriteZone(std::ostream& stream) -{ - WritingFileStream fileStream(stream); - auto* endStream = BuildWritingChain(&fileStream); +bool ZoneWriter::WriteZone(std::ostream &stream) { + WritingFileStream fileStream(stream); + auto *endStream = BuildWritingChain(&fileStream); - try - { - for (const auto& step : m_steps) - { - step->PerformStep(this, endStream); + try { + for (const auto &step : m_steps) { + step->PerformStep(this, endStream); - if (m_processor_chain_dirty) - endStream = BuildWritingChain(&fileStream); - } - } - catch (WritingException& e) - { - std::cout << "Writing fastfile failed: " << e.Message() << std::endl; - return false; - } - catch (std::runtime_error& e) - { - std::cout << "Writing fastfile failed: " << e.what() << std::endl; - return false; + if (m_processor_chain_dirty) + endStream = BuildWritingChain(&fileStream); } + } catch (WritingException &e) { + std::cout << "Writing fastfile failed: " << e.Message() << std::endl; + return false; + } catch (std::runtime_error &e) { + std::cout << "Writing fastfile failed: " << e.what() << std::endl; + return false; + } - endStream->Flush(); + endStream->Flush(); - return true; + return true; } diff --git a/src/ZoneWriting/Writing/ZoneWriter.h b/src/ZoneWriting/Writing/ZoneWriter.h index 05cae4a43..e11d631d7 100644 --- a/src/ZoneWriting/Writing/ZoneWriter.h +++ b/src/ZoneWriting/Writing/ZoneWriter.h @@ -1,7 +1,7 @@ #pragma once -#include <vector> #include <memory> +#include <vector> #include "IWritingStep.h" #include "OutputStreamProcessor.h" @@ -9,25 +9,24 @@ class IWritingStep; -class ZoneWriter -{ - std::vector<std::unique_ptr<IWritingStep>> m_steps; - std::vector<std::unique_ptr<OutputStreamProcessor>> m_processors; +class ZoneWriter { + std::vector<std::unique_ptr<IWritingStep>> m_steps; + std::vector<std::unique_ptr<OutputStreamProcessor>> m_processors; - bool m_processor_chain_dirty; + bool m_processor_chain_dirty; - IWritingStream* BuildWritingChain(IWritingStream* rootStream); + IWritingStream *BuildWritingChain(IWritingStream *rootStream); public: - std::vector<std::unique_ptr<XBlock>> m_blocks; + std::vector<std::unique_ptr<XBlock>> m_blocks; - ZoneWriter(); + ZoneWriter(); - void AddXBlock(std::unique_ptr<XBlock> block); - void AddWritingStep(std::unique_ptr<IWritingStep> step); - void AddStreamProcessor(std::unique_ptr<OutputStreamProcessor> streamProcessor); + void AddXBlock(std::unique_ptr<XBlock> block); + void AddWritingStep(std::unique_ptr<IWritingStep> step); + void AddStreamProcessor(std::unique_ptr<OutputStreamProcessor> streamProcessor); - void RemoveStreamProcessor(OutputStreamProcessor* streamProcessor); + void RemoveStreamProcessor(OutputStreamProcessor *streamProcessor); - bool WriteZone(std::ostream& stream); + bool WriteZone(std::ostream &stream); }; diff --git a/src/ZoneWriting/Zone/Stream/IZoneOutputStream.h b/src/ZoneWriting/Zone/Stream/IZoneOutputStream.h index 407685150..142c23b51 100644 --- a/src/ZoneWriting/Zone/Stream/IZoneOutputStream.h +++ b/src/ZoneWriting/Zone/Stream/IZoneOutputStream.h @@ -6,62 +6,41 @@ #include "Zone/Stream/IZoneStream.h" -class IZoneOutputStream : public IZoneStream -{ +class IZoneOutputStream : public IZoneStream { public: - inline static void* const PTR_FOLLOWING = reinterpret_cast<void*>(-1); - inline static void* const PTR_INSERT = reinterpret_cast<void*>(-2); + inline static void *const PTR_FOLLOWING = reinterpret_cast<void *>(-1); + inline static void *const PTR_INSERT = reinterpret_cast<void *>(-2); - virtual void Align(int alignTo) = 0; + virtual void Align(int alignTo) = 0; - virtual void* WriteDataRaw(const void* dst, size_t size) = 0; - virtual void* WriteDataInBlock(const void* dst, size_t size) = 0; - virtual void IncBlockPos(size_t size) = 0; - virtual void WriteNullTerminated(const void* dst) = 0; + virtual void *WriteDataRaw(const void *dst, size_t size) = 0; + virtual void *WriteDataInBlock(const void *dst, size_t size) = 0; + virtual void IncBlockPos(size_t size) = 0; + virtual void WriteNullTerminated(const void *dst) = 0; - virtual bool ReusableShouldWrite(void** pPtr, size_t size, std::type_index type) = 0; - virtual void ReusableAddOffset(void* ptr, size_t size, size_t count, std::type_index type) = 0; - virtual void MarkFollowing(void** pPtr) = 0; + virtual bool ReusableShouldWrite(void **pPtr, size_t size, std::type_index type) = 0; + virtual void ReusableAddOffset(void *ptr, size_t size, size_t count, std::type_index type) = 0; + virtual void MarkFollowing(void **pPtr) = 0; - template<typename T> - bool ReusableShouldWrite(T** pPtr) - { - return ReusableShouldWrite(reinterpret_cast<void**>(reinterpret_cast<uintptr_t>(pPtr)), sizeof(T), std::type_index(typeid(T))); - } + template <typename T> bool ReusableShouldWrite(T **pPtr) { + return ReusableShouldWrite(reinterpret_cast<void **>(reinterpret_cast<uintptr_t>(pPtr)), sizeof(T), std::type_index(typeid(T))); + } - template<typename T> - void ReusableAddOffset(T* ptr) - { - ReusableAddOffset(const_cast<void*>(reinterpret_cast<const void*>(ptr)), sizeof(T), 1, std::type_index(typeid(T))); - } + template <typename T> void ReusableAddOffset(T *ptr) { + ReusableAddOffset(const_cast<void *>(reinterpret_cast<const void *>(ptr)), sizeof(T), 1, std::type_index(typeid(T))); + } - template<typename T> - void ReusableAddOffset(T* ptr, const size_t count) - { - ReusableAddOffset(const_cast<void*>(reinterpret_cast<const void*>(ptr)), sizeof(T), count, std::type_index(typeid(T))); - } + template <typename T> void ReusableAddOffset(T *ptr, const size_t count) { + ReusableAddOffset(const_cast<void *>(reinterpret_cast<const void *>(ptr)), sizeof(T), count, std::type_index(typeid(T))); + } - template<typename T> - T* Write(T* dst) - { - return static_cast<T*>(WriteDataInBlock(reinterpret_cast<const void*>(dst), sizeof(T))); - } + template <typename T> T *Write(T *dst) { return static_cast<T *>(WriteDataInBlock(reinterpret_cast<const void *>(dst), sizeof(T))); } - template<typename T> - T* Write(T* dst, const uint32_t count) - { - return static_cast<T*>(WriteDataInBlock(reinterpret_cast<const void*>(dst), count * sizeof(T))); - } + template <typename T> T *Write(T *dst, const uint32_t count) { + return static_cast<T *>(WriteDataInBlock(reinterpret_cast<const void *>(dst), count * sizeof(T))); + } - template<typename T> - T* WritePartial(T* dst, const size_t size) - { - return static_cast<T*>(WriteDataInBlock(reinterpret_cast<const void*>(dst), size)); - } + template <typename T> T *WritePartial(T *dst, const size_t size) { return static_cast<T *>(WriteDataInBlock(reinterpret_cast<const void *>(dst), size)); } - template<typename T> - void MarkFollowing(T*& ptr) - { - MarkFollowing(reinterpret_cast<void**>(reinterpret_cast<uintptr_t>(&ptr))); - } + template <typename T> void MarkFollowing(T *&ptr) { MarkFollowing(reinterpret_cast<void **>(reinterpret_cast<uintptr_t>(&ptr))); } }; diff --git a/src/ZoneWriting/Zone/Stream/Impl/InMemoryZoneOutputStream.cpp b/src/ZoneWriting/Zone/Stream/Impl/InMemoryZoneOutputStream.cpp index df4411ed4..aecdf88ea 100644 --- a/src/ZoneWriting/Zone/Stream/Impl/InMemoryZoneOutputStream.cpp +++ b/src/ZoneWriting/Zone/Stream/Impl/InMemoryZoneOutputStream.cpp @@ -3,215 +3,181 @@ #include <cassert> #include <cstring> -InMemoryZoneOutputStream::InMemoryZoneOutputStream(InMemoryZoneData* zoneData, std::vector<XBlock*> blocks, const int blockBitCount, const block_t insertBlock) - : m_zone_data(zoneData), - m_blocks(std::move(blocks)), - m_block_bit_count(blockBitCount), - m_insert_block(m_blocks[insertBlock]) -{ -} +InMemoryZoneOutputStream::InMemoryZoneOutputStream(InMemoryZoneData *zoneData, std::vector<XBlock *> blocks, const int blockBitCount, const block_t insertBlock) + : m_zone_data(zoneData), m_blocks(std::move(blocks)), m_block_bit_count(blockBitCount), m_insert_block(m_blocks[insertBlock]) {} -InMemoryZoneOutputStream::ReusableEntry::ReusableEntry(void* startPtr, const size_t entrySize, const size_t entryCount, const uintptr_t startZonePtr) - : m_start_ptr(startPtr), - m_end_ptr(reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(startPtr) + entrySize * entryCount)), - m_start_zone_ptr(startZonePtr), - m_entry_size(entrySize), m_entry_count(entryCount) -{ -} +InMemoryZoneOutputStream::ReusableEntry::ReusableEntry(void *startPtr, const size_t entrySize, const size_t entryCount, const uintptr_t startZonePtr) + : m_start_ptr(startPtr), m_end_ptr(reinterpret_cast<void *>(reinterpret_cast<uintptr_t>(startPtr) + entrySize * entryCount)), + m_start_zone_ptr(startZonePtr), m_entry_size(entrySize), m_entry_count(entryCount) {} -void InMemoryZoneOutputStream::PushBlock(const block_t block) -{ - assert(block >= 0 && block < static_cast<block_t>(m_blocks.size())); +void InMemoryZoneOutputStream::PushBlock(const block_t block) { + assert(block >= 0 && block < static_cast<block_t>(m_blocks.size())); - auto* newBlock = m_blocks[block]; + auto *newBlock = m_blocks[block]; - assert(newBlock->m_index == block); + assert(newBlock->m_index == block); - m_block_stack.push(newBlock); + m_block_stack.push(newBlock); - if (newBlock->m_type == XBlock::Type::BLOCK_TYPE_TEMP) - { - if (m_temp_sizes.empty()) - m_temp_sizes.push(0); - else - m_temp_sizes.push(m_temp_sizes.top()); - } + if (newBlock->m_type == XBlock::Type::BLOCK_TYPE_TEMP) { + if (m_temp_sizes.empty()) + m_temp_sizes.push(0); + else + m_temp_sizes.push(m_temp_sizes.top()); + } } -block_t InMemoryZoneOutputStream::PopBlock() -{ - assert(!m_block_stack.empty()); +block_t InMemoryZoneOutputStream::PopBlock() { + assert(!m_block_stack.empty()); - if (m_block_stack.empty()) - return -1; + if (m_block_stack.empty()) + return -1; - auto* poppedBlock = m_block_stack.top(); - m_block_stack.pop(); + auto *poppedBlock = m_block_stack.top(); + m_block_stack.pop(); - // If temp block is popped, see if its size is bigger than the current maximum temp size - if (poppedBlock->m_type == XBlock::Type::BLOCK_TYPE_TEMP) - { - const auto tempSize = m_temp_sizes.top(); - m_temp_sizes.pop(); + // If temp block is popped, see if its size is bigger than the current maximum temp size + if (poppedBlock->m_type == XBlock::Type::BLOCK_TYPE_TEMP) { + const auto tempSize = m_temp_sizes.top(); + m_temp_sizes.pop(); - if (tempSize > poppedBlock->m_buffer_size) - poppedBlock->m_buffer_size = tempSize; - } + if (tempSize > poppedBlock->m_buffer_size) + poppedBlock->m_buffer_size = tempSize; + } - return poppedBlock->m_index; + return poppedBlock->m_index; } -void InMemoryZoneOutputStream::Align(const int align) -{ - assert(!m_block_stack.empty()); +void InMemoryZoneOutputStream::Align(const int align) { + assert(!m_block_stack.empty()); - if (align > 1) - { - auto* block = m_block_stack.top(); + if (align > 1) { + auto *block = m_block_stack.top(); - if (block->m_type == XBlock::Type::BLOCK_TYPE_TEMP) - m_temp_sizes.top() = (m_temp_sizes.top() + align - 1) / align * align; - else - block->m_buffer_size = (block->m_buffer_size + align - 1) / align * align; - } + if (block->m_type == XBlock::Type::BLOCK_TYPE_TEMP) + m_temp_sizes.top() = (m_temp_sizes.top() + align - 1) / align * align; + else + block->m_buffer_size = (block->m_buffer_size + align - 1) / align * align; + } } -void* InMemoryZoneOutputStream::WriteDataRaw(const void* src, const size_t size) -{ - auto* result = m_zone_data->GetBufferOfSize(size); - memcpy(result, src, size); - return result; +void *InMemoryZoneOutputStream::WriteDataRaw(const void *src, const size_t size) { + auto *result = m_zone_data->GetBufferOfSize(size); + memcpy(result, src, size); + return result; } -void* InMemoryZoneOutputStream::WriteDataInBlock(const void* src, const size_t size) -{ - assert(!m_block_stack.empty()); +void *InMemoryZoneOutputStream::WriteDataInBlock(const void *src, const size_t size) { + assert(!m_block_stack.empty()); - if (m_block_stack.empty()) - return nullptr; + if (m_block_stack.empty()) + return nullptr; - auto* block = m_block_stack.top(); + auto *block = m_block_stack.top(); - void* result = nullptr; - switch (block->m_type) - { - case XBlock::Type::BLOCK_TYPE_TEMP: - case XBlock::Type::BLOCK_TYPE_NORMAL: - result = m_zone_data->GetBufferOfSize(size); - memcpy(result, src, size); - break; + void *result = nullptr; + switch (block->m_type) { + case XBlock::Type::BLOCK_TYPE_TEMP: + case XBlock::Type::BLOCK_TYPE_NORMAL: + result = m_zone_data->GetBufferOfSize(size); + memcpy(result, src, size); + break; - case XBlock::Type::BLOCK_TYPE_RUNTIME: - break; + case XBlock::Type::BLOCK_TYPE_RUNTIME: + break; - case XBlock::Type::BLOCK_TYPE_DELAY: - assert(false); - break; - } + case XBlock::Type::BLOCK_TYPE_DELAY: + assert(false); + break; + } - IncBlockPos(size); - return result; + IncBlockPos(size); + return result; } -void InMemoryZoneOutputStream::IncBlockPos(const size_t size) -{ - assert(!m_block_stack.empty()); +void InMemoryZoneOutputStream::IncBlockPos(const size_t size) { + assert(!m_block_stack.empty()); - if (m_block_stack.empty()) - return; + if (m_block_stack.empty()) + return; - auto* block = m_block_stack.top(); - if (block->m_type == XBlock::Type::BLOCK_TYPE_TEMP) - { - m_temp_sizes.top() += size; - } - else - { - block->m_buffer_size += size; - } + auto *block = m_block_stack.top(); + if (block->m_type == XBlock::Type::BLOCK_TYPE_TEMP) { + m_temp_sizes.top() += size; + } else { + block->m_buffer_size += size; + } } -void InMemoryZoneOutputStream::WriteNullTerminated(const void* src) -{ - const auto len = strlen(static_cast<const char*>(src)); - WriteDataInBlock(src, len + 1); +void InMemoryZoneOutputStream::WriteNullTerminated(const void *src) { + const auto len = strlen(static_cast<const char *>(src)); + WriteDataInBlock(src, len + 1); } -uintptr_t InMemoryZoneOutputStream::GetCurrentZonePointer() -{ - assert(!m_block_stack.empty()); - assert(m_block_stack.top()->m_type == XBlock::Type::BLOCK_TYPE_NORMAL); +uintptr_t InMemoryZoneOutputStream::GetCurrentZonePointer() { + assert(!m_block_stack.empty()); + assert(m_block_stack.top()->m_type == XBlock::Type::BLOCK_TYPE_NORMAL); - uintptr_t ptr = 0; - ptr |= static_cast<uintptr_t>(m_block_stack.top()->m_index) << (sizeof(uintptr_t) * 8 - m_block_bit_count); - ptr |= m_block_stack.top()->m_buffer_size & (UINTPTR_MAX >> m_block_bit_count); - ptr++; + uintptr_t ptr = 0; + ptr |= static_cast<uintptr_t>(m_block_stack.top()->m_index) << (sizeof(uintptr_t) * 8 - m_block_bit_count); + ptr |= m_block_stack.top()->m_buffer_size & (UINTPTR_MAX >> m_block_bit_count); + ptr++; - return ptr; + return ptr; } -uintptr_t InMemoryZoneOutputStream::InsertPointer() -{ - PushBlock(m_insert_block->m_index); +uintptr_t InMemoryZoneOutputStream::InsertPointer() { + PushBlock(m_insert_block->m_index); - Align(sizeof(uintptr_t)); - const auto result = GetCurrentZonePointer(); - IncBlockPos(sizeof(uintptr_t)); + Align(sizeof(uintptr_t)); + const auto result = GetCurrentZonePointer(); + IncBlockPos(sizeof(uintptr_t)); - PopBlock(); + PopBlock(); - return result; + return result; } -void InMemoryZoneOutputStream::MarkFollowing(void** pPtr) -{ - assert(!m_block_stack.empty()); - assert(pPtr != nullptr); - *pPtr = m_block_stack.top()->m_type == XBlock::Type::BLOCK_TYPE_TEMP ? PTR_INSERT : PTR_FOLLOWING; +void InMemoryZoneOutputStream::MarkFollowing(void **pPtr) { + assert(!m_block_stack.empty()); + assert(pPtr != nullptr); + *pPtr = m_block_stack.top()->m_type == XBlock::Type::BLOCK_TYPE_TEMP ? PTR_INSERT : PTR_FOLLOWING; } -bool InMemoryZoneOutputStream::ReusableShouldWrite(void** pPtr, const size_t entrySize, const std::type_index type) -{ - assert(!m_block_stack.empty()); - assert(pPtr != nullptr); +bool InMemoryZoneOutputStream::ReusableShouldWrite(void **pPtr, const size_t entrySize, const std::type_index type) { + assert(!m_block_stack.empty()); + assert(pPtr != nullptr); - if (*pPtr == nullptr) - return false; + if (*pPtr == nullptr) + return false; - const auto foundEntriesForType = m_reusable_entries.find(type); - if (foundEntriesForType == m_reusable_entries.end()) - { - return true; - } + const auto foundEntriesForType = m_reusable_entries.find(type); + if (foundEntriesForType == m_reusable_entries.end()) { + return true; + } - for(const auto& entry : foundEntriesForType->second) - { - if(*pPtr >= entry.m_start_ptr && *pPtr < entry.m_end_ptr) - { - assert((reinterpret_cast<uintptr_t>(*pPtr) - reinterpret_cast<uintptr_t>(entry.m_start_ptr)) % entrySize == 0); - *pPtr = reinterpret_cast<void*>(entry.m_start_zone_ptr + (reinterpret_cast<uintptr_t>(*pPtr) - reinterpret_cast<uintptr_t>(entry.m_start_ptr))); - return false; - } + for (const auto &entry : foundEntriesForType->second) { + if (*pPtr >= entry.m_start_ptr && *pPtr < entry.m_end_ptr) { + assert((reinterpret_cast<uintptr_t>(*pPtr) - reinterpret_cast<uintptr_t>(entry.m_start_ptr)) % entrySize == 0); + *pPtr = reinterpret_cast<void *>(entry.m_start_zone_ptr + (reinterpret_cast<uintptr_t>(*pPtr) - reinterpret_cast<uintptr_t>(entry.m_start_ptr))); + return false; } - - return true; + } + + return true; } -void InMemoryZoneOutputStream::ReusableAddOffset(void* ptr, size_t size, size_t count, std::type_index type) -{ - assert(!m_block_stack.empty()); - - const auto inTemp = m_block_stack.top()->m_type == XBlock::Type::BLOCK_TYPE_TEMP; - auto zoneOffset = inTemp ? InsertPointer() : GetCurrentZonePointer(); - const auto foundEntriesForType = m_reusable_entries.find(type); - if (foundEntriesForType == m_reusable_entries.end()) - { - std::vector<ReusableEntry> entries; - entries.emplace_back(ptr, size, count, zoneOffset); - m_reusable_entries.emplace(std::make_pair(type, std::move(entries))); - } - else - { - foundEntriesForType->second.emplace_back(ptr, size, count, zoneOffset); - } +void InMemoryZoneOutputStream::ReusableAddOffset(void *ptr, size_t size, size_t count, std::type_index type) { + assert(!m_block_stack.empty()); + + const auto inTemp = m_block_stack.top()->m_type == XBlock::Type::BLOCK_TYPE_TEMP; + auto zoneOffset = inTemp ? InsertPointer() : GetCurrentZonePointer(); + const auto foundEntriesForType = m_reusable_entries.find(type); + if (foundEntriesForType == m_reusable_entries.end()) { + std::vector<ReusableEntry> entries; + entries.emplace_back(ptr, size, count, zoneOffset); + m_reusable_entries.emplace(std::make_pair(type, std::move(entries))); + } else { + foundEntriesForType->second.emplace_back(ptr, size, count, zoneOffset); + } } diff --git a/src/ZoneWriting/Zone/Stream/Impl/InMemoryZoneOutputStream.h b/src/ZoneWriting/Zone/Stream/Impl/InMemoryZoneOutputStream.h index f255591c0..a1a1a192d 100644 --- a/src/ZoneWriting/Zone/Stream/Impl/InMemoryZoneOutputStream.h +++ b/src/ZoneWriting/Zone/Stream/Impl/InMemoryZoneOutputStream.h @@ -4,48 +4,46 @@ #include <vector> #include "Writing/InMemoryZoneData.h" -#include "Zone/XBlock.h" #include "Zone/Stream/IZoneOutputStream.h" +#include "Zone/XBlock.h" -class InMemoryZoneOutputStream final : public IZoneOutputStream -{ - class ReusableEntry - { - public: - void* m_start_ptr; - void* m_end_ptr; - uintptr_t m_start_zone_ptr; - size_t m_entry_size; - size_t m_entry_count; +class InMemoryZoneOutputStream final : public IZoneOutputStream { + class ReusableEntry { + public: + void *m_start_ptr; + void *m_end_ptr; + uintptr_t m_start_zone_ptr; + size_t m_entry_size; + size_t m_entry_count; - ReusableEntry(void* startPtr, size_t entrySize, size_t entryCount, uintptr_t startZonePtr); - }; + ReusableEntry(void *startPtr, size_t entrySize, size_t entryCount, uintptr_t startZonePtr); + }; - InMemoryZoneData* m_zone_data; - std::vector<XBlock*> m_blocks; + InMemoryZoneData *m_zone_data; + std::vector<XBlock *> m_blocks; - std::stack<XBlock*> m_block_stack; - std::stack<size_t> m_temp_sizes; + std::stack<XBlock *> m_block_stack; + std::stack<size_t> m_temp_sizes; - int m_block_bit_count; - XBlock* m_insert_block; + int m_block_bit_count; + XBlock *m_insert_block; - std::unordered_map<std::type_index, std::vector<ReusableEntry>> m_reusable_entries; + std::unordered_map<std::type_index, std::vector<ReusableEntry>> m_reusable_entries; - uintptr_t GetCurrentZonePointer(); - uintptr_t InsertPointer(); + uintptr_t GetCurrentZonePointer(); + uintptr_t InsertPointer(); public: - InMemoryZoneOutputStream(InMemoryZoneData* zoneData, std::vector<XBlock*> blocks, int blockBitCount, block_t insertBlock); - - void PushBlock(block_t block) override; - block_t PopBlock() override; - void Align(int align) override; - void* WriteDataRaw(const void* src, size_t size) override; - void* WriteDataInBlock(const void* src, size_t size) override; - void IncBlockPos(size_t size) override; - void WriteNullTerminated(const void* src) override; - void MarkFollowing(void** pPtr) override; - bool ReusableShouldWrite(void** pPtr, size_t entrySize, std::type_index type) override; - void ReusableAddOffset(void* ptr, size_t size, size_t count, std::type_index type) override; + InMemoryZoneOutputStream(InMemoryZoneData *zoneData, std::vector<XBlock *> blocks, int blockBitCount, block_t insertBlock); + + void PushBlock(block_t block) override; + block_t PopBlock() override; + void Align(int align) override; + void *WriteDataRaw(const void *src, size_t size) override; + void *WriteDataInBlock(const void *src, size_t size) override; + void IncBlockPos(size_t size) override; + void WriteNullTerminated(const void *src) override; + void MarkFollowing(void **pPtr) override; + bool ReusableShouldWrite(void **pPtr, size_t entrySize, std::type_index type) override; + void ReusableAddOffset(void *ptr, size_t size, size_t count, std::type_index type) override; }; diff --git a/src/ZoneWriting/ZoneWriting.cpp b/src/ZoneWriting/ZoneWriting.cpp index 75e6dc116..409ebb9b2 100644 --- a/src/ZoneWriting/ZoneWriting.cpp +++ b/src/ZoneWriting/ZoneWriting.cpp @@ -7,32 +7,22 @@ #include "Game/T6/ZoneWriterFactoryT6.h" #include "Writing/IZoneWriterFactory.h" -IZoneWriterFactory* ZoneWriterFactories[] -{ - new IW3::ZoneWriterFactory(), - new IW4::ZoneWriterFactory(), - new IW5::ZoneWriterFactory(), - new T5::ZoneWriterFactory(), - new T6::ZoneWriterFactory() -}; +IZoneWriterFactory *ZoneWriterFactories[]{new IW3::ZoneWriterFactory(), new IW4::ZoneWriterFactory(), new IW5::ZoneWriterFactory(), new T5::ZoneWriterFactory(), + new T6::ZoneWriterFactory()}; -bool ZoneWriting::WriteZone(std::ostream& stream, Zone* zone) -{ - std::unique_ptr<ZoneWriter> zoneWriter; - for (auto* factory : ZoneWriterFactories) - { - if (factory->SupportsZone(zone)) - { - zoneWriter = factory->CreateWriter(zone); - break; - } +bool ZoneWriting::WriteZone(std::ostream &stream, Zone *zone) { + std::unique_ptr<ZoneWriter> zoneWriter; + for (auto *factory : ZoneWriterFactories) { + if (factory->SupportsZone(zone)) { + zoneWriter = factory->CreateWriter(zone); + break; } + } - if (zoneWriter == nullptr) - { - printf("Could not create ZoneWriter for zone '%s'.\n", zone->m_name.c_str()); - return false; - } + if (zoneWriter == nullptr) { + printf("Could not create ZoneWriter for zone '%s'.\n", zone->m_name.c_str()); + return false; + } - return zoneWriter->WriteZone(stream); + return zoneWriter->WriteZone(stream); } diff --git a/src/ZoneWriting/ZoneWriting.h b/src/ZoneWriting/ZoneWriting.h index 8d11f67c7..4c5fd9002 100644 --- a/src/ZoneWriting/ZoneWriting.h +++ b/src/ZoneWriting/ZoneWriting.h @@ -1,11 +1,10 @@ #pragma once -#include <string> #include <ostream> +#include <string> #include "Zone/Zone.h" -class ZoneWriting -{ +class ZoneWriting { public: - static bool WriteZone(std::ostream& stream, Zone* zone); + static bool WriteZone(std::ostream &stream, Zone *zone); }; \ No newline at end of file diff --git a/test/ObjCommonTests/Image/ImageFormatTests.cpp b/test/ObjCommonTests/Image/ImageFormatTests.cpp index a87e1c322..164799bd8 100644 --- a/test/ObjCommonTests/Image/ImageFormatTests.cpp +++ b/test/ObjCommonTests/Image/ImageFormatTests.cpp @@ -5,16 +5,13 @@ #include "Image/ImageFormat.h" -namespace image::image_format -{ - TEST_CASE("ImageFormat: EnsureAllFormatsArrayIndicesAreIds", "[image]") - { - REQUIRE(static_cast<unsigned int>(ImageFormatId::MAX) == std::extent<decltype(ImageFormat::ALL_FORMATS)>::value); +namespace image::image_format { +TEST_CASE("ImageFormat: EnsureAllFormatsArrayIndicesAreIds", "[image]") { + REQUIRE(static_cast<unsigned int>(ImageFormatId::MAX) == std::extent<decltype(ImageFormat::ALL_FORMATS)>::value); - for(unsigned i = 0; i < std::extent<decltype(ImageFormat::ALL_FORMATS)>::value; i++) - { - REQUIRE(ImageFormat::ALL_FORMATS[i] != nullptr); - REQUIRE(i == static_cast<unsigned>(ImageFormat::ALL_FORMATS[i]->GetId())); - } - } -} \ No newline at end of file + for (unsigned i = 0; i < std::extent<decltype(ImageFormat::ALL_FORMATS)>::value; i++) { + REQUIRE(ImageFormat::ALL_FORMATS[i] != nullptr); + REQUIRE(i == static_cast<unsigned>(ImageFormat::ALL_FORMATS[i]->GetId())); + } +} +} // namespace image::image_format \ No newline at end of file diff --git a/test/ObjCommonTests/Obj/Gdt/GdtTests.cpp b/test/ObjCommonTests/Obj/Gdt/GdtTests.cpp index d8bfa8f23..8f27dafb9 100644 --- a/test/ObjCommonTests/Obj/Gdt/GdtTests.cpp +++ b/test/ObjCommonTests/Obj/Gdt/GdtTests.cpp @@ -6,336 +6,327 @@ #include "Obj/Gdt/Gdt.h" #include "Obj/Gdt/GdtStream.h" -namespace obj::gdt -{ - TEST_CASE("Gdt: Ensure can parse simple gdt", "[gdt]") - { - std::string gdtString = "{\n" - "\t\"test_entry\" ( \"test.gdf\" )\n" - "\t{\n" - "\t\t\"testkey\" \"testvalue\"\n" - "\t\t\"test2key\" \"test2value\"\n" - "\t}\n" - "}"; - std::istringstream ss(gdtString); - - Gdt gdt; - GdtReader reader(ss); - REQUIRE(reader.Read(gdt)); - - REQUIRE(gdt.m_entries.size() == 1); - - { - const auto& entry = *gdt.m_entries[0]; - REQUIRE(entry.m_name == "test_entry"); - REQUIRE(entry.m_gdf_name == "test.gdf"); - REQUIRE(entry.m_parent == nullptr); - REQUIRE(entry.m_properties.size() == 2); - - REQUIRE(entry.m_properties.at("testkey") == "testvalue"); - REQUIRE(entry.m_properties.at("test2key") == "test2value"); - } - } - - TEST_CASE("Gdt: Ensure can parse compact gdt", "[gdt]") - { - std::string gdtString = "{" - R"("test_entry"("test.gdf"))" - "{" - R"("testkey""testvalue")" - R"("test2key""test2value")" - "}" - "}"; - std::istringstream ss(gdtString); - - Gdt gdt; - GdtReader reader(ss); - REQUIRE(reader.Read(gdt)); - - REQUIRE(gdt.m_entries.size() == 1); - - { - const auto& entry = *gdt.m_entries[0]; - REQUIRE(entry.m_name == "test_entry"); - REQUIRE(entry.m_gdf_name == "test.gdf"); - REQUIRE(entry.m_parent == nullptr); - REQUIRE(entry.m_properties.size() == 2); - - REQUIRE(entry.m_properties.at("testkey") == "testvalue"); - REQUIRE(entry.m_properties.at("test2key") == "test2value"); - } - } - - TEST_CASE("Gdt: Ensure can parse version section", "[gdt]") - { - std::string gdtString = "{" - R"("version" ( "version.gdf" ))" - "{" - R"("game" "t6")" - R"("version" "1337")" - "}" - "}"; - std::istringstream ss(gdtString); - - Gdt gdt; - GdtReader reader(ss); - REQUIRE(reader.Read(gdt)); - - REQUIRE(gdt.m_entries.empty()); - REQUIRE(gdt.m_version.m_game == "t6"); - REQUIRE(gdt.m_version.m_version == 1337); - } - - TEST_CASE("Gdt: Ensure can parse version section and entries", "[gdt]") - { - std::string gdtString = "{" - R"("version" ( "version.gdf" ))" - "{" - R"("game" "t6")" - R"("version" "1337")" - "}" - R"("test_entry" ( "another_test.gdf" ))" - "{" - R"("game" "t6")" - R"("version" "420")" - "}" - "}"; - std::istringstream ss(gdtString); - - Gdt gdt; - GdtReader reader(ss); - REQUIRE(reader.Read(gdt)); - - REQUIRE(gdt.m_version.m_game == "t6"); - REQUIRE(gdt.m_version.m_version == 1337); - - REQUIRE(gdt.m_entries.size() == 1); - - { - const auto& entry = *gdt.m_entries[0]; - REQUIRE(entry.m_name == "test_entry"); - REQUIRE(entry.m_gdf_name == "another_test.gdf"); - REQUIRE(entry.m_parent == nullptr); - REQUIRE(entry.m_properties.size() == 2); - - REQUIRE(entry.m_properties.at("game") == "t6"); - REQUIRE(entry.m_properties.at("version") == "420"); - } - } - - TEST_CASE("Gdt: Ensure can parse multiple entries", "[gdt]") - { - std::string gdtString = "{" - R"("version" ( "version.gdf" ))" - "{" - R"("game" "t6")" - R"("version" "1337")" - "}" - R"("test_entry" ( "another_test.gdf" ))" - "{" - R"("game" "t6")" - R"("version" "420")" - "}" - R"("yet_another_entry" ( "super_kewl_asset_type.gdf" ))" - "{" - R"("name" "hello")" - R"("value" "asdf")" - R"("value2" "22")" - "}" - R"("final_entry" ( "quite_boring.gdf" ))" - "{" - R"("_HI_" "Hello World")" - "}" - "}"; - std::istringstream ss(gdtString); - - Gdt gdt; - GdtReader reader(ss); - REQUIRE(reader.Read(gdt)); - - REQUIRE(gdt.m_version.m_game == "t6"); - REQUIRE(gdt.m_version.m_version == 1337); - - REQUIRE(gdt.m_entries.size() == 3); - - { - const auto& entry = *gdt.m_entries[0]; - REQUIRE(entry.m_name == "test_entry"); - REQUIRE(entry.m_gdf_name == "another_test.gdf"); - REQUIRE(entry.m_parent == nullptr); - REQUIRE(entry.m_properties.size() == 2); - - REQUIRE(entry.m_properties.at("game") == "t6"); - REQUIRE(entry.m_properties.at("version") == "420"); - } - - { - const auto& entry = *gdt.m_entries[1]; - REQUIRE(entry.m_name == "yet_another_entry"); - REQUIRE(entry.m_gdf_name == "super_kewl_asset_type.gdf"); - REQUIRE(entry.m_parent == nullptr); - REQUIRE(entry.m_properties.size() == 3); - - REQUIRE(entry.m_properties.at("name") == "hello"); - REQUIRE(entry.m_properties.at("value") == "asdf"); - REQUIRE(entry.m_properties.at("value2") == "22"); - } - - { - const auto& entry = *gdt.m_entries[2]; - REQUIRE(entry.m_name == "final_entry"); - REQUIRE(entry.m_gdf_name == "quite_boring.gdf"); - REQUIRE(entry.m_parent == nullptr); - REQUIRE(entry.m_properties.size() == 1); - - REQUIRE(entry.m_properties.at("_HI_") == "Hello World"); - } - } - - TEST_CASE("Gdt: Ensure can parse entries with parent", "[gdt]") - { - std::string gdtString = "{" - R"("version" ( "version.gdf" ))" - "{" - R"("game" "t6")" - R"("version" "1337")" - "}" - R"("test_entry" ( "another_test.gdf" ))" - "{" - R"("game" "t6")" - R"("version" "420")" - "}" - R"("yet_another_entry" [ "test_entry" ])" - "{" - R"("name" "hello")" - R"("value" "asdf")" - R"("value2" "22")" - "}" - "}"; - std::istringstream ss(gdtString); - - Gdt gdt; - GdtReader reader(ss); - REQUIRE(reader.Read(gdt)); - - REQUIRE(gdt.m_version.m_game == "t6"); - REQUIRE(gdt.m_version.m_version == 1337); - - REQUIRE(gdt.m_entries.size() == 2); - - { - const auto& entry = *gdt.m_entries[0]; - REQUIRE(entry.m_name == "test_entry"); - REQUIRE(entry.m_gdf_name == "another_test.gdf"); - REQUIRE(entry.m_parent == nullptr); - REQUIRE(entry.m_properties.size() == 2); - - REQUIRE(entry.m_properties.at("game") == "t6"); - REQUIRE(entry.m_properties.at("version") == "420"); - } - - { - const auto& entry = *gdt.m_entries[1]; - REQUIRE(entry.m_name == "yet_another_entry"); - REQUIRE(entry.m_parent == gdt.m_entries[0].get()); - REQUIRE(entry.m_properties.size() == 3); - - REQUIRE(entry.m_properties.at("name") == "hello"); - REQUIRE(entry.m_properties.at("value") == "asdf"); - REQUIRE(entry.m_properties.at("value2") == "22"); - } - } - - TEST_CASE("Gdt: Ensure can write simple gdt and parse it again", "[gdt]") - { - Gdt gdt; - gdt.m_version.m_game = "whatagame"; - gdt.m_version.m_version = 6969; - - { - auto entry = std::make_unique<GdtEntry>("sickentry", "verycool.gdf"); - entry->m_properties["hello"] = "world"; - entry->m_properties["hi"] = "universe"; - gdt.m_entries.emplace_back(std::move(entry)); - } - - { - auto entry = std::make_unique<GdtEntry>("evencoolerentry", gdt.m_entries[0].get()); - entry->m_properties["nope"] = "xd"; - entry->m_properties["idk"] = "whattotypeanymore"; - gdt.m_entries.emplace_back(std::move(entry)); - } - - std::stringstream ss; - GdtOutputStream::WriteGdt(gdt, ss); - - std::cout << ss.str() << std::endl; - - Gdt gdt2; - GdtReader reader(ss); - REQUIRE(reader.Read(gdt2)); - - REQUIRE(gdt2.m_version.m_game == "whatagame"); - REQUIRE(gdt2.m_version.m_version == 6969); - - REQUIRE(gdt2.m_entries.size() == 2); - - { - const auto& entry = *gdt2.m_entries[0]; - REQUIRE(entry.m_name == "sickentry"); - REQUIRE(entry.m_gdf_name == "verycool.gdf"); - REQUIRE(entry.m_parent == nullptr); - REQUIRE(entry.m_properties.size() == 2); - - REQUIRE(entry.m_properties.at("hello") == "world"); - REQUIRE(entry.m_properties.at("hi") == "universe"); - } - - { - const auto& entry = *gdt2.m_entries[1]; - REQUIRE(entry.m_name == "evencoolerentry"); - REQUIRE(entry.m_parent == gdt2.m_entries[0].get()); - REQUIRE(entry.m_properties.size() == 2); - - REQUIRE(entry.m_properties.at("nope") == "xd"); - REQUIRE(entry.m_properties.at("idk") == "whattotypeanymore"); - } - } - - TEST_CASE("Gdt: Ensure can write gdt with escape values and parse it again", "[gdt]") - { - Gdt gdt; - gdt.m_version.m_game = "whatagame"; - gdt.m_version.m_version = 6969; - - { - auto entry = std::make_unique<GdtEntry>("sickentry", "verycool.gdf"); - entry->m_properties["hello"] = "very\nkewl\\stuff"; - gdt.m_entries.emplace_back(std::move(entry)); - } - - std::stringstream ss; - GdtOutputStream::WriteGdt(gdt, ss); - - std::cout << ss.str() << std::endl; - - Gdt gdt2; - GdtReader reader(ss); - REQUIRE(reader.Read(gdt2)); - - REQUIRE(gdt2.m_version.m_game == "whatagame"); - REQUIRE(gdt2.m_version.m_version == 6969); - - REQUIRE(gdt2.m_entries.size() == 1); - - { - const auto& entry = *gdt2.m_entries[0]; - REQUIRE(entry.m_name == "sickentry"); - REQUIRE(entry.m_gdf_name == "verycool.gdf"); - REQUIRE(entry.m_parent == nullptr); - REQUIRE(entry.m_properties.size() == 1); - - REQUIRE(entry.m_properties.at("hello") == "very\nkewl\\stuff"); - } - } +namespace obj::gdt { +TEST_CASE("Gdt: Ensure can parse simple gdt", "[gdt]") { + std::string gdtString = "{\n" + "\t\"test_entry\" ( \"test.gdf\" )\n" + "\t{\n" + "\t\t\"testkey\" \"testvalue\"\n" + "\t\t\"test2key\" \"test2value\"\n" + "\t}\n" + "}"; + std::istringstream ss(gdtString); + + Gdt gdt; + GdtReader reader(ss); + REQUIRE(reader.Read(gdt)); + + REQUIRE(gdt.m_entries.size() == 1); + + { + const auto &entry = *gdt.m_entries[0]; + REQUIRE(entry.m_name == "test_entry"); + REQUIRE(entry.m_gdf_name == "test.gdf"); + REQUIRE(entry.m_parent == nullptr); + REQUIRE(entry.m_properties.size() == 2); + + REQUIRE(entry.m_properties.at("testkey") == "testvalue"); + REQUIRE(entry.m_properties.at("test2key") == "test2value"); + } } + +TEST_CASE("Gdt: Ensure can parse compact gdt", "[gdt]") { + std::string gdtString = "{" + R"("test_entry"("test.gdf"))" + "{" + R"("testkey""testvalue")" + R"("test2key""test2value")" + "}" + "}"; + std::istringstream ss(gdtString); + + Gdt gdt; + GdtReader reader(ss); + REQUIRE(reader.Read(gdt)); + + REQUIRE(gdt.m_entries.size() == 1); + + { + const auto &entry = *gdt.m_entries[0]; + REQUIRE(entry.m_name == "test_entry"); + REQUIRE(entry.m_gdf_name == "test.gdf"); + REQUIRE(entry.m_parent == nullptr); + REQUIRE(entry.m_properties.size() == 2); + + REQUIRE(entry.m_properties.at("testkey") == "testvalue"); + REQUIRE(entry.m_properties.at("test2key") == "test2value"); + } +} + +TEST_CASE("Gdt: Ensure can parse version section", "[gdt]") { + std::string gdtString = "{" + R"("version" ( "version.gdf" ))" + "{" + R"("game" "t6")" + R"("version" "1337")" + "}" + "}"; + std::istringstream ss(gdtString); + + Gdt gdt; + GdtReader reader(ss); + REQUIRE(reader.Read(gdt)); + + REQUIRE(gdt.m_entries.empty()); + REQUIRE(gdt.m_version.m_game == "t6"); + REQUIRE(gdt.m_version.m_version == 1337); +} + +TEST_CASE("Gdt: Ensure can parse version section and entries", "[gdt]") { + std::string gdtString = "{" + R"("version" ( "version.gdf" ))" + "{" + R"("game" "t6")" + R"("version" "1337")" + "}" + R"("test_entry" ( "another_test.gdf" ))" + "{" + R"("game" "t6")" + R"("version" "420")" + "}" + "}"; + std::istringstream ss(gdtString); + + Gdt gdt; + GdtReader reader(ss); + REQUIRE(reader.Read(gdt)); + + REQUIRE(gdt.m_version.m_game == "t6"); + REQUIRE(gdt.m_version.m_version == 1337); + + REQUIRE(gdt.m_entries.size() == 1); + + { + const auto &entry = *gdt.m_entries[0]; + REQUIRE(entry.m_name == "test_entry"); + REQUIRE(entry.m_gdf_name == "another_test.gdf"); + REQUIRE(entry.m_parent == nullptr); + REQUIRE(entry.m_properties.size() == 2); + + REQUIRE(entry.m_properties.at("game") == "t6"); + REQUIRE(entry.m_properties.at("version") == "420"); + } +} + +TEST_CASE("Gdt: Ensure can parse multiple entries", "[gdt]") { + std::string gdtString = "{" + R"("version" ( "version.gdf" ))" + "{" + R"("game" "t6")" + R"("version" "1337")" + "}" + R"("test_entry" ( "another_test.gdf" ))" + "{" + R"("game" "t6")" + R"("version" "420")" + "}" + R"("yet_another_entry" ( "super_kewl_asset_type.gdf" ))" + "{" + R"("name" "hello")" + R"("value" "asdf")" + R"("value2" "22")" + "}" + R"("final_entry" ( "quite_boring.gdf" ))" + "{" + R"("_HI_" "Hello World")" + "}" + "}"; + std::istringstream ss(gdtString); + + Gdt gdt; + GdtReader reader(ss); + REQUIRE(reader.Read(gdt)); + + REQUIRE(gdt.m_version.m_game == "t6"); + REQUIRE(gdt.m_version.m_version == 1337); + + REQUIRE(gdt.m_entries.size() == 3); + + { + const auto &entry = *gdt.m_entries[0]; + REQUIRE(entry.m_name == "test_entry"); + REQUIRE(entry.m_gdf_name == "another_test.gdf"); + REQUIRE(entry.m_parent == nullptr); + REQUIRE(entry.m_properties.size() == 2); + + REQUIRE(entry.m_properties.at("game") == "t6"); + REQUIRE(entry.m_properties.at("version") == "420"); + } + + { + const auto &entry = *gdt.m_entries[1]; + REQUIRE(entry.m_name == "yet_another_entry"); + REQUIRE(entry.m_gdf_name == "super_kewl_asset_type.gdf"); + REQUIRE(entry.m_parent == nullptr); + REQUIRE(entry.m_properties.size() == 3); + + REQUIRE(entry.m_properties.at("name") == "hello"); + REQUIRE(entry.m_properties.at("value") == "asdf"); + REQUIRE(entry.m_properties.at("value2") == "22"); + } + + { + const auto &entry = *gdt.m_entries[2]; + REQUIRE(entry.m_name == "final_entry"); + REQUIRE(entry.m_gdf_name == "quite_boring.gdf"); + REQUIRE(entry.m_parent == nullptr); + REQUIRE(entry.m_properties.size() == 1); + + REQUIRE(entry.m_properties.at("_HI_") == "Hello World"); + } +} + +TEST_CASE("Gdt: Ensure can parse entries with parent", "[gdt]") { + std::string gdtString = "{" + R"("version" ( "version.gdf" ))" + "{" + R"("game" "t6")" + R"("version" "1337")" + "}" + R"("test_entry" ( "another_test.gdf" ))" + "{" + R"("game" "t6")" + R"("version" "420")" + "}" + R"("yet_another_entry" [ "test_entry" ])" + "{" + R"("name" "hello")" + R"("value" "asdf")" + R"("value2" "22")" + "}" + "}"; + std::istringstream ss(gdtString); + + Gdt gdt; + GdtReader reader(ss); + REQUIRE(reader.Read(gdt)); + + REQUIRE(gdt.m_version.m_game == "t6"); + REQUIRE(gdt.m_version.m_version == 1337); + + REQUIRE(gdt.m_entries.size() == 2); + + { + const auto &entry = *gdt.m_entries[0]; + REQUIRE(entry.m_name == "test_entry"); + REQUIRE(entry.m_gdf_name == "another_test.gdf"); + REQUIRE(entry.m_parent == nullptr); + REQUIRE(entry.m_properties.size() == 2); + + REQUIRE(entry.m_properties.at("game") == "t6"); + REQUIRE(entry.m_properties.at("version") == "420"); + } + + { + const auto &entry = *gdt.m_entries[1]; + REQUIRE(entry.m_name == "yet_another_entry"); + REQUIRE(entry.m_parent == gdt.m_entries[0].get()); + REQUIRE(entry.m_properties.size() == 3); + + REQUIRE(entry.m_properties.at("name") == "hello"); + REQUIRE(entry.m_properties.at("value") == "asdf"); + REQUIRE(entry.m_properties.at("value2") == "22"); + } +} + +TEST_CASE("Gdt: Ensure can write simple gdt and parse it again", "[gdt]") { + Gdt gdt; + gdt.m_version.m_game = "whatagame"; + gdt.m_version.m_version = 6969; + + { + auto entry = std::make_unique<GdtEntry>("sickentry", "verycool.gdf"); + entry->m_properties["hello"] = "world"; + entry->m_properties["hi"] = "universe"; + gdt.m_entries.emplace_back(std::move(entry)); + } + + { + auto entry = std::make_unique<GdtEntry>("evencoolerentry", gdt.m_entries[0].get()); + entry->m_properties["nope"] = "xd"; + entry->m_properties["idk"] = "whattotypeanymore"; + gdt.m_entries.emplace_back(std::move(entry)); + } + + std::stringstream ss; + GdtOutputStream::WriteGdt(gdt, ss); + + std::cout << ss.str() << std::endl; + + Gdt gdt2; + GdtReader reader(ss); + REQUIRE(reader.Read(gdt2)); + + REQUIRE(gdt2.m_version.m_game == "whatagame"); + REQUIRE(gdt2.m_version.m_version == 6969); + + REQUIRE(gdt2.m_entries.size() == 2); + + { + const auto &entry = *gdt2.m_entries[0]; + REQUIRE(entry.m_name == "sickentry"); + REQUIRE(entry.m_gdf_name == "verycool.gdf"); + REQUIRE(entry.m_parent == nullptr); + REQUIRE(entry.m_properties.size() == 2); + + REQUIRE(entry.m_properties.at("hello") == "world"); + REQUIRE(entry.m_properties.at("hi") == "universe"); + } + + { + const auto &entry = *gdt2.m_entries[1]; + REQUIRE(entry.m_name == "evencoolerentry"); + REQUIRE(entry.m_parent == gdt2.m_entries[0].get()); + REQUIRE(entry.m_properties.size() == 2); + + REQUIRE(entry.m_properties.at("nope") == "xd"); + REQUIRE(entry.m_properties.at("idk") == "whattotypeanymore"); + } +} + +TEST_CASE("Gdt: Ensure can write gdt with escape values and parse it again", "[gdt]") { + Gdt gdt; + gdt.m_version.m_game = "whatagame"; + gdt.m_version.m_version = 6969; + + { + auto entry = std::make_unique<GdtEntry>("sickentry", "verycool.gdf"); + entry->m_properties["hello"] = "very\nkewl\\stuff"; + gdt.m_entries.emplace_back(std::move(entry)); + } + + std::stringstream ss; + GdtOutputStream::WriteGdt(gdt, ss); + + std::cout << ss.str() << std::endl; + + Gdt gdt2; + GdtReader reader(ss); + REQUIRE(reader.Read(gdt2)); + + REQUIRE(gdt2.m_version.m_game == "whatagame"); + REQUIRE(gdt2.m_version.m_version == 6969); + + REQUIRE(gdt2.m_entries.size() == 1); + + { + const auto &entry = *gdt2.m_entries[0]; + REQUIRE(entry.m_name == "sickentry"); + REQUIRE(entry.m_gdf_name == "verycool.gdf"); + REQUIRE(entry.m_parent == nullptr); + REQUIRE(entry.m_properties.size() == 1); + + REQUIRE(entry.m_properties.at("hello") == "very\nkewl\\stuff"); + } +} +} // namespace obj::gdt diff --git a/test/ObjLoadingTests/Game/IW4/Menu/MenuParsingIW4IT.cpp b/test/ObjLoadingTests/Game/IW4/Menu/MenuParsingIW4IT.cpp index 493cf5d97..62b8ea27f 100644 --- a/test/ObjLoadingTests/Game/IW4/Menu/MenuParsingIW4IT.cpp +++ b/test/ObjLoadingTests/Game/IW4/Menu/MenuParsingIW4IT.cpp @@ -1,11 +1,11 @@ #include <catch2/catch_test_macros.hpp> -#include <catch2/matchers/catch_matchers_floating_point.hpp> #include <catch2/generators/catch_generators.hpp> +#include <catch2/matchers/catch_matchers_floating_point.hpp> #include <string> -#include "Game/IW4/GameIW4.h" #include "Game/IW4/AssetLoaders/AssetLoaderMenuList.h" +#include "Game/IW4/GameIW4.h" #include "Mock/MockAssetLoadingManager.h" #include "Mock/MockSearchPath.h" #include "Parsing/Menu/MenuFileReader.h" @@ -16,73 +16,54 @@ using namespace IW4; using namespace std::literals; using namespace Catch::Matchers; -namespace test::game::iw4::menu::parsing::it -{ - class MenuParsingItHelper - { - static constexpr const char* DEFAULT_ASSET_NAME = "test.txt"; +namespace test::game::iw4::menu::parsing::it { +class MenuParsingItHelper { + static constexpr const char *DEFAULT_ASSET_NAME = "test.txt"; - Zone m_zone; - MockSearchPath m_search_path; - MockAssetLoadingManager m_manager; - AssetLoaderMenuList m_asset_loader; + Zone m_zone; + MockSearchPath m_search_path; + MockAssetLoadingManager m_manager; + AssetLoaderMenuList m_asset_loader; - public: - MenuParsingItHelper() - : m_zone("MockZone", 0, &g_GameIW4), - m_manager(&m_zone, &m_search_path) - { - } +public: + MenuParsingItHelper() : m_zone("MockZone", 0, &g_GameIW4), m_manager(&m_zone, &m_search_path) {} - void AddFile(std::string fileName, std::string data) - { - m_search_path.AddFileData(std::move(fileName), std::move(data)); - } + void AddFile(std::string fileName, std::string data) { m_search_path.AddFileData(std::move(fileName), std::move(data)); } - void AddFile(std::string data) - { - AddFile(DEFAULT_ASSET_NAME, std::move(data)); - } + void AddFile(std::string data) { AddFile(DEFAULT_ASSET_NAME, std::move(data)); } - Material* AddMaterial(const std::string& name) - { - auto* material = m_zone.GetMemory()->Create<Material>(); - material->info.name = m_zone.GetMemory()->Dup(name.c_str()); + Material *AddMaterial(const std::string &name) { + auto *material = m_zone.GetMemory()->Create<Material>(); + material->info.name = m_zone.GetMemory()->Dup(name.c_str()); - m_manager.MockAddAvailableDependency(ASSET_TYPE_MATERIAL, name, material); + m_manager.MockAddAvailableDependency(ASSET_TYPE_MATERIAL, name, material); - return material; - } + return material; + } - bool RunIntegrationTest() - { - return m_asset_loader.LoadFromRaw(DEFAULT_ASSET_NAME, &m_search_path, m_zone.GetMemory(), &m_manager, &m_zone); - } + bool RunIntegrationTest() { return m_asset_loader.LoadFromRaw(DEFAULT_ASSET_NAME, &m_search_path, m_zone.GetMemory(), &m_manager, &m_zone); } - MenuList* GetMenuListAsset() - { - const auto addedAsset = m_manager.MockGetAddedAsset(DEFAULT_ASSET_NAME); - REQUIRE(addedAsset); - REQUIRE(addedAsset->m_type == ASSET_TYPE_MENULIST); + MenuList *GetMenuListAsset() { + const auto addedAsset = m_manager.MockGetAddedAsset(DEFAULT_ASSET_NAME); + REQUIRE(addedAsset); + REQUIRE(addedAsset->m_type == ASSET_TYPE_MENULIST); - return static_cast<MenuList*>(addedAsset->m_ptr); - } + return static_cast<MenuList *>(addedAsset->m_ptr); + } - menuDef_t* GetMenuAsset(const std::string& menuName) - { - const auto addedAsset = m_manager.MockGetAddedAsset(menuName); - REQUIRE(addedAsset); - REQUIRE(addedAsset->m_type == ASSET_TYPE_MENU); + menuDef_t *GetMenuAsset(const std::string &menuName) { + const auto addedAsset = m_manager.MockGetAddedAsset(menuName); + REQUIRE(addedAsset); + REQUIRE(addedAsset->m_type == ASSET_TYPE_MENU); - return static_cast<menuDef_t*>(addedAsset->m_ptr); - } - }; + return static_cast<menuDef_t *>(addedAsset->m_ptr); + } +}; - TEST_CASE("MenuParsingIW4IT: Can convert simple menu without properties", "[parsing][converting][menu][it]") - { - MenuParsingItHelper helper; +TEST_CASE("MenuParsingIW4IT: Can convert simple menu without properties", "[parsing][converting][menu][it]") { + MenuParsingItHelper helper; - helper.AddFile(R"testmenu( + helper.AddFile(R"testmenu( { menuDef { @@ -91,27 +72,26 @@ namespace test::game::iw4::menu::parsing::it } )testmenu"); - const auto result = helper.RunIntegrationTest(); - REQUIRE(result); + const auto result = helper.RunIntegrationTest(); + REQUIRE(result); - const auto* menuList = helper.GetMenuListAsset(); - const auto* menu = helper.GetMenuAsset("Hello"); + const auto *menuList = helper.GetMenuListAsset(); + const auto *menu = helper.GetMenuAsset("Hello"); - REQUIRE(menuList->menuCount == 1); - REQUIRE(menuList->menus); + REQUIRE(menuList->menuCount == 1); + REQUIRE(menuList->menus); - REQUIRE(menuList->menus[0] == menu); + REQUIRE(menuList->menus[0] == menu); - REQUIRE(menu->window.name == "Hello"s); - REQUIRE(menu->itemCount == 0); - REQUIRE(menu->items == nullptr); - } + REQUIRE(menu->window.name == "Hello"s); + REQUIRE(menu->itemCount == 0); + REQUIRE(menu->items == nullptr); +} - TEST_CASE("MenuParsingIW4IT: Can convert simple menu", "[parsing][converting][menu][it]") - { - MenuParsingItHelper helper; +TEST_CASE("MenuParsingIW4IT: Can convert simple menu", "[parsing][converting][menu][it]") { + MenuParsingItHelper helper; - helper.AddFile(R"testmenu( + helper.AddFile(R"testmenu( #define COOL_STYLE 5 #define VISIBILITY_ENABLED 1 #define HIDE_STUPID_ELEMENTS 0 @@ -170,144 +150,141 @@ namespace test::game::iw4::menu::parsing::it } )testmenu"); - const auto* funnyDogMaterial = helper.AddMaterial("funny_dog.png"); - - const auto result = helper.RunIntegrationTest(); - REQUIRE(result); - - const auto* menuList = helper.GetMenuListAsset(); - const auto* menu = helper.GetMenuAsset("Bla"); - - REQUIRE(menuList->menuCount == 1); - REQUIRE(menuList->menus); - - REQUIRE(menuList->menus[0] == menu); - - REQUIRE(menu->window.name == "Bla"s); - REQUIRE(menu->fullScreen > 0); - REQUIRE(menu->window.staticFlags & WINDOW_FLAG_SCREEN_SPACE); - REQUIRE(menu->window.staticFlags & WINDOW_FLAG_DECORATION); - REQUIRE_THAT(menu->window.rect.x, WithinRel(420.0f)); - REQUIRE_THAT(menu->window.rect.y, WithinRel(1337.0f)); - REQUIRE_THAT(menu->window.rect.w, WithinRel(12.0f)); - REQUIRE_THAT(menu->window.rect.h, WithinRel(64.0f)); - REQUIRE(menu->window.rect.horzAlign == 1); - REQUIRE(menu->window.rect.vertAlign == 2); - REQUIRE(menu->window.style == 5); - - REQUIRE(menu->visibleExp == nullptr); - REQUIRE(menu->window.dynamicFlags[0] & WINDOW_FLAG_VISIBLE); - - REQUIRE(menu->onOpen != nullptr); - REQUIRE(menu->onOpen->eventHandlerCount == 1); - REQUIRE(menu->onOpen->eventHandlers[0]->eventType == EventType::EVENT_UNCONDITIONAL); - REQUIRE(menu->onOpen->eventHandlers[0]->eventData.unconditionalScript != nullptr); - REQUIRE(menu->onOpen->eventHandlers[0]->eventData.unconditionalScript == R"("focusFirst" ; "play" "fart_sound" ; "exec" "wait 1; set r_fullbright 1" ; )"s); - - REQUIRE(menu->onClose != nullptr); - REQUIRE(menu->onClose->eventHandlerCount == 4); - REQUIRE(menu->onClose->eventHandlers[0]->eventType == EventType::EVENT_UNCONDITIONAL); - REQUIRE(menu->onClose->eventHandlers[0]->eventData.unconditionalScript != nullptr); - REQUIRE(menu->onClose->eventHandlers[0]->eventData.unconditionalScript == R"("setBackground" "cute_cat.jpg" ; )"s); - REQUIRE(menu->onClose->eventHandlers[1]->eventType == EventType::EVENT_IF); - REQUIRE(menu->onClose->eventHandlers[1]->eventData.conditionalScript != nullptr); - REQUIRE(menu->onClose->eventHandlers[1]->eventData.conditionalScript->eventExpression != nullptr); - REQUIRE(menu->onClose->eventHandlers[1]->eventData.conditionalScript->eventExpression->numEntries == 5); - REQUIRE(menu->onClose->eventHandlers[1]->eventData.conditionalScript->eventExpression->entries[0].type == expressionEntryType::EET_OPERATOR); - REQUIRE(menu->onClose->eventHandlers[1]->eventData.conditionalScript->eventExpression->entries[0].data.op == 102); // anynewmappacks - REQUIRE(menu->onClose->eventHandlers[1]->eventData.conditionalScript->eventExpression->entries[1].type == expressionEntryType::EET_OPERATOR); - REQUIRE(menu->onClose->eventHandlers[1]->eventData.conditionalScript->eventExpression->entries[1].data.op == OP_RIGHTPAREN); - REQUIRE(menu->onClose->eventHandlers[1]->eventData.conditionalScript->eventExpression->entries[2].type == expressionEntryType::EET_OPERATOR); - REQUIRE(menu->onClose->eventHandlers[1]->eventData.conditionalScript->eventExpression->entries[2].data.op == OP_AND); - REQUIRE(menu->onClose->eventHandlers[1]->eventData.conditionalScript->eventExpression->entries[3].type == expressionEntryType::EET_OPERATOR); - REQUIRE(menu->onClose->eventHandlers[1]->eventData.conditionalScript->eventExpression->entries[3].data.op == 118); // isreloading - REQUIRE(menu->onClose->eventHandlers[1]->eventData.conditionalScript->eventExpression->entries[4].type == expressionEntryType::EET_OPERATOR); - REQUIRE(menu->onClose->eventHandlers[1]->eventData.conditionalScript->eventExpression->entries[4].data.op == OP_RIGHTPAREN); - REQUIRE(menu->onClose->eventHandlers[1]->eventData.conditionalScript->eventHandlerSet != nullptr); - REQUIRE(menu->onClose->eventHandlers[1]->eventData.conditionalScript->eventHandlerSet->eventHandlerCount == 1); - REQUIRE(menu->onClose->eventHandlers[1]->eventData.conditionalScript->eventHandlerSet->eventHandlers != nullptr); - REQUIRE(menu->onClose->eventHandlers[1]->eventData.conditionalScript->eventHandlerSet->eventHandlers[0] != nullptr); - REQUIRE(menu->onClose->eventHandlers[1]->eventData.conditionalScript->eventHandlerSet->eventHandlers[0]->eventType == EventType::EVENT_UNCONDITIONAL); - REQUIRE(menu->onClose->eventHandlers[1]->eventData.conditionalScript->eventHandlerSet->eventHandlers[0]->eventData.unconditionalScript == R"("exec" "quit" ; )"s); - REQUIRE(menu->onClose->eventHandlers[2]->eventType == EventType::EVENT_ELSE); - REQUIRE(menu->onClose->eventHandlers[2]->eventData.elseScript != nullptr); - REQUIRE(menu->onClose->eventHandlers[2]->eventData.elseScript->eventHandlerCount == 1); - REQUIRE(menu->onClose->eventHandlers[2]->eventData.elseScript->eventHandlers != nullptr); - REQUIRE(menu->onClose->eventHandlers[2]->eventData.elseScript->eventHandlers[0] != nullptr); - REQUIRE(menu->onClose->eventHandlers[2]->eventData.elseScript->eventHandlers[0]->eventType == EventType::EVENT_UNCONDITIONAL); - REQUIRE(menu->onClose->eventHandlers[2]->eventData.elseScript->eventHandlers[0]->eventData.unconditionalScript == R"("uiScript" "startSingleplayer" ; )"s); - REQUIRE(menu->onClose->eventHandlers[3]->eventType == EventType::EVENT_UNCONDITIONAL); - REQUIRE(menu->onClose->eventHandlers[3]->eventData.unconditionalScript != nullptr); - REQUIRE(menu->onClose->eventHandlers[3]->eventData.unconditionalScript == R"("setGameMode" "dm" ; )"s); - - REQUIRE(menu->onCloseRequest != nullptr); - REQUIRE(menu->onCloseRequest->eventHandlerCount == 1); - REQUIRE(menu->onCloseRequest->eventHandlers[0]->eventType == EventType::EVENT_UNCONDITIONAL); - REQUIRE(menu->onCloseRequest->eventHandlers[0]->eventData.unconditionalScript != nullptr); - REQUIRE(menu->onCloseRequest->eventHandlers[0]->eventData.unconditionalScript == R"("play" "nope" ; )"s); - - REQUIRE(menu->onESC != nullptr); - REQUIRE(menu->onESC->eventHandlerCount == 1); - REQUIRE(menu->onESC->eventHandlers[0]->eventType == EventType::EVENT_UNCONDITIONAL); - REQUIRE(menu->onESC->eventHandlers[0]->eventData.unconditionalScript != nullptr); - REQUIRE(menu->onESC->eventHandlers[0]->eventData.unconditionalScript == R"("setColor" "backColor" "1" "0.5" "0.1" "1" ; )"s); - - REQUIRE(menu->window.border == 1); - REQUIRE_THAT(menu->window.borderSize, WithinRel(1.25f)); - REQUIRE_THAT(menu->window.borderSize, WithinRel(1.25)); - REQUIRE_THAT(menu->window.backColor[0], WithinRel(1.0f)); - REQUIRE_THAT(menu->window.backColor[1], WithinRel(0.8f)); - REQUIRE_THAT(menu->window.backColor[2], WithinRel(0.4f)); - REQUIRE_THAT(menu->window.backColor[3], WithinRel(0.95f)); - REQUIRE_THAT(menu->window.foreColor[0], WithinRel(0.7f)); - REQUIRE_THAT(menu->window.foreColor[1], WithinRel(0.0f)); - REQUIRE_THAT(menu->window.foreColor[2], WithinRel(0.0f)); - REQUIRE_THAT(menu->window.foreColor[3], WithinRel(0.0f)); - REQUIRE(menu->window.background == funnyDogMaterial); - - REQUIRE(menu->onKey != nullptr); - REQUIRE(menu->onKey->next != nullptr); - REQUIRE(menu->onKey->next->next == nullptr); - - const auto keyHandler1 = menu->onKey; - const auto keyHandler2 = menu->onKey->next; - - ItemKeyHandler* qKeyHandler; - ItemKeyHandler* leetKeyHandler; - if (keyHandler1->key == 'q') - { - qKeyHandler = keyHandler1; - leetKeyHandler = keyHandler2; - } - else - { - leetKeyHandler = keyHandler1; - qKeyHandler = keyHandler2; - } - - REQUIRE(qKeyHandler->key == 'q'); - REQUIRE(qKeyHandler->action->eventHandlerCount == 1); - REQUIRE(qKeyHandler->action->eventHandlers != nullptr); - REQUIRE(qKeyHandler->action->eventHandlers[0] != nullptr); - REQUIRE(qKeyHandler->action->eventHandlers[0]->eventType == EVENT_UNCONDITIONAL); - REQUIRE(qKeyHandler->action->eventHandlers[0]->eventData.unconditionalScript == R"("exec" "quit" ; )"s); - - REQUIRE(leetKeyHandler->key == 1337); - REQUIRE(leetKeyHandler->action->eventHandlerCount == 1); - REQUIRE(leetKeyHandler->action->eventHandlers != nullptr); - REQUIRE(leetKeyHandler->action->eventHandlers[0] != nullptr); - REQUIRE(leetKeyHandler->action->eventHandlers[0]->eventType == EVENT_UNCONDITIONAL); - REQUIRE(leetKeyHandler->action->eventHandlers[0]->eventData.unconditionalScript == R"("exec" "vid_restart" ; )"s); - - REQUIRE(menu->itemCount == 0); - REQUIRE(menu->items == nullptr); - } + const auto *funnyDogMaterial = helper.AddMaterial("funny_dog.png"); + + const auto result = helper.RunIntegrationTest(); + REQUIRE(result); + + const auto *menuList = helper.GetMenuListAsset(); + const auto *menu = helper.GetMenuAsset("Bla"); + + REQUIRE(menuList->menuCount == 1); + REQUIRE(menuList->menus); + + REQUIRE(menuList->menus[0] == menu); + + REQUIRE(menu->window.name == "Bla"s); + REQUIRE(menu->fullScreen > 0); + REQUIRE(menu->window.staticFlags & WINDOW_FLAG_SCREEN_SPACE); + REQUIRE(menu->window.staticFlags & WINDOW_FLAG_DECORATION); + REQUIRE_THAT(menu->window.rect.x, WithinRel(420.0f)); + REQUIRE_THAT(menu->window.rect.y, WithinRel(1337.0f)); + REQUIRE_THAT(menu->window.rect.w, WithinRel(12.0f)); + REQUIRE_THAT(menu->window.rect.h, WithinRel(64.0f)); + REQUIRE(menu->window.rect.horzAlign == 1); + REQUIRE(menu->window.rect.vertAlign == 2); + REQUIRE(menu->window.style == 5); + + REQUIRE(menu->visibleExp == nullptr); + REQUIRE(menu->window.dynamicFlags[0] & WINDOW_FLAG_VISIBLE); + + REQUIRE(menu->onOpen != nullptr); + REQUIRE(menu->onOpen->eventHandlerCount == 1); + REQUIRE(menu->onOpen->eventHandlers[0]->eventType == EventType::EVENT_UNCONDITIONAL); + REQUIRE(menu->onOpen->eventHandlers[0]->eventData.unconditionalScript != nullptr); + REQUIRE(menu->onOpen->eventHandlers[0]->eventData.unconditionalScript == R"("focusFirst" ; "play" "fart_sound" ; "exec" "wait 1; set r_fullbright 1" ; )"s); + + REQUIRE(menu->onClose != nullptr); + REQUIRE(menu->onClose->eventHandlerCount == 4); + REQUIRE(menu->onClose->eventHandlers[0]->eventType == EventType::EVENT_UNCONDITIONAL); + REQUIRE(menu->onClose->eventHandlers[0]->eventData.unconditionalScript != nullptr); + REQUIRE(menu->onClose->eventHandlers[0]->eventData.unconditionalScript == R"("setBackground" "cute_cat.jpg" ; )"s); + REQUIRE(menu->onClose->eventHandlers[1]->eventType == EventType::EVENT_IF); + REQUIRE(menu->onClose->eventHandlers[1]->eventData.conditionalScript != nullptr); + REQUIRE(menu->onClose->eventHandlers[1]->eventData.conditionalScript->eventExpression != nullptr); + REQUIRE(menu->onClose->eventHandlers[1]->eventData.conditionalScript->eventExpression->numEntries == 5); + REQUIRE(menu->onClose->eventHandlers[1]->eventData.conditionalScript->eventExpression->entries[0].type == expressionEntryType::EET_OPERATOR); + REQUIRE(menu->onClose->eventHandlers[1]->eventData.conditionalScript->eventExpression->entries[0].data.op == 102); // anynewmappacks + REQUIRE(menu->onClose->eventHandlers[1]->eventData.conditionalScript->eventExpression->entries[1].type == expressionEntryType::EET_OPERATOR); + REQUIRE(menu->onClose->eventHandlers[1]->eventData.conditionalScript->eventExpression->entries[1].data.op == OP_RIGHTPAREN); + REQUIRE(menu->onClose->eventHandlers[1]->eventData.conditionalScript->eventExpression->entries[2].type == expressionEntryType::EET_OPERATOR); + REQUIRE(menu->onClose->eventHandlers[1]->eventData.conditionalScript->eventExpression->entries[2].data.op == OP_AND); + REQUIRE(menu->onClose->eventHandlers[1]->eventData.conditionalScript->eventExpression->entries[3].type == expressionEntryType::EET_OPERATOR); + REQUIRE(menu->onClose->eventHandlers[1]->eventData.conditionalScript->eventExpression->entries[3].data.op == 118); // isreloading + REQUIRE(menu->onClose->eventHandlers[1]->eventData.conditionalScript->eventExpression->entries[4].type == expressionEntryType::EET_OPERATOR); + REQUIRE(menu->onClose->eventHandlers[1]->eventData.conditionalScript->eventExpression->entries[4].data.op == OP_RIGHTPAREN); + REQUIRE(menu->onClose->eventHandlers[1]->eventData.conditionalScript->eventHandlerSet != nullptr); + REQUIRE(menu->onClose->eventHandlers[1]->eventData.conditionalScript->eventHandlerSet->eventHandlerCount == 1); + REQUIRE(menu->onClose->eventHandlers[1]->eventData.conditionalScript->eventHandlerSet->eventHandlers != nullptr); + REQUIRE(menu->onClose->eventHandlers[1]->eventData.conditionalScript->eventHandlerSet->eventHandlers[0] != nullptr); + REQUIRE(menu->onClose->eventHandlers[1]->eventData.conditionalScript->eventHandlerSet->eventHandlers[0]->eventType == EventType::EVENT_UNCONDITIONAL); + REQUIRE(menu->onClose->eventHandlers[1]->eventData.conditionalScript->eventHandlerSet->eventHandlers[0]->eventData.unconditionalScript == + R"("exec" "quit" ; )"s); + REQUIRE(menu->onClose->eventHandlers[2]->eventType == EventType::EVENT_ELSE); + REQUIRE(menu->onClose->eventHandlers[2]->eventData.elseScript != nullptr); + REQUIRE(menu->onClose->eventHandlers[2]->eventData.elseScript->eventHandlerCount == 1); + REQUIRE(menu->onClose->eventHandlers[2]->eventData.elseScript->eventHandlers != nullptr); + REQUIRE(menu->onClose->eventHandlers[2]->eventData.elseScript->eventHandlers[0] != nullptr); + REQUIRE(menu->onClose->eventHandlers[2]->eventData.elseScript->eventHandlers[0]->eventType == EventType::EVENT_UNCONDITIONAL); + REQUIRE(menu->onClose->eventHandlers[2]->eventData.elseScript->eventHandlers[0]->eventData.unconditionalScript == R"("uiScript" "startSingleplayer" ; )"s); + REQUIRE(menu->onClose->eventHandlers[3]->eventType == EventType::EVENT_UNCONDITIONAL); + REQUIRE(menu->onClose->eventHandlers[3]->eventData.unconditionalScript != nullptr); + REQUIRE(menu->onClose->eventHandlers[3]->eventData.unconditionalScript == R"("setGameMode" "dm" ; )"s); + + REQUIRE(menu->onCloseRequest != nullptr); + REQUIRE(menu->onCloseRequest->eventHandlerCount == 1); + REQUIRE(menu->onCloseRequest->eventHandlers[0]->eventType == EventType::EVENT_UNCONDITIONAL); + REQUIRE(menu->onCloseRequest->eventHandlers[0]->eventData.unconditionalScript != nullptr); + REQUIRE(menu->onCloseRequest->eventHandlers[0]->eventData.unconditionalScript == R"("play" "nope" ; )"s); + + REQUIRE(menu->onESC != nullptr); + REQUIRE(menu->onESC->eventHandlerCount == 1); + REQUIRE(menu->onESC->eventHandlers[0]->eventType == EventType::EVENT_UNCONDITIONAL); + REQUIRE(menu->onESC->eventHandlers[0]->eventData.unconditionalScript != nullptr); + REQUIRE(menu->onESC->eventHandlers[0]->eventData.unconditionalScript == R"("setColor" "backColor" "1" "0.5" "0.1" "1" ; )"s); + + REQUIRE(menu->window.border == 1); + REQUIRE_THAT(menu->window.borderSize, WithinRel(1.25f)); + REQUIRE_THAT(menu->window.borderSize, WithinRel(1.25)); + REQUIRE_THAT(menu->window.backColor[0], WithinRel(1.0f)); + REQUIRE_THAT(menu->window.backColor[1], WithinRel(0.8f)); + REQUIRE_THAT(menu->window.backColor[2], WithinRel(0.4f)); + REQUIRE_THAT(menu->window.backColor[3], WithinRel(0.95f)); + REQUIRE_THAT(menu->window.foreColor[0], WithinRel(0.7f)); + REQUIRE_THAT(menu->window.foreColor[1], WithinRel(0.0f)); + REQUIRE_THAT(menu->window.foreColor[2], WithinRel(0.0f)); + REQUIRE_THAT(menu->window.foreColor[3], WithinRel(0.0f)); + REQUIRE(menu->window.background == funnyDogMaterial); + + REQUIRE(menu->onKey != nullptr); + REQUIRE(menu->onKey->next != nullptr); + REQUIRE(menu->onKey->next->next == nullptr); + + const auto keyHandler1 = menu->onKey; + const auto keyHandler2 = menu->onKey->next; + + ItemKeyHandler *qKeyHandler; + ItemKeyHandler *leetKeyHandler; + if (keyHandler1->key == 'q') { + qKeyHandler = keyHandler1; + leetKeyHandler = keyHandler2; + } else { + leetKeyHandler = keyHandler1; + qKeyHandler = keyHandler2; + } + + REQUIRE(qKeyHandler->key == 'q'); + REQUIRE(qKeyHandler->action->eventHandlerCount == 1); + REQUIRE(qKeyHandler->action->eventHandlers != nullptr); + REQUIRE(qKeyHandler->action->eventHandlers[0] != nullptr); + REQUIRE(qKeyHandler->action->eventHandlers[0]->eventType == EVENT_UNCONDITIONAL); + REQUIRE(qKeyHandler->action->eventHandlers[0]->eventData.unconditionalScript == R"("exec" "quit" ; )"s); + + REQUIRE(leetKeyHandler->key == 1337); + REQUIRE(leetKeyHandler->action->eventHandlerCount == 1); + REQUIRE(leetKeyHandler->action->eventHandlers != nullptr); + REQUIRE(leetKeyHandler->action->eventHandlers[0] != nullptr); + REQUIRE(leetKeyHandler->action->eventHandlers[0]->eventType == EVENT_UNCONDITIONAL); + REQUIRE(leetKeyHandler->action->eventHandlers[0]->eventData.unconditionalScript == R"("exec" "vid_restart" ; )"s); + + REQUIRE(menu->itemCount == 0); + REQUIRE(menu->items == nullptr); +} - TEST_CASE("MenuParsingIW4IT: Can specify event handler multiple times", "[parsing][converting][menu][it]") - { - MenuParsingItHelper helper; +TEST_CASE("MenuParsingIW4IT: Can specify event handler multiple times", "[parsing][converting][menu][it]") { + MenuParsingItHelper helper; - helper.AddFile(R"testmenu( + helper.AddFile(R"testmenu( { menuDef { @@ -340,45 +317,44 @@ namespace test::game::iw4::menu::parsing::it } )testmenu"); - const auto result = helper.RunIntegrationTest(); - REQUIRE(result); - - const auto* menuList = helper.GetMenuListAsset(); - const auto* menu = helper.GetMenuAsset("Blab"); - - REQUIRE(menuList->menuCount == 1); - REQUIRE(menuList->menus); - - REQUIRE(menuList->menus[0] == menu); - - REQUIRE(menu->window.name == "Blab"s); - - REQUIRE(menu->onOpen != nullptr); - REQUIRE(menu->onOpen->eventHandlerCount == 3); - REQUIRE(menu->onOpen->eventHandlers[0]->eventType == EventType::EVENT_UNCONDITIONAL); - REQUIRE(menu->onOpen->eventHandlers[0]->eventData.unconditionalScript != nullptr); - REQUIRE(menu->onOpen->eventHandlers[0]->eventData.unconditionalScript == R"("focusFirst" ; )"s); - REQUIRE(menu->onOpen->eventHandlers[1]->eventType == EventType::EVENT_UNCONDITIONAL); - REQUIRE(menu->onOpen->eventHandlers[1]->eventData.unconditionalScript != nullptr); - REQUIRE(menu->onOpen->eventHandlers[1]->eventData.unconditionalScript == R"("play" "fart_sound" ; )"s); - REQUIRE(menu->onOpen->eventHandlers[2]->eventType == EventType::EVENT_UNCONDITIONAL); - REQUIRE(menu->onOpen->eventHandlers[2]->eventData.unconditionalScript != nullptr); - REQUIRE(menu->onOpen->eventHandlers[2]->eventData.unconditionalScript == R"("exec" "wait 1; set r_fullbright 1" ; )"s); - - - REQUIRE(menu->itemCount == 1); - REQUIRE(menu->items != nullptr); - - const auto* item = menu->items[0]; - REQUIRE(item != nullptr); - - REQUIRE(item->action != nullptr); - REQUIRE(item->action->eventHandlerCount == 2); - REQUIRE(item->action->eventHandlers[0]->eventType == EventType::EVENT_UNCONDITIONAL); - REQUIRE(item->action->eventHandlers[0]->eventData.unconditionalScript != nullptr); - REQUIRE(item->action->eventHandlers[0]->eventData.unconditionalScript == R"("play" "lmfao" ; )"s); - REQUIRE(item->action->eventHandlers[1]->eventType == EventType::EVENT_UNCONDITIONAL); - REQUIRE(item->action->eventHandlers[1]->eventData.unconditionalScript != nullptr); - REQUIRE(item->action->eventHandlers[1]->eventData.unconditionalScript == R"("play" "lol" ; )"s); - } + const auto result = helper.RunIntegrationTest(); + REQUIRE(result); + + const auto *menuList = helper.GetMenuListAsset(); + const auto *menu = helper.GetMenuAsset("Blab"); + + REQUIRE(menuList->menuCount == 1); + REQUIRE(menuList->menus); + + REQUIRE(menuList->menus[0] == menu); + + REQUIRE(menu->window.name == "Blab"s); + + REQUIRE(menu->onOpen != nullptr); + REQUIRE(menu->onOpen->eventHandlerCount == 3); + REQUIRE(menu->onOpen->eventHandlers[0]->eventType == EventType::EVENT_UNCONDITIONAL); + REQUIRE(menu->onOpen->eventHandlers[0]->eventData.unconditionalScript != nullptr); + REQUIRE(menu->onOpen->eventHandlers[0]->eventData.unconditionalScript == R"("focusFirst" ; )"s); + REQUIRE(menu->onOpen->eventHandlers[1]->eventType == EventType::EVENT_UNCONDITIONAL); + REQUIRE(menu->onOpen->eventHandlers[1]->eventData.unconditionalScript != nullptr); + REQUIRE(menu->onOpen->eventHandlers[1]->eventData.unconditionalScript == R"("play" "fart_sound" ; )"s); + REQUIRE(menu->onOpen->eventHandlers[2]->eventType == EventType::EVENT_UNCONDITIONAL); + REQUIRE(menu->onOpen->eventHandlers[2]->eventData.unconditionalScript != nullptr); + REQUIRE(menu->onOpen->eventHandlers[2]->eventData.unconditionalScript == R"("exec" "wait 1; set r_fullbright 1" ; )"s); + + REQUIRE(menu->itemCount == 1); + REQUIRE(menu->items != nullptr); + + const auto *item = menu->items[0]; + REQUIRE(item != nullptr); + + REQUIRE(item->action != nullptr); + REQUIRE(item->action->eventHandlerCount == 2); + REQUIRE(item->action->eventHandlers[0]->eventType == EventType::EVENT_UNCONDITIONAL); + REQUIRE(item->action->eventHandlers[0]->eventData.unconditionalScript != nullptr); + REQUIRE(item->action->eventHandlers[0]->eventData.unconditionalScript == R"("play" "lmfao" ; )"s); + REQUIRE(item->action->eventHandlers[1]->eventType == EventType::EVENT_UNCONDITIONAL); + REQUIRE(item->action->eventHandlers[1]->eventData.unconditionalScript != nullptr); + REQUIRE(item->action->eventHandlers[1]->eventData.unconditionalScript == R"("play" "lol" ; )"s); } +} // namespace test::game::iw4::menu::parsing::it diff --git a/test/ObjLoadingTests/Mock/MockAssetLoadingManager.cpp b/test/ObjLoadingTests/Mock/MockAssetLoadingManager.cpp index 20c72373e..60207a17d 100644 --- a/test/ObjLoadingTests/Mock/MockAssetLoadingManager.cpp +++ b/test/ObjLoadingTests/Mock/MockAssetLoadingManager.cpp @@ -1,56 +1,44 @@ #include "MockAssetLoadingManager.h" -MockAssetLoadingManager::MockAssetLoadingManager(Zone* zone, ISearchPath* searchPath) - : m_zone(zone), - m_mock_gdt(std::make_unique<Gdt>()), - m_context(std::make_unique<AssetLoadingContext>(zone, searchPath, std::vector({m_mock_gdt.get()}))) -{ -} +MockAssetLoadingManager::MockAssetLoadingManager(Zone *zone, ISearchPath *searchPath) + : m_zone(zone), m_mock_gdt(std::make_unique<Gdt>()), m_context(std::make_unique<AssetLoadingContext>(zone, searchPath, std::vector({m_mock_gdt.get()}))) {} -AssetLoadingContext* MockAssetLoadingManager::GetAssetLoadingContext() const -{ - return m_context.get(); -} +AssetLoadingContext *MockAssetLoadingManager::GetAssetLoadingContext() const { return m_context.get(); } -XAssetInfoGeneric* MockAssetLoadingManager::AddAsset(const asset_type_t assetType, const std::string& assetName, void* asset, std::vector<XAssetInfoGeneric*> dependencies, - std::vector<scr_string_t> usedScriptStrings) -{ - XAssetInfoGeneric assetInfoObj{assetType, assetName, m_zone, std::move(dependencies), std::move(usedScriptStrings), asset}; - auto assetInfo = std::make_unique<XAssetInfoGeneric>(std::move(assetInfoObj)); - const auto assetInfoPtr = assetInfo.get(); - m_added_assets.emplace(std::make_pair(assetInfo->m_name, std::move(assetInfo))); +XAssetInfoGeneric *MockAssetLoadingManager::AddAsset(const asset_type_t assetType, const std::string &assetName, void *asset, + std::vector<XAssetInfoGeneric *> dependencies, std::vector<scr_string_t> usedScriptStrings) { + XAssetInfoGeneric assetInfoObj{assetType, assetName, m_zone, std::move(dependencies), std::move(usedScriptStrings), asset}; + auto assetInfo = std::make_unique<XAssetInfoGeneric>(std::move(assetInfoObj)); + const auto assetInfoPtr = assetInfo.get(); + m_added_assets.emplace(std::make_pair(assetInfo->m_name, std::move(assetInfo))); - return assetInfoPtr; + return assetInfoPtr; } -XAssetInfoGeneric* MockAssetLoadingManager::LoadDependency(const asset_type_t assetType, const std::string& assetName) -{ - auto foundDependencies = m_available_dependencies.find(assetName); +XAssetInfoGeneric *MockAssetLoadingManager::LoadDependency(const asset_type_t assetType, const std::string &assetName) { + auto foundDependencies = m_available_dependencies.find(assetName); - while (foundDependencies != m_available_dependencies.end()) - { - if (foundDependencies->second->m_type == assetType) - return foundDependencies->second.get(); + while (foundDependencies != m_available_dependencies.end()) { + if (foundDependencies->second->m_type == assetType) + return foundDependencies->second.get(); - ++foundDependencies; - } + ++foundDependencies; + } - return nullptr; + return nullptr; } -void MockAssetLoadingManager::MockAddAvailableDependency(const asset_type_t assetType, std::string assetName, void* asset) -{ - XAssetInfoGeneric assetInfoObj{assetType, std::move(assetName), m_zone, std::vector<XAssetInfoGeneric*>(), std::vector<scr_string_t>(), asset}; - auto assetInfo = std::make_unique<XAssetInfoGeneric>(std::move(assetInfoObj)); - m_available_dependencies.emplace(std::make_pair(assetInfo->m_name, std::move(assetInfo))); +void MockAssetLoadingManager::MockAddAvailableDependency(const asset_type_t assetType, std::string assetName, void *asset) { + XAssetInfoGeneric assetInfoObj{assetType, std::move(assetName), m_zone, std::vector<XAssetInfoGeneric *>(), std::vector<scr_string_t>(), asset}; + auto assetInfo = std::make_unique<XAssetInfoGeneric>(std::move(assetInfoObj)); + m_available_dependencies.emplace(std::make_pair(assetInfo->m_name, std::move(assetInfo))); } -XAssetInfoGeneric* MockAssetLoadingManager::MockGetAddedAsset(const std::string& assetName) -{ - const auto foundAsset = m_added_assets.find(assetName); +XAssetInfoGeneric *MockAssetLoadingManager::MockGetAddedAsset(const std::string &assetName) { + const auto foundAsset = m_added_assets.find(assetName); - if (foundAsset != m_added_assets.end()) - return foundAsset->second.get(); + if (foundAsset != m_added_assets.end()) + return foundAsset->second.get(); - return nullptr; + return nullptr; } diff --git a/test/ObjLoadingTests/Mock/MockAssetLoadingManager.h b/test/ObjLoadingTests/Mock/MockAssetLoadingManager.h index a0867169a..bb5080557 100644 --- a/test/ObjLoadingTests/Mock/MockAssetLoadingManager.h +++ b/test/ObjLoadingTests/Mock/MockAssetLoadingManager.h @@ -1,25 +1,25 @@ #pragma once -#include <memory> #include <map> +#include <memory> #include "AssetLoading/IAssetLoadingManager.h" -class MockAssetLoadingManager final : public IAssetLoadingManager -{ - Zone* m_zone; - std::unique_ptr<Gdt> m_mock_gdt; - std::unique_ptr<AssetLoadingContext> m_context; - std::map<std::string, std::unique_ptr<XAssetInfoGeneric>> m_added_assets; - std::multimap<std::string, std::unique_ptr<XAssetInfoGeneric>> m_available_dependencies; +class MockAssetLoadingManager final : public IAssetLoadingManager { + Zone *m_zone; + std::unique_ptr<Gdt> m_mock_gdt; + std::unique_ptr<AssetLoadingContext> m_context; + std::map<std::string, std::unique_ptr<XAssetInfoGeneric>> m_added_assets; + std::multimap<std::string, std::unique_ptr<XAssetInfoGeneric>> m_available_dependencies; public: - MockAssetLoadingManager(Zone* zone, ISearchPath* searchPath); + MockAssetLoadingManager(Zone *zone, ISearchPath *searchPath); - _NODISCARD AssetLoadingContext* GetAssetLoadingContext() const override; - XAssetInfoGeneric* AddAsset(asset_type_t assetType, const std::string& assetName, void* asset, std::vector<XAssetInfoGeneric*> dependencies, std::vector<scr_string_t> usedScriptStrings) override; - XAssetInfoGeneric* LoadDependency(asset_type_t assetType, const std::string& assetName) override; + _NODISCARD AssetLoadingContext *GetAssetLoadingContext() const override; + XAssetInfoGeneric *AddAsset(asset_type_t assetType, const std::string &assetName, void *asset, std::vector<XAssetInfoGeneric *> dependencies, + std::vector<scr_string_t> usedScriptStrings) override; + XAssetInfoGeneric *LoadDependency(asset_type_t assetType, const std::string &assetName) override; - void MockAddAvailableDependency(asset_type_t assetType, std::string assetName, void* asset); - XAssetInfoGeneric* MockGetAddedAsset(const std::string& assetName); + void MockAddAvailableDependency(asset_type_t assetType, std::string assetName, void *asset); + XAssetInfoGeneric *MockGetAddedAsset(const std::string &assetName); }; diff --git a/test/ObjLoadingTests/Mock/MockSearchPath.cpp b/test/ObjLoadingTests/Mock/MockSearchPath.cpp index b0662a4ae..d7812bb2e 100644 --- a/test/ObjLoadingTests/Mock/MockSearchPath.cpp +++ b/test/ObjLoadingTests/Mock/MockSearchPath.cpp @@ -2,26 +2,19 @@ #include <sstream> -void MockSearchPath::AddFileData(std::string fileName, std::string fileData) -{ - m_file_data_map.emplace(std::make_pair(std::move(fileName), std::move(fileData))); +void MockSearchPath::AddFileData(std::string fileName, std::string fileData) { + m_file_data_map.emplace(std::make_pair(std::move(fileName), std::move(fileData))); } -SearchPathOpenFile MockSearchPath::Open(const std::string& fileName) -{ - const auto foundFileData = m_file_data_map.find(fileName); +SearchPathOpenFile MockSearchPath::Open(const std::string &fileName) { + const auto foundFileData = m_file_data_map.find(fileName); - if(foundFileData == m_file_data_map.end()) - return {}; + if (foundFileData == m_file_data_map.end()) + return {}; - return {std::make_unique<std::istringstream>(foundFileData->second), foundFileData->second.size()}; + return {std::make_unique<std::istringstream>(foundFileData->second), foundFileData->second.size()}; } -std::string MockSearchPath::GetPath() -{ - return "MockFiles"; -} +std::string MockSearchPath::GetPath() { return "MockFiles"; } -void MockSearchPath::Find(const SearchPathSearchOptions& options, const std::function<void(const std::string&)>& callback) -{ -} +void MockSearchPath::Find(const SearchPathSearchOptions &options, const std::function<void(const std::string &)> &callback) {} diff --git a/test/ObjLoadingTests/Mock/MockSearchPath.h b/test/ObjLoadingTests/Mock/MockSearchPath.h index b43bc8f2c..447ab6da3 100644 --- a/test/ObjLoadingTests/Mock/MockSearchPath.h +++ b/test/ObjLoadingTests/Mock/MockSearchPath.h @@ -3,14 +3,13 @@ #include "SearchPath/ISearchPath.h" -class MockSearchPath final : public ISearchPath -{ - std::map<std::string, std::string> m_file_data_map; +class MockSearchPath final : public ISearchPath { + std::map<std::string, std::string> m_file_data_map; public: - void AddFileData(std::string fileName, std::string fileData); + void AddFileData(std::string fileName, std::string fileData); - SearchPathOpenFile Open(const std::string& fileName) override; - std::string GetPath() override; - void Find(const SearchPathSearchOptions& options, const std::function<void(const std::string&)>& callback) override; + SearchPathOpenFile Open(const std::string &fileName) override; + std::string GetPath() override; + void Find(const SearchPathSearchOptions &options, const std::function<void(const std::string &)> &callback) override; }; diff --git a/test/ObjLoadingTests/Parsing/Menu/Sequence/EventHandlerSetScopeSequencesTests.cpp b/test/ObjLoadingTests/Parsing/Menu/Sequence/EventHandlerSetScopeSequencesTests.cpp index 441a05c7a..caaf43579 100644 --- a/test/ObjLoadingTests/Parsing/Menu/Sequence/EventHandlerSetScopeSequencesTests.cpp +++ b/test/ObjLoadingTests/Parsing/Menu/Sequence/EventHandlerSetScopeSequencesTests.cpp @@ -3,1494 +3,1191 @@ #include "Parsing/Menu/Domain/EventHandler/CommonEventHandlerScript.h" #include "Parsing/Menu/Domain/EventHandler/CommonEventHandlerSetLocalVar.h" -#include "Utils/ClassUtils.h" #include "Parsing/Menu/Sequence/EventHandlerSetScopeSequences.h" #include "Parsing/Mock/MockLexer.h" +#include "Utils/ClassUtils.h" using namespace menu; -namespace test::parsing::menu::sequence::event_handler_set -{ - class EventHandlerSetSequenceTestsHelper - { - public: - std::vector<std::unique_ptr<MenuFileParser::sequence_t>> m_all_sequences; - std::vector<MenuFileParser::sequence_t*> m_scope_sequences; - std::unique_ptr<MenuFileParserState> m_state; - std::unique_ptr<ILexer<SimpleParserValue>> m_lexer; - - std::unique_ptr<CommonEventHandlerSet> m_event_handler_set; - - unsigned m_consumed_token_count; - - explicit EventHandlerSetSequenceTestsHelper(FeatureLevel featureLevel, bool permissive) - : m_state(std::make_unique<MenuFileParserState>(featureLevel, false)), - m_event_handler_set(std::make_unique<CommonEventHandlerSet>()), - m_consumed_token_count(0u) - { - EventHandlerSetScopeSequences scopeSequences(m_all_sequences, m_scope_sequences); - scopeSequences.AddSequences(m_state->m_feature_level, permissive); - - m_state->m_current_menu = m_state->m_menus.emplace_back(std::make_unique<CommonMenuDef>()).get(); - m_state->m_current_event_handler_set = m_event_handler_set.get(); - m_state->m_current_nested_event_handler_set = m_event_handler_set.get(); - } - - void Tokens(std::initializer_list<Movable<SimpleParserValue>> tokens) - { - m_lexer = std::make_unique<MockLexer<SimpleParserValue>>(tokens, SimpleParserValue::EndOfFile(TokenPos())); - } - - void Tokens(std::vector<SimpleParserValue> tokens) - { - m_lexer = std::make_unique<MockLexer<SimpleParserValue>>(std::move(tokens), SimpleParserValue::EndOfFile(TokenPos())); - } - - bool PerformTest() - { - REQUIRE(m_lexer); - - m_consumed_token_count = 0; - for (const auto* sequence : m_scope_sequences) - { - const auto couldMatch = sequence->MatchSequence(m_lexer.get(), m_state.get(), m_consumed_token_count); - if (couldMatch) - { - m_lexer->PopTokens(static_cast<int>(m_consumed_token_count)); - return couldMatch; - } - } - - return false; - } - }; +namespace test::parsing::menu::sequence::event_handler_set { +class EventHandlerSetSequenceTestsHelper { +public: + std::vector<std::unique_ptr<MenuFileParser::sequence_t>> m_all_sequences; + std::vector<MenuFileParser::sequence_t *> m_scope_sequences; + std::unique_ptr<MenuFileParserState> m_state; + std::unique_ptr<ILexer<SimpleParserValue>> m_lexer; -#pragma region General - TEST_CASE("EventHandlerSetScopeSequences: Keyword casing doesnt matter", "[parsing][sequence][menu]") - { - EventHandlerSetSequenceTestsHelper helper(FeatureLevel::IW4, false); - const TokenPos pos; - helper.Tokens({ - SimpleParserValue::Identifier(pos, new std::string("fadein")), - SimpleParserValue::String(pos, new std::string("some_element")), - SimpleParserValue::Character(pos, ';'), - SimpleParserValue::EndOfFile(pos) - }); - - const auto result = helper.PerformTest(); - - REQUIRE(result); - REQUIRE(helper.m_consumed_token_count == 3); - - const auto script = helper.m_state->m_current_script.str(); - REQUIRE(script == R"("fadein" "some_element" ; )"); - } + std::unique_ptr<CommonEventHandlerSet> m_event_handler_set; - TEST_CASE("EventHandlerSetScopeSequences: Invalid keywords are not recognized", "[parsing][sequence][menu]") - { - EventHandlerSetSequenceTestsHelper helper(FeatureLevel::IW4, false); - const TokenPos pos; - helper.Tokens({ - SimpleParserValue::Identifier(pos, new std::string("noScriptCommand")), - SimpleParserValue::String(pos, new std::string("some_element")), - SimpleParserValue::Character(pos, ';'), - SimpleParserValue::EndOfFile(pos) - }); - - const auto result = helper.PerformTest(); - - REQUIRE(!result); - REQUIRE(helper.m_consumed_token_count == 0); - } + unsigned m_consumed_token_count; + + explicit EventHandlerSetSequenceTestsHelper(FeatureLevel featureLevel, bool permissive) + : m_state(std::make_unique<MenuFileParserState>(featureLevel, false)), m_event_handler_set(std::make_unique<CommonEventHandlerSet>()), + m_consumed_token_count(0u) { + EventHandlerSetScopeSequences scopeSequences(m_all_sequences, m_scope_sequences); + scopeSequences.AddSequences(m_state->m_feature_level, permissive); + + m_state->m_current_menu = m_state->m_menus.emplace_back(std::make_unique<CommonMenuDef>()).get(); + m_state->m_current_event_handler_set = m_event_handler_set.get(); + m_state->m_current_nested_event_handler_set = m_event_handler_set.get(); + } + + void Tokens(std::initializer_list<Movable<SimpleParserValue>> tokens) { + m_lexer = std::make_unique<MockLexer<SimpleParserValue>>(tokens, SimpleParserValue::EndOfFile(TokenPos())); + } + + void Tokens(std::vector<SimpleParserValue> tokens) { + m_lexer = std::make_unique<MockLexer<SimpleParserValue>>(std::move(tokens), SimpleParserValue::EndOfFile(TokenPos())); + } - TEST_CASE("EventHandlerSetScopeSequences: Permissive mode ignores unknown script tokens and adds them to script", "[parsing][sequence][menu]") - { - EventHandlerSetSequenceTestsHelper helper(FeatureLevel::IW4, true); - const TokenPos pos; - helper.Tokens({ - SimpleParserValue::Identifier(pos, new std::string("uiScript")), - SimpleParserValue::Identifier(pos, new std::string("somethingUnknown")), - SimpleParserValue::String(pos, new std::string("anArgumentForTheUnknownScript")), - SimpleParserValue::Character(pos, ';'), - SimpleParserValue::EndOfFile(pos) - }); - - auto result = helper.PerformTest(); - REQUIRE(result); - REQUIRE(helper.m_consumed_token_count == 1); - auto script = helper.m_state->m_current_script.str(); - REQUIRE(script == R"("uiScript" )"); - - result = helper.PerformTest(); - REQUIRE(result); - REQUIRE(helper.m_consumed_token_count == 1); - script = helper.m_state->m_current_script.str(); - REQUIRE(script == R"("uiScript" "somethingUnknown" )"); - - result = helper.PerformTest(); - REQUIRE(result); - REQUIRE(helper.m_consumed_token_count == 1); - script = helper.m_state->m_current_script.str(); - REQUIRE(script == R"("uiScript" "somethingUnknown" "anArgumentForTheUnknownScript" )"); - - result = helper.PerformTest(); - REQUIRE(result); - REQUIRE(helper.m_consumed_token_count == 1); - script = helper.m_state->m_current_script.str(); - REQUIRE(script == R"("uiScript" "somethingUnknown" "anArgumentForTheUnknownScript" ; )"); + bool PerformTest() { + REQUIRE(m_lexer); + + m_consumed_token_count = 0; + for (const auto *sequence : m_scope_sequences) { + const auto couldMatch = sequence->MatchSequence(m_lexer.get(), m_state.get(), m_consumed_token_count); + if (couldMatch) { + m_lexer->PopTokens(static_cast<int>(m_consumed_token_count)); + return couldMatch; + } } + return false; + } +}; + +#pragma region General +TEST_CASE("EventHandlerSetScopeSequences: Keyword casing doesnt matter", "[parsing][sequence][menu]") { + EventHandlerSetSequenceTestsHelper helper(FeatureLevel::IW4, false); + const TokenPos pos; + helper.Tokens({SimpleParserValue::Identifier(pos, new std::string("fadein")), SimpleParserValue::String(pos, new std::string("some_element")), + SimpleParserValue::Character(pos, ';'), SimpleParserValue::EndOfFile(pos)}); + + const auto result = helper.PerformTest(); + + REQUIRE(result); + REQUIRE(helper.m_consumed_token_count == 3); + + const auto script = helper.m_state->m_current_script.str(); + REQUIRE(script == R"("fadein" "some_element" ; )"); +} + +TEST_CASE("EventHandlerSetScopeSequences: Invalid keywords are not recognized", "[parsing][sequence][menu]") { + EventHandlerSetSequenceTestsHelper helper(FeatureLevel::IW4, false); + const TokenPos pos; + helper.Tokens({SimpleParserValue::Identifier(pos, new std::string("noScriptCommand")), SimpleParserValue::String(pos, new std::string("some_element")), + SimpleParserValue::Character(pos, ';'), SimpleParserValue::EndOfFile(pos)}); + + const auto result = helper.PerformTest(); + + REQUIRE(!result); + REQUIRE(helper.m_consumed_token_count == 0); +} + +TEST_CASE("EventHandlerSetScopeSequences: Permissive mode ignores unknown script tokens and adds them to script", "[parsing][sequence][menu]") { + EventHandlerSetSequenceTestsHelper helper(FeatureLevel::IW4, true); + const TokenPos pos; + helper.Tokens({SimpleParserValue::Identifier(pos, new std::string("uiScript")), SimpleParserValue::Identifier(pos, new std::string("somethingUnknown")), + SimpleParserValue::String(pos, new std::string("anArgumentForTheUnknownScript")), SimpleParserValue::Character(pos, ';'), + SimpleParserValue::EndOfFile(pos)}); + + auto result = helper.PerformTest(); + REQUIRE(result); + REQUIRE(helper.m_consumed_token_count == 1); + auto script = helper.m_state->m_current_script.str(); + REQUIRE(script == R"("uiScript" )"); + + result = helper.PerformTest(); + REQUIRE(result); + REQUIRE(helper.m_consumed_token_count == 1); + script = helper.m_state->m_current_script.str(); + REQUIRE(script == R"("uiScript" "somethingUnknown" )"); + + result = helper.PerformTest(); + REQUIRE(result); + REQUIRE(helper.m_consumed_token_count == 1); + script = helper.m_state->m_current_script.str(); + REQUIRE(script == R"("uiScript" "somethingUnknown" "anArgumentForTheUnknownScript" )"); + + result = helper.PerformTest(); + REQUIRE(result); + REQUIRE(helper.m_consumed_token_count == 1); + script = helper.m_state->m_current_script.str(); + REQUIRE(script == R"("uiScript" "somethingUnknown" "anArgumentForTheUnknownScript" ; )"); +} + #pragma endregion - void TestGenericScriptStatement(const std::initializer_list<Movable<SimpleParserValue>> tokens, const std::string& expectedScript) - { - std::vector<SimpleParserValue> tokenList(std::make_move_iterator(tokens.begin()), std::make_move_iterator(tokens.end())); - const auto initialValueCount = tokenList.size(); +void TestGenericScriptStatement(const std::initializer_list<Movable<SimpleParserValue>> tokens, const std::string &expectedScript) { + std::vector<SimpleParserValue> tokenList(std::make_move_iterator(tokens.begin()), std::make_move_iterator(tokens.end())); + const auto initialValueCount = tokenList.size(); - tokenList.emplace_back(SimpleParserValue::Character(TokenPos(), ';')); - tokenList.emplace_back(SimpleParserValue::EndOfFile(TokenPos())); + tokenList.emplace_back(SimpleParserValue::Character(TokenPos(), ';')); + tokenList.emplace_back(SimpleParserValue::EndOfFile(TokenPos())); - EventHandlerSetSequenceTestsHelper helper(FeatureLevel::IW4, false); - helper.Tokens(std::move(tokenList)); + EventHandlerSetSequenceTestsHelper helper(FeatureLevel::IW4, false); + helper.Tokens(std::move(tokenList)); - const auto result = helper.PerformTest(); - REQUIRE(result); - REQUIRE(helper.m_consumed_token_count == initialValueCount + 1); + const auto result = helper.PerformTest(); + REQUIRE(result); + REQUIRE(helper.m_consumed_token_count == initialValueCount + 1); - const auto script = helper.m_state->m_current_script.str(); - REQUIRE(script == expectedScript); - } + const auto script = helper.m_state->m_current_script.str(); + REQUIRE(script == expectedScript); +} #pragma region Command Tests - TEST_CASE("EventHandlerSetScopeSequences: Ensure can use fadeIn", "[parsing][sequence][menu]") - { - TestGenericScriptStatement( - { - SimpleParserValue::Identifier(TokenPos(), new std::string("fadeIn")), - SimpleParserValue::String(TokenPos(), new std::string("some_element")) - }, R"("fadeIn" "some_element" ; )"); - } +TEST_CASE("EventHandlerSetScopeSequences: Ensure can use fadeIn", "[parsing][sequence][menu]") { + TestGenericScriptStatement( + {SimpleParserValue::Identifier(TokenPos(), new std::string("fadeIn")), SimpleParserValue::String(TokenPos(), new std::string("some_element"))}, + R"("fadeIn" "some_element" ; )"); +} - TEST_CASE("EventHandlerSetScopeSequences: Ensure can use fadeOut", "[parsing][sequence][menu]") - { - TestGenericScriptStatement( - { - SimpleParserValue::Identifier(TokenPos(), new std::string("fadeOut")), - SimpleParserValue::String(TokenPos(), new std::string("some_element")) - }, R"("fadeOut" "some_element" ; )"); - } +TEST_CASE("EventHandlerSetScopeSequences: Ensure can use fadeOut", "[parsing][sequence][menu]") { + TestGenericScriptStatement( + {SimpleParserValue::Identifier(TokenPos(), new std::string("fadeOut")), SimpleParserValue::String(TokenPos(), new std::string("some_element"))}, + R"("fadeOut" "some_element" ; )"); +} - TEST_CASE("EventHandlerSetScopeSequences: Ensure can use show", "[parsing][sequence][menu]") - { - TestGenericScriptStatement( - { - SimpleParserValue::Identifier(TokenPos(), new std::string("show")), - SimpleParserValue::String(TokenPos(), new std::string("some_element")) - }, R"("show" "some_element" ; )"); - } +TEST_CASE("EventHandlerSetScopeSequences: Ensure can use show", "[parsing][sequence][menu]") { + TestGenericScriptStatement( + {SimpleParserValue::Identifier(TokenPos(), new std::string("show")), SimpleParserValue::String(TokenPos(), new std::string("some_element"))}, + R"("show" "some_element" ; )"); +} - TEST_CASE("EventHandlerSetScopeSequences: Ensure can use hide", "[parsing][sequence][menu]") - { - TestGenericScriptStatement( - { - SimpleParserValue::Identifier(TokenPos(), new std::string("hide")), - SimpleParserValue::String(TokenPos(), new std::string("some_element")) - }, R"("hide" "some_element" ; )"); - } +TEST_CASE("EventHandlerSetScopeSequences: Ensure can use hide", "[parsing][sequence][menu]") { + TestGenericScriptStatement( + {SimpleParserValue::Identifier(TokenPos(), new std::string("hide")), SimpleParserValue::String(TokenPos(), new std::string("some_element"))}, + R"("hide" "some_element" ; )"); +} - TEST_CASE("EventHandlerSetScopeSequences: Ensure can use showMenu", "[parsing][sequence][menu]") - { - TestGenericScriptStatement( - { - SimpleParserValue::Identifier(TokenPos(), new std::string("showMenu")), - SimpleParserValue::String(TokenPos(), new std::string("some_element")) - }, R"("showMenu" "some_element" ; )"); - } +TEST_CASE("EventHandlerSetScopeSequences: Ensure can use showMenu", "[parsing][sequence][menu]") { + TestGenericScriptStatement( + {SimpleParserValue::Identifier(TokenPos(), new std::string("showMenu")), SimpleParserValue::String(TokenPos(), new std::string("some_element"))}, + R"("showMenu" "some_element" ; )"); +} - TEST_CASE("EventHandlerSetScopeSequences: Ensure can use hideMenu", "[parsing][sequence][menu]") - { - TestGenericScriptStatement( - { - SimpleParserValue::Identifier(TokenPos(), new std::string("hideMenu")), - SimpleParserValue::String(TokenPos(), new std::string("some_element")) - }, R"("hideMenu" "some_element" ; )"); - } +TEST_CASE("EventHandlerSetScopeSequences: Ensure can use hideMenu", "[parsing][sequence][menu]") { + TestGenericScriptStatement( + {SimpleParserValue::Identifier(TokenPos(), new std::string("hideMenu")), SimpleParserValue::String(TokenPos(), new std::string("some_element"))}, + R"("hideMenu" "some_element" ; )"); +} - TEST_CASE("EventHandlerSetScopeSequences: Ensure can use setColor", "[parsing][sequence][menu]") - { - TestGenericScriptStatement( - { - SimpleParserValue::Identifier(TokenPos(), new std::string("setColor")), - SimpleParserValue::Identifier(TokenPos(), new std::string("backColor")), - SimpleParserValue::Integer(TokenPos(), 1), - SimpleParserValue::Integer(TokenPos(), 1), - SimpleParserValue::Integer(TokenPos(), 1), - SimpleParserValue::Integer(TokenPos(), 1), - }, R"("setColor" "backColor" "1" "1" "1" "1" ; )"); - } +TEST_CASE("EventHandlerSetScopeSequences: Ensure can use setColor", "[parsing][sequence][menu]") { + TestGenericScriptStatement( + { + SimpleParserValue::Identifier(TokenPos(), new std::string("setColor")), + SimpleParserValue::Identifier(TokenPos(), new std::string("backColor")), + SimpleParserValue::Integer(TokenPos(), 1), + SimpleParserValue::Integer(TokenPos(), 1), + SimpleParserValue::Integer(TokenPos(), 1), + SimpleParserValue::Integer(TokenPos(), 1), + }, + R"("setColor" "backColor" "1" "1" "1" "1" ; )"); +} - TEST_CASE("EventHandlerSetScopeSequences: Ensure can use setColor with 3 colors", "[parsing][sequence][menu]") - { - TestGenericScriptStatement( - { - SimpleParserValue::Identifier(TokenPos(), new std::string("setColor")), - SimpleParserValue::Identifier(TokenPos(), new std::string("backColor")), - SimpleParserValue::Integer(TokenPos(), 1), - SimpleParserValue::Integer(TokenPos(), 1), - SimpleParserValue::Integer(TokenPos(), 1), - }, R"("setColor" "backColor" "1" "1" "1" ; )"); - } +TEST_CASE("EventHandlerSetScopeSequences: Ensure can use setColor with 3 colors", "[parsing][sequence][menu]") { + TestGenericScriptStatement( + { + SimpleParserValue::Identifier(TokenPos(), new std::string("setColor")), + SimpleParserValue::Identifier(TokenPos(), new std::string("backColor")), + SimpleParserValue::Integer(TokenPos(), 1), + SimpleParserValue::Integer(TokenPos(), 1), + SimpleParserValue::Integer(TokenPos(), 1), + }, + R"("setColor" "backColor" "1" "1" "1" ; )"); +} - TEST_CASE("EventHandlerSetScopeSequences: Ensure can use setColor with 2 colors", "[parsing][sequence][menu]") - { - TestGenericScriptStatement( - { - SimpleParserValue::Identifier(TokenPos(), new std::string("setColor")), - SimpleParserValue::Identifier(TokenPos(), new std::string("backColor")), - SimpleParserValue::Integer(TokenPos(), 1), - SimpleParserValue::Integer(TokenPos(), 1), - }, R"("setColor" "backColor" "1" "1" ; )"); - } +TEST_CASE("EventHandlerSetScopeSequences: Ensure can use setColor with 2 colors", "[parsing][sequence][menu]") { + TestGenericScriptStatement( + { + SimpleParserValue::Identifier(TokenPos(), new std::string("setColor")), + SimpleParserValue::Identifier(TokenPos(), new std::string("backColor")), + SimpleParserValue::Integer(TokenPos(), 1), + SimpleParserValue::Integer(TokenPos(), 1), + }, + R"("setColor" "backColor" "1" "1" ; )"); +} - TEST_CASE("EventHandlerSetScopeSequences: Ensure can use setColor with 1 color", "[parsing][sequence][menu]") - { - TestGenericScriptStatement( - { - SimpleParserValue::Identifier(TokenPos(), new std::string("setColor")), - SimpleParserValue::Identifier(TokenPos(), new std::string("backColor")), - SimpleParserValue::Integer(TokenPos(), 1), - }, R"("setColor" "backColor" "1" ; )"); - } +TEST_CASE("EventHandlerSetScopeSequences: Ensure can use setColor with 1 color", "[parsing][sequence][menu]") { + TestGenericScriptStatement( + { + SimpleParserValue::Identifier(TokenPos(), new std::string("setColor")), + SimpleParserValue::Identifier(TokenPos(), new std::string("backColor")), + SimpleParserValue::Integer(TokenPos(), 1), + }, + R"("setColor" "backColor" "1" ; )"); +} - TEST_CASE("EventHandlerSetScopeSequences: Ensure cannot use setColor with no color", "[parsing][sequence][menu]") - { - EventHandlerSetSequenceTestsHelper helper(FeatureLevel::IW4, false); - const TokenPos pos; - helper.Tokens({ - SimpleParserValue::Identifier(pos, new std::string("setColor")), - SimpleParserValue::Identifier(TokenPos(), new std::string("backColor")), - SimpleParserValue::Character(pos, ';'), - SimpleParserValue::EndOfFile(pos) - }); - - const auto result = helper.PerformTest(); - - REQUIRE(result == false); - REQUIRE(helper.m_consumed_token_count == 0); - } +TEST_CASE("EventHandlerSetScopeSequences: Ensure cannot use setColor with no color", "[parsing][sequence][menu]") { + EventHandlerSetSequenceTestsHelper helper(FeatureLevel::IW4, false); + const TokenPos pos; + helper.Tokens({SimpleParserValue::Identifier(pos, new std::string("setColor")), SimpleParserValue::Identifier(TokenPos(), new std::string("backColor")), + SimpleParserValue::Character(pos, ';'), SimpleParserValue::EndOfFile(pos)}); - TEST_CASE("EventHandlerSetScopeSequences: Ensure can use open", "[parsing][sequence][menu]") - { - TestGenericScriptStatement( - { - SimpleParserValue::Identifier(TokenPos(), new std::string("open")), - SimpleParserValue::String(TokenPos(), new std::string("some_element")) - }, R"("open" "some_element" ; )"); - } + const auto result = helper.PerformTest(); - TEST_CASE("EventHandlerSetScopeSequences: Ensure can use close", "[parsing][sequence][menu]") - { - TestGenericScriptStatement( - { - SimpleParserValue::Identifier(TokenPos(), new std::string("close")), - SimpleParserValue::String(TokenPos(), new std::string("some_element")) - }, R"("close" "some_element" ; )"); - } + REQUIRE(result == false); + REQUIRE(helper.m_consumed_token_count == 0); +} - TEST_CASE("EventHandlerSetScopeSequences: Ensure can use escape", "[parsing][sequence][menu]") - { - TestGenericScriptStatement( - { - SimpleParserValue::Identifier(TokenPos(), new std::string("escape")), - SimpleParserValue::String(TokenPos(), new std::string("some_element")) - }, R"("escape" "some_element" ; )"); - } +TEST_CASE("EventHandlerSetScopeSequences: Ensure can use open", "[parsing][sequence][menu]") { + TestGenericScriptStatement( + {SimpleParserValue::Identifier(TokenPos(), new std::string("open")), SimpleParserValue::String(TokenPos(), new std::string("some_element"))}, + R"("open" "some_element" ; )"); +} - TEST_CASE("EventHandlerSetScopeSequences: Ensure can use closeForAllPlayers", "[parsing][sequence][menu]") - { - TestGenericScriptStatement( - { - SimpleParserValue::Identifier(TokenPos(), new std::string("closeForAllPlayers")), - SimpleParserValue::String(TokenPos(), new std::string("some_element")) - }, R"("closeForAllPlayers" "some_element" ; )"); - } +TEST_CASE("EventHandlerSetScopeSequences: Ensure can use close", "[parsing][sequence][menu]") { + TestGenericScriptStatement( + {SimpleParserValue::Identifier(TokenPos(), new std::string("close")), SimpleParserValue::String(TokenPos(), new std::string("some_element"))}, + R"("close" "some_element" ; )"); +} - TEST_CASE("EventHandlerSetScopeSequences: Ensure can use ingameOpen", "[parsing][sequence][menu]") - { - TestGenericScriptStatement( - { - SimpleParserValue::Identifier(TokenPos(), new std::string("ingameOpen")), - SimpleParserValue::String(TokenPos(), new std::string("some_element")) - }, R"("ingameOpen" "some_element" ; )"); - } +TEST_CASE("EventHandlerSetScopeSequences: Ensure can use escape", "[parsing][sequence][menu]") { + TestGenericScriptStatement( + {SimpleParserValue::Identifier(TokenPos(), new std::string("escape")), SimpleParserValue::String(TokenPos(), new std::string("some_element"))}, + R"("escape" "some_element" ; )"); +} - TEST_CASE("EventHandlerSetScopeSequences: Ensure can use ingameClose", "[parsing][sequence][menu]") - { - TestGenericScriptStatement( - { - SimpleParserValue::Identifier(TokenPos(), new std::string("ingameClose")), - SimpleParserValue::String(TokenPos(), new std::string("some_element")) - }, R"("ingameClose" "some_element" ; )"); - } +TEST_CASE("EventHandlerSetScopeSequences: Ensure can use closeForAllPlayers", "[parsing][sequence][menu]") { + TestGenericScriptStatement({SimpleParserValue::Identifier(TokenPos(), new std::string("closeForAllPlayers")), + SimpleParserValue::String(TokenPos(), new std::string("some_element"))}, + R"("closeForAllPlayers" "some_element" ; )"); +} - TEST_CASE("EventHandlerSetScopeSequences: Ensure can use setBackground", "[parsing][sequence][menu]") - { - TestGenericScriptStatement( - { - SimpleParserValue::Identifier(TokenPos(), new std::string("setBackground")), - SimpleParserValue::String(TokenPos(), new std::string("some_element")) - }, R"("setBackground" "some_element" ; )"); - } +TEST_CASE("EventHandlerSetScopeSequences: Ensure can use ingameOpen", "[parsing][sequence][menu]") { + TestGenericScriptStatement( + {SimpleParserValue::Identifier(TokenPos(), new std::string("ingameOpen")), SimpleParserValue::String(TokenPos(), new std::string("some_element"))}, + R"("ingameOpen" "some_element" ; )"); +} - TEST_CASE("EventHandlerSetScopeSequences: Ensure can use setItemColor with forecolor", "[parsing][sequence][menu]") - { - TestGenericScriptStatement( - { - SimpleParserValue::Identifier(TokenPos(), new std::string("setItemColor")), - SimpleParserValue::String(TokenPos(), new std::string("some_element")), - SimpleParserValue::Identifier(TokenPos(), new std::string("forecolor")), - SimpleParserValue::Integer(TokenPos(), 1), - SimpleParserValue::Integer(TokenPos(), 1), - SimpleParserValue::Integer(TokenPos(), 1), - SimpleParserValue::Integer(TokenPos(), 1), - }, R"("setItemColor" "some_element" "forecolor" "1" "1" "1" "1" ; )"); - } +TEST_CASE("EventHandlerSetScopeSequences: Ensure can use ingameClose", "[parsing][sequence][menu]") { + TestGenericScriptStatement( + {SimpleParserValue::Identifier(TokenPos(), new std::string("ingameClose")), SimpleParserValue::String(TokenPos(), new std::string("some_element"))}, + R"("ingameClose" "some_element" ; )"); +} - TEST_CASE("EventHandlerSetScopeSequences: Ensure can use setItemColor with backcolor", "[parsing][sequence][menu]") - { - TestGenericScriptStatement( - { - SimpleParserValue::Identifier(TokenPos(), new std::string("setItemColor")), - SimpleParserValue::String(TokenPos(), new std::string("some_element")), - SimpleParserValue::Identifier(TokenPos(), new std::string("backColor")), - SimpleParserValue::Integer(TokenPos(), 1), - SimpleParserValue::Integer(TokenPos(), 1), - SimpleParserValue::Integer(TokenPos(), 1), - SimpleParserValue::Integer(TokenPos(), 1), - }, R"("setItemColor" "some_element" "backColor" "1" "1" "1" "1" ; )"); - } +TEST_CASE("EventHandlerSetScopeSequences: Ensure can use setBackground", "[parsing][sequence][menu]") { + TestGenericScriptStatement( + {SimpleParserValue::Identifier(TokenPos(), new std::string("setBackground")), SimpleParserValue::String(TokenPos(), new std::string("some_element"))}, + R"("setBackground" "some_element" ; )"); +} - TEST_CASE("EventHandlerSetScopeSequences: Ensure can use setItemColor with bordercolor", "[parsing][sequence][menu]") - { - TestGenericScriptStatement( - { - SimpleParserValue::Identifier(TokenPos(), new std::string("setItemColor")), - SimpleParserValue::String(TokenPos(), new std::string("some_element")), - SimpleParserValue::Identifier(TokenPos(), new std::string("bordercolor")), - SimpleParserValue::Integer(TokenPos(), 1), - SimpleParserValue::Integer(TokenPos(), 1), - SimpleParserValue::Integer(TokenPos(), 1), - SimpleParserValue::Integer(TokenPos(), 1), - }, R"("setItemColor" "some_element" "bordercolor" "1" "1" "1" "1" ; )"); - } +TEST_CASE("EventHandlerSetScopeSequences: Ensure can use setItemColor with forecolor", "[parsing][sequence][menu]") { + TestGenericScriptStatement( + { + SimpleParserValue::Identifier(TokenPos(), new std::string("setItemColor")), + SimpleParserValue::String(TokenPos(), new std::string("some_element")), + SimpleParserValue::Identifier(TokenPos(), new std::string("forecolor")), + SimpleParserValue::Integer(TokenPos(), 1), + SimpleParserValue::Integer(TokenPos(), 1), + SimpleParserValue::Integer(TokenPos(), 1), + SimpleParserValue::Integer(TokenPos(), 1), + }, + R"("setItemColor" "some_element" "forecolor" "1" "1" "1" "1" ; )"); +} - TEST_CASE("EventHandlerSetScopeSequences: Ensure can use setItemColor with disablecolor", "[parsing][sequence][menu]") - { - TestGenericScriptStatement( - { - SimpleParserValue::Identifier(TokenPos(), new std::string("setItemColor")), - SimpleParserValue::String(TokenPos(), new std::string("some_element")), - SimpleParserValue::Identifier(TokenPos(), new std::string("disablecolor")), - SimpleParserValue::Integer(TokenPos(), 1), - SimpleParserValue::Integer(TokenPos(), 1), - SimpleParserValue::Integer(TokenPos(), 1), - SimpleParserValue::Integer(TokenPos(), 1), - }, R"("setItemColor" "some_element" "disablecolor" "1" "1" "1" "1" ; )"); - } +TEST_CASE("EventHandlerSetScopeSequences: Ensure can use setItemColor with backcolor", "[parsing][sequence][menu]") { + TestGenericScriptStatement( + { + SimpleParserValue::Identifier(TokenPos(), new std::string("setItemColor")), + SimpleParserValue::String(TokenPos(), new std::string("some_element")), + SimpleParserValue::Identifier(TokenPos(), new std::string("backColor")), + SimpleParserValue::Integer(TokenPos(), 1), + SimpleParserValue::Integer(TokenPos(), 1), + SimpleParserValue::Integer(TokenPos(), 1), + SimpleParserValue::Integer(TokenPos(), 1), + }, + R"("setItemColor" "some_element" "backColor" "1" "1" "1" "1" ; )"); +} - TEST_CASE("EventHandlerSetScopeSequences: Ensure can use focusFirst", "[parsing][sequence][menu]") - { - TestGenericScriptStatement( - { - SimpleParserValue::Identifier(TokenPos(), new std::string("focusFirst")), - }, R"("focusFirst" ; )"); - } +TEST_CASE("EventHandlerSetScopeSequences: Ensure can use setItemColor with bordercolor", "[parsing][sequence][menu]") { + TestGenericScriptStatement( + { + SimpleParserValue::Identifier(TokenPos(), new std::string("setItemColor")), + SimpleParserValue::String(TokenPos(), new std::string("some_element")), + SimpleParserValue::Identifier(TokenPos(), new std::string("bordercolor")), + SimpleParserValue::Integer(TokenPos(), 1), + SimpleParserValue::Integer(TokenPos(), 1), + SimpleParserValue::Integer(TokenPos(), 1), + SimpleParserValue::Integer(TokenPos(), 1), + }, + R"("setItemColor" "some_element" "bordercolor" "1" "1" "1" "1" ; )"); +} - TEST_CASE("EventHandlerSetScopeSequences: Ensure can use setFocus", "[parsing][sequence][menu]") - { - TestGenericScriptStatement( - { - SimpleParserValue::Identifier(TokenPos(), new std::string("setFocus")), - SimpleParserValue::String(TokenPos(), new std::string("some_element")) - }, R"("setFocus" "some_element" ; )"); - } +TEST_CASE("EventHandlerSetScopeSequences: Ensure can use setItemColor with disablecolor", "[parsing][sequence][menu]") { + TestGenericScriptStatement( + { + SimpleParserValue::Identifier(TokenPos(), new std::string("setItemColor")), + SimpleParserValue::String(TokenPos(), new std::string("some_element")), + SimpleParserValue::Identifier(TokenPos(), new std::string("disablecolor")), + SimpleParserValue::Integer(TokenPos(), 1), + SimpleParserValue::Integer(TokenPos(), 1), + SimpleParserValue::Integer(TokenPos(), 1), + SimpleParserValue::Integer(TokenPos(), 1), + }, + R"("setItemColor" "some_element" "disablecolor" "1" "1" "1" "1" ; )"); +} - TEST_CASE("EventHandlerSetScopeSequences: Ensure can use setFocusByDvar", "[parsing][sequence][menu]") - { - TestGenericScriptStatement( - { - SimpleParserValue::Identifier(TokenPos(), new std::string("setFocusByDvar")), - SimpleParserValue::String(TokenPos(), new std::string("some_dvar")) - }, R"("setFocusByDvar" "some_dvar" ; )"); - } +TEST_CASE("EventHandlerSetScopeSequences: Ensure can use focusFirst", "[parsing][sequence][menu]") { + TestGenericScriptStatement( + { + SimpleParserValue::Identifier(TokenPos(), new std::string("focusFirst")), + }, + R"("focusFirst" ; )"); +} - TEST_CASE("EventHandlerSetScopeSequences: Ensure can use setDvar", "[parsing][sequence][menu]") - { - TestGenericScriptStatement( - { - SimpleParserValue::Identifier(TokenPos(), new std::string("setDvar")), - SimpleParserValue::String(TokenPos(), new std::string("some_dvar")), - SimpleParserValue::String(TokenPos(), new std::string("some_value")), - }, R"("setDvar" "some_dvar" "some_value" ; )"); - } +TEST_CASE("EventHandlerSetScopeSequences: Ensure can use setFocus", "[parsing][sequence][menu]") { + TestGenericScriptStatement( + {SimpleParserValue::Identifier(TokenPos(), new std::string("setFocus")), SimpleParserValue::String(TokenPos(), new std::string("some_element"))}, + R"("setFocus" "some_element" ; )"); +} - TEST_CASE("EventHandlerSetScopeSequences: Ensure can use exec", "[parsing][sequence][menu]") - { - TestGenericScriptStatement( - { - SimpleParserValue::Identifier(TokenPos(), new std::string("exec")), - SimpleParserValue::String(TokenPos(), new std::string("some_command")) - }, R"("exec" "some_command" ; )"); - } +TEST_CASE("EventHandlerSetScopeSequences: Ensure can use setFocusByDvar", "[parsing][sequence][menu]") { + TestGenericScriptStatement( + {SimpleParserValue::Identifier(TokenPos(), new std::string("setFocusByDvar")), SimpleParserValue::String(TokenPos(), new std::string("some_dvar"))}, + R"("setFocusByDvar" "some_dvar" ; )"); +} - TEST_CASE("EventHandlerSetScopeSequences: Ensure can use execNow", "[parsing][sequence][menu]") - { - TestGenericScriptStatement( - { - SimpleParserValue::Identifier(TokenPos(), new std::string("execNow")), - SimpleParserValue::String(TokenPos(), new std::string("some_command")) - }, R"("execNow" "some_command" ; )"); - } +TEST_CASE("EventHandlerSetScopeSequences: Ensure can use setDvar", "[parsing][sequence][menu]") { + TestGenericScriptStatement( + { + SimpleParserValue::Identifier(TokenPos(), new std::string("setDvar")), + SimpleParserValue::String(TokenPos(), new std::string("some_dvar")), + SimpleParserValue::String(TokenPos(), new std::string("some_value")), + }, + R"("setDvar" "some_dvar" "some_value" ; )"); +} - TEST_CASE("EventHandlerSetScopeSequences: Ensure can use execOnDvarStringValue", "[parsing][sequence][menu]") - { - TestGenericScriptStatement( - { - SimpleParserValue::Identifier(TokenPos(), new std::string("execOnDvarStringValue")), - SimpleParserValue::String(TokenPos(), new std::string("some_dvar")), - SimpleParserValue::String(TokenPos(), new std::string("some_value")), - SimpleParserValue::String(TokenPos(), new std::string("some_command")) - }, R"("execOnDvarStringValue" "some_dvar" "some_value" "some_command" ; )"); - } +TEST_CASE("EventHandlerSetScopeSequences: Ensure can use exec", "[parsing][sequence][menu]") { + TestGenericScriptStatement( + {SimpleParserValue::Identifier(TokenPos(), new std::string("exec")), SimpleParserValue::String(TokenPos(), new std::string("some_command"))}, + R"("exec" "some_command" ; )"); +} - TEST_CASE("EventHandlerSetScopeSequences: Ensure can use execOnDvarIntValue", "[parsing][sequence][menu]") - { - TestGenericScriptStatement( - { - SimpleParserValue::Identifier(TokenPos(), new std::string("execOnDvarIntValue")), - SimpleParserValue::String(TokenPos(), new std::string("some_dvar")), - SimpleParserValue::Integer(TokenPos(), 1), - SimpleParserValue::String(TokenPos(), new std::string("some_command")) - }, R"("execOnDvarIntValue" "some_dvar" "1" "some_command" ; )"); - } +TEST_CASE("EventHandlerSetScopeSequences: Ensure can use execNow", "[parsing][sequence][menu]") { + TestGenericScriptStatement( + {SimpleParserValue::Identifier(TokenPos(), new std::string("execNow")), SimpleParserValue::String(TokenPos(), new std::string("some_command"))}, + R"("execNow" "some_command" ; )"); +} - TEST_CASE("EventHandlerSetScopeSequences: Ensure can use execOnDvarFloatValue", "[parsing][sequence][menu]") - { - TestGenericScriptStatement( - { - SimpleParserValue::Identifier(TokenPos(), new std::string("execOnDvarFloatValue")), - SimpleParserValue::String(TokenPos(), new std::string("some_dvar")), - SimpleParserValue::Integer(TokenPos(), 1), - SimpleParserValue::String(TokenPos(), new std::string("some_command")) - }, R"("execOnDvarFloatValue" "some_dvar" "1" "some_command" ; )"); - } +TEST_CASE("EventHandlerSetScopeSequences: Ensure can use execOnDvarStringValue", "[parsing][sequence][menu]") { + TestGenericScriptStatement( + {SimpleParserValue::Identifier(TokenPos(), new std::string("execOnDvarStringValue")), SimpleParserValue::String(TokenPos(), new std::string("some_dvar")), + SimpleParserValue::String(TokenPos(), new std::string("some_value")), SimpleParserValue::String(TokenPos(), new std::string("some_command"))}, + R"("execOnDvarStringValue" "some_dvar" "some_value" "some_command" ; )"); +} - TEST_CASE("EventHandlerSetScopeSequences: Ensure can use execNowOnDvarStringValue", "[parsing][sequence][menu]") - { - TestGenericScriptStatement( - { - SimpleParserValue::Identifier(TokenPos(), new std::string("execNowOnDvarStringValue")), - SimpleParserValue::String(TokenPos(), new std::string("some_dvar")), - SimpleParserValue::String(TokenPos(), new std::string("some_value")), - SimpleParserValue::String(TokenPos(), new std::string("some_command")) - }, R"("execNowOnDvarStringValue" "some_dvar" "some_value" "some_command" ; )"); - } +TEST_CASE("EventHandlerSetScopeSequences: Ensure can use execOnDvarIntValue", "[parsing][sequence][menu]") { + TestGenericScriptStatement({SimpleParserValue::Identifier(TokenPos(), new std::string("execOnDvarIntValue")), + SimpleParserValue::String(TokenPos(), new std::string("some_dvar")), SimpleParserValue::Integer(TokenPos(), 1), + SimpleParserValue::String(TokenPos(), new std::string("some_command"))}, + R"("execOnDvarIntValue" "some_dvar" "1" "some_command" ; )"); +} - TEST_CASE("EventHandlerSetScopeSequences: Ensure can use execNowOnDvarIntValue", "[parsing][sequence][menu]") - { - TestGenericScriptStatement( - { - SimpleParserValue::Identifier(TokenPos(), new std::string("execNowOnDvarIntValue")), - SimpleParserValue::String(TokenPos(), new std::string("some_dvar")), - SimpleParserValue::Integer(TokenPos(), 1), - SimpleParserValue::String(TokenPos(), new std::string("some_command")) - }, R"("execNowOnDvarIntValue" "some_dvar" "1" "some_command" ; )"); - } +TEST_CASE("EventHandlerSetScopeSequences: Ensure can use execOnDvarFloatValue", "[parsing][sequence][menu]") { + TestGenericScriptStatement({SimpleParserValue::Identifier(TokenPos(), new std::string("execOnDvarFloatValue")), + SimpleParserValue::String(TokenPos(), new std::string("some_dvar")), SimpleParserValue::Integer(TokenPos(), 1), + SimpleParserValue::String(TokenPos(), new std::string("some_command"))}, + R"("execOnDvarFloatValue" "some_dvar" "1" "some_command" ; )"); +} - TEST_CASE("EventHandlerSetScopeSequences: Ensure can use execNowOnDvarFloatValue", "[parsing][sequence][menu]") - { - TestGenericScriptStatement( - { - SimpleParserValue::Identifier(TokenPos(), new std::string("execNowOnDvarFloatValue")), - SimpleParserValue::String(TokenPos(), new std::string("some_dvar")), - SimpleParserValue::Integer(TokenPos(), 1), - SimpleParserValue::String(TokenPos(), new std::string("some_command")) - }, R"("execNowOnDvarFloatValue" "some_dvar" "1" "some_command" ; )"); - } +TEST_CASE("EventHandlerSetScopeSequences: Ensure can use execNowOnDvarStringValue", "[parsing][sequence][menu]") { + TestGenericScriptStatement({SimpleParserValue::Identifier(TokenPos(), new std::string("execNowOnDvarStringValue")), + SimpleParserValue::String(TokenPos(), new std::string("some_dvar")), + SimpleParserValue::String(TokenPos(), new std::string("some_value")), + SimpleParserValue::String(TokenPos(), new std::string("some_command"))}, + R"("execNowOnDvarStringValue" "some_dvar" "some_value" "some_command" ; )"); +} - TEST_CASE("EventHandlerSetScopeSequences: Ensure can use play", "[parsing][sequence][menu]") - { - TestGenericScriptStatement( - { - SimpleParserValue::Identifier(TokenPos(), new std::string("play")), - SimpleParserValue::String(TokenPos(), new std::string("some_sound")) - }, R"("play" "some_sound" ; )"); - } +TEST_CASE("EventHandlerSetScopeSequences: Ensure can use execNowOnDvarIntValue", "[parsing][sequence][menu]") { + TestGenericScriptStatement({SimpleParserValue::Identifier(TokenPos(), new std::string("execNowOnDvarIntValue")), + SimpleParserValue::String(TokenPos(), new std::string("some_dvar")), SimpleParserValue::Integer(TokenPos(), 1), + SimpleParserValue::String(TokenPos(), new std::string("some_command"))}, + R"("execNowOnDvarIntValue" "some_dvar" "1" "some_command" ; )"); +} - TEST_CASE("EventHandlerSetScopeSequences: Ensure can use scriptMenuResponse", "[parsing][sequence][menu]") - { - TestGenericScriptStatement( - { - SimpleParserValue::Identifier(TokenPos(), new std::string("scriptMenuResponse")), - SimpleParserValue::String(TokenPos(), new std::string("some_response")) - }, R"("scriptMenuResponse" "some_response" ; )"); - } +TEST_CASE("EventHandlerSetScopeSequences: Ensure can use execNowOnDvarFloatValue", "[parsing][sequence][menu]") { + TestGenericScriptStatement({SimpleParserValue::Identifier(TokenPos(), new std::string("execNowOnDvarFloatValue")), + SimpleParserValue::String(TokenPos(), new std::string("some_dvar")), SimpleParserValue::Integer(TokenPos(), 1), + SimpleParserValue::String(TokenPos(), new std::string("some_command"))}, + R"("execNowOnDvarFloatValue" "some_dvar" "1" "some_command" ; )"); +} - TEST_CASE("EventHandlerSetScopeSequences: Ensure can use scriptMenuRespondOnDvarStringValue", "[parsing][sequence][menu]") - { - TestGenericScriptStatement( - { - SimpleParserValue::Identifier(TokenPos(), new std::string("scriptMenuRespondOnDvarStringValue")), - SimpleParserValue::String(TokenPos(), new std::string("some_dvar")), - SimpleParserValue::String(TokenPos(), new std::string("some_value")), - SimpleParserValue::String(TokenPos(), new std::string("some_response")) - }, R"("scriptMenuRespondOnDvarStringValue" "some_dvar" "some_value" "some_response" ; )"); - } +TEST_CASE("EventHandlerSetScopeSequences: Ensure can use play", "[parsing][sequence][menu]") { + TestGenericScriptStatement( + {SimpleParserValue::Identifier(TokenPos(), new std::string("play")), SimpleParserValue::String(TokenPos(), new std::string("some_sound"))}, + R"("play" "some_sound" ; )"); +} - TEST_CASE("EventHandlerSetScopeSequences: Ensure can use scriptMenuRespondOnDvarIntValue", "[parsing][sequence][menu]") - { - TestGenericScriptStatement( - { - SimpleParserValue::Identifier(TokenPos(), new std::string("scriptMenuRespondOnDvarIntValue")), - SimpleParserValue::String(TokenPos(), new std::string("some_dvar")), - SimpleParserValue::Integer(TokenPos(), 1), - SimpleParserValue::String(TokenPos(), new std::string("some_response")) - }, R"("scriptMenuRespondOnDvarIntValue" "some_dvar" "1" "some_response" ; )"); - } +TEST_CASE("EventHandlerSetScopeSequences: Ensure can use scriptMenuResponse", "[parsing][sequence][menu]") { + TestGenericScriptStatement({SimpleParserValue::Identifier(TokenPos(), new std::string("scriptMenuResponse")), + SimpleParserValue::String(TokenPos(), new std::string("some_response"))}, + R"("scriptMenuResponse" "some_response" ; )"); +} - TEST_CASE("EventHandlerSetScopeSequences: Ensure can use scriptMenuRespondOnDvarFloatValue", "[parsing][sequence][menu]") - { - TestGenericScriptStatement( - { - SimpleParserValue::Identifier(TokenPos(), new std::string("scriptMenuRespondOnDvarFloatValue")), - SimpleParserValue::String(TokenPos(), new std::string("some_dvar")), - SimpleParserValue::Integer(TokenPos(), 1), - SimpleParserValue::String(TokenPos(), new std::string("some_response")) - }, R"("scriptMenuRespondOnDvarFloatValue" "some_dvar" "1" "some_response" ; )"); - } +TEST_CASE("EventHandlerSetScopeSequences: Ensure can use scriptMenuRespondOnDvarStringValue", "[parsing][sequence][menu]") { + TestGenericScriptStatement({SimpleParserValue::Identifier(TokenPos(), new std::string("scriptMenuRespondOnDvarStringValue")), + SimpleParserValue::String(TokenPos(), new std::string("some_dvar")), + SimpleParserValue::String(TokenPos(), new std::string("some_value")), + SimpleParserValue::String(TokenPos(), new std::string("some_response"))}, + R"("scriptMenuRespondOnDvarStringValue" "some_dvar" "some_value" "some_response" ; )"); +} - TEST_CASE("EventHandlerSetScopeSequences: Ensure can use updateMail", "[parsing][sequence][menu]") - { - TestGenericScriptStatement( - { - SimpleParserValue::Identifier(TokenPos(), new std::string("updateMail")) - }, R"("updateMail" ; )"); - } +TEST_CASE("EventHandlerSetScopeSequences: Ensure can use scriptMenuRespondOnDvarIntValue", "[parsing][sequence][menu]") { + TestGenericScriptStatement({SimpleParserValue::Identifier(TokenPos(), new std::string("scriptMenuRespondOnDvarIntValue")), + SimpleParserValue::String(TokenPos(), new std::string("some_dvar")), SimpleParserValue::Integer(TokenPos(), 1), + SimpleParserValue::String(TokenPos(), new std::string("some_response"))}, + R"("scriptMenuRespondOnDvarIntValue" "some_dvar" "1" "some_response" ; )"); +} - TEST_CASE("EventHandlerSetScopeSequences: Ensure can use openMail", "[parsing][sequence][menu]") - { - TestGenericScriptStatement( - { - SimpleParserValue::Identifier(TokenPos(), new std::string("openMail")) - }, R"("openMail" ; )"); - } +TEST_CASE("EventHandlerSetScopeSequences: Ensure can use scriptMenuRespondOnDvarFloatValue", "[parsing][sequence][menu]") { + TestGenericScriptStatement({SimpleParserValue::Identifier(TokenPos(), new std::string("scriptMenuRespondOnDvarFloatValue")), + SimpleParserValue::String(TokenPos(), new std::string("some_dvar")), SimpleParserValue::Integer(TokenPos(), 1), + SimpleParserValue::String(TokenPos(), new std::string("some_response"))}, + R"("scriptMenuRespondOnDvarFloatValue" "some_dvar" "1" "some_response" ; )"); +} - TEST_CASE("EventHandlerSetScopeSequences: Ensure can use deleteMail", "[parsing][sequence][menu]") - { - TestGenericScriptStatement( - { - SimpleParserValue::Identifier(TokenPos(), new std::string("deleteMail")) - }, R"("deleteMail" ; )"); - } +TEST_CASE("EventHandlerSetScopeSequences: Ensure can use updateMail", "[parsing][sequence][menu]") { + TestGenericScriptStatement({SimpleParserValue::Identifier(TokenPos(), new std::string("updateMail"))}, R"("updateMail" ; )"); +} - TEST_CASE("EventHandlerSetScopeSequences: Ensure can use doMailLottery", "[parsing][sequence][menu]") - { - TestGenericScriptStatement( - { - SimpleParserValue::Identifier(TokenPos(), new std::string("doMailLottery")) - }, R"("doMailLottery" ; )"); - } +TEST_CASE("EventHandlerSetScopeSequences: Ensure can use openMail", "[parsing][sequence][menu]") { + TestGenericScriptStatement({SimpleParserValue::Identifier(TokenPos(), new std::string("openMail"))}, R"("openMail" ; )"); +} - TEST_CASE("EventHandlerSetScopeSequences: Ensure can use resetStatsConfirm", "[parsing][sequence][menu]") - { - TestGenericScriptStatement( - { - SimpleParserValue::Identifier(TokenPos(), new std::string("resetStatsConfirm")) - }, R"("resetStatsConfirm" ; )"); - } +TEST_CASE("EventHandlerSetScopeSequences: Ensure can use deleteMail", "[parsing][sequence][menu]") { + TestGenericScriptStatement({SimpleParserValue::Identifier(TokenPos(), new std::string("deleteMail"))}, R"("deleteMail" ; )"); +} - TEST_CASE("EventHandlerSetScopeSequences: Ensure can use resetStatsCancel", "[parsing][sequence][menu]") - { - TestGenericScriptStatement( - { - SimpleParserValue::Identifier(TokenPos(), new std::string("resetStatsCancel")) - }, R"("resetStatsCancel" ; )"); - } +TEST_CASE("EventHandlerSetScopeSequences: Ensure can use doMailLottery", "[parsing][sequence][menu]") { + TestGenericScriptStatement({SimpleParserValue::Identifier(TokenPos(), new std::string("doMailLottery"))}, R"("doMailLottery" ; )"); +} - TEST_CASE("EventHandlerSetScopeSequences: Ensure can use setGameMode", "[parsing][sequence][menu]") - { - TestGenericScriptStatement( - { - SimpleParserValue::Identifier(TokenPos(), new std::string("setGameMode")), - SimpleParserValue::String(TokenPos(), new std::string("some_game_mode")) - }, R"("setGameMode" "some_game_mode" ; )"); - } +TEST_CASE("EventHandlerSetScopeSequences: Ensure can use resetStatsConfirm", "[parsing][sequence][menu]") { + TestGenericScriptStatement({SimpleParserValue::Identifier(TokenPos(), new std::string("resetStatsConfirm"))}, R"("resetStatsConfirm" ; )"); +} - TEST_CASE("EventHandlerSetScopeSequences: Ensure can use feederTop", "[parsing][sequence][menu]") - { - TestGenericScriptStatement( - { - SimpleParserValue::Identifier(TokenPos(), new std::string("feederTop")) - }, R"("feederTop" ; )"); - } +TEST_CASE("EventHandlerSetScopeSequences: Ensure can use resetStatsCancel", "[parsing][sequence][menu]") { + TestGenericScriptStatement({SimpleParserValue::Identifier(TokenPos(), new std::string("resetStatsCancel"))}, R"("resetStatsCancel" ; )"); +} - TEST_CASE("EventHandlerSetScopeSequences: Ensure can use feederBottom", "[parsing][sequence][menu]") - { - TestGenericScriptStatement( - { - SimpleParserValue::Identifier(TokenPos(), new std::string("feederBottom")) - }, R"("feederBottom" ; )"); - } +TEST_CASE("EventHandlerSetScopeSequences: Ensure can use setGameMode", "[parsing][sequence][menu]") { + TestGenericScriptStatement( + {SimpleParserValue::Identifier(TokenPos(), new std::string("setGameMode")), SimpleParserValue::String(TokenPos(), new std::string("some_game_mode"))}, + R"("setGameMode" "some_game_mode" ; )"); +} - TEST_CASE("EventHandlerSetScopeSequences: Ensure can use showGamerCard", "[parsing][sequence][menu]") - { - TestGenericScriptStatement( - { - SimpleParserValue::Identifier(TokenPos(), new std::string("showGamerCard")) - }, R"("showGamerCard" ; )"); - } +TEST_CASE("EventHandlerSetScopeSequences: Ensure can use feederTop", "[parsing][sequence][menu]") { + TestGenericScriptStatement({SimpleParserValue::Identifier(TokenPos(), new std::string("feederTop"))}, R"("feederTop" ; )"); +} - TEST_CASE("EventHandlerSetScopeSequences: Ensure can use openForGameType", "[parsing][sequence][menu]") - { - TestGenericScriptStatement( - { - SimpleParserValue::Identifier(TokenPos(), new std::string("openForGameType")), - SimpleParserValue::String(TokenPos(), new std::string("some_game_type")) - }, R"("openForGameType" "some_game_type" ; )"); - } +TEST_CASE("EventHandlerSetScopeSequences: Ensure can use feederBottom", "[parsing][sequence][menu]") { + TestGenericScriptStatement({SimpleParserValue::Identifier(TokenPos(), new std::string("feederBottom"))}, R"("feederBottom" ; )"); +} - TEST_CASE("EventHandlerSetScopeSequences: Ensure can use closeForGameType", "[parsing][sequence][menu]") - { - TestGenericScriptStatement( - { - SimpleParserValue::Identifier(TokenPos(), new std::string("closeForGameType")), - SimpleParserValue::String(TokenPos(), new std::string("some_game_type")) - }, R"("closeForGameType" "some_game_type" ; )"); - } +TEST_CASE("EventHandlerSetScopeSequences: Ensure can use showGamerCard", "[parsing][sequence][menu]") { + TestGenericScriptStatement({SimpleParserValue::Identifier(TokenPos(), new std::string("showGamerCard"))}, R"("showGamerCard" ; )"); +} - TEST_CASE("EventHandlerSetScopeSequences: Ensure can use kickPlayer", "[parsing][sequence][menu]") - { - TestGenericScriptStatement( - { - SimpleParserValue::Identifier(TokenPos(), new std::string("kickPlayer")) - }, R"("kickPlayer" ; )"); - } +TEST_CASE("EventHandlerSetScopeSequences: Ensure can use openForGameType", "[parsing][sequence][menu]") { + TestGenericScriptStatement( + {SimpleParserValue::Identifier(TokenPos(), new std::string("openForGameType")), SimpleParserValue::String(TokenPos(), new std::string("some_game_type"))}, + R"("openForGameType" "some_game_type" ; )"); +} - TEST_CASE("EventHandlerSetScopeSequences: Ensure can use getKickPlayerQuestion", "[parsing][sequence][menu]") - { - TestGenericScriptStatement( - { - SimpleParserValue::Identifier(TokenPos(), new std::string("getKickPlayerQuestion")) - }, R"("getKickPlayerQuestion" ; )"); - } +TEST_CASE("EventHandlerSetScopeSequences: Ensure can use closeForGameType", "[parsing][sequence][menu]") { + TestGenericScriptStatement({SimpleParserValue::Identifier(TokenPos(), new std::string("closeForGameType")), + SimpleParserValue::String(TokenPos(), new std::string("some_game_type"))}, + R"("closeForGameType" "some_game_type" ; )"); +} - TEST_CASE("EventHandlerSetScopeSequences: Ensure can use partyUpdateMissingMapPackDvar", "[parsing][sequence][menu]") - { - TestGenericScriptStatement( - { - SimpleParserValue::Identifier(TokenPos(), new std::string("partyUpdateMissingMapPackDvar")) - }, R"("partyUpdateMissingMapPackDvar" ; )"); - } +TEST_CASE("EventHandlerSetScopeSequences: Ensure can use kickPlayer", "[parsing][sequence][menu]") { + TestGenericScriptStatement({SimpleParserValue::Identifier(TokenPos(), new std::string("kickPlayer"))}, R"("kickPlayer" ; )"); +} - TEST_CASE("EventHandlerSetScopeSequences: Ensure can use togglePlayerMute", "[parsing][sequence][menu]") - { - TestGenericScriptStatement( - { - SimpleParserValue::Identifier(TokenPos(), new std::string("togglePlayerMute")) - }, R"("togglePlayerMute" ; )"); - } +TEST_CASE("EventHandlerSetScopeSequences: Ensure can use getKickPlayerQuestion", "[parsing][sequence][menu]") { + TestGenericScriptStatement({SimpleParserValue::Identifier(TokenPos(), new std::string("getKickPlayerQuestion"))}, R"("getKickPlayerQuestion" ; )"); +} - TEST_CASE("EventHandlerSetScopeSequences: Ensure can use resolveError", "[parsing][sequence][menu]") - { - TestGenericScriptStatement( - { - SimpleParserValue::Identifier(TokenPos(), new std::string("resolveError")) - }, R"("resolveError" ; )"); - } +TEST_CASE("EventHandlerSetScopeSequences: Ensure can use partyUpdateMissingMapPackDvar", "[parsing][sequence][menu]") { + TestGenericScriptStatement({SimpleParserValue::Identifier(TokenPos(), new std::string("partyUpdateMissingMapPackDvar"))}, + R"("partyUpdateMissingMapPackDvar" ; )"); +} - TEST_CASE("EventHandlerSetScopeSequences: Ensure can use lerp scale", "[parsing][sequence][menu]") - { - TestGenericScriptStatement( - { - SimpleParserValue::Identifier(TokenPos(), new std::string("lerp")), - SimpleParserValue::Identifier(TokenPos(), new std::string("scale")), - SimpleParserValue::Identifier(TokenPos(), new std::string("from")), - SimpleParserValue::Integer(TokenPos(), 1), - SimpleParserValue::Identifier(TokenPos(), new std::string("to")), - SimpleParserValue::Integer(TokenPos(), 2), - SimpleParserValue::Identifier(TokenPos(), new std::string("over")), - SimpleParserValue::Integer(TokenPos(), 3), - }, R"("lerp" "scale" "from" "1" "to" "2" "over" "3" ; )"); - } +TEST_CASE("EventHandlerSetScopeSequences: Ensure can use togglePlayerMute", "[parsing][sequence][menu]") { + TestGenericScriptStatement({SimpleParserValue::Identifier(TokenPos(), new std::string("togglePlayerMute"))}, R"("togglePlayerMute" ; )"); +} - TEST_CASE("EventHandlerSetScopeSequences: Ensure can use lerp alpha", "[parsing][sequence][menu]") - { - TestGenericScriptStatement( - { - SimpleParserValue::Identifier(TokenPos(), new std::string("lerp")), - SimpleParserValue::Identifier(TokenPos(), new std::string("alpha")), - SimpleParserValue::Identifier(TokenPos(), new std::string("from")), - SimpleParserValue::Integer(TokenPos(), 1), - SimpleParserValue::Identifier(TokenPos(), new std::string("to")), - SimpleParserValue::Integer(TokenPos(), 2), - SimpleParserValue::Identifier(TokenPos(), new std::string("over")), - SimpleParserValue::Integer(TokenPos(), 3), - }, R"("lerp" "alpha" "from" "1" "to" "2" "over" "3" ; )"); - } +TEST_CASE("EventHandlerSetScopeSequences: Ensure can use resolveError", "[parsing][sequence][menu]") { + TestGenericScriptStatement({SimpleParserValue::Identifier(TokenPos(), new std::string("resolveError"))}, R"("resolveError" ; )"); +} - TEST_CASE("EventHandlerSetScopeSequences: Ensure can use lerp x", "[parsing][sequence][menu]") - { - TestGenericScriptStatement( - { - SimpleParserValue::Identifier(TokenPos(), new std::string("lerp")), - SimpleParserValue::Identifier(TokenPos(), new std::string("x")), - SimpleParserValue::Identifier(TokenPos(), new std::string("from")), - SimpleParserValue::Integer(TokenPos(), 1), - SimpleParserValue::Identifier(TokenPos(), new std::string("to")), - SimpleParserValue::Integer(TokenPos(), 2), - SimpleParserValue::Identifier(TokenPos(), new std::string("over")), - SimpleParserValue::Integer(TokenPos(), 3), - }, R"("lerp" "x" "from" "1" "to" "2" "over" "3" ; )"); - } +TEST_CASE("EventHandlerSetScopeSequences: Ensure can use lerp scale", "[parsing][sequence][menu]") { + TestGenericScriptStatement( + { + SimpleParserValue::Identifier(TokenPos(), new std::string("lerp")), + SimpleParserValue::Identifier(TokenPos(), new std::string("scale")), + SimpleParserValue::Identifier(TokenPos(), new std::string("from")), + SimpleParserValue::Integer(TokenPos(), 1), + SimpleParserValue::Identifier(TokenPos(), new std::string("to")), + SimpleParserValue::Integer(TokenPos(), 2), + SimpleParserValue::Identifier(TokenPos(), new std::string("over")), + SimpleParserValue::Integer(TokenPos(), 3), + }, + R"("lerp" "scale" "from" "1" "to" "2" "over" "3" ; )"); +} - TEST_CASE("EventHandlerSetScopeSequences: Ensure can use lerp y", "[parsing][sequence][menu]") - { - TestGenericScriptStatement( - { - SimpleParserValue::Identifier(TokenPos(), new std::string("lerp")), - SimpleParserValue::Identifier(TokenPos(), new std::string("y")), - SimpleParserValue::Identifier(TokenPos(), new std::string("from")), - SimpleParserValue::Integer(TokenPos(), 1), - SimpleParserValue::Identifier(TokenPos(), new std::string("to")), - SimpleParserValue::Integer(TokenPos(), 2), - SimpleParserValue::Identifier(TokenPos(), new std::string("over")), - SimpleParserValue::Integer(TokenPos(), 3), - }, R"("lerp" "y" "from" "1" "to" "2" "over" "3" ; )"); - } +TEST_CASE("EventHandlerSetScopeSequences: Ensure can use lerp alpha", "[parsing][sequence][menu]") { + TestGenericScriptStatement( + { + SimpleParserValue::Identifier(TokenPos(), new std::string("lerp")), + SimpleParserValue::Identifier(TokenPos(), new std::string("alpha")), + SimpleParserValue::Identifier(TokenPos(), new std::string("from")), + SimpleParserValue::Integer(TokenPos(), 1), + SimpleParserValue::Identifier(TokenPos(), new std::string("to")), + SimpleParserValue::Integer(TokenPos(), 2), + SimpleParserValue::Identifier(TokenPos(), new std::string("over")), + SimpleParserValue::Integer(TokenPos(), 3), + }, + R"("lerp" "alpha" "from" "1" "to" "2" "over" "3" ; )"); +} - TEST_CASE("EventHandlerSetScopeSequences: Ensure can use setPlayerData", "[parsing][sequence][menu]") - { - TestGenericScriptStatement( - { - SimpleParserValue::Identifier(TokenPos(), new std::string("setPlayerData")), - SimpleParserValue::Character(TokenPos(), '('), - SimpleParserValue::Identifier(TokenPos(), new std::string("customClasses")), - SimpleParserValue::Character(TokenPos(), ','), - SimpleParserValue::Identifier(TokenPos(), new std::string("localVarInt")), - SimpleParserValue::Character(TokenPos(), '('), - SimpleParserValue::Identifier(TokenPos(), new std::string("classIndex")), - SimpleParserValue::Character(TokenPos(), ')'), - SimpleParserValue::Character(TokenPos(), ','), - SimpleParserValue::String(TokenPos(), new std::string("perks")), - SimpleParserValue::Character(TokenPos(), ','), - SimpleParserValue::Integer(TokenPos(), 0), - SimpleParserValue::Character(TokenPos(), ','), - SimpleParserValue::Identifier(TokenPos(), new std::string("speciality_null")), - SimpleParserValue::Character(TokenPos(), ')'), - }, R"("setPlayerData" ( "customClasses" , "localVarInt" ( "classIndex" ) , "perks" , "0" , "speciality_null" ) ; )"); - } +TEST_CASE("EventHandlerSetScopeSequences: Ensure can use lerp x", "[parsing][sequence][menu]") { + TestGenericScriptStatement( + { + SimpleParserValue::Identifier(TokenPos(), new std::string("lerp")), + SimpleParserValue::Identifier(TokenPos(), new std::string("x")), + SimpleParserValue::Identifier(TokenPos(), new std::string("from")), + SimpleParserValue::Integer(TokenPos(), 1), + SimpleParserValue::Identifier(TokenPos(), new std::string("to")), + SimpleParserValue::Integer(TokenPos(), 2), + SimpleParserValue::Identifier(TokenPos(), new std::string("over")), + SimpleParserValue::Integer(TokenPos(), 3), + }, + R"("lerp" "x" "from" "1" "to" "2" "over" "3" ; )"); +} + +TEST_CASE("EventHandlerSetScopeSequences: Ensure can use lerp y", "[parsing][sequence][menu]") { + TestGenericScriptStatement( + { + SimpleParserValue::Identifier(TokenPos(), new std::string("lerp")), + SimpleParserValue::Identifier(TokenPos(), new std::string("y")), + SimpleParserValue::Identifier(TokenPos(), new std::string("from")), + SimpleParserValue::Integer(TokenPos(), 1), + SimpleParserValue::Identifier(TokenPos(), new std::string("to")), + SimpleParserValue::Integer(TokenPos(), 2), + SimpleParserValue::Identifier(TokenPos(), new std::string("over")), + SimpleParserValue::Integer(TokenPos(), 3), + }, + R"("lerp" "y" "from" "1" "to" "2" "over" "3" ; )"); +} + +TEST_CASE("EventHandlerSetScopeSequences: Ensure can use setPlayerData", "[parsing][sequence][menu]") { + TestGenericScriptStatement( + { + SimpleParserValue::Identifier(TokenPos(), new std::string("setPlayerData")), + SimpleParserValue::Character(TokenPos(), '('), + SimpleParserValue::Identifier(TokenPos(), new std::string("customClasses")), + SimpleParserValue::Character(TokenPos(), ','), + SimpleParserValue::Identifier(TokenPos(), new std::string("localVarInt")), + SimpleParserValue::Character(TokenPos(), '('), + SimpleParserValue::Identifier(TokenPos(), new std::string("classIndex")), + SimpleParserValue::Character(TokenPos(), ')'), + SimpleParserValue::Character(TokenPos(), ','), + SimpleParserValue::String(TokenPos(), new std::string("perks")), + SimpleParserValue::Character(TokenPos(), ','), + SimpleParserValue::Integer(TokenPos(), 0), + SimpleParserValue::Character(TokenPos(), ','), + SimpleParserValue::Identifier(TokenPos(), new std::string("speciality_null")), + SimpleParserValue::Character(TokenPos(), ')'), + }, + R"("setPlayerData" ( "customClasses" , "localVarInt" ( "classIndex" ) , "perks" , "0" , "speciality_null" ) ; )"); +} #pragma endregion #pragma region Unit Tests for setLocalVar - TEST_CASE("EventHandlerSetScopeSequences: Ensure setLocalVarBool is script on static value", "[parsing][sequence][menu]") - { - TestGenericScriptStatement( - { - SimpleParserValue::Identifier(TokenPos(), new std::string("setLocalVarBool")), - SimpleParserValue::Identifier(TokenPos(), new std::string("sample_var")), - SimpleParserValue::Integer(TokenPos(), 1339), - SimpleParserValue::Character(TokenPos(), '-'), - SimpleParserValue::Integer(TokenPos(), 2), - }, R"("setLocalVarBool" "sample_var" "1337" ; )"); - } +TEST_CASE("EventHandlerSetScopeSequences: Ensure setLocalVarBool is script on static value", "[parsing][sequence][menu]") { + TestGenericScriptStatement( + { + SimpleParserValue::Identifier(TokenPos(), new std::string("setLocalVarBool")), + SimpleParserValue::Identifier(TokenPos(), new std::string("sample_var")), + SimpleParserValue::Integer(TokenPos(), 1339), + SimpleParserValue::Character(TokenPos(), '-'), + SimpleParserValue::Integer(TokenPos(), 2), + }, + R"("setLocalVarBool" "sample_var" "1337" ; )"); +} - TEST_CASE("EventHandlerSetScopeSequences: Ensure setLocalVarInt is script on static value", "[parsing][sequence][menu]") - { - TestGenericScriptStatement( - { - SimpleParserValue::Identifier(TokenPos(), new std::string("setLocalVarInt")), - SimpleParserValue::Identifier(TokenPos(), new std::string("sample_var")), - SimpleParserValue::Integer(TokenPos(), 1339), - SimpleParserValue::Character(TokenPos(), '-'), - SimpleParserValue::Integer(TokenPos(), 2), - }, R"("setLocalVarInt" "sample_var" "1337" ; )"); - } +TEST_CASE("EventHandlerSetScopeSequences: Ensure setLocalVarInt is script on static value", "[parsing][sequence][menu]") { + TestGenericScriptStatement( + { + SimpleParserValue::Identifier(TokenPos(), new std::string("setLocalVarInt")), + SimpleParserValue::Identifier(TokenPos(), new std::string("sample_var")), + SimpleParserValue::Integer(TokenPos(), 1339), + SimpleParserValue::Character(TokenPos(), '-'), + SimpleParserValue::Integer(TokenPos(), 2), + }, + R"("setLocalVarInt" "sample_var" "1337" ; )"); +} - TEST_CASE("EventHandlerSetScopeSequences: Ensure setLocalVarString is script on static value", "[parsing][sequence][menu]") - { - TestGenericScriptStatement( - { - SimpleParserValue::Identifier(TokenPos(), new std::string("setLocalVarString")), - SimpleParserValue::Identifier(TokenPos(), new std::string("sample_var")), - SimpleParserValue::String(TokenPos(), new std::string("Hello")), - SimpleParserValue::Character(TokenPos(), '+'), - SimpleParserValue::String(TokenPos(), new std::string(" ")), - SimpleParserValue::Character(TokenPos(), '+'), - SimpleParserValue::String(TokenPos(), new std::string("World")), - }, R"("setLocalVarString" "sample_var" "Hello World" ; )"); - } +TEST_CASE("EventHandlerSetScopeSequences: Ensure setLocalVarString is script on static value", "[parsing][sequence][menu]") { + TestGenericScriptStatement( + { + SimpleParserValue::Identifier(TokenPos(), new std::string("setLocalVarString")), + SimpleParserValue::Identifier(TokenPos(), new std::string("sample_var")), + SimpleParserValue::String(TokenPos(), new std::string("Hello")), + SimpleParserValue::Character(TokenPos(), '+'), + SimpleParserValue::String(TokenPos(), new std::string(" ")), + SimpleParserValue::Character(TokenPos(), '+'), + SimpleParserValue::String(TokenPos(), new std::string("World")), + }, + R"("setLocalVarString" "sample_var" "Hello World" ; )"); +} - TEST_CASE("EventHandlerSetScopeSequences: Ensure setLocalVarBool is setLocalVar handler on non-static value", "[parsing][sequence][menu]") - { - EventHandlerSetSequenceTestsHelper helper(FeatureLevel::IW4, false); - const TokenPos pos; - helper.Tokens({ - SimpleParserValue::Identifier(TokenPos(), new std::string("setLocalVarBool")), - SimpleParserValue::Identifier(TokenPos(), new std::string("sample_var")), - SimpleParserValue::Identifier(TokenPos(), new std::string("milliseconds")), - SimpleParserValue::Character(TokenPos(), '('), - SimpleParserValue::Character(TokenPos(), ')'), - SimpleParserValue::Character(TokenPos(), '%'), - SimpleParserValue::Integer(TokenPos(), 2), - SimpleParserValue::Character(TokenPos(), ';'), - SimpleParserValue::EndOfFile(pos) - }); - - const auto result = helper.PerformTest(); - REQUIRE(result); - REQUIRE(helper.m_consumed_token_count == 8); - - REQUIRE(helper.m_event_handler_set->m_elements.size() == 1); - - const auto* firstElement = helper.m_event_handler_set->m_elements[0].get(); - - REQUIRE(firstElement->GetType() == CommonEventHandlerElementType::SET_LOCAL_VAR); - - const auto* setLocalVarElement = dynamic_cast<const CommonEventHandlerSetLocalVar*>(firstElement); - REQUIRE(setLocalVarElement != nullptr); - - REQUIRE(setLocalVarElement->m_type == SetLocalVarType::BOOL); - REQUIRE(setLocalVarElement->m_var_name == "sample_var"); - REQUIRE(setLocalVarElement->m_value); - REQUIRE(setLocalVarElement->m_value->IsStatic() == false); - } +TEST_CASE("EventHandlerSetScopeSequences: Ensure setLocalVarBool is setLocalVar handler on non-static value", "[parsing][sequence][menu]") { + EventHandlerSetSequenceTestsHelper helper(FeatureLevel::IW4, false); + const TokenPos pos; + helper.Tokens({SimpleParserValue::Identifier(TokenPos(), new std::string("setLocalVarBool")), + SimpleParserValue::Identifier(TokenPos(), new std::string("sample_var")), + SimpleParserValue::Identifier(TokenPos(), new std::string("milliseconds")), SimpleParserValue::Character(TokenPos(), '('), + SimpleParserValue::Character(TokenPos(), ')'), SimpleParserValue::Character(TokenPos(), '%'), SimpleParserValue::Integer(TokenPos(), 2), + SimpleParserValue::Character(TokenPos(), ';'), SimpleParserValue::EndOfFile(pos)}); - TEST_CASE("EventHandlerSetScopeSequences: Ensure setLocalVarInt is setLocalVar handler on non-static value", "[parsing][sequence][menu]") - { - EventHandlerSetSequenceTestsHelper helper(FeatureLevel::IW4, false); - const TokenPos pos; - helper.Tokens({ - SimpleParserValue::Identifier(TokenPos(), new std::string("setLocalVarInt")), - SimpleParserValue::Identifier(TokenPos(), new std::string("sample_var")), - SimpleParserValue::Identifier(TokenPos(), new std::string("milliseconds")), - SimpleParserValue::Character(TokenPos(), '('), - SimpleParserValue::Character(TokenPos(), ')'), - SimpleParserValue::Character(TokenPos(), '*'), - SimpleParserValue::Integer(TokenPos(), 2), - SimpleParserValue::Character(TokenPos(), ';'), - SimpleParserValue::EndOfFile(pos) - }); - - const auto result = helper.PerformTest(); - REQUIRE(result); - REQUIRE(helper.m_consumed_token_count == 8); - - REQUIRE(helper.m_event_handler_set->m_elements.size() == 1); - - const auto* firstElement = helper.m_event_handler_set->m_elements[0].get(); - - REQUIRE(firstElement->GetType() == CommonEventHandlerElementType::SET_LOCAL_VAR); - - const auto* setLocalVarElement = dynamic_cast<const CommonEventHandlerSetLocalVar*>(firstElement); - REQUIRE(setLocalVarElement != nullptr); - - REQUIRE(setLocalVarElement->m_type == SetLocalVarType::INT); - REQUIRE(setLocalVarElement->m_var_name == "sample_var"); - REQUIRE(setLocalVarElement->m_value); - REQUIRE(setLocalVarElement->m_value->IsStatic() == false); - } + const auto result = helper.PerformTest(); + REQUIRE(result); + REQUIRE(helper.m_consumed_token_count == 8); - TEST_CASE("EventHandlerSetScopeSequences: Ensure setLocalVarFloat is setLocalVar handler on non-static value", "[parsing][sequence][menu]") - { - EventHandlerSetSequenceTestsHelper helper(FeatureLevel::IW4, false); - const TokenPos pos; - helper.Tokens({ - SimpleParserValue::Identifier(TokenPos(), new std::string("setLocalVarFloat")), - SimpleParserValue::Identifier(TokenPos(), new std::string("sample_var")), - SimpleParserValue::Identifier(TokenPos(), new std::string("milliseconds")), - SimpleParserValue::Character(TokenPos(), '('), - SimpleParserValue::Character(TokenPos(), ')'), - SimpleParserValue::Character(TokenPos(), '/'), - SimpleParserValue::Integer(TokenPos(), 2), - SimpleParserValue::Character(TokenPos(), ';'), - SimpleParserValue::EndOfFile(pos) - }); - - const auto result = helper.PerformTest(); - REQUIRE(result); - REQUIRE(helper.m_consumed_token_count == 8); - - REQUIRE(helper.m_event_handler_set->m_elements.size() == 1); - - const auto* firstElement = helper.m_event_handler_set->m_elements[0].get(); - - REQUIRE(firstElement->GetType() == CommonEventHandlerElementType::SET_LOCAL_VAR); - - const auto* setLocalVarElement = dynamic_cast<const CommonEventHandlerSetLocalVar*>(firstElement); - REQUIRE(setLocalVarElement != nullptr); - - REQUIRE(setLocalVarElement->m_type == SetLocalVarType::FLOAT); - REQUIRE(setLocalVarElement->m_var_name == "sample_var"); - REQUIRE(setLocalVarElement->m_value); - REQUIRE(setLocalVarElement->m_value->IsStatic() == false); - } + REQUIRE(helper.m_event_handler_set->m_elements.size() == 1); - TEST_CASE("EventHandlerSetScopeSequences: Ensure setLocalVarString is setLocalVar handler on non-static value", "[parsing][sequence][menu]") - { - EventHandlerSetSequenceTestsHelper helper(FeatureLevel::IW4, false); - const TokenPos pos; - helper.Tokens({ - SimpleParserValue::Identifier(TokenPos(), new std::string("setLocalVarString")), - SimpleParserValue::Identifier(TokenPos(), new std::string("sample_var")), - SimpleParserValue::Identifier(TokenPos(), new std::string("milliseconds")), - SimpleParserValue::Character(TokenPos(), '('), - SimpleParserValue::Character(TokenPos(), ')'), - SimpleParserValue::Character(TokenPos(), '+'), - SimpleParserValue::String(TokenPos(), new std::string(" Hello")), - SimpleParserValue::Character(TokenPos(), ';'), - SimpleParserValue::EndOfFile(pos) - }); - - const auto result = helper.PerformTest(); - REQUIRE(result); - REQUIRE(helper.m_consumed_token_count == 8); - - REQUIRE(helper.m_event_handler_set->m_elements.size() == 1); - - const auto* firstElement = helper.m_event_handler_set->m_elements[0].get(); - - REQUIRE(firstElement->GetType() == CommonEventHandlerElementType::SET_LOCAL_VAR); - - const auto* setLocalVarElement = dynamic_cast<const CommonEventHandlerSetLocalVar*>(firstElement); - REQUIRE(setLocalVarElement != nullptr); - - REQUIRE(setLocalVarElement->m_type == SetLocalVarType::STRING); - REQUIRE(setLocalVarElement->m_var_name == "sample_var"); - REQUIRE(setLocalVarElement->m_value); - REQUIRE(setLocalVarElement->m_value->IsStatic() == false); - } + const auto *firstElement = helper.m_event_handler_set->m_elements[0].get(); + + REQUIRE(firstElement->GetType() == CommonEventHandlerElementType::SET_LOCAL_VAR); + + const auto *setLocalVarElement = dynamic_cast<const CommonEventHandlerSetLocalVar *>(firstElement); + REQUIRE(setLocalVarElement != nullptr); + + REQUIRE(setLocalVarElement->m_type == SetLocalVarType::BOOL); + REQUIRE(setLocalVarElement->m_var_name == "sample_var"); + REQUIRE(setLocalVarElement->m_value); + REQUIRE(setLocalVarElement->m_value->IsStatic() == false); +} + +TEST_CASE("EventHandlerSetScopeSequences: Ensure setLocalVarInt is setLocalVar handler on non-static value", "[parsing][sequence][menu]") { + EventHandlerSetSequenceTestsHelper helper(FeatureLevel::IW4, false); + const TokenPos pos; + helper.Tokens({SimpleParserValue::Identifier(TokenPos(), new std::string("setLocalVarInt")), + SimpleParserValue::Identifier(TokenPos(), new std::string("sample_var")), + SimpleParserValue::Identifier(TokenPos(), new std::string("milliseconds")), SimpleParserValue::Character(TokenPos(), '('), + SimpleParserValue::Character(TokenPos(), ')'), SimpleParserValue::Character(TokenPos(), '*'), SimpleParserValue::Integer(TokenPos(), 2), + SimpleParserValue::Character(TokenPos(), ';'), SimpleParserValue::EndOfFile(pos)}); + + const auto result = helper.PerformTest(); + REQUIRE(result); + REQUIRE(helper.m_consumed_token_count == 8); + + REQUIRE(helper.m_event_handler_set->m_elements.size() == 1); + + const auto *firstElement = helper.m_event_handler_set->m_elements[0].get(); + + REQUIRE(firstElement->GetType() == CommonEventHandlerElementType::SET_LOCAL_VAR); + + const auto *setLocalVarElement = dynamic_cast<const CommonEventHandlerSetLocalVar *>(firstElement); + REQUIRE(setLocalVarElement != nullptr); + + REQUIRE(setLocalVarElement->m_type == SetLocalVarType::INT); + REQUIRE(setLocalVarElement->m_var_name == "sample_var"); + REQUIRE(setLocalVarElement->m_value); + REQUIRE(setLocalVarElement->m_value->IsStatic() == false); +} + +TEST_CASE("EventHandlerSetScopeSequences: Ensure setLocalVarFloat is setLocalVar handler on non-static value", "[parsing][sequence][menu]") { + EventHandlerSetSequenceTestsHelper helper(FeatureLevel::IW4, false); + const TokenPos pos; + helper.Tokens({SimpleParserValue::Identifier(TokenPos(), new std::string("setLocalVarFloat")), + SimpleParserValue::Identifier(TokenPos(), new std::string("sample_var")), + SimpleParserValue::Identifier(TokenPos(), new std::string("milliseconds")), SimpleParserValue::Character(TokenPos(), '('), + SimpleParserValue::Character(TokenPos(), ')'), SimpleParserValue::Character(TokenPos(), '/'), SimpleParserValue::Integer(TokenPos(), 2), + SimpleParserValue::Character(TokenPos(), ';'), SimpleParserValue::EndOfFile(pos)}); + + const auto result = helper.PerformTest(); + REQUIRE(result); + REQUIRE(helper.m_consumed_token_count == 8); + + REQUIRE(helper.m_event_handler_set->m_elements.size() == 1); + + const auto *firstElement = helper.m_event_handler_set->m_elements[0].get(); + + REQUIRE(firstElement->GetType() == CommonEventHandlerElementType::SET_LOCAL_VAR); + + const auto *setLocalVarElement = dynamic_cast<const CommonEventHandlerSetLocalVar *>(firstElement); + REQUIRE(setLocalVarElement != nullptr); + + REQUIRE(setLocalVarElement->m_type == SetLocalVarType::FLOAT); + REQUIRE(setLocalVarElement->m_var_name == "sample_var"); + REQUIRE(setLocalVarElement->m_value); + REQUIRE(setLocalVarElement->m_value->IsStatic() == false); +} + +TEST_CASE("EventHandlerSetScopeSequences: Ensure setLocalVarString is setLocalVar handler on non-static value", "[parsing][sequence][menu]") { + EventHandlerSetSequenceTestsHelper helper(FeatureLevel::IW4, false); + const TokenPos pos; + helper.Tokens( + {SimpleParserValue::Identifier(TokenPos(), new std::string("setLocalVarString")), + SimpleParserValue::Identifier(TokenPos(), new std::string("sample_var")), SimpleParserValue::Identifier(TokenPos(), new std::string("milliseconds")), + SimpleParserValue::Character(TokenPos(), '('), SimpleParserValue::Character(TokenPos(), ')'), SimpleParserValue::Character(TokenPos(), '+'), + SimpleParserValue::String(TokenPos(), new std::string(" Hello")), SimpleParserValue::Character(TokenPos(), ';'), SimpleParserValue::EndOfFile(pos)}); + + const auto result = helper.PerformTest(); + REQUIRE(result); + REQUIRE(helper.m_consumed_token_count == 8); + + REQUIRE(helper.m_event_handler_set->m_elements.size() == 1); + + const auto *firstElement = helper.m_event_handler_set->m_elements[0].get(); + + REQUIRE(firstElement->GetType() == CommonEventHandlerElementType::SET_LOCAL_VAR); + + const auto *setLocalVarElement = dynamic_cast<const CommonEventHandlerSetLocalVar *>(firstElement); + REQUIRE(setLocalVarElement != nullptr); + + REQUIRE(setLocalVarElement->m_type == SetLocalVarType::STRING); + REQUIRE(setLocalVarElement->m_var_name == "sample_var"); + REQUIRE(setLocalVarElement->m_value); + REQUIRE(setLocalVarElement->m_value->IsStatic() == false); +} #pragma endregion #pragma region Unit Tests for If/ElseIf/Else/CloseBracket - TEST_CASE("EventHandlerSetScopeSequences: Closing block terminates EventHandlerSet", "[parsing][sequence][menu]") - { - EventHandlerSetSequenceTestsHelper helper(FeatureLevel::IW4, false); - const TokenPos pos; - helper.Tokens({ - SimpleParserValue::Character(pos, '}'), - SimpleParserValue::EndOfFile(pos) - }); - - const auto result = helper.PerformTest(); - - REQUIRE(result); - REQUIRE(helper.m_consumed_token_count == 1); - - const auto script = helper.m_state->m_current_script.str(); - REQUIRE(helper.m_state->m_current_event_handler_set == nullptr); - REQUIRE(helper.m_state->m_current_nested_event_handler_set == nullptr); - REQUIRE(helper.m_event_handler_set); - REQUIRE(helper.m_event_handler_set->m_elements.empty()); - } +TEST_CASE("EventHandlerSetScopeSequences: Closing block terminates EventHandlerSet", "[parsing][sequence][menu]") { + EventHandlerSetSequenceTestsHelper helper(FeatureLevel::IW4, false); + const TokenPos pos; + helper.Tokens({SimpleParserValue::Character(pos, '}'), SimpleParserValue::EndOfFile(pos)}); - TEST_CASE("EventHandlerSetScopeSequences: Closing block finishes current script", "[parsing][sequence][menu]") - { - EventHandlerSetSequenceTestsHelper helper(FeatureLevel::IW4, false); - const TokenPos pos; - helper.Tokens({ - SimpleParserValue::Character(pos, '}'), - SimpleParserValue::EndOfFile(pos) - }); + const auto result = helper.PerformTest(); - helper.m_state->m_current_script << R"("fadeIn" "some_element" ; )"; + REQUIRE(result); + REQUIRE(helper.m_consumed_token_count == 1); - const auto result = helper.PerformTest(); + const auto script = helper.m_state->m_current_script.str(); + REQUIRE(helper.m_state->m_current_event_handler_set == nullptr); + REQUIRE(helper.m_state->m_current_nested_event_handler_set == nullptr); + REQUIRE(helper.m_event_handler_set); + REQUIRE(helper.m_event_handler_set->m_elements.empty()); +} - REQUIRE(result); - REQUIRE(helper.m_consumed_token_count == 1); - REQUIRE(helper.m_state->m_current_event_handler_set == nullptr); - REQUIRE(helper.m_state->m_current_nested_event_handler_set == nullptr); - REQUIRE(helper.m_event_handler_set); - REQUIRE(helper.m_event_handler_set->m_elements.size() == 1); +TEST_CASE("EventHandlerSetScopeSequences: Closing block finishes current script", "[parsing][sequence][menu]") { + EventHandlerSetSequenceTestsHelper helper(FeatureLevel::IW4, false); + const TokenPos pos; + helper.Tokens({SimpleParserValue::Character(pos, '}'), SimpleParserValue::EndOfFile(pos)}); - const auto* firstElement = helper.m_event_handler_set->m_elements[0].get(); + helper.m_state->m_current_script << R"("fadeIn" "some_element" ; )"; - REQUIRE(firstElement->GetType() == CommonEventHandlerElementType::SCRIPT); + const auto result = helper.PerformTest(); - const auto* scriptElement = dynamic_cast<const CommonEventHandlerScript*>(firstElement); - REQUIRE(scriptElement != nullptr); - REQUIRE(scriptElement->m_script == R"("fadeIn" "some_element" ; )"); - } + REQUIRE(result); + REQUIRE(helper.m_consumed_token_count == 1); + REQUIRE(helper.m_state->m_current_event_handler_set == nullptr); + REQUIRE(helper.m_state->m_current_nested_event_handler_set == nullptr); + REQUIRE(helper.m_event_handler_set); + REQUIRE(helper.m_event_handler_set->m_elements.size() == 1); - TEST_CASE("EventHandlerSetScopeSequences: If opens new condition", "[parsing][sequence][menu]") - { - EventHandlerSetSequenceTestsHelper helper(FeatureLevel::IW4, false); - const TokenPos pos; - helper.Tokens({ - SimpleParserValue::Identifier(pos, new std::string("if")), - SimpleParserValue::Character(pos, '('), - SimpleParserValue::Integer(pos, 1336), - SimpleParserValue::Character(pos, '+'), - SimpleParserValue::Integer(pos, 1), - SimpleParserValue::Character(pos, ')'), - SimpleParserValue::Character(pos, '{'), - SimpleParserValue::EndOfFile(pos) - }); - - const auto result = helper.PerformTest(); - - REQUIRE(result); - REQUIRE(helper.m_consumed_token_count == 7); - REQUIRE(helper.m_state->m_current_event_handler_set == helper.m_event_handler_set.get()); - REQUIRE(helper.m_event_handler_set); - REQUIRE(helper.m_event_handler_set->m_elements.size() == 1); - - const auto* firstElement = helper.m_event_handler_set->m_elements[0].get(); - - REQUIRE(firstElement->GetType() == CommonEventHandlerElementType::CONDITION); - - const auto* conditionElement = dynamic_cast<const CommonEventHandlerCondition*>(firstElement); - REQUIRE(conditionElement != nullptr); - - REQUIRE(conditionElement->m_condition != nullptr); - REQUIRE(conditionElement->m_condition->IsStatic()); - const auto staticValue = conditionElement->m_condition->EvaluateStatic(); - REQUIRE(staticValue.m_type == SimpleExpressionValue::Type::INT); - REQUIRE(staticValue.m_int_value == 1337); - - REQUIRE(conditionElement->m_condition_elements); - REQUIRE(helper.m_state->m_current_nested_event_handler_set == conditionElement->m_condition_elements.get()); - REQUIRE(!conditionElement->m_else_elements); - - REQUIRE(helper.m_state->m_condition_stack.size() == 1); - REQUIRE(helper.m_state->m_condition_stack.top().m_condition == conditionElement); - REQUIRE(helper.m_state->m_condition_stack.top().m_auto_skip == false); - REQUIRE(helper.m_state->m_condition_stack.top().m_in_condition_elements == true); - } + const auto *firstElement = helper.m_event_handler_set->m_elements[0].get(); - TEST_CASE("EventHandlerSetScopeSequences: If applies current script", "[parsing][sequence][menu]") - { - EventHandlerSetSequenceTestsHelper helper(FeatureLevel::IW4, false); - const TokenPos pos; - helper.Tokens({ - SimpleParserValue::Identifier(pos, new std::string("if")), - SimpleParserValue::Character(pos, '('), - SimpleParserValue::Integer(pos, 420), - SimpleParserValue::Character(pos, ')'), - SimpleParserValue::Character(pos, '{'), - SimpleParserValue::EndOfFile(pos) - }); + REQUIRE(firstElement->GetType() == CommonEventHandlerElementType::SCRIPT); - helper.m_state->m_current_script << R"("fadeIn" "some_element" ; )"; + const auto *scriptElement = dynamic_cast<const CommonEventHandlerScript *>(firstElement); + REQUIRE(scriptElement != nullptr); + REQUIRE(scriptElement->m_script == R"("fadeIn" "some_element" ; )"); +} - const auto result = helper.PerformTest(); +TEST_CASE("EventHandlerSetScopeSequences: If opens new condition", "[parsing][sequence][menu]") { + EventHandlerSetSequenceTestsHelper helper(FeatureLevel::IW4, false); + const TokenPos pos; + helper.Tokens({SimpleParserValue::Identifier(pos, new std::string("if")), SimpleParserValue::Character(pos, '('), SimpleParserValue::Integer(pos, 1336), + SimpleParserValue::Character(pos, '+'), SimpleParserValue::Integer(pos, 1), SimpleParserValue::Character(pos, ')'), + SimpleParserValue::Character(pos, '{'), SimpleParserValue::EndOfFile(pos)}); - REQUIRE(result); - REQUIRE(helper.m_consumed_token_count == 5); - REQUIRE(helper.m_state->m_current_event_handler_set == helper.m_event_handler_set.get()); - REQUIRE(helper.m_event_handler_set); - REQUIRE(helper.m_event_handler_set->m_elements.size() == 2); + const auto result = helper.PerformTest(); - const auto* firstElement = helper.m_event_handler_set->m_elements[0].get(); + REQUIRE(result); + REQUIRE(helper.m_consumed_token_count == 7); + REQUIRE(helper.m_state->m_current_event_handler_set == helper.m_event_handler_set.get()); + REQUIRE(helper.m_event_handler_set); + REQUIRE(helper.m_event_handler_set->m_elements.size() == 1); - REQUIRE(firstElement->GetType() == CommonEventHandlerElementType::SCRIPT); + const auto *firstElement = helper.m_event_handler_set->m_elements[0].get(); - const auto* scriptElement = dynamic_cast<const CommonEventHandlerScript*>(firstElement); - REQUIRE(scriptElement != nullptr); - REQUIRE(scriptElement->m_script == R"("fadeIn" "some_element" ; )"); + REQUIRE(firstElement->GetType() == CommonEventHandlerElementType::CONDITION); - const auto* secondElement = helper.m_event_handler_set->m_elements[1].get(); + const auto *conditionElement = dynamic_cast<const CommonEventHandlerCondition *>(firstElement); + REQUIRE(conditionElement != nullptr); - REQUIRE(secondElement->GetType() == CommonEventHandlerElementType::CONDITION); + REQUIRE(conditionElement->m_condition != nullptr); + REQUIRE(conditionElement->m_condition->IsStatic()); + const auto staticValue = conditionElement->m_condition->EvaluateStatic(); + REQUIRE(staticValue.m_type == SimpleExpressionValue::Type::INT); + REQUIRE(staticValue.m_int_value == 1337); - const auto* conditionElement = dynamic_cast<const CommonEventHandlerCondition*>(secondElement); - REQUIRE(conditionElement != nullptr); - } + REQUIRE(conditionElement->m_condition_elements); + REQUIRE(helper.m_state->m_current_nested_event_handler_set == conditionElement->m_condition_elements.get()); + REQUIRE(!conditionElement->m_else_elements); - TEST_CASE("EventHandlerSetScopeSequences: ElseIf opens new condition", "[parsing][sequence][menu]") - { - EventHandlerSetSequenceTestsHelper helper(FeatureLevel::IW4, false); - const TokenPos pos; - helper.Tokens({ - SimpleParserValue::Character(pos, '}'), - SimpleParserValue::Identifier(pos, new std::string("elseif")), - SimpleParserValue::Character(pos, '('), - SimpleParserValue::Integer(pos, 1336), - SimpleParserValue::Character(pos, '+'), - SimpleParserValue::Integer(pos, 1), - SimpleParserValue::Character(pos, ')'), - SimpleParserValue::Character(pos, '{'), - SimpleParserValue::EndOfFile(pos) - }); - - const auto currentIfCondition = std::make_unique<CommonEventHandlerCondition>(nullptr, std::make_unique<CommonEventHandlerSet>(), nullptr); - helper.m_state->m_current_nested_event_handler_set = currentIfCondition->m_condition_elements.get(); - helper.m_state->m_condition_stack.emplace(currentIfCondition.get()); - - const auto result = helper.PerformTest(); - - REQUIRE(result); - REQUIRE(helper.m_consumed_token_count == 8); - REQUIRE(helper.m_state->m_current_event_handler_set == helper.m_event_handler_set.get()); - REQUIRE(helper.m_event_handler_set); - REQUIRE(helper.m_event_handler_set->m_elements.empty()); // Doesnt add new element - - REQUIRE(currentIfCondition->m_else_elements); - REQUIRE(currentIfCondition->m_else_elements->m_elements.size() == 1); - - const auto* firstElement = currentIfCondition->m_else_elements->m_elements[0].get(); - - REQUIRE(firstElement->GetType() == CommonEventHandlerElementType::CONDITION); - - const auto* conditionElement = dynamic_cast<const CommonEventHandlerCondition*>(firstElement); - REQUIRE(conditionElement != nullptr); - - REQUIRE(conditionElement->m_condition != nullptr); - REQUIRE(conditionElement->m_condition->IsStatic()); - const auto staticValue = conditionElement->m_condition->EvaluateStatic(); - REQUIRE(staticValue.m_type == SimpleExpressionValue::Type::INT); - REQUIRE(staticValue.m_int_value == 1337); - - REQUIRE(conditionElement->m_condition_elements); - REQUIRE(helper.m_state->m_current_nested_event_handler_set == conditionElement->m_condition_elements.get()); - REQUIRE(!conditionElement->m_else_elements); - - REQUIRE(helper.m_state->m_condition_stack.size() == 2); - REQUIRE(helper.m_state->m_condition_stack.top().m_condition == conditionElement); - REQUIRE(helper.m_state->m_condition_stack.top().m_auto_skip == true); - REQUIRE(helper.m_state->m_condition_stack.top().m_in_condition_elements == true); - } + REQUIRE(helper.m_state->m_condition_stack.size() == 1); + REQUIRE(helper.m_state->m_condition_stack.top().m_condition == conditionElement); + REQUIRE(helper.m_state->m_condition_stack.top().m_auto_skip == false); + REQUIRE(helper.m_state->m_condition_stack.top().m_in_condition_elements == true); +} - TEST_CASE("EventHandlerSetScopeSequences: ElseIf applies current script", "[parsing][sequence][menu]") - { - EventHandlerSetSequenceTestsHelper helper(FeatureLevel::IW4, false); - const TokenPos pos; - helper.Tokens({ - SimpleParserValue::Character(pos, '}'), - SimpleParserValue::Identifier(pos, new std::string("elseif")), - SimpleParserValue::Character(pos, '('), - SimpleParserValue::Integer(pos, 420), - SimpleParserValue::Character(pos, ')'), - SimpleParserValue::Character(pos, '{'), - SimpleParserValue::EndOfFile(pos) - }); +TEST_CASE("EventHandlerSetScopeSequences: If applies current script", "[parsing][sequence][menu]") { + EventHandlerSetSequenceTestsHelper helper(FeatureLevel::IW4, false); + const TokenPos pos; + helper.Tokens({SimpleParserValue::Identifier(pos, new std::string("if")), SimpleParserValue::Character(pos, '('), SimpleParserValue::Integer(pos, 420), + SimpleParserValue::Character(pos, ')'), SimpleParserValue::Character(pos, '{'), SimpleParserValue::EndOfFile(pos)}); - const auto currentIfCondition = std::make_unique<CommonEventHandlerCondition>(nullptr, std::make_unique<CommonEventHandlerSet>(), nullptr); - helper.m_state->m_current_nested_event_handler_set = currentIfCondition->m_condition_elements.get(); - helper.m_state->m_condition_stack.emplace(currentIfCondition.get()); + helper.m_state->m_current_script << R"("fadeIn" "some_element" ; )"; - helper.m_state->m_current_script << R"("fadeIn" "some_element" ; )"; + const auto result = helper.PerformTest(); - const auto result = helper.PerformTest(); + REQUIRE(result); + REQUIRE(helper.m_consumed_token_count == 5); + REQUIRE(helper.m_state->m_current_event_handler_set == helper.m_event_handler_set.get()); + REQUIRE(helper.m_event_handler_set); + REQUIRE(helper.m_event_handler_set->m_elements.size() == 2); - REQUIRE(result); - REQUIRE(helper.m_consumed_token_count == 6); + const auto *firstElement = helper.m_event_handler_set->m_elements[0].get(); - REQUIRE(currentIfCondition->m_condition_elements); - REQUIRE(currentIfCondition->m_condition_elements->m_elements.size() == 1); + REQUIRE(firstElement->GetType() == CommonEventHandlerElementType::SCRIPT); - const auto* firstConditionElement = currentIfCondition->m_condition_elements->m_elements[0].get(); + const auto *scriptElement = dynamic_cast<const CommonEventHandlerScript *>(firstElement); + REQUIRE(scriptElement != nullptr); + REQUIRE(scriptElement->m_script == R"("fadeIn" "some_element" ; )"); - REQUIRE(firstConditionElement->GetType() == CommonEventHandlerElementType::SCRIPT); + const auto *secondElement = helper.m_event_handler_set->m_elements[1].get(); - const auto* scriptElement = dynamic_cast<const CommonEventHandlerScript*>(firstConditionElement); - REQUIRE(scriptElement != nullptr); - REQUIRE(scriptElement->m_script == R"("fadeIn" "some_element" ; )"); + REQUIRE(secondElement->GetType() == CommonEventHandlerElementType::CONDITION); - REQUIRE(currentIfCondition->m_else_elements); - REQUIRE(currentIfCondition->m_else_elements->m_elements.size() == 1); + const auto *conditionElement = dynamic_cast<const CommonEventHandlerCondition *>(secondElement); + REQUIRE(conditionElement != nullptr); +} - const auto* firstElseElement = currentIfCondition->m_else_elements->m_elements[0].get(); +TEST_CASE("EventHandlerSetScopeSequences: ElseIf opens new condition", "[parsing][sequence][menu]") { + EventHandlerSetSequenceTestsHelper helper(FeatureLevel::IW4, false); + const TokenPos pos; + helper.Tokens({SimpleParserValue::Character(pos, '}'), SimpleParserValue::Identifier(pos, new std::string("elseif")), SimpleParserValue::Character(pos, '('), + SimpleParserValue::Integer(pos, 1336), SimpleParserValue::Character(pos, '+'), SimpleParserValue::Integer(pos, 1), + SimpleParserValue::Character(pos, ')'), SimpleParserValue::Character(pos, '{'), SimpleParserValue::EndOfFile(pos)}); - REQUIRE(firstElseElement->GetType() == CommonEventHandlerElementType::CONDITION); - } + const auto currentIfCondition = std::make_unique<CommonEventHandlerCondition>(nullptr, std::make_unique<CommonEventHandlerSet>(), nullptr); + helper.m_state->m_current_nested_event_handler_set = currentIfCondition->m_condition_elements.get(); + helper.m_state->m_condition_stack.emplace(currentIfCondition.get()); - TEST_CASE("EventHandlerSetScopeSequences: ElseIf cannot be specified when not in if", "[parsing][sequence][menu]") - { - EventHandlerSetSequenceTestsHelper helper(FeatureLevel::IW4, false); - const TokenPos pos; - helper.Tokens({ - SimpleParserValue::Character(pos, '}'), - SimpleParserValue::Identifier(pos, new std::string("elseif")), - SimpleParserValue::Character(pos, '('), - SimpleParserValue::Integer(pos, 420), - SimpleParserValue::Character(pos, ')'), - SimpleParserValue::Character(pos, '{'), - SimpleParserValue::EndOfFile(pos) - }); - - REQUIRE_THROWS_AS(helper.PerformTest(), ParsingException); - } + const auto result = helper.PerformTest(); - TEST_CASE("EventHandlerSetScopeSequences: ElseIf cannot be specified when else was already used", "[parsing][sequence][menu]") - { - EventHandlerSetSequenceTestsHelper helper(FeatureLevel::IW4, false); - const TokenPos pos; - helper.Tokens({ - SimpleParserValue::Character(pos, '}'), - SimpleParserValue::Identifier(pos, new std::string("elseif")), - SimpleParserValue::Character(pos, '('), - SimpleParserValue::Integer(pos, 420), - SimpleParserValue::Character(pos, ')'), - SimpleParserValue::Character(pos, '{'), - SimpleParserValue::EndOfFile(pos) - }); - - const auto currentIfCondition = std::make_unique<CommonEventHandlerCondition>(nullptr, std::make_unique<CommonEventHandlerSet>(), std::make_unique<CommonEventHandlerSet>()); - helper.m_state->m_current_nested_event_handler_set = currentIfCondition->m_condition_elements.get(); - helper.m_state->m_condition_stack.emplace(currentIfCondition.get()); - helper.m_state->m_condition_stack.top().m_in_condition_elements = false; - - REQUIRE_THROWS_AS(helper.PerformTest(), ParsingException); - } + REQUIRE(result); + REQUIRE(helper.m_consumed_token_count == 8); + REQUIRE(helper.m_state->m_current_event_handler_set == helper.m_event_handler_set.get()); + REQUIRE(helper.m_event_handler_set); + REQUIRE(helper.m_event_handler_set->m_elements.empty()); // Doesnt add new element - TEST_CASE("EventHandlerSetScopeSequences: Else switches to else element", "[parsing][sequence][menu]") - { - EventHandlerSetSequenceTestsHelper helper(FeatureLevel::IW4, false); - const TokenPos pos; - helper.Tokens({ - SimpleParserValue::Character(pos, '}'), - SimpleParserValue::Identifier(pos, new std::string("else")), - SimpleParserValue::Character(pos, '{'), - SimpleParserValue::EndOfFile(pos) - }); - - const auto currentIfCondition = std::make_unique<CommonEventHandlerCondition>(nullptr, std::make_unique<CommonEventHandlerSet>(), nullptr); - helper.m_state->m_current_nested_event_handler_set = currentIfCondition->m_condition_elements.get(); - helper.m_state->m_condition_stack.emplace(currentIfCondition.get()); - - const auto result = helper.PerformTest(); - - REQUIRE(result); - REQUIRE(helper.m_consumed_token_count == 3); - REQUIRE(helper.m_state->m_current_event_handler_set == helper.m_event_handler_set.get()); - REQUIRE(helper.m_event_handler_set); - REQUIRE(helper.m_event_handler_set->m_elements.empty()); // Doesn't add new element - - REQUIRE(currentIfCondition->m_else_elements); - REQUIRE(currentIfCondition->m_else_elements->m_elements.empty()); - - REQUIRE(helper.m_state->m_condition_stack.size() == 1); - REQUIRE(helper.m_state->m_condition_stack.top().m_condition == currentIfCondition.get()); - REQUIRE(helper.m_state->m_condition_stack.top().m_auto_skip == false); - REQUIRE(helper.m_state->m_condition_stack.top().m_in_condition_elements == false); - } + REQUIRE(currentIfCondition->m_else_elements); + REQUIRE(currentIfCondition->m_else_elements->m_elements.size() == 1); - TEST_CASE("EventHandlerSetScopeSequences: Else keeps auto_skip value", "[parsing][sequence][menu]") - { - EventHandlerSetSequenceTestsHelper helper(FeatureLevel::IW4, false); - const TokenPos pos; - helper.Tokens({ - SimpleParserValue::Character(pos, '}'), - SimpleParserValue::Identifier(pos, new std::string("else")), - SimpleParserValue::Character(pos, '{'), - SimpleParserValue::EndOfFile(pos) - }); - - const auto currentIfCondition = std::make_unique<CommonEventHandlerCondition>(nullptr, std::make_unique<CommonEventHandlerSet>(), nullptr); - helper.m_state->m_current_nested_event_handler_set = currentIfCondition->m_condition_elements.get(); - helper.m_state->m_condition_stack.emplace(currentIfCondition.get(), true); - - const auto result = helper.PerformTest(); - - REQUIRE(result); - REQUIRE(helper.m_consumed_token_count == 3); - REQUIRE(helper.m_state->m_current_event_handler_set == helper.m_event_handler_set.get()); - REQUIRE(helper.m_event_handler_set); - REQUIRE(helper.m_event_handler_set->m_elements.empty()); // Doesn't add new element - - REQUIRE(currentIfCondition->m_else_elements); - REQUIRE(currentIfCondition->m_else_elements->m_elements.empty()); - - REQUIRE(helper.m_state->m_condition_stack.size() == 1); - REQUIRE(helper.m_state->m_condition_stack.top().m_condition == currentIfCondition.get()); - REQUIRE(helper.m_state->m_condition_stack.top().m_auto_skip == true); - REQUIRE(helper.m_state->m_condition_stack.top().m_in_condition_elements == false); - } + const auto *firstElement = currentIfCondition->m_else_elements->m_elements[0].get(); - TEST_CASE("EventHandlerSetScopeSequences: Else cannot be specified when not in if", "[parsing][sequence][menu]") - { - EventHandlerSetSequenceTestsHelper helper(FeatureLevel::IW4, false); - const TokenPos pos; - helper.Tokens({ - SimpleParserValue::Character(pos, '}'), - SimpleParserValue::Identifier(pos, new std::string("else")), - SimpleParserValue::Character(pos, '{'), - SimpleParserValue::EndOfFile(pos) - }); - - REQUIRE_THROWS_AS(helper.PerformTest(), ParsingException); - } + REQUIRE(firstElement->GetType() == CommonEventHandlerElementType::CONDITION); - TEST_CASE("EventHandlerSetScopeSequences: Else cannot be specified when else was already used", "[parsing][sequence][menu]") - { - EventHandlerSetSequenceTestsHelper helper(FeatureLevel::IW4, false); - const TokenPos pos; - helper.Tokens({ - SimpleParserValue::Character(pos, '}'), - SimpleParserValue::Identifier(pos, new std::string("else")), - SimpleParserValue::Character(pos, '{'), - SimpleParserValue::EndOfFile(pos) - }); - - const auto currentIfCondition = std::make_unique<CommonEventHandlerCondition>(nullptr, std::make_unique<CommonEventHandlerSet>(), std::make_unique<CommonEventHandlerSet>()); - helper.m_state->m_current_nested_event_handler_set = currentIfCondition->m_condition_elements.get(); - helper.m_state->m_condition_stack.emplace(currentIfCondition.get()); - helper.m_state->m_condition_stack.top().m_in_condition_elements = false; - - REQUIRE_THROWS_AS(helper.PerformTest(), ParsingException); - } + const auto *conditionElement = dynamic_cast<const CommonEventHandlerCondition *>(firstElement); + REQUIRE(conditionElement != nullptr); - TEST_CASE("EventHandlerSetScopeSequences: CloseBlock closes if statements", "[parsing][sequence][menu]") - { - EventHandlerSetSequenceTestsHelper helper(FeatureLevel::IW4, false); - const TokenPos pos; - helper.Tokens({ - SimpleParserValue::Character(pos, '}'), - SimpleParserValue::EndOfFile(pos) - }); - - const auto currentIfCondition = std::make_unique<CommonEventHandlerCondition>(nullptr, std::make_unique<CommonEventHandlerSet>(), nullptr); - helper.m_state->m_current_nested_event_handler_set = currentIfCondition->m_condition_elements.get(); - helper.m_state->m_condition_stack.emplace(currentIfCondition.get()); - - const auto result = helper.PerformTest(); - - REQUIRE(result); - REQUIRE(helper.m_consumed_token_count == 1); - REQUIRE(helper.m_state->m_current_event_handler_set == helper.m_event_handler_set.get()); - REQUIRE(helper.m_event_handler_set); - REQUIRE(helper.m_event_handler_set->m_elements.empty()); // Doesn't add new element - - REQUIRE(helper.m_state->m_current_nested_event_handler_set == helper.m_event_handler_set.get()); - REQUIRE(helper.m_state->m_condition_stack.empty()); - } + REQUIRE(conditionElement->m_condition != nullptr); + REQUIRE(conditionElement->m_condition->IsStatic()); + const auto staticValue = conditionElement->m_condition->EvaluateStatic(); + REQUIRE(staticValue.m_type == SimpleExpressionValue::Type::INT); + REQUIRE(staticValue.m_int_value == 1337); - TEST_CASE("EventHandlerSetScopeSequences: CloseBlock closes nested if statements to parent if statement", "[parsing][sequence][menu]") - { - EventHandlerSetSequenceTestsHelper helper(FeatureLevel::IW4, false); - const TokenPos pos; - helper.Tokens({ - SimpleParserValue::Character(pos, '}'), - SimpleParserValue::EndOfFile(pos) - }); - - const auto baseIfCondition = std::make_unique<CommonEventHandlerCondition>(nullptr, std::make_unique<CommonEventHandlerSet>(), nullptr); - helper.m_state->m_current_nested_event_handler_set = baseIfCondition->m_condition_elements.get(); - helper.m_state->m_condition_stack.emplace(baseIfCondition.get()); - - const auto nestedIfCondition = std::make_unique<CommonEventHandlerCondition>(nullptr, std::make_unique<CommonEventHandlerSet>(), nullptr); - helper.m_state->m_current_nested_event_handler_set = nestedIfCondition->m_condition_elements.get(); - helper.m_state->m_condition_stack.emplace(nestedIfCondition.get()); - - const auto result = helper.PerformTest(); - - REQUIRE(result); - REQUIRE(helper.m_consumed_token_count == 1); - REQUIRE(helper.m_state->m_current_event_handler_set == helper.m_event_handler_set.get()); - REQUIRE(helper.m_event_handler_set); - REQUIRE(helper.m_state->m_current_nested_event_handler_set->m_elements.empty()); // Doesn't add new element - - REQUIRE(helper.m_state->m_current_nested_event_handler_set == baseIfCondition->m_condition_elements.get()); - REQUIRE(helper.m_state->m_condition_stack.size() == 1); - } + REQUIRE(conditionElement->m_condition_elements); + REQUIRE(helper.m_state->m_current_nested_event_handler_set == conditionElement->m_condition_elements.get()); + REQUIRE(!conditionElement->m_else_elements); - TEST_CASE("EventHandlerSetScopeSequences: CloseBlock closes nested if statements to parent else statement", "[parsing][sequence][menu]") - { - EventHandlerSetSequenceTestsHelper helper(FeatureLevel::IW4, false); - const TokenPos pos; - helper.Tokens({ - SimpleParserValue::Character(pos, '}'), - SimpleParserValue::EndOfFile(pos) - }); - - const auto baseIfCondition = std::make_unique<CommonEventHandlerCondition>(nullptr, std::make_unique<CommonEventHandlerSet>(), std::make_unique<CommonEventHandlerSet>()); - helper.m_state->m_current_nested_event_handler_set = baseIfCondition->m_condition_elements.get(); - helper.m_state->m_condition_stack.emplace(baseIfCondition.get()); - helper.m_state->m_condition_stack.top().m_in_condition_elements = false; - - const auto nestedIfCondition = std::make_unique<CommonEventHandlerCondition>(nullptr, std::make_unique<CommonEventHandlerSet>(), nullptr); - helper.m_state->m_current_nested_event_handler_set = nestedIfCondition->m_condition_elements.get(); - helper.m_state->m_condition_stack.emplace(nestedIfCondition.get()); - - const auto result = helper.PerformTest(); - - REQUIRE(result); - REQUIRE(helper.m_consumed_token_count == 1); - REQUIRE(helper.m_state->m_current_event_handler_set == helper.m_event_handler_set.get()); - REQUIRE(helper.m_event_handler_set); - REQUIRE(helper.m_state->m_current_nested_event_handler_set->m_elements.empty()); // Doesn't add new element - - REQUIRE(helper.m_state->m_current_nested_event_handler_set == baseIfCondition->m_else_elements.get()); - REQUIRE(helper.m_state->m_condition_stack.size() == 1); - } + REQUIRE(helper.m_state->m_condition_stack.size() == 2); + REQUIRE(helper.m_state->m_condition_stack.top().m_condition == conditionElement); + REQUIRE(helper.m_state->m_condition_stack.top().m_auto_skip == true); + REQUIRE(helper.m_state->m_condition_stack.top().m_in_condition_elements == true); +} - TEST_CASE("EventHandlerSetScopeSequences: CloseBlock closes all autoskip conditions to parent if statement", "[parsing][sequence][menu]") - { - EventHandlerSetSequenceTestsHelper helper(FeatureLevel::IW4, false); - const TokenPos pos; - helper.Tokens({ - SimpleParserValue::Character(pos, '}'), - SimpleParserValue::EndOfFile(pos) - }); - - const auto baseIfCondition = std::make_unique<CommonEventHandlerCondition>(nullptr, std::make_unique<CommonEventHandlerSet>(), nullptr); - helper.m_state->m_current_nested_event_handler_set = baseIfCondition->m_condition_elements.get(); - helper.m_state->m_condition_stack.emplace(baseIfCondition.get()); - - const auto nestedIfCondition = std::make_unique<CommonEventHandlerCondition>(nullptr, std::make_unique<CommonEventHandlerSet>(), nullptr); - helper.m_state->m_current_nested_event_handler_set = nestedIfCondition->m_condition_elements.get(); - helper.m_state->m_condition_stack.emplace(nestedIfCondition.get()); - - const auto moreNestedIfCondition = std::make_unique<CommonEventHandlerCondition>(nullptr, std::make_unique<CommonEventHandlerSet>(), nullptr); - helper.m_state->m_current_nested_event_handler_set = moreNestedIfCondition->m_condition_elements.get(); - helper.m_state->m_condition_stack.emplace(moreNestedIfCondition.get(), true); - - const auto result = helper.PerformTest(); - - REQUIRE(result); - REQUIRE(helper.m_consumed_token_count == 1); - REQUIRE(helper.m_state->m_current_event_handler_set == helper.m_event_handler_set.get()); - REQUIRE(helper.m_event_handler_set); - REQUIRE(helper.m_state->m_current_nested_event_handler_set->m_elements.empty()); // Doesn't add new element - - REQUIRE(helper.m_state->m_current_nested_event_handler_set == baseIfCondition->m_condition_elements.get()); - REQUIRE(helper.m_state->m_condition_stack.size() == 1); - } +TEST_CASE("EventHandlerSetScopeSequences: ElseIf applies current script", "[parsing][sequence][menu]") { + EventHandlerSetSequenceTestsHelper helper(FeatureLevel::IW4, false); + const TokenPos pos; + helper.Tokens({SimpleParserValue::Character(pos, '}'), SimpleParserValue::Identifier(pos, new std::string("elseif")), SimpleParserValue::Character(pos, '('), + SimpleParserValue::Integer(pos, 420), SimpleParserValue::Character(pos, ')'), SimpleParserValue::Character(pos, '{'), + SimpleParserValue::EndOfFile(pos)}); - TEST_CASE("EventHandlerSetScopeSequences: CloseBlock closes all autoskip conditions to base", "[parsing][sequence][menu]") - { - EventHandlerSetSequenceTestsHelper helper(FeatureLevel::IW4, false); - const TokenPos pos; - helper.Tokens({ - SimpleParserValue::Character(pos, '}'), - SimpleParserValue::EndOfFile(pos) - }); - - const auto baseIfCondition = std::make_unique<CommonEventHandlerCondition>(nullptr, std::make_unique<CommonEventHandlerSet>(), nullptr); - helper.m_state->m_current_nested_event_handler_set = baseIfCondition->m_condition_elements.get(); - helper.m_state->m_condition_stack.emplace(baseIfCondition.get()); - - const auto nestedIfCondition = std::make_unique<CommonEventHandlerCondition>(nullptr, std::make_unique<CommonEventHandlerSet>(), nullptr); - helper.m_state->m_current_nested_event_handler_set = nestedIfCondition->m_condition_elements.get(); - helper.m_state->m_condition_stack.emplace(nestedIfCondition.get(), true); - - const auto result = helper.PerformTest(); - - REQUIRE(result); - REQUIRE(helper.m_consumed_token_count == 1); - REQUIRE(helper.m_state->m_current_event_handler_set == helper.m_event_handler_set.get()); - REQUIRE(helper.m_event_handler_set); - REQUIRE(helper.m_state->m_current_nested_event_handler_set->m_elements.empty()); // Doesn't add new element - - REQUIRE(helper.m_state->m_current_nested_event_handler_set == helper.m_event_handler_set.get()); - REQUIRE(helper.m_state->m_condition_stack.empty()); - } + const auto currentIfCondition = std::make_unique<CommonEventHandlerCondition>(nullptr, std::make_unique<CommonEventHandlerSet>(), nullptr); + helper.m_state->m_current_nested_event_handler_set = currentIfCondition->m_condition_elements.get(); + helper.m_state->m_condition_stack.emplace(currentIfCondition.get()); -#pragma endregion + helper.m_state->m_current_script << R"("fadeIn" "some_element" ; )"; + + const auto result = helper.PerformTest(); + + REQUIRE(result); + REQUIRE(helper.m_consumed_token_count == 6); + + REQUIRE(currentIfCondition->m_condition_elements); + REQUIRE(currentIfCondition->m_condition_elements->m_elements.size() == 1); + + const auto *firstConditionElement = currentIfCondition->m_condition_elements->m_elements[0].get(); + + REQUIRE(firstConditionElement->GetType() == CommonEventHandlerElementType::SCRIPT); + + const auto *scriptElement = dynamic_cast<const CommonEventHandlerScript *>(firstConditionElement); + REQUIRE(scriptElement != nullptr); + REQUIRE(scriptElement->m_script == R"("fadeIn" "some_element" ; )"); + + REQUIRE(currentIfCondition->m_else_elements); + REQUIRE(currentIfCondition->m_else_elements->m_elements.size() == 1); + + const auto *firstElseElement = currentIfCondition->m_else_elements->m_elements[0].get(); + + REQUIRE(firstElseElement->GetType() == CommonEventHandlerElementType::CONDITION); +} + +TEST_CASE("EventHandlerSetScopeSequences: ElseIf cannot be specified when not in if", "[parsing][sequence][menu]") { + EventHandlerSetSequenceTestsHelper helper(FeatureLevel::IW4, false); + const TokenPos pos; + helper.Tokens({SimpleParserValue::Character(pos, '}'), SimpleParserValue::Identifier(pos, new std::string("elseif")), SimpleParserValue::Character(pos, '('), + SimpleParserValue::Integer(pos, 420), SimpleParserValue::Character(pos, ')'), SimpleParserValue::Character(pos, '{'), + SimpleParserValue::EndOfFile(pos)}); + + REQUIRE_THROWS_AS(helper.PerformTest(), ParsingException); +} + +TEST_CASE("EventHandlerSetScopeSequences: ElseIf cannot be specified when else was already used", "[parsing][sequence][menu]") { + EventHandlerSetSequenceTestsHelper helper(FeatureLevel::IW4, false); + const TokenPos pos; + helper.Tokens({SimpleParserValue::Character(pos, '}'), SimpleParserValue::Identifier(pos, new std::string("elseif")), SimpleParserValue::Character(pos, '('), + SimpleParserValue::Integer(pos, 420), SimpleParserValue::Character(pos, ')'), SimpleParserValue::Character(pos, '{'), + SimpleParserValue::EndOfFile(pos)}); + + const auto currentIfCondition = + std::make_unique<CommonEventHandlerCondition>(nullptr, std::make_unique<CommonEventHandlerSet>(), std::make_unique<CommonEventHandlerSet>()); + helper.m_state->m_current_nested_event_handler_set = currentIfCondition->m_condition_elements.get(); + helper.m_state->m_condition_stack.emplace(currentIfCondition.get()); + helper.m_state->m_condition_stack.top().m_in_condition_elements = false; + + REQUIRE_THROWS_AS(helper.PerformTest(), ParsingException); +} + +TEST_CASE("EventHandlerSetScopeSequences: Else switches to else element", "[parsing][sequence][menu]") { + EventHandlerSetSequenceTestsHelper helper(FeatureLevel::IW4, false); + const TokenPos pos; + helper.Tokens({SimpleParserValue::Character(pos, '}'), SimpleParserValue::Identifier(pos, new std::string("else")), SimpleParserValue::Character(pos, '{'), + SimpleParserValue::EndOfFile(pos)}); + + const auto currentIfCondition = std::make_unique<CommonEventHandlerCondition>(nullptr, std::make_unique<CommonEventHandlerSet>(), nullptr); + helper.m_state->m_current_nested_event_handler_set = currentIfCondition->m_condition_elements.get(); + helper.m_state->m_condition_stack.emplace(currentIfCondition.get()); + + const auto result = helper.PerformTest(); + + REQUIRE(result); + REQUIRE(helper.m_consumed_token_count == 3); + REQUIRE(helper.m_state->m_current_event_handler_set == helper.m_event_handler_set.get()); + REQUIRE(helper.m_event_handler_set); + REQUIRE(helper.m_event_handler_set->m_elements.empty()); // Doesn't add new element + + REQUIRE(currentIfCondition->m_else_elements); + REQUIRE(currentIfCondition->m_else_elements->m_elements.empty()); + + REQUIRE(helper.m_state->m_condition_stack.size() == 1); + REQUIRE(helper.m_state->m_condition_stack.top().m_condition == currentIfCondition.get()); + REQUIRE(helper.m_state->m_condition_stack.top().m_auto_skip == false); + REQUIRE(helper.m_state->m_condition_stack.top().m_in_condition_elements == false); +} + +TEST_CASE("EventHandlerSetScopeSequences: Else keeps auto_skip value", "[parsing][sequence][menu]") { + EventHandlerSetSequenceTestsHelper helper(FeatureLevel::IW4, false); + const TokenPos pos; + helper.Tokens({SimpleParserValue::Character(pos, '}'), SimpleParserValue::Identifier(pos, new std::string("else")), SimpleParserValue::Character(pos, '{'), + SimpleParserValue::EndOfFile(pos)}); + + const auto currentIfCondition = std::make_unique<CommonEventHandlerCondition>(nullptr, std::make_unique<CommonEventHandlerSet>(), nullptr); + helper.m_state->m_current_nested_event_handler_set = currentIfCondition->m_condition_elements.get(); + helper.m_state->m_condition_stack.emplace(currentIfCondition.get(), true); + + const auto result = helper.PerformTest(); + + REQUIRE(result); + REQUIRE(helper.m_consumed_token_count == 3); + REQUIRE(helper.m_state->m_current_event_handler_set == helper.m_event_handler_set.get()); + REQUIRE(helper.m_event_handler_set); + REQUIRE(helper.m_event_handler_set->m_elements.empty()); // Doesn't add new element + + REQUIRE(currentIfCondition->m_else_elements); + REQUIRE(currentIfCondition->m_else_elements->m_elements.empty()); + + REQUIRE(helper.m_state->m_condition_stack.size() == 1); + REQUIRE(helper.m_state->m_condition_stack.top().m_condition == currentIfCondition.get()); + REQUIRE(helper.m_state->m_condition_stack.top().m_auto_skip == true); + REQUIRE(helper.m_state->m_condition_stack.top().m_in_condition_elements == false); } + +TEST_CASE("EventHandlerSetScopeSequences: Else cannot be specified when not in if", "[parsing][sequence][menu]") { + EventHandlerSetSequenceTestsHelper helper(FeatureLevel::IW4, false); + const TokenPos pos; + helper.Tokens({SimpleParserValue::Character(pos, '}'), SimpleParserValue::Identifier(pos, new std::string("else")), SimpleParserValue::Character(pos, '{'), + SimpleParserValue::EndOfFile(pos)}); + + REQUIRE_THROWS_AS(helper.PerformTest(), ParsingException); +} + +TEST_CASE("EventHandlerSetScopeSequences: Else cannot be specified when else was already used", "[parsing][sequence][menu]") { + EventHandlerSetSequenceTestsHelper helper(FeatureLevel::IW4, false); + const TokenPos pos; + helper.Tokens({SimpleParserValue::Character(pos, '}'), SimpleParserValue::Identifier(pos, new std::string("else")), SimpleParserValue::Character(pos, '{'), + SimpleParserValue::EndOfFile(pos)}); + + const auto currentIfCondition = + std::make_unique<CommonEventHandlerCondition>(nullptr, std::make_unique<CommonEventHandlerSet>(), std::make_unique<CommonEventHandlerSet>()); + helper.m_state->m_current_nested_event_handler_set = currentIfCondition->m_condition_elements.get(); + helper.m_state->m_condition_stack.emplace(currentIfCondition.get()); + helper.m_state->m_condition_stack.top().m_in_condition_elements = false; + + REQUIRE_THROWS_AS(helper.PerformTest(), ParsingException); +} + +TEST_CASE("EventHandlerSetScopeSequences: CloseBlock closes if statements", "[parsing][sequence][menu]") { + EventHandlerSetSequenceTestsHelper helper(FeatureLevel::IW4, false); + const TokenPos pos; + helper.Tokens({SimpleParserValue::Character(pos, '}'), SimpleParserValue::EndOfFile(pos)}); + + const auto currentIfCondition = std::make_unique<CommonEventHandlerCondition>(nullptr, std::make_unique<CommonEventHandlerSet>(), nullptr); + helper.m_state->m_current_nested_event_handler_set = currentIfCondition->m_condition_elements.get(); + helper.m_state->m_condition_stack.emplace(currentIfCondition.get()); + + const auto result = helper.PerformTest(); + + REQUIRE(result); + REQUIRE(helper.m_consumed_token_count == 1); + REQUIRE(helper.m_state->m_current_event_handler_set == helper.m_event_handler_set.get()); + REQUIRE(helper.m_event_handler_set); + REQUIRE(helper.m_event_handler_set->m_elements.empty()); // Doesn't add new element + + REQUIRE(helper.m_state->m_current_nested_event_handler_set == helper.m_event_handler_set.get()); + REQUIRE(helper.m_state->m_condition_stack.empty()); +} + +TEST_CASE("EventHandlerSetScopeSequences: CloseBlock closes nested if statements to parent if statement", "[parsing][sequence][menu]") { + EventHandlerSetSequenceTestsHelper helper(FeatureLevel::IW4, false); + const TokenPos pos; + helper.Tokens({SimpleParserValue::Character(pos, '}'), SimpleParserValue::EndOfFile(pos)}); + + const auto baseIfCondition = std::make_unique<CommonEventHandlerCondition>(nullptr, std::make_unique<CommonEventHandlerSet>(), nullptr); + helper.m_state->m_current_nested_event_handler_set = baseIfCondition->m_condition_elements.get(); + helper.m_state->m_condition_stack.emplace(baseIfCondition.get()); + + const auto nestedIfCondition = std::make_unique<CommonEventHandlerCondition>(nullptr, std::make_unique<CommonEventHandlerSet>(), nullptr); + helper.m_state->m_current_nested_event_handler_set = nestedIfCondition->m_condition_elements.get(); + helper.m_state->m_condition_stack.emplace(nestedIfCondition.get()); + + const auto result = helper.PerformTest(); + + REQUIRE(result); + REQUIRE(helper.m_consumed_token_count == 1); + REQUIRE(helper.m_state->m_current_event_handler_set == helper.m_event_handler_set.get()); + REQUIRE(helper.m_event_handler_set); + REQUIRE(helper.m_state->m_current_nested_event_handler_set->m_elements.empty()); // Doesn't add new element + + REQUIRE(helper.m_state->m_current_nested_event_handler_set == baseIfCondition->m_condition_elements.get()); + REQUIRE(helper.m_state->m_condition_stack.size() == 1); +} + +TEST_CASE("EventHandlerSetScopeSequences: CloseBlock closes nested if statements to parent else statement", "[parsing][sequence][menu]") { + EventHandlerSetSequenceTestsHelper helper(FeatureLevel::IW4, false); + const TokenPos pos; + helper.Tokens({SimpleParserValue::Character(pos, '}'), SimpleParserValue::EndOfFile(pos)}); + + const auto baseIfCondition = + std::make_unique<CommonEventHandlerCondition>(nullptr, std::make_unique<CommonEventHandlerSet>(), std::make_unique<CommonEventHandlerSet>()); + helper.m_state->m_current_nested_event_handler_set = baseIfCondition->m_condition_elements.get(); + helper.m_state->m_condition_stack.emplace(baseIfCondition.get()); + helper.m_state->m_condition_stack.top().m_in_condition_elements = false; + + const auto nestedIfCondition = std::make_unique<CommonEventHandlerCondition>(nullptr, std::make_unique<CommonEventHandlerSet>(), nullptr); + helper.m_state->m_current_nested_event_handler_set = nestedIfCondition->m_condition_elements.get(); + helper.m_state->m_condition_stack.emplace(nestedIfCondition.get()); + + const auto result = helper.PerformTest(); + + REQUIRE(result); + REQUIRE(helper.m_consumed_token_count == 1); + REQUIRE(helper.m_state->m_current_event_handler_set == helper.m_event_handler_set.get()); + REQUIRE(helper.m_event_handler_set); + REQUIRE(helper.m_state->m_current_nested_event_handler_set->m_elements.empty()); // Doesn't add new element + + REQUIRE(helper.m_state->m_current_nested_event_handler_set == baseIfCondition->m_else_elements.get()); + REQUIRE(helper.m_state->m_condition_stack.size() == 1); +} + +TEST_CASE("EventHandlerSetScopeSequences: CloseBlock closes all autoskip conditions to parent if statement", "[parsing][sequence][menu]") { + EventHandlerSetSequenceTestsHelper helper(FeatureLevel::IW4, false); + const TokenPos pos; + helper.Tokens({SimpleParserValue::Character(pos, '}'), SimpleParserValue::EndOfFile(pos)}); + + const auto baseIfCondition = std::make_unique<CommonEventHandlerCondition>(nullptr, std::make_unique<CommonEventHandlerSet>(), nullptr); + helper.m_state->m_current_nested_event_handler_set = baseIfCondition->m_condition_elements.get(); + helper.m_state->m_condition_stack.emplace(baseIfCondition.get()); + + const auto nestedIfCondition = std::make_unique<CommonEventHandlerCondition>(nullptr, std::make_unique<CommonEventHandlerSet>(), nullptr); + helper.m_state->m_current_nested_event_handler_set = nestedIfCondition->m_condition_elements.get(); + helper.m_state->m_condition_stack.emplace(nestedIfCondition.get()); + + const auto moreNestedIfCondition = std::make_unique<CommonEventHandlerCondition>(nullptr, std::make_unique<CommonEventHandlerSet>(), nullptr); + helper.m_state->m_current_nested_event_handler_set = moreNestedIfCondition->m_condition_elements.get(); + helper.m_state->m_condition_stack.emplace(moreNestedIfCondition.get(), true); + + const auto result = helper.PerformTest(); + + REQUIRE(result); + REQUIRE(helper.m_consumed_token_count == 1); + REQUIRE(helper.m_state->m_current_event_handler_set == helper.m_event_handler_set.get()); + REQUIRE(helper.m_event_handler_set); + REQUIRE(helper.m_state->m_current_nested_event_handler_set->m_elements.empty()); // Doesn't add new element + + REQUIRE(helper.m_state->m_current_nested_event_handler_set == baseIfCondition->m_condition_elements.get()); + REQUIRE(helper.m_state->m_condition_stack.size() == 1); +} + +TEST_CASE("EventHandlerSetScopeSequences: CloseBlock closes all autoskip conditions to base", "[parsing][sequence][menu]") { + EventHandlerSetSequenceTestsHelper helper(FeatureLevel::IW4, false); + const TokenPos pos; + helper.Tokens({SimpleParserValue::Character(pos, '}'), SimpleParserValue::EndOfFile(pos)}); + + const auto baseIfCondition = std::make_unique<CommonEventHandlerCondition>(nullptr, std::make_unique<CommonEventHandlerSet>(), nullptr); + helper.m_state->m_current_nested_event_handler_set = baseIfCondition->m_condition_elements.get(); + helper.m_state->m_condition_stack.emplace(baseIfCondition.get()); + + const auto nestedIfCondition = std::make_unique<CommonEventHandlerCondition>(nullptr, std::make_unique<CommonEventHandlerSet>(), nullptr); + helper.m_state->m_current_nested_event_handler_set = nestedIfCondition->m_condition_elements.get(); + helper.m_state->m_condition_stack.emplace(nestedIfCondition.get(), true); + + const auto result = helper.PerformTest(); + + REQUIRE(result); + REQUIRE(helper.m_consumed_token_count == 1); + REQUIRE(helper.m_state->m_current_event_handler_set == helper.m_event_handler_set.get()); + REQUIRE(helper.m_event_handler_set); + REQUIRE(helper.m_state->m_current_nested_event_handler_set->m_elements.empty()); // Doesn't add new element + + REQUIRE(helper.m_state->m_current_nested_event_handler_set == helper.m_event_handler_set.get()); + REQUIRE(helper.m_state->m_condition_stack.empty()); +} + +#pragma endregion +} // namespace test::parsing::menu::sequence::event_handler_set diff --git a/test/ObjLoadingTests/Parsing/Menu/Sequence/ItemScopeSequencesTests.cpp b/test/ObjLoadingTests/Parsing/Menu/Sequence/ItemScopeSequencesTests.cpp index e15e87646..9674dc158 100644 --- a/test/ObjLoadingTests/Parsing/Menu/Sequence/ItemScopeSequencesTests.cpp +++ b/test/ObjLoadingTests/Parsing/Menu/Sequence/ItemScopeSequencesTests.cpp @@ -1,92 +1,73 @@ #include <catch2/catch_test_macros.hpp> #include <catch2/generators/catch_generators.hpp> -#include "Utils/ClassUtils.h" #include "Parsing/Menu/Sequence/ItemScopeSequences.h" #include "Parsing/Mock/MockLexer.h" +#include "Utils/ClassUtils.h" using namespace menu; -namespace test::parsing::menu::sequence::item -{ - class ItemSequenceTestsHelper - { - public: - std::vector<std::unique_ptr<MenuFileParser::sequence_t>> m_all_sequences; - std::vector<MenuFileParser::sequence_t*> m_scope_sequences; - std::unique_ptr<MenuFileParserState> m_state; - std::unique_ptr<ILexer<SimpleParserValue>> m_lexer; - - std::unique_ptr<CommonItemDef> m_item; - - unsigned m_consumed_token_count; - - explicit ItemSequenceTestsHelper(FeatureLevel featureLevel, const bool permissive) - : m_state(std::make_unique<MenuFileParserState>(featureLevel, false)), - m_item(std::make_unique<CommonItemDef>()), - m_consumed_token_count(0u) - { - ItemScopeSequences scopeSequences(m_all_sequences, m_scope_sequences); - scopeSequences.AddSequences(m_state->m_feature_level, permissive); - - m_state->m_current_menu = m_state->m_menus.emplace_back(std::make_unique<CommonMenuDef>()).get(); - m_state->m_current_item = m_item.get(); - } - - void Tokens(std::initializer_list<Movable<SimpleParserValue>> tokens) - { - m_lexer = std::make_unique<MockLexer<SimpleParserValue>>(tokens, SimpleParserValue::EndOfFile(TokenPos())); - } - - void Tokens(std::vector<SimpleParserValue> tokens) - { - m_lexer = std::make_unique<MockLexer<SimpleParserValue>>(std::move(tokens), SimpleParserValue::EndOfFile(TokenPos())); - } - - bool PerformTest() - { - REQUIRE(m_lexer); - - m_consumed_token_count = 0; - for (const auto* sequence : m_scope_sequences) - { - const auto couldMatch = sequence->MatchSequence(m_lexer.get(), m_state.get(), m_consumed_token_count); - if (couldMatch) - { - m_lexer->PopTokens(static_cast<int>(m_consumed_token_count)); - return couldMatch; - } - } - - return false; - } - }; - - TEST_CASE("ItemScopeSequences: Simple dvarStrList works", "[parsing][sequence][menu]") - { - ItemSequenceTestsHelper helper(FeatureLevel::IW4, false); - const TokenPos pos; - helper.Tokens({ - SimpleParserValue::Identifier(pos, new std::string("dvarStrList")), - SimpleParserValue::Character(pos, '{'), - SimpleParserValue::String(pos, new std::string("@MENU_AUTO")), - SimpleParserValue::String(pos, new std::string("auto")), - SimpleParserValue::String(pos, new std::string("@MENU_STANDARD_4_3")), - SimpleParserValue::String(pos, new std::string("standard")), - SimpleParserValue::String(pos, new std::string("@MENU_WIDE_16_10")), - SimpleParserValue::String(pos, new std::string("wide 16:10")), - SimpleParserValue::String(pos, new std::string("@MENU_WIDE_16_9")), - SimpleParserValue::String(pos, new std::string("wide 16:9")), - SimpleParserValue::Character(pos, '}'), - SimpleParserValue::EndOfFile(pos) - }); - - helper.m_item->m_feature_type = CommonItemFeatureType::MULTI_VALUE; - helper.m_item->m_multi_value_features = std::make_unique<CommonItemFeaturesMultiValue>(); - - const auto result = helper.PerformTest(); - - REQUIRE(result); - REQUIRE(helper.m_consumed_token_count == 11); +namespace test::parsing::menu::sequence::item { +class ItemSequenceTestsHelper { +public: + std::vector<std::unique_ptr<MenuFileParser::sequence_t>> m_all_sequences; + std::vector<MenuFileParser::sequence_t *> m_scope_sequences; + std::unique_ptr<MenuFileParserState> m_state; + std::unique_ptr<ILexer<SimpleParserValue>> m_lexer; + + std::unique_ptr<CommonItemDef> m_item; + + unsigned m_consumed_token_count; + + explicit ItemSequenceTestsHelper(FeatureLevel featureLevel, const bool permissive) + : m_state(std::make_unique<MenuFileParserState>(featureLevel, false)), m_item(std::make_unique<CommonItemDef>()), m_consumed_token_count(0u) { + ItemScopeSequences scopeSequences(m_all_sequences, m_scope_sequences); + scopeSequences.AddSequences(m_state->m_feature_level, permissive); + + m_state->m_current_menu = m_state->m_menus.emplace_back(std::make_unique<CommonMenuDef>()).get(); + m_state->m_current_item = m_item.get(); + } + + void Tokens(std::initializer_list<Movable<SimpleParserValue>> tokens) { + m_lexer = std::make_unique<MockLexer<SimpleParserValue>>(tokens, SimpleParserValue::EndOfFile(TokenPos())); + } + + void Tokens(std::vector<SimpleParserValue> tokens) { + m_lexer = std::make_unique<MockLexer<SimpleParserValue>>(std::move(tokens), SimpleParserValue::EndOfFile(TokenPos())); + } + + bool PerformTest() { + REQUIRE(m_lexer); + + m_consumed_token_count = 0; + for (const auto *sequence : m_scope_sequences) { + const auto couldMatch = sequence->MatchSequence(m_lexer.get(), m_state.get(), m_consumed_token_count); + if (couldMatch) { + m_lexer->PopTokens(static_cast<int>(m_consumed_token_count)); + return couldMatch; + } } + + return false; + } +}; + +TEST_CASE("ItemScopeSequences: Simple dvarStrList works", "[parsing][sequence][menu]") { + ItemSequenceTestsHelper helper(FeatureLevel::IW4, false); + const TokenPos pos; + helper.Tokens({SimpleParserValue::Identifier(pos, new std::string("dvarStrList")), SimpleParserValue::Character(pos, '{'), + SimpleParserValue::String(pos, new std::string("@MENU_AUTO")), SimpleParserValue::String(pos, new std::string("auto")), + SimpleParserValue::String(pos, new std::string("@MENU_STANDARD_4_3")), SimpleParserValue::String(pos, new std::string("standard")), + SimpleParserValue::String(pos, new std::string("@MENU_WIDE_16_10")), SimpleParserValue::String(pos, new std::string("wide 16:10")), + SimpleParserValue::String(pos, new std::string("@MENU_WIDE_16_9")), SimpleParserValue::String(pos, new std::string("wide 16:9")), + SimpleParserValue::Character(pos, '}'), SimpleParserValue::EndOfFile(pos)}); + + helper.m_item->m_feature_type = CommonItemFeatureType::MULTI_VALUE; + helper.m_item->m_multi_value_features = std::make_unique<CommonItemFeaturesMultiValue>(); + + const auto result = helper.PerformTest(); + + REQUIRE(result); + REQUIRE(helper.m_consumed_token_count == 11); } +} // namespace test::parsing::menu::sequence::item diff --git a/test/ParserTestUtils/Parsing/Mock/MockLexer.h b/test/ParserTestUtils/Parsing/Mock/MockLexer.h index 78be4b34b..9cae532f4 100644 --- a/test/ParserTestUtils/Parsing/Mock/MockLexer.h +++ b/test/ParserTestUtils/Parsing/Mock/MockLexer.h @@ -1,74 +1,49 @@ #pragma once -#include <vector> #include <iterator> +#include <vector> -#include "Utils/ClassUtils.h" #include "Parsing/ILexer.h" +#include "Utils/ClassUtils.h" -template <typename TokenType> -class MockLexer final : public ILexer<TokenType> -{ - // TokenType must inherit IParserValue - static_assert(std::is_base_of<IParserValue, TokenType>::value); +template <typename TokenType> class MockLexer final : public ILexer<TokenType> { + // TokenType must inherit IParserValue + static_assert(std::is_base_of<IParserValue, TokenType>::value); - std::vector<TokenType> m_tokens; - TokenType m_eof; - size_t m_pop_count; + std::vector<TokenType> m_tokens; + TokenType m_eof; + size_t m_pop_count; public: - MockLexer(std::initializer_list<Movable<TokenType>> tokens, TokenType eof) - : m_tokens(std::make_move_iterator(tokens.begin()), std::make_move_iterator(tokens.end())), - m_eof(std::move(eof)), - m_pop_count(0u) - { - } + MockLexer(std::initializer_list<Movable<TokenType>> tokens, TokenType eof) + : m_tokens(std::make_move_iterator(tokens.begin()), std::make_move_iterator(tokens.end())), m_eof(std::move(eof)), m_pop_count(0u) {} - MockLexer(std::vector<TokenType> tokens, TokenType eof) - : m_tokens(std::move(tokens)), - m_eof(std::move(eof)), - m_pop_count(0u) - { - } + MockLexer(std::vector<TokenType> tokens, TokenType eof) : m_tokens(std::move(tokens)), m_eof(std::move(eof)), m_pop_count(0u) {} - ~MockLexer() override = default; - MockLexer(const MockLexer& other) = delete; - MockLexer(MockLexer&& other) noexcept = default; - MockLexer& operator=(const MockLexer& other) = delete; - MockLexer& operator=(MockLexer&& other) noexcept = default; + ~MockLexer() override = default; + MockLexer(const MockLexer &other) = delete; + MockLexer(MockLexer &&other) noexcept = default; + MockLexer &operator=(const MockLexer &other) = delete; + MockLexer &operator=(MockLexer &&other) noexcept = default; - const TokenType& GetToken(const unsigned index) override - { - const auto absoluteIndex = m_pop_count + index; - if (absoluteIndex < m_tokens.size()) - return m_tokens[absoluteIndex]; + const TokenType &GetToken(const unsigned index) override { + const auto absoluteIndex = m_pop_count + index; + if (absoluteIndex < m_tokens.size()) + return m_tokens[absoluteIndex]; - return m_eof; - } + return m_eof; + } - void PopTokens(const int amount) override - { - assert(amount >= 0); - m_pop_count += static_cast<size_t>(amount); - } + void PopTokens(const int amount) override { + assert(amount >= 0); + m_pop_count += static_cast<size_t>(amount); + } - bool IsEof() override - { - return !m_tokens.empty() || m_pop_count >= m_tokens.size(); - } + bool IsEof() override { return !m_tokens.empty() || m_pop_count >= m_tokens.size(); } - const TokenPos& GetPos() override - { - return !m_tokens.empty() && m_pop_count < m_tokens.size() ? m_tokens[m_pop_count].GetPos() : m_eof.GetPos(); - } + const TokenPos &GetPos() override { return !m_tokens.empty() && m_pop_count < m_tokens.size() ? m_tokens[m_pop_count].GetPos() : m_eof.GetPos(); } - _NODISCARD size_t GetPopCount() const - { - return m_pop_count; - } + _NODISCARD size_t GetPopCount() const { return m_pop_count; } - _NODISCARD ParserLine GetLineForPos(const TokenPos& pos) const override - { - return ParserLine(); - } + _NODISCARD ParserLine GetLineForPos(const TokenPos &pos) const override { return ParserLine(); } }; diff --git a/test/ParserTestUtils/Parsing/Mock/MockPackValueSupplier.cpp b/test/ParserTestUtils/Parsing/Mock/MockPackValueSupplier.cpp index a839dec9b..c0977db52 100644 --- a/test/ParserTestUtils/Parsing/Mock/MockPackValueSupplier.cpp +++ b/test/ParserTestUtils/Parsing/Mock/MockPackValueSupplier.cpp @@ -2,7 +2,4 @@ #include "Parsing/Impl/PackDefinitionStreamProxy.h" -int MockPackValueSupplier::GetCurrentPack() const -{ - return PackDefinitionStreamProxy::DEFAULT_PACK; -} +int MockPackValueSupplier::GetCurrentPack() const { return PackDefinitionStreamProxy::DEFAULT_PACK; } diff --git a/test/ParserTestUtils/Parsing/Mock/MockPackValueSupplier.h b/test/ParserTestUtils/Parsing/Mock/MockPackValueSupplier.h index adcb01140..e18ed1c37 100644 --- a/test/ParserTestUtils/Parsing/Mock/MockPackValueSupplier.h +++ b/test/ParserTestUtils/Parsing/Mock/MockPackValueSupplier.h @@ -1,10 +1,9 @@ #pragma once -#include "Utils/ClassUtils.h" #include "Parsing/IPackValueSupplier.h" +#include "Utils/ClassUtils.h" -class MockPackValueSupplier final : public IPackValueSupplier -{ +class MockPackValueSupplier final : public IPackValueSupplier { public: - _NODISCARD int GetCurrentPack() const override; + _NODISCARD int GetCurrentPack() const override; }; diff --git a/test/ParserTestUtils/Parsing/Mock/MockParserLineStream.cpp b/test/ParserTestUtils/Parsing/Mock/MockParserLineStream.cpp index 5bae82b4e..a4c138d0b 100644 --- a/test/ParserTestUtils/Parsing/Mock/MockParserLineStream.cpp +++ b/test/ParserTestUtils/Parsing/Mock/MockParserLineStream.cpp @@ -2,67 +2,47 @@ #include <algorithm> -MockParserLineStream::MockParserLineStream(const std::vector<std::string>& lines) -{ - AddIncludeLines(MOCK_FILENAME, lines); - m_include_positions.emplace_back(MOCK_FILENAME, lines); +MockParserLineStream::MockParserLineStream(const std::vector<std::string> &lines) { + AddIncludeLines(MOCK_FILENAME, lines); + m_include_positions.emplace_back(MOCK_FILENAME, lines); } -MockParserLineStream::IncludePos::IncludePos(std::string filename, const std::vector<std::string>& lines) - : m_filename(std::make_shared<std::string>(std::move(filename))), - m_lines(lines), - m_pos(0) -{ -} - -void MockParserLineStream::AddIncludeLines(const std::string& filename, const std::vector<std::string>& lines) -{ - m_include_lines[filename] = lines; -} +MockParserLineStream::IncludePos::IncludePos(std::string filename, const std::vector<std::string> &lines) + : m_filename(std::make_shared<std::string>(std::move(filename))), m_lines(lines), m_pos(0) {} -ParserLine MockParserLineStream::NextLine() -{ - while (!m_include_positions.empty()) - { - auto& currentInclude = m_include_positions.back(); +void MockParserLineStream::AddIncludeLines(const std::string &filename, const std::vector<std::string> &lines) { m_include_lines[filename] = lines; } - if (currentInclude.m_pos < currentInclude.m_lines.size()) - { - const auto line = currentInclude.m_pos++; - return ParserLine(currentInclude.m_filename, static_cast<int>(line + 1), currentInclude.m_lines[line]); - } +ParserLine MockParserLineStream::NextLine() { + while (!m_include_positions.empty()) { + auto ¤tInclude = m_include_positions.back(); - m_include_positions.pop_back(); + if (currentInclude.m_pos < currentInclude.m_lines.size()) { + const auto line = currentInclude.m_pos++; + return ParserLine(currentInclude.m_filename, static_cast<int>(line + 1), currentInclude.m_lines[line]); } - return ParserLine(); + m_include_positions.pop_back(); + } + + return ParserLine(); } -bool MockParserLineStream::IncludeFile(const std::string& filename) -{ - const auto foundInclude = m_include_lines.find(filename); - if (foundInclude == m_include_lines.end()) - return false; +bool MockParserLineStream::IncludeFile(const std::string &filename) { + const auto foundInclude = m_include_lines.find(filename); + if (foundInclude == m_include_lines.end()) + return false; - m_include_positions.emplace_back(foundInclude->first, foundInclude->second); - return true; + m_include_positions.emplace_back(foundInclude->first, foundInclude->second); + return true; } -void MockParserLineStream::PopCurrentFile() -{ - if (!m_include_positions.empty()) - m_include_positions.pop_back(); +void MockParserLineStream::PopCurrentFile() { + if (!m_include_positions.empty()) + m_include_positions.pop_back(); } -bool MockParserLineStream::IsOpen() const -{ - return true; -} +bool MockParserLineStream::IsOpen() const { return true; } -bool MockParserLineStream::Eof() const -{ - return !std::any_of(m_include_positions.begin(), m_include_positions.end(), [](const IncludePos& pos) - { - return pos.m_pos < pos.m_lines.size(); - }); +bool MockParserLineStream::Eof() const { + return !std::any_of(m_include_positions.begin(), m_include_positions.end(), [](const IncludePos &pos) { return pos.m_pos < pos.m_lines.size(); }); } diff --git a/test/ParserTestUtils/Parsing/Mock/MockParserLineStream.h b/test/ParserTestUtils/Parsing/Mock/MockParserLineStream.h index 31e10b5ba..91e29c54d 100644 --- a/test/ParserTestUtils/Parsing/Mock/MockParserLineStream.h +++ b/test/ParserTestUtils/Parsing/Mock/MockParserLineStream.h @@ -1,36 +1,34 @@ #pragma once -#include <vector> #include <unordered_map> +#include <vector> #include "Parsing/IParserLineStream.h" -class MockParserLineStream final : public IParserLineStream -{ +class MockParserLineStream final : public IParserLineStream { public: - static constexpr const char* MOCK_FILENAME = "MockFile"; + static constexpr const char *MOCK_FILENAME = "MockFile"; private: - class IncludePos - { - public: - std::shared_ptr<std::string> m_filename; - const std::vector<std::string>& m_lines; - unsigned m_pos; - - IncludePos(std::string filename, const std::vector<std::string>& lines); - }; - - std::unordered_map<std::string, std::vector<std::string>> m_include_lines; - std::vector<IncludePos> m_include_positions; + class IncludePos { + public: + std::shared_ptr<std::string> m_filename; + const std::vector<std::string> &m_lines; + unsigned m_pos; + + IncludePos(std::string filename, const std::vector<std::string> &lines); + }; + + std::unordered_map<std::string, std::vector<std::string>> m_include_lines; + std::vector<IncludePos> m_include_positions; public: - explicit MockParserLineStream(const std::vector<std::string>& lines); - - void AddIncludeLines(const std::string& filename, const std::vector<std::string>& lines); - ParserLine NextLine() override; - bool IncludeFile(const std::string& filename) override; - void PopCurrentFile() override; - _NODISCARD bool IsOpen() const override; - _NODISCARD bool Eof() const override; + explicit MockParserLineStream(const std::vector<std::string> &lines); + + void AddIncludeLines(const std::string &filename, const std::vector<std::string> &lines); + ParserLine NextLine() override; + bool IncludeFile(const std::string &filename) override; + void PopCurrentFile() override; + _NODISCARD bool IsOpen() const override; + _NODISCARD bool Eof() const override; }; diff --git a/test/ParserTestUtils/Parsing/Mock/MockSequence.h b/test/ParserTestUtils/Parsing/Mock/MockSequence.h index bd052e297..5f263cc1c 100644 --- a/test/ParserTestUtils/Parsing/Mock/MockSequence.h +++ b/test/ParserTestUtils/Parsing/Mock/MockSequence.h @@ -2,48 +2,34 @@ #include "Parsing/Sequence/AbstractSequence.h" -struct MockSequenceState -{ - char m_dummy; +struct MockSequenceState { + char m_dummy; }; -template<typename TokenType> -class MockSequence final : public AbstractSequence<TokenType, MockSequenceState> -{ +template <typename TokenType> class MockSequence final : public AbstractSequence<TokenType, MockSequenceState> { public: - typedef AbstractSequence<TokenType, MockSequenceState> parent_t; + typedef AbstractSequence<TokenType, MockSequenceState> parent_t; private: - using parent_t::AddMatchers; - using parent_t::AddLabeledMatchers; + using parent_t::AddLabeledMatchers; + using parent_t::AddMatchers; - std::function<void(SequenceResult<TokenType>&)> m_handler; + std::function<void(SequenceResult<TokenType> &)> m_handler; protected: - void ProcessMatch(MockSequenceState* state, SequenceResult<TokenType>& result) const override - { - if (m_handler) - m_handler(result); - } + void ProcessMatch(MockSequenceState *state, SequenceResult<TokenType> &result) const override { + if (m_handler) + m_handler(result); + } public: - void AddMockMatchers(std::initializer_list<Movable<std::unique_ptr<typename parent_t::matcher_t>>> matchers) - { - AddMatchers(matchers); - } - - void AddMockLabeledMatchers(std::initializer_list<Movable<std::unique_ptr<typename parent_t::matcher_t>>> matchers, const int label) - { - AddLabeledMatchers(matchers, label); - } - - void Handle(std::function<void(SequenceResult<TokenType>&)> handler) - { - m_handler = std::move(handler); - } - - IMatcherForLabelSupplier<TokenType>* GetLabelSupplier() - { - return this; - } + void AddMockMatchers(std::initializer_list<Movable<std::unique_ptr<typename parent_t::matcher_t>>> matchers) { AddMatchers(matchers); } + + void AddMockLabeledMatchers(std::initializer_list<Movable<std::unique_ptr<typename parent_t::matcher_t>>> matchers, const int label) { + AddLabeledMatchers(matchers, label); + } + + void Handle(std::function<void(SequenceResult<TokenType> &)> handler) { m_handler = std::move(handler); } + + IMatcherForLabelSupplier<TokenType> *GetLabelSupplier() { return this; } }; \ No newline at end of file diff --git a/test/ParserTests/Parsing/Impl/CommentRemovingStreamProxyTests.cpp b/test/ParserTests/Parsing/Impl/CommentRemovingStreamProxyTests.cpp index af6fca37e..324302804 100644 --- a/test/ParserTests/Parsing/Impl/CommentRemovingStreamProxyTests.cpp +++ b/test/ParserTests/Parsing/Impl/CommentRemovingStreamProxyTests.cpp @@ -4,250 +4,208 @@ #include "Parsing/Impl/CommentRemovingStreamProxy.h" #include "Parsing/Mock/MockParserLineStream.h" -namespace test::parsing::impl::comment_removing_stream_proxy -{ - TEST_CASE("CommentRemovingStreamProxy: Ensure simple single line comment is working", "[parsing][parsingstream]") - { - const std::vector<std::string> lines - { - "// hello", - "prefix // test", - "t//est" - }; - - MockParserLineStream mockStream(lines); - CommentRemovingStreamProxy proxy(&mockStream); - - { - auto line = proxy.NextLine(); - REQUIRE(line.m_line_number == 1); - REQUIRE(line.m_line.empty()); - } - - { - auto line = proxy.NextLine(); - REQUIRE(line.m_line_number == 2); - REQUIRE(line.m_line == "prefix "); - } - - { - auto line = proxy.NextLine(); - REQUIRE(line.m_line_number == 3); - REQUIRE(line.m_line == "t"); - } - - REQUIRE(proxy.Eof()); - } - - TEST_CASE("CommentRemovingStreamProxy: Ensure single line comment expands to next line on backslash", "[parsing][parsingstream]") - { - const std::vector<std::string> lines - { - "// hello\\", - "this should still be a comment", - "this should not be a comment anymore" - }; - - MockParserLineStream mockStream(lines); - CommentRemovingStreamProxy proxy(&mockStream); - - { - auto line = proxy.NextLine(); - REQUIRE(line.m_line_number == 1); - REQUIRE(line.m_line.empty()); - } - - { - auto line = proxy.NextLine(); - REQUIRE(line.m_line_number == 2); - REQUIRE(line.m_line.empty()); - } - - { - auto line = proxy.NextLine(); - REQUIRE(line.m_line_number == 3); - REQUIRE(line.m_line == "this should not be a comment anymore"); - } - - REQUIRE(proxy.Eof()); - } - - TEST_CASE("CommentRemovingStreamProxy: Ensure single line comment expands to next line on backslash and is repeatable", "[parsing][parsingstream]") - { - const std::vector<std::string> lines - { - "// hello\\", - "this should still be a comment \\", - "this as well", - "this not anymore" - }; - - MockParserLineStream mockStream(lines); - CommentRemovingStreamProxy proxy(&mockStream); - - { - auto line = proxy.NextLine(); - REQUIRE(line.m_line_number == 1); - REQUIRE(line.m_line.empty()); - } - - { - auto line = proxy.NextLine(); - REQUIRE(line.m_line_number == 2); - REQUIRE(line.m_line.empty()); - } - - { - auto line = proxy.NextLine(); - REQUIRE(line.m_line_number == 3); - REQUIRE(line.m_line.empty()); - } - - { - auto line = proxy.NextLine(); - REQUIRE(line.m_line_number == 4); - REQUIRE(line.m_line == "this not anymore"); - } - - REQUIRE(proxy.Eof()); - } - - TEST_CASE("CommentRemovingStreamProxy: Ensure backslash must be last character to expand single line comment to next line", "[parsing][parsingstream]") - { - const std::vector<std::string> lines - { - "// hello\\", - "this should still be a comment \\ ", - "this not anymore" - }; - - MockParserLineStream mockStream(lines); - CommentRemovingStreamProxy proxy(&mockStream); - - { - auto line = proxy.NextLine(); - REQUIRE(line.m_line_number == 1); - REQUIRE(line.m_line.empty()); - } - - { - auto line = proxy.NextLine(); - REQUIRE(line.m_line_number == 2); - REQUIRE(line.m_line.empty()); - } - - { - auto line = proxy.NextLine(); - REQUIRE(line.m_line_number == 3); - REQUIRE(line.m_line == "this not anymore"); - } - - REQUIRE(proxy.Eof()); - } - - TEST_CASE("CommentRemovingStreamProxy: Ensure simple multiline comment works on one line", "[parsing][parsingstream]") - { - const std::vector<std::string> lines - { - "hello/* hell*/ world", - "/*this should be a comment*/", - "Hello /*asdf*/", - "/*asdf*/World" - }; - - MockParserLineStream mockStream(lines); - CommentRemovingStreamProxy proxy(&mockStream); - - { - auto line = proxy.NextLine(); - REQUIRE(line.m_line_number == 1); - REQUIRE(line.m_line == "hello world"); - } - - { - auto line = proxy.NextLine(); - REQUIRE(line.m_line_number == 2); - REQUIRE(line.m_line.empty()); - } - - { - auto line = proxy.NextLine(); - REQUIRE(line.m_line_number == 3); - REQUIRE(line.m_line == "Hello "); - } - - { - auto line = proxy.NextLine(); - REQUIRE(line.m_line_number == 4); - REQUIRE(line.m_line == "World"); - } - - REQUIRE(proxy.Eof()); - } - - TEST_CASE("CommentRemovingStreamProxy: Ensure simple multiline comment works over multiple lines", "[parsing][parsingstream]") - { - const std::vector<std::string> lines - { - "hello/* hell", - " hell*/ world/*nope", - "notatall", - "hehe*/xd" - }; - - MockParserLineStream mockStream(lines); - CommentRemovingStreamProxy proxy(&mockStream); - - { - auto line = proxy.NextLine(); - REQUIRE(line.m_line_number == 1); - REQUIRE(line.m_line == "hello"); - } - - { - auto line = proxy.NextLine(); - REQUIRE(line.m_line_number == 2); - REQUIRE(line.m_line == " world"); - } - - { - auto line = proxy.NextLine(); - REQUIRE(line.m_line_number == 3); - REQUIRE(line.m_line.empty()); - } - - { - auto line = proxy.NextLine(); - REQUIRE(line.m_line_number == 4); - REQUIRE(line.m_line == "xd"); - } - - REQUIRE(proxy.Eof()); - } - - TEST_CASE("CommentRemovingStreamProxy: Can have multiple comment blocks in one line", "[parsing][parsingstream]") - { - const std::vector<std::string> lines - { - "Hello/* lovely*/ world and/* beautiful*/ universe", - "Hello/* lovely*/ world// and beautiful universe", - }; - - MockParserLineStream mockStream(lines); - CommentRemovingStreamProxy proxy(&mockStream); - - { - auto line = proxy.NextLine(); - REQUIRE(line.m_line_number == 1); - REQUIRE(line.m_line == "Hello world and universe"); - } - - { - auto line = proxy.NextLine(); - REQUIRE(line.m_line_number == 2); - REQUIRE(line.m_line == "Hello world"); - } - - REQUIRE(proxy.Eof()); - } +namespace test::parsing::impl::comment_removing_stream_proxy { +TEST_CASE("CommentRemovingStreamProxy: Ensure simple single line comment is working", "[parsing][parsingstream]") { + const std::vector<std::string> lines{"// hello", "prefix // test", "t//est"}; + + MockParserLineStream mockStream(lines); + CommentRemovingStreamProxy proxy(&mockStream); + + { + auto line = proxy.NextLine(); + REQUIRE(line.m_line_number == 1); + REQUIRE(line.m_line.empty()); + } + + { + auto line = proxy.NextLine(); + REQUIRE(line.m_line_number == 2); + REQUIRE(line.m_line == "prefix "); + } + + { + auto line = proxy.NextLine(); + REQUIRE(line.m_line_number == 3); + REQUIRE(line.m_line == "t"); + } + + REQUIRE(proxy.Eof()); } + +TEST_CASE("CommentRemovingStreamProxy: Ensure single line comment expands to next line on backslash", "[parsing][parsingstream]") { + const std::vector<std::string> lines{"// hello\\", "this should still be a comment", "this should not be a comment anymore"}; + + MockParserLineStream mockStream(lines); + CommentRemovingStreamProxy proxy(&mockStream); + + { + auto line = proxy.NextLine(); + REQUIRE(line.m_line_number == 1); + REQUIRE(line.m_line.empty()); + } + + { + auto line = proxy.NextLine(); + REQUIRE(line.m_line_number == 2); + REQUIRE(line.m_line.empty()); + } + + { + auto line = proxy.NextLine(); + REQUIRE(line.m_line_number == 3); + REQUIRE(line.m_line == "this should not be a comment anymore"); + } + + REQUIRE(proxy.Eof()); +} + +TEST_CASE("CommentRemovingStreamProxy: Ensure single line comment expands to next line on backslash and is repeatable", "[parsing][parsingstream]") { + const std::vector<std::string> lines{"// hello\\", "this should still be a comment \\", "this as well", "this not anymore"}; + + MockParserLineStream mockStream(lines); + CommentRemovingStreamProxy proxy(&mockStream); + + { + auto line = proxy.NextLine(); + REQUIRE(line.m_line_number == 1); + REQUIRE(line.m_line.empty()); + } + + { + auto line = proxy.NextLine(); + REQUIRE(line.m_line_number == 2); + REQUIRE(line.m_line.empty()); + } + + { + auto line = proxy.NextLine(); + REQUIRE(line.m_line_number == 3); + REQUIRE(line.m_line.empty()); + } + + { + auto line = proxy.NextLine(); + REQUIRE(line.m_line_number == 4); + REQUIRE(line.m_line == "this not anymore"); + } + + REQUIRE(proxy.Eof()); +} + +TEST_CASE("CommentRemovingStreamProxy: Ensure backslash must be last character to expand single line comment to next line", "[parsing][parsingstream]") { + const std::vector<std::string> lines{"// hello\\", "this should still be a comment \\ ", "this not anymore"}; + + MockParserLineStream mockStream(lines); + CommentRemovingStreamProxy proxy(&mockStream); + + { + auto line = proxy.NextLine(); + REQUIRE(line.m_line_number == 1); + REQUIRE(line.m_line.empty()); + } + + { + auto line = proxy.NextLine(); + REQUIRE(line.m_line_number == 2); + REQUIRE(line.m_line.empty()); + } + + { + auto line = proxy.NextLine(); + REQUIRE(line.m_line_number == 3); + REQUIRE(line.m_line == "this not anymore"); + } + + REQUIRE(proxy.Eof()); +} + +TEST_CASE("CommentRemovingStreamProxy: Ensure simple multiline comment works on one line", "[parsing][parsingstream]") { + const std::vector<std::string> lines{"hello/* hell*/ world", "/*this should be a comment*/", "Hello /*asdf*/", "/*asdf*/World"}; + + MockParserLineStream mockStream(lines); + CommentRemovingStreamProxy proxy(&mockStream); + + { + auto line = proxy.NextLine(); + REQUIRE(line.m_line_number == 1); + REQUIRE(line.m_line == "hello world"); + } + + { + auto line = proxy.NextLine(); + REQUIRE(line.m_line_number == 2); + REQUIRE(line.m_line.empty()); + } + + { + auto line = proxy.NextLine(); + REQUIRE(line.m_line_number == 3); + REQUIRE(line.m_line == "Hello "); + } + + { + auto line = proxy.NextLine(); + REQUIRE(line.m_line_number == 4); + REQUIRE(line.m_line == "World"); + } + + REQUIRE(proxy.Eof()); +} + +TEST_CASE("CommentRemovingStreamProxy: Ensure simple multiline comment works over multiple lines", "[parsing][parsingstream]") { + const std::vector<std::string> lines{"hello/* hell", " hell*/ world/*nope", "notatall", "hehe*/xd"}; + + MockParserLineStream mockStream(lines); + CommentRemovingStreamProxy proxy(&mockStream); + + { + auto line = proxy.NextLine(); + REQUIRE(line.m_line_number == 1); + REQUIRE(line.m_line == "hello"); + } + + { + auto line = proxy.NextLine(); + REQUIRE(line.m_line_number == 2); + REQUIRE(line.m_line == " world"); + } + + { + auto line = proxy.NextLine(); + REQUIRE(line.m_line_number == 3); + REQUIRE(line.m_line.empty()); + } + + { + auto line = proxy.NextLine(); + REQUIRE(line.m_line_number == 4); + REQUIRE(line.m_line == "xd"); + } + + REQUIRE(proxy.Eof()); +} + +TEST_CASE("CommentRemovingStreamProxy: Can have multiple comment blocks in one line", "[parsing][parsingstream]") { + const std::vector<std::string> lines{ + "Hello/* lovely*/ world and/* beautiful*/ universe", + "Hello/* lovely*/ world// and beautiful universe", + }; + + MockParserLineStream mockStream(lines); + CommentRemovingStreamProxy proxy(&mockStream); + + { + auto line = proxy.NextLine(); + REQUIRE(line.m_line_number == 1); + REQUIRE(line.m_line == "Hello world and universe"); + } + + { + auto line = proxy.NextLine(); + REQUIRE(line.m_line_number == 2); + REQUIRE(line.m_line == "Hello world"); + } + + REQUIRE(proxy.Eof()); +} +} // namespace test::parsing::impl::comment_removing_stream_proxy diff --git a/test/ParserTests/Parsing/Impl/DefinesStreamProxyTests.cpp b/test/ParserTests/Parsing/Impl/DefinesStreamProxyTests.cpp index ba3d53ce9..df6e351e9 100644 --- a/test/ParserTests/Parsing/Impl/DefinesStreamProxyTests.cpp +++ b/test/ParserTests/Parsing/Impl/DefinesStreamProxyTests.cpp @@ -4,741 +4,530 @@ #include "Parsing/Impl/DefinesStreamProxy.h" #include "Parsing/Mock/MockParserLineStream.h" -namespace test::parsing::impl::defines_stream_proxy -{ - void ExpectLine(IParserLineStream* stream, const int lineNumber, const std::string& value) - { - auto line = stream->NextLine(); - REQUIRE(line.m_line_number == lineNumber); - REQUIRE(line.m_line == value); - } - - TEST_CASE("DefinesStreamProxy: Ensure simple define and positive ifdef is working", "[parsing][parsingstream]") - { - const std::vector<std::string> lines - { - "#define ASDF", - "#ifdef ASDF", - "Hello World", - "#endif", - "Hello Galaxy" - }; - - MockParserLineStream mockStream(lines); - DefinesStreamProxy proxy(&mockStream); - - ExpectLine(&proxy, 1, ""); - ExpectLine(&proxy, 2, ""); - ExpectLine(&proxy, 3, "Hello World"); - ExpectLine(&proxy, 4, ""); - ExpectLine(&proxy, 5, "Hello Galaxy"); - - REQUIRE(proxy.Eof()); - } - - TEST_CASE("DefinesStreamProxy: Ensure simple define and negative ifdef is working", "[parsing][parsingstream]") - { - const std::vector<std::string> lines - { - "#define ASDF", - "#ifdef NONO", - "Hello World", - "#endif", - "Hello Galaxy" - }; - - MockParserLineStream mockStream(lines); - DefinesStreamProxy proxy(&mockStream); - - ExpectLine(&proxy, 1, ""); - ExpectLine(&proxy, 2, ""); - ExpectLine(&proxy, 3, ""); - ExpectLine(&proxy, 4, ""); - ExpectLine(&proxy, 5, "Hello Galaxy"); - - REQUIRE(proxy.Eof()); - } - - TEST_CASE("DefinesStreamProxy: Ensure simple define and positive ifndef is working", "[parsing][parsingstream]") - { - const std::vector<std::string> lines - { - "#define ASDF", - "#ifndef NONO", - "Hello World", - "#endif", - "Hello Galaxy" - }; - - MockParserLineStream mockStream(lines); - DefinesStreamProxy proxy(&mockStream); - - ExpectLine(&proxy, 1, ""); - ExpectLine(&proxy, 2, ""); - ExpectLine(&proxy, 3, "Hello World"); - ExpectLine(&proxy, 4, ""); - ExpectLine(&proxy, 5, "Hello Galaxy"); - - REQUIRE(proxy.Eof()); - } - - TEST_CASE("DefinesStreamProxy: Ensure simple define and negative ifndef is working", "[parsing][parsingstream]") - { - const std::vector<std::string> lines - { - "#define ASDF", - "#ifndef ASDF", - "Hello World", - "#endif", - "Hello Galaxy" - }; - - MockParserLineStream mockStream(lines); - DefinesStreamProxy proxy(&mockStream); - - ExpectLine(&proxy, 1, ""); - ExpectLine(&proxy, 2, ""); - ExpectLine(&proxy, 3, ""); - ExpectLine(&proxy, 4, ""); - ExpectLine(&proxy, 5, "Hello Galaxy"); - - REQUIRE(proxy.Eof()); - } - - TEST_CASE("DefinesStreamProxy: Ensure else is working", "[parsing][parsingstream]") - { - const std::vector<std::string> lines - { - "#define ASDF", - "#ifdef NONO", - "Hello World1", - "#else", - "Hello World2", - "#endif", - "Hello Galaxy" - }; - - MockParserLineStream mockStream(lines); - DefinesStreamProxy proxy(&mockStream); - - ExpectLine(&proxy, 1, ""); - ExpectLine(&proxy, 2, ""); - ExpectLine(&proxy, 3, ""); - ExpectLine(&proxy, 4, ""); - ExpectLine(&proxy, 5, "Hello World2"); - ExpectLine(&proxy, 6, ""); - ExpectLine(&proxy, 7, "Hello Galaxy"); - - REQUIRE(proxy.Eof()); - } - - TEST_CASE("DefinesStreamProxy: Ensure nested ifdef is working", "[parsing][parsingstream]") - { - const std::vector<std::string> lines - { - "#define ASDF", - "#ifdef ASDF", - "#ifdef NONO", - "Hello World1", - "#else", - "Hello World2", - "#endif", - "#else", - "#ifdef ASDF", - "Hello World3", - "#else", - "Hello World4", - "#endif", - "#endif", - "Hello Galaxy" - }; - - MockParserLineStream mockStream(lines); - DefinesStreamProxy proxy(&mockStream); - - ExpectLine(&proxy, 1, ""); - ExpectLine(&proxy, 2, ""); - ExpectLine(&proxy, 3, ""); - ExpectLine(&proxy, 4, ""); - ExpectLine(&proxy, 5, ""); - ExpectLine(&proxy, 6, "Hello World2"); - ExpectLine(&proxy, 7, ""); - ExpectLine(&proxy, 8, ""); - ExpectLine(&proxy, 9, ""); - ExpectLine(&proxy, 10, ""); - ExpectLine(&proxy, 11, ""); - ExpectLine(&proxy, 12, ""); - ExpectLine(&proxy, 13, ""); - ExpectLine(&proxy, 14, ""); - ExpectLine(&proxy, 15, "Hello Galaxy"); - - REQUIRE(proxy.Eof()); - } - - TEST_CASE("DefinesStreamProxy: Ensure undef is working", "[parsing][parsingstream]") - { - const std::vector<std::string> lines - { - "#define ASDF", - "#ifdef ASDF", - "Hello World", - "#endif", - "#undef ASDF", - "#ifdef ASDF", - "Hello World", - "#endif", - "Hello Galaxy" - }; - - MockParserLineStream mockStream(lines); - DefinesStreamProxy proxy(&mockStream); - - ExpectLine(&proxy, 1, ""); - ExpectLine(&proxy, 2, ""); - ExpectLine(&proxy, 3, "Hello World"); - ExpectLine(&proxy, 4, ""); - ExpectLine(&proxy, 5, ""); - ExpectLine(&proxy, 6, ""); - ExpectLine(&proxy, 7, ""); - ExpectLine(&proxy, 8, ""); - ExpectLine(&proxy, 9, "Hello Galaxy"); - - REQUIRE(proxy.Eof()); - } - - TEST_CASE("DefinesStreamProxy: Ensure undef does not undefine everything", "[parsing][parsingstream]") - { - const std::vector<std::string> lines - { - "#define ASDF", - "#ifdef ASDF", - "Hello World", - "#endif", - "#undef NONO", - "#ifdef ASDF", - "Hello World", - "#endif", - "Hello Galaxy" - }; - - MockParserLineStream mockStream(lines); - DefinesStreamProxy proxy(&mockStream); - - ExpectLine(&proxy, 1, ""); - ExpectLine(&proxy, 2, ""); - ExpectLine(&proxy, 3, "Hello World"); - ExpectLine(&proxy, 4, ""); - ExpectLine(&proxy, 5, ""); - ExpectLine(&proxy, 6, ""); - ExpectLine(&proxy, 7, "Hello World"); - ExpectLine(&proxy, 8, ""); - ExpectLine(&proxy, 9, "Hello Galaxy"); - - REQUIRE(proxy.Eof()); - } - - TEST_CASE("DefinesStreamProxy: Ensure simple defines are working", "[parsing][parsingstream]") - { - const std::vector<std::string> lines - { - "#define ASDF LOL", - "ASDF", - "A ASDF B", - "ASDF B", - "A ASDF" - }; - - MockParserLineStream mockStream(lines); - DefinesStreamProxy proxy(&mockStream); - - ExpectLine(&proxy, 1, ""); - ExpectLine(&proxy, 2, "LOL"); - ExpectLine(&proxy, 3, "A LOL B"); - ExpectLine(&proxy, 4, "LOL B"); - ExpectLine(&proxy, 5, "A LOL"); - - REQUIRE(proxy.Eof()); - } - - TEST_CASE("DefinesStreamProxy: Ensure defines can be surrounded by symbols", "[parsing][parsingstream]") - { - const std::vector<std::string> lines - { - "#define ASDF LOL", - "!ASDF%" - }; - - MockParserLineStream mockStream(lines); - DefinesStreamProxy proxy(&mockStream); - - ExpectLine(&proxy, 1, ""); - ExpectLine(&proxy, 2, "!LOL%"); - - REQUIRE(proxy.Eof()); - } - - TEST_CASE("DefinesStreamProxy: Ensure can use multiple defines in one line", "[parsing][parsingstream]") - { - const std::vector<std::string> lines - { - "#define A Hello", - "#define B world", - "A my dear B!" - }; - - MockParserLineStream mockStream(lines); - DefinesStreamProxy proxy(&mockStream); - - ExpectLine(&proxy, 1, ""); - ExpectLine(&proxy, 2, ""); - ExpectLine(&proxy, 3, "Hello my dear world!"); - - REQUIRE(proxy.Eof()); - } - - TEST_CASE("DefinesStreamProxy: Ensure defines in disabled block are ignored", "[parsing][parsingstream]") - { - const std::vector<std::string> lines - { - "#ifdef LOLO", - "#define hello world", - "#endif", - "hello" - }; - - MockParserLineStream mockStream(lines); - DefinesStreamProxy proxy(&mockStream); - - ExpectLine(&proxy, 1, ""); - ExpectLine(&proxy, 2, ""); - ExpectLine(&proxy, 3, ""); - ExpectLine(&proxy, 4, "hello"); - - REQUIRE(proxy.Eof()); - } - - TEST_CASE("DefinesStreamProxy: Ensure undefs in disabled block are ignored", "[parsing][parsingstream]") - { - const std::vector<std::string> lines - { - "#define hello world", - "#ifdef LOLO", - "#undef hello", - "#endif", - "hello" - }; - - MockParserLineStream mockStream(lines); - DefinesStreamProxy proxy(&mockStream); - - ExpectLine(&proxy, 1, ""); - ExpectLine(&proxy, 2, ""); - ExpectLine(&proxy, 3, ""); - ExpectLine(&proxy, 4, ""); - ExpectLine(&proxy, 5, "world"); - - REQUIRE(proxy.Eof()); - } - - TEST_CASE("DefinesStreamProxy: Ensure can define name with underscores and digits", "[parsing][parsingstream]") - { - const std::vector<std::string> lines - { - "#define __int16 short", - "unsigned __int16 value;" - }; - - MockParserLineStream mockStream(lines); - DefinesStreamProxy proxy(&mockStream); - - ExpectLine(&proxy, 1, ""); - ExpectLine(&proxy, 2, "unsigned short value;"); - - REQUIRE(proxy.Eof()); - } - - TEST_CASE("DefinesStreamProxy: Ensure define can render parameters", "[parsing][parsingstream]") - { - DefinesStreamProxy::Define define("helloworld", "hello universe"); - - std::vector<std::string> parameterNames({ - "universe" - }); - define.IdentifyParameters(parameterNames); - - std::vector<std::string> parameterValues({ - "mr moneyman" - }); - REQUIRE(define.Render(parameterValues) == "hello mr moneyman"); - } - - TEST_CASE("DefinesStreamProxy: Ensure define can render parameters in middle of symbols", "[parsing][parsingstream]") - { - DefinesStreamProxy::Define define("helloworld", "alignas(x)"); - - std::vector<std::string> parameterNames({ - "x" - }); - define.IdentifyParameters(parameterNames); - - std::vector<std::string> parameterValues({ - "1337" - }); - REQUIRE(define.Render(parameterValues) == "alignas(1337)"); - } - - TEST_CASE("DefinesStreamProxy: Ensure can add define with parameters", "[parsing][parsingstream]") - { - const std::vector<std::string> lines - { - "#define test(x) alignas(x)", - "struct test(1337) test_struct" - }; - - MockParserLineStream mockStream(lines); - DefinesStreamProxy proxy(&mockStream); - - ExpectLine(&proxy, 1, ""); - ExpectLine(&proxy, 2, "struct alignas(1337) test_struct"); - - REQUIRE(proxy.Eof()); - } - - TEST_CASE("DefinesStreamProxy: Ensure can use parameter multiple times", "[parsing][parsingstream]") - { - const std::vector<std::string> lines - { - "#define test(x) x|x|x|x", - "struct test(1337) test_struct" - }; - - MockParserLineStream mockStream(lines); - DefinesStreamProxy proxy(&mockStream); - - ExpectLine(&proxy, 1, ""); - ExpectLine(&proxy, 2, "struct 1337|1337|1337|1337 test_struct"); - - REQUIRE(proxy.Eof()); - } - - TEST_CASE("DefinesStreamProxy: Ensure can use parameterized define in between symbols", "[parsing][parsingstream]") - { - const std::vector<std::string> lines - { - "#define test(x) x|x|x|x", - "%test(5)%" - }; - - MockParserLineStream mockStream(lines); - DefinesStreamProxy proxy(&mockStream); - - ExpectLine(&proxy, 1, ""); - ExpectLine(&proxy, 2, "%5|5|5|5%"); - - REQUIRE(proxy.Eof()); - } - - TEST_CASE("DefinesStreamProxy: Ensure can define multiple parameters", "[parsing][parsingstream]") - { - const std::vector<std::string> lines - { - "#define test(a1, a2, a3) a1 + a2 = a3", - "make calc test(1, 2, 3);" - }; - - MockParserLineStream mockStream(lines); - DefinesStreamProxy proxy(&mockStream); - - ExpectLine(&proxy, 1, ""); - ExpectLine(&proxy, 2, "make calc 1 + 2 = 3;"); - - REQUIRE(proxy.Eof()); - } - - TEST_CASE("DefinesStreamProxy: Ensure can define multiple parameters without spacing", "[parsing][parsingstream]") - { - const std::vector<std::string> lines - { - "#define test(a1,a2,a3) a1+a2=a3", - "make calc test(1,2,3);" - }; - - MockParserLineStream mockStream(lines); - DefinesStreamProxy proxy(&mockStream); - - ExpectLine(&proxy, 1, ""); - ExpectLine(&proxy, 2, "make calc 1+2=3;"); - - REQUIRE(proxy.Eof()); - } - - TEST_CASE("DefinesStreamProxy: Ensure can define parameters with underscore", "[parsing][parsingstream]") - { - const std::vector<std::string> lines - { - "#define test(test_parameter) this is test_parameter", - "Apparently test(a very cool text);" - }; - - MockParserLineStream mockStream(lines); - DefinesStreamProxy proxy(&mockStream); - - ExpectLine(&proxy, 1, ""); - ExpectLine(&proxy, 2, "Apparently this is a very cool text;"); - - REQUIRE(proxy.Eof()); - } - - TEST_CASE("DefinesStreamProxy: Ensure simple if is working with truthy value", "[parsing][parsingstream]") - { - const std::vector<std::string> lines - { - "#if 1", - "Hello World", - "#endif", - }; - - MockParserLineStream mockStream(lines); - DefinesStreamProxy proxy(&mockStream); - - ExpectLine(&proxy, 1, ""); - ExpectLine(&proxy, 2, "Hello World"); - ExpectLine(&proxy, 3, ""); - - REQUIRE(proxy.Eof()); - } - - TEST_CASE("DefinesStreamProxy: Ensure simple if is working with non-truthy value", "[parsing][parsingstream]") - { - const std::vector<std::string> lines - { - "#if 0", - "Hello World", - "#endif", - }; - - MockParserLineStream mockStream(lines); - DefinesStreamProxy proxy(&mockStream); - - ExpectLine(&proxy, 1, ""); - ExpectLine(&proxy, 2, ""); - ExpectLine(&proxy, 3, ""); - - REQUIRE(proxy.Eof()); - } - - TEST_CASE("DefinesStreamProxy: Ensure simple if is working with calculated values", "[parsing][parsingstream]") - { - const std::vector<std::string> lines - { - "#if 0 || 1", - "Hello World", - "#endif", - "#if 0 && 1", - "Hello World", - "#endif", - }; - - MockParserLineStream mockStream(lines); - DefinesStreamProxy proxy(&mockStream); - - ExpectLine(&proxy, 1, ""); - ExpectLine(&proxy, 2, "Hello World"); - ExpectLine(&proxy, 3, ""); - ExpectLine(&proxy, 4, ""); - ExpectLine(&proxy, 5, ""); - ExpectLine(&proxy, 6, ""); - - REQUIRE(proxy.Eof()); - } - - TEST_CASE("DefinesStreamProxy: Ensure can handle defined operator with defined definition", "[parsing][parsingstream]") - { - const std::vector<std::string> lines - { - "#define someStuff 1", - "#if defined(someStuff)", - "Hello World", - "#endif", - }; - - MockParserLineStream mockStream(lines); - DefinesStreamProxy proxy(&mockStream); - - ExpectLine(&proxy, 1, ""); - ExpectLine(&proxy, 2, ""); - ExpectLine(&proxy, 3, "Hello World"); - ExpectLine(&proxy, 4, ""); - - REQUIRE(proxy.Eof()); - } - - TEST_CASE("DefinesStreamProxy: Ensure can handle defined operator with undefined definition", "[parsing][parsingstream]") - { - const std::vector<std::string> lines - { - "#define someStuff 1", - "#if defined(someStuff) && defined(thisIsNotDefined)", - "Hello World", - "#endif", - "#if defined(thisIsNotDefined)", - "Hello World", - "#endif", - }; - - MockParserLineStream mockStream(lines); - DefinesStreamProxy proxy(&mockStream); - - ExpectLine(&proxy, 1, ""); - ExpectLine(&proxy, 2, ""); - ExpectLine(&proxy, 3, ""); - ExpectLine(&proxy, 4, ""); - ExpectLine(&proxy, 5, ""); - ExpectLine(&proxy, 6, ""); - ExpectLine(&proxy, 7, ""); - - REQUIRE(proxy.Eof()); - } - - TEST_CASE("DefinesStreamProxy: Ensure can use elif", "[parsing][parsingstream]") - { - const std::vector<std::string> lines - { - "#define someStuff 1", - "#if defined(someStuff) && defined(thisIsNotDefined)", - "Hello World", - "#elif 1", - "Hello Universe", - "#elif 1", - "Hello Galaxy", - "#endif", - "#if defined(thisIsNotDefined)", - "Hello World", - "#endif", - }; - - MockParserLineStream mockStream(lines); - DefinesStreamProxy proxy(&mockStream); - - ExpectLine(&proxy, 1, ""); - ExpectLine(&proxy, 2, ""); - ExpectLine(&proxy, 3, ""); - ExpectLine(&proxy, 4, ""); - ExpectLine(&proxy, 5, "Hello Universe"); - ExpectLine(&proxy, 6, ""); - ExpectLine(&proxy, 7, ""); - ExpectLine(&proxy, 8, ""); - ExpectLine(&proxy, 9, ""); - ExpectLine(&proxy, 10, ""); - ExpectLine(&proxy, 11, ""); - - REQUIRE(proxy.Eof()); - } - - TEST_CASE("DefinesStreamProxy: Ensure elif does not work when if was true", "[parsing][parsingstream]") - { - const std::vector<std::string> lines - { - "#define someStuff 1", - "#if defined(someStuff)", - "Hello World", - "#elif 1", - "Hello Universe", - "#endif", - }; - - MockParserLineStream mockStream(lines); - DefinesStreamProxy proxy(&mockStream); - - ExpectLine(&proxy, 1, ""); - ExpectLine(&proxy, 2, ""); - ExpectLine(&proxy, 3, "Hello World"); - ExpectLine(&proxy, 4, ""); - ExpectLine(&proxy, 5, ""); - ExpectLine(&proxy, 6, ""); - - REQUIRE(proxy.Eof()); - } - - TEST_CASE("DefinesStreamProxy: Ensure can use else when no elif matched", "[parsing][parsingstream]") - { - const std::vector<std::string> lines - { - "#define someStuff 1", - "#if 0", - "Hello World", - "#elif 0", - "Hello Universe", - "#else", - "Hello Galaxy", - "#endif", - }; - - MockParserLineStream mockStream(lines); - DefinesStreamProxy proxy(&mockStream); - - ExpectLine(&proxy, 1, ""); - ExpectLine(&proxy, 2, ""); - ExpectLine(&proxy, 3, ""); - ExpectLine(&proxy, 4, ""); - ExpectLine(&proxy, 5, ""); - ExpectLine(&proxy, 6, ""); - ExpectLine(&proxy, 7, "Hello Galaxy"); - ExpectLine(&proxy, 8, ""); - - REQUIRE(proxy.Eof()); - } - - TEST_CASE("DefinesStreamProxy: Ensure can use parenthesis in parameters values", "[parsing][parsingstream]") - { - const std::vector<std::string> lines - { - "#define someStuff(param1) Hello param1 World", - "someStuff(A sentence with (parenthesis) and stuff)" - }; - - MockParserLineStream mockStream(lines); - DefinesStreamProxy proxy(&mockStream); - - ExpectLine(&proxy, 1, ""); - ExpectLine(&proxy, 2, "Hello A sentence with (parenthesis) and stuff World"); - - REQUIRE(proxy.Eof()); - } - - TEST_CASE("DefinesStreamProxy: Ensure can use comma in parenthesis in parameters values", "[parsing][parsingstream]") - { - const std::vector<std::string> lines - { - "#define someStuff(param1) Hello param1 World", - "someStuff(A sentence with (parenthesis and a , character) and stuff)" - }; - - MockParserLineStream mockStream(lines); - DefinesStreamProxy proxy(&mockStream); - - ExpectLine(&proxy, 1, ""); - ExpectLine(&proxy, 2, "Hello A sentence with (parenthesis and a , character) and stuff World"); - - REQUIRE(proxy.Eof()); - } - - TEST_CASE("DefinesStreamProxy: Ensure defines can go over multiple lines", "[parsing][parsingstream]") - { - const std::vector<std::string> lines - { - "#define someStuff(param1) Hello param1 World \\", - "and hello universe", - "someStuff(lovely)" - }; - - MockParserLineStream mockStream(lines); - DefinesStreamProxy proxy(&mockStream); - - ExpectLine(&proxy, 1, ""); - ExpectLine(&proxy, 2, ""); - ExpectLine(&proxy, 3, "Hello lovely World and hello universe"); - - REQUIRE(proxy.Eof()); - } +namespace test::parsing::impl::defines_stream_proxy { +void ExpectLine(IParserLineStream *stream, const int lineNumber, const std::string &value) { + auto line = stream->NextLine(); + REQUIRE(line.m_line_number == lineNumber); + REQUIRE(line.m_line == value); } + +TEST_CASE("DefinesStreamProxy: Ensure simple define and positive ifdef is working", "[parsing][parsingstream]") { + const std::vector<std::string> lines{"#define ASDF", "#ifdef ASDF", "Hello World", "#endif", "Hello Galaxy"}; + + MockParserLineStream mockStream(lines); + DefinesStreamProxy proxy(&mockStream); + + ExpectLine(&proxy, 1, ""); + ExpectLine(&proxy, 2, ""); + ExpectLine(&proxy, 3, "Hello World"); + ExpectLine(&proxy, 4, ""); + ExpectLine(&proxy, 5, "Hello Galaxy"); + + REQUIRE(proxy.Eof()); +} + +TEST_CASE("DefinesStreamProxy: Ensure simple define and negative ifdef is working", "[parsing][parsingstream]") { + const std::vector<std::string> lines{"#define ASDF", "#ifdef NONO", "Hello World", "#endif", "Hello Galaxy"}; + + MockParserLineStream mockStream(lines); + DefinesStreamProxy proxy(&mockStream); + + ExpectLine(&proxy, 1, ""); + ExpectLine(&proxy, 2, ""); + ExpectLine(&proxy, 3, ""); + ExpectLine(&proxy, 4, ""); + ExpectLine(&proxy, 5, "Hello Galaxy"); + + REQUIRE(proxy.Eof()); +} + +TEST_CASE("DefinesStreamProxy: Ensure simple define and positive ifndef is working", "[parsing][parsingstream]") { + const std::vector<std::string> lines{"#define ASDF", "#ifndef NONO", "Hello World", "#endif", "Hello Galaxy"}; + + MockParserLineStream mockStream(lines); + DefinesStreamProxy proxy(&mockStream); + + ExpectLine(&proxy, 1, ""); + ExpectLine(&proxy, 2, ""); + ExpectLine(&proxy, 3, "Hello World"); + ExpectLine(&proxy, 4, ""); + ExpectLine(&proxy, 5, "Hello Galaxy"); + + REQUIRE(proxy.Eof()); +} + +TEST_CASE("DefinesStreamProxy: Ensure simple define and negative ifndef is working", "[parsing][parsingstream]") { + const std::vector<std::string> lines{"#define ASDF", "#ifndef ASDF", "Hello World", "#endif", "Hello Galaxy"}; + + MockParserLineStream mockStream(lines); + DefinesStreamProxy proxy(&mockStream); + + ExpectLine(&proxy, 1, ""); + ExpectLine(&proxy, 2, ""); + ExpectLine(&proxy, 3, ""); + ExpectLine(&proxy, 4, ""); + ExpectLine(&proxy, 5, "Hello Galaxy"); + + REQUIRE(proxy.Eof()); +} + +TEST_CASE("DefinesStreamProxy: Ensure else is working", "[parsing][parsingstream]") { + const std::vector<std::string> lines{"#define ASDF", "#ifdef NONO", "Hello World1", "#else", "Hello World2", "#endif", "Hello Galaxy"}; + + MockParserLineStream mockStream(lines); + DefinesStreamProxy proxy(&mockStream); + + ExpectLine(&proxy, 1, ""); + ExpectLine(&proxy, 2, ""); + ExpectLine(&proxy, 3, ""); + ExpectLine(&proxy, 4, ""); + ExpectLine(&proxy, 5, "Hello World2"); + ExpectLine(&proxy, 6, ""); + ExpectLine(&proxy, 7, "Hello Galaxy"); + + REQUIRE(proxy.Eof()); +} + +TEST_CASE("DefinesStreamProxy: Ensure nested ifdef is working", "[parsing][parsingstream]") { + const std::vector<std::string> lines{"#define ASDF", "#ifdef ASDF", "#ifdef NONO", "Hello World1", "#else", "Hello World2", "#endif", "#else", + "#ifdef ASDF", "Hello World3", "#else", "Hello World4", "#endif", "#endif", "Hello Galaxy"}; + + MockParserLineStream mockStream(lines); + DefinesStreamProxy proxy(&mockStream); + + ExpectLine(&proxy, 1, ""); + ExpectLine(&proxy, 2, ""); + ExpectLine(&proxy, 3, ""); + ExpectLine(&proxy, 4, ""); + ExpectLine(&proxy, 5, ""); + ExpectLine(&proxy, 6, "Hello World2"); + ExpectLine(&proxy, 7, ""); + ExpectLine(&proxy, 8, ""); + ExpectLine(&proxy, 9, ""); + ExpectLine(&proxy, 10, ""); + ExpectLine(&proxy, 11, ""); + ExpectLine(&proxy, 12, ""); + ExpectLine(&proxy, 13, ""); + ExpectLine(&proxy, 14, ""); + ExpectLine(&proxy, 15, "Hello Galaxy"); + + REQUIRE(proxy.Eof()); +} + +TEST_CASE("DefinesStreamProxy: Ensure undef is working", "[parsing][parsingstream]") { + const std::vector<std::string> lines{"#define ASDF", "#ifdef ASDF", "Hello World", "#endif", "#undef ASDF", + "#ifdef ASDF", "Hello World", "#endif", "Hello Galaxy"}; + + MockParserLineStream mockStream(lines); + DefinesStreamProxy proxy(&mockStream); + + ExpectLine(&proxy, 1, ""); + ExpectLine(&proxy, 2, ""); + ExpectLine(&proxy, 3, "Hello World"); + ExpectLine(&proxy, 4, ""); + ExpectLine(&proxy, 5, ""); + ExpectLine(&proxy, 6, ""); + ExpectLine(&proxy, 7, ""); + ExpectLine(&proxy, 8, ""); + ExpectLine(&proxy, 9, "Hello Galaxy"); + + REQUIRE(proxy.Eof()); +} + +TEST_CASE("DefinesStreamProxy: Ensure undef does not undefine everything", "[parsing][parsingstream]") { + const std::vector<std::string> lines{"#define ASDF", "#ifdef ASDF", "Hello World", "#endif", "#undef NONO", + "#ifdef ASDF", "Hello World", "#endif", "Hello Galaxy"}; + + MockParserLineStream mockStream(lines); + DefinesStreamProxy proxy(&mockStream); + + ExpectLine(&proxy, 1, ""); + ExpectLine(&proxy, 2, ""); + ExpectLine(&proxy, 3, "Hello World"); + ExpectLine(&proxy, 4, ""); + ExpectLine(&proxy, 5, ""); + ExpectLine(&proxy, 6, ""); + ExpectLine(&proxy, 7, "Hello World"); + ExpectLine(&proxy, 8, ""); + ExpectLine(&proxy, 9, "Hello Galaxy"); + + REQUIRE(proxy.Eof()); +} + +TEST_CASE("DefinesStreamProxy: Ensure simple defines are working", "[parsing][parsingstream]") { + const std::vector<std::string> lines{"#define ASDF LOL", "ASDF", "A ASDF B", "ASDF B", "A ASDF"}; + + MockParserLineStream mockStream(lines); + DefinesStreamProxy proxy(&mockStream); + + ExpectLine(&proxy, 1, ""); + ExpectLine(&proxy, 2, "LOL"); + ExpectLine(&proxy, 3, "A LOL B"); + ExpectLine(&proxy, 4, "LOL B"); + ExpectLine(&proxy, 5, "A LOL"); + + REQUIRE(proxy.Eof()); +} + +TEST_CASE("DefinesStreamProxy: Ensure defines can be surrounded by symbols", "[parsing][parsingstream]") { + const std::vector<std::string> lines{"#define ASDF LOL", "!ASDF%"}; + + MockParserLineStream mockStream(lines); + DefinesStreamProxy proxy(&mockStream); + + ExpectLine(&proxy, 1, ""); + ExpectLine(&proxy, 2, "!LOL%"); + + REQUIRE(proxy.Eof()); +} + +TEST_CASE("DefinesStreamProxy: Ensure can use multiple defines in one line", "[parsing][parsingstream]") { + const std::vector<std::string> lines{"#define A Hello", "#define B world", "A my dear B!"}; + + MockParserLineStream mockStream(lines); + DefinesStreamProxy proxy(&mockStream); + + ExpectLine(&proxy, 1, ""); + ExpectLine(&proxy, 2, ""); + ExpectLine(&proxy, 3, "Hello my dear world!"); + + REQUIRE(proxy.Eof()); +} + +TEST_CASE("DefinesStreamProxy: Ensure defines in disabled block are ignored", "[parsing][parsingstream]") { + const std::vector<std::string> lines{"#ifdef LOLO", "#define hello world", "#endif", "hello"}; + + MockParserLineStream mockStream(lines); + DefinesStreamProxy proxy(&mockStream); + + ExpectLine(&proxy, 1, ""); + ExpectLine(&proxy, 2, ""); + ExpectLine(&proxy, 3, ""); + ExpectLine(&proxy, 4, "hello"); + + REQUIRE(proxy.Eof()); +} + +TEST_CASE("DefinesStreamProxy: Ensure undefs in disabled block are ignored", "[parsing][parsingstream]") { + const std::vector<std::string> lines{"#define hello world", "#ifdef LOLO", "#undef hello", "#endif", "hello"}; + + MockParserLineStream mockStream(lines); + DefinesStreamProxy proxy(&mockStream); + + ExpectLine(&proxy, 1, ""); + ExpectLine(&proxy, 2, ""); + ExpectLine(&proxy, 3, ""); + ExpectLine(&proxy, 4, ""); + ExpectLine(&proxy, 5, "world"); + + REQUIRE(proxy.Eof()); +} + +TEST_CASE("DefinesStreamProxy: Ensure can define name with underscores and digits", "[parsing][parsingstream]") { + const std::vector<std::string> lines{"#define __int16 short", "unsigned __int16 value;"}; + + MockParserLineStream mockStream(lines); + DefinesStreamProxy proxy(&mockStream); + + ExpectLine(&proxy, 1, ""); + ExpectLine(&proxy, 2, "unsigned short value;"); + + REQUIRE(proxy.Eof()); +} + +TEST_CASE("DefinesStreamProxy: Ensure define can render parameters", "[parsing][parsingstream]") { + DefinesStreamProxy::Define define("helloworld", "hello universe"); + + std::vector<std::string> parameterNames({"universe"}); + define.IdentifyParameters(parameterNames); + + std::vector<std::string> parameterValues({"mr moneyman"}); + REQUIRE(define.Render(parameterValues) == "hello mr moneyman"); +} + +TEST_CASE("DefinesStreamProxy: Ensure define can render parameters in middle of symbols", "[parsing][parsingstream]") { + DefinesStreamProxy::Define define("helloworld", "alignas(x)"); + + std::vector<std::string> parameterNames({"x"}); + define.IdentifyParameters(parameterNames); + + std::vector<std::string> parameterValues({"1337"}); + REQUIRE(define.Render(parameterValues) == "alignas(1337)"); +} + +TEST_CASE("DefinesStreamProxy: Ensure can add define with parameters", "[parsing][parsingstream]") { + const std::vector<std::string> lines{"#define test(x) alignas(x)", "struct test(1337) test_struct"}; + + MockParserLineStream mockStream(lines); + DefinesStreamProxy proxy(&mockStream); + + ExpectLine(&proxy, 1, ""); + ExpectLine(&proxy, 2, "struct alignas(1337) test_struct"); + + REQUIRE(proxy.Eof()); +} + +TEST_CASE("DefinesStreamProxy: Ensure can use parameter multiple times", "[parsing][parsingstream]") { + const std::vector<std::string> lines{"#define test(x) x|x|x|x", "struct test(1337) test_struct"}; + + MockParserLineStream mockStream(lines); + DefinesStreamProxy proxy(&mockStream); + + ExpectLine(&proxy, 1, ""); + ExpectLine(&proxy, 2, "struct 1337|1337|1337|1337 test_struct"); + + REQUIRE(proxy.Eof()); +} + +TEST_CASE("DefinesStreamProxy: Ensure can use parameterized define in between symbols", "[parsing][parsingstream]") { + const std::vector<std::string> lines{"#define test(x) x|x|x|x", "%test(5)%"}; + + MockParserLineStream mockStream(lines); + DefinesStreamProxy proxy(&mockStream); + + ExpectLine(&proxy, 1, ""); + ExpectLine(&proxy, 2, "%5|5|5|5%"); + + REQUIRE(proxy.Eof()); +} + +TEST_CASE("DefinesStreamProxy: Ensure can define multiple parameters", "[parsing][parsingstream]") { + const std::vector<std::string> lines{"#define test(a1, a2, a3) a1 + a2 = a3", "make calc test(1, 2, 3);"}; + + MockParserLineStream mockStream(lines); + DefinesStreamProxy proxy(&mockStream); + + ExpectLine(&proxy, 1, ""); + ExpectLine(&proxy, 2, "make calc 1 + 2 = 3;"); + + REQUIRE(proxy.Eof()); +} + +TEST_CASE("DefinesStreamProxy: Ensure can define multiple parameters without spacing", "[parsing][parsingstream]") { + const std::vector<std::string> lines{"#define test(a1,a2,a3) a1+a2=a3", "make calc test(1,2,3);"}; + + MockParserLineStream mockStream(lines); + DefinesStreamProxy proxy(&mockStream); + + ExpectLine(&proxy, 1, ""); + ExpectLine(&proxy, 2, "make calc 1+2=3;"); + + REQUIRE(proxy.Eof()); +} + +TEST_CASE("DefinesStreamProxy: Ensure can define parameters with underscore", "[parsing][parsingstream]") { + const std::vector<std::string> lines{"#define test(test_parameter) this is test_parameter", "Apparently test(a very cool text);"}; + + MockParserLineStream mockStream(lines); + DefinesStreamProxy proxy(&mockStream); + + ExpectLine(&proxy, 1, ""); + ExpectLine(&proxy, 2, "Apparently this is a very cool text;"); + + REQUIRE(proxy.Eof()); +} + +TEST_CASE("DefinesStreamProxy: Ensure simple if is working with truthy value", "[parsing][parsingstream]") { + const std::vector<std::string> lines{ + "#if 1", + "Hello World", + "#endif", + }; + + MockParserLineStream mockStream(lines); + DefinesStreamProxy proxy(&mockStream); + + ExpectLine(&proxy, 1, ""); + ExpectLine(&proxy, 2, "Hello World"); + ExpectLine(&proxy, 3, ""); + + REQUIRE(proxy.Eof()); +} + +TEST_CASE("DefinesStreamProxy: Ensure simple if is working with non-truthy value", "[parsing][parsingstream]") { + const std::vector<std::string> lines{ + "#if 0", + "Hello World", + "#endif", + }; + + MockParserLineStream mockStream(lines); + DefinesStreamProxy proxy(&mockStream); + + ExpectLine(&proxy, 1, ""); + ExpectLine(&proxy, 2, ""); + ExpectLine(&proxy, 3, ""); + + REQUIRE(proxy.Eof()); +} + +TEST_CASE("DefinesStreamProxy: Ensure simple if is working with calculated values", "[parsing][parsingstream]") { + const std::vector<std::string> lines{ + "#if 0 || 1", "Hello World", "#endif", "#if 0 && 1", "Hello World", "#endif", + }; + + MockParserLineStream mockStream(lines); + DefinesStreamProxy proxy(&mockStream); + + ExpectLine(&proxy, 1, ""); + ExpectLine(&proxy, 2, "Hello World"); + ExpectLine(&proxy, 3, ""); + ExpectLine(&proxy, 4, ""); + ExpectLine(&proxy, 5, ""); + ExpectLine(&proxy, 6, ""); + + REQUIRE(proxy.Eof()); +} + +TEST_CASE("DefinesStreamProxy: Ensure can handle defined operator with defined definition", "[parsing][parsingstream]") { + const std::vector<std::string> lines{ + "#define someStuff 1", + "#if defined(someStuff)", + "Hello World", + "#endif", + }; + + MockParserLineStream mockStream(lines); + DefinesStreamProxy proxy(&mockStream); + + ExpectLine(&proxy, 1, ""); + ExpectLine(&proxy, 2, ""); + ExpectLine(&proxy, 3, "Hello World"); + ExpectLine(&proxy, 4, ""); + + REQUIRE(proxy.Eof()); +} + +TEST_CASE("DefinesStreamProxy: Ensure can handle defined operator with undefined definition", "[parsing][parsingstream]") { + const std::vector<std::string> lines{ + "#define someStuff 1", + "#if defined(someStuff) && defined(thisIsNotDefined)", + "Hello World", + "#endif", + "#if defined(thisIsNotDefined)", + "Hello World", + "#endif", + }; + + MockParserLineStream mockStream(lines); + DefinesStreamProxy proxy(&mockStream); + + ExpectLine(&proxy, 1, ""); + ExpectLine(&proxy, 2, ""); + ExpectLine(&proxy, 3, ""); + ExpectLine(&proxy, 4, ""); + ExpectLine(&proxy, 5, ""); + ExpectLine(&proxy, 6, ""); + ExpectLine(&proxy, 7, ""); + + REQUIRE(proxy.Eof()); +} + +TEST_CASE("DefinesStreamProxy: Ensure can use elif", "[parsing][parsingstream]") { + const std::vector<std::string> lines{ + "#define someStuff 1", + "#if defined(someStuff) && defined(thisIsNotDefined)", + "Hello World", + "#elif 1", + "Hello Universe", + "#elif 1", + "Hello Galaxy", + "#endif", + "#if defined(thisIsNotDefined)", + "Hello World", + "#endif", + }; + + MockParserLineStream mockStream(lines); + DefinesStreamProxy proxy(&mockStream); + + ExpectLine(&proxy, 1, ""); + ExpectLine(&proxy, 2, ""); + ExpectLine(&proxy, 3, ""); + ExpectLine(&proxy, 4, ""); + ExpectLine(&proxy, 5, "Hello Universe"); + ExpectLine(&proxy, 6, ""); + ExpectLine(&proxy, 7, ""); + ExpectLine(&proxy, 8, ""); + ExpectLine(&proxy, 9, ""); + ExpectLine(&proxy, 10, ""); + ExpectLine(&proxy, 11, ""); + + REQUIRE(proxy.Eof()); +} + +TEST_CASE("DefinesStreamProxy: Ensure elif does not work when if was true", "[parsing][parsingstream]") { + const std::vector<std::string> lines{ + "#define someStuff 1", "#if defined(someStuff)", "Hello World", "#elif 1", "Hello Universe", "#endif", + }; + + MockParserLineStream mockStream(lines); + DefinesStreamProxy proxy(&mockStream); + + ExpectLine(&proxy, 1, ""); + ExpectLine(&proxy, 2, ""); + ExpectLine(&proxy, 3, "Hello World"); + ExpectLine(&proxy, 4, ""); + ExpectLine(&proxy, 5, ""); + ExpectLine(&proxy, 6, ""); + + REQUIRE(proxy.Eof()); +} + +TEST_CASE("DefinesStreamProxy: Ensure can use else when no elif matched", "[parsing][parsingstream]") { + const std::vector<std::string> lines{ + "#define someStuff 1", "#if 0", "Hello World", "#elif 0", "Hello Universe", "#else", "Hello Galaxy", "#endif", + }; + + MockParserLineStream mockStream(lines); + DefinesStreamProxy proxy(&mockStream); + + ExpectLine(&proxy, 1, ""); + ExpectLine(&proxy, 2, ""); + ExpectLine(&proxy, 3, ""); + ExpectLine(&proxy, 4, ""); + ExpectLine(&proxy, 5, ""); + ExpectLine(&proxy, 6, ""); + ExpectLine(&proxy, 7, "Hello Galaxy"); + ExpectLine(&proxy, 8, ""); + + REQUIRE(proxy.Eof()); +} + +TEST_CASE("DefinesStreamProxy: Ensure can use parenthesis in parameters values", "[parsing][parsingstream]") { + const std::vector<std::string> lines{"#define someStuff(param1) Hello param1 World", "someStuff(A sentence with (parenthesis) and stuff)"}; + + MockParserLineStream mockStream(lines); + DefinesStreamProxy proxy(&mockStream); + + ExpectLine(&proxy, 1, ""); + ExpectLine(&proxy, 2, "Hello A sentence with (parenthesis) and stuff World"); + + REQUIRE(proxy.Eof()); +} + +TEST_CASE("DefinesStreamProxy: Ensure can use comma in parenthesis in parameters values", "[parsing][parsingstream]") { + const std::vector<std::string> lines{"#define someStuff(param1) Hello param1 World", "someStuff(A sentence with (parenthesis and a , character) and stuff)"}; + + MockParserLineStream mockStream(lines); + DefinesStreamProxy proxy(&mockStream); + + ExpectLine(&proxy, 1, ""); + ExpectLine(&proxy, 2, "Hello A sentence with (parenthesis and a , character) and stuff World"); + + REQUIRE(proxy.Eof()); +} + +TEST_CASE("DefinesStreamProxy: Ensure defines can go over multiple lines", "[parsing][parsingstream]") { + const std::vector<std::string> lines{"#define someStuff(param1) Hello param1 World \\", "and hello universe", "someStuff(lovely)"}; + + MockParserLineStream mockStream(lines); + DefinesStreamProxy proxy(&mockStream); + + ExpectLine(&proxy, 1, ""); + ExpectLine(&proxy, 2, ""); + ExpectLine(&proxy, 3, "Hello lovely World and hello universe"); + + REQUIRE(proxy.Eof()); +} +} // namespace test::parsing::impl::defines_stream_proxy diff --git a/test/ParserTests/Parsing/Impl/IncludingStreamProxyTests.cpp b/test/ParserTests/Parsing/Impl/IncludingStreamProxyTests.cpp index 13f329335..9c258beef 100644 --- a/test/ParserTests/Parsing/Impl/IncludingStreamProxyTests.cpp +++ b/test/ParserTests/Parsing/Impl/IncludingStreamProxyTests.cpp @@ -4,179 +4,140 @@ #include "Parsing/Impl/IncludingStreamProxy.h" #include "Parsing/Mock/MockParserLineStream.h" -namespace test::parsing::impl::including_stream_proxy -{ - TEST_CASE("IncludingStreamProxy: Ensure simple include is working", "[parsing][parsingstream]") - { - const std::vector<std::string> lines - { - "Hello world", - "#include \"ASDF.txt\"", - "and bye" - }; - - const std::vector<std::string> asdf - { - "Hello galaxy" - }; - - MockParserLineStream mockStream(lines); - mockStream.AddIncludeLines("ASDF.txt", asdf); - - IncludingStreamProxy proxy(&mockStream); - - { - auto line = proxy.NextLine(); - REQUIRE(line.m_line_number == 1); - REQUIRE(*line.m_filename == MockParserLineStream::MOCK_FILENAME); - REQUIRE(line.m_line == "Hello world"); - } - - { - auto line = proxy.NextLine(); - REQUIRE(line.m_line_number == 1); - REQUIRE(*line.m_filename == "ASDF.txt"); - REQUIRE(line.m_line == "Hello galaxy"); - } - - { - auto line = proxy.NextLine(); - REQUIRE(line.m_line_number == 3); - REQUIRE(*line.m_filename == MockParserLineStream::MOCK_FILENAME); - REQUIRE(line.m_line == "and bye"); - } - - REQUIRE(proxy.Eof()); - } - - TEST_CASE("IncludingStreamProxy: Ensure simple include with angle brackets is working", "[parsing][parsingstream]") - { - const std::vector<std::string> lines - { - "Hello world", - "#include <ASDF.txt>", - "and bye" - }; - - const std::vector<std::string> asdf - { - "Hello galaxy" - }; - - MockParserLineStream mockStream(lines); - mockStream.AddIncludeLines("ASDF.txt", asdf); - - IncludingStreamProxy proxy(&mockStream); - - { - auto line = proxy.NextLine(); - REQUIRE(line.m_line_number == 1); - REQUIRE(*line.m_filename == MockParserLineStream::MOCK_FILENAME); - REQUIRE(line.m_line == "Hello world"); - } - - { - auto line = proxy.NextLine(); - REQUIRE(line.m_line_number == 1); - REQUIRE(*line.m_filename == "ASDF.txt"); - REQUIRE(line.m_line == "Hello galaxy"); - } - - { - auto line = proxy.NextLine(); - REQUIRE(line.m_line_number == 3); - REQUIRE(*line.m_filename == MockParserLineStream::MOCK_FILENAME); - REQUIRE(line.m_line == "and bye"); - } - - REQUIRE(proxy.Eof()); - } - - TEST_CASE("IncludingStreamProxy: Ensure can have spaces before include directive", "[parsing][parsingstream]") - { - const std::vector<std::string> lines - { - "Hello world", - " #include \"ASDF.txt\" ", - "and bye" - }; - - const std::vector<std::string> asdf - { - "Hello galaxy" - }; - - MockParserLineStream mockStream(lines); - mockStream.AddIncludeLines("ASDF.txt", asdf); - - IncludingStreamProxy proxy(&mockStream); - - { - auto line = proxy.NextLine(); - REQUIRE(line.m_line_number == 1); - REQUIRE(*line.m_filename == MockParserLineStream::MOCK_FILENAME); - REQUIRE(line.m_line == "Hello world"); - } - - { - auto line = proxy.NextLine(); - REQUIRE(line.m_line_number == 1); - REQUIRE(*line.m_filename == "ASDF.txt"); - REQUIRE(line.m_line == "Hello galaxy"); - } - - { - auto line = proxy.NextLine(); - REQUIRE(line.m_line_number == 3); - REQUIRE(*line.m_filename == MockParserLineStream::MOCK_FILENAME); - REQUIRE(line.m_line == "and bye"); - } - - REQUIRE(proxy.Eof()); - } - - TEST_CASE("IncludingStreamProxy: Ensure pragma once prevents including the same file more than once", "[parsing][parsingstream]") - { - const std::vector<std::string> lines - { - "Hello world", - "#include \"ASDF.txt\"", - "#include \"ASDF.txt\"", - "and bye" - }; - - const std::vector<std::string> asdf - { - "#pragma once", - "Hello galaxy" - }; - - MockParserLineStream mockStream(lines); - mockStream.AddIncludeLines("ASDF.txt", asdf); - - IncludingStreamProxy proxy(&mockStream); - - { - auto line = proxy.NextLine(); - REQUIRE(line.m_line_number == 1); - REQUIRE(*line.m_filename == MockParserLineStream::MOCK_FILENAME); - REQUIRE(line.m_line == "Hello world"); - } - - { - auto line = proxy.NextLine(); - REQUIRE(line.m_line_number == 2); - REQUIRE(*line.m_filename == "ASDF.txt"); - REQUIRE(line.m_line == "Hello galaxy"); - } - - { - auto line = proxy.NextLine(); - REQUIRE(line.m_line_number == 4); - REQUIRE(*line.m_filename == MockParserLineStream::MOCK_FILENAME); - REQUIRE(line.m_line == "and bye"); - } - - REQUIRE(proxy.Eof()); - } +namespace test::parsing::impl::including_stream_proxy { +TEST_CASE("IncludingStreamProxy: Ensure simple include is working", "[parsing][parsingstream]") { + const std::vector<std::string> lines{"Hello world", "#include \"ASDF.txt\"", "and bye"}; + + const std::vector<std::string> asdf{"Hello galaxy"}; + + MockParserLineStream mockStream(lines); + mockStream.AddIncludeLines("ASDF.txt", asdf); + + IncludingStreamProxy proxy(&mockStream); + + { + auto line = proxy.NextLine(); + REQUIRE(line.m_line_number == 1); + REQUIRE(*line.m_filename == MockParserLineStream::MOCK_FILENAME); + REQUIRE(line.m_line == "Hello world"); + } + + { + auto line = proxy.NextLine(); + REQUIRE(line.m_line_number == 1); + REQUIRE(*line.m_filename == "ASDF.txt"); + REQUIRE(line.m_line == "Hello galaxy"); + } + + { + auto line = proxy.NextLine(); + REQUIRE(line.m_line_number == 3); + REQUIRE(*line.m_filename == MockParserLineStream::MOCK_FILENAME); + REQUIRE(line.m_line == "and bye"); + } + + REQUIRE(proxy.Eof()); } + +TEST_CASE("IncludingStreamProxy: Ensure simple include with angle brackets is working", "[parsing][parsingstream]") { + const std::vector<std::string> lines{"Hello world", "#include <ASDF.txt>", "and bye"}; + + const std::vector<std::string> asdf{"Hello galaxy"}; + + MockParserLineStream mockStream(lines); + mockStream.AddIncludeLines("ASDF.txt", asdf); + + IncludingStreamProxy proxy(&mockStream); + + { + auto line = proxy.NextLine(); + REQUIRE(line.m_line_number == 1); + REQUIRE(*line.m_filename == MockParserLineStream::MOCK_FILENAME); + REQUIRE(line.m_line == "Hello world"); + } + + { + auto line = proxy.NextLine(); + REQUIRE(line.m_line_number == 1); + REQUIRE(*line.m_filename == "ASDF.txt"); + REQUIRE(line.m_line == "Hello galaxy"); + } + + { + auto line = proxy.NextLine(); + REQUIRE(line.m_line_number == 3); + REQUIRE(*line.m_filename == MockParserLineStream::MOCK_FILENAME); + REQUIRE(line.m_line == "and bye"); + } + + REQUIRE(proxy.Eof()); +} + +TEST_CASE("IncludingStreamProxy: Ensure can have spaces before include directive", "[parsing][parsingstream]") { + const std::vector<std::string> lines{"Hello world", " #include \"ASDF.txt\" ", "and bye"}; + + const std::vector<std::string> asdf{"Hello galaxy"}; + + MockParserLineStream mockStream(lines); + mockStream.AddIncludeLines("ASDF.txt", asdf); + + IncludingStreamProxy proxy(&mockStream); + + { + auto line = proxy.NextLine(); + REQUIRE(line.m_line_number == 1); + REQUIRE(*line.m_filename == MockParserLineStream::MOCK_FILENAME); + REQUIRE(line.m_line == "Hello world"); + } + + { + auto line = proxy.NextLine(); + REQUIRE(line.m_line_number == 1); + REQUIRE(*line.m_filename == "ASDF.txt"); + REQUIRE(line.m_line == "Hello galaxy"); + } + + { + auto line = proxy.NextLine(); + REQUIRE(line.m_line_number == 3); + REQUIRE(*line.m_filename == MockParserLineStream::MOCK_FILENAME); + REQUIRE(line.m_line == "and bye"); + } + + REQUIRE(proxy.Eof()); +} + +TEST_CASE("IncludingStreamProxy: Ensure pragma once prevents including the same file more than once", "[parsing][parsingstream]") { + const std::vector<std::string> lines{"Hello world", "#include \"ASDF.txt\"", "#include \"ASDF.txt\"", "and bye"}; + + const std::vector<std::string> asdf{"#pragma once", "Hello galaxy"}; + + MockParserLineStream mockStream(lines); + mockStream.AddIncludeLines("ASDF.txt", asdf); + + IncludingStreamProxy proxy(&mockStream); + + { + auto line = proxy.NextLine(); + REQUIRE(line.m_line_number == 1); + REQUIRE(*line.m_filename == MockParserLineStream::MOCK_FILENAME); + REQUIRE(line.m_line == "Hello world"); + } + + { + auto line = proxy.NextLine(); + REQUIRE(line.m_line_number == 2); + REQUIRE(*line.m_filename == "ASDF.txt"); + REQUIRE(line.m_line == "Hello galaxy"); + } + + { + auto line = proxy.NextLine(); + REQUIRE(line.m_line_number == 4); + REQUIRE(*line.m_filename == MockParserLineStream::MOCK_FILENAME); + REQUIRE(line.m_line == "and bye"); + } + + REQUIRE(proxy.Eof()); +} +} // namespace test::parsing::impl::including_stream_proxy diff --git a/test/ParserTests/Parsing/Impl/PackDefinitionStreamProxyTests.cpp b/test/ParserTests/Parsing/Impl/PackDefinitionStreamProxyTests.cpp index 7f85f4e5e..4115c3f8b 100644 --- a/test/ParserTests/Parsing/Impl/PackDefinitionStreamProxyTests.cpp +++ b/test/ParserTests/Parsing/Impl/PackDefinitionStreamProxyTests.cpp @@ -4,37 +4,27 @@ #include "Parsing/Impl/PackDefinitionStreamProxy.h" #include "Parsing/Mock/MockParserLineStream.h" -namespace test::parsing::impl::pack_definition_stream_proxy -{ - void ExpectLine(IParserLineStream* stream, const int lineNumber, const std::string& value) - { - auto line = stream->NextLine(); - REQUIRE(line.m_line_number == lineNumber); - REQUIRE(line.m_line == value); - } +namespace test::parsing::impl::pack_definition_stream_proxy { +void ExpectLine(IParserLineStream *stream, const int lineNumber, const std::string &value) { + auto line = stream->NextLine(); + REQUIRE(line.m_line_number == lineNumber); + REQUIRE(line.m_line == value); +} - TEST_CASE("PackDefinitionStreamProxy: Ensure simple pack directives are working", "[parsing][parsingstream]") - { - const std::vector<std::string> lines - { - "hello world", - "#pragma pack(push, 32)", - "hello galaxy", - "#pragma pack(pop)", - "hello universe" - }; +TEST_CASE("PackDefinitionStreamProxy: Ensure simple pack directives are working", "[parsing][parsingstream]") { + const std::vector<std::string> lines{"hello world", "#pragma pack(push, 32)", "hello galaxy", "#pragma pack(pop)", "hello universe"}; - MockParserLineStream mockStream(lines); - PackDefinitionStreamProxy proxy(&mockStream); + MockParserLineStream mockStream(lines); + PackDefinitionStreamProxy proxy(&mockStream); - REQUIRE(proxy.GetCurrentPack() == PackDefinitionStreamProxy::DEFAULT_PACK); - ExpectLine(&proxy, 1, "hello world"); - REQUIRE(proxy.GetCurrentPack() == PackDefinitionStreamProxy::DEFAULT_PACK); - ExpectLine(&proxy, 3, "hello galaxy"); - REQUIRE(proxy.GetCurrentPack() == 32); - ExpectLine(&proxy, 5, "hello universe"); - REQUIRE(proxy.GetCurrentPack() == PackDefinitionStreamProxy::DEFAULT_PACK); + REQUIRE(proxy.GetCurrentPack() == PackDefinitionStreamProxy::DEFAULT_PACK); + ExpectLine(&proxy, 1, "hello world"); + REQUIRE(proxy.GetCurrentPack() == PackDefinitionStreamProxy::DEFAULT_PACK); + ExpectLine(&proxy, 3, "hello galaxy"); + REQUIRE(proxy.GetCurrentPack() == 32); + ExpectLine(&proxy, 5, "hello universe"); + REQUIRE(proxy.GetCurrentPack() == PackDefinitionStreamProxy::DEFAULT_PACK); - REQUIRE(proxy.Eof()); - } -} \ No newline at end of file + REQUIRE(proxy.Eof()); +} +} // namespace test::parsing::impl::pack_definition_stream_proxy \ No newline at end of file diff --git a/test/ParserTests/Parsing/Simple/SimpleExpressionTests.cpp b/test/ParserTests/Parsing/Simple/SimpleExpressionTests.cpp index 14082bd35..60dd4aec5 100644 --- a/test/ParserTests/Parsing/Simple/SimpleExpressionTests.cpp +++ b/test/ParserTests/Parsing/Simple/SimpleExpressionTests.cpp @@ -5,840 +5,664 @@ #include "Parsing/Impl/AbstractParser.h" #include "Parsing/Impl/ParserSingleInputStream.h" -#include "Utils/ClassUtils.h" #include "Parsing/Mock/MockLexer.h" -#include "Parsing/Simple/SimpleParserValue.h" #include "Parsing/Simple/Expression/ISimpleExpression.h" #include "Parsing/Simple/Expression/SimpleExpressionMatchers.h" #include "Parsing/Simple/Matcher/SimpleMatcherFactory.h" +#include "Parsing/Simple/SimpleParserValue.h" +#include "Utils/ClassUtils.h" + +namespace test::parsing::simple::expression { +class SimpleExpressionTestState { +public: + std::unique_ptr<ISimpleExpression> m_expression; +}; + +class SimpleExpressionSequence final : public AbstractSequence<SimpleParserValue, SimpleExpressionTestState> { + const SimpleExpressionMatchers m_expression_matchers; + +public: + SimpleExpressionSequence() : m_expression_matchers(true, true, true, true, true) { + const SimpleMatcherFactory create(this); + + AddLabeledMatchers(m_expression_matchers.Expression(this), SimpleExpressionMatchers::LABEL_EXPRESSION); + AddMatchers(create.Label(SimpleExpressionMatchers::LABEL_EXPRESSION)); + } + +protected: + void ProcessMatch(SimpleExpressionTestState *state, SequenceResult<SimpleParserValue> &result) const override { + if (state->m_expression) + throw ParsingException(TokenPos(), "Expression already set"); + + state->m_expression = m_expression_matchers.ProcessExpression(result); + } +}; + +class SimpleExpressionParser final : public AbstractParser<SimpleParserValue, SimpleExpressionTestState> { +public: + explicit SimpleExpressionParser(ILexer<SimpleParserValue> *lexer) : AbstractParser(lexer, std::make_unique<SimpleExpressionTestState>()) {} + + _NODISCARD SimpleExpressionTestState *GetState() const { return m_state.get(); } + +protected: + const std::vector<sequence_t *> &GetTestsForState() override { + static std::vector<sequence_t *> tests({new SimpleExpressionSequence()}); + + return tests; + } +}; + +class SimpleExpressionTestsHelper { +public: + SimpleExpressionTestState *m_state; + std::unique_ptr<SimpleExpressionTestState> m_state_holder; + std::string m_str; + std::istringstream m_ss; + std::unique_ptr<IParserLineStream> m_stream; + std::unique_ptr<ILexer<SimpleParserValue>> m_lexer; + std::unique_ptr<SimpleExpressionParser> m_parser; + + std::unique_ptr<SimpleExpressionSequence> m_sequence; + + unsigned m_consumed_token_count; + + SimpleExpressionTestsHelper() : m_state(nullptr), m_sequence(std::make_unique<SimpleExpressionSequence>()), m_consumed_token_count(0u) {} + + void Tokens(std::initializer_list<Movable<SimpleParserValue>> tokens) { + m_state_holder = std::make_unique<SimpleExpressionTestState>(); + m_state = m_state_holder.get(); + m_lexer = std::make_unique<MockLexer<SimpleParserValue>>(tokens, SimpleParserValue::EndOfFile(TokenPos())); + } + + void Tokens(std::vector<SimpleParserValue> tokens) { + m_state_holder = std::make_unique<SimpleExpressionTestState>(); + m_state = m_state_holder.get(); + m_lexer = std::make_unique<MockLexer<SimpleParserValue>>(std::move(tokens), SimpleParserValue::EndOfFile(TokenPos())); + } + + void String(std::string str) { + m_str = std::move(str); + m_ss = std::istringstream(m_str); + m_stream = std::make_unique<ParserSingleInputStream>(m_ss, "InputString"); + + SimpleLexer::Config lexerConfig; + lexerConfig.m_read_strings = true; + lexerConfig.m_string_escape_sequences = true; + lexerConfig.m_read_integer_numbers = true; + lexerConfig.m_read_floating_point_numbers = true; + lexerConfig.m_emit_new_line_tokens = false; + SimpleExpressionMatchers(true, true, true, true, true).ApplyTokensToLexerConfig(lexerConfig); + m_lexer = std::make_unique<SimpleLexer>(m_stream.get(), std::move(lexerConfig)); + m_parser = std::make_unique<SimpleExpressionParser>(m_lexer.get()); + m_state = m_parser->GetState(); + } + + bool PerformTest() { + REQUIRE(m_lexer); + + m_consumed_token_count = 0; + return m_sequence->MatchSequence(m_lexer.get(), m_state, m_consumed_token_count); + } + + _NODISCARD bool PerformIntegrationTest() const { + REQUIRE(m_lexer); + REQUIRE(m_parser); + + return m_parser->Parse(); + } +}; + +TEST_CASE("SimpleExpressions: Can parse expression with add operation", "[parsing][simple][expression]") { + SimpleExpressionTestsHelper helper; + const TokenPos pos; + helper.Tokens( + {SimpleParserValue::Integer(pos, 1336), SimpleParserValue::Character(pos, '+'), SimpleParserValue::Integer(pos, 1), SimpleParserValue::EndOfFile(pos)}); + + const auto result = helper.PerformTest(); + + REQUIRE(result); + REQUIRE(helper.m_consumed_token_count == 3); + + const auto &expression = helper.m_state->m_expression; + REQUIRE(expression->IsStatic()); + + const auto value = expression->EvaluateStatic(); + REQUIRE(value.m_type == SimpleExpressionValue::Type::INT); + REQUIRE(value.m_int_value == 1337); +} + +TEST_CASE("SimpleExpressions: Can parse expression with subtract operation", "[parsing][simple][expression]") { + SimpleExpressionTestsHelper helper; + const TokenPos pos; + helper.Tokens( + {SimpleParserValue::Integer(pos, 428), SimpleParserValue::Character(pos, '-'), SimpleParserValue::Integer(pos, 8), SimpleParserValue::EndOfFile(pos)}); + + const auto result = helper.PerformTest(); + + REQUIRE(result); + REQUIRE(helper.m_consumed_token_count == 3); + + const auto &expression = helper.m_state->m_expression; + REQUIRE(expression->IsStatic()); + + const auto value = expression->EvaluateStatic(); + REQUIRE(value.m_type == SimpleExpressionValue::Type::INT); + REQUIRE(value.m_int_value == 420); +} + +TEST_CASE("SimpleExpressions: Can parse expression with multiply operation", "[parsing][simple][expression]") { + SimpleExpressionTestsHelper helper; + const TokenPos pos; + helper.Tokens( + {SimpleParserValue::Integer(pos, 105), SimpleParserValue::Character(pos, '*'), SimpleParserValue::Integer(pos, 4), SimpleParserValue::EndOfFile(pos)}); + + const auto result = helper.PerformTest(); + + REQUIRE(result); + REQUIRE(helper.m_consumed_token_count == 3); + + const auto &expression = helper.m_state->m_expression; + REQUIRE(expression->IsStatic()); + + const auto value = expression->EvaluateStatic(); + REQUIRE(value.m_type == SimpleExpressionValue::Type::INT); + REQUIRE(value.m_int_value == 420); +} + +TEST_CASE("SimpleExpressions: Can parse expression with divide operation", "[parsing][simple][expression]") { + SimpleExpressionTestsHelper helper; + const TokenPos pos; + helper.Tokens({SimpleParserValue::Integer(pos, 561540), SimpleParserValue::Character(pos, '/'), SimpleParserValue::Integer(pos, 420), + SimpleParserValue::EndOfFile(pos)}); + + const auto result = helper.PerformTest(); + + REQUIRE(result); + REQUIRE(helper.m_consumed_token_count == 3); + + const auto &expression = helper.m_state->m_expression; + REQUIRE(expression->IsStatic()); + + const auto value = expression->EvaluateStatic(); + REQUIRE(value.m_type == SimpleExpressionValue::Type::INT); + REQUIRE(value.m_int_value == 1337); +} + +TEST_CASE("SimpleExpressions: Can parse expression with remainder operation", "[parsing][simple][expression]") { + SimpleExpressionTestsHelper helper; + const TokenPos pos; + helper.Tokens({SimpleParserValue::Integer(pos, 92673), SimpleParserValue::Character(pos, '%'), SimpleParserValue::Integer(pos, 1337), + SimpleParserValue::EndOfFile(pos)}); + + const auto result = helper.PerformTest(); + + REQUIRE(result); + REQUIRE(helper.m_consumed_token_count == 3); + + const auto &expression = helper.m_state->m_expression; + REQUIRE(expression->IsStatic()); + + const auto value = expression->EvaluateStatic(); + REQUIRE(value.m_type == SimpleExpressionValue::Type::INT); + REQUIRE(value.m_int_value == 420); +} + +TEST_CASE("SimpleExpressions: Can parse expression with bitwise and operation", "[parsing][simple][expression]") { + SimpleExpressionTestsHelper helper; + const TokenPos pos; + helper.Tokens({SimpleParserValue::Integer(pos, 0x7FFFFFF0), SimpleParserValue::Character(pos, '&'), SimpleParserValue::Integer(pos, 0x2AAAAAAA), + SimpleParserValue::EndOfFile(pos)}); + + const auto result = helper.PerformTest(); + + REQUIRE(result); + REQUIRE(helper.m_consumed_token_count == 3); + + const auto &expression = helper.m_state->m_expression; + REQUIRE(expression->IsStatic()); + + const auto value = expression->EvaluateStatic(); + REQUIRE(value.m_type == SimpleExpressionValue::Type::INT); + REQUIRE(value.m_int_value == 0x2AAAAAA0); +} + +TEST_CASE("SimpleExpressions: Can parse expression with bitwise or operation", "[parsing][simple][expression]") { + SimpleExpressionTestsHelper helper; + const TokenPos pos; + helper.Tokens( + {SimpleParserValue::Integer(pos, 5), SimpleParserValue::Character(pos, '|'), SimpleParserValue::Integer(pos, 3), SimpleParserValue::EndOfFile(pos)}); + + const auto result = helper.PerformTest(); + + REQUIRE(result); + REQUIRE(helper.m_consumed_token_count == 3); + + const auto &expression = helper.m_state->m_expression; + REQUIRE(expression->IsStatic()); + + const auto value = expression->EvaluateStatic(); + REQUIRE(value.m_type == SimpleExpressionValue::Type::INT); + REQUIRE(value.m_int_value == 7); +} + +TEST_CASE("SimpleExpressions: Can parse expression with shift left operation", "[parsing][simple][expression]") { + SimpleExpressionTestsHelper helper; + const TokenPos pos; + helper.Tokens( + {SimpleParserValue::Integer(pos, 105), + SimpleParserValue::MultiCharacter(pos, SimpleExpressionMatchers::MULTI_TOKEN_OFFSET_BINARY + static_cast<int>(SimpleBinaryOperationId::SHIFT_LEFT)), + SimpleParserValue::Integer(pos, 2), SimpleParserValue::EndOfFile(pos)}); + + const auto result = helper.PerformTest(); + + REQUIRE(result); + REQUIRE(helper.m_consumed_token_count == 3); + + const auto &expression = helper.m_state->m_expression; + REQUIRE(expression->IsStatic()); + + const auto value = expression->EvaluateStatic(); + REQUIRE(value.m_type == SimpleExpressionValue::Type::INT); + REQUIRE(value.m_int_value == 420); +} + +TEST_CASE("SimpleExpressions: Can parse expression with shift right operation", "[parsing][simple][expression]") { + SimpleExpressionTestsHelper helper; + const TokenPos pos; + helper.Tokens( + {SimpleParserValue::Integer(pos, 42784), + SimpleParserValue::MultiCharacter(pos, SimpleExpressionMatchers::MULTI_TOKEN_OFFSET_BINARY + static_cast<int>(SimpleBinaryOperationId::SHIFT_RIGHT)), + SimpleParserValue::Integer(pos, 5), SimpleParserValue::EndOfFile(pos)}); + + const auto result = helper.PerformTest(); + + REQUIRE(result); + REQUIRE(helper.m_consumed_token_count == 3); + + const auto &expression = helper.m_state->m_expression; + REQUIRE(expression->IsStatic()); + + const auto value = expression->EvaluateStatic(); + REQUIRE(value.m_type == SimpleExpressionValue::Type::INT); + REQUIRE(value.m_int_value == 1337); +} + +TEST_CASE("SimpleExpressions: Can parse expression with greater operation", "[parsing][simple][expression]") { + SimpleExpressionTestsHelper helper; + const TokenPos pos; + helper.Tokens( + {SimpleParserValue::Integer(pos, 1337), SimpleParserValue::Character(pos, '>'), SimpleParserValue::Integer(pos, 420), SimpleParserValue::EndOfFile(pos)}); + + const auto result = helper.PerformTest(); + + REQUIRE(result); + REQUIRE(helper.m_consumed_token_count == 3); + + const auto &expression = helper.m_state->m_expression; + REQUIRE(expression->IsStatic()); + + const auto value = expression->EvaluateStatic(); + REQUIRE(value.m_type == SimpleExpressionValue::Type::INT); + REQUIRE(value.m_int_value == 1); +} + +TEST_CASE("SimpleExpressions: Can parse expression with greater equal operation", "[parsing][simple][expression]") { + SimpleExpressionTestsHelper helper; + const TokenPos pos; + helper.Tokens({SimpleParserValue::Integer(pos, 1337), + SimpleParserValue::MultiCharacter(pos, SimpleExpressionMatchers::MULTI_TOKEN_OFFSET_BINARY + + static_cast<int>(SimpleBinaryOperationId::GREATER_EQUAL_THAN)), + SimpleParserValue::Integer(pos, 420), SimpleParserValue::EndOfFile(pos)}); + + const auto result = helper.PerformTest(); + + REQUIRE(result); + REQUIRE(helper.m_consumed_token_count == 3); + + const auto &expression = helper.m_state->m_expression; + REQUIRE(expression->IsStatic()); + + const auto value = expression->EvaluateStatic(); + REQUIRE(value.m_type == SimpleExpressionValue::Type::INT); + REQUIRE(value.m_int_value == 1); +} + +TEST_CASE("SimpleExpressions: Can parse expression with less operation", "[parsing][simple][expression]") { + SimpleExpressionTestsHelper helper; + const TokenPos pos; + helper.Tokens( + {SimpleParserValue::Integer(pos, 420), SimpleParserValue::Character(pos, '<'), SimpleParserValue::Integer(pos, 421), SimpleParserValue::EndOfFile(pos)}); + + const auto result = helper.PerformTest(); + + REQUIRE(result); + REQUIRE(helper.m_consumed_token_count == 3); + + const auto &expression = helper.m_state->m_expression; + REQUIRE(expression->IsStatic()); + + const auto value = expression->EvaluateStatic(); + REQUIRE(value.m_type == SimpleExpressionValue::Type::INT); + REQUIRE(value.m_int_value == 1); +} + +TEST_CASE("SimpleExpressions: Can parse expression with less equal operation", "[parsing][simple][expression]") { + SimpleExpressionTestsHelper helper; + const TokenPos pos; + helper.Tokens( + {SimpleParserValue::Integer(pos, 420), + SimpleParserValue::MultiCharacter(pos, SimpleExpressionMatchers::MULTI_TOKEN_OFFSET_BINARY + static_cast<int>(SimpleBinaryOperationId::LESS_EQUAL_THAN)), + SimpleParserValue::Integer(pos, 421), SimpleParserValue::EndOfFile(pos)}); + + const auto result = helper.PerformTest(); + + REQUIRE(result); + REQUIRE(helper.m_consumed_token_count == 3); + + const auto &expression = helper.m_state->m_expression; + REQUIRE(expression->IsStatic()); + + const auto value = expression->EvaluateStatic(); + REQUIRE(value.m_type == SimpleExpressionValue::Type::INT); + REQUIRE(value.m_int_value == 1); +} + +TEST_CASE("SimpleExpressions: Can parse expression with equals operation", "[parsing][simple][expression]") { + SimpleExpressionTestsHelper helper; + const TokenPos pos; + helper.Tokens( + {SimpleParserValue::Integer(pos, 1337), + SimpleParserValue::MultiCharacter(pos, SimpleExpressionMatchers::MULTI_TOKEN_OFFSET_BINARY + static_cast<int>(SimpleBinaryOperationId::EQUALS)), + SimpleParserValue::Integer(pos, 1337), SimpleParserValue::EndOfFile(pos)}); + + const auto result = helper.PerformTest(); + + REQUIRE(result); + REQUIRE(helper.m_consumed_token_count == 3); + + const auto &expression = helper.m_state->m_expression; + REQUIRE(expression->IsStatic()); + + const auto value = expression->EvaluateStatic(); + REQUIRE(value.m_type == SimpleExpressionValue::Type::INT); + REQUIRE(value.m_int_value == 1); +} + +TEST_CASE("SimpleExpressions: Can parse expression with not equal operation", "[parsing][simple][expression]") { + SimpleExpressionTestsHelper helper; + const TokenPos pos; + helper.Tokens( + {SimpleParserValue::Integer(pos, 1337), + SimpleParserValue::MultiCharacter(pos, SimpleExpressionMatchers::MULTI_TOKEN_OFFSET_BINARY + static_cast<int>(SimpleBinaryOperationId::NOT_EQUAL)), + SimpleParserValue::Integer(pos, 1337), SimpleParserValue::EndOfFile(pos)}); + + const auto result = helper.PerformTest(); + + REQUIRE(result); + REQUIRE(helper.m_consumed_token_count == 3); + + const auto &expression = helper.m_state->m_expression; + REQUIRE(expression->IsStatic()); + + const auto value = expression->EvaluateStatic(); + REQUIRE(value.m_type == SimpleExpressionValue::Type::INT); + REQUIRE(value.m_int_value == 0); +} + +TEST_CASE("SimpleExpressions: Can parse expression with and operation", "[parsing][simple][expression]") { + SimpleExpressionTestsHelper helper; + const TokenPos pos; + helper.Tokens({SimpleParserValue::Integer(pos, 1337), + SimpleParserValue::MultiCharacter(pos, SimpleExpressionMatchers::MULTI_TOKEN_OFFSET_BINARY + static_cast<int>(SimpleBinaryOperationId::AND)), + SimpleParserValue::Integer(pos, 420), SimpleParserValue::EndOfFile(pos)}); + + const auto result = helper.PerformTest(); + + REQUIRE(result); + REQUIRE(helper.m_consumed_token_count == 3); + + const auto &expression = helper.m_state->m_expression; + REQUIRE(expression->IsStatic()); + + const auto value = expression->EvaluateStatic(); + REQUIRE(value.m_type == SimpleExpressionValue::Type::INT); + REQUIRE(value.m_int_value == 420); +} + +TEST_CASE("SimpleExpressions: Can parse expression with or operation", "[parsing][simple][expression]") { + SimpleExpressionTestsHelper helper; + const TokenPos pos; + helper.Tokens({SimpleParserValue::Integer(pos, 0), + SimpleParserValue::MultiCharacter(pos, SimpleExpressionMatchers::MULTI_TOKEN_OFFSET_BINARY + static_cast<int>(SimpleBinaryOperationId::OR)), + SimpleParserValue::Integer(pos, 1337), SimpleParserValue::EndOfFile(pos)}); + + const auto result = helper.PerformTest(); + + REQUIRE(result); + REQUIRE(helper.m_consumed_token_count == 3); + + const auto &expression = helper.m_state->m_expression; + REQUIRE(expression->IsStatic()); + + const auto value = expression->EvaluateStatic(); + REQUIRE(value.m_type == SimpleExpressionValue::Type::INT); + REQUIRE(value.m_int_value == 1337); +} + +TEST_CASE("SimpleExpressions: Operator precedence is applied", "[parsing][simple][expression]") { + SimpleExpressionTestsHelper helper; + const TokenPos pos; + helper.Tokens({SimpleParserValue::Integer(pos, 100), SimpleParserValue::Character(pos, '+'), SimpleParserValue::Integer(pos, 4), + SimpleParserValue::Character(pos, '*'), SimpleParserValue::Integer(pos, 25), SimpleParserValue::Character(pos, '+'), + SimpleParserValue::Integer(pos, 220), SimpleParserValue::EndOfFile(pos)}); + + const auto result = helper.PerformTest(); + + REQUIRE(result); + REQUIRE(helper.m_consumed_token_count == 7); + + const auto &expression = helper.m_state->m_expression; + REQUIRE(expression->IsStatic()); + + const auto value = expression->EvaluateStatic(); + REQUIRE(value.m_type == SimpleExpressionValue::Type::INT); + REQUIRE(value.m_int_value == 420); +} + +TEST_CASE("SimpleExpressions: Parenthesis have highest precedence", "[parsing][simple][expression]") { + SimpleExpressionTestsHelper helper; + const TokenPos pos; + helper.Tokens({SimpleParserValue::Character(pos, '('), SimpleParserValue::Integer(pos, 40), SimpleParserValue::Character(pos, '+'), + SimpleParserValue::Integer(pos, 2), SimpleParserValue::Character(pos, ')'), SimpleParserValue::Character(pos, '*'), + SimpleParserValue::Integer(pos, 10), SimpleParserValue::EndOfFile(pos)}); + + const auto result = helper.PerformTest(); + + REQUIRE(result); + REQUIRE(helper.m_consumed_token_count == 7); + + const auto &expression = helper.m_state->m_expression; + REQUIRE(expression->IsStatic()); + + const auto value = expression->EvaluateStatic(); + REQUIRE(value.m_type == SimpleExpressionValue::Type::INT); + REQUIRE(value.m_int_value == 420); +} + +TEST_CASE("SimpleExpressions: Simple conditional operator can be used with true value", "[parsing][simple][expression]") { + SimpleExpressionTestsHelper helper; + const TokenPos pos; + helper.Tokens({SimpleParserValue::Integer(pos, 1), SimpleParserValue::Character(pos, '?'), SimpleParserValue::Integer(pos, 420), + SimpleParserValue::Character(pos, ':'), SimpleParserValue::Integer(pos, 1337), SimpleParserValue::EndOfFile(pos)}); + + const auto result = helper.PerformTest(); + + REQUIRE(result); + REQUIRE(helper.m_consumed_token_count == 5); + + const auto &expression = helper.m_state->m_expression; + REQUIRE(expression->IsStatic()); + + const auto value = expression->EvaluateStatic(); + REQUIRE(value.m_type == SimpleExpressionValue::Type::INT); + REQUIRE(value.m_int_value == 420); +} + +TEST_CASE("SimpleExpressions: Simple conditional operator can be used with false value", "[parsing][simple][expression]") { + SimpleExpressionTestsHelper helper; + const TokenPos pos; + helper.Tokens({SimpleParserValue::Integer(pos, 0), SimpleParserValue::Character(pos, '?'), SimpleParserValue::Integer(pos, 420), + SimpleParserValue::Character(pos, ':'), SimpleParserValue::Integer(pos, 1337), SimpleParserValue::EndOfFile(pos)}); + + const auto result = helper.PerformTest(); + + REQUIRE(result); + REQUIRE(helper.m_consumed_token_count == 5); + + const auto &expression = helper.m_state->m_expression; + REQUIRE(expression->IsStatic()); + + const auto value = expression->EvaluateStatic(); + REQUIRE(value.m_type == SimpleExpressionValue::Type::INT); + REQUIRE(value.m_int_value == 1337); +} + +TEST_CASE("SimpleExpressions: Simple conditional operator can be used within parenthesis with true value", "[parsing][simple][expression]") { + SimpleExpressionTestsHelper helper; + const TokenPos pos; + helper.Tokens({SimpleParserValue::Character(pos, '('), SimpleParserValue::Integer(pos, 1), SimpleParserValue::Character(pos, '?'), + SimpleParserValue::Integer(pos, 420), SimpleParserValue::Character(pos, ':'), SimpleParserValue::Integer(pos, 1337), + SimpleParserValue::Character(pos, ')'), SimpleParserValue::Character(pos, '+'), SimpleParserValue::Integer(pos, 1), + SimpleParserValue::EndOfFile(pos)}); + + const auto result = helper.PerformTest(); + + REQUIRE(result); + REQUIRE(helper.m_consumed_token_count == 9); + + const auto &expression = helper.m_state->m_expression; + REQUIRE(expression->IsStatic()); + + const auto value = expression->EvaluateStatic(); + REQUIRE(value.m_type == SimpleExpressionValue::Type::INT); + REQUIRE(value.m_int_value == 421); +} + +TEST_CASE("SimpleExpressions: Simple conditional operator can be used within parenthesis with false value", "[parsing][simple][expression]") { + SimpleExpressionTestsHelper helper; + const TokenPos pos; + helper.Tokens({SimpleParserValue::Character(pos, '('), SimpleParserValue::Integer(pos, 0), SimpleParserValue::Character(pos, '?'), + SimpleParserValue::Integer(pos, 420), SimpleParserValue::Character(pos, ':'), SimpleParserValue::Integer(pos, 1337), + SimpleParserValue::Character(pos, ')'), SimpleParserValue::Character(pos, '+'), SimpleParserValue::Integer(pos, 1), + SimpleParserValue::EndOfFile(pos)}); + + const auto result = helper.PerformTest(); + + REQUIRE(result); + REQUIRE(helper.m_consumed_token_count == 9); + + const auto &expression = helper.m_state->m_expression; + REQUIRE(expression->IsStatic()); + + const auto value = expression->EvaluateStatic(); + REQUIRE(value.m_type == SimpleExpressionValue::Type::INT); + REQUIRE(value.m_int_value == 1338); +} + +TEST_CASE("SimpleExpressions: Simple conditional operator can have an expression as condition", "[parsing][simple][expression]") { + SimpleExpressionTestsHelper helper; + const TokenPos pos; + helper.Tokens({SimpleParserValue::Character(pos, '('), SimpleParserValue::Integer(pos, -1), SimpleParserValue::Character(pos, '+'), + SimpleParserValue::Integer(pos, 2), SimpleParserValue::Character(pos, ')'), SimpleParserValue::Character(pos, '?'), + SimpleParserValue::Integer(pos, 420), SimpleParserValue::Character(pos, ':'), SimpleParserValue::Integer(pos, 1337), + SimpleParserValue::EndOfFile(pos)}); + + const auto result = helper.PerformTest(); + + REQUIRE(result); + REQUIRE(helper.m_consumed_token_count == 9); + + const auto &expression = helper.m_state->m_expression; + REQUIRE(expression->IsStatic()); + + const auto value = expression->EvaluateStatic(); + REQUIRE(value.m_type == SimpleExpressionValue::Type::INT); + REQUIRE(value.m_int_value == 420); +} + +TEST_CASE("SimpleExpressions: Simple conditional operator can have an expression as true value", "[parsing][simple][expression]") { + SimpleExpressionTestsHelper helper; + const TokenPos pos; + helper.Tokens({SimpleParserValue::Integer(pos, 1), SimpleParserValue::Character(pos, '?'), SimpleParserValue::Character(pos, '('), + SimpleParserValue::Integer(pos, 210), SimpleParserValue::Character(pos, '*'), SimpleParserValue::Integer(pos, 2), + SimpleParserValue::Character(pos, ')'), SimpleParserValue::Character(pos, ':'), SimpleParserValue::Integer(pos, 1337), + SimpleParserValue::EndOfFile(pos)}); + + const auto result = helper.PerformTest(); + + REQUIRE(result); + REQUIRE(helper.m_consumed_token_count == 9); + + const auto &expression = helper.m_state->m_expression; + REQUIRE(expression->IsStatic()); + + const auto value = expression->EvaluateStatic(); + REQUIRE(value.m_type == SimpleExpressionValue::Type::INT); + REQUIRE(value.m_int_value == 420); +} + +TEST_CASE("SimpleExpressions: Simple conditional operator can have an expression as false value", "[parsing][simple][expression]") { + SimpleExpressionTestsHelper helper; + const TokenPos pos; + helper.Tokens({SimpleParserValue::Integer(pos, 0), SimpleParserValue::Character(pos, '?'), SimpleParserValue::Integer(pos, 420), + SimpleParserValue::Character(pos, ':'), SimpleParserValue::Character(pos, '('), SimpleParserValue::Integer(pos, 1336), + SimpleParserValue::Character(pos, '+'), SimpleParserValue::Integer(pos, 1), SimpleParserValue::Character(pos, ')'), + SimpleParserValue::EndOfFile(pos)}); + + const auto result = helper.PerformTest(); + + REQUIRE(result); + REQUIRE(helper.m_consumed_token_count == 9); + + const auto &expression = helper.m_state->m_expression; + REQUIRE(expression->IsStatic()); + + const auto value = expression->EvaluateStatic(); + REQUIRE(value.m_type == SimpleExpressionValue::Type::INT); + REQUIRE(value.m_int_value == 1337); +} + +namespace it { +TEST_CASE("SimpleExpressionsIT: Can parse subtraction without space", "[parsing][simple][expression][it]") { + SimpleExpressionTestsHelper helper; + helper.String("6-5"); + + const auto result = helper.PerformIntegrationTest(); + + REQUIRE(result); + + const auto &expression = helper.m_state->m_expression; + REQUIRE(expression->IsStatic()); + + const auto value = expression->EvaluateStatic(); + REQUIRE(value.m_type == SimpleExpressionValue::Type::INT); + REQUIRE(value.m_int_value == 1); +} + +TEST_CASE("SimpleExpressionsIT: Can parse addition without space", "[parsing][simple][expression][it]") { + SimpleExpressionTestsHelper helper; + helper.String("6+5"); + + const auto result = helper.PerformIntegrationTest(); + + REQUIRE(result); + + const auto &expression = helper.m_state->m_expression; + REQUIRE(expression->IsStatic()); -namespace test::parsing::simple::expression -{ - class SimpleExpressionTestState - { - public: - std::unique_ptr<ISimpleExpression> m_expression; - }; - - class SimpleExpressionSequence final : public AbstractSequence<SimpleParserValue, SimpleExpressionTestState> - { - const SimpleExpressionMatchers m_expression_matchers; - - public: - SimpleExpressionSequence() - : m_expression_matchers(true, true, true, true, true) - { - const SimpleMatcherFactory create(this); - - AddLabeledMatchers(m_expression_matchers.Expression(this), SimpleExpressionMatchers::LABEL_EXPRESSION); - AddMatchers(create.Label(SimpleExpressionMatchers::LABEL_EXPRESSION)); - } - - protected: - void ProcessMatch(SimpleExpressionTestState* state, SequenceResult<SimpleParserValue>& result) const override - { - if (state->m_expression) - throw ParsingException(TokenPos(), "Expression already set"); - - state->m_expression = m_expression_matchers.ProcessExpression(result); - } - }; - - class SimpleExpressionParser final : public AbstractParser<SimpleParserValue, SimpleExpressionTestState> - { - public: - explicit SimpleExpressionParser(ILexer<SimpleParserValue>* lexer) - : AbstractParser(lexer, std::make_unique<SimpleExpressionTestState>()) - { - } - - _NODISCARD SimpleExpressionTestState* GetState() const - { - return m_state.get(); - } - - protected: - const std::vector<sequence_t*>& GetTestsForState() override - { - static std::vector<sequence_t*> tests({ - new SimpleExpressionSequence() - }); - - return tests; - } - }; - - class SimpleExpressionTestsHelper - { - public: - SimpleExpressionTestState* m_state; - std::unique_ptr<SimpleExpressionTestState> m_state_holder; - std::string m_str; - std::istringstream m_ss; - std::unique_ptr<IParserLineStream> m_stream; - std::unique_ptr<ILexer<SimpleParserValue>> m_lexer; - std::unique_ptr<SimpleExpressionParser> m_parser; - - std::unique_ptr<SimpleExpressionSequence> m_sequence; - - unsigned m_consumed_token_count; - - SimpleExpressionTestsHelper() - : m_state(nullptr), - m_sequence(std::make_unique<SimpleExpressionSequence>()), - m_consumed_token_count(0u) - { - } - - void Tokens(std::initializer_list<Movable<SimpleParserValue>> tokens) - { - m_state_holder = std::make_unique<SimpleExpressionTestState>(); - m_state = m_state_holder.get(); - m_lexer = std::make_unique<MockLexer<SimpleParserValue>>(tokens, SimpleParserValue::EndOfFile(TokenPos())); - } - - void Tokens(std::vector<SimpleParserValue> tokens) - { - m_state_holder = std::make_unique<SimpleExpressionTestState>(); - m_state = m_state_holder.get(); - m_lexer = std::make_unique<MockLexer<SimpleParserValue>>(std::move(tokens), SimpleParserValue::EndOfFile(TokenPos())); - } - - void String(std::string str) - { - m_str = std::move(str); - m_ss = std::istringstream(m_str); - m_stream = std::make_unique<ParserSingleInputStream>(m_ss, "InputString"); - - SimpleLexer::Config lexerConfig; - lexerConfig.m_read_strings = true; - lexerConfig.m_string_escape_sequences = true; - lexerConfig.m_read_integer_numbers = true; - lexerConfig.m_read_floating_point_numbers = true; - lexerConfig.m_emit_new_line_tokens = false; - SimpleExpressionMatchers(true, true, true, true, true).ApplyTokensToLexerConfig(lexerConfig); - m_lexer = std::make_unique<SimpleLexer>(m_stream.get(), std::move(lexerConfig)); - m_parser = std::make_unique<SimpleExpressionParser>(m_lexer.get()); - m_state = m_parser->GetState(); - } - - bool PerformTest() - { - REQUIRE(m_lexer); - - m_consumed_token_count = 0; - return m_sequence->MatchSequence(m_lexer.get(), m_state, m_consumed_token_count); - } - - _NODISCARD bool PerformIntegrationTest() const - { - REQUIRE(m_lexer); - REQUIRE(m_parser); - - return m_parser->Parse(); - } - }; - - TEST_CASE("SimpleExpressions: Can parse expression with add operation", "[parsing][simple][expression]") - { - SimpleExpressionTestsHelper helper; - const TokenPos pos; - helper.Tokens({ - SimpleParserValue::Integer(pos, 1336), - SimpleParserValue::Character(pos, '+'), - SimpleParserValue::Integer(pos, 1), - SimpleParserValue::EndOfFile(pos) - }); - - const auto result = helper.PerformTest(); - - REQUIRE(result); - REQUIRE(helper.m_consumed_token_count == 3); - - const auto& expression = helper.m_state->m_expression; - REQUIRE(expression->IsStatic()); - - const auto value = expression->EvaluateStatic(); - REQUIRE(value.m_type == SimpleExpressionValue::Type::INT); - REQUIRE(value.m_int_value == 1337); - } - - TEST_CASE("SimpleExpressions: Can parse expression with subtract operation", "[parsing][simple][expression]") - { - SimpleExpressionTestsHelper helper; - const TokenPos pos; - helper.Tokens({ - SimpleParserValue::Integer(pos, 428), - SimpleParserValue::Character(pos, '-'), - SimpleParserValue::Integer(pos, 8), - SimpleParserValue::EndOfFile(pos) - }); - - const auto result = helper.PerformTest(); - - REQUIRE(result); - REQUIRE(helper.m_consumed_token_count == 3); - - const auto& expression = helper.m_state->m_expression; - REQUIRE(expression->IsStatic()); - - const auto value = expression->EvaluateStatic(); - REQUIRE(value.m_type == SimpleExpressionValue::Type::INT); - REQUIRE(value.m_int_value == 420); - } - - TEST_CASE("SimpleExpressions: Can parse expression with multiply operation", "[parsing][simple][expression]") - { - SimpleExpressionTestsHelper helper; - const TokenPos pos; - helper.Tokens({ - SimpleParserValue::Integer(pos, 105), - SimpleParserValue::Character(pos, '*'), - SimpleParserValue::Integer(pos, 4), - SimpleParserValue::EndOfFile(pos) - }); - - const auto result = helper.PerformTest(); - - REQUIRE(result); - REQUIRE(helper.m_consumed_token_count == 3); - - const auto& expression = helper.m_state->m_expression; - REQUIRE(expression->IsStatic()); - - const auto value = expression->EvaluateStatic(); - REQUIRE(value.m_type == SimpleExpressionValue::Type::INT); - REQUIRE(value.m_int_value == 420); - } - - TEST_CASE("SimpleExpressions: Can parse expression with divide operation", "[parsing][simple][expression]") - { - SimpleExpressionTestsHelper helper; - const TokenPos pos; - helper.Tokens({ - SimpleParserValue::Integer(pos, 561540), - SimpleParserValue::Character(pos, '/'), - SimpleParserValue::Integer(pos, 420), - SimpleParserValue::EndOfFile(pos) - }); - - const auto result = helper.PerformTest(); - - REQUIRE(result); - REQUIRE(helper.m_consumed_token_count == 3); - - const auto& expression = helper.m_state->m_expression; - REQUIRE(expression->IsStatic()); - - const auto value = expression->EvaluateStatic(); - REQUIRE(value.m_type == SimpleExpressionValue::Type::INT); - REQUIRE(value.m_int_value == 1337); - } - - TEST_CASE("SimpleExpressions: Can parse expression with remainder operation", "[parsing][simple][expression]") - { - SimpleExpressionTestsHelper helper; - const TokenPos pos; - helper.Tokens({ - SimpleParserValue::Integer(pos, 92673), - SimpleParserValue::Character(pos, '%'), - SimpleParserValue::Integer(pos, 1337), - SimpleParserValue::EndOfFile(pos) - }); - - const auto result = helper.PerformTest(); - - REQUIRE(result); - REQUIRE(helper.m_consumed_token_count == 3); - - const auto& expression = helper.m_state->m_expression; - REQUIRE(expression->IsStatic()); - - const auto value = expression->EvaluateStatic(); - REQUIRE(value.m_type == SimpleExpressionValue::Type::INT); - REQUIRE(value.m_int_value == 420); - } - - TEST_CASE("SimpleExpressions: Can parse expression with bitwise and operation", "[parsing][simple][expression]") - { - SimpleExpressionTestsHelper helper; - const TokenPos pos; - helper.Tokens({ - SimpleParserValue::Integer(pos, 0x7FFFFFF0), - SimpleParserValue::Character(pos, '&'), - SimpleParserValue::Integer(pos, 0x2AAAAAAA), - SimpleParserValue::EndOfFile(pos) - }); - - const auto result = helper.PerformTest(); - - REQUIRE(result); - REQUIRE(helper.m_consumed_token_count == 3); - - const auto& expression = helper.m_state->m_expression; - REQUIRE(expression->IsStatic()); - - const auto value = expression->EvaluateStatic(); - REQUIRE(value.m_type == SimpleExpressionValue::Type::INT); - REQUIRE(value.m_int_value == 0x2AAAAAA0); - } - - TEST_CASE("SimpleExpressions: Can parse expression with bitwise or operation", "[parsing][simple][expression]") - { - SimpleExpressionTestsHelper helper; - const TokenPos pos; - helper.Tokens({ - SimpleParserValue::Integer(pos, 5), - SimpleParserValue::Character(pos, '|'), - SimpleParserValue::Integer(pos, 3), - SimpleParserValue::EndOfFile(pos) - }); - - const auto result = helper.PerformTest(); - - REQUIRE(result); - REQUIRE(helper.m_consumed_token_count == 3); - - const auto& expression = helper.m_state->m_expression; - REQUIRE(expression->IsStatic()); - - const auto value = expression->EvaluateStatic(); - REQUIRE(value.m_type == SimpleExpressionValue::Type::INT); - REQUIRE(value.m_int_value == 7); - } - - TEST_CASE("SimpleExpressions: Can parse expression with shift left operation", "[parsing][simple][expression]") - { - SimpleExpressionTestsHelper helper; - const TokenPos pos; - helper.Tokens({ - SimpleParserValue::Integer(pos, 105), - SimpleParserValue::MultiCharacter(pos, SimpleExpressionMatchers::MULTI_TOKEN_OFFSET_BINARY + static_cast<int>(SimpleBinaryOperationId::SHIFT_LEFT)), - SimpleParserValue::Integer(pos, 2), - SimpleParserValue::EndOfFile(pos) - }); - - const auto result = helper.PerformTest(); - - REQUIRE(result); - REQUIRE(helper.m_consumed_token_count == 3); - - const auto& expression = helper.m_state->m_expression; - REQUIRE(expression->IsStatic()); - - const auto value = expression->EvaluateStatic(); - REQUIRE(value.m_type == SimpleExpressionValue::Type::INT); - REQUIRE(value.m_int_value == 420); - } - - TEST_CASE("SimpleExpressions: Can parse expression with shift right operation", "[parsing][simple][expression]") - { - SimpleExpressionTestsHelper helper; - const TokenPos pos; - helper.Tokens({ - SimpleParserValue::Integer(pos, 42784), - SimpleParserValue::MultiCharacter(pos, SimpleExpressionMatchers::MULTI_TOKEN_OFFSET_BINARY + static_cast<int>(SimpleBinaryOperationId::SHIFT_RIGHT)), - SimpleParserValue::Integer(pos, 5), - SimpleParserValue::EndOfFile(pos) - }); - - const auto result = helper.PerformTest(); - - REQUIRE(result); - REQUIRE(helper.m_consumed_token_count == 3); - - const auto& expression = helper.m_state->m_expression; - REQUIRE(expression->IsStatic()); - - const auto value = expression->EvaluateStatic(); - REQUIRE(value.m_type == SimpleExpressionValue::Type::INT); - REQUIRE(value.m_int_value == 1337); - } - - TEST_CASE("SimpleExpressions: Can parse expression with greater operation", "[parsing][simple][expression]") - { - SimpleExpressionTestsHelper helper; - const TokenPos pos; - helper.Tokens({ - SimpleParserValue::Integer(pos, 1337), - SimpleParserValue::Character(pos, '>'), - SimpleParserValue::Integer(pos, 420), - SimpleParserValue::EndOfFile(pos) - }); - - const auto result = helper.PerformTest(); - - REQUIRE(result); - REQUIRE(helper.m_consumed_token_count == 3); - - const auto& expression = helper.m_state->m_expression; - REQUIRE(expression->IsStatic()); - - const auto value = expression->EvaluateStatic(); - REQUIRE(value.m_type == SimpleExpressionValue::Type::INT); - REQUIRE(value.m_int_value == 1); - } - - TEST_CASE("SimpleExpressions: Can parse expression with greater equal operation", "[parsing][simple][expression]") - { - SimpleExpressionTestsHelper helper; - const TokenPos pos; - helper.Tokens({ - SimpleParserValue::Integer(pos, 1337), - SimpleParserValue::MultiCharacter(pos, SimpleExpressionMatchers::MULTI_TOKEN_OFFSET_BINARY + static_cast<int>(SimpleBinaryOperationId::GREATER_EQUAL_THAN)), - SimpleParserValue::Integer(pos, 420), - SimpleParserValue::EndOfFile(pos) - }); - - const auto result = helper.PerformTest(); - - REQUIRE(result); - REQUIRE(helper.m_consumed_token_count == 3); - - const auto& expression = helper.m_state->m_expression; - REQUIRE(expression->IsStatic()); - - const auto value = expression->EvaluateStatic(); - REQUIRE(value.m_type == SimpleExpressionValue::Type::INT); - REQUIRE(value.m_int_value == 1); - } - - TEST_CASE("SimpleExpressions: Can parse expression with less operation", "[parsing][simple][expression]") - { - SimpleExpressionTestsHelper helper; - const TokenPos pos; - helper.Tokens({ - SimpleParserValue::Integer(pos, 420), - SimpleParserValue::Character(pos, '<'), - SimpleParserValue::Integer(pos, 421), - SimpleParserValue::EndOfFile(pos) - }); - - const auto result = helper.PerformTest(); - - REQUIRE(result); - REQUIRE(helper.m_consumed_token_count == 3); - - const auto& expression = helper.m_state->m_expression; - REQUIRE(expression->IsStatic()); - - const auto value = expression->EvaluateStatic(); - REQUIRE(value.m_type == SimpleExpressionValue::Type::INT); - REQUIRE(value.m_int_value == 1); - } - - TEST_CASE("SimpleExpressions: Can parse expression with less equal operation", "[parsing][simple][expression]") - { - SimpleExpressionTestsHelper helper; - const TokenPos pos; - helper.Tokens({ - SimpleParserValue::Integer(pos, 420), - SimpleParserValue::MultiCharacter(pos, SimpleExpressionMatchers::MULTI_TOKEN_OFFSET_BINARY + static_cast<int>(SimpleBinaryOperationId::LESS_EQUAL_THAN)), - SimpleParserValue::Integer(pos, 421), - SimpleParserValue::EndOfFile(pos) - }); - - const auto result = helper.PerformTest(); - - REQUIRE(result); - REQUIRE(helper.m_consumed_token_count == 3); - - const auto& expression = helper.m_state->m_expression; - REQUIRE(expression->IsStatic()); - - const auto value = expression->EvaluateStatic(); - REQUIRE(value.m_type == SimpleExpressionValue::Type::INT); - REQUIRE(value.m_int_value == 1); - } - - TEST_CASE("SimpleExpressions: Can parse expression with equals operation", "[parsing][simple][expression]") - { - SimpleExpressionTestsHelper helper; - const TokenPos pos; - helper.Tokens({ - SimpleParserValue::Integer(pos, 1337), - SimpleParserValue::MultiCharacter(pos, SimpleExpressionMatchers::MULTI_TOKEN_OFFSET_BINARY + static_cast<int>(SimpleBinaryOperationId::EQUALS)), - SimpleParserValue::Integer(pos, 1337), - SimpleParserValue::EndOfFile(pos) - }); - - const auto result = helper.PerformTest(); - - REQUIRE(result); - REQUIRE(helper.m_consumed_token_count == 3); - - const auto& expression = helper.m_state->m_expression; - REQUIRE(expression->IsStatic()); - - const auto value = expression->EvaluateStatic(); - REQUIRE(value.m_type == SimpleExpressionValue::Type::INT); - REQUIRE(value.m_int_value == 1); - } - - TEST_CASE("SimpleExpressions: Can parse expression with not equal operation", "[parsing][simple][expression]") - { - SimpleExpressionTestsHelper helper; - const TokenPos pos; - helper.Tokens({ - SimpleParserValue::Integer(pos, 1337), - SimpleParserValue::MultiCharacter(pos, SimpleExpressionMatchers::MULTI_TOKEN_OFFSET_BINARY + static_cast<int>(SimpleBinaryOperationId::NOT_EQUAL)), - SimpleParserValue::Integer(pos, 1337), - SimpleParserValue::EndOfFile(pos) - }); - - const auto result = helper.PerformTest(); - - REQUIRE(result); - REQUIRE(helper.m_consumed_token_count == 3); - - const auto& expression = helper.m_state->m_expression; - REQUIRE(expression->IsStatic()); - - const auto value = expression->EvaluateStatic(); - REQUIRE(value.m_type == SimpleExpressionValue::Type::INT); - REQUIRE(value.m_int_value == 0); - } - - TEST_CASE("SimpleExpressions: Can parse expression with and operation", "[parsing][simple][expression]") - { - SimpleExpressionTestsHelper helper; - const TokenPos pos; - helper.Tokens({ - SimpleParserValue::Integer(pos, 1337), - SimpleParserValue::MultiCharacter(pos, SimpleExpressionMatchers::MULTI_TOKEN_OFFSET_BINARY + static_cast<int>(SimpleBinaryOperationId::AND)), - SimpleParserValue::Integer(pos, 420), - SimpleParserValue::EndOfFile(pos) - }); - - const auto result = helper.PerformTest(); - - REQUIRE(result); - REQUIRE(helper.m_consumed_token_count == 3); - - const auto& expression = helper.m_state->m_expression; - REQUIRE(expression->IsStatic()); - - const auto value = expression->EvaluateStatic(); - REQUIRE(value.m_type == SimpleExpressionValue::Type::INT); - REQUIRE(value.m_int_value == 420); - } - - TEST_CASE("SimpleExpressions: Can parse expression with or operation", "[parsing][simple][expression]") - { - SimpleExpressionTestsHelper helper; - const TokenPos pos; - helper.Tokens({ - SimpleParserValue::Integer(pos, 0), - SimpleParserValue::MultiCharacter(pos, SimpleExpressionMatchers::MULTI_TOKEN_OFFSET_BINARY + static_cast<int>(SimpleBinaryOperationId::OR)), - SimpleParserValue::Integer(pos, 1337), - SimpleParserValue::EndOfFile(pos) - }); - - const auto result = helper.PerformTest(); - - REQUIRE(result); - REQUIRE(helper.m_consumed_token_count == 3); - - const auto& expression = helper.m_state->m_expression; - REQUIRE(expression->IsStatic()); - - const auto value = expression->EvaluateStatic(); - REQUIRE(value.m_type == SimpleExpressionValue::Type::INT); - REQUIRE(value.m_int_value == 1337); - } - - TEST_CASE("SimpleExpressions: Operator precedence is applied", "[parsing][simple][expression]") - { - SimpleExpressionTestsHelper helper; - const TokenPos pos; - helper.Tokens({ - SimpleParserValue::Integer(pos, 100), - SimpleParserValue::Character(pos, '+'), - SimpleParserValue::Integer(pos, 4), - SimpleParserValue::Character(pos, '*'), - SimpleParserValue::Integer(pos, 25), - SimpleParserValue::Character(pos, '+'), - SimpleParserValue::Integer(pos, 220), - SimpleParserValue::EndOfFile(pos) - }); - - const auto result = helper.PerformTest(); - - REQUIRE(result); - REQUIRE(helper.m_consumed_token_count == 7); - - const auto& expression = helper.m_state->m_expression; - REQUIRE(expression->IsStatic()); - - const auto value = expression->EvaluateStatic(); - REQUIRE(value.m_type == SimpleExpressionValue::Type::INT); - REQUIRE(value.m_int_value == 420); - } - - TEST_CASE("SimpleExpressions: Parenthesis have highest precedence", "[parsing][simple][expression]") - { - SimpleExpressionTestsHelper helper; - const TokenPos pos; - helper.Tokens({ - SimpleParserValue::Character(pos, '('), - SimpleParserValue::Integer(pos, 40), - SimpleParserValue::Character(pos, '+'), - SimpleParserValue::Integer(pos, 2), - SimpleParserValue::Character(pos, ')'), - SimpleParserValue::Character(pos, '*'), - SimpleParserValue::Integer(pos, 10), - SimpleParserValue::EndOfFile(pos) - }); - - const auto result = helper.PerformTest(); - - REQUIRE(result); - REQUIRE(helper.m_consumed_token_count == 7); - - const auto& expression = helper.m_state->m_expression; - REQUIRE(expression->IsStatic()); - - const auto value = expression->EvaluateStatic(); - REQUIRE(value.m_type == SimpleExpressionValue::Type::INT); - REQUIRE(value.m_int_value == 420); - } - - TEST_CASE("SimpleExpressions: Simple conditional operator can be used with true value", "[parsing][simple][expression]") - { - SimpleExpressionTestsHelper helper; - const TokenPos pos; - helper.Tokens({ - SimpleParserValue::Integer(pos, 1), - SimpleParserValue::Character(pos, '?'), - SimpleParserValue::Integer(pos, 420), - SimpleParserValue::Character(pos, ':'), - SimpleParserValue::Integer(pos, 1337), - SimpleParserValue::EndOfFile(pos) - }); - - const auto result = helper.PerformTest(); - - REQUIRE(result); - REQUIRE(helper.m_consumed_token_count == 5); - - const auto& expression = helper.m_state->m_expression; - REQUIRE(expression->IsStatic()); - - const auto value = expression->EvaluateStatic(); - REQUIRE(value.m_type == SimpleExpressionValue::Type::INT); - REQUIRE(value.m_int_value == 420); - } - - TEST_CASE("SimpleExpressions: Simple conditional operator can be used with false value", "[parsing][simple][expression]") - { - SimpleExpressionTestsHelper helper; - const TokenPos pos; - helper.Tokens({ - SimpleParserValue::Integer(pos, 0), - SimpleParserValue::Character(pos, '?'), - SimpleParserValue::Integer(pos, 420), - SimpleParserValue::Character(pos, ':'), - SimpleParserValue::Integer(pos, 1337), - SimpleParserValue::EndOfFile(pos) - }); - - const auto result = helper.PerformTest(); - - REQUIRE(result); - REQUIRE(helper.m_consumed_token_count == 5); - - const auto& expression = helper.m_state->m_expression; - REQUIRE(expression->IsStatic()); - - const auto value = expression->EvaluateStatic(); - REQUIRE(value.m_type == SimpleExpressionValue::Type::INT); - REQUIRE(value.m_int_value == 1337); - } - - TEST_CASE("SimpleExpressions: Simple conditional operator can be used within parenthesis with true value", "[parsing][simple][expression]") - { - SimpleExpressionTestsHelper helper; - const TokenPos pos; - helper.Tokens({ - SimpleParserValue::Character(pos, '('), - SimpleParserValue::Integer(pos, 1), - SimpleParserValue::Character(pos, '?'), - SimpleParserValue::Integer(pos, 420), - SimpleParserValue::Character(pos, ':'), - SimpleParserValue::Integer(pos, 1337), - SimpleParserValue::Character(pos, ')'), - SimpleParserValue::Character(pos, '+'), - SimpleParserValue::Integer(pos, 1), - SimpleParserValue::EndOfFile(pos) - }); - - const auto result = helper.PerformTest(); - - REQUIRE(result); - REQUIRE(helper.m_consumed_token_count == 9); - - const auto& expression = helper.m_state->m_expression; - REQUIRE(expression->IsStatic()); - - const auto value = expression->EvaluateStatic(); - REQUIRE(value.m_type == SimpleExpressionValue::Type::INT); - REQUIRE(value.m_int_value == 421); - } - - TEST_CASE("SimpleExpressions: Simple conditional operator can be used within parenthesis with false value", "[parsing][simple][expression]") - { - SimpleExpressionTestsHelper helper; - const TokenPos pos; - helper.Tokens({ - SimpleParserValue::Character(pos, '('), - SimpleParserValue::Integer(pos, 0), - SimpleParserValue::Character(pos, '?'), - SimpleParserValue::Integer(pos, 420), - SimpleParserValue::Character(pos, ':'), - SimpleParserValue::Integer(pos, 1337), - SimpleParserValue::Character(pos, ')'), - SimpleParserValue::Character(pos, '+'), - SimpleParserValue::Integer(pos, 1), - SimpleParserValue::EndOfFile(pos) - }); - - const auto result = helper.PerformTest(); - - REQUIRE(result); - REQUIRE(helper.m_consumed_token_count == 9); - - const auto& expression = helper.m_state->m_expression; - REQUIRE(expression->IsStatic()); - - const auto value = expression->EvaluateStatic(); - REQUIRE(value.m_type == SimpleExpressionValue::Type::INT); - REQUIRE(value.m_int_value == 1338); - } - - TEST_CASE("SimpleExpressions: Simple conditional operator can have an expression as condition", "[parsing][simple][expression]") - { - SimpleExpressionTestsHelper helper; - const TokenPos pos; - helper.Tokens({ - SimpleParserValue::Character(pos, '('), - SimpleParserValue::Integer(pos, -1), - SimpleParserValue::Character(pos, '+'), - SimpleParserValue::Integer(pos, 2), - SimpleParserValue::Character(pos, ')'), - SimpleParserValue::Character(pos, '?'), - SimpleParserValue::Integer(pos, 420), - SimpleParserValue::Character(pos, ':'), - SimpleParserValue::Integer(pos, 1337), - SimpleParserValue::EndOfFile(pos) - }); - - const auto result = helper.PerformTest(); - - REQUIRE(result); - REQUIRE(helper.m_consumed_token_count == 9); - - const auto& expression = helper.m_state->m_expression; - REQUIRE(expression->IsStatic()); - - const auto value = expression->EvaluateStatic(); - REQUIRE(value.m_type == SimpleExpressionValue::Type::INT); - REQUIRE(value.m_int_value == 420); - } - - TEST_CASE("SimpleExpressions: Simple conditional operator can have an expression as true value", "[parsing][simple][expression]") - { - SimpleExpressionTestsHelper helper; - const TokenPos pos; - helper.Tokens({ - SimpleParserValue::Integer(pos, 1), - SimpleParserValue::Character(pos, '?'), - SimpleParserValue::Character(pos, '('), - SimpleParserValue::Integer(pos, 210), - SimpleParserValue::Character(pos, '*'), - SimpleParserValue::Integer(pos, 2), - SimpleParserValue::Character(pos, ')'), - SimpleParserValue::Character(pos, ':'), - SimpleParserValue::Integer(pos, 1337), - SimpleParserValue::EndOfFile(pos) - }); - - const auto result = helper.PerformTest(); - - REQUIRE(result); - REQUIRE(helper.m_consumed_token_count == 9); - - const auto& expression = helper.m_state->m_expression; - REQUIRE(expression->IsStatic()); - - const auto value = expression->EvaluateStatic(); - REQUIRE(value.m_type == SimpleExpressionValue::Type::INT); - REQUIRE(value.m_int_value == 420); - } - - TEST_CASE("SimpleExpressions: Simple conditional operator can have an expression as false value", "[parsing][simple][expression]") - { - SimpleExpressionTestsHelper helper; - const TokenPos pos; - helper.Tokens({ - SimpleParserValue::Integer(pos, 0), - SimpleParserValue::Character(pos, '?'), - SimpleParserValue::Integer(pos, 420), - SimpleParserValue::Character(pos, ':'), - SimpleParserValue::Character(pos, '('), - SimpleParserValue::Integer(pos, 1336), - SimpleParserValue::Character(pos, '+'), - SimpleParserValue::Integer(pos, 1), - SimpleParserValue::Character(pos, ')'), - SimpleParserValue::EndOfFile(pos) - }); - - const auto result = helper.PerformTest(); - - REQUIRE(result); - REQUIRE(helper.m_consumed_token_count == 9); - - const auto& expression = helper.m_state->m_expression; - REQUIRE(expression->IsStatic()); - - const auto value = expression->EvaluateStatic(); - REQUIRE(value.m_type == SimpleExpressionValue::Type::INT); - REQUIRE(value.m_int_value == 1337); - } - - namespace it - { - TEST_CASE("SimpleExpressionsIT: Can parse subtraction without space", "[parsing][simple][expression][it]") - { - SimpleExpressionTestsHelper helper; - helper.String("6-5"); - - const auto result = helper.PerformIntegrationTest(); - - REQUIRE(result); - - const auto& expression = helper.m_state->m_expression; - REQUIRE(expression->IsStatic()); - - const auto value = expression->EvaluateStatic(); - REQUIRE(value.m_type == SimpleExpressionValue::Type::INT); - REQUIRE(value.m_int_value == 1); - } - - TEST_CASE("SimpleExpressionsIT: Can parse addition without space", "[parsing][simple][expression][it]") - { - SimpleExpressionTestsHelper helper; - helper.String("6+5"); - - const auto result = helper.PerformIntegrationTest(); - - REQUIRE(result); - - const auto& expression = helper.m_state->m_expression; - REQUIRE(expression->IsStatic()); - - const auto value = expression->EvaluateStatic(); - REQUIRE(value.m_type == SimpleExpressionValue::Type::INT); - REQUIRE(value.m_int_value == 11); - } - } + const auto value = expression->EvaluateStatic(); + REQUIRE(value.m_type == SimpleExpressionValue::Type::INT); + REQUIRE(value.m_int_value == 11); } +} // namespace it +} // namespace test::parsing::simple::expression diff --git a/test/ZoneCodeGeneratorLibTests/Parsing/Commands/Impl/CommandsLexerTests.cpp b/test/ZoneCodeGeneratorLibTests/Parsing/Commands/Impl/CommandsLexerTests.cpp index 8f5ed4172..a0cce7bce 100644 --- a/test/ZoneCodeGeneratorLibTests/Parsing/Commands/Impl/CommandsLexerTests.cpp +++ b/test/ZoneCodeGeneratorLibTests/Parsing/Commands/Impl/CommandsLexerTests.cpp @@ -4,10 +4,6 @@ #include "Parsing/Commands/Impl/CommandsLexer.h" #include "Parsing/Mock/MockParserLineStream.h" -namespace test::parsing::commands::impl::commands_lexer -{ - TEST_CASE("CommandsLexer: ", "[parsing][commands]") - { - - } -} +namespace test::parsing::commands::impl::commands_lexer { +TEST_CASE("CommandsLexer: ", "[parsing][commands]") {} +} // namespace test::parsing::commands::impl::commands_lexer diff --git a/test/ZoneCodeGeneratorLibTests/Parsing/Commands/Sequence/SequenceActionTests.cpp b/test/ZoneCodeGeneratorLibTests/Parsing/Commands/Sequence/SequenceActionTests.cpp index f801b59d6..45e306836 100644 --- a/test/ZoneCodeGeneratorLibTests/Parsing/Commands/Sequence/SequenceActionTests.cpp +++ b/test/ZoneCodeGeneratorLibTests/Parsing/Commands/Sequence/SequenceActionTests.cpp @@ -1,423 +1,304 @@ #include <catch2/catch_test_macros.hpp> #include <catch2/generators/catch_generators.hpp> -#include "Utils/ClassUtils.h" #include "Parsing/Commands/Sequence/SequenceAction.h" #include "Parsing/Mock/MockLexer.h" #include "Parsing/PostProcessing/CreateMemberInformationPostProcessor.h" #include "Parsing/PostProcessing/CreateStructureInformationPostProcessor.h" #include "Persistence/InMemory/InMemoryRepository.h" +#include "Utils/ClassUtils.h" + +namespace test::parsing::commands::sequence::sequence_action { +class CommandsSequenceTestsHelper { +public: + std::unique_ptr<IDataRepository> m_repository; + std::unique_ptr<CommandsParserState> m_state; + std::unique_ptr<ILexer<CommandsParserValue>> m_lexer; + + StructDefinition *m_test_struct_raw; + StructureInformation *m_test_struct; + + StructDefinition *m_test_struct2_raw; + StructureInformation *m_test_struct2; + + StructDefinition *m_arg_struct_raw; + StructureInformation *m_arg_struct; + + StructDefinition *m_arg_struct2_raw; + StructureInformation *m_arg_struct2; + + StructDefinition *m_arg_struct3_raw; + StructureInformation *m_arg_struct3; + + unsigned m_consumed_token_count; + +private: + void RetrieveInformationPointers() { + m_test_struct = m_repository->GetInformationFor(m_test_struct_raw); + REQUIRE(m_test_struct != nullptr); + m_test_struct2 = m_repository->GetInformationFor(m_test_struct2_raw); + REQUIRE(m_test_struct2 != nullptr); + m_arg_struct = m_repository->GetInformationFor(m_arg_struct_raw); + REQUIRE(m_arg_struct != nullptr); + m_arg_struct2 = m_repository->GetInformationFor(m_arg_struct2_raw); + REQUIRE(m_arg_struct2 != nullptr); + m_arg_struct3 = m_repository->GetInformationFor(m_arg_struct3_raw); + REQUIRE(m_arg_struct3 != nullptr); + } + + _NODISCARD bool CreateInformation() const { + auto createStructureInformation = std::make_unique<CreateStructureInformationPostProcessor>(); + auto createMemberInformation = std::make_unique<CreateMemberInformationPostProcessor>(); + + return createStructureInformation->PostProcess(m_repository.get()) && createMemberInformation->PostProcess(m_repository.get()); + } + + void AddSampleData() { + auto def = std::make_unique<StructDefinition>("", "test_struct_t", 8); + def->m_members.emplace_back(std::make_shared<Variable>("m_test", std::make_unique<TypeDeclaration>(BaseTypeDefinition::BOOL))); + m_test_struct_raw = def.get(); + m_repository->Add(std::move(def)); + + def = std::make_unique<StructDefinition>("", "container_struct_t", 8); + def->m_members.emplace_back(std::make_shared<Variable>("m_child", std::make_unique<TypeDeclaration>(m_test_struct_raw))); + m_test_struct2_raw = def.get(); + m_repository->Add(std::move(def)); + + def = std::make_unique<StructDefinition>("", "arg_t", 8); + def->m_members.emplace_back(std::make_shared<Variable>("m_hello_world", std::make_unique<TypeDeclaration>(BaseTypeDefinition::INT))); + m_arg_struct_raw = def.get(); + m_repository->Add(std::move(def)); + + def = std::make_unique<StructDefinition>("", "another_arg_t", 8); + def->m_members.emplace_back(std::make_shared<Variable>("m_hello_galaxy", std::make_unique<TypeDeclaration>(BaseTypeDefinition::DOUBLE))); + def->m_members.emplace_back(std::make_shared<Variable>("m_hello_universe", std::make_unique<TypeDeclaration>(BaseTypeDefinition::CHAR))); + m_arg_struct2_raw = def.get(); + m_repository->Add(std::move(def)); + + def = std::make_unique<StructDefinition>("", "yeet_t", 8); + def->m_members.emplace_back(std::make_shared<Variable>("m_ya", std::make_unique<TypeDeclaration>(m_arg_struct_raw))); + def->m_members.emplace_back(std::make_shared<Variable>("m_yeeeeeet", std::make_unique<TypeDeclaration>(m_arg_struct2_raw))); + m_arg_struct3_raw = def.get(); + m_repository->Add(std::move(def)); + } + +public: + CommandsSequenceTestsHelper() + : m_repository(std::make_unique<InMemoryRepository>()), m_state(std::make_unique<CommandsParserState>(m_repository.get())), m_test_struct_raw(nullptr), + m_test_struct(nullptr), m_test_struct2_raw(nullptr), m_test_struct2(nullptr), m_arg_struct_raw(nullptr), m_arg_struct(nullptr), + m_arg_struct2_raw(nullptr), m_arg_struct2(nullptr), m_arg_struct3_raw(nullptr), m_arg_struct3(nullptr), m_consumed_token_count(0u) { + AddSampleData(); + REQUIRE(CreateInformation()); + RetrieveInformationPointers(); + } + + void Tokens(std::initializer_list<Movable<CommandsParserValue>> tokens) { + m_lexer = std::make_unique<MockLexer<CommandsParserValue>>(tokens, CommandsParserValue::EndOfFile(TokenPos())); + } + + bool PerformTest() { + REQUIRE(m_lexer); + const auto sequence = std::make_unique<SequenceAction>(); + return sequence->MatchSequence(m_lexer.get(), m_state.get(), m_consumed_token_count); + } +}; + +TEST_CASE("SequenceAction: Ensure can parse simple action directive", "[parsing][sequence]") { + CommandsSequenceTestsHelper helper; + const TokenPos pos; + helper.Tokens({CommandsParserValue::Identifier(pos, new std::string("set")), CommandsParserValue::Identifier(pos, new std::string("action")), + CommandsParserValue::Identifier(pos, new std::string("test_struct_t")), CommandsParserValue::Identifier(pos, new std::string("TestMethod")), + CommandsParserValue::Character(pos, '('), CommandsParserValue::Character(pos, ')'), CommandsParserValue::Character(pos, ';'), + CommandsParserValue::EndOfFile(pos)}); + + auto result = helper.PerformTest(); + + REQUIRE(result); + REQUIRE(helper.m_consumed_token_count == 7); + REQUIRE(helper.m_test_struct->m_post_load_action); + REQUIRE(helper.m_test_struct->m_post_load_action->m_action_name == "TestMethod"); + REQUIRE(helper.m_test_struct->m_post_load_action->m_parameter_types.empty()); +} + +TEST_CASE("SequenceAction: Ensure can parse simple action directive with one arg", "[parsing][sequence]") { + CommandsSequenceTestsHelper helper; + const TokenPos pos; + helper.Tokens({CommandsParserValue::Identifier(pos, new std::string("set")), CommandsParserValue::Identifier(pos, new std::string("action")), + CommandsParserValue::Identifier(pos, new std::string("test_struct_t")), CommandsParserValue::Identifier(pos, new std::string("TestMethod")), + CommandsParserValue::Character(pos, '('), CommandsParserValue::Identifier(pos, new std::string("arg_t")), + CommandsParserValue::Character(pos, ')'), CommandsParserValue::Character(pos, ';'), CommandsParserValue::EndOfFile(pos)}); + + auto result = helper.PerformTest(); + + REQUIRE(result); + REQUIRE(helper.m_consumed_token_count == 8); + REQUIRE(helper.m_test_struct->m_post_load_action); + REQUIRE(helper.m_test_struct->m_post_load_action->m_action_name == "TestMethod"); + REQUIRE(helper.m_test_struct->m_post_load_action->m_parameter_types.size() == 1); + REQUIRE(helper.m_test_struct->m_post_load_action->m_parameter_types[0] == helper.m_arg_struct_raw); +} + +TEST_CASE("SequenceAction: Ensure can parse simple action directive with two args", "[parsing][sequence]") { + CommandsSequenceTestsHelper helper; + const TokenPos pos; + helper.Tokens({CommandsParserValue::Identifier(pos, new std::string("set")), CommandsParserValue::Identifier(pos, new std::string("action")), + CommandsParserValue::Identifier(pos, new std::string("test_struct_t")), CommandsParserValue::Identifier(pos, new std::string("TestMethod")), + CommandsParserValue::Character(pos, '('), CommandsParserValue::Identifier(pos, new std::string("arg_t")), + CommandsParserValue::Character(pos, ','), CommandsParserValue::Identifier(pos, new std::string("another_arg_t")), + CommandsParserValue::Character(pos, ')'), CommandsParserValue::Character(pos, ';'), CommandsParserValue::EndOfFile(pos)}); + + auto result = helper.PerformTest(); + + REQUIRE(result); + REQUIRE(helper.m_consumed_token_count == 10); + REQUIRE(helper.m_test_struct->m_post_load_action); + REQUIRE(helper.m_test_struct->m_post_load_action->m_action_name == "TestMethod"); + REQUIRE(helper.m_test_struct->m_post_load_action->m_parameter_types.size() == 2); + REQUIRE(helper.m_test_struct->m_post_load_action->m_parameter_types[0] == helper.m_arg_struct_raw); + REQUIRE(helper.m_test_struct->m_post_load_action->m_parameter_types[1] == helper.m_arg_struct2_raw); +} + +TEST_CASE("SequenceAction: Ensure can parse simple action directive with three args", "[parsing][sequence]") { + CommandsSequenceTestsHelper helper; + const TokenPos pos; + helper.Tokens({CommandsParserValue::Identifier(pos, new std::string("set")), CommandsParserValue::Identifier(pos, new std::string("action")), + CommandsParserValue::Identifier(pos, new std::string("test_struct_t")), CommandsParserValue::Identifier(pos, new std::string("TestMethod")), + CommandsParserValue::Character(pos, '('), CommandsParserValue::Identifier(pos, new std::string("arg_t")), + CommandsParserValue::Character(pos, ','), CommandsParserValue::Identifier(pos, new std::string("another_arg_t")), + CommandsParserValue::Character(pos, ','), CommandsParserValue::Identifier(pos, new std::string("yeet_t")), + CommandsParserValue::Character(pos, ')'), CommandsParserValue::Character(pos, ';'), CommandsParserValue::EndOfFile(pos)}); + + auto result = helper.PerformTest(); + + REQUIRE(result); + REQUIRE(helper.m_consumed_token_count == 12); + REQUIRE(helper.m_test_struct->m_post_load_action); + REQUIRE(helper.m_test_struct->m_post_load_action->m_action_name == "TestMethod"); + REQUIRE(helper.m_test_struct->m_post_load_action->m_parameter_types.size() == 3); + REQUIRE(helper.m_test_struct->m_post_load_action->m_parameter_types[0] == helper.m_arg_struct_raw); + REQUIRE(helper.m_test_struct->m_post_load_action->m_parameter_types[1] == helper.m_arg_struct2_raw); + REQUIRE(helper.m_test_struct->m_post_load_action->m_parameter_types[2] == helper.m_arg_struct3_raw); +} + +TEST_CASE("SequenceAction: Fails if base typename does not exist", "[parsing][sequence]") { + CommandsSequenceTestsHelper helper; + const TokenPos pos; + helper.Tokens({CommandsParserValue::Identifier(pos, new std::string("set")), CommandsParserValue::Identifier(pos, new std::string("action")), + CommandsParserValue::Identifier(pos, new std::string("unknown_struct_t")), CommandsParserValue::Identifier(pos, new std::string("TestMethod")), + CommandsParserValue::Character(pos, '('), CommandsParserValue::Character(pos, ')'), CommandsParserValue::Character(pos, ';'), + CommandsParserValue::EndOfFile(pos)}); + + REQUIRE_THROWS_AS(helper.PerformTest(), ParsingException); + REQUIRE(helper.m_test_struct->m_post_load_action == nullptr); +} + +TEST_CASE("SequenceAction: Fails if arg typename does not exist", "[parsing][sequence]") { + CommandsSequenceTestsHelper helper; + const TokenPos pos; + helper.Tokens({CommandsParserValue::Identifier(pos, new std::string("set")), CommandsParserValue::Identifier(pos, new std::string("action")), + CommandsParserValue::Identifier(pos, new std::string("test_struct_t")), CommandsParserValue::Identifier(pos, new std::string("TestMethod")), + CommandsParserValue::Character(pos, '('), CommandsParserValue::Identifier(pos, new std::string("arg_t")), + CommandsParserValue::Character(pos, ','), CommandsParserValue::Identifier(pos, new std::string("another_arg_t")), + CommandsParserValue::Character(pos, ','), CommandsParserValue::Identifier(pos, new std::string("unknown_type_t")), + CommandsParserValue::Character(pos, ')'), CommandsParserValue::Character(pos, ';'), CommandsParserValue::EndOfFile(pos)}); + + REQUIRE_THROWS_AS(helper.PerformTest(), ParsingException); + REQUIRE(helper.m_test_struct->m_post_load_action == nullptr); +} + +TEST_CASE("SequenceAction: Fails if no type and no use", "[parsing][sequence]") { + CommandsSequenceTestsHelper helper; + const TokenPos pos; + helper.Tokens({CommandsParserValue::Identifier(pos, new std::string("set")), CommandsParserValue::Identifier(pos, new std::string("action")), + CommandsParserValue::Identifier(pos, new std::string("TestMethod")), CommandsParserValue::Character(pos, '('), + CommandsParserValue::Character(pos, ')'), CommandsParserValue::Character(pos, ';'), CommandsParserValue::EndOfFile(pos)}); + + REQUIRE_THROWS_AS(helper.PerformTest(), ParsingException); + REQUIRE(helper.m_test_struct->m_post_load_action == nullptr); +} + +TEST_CASE("SequenceAction: Ensure can parse action directive with used type", "[parsing][sequence]") { + CommandsSequenceTestsHelper helper; + const TokenPos pos; + helper.Tokens({CommandsParserValue::Identifier(pos, new std::string("set")), CommandsParserValue::Identifier(pos, new std::string("action")), + CommandsParserValue::Identifier(pos, new std::string("TestMethod")), CommandsParserValue::Character(pos, '('), + CommandsParserValue::Character(pos, ')'), CommandsParserValue::Character(pos, ';'), CommandsParserValue::EndOfFile(pos)}); + helper.m_state->SetInUse(helper.m_test_struct); + + auto result = helper.PerformTest(); + + REQUIRE(result); + REQUIRE(helper.m_consumed_token_count == 6); + REQUIRE(helper.m_test_struct->m_post_load_action); + REQUIRE(helper.m_test_struct->m_post_load_action->m_action_name == "TestMethod"); + REQUIRE(helper.m_test_struct->m_post_load_action->m_parameter_types.empty()); +} + +TEST_CASE("SequenceAction: Ensure can parse action directive with type from member", "[parsing][sequence]") { + CommandsSequenceTestsHelper helper; + const TokenPos pos; + helper.Tokens({CommandsParserValue::Identifier(pos, new std::string("set")), CommandsParserValue::Identifier(pos, new std::string("action")), + CommandsParserValue::Identifier(pos, new std::string("container_struct_t")), CommandsParserValue::Character(pos, ':'), + CommandsParserValue::Character(pos, ':'), CommandsParserValue::Identifier(pos, new std::string("m_child")), + CommandsParserValue::Identifier(pos, new std::string("TestMethod")), CommandsParserValue::Character(pos, '('), + CommandsParserValue::Character(pos, ')'), CommandsParserValue::Character(pos, ';'), CommandsParserValue::EndOfFile(pos)}); + + auto result = helper.PerformTest(); + + REQUIRE(result); + REQUIRE(helper.m_consumed_token_count == 10); + REQUIRE(helper.m_test_struct->m_post_load_action); + REQUIRE(helper.m_test_struct->m_post_load_action->m_action_name == "TestMethod"); + REQUIRE(helper.m_test_struct->m_post_load_action->m_parameter_types.empty()); +} + +TEST_CASE("SequenceAction: Ensure can parse action directive with type from member and in use", "[parsing][sequence]") { + CommandsSequenceTestsHelper helper; + const TokenPos pos; + helper.Tokens({CommandsParserValue::Identifier(pos, new std::string("set")), CommandsParserValue::Identifier(pos, new std::string("action")), + CommandsParserValue::Identifier(pos, new std::string("m_child")), CommandsParserValue::Identifier(pos, new std::string("TestMethod")), + CommandsParserValue::Character(pos, '('), CommandsParserValue::Character(pos, ')'), CommandsParserValue::Character(pos, ';'), + CommandsParserValue::EndOfFile(pos)}); + helper.m_state->SetInUse(helper.m_test_struct2); + + auto result = helper.PerformTest(); + + REQUIRE(result); + REQUIRE(helper.m_consumed_token_count == 7); + REQUIRE(helper.m_test_struct->m_post_load_action); + REQUIRE(helper.m_test_struct->m_post_load_action->m_action_name == "TestMethod"); + REQUIRE(helper.m_test_struct->m_post_load_action->m_parameter_types.empty()); +} + +TEST_CASE("SequenceAction: Ensure can use different struct even though something is used", "[parsing][sequence]") { + CommandsSequenceTestsHelper helper; + const TokenPos pos; + helper.Tokens({CommandsParserValue::Identifier(pos, new std::string("set")), CommandsParserValue::Identifier(pos, new std::string("action")), + CommandsParserValue::Identifier(pos, new std::string("container_struct_t")), CommandsParserValue::Character(pos, ':'), + CommandsParserValue::Character(pos, ':'), CommandsParserValue::Identifier(pos, new std::string("m_child")), + CommandsParserValue::Identifier(pos, new std::string("TestMethod")), CommandsParserValue::Character(pos, '('), + CommandsParserValue::Character(pos, ')'), CommandsParserValue::Character(pos, ';'), CommandsParserValue::EndOfFile(pos)}); + helper.m_state->SetInUse(helper.m_arg_struct2); + + auto result = helper.PerformTest(); + + REQUIRE(result); + REQUIRE(helper.m_consumed_token_count == 10); + REQUIRE(helper.m_test_struct->m_post_load_action); + REQUIRE(helper.m_test_struct->m_post_load_action->m_action_name == "TestMethod"); + REQUIRE(helper.m_test_struct->m_post_load_action->m_parameter_types.empty()); +} -namespace test::parsing::commands::sequence::sequence_action -{ - class CommandsSequenceTestsHelper - { - public: - std::unique_ptr<IDataRepository> m_repository; - std::unique_ptr<CommandsParserState> m_state; - std::unique_ptr<ILexer<CommandsParserValue>> m_lexer; - - StructDefinition* m_test_struct_raw; - StructureInformation* m_test_struct; - - StructDefinition* m_test_struct2_raw; - StructureInformation* m_test_struct2; - - StructDefinition* m_arg_struct_raw; - StructureInformation* m_arg_struct; - - StructDefinition* m_arg_struct2_raw; - StructureInformation* m_arg_struct2; - - StructDefinition* m_arg_struct3_raw; - StructureInformation* m_arg_struct3; - - unsigned m_consumed_token_count; - - private: - void RetrieveInformationPointers() - { - m_test_struct = m_repository->GetInformationFor(m_test_struct_raw); - REQUIRE(m_test_struct != nullptr); - m_test_struct2 = m_repository->GetInformationFor(m_test_struct2_raw); - REQUIRE(m_test_struct2 != nullptr); - m_arg_struct = m_repository->GetInformationFor(m_arg_struct_raw); - REQUIRE(m_arg_struct != nullptr); - m_arg_struct2 = m_repository->GetInformationFor(m_arg_struct2_raw); - REQUIRE(m_arg_struct2 != nullptr); - m_arg_struct3 = m_repository->GetInformationFor(m_arg_struct3_raw); - REQUIRE(m_arg_struct3 != nullptr); - } - - _NODISCARD bool CreateInformation() const - { - auto createStructureInformation = std::make_unique<CreateStructureInformationPostProcessor>(); - auto createMemberInformation = std::make_unique<CreateMemberInformationPostProcessor>(); - - return createStructureInformation->PostProcess(m_repository.get()) - && createMemberInformation->PostProcess(m_repository.get()); - } - - void AddSampleData() - { - auto def = std::make_unique<StructDefinition>("", "test_struct_t", 8); - def->m_members.emplace_back(std::make_shared<Variable>("m_test", std::make_unique<TypeDeclaration>(BaseTypeDefinition::BOOL))); - m_test_struct_raw = def.get(); - m_repository->Add(std::move(def)); - - def = std::make_unique<StructDefinition>("", "container_struct_t", 8); - def->m_members.emplace_back(std::make_shared<Variable>("m_child", std::make_unique<TypeDeclaration>(m_test_struct_raw))); - m_test_struct2_raw = def.get(); - m_repository->Add(std::move(def)); - - def = std::make_unique<StructDefinition>("", "arg_t", 8); - def->m_members.emplace_back(std::make_shared<Variable>("m_hello_world", std::make_unique<TypeDeclaration>(BaseTypeDefinition::INT))); - m_arg_struct_raw = def.get(); - m_repository->Add(std::move(def)); - - def = std::make_unique<StructDefinition>("", "another_arg_t", 8); - def->m_members.emplace_back(std::make_shared<Variable>("m_hello_galaxy", std::make_unique<TypeDeclaration>(BaseTypeDefinition::DOUBLE))); - def->m_members.emplace_back(std::make_shared<Variable>("m_hello_universe", std::make_unique<TypeDeclaration>(BaseTypeDefinition::CHAR))); - m_arg_struct2_raw = def.get(); - m_repository->Add(std::move(def)); - - def = std::make_unique<StructDefinition>("", "yeet_t", 8); - def->m_members.emplace_back(std::make_shared<Variable>("m_ya", std::make_unique<TypeDeclaration>(m_arg_struct_raw))); - def->m_members.emplace_back(std::make_shared<Variable>("m_yeeeeeet", std::make_unique<TypeDeclaration>(m_arg_struct2_raw))); - m_arg_struct3_raw = def.get(); - m_repository->Add(std::move(def)); - } - - public: - - CommandsSequenceTestsHelper() - : m_repository(std::make_unique<InMemoryRepository>()), - m_state(std::make_unique<CommandsParserState>(m_repository.get())), - m_test_struct_raw(nullptr), - m_test_struct(nullptr), - m_test_struct2_raw(nullptr), - m_test_struct2(nullptr), - m_arg_struct_raw(nullptr), - m_arg_struct(nullptr), - m_arg_struct2_raw(nullptr), - m_arg_struct2(nullptr), - m_arg_struct3_raw(nullptr), - m_arg_struct3(nullptr), - m_consumed_token_count(0u) - { - AddSampleData(); - REQUIRE(CreateInformation()); - RetrieveInformationPointers(); - } - - void Tokens(std::initializer_list<Movable<CommandsParserValue>> tokens) - { - m_lexer = std::make_unique<MockLexer<CommandsParserValue>>(tokens, CommandsParserValue::EndOfFile(TokenPos())); - } - - bool PerformTest() - { - REQUIRE(m_lexer); - const auto sequence = std::make_unique<SequenceAction>(); - return sequence->MatchSequence(m_lexer.get(), m_state.get(), m_consumed_token_count); - } - }; - - TEST_CASE("SequenceAction: Ensure can parse simple action directive", "[parsing][sequence]") - { - CommandsSequenceTestsHelper helper; - const TokenPos pos; - helper.Tokens({ - CommandsParserValue::Identifier(pos, new std::string("set")), - CommandsParserValue::Identifier(pos, new std::string("action")), - CommandsParserValue::Identifier(pos, new std::string("test_struct_t")), - CommandsParserValue::Identifier(pos, new std::string("TestMethod")), - CommandsParserValue::Character(pos, '('), - CommandsParserValue::Character(pos, ')'), - CommandsParserValue::Character(pos, ';'), - CommandsParserValue::EndOfFile(pos) - }); - - auto result = helper.PerformTest(); - - REQUIRE(result); - REQUIRE(helper.m_consumed_token_count == 7); - REQUIRE(helper.m_test_struct->m_post_load_action); - REQUIRE(helper.m_test_struct->m_post_load_action->m_action_name == "TestMethod"); - REQUIRE(helper.m_test_struct->m_post_load_action->m_parameter_types.empty()); - } - - TEST_CASE("SequenceAction: Ensure can parse simple action directive with one arg", "[parsing][sequence]") - { - CommandsSequenceTestsHelper helper; - const TokenPos pos; - helper.Tokens({ - CommandsParserValue::Identifier(pos, new std::string("set")), - CommandsParserValue::Identifier(pos, new std::string("action")), - CommandsParserValue::Identifier(pos, new std::string("test_struct_t")), - CommandsParserValue::Identifier(pos, new std::string("TestMethod")), - CommandsParserValue::Character(pos, '('), - CommandsParserValue::Identifier(pos, new std::string("arg_t")), - CommandsParserValue::Character(pos, ')'), - CommandsParserValue::Character(pos, ';'), - CommandsParserValue::EndOfFile(pos) - }); - - auto result = helper.PerformTest(); - - REQUIRE(result); - REQUIRE(helper.m_consumed_token_count == 8); - REQUIRE(helper.m_test_struct->m_post_load_action); - REQUIRE(helper.m_test_struct->m_post_load_action->m_action_name == "TestMethod"); - REQUIRE(helper.m_test_struct->m_post_load_action->m_parameter_types.size() == 1); - REQUIRE(helper.m_test_struct->m_post_load_action->m_parameter_types[0] == helper.m_arg_struct_raw); - } - - TEST_CASE("SequenceAction: Ensure can parse simple action directive with two args", "[parsing][sequence]") - { - CommandsSequenceTestsHelper helper; - const TokenPos pos; - helper.Tokens({ - CommandsParserValue::Identifier(pos, new std::string("set")), - CommandsParserValue::Identifier(pos, new std::string("action")), - CommandsParserValue::Identifier(pos, new std::string("test_struct_t")), - CommandsParserValue::Identifier(pos, new std::string("TestMethod")), - CommandsParserValue::Character(pos, '('), - CommandsParserValue::Identifier(pos, new std::string("arg_t")), - CommandsParserValue::Character(pos, ','), - CommandsParserValue::Identifier(pos, new std::string("another_arg_t")), - CommandsParserValue::Character(pos, ')'), - CommandsParserValue::Character(pos, ';'), - CommandsParserValue::EndOfFile(pos) - }); - - auto result = helper.PerformTest(); - - REQUIRE(result); - REQUIRE(helper.m_consumed_token_count == 10); - REQUIRE(helper.m_test_struct->m_post_load_action); - REQUIRE(helper.m_test_struct->m_post_load_action->m_action_name == "TestMethod"); - REQUIRE(helper.m_test_struct->m_post_load_action->m_parameter_types.size() == 2); - REQUIRE(helper.m_test_struct->m_post_load_action->m_parameter_types[0] == helper.m_arg_struct_raw); - REQUIRE(helper.m_test_struct->m_post_load_action->m_parameter_types[1] == helper.m_arg_struct2_raw); - } - - TEST_CASE("SequenceAction: Ensure can parse simple action directive with three args", "[parsing][sequence]") - { - CommandsSequenceTestsHelper helper; - const TokenPos pos; - helper.Tokens({ - CommandsParserValue::Identifier(pos, new std::string("set")), - CommandsParserValue::Identifier(pos, new std::string("action")), - CommandsParserValue::Identifier(pos, new std::string("test_struct_t")), - CommandsParserValue::Identifier(pos, new std::string("TestMethod")), - CommandsParserValue::Character(pos, '('), - CommandsParserValue::Identifier(pos, new std::string("arg_t")), - CommandsParserValue::Character(pos, ','), - CommandsParserValue::Identifier(pos, new std::string("another_arg_t")), - CommandsParserValue::Character(pos, ','), - CommandsParserValue::Identifier(pos, new std::string("yeet_t")), - CommandsParserValue::Character(pos, ')'), - CommandsParserValue::Character(pos, ';'), - CommandsParserValue::EndOfFile(pos) - }); - - auto result = helper.PerformTest(); - - REQUIRE(result); - REQUIRE(helper.m_consumed_token_count == 12); - REQUIRE(helper.m_test_struct->m_post_load_action); - REQUIRE(helper.m_test_struct->m_post_load_action->m_action_name == "TestMethod"); - REQUIRE(helper.m_test_struct->m_post_load_action->m_parameter_types.size() == 3); - REQUIRE(helper.m_test_struct->m_post_load_action->m_parameter_types[0] == helper.m_arg_struct_raw); - REQUIRE(helper.m_test_struct->m_post_load_action->m_parameter_types[1] == helper.m_arg_struct2_raw); - REQUIRE(helper.m_test_struct->m_post_load_action->m_parameter_types[2] == helper.m_arg_struct3_raw); - } - - TEST_CASE("SequenceAction: Fails if base typename does not exist", "[parsing][sequence]") - { - CommandsSequenceTestsHelper helper; - const TokenPos pos; - helper.Tokens({ - CommandsParserValue::Identifier(pos, new std::string("set")), - CommandsParserValue::Identifier(pos, new std::string("action")), - CommandsParserValue::Identifier(pos, new std::string("unknown_struct_t")), - CommandsParserValue::Identifier(pos, new std::string("TestMethod")), - CommandsParserValue::Character(pos, '('), - CommandsParserValue::Character(pos, ')'), - CommandsParserValue::Character(pos, ';'), - CommandsParserValue::EndOfFile(pos) - }); - - REQUIRE_THROWS_AS(helper.PerformTest(), ParsingException); - REQUIRE(helper.m_test_struct->m_post_load_action == nullptr); - } - - TEST_CASE("SequenceAction: Fails if arg typename does not exist", "[parsing][sequence]") - { - CommandsSequenceTestsHelper helper; - const TokenPos pos; - helper.Tokens({ - CommandsParserValue::Identifier(pos, new std::string("set")), - CommandsParserValue::Identifier(pos, new std::string("action")), - CommandsParserValue::Identifier(pos, new std::string("test_struct_t")), - CommandsParserValue::Identifier(pos, new std::string("TestMethod")), - CommandsParserValue::Character(pos, '('), - CommandsParserValue::Identifier(pos, new std::string("arg_t")), - CommandsParserValue::Character(pos, ','), - CommandsParserValue::Identifier(pos, new std::string("another_arg_t")), - CommandsParserValue::Character(pos, ','), - CommandsParserValue::Identifier(pos, new std::string("unknown_type_t")), - CommandsParserValue::Character(pos, ')'), - CommandsParserValue::Character(pos, ';'), - CommandsParserValue::EndOfFile(pos) - }); - - REQUIRE_THROWS_AS(helper.PerformTest(), ParsingException); - REQUIRE(helper.m_test_struct->m_post_load_action == nullptr); - } - - TEST_CASE("SequenceAction: Fails if no type and no use", "[parsing][sequence]") - { - CommandsSequenceTestsHelper helper; - const TokenPos pos; - helper.Tokens({ - CommandsParserValue::Identifier(pos, new std::string("set")), - CommandsParserValue::Identifier(pos, new std::string("action")), - CommandsParserValue::Identifier(pos, new std::string("TestMethod")), - CommandsParserValue::Character(pos, '('), - CommandsParserValue::Character(pos, ')'), - CommandsParserValue::Character(pos, ';'), - CommandsParserValue::EndOfFile(pos) - }); - - REQUIRE_THROWS_AS(helper.PerformTest(), ParsingException); - REQUIRE(helper.m_test_struct->m_post_load_action == nullptr); - } - - TEST_CASE("SequenceAction: Ensure can parse action directive with used type", "[parsing][sequence]") - { - CommandsSequenceTestsHelper helper; - const TokenPos pos; - helper.Tokens({ - CommandsParserValue::Identifier(pos, new std::string("set")), - CommandsParserValue::Identifier(pos, new std::string("action")), - CommandsParserValue::Identifier(pos, new std::string("TestMethod")), - CommandsParserValue::Character(pos, '('), - CommandsParserValue::Character(pos, ')'), - CommandsParserValue::Character(pos, ';'), - CommandsParserValue::EndOfFile(pos) - }); - helper.m_state->SetInUse(helper.m_test_struct); - - auto result = helper.PerformTest(); - - REQUIRE(result); - REQUIRE(helper.m_consumed_token_count == 6); - REQUIRE(helper.m_test_struct->m_post_load_action); - REQUIRE(helper.m_test_struct->m_post_load_action->m_action_name == "TestMethod"); - REQUIRE(helper.m_test_struct->m_post_load_action->m_parameter_types.empty()); - } - - TEST_CASE("SequenceAction: Ensure can parse action directive with type from member", "[parsing][sequence]") - { - CommandsSequenceTestsHelper helper; - const TokenPos pos; - helper.Tokens({ - CommandsParserValue::Identifier(pos, new std::string("set")), - CommandsParserValue::Identifier(pos, new std::string("action")), - CommandsParserValue::Identifier(pos, new std::string("container_struct_t")), - CommandsParserValue::Character(pos, ':'), - CommandsParserValue::Character(pos, ':'), - CommandsParserValue::Identifier(pos, new std::string("m_child")), - CommandsParserValue::Identifier(pos, new std::string("TestMethod")), - CommandsParserValue::Character(pos, '('), - CommandsParserValue::Character(pos, ')'), - CommandsParserValue::Character(pos, ';'), - CommandsParserValue::EndOfFile(pos) - }); - - auto result = helper.PerformTest(); - - REQUIRE(result); - REQUIRE(helper.m_consumed_token_count == 10); - REQUIRE(helper.m_test_struct->m_post_load_action); - REQUIRE(helper.m_test_struct->m_post_load_action->m_action_name == "TestMethod"); - REQUIRE(helper.m_test_struct->m_post_load_action->m_parameter_types.empty()); - } - - TEST_CASE("SequenceAction: Ensure can parse action directive with type from member and in use", "[parsing][sequence]") - { - CommandsSequenceTestsHelper helper; - const TokenPos pos; - helper.Tokens({ - CommandsParserValue::Identifier(pos, new std::string("set")), - CommandsParserValue::Identifier(pos, new std::string("action")), - CommandsParserValue::Identifier(pos, new std::string("m_child")), - CommandsParserValue::Identifier(pos, new std::string("TestMethod")), - CommandsParserValue::Character(pos, '('), - CommandsParserValue::Character(pos, ')'), - CommandsParserValue::Character(pos, ';'), - CommandsParserValue::EndOfFile(pos) - }); - helper.m_state->SetInUse(helper.m_test_struct2); - - auto result = helper.PerformTest(); - - REQUIRE(result); - REQUIRE(helper.m_consumed_token_count == 7); - REQUIRE(helper.m_test_struct->m_post_load_action); - REQUIRE(helper.m_test_struct->m_post_load_action->m_action_name == "TestMethod"); - REQUIRE(helper.m_test_struct->m_post_load_action->m_parameter_types.empty()); - } - - TEST_CASE("SequenceAction: Ensure can use different struct even though something is used", "[parsing][sequence]") - { - CommandsSequenceTestsHelper helper; - const TokenPos pos; - helper.Tokens({ - CommandsParserValue::Identifier(pos, new std::string("set")), - CommandsParserValue::Identifier(pos, new std::string("action")), - CommandsParserValue::Identifier(pos, new std::string("container_struct_t")), - CommandsParserValue::Character(pos, ':'), - CommandsParserValue::Character(pos, ':'), - CommandsParserValue::Identifier(pos, new std::string("m_child")), - CommandsParserValue::Identifier(pos, new std::string("TestMethod")), - CommandsParserValue::Character(pos, '('), - CommandsParserValue::Character(pos, ')'), - CommandsParserValue::Character(pos, ';'), - CommandsParserValue::EndOfFile(pos) - }); - helper.m_state->SetInUse(helper.m_arg_struct2); - - auto result = helper.PerformTest(); - - REQUIRE(result); - REQUIRE(helper.m_consumed_token_count == 10); - REQUIRE(helper.m_test_struct->m_post_load_action); - REQUIRE(helper.m_test_struct->m_post_load_action->m_action_name == "TestMethod"); - REQUIRE(helper.m_test_struct->m_post_load_action->m_parameter_types.empty()); - } - - TEST_CASE("SequenceAction: Ensure member must be type with members", "[parsing][sequence]") - { - CommandsSequenceTestsHelper helper; - const TokenPos pos; - helper.Tokens({ - CommandsParserValue::Identifier(pos, new std::string("set")), - CommandsParserValue::Identifier(pos, new std::string("action")), - CommandsParserValue::Identifier(pos, new std::string("test_struct_t")), - CommandsParserValue::Character(pos, ':'), - CommandsParserValue::Character(pos, ':'), - CommandsParserValue::Identifier(pos, new std::string("m_test")), - CommandsParserValue::Identifier(pos, new std::string("TestMethod")), - CommandsParserValue::Character(pos, '('), - CommandsParserValue::Character(pos, ')'), - CommandsParserValue::Character(pos, ';'), - CommandsParserValue::EndOfFile(pos) - }); - - REQUIRE_THROWS_AS(helper.PerformTest(), ParsingException); - REQUIRE(helper.m_test_struct->m_post_load_action == nullptr); - } +TEST_CASE("SequenceAction: Ensure member must be type with members", "[parsing][sequence]") { + CommandsSequenceTestsHelper helper; + const TokenPos pos; + helper.Tokens({CommandsParserValue::Identifier(pos, new std::string("set")), CommandsParserValue::Identifier(pos, new std::string("action")), + CommandsParserValue::Identifier(pos, new std::string("test_struct_t")), CommandsParserValue::Character(pos, ':'), + CommandsParserValue::Character(pos, ':'), CommandsParserValue::Identifier(pos, new std::string("m_test")), + CommandsParserValue::Identifier(pos, new std::string("TestMethod")), CommandsParserValue::Character(pos, '('), + CommandsParserValue::Character(pos, ')'), CommandsParserValue::Character(pos, ';'), CommandsParserValue::EndOfFile(pos)}); + + REQUIRE_THROWS_AS(helper.PerformTest(), ParsingException); + REQUIRE(helper.m_test_struct->m_post_load_action == nullptr); } +} // namespace test::parsing::commands::sequence::sequence_action diff --git a/test/ZoneCodeGeneratorLibTests/Parsing/Commands/Sequence/SequenceArchitectureTests.cpp b/test/ZoneCodeGeneratorLibTests/Parsing/Commands/Sequence/SequenceArchitectureTests.cpp index 12e7518de..0b1f0a295 100644 --- a/test/ZoneCodeGeneratorLibTests/Parsing/Commands/Sequence/SequenceArchitectureTests.cpp +++ b/test/ZoneCodeGeneratorLibTests/Parsing/Commands/Sequence/SequenceArchitectureTests.cpp @@ -1,90 +1,67 @@ #include <catch2/catch_test_macros.hpp> #include <catch2/generators/catch_generators.hpp> -#include "Utils/ClassUtils.h" #include "Parsing/Commands/Sequence/SequenceArchitecture.h" #include "Parsing/Mock/MockLexer.h" #include "Persistence/InMemory/InMemoryRepository.h" +#include "Utils/ClassUtils.h" + +namespace test::parsing::commands::sequence::sequence_architecture { +class CommandsSequenceTestsHelper { +public: + std::unique_ptr<IDataRepository> m_repository; + std::unique_ptr<CommandsParserState> m_state; + std::unique_ptr<ILexer<CommandsParserValue>> m_lexer; -namespace test::parsing::commands::sequence::sequence_architecture -{ - class CommandsSequenceTestsHelper - { - public: - std::unique_ptr<IDataRepository> m_repository; - std::unique_ptr<CommandsParserState> m_state; - std::unique_ptr<ILexer<CommandsParserValue>> m_lexer; + unsigned m_consumed_token_count; - unsigned m_consumed_token_count; - - CommandsSequenceTestsHelper() - : m_repository(std::make_unique<InMemoryRepository>()), - m_state(std::make_unique<CommandsParserState>(m_repository.get())), - m_consumed_token_count(0u) - { - } + CommandsSequenceTestsHelper() + : m_repository(std::make_unique<InMemoryRepository>()), m_state(std::make_unique<CommandsParserState>(m_repository.get())), m_consumed_token_count(0u) {} - void Tokens(std::initializer_list<Movable<CommandsParserValue>> tokens) - { - m_lexer = std::make_unique<MockLexer<CommandsParserValue>>(tokens, CommandsParserValue::EndOfFile(TokenPos())); - } + void Tokens(std::initializer_list<Movable<CommandsParserValue>> tokens) { + m_lexer = std::make_unique<MockLexer<CommandsParserValue>>(tokens, CommandsParserValue::EndOfFile(TokenPos())); + } - bool PerformTest() - { - REQUIRE(m_lexer); - const auto sequence = std::make_unique<SequenceArchitecture>(); - return sequence->MatchSequence(m_lexer.get(), m_state.get(), m_consumed_token_count); - } - }; + bool PerformTest() { + REQUIRE(m_lexer); + const auto sequence = std::make_unique<SequenceArchitecture>(); + return sequence->MatchSequence(m_lexer.get(), m_state.get(), m_consumed_token_count); + } +}; - TEST_CASE("SequenceArchitecture: Ensure can set x86", "[parsing][sequence]") - { - CommandsSequenceTestsHelper helper; - const TokenPos pos; - helper.Tokens({ - CommandsParserValue::Identifier(pos, new std::string("architecture")), - CommandsParserValue::Identifier(pos, new std::string("x86")), - CommandsParserValue::Character(pos, ';'), - CommandsParserValue::EndOfFile(pos) - }); +TEST_CASE("SequenceArchitecture: Ensure can set x86", "[parsing][sequence]") { + CommandsSequenceTestsHelper helper; + const TokenPos pos; + helper.Tokens({CommandsParserValue::Identifier(pos, new std::string("architecture")), CommandsParserValue::Identifier(pos, new std::string("x86")), + CommandsParserValue::Character(pos, ';'), CommandsParserValue::EndOfFile(pos)}); - auto result = helper.PerformTest(); + auto result = helper.PerformTest(); - REQUIRE(result); - REQUIRE(helper.m_consumed_token_count == 3); - REQUIRE(helper.m_repository->GetArchitecture() == Architecture::X86); - } + REQUIRE(result); + REQUIRE(helper.m_consumed_token_count == 3); + REQUIRE(helper.m_repository->GetArchitecture() == Architecture::X86); +} + +TEST_CASE("SequenceArchitecture: Ensure can set x64", "[parsing][sequence]") { + CommandsSequenceTestsHelper helper; + const TokenPos pos; + helper.Tokens({CommandsParserValue::Identifier(pos, new std::string("architecture")), CommandsParserValue::Identifier(pos, new std::string("x86")), + CommandsParserValue::Character(pos, ';'), CommandsParserValue::EndOfFile(pos)}); - TEST_CASE("SequenceArchitecture: Ensure can set x64", "[parsing][sequence]") - { - CommandsSequenceTestsHelper helper; - const TokenPos pos; - helper.Tokens({ - CommandsParserValue::Identifier(pos, new std::string("architecture")), - CommandsParserValue::Identifier(pos, new std::string("x86")), - CommandsParserValue::Character(pos, ';'), - CommandsParserValue::EndOfFile(pos) - }); + auto result = helper.PerformTest(); - auto result = helper.PerformTest(); + REQUIRE(result); + REQUIRE(helper.m_consumed_token_count == 3); + REQUIRE(helper.m_repository->GetArchitecture() == Architecture::X86); +} - REQUIRE(result); - REQUIRE(helper.m_consumed_token_count == 3); - REQUIRE(helper.m_repository->GetArchitecture() == Architecture::X86); - } +TEST_CASE("SequenceArchitecture: Ensure cannot match unknown value", "[parsing][sequence]") { + CommandsSequenceTestsHelper helper; + const TokenPos pos; + helper.Tokens({CommandsParserValue::Identifier(pos, new std::string("architecture")), CommandsParserValue::Identifier(pos, new std::string("x1337")), + CommandsParserValue::Character(pos, ';'), CommandsParserValue::EndOfFile(pos)}); - TEST_CASE("SequenceArchitecture: Ensure cannot match unknown value", "[parsing][sequence]") - { - CommandsSequenceTestsHelper helper; - const TokenPos pos; - helper.Tokens({ - CommandsParserValue::Identifier(pos, new std::string("architecture")), - CommandsParserValue::Identifier(pos, new std::string("x1337")), - CommandsParserValue::Character(pos, ';'), - CommandsParserValue::EndOfFile(pos) - }); - - REQUIRE_THROWS_AS(helper.PerformTest(), ParsingException); - REQUIRE(helper.m_repository->GetArchitecture() == Architecture::UNKNOWN); - } + REQUIRE_THROWS_AS(helper.PerformTest(), ParsingException); + REQUIRE(helper.m_repository->GetArchitecture() == Architecture::UNKNOWN); } +} // namespace test::parsing::commands::sequence::sequence_architecture diff --git a/test/ZoneCodeGeneratorLibTests/Parsing/Commands/Sequence/SequenceGameTests.cpp b/test/ZoneCodeGeneratorLibTests/Parsing/Commands/Sequence/SequenceGameTests.cpp index 03cc85c68..3e2b9e9ad 100644 --- a/test/ZoneCodeGeneratorLibTests/Parsing/Commands/Sequence/SequenceGameTests.cpp +++ b/test/ZoneCodeGeneratorLibTests/Parsing/Commands/Sequence/SequenceGameTests.cpp @@ -1,57 +1,44 @@ #include <catch2/catch_test_macros.hpp> #include <catch2/generators/catch_generators.hpp> -#include "Utils/ClassUtils.h" #include "Parsing/Commands/Sequence/SequenceGame.h" #include "Parsing/Mock/MockLexer.h" #include "Persistence/InMemory/InMemoryRepository.h" +#include "Utils/ClassUtils.h" + +namespace test::parsing::commands::sequence::sequence_game { +class CommandsSequenceTestsHelper { +public: + std::unique_ptr<IDataRepository> m_repository; + std::unique_ptr<CommandsParserState> m_state; + std::unique_ptr<ILexer<CommandsParserValue>> m_lexer; + + unsigned m_consumed_token_count; + + CommandsSequenceTestsHelper() + : m_repository(std::make_unique<InMemoryRepository>()), m_state(std::make_unique<CommandsParserState>(m_repository.get())), m_consumed_token_count(0u) {} + + void Tokens(std::initializer_list<Movable<CommandsParserValue>> tokens) { + m_lexer = std::make_unique<MockLexer<CommandsParserValue>>(tokens, CommandsParserValue::EndOfFile(TokenPos())); + } + + bool PerformTest() { + REQUIRE(m_lexer); + const auto sequence = std::make_unique<SequenceGame>(); + return sequence->MatchSequence(m_lexer.get(), m_state.get(), m_consumed_token_count); + } +}; + +TEST_CASE("SequenceGame: Ensure can set game", "[parsing][sequence]") { + CommandsSequenceTestsHelper helper; + const TokenPos pos; + helper.Tokens({CommandsParserValue::Identifier(pos, new std::string("game")), CommandsParserValue::Identifier(pos, new std::string("very_cool_game")), + CommandsParserValue::Character(pos, ';'), CommandsParserValue::EndOfFile(pos)}); + + auto result = helper.PerformTest(); -namespace test::parsing::commands::sequence::sequence_game -{ - class CommandsSequenceTestsHelper - { - public: - std::unique_ptr<IDataRepository> m_repository; - std::unique_ptr<CommandsParserState> m_state; - std::unique_ptr<ILexer<CommandsParserValue>> m_lexer; - - unsigned m_consumed_token_count; - - CommandsSequenceTestsHelper() - : m_repository(std::make_unique<InMemoryRepository>()), - m_state(std::make_unique<CommandsParserState>(m_repository.get())), - m_consumed_token_count(0u) - { - } - - void Tokens(std::initializer_list<Movable<CommandsParserValue>> tokens) - { - m_lexer = std::make_unique<MockLexer<CommandsParserValue>>(tokens, CommandsParserValue::EndOfFile(TokenPos())); - } - - bool PerformTest() - { - REQUIRE(m_lexer); - const auto sequence = std::make_unique<SequenceGame>(); - return sequence->MatchSequence(m_lexer.get(), m_state.get(), m_consumed_token_count); - } - }; - - TEST_CASE("SequenceGame: Ensure can set game", "[parsing][sequence]") - { - CommandsSequenceTestsHelper helper; - const TokenPos pos; - helper.Tokens({ - CommandsParserValue::Identifier(pos, new std::string("game")), - CommandsParserValue::Identifier(pos, new std::string("very_cool_game")), - CommandsParserValue::Character(pos, ';'), - CommandsParserValue::EndOfFile(pos) - }); - - auto result = helper.PerformTest(); - - REQUIRE(result); - REQUIRE(helper.m_consumed_token_count == 3); - REQUIRE(helper.m_repository->GetGameName() == "very_cool_game"); - } + REQUIRE(result); + REQUIRE(helper.m_consumed_token_count == 3); + REQUIRE(helper.m_repository->GetGameName() == "very_cool_game"); } +} // namespace test::parsing::commands::sequence::sequence_game diff --git a/test/ZoneCodeGeneratorLibTests/Parsing/Header/Impl/HeaderLexerTests.cpp b/test/ZoneCodeGeneratorLibTests/Parsing/Header/Impl/HeaderLexerTests.cpp index b33cc697e..5a220a459 100644 --- a/test/ZoneCodeGeneratorLibTests/Parsing/Header/Impl/HeaderLexerTests.cpp +++ b/test/ZoneCodeGeneratorLibTests/Parsing/Header/Impl/HeaderLexerTests.cpp @@ -1,565 +1,430 @@ #include <catch2/catch_test_macros.hpp> -#include <catch2/matchers/catch_matchers_floating_point.hpp> #include <catch2/generators/catch_generators.hpp> +#include <catch2/matchers/catch_matchers_floating_point.hpp> #include "Parsing/Header/Impl/HeaderLexer.h" #include "Parsing/Mock/MockParserLineStream.h" using namespace Catch::Matchers; -namespace test::parsing::header::impl::header_lexer -{ - void ExpectCharacterToken(HeaderLexer& lexer, char c) - { - REQUIRE(lexer.GetToken(0).m_type == HeaderParserValueType::CHARACTER); - REQUIRE(lexer.GetToken(0).CharacterValue() == c); - lexer.PopTokens(1); - } - - void ExpectIntegerToken(HeaderLexer& lexer, int number) - { - REQUIRE(lexer.GetToken(0).m_type == HeaderParserValueType::INTEGER); - REQUIRE(lexer.GetToken(0).IntegerValue() == number); - lexer.PopTokens(1); - } - - void ExpectFloatingPointToken(HeaderLexer& lexer, double number) - { - REQUIRE(lexer.GetToken(0).m_type == HeaderParserValueType::FLOATING_POINT); - const auto a = lexer.GetToken(0).FloatingPointValue(); - REQUIRE_THAT(lexer.GetToken(0).FloatingPointValue(), WithinRel(number)); - lexer.PopTokens(1); - } - - void ExpectIdentifierToken(HeaderLexer& lexer, const std::string& identifier) - { - REQUIRE(lexer.GetToken(0).m_type == HeaderParserValueType::IDENTIFIER); - REQUIRE(lexer.GetToken(0).IdentifierValue() == identifier); - lexer.PopTokens(1); - } - - void ExpectStringToken(HeaderLexer& lexer, const std::string& c) - { - REQUIRE(lexer.GetToken(0).m_type == HeaderParserValueType::STRING); - REQUIRE(lexer.GetToken(0).StringValue() == c); - lexer.PopTokens(1); - } - - void ExpectTokenWithType(HeaderLexer& lexer, HeaderParserValueType type) - { - REQUIRE(lexer.GetToken(0).m_type == type); - lexer.PopTokens(1); - } - - TEST_CASE("HeaderLexer: Ensure can parse simple hex numbers", "[parsing][header]") - { - const std::vector<std::string> lines - { - "0x1A4", - " 0xABC ", - " 0xAAA", - "0xBBB " - }; - - MockParserLineStream mockStream(lines); - HeaderLexer lexer(&mockStream); - - ExpectIntegerToken(lexer, 0x1a4); - ExpectIntegerToken(lexer, 0xabc); - ExpectIntegerToken(lexer, 0xaaa); - ExpectIntegerToken(lexer, 0xbbb); - - REQUIRE(lexer.GetToken(0).m_type == HeaderParserValueType::END_OF_FILE); - } - - TEST_CASE("HeaderLexer: Ensure can parse simple hex numbers surrounded by identifiers", "[parsing][header]") - { - const std::vector<std::string> lines - { - "abc 0xABC cba", - "aaa 0xAAA", - "0xBBB bbb" - }; - - MockParserLineStream mockStream(lines); - HeaderLexer lexer(&mockStream); - - ExpectIdentifierToken(lexer, "abc"); - ExpectIntegerToken(lexer, 0xabc); - ExpectIdentifierToken(lexer, "cba"); - - ExpectIdentifierToken(lexer, "aaa"); - ExpectIntegerToken(lexer, 0xaaa); - - ExpectIntegerToken(lexer, 0xbbb); - ExpectIdentifierToken(lexer, "bbb"); - - REQUIRE(lexer.GetToken(0).m_type == HeaderParserValueType::END_OF_FILE); - } - - TEST_CASE("HeaderLexer: Ensure can parse simple hex numbers surrounded by symbols", "[parsing][header]") - { - const std::vector<std::string> lines - { - "0x25:0xABC,0x1a4", - }; - - MockParserLineStream mockStream(lines); - HeaderLexer lexer(&mockStream); - - ExpectIntegerToken(lexer, 0x25); - ExpectCharacterToken(lexer, ':'); - ExpectIntegerToken(lexer, 0xABC); - ExpectCharacterToken(lexer, ','); - ExpectIntegerToken(lexer, 0x1a4); - - REQUIRE(lexer.GetToken(0).m_type == HeaderParserValueType::END_OF_FILE); - } - - TEST_CASE("HeaderLexer: Ensure throws exception when parsing incomplete hex number", "[parsing][header]") - { - const std::vector<std::string> lines - { - "0x" - }; - - MockParserLineStream mockStream(lines); - HeaderLexer lexer(&mockStream); - - REQUIRE_THROWS_AS(lexer.GetToken(0), ParsingException); - } - - TEST_CASE("HeaderLexer: Ensure throws exception when parsing invalid hex number", "[parsing][header]") - { - const std::vector<std::string> lines - { - "0xGEGE" - }; - - MockParserLineStream mockStream(lines); - HeaderLexer lexer(&mockStream); - - REQUIRE_THROWS_AS(lexer.GetToken(0), ParsingException); - } - - TEST_CASE("HeaderLexer: Ensure throws exception when parsing invalid hex number that starts with a valid letter", "[parsing][header]") - { - const std::vector<std::string> lines - { - "0xEGEG" - }; - - MockParserLineStream mockStream(lines); - HeaderLexer lexer(&mockStream); - - REQUIRE_THROWS_AS(lexer.GetToken(0), ParsingException); - } - - TEST_CASE("HeaderLexer: Ensure can parse simple integers", "[parsing][header]") - { - const std::vector<std::string> lines - { - " 524 ", - "4221111 1337 ", - "0 420" - }; - - MockParserLineStream mockStream(lines); - HeaderLexer lexer(&mockStream); - - ExpectIntegerToken(lexer, 524); - ExpectIntegerToken(lexer, 4221111); - ExpectIntegerToken(lexer, 1337); - ExpectIntegerToken(lexer, 0); - ExpectIntegerToken(lexer, 420); - } - - TEST_CASE("HeaderLexer: Ensure can parse integers surrounded by identifiers", "[parsing][header]") - { - const std::vector<std::string> lines - { - "aa 6 bb", - "123456789 ccc", - "0 d 420" - }; - - MockParserLineStream mockStream(lines); - HeaderLexer lexer(&mockStream); - - ExpectIdentifierToken(lexer, "aa"); - ExpectIntegerToken(lexer, 6); - ExpectIdentifierToken(lexer, "bb"); - ExpectIntegerToken(lexer, 123456789); - ExpectIdentifierToken(lexer, "ccc"); - ExpectIntegerToken(lexer, 0); - ExpectIdentifierToken(lexer, "d"); - ExpectIntegerToken(lexer, 420); - } - - TEST_CASE("HeaderLexer: Ensure parses negative numbers as character and number", "[parsing][header]") - { - const std::vector<std::string> lines - { - "-1337" - }; - - MockParserLineStream mockStream(lines); - HeaderLexer lexer(&mockStream); - - ExpectCharacterToken(lexer, '-'); - ExpectIntegerToken(lexer, 1337); - } - - TEST_CASE("HeaderLexer: Ensure recognizes numbers surrounded by characters", "[parsing][header]") - { - const std::vector<std::string> lines - { - "(1337)" - }; - - MockParserLineStream mockStream(lines); - HeaderLexer lexer(&mockStream); - - ExpectCharacterToken(lexer, '('); - ExpectIntegerToken(lexer, 1337); - ExpectCharacterToken(lexer, ')'); - } - - TEST_CASE("HeaderLexer: Ensure parses simple floating point numbers", "[parsing][header]") - { - const std::vector<std::string> lines - { - "420.1337" - }; - - MockParserLineStream mockStream(lines); - HeaderLexer lexer(&mockStream); - - ExpectFloatingPointToken(lexer, 420.1337); - } - - TEST_CASE("HeaderLexer: Ensure parses simple floating point numbers surrounded by identifiers", "[parsing][header]") - { - const std::vector<std::string> lines - { - "aa 50.24 a", - "b 36.999", - "59595.2414 c" - }; - - MockParserLineStream mockStream(lines); - HeaderLexer lexer(&mockStream); - - ExpectIdentifierToken(lexer, "aa"); - ExpectFloatingPointToken(lexer, 50.24); - ExpectIdentifierToken(lexer, "a"); - ExpectIdentifierToken(lexer, "b"); - ExpectFloatingPointToken(lexer, 36.999); - ExpectFloatingPointToken(lexer, 59595.2414); - ExpectIdentifierToken(lexer, "c"); - } - - TEST_CASE("HeaderLexer: Ensure recognizes floating point numbers surrounded by characters", "[parsing][header]") - { - const std::vector<std::string> lines - { - "(1337.420)" - }; - - MockParserLineStream mockStream(lines); - HeaderLexer lexer(&mockStream); - - ExpectCharacterToken(lexer, '('); - ExpectFloatingPointToken(lexer, 1337.420); - ExpectCharacterToken(lexer, ')'); - } - - TEST_CASE("HeaderLexer: Ensure can separate identifiers with symbols", "[parsing][header]") - { - const std::vector<std::string> lines - { - "hello|world hello_+universe" - }; - - MockParserLineStream mockStream(lines); - HeaderLexer lexer(&mockStream); - - ExpectIdentifierToken(lexer, "hello"); - ExpectCharacterToken(lexer, '|'); - ExpectIdentifierToken(lexer, "world"); - ExpectIdentifierToken(lexer, "hello_"); - ExpectCharacterToken(lexer, '+'); - ExpectIdentifierToken(lexer, "universe"); - } - - TEST_CASE("HeaderLexer: Can recognize shift left", "[parsing][header]") - { - const std::vector<std::string> lines - { - "<<hello<<world<<" - }; - - MockParserLineStream mockStream(lines); - HeaderLexer lexer(&mockStream); - - ExpectTokenWithType(lexer, HeaderParserValueType::SHIFT_LEFT); - ExpectIdentifierToken(lexer, "hello"); - ExpectTokenWithType(lexer, HeaderParserValueType::SHIFT_LEFT); - ExpectIdentifierToken(lexer, "world"); - ExpectTokenWithType(lexer, HeaderParserValueType::SHIFT_LEFT); - } - - TEST_CASE("HeaderLexer: Can recognize less equals", "[parsing][header]") - { - const std::vector<std::string> lines - { - "<=hello<=world<=" - }; - - MockParserLineStream mockStream(lines); - HeaderLexer lexer(&mockStream); - - ExpectTokenWithType(lexer, HeaderParserValueType::LESS_EQUAL); - ExpectIdentifierToken(lexer, "hello"); - ExpectTokenWithType(lexer, HeaderParserValueType::LESS_EQUAL); - ExpectIdentifierToken(lexer, "world"); - ExpectTokenWithType(lexer, HeaderParserValueType::LESS_EQUAL); - } - - TEST_CASE("HeaderLexer: Can recognize less", "[parsing][header]") - { - const std::vector<std::string> lines - { - "<%hello<world<&" - }; - - MockParserLineStream mockStream(lines); - HeaderLexer lexer(&mockStream); - - ExpectCharacterToken(lexer, '<'); - ExpectCharacterToken(lexer, '%'); - ExpectIdentifierToken(lexer, "hello"); - ExpectCharacterToken(lexer, '<'); - ExpectIdentifierToken(lexer, "world"); - ExpectCharacterToken(lexer, '<'); - ExpectCharacterToken(lexer, '&'); - } - - TEST_CASE("HeaderLexer: Can recognize shift right", "[parsing][header]") - { - const std::vector<std::string> lines - { - ">>hello>>world>>" - }; - - MockParserLineStream mockStream(lines); - HeaderLexer lexer(&mockStream); - - ExpectTokenWithType(lexer, HeaderParserValueType::SHIFT_RIGHT); - ExpectIdentifierToken(lexer, "hello"); - ExpectTokenWithType(lexer, HeaderParserValueType::SHIFT_RIGHT); - ExpectIdentifierToken(lexer, "world"); - ExpectTokenWithType(lexer, HeaderParserValueType::SHIFT_RIGHT); - } - - TEST_CASE("HeaderLexer: Can recognize greater equals", "[parsing][header]") - { - const std::vector<std::string> lines - { - ">=hello>=world>=" - }; - - MockParserLineStream mockStream(lines); - HeaderLexer lexer(&mockStream); - - ExpectTokenWithType(lexer, HeaderParserValueType::GREATER_EQUAL); - ExpectIdentifierToken(lexer, "hello"); - ExpectTokenWithType(lexer, HeaderParserValueType::GREATER_EQUAL); - ExpectIdentifierToken(lexer, "world"); - ExpectTokenWithType(lexer, HeaderParserValueType::GREATER_EQUAL); - } - - TEST_CASE("HeaderLexer: Can recognize greater", "[parsing][header]") - { - const std::vector<std::string> lines - { - ">%hello>world>&" - }; - - MockParserLineStream mockStream(lines); - HeaderLexer lexer(&mockStream); - - ExpectCharacterToken(lexer, '>'); - ExpectCharacterToken(lexer, '%'); - ExpectIdentifierToken(lexer, "hello"); - ExpectCharacterToken(lexer, '>'); - ExpectIdentifierToken(lexer, "world"); - ExpectCharacterToken(lexer, '>'); - ExpectCharacterToken(lexer, '&'); - } - - TEST_CASE("HeaderLexer: Can recognize equals", "[parsing][header]") - { - const std::vector<std::string> lines - { - "==hello==world==" - }; - - MockParserLineStream mockStream(lines); - HeaderLexer lexer(&mockStream); - - ExpectTokenWithType(lexer, HeaderParserValueType::EQUALS); - ExpectIdentifierToken(lexer, "hello"); - ExpectTokenWithType(lexer, HeaderParserValueType::EQUALS); - ExpectIdentifierToken(lexer, "world"); - ExpectTokenWithType(lexer, HeaderParserValueType::EQUALS); - } - - TEST_CASE("HeaderLexer: Can recognize assign", "[parsing][header]") - { - const std::vector<std::string> lines - { - "=%hello=world=&" - }; - - MockParserLineStream mockStream(lines); - HeaderLexer lexer(&mockStream); - - ExpectCharacterToken(lexer, '='); - ExpectCharacterToken(lexer, '%'); - ExpectIdentifierToken(lexer, "hello"); - ExpectCharacterToken(lexer, '='); - ExpectIdentifierToken(lexer, "world"); - ExpectCharacterToken(lexer, '='); - ExpectCharacterToken(lexer, '&'); - } - - TEST_CASE("HeaderLexer: Can recognize logical and", "[parsing][header]") - { - const std::vector<std::string> lines - { - "&&hello&&world&&" - }; - - MockParserLineStream mockStream(lines); - HeaderLexer lexer(&mockStream); - - ExpectTokenWithType(lexer, HeaderParserValueType::LOGICAL_AND); - ExpectIdentifierToken(lexer, "hello"); - ExpectTokenWithType(lexer, HeaderParserValueType::LOGICAL_AND); - ExpectIdentifierToken(lexer, "world"); - ExpectTokenWithType(lexer, HeaderParserValueType::LOGICAL_AND); - } - - TEST_CASE("HeaderLexer: Can recognize ampersand", "[parsing][header]") - { - const std::vector<std::string> lines - { - "&%hello&world&+" - }; - - MockParserLineStream mockStream(lines); - HeaderLexer lexer(&mockStream); - - ExpectCharacterToken(lexer, '&'); - ExpectCharacterToken(lexer, '%'); - ExpectIdentifierToken(lexer, "hello"); - ExpectCharacterToken(lexer, '&'); - ExpectIdentifierToken(lexer, "world"); - ExpectCharacterToken(lexer, '&'); - ExpectCharacterToken(lexer, '+'); - } - - TEST_CASE("HeaderLexer: Can recognize logical or", "[parsing][header]") - { - const std::vector<std::string> lines - { - "||hello||world||" - }; - - MockParserLineStream mockStream(lines); - HeaderLexer lexer(&mockStream); - - ExpectTokenWithType(lexer, HeaderParserValueType::LOGICAL_OR); - ExpectIdentifierToken(lexer, "hello"); - ExpectTokenWithType(lexer, HeaderParserValueType::LOGICAL_OR); - ExpectIdentifierToken(lexer, "world"); - ExpectTokenWithType(lexer, HeaderParserValueType::LOGICAL_OR); - } - - TEST_CASE("HeaderLexer: Can recognize pipe", "[parsing][header]") - { - const std::vector<std::string> lines - { - "|%hello|world|&" - }; - - MockParserLineStream mockStream(lines); - HeaderLexer lexer(&mockStream); - - ExpectCharacterToken(lexer, '|'); - ExpectCharacterToken(lexer, '%'); - ExpectIdentifierToken(lexer, "hello"); - ExpectCharacterToken(lexer, '|'); - ExpectIdentifierToken(lexer, "world"); - ExpectCharacterToken(lexer, '|'); - ExpectCharacterToken(lexer, '&'); - } - - TEST_CASE("HeaderLexer: Can recognize not equals", "[parsing][header]") - { - const std::vector<std::string> lines - { - "!=hello!=world!=" - }; - - MockParserLineStream mockStream(lines); - HeaderLexer lexer(&mockStream); - - ExpectTokenWithType(lexer, HeaderParserValueType::NOT_EQUAL); - ExpectIdentifierToken(lexer, "hello"); - ExpectTokenWithType(lexer, HeaderParserValueType::NOT_EQUAL); - ExpectIdentifierToken(lexer, "world"); - ExpectTokenWithType(lexer, HeaderParserValueType::NOT_EQUAL); - } - - TEST_CASE("HeaderLexer: Can recognize exclamation mark", "[parsing][header]") - { - const std::vector<std::string> lines - { - "!%hello!world!&" - }; - - MockParserLineStream mockStream(lines); - HeaderLexer lexer(&mockStream); - - ExpectCharacterToken(lexer, '!'); - ExpectCharacterToken(lexer, '%'); - ExpectIdentifierToken(lexer, "hello"); - ExpectCharacterToken(lexer, '!'); - ExpectIdentifierToken(lexer, "world"); - ExpectCharacterToken(lexer, '!'); - ExpectCharacterToken(lexer, '&'); - } - - TEST_CASE("HeaderLexer: Can recognize strings", "[parsing][header]") - { - const std::vector<std::string> lines - { - "\"hello world\"", - "a\"hi there\"bbb", - " \"nice\"", - "\"meme\" " - }; - - MockParserLineStream mockStream(lines); - HeaderLexer lexer(&mockStream); - - ExpectStringToken(lexer, "hello world"); - ExpectIdentifierToken(lexer, "a"); - ExpectStringToken(lexer, "hi there"); - ExpectIdentifierToken(lexer, "bbb"); - ExpectStringToken(lexer, "nice"); - ExpectStringToken(lexer, "meme"); - } +namespace test::parsing::header::impl::header_lexer { +void ExpectCharacterToken(HeaderLexer &lexer, char c) { + REQUIRE(lexer.GetToken(0).m_type == HeaderParserValueType::CHARACTER); + REQUIRE(lexer.GetToken(0).CharacterValue() == c); + lexer.PopTokens(1); +} + +void ExpectIntegerToken(HeaderLexer &lexer, int number) { + REQUIRE(lexer.GetToken(0).m_type == HeaderParserValueType::INTEGER); + REQUIRE(lexer.GetToken(0).IntegerValue() == number); + lexer.PopTokens(1); +} + +void ExpectFloatingPointToken(HeaderLexer &lexer, double number) { + REQUIRE(lexer.GetToken(0).m_type == HeaderParserValueType::FLOATING_POINT); + const auto a = lexer.GetToken(0).FloatingPointValue(); + REQUIRE_THAT(lexer.GetToken(0).FloatingPointValue(), WithinRel(number)); + lexer.PopTokens(1); +} + +void ExpectIdentifierToken(HeaderLexer &lexer, const std::string &identifier) { + REQUIRE(lexer.GetToken(0).m_type == HeaderParserValueType::IDENTIFIER); + REQUIRE(lexer.GetToken(0).IdentifierValue() == identifier); + lexer.PopTokens(1); +} + +void ExpectStringToken(HeaderLexer &lexer, const std::string &c) { + REQUIRE(lexer.GetToken(0).m_type == HeaderParserValueType::STRING); + REQUIRE(lexer.GetToken(0).StringValue() == c); + lexer.PopTokens(1); +} + +void ExpectTokenWithType(HeaderLexer &lexer, HeaderParserValueType type) { + REQUIRE(lexer.GetToken(0).m_type == type); + lexer.PopTokens(1); +} + +TEST_CASE("HeaderLexer: Ensure can parse simple hex numbers", "[parsing][header]") { + const std::vector<std::string> lines{"0x1A4", " 0xABC ", " 0xAAA", "0xBBB "}; + + MockParserLineStream mockStream(lines); + HeaderLexer lexer(&mockStream); + + ExpectIntegerToken(lexer, 0x1a4); + ExpectIntegerToken(lexer, 0xabc); + ExpectIntegerToken(lexer, 0xaaa); + ExpectIntegerToken(lexer, 0xbbb); + + REQUIRE(lexer.GetToken(0).m_type == HeaderParserValueType::END_OF_FILE); +} + +TEST_CASE("HeaderLexer: Ensure can parse simple hex numbers surrounded by identifiers", "[parsing][header]") { + const std::vector<std::string> lines{"abc 0xABC cba", "aaa 0xAAA", "0xBBB bbb"}; + + MockParserLineStream mockStream(lines); + HeaderLexer lexer(&mockStream); + + ExpectIdentifierToken(lexer, "abc"); + ExpectIntegerToken(lexer, 0xabc); + ExpectIdentifierToken(lexer, "cba"); + + ExpectIdentifierToken(lexer, "aaa"); + ExpectIntegerToken(lexer, 0xaaa); + + ExpectIntegerToken(lexer, 0xbbb); + ExpectIdentifierToken(lexer, "bbb"); + + REQUIRE(lexer.GetToken(0).m_type == HeaderParserValueType::END_OF_FILE); +} + +TEST_CASE("HeaderLexer: Ensure can parse simple hex numbers surrounded by symbols", "[parsing][header]") { + const std::vector<std::string> lines{ + "0x25:0xABC,0x1a4", + }; + + MockParserLineStream mockStream(lines); + HeaderLexer lexer(&mockStream); + + ExpectIntegerToken(lexer, 0x25); + ExpectCharacterToken(lexer, ':'); + ExpectIntegerToken(lexer, 0xABC); + ExpectCharacterToken(lexer, ','); + ExpectIntegerToken(lexer, 0x1a4); + + REQUIRE(lexer.GetToken(0).m_type == HeaderParserValueType::END_OF_FILE); +} + +TEST_CASE("HeaderLexer: Ensure throws exception when parsing incomplete hex number", "[parsing][header]") { + const std::vector<std::string> lines{"0x"}; + + MockParserLineStream mockStream(lines); + HeaderLexer lexer(&mockStream); + + REQUIRE_THROWS_AS(lexer.GetToken(0), ParsingException); +} + +TEST_CASE("HeaderLexer: Ensure throws exception when parsing invalid hex number", "[parsing][header]") { + const std::vector<std::string> lines{"0xGEGE"}; + + MockParserLineStream mockStream(lines); + HeaderLexer lexer(&mockStream); + + REQUIRE_THROWS_AS(lexer.GetToken(0), ParsingException); +} + +TEST_CASE("HeaderLexer: Ensure throws exception when parsing invalid hex number that starts with a valid letter", "[parsing][header]") { + const std::vector<std::string> lines{"0xEGEG"}; + + MockParserLineStream mockStream(lines); + HeaderLexer lexer(&mockStream); + + REQUIRE_THROWS_AS(lexer.GetToken(0), ParsingException); +} + +TEST_CASE("HeaderLexer: Ensure can parse simple integers", "[parsing][header]") { + const std::vector<std::string> lines{" 524 ", "4221111 1337 ", "0 420"}; + + MockParserLineStream mockStream(lines); + HeaderLexer lexer(&mockStream); + + ExpectIntegerToken(lexer, 524); + ExpectIntegerToken(lexer, 4221111); + ExpectIntegerToken(lexer, 1337); + ExpectIntegerToken(lexer, 0); + ExpectIntegerToken(lexer, 420); +} + +TEST_CASE("HeaderLexer: Ensure can parse integers surrounded by identifiers", "[parsing][header]") { + const std::vector<std::string> lines{"aa 6 bb", "123456789 ccc", "0 d 420"}; + + MockParserLineStream mockStream(lines); + HeaderLexer lexer(&mockStream); + + ExpectIdentifierToken(lexer, "aa"); + ExpectIntegerToken(lexer, 6); + ExpectIdentifierToken(lexer, "bb"); + ExpectIntegerToken(lexer, 123456789); + ExpectIdentifierToken(lexer, "ccc"); + ExpectIntegerToken(lexer, 0); + ExpectIdentifierToken(lexer, "d"); + ExpectIntegerToken(lexer, 420); +} + +TEST_CASE("HeaderLexer: Ensure parses negative numbers as character and number", "[parsing][header]") { + const std::vector<std::string> lines{"-1337"}; + + MockParserLineStream mockStream(lines); + HeaderLexer lexer(&mockStream); + + ExpectCharacterToken(lexer, '-'); + ExpectIntegerToken(lexer, 1337); +} + +TEST_CASE("HeaderLexer: Ensure recognizes numbers surrounded by characters", "[parsing][header]") { + const std::vector<std::string> lines{"(1337)"}; + + MockParserLineStream mockStream(lines); + HeaderLexer lexer(&mockStream); + + ExpectCharacterToken(lexer, '('); + ExpectIntegerToken(lexer, 1337); + ExpectCharacterToken(lexer, ')'); +} + +TEST_CASE("HeaderLexer: Ensure parses simple floating point numbers", "[parsing][header]") { + const std::vector<std::string> lines{"420.1337"}; + + MockParserLineStream mockStream(lines); + HeaderLexer lexer(&mockStream); + + ExpectFloatingPointToken(lexer, 420.1337); +} + +TEST_CASE("HeaderLexer: Ensure parses simple floating point numbers surrounded by identifiers", "[parsing][header]") { + const std::vector<std::string> lines{"aa 50.24 a", "b 36.999", "59595.2414 c"}; + + MockParserLineStream mockStream(lines); + HeaderLexer lexer(&mockStream); + + ExpectIdentifierToken(lexer, "aa"); + ExpectFloatingPointToken(lexer, 50.24); + ExpectIdentifierToken(lexer, "a"); + ExpectIdentifierToken(lexer, "b"); + ExpectFloatingPointToken(lexer, 36.999); + ExpectFloatingPointToken(lexer, 59595.2414); + ExpectIdentifierToken(lexer, "c"); +} + +TEST_CASE("HeaderLexer: Ensure recognizes floating point numbers surrounded by characters", "[parsing][header]") { + const std::vector<std::string> lines{"(1337.420)"}; + + MockParserLineStream mockStream(lines); + HeaderLexer lexer(&mockStream); + + ExpectCharacterToken(lexer, '('); + ExpectFloatingPointToken(lexer, 1337.420); + ExpectCharacterToken(lexer, ')'); +} + +TEST_CASE("HeaderLexer: Ensure can separate identifiers with symbols", "[parsing][header]") { + const std::vector<std::string> lines{"hello|world hello_+universe"}; + + MockParserLineStream mockStream(lines); + HeaderLexer lexer(&mockStream); + + ExpectIdentifierToken(lexer, "hello"); + ExpectCharacterToken(lexer, '|'); + ExpectIdentifierToken(lexer, "world"); + ExpectIdentifierToken(lexer, "hello_"); + ExpectCharacterToken(lexer, '+'); + ExpectIdentifierToken(lexer, "universe"); +} + +TEST_CASE("HeaderLexer: Can recognize shift left", "[parsing][header]") { + const std::vector<std::string> lines{"<<hello<<world<<"}; + + MockParserLineStream mockStream(lines); + HeaderLexer lexer(&mockStream); + + ExpectTokenWithType(lexer, HeaderParserValueType::SHIFT_LEFT); + ExpectIdentifierToken(lexer, "hello"); + ExpectTokenWithType(lexer, HeaderParserValueType::SHIFT_LEFT); + ExpectIdentifierToken(lexer, "world"); + ExpectTokenWithType(lexer, HeaderParserValueType::SHIFT_LEFT); +} + +TEST_CASE("HeaderLexer: Can recognize less equals", "[parsing][header]") { + const std::vector<std::string> lines{"<=hello<=world<="}; + + MockParserLineStream mockStream(lines); + HeaderLexer lexer(&mockStream); + + ExpectTokenWithType(lexer, HeaderParserValueType::LESS_EQUAL); + ExpectIdentifierToken(lexer, "hello"); + ExpectTokenWithType(lexer, HeaderParserValueType::LESS_EQUAL); + ExpectIdentifierToken(lexer, "world"); + ExpectTokenWithType(lexer, HeaderParserValueType::LESS_EQUAL); +} + +TEST_CASE("HeaderLexer: Can recognize less", "[parsing][header]") { + const std::vector<std::string> lines{"<%hello<world<&"}; + + MockParserLineStream mockStream(lines); + HeaderLexer lexer(&mockStream); + + ExpectCharacterToken(lexer, '<'); + ExpectCharacterToken(lexer, '%'); + ExpectIdentifierToken(lexer, "hello"); + ExpectCharacterToken(lexer, '<'); + ExpectIdentifierToken(lexer, "world"); + ExpectCharacterToken(lexer, '<'); + ExpectCharacterToken(lexer, '&'); +} + +TEST_CASE("HeaderLexer: Can recognize shift right", "[parsing][header]") { + const std::vector<std::string> lines{">>hello>>world>>"}; + + MockParserLineStream mockStream(lines); + HeaderLexer lexer(&mockStream); + + ExpectTokenWithType(lexer, HeaderParserValueType::SHIFT_RIGHT); + ExpectIdentifierToken(lexer, "hello"); + ExpectTokenWithType(lexer, HeaderParserValueType::SHIFT_RIGHT); + ExpectIdentifierToken(lexer, "world"); + ExpectTokenWithType(lexer, HeaderParserValueType::SHIFT_RIGHT); +} + +TEST_CASE("HeaderLexer: Can recognize greater equals", "[parsing][header]") { + const std::vector<std::string> lines{">=hello>=world>="}; + + MockParserLineStream mockStream(lines); + HeaderLexer lexer(&mockStream); + + ExpectTokenWithType(lexer, HeaderParserValueType::GREATER_EQUAL); + ExpectIdentifierToken(lexer, "hello"); + ExpectTokenWithType(lexer, HeaderParserValueType::GREATER_EQUAL); + ExpectIdentifierToken(lexer, "world"); + ExpectTokenWithType(lexer, HeaderParserValueType::GREATER_EQUAL); +} + +TEST_CASE("HeaderLexer: Can recognize greater", "[parsing][header]") { + const std::vector<std::string> lines{">%hello>world>&"}; + + MockParserLineStream mockStream(lines); + HeaderLexer lexer(&mockStream); + + ExpectCharacterToken(lexer, '>'); + ExpectCharacterToken(lexer, '%'); + ExpectIdentifierToken(lexer, "hello"); + ExpectCharacterToken(lexer, '>'); + ExpectIdentifierToken(lexer, "world"); + ExpectCharacterToken(lexer, '>'); + ExpectCharacterToken(lexer, '&'); +} + +TEST_CASE("HeaderLexer: Can recognize equals", "[parsing][header]") { + const std::vector<std::string> lines{"==hello==world=="}; + + MockParserLineStream mockStream(lines); + HeaderLexer lexer(&mockStream); + + ExpectTokenWithType(lexer, HeaderParserValueType::EQUALS); + ExpectIdentifierToken(lexer, "hello"); + ExpectTokenWithType(lexer, HeaderParserValueType::EQUALS); + ExpectIdentifierToken(lexer, "world"); + ExpectTokenWithType(lexer, HeaderParserValueType::EQUALS); +} + +TEST_CASE("HeaderLexer: Can recognize assign", "[parsing][header]") { + const std::vector<std::string> lines{"=%hello=world=&"}; + + MockParserLineStream mockStream(lines); + HeaderLexer lexer(&mockStream); + + ExpectCharacterToken(lexer, '='); + ExpectCharacterToken(lexer, '%'); + ExpectIdentifierToken(lexer, "hello"); + ExpectCharacterToken(lexer, '='); + ExpectIdentifierToken(lexer, "world"); + ExpectCharacterToken(lexer, '='); + ExpectCharacterToken(lexer, '&'); +} + +TEST_CASE("HeaderLexer: Can recognize logical and", "[parsing][header]") { + const std::vector<std::string> lines{"&&hello&&world&&"}; + + MockParserLineStream mockStream(lines); + HeaderLexer lexer(&mockStream); + + ExpectTokenWithType(lexer, HeaderParserValueType::LOGICAL_AND); + ExpectIdentifierToken(lexer, "hello"); + ExpectTokenWithType(lexer, HeaderParserValueType::LOGICAL_AND); + ExpectIdentifierToken(lexer, "world"); + ExpectTokenWithType(lexer, HeaderParserValueType::LOGICAL_AND); +} + +TEST_CASE("HeaderLexer: Can recognize ampersand", "[parsing][header]") { + const std::vector<std::string> lines{"&%hello&world&+"}; + + MockParserLineStream mockStream(lines); + HeaderLexer lexer(&mockStream); + + ExpectCharacterToken(lexer, '&'); + ExpectCharacterToken(lexer, '%'); + ExpectIdentifierToken(lexer, "hello"); + ExpectCharacterToken(lexer, '&'); + ExpectIdentifierToken(lexer, "world"); + ExpectCharacterToken(lexer, '&'); + ExpectCharacterToken(lexer, '+'); +} + +TEST_CASE("HeaderLexer: Can recognize logical or", "[parsing][header]") { + const std::vector<std::string> lines{"||hello||world||"}; + + MockParserLineStream mockStream(lines); + HeaderLexer lexer(&mockStream); + + ExpectTokenWithType(lexer, HeaderParserValueType::LOGICAL_OR); + ExpectIdentifierToken(lexer, "hello"); + ExpectTokenWithType(lexer, HeaderParserValueType::LOGICAL_OR); + ExpectIdentifierToken(lexer, "world"); + ExpectTokenWithType(lexer, HeaderParserValueType::LOGICAL_OR); +} + +TEST_CASE("HeaderLexer: Can recognize pipe", "[parsing][header]") { + const std::vector<std::string> lines{"|%hello|world|&"}; + + MockParserLineStream mockStream(lines); + HeaderLexer lexer(&mockStream); + + ExpectCharacterToken(lexer, '|'); + ExpectCharacterToken(lexer, '%'); + ExpectIdentifierToken(lexer, "hello"); + ExpectCharacterToken(lexer, '|'); + ExpectIdentifierToken(lexer, "world"); + ExpectCharacterToken(lexer, '|'); + ExpectCharacterToken(lexer, '&'); +} + +TEST_CASE("HeaderLexer: Can recognize not equals", "[parsing][header]") { + const std::vector<std::string> lines{"!=hello!=world!="}; + + MockParserLineStream mockStream(lines); + HeaderLexer lexer(&mockStream); + + ExpectTokenWithType(lexer, HeaderParserValueType::NOT_EQUAL); + ExpectIdentifierToken(lexer, "hello"); + ExpectTokenWithType(lexer, HeaderParserValueType::NOT_EQUAL); + ExpectIdentifierToken(lexer, "world"); + ExpectTokenWithType(lexer, HeaderParserValueType::NOT_EQUAL); +} + +TEST_CASE("HeaderLexer: Can recognize exclamation mark", "[parsing][header]") { + const std::vector<std::string> lines{"!%hello!world!&"}; + + MockParserLineStream mockStream(lines); + HeaderLexer lexer(&mockStream); + + ExpectCharacterToken(lexer, '!'); + ExpectCharacterToken(lexer, '%'); + ExpectIdentifierToken(lexer, "hello"); + ExpectCharacterToken(lexer, '!'); + ExpectIdentifierToken(lexer, "world"); + ExpectCharacterToken(lexer, '!'); + ExpectCharacterToken(lexer, '&'); +} + +TEST_CASE("HeaderLexer: Can recognize strings", "[parsing][header]") { + const std::vector<std::string> lines{"\"hello world\"", "a\"hi there\"bbb", " \"nice\"", "\"meme\" "}; + + MockParserLineStream mockStream(lines); + HeaderLexer lexer(&mockStream); + + ExpectStringToken(lexer, "hello world"); + ExpectIdentifierToken(lexer, "a"); + ExpectStringToken(lexer, "hi there"); + ExpectIdentifierToken(lexer, "bbb"); + ExpectStringToken(lexer, "nice"); + ExpectStringToken(lexer, "meme"); } +} // namespace test::parsing::header::impl::header_lexer diff --git a/test/ZoneCodeGeneratorLibTests/Parsing/Header/Sequence/SequenceNamespaceTests.cpp b/test/ZoneCodeGeneratorLibTests/Parsing/Header/Sequence/SequenceNamespaceTests.cpp index 3497dbd44..f53f1b83a 100644 --- a/test/ZoneCodeGeneratorLibTests/Parsing/Header/Sequence/SequenceNamespaceTests.cpp +++ b/test/ZoneCodeGeneratorLibTests/Parsing/Header/Sequence/SequenceNamespaceTests.cpp @@ -5,25 +5,21 @@ #include "Parsing/Mock/MockLexer.h" #include "Parsing/Mock/MockPackValueSupplier.h" -namespace test::parsing::header::sequence::sequence_namespace -{ - TEST_CASE("SequenceNamespace: Ensure can parse simple namespace directive", "[parsing][parsingstream]") - { - const TokenPos pos; - const auto lexer = std::make_unique<MockLexer<HeaderParserValue>>(MockLexer<HeaderParserValue>( - { - HeaderParserValue::Keyword(pos, HeaderParserValueType::NAMESPACE), - HeaderParserValue::Identifier(pos, new std::string("test_namespace")), - HeaderParserValue::Character(pos, '{') - }, HeaderParserValue::EndOfFile(pos))); +namespace test::parsing::header::sequence::sequence_namespace { +TEST_CASE("SequenceNamespace: Ensure can parse simple namespace directive", "[parsing][parsingstream]") { + const TokenPos pos; + const auto lexer = std::make_unique<MockLexer<HeaderParserValue>>( + MockLexer<HeaderParserValue>({HeaderParserValue::Keyword(pos, HeaderParserValueType::NAMESPACE), + HeaderParserValue::Identifier(pos, new std::string("test_namespace")), HeaderParserValue::Character(pos, '{')}, + HeaderParserValue::EndOfFile(pos))); - const auto packValueSupplier = std::make_unique<MockPackValueSupplier>(); - const auto sequence = std::make_unique<SequenceNamespace>(); - const auto state = std::make_unique<HeaderParserState>(packValueSupplier.get()); + const auto packValueSupplier = std::make_unique<MockPackValueSupplier>(); + const auto sequence = std::make_unique<SequenceNamespace>(); + const auto state = std::make_unique<HeaderParserState>(packValueSupplier.get()); - unsigned consumedTokenCount; - auto result = sequence->MatchSequence(lexer.get(), state.get(), consumedTokenCount); + unsigned consumedTokenCount; + auto result = sequence->MatchSequence(lexer.get(), state.get(), consumedTokenCount); - REQUIRE(result); - } + REQUIRE(result); } +} // namespace test::parsing::header::sequence::sequence_namespace diff --git a/test/ZoneCodeGeneratorLibTests/Parsing/Matcher/MatcherTests.cpp b/test/ZoneCodeGeneratorLibTests/Parsing/Matcher/MatcherTests.cpp index d04e23f56..2ae683b99 100644 --- a/test/ZoneCodeGeneratorLibTests/Parsing/Matcher/MatcherTests.cpp +++ b/test/ZoneCodeGeneratorLibTests/Parsing/Matcher/MatcherTests.cpp @@ -4,1025 +4,723 @@ #include <algorithm> #include <sstream> -#include "Utils/ClassUtils.h" #include "Parsing/Header/Impl/HeaderParserValue.h" #include "Parsing/Header/Matcher/HeaderMatcherFactory.h" #include "Parsing/Impl/DefinesStreamProxy.h" #include "Parsing/Mock/MockLexer.h" #include "Parsing/Mock/MockSequence.h" +#include "Utils/ClassUtils.h" -namespace test::parsing::matcher -{ - // This class uses the header implementation of IParserValues - // This should not make a difference in behaviour and only affects test data +namespace test::parsing::matcher { +// This class uses the header implementation of IParserValues +// This should not make a difference in behaviour and only affects test data - typedef MockLexer<HeaderParserValue> lexer_t; - typedef MockSequence<HeaderParserValue> sequence_t; - typedef sequence_t::parent_t::matcher_t matcher_t; - typedef SequenceResult<HeaderParserValue> sequence_result_t; - typedef HeaderMatcherFactory factory_t; +typedef MockLexer<HeaderParserValue> lexer_t; +typedef MockSequence<HeaderParserValue> sequence_t; +typedef sequence_t::parent_t::matcher_t matcher_t; +typedef SequenceResult<HeaderParserValue> sequence_result_t; +typedef HeaderMatcherFactory factory_t; - class MatchersTestsHelper - { - std::unique_ptr<MockSequenceState> m_mock_state; - std::unique_ptr<lexer_t> m_lexer; - std::unique_ptr<sequence_t> m_sequence; - - unsigned m_consumed_token_count; - - public: - MatchersTestsHelper() - : m_mock_state(std::make_unique<MockSequenceState>()), - m_sequence(std::make_unique<sequence_t>()), - m_consumed_token_count(0) - { - } - - void Tokens(std::initializer_list<Movable<HeaderParserValue>> tokens) - { - m_lexer = std::make_unique<lexer_t>(tokens, HeaderParserValue::EndOfFile(TokenPos())); - } - - void Matchers(const std::initializer_list<Movable<std::unique_ptr<matcher_t>>> matchers) const - { - m_sequence->AddMockMatchers(matchers); - } - - void LabeledMatchers(const std::initializer_list<Movable<std::unique_ptr<matcher_t>>> matchers, const int label) const - { - m_sequence->AddMockLabeledMatchers(matchers, label); - } - - _NODISCARD factory_t Factory() const - { - return HeaderMatcherFactory(m_sequence->GetLabelSupplier()); - } - - void MatchCallback(std::function<void(sequence_result_t& result)> cb) const - { - m_sequence->Handle(std::move(cb)); - } - - bool PerformTest() - { - // Tokens must be set first - REQUIRE(m_lexer.get() != nullptr); - return m_sequence->MatchSequence(m_lexer.get(), m_mock_state.get(), m_consumed_token_count); - } - - _NODISCARD unsigned GetConsumedTokenCount() const - { - return m_consumed_token_count; - } - }; - - TEST_CASE("Matcher: Ensure can match simple AND token sequence", "[parsing][matcher]") - { - MatchersTestsHelper test; - const TokenPos pos; - test.Tokens({ - HeaderParserValue::Keyword(pos, HeaderParserValueType::NAMESPACE), - HeaderParserValue::Identifier(pos, new std::string("test_namespace")), - HeaderParserValue::Character(pos, '{'), - HeaderParserValue::Invalid(pos) - }); - const auto create = test.Factory(); - test.Matchers({ - create.Type(HeaderParserValueType::NAMESPACE), - create.Identifier(), - create.Char('{') - }); - - REQUIRE(test.PerformTest()); - REQUIRE(test.GetConsumedTokenCount() == 3); - } +class MatchersTestsHelper { + std::unique_ptr<MockSequenceState> m_mock_state; + std::unique_ptr<lexer_t> m_lexer; + std::unique_ptr<sequence_t> m_sequence; - TEST_CASE("Matcher: Ensure AND matcher can fail", "[parsing][matcher]") - { - MatchersTestsHelper test; - const TokenPos pos; - test.Tokens({ - HeaderParserValue::Keyword(pos, HeaderParserValueType::NAMESPACE), - HeaderParserValue::Identifier(pos, new std::string("test_namespace")), - HeaderParserValue::Character(pos, '{'), - HeaderParserValue::Invalid(pos) - }); - const auto create = test.Factory(); - test.Matchers({ - create.Type(HeaderParserValueType::NAMESPACE), - create.Identifier(), - create.Char('+') - }); - - REQUIRE(!test.PerformTest()); - } + unsigned m_consumed_token_count; - TEST_CASE("Matcher: Ensure match callback is called", "[parsing][matcher]") - { - MatchersTestsHelper test; - const TokenPos pos; - auto callbackCalled = false; - test.Tokens({ - HeaderParserValue::Keyword(pos, HeaderParserValueType::NAMESPACE), - HeaderParserValue::Identifier(pos, new std::string("test_namespace")), - HeaderParserValue::Character(pos, '{'), - HeaderParserValue::Invalid(pos) - }); - const auto create = test.Factory(); - test.Matchers({ - create.Type(HeaderParserValueType::NAMESPACE) - }); - test.MatchCallback([&callbackCalled](sequence_result_t& result) - { - callbackCalled = true; - }); - - REQUIRE(test.PerformTest()); - REQUIRE(callbackCalled); - } +public: + MatchersTestsHelper() : m_mock_state(std::make_unique<MockSequenceState>()), m_sequence(std::make_unique<sequence_t>()), m_consumed_token_count(0) {} - TEST_CASE("Matcher: Ensure match callback is not called on fail", "[parsing][matcher]") - { - MatchersTestsHelper test; - const TokenPos pos; - auto callbackCalled = false; - test.Tokens({ - HeaderParserValue::Keyword(pos, HeaderParserValueType::STRUCT), - HeaderParserValue::Invalid(pos) - }); - const auto create = test.Factory(); - test.Matchers({ - create.Type(HeaderParserValueType::NAMESPACE) - }); - test.MatchCallback([&callbackCalled](sequence_result_t& result) - { - callbackCalled = true; - }); - - REQUIRE(!test.PerformTest()); - REQUIRE(!callbackCalled); - } + void Tokens(std::initializer_list<Movable<HeaderParserValue>> tokens) { + m_lexer = std::make_unique<lexer_t>(tokens, HeaderParserValue::EndOfFile(TokenPos())); + } - TEST_CASE("Matcher: Ensure can match simple OR token sequence", "[parsing][matcher]") - { - static constexpr auto TAG_NAMESPACE = 1; - static constexpr auto TAG_STRUCT = 2; - - MatchersTestsHelper test; - const TokenPos pos; - const auto create = test.Factory(); - test.Matchers({ - create.Or({ - create.Type(HeaderParserValueType::NAMESPACE).Tag(TAG_NAMESPACE), - create.Type(HeaderParserValueType::STRUCT).Tag(TAG_STRUCT), - }) - }); - - test.Tokens({ - HeaderParserValue::Keyword(pos, HeaderParserValueType::NAMESPACE), - HeaderParserValue::Identifier(pos, new std::string("test_namespace")), - HeaderParserValue::Character(pos, '{'), - HeaderParserValue::Invalid(pos) - }); - test.MatchCallback([](sequence_result_t& result) - { - REQUIRE(result.NextTag() == TAG_NAMESPACE); - }); - - REQUIRE(test.PerformTest()); - REQUIRE(test.GetConsumedTokenCount() == 1); - - test.Tokens({ - HeaderParserValue::Keyword(pos, HeaderParserValueType::STRUCT), - HeaderParserValue::Identifier(pos, new std::string("test_struct")), - HeaderParserValue::Character(pos, '{'), - HeaderParserValue::Invalid(pos) - }); - test.MatchCallback([](sequence_result_t& result) - { - REQUIRE(result.NextTag() == TAG_STRUCT); - }); - - REQUIRE(test.PerformTest()); - REQUIRE(test.GetConsumedTokenCount() == 1); - } + void Matchers(const std::initializer_list<Movable<std::unique_ptr<matcher_t>>> matchers) const { m_sequence->AddMockMatchers(matchers); } - TEST_CASE("Matcher: Ensure OR matcher can fail", "[parsing][matcher]") - { - static constexpr auto TAG_NAMESPACE = 1; - static constexpr auto TAG_STRUCT = 2; - - MatchersTestsHelper test; - const TokenPos pos; - const auto create = test.Factory(); - test.Matchers({ - create.Or({ - create.Type(HeaderParserValueType::NAMESPACE).Tag(TAG_NAMESPACE), - create.Type(HeaderParserValueType::STRUCT).Tag(TAG_STRUCT), - }) - }); - - test.Tokens({ - HeaderParserValue::Keyword(pos, HeaderParserValueType::ENUM), - HeaderParserValue::Identifier(pos, new std::string("test_namespace")), - HeaderParserValue::Character(pos, '{'), - HeaderParserValue::Invalid(pos) - }); - test.MatchCallback([](sequence_result_t& result) - { - FAIL(); - }); - - REQUIRE(!test.PerformTest()); - } + void LabeledMatchers(const std::initializer_list<Movable<std::unique_ptr<matcher_t>>> matchers, const int label) const { + m_sequence->AddMockLabeledMatchers(matchers, label); + } - TEST_CASE("Matcher: Ensure can match simple LOOP token sequence", "[parsing][matcher]") - { - static constexpr auto TAG_NAMESPACE = 1; - static constexpr auto TAG_STRUCT = 2; - - MatchersTestsHelper test; - const TokenPos pos; - const auto create = test.Factory(); - test.Matchers({ - create.Loop(create.Type(HeaderParserValueType::NAMESPACE).Tag(TAG_NAMESPACE)), - create.Type(HeaderParserValueType::STRUCT).Tag(TAG_STRUCT) - }); - - test.Tokens({ - HeaderParserValue::Keyword(pos, HeaderParserValueType::NAMESPACE), - HeaderParserValue::Keyword(pos, HeaderParserValueType::NAMESPACE), - HeaderParserValue::Keyword(pos, HeaderParserValueType::NAMESPACE), - HeaderParserValue::Keyword(pos, HeaderParserValueType::STRUCT), - HeaderParserValue::Invalid(pos) - }); - test.MatchCallback([](sequence_result_t& result) - { - REQUIRE(result.NextTag() == TAG_NAMESPACE); - REQUIRE(result.NextTag() == TAG_NAMESPACE); - REQUIRE(result.NextTag() == TAG_NAMESPACE); - REQUIRE(result.NextTag() == TAG_STRUCT); - }); - - REQUIRE(test.PerformTest()); - REQUIRE(test.GetConsumedTokenCount() == 4); - } + _NODISCARD factory_t Factory() const { return HeaderMatcherFactory(m_sequence->GetLabelSupplier()); } - TEST_CASE("Matcher: Ensure LOOP token sequence must be called at least once to succeed", "[parsing][matcher]") - { - static constexpr auto TAG_NAMESPACE = 1; - static constexpr auto TAG_STRUCT = 2; - - MatchersTestsHelper test; - const TokenPos pos; - const auto create = test.Factory(); - test.Matchers({ - create.Loop(create.Type(HeaderParserValueType::NAMESPACE).Tag(TAG_NAMESPACE)), - create.Type(HeaderParserValueType::STRUCT).Tag(TAG_STRUCT) - }); - - test.Tokens({ - HeaderParserValue::Keyword(pos, HeaderParserValueType::STRUCT), - HeaderParserValue::Invalid(pos) - }); - - REQUIRE(!test.PerformTest()); - } + void MatchCallback(std::function<void(sequence_result_t &result)> cb) const { m_sequence->Handle(std::move(cb)); } - TEST_CASE("Matcher: Ensure OPTIONAL_LOOP token sequence can be called zero times", "[parsing][matcher]") - { - static constexpr auto TAG_NAMESPACE = 1; - static constexpr auto TAG_STRUCT = 2; - - MatchersTestsHelper test; - const TokenPos pos; - const auto create = test.Factory(); - test.Matchers({ - create.OptionalLoop(create.Type(HeaderParserValueType::NAMESPACE).Tag(TAG_NAMESPACE)), - create.Type(HeaderParserValueType::STRUCT).Tag(TAG_STRUCT) - }); - - test.Tokens({ - HeaderParserValue::Keyword(pos, HeaderParserValueType::STRUCT), - HeaderParserValue::Invalid(pos) - }); - - REQUIRE(test.PerformTest()); - REQUIRE(test.GetConsumedTokenCount() == 1); - } + bool PerformTest() { + // Tokens must be set first + REQUIRE(m_lexer.get() != nullptr); + return m_sequence->MatchSequence(m_lexer.get(), m_mock_state.get(), m_consumed_token_count); + } - TEST_CASE("Matcher: Ensure OPTIONAL token sequence can be called zero times", "[parsing][matcher]") - { - static constexpr auto TAG_NAMESPACE = 1; - static constexpr auto TAG_STRUCT = 2; - static constexpr auto TAG_ENUM = 3; - - MatchersTestsHelper test; - const TokenPos pos; - const auto create = test.Factory(); - test.Matchers({ - create.Type(HeaderParserValueType::NAMESPACE).Tag(TAG_NAMESPACE), - create.Optional(create.Type(HeaderParserValueType::STRUCT).Tag(TAG_STRUCT)), - create.Type(HeaderParserValueType::ENUM).Tag(TAG_ENUM) - }); - - test.Tokens({ - HeaderParserValue::Keyword(pos, HeaderParserValueType::NAMESPACE), - HeaderParserValue::Keyword(pos, HeaderParserValueType::ENUM), - HeaderParserValue::Invalid(pos) - }); - - REQUIRE(test.PerformTest()); - REQUIRE(test.GetConsumedTokenCount() == 2); - } + _NODISCARD unsigned GetConsumedTokenCount() const { return m_consumed_token_count; } +}; - TEST_CASE("Matcher: Ensure OPTIONAL token sequence can be called once", "[parsing][matcher]") - { - static constexpr auto TAG_NAMESPACE = 1; - static constexpr auto TAG_STRUCT = 2; - static constexpr auto TAG_ENUM = 3; - - MatchersTestsHelper test; - const TokenPos pos; - const auto create = test.Factory(); - test.Matchers({ - create.Type(HeaderParserValueType::NAMESPACE).Tag(TAG_NAMESPACE), - create.Optional(create.Type(HeaderParserValueType::STRUCT).Tag(TAG_STRUCT)), - create.Type(HeaderParserValueType::ENUM).Tag(TAG_ENUM) - }); - - test.Tokens({ - HeaderParserValue::Keyword(pos, HeaderParserValueType::NAMESPACE), - HeaderParserValue::Keyword(pos, HeaderParserValueType::STRUCT), - HeaderParserValue::Keyword(pos, HeaderParserValueType::ENUM), - HeaderParserValue::Invalid(pos) - }); - - REQUIRE(test.PerformTest()); - REQUIRE(test.GetConsumedTokenCount() == 3); - } +TEST_CASE("Matcher: Ensure can match simple AND token sequence", "[parsing][matcher]") { + MatchersTestsHelper test; + const TokenPos pos; + test.Tokens({HeaderParserValue::Keyword(pos, HeaderParserValueType::NAMESPACE), HeaderParserValue::Identifier(pos, new std::string("test_namespace")), + HeaderParserValue::Character(pos, '{'), HeaderParserValue::Invalid(pos)}); + const auto create = test.Factory(); + test.Matchers({create.Type(HeaderParserValueType::NAMESPACE), create.Identifier(), create.Char('{')}); + + REQUIRE(test.PerformTest()); + REQUIRE(test.GetConsumedTokenCount() == 3); +} + +TEST_CASE("Matcher: Ensure AND matcher can fail", "[parsing][matcher]") { + MatchersTestsHelper test; + const TokenPos pos; + test.Tokens({HeaderParserValue::Keyword(pos, HeaderParserValueType::NAMESPACE), HeaderParserValue::Identifier(pos, new std::string("test_namespace")), + HeaderParserValue::Character(pos, '{'), HeaderParserValue::Invalid(pos)}); + const auto create = test.Factory(); + test.Matchers({create.Type(HeaderParserValueType::NAMESPACE), create.Identifier(), create.Char('+')}); + + REQUIRE(!test.PerformTest()); +} + +TEST_CASE("Matcher: Ensure match callback is called", "[parsing][matcher]") { + MatchersTestsHelper test; + const TokenPos pos; + auto callbackCalled = false; + test.Tokens({HeaderParserValue::Keyword(pos, HeaderParserValueType::NAMESPACE), HeaderParserValue::Identifier(pos, new std::string("test_namespace")), + HeaderParserValue::Character(pos, '{'), HeaderParserValue::Invalid(pos)}); + const auto create = test.Factory(); + test.Matchers({create.Type(HeaderParserValueType::NAMESPACE)}); + test.MatchCallback([&callbackCalled](sequence_result_t &result) { callbackCalled = true; }); + + REQUIRE(test.PerformTest()); + REQUIRE(callbackCalled); +} + +TEST_CASE("Matcher: Ensure match callback is not called on fail", "[parsing][matcher]") { + MatchersTestsHelper test; + const TokenPos pos; + auto callbackCalled = false; + test.Tokens({HeaderParserValue::Keyword(pos, HeaderParserValueType::STRUCT), HeaderParserValue::Invalid(pos)}); + const auto create = test.Factory(); + test.Matchers({create.Type(HeaderParserValueType::NAMESPACE)}); + test.MatchCallback([&callbackCalled](sequence_result_t &result) { callbackCalled = true; }); + + REQUIRE(!test.PerformTest()); + REQUIRE(!callbackCalled); +} + +TEST_CASE("Matcher: Ensure can match simple OR token sequence", "[parsing][matcher]") { + static constexpr auto TAG_NAMESPACE = 1; + static constexpr auto TAG_STRUCT = 2; + + MatchersTestsHelper test; + const TokenPos pos; + const auto create = test.Factory(); + test.Matchers({create.Or({ + create.Type(HeaderParserValueType::NAMESPACE).Tag(TAG_NAMESPACE), + create.Type(HeaderParserValueType::STRUCT).Tag(TAG_STRUCT), + })}); + + test.Tokens({HeaderParserValue::Keyword(pos, HeaderParserValueType::NAMESPACE), HeaderParserValue::Identifier(pos, new std::string("test_namespace")), + HeaderParserValue::Character(pos, '{'), HeaderParserValue::Invalid(pos)}); + test.MatchCallback([](sequence_result_t &result) { REQUIRE(result.NextTag() == TAG_NAMESPACE); }); + + REQUIRE(test.PerformTest()); + REQUIRE(test.GetConsumedTokenCount() == 1); + + test.Tokens({HeaderParserValue::Keyword(pos, HeaderParserValueType::STRUCT), HeaderParserValue::Identifier(pos, new std::string("test_struct")), + HeaderParserValue::Character(pos, '{'), HeaderParserValue::Invalid(pos)}); + test.MatchCallback([](sequence_result_t &result) { REQUIRE(result.NextTag() == TAG_STRUCT); }); + + REQUIRE(test.PerformTest()); + REQUIRE(test.GetConsumedTokenCount() == 1); +} + +TEST_CASE("Matcher: Ensure OR matcher can fail", "[parsing][matcher]") { + static constexpr auto TAG_NAMESPACE = 1; + static constexpr auto TAG_STRUCT = 2; + + MatchersTestsHelper test; + const TokenPos pos; + const auto create = test.Factory(); + test.Matchers({create.Or({ + create.Type(HeaderParserValueType::NAMESPACE).Tag(TAG_NAMESPACE), + create.Type(HeaderParserValueType::STRUCT).Tag(TAG_STRUCT), + })}); + + test.Tokens({HeaderParserValue::Keyword(pos, HeaderParserValueType::ENUM), HeaderParserValue::Identifier(pos, new std::string("test_namespace")), + HeaderParserValue::Character(pos, '{'), HeaderParserValue::Invalid(pos)}); + test.MatchCallback([](sequence_result_t &result) { FAIL(); }); + + REQUIRE(!test.PerformTest()); +} + +TEST_CASE("Matcher: Ensure can match simple LOOP token sequence", "[parsing][matcher]") { + static constexpr auto TAG_NAMESPACE = 1; + static constexpr auto TAG_STRUCT = 2; + + MatchersTestsHelper test; + const TokenPos pos; + const auto create = test.Factory(); + test.Matchers({create.Loop(create.Type(HeaderParserValueType::NAMESPACE).Tag(TAG_NAMESPACE)), create.Type(HeaderParserValueType::STRUCT).Tag(TAG_STRUCT)}); + + test.Tokens({HeaderParserValue::Keyword(pos, HeaderParserValueType::NAMESPACE), HeaderParserValue::Keyword(pos, HeaderParserValueType::NAMESPACE), + HeaderParserValue::Keyword(pos, HeaderParserValueType::NAMESPACE), HeaderParserValue::Keyword(pos, HeaderParserValueType::STRUCT), + HeaderParserValue::Invalid(pos)}); + test.MatchCallback([](sequence_result_t &result) { + REQUIRE(result.NextTag() == TAG_NAMESPACE); + REQUIRE(result.NextTag() == TAG_NAMESPACE); + REQUIRE(result.NextTag() == TAG_NAMESPACE); + REQUIRE(result.NextTag() == TAG_STRUCT); + }); + + REQUIRE(test.PerformTest()); + REQUIRE(test.GetConsumedTokenCount() == 4); +} + +TEST_CASE("Matcher: Ensure LOOP token sequence must be called at least once to succeed", "[parsing][matcher]") { + static constexpr auto TAG_NAMESPACE = 1; + static constexpr auto TAG_STRUCT = 2; + + MatchersTestsHelper test; + const TokenPos pos; + const auto create = test.Factory(); + test.Matchers({create.Loop(create.Type(HeaderParserValueType::NAMESPACE).Tag(TAG_NAMESPACE)), create.Type(HeaderParserValueType::STRUCT).Tag(TAG_STRUCT)}); + + test.Tokens({HeaderParserValue::Keyword(pos, HeaderParserValueType::STRUCT), HeaderParserValue::Invalid(pos)}); + + REQUIRE(!test.PerformTest()); +} + +TEST_CASE("Matcher: Ensure OPTIONAL_LOOP token sequence can be called zero times", "[parsing][matcher]") { + static constexpr auto TAG_NAMESPACE = 1; + static constexpr auto TAG_STRUCT = 2; + + MatchersTestsHelper test; + const TokenPos pos; + const auto create = test.Factory(); + test.Matchers( + {create.OptionalLoop(create.Type(HeaderParserValueType::NAMESPACE).Tag(TAG_NAMESPACE)), create.Type(HeaderParserValueType::STRUCT).Tag(TAG_STRUCT)}); + + test.Tokens({HeaderParserValue::Keyword(pos, HeaderParserValueType::STRUCT), HeaderParserValue::Invalid(pos)}); + + REQUIRE(test.PerformTest()); + REQUIRE(test.GetConsumedTokenCount() == 1); +} + +TEST_CASE("Matcher: Ensure OPTIONAL token sequence can be called zero times", "[parsing][matcher]") { + static constexpr auto TAG_NAMESPACE = 1; + static constexpr auto TAG_STRUCT = 2; + static constexpr auto TAG_ENUM = 3; + + MatchersTestsHelper test; + const TokenPos pos; + const auto create = test.Factory(); + test.Matchers({create.Type(HeaderParserValueType::NAMESPACE).Tag(TAG_NAMESPACE), create.Optional(create.Type(HeaderParserValueType::STRUCT).Tag(TAG_STRUCT)), + create.Type(HeaderParserValueType::ENUM).Tag(TAG_ENUM)}); + + test.Tokens({HeaderParserValue::Keyword(pos, HeaderParserValueType::NAMESPACE), HeaderParserValue::Keyword(pos, HeaderParserValueType::ENUM), + HeaderParserValue::Invalid(pos)}); + + REQUIRE(test.PerformTest()); + REQUIRE(test.GetConsumedTokenCount() == 2); +} + +TEST_CASE("Matcher: Ensure OPTIONAL token sequence can be called once", "[parsing][matcher]") { + static constexpr auto TAG_NAMESPACE = 1; + static constexpr auto TAG_STRUCT = 2; + static constexpr auto TAG_ENUM = 3; + + MatchersTestsHelper test; + const TokenPos pos; + const auto create = test.Factory(); + test.Matchers({create.Type(HeaderParserValueType::NAMESPACE).Tag(TAG_NAMESPACE), create.Optional(create.Type(HeaderParserValueType::STRUCT).Tag(TAG_STRUCT)), + create.Type(HeaderParserValueType::ENUM).Tag(TAG_ENUM)}); + + test.Tokens({HeaderParserValue::Keyword(pos, HeaderParserValueType::NAMESPACE), HeaderParserValue::Keyword(pos, HeaderParserValueType::STRUCT), + HeaderParserValue::Keyword(pos, HeaderParserValueType::ENUM), HeaderParserValue::Invalid(pos)}); + + REQUIRE(test.PerformTest()); + REQUIRE(test.GetConsumedTokenCount() == 3); +} + +TEST_CASE("Matcher: Ensure OPTIONAL token sequence can not be called more than once", "[parsing][matcher]") { + static constexpr auto TAG_NAMESPACE = 1; + static constexpr auto TAG_STRUCT = 2; + static constexpr auto TAG_ENUM = 3; + + MatchersTestsHelper test; + const TokenPos pos; + const auto create = test.Factory(); + test.Matchers({create.Type(HeaderParserValueType::NAMESPACE).Tag(TAG_NAMESPACE), create.Optional(create.Type(HeaderParserValueType::STRUCT).Tag(TAG_STRUCT)), + create.Type(HeaderParserValueType::ENUM).Tag(TAG_ENUM)}); + + test.Tokens({HeaderParserValue::Keyword(pos, HeaderParserValueType::NAMESPACE), HeaderParserValue::Keyword(pos, HeaderParserValueType::STRUCT), + HeaderParserValue::Keyword(pos, HeaderParserValueType::STRUCT), HeaderParserValue::Keyword(pos, HeaderParserValueType::ENUM), + HeaderParserValue::Invalid(pos)}); + + REQUIRE(!test.PerformTest()); +} + +TEST_CASE("Matcher: Ensure LOOP matchers are greedy", "[parsing][matcher]") { + static constexpr auto TAG_NAMESPACE = 1; + static constexpr auto TAG_STRUCT = 2; + static constexpr auto TAG_ENUM = 3; + static constexpr auto TAG_TYPEDEF = 4; + + MatchersTestsHelper test; + const TokenPos pos; + const auto create = test.Factory(); + test.Matchers( + {create.Type(HeaderParserValueType::NAMESPACE).Tag(TAG_NAMESPACE), + create.Loop(create.Or({create.Type(HeaderParserValueType::STRUCT).Tag(TAG_STRUCT), create.Type(HeaderParserValueType::TYPEDEF).Tag(TAG_TYPEDEF)})), + create.Or({create.Type(HeaderParserValueType::TYPEDEF).Tag(TAG_TYPEDEF), create.Type(HeaderParserValueType::ENUM).Tag(TAG_ENUM)})}); + + test.Tokens({HeaderParserValue::Keyword(pos, HeaderParserValueType::NAMESPACE), HeaderParserValue::Keyword(pos, HeaderParserValueType::STRUCT), + HeaderParserValue::Keyword(pos, HeaderParserValueType::STRUCT), HeaderParserValue::Keyword(pos, HeaderParserValueType::TYPEDEF), + HeaderParserValue::Keyword(pos, HeaderParserValueType::STRUCT), HeaderParserValue::Keyword(pos, HeaderParserValueType::TYPEDEF), + HeaderParserValue::Keyword(pos, HeaderParserValueType::ENUM), HeaderParserValue::Invalid(pos)}); + + test.MatchCallback([](sequence_result_t &result) { + REQUIRE(result.NextTag() == TAG_NAMESPACE); + REQUIRE(result.NextTag() == TAG_STRUCT); + REQUIRE(result.NextTag() == TAG_STRUCT); + REQUIRE(result.NextTag() == TAG_TYPEDEF); + REQUIRE(result.NextTag() == TAG_STRUCT); + REQUIRE(result.NextTag() == TAG_TYPEDEF); + REQUIRE(result.NextTag() == TAG_ENUM); + }); + + REQUIRE(test.PerformTest()); + REQUIRE(test.GetConsumedTokenCount() == 7); +} + +TEST_CASE("Matcher: Ensure LABEL matcher are working", "[parsing][matcher]") { + static constexpr auto TAG_NAMESPACE = 1; + static constexpr auto TAG_STRUCT = 2; + + static constexpr auto LABEL_TEST = 1; + + MatchersTestsHelper test; + const TokenPos pos; + const auto create = test.Factory(); + test.Matchers({create.Type(HeaderParserValueType::NAMESPACE).Tag(TAG_NAMESPACE), create.Label(LABEL_TEST)}); + test.LabeledMatchers({create.Type(HeaderParserValueType::STRUCT).Tag(TAG_STRUCT), create.Type(HeaderParserValueType::STRUCT).Tag(TAG_STRUCT)}, LABEL_TEST); + + test.Tokens({HeaderParserValue::Keyword(pos, HeaderParserValueType::NAMESPACE), HeaderParserValue::Keyword(pos, HeaderParserValueType::STRUCT), + HeaderParserValue::Keyword(pos, HeaderParserValueType::STRUCT), HeaderParserValue::Invalid(pos)}); + + test.MatchCallback([](sequence_result_t &result) { + REQUIRE(result.NextTag() == TAG_NAMESPACE); + REQUIRE(result.NextTag() == TAG_STRUCT); + REQUIRE(result.NextTag() == TAG_STRUCT); + }); + + REQUIRE(test.PerformTest()); + REQUIRE(test.GetConsumedTokenCount() == 3); +} + +TEST_CASE("Matcher: Ensure LABEL matchers can refer to themselves are working", "[parsing][matcher]") { + static constexpr auto TAG_NAMESPACE = 1; + static constexpr auto TAG_STRUCT = 2; + + static constexpr auto LABEL_TEST = 1; + + MatchersTestsHelper test; + const TokenPos pos; + const auto create = test.Factory(); + test.Matchers({create.Type(HeaderParserValueType::NAMESPACE).Tag(TAG_NAMESPACE), create.Label(LABEL_TEST)}); + test.LabeledMatchers({create.Type(HeaderParserValueType::STRUCT).Tag(TAG_STRUCT), create.Optional(create.Label(LABEL_TEST))}, LABEL_TEST); + + test.Tokens({HeaderParserValue::Keyword(pos, HeaderParserValueType::NAMESPACE), HeaderParserValue::Keyword(pos, HeaderParserValueType::STRUCT), + HeaderParserValue::Keyword(pos, HeaderParserValueType::STRUCT), HeaderParserValue::Keyword(pos, HeaderParserValueType::STRUCT), + HeaderParserValue::Invalid(pos)}); + + test.MatchCallback([](sequence_result_t &result) { + REQUIRE(result.NextTag() == TAG_NAMESPACE); + REQUIRE(result.NextTag() == TAG_STRUCT); + REQUIRE(result.NextTag() == TAG_STRUCT); + REQUIRE(result.NextTag() == TAG_STRUCT); + }); + + REQUIRE(test.PerformTest()); + REQUIRE(test.GetConsumedTokenCount() == 4); +} + +TEST_CASE("Matcher: Can capture tokens", "[parsing][matcher]") { + static constexpr auto TAG_NAMESPACE = 1; + + static constexpr auto CAPTURE_NAMESPACE_NAME = 1; + + MatchersTestsHelper test; + const TokenPos pos; + const auto create = test.Factory(); + test.Matchers({create.Type(HeaderParserValueType::NAMESPACE).Tag(TAG_NAMESPACE), create.Identifier().Capture(CAPTURE_NAMESPACE_NAME), create.Char('{')}); - TEST_CASE("Matcher: Ensure OPTIONAL token sequence can not be called more than once", "[parsing][matcher]") + test.Tokens({HeaderParserValue::Keyword(pos, HeaderParserValueType::NAMESPACE), HeaderParserValue::Identifier(pos, new std::string("hello_world")), + HeaderParserValue::Character(pos, '{'), HeaderParserValue::Invalid(pos)}); + + test.MatchCallback([](sequence_result_t &result) { + REQUIRE(result.NextTag() == TAG_NAMESPACE); + REQUIRE(result.NextTag() == matcher_t::NO_ID); + + REQUIRE(result.HasNextCapture(CAPTURE_NAMESPACE_NAME)); { - static constexpr auto TAG_NAMESPACE = 1; - static constexpr auto TAG_STRUCT = 2; - static constexpr auto TAG_ENUM = 3; - - MatchersTestsHelper test; - const TokenPos pos; - const auto create = test.Factory(); - test.Matchers({ - create.Type(HeaderParserValueType::NAMESPACE).Tag(TAG_NAMESPACE), - create.Optional(create.Type(HeaderParserValueType::STRUCT).Tag(TAG_STRUCT)), - create.Type(HeaderParserValueType::ENUM).Tag(TAG_ENUM) - }); - - test.Tokens({ - HeaderParserValue::Keyword(pos, HeaderParserValueType::NAMESPACE), - HeaderParserValue::Keyword(pos, HeaderParserValueType::STRUCT), - HeaderParserValue::Keyword(pos, HeaderParserValueType::STRUCT), - HeaderParserValue::Keyword(pos, HeaderParserValueType::ENUM), - HeaderParserValue::Invalid(pos) - }); - - REQUIRE(!test.PerformTest()); + const auto &capture = result.NextCapture(CAPTURE_NAMESPACE_NAME); + REQUIRE(capture.m_type == HeaderParserValueType::IDENTIFIER); + REQUIRE(capture.IdentifierValue() == "hello_world"); } - TEST_CASE("Matcher: Ensure LOOP matchers are greedy", "[parsing][matcher]") + REQUIRE(!result.HasNextCapture(CAPTURE_NAMESPACE_NAME)); + }); + + REQUIRE(test.PerformTest()); + REQUIRE(test.GetConsumedTokenCount() == 3); +} + +TEST_CASE("Matcher: Can capture in OR matchers", "[parsing][matcher]") { + static constexpr auto TAG_NAMESPACE = 1; + static constexpr auto TAG_STRUCT = 2; + + static constexpr auto CAPTURE_NAMESPACE_NAME = 1; + static constexpr auto CAPTURE_STRUCT_NAME = 2; + + MatchersTestsHelper test; + const TokenPos pos; + const auto create = test.Factory(); + test.Matchers({create.Or({create.And({ + create.Type(HeaderParserValueType::NAMESPACE).Tag(TAG_NAMESPACE), + create.Identifier().Capture(CAPTURE_NAMESPACE_NAME), + }), + create.And({ + create.Type(HeaderParserValueType::STRUCT).Tag(TAG_STRUCT), + create.Identifier().Capture(CAPTURE_STRUCT_NAME), + })}), + create.Char('{')}); + + test.Tokens({HeaderParserValue::Keyword(pos, HeaderParserValueType::NAMESPACE), HeaderParserValue::Identifier(pos, new std::string("hello_world")), + HeaderParserValue::Character(pos, '{'), HeaderParserValue::Invalid(pos)}); + test.MatchCallback([](sequence_result_t &result) { + REQUIRE(result.NextTag() == TAG_NAMESPACE); + REQUIRE(result.NextTag() == matcher_t::NO_ID); + + REQUIRE(result.HasNextCapture(CAPTURE_NAMESPACE_NAME)); { - static constexpr auto TAG_NAMESPACE = 1; - static constexpr auto TAG_STRUCT = 2; - static constexpr auto TAG_ENUM = 3; - static constexpr auto TAG_TYPEDEF = 4; - - MatchersTestsHelper test; - const TokenPos pos; - const auto create = test.Factory(); - test.Matchers({ - create.Type(HeaderParserValueType::NAMESPACE).Tag(TAG_NAMESPACE), - create.Loop(create.Or({ - create.Type(HeaderParserValueType::STRUCT).Tag(TAG_STRUCT), - create.Type(HeaderParserValueType::TYPEDEF).Tag(TAG_TYPEDEF) - })), - create.Or({ - create.Type(HeaderParserValueType::TYPEDEF).Tag(TAG_TYPEDEF), - create.Type(HeaderParserValueType::ENUM).Tag(TAG_ENUM) - }) - }); - - test.Tokens({ - HeaderParserValue::Keyword(pos, HeaderParserValueType::NAMESPACE), - HeaderParserValue::Keyword(pos, HeaderParserValueType::STRUCT), - HeaderParserValue::Keyword(pos, HeaderParserValueType::STRUCT), - HeaderParserValue::Keyword(pos, HeaderParserValueType::TYPEDEF), - HeaderParserValue::Keyword(pos, HeaderParserValueType::STRUCT), - HeaderParserValue::Keyword(pos, HeaderParserValueType::TYPEDEF), - HeaderParserValue::Keyword(pos, HeaderParserValueType::ENUM), - HeaderParserValue::Invalid(pos) - }); - - test.MatchCallback([](sequence_result_t& result) - { - REQUIRE(result.NextTag() == TAG_NAMESPACE); - REQUIRE(result.NextTag() == TAG_STRUCT); - REQUIRE(result.NextTag() == TAG_STRUCT); - REQUIRE(result.NextTag() == TAG_TYPEDEF); - REQUIRE(result.NextTag() == TAG_STRUCT); - REQUIRE(result.NextTag() == TAG_TYPEDEF); - REQUIRE(result.NextTag() == TAG_ENUM); - }); - - REQUIRE(test.PerformTest()); - REQUIRE(test.GetConsumedTokenCount() == 7); + const auto &capture = result.NextCapture(CAPTURE_NAMESPACE_NAME); + REQUIRE(capture.m_type == HeaderParserValueType::IDENTIFIER); + REQUIRE(capture.IdentifierValue() == "hello_world"); } - TEST_CASE("Matcher: Ensure LABEL matcher are working", "[parsing][matcher]") + REQUIRE(!result.HasNextCapture(CAPTURE_NAMESPACE_NAME)); + }); + + REQUIRE(test.PerformTest()); + REQUIRE(test.GetConsumedTokenCount() == 3); + + test.Tokens({HeaderParserValue::Keyword(pos, HeaderParserValueType::STRUCT), HeaderParserValue::Identifier(pos, new std::string("bye_struct")), + HeaderParserValue::Character(pos, '{'), HeaderParserValue::Invalid(pos)}); + test.MatchCallback([](sequence_result_t &result) { + REQUIRE(result.NextTag() == TAG_STRUCT); + REQUIRE(result.NextTag() == matcher_t::NO_ID); + + REQUIRE(result.HasNextCapture(CAPTURE_STRUCT_NAME)); { - static constexpr auto TAG_NAMESPACE = 1; - static constexpr auto TAG_STRUCT = 2; - - static constexpr auto LABEL_TEST = 1; - - MatchersTestsHelper test; - const TokenPos pos; - const auto create = test.Factory(); - test.Matchers( - { - create.Type(HeaderParserValueType::NAMESPACE).Tag(TAG_NAMESPACE), - create.Label(LABEL_TEST) - }); - test.LabeledMatchers( - { - create.Type(HeaderParserValueType::STRUCT).Tag(TAG_STRUCT), - create.Type(HeaderParserValueType::STRUCT).Tag(TAG_STRUCT) - }, LABEL_TEST); - - test.Tokens({ - HeaderParserValue::Keyword(pos, HeaderParserValueType::NAMESPACE), - HeaderParserValue::Keyword(pos, HeaderParserValueType::STRUCT), - HeaderParserValue::Keyword(pos, HeaderParserValueType::STRUCT), - HeaderParserValue::Invalid(pos) - }); - - test.MatchCallback([](sequence_result_t& result) - { - REQUIRE(result.NextTag() == TAG_NAMESPACE); - REQUIRE(result.NextTag() == TAG_STRUCT); - REQUIRE(result.NextTag() == TAG_STRUCT); - }); - - REQUIRE(test.PerformTest()); - REQUIRE(test.GetConsumedTokenCount() == 3); + const auto &capture = result.NextCapture(CAPTURE_STRUCT_NAME); + REQUIRE(capture.m_type == HeaderParserValueType::IDENTIFIER); + REQUIRE(capture.IdentifierValue() == "bye_struct"); } - TEST_CASE("Matcher: Ensure LABEL matchers can refer to themselves are working", "[parsing][matcher]") + REQUIRE(!result.HasNextCapture(CAPTURE_STRUCT_NAME)); + }); + + REQUIRE(test.PerformTest()); + REQUIRE(test.GetConsumedTokenCount() == 3); +} + +TEST_CASE("Matcher: Can capture in LOOP matchers", "[parsing][matcher]") { + static constexpr auto TAG_NAMESPACE = 1; + + static constexpr auto CAPTURE_NAMESPACE_NAME = 1; + + MatchersTestsHelper test; + const TokenPos pos; + const auto create = test.Factory(); + test.Matchers( + {create.Type(HeaderParserValueType::NAMESPACE).Tag(TAG_NAMESPACE), create.Loop(create.Identifier().Capture(CAPTURE_NAMESPACE_NAME)), create.Char('{')}); + + test.Tokens({HeaderParserValue::Keyword(pos, HeaderParserValueType::NAMESPACE), HeaderParserValue::Identifier(pos, new std::string("hello_world")), + HeaderParserValue::Identifier(pos, new std::string("hello_universe")), HeaderParserValue::Identifier(pos, new std::string("hello_everyone")), + HeaderParserValue::Character(pos, '{'), HeaderParserValue::Invalid(pos)}); + + test.MatchCallback([](sequence_result_t &result) { + REQUIRE(result.NextTag() == TAG_NAMESPACE); + REQUIRE(result.NextTag() == matcher_t::NO_ID); + + REQUIRE(result.HasNextCapture(CAPTURE_NAMESPACE_NAME)); { - static constexpr auto TAG_NAMESPACE = 1; - static constexpr auto TAG_STRUCT = 2; - - static constexpr auto LABEL_TEST = 1; - - MatchersTestsHelper test; - const TokenPos pos; - const auto create = test.Factory(); - test.Matchers( - { - create.Type(HeaderParserValueType::NAMESPACE).Tag(TAG_NAMESPACE), - create.Label(LABEL_TEST) - }); - test.LabeledMatchers( - { - create.Type(HeaderParserValueType::STRUCT).Tag(TAG_STRUCT), - create.Optional(create.Label(LABEL_TEST)) - }, LABEL_TEST); - - test.Tokens({ - HeaderParserValue::Keyword(pos, HeaderParserValueType::NAMESPACE), - HeaderParserValue::Keyword(pos, HeaderParserValueType::STRUCT), - HeaderParserValue::Keyword(pos, HeaderParserValueType::STRUCT), - HeaderParserValue::Keyword(pos, HeaderParserValueType::STRUCT), - HeaderParserValue::Invalid(pos) - }); - - test.MatchCallback([](sequence_result_t& result) - { - REQUIRE(result.NextTag() == TAG_NAMESPACE); - REQUIRE(result.NextTag() == TAG_STRUCT); - REQUIRE(result.NextTag() == TAG_STRUCT); - REQUIRE(result.NextTag() == TAG_STRUCT); - }); - - REQUIRE(test.PerformTest()); - REQUIRE(test.GetConsumedTokenCount() == 4); + const auto &capture = result.NextCapture(CAPTURE_NAMESPACE_NAME); + REQUIRE(capture.m_type == HeaderParserValueType::IDENTIFIER); + REQUIRE(capture.IdentifierValue() == "hello_world"); } - TEST_CASE("Matcher: Can capture tokens", "[parsing][matcher]") + REQUIRE(result.HasNextCapture(CAPTURE_NAMESPACE_NAME)); { - static constexpr auto TAG_NAMESPACE = 1; - - static constexpr auto CAPTURE_NAMESPACE_NAME = 1; - - MatchersTestsHelper test; - const TokenPos pos; - const auto create = test.Factory(); - test.Matchers({ - create.Type(HeaderParserValueType::NAMESPACE).Tag(TAG_NAMESPACE), - create.Identifier().Capture(CAPTURE_NAMESPACE_NAME), - create.Char('{') - }); - - test.Tokens({ - HeaderParserValue::Keyword(pos, HeaderParserValueType::NAMESPACE), - HeaderParserValue::Identifier(pos, new std::string("hello_world")), - HeaderParserValue::Character(pos, '{'), - HeaderParserValue::Invalid(pos) - }); - - test.MatchCallback([](sequence_result_t& result) - { - REQUIRE(result.NextTag() == TAG_NAMESPACE); - REQUIRE(result.NextTag() == matcher_t::NO_ID); - - REQUIRE(result.HasNextCapture(CAPTURE_NAMESPACE_NAME)); - { - const auto& capture = result.NextCapture(CAPTURE_NAMESPACE_NAME); - REQUIRE(capture.m_type == HeaderParserValueType::IDENTIFIER); - REQUIRE(capture.IdentifierValue() == "hello_world"); - } - - REQUIRE(!result.HasNextCapture(CAPTURE_NAMESPACE_NAME)); - }); - - REQUIRE(test.PerformTest()); - REQUIRE(test.GetConsumedTokenCount() == 3); + const auto &capture = result.NextCapture(CAPTURE_NAMESPACE_NAME); + REQUIRE(capture.m_type == HeaderParserValueType::IDENTIFIER); + REQUIRE(capture.IdentifierValue() == "hello_universe"); } - TEST_CASE("Matcher: Can capture in OR matchers", "[parsing][matcher]") + REQUIRE(result.HasNextCapture(CAPTURE_NAMESPACE_NAME)); { - static constexpr auto TAG_NAMESPACE = 1; - static constexpr auto TAG_STRUCT = 2; - - static constexpr auto CAPTURE_NAMESPACE_NAME = 1; - static constexpr auto CAPTURE_STRUCT_NAME = 2; - - MatchersTestsHelper test; - const TokenPos pos; - const auto create = test.Factory(); - test.Matchers({ - create.Or({ - create.And({ - create.Type(HeaderParserValueType::NAMESPACE).Tag(TAG_NAMESPACE), - create.Identifier().Capture(CAPTURE_NAMESPACE_NAME), - }), - create.And({ - create.Type(HeaderParserValueType::STRUCT).Tag(TAG_STRUCT), - create.Identifier().Capture(CAPTURE_STRUCT_NAME), - }) - }), - create.Char('{') - }); - - test.Tokens({ - HeaderParserValue::Keyword(pos, HeaderParserValueType::NAMESPACE), - HeaderParserValue::Identifier(pos, new std::string("hello_world")), - HeaderParserValue::Character(pos, '{'), - HeaderParserValue::Invalid(pos) - }); - test.MatchCallback([](sequence_result_t& result) - { - REQUIRE(result.NextTag() == TAG_NAMESPACE); - REQUIRE(result.NextTag() == matcher_t::NO_ID); - - REQUIRE(result.HasNextCapture(CAPTURE_NAMESPACE_NAME)); - { - const auto& capture = result.NextCapture(CAPTURE_NAMESPACE_NAME); - REQUIRE(capture.m_type == HeaderParserValueType::IDENTIFIER); - REQUIRE(capture.IdentifierValue() == "hello_world"); - } - - REQUIRE(!result.HasNextCapture(CAPTURE_NAMESPACE_NAME)); - }); - - REQUIRE(test.PerformTest()); - REQUIRE(test.GetConsumedTokenCount() == 3); - - test.Tokens({ - HeaderParserValue::Keyword(pos, HeaderParserValueType::STRUCT), - HeaderParserValue::Identifier(pos, new std::string("bye_struct")), - HeaderParserValue::Character(pos, '{'), - HeaderParserValue::Invalid(pos) - }); - test.MatchCallback([](sequence_result_t& result) - { - REQUIRE(result.NextTag() == TAG_STRUCT); - REQUIRE(result.NextTag() == matcher_t::NO_ID); - - REQUIRE(result.HasNextCapture(CAPTURE_STRUCT_NAME)); - { - const auto& capture = result.NextCapture(CAPTURE_STRUCT_NAME); - REQUIRE(capture.m_type == HeaderParserValueType::IDENTIFIER); - REQUIRE(capture.IdentifierValue() == "bye_struct"); - } - - REQUIRE(!result.HasNextCapture(CAPTURE_STRUCT_NAME)); - }); - - REQUIRE(test.PerformTest()); - REQUIRE(test.GetConsumedTokenCount() == 3); + const auto &capture = result.NextCapture(CAPTURE_NAMESPACE_NAME); + REQUIRE(capture.m_type == HeaderParserValueType::IDENTIFIER); + REQUIRE(capture.IdentifierValue() == "hello_everyone"); } - TEST_CASE("Matcher: Can capture in LOOP matchers", "[parsing][matcher]") + REQUIRE(!result.HasNextCapture(CAPTURE_NAMESPACE_NAME)); + }); + + REQUIRE(test.PerformTest()); + REQUIRE(test.GetConsumedTokenCount() == 5); +} + +TEST_CASE("Matcher: Capturing an AND group captures all matched tokens", "[parsing][matcher]") { + static constexpr auto TAG_AND_GROUP = 1; + + static constexpr auto CAPTURE_AND_GROUP = 1; + + MatchersTestsHelper test; + const TokenPos pos; + const auto create = test.Factory(); + test.Matchers( + {create.And({create.Type(HeaderParserValueType::NAMESPACE), create.Identifier()}).Tag(TAG_AND_GROUP).Capture(CAPTURE_AND_GROUP), create.Char('{')}); + + test.Tokens({HeaderParserValue::Keyword(pos, HeaderParserValueType::NAMESPACE), HeaderParserValue::Identifier(pos, new std::string("hello_world")), + HeaderParserValue::Character(pos, '{'), HeaderParserValue::Invalid(pos)}); + + test.MatchCallback([](sequence_result_t &result) { + REQUIRE(result.NextTag() == TAG_AND_GROUP); + REQUIRE(result.NextTag() == matcher_t::NO_ID); + + REQUIRE(result.HasNextCapture(CAPTURE_AND_GROUP)); + REQUIRE(result.NextCapture(CAPTURE_AND_GROUP).m_type == HeaderParserValueType::NAMESPACE); + + REQUIRE(result.HasNextCapture(CAPTURE_AND_GROUP)); { - static constexpr auto TAG_NAMESPACE = 1; - - static constexpr auto CAPTURE_NAMESPACE_NAME = 1; - - MatchersTestsHelper test; - const TokenPos pos; - const auto create = test.Factory(); - test.Matchers({ - create.Type(HeaderParserValueType::NAMESPACE).Tag(TAG_NAMESPACE), - create.Loop(create.Identifier().Capture(CAPTURE_NAMESPACE_NAME)), - create.Char('{') - }); - - test.Tokens({ - HeaderParserValue::Keyword(pos, HeaderParserValueType::NAMESPACE), - HeaderParserValue::Identifier(pos, new std::string("hello_world")), - HeaderParserValue::Identifier(pos, new std::string("hello_universe")), - HeaderParserValue::Identifier(pos, new std::string("hello_everyone")), - HeaderParserValue::Character(pos, '{'), - HeaderParserValue::Invalid(pos) - }); - - test.MatchCallback([](sequence_result_t& result) - { - REQUIRE(result.NextTag() == TAG_NAMESPACE); - REQUIRE(result.NextTag() == matcher_t::NO_ID); - - REQUIRE(result.HasNextCapture(CAPTURE_NAMESPACE_NAME)); - { - const auto& capture = result.NextCapture(CAPTURE_NAMESPACE_NAME); - REQUIRE(capture.m_type == HeaderParserValueType::IDENTIFIER); - REQUIRE(capture.IdentifierValue() == "hello_world"); - } - - REQUIRE(result.HasNextCapture(CAPTURE_NAMESPACE_NAME)); - { - const auto& capture = result.NextCapture(CAPTURE_NAMESPACE_NAME); - REQUIRE(capture.m_type == HeaderParserValueType::IDENTIFIER); - REQUIRE(capture.IdentifierValue() == "hello_universe"); - } - - REQUIRE(result.HasNextCapture(CAPTURE_NAMESPACE_NAME)); - { - const auto& capture = result.NextCapture(CAPTURE_NAMESPACE_NAME); - REQUIRE(capture.m_type == HeaderParserValueType::IDENTIFIER); - REQUIRE(capture.IdentifierValue() == "hello_everyone"); - } - - REQUIRE(!result.HasNextCapture(CAPTURE_NAMESPACE_NAME)); - }); - - REQUIRE(test.PerformTest()); - REQUIRE(test.GetConsumedTokenCount() == 5); + const auto &capture = result.NextCapture(CAPTURE_AND_GROUP); + REQUIRE(capture.m_type == HeaderParserValueType::IDENTIFIER); + REQUIRE(capture.IdentifierValue() == "hello_world"); } - TEST_CASE("Matcher: Capturing an AND group captures all matched tokens", "[parsing][matcher]") + REQUIRE(!result.HasNextCapture(CAPTURE_AND_GROUP)); + }); + + REQUIRE(test.PerformTest()); + REQUIRE(test.GetConsumedTokenCount() == 3); +} + +TEST_CASE("Matcher: Capturing an LOOP group captures all matched tokens", "[parsing][matcher]") { + static constexpr auto TAG_LOOP_GROUP = 1; + + static constexpr auto CAPTURE_LOOP_GROUP = 1; + + MatchersTestsHelper test; + const TokenPos pos; + const auto create = test.Factory(); + test.Matchers({create.Loop(create.And({create.Type(HeaderParserValueType::NAMESPACE), create.Identifier()})).Tag(TAG_LOOP_GROUP).Capture(CAPTURE_LOOP_GROUP), + create.Char('{')}); + + test.Tokens({HeaderParserValue::Keyword(pos, HeaderParserValueType::NAMESPACE), HeaderParserValue::Identifier(pos, new std::string("hello_world")), + HeaderParserValue::Keyword(pos, HeaderParserValueType::NAMESPACE), HeaderParserValue::Identifier(pos, new std::string("hello_universe")), + HeaderParserValue::Character(pos, '{'), HeaderParserValue::Invalid(pos)}); + + test.MatchCallback([](sequence_result_t &result) { + REQUIRE(result.NextTag() == TAG_LOOP_GROUP); + REQUIRE(result.NextTag() == matcher_t::NO_ID); + + REQUIRE(result.HasNextCapture(CAPTURE_LOOP_GROUP)); + REQUIRE(result.NextCapture(CAPTURE_LOOP_GROUP).m_type == HeaderParserValueType::NAMESPACE); + + REQUIRE(result.HasNextCapture(CAPTURE_LOOP_GROUP)); { - static constexpr auto TAG_AND_GROUP = 1; - - static constexpr auto CAPTURE_AND_GROUP = 1; - - MatchersTestsHelper test; - const TokenPos pos; - const auto create = test.Factory(); - test.Matchers({ - create.And({ - create.Type(HeaderParserValueType::NAMESPACE), - create.Identifier() - }).Tag(TAG_AND_GROUP).Capture(CAPTURE_AND_GROUP), - create.Char('{') - }); - - test.Tokens({ - HeaderParserValue::Keyword(pos, HeaderParserValueType::NAMESPACE), - HeaderParserValue::Identifier(pos, new std::string("hello_world")), - HeaderParserValue::Character(pos, '{'), - HeaderParserValue::Invalid(pos) - }); - - test.MatchCallback([](sequence_result_t& result) - { - REQUIRE(result.NextTag() == TAG_AND_GROUP); - REQUIRE(result.NextTag() == matcher_t::NO_ID); - - REQUIRE(result.HasNextCapture(CAPTURE_AND_GROUP)); - REQUIRE(result.NextCapture(CAPTURE_AND_GROUP).m_type == HeaderParserValueType::NAMESPACE); - - REQUIRE(result.HasNextCapture(CAPTURE_AND_GROUP)); - { - const auto& capture = result.NextCapture(CAPTURE_AND_GROUP); - REQUIRE(capture.m_type == HeaderParserValueType::IDENTIFIER); - REQUIRE(capture.IdentifierValue() == "hello_world"); - } - - REQUIRE(!result.HasNextCapture(CAPTURE_AND_GROUP)); - }); - - REQUIRE(test.PerformTest()); - REQUIRE(test.GetConsumedTokenCount() == 3); + const auto &capture = result.NextCapture(CAPTURE_LOOP_GROUP); + REQUIRE(capture.m_type == HeaderParserValueType::IDENTIFIER); + REQUIRE(capture.IdentifierValue() == "hello_world"); } - TEST_CASE("Matcher: Capturing an LOOP group captures all matched tokens", "[parsing][matcher]") + REQUIRE(result.HasNextCapture(CAPTURE_LOOP_GROUP)); + REQUIRE(result.NextCapture(CAPTURE_LOOP_GROUP).m_type == HeaderParserValueType::NAMESPACE); + + REQUIRE(result.HasNextCapture(CAPTURE_LOOP_GROUP)); { - static constexpr auto TAG_LOOP_GROUP = 1; - - static constexpr auto CAPTURE_LOOP_GROUP = 1; - - MatchersTestsHelper test; - const TokenPos pos; - const auto create = test.Factory(); - test.Matchers({ - create.Loop(create.And({ - create.Type(HeaderParserValueType::NAMESPACE), - create.Identifier() - })).Tag(TAG_LOOP_GROUP).Capture(CAPTURE_LOOP_GROUP), - create.Char('{') - }); - - test.Tokens({ - HeaderParserValue::Keyword(pos, HeaderParserValueType::NAMESPACE), - HeaderParserValue::Identifier(pos, new std::string("hello_world")), - HeaderParserValue::Keyword(pos, HeaderParserValueType::NAMESPACE), - HeaderParserValue::Identifier(pos, new std::string("hello_universe")), - HeaderParserValue::Character(pos, '{'), - HeaderParserValue::Invalid(pos) - }); - - test.MatchCallback([](sequence_result_t& result) - { - REQUIRE(result.NextTag() == TAG_LOOP_GROUP); - REQUIRE(result.NextTag() == matcher_t::NO_ID); - - REQUIRE(result.HasNextCapture(CAPTURE_LOOP_GROUP)); - REQUIRE(result.NextCapture(CAPTURE_LOOP_GROUP).m_type == HeaderParserValueType::NAMESPACE); - - REQUIRE(result.HasNextCapture(CAPTURE_LOOP_GROUP)); - { - const auto& capture = result.NextCapture(CAPTURE_LOOP_GROUP); - REQUIRE(capture.m_type == HeaderParserValueType::IDENTIFIER); - REQUIRE(capture.IdentifierValue() == "hello_world"); - } - - REQUIRE(result.HasNextCapture(CAPTURE_LOOP_GROUP)); - REQUIRE(result.NextCapture(CAPTURE_LOOP_GROUP).m_type == HeaderParserValueType::NAMESPACE); - - REQUIRE(result.HasNextCapture(CAPTURE_LOOP_GROUP)); - { - const auto& capture = result.NextCapture(CAPTURE_LOOP_GROUP); - REQUIRE(capture.m_type == HeaderParserValueType::IDENTIFIER); - REQUIRE(capture.IdentifierValue() == "hello_universe"); - } - - REQUIRE(!result.HasNextCapture(CAPTURE_LOOP_GROUP)); - }); - - REQUIRE(test.PerformTest()); - REQUIRE(test.GetConsumedTokenCount() == 5); + const auto &capture = result.NextCapture(CAPTURE_LOOP_GROUP); + REQUIRE(capture.m_type == HeaderParserValueType::IDENTIFIER); + REQUIRE(capture.IdentifierValue() == "hello_universe"); } - TEST_CASE("Matcher: Capture transform works", "[parsing][matcher]") + REQUIRE(!result.HasNextCapture(CAPTURE_LOOP_GROUP)); + }); + + REQUIRE(test.PerformTest()); + REQUIRE(test.GetConsumedTokenCount() == 5); +} + +TEST_CASE("Matcher: Capture transform works", "[parsing][matcher]") { + static constexpr auto LABEL_TYPENAME = 1; + + static constexpr auto CAPTURE_TYPENAME = 1; + + MatchersTestsHelper test; + const TokenPos pos; + const auto create = test.Factory(); + test.Matchers({create.Type(HeaderParserValueType::STRUCT), create.Label(LABEL_TYPENAME).Capture(CAPTURE_TYPENAME), create.Char('{')}); + test.LabeledMatchers({create.And({create.Identifier(), create.OptionalLoop(create.And({create.Char(':'), create.Char(':'), create.Identifier()}))}) + .Transform([](HeaderMatcherFactory::token_list_t &values) { + std::ostringstream str; + str << values[0].get().IdentifierValue(); + + for (auto i = 3u; i < values.size(); i += 3) + str << "::" << values[i].get().IdentifierValue(); + + return HeaderParserValue::TypeName(values[0].get().GetPos(), new std::string(str.str())); + })}, + LABEL_TYPENAME); + + test.Tokens({HeaderParserValue::Keyword(pos, HeaderParserValueType::STRUCT), HeaderParserValue::Identifier(pos, new std::string("hello")), + HeaderParserValue::Character(pos, ':'), HeaderParserValue::Character(pos, ':'), HeaderParserValue::Identifier(pos, new std::string("world")), + HeaderParserValue::Character(pos, '{'), HeaderParserValue::Invalid(pos)}); + + test.MatchCallback([](sequence_result_t &result) { + REQUIRE(result.NextTag() == matcher_t::NO_ID); + + REQUIRE(result.HasNextCapture(CAPTURE_TYPENAME)); { - static constexpr auto LABEL_TYPENAME = 1; - - static constexpr auto CAPTURE_TYPENAME = 1; - - MatchersTestsHelper test; - const TokenPos pos; - const auto create = test.Factory(); - test.Matchers( - { - create.Type(HeaderParserValueType::STRUCT), - create.Label(LABEL_TYPENAME).Capture(CAPTURE_TYPENAME), - create.Char('{') - }); - test.LabeledMatchers( - { - create.And({ - create.Identifier(), - create.OptionalLoop(create.And({ - create.Char(':'), - create.Char(':'), - create.Identifier() - })) - }).Transform([](HeaderMatcherFactory::token_list_t& values) - { - std::ostringstream str; - str << values[0].get().IdentifierValue(); - - for (auto i = 3u; i < values.size(); i += 3) - str << "::" << values[i].get().IdentifierValue(); - - return HeaderParserValue::TypeName(values[0].get().GetPos(), new std::string(str.str())); - }) - }, LABEL_TYPENAME); - - test.Tokens({ - HeaderParserValue::Keyword(pos, HeaderParserValueType::STRUCT), - HeaderParserValue::Identifier(pos, new std::string("hello")), - HeaderParserValue::Character(pos, ':'), - HeaderParserValue::Character(pos, ':'), - HeaderParserValue::Identifier(pos, new std::string("world")), - HeaderParserValue::Character(pos, '{'), - HeaderParserValue::Invalid(pos) - }); - - test.MatchCallback([](sequence_result_t& result) - { - REQUIRE(result.NextTag() == matcher_t::NO_ID); - - REQUIRE(result.HasNextCapture(CAPTURE_TYPENAME)); - { - const auto& capture = result.NextCapture(CAPTURE_TYPENAME); - REQUIRE(capture.m_type == HeaderParserValueType::TYPE_NAME); - REQUIRE(capture.TypeNameValue() == "hello::world"); - } - - REQUIRE(!result.HasNextCapture(CAPTURE_TYPENAME)); - }); - - REQUIRE(test.PerformTest()); - REQUIRE(test.GetConsumedTokenCount() == 6); + const auto &capture = result.NextCapture(CAPTURE_TYPENAME); + REQUIRE(capture.m_type == HeaderParserValueType::TYPE_NAME); + REQUIRE(capture.TypeNameValue() == "hello::world"); } - TEST_CASE("Matcher: Can capture within transform", "[parsing][matcher]") + REQUIRE(!result.HasNextCapture(CAPTURE_TYPENAME)); + }); + + REQUIRE(test.PerformTest()); + REQUIRE(test.GetConsumedTokenCount() == 6); +} + +TEST_CASE("Matcher: Can capture within transform", "[parsing][matcher]") { + static constexpr auto LABEL_TYPENAME = 1; + + static constexpr auto CAPTURE_TYPENAME = 1; + static constexpr auto CAPTURE_FIRST_TYPENAME_IDENTIFIER = 2; + + MatchersTestsHelper test; + const TokenPos pos; + const auto create = test.Factory(); + test.Matchers({create.Type(HeaderParserValueType::STRUCT), create.Label(LABEL_TYPENAME).Capture(CAPTURE_TYPENAME), create.Char('{')}); + test.LabeledMatchers({create + .And({create.Identifier().Capture(CAPTURE_FIRST_TYPENAME_IDENTIFIER), + create.OptionalLoop(create.And({create.Char(':'), create.Char(':'), create.Identifier()}))}) + .Transform([](HeaderMatcherFactory::token_list_t &values) { + std::ostringstream str; + str << values[0].get().IdentifierValue(); + + for (auto i = 3u; i < values.size(); i += 3) + str << "::" << values[i].get().IdentifierValue(); + + return HeaderParserValue::TypeName(values[0].get().GetPos(), new std::string(str.str())); + })}, + LABEL_TYPENAME); + + test.Tokens({HeaderParserValue::Keyword(pos, HeaderParserValueType::STRUCT), HeaderParserValue::Identifier(pos, new std::string("hello")), + HeaderParserValue::Character(pos, ':'), HeaderParserValue::Character(pos, ':'), HeaderParserValue::Identifier(pos, new std::string("world")), + HeaderParserValue::Character(pos, '{'), HeaderParserValue::Invalid(pos)}); + + test.MatchCallback([](sequence_result_t &result) { + REQUIRE(result.NextTag() == matcher_t::NO_ID); + + REQUIRE(result.HasNextCapture(CAPTURE_TYPENAME)); { - static constexpr auto LABEL_TYPENAME = 1; - - static constexpr auto CAPTURE_TYPENAME = 1; - static constexpr auto CAPTURE_FIRST_TYPENAME_IDENTIFIER = 2; - - MatchersTestsHelper test; - const TokenPos pos; - const auto create = test.Factory(); - test.Matchers( - { - create.Type(HeaderParserValueType::STRUCT), - create.Label(LABEL_TYPENAME).Capture(CAPTURE_TYPENAME), - create.Char('{') - }); - test.LabeledMatchers( - { - create.And({ - create.Identifier().Capture(CAPTURE_FIRST_TYPENAME_IDENTIFIER), - create.OptionalLoop(create.And({ - create.Char(':'), - create.Char(':'), - create.Identifier() - })) - }).Transform([](HeaderMatcherFactory::token_list_t& values) - { - std::ostringstream str; - str << values[0].get().IdentifierValue(); - - for (auto i = 3u; i < values.size(); i += 3) - str << "::" << values[i].get().IdentifierValue(); - - return HeaderParserValue::TypeName(values[0].get().GetPos(), new std::string(str.str())); - }) - }, LABEL_TYPENAME); - - test.Tokens({ - HeaderParserValue::Keyword(pos, HeaderParserValueType::STRUCT), - HeaderParserValue::Identifier(pos, new std::string("hello")), - HeaderParserValue::Character(pos, ':'), - HeaderParserValue::Character(pos, ':'), - HeaderParserValue::Identifier(pos, new std::string("world")), - HeaderParserValue::Character(pos, '{'), - HeaderParserValue::Invalid(pos) - }); - - test.MatchCallback([](sequence_result_t& result) - { - REQUIRE(result.NextTag() == matcher_t::NO_ID); - - REQUIRE(result.HasNextCapture(CAPTURE_TYPENAME)); - { - const auto& capture = result.NextCapture(CAPTURE_TYPENAME); - REQUIRE(capture.m_type == HeaderParserValueType::TYPE_NAME); - REQUIRE(capture.TypeNameValue() == "hello::world"); - } - - REQUIRE(!result.HasNextCapture(CAPTURE_TYPENAME)); - - REQUIRE(result.HasNextCapture(CAPTURE_FIRST_TYPENAME_IDENTIFIER)); - { - const auto& capture = result.NextCapture(CAPTURE_FIRST_TYPENAME_IDENTIFIER); - REQUIRE(capture.m_type == HeaderParserValueType::IDENTIFIER); - REQUIRE(capture.IdentifierValue() == "hello"); - } - - REQUIRE(!result.HasNextCapture(CAPTURE_FIRST_TYPENAME_IDENTIFIER)); - }); - - REQUIRE(test.PerformTest()); - REQUIRE(test.GetConsumedTokenCount() == 6); + const auto &capture = result.NextCapture(CAPTURE_TYPENAME); + REQUIRE(capture.m_type == HeaderParserValueType::TYPE_NAME); + REQUIRE(capture.TypeNameValue() == "hello::world"); } - TEST_CASE("Matcher: Can transform and capture in the same matcher", "[parsing][matcher]") + REQUIRE(!result.HasNextCapture(CAPTURE_TYPENAME)); + + REQUIRE(result.HasNextCapture(CAPTURE_FIRST_TYPENAME_IDENTIFIER)); { - static constexpr auto CAPTURE_NAME = 1; - - MatchersTestsHelper test; - const TokenPos pos; - const auto create = test.Factory(); - test.Matchers( - { - create.Type(HeaderParserValueType::STRUCT), - create.Identifier().Capture(CAPTURE_NAME).Transform([](HeaderMatcherFactory::token_list_t& tokens) - { - auto str = tokens[0].get().IdentifierValue(); - std::transform(str.begin(), str.end(), str.begin(), toupper); - return HeaderParserValue::Identifier(tokens[0].get().GetPos(), new std::string(std::move(str))); - }), - create.Char('{') - }); - - test.Tokens({ - HeaderParserValue::Keyword(pos, HeaderParserValueType::STRUCT), - HeaderParserValue::Identifier(pos, new std::string("hello_world")), - HeaderParserValue::Character(pos, '{'), - HeaderParserValue::Invalid(pos) - }); - - test.MatchCallback([](sequence_result_t& result) - { - REQUIRE(result.NextTag() == matcher_t::NO_ID); - - REQUIRE(result.HasNextCapture(CAPTURE_NAME)); - { - const auto& capture = result.NextCapture(CAPTURE_NAME); - REQUIRE(capture.m_type == HeaderParserValueType::IDENTIFIER); - REQUIRE(capture.IdentifierValue() == "HELLO_WORLD"); - } - - REQUIRE(!result.HasNextCapture(CAPTURE_NAME)); - }); - - REQUIRE(test.PerformTest()); - REQUIRE(test.GetConsumedTokenCount() == 3); + const auto &capture = result.NextCapture(CAPTURE_FIRST_TYPENAME_IDENTIFIER); + REQUIRE(capture.m_type == HeaderParserValueType::IDENTIFIER); + REQUIRE(capture.IdentifierValue() == "hello"); } - TEST_CASE("Matcher: Ensure noconsume does not consume a token", "[parsing][matcher]") + REQUIRE(!result.HasNextCapture(CAPTURE_FIRST_TYPENAME_IDENTIFIER)); + }); + + REQUIRE(test.PerformTest()); + REQUIRE(test.GetConsumedTokenCount() == 6); +} + +TEST_CASE("Matcher: Can transform and capture in the same matcher", "[parsing][matcher]") { + static constexpr auto CAPTURE_NAME = 1; + + MatchersTestsHelper test; + const TokenPos pos; + const auto create = test.Factory(); + test.Matchers({create.Type(HeaderParserValueType::STRUCT), + create.Identifier().Capture(CAPTURE_NAME).Transform([](HeaderMatcherFactory::token_list_t &tokens) { + auto str = tokens[0].get().IdentifierValue(); + std::transform(str.begin(), str.end(), str.begin(), toupper); + return HeaderParserValue::Identifier(tokens[0].get().GetPos(), new std::string(std::move(str))); + }), + create.Char('{')}); + + test.Tokens({HeaderParserValue::Keyword(pos, HeaderParserValueType::STRUCT), HeaderParserValue::Identifier(pos, new std::string("hello_world")), + HeaderParserValue::Character(pos, '{'), HeaderParserValue::Invalid(pos)}); + + test.MatchCallback([](sequence_result_t &result) { + REQUIRE(result.NextTag() == matcher_t::NO_ID); + + REQUIRE(result.HasNextCapture(CAPTURE_NAME)); { - MatchersTestsHelper test; - const TokenPos pos; - test.Tokens({ - HeaderParserValue::Keyword(pos, HeaderParserValueType::NAMESPACE), - HeaderParserValue::Identifier(pos, new std::string("test_namespace")), - HeaderParserValue::Character(pos, '{'), - HeaderParserValue::Invalid(pos) - }); - const auto create = test.Factory(); - test.Matchers({ - create.Type(HeaderParserValueType::NAMESPACE), - create.Identifier(), - create.Char('{').NoConsume() - }); - - REQUIRE(test.PerformTest()); - REQUIRE(test.GetConsumedTokenCount() == 2); + const auto &capture = result.NextCapture(CAPTURE_NAME); + REQUIRE(capture.m_type == HeaderParserValueType::IDENTIFIER); + REQUIRE(capture.IdentifierValue() == "HELLO_WORLD"); } - TEST_CASE("Matcher: Ensure noconsume can be captured", "[parsing][matcher]") + REQUIRE(!result.HasNextCapture(CAPTURE_NAME)); + }); + + REQUIRE(test.PerformTest()); + REQUIRE(test.GetConsumedTokenCount() == 3); +} + +TEST_CASE("Matcher: Ensure noconsume does not consume a token", "[parsing][matcher]") { + MatchersTestsHelper test; + const TokenPos pos; + test.Tokens({HeaderParserValue::Keyword(pos, HeaderParserValueType::NAMESPACE), HeaderParserValue::Identifier(pos, new std::string("test_namespace")), + HeaderParserValue::Character(pos, '{'), HeaderParserValue::Invalid(pos)}); + const auto create = test.Factory(); + test.Matchers({create.Type(HeaderParserValueType::NAMESPACE), create.Identifier(), create.Char('{').NoConsume()}); + + REQUIRE(test.PerformTest()); + REQUIRE(test.GetConsumedTokenCount() == 2); +} + +TEST_CASE("Matcher: Ensure noconsume can be captured", "[parsing][matcher]") { + static constexpr auto CAPTURE_NAME = 1; + + MatchersTestsHelper test; + const TokenPos pos; + test.Tokens({HeaderParserValue::Keyword(pos, HeaderParserValueType::NAMESPACE), HeaderParserValue::Identifier(pos, new std::string("test_namespace")), + HeaderParserValue::Character(pos, '{'), HeaderParserValue::Invalid(pos)}); + const auto create = test.Factory(); + test.Matchers({create.Type(HeaderParserValueType::NAMESPACE), create.Identifier().NoConsume().Capture(CAPTURE_NAME)}); + test.MatchCallback([](sequence_result_t &result) { + REQUIRE(result.HasNextCapture(CAPTURE_NAME)); { - static constexpr auto CAPTURE_NAME = 1; - - MatchersTestsHelper test; - const TokenPos pos; - test.Tokens({ - HeaderParserValue::Keyword(pos, HeaderParserValueType::NAMESPACE), - HeaderParserValue::Identifier(pos, new std::string("test_namespace")), - HeaderParserValue::Character(pos, '{'), - HeaderParserValue::Invalid(pos) - }); - const auto create = test.Factory(); - test.Matchers({ - create.Type(HeaderParserValueType::NAMESPACE), - create.Identifier().NoConsume().Capture(CAPTURE_NAME) - }); - test.MatchCallback([](sequence_result_t& result) - { - REQUIRE(result.HasNextCapture(CAPTURE_NAME)); - { - const auto& capture = result.NextCapture(CAPTURE_NAME); - REQUIRE(capture.m_type == HeaderParserValueType::IDENTIFIER); - REQUIRE(capture.IdentifierValue() == "test_namespace"); - } - }); - - REQUIRE(test.PerformTest()); - REQUIRE(test.GetConsumedTokenCount() == 1); + const auto &capture = result.NextCapture(CAPTURE_NAME); + REQUIRE(capture.m_type == HeaderParserValueType::IDENTIFIER); + REQUIRE(capture.IdentifierValue() == "test_namespace"); } + }); + + REQUIRE(test.PerformTest()); + REQUIRE(test.GetConsumedTokenCount() == 1); } +} // namespace test::parsing::matcher